J-Index

请注意：本 java api 1.7Beta 规范不是最终稳定版，未来随着版本的更迭，本规范可能有更新。
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _

J

JANUARY - Static variable in class java.util.Calendar
Value of the Calendar.MONTH field indicating the first month of the year in the Gregorian and Julian calendars.
JANUARY - Static variable in class javax.xml.datatype.DatatypeConstants
Value for first month of year.
JAPAN - Static variable in class java.util.Locale
Useful constant for country.
JAPANESE - Static variable in class java.util.Locale
Useful constant for language.
JAPANESE_DOUBLE_POSTCARD - Static variable in class javax.print.attribute.standard.MediaSize.Other
Specifies the Japanese Double postcard size, 148 mm by 200 mm.
JAPANESE_DOUBLE_POSTCARD - Static variable in class javax.print.attribute.standard.MediaSizeName
Japanese Double Postcard size.
JAPANESE_POSTCARD - Static variable in class javax.print.attribute.standard.MediaSize.Other
Specifies the Japanese postcard size, 100 mm by 148 mm.
JAPANESE_POSTCARD - Static variable in class javax.print.attribute.standard.MediaSizeName
Japanese Postcard size.
JApplet - Class in javax.swing
An extended version of java.applet.Applet that adds support for the JFC/Swing component architecture.
JApplet() - Constructor for class javax.swing.JApplet
Creates a swing applet instance.
JApplet.AccessibleJApplet - Class in javax.swing
This class implements accessibility support for the JApplet class.
JApplet.AccessibleJApplet() - Constructor for class javax.swing.JApplet.AccessibleJApplet
JarEntry - Class in java.util.jar
This class is used to represent a JAR file entry.
JarEntry(String) - Constructor for class java.util.jar.JarEntry
Creates a new JarEntry for the specified JAR file entry name.
JarEntry(ZipEntry) - Constructor for class java.util.jar.JarEntry
Creates a new JarEntry with fields taken from the specified ZipEntry object.
JarEntry(JarEntry) - Constructor for class java.util.jar.JarEntry
Creates a new JarEntry with fields taken from the specified JarEntry object.
JarException - Exception in java.util.jar
Signals that an error of some sort has occurred while reading from or writing to a JAR file.
JarException() - Constructor for exception java.util.jar.JarException
Constructs a JarException with no detail message.
JarException(String) - Constructor for exception java.util.jar.JarException
Constructs a JarException with the specified detail message.
JarFile - Class in java.util.jar
The JarFile class is used to read the contents of a jar file from any file that can be opened with java.io.RandomAccessFile.
JarFile(String) - Constructor for class java.util.jar.JarFile
Creates a new JarFile to read from the specified file name.
JarFile(String, boolean) - Constructor for class java.util.jar.JarFile
Creates a new JarFile to read from the specified file name.
JarFile(File) - Constructor for class java.util.jar.JarFile
Creates a new JarFile to read from the specified File object.
JarFile(File, boolean) - Constructor for class java.util.jar.JarFile
Creates a new JarFile to read from the specified File object.
JarFile(File, boolean, int) - Constructor for class java.util.jar.JarFile
Creates a new JarFile to read from the specified File object in the specified mode.
jarFileURLConnection - Variable in class java.net.JarURLConnection
The connection to the JAR file URL, if the connection has been initiated.
JarInputStream - Class in java.util.jar
The JarInputStream class is used to read the contents of a JAR file from any input stream.
JarInputStream(InputStream) - Constructor for class java.util.jar.JarInputStream
Creates a new JarInputStream and reads the optional manifest.
JarInputStream(InputStream, boolean) - Constructor for class java.util.jar.JarInputStream
Creates a new JarInputStream and reads the optional manifest.
JarOutputStream - Class in java.util.jar
The JarOutputStream class is used to write the contents of a JAR file to any output stream.
JarOutputStream(OutputStream, Manifest) - Constructor for class java.util.jar.JarOutputStream
Creates a new JarOutputStream with the specified Manifest.
JarOutputStream(OutputStream) - Constructor for class java.util.jar.JarOutputStream
Creates a new JarOutputStream with no manifest.
JarURLConnection - Class in java.net
A URL Connection to a Java ARchive (JAR) file or an entry in a JAR file.
JarURLConnection(URL) - Constructor for class java.net.JarURLConnection
Creates the new JarURLConnection to the specified URL.
java.applet - package java.applet
Provides the classes necessary to create an applet and the classes an applet uses to communicate with its applet context.
java.awt - package java.awt
Contains all of the classes for creating user interfaces and for painting graphics and images.
java.awt.color - package java.awt.color
Provides classes for color spaces.
java.awt.datatransfer - package java.awt.datatransfer
Provides interfaces and classes for transferring data between and within applications.
java.awt.dnd - package java.awt.dnd
Drag and Drop is a direct manipulation gesture found in many Graphical User Interface systems that provides a mechanism to transfer information between two entities logically associated with presentation elements in the GUI.
java.awt.event - package java.awt.event
Provides interfaces and classes for dealing with different types of events fired by AWT components.
java.awt.font - package java.awt.font
Provides classes and interface relating to fonts.
java.awt.geom - package java.awt.geom
Provides the Java 2D classes for defining and performing operations on objects related to two-dimensional geometry.
java.awt.im - package java.awt.im
Provides classes and interfaces for the input method framework.
java.awt.im.spi - package java.awt.im.spi
Provides interfaces that enable the development of input methods that can be used with any Java runtime environment.
java.awt.image - package java.awt.image
Provides classes for creating and modifying images.
java.awt.image.renderable - package java.awt.image.renderable
Provides classes and interfaces for producing rendering-independent images.
java.awt.print - package java.awt.print
Provides classes and interfaces for a general printing API.
java.beans - package java.beans
Contains classes related to developing beans -- components based on the JavaBeans™ architecture.
java.beans.beancontext - package java.beans.beancontext
Provides classes and interfaces relating to bean context.
java.io - package java.io
Provides for system input and output through data streams, serialization and the file system.
java.lang - package java.lang
Provides classes that are fundamental to the design of the Java programming language.
java.lang.annotation - package java.lang.annotation
Provides library support for the Java programming language annotation facility.
java.lang.instrument - package java.lang.instrument
Provides services that allow Java programming language agents to instrument programs running on the JVM.
java.lang.invoke - package java.lang.invoke
The java.lang.invoke package contains dynamic language support provided directly by the Java core class libraries and virtual machine.
java.lang.management - package java.lang.management
Provides the management interfaces for monitoring and management of the Java virtual machine and other components in the Java runtime.
java.lang.ref - package java.lang.ref
Provides reference-object classes, which support a limited degree of interaction with the garbage collector.
java.lang.reflect - package java.lang.reflect
Provides classes and interfaces for obtaining reflective information about classes and objects.
java.math - package java.math
Provides classes for performing arbitrary-precision integer arithmetic (BigInteger) and arbitrary-precision decimal arithmetic (BigDecimal).
java.net - package java.net
Provides the classes for implementing networking applications.
java.nio - package java.nio
Defines buffers, which are containers for data, and provides an overview of the other NIO packages.
java.nio.channels - package java.nio.channels
Defines channels, which represent connections to entities that are capable of performing I/O operations, such as files and sockets; defines selectors, for multiplexed, non-blocking I/O operations.
java.nio.channels.spi - package java.nio.channels.spi
Service-provider classes for the java.nio.channels package.
java.nio.charset - package java.nio.charset
Defines charsets, decoders, and encoders, for translating between bytes and Unicode characters.
java.nio.charset.spi - package java.nio.charset.spi
Service-provider classes for the java.nio.charset package.
java.nio.file - package java.nio.file
Defines interfaces and classes for the Java virtual machine to access files, file attributes, and file systems.
java.nio.file.attribute - package java.nio.file.attribute
Interfaces and classes providing access to file and file system attributes.
java.nio.file.spi - package java.nio.file.spi
Service-provider classes for the java.nio.file package.
java.rmi - package java.rmi
Provides the RMI package.
java.rmi.activation - package java.rmi.activation
Provides support for RMI Object Activation.
java.rmi.dgc - package java.rmi.dgc
Provides classes and interface for RMI distributed garbage-collection (DGC).
java.rmi.registry - package java.rmi.registry
Provides a class and two interfaces for the RMI registry.
java.rmi.server - package java.rmi.server
Provides classes and interfaces for supporting the server side of RMI.
java.security - package java.security
Provides the classes and interfaces for the security framework.
java.security.acl - package java.security.acl
The classes and interfaces in this package have been superseded by classes in the java.security package.
java.security.cert - package java.security.cert
Provides classes and interfaces for parsing and managing certificates, certificate revocation lists (CRLs), and certification paths.
java.security.interfaces - package java.security.interfaces
Provides interfaces for generating RSA (Rivest, Shamir and Adleman AsymmetricCipher algorithm) keys as defined in the RSA Laboratory Technical Note PKCS#1, and DSA (Digital Signature Algorithm) keys as defined in NIST's FIPS-186.
java.security.spec - package java.security.spec
Provides classes and interfaces for key specifications and algorithm parameter specifications.
java.sql - package java.sql
Provides the API for accessing and processing data stored in a data source (usually a relational database) using the JavaTM programming language.
java.text - package java.text
Provides classes and interfaces for handling text, dates, numbers, and messages in a manner independent of natural languages.
java.text.spi - package java.text.spi
Service provider classes for the classes in the java.text package.
java.util - package java.util
Contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator, and a bit array).
java.util.concurrent - package java.util.concurrent
Utility classes commonly useful in concurrent programming.
java.util.concurrent.atomic - package java.util.concurrent.atomic
A small toolkit of classes that support lock-free thread-safe programming on single variables.
java.util.concurrent.locks - package java.util.concurrent.locks
Interfaces and classes providing a framework for locking and waiting for conditions that is distinct from built-in synchronization and monitors.
java.util.jar - package java.util.jar
Provides classes for reading and writing the JAR (Java ARchive) file format, which is based on the standard ZIP file format with an optional manifest file.
java.util.logging - package java.util.logging
Provides the classes and interfaces of the JavaTM 2 platform's core logging facilities.
java.util.prefs - package java.util.prefs
This package allows applications to store and retrieve user and system preference and configuration data.
java.util.regex - package java.util.regex
Classes for matching character sequences against patterns specified by regular expressions.
java.util.spi - package java.util.spi
Service provider classes for the classes in the java.util package.
java.util.zip - package java.util.zip
Provides classes for reading and writing the standard ZIP and GZIP file formats.
JAVA_OBJECT - Static variable in class java.sql.Types
The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type JAVA_OBJECT.
JavaCompiler - Interface in javax.tools
Interface to invoke Java™ programming language compilers from programs.
JavaCompiler.CompilationTask - Interface in javax.tools
Interface representing a future for a compilation task.
javaFileListFlavor - Static variable in class java.awt.datatransfer.DataFlavor
To transfer a list of files to/from Java (and the underlying platform) a DataFlavor of this type/subtype and representation class of java.util.List is used.
JavaFileManager - Interface in javax.tools
File manager for tools operating on Java™ programming language source and class files.
JavaFileManager.Location - Interface in javax.tools
Interface for locations of file objects.
JavaFileObject - Interface in javax.tools
File abstraction for tools operating on Java™ programming language source and class files.
JavaFileObject.Kind - Enum in javax.tools
Kinds of JavaFileObjects.
javaJVMLocalObjectMimeType - Static variable in class java.awt.datatransfer.DataFlavor
To transfer a reference to an arbitrary Java object reference that has no associated MIME Content-type, across a Transferable interface WITHIN THE SAME JVM, a DataFlavor with this type/subtype is used, with a representationClass equal to the type of the class/interface being passed across the Transferable.
JAVANESE - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Javanese" Unicode character block.
javaRemoteObjectMimeType - Static variable in class java.awt.datatransfer.DataFlavor
In order to pass a live link to a Remote object via a Drag and Drop ACTION_LINK operation a Mime Content Type of application/x-java-remote-object should be used, where the representation class of the DataFlavor represents the type of the Remote interface to be transferred.
javaSerializedObjectMimeType - Static variable in class java.awt.datatransfer.DataFlavor
A MIME Content-Type of application/x-java-serialized-object represents a graph of Java object(s) that have been made persistent.
javax.accessibility - package javax.accessibility
Defines a contract between user-interface components and an assistive technology that provides access to those components.
javax.activation - package javax.activation
javax.activity - package javax.activity
Contains Activity service related exceptions thrown by the ORB machinery during unmarshalling.
javax.annotation - package javax.annotation
javax.annotation.processing - package javax.annotation.processing
Facilities for declaring annotation processors and for allowing annotation processors to communicate with an annotation processing tool environment.
javax.crypto - package javax.crypto
Provides the classes and interfaces for cryptographic operations.
javax.crypto.interfaces - package javax.crypto.interfaces
Provides interfaces for Diffie-Hellman keys as defined in RSA Laboratories' PKCS #3.
javax.crypto.spec - package javax.crypto.spec
Provides classes and interfaces for key specifications and algorithm parameter specifications.
javax.imageio - package javax.imageio
The main package of the Java Image I/O API.
javax.imageio.event - package javax.imageio.event
A package of the Java Image I/O API dealing with synchronous notification of events during the reading and writing of images.
javax.imageio.metadata - package javax.imageio.metadata
A package of the Java Image I/O API dealing with reading and writing metadata.
javax.imageio.plugins.bmp - package javax.imageio.plugins.bmp
软件包 containing the public classes used by the built-in BMP plug-in.
javax.imageio.plugins.jpeg - package javax.imageio.plugins.jpeg
Classes supporting the built-in JPEG plug-in.
javax.imageio.spi - package javax.imageio.spi
A package of the Java Image I/O API containing the plug-in interfaces for readers, writers, transcoders, and streams, and a runtime registry.
javax.imageio.stream - package javax.imageio.stream
A package of the Java Image I/O API dealing with low-level I/O from files and streams.
javax.jws - package javax.jws
javax.jws.soap - package javax.jws.soap
javax.lang.model - package javax.lang.model
Classes and hierarchies of packages used to model the Java programming language.
javax.lang.model.element - package javax.lang.model.element
Interfaces used to model elements of the Java programming language.
javax.lang.model.type - package javax.lang.model.type
Interfaces used to model Java programming language types.
javax.lang.model.util - package javax.lang.model.util
Utilities to assist in the processing of program elements and types.
javax.management - package javax.management
Provides the core classes for the Java Management Extensions.
javax.management.loading - package javax.management.loading
Provides the classes which implement advanced dynamic loading.
javax.management.modelmbean - package javax.management.modelmbean
Provides the definition of the ModelMBean classes.
javax.management.monitor - package javax.management.monitor
Provides the definition of the monitor classes.
javax.management.openmbean - package javax.management.openmbean
Provides the open data types and Open MBean descriptor classes.
javax.management.relation - package javax.management.relation
Provides the definition of the Relation Service.
javax.management.remote - package javax.management.remote
Interfaces for remote access to JMX MBean servers.
javax.management.remote.rmi - package javax.management.remote.rmi
The RMI connector is a connector for the JMX Remote API that uses RMI to transmit client requests to a remote MBean server.
javax.management.timer - package javax.management.timer
Provides the definition of the Timer MBean.
javax.naming - package javax.naming
Provides the classes and interfaces for accessing naming services.
javax.naming.directory - package javax.naming.directory
Extends the javax.naming package to provide functionality for accessing directory services.
javax.naming.event - package javax.naming.event
Provides support for event notification when accessing naming and directory services.
javax.naming.ldap - package javax.naming.ldap
Provides support for LDAPv3 extended operations and controls.
javax.naming.spi - package javax.naming.spi
javax.net - package javax.net
Provides classes for networking applications.
javax.net.ssl - package javax.net.ssl
Provides classes for the secure socket package.
javax.print - package javax.print
Provides the principal classes and interfaces for the JavaTM Print Service API.
javax.print.attribute - package javax.print.attribute
Provides classes and interfaces that describe the types of JavaTM Print Service attributes and how they can be collected into attribute sets.
javax.print.attribute.standard - package javax.print.attribute.standard
软件包 javax.print.attribute.standard contains classes for specific printing attributes.
javax.print.event - package javax.print.event
软件包 javax.print.event contains event classes and listener interfaces.
javax.rmi - package javax.rmi
Contains user APIs for RMI-IIOP.
javax.rmi.CORBA - package javax.rmi.CORBA
Contains portability APIs for RMI-IIOP.
javax.rmi.ssl - package javax.rmi.ssl
Provides implementations of RMIClientSocketFactory and RMIServerSocketFactory over the Secure Sockets Layer (SSL) or Transport Layer Security (TLS) protocols.
javax.script - package javax.script
The scripting API consists of interfaces and classes that define Java TM Scripting Engines and provides a framework for their use in Java applications.
javax.security.auth - package javax.security.auth
This package provides a framework for authentication and authorization.
javax.security.auth.callback - package javax.security.auth.callback
This package provides the classes necessary for services to interact with applications in order to retrieve information (authentication data including usernames or passwords, for example) or to display information (error and warning messages, for example).
javax.security.auth.kerberos - package javax.security.auth.kerberos
This package contains utility classes related to the Kerberos network authentication protocol.
javax.security.auth.login - package javax.security.auth.login
This package provides a pluggable authentication framework.
javax.security.auth.spi - package javax.security.auth.spi
This package provides the interface to be used for implementing pluggable authentication modules.
javax.security.auth.x500 - package javax.security.auth.x500
This package contains the classes that should be used to store X500 Principal and X500 Private Crendentials in a Subject.
javax.security.cert - package javax.security.cert
Provides classes for public key certificates.
javax.security.sasl - package javax.security.sasl
Contains class and interfaces for supporting SASL.
javax.sound.midi - package javax.sound.midi
Provides interfaces and classes for I/O, sequencing, and synthesis of MIDI (Musical Instrument Digital Interface) data.
javax.sound.midi.spi - package javax.sound.midi.spi
Supplies interfaces for service providers to implement when offering new MIDI devices, MIDI file readers and writers, or sound bank readers.
javax.sound.sampled - package javax.sound.sampled
Provides interfaces and classes for capture, processing, and playback of sampled audio data.
javax.sound.sampled.spi - package javax.sound.sampled.spi
Supplies abstract classes for service providers to subclass when offering new audio devices, sound file readers and writers, or audio format converters.
javax.sql - package javax.sql
Provides the API for server side data source access and processing from the JavaTM programming language.
javax.sql.rowset - package javax.sql.rowset
Standard interfaces and base classes for JDBC RowSet implementations.
javax.sql.rowset.serial - package javax.sql.rowset.serial
Provides utility classes to allow serializable mappings between SQL types and data types in the Java programming language.
javax.sql.rowset.spi - package javax.sql.rowset.spi
The standard classes and interfaces that a third party vendor has to use in its implementation of a synchronization provider.
javax.swing - package javax.swing
Provides a set of "lightweight" (all-Java language) components that, to the maximum degree possible, work the same on all platforms.
javax.swing.border - package javax.swing.border
Provides classes and interface for drawing specialized borders around a Swing component.
javax.swing.colorchooser - package javax.swing.colorchooser
Contains classes and interfaces used by the JColorChooser component.
javax.swing.event - package javax.swing.event
Provides for events fired by Swing components.
javax.swing.filechooser - package javax.swing.filechooser
Contains classes and interfaces used by the JFileChooser component.
javax.swing.plaf - package javax.swing.plaf
Provides one interface and many abstract classes that Swing uses to provide its pluggable look-and-feel capabilities.
javax.swing.plaf.basic - package javax.swing.plaf.basic
Provides user interface objects built according to the Basic look and feel.
javax.swing.plaf.metal - package javax.swing.plaf.metal
Provides user interface objects built according to the Java look and feel (once codenamed Metal), which is the default look and feel.
javax.swing.plaf.multi - package javax.swing.plaf.multi
Provides user interface objects that combine two or more look and feels.
javax.swing.plaf.nimbus - package javax.swing.plaf.nimbus
Provides user interface objects built according to the cross-platform Nimbus look and feel.
javax.swing.plaf.synth - package javax.swing.plaf.synth
Synth is a skinnable look and feel in which all painting is delegated.
javax.swing.table - package javax.swing.table
Provides classes and interfaces for dealing with javax.swing.JTable.
javax.swing.text - package javax.swing.text
Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html - package javax.swing.text.html
Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.
javax.swing.text.html.parser - package javax.swing.text.html.parser
Provides the default HTML parser, along with support classes.
javax.swing.text.rtf - package javax.swing.text.rtf
Provides a class (RTFEditorKit) for creating Rich-Text-Format text editors.
javax.swing.tree - package javax.swing.tree
Provides classes and interfaces for dealing with javax.swing.JTree.
javax.swing.undo - package javax.swing.undo
Allows developers to provide support for undo/redo in applications such as text editors.
javax.tools - package javax.tools
Provides interfaces for tools which can be invoked from a program, for example, compilers.
javax.transaction - package javax.transaction
Contains three exceptions thrown by the ORB machinery during unmarshalling.
javax.transaction.xa - package javax.transaction.xa
Provides the API that defines the contract between the transaction manager and the resource manager, which allows the transaction manager to enlist and delist resource objects (supplied by the resource manager driver) in JTA transactions.
javax.xml - package javax.xml
javax.xml.bind - package javax.xml.bind
Provides a runtime binding framework for client applications including unmarshalling, marshalling, and validation capabilities.
javax.xml.bind.annotation - package javax.xml.bind.annotation
Defines annotations for customizing Java program elements to XML Schema mapping.
javax.xml.bind.annotation.adapters - package javax.xml.bind.annotation.adapters
XmlAdapter and its spec-defined sub-classes to allow arbitrary Java classes to be used with JAXB.
javax.xml.bind.attachment - package javax.xml.bind.attachment
This package is implemented by a MIME-based package processor that enables the interpretation and creation of optimized binary data within an MIME-based package format.
javax.xml.bind.helpers - package javax.xml.bind.helpers
JAXB Provider Use Only: Provides partial default implementations for some of the javax.xml.bind interfaces.
javax.xml.bind.util - package javax.xml.bind.util
Useful client utility classes.
javax.xml.crypto - package javax.xml.crypto
Common classes for XML cryptography.
javax.xml.crypto.dom - package javax.xml.crypto.dom
DOM-specific classes for the javax.xml.crypto package.
javax.xml.crypto.dsig - package javax.xml.crypto.dsig
Classes for generating and validating XML digital signatures.
javax.xml.crypto.dsig.dom - package javax.xml.crypto.dsig.dom
DOM-specific classes for the javax.xml.crypto.dsig package.
javax.xml.crypto.dsig.keyinfo - package javax.xml.crypto.dsig.keyinfo
Classes for parsing and processing KeyInfo elements and structures.
javax.xml.crypto.dsig.spec - package javax.xml.crypto.dsig.spec
Parameter classes for XML digital signatures.
javax.xml.datatype - package javax.xml.datatype
XML/Java Type Mappings.
javax.xml.namespace - package javax.xml.namespace
XML Namespace processing.
javax.xml.parsers - package javax.xml.parsers
Provides classes allowing the processing of XML documents.
javax.xml.soap - package javax.xml.soap
Provides the API for creating and building SOAP messages.
javax.xml.stream - package javax.xml.stream
javax.xml.stream.events - package javax.xml.stream.events
javax.xml.stream.util - package javax.xml.stream.util
javax.xml.transform - package javax.xml.transform
This package defines the generic APIs for processing transformation instructions, and performing a transformation from source to result.
javax.xml.transform.dom - package javax.xml.transform.dom
This package implements DOM-specific transformation APIs.
javax.xml.transform.sax - package javax.xml.transform.sax
This package implements SAX2-specific transformation APIs.
javax.xml.transform.stax - package javax.xml.transform.stax
Provides for StAX-specific transformation APIs.
javax.xml.transform.stream - package javax.xml.transform.stream
This package implements stream- and URI- specific transformation APIs.
javax.xml.validation - package javax.xml.validation
This package provides an API for validation of XML documents.
javax.xml.ws - package javax.xml.ws
This package contains the core JAX-WS APIs.
javax.xml.ws.handler - package javax.xml.ws.handler
This package defines APIs for message handlers.
javax.xml.ws.handler.soap - package javax.xml.ws.handler.soap
This package defines APIs for SOAP message handlers.
javax.xml.ws.http - package javax.xml.ws.http
This package defines APIs specific to the HTTP binding.
javax.xml.ws.soap - package javax.xml.ws.soap
This package defines APIs specific to the SOAP binding.
javax.xml.ws.spi - package javax.xml.ws.spi
This package defines SPIs for JAX-WS.
javax.xml.ws.spi.http - package javax.xml.ws.spi.http
Provides HTTP SPI that is used for portable deployment of JAX-WS web services in containers(for e.g.
javax.xml.ws.wsaddressing - package javax.xml.ws.wsaddressing
This package defines APIs related to WS-Addressing.
javax.xml.xpath - package javax.xml.xpath
This package provides an object-model neutral API for the evaluation of XPath expressions and access to the evaluation environment.
JAXB - Class in javax.xml.bind
Class that defines convenience methods for common, simple use of JAXB.
JAXB_CONTEXT_FACTORY - Static variable in class javax.xml.bind.JAXBContext
The name of the property that contains the name of the class capable of creating new JAXBContext objects.
JAXB_ENCODING - Static variable in interface javax.xml.bind.Marshaller
The name of the property used to specify the output encoding in the marshalled XML data.
JAXB_FORMATTED_OUTPUT - Static variable in interface javax.xml.bind.Marshaller
The name of the property used to specify whether or not the marshalled XML data is formatted with linefeeds and indentation.
JAXB_FRAGMENT - Static variable in interface javax.xml.bind.Marshaller
The name of the property used to specify whether or not the marshaller will generate document level events (ie calling startDocument or endDocument).
JAXB_NO_NAMESPACE_SCHEMA_LOCATION - Static variable in interface javax.xml.bind.Marshaller
The name of the property used to specify the xsi:noNamespaceSchemaLocation attribute value to place in the marshalled XML output.
JAXB_SCHEMA_LOCATION - Static variable in interface javax.xml.bind.Marshaller
The name of the property used to specify the xsi:schemaLocation attribute value to place in the marshalled XML output.
JAXBContext - Class in javax.xml.bind
The JAXBContext class provides the client's entry point to the JAXB API.
JAXBContext() - Constructor for class javax.xml.bind.JAXBContext
JAXBElement<T> - Class in javax.xml.bind
JAXB representation of an Xml Element.
JAXBElement(QName, Class<T>, Class, T) - Constructor for class javax.xml.bind.JAXBElement
Construct an xml element instance.
JAXBElement(QName, Class<T>, T) - Constructor for class javax.xml.bind.JAXBElement
Construct an xml element instance.
JAXBElement.GlobalScope - Class in javax.xml.bind
Designates global scope for an xml element.
JAXBElement.GlobalScope() - Constructor for class javax.xml.bind.JAXBElement.GlobalScope
JAXBException - Exception in javax.xml.bind
This is the root exception class for all JAXB exceptions.
JAXBException(String) - Constructor for exception javax.xml.bind.JAXBException
Construct a JAXBException with the specified detail message.
JAXBException(String, String) - Constructor for exception javax.xml.bind.JAXBException
Construct a JAXBException with the specified detail message and vendor specific errorCode.
JAXBException(Throwable) - Constructor for exception javax.xml.bind.JAXBException
Construct a JAXBException with a linkedException.
JAXBException(String, Throwable) - Constructor for exception javax.xml.bind.JAXBException
Construct a JAXBException with the specified detail message and linkedException.
JAXBException(String, String, Throwable) - Constructor for exception javax.xml.bind.JAXBException
Construct a JAXBException with the specified detail message, vendor specific errorCode, and linkedException.
JAXBIntrospector - Class in javax.xml.bind
Provide access to JAXB xml binding data for a JAXB object.
JAXBIntrospector() - Constructor for class javax.xml.bind.JAXBIntrospector
JAXBPermission - Class in javax.xml.bind
This class is for JAXB permissions.
JAXBPermission(String) - Constructor for class javax.xml.bind.JAXBPermission
Creates a new JAXBPermission with the specified name.
JAXBResult - Class in javax.xml.bind.util
JAXP Result implementation that unmarshals a JAXB object.
JAXBResult(JAXBContext) - Constructor for class javax.xml.bind.util.JAXBResult
Creates a new instance that uses the specified JAXBContext to unmarshal.
JAXBResult(Unmarshaller) - Constructor for class javax.xml.bind.util.JAXBResult
Creates a new instance that uses the specified Unmarshaller to unmarshal an object.
JAXBSource - Class in javax.xml.bind.util
JAXP Source implementation that marshals a JAXB-generated object.
JAXBSource(JAXBContext, Object) - Constructor for class javax.xml.bind.util.JAXBSource
Creates a new Source for the given content object.
JAXBSource(Marshaller, Object) - Constructor for class javax.xml.bind.util.JAXBSource
Creates a new Source for the given content object.
JAXWSPROVIDER_PROPERTY - Static variable in class javax.xml.ws.spi.Provider
A constant representing the property used to lookup the name of a Provider implementation class.
JButton - Class in javax.swing
An implementation of a "push" button.
JButton() - Constructor for class javax.swing.JButton
Creates a button with no set text or icon.
JButton(Icon) - Constructor for class javax.swing.JButton
Creates a button with an icon.
JButton(String) - Constructor for class javax.swing.JButton
Creates a button with text.
JButton(Action) - Constructor for class javax.swing.JButton
Creates a button where properties are taken from the Action supplied.
JButton(String, Icon) - Constructor for class javax.swing.JButton
Creates a button with initial text and an icon.
JButton.AccessibleJButton - Class in javax.swing
This class implements accessibility support for the JButton class.
JButton.AccessibleJButton() - Constructor for class javax.swing.JButton.AccessibleJButton
JCheckBox - Class in javax.swing
An implementation of a check box -- an item that can be selected or deselected, and which displays its state to the user.
JCheckBox() - Constructor for class javax.swing.JCheckBox
Creates an initially unselected check box button with no text, no icon.
JCheckBox(Icon) - Constructor for class javax.swing.JCheckBox
Creates an initially unselected check box with an icon.
JCheckBox(Icon, boolean) - Constructor for class javax.swing.JCheckBox
Creates a check box with an icon and specifies whether or not it is initially selected.
JCheckBox(String) - Constructor for class javax.swing.JCheckBox
Creates an initially unselected check box with text.
JCheckBox(Action) - Constructor for class javax.swing.JCheckBox
Creates a check box where properties are taken from the Action supplied.
JCheckBox(String, boolean) - Constructor for class javax.swing.JCheckBox
Creates a check box with text and specifies whether or not it is initially selected.
JCheckBox(String, Icon) - Constructor for class javax.swing.JCheckBox
Creates an initially unselected check box with the specified text and icon.
JCheckBox(String, Icon, boolean) - Constructor for class javax.swing.JCheckBox
Creates a check box with text and icon, and specifies whether or not it is initially selected.
JCheckBox.AccessibleJCheckBox - Class in javax.swing
This class implements accessibility support for the JCheckBox class.
JCheckBox.AccessibleJCheckBox() - Constructor for class javax.swing.JCheckBox.AccessibleJCheckBox
JCheckBoxMenuItem - Class in javax.swing
A menu item that can be selected or deselected.
JCheckBoxMenuItem() - Constructor for class javax.swing.JCheckBoxMenuItem
Creates an initially unselected check box menu item with no set text or icon.
JCheckBoxMenuItem(Icon) - Constructor for class javax.swing.JCheckBoxMenuItem
Creates an initially unselected check box menu item with an icon.
JCheckBoxMenuItem(String) - Constructor for class javax.swing.JCheckBoxMenuItem
Creates an initially unselected check box menu item with text.
JCheckBoxMenuItem(Action) - Constructor for class javax.swing.JCheckBoxMenuItem
Creates a menu item whose properties are taken from the Action supplied.
JCheckBoxMenuItem(String, Icon) - Constructor for class javax.swing.JCheckBoxMenuItem
Creates an initially unselected check box menu item with the specified text and icon.
JCheckBoxMenuItem(String, boolean) - Constructor for class javax.swing.JCheckBoxMenuItem
Creates a check box menu item with the specified text and selection state.
JCheckBoxMenuItem(String, Icon, boolean) - Constructor for class javax.swing.JCheckBoxMenuItem
Creates a check box menu item with the specified text, icon, and selection state.
JCheckBoxMenuItem.AccessibleJCheckBoxMenuItem - Class in javax.swing
This class implements accessibility support for the JCheckBoxMenuItem class.
JCheckBoxMenuItem.AccessibleJCheckBoxMenuItem() - Constructor for class javax.swing.JCheckBoxMenuItem.AccessibleJCheckBoxMenuItem
JColorChooser - Class in javax.swing
JColorChooser provides a pane of controls designed to allow a user to manipulate and select a color.
JColorChooser() - Constructor for class javax.swing.JColorChooser
Creates a color chooser pane with an initial color of white.
JColorChooser(Color) - Constructor for class javax.swing.JColorChooser
Creates a color chooser pane with the specified initial color.
JColorChooser(ColorSelectionModel) - Constructor for class javax.swing.JColorChooser
Creates a color chooser pane with the specified ColorSelectionModel.
JColorChooser.AccessibleJColorChooser - Class in javax.swing
This class implements accessibility support for the JColorChooser class.
JColorChooser.AccessibleJColorChooser() - Constructor for class javax.swing.JColorChooser.AccessibleJColorChooser
JComboBox - Class in javax.swing
A component that combines a button or editable field and a drop-down list.
JComboBox(ComboBoxModel) - Constructor for class javax.swing.JComboBox
Creates a JComboBox that takes its items from an existing ComboBoxModel.
JComboBox(Object[]) - Constructor for class javax.swing.JComboBox
Creates a JComboBox that contains the elements in the specified array.
JComboBox(Vector<?>) - Constructor for class javax.swing.JComboBox
Creates a JComboBox that contains the elements in the specified Vector.
JComboBox() - Constructor for class javax.swing.JComboBox
Creates a JComboBox with a default data model.
JComboBox.AccessibleJComboBox - Class in javax.swing
This class implements accessibility support for the JComboBox class.
JComboBox.AccessibleJComboBox() - Constructor for class javax.swing.JComboBox.AccessibleJComboBox
Returns an AccessibleJComboBox instance
JComboBox.KeySelectionManager - Interface in javax.swing
The interface that defines a KeySelectionManager.
JComponent - Class in javax.swing
The base class for all Swing components except top-level containers.
JComponent() - Constructor for class javax.swing.JComponent
Default JComponent constructor.
JComponent.AccessibleJComponent - Class in javax.swing
Inner class of JComponent used to provide default support for accessibility.
JComponent.AccessibleJComponent() - Constructor for class javax.swing.JComponent.AccessibleJComponent
Though the class is abstract, this should be called by all sub-classes.
JComponent.AccessibleJComponent.AccessibleContainerHandler - Class in javax.swing
Fire PropertyChange listener, if one is registered, when children added/removed.
JComponent.AccessibleJComponent.AccessibleContainerHandler() - Constructor for class javax.swing.JComponent.AccessibleJComponent.AccessibleContainerHandler
JComponent.AccessibleJComponent.AccessibleFocusHandler - Class in javax.swing
Fire PropertyChange listener, if one is registered, when focus events happen
JComponent.AccessibleJComponent.AccessibleFocusHandler() - Constructor for class javax.swing.JComponent.AccessibleJComponent.AccessibleFocusHandler
JCOMPONENT_UI - Static variable in class javax.print.ServiceUIFactory
Denotes a UI implemented as a Swing component.
jdbcCompliant() - Method in interface java.sql.Driver
Reports whether this driver is a genuine JDBC CompliantTM driver.
JdbcRowSet - Interface in javax.sql.rowset
The standard interface that all standard implementations of JdbcRowSet must implement.
JDesktopPane - Class in javax.swing
A container used to create a multiple-document interface or a virtual desktop.
JDesktopPane() - Constructor for class javax.swing.JDesktopPane
Creates a new JDesktopPane.
JDesktopPane.AccessibleJDesktopPane - Class in javax.swing
This class implements accessibility support for the JDesktopPane class.
JDesktopPane.AccessibleJDesktopPane() - Constructor for class javax.swing.JDesktopPane.AccessibleJDesktopPane
JDialog - Class in javax.swing
The main class for creating a dialog window.
JDialog() - Constructor for class javax.swing.JDialog
Creates a modeless dialog without a title and without a specified Frame owner.
JDialog(Frame) - Constructor for class javax.swing.JDialog
Creates a modeless dialog with the specified Frame as its owner and an empty title.
JDialog(Frame, boolean) - Constructor for class javax.swing.JDialog
Creates a dialog with an empty title and the specified modality and Frame as its owner.
JDialog(Frame, String) - Constructor for class javax.swing.JDialog
Creates a modeless dialog with the specified title and with the specified owner frame.
JDialog(Frame, String, boolean) - Constructor for class javax.swing.JDialog
Creates a dialog with the specified title, owner Frame and modality.
JDialog(Frame, String, boolean, GraphicsConfiguration) - Constructor for class javax.swing.JDialog
Creates a dialog with the specified title, owner Frame, modality and GraphicsConfiguration.
JDialog(Dialog) - Constructor for class javax.swing.JDialog
Creates a modeless dialog with the specified Dialog as its owner and an empty title.
JDialog(Dialog, boolean) - Constructor for class javax.swing.JDialog
Creates a dialog with an empty title and the specified modality and Dialog as its owner.
JDialog(Dialog, String) - Constructor for class javax.swing.JDialog
Creates a modeless dialog with the specified title and with the specified owner dialog.
JDialog(Dialog, String, boolean) - Constructor for class javax.swing.JDialog
Creates a dialog with the specified title, modality and the specified owner Dialog.
JDialog(Dialog, String, boolean, GraphicsConfiguration) - Constructor for class javax.swing.JDialog
Creates a dialog with the specified title, owner Dialog, modality and GraphicsConfiguration.
JDialog(Window) - Constructor for class javax.swing.JDialog
Creates a modeless dialog with the specified Window as its owner and an empty title.
JDialog(Window, Dialog.ModalityType) - Constructor for class javax.swing.JDialog
Creates a dialog with an empty title and the specified modality and Window as its owner.
JDialog(Window, String) - Constructor for class javax.swing.JDialog
Creates a modeless dialog with the specified title and owner Window.
JDialog(Window, String, Dialog.ModalityType) - Constructor for class javax.swing.JDialog
Creates a dialog with the specified title, owner Window and modality.
JDialog(Window, String, Dialog.ModalityType, GraphicsConfiguration) - Constructor for class javax.swing.JDialog
Creates a dialog with the specified title, owner Window, modality and GraphicsConfiguration.
JDialog.AccessibleJDialog - Class in javax.swing
This class implements accessibility support for the JDialog class.
JDialog.AccessibleJDialog() - Constructor for class javax.swing.JDialog.AccessibleJDialog
JDIALOG_UI - Static variable in class javax.print.ServiceUIFactory
Denotes a UI implemented as a Swing dialog.
JEditorPane - Class in javax.swing
A text component to edit various kinds of content.
JEditorPane() - Constructor for class javax.swing.JEditorPane
Creates a new JEditorPane.
JEditorPane(URL) - Constructor for class javax.swing.JEditorPane
Creates a JEditorPane based on a specified URL for input.
JEditorPane(String) - Constructor for class javax.swing.JEditorPane
Creates a JEditorPane based on a string containing a URL specification.
JEditorPane(String, String) - Constructor for class javax.swing.JEditorPane
Creates a JEditorPane that has been initialized to the given text.
JEditorPane.AccessibleJEditorPane - Class in javax.swing
This class implements accessibility support for the JEditorPane class.
JEditorPane.AccessibleJEditorPane() - Constructor for class javax.swing.JEditorPane.AccessibleJEditorPane
JEditorPane.AccessibleJEditorPaneHTML - Class in javax.swing
This class provides support for AccessibleHypertext, and is used in instances where the EditorKit installed in this JEditorPane is an instance of HTMLEditorKit.
JEditorPane.AccessibleJEditorPaneHTML() - Constructor for class javax.swing.JEditorPane.AccessibleJEditorPaneHTML
JEditorPane.JEditorPaneAccessibleHypertextSupport - Class in javax.swing
What's returned by AccessibleJEditorPaneHTML.getAccessibleText.
JEditorPane.JEditorPaneAccessibleHypertextSupport() - Constructor for class javax.swing.JEditorPane.JEditorPaneAccessibleHypertextSupport
Make one of these puppies
JEditorPane.JEditorPaneAccessibleHypertextSupport.HTMLLink - Class in javax.swing
JEditorPane.JEditorPaneAccessibleHypertextSupport.HTMLLink(Element) - Constructor for class javax.swing.JEditorPane.JEditorPaneAccessibleHypertextSupport.HTMLLink
JFileChooser - Class in javax.swing
JFileChooser provides a simple mechanism for the user to choose a file.
JFileChooser() - Constructor for class javax.swing.JFileChooser
Constructs a JFileChooser pointing to the user's default directory.
JFileChooser(String) - Constructor for class javax.swing.JFileChooser
Constructs a JFileChooser using the given path.
JFileChooser(File) - Constructor for class javax.swing.JFileChooser
Constructs a JFileChooser using the given File as the path.
JFileChooser(FileSystemView) - Constructor for class javax.swing.JFileChooser
Constructs a JFileChooser using the given FileSystemView.
JFileChooser(File, FileSystemView) - Constructor for class javax.swing.JFileChooser
Constructs a JFileChooser using the given current directory and FileSystemView.
JFileChooser(String, FileSystemView) - Constructor for class javax.swing.JFileChooser
Constructs a JFileChooser using the given current directory path and FileSystemView.
JFileChooser.AccessibleJFileChooser - Class in javax.swing
This class implements accessibility support for the JFileChooser class.
JFileChooser.AccessibleJFileChooser() - Constructor for class javax.swing.JFileChooser.AccessibleJFileChooser
JFormattedTextField - Class in javax.swing
JFormattedTextField extends JTextField adding support for formatting arbitrary values, as well as retrieving a particular object once the user has edited the text.
JFormattedTextField() - Constructor for class javax.swing.JFormattedTextField
Creates a JFormattedTextField with no AbstractFormatterFactory.
JFormattedTextField(Object) - Constructor for class javax.swing.JFormattedTextField
Creates a JFormattedTextField with the specified value.
JFormattedTextField(Format) - Constructor for class javax.swing.JFormattedTextField
Creates a JFormattedTextField.
JFormattedTextField(JFormattedTextField.AbstractFormatter) - Constructor for class javax.swing.JFormattedTextField
Creates a JFormattedTextField with the specified AbstractFormatter.
JFormattedTextField(JFormattedTextField.AbstractFormatterFactory) - Constructor for class javax.swing.JFormattedTextField
Creates a JFormattedTextField with the specified AbstractFormatterFactory.
JFormattedTextField(JFormattedTextField.AbstractFormatterFactory, Object) - Constructor for class javax.swing.JFormattedTextField
Creates a JFormattedTextField with the specified AbstractFormatterFactory and initial value.
JFormattedTextField.AbstractFormatter - Class in javax.swing
Instances of AbstractFormatter are used by JFormattedTextField to handle the conversion both from an Object to a String, and back from a String to an Object.
JFormattedTextField.AbstractFormatter() - Constructor for class javax.swing.JFormattedTextField.AbstractFormatter
JFormattedTextField.AbstractFormatterFactory - Class in javax.swing
Instances of AbstractFormatterFactory are used by JFormattedTextField to obtain instances of AbstractFormatter which in turn are used to format values.
JFormattedTextField.AbstractFormatterFactory() - Constructor for class javax.swing.JFormattedTextField.AbstractFormatterFactory
JFrame - Class in javax.swing
An extended version of java.awt.Frame that adds support for the JFC/Swing component architecture.
JFrame() - Constructor for class javax.swing.JFrame
Constructs a new frame that is initially invisible.
JFrame(GraphicsConfiguration) - Constructor for class javax.swing.JFrame
Creates a Frame in the specified GraphicsConfiguration of a screen device and a blank title.
JFrame(String) - Constructor for class javax.swing.JFrame
Creates a new, initially invisible Frame with the specified title.
JFrame(String, GraphicsConfiguration) - Constructor for class javax.swing.JFrame
Creates a JFrame with the specified title and the specified GraphicsConfiguration of a screen device.
JFrame.AccessibleJFrame - Class in javax.swing
This class implements accessibility support for the JFrame class.
JFrame.AccessibleJFrame() - Constructor for class javax.swing.JFrame.AccessibleJFrame
JInternalFrame - Class in javax.swing
A lightweight object that provides many of the features of a native frame, including dragging, closing, becoming an icon, resizing, title display, and support for a menu bar.
JInternalFrame() - Constructor for class javax.swing.JInternalFrame
Creates a non-resizable, non-closable, non-maximizable, non-iconifiable JInternalFrame with no title.
JInternalFrame(String) - Constructor for class javax.swing.JInternalFrame
Creates a non-resizable, non-closable, non-maximizable, non-iconifiable JInternalFrame with the specified title.
JInternalFrame(String, boolean) - Constructor for class javax.swing.JInternalFrame
Creates a non-closable, non-maximizable, non-iconifiable JInternalFrame with the specified title and resizability.
JInternalFrame(String, boolean, boolean) - Constructor for class javax.swing.JInternalFrame
Creates a non-maximizable, non-iconifiable JInternalFrame with the specified title, resizability, and closability.
JInternalFrame(String, boolean, boolean, boolean) - Constructor for class javax.swing.JInternalFrame
Creates a non-iconifiable JInternalFrame with the specified title, resizability, closability, and maximizability.
JInternalFrame(String, boolean, boolean, boolean, boolean) - Constructor for class javax.swing.JInternalFrame
Creates a JInternalFrame with the specified title, resizability, closability, maximizability, and iconifiability.
JInternalFrame.AccessibleJInternalFrame - Class in javax.swing
This class implements accessibility support for the JInternalFrame class.
JInternalFrame.AccessibleJInternalFrame() - Constructor for class javax.swing.JInternalFrame.AccessibleJInternalFrame
JInternalFrame.JDesktopIcon - Class in javax.swing
This component represents an iconified version of a JInternalFrame.
JInternalFrame.JDesktopIcon(JInternalFrame) - Constructor for class javax.swing.JInternalFrame.JDesktopIcon
Creates an icon for an internal frame.
JInternalFrame.JDesktopIcon.AccessibleJDesktopIcon - Class in javax.swing
This class implements accessibility support for the JInternalFrame.JDesktopIcon class.
JInternalFrame.JDesktopIcon.AccessibleJDesktopIcon() - Constructor for class javax.swing.JInternalFrame.JDesktopIcon.AccessibleJDesktopIcon
JIS_B0 - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for JIS B0, 1030 x 1456 mm.
JIS_B0 - Static variable in class javax.print.attribute.standard.MediaSizeName
JIS B0 size.
JIS_B1 - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for JIS B1, 728 x 1030 mm.
JIS_B1 - Static variable in class javax.print.attribute.standard.MediaSizeName
JIS B1 size.
JIS_B10 - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for JIS B10, 32 x 45 mm.
JIS_B10 - Static variable in class javax.print.attribute.standard.MediaSizeName
JIS B10 size.
JIS_B2 - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for JIS B2, 515 x 728 mm.
JIS_B2 - Static variable in class javax.print.attribute.standard.MediaSizeName
JIS B2 size.
JIS_B3 - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for JIS B3, 364 x 515 mm.
JIS_B3 - Static variable in class javax.print.attribute.standard.MediaSizeName
JIS B3 size.
JIS_B4 - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for JIS B4, 257 x 364 mm.
JIS_B4 - Static variable in class javax.print.attribute.standard.MediaSizeName
JIS B4 size.
JIS_B5 - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for JIS B5, 182 x 257 mm.
JIS_B5 - Static variable in class javax.print.attribute.standard.MediaSizeName
JIS B5 size.
JIS_B6 - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for JIS B6, 128 x 182 mm.
JIS_B6 - Static variable in class javax.print.attribute.standard.MediaSizeName
JIS B6 size.
JIS_B7 - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for JIS B7, 91 x 128 mm.
JIS_B7 - Static variable in class javax.print.attribute.standard.MediaSizeName
JIS B7 size.
JIS_B8 - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for JIS B8, 64 x 91 mm.
JIS_B8 - Static variable in class javax.print.attribute.standard.MediaSizeName
JIS B8 size.
JIS_B9 - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for JIS B9, 45 x 64 mm.
JIS_B9 - Static variable in class javax.print.attribute.standard.MediaSizeName
JIS B9 size.
JLabel - Class in javax.swing
A display area for a short text string or an image, or both.
JLabel(String, Icon, int) - Constructor for class javax.swing.JLabel
Creates a JLabel instance with the specified text, image, and horizontal alignment.
JLabel(String, int) - Constructor for class javax.swing.JLabel
Creates a JLabel instance with the specified text and horizontal alignment.
JLabel(String) - Constructor for class javax.swing.JLabel
Creates a JLabel instance with the specified text.
JLabel(Icon, int) - Constructor for class javax.swing.JLabel
Creates a JLabel instance with the specified image and horizontal alignment.
JLabel(Icon) - Constructor for class javax.swing.JLabel
Creates a JLabel instance with the specified image.
JLabel() - Constructor for class javax.swing.JLabel
Creates a JLabel instance with no image and with an empty string for the title.
JLabel.AccessibleJLabel - Class in javax.swing
The class used to obtain the accessible role for this object.
JLabel.AccessibleJLabel() - Constructor for class javax.swing.JLabel.AccessibleJLabel
JLayer<V extends Component> - Class in javax.swing
JLayer is a universal decorator for Swing components which enables you to implement various advanced painting effects as well as receive notifications of all AWTEvents generated within its borders.
JLayer() - Constructor for class javax.swing.JLayer
Creates a new JLayer object with a null view component and default LayerUI.
JLayer(V) - Constructor for class javax.swing.JLayer
Creates a new JLayer object with default LayerUI.
JLayer(V, LayerUI<V>) - Constructor for class javax.swing.JLayer
Creates a new JLayer object with the specified view component and LayerUI object.
JLayeredPane - Class in javax.swing
JLayeredPane adds depth to a JFC/Swing container, allowing components to overlap each other when needed.
JLayeredPane() - Constructor for class javax.swing.JLayeredPane
Create a new JLayeredPane
JLayeredPane.AccessibleJLayeredPane - Class in javax.swing
This class implements accessibility support for the JLayeredPane class.
JLayeredPane.AccessibleJLayeredPane() - Constructor for class javax.swing.JLayeredPane.AccessibleJLayeredPane
JList<E> - Class in javax.swing
A component that displays a list of objects and allows the user to select one or more items.
JList(ListModel<E>) - Constructor for class javax.swing.JList
Constructs a JList that displays elements from the specified, non-null, model.
JList(E[]) - Constructor for class javax.swing.JList
Constructs a JList that displays the elements in the specified array.
JList(Vector<? extends E>) - Constructor for class javax.swing.JList
Constructs a JList that displays the elements in the specified Vector.
JList() - Constructor for class javax.swing.JList
Constructs a JList with an empty, read-only, model.
JList.AccessibleJList - Class in javax.swing
This class implements accessibility support for the JList class.
JList.AccessibleJList() - Constructor for class javax.swing.JList.AccessibleJList
JList.AccessibleJList.AccessibleJListChild - Class in javax.swing
This class implements accessibility support appropriate for list children.
JList.AccessibleJList.AccessibleJListChild(JList<E>, int) - Constructor for class javax.swing.JList.AccessibleJList.AccessibleJListChild
JList.DropLocation - Class in javax.swing
A subclass of TransferHandler.DropLocation representing a drop location for a JList.
JMenu - Class in javax.swing
An implementation of a menu -- a popup window containing JMenuItems that is displayed when the user selects an item on the JMenuBar.
JMenu() - Constructor for class javax.swing.JMenu
Constructs a new JMenu with no text.
JMenu(String) - Constructor for class javax.swing.JMenu
Constructs a new JMenu with the supplied string as its text.
JMenu(Action) - Constructor for class javax.swing.JMenu
Constructs a menu whose properties are taken from the Action supplied.
JMenu(String, boolean) - Constructor for class javax.swing.JMenu
Constructs a new JMenu with the supplied string as its text and specified as a tear-off menu or not.
JMenu.AccessibleJMenu - Class in javax.swing
This class implements accessibility support for the JMenu class.
JMenu.AccessibleJMenu() - Constructor for class javax.swing.JMenu.AccessibleJMenu
JMenu.WinListener - Class in javax.swing
A listener class that watches for a popup window closing.
JMenu.WinListener(JPopupMenu) - Constructor for class javax.swing.JMenu.WinListener
Create the window listener for the specified popup.
JMenuBar - Class in javax.swing
An implementation of a menu bar.
JMenuBar() - Constructor for class javax.swing.JMenuBar
Creates a new menu bar.
JMenuBar.AccessibleJMenuBar - Class in javax.swing
This class implements accessibility support for the JMenuBar class.
JMenuBar.AccessibleJMenuBar() - Constructor for class javax.swing.JMenuBar.AccessibleJMenuBar
JMenuItem - Class in javax.swing
An implementation of an item in a menu.
JMenuItem() - Constructor for class javax.swing.JMenuItem
Creates a JMenuItem with no set text or icon.
JMenuItem(Icon) - Constructor for class javax.swing.JMenuItem
Creates a JMenuItem with the specified icon.
JMenuItem(String) - Constructor for class javax.swing.JMenuItem
Creates a JMenuItem with the specified text.
JMenuItem(Action) - Constructor for class javax.swing.JMenuItem
Creates a menu item whose properties are taken from the specified Action.
JMenuItem(String, Icon) - Constructor for class javax.swing.JMenuItem
Creates a JMenuItem with the specified text and icon.
JMenuItem(String, int) - Constructor for class javax.swing.JMenuItem
Creates a JMenuItem with the specified text and keyboard mnemonic.
JMenuItem.AccessibleJMenuItem - Class in javax.swing
This class implements accessibility support for the JMenuItem class.
JMException - Exception in javax.management
Exceptions thrown by JMX implementations.
JMException() - Constructor for exception javax.management.JMException
Default constructor.
JMException(String) - Constructor for exception javax.management.JMException
Constructor that allows a specific error message to be specified.
JMRuntimeException - Exception in javax.management
Runtime exceptions emitted by JMX implementations.
JMRuntimeException() - Constructor for exception javax.management.JMRuntimeException
Default constructor.
JMRuntimeException(String) - Constructor for exception javax.management.JMRuntimeException
Constructor that allows a specific error message to be specified.
JMX - Class in javax.management
Static methods from the JMX API.
JMXAddressable - Interface in javax.management.remote
Implemented by objects that can have a JMXServiceURL address.
JMXAuthenticator - Interface in javax.management.remote
Interface to define how remote credentials are converted into a JAAS Subject.
JMXConnectionNotification - Class in javax.management.remote
Notification emitted when a client connection is opened or closed or when notifications are lost.
JMXConnectionNotification(String, Object, String, long, String, Object) - Constructor for class javax.management.remote.JMXConnectionNotification
Constructs a new connection notification.
JMXConnector - Interface in javax.management.remote
The client end of a JMX API connector.
JMXConnectorFactory - Class in javax.management.remote
Factory to create JMX API connector clients.
JMXConnectorProvider - Interface in javax.management.remote
A provider for creating JMX API connector clients using a given protocol.
JMXConnectorServer - Class in javax.management.remote
Superclass of every connector server.
JMXConnectorServer() - Constructor for class javax.management.remote.JMXConnectorServer
Constructs a connector server that will be registered as an MBean in the MBean server it is attached to.
JMXConnectorServer(MBeanServer) - Constructor for class javax.management.remote.JMXConnectorServer
Constructs a connector server that is attached to the given MBean server.
JMXConnectorServerFactory - Class in javax.management.remote
Factory to create JMX API connector servers.
JMXConnectorServerMBean - Interface in javax.management.remote
MBean interface for connector servers.
JMXConnectorServerProvider - Interface in javax.management.remote
A provider for creating JMX API connector servers using a given protocol.
JMXPrincipal - Class in javax.management.remote
The identity of a remote client of the JMX Remote API.
JMXPrincipal(String) - Constructor for class javax.management.remote.JMXPrincipal
Creates a JMXPrincipal for a given identity.
JMXProviderException - Exception in javax.management.remote
Exception thrown by JMXConnectorFactory and JMXConnectorServerFactory when a provider exists for the required protocol but cannot be used for some reason.
JMXProviderException() - Constructor for exception javax.management.remote.JMXProviderException
Constructs a JMXProviderException with no specified detail message.
JMXProviderException(String) - Constructor for exception javax.management.remote.JMXProviderException
Constructs a JMXProviderException with the specified detail message.
JMXProviderException(String, Throwable) - Constructor for exception javax.management.remote.JMXProviderException
Constructs a JMXProviderException with the specified detail message and nested exception.
JMXServerErrorException - Exception in javax.management.remote
Exception thrown as the result of a remote MBeanServer method invocation when an Error is thrown while processing the invocation in the remote MBean server.
JMXServerErrorException(String, Error) - Constructor for exception javax.management.remote.JMXServerErrorException
Constructs a JMXServerErrorException with the specified detail message and nested error.
JMXServiceURL - Class in javax.management.remote
The address of a JMX API connector server.
JMXServiceURL(String) - Constructor for class javax.management.remote.JMXServiceURL
Constructs a JMXServiceURL by parsing a Service URL string.
JMXServiceURL(String, String, int) - Constructor for class javax.management.remote.JMXServiceURL
Constructs a JMXServiceURL with the given protocol, host, and port.
JMXServiceURL(String, String, int, String) - Constructor for class javax.management.remote.JMXServiceURL
Constructs a JMXServiceURL with the given parts.
JNDI_REBIND_ATTRIBUTE - Static variable in class javax.management.remote.rmi.RMIConnectorServer
Name of the attribute that specifies whether the RMIServer stub that represents an RMI connector server should override an existing stub at the same address.
JOB_CANCELED - Static variable in class javax.print.event.PrintJobEvent
The job was canceled by the PrintService.
JOB_CANCELED_AT_DEVICE - Static variable in class javax.print.attribute.standard.JobStateReason
The job was canceled by an unidentified local user, i.e., a user at a console at the device.
JOB_CANCELED_BY_OPERATOR - Static variable in class javax.print.attribute.standard.JobStateReason
The job was canceled by the operator, i.e., by a user who has been authenticated as having operator privileges (whether local or remote).
JOB_CANCELED_BY_USER - Static variable in class javax.print.attribute.standard.JobStateReason
The job was canceled by the owner of the job, i.e., by a user whose authenticated identity is the same as the value of the originating user that created the Print Job, or by some other authorized end-user, such as a member of the job owner's security group.
JOB_COMPLETE - Static variable in class javax.print.event.PrintJobEvent
The document cis completely printed.
JOB_COMPLETED_SUCCESSFULLY - Static variable in class javax.print.attribute.standard.JobStateReason
The job completed successfully.
JOB_COMPLETED_WITH_ERRORS - Static variable in class javax.print.attribute.standard.JobStateReason
The job completed with errors (and possibly warnings too).
JOB_COMPLETED_WITH_WARNINGS - Static variable in class javax.print.attribute.standard.JobStateReason
The job completed with warnings.
JOB_DATA_INSUFFICIENT - Static variable in class javax.print.attribute.standard.JobStateReason
The printer has created the Print Job, but the printer is expecting additional print data before it can move the job into the PROCESSING state.
JOB_FAILED - Static variable in class javax.print.event.PrintJobEvent
The print service reports that the job cannot be completed.
JOB_HOLD_UNTIL_SPECIFIED - Static variable in class javax.print.attribute.standard.JobStateReason
The value of the job's JobHoldUntil attribute was specified with a date-time that is still in the future.
JOB_INCOMING - Static variable in class javax.print.attribute.standard.JobStateReason
The printer has created the Print Job, but the printer has not finished accessing or accepting all the print data yet.
JOB_INTERPRETING - Static variable in class javax.print.attribute.standard.JobStateReason
The job is in the PROCESSING state, but more specifically, the printer ia interpreting the document data.
JOB_OUTGOING - Static variable in class javax.print.attribute.standard.JobStateReason
The printer is transmitting the job to the output device.
JOB_PRINTING - Static variable in class javax.print.attribute.standard.JobStateReason
The output device is marking media.
JOB_QUEUED - Static variable in class javax.print.attribute.standard.JobStateReason
The job is in the PROCESSING state, but more specifically, the printer has queued the document data.
JOB_QUEUED_FOR_MARKER - Static variable in class javax.print.attribute.standard.JobStateReason
The job is in the PENDING_HELD, PENDING, or PROCESSING state, but more specifically, the printer has completed enough processing of the document to be able to start marking and the job is waiting for the marker.
JOB_RESTARTABLE - Static variable in class javax.print.attribute.standard.JobStateReason
This job is retained and is currently able to be restarted.
JOB_TRANSFORMING - Static variable in class javax.print.attribute.standard.JobStateReason
The job is in the PROCESSING state, but more specifically, the printer is interpreting document data and producing another electronic representation.
JobAttributes - Class in java.awt
A set of attributes which control a print job.
JobAttributes() - Constructor for class java.awt.JobAttributes
Constructs a JobAttributes instance with default values for every attribute.
JobAttributes(JobAttributes) - Constructor for class java.awt.JobAttributes
Constructs a JobAttributes instance which is a copy of the supplied JobAttributes.
JobAttributes(int, JobAttributes.DefaultSelectionType, JobAttributes.DestinationType, JobAttributes.DialogType, String, int, int, JobAttributes.MultipleDocumentHandlingType, int[][], String, JobAttributes.SidesType) - Constructor for class java.awt.JobAttributes
Constructs a JobAttributes instance with the specified values for every attribute.
JobAttributes.DefaultSelectionType - Class in java.awt
A type-safe enumeration of possible default selection states.
JobAttributes.DestinationType - Class in java.awt
A type-safe enumeration of possible job destinations.
JobAttributes.DialogType - Class in java.awt
A type-safe enumeration of possible dialogs to display to the user.
JobAttributes.MultipleDocumentHandlingType - Class in java.awt
A type-safe enumeration of possible multiple copy handling states.
JobAttributes.SidesType - Class in java.awt
A type-safe enumeration of possible multi-page impositions.
JobHoldUntil - Class in javax.print.attribute.standard
Class JobHoldUntil is a printing attribute class, a date-time attribute, that specifies the exact date and time at which the job must become a candidate for printing.
JobHoldUntil(Date) - Constructor for class javax.print.attribute.standard.JobHoldUntil
Construct a new job hold until date-time attribute with the given Date value.
JobImpressions - Class in javax.print.attribute.standard
Class JobImpressions is an integer valued printing attribute class that specifies the total size in number of impressions of the document(s) being submitted.
JobImpressions(int) - Constructor for class javax.print.attribute.standard.JobImpressions
Construct a new job impressions attribute with the given integer value.
JobImpressionsCompleted - Class in javax.print.attribute.standard
Class JobImpressionsCompleted is an integer valued printing attribute class that specifies the number of impressions completed for the job so far.
JobImpressionsCompleted(int) - Constructor for class javax.print.attribute.standard.JobImpressionsCompleted
Construct a new job impressions completed attribute with the given integer value.
JobImpressionsSupported - Class in javax.print.attribute.standard
Class JobImpressionsSupported is a printing attribute class, a set of integers, that gives the supported values for a JobImpressions attribute.
JobImpressionsSupported(int, int) - Constructor for class javax.print.attribute.standard.JobImpressionsSupported
Construct a new job impressions supported attribute containing a single range of integers.
JobKOctets - Class in javax.print.attribute.standard
Class JobKOctets is an integer valued printing attribute class that specifies the total size of the document(s) in K octets, i.e., in units of 1024 octets requested to be processed in the job.
JobKOctets(int) - Constructor for class javax.print.attribute.standard.JobKOctets
Construct a new job K octets attribute with the given integer value.
JobKOctetsProcessed - Class in javax.print.attribute.standard
Class JobKOctetsProcessed is an integer valued printing attribute class that specifies the total number of print data octets processed so far in K octets, i.e., in units of 1024 octets.
JobKOctetsProcessed(int) - Constructor for class javax.print.attribute.standard.JobKOctetsProcessed
Construct a new job K octets processed attribute with the given integer value.
JobKOctetsSupported - Class in javax.print.attribute.standard
Class JobKOctetsSupported is a printing attribute class, a set of integers, that gives the supported values for a JobKOctets attribute.
JobKOctetsSupported(int, int) - Constructor for class javax.print.attribute.standard.JobKOctetsSupported
Construct a new job K octets supported attribute containing a single range of integers.
JobMediaSheets - Class in javax.print.attribute.standard
Class JobMediaSheets is an integer valued printing attribute class that specifies the total number of media sheets to be produced for this job.
JobMediaSheets(int) - Constructor for class javax.print.attribute.standard.JobMediaSheets
Construct a new job media sheets attribute with the given integer value.
JobMediaSheetsCompleted - Class in javax.print.attribute.standard
Class JobMediaSheetsCompleted is an integer valued printing attribute class that specifies the number of media sheets which have completed marking and stacking for the entire job so far, whether those sheets have been processed on one side or on both.
JobMediaSheetsCompleted(int) - Constructor for class javax.print.attribute.standard.JobMediaSheetsCompleted
Construct a new job media sheets completed attribute with the given integer value.
JobMediaSheetsSupported - Class in javax.print.attribute.standard
Class JobMediaSheetsSupported is a printing attribute class, a set of integers, that gives the supported values for a JobMediaSheets attribute.
JobMediaSheetsSupported(int, int) - Constructor for class javax.print.attribute.standard.JobMediaSheetsSupported
Construct a new job media sheets supported attribute containing a single range of integers.
JobMessageFromOperator - Class in javax.print.attribute.standard
Class JobMessageFromOperator is a printing attribute class, a text attribute, that provides a message from an operator, system administrator, or "intelligent" process to indicate to the end user the reasons for modification or other management action taken on a job.
JobMessageFromOperator(String, Locale) - Constructor for class javax.print.attribute.standard.JobMessageFromOperator
Constructs a new job message from operator attribute with the given message and locale.
JobName - Class in javax.print.attribute.standard
Class JobName is a printing attribute class, a text attribute, that specifies the name of a print job.
JobName(String, Locale) - Constructor for class javax.print.attribute.standard.JobName
Constructs a new job name attribute with the given job name and locale.
JobOriginatingUserName - Class in javax.print.attribute.standard
Class JobOriginatingUserName is a printing attribute class, a text attribute, that contains the name of the end user that submitted the print job.
JobOriginatingUserName(String, Locale) - Constructor for class javax.print.attribute.standard.JobOriginatingUserName
Constructs a new job originating user name attribute with the given user name and locale.
JobPriority - Class in javax.print.attribute.standard
Class JobPriority is an integer valued printing attribute class that specifies a print job's priority.
JobPriority(int) - Constructor for class javax.print.attribute.standard.JobPriority
Construct a new job priority attribute with the given integer value.
JobPrioritySupported - Class in javax.print.attribute.standard
Class JobPrioritySupported is an integer valued printing attribute class that specifies whether a Print Service instance supports the JobPriority attribute and the number of different job priority levels supported.
JobPrioritySupported(int) - Constructor for class javax.print.attribute.standard.JobPrioritySupported
Construct a new job priority supported attribute with the given integer value.
JobSheets - Class in javax.print.attribute.standard
Class JobSheets is a printing attribute class, an enumeration, that determines which job start and end sheets, if any, must be printed with a job.
JobSheets(int) - Constructor for class javax.print.attribute.standard.JobSheets
Construct a new job sheets enumeration value with the given integer value.
JobState - Class in javax.print.attribute.standard
JobState is a printing attribute class, an enumeration, that identifies the current state of a print job.
JobState(int) - Constructor for class javax.print.attribute.standard.JobState
Construct a new job state enumeration value with the given integer value.
JobStateReason - Class in javax.print.attribute.standard
Class JobStateReason is a printing attribute class, an enumeration, that provides additional information about the job's current state, i.e., information that augments the value of the job's JobState attribute.
JobStateReason(int) - Constructor for class javax.print.attribute.standard.JobStateReason
Construct a new job state reason enumeration value with the given integer value.
JobStateReasons - Class in javax.print.attribute.standard
Class JobStateReasons is a printing attribute class, a set of enumeration values, that provides additional information about the job's current state, i.e., information that augments the value of the job's JobState attribute.
JobStateReasons() - Constructor for class javax.print.attribute.standard.JobStateReasons
Construct a new, empty job state reasons attribute; the underlying hash set has the default initial capacity and load factor.
JobStateReasons(int) - Constructor for class javax.print.attribute.standard.JobStateReasons
Construct a new, empty job state reasons attribute; the underlying hash set has the given initial capacity and the default load factor.
JobStateReasons(int, float) - Constructor for class javax.print.attribute.standard.JobStateReasons
Construct a new, empty job state reasons attribute; the underlying hash set has the given initial capacity and load factor.
JobStateReasons(Collection<JobStateReason>) - Constructor for class javax.print.attribute.standard.JobStateReasons
Construct a new job state reasons attribute that contains the same JobStateReason objects as the given collection.
join(long) - Method in class java.lang.Thread
Waits at most millis milliseconds for this thread to die.
join(long, int) - Method in class java.lang.Thread
Waits at most millis milliseconds plus nanos nanoseconds for this thread to die.
join() - Method in class java.lang.Thread
Waits for this thread to die.
join(InetAddress) - Method in class java.net.DatagramSocketImpl
Join the multicast group.
join(InetAddress, NetworkInterface) - Method in interface java.nio.channels.MulticastChannel
Joins a multicast group to begin receiving all datagrams sent to the group, returning a membership key.
join(InetAddress, NetworkInterface, InetAddress) - Method in interface java.nio.channels.MulticastChannel
Joins a multicast group to begin receiving datagrams sent to the group from a given source address.
join() - Method in class java.util.concurrent.ForkJoinTask
Returns the result of the computation when it is done.
JOIN_BEVEL - Static variable in class java.awt.BasicStroke
Joins path segments by connecting the outer corners of their wide outlines with a straight segment.
JOIN_MITER - Static variable in class java.awt.BasicStroke
Joins path segments by extending their outside edges until they meet.
JOIN_ROUND - Static variable in class java.awt.BasicStroke
Joins path segments by rounding off the corner at a radius of half the line width.
Joinable - Interface in javax.sql.rowset
1.0 Background
JoinFractureDirection - Static variable in class javax.swing.text.DefaultStyledDocument.ElementSpec
A possible value for getDirection.
joinGroup(SocketAddress, NetworkInterface) - Method in class java.net.DatagramSocketImpl
Join the multicast group.
joinGroup(InetAddress) - Method in class java.net.MulticastSocket
Joins a multicast group.
joinGroup(SocketAddress, NetworkInterface) - Method in class java.net.MulticastSocket
Joins the specified multicast group at the specified interface.
JoinNextDirection - Static variable in class javax.swing.text.DefaultStyledDocument.ElementSpec
A possible value for getDirection.
JoinPreviousDirection - Static variable in class javax.swing.text.DefaultStyledDocument.ElementSpec
A possible value for getDirection.
JoinRowSet - Interface in javax.sql.rowset
The JoinRowSet interface provides a mechanism for combining related data from different RowSet objects into one JoinRowSet object, which represents an SQL JOIN.
JOptionPane - Class in javax.swing
JOptionPane makes it easy to pop up a standard dialog box that prompts users for a value or informs them of something.
JOptionPane() - Constructor for class javax.swing.JOptionPane
Creates a JOptionPane with a test message.
JOptionPane(Object) - Constructor for class javax.swing.JOptionPane
Creates a instance of JOptionPane to display a message using the plain-message message type and the default options delivered by the UI.
JOptionPane(Object, int) - Constructor for class javax.swing.JOptionPane
Creates an instance of JOptionPane to display a message with the specified message type and the default options,
JOptionPane(Object, int, int) - Constructor for class javax.swing.JOptionPane
Creates an instance of JOptionPane to display a message with the specified message type and options.
JOptionPane(Object, int, int, Icon) - Constructor for class javax.swing.JOptionPane
Creates an instance of JOptionPane to display a message with the specified message type, options, and icon.
JOptionPane(Object, int, int, Icon, Object[]) - Constructor for class javax.swing.JOptionPane
Creates an instance of JOptionPane to display a message with the specified message type, icon, and options.
JOptionPane(Object, int, int, Icon, Object[], Object) - Constructor for class javax.swing.JOptionPane
Creates an instance of JOptionPane to display a message with the specified message type, icon, and options, with the initially-selected option specified.
JOptionPane.AccessibleJOptionPane - Class in javax.swing
This class implements accessibility support for the JOptionPane class.
JOptionPane.AccessibleJOptionPane() - Constructor for class javax.swing.JOptionPane.AccessibleJOptionPane
JPanel - Class in javax.swing
JPanel is a generic lightweight container.
JPanel(LayoutManager, boolean) - Constructor for class javax.swing.JPanel
Creates a new JPanel with the specified layout manager and buffering strategy.
JPanel(LayoutManager) - Constructor for class javax.swing.JPanel
Create a new buffered JPanel with the specified layout manager
JPanel(boolean) - Constructor for class javax.swing.JPanel
Creates a new JPanel with FlowLayout and the specified buffering strategy.
JPanel() - Constructor for class javax.swing.JPanel
Creates a new JPanel with a double buffer and a flow layout.
JPanel.AccessibleJPanel - Class in javax.swing
This class implements accessibility support for the JPanel class.
JPanel.AccessibleJPanel() - Constructor for class javax.swing.JPanel.AccessibleJPanel
JPasswordField - Class in javax.swing
JPasswordField is a lightweight component that allows the editing of a single line of text where the view indicates something was typed, but does not show the original characters.
JPasswordField() - Constructor for class javax.swing.JPasswordField
Constructs a new JPasswordField, with a default document, null starting text string, and 0 column width.
JPasswordField(String) - Constructor for class javax.swing.JPasswordField
Constructs a new JPasswordField initialized with the specified text.
JPasswordField(int) - Constructor for class javax.swing.JPasswordField
Constructs a new empty JPasswordField with the specified number of columns.
JPasswordField(String, int) - Constructor for class javax.swing.JPasswordField
Constructs a new JPasswordField initialized with the specified text and columns.
JPasswordField(Document, String, int) - Constructor for class javax.swing.JPasswordField
Constructs a new JPasswordField that uses the given text storage model and the given number of columns.
JPasswordField.AccessibleJPasswordField - Class in javax.swing
This class implements accessibility support for the JPasswordField class.
JPasswordField.AccessibleJPasswordField() - Constructor for class javax.swing.JPasswordField.AccessibleJPasswordField
JPEG - Static variable in class javax.print.DocFlavor.BYTE_ARRAY
Doc flavor with MIME type = "image/jpeg", print data representation class name = "[B" (byte array).
JPEG - Static variable in class javax.print.DocFlavor.INPUT_STREAM
Doc flavor with MIME type = "image/jpeg", print data representation class name = "java.io.InputStream" (byte stream).
JPEG - Static variable in class javax.print.DocFlavor.URL
Doc flavor with MIME type = "image/jpeg", print data representation class name = "java.net.URL".
JPEGHuffmanTable - Class in javax.imageio.plugins.jpeg
A class encapsulating a single JPEG Huffman table.
JPEGHuffmanTable(short[], short[]) - Constructor for class javax.imageio.plugins.jpeg.JPEGHuffmanTable
Creates a Huffman table and initializes it.
JPEGImageReadParam - Class in javax.imageio.plugins.jpeg
This class adds the ability to set JPEG quantization and Huffman tables when using the built-in JPEG reader plug-in.
JPEGImageReadParam() - Constructor for class javax.imageio.plugins.jpeg.JPEGImageReadParam
Constructs a JPEGImageReadParam.
JPEGImageWriteParam - Class in javax.imageio.plugins.jpeg
This class adds the ability to set JPEG quantization and Huffman tables when using the built-in JPEG writer plug-in, and to request that optimized Huffman tables be computed for an image.
JPEGImageWriteParam(Locale) - Constructor for class javax.imageio.plugins.jpeg.JPEGImageWriteParam
Constructs a JPEGImageWriteParam.
JPEGQTable - Class in javax.imageio.plugins.jpeg
A class encapsulating a single JPEG quantization table.
JPEGQTable(int[]) - Constructor for class javax.imageio.plugins.jpeg.JPEGQTable
Constructs a quantization table from the argument, which must contain 64 elements in natural order (not zig-zag order).
JPopupMenu - Class in javax.swing
An implementation of a popup menu -- a small window that pops up and displays a series of choices.
JPopupMenu() - Constructor for class javax.swing.JPopupMenu
Constructs a JPopupMenu without an "invoker".
JPopupMenu(String) - Constructor for class javax.swing.JPopupMenu
Constructs a JPopupMenu with the specified title.
JPopupMenu.AccessibleJPopupMenu - Class in javax.swing
This class implements accessibility support for the JPopupMenu class.
JPopupMenu.AccessibleJPopupMenu() - Constructor for class javax.swing.JPopupMenu.AccessibleJPopupMenu
AccessibleJPopupMenu constructor
JPopupMenu.Separator - Class in javax.swing
A popup menu-specific separator.
JPopupMenu.Separator() - Constructor for class javax.swing.JPopupMenu.Separator
JProgressBar - Class in javax.swing
A component that visually displays the progress of some task.
JProgressBar() - Constructor for class javax.swing.JProgressBar
Creates a horizontal progress bar that displays a border but no progress string.
JProgressBar(int) - Constructor for class javax.swing.JProgressBar
Creates a progress bar with the specified orientation, which can be either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.
JProgressBar(int, int) - Constructor for class javax.swing.JProgressBar
Creates a horizontal progress bar with the specified minimum and maximum.
JProgressBar(int, int, int) - Constructor for class javax.swing.JProgressBar
Creates a progress bar using the specified orientation, minimum, and maximum.
JProgressBar(BoundedRangeModel) - Constructor for class javax.swing.JProgressBar
Creates a horizontal progress bar that uses the specified model to hold the progress bar's data.
JProgressBar.AccessibleJProgressBar - Class in javax.swing
This class implements accessibility support for the JProgressBar class.
JProgressBar.AccessibleJProgressBar() - Constructor for class javax.swing.JProgressBar.AccessibleJProgressBar
JRadioButton - Class in javax.swing
An implementation of a radio button -- an item that can be selected or deselected, and which displays its state to the user.
JRadioButton() - Constructor for class javax.swing.JRadioButton
Creates an initially unselected radio button with no set text.
JRadioButton(Icon) - Constructor for class javax.swing.JRadioButton
Creates an initially unselected radio button with the specified image but no text.
JRadioButton(Action) - Constructor for class javax.swing.JRadioButton
Creates a radiobutton where properties are taken from the Action supplied.
JRadioButton(Icon, boolean) - Constructor for class javax.swing.JRadioButton
Creates a radio button with the specified image and selection state, but no text.
JRadioButton(String) - Constructor for class javax.swing.JRadioButton
Creates an unselected radio button with the specified text.
JRadioButton(String, boolean) - Constructor for class javax.swing.JRadioButton
Creates a radio button with the specified text and selection state.
JRadioButton(String, Icon) - Constructor for class javax.swing.JRadioButton
Creates a radio button that has the specified text and image, and that is initially unselected.
JRadioButton(String, Icon, boolean) - Constructor for class javax.swing.JRadioButton
Creates a radio button that has the specified text, image, and selection state.
JRadioButton.AccessibleJRadioButton - Class in javax.swing
This class implements accessibility support for the JRadioButton class.
JRadioButton.AccessibleJRadioButton() - Constructor for class javax.swing.JRadioButton.AccessibleJRadioButton
JRadioButtonMenuItem - Class in javax.swing
An implementation of a radio button menu item.
JRadioButtonMenuItem() - Constructor for class javax.swing.JRadioButtonMenuItem
Creates a JRadioButtonMenuItem with no set text or icon.
JRadioButtonMenuItem(Icon) - Constructor for class javax.swing.JRadioButtonMenuItem
Creates a JRadioButtonMenuItem with an icon.
JRadioButtonMenuItem(String) - Constructor for class javax.swing.JRadioButtonMenuItem
Creates a JRadioButtonMenuItem with text.
JRadioButtonMenuItem(Action) - Constructor for class javax.swing.JRadioButtonMenuItem
Creates a radio button menu item whose properties are taken from the Action supplied.
JRadioButtonMenuItem(String, Icon) - Constructor for class javax.swing.JRadioButtonMenuItem
Creates a radio button menu item with the specified text and Icon.
JRadioButtonMenuItem(String, boolean) - Constructor for class javax.swing.JRadioButtonMenuItem
Creates a radio button menu item with the specified text and selection state.
JRadioButtonMenuItem(Icon, boolean) - Constructor for class javax.swing.JRadioButtonMenuItem
Creates a radio button menu item with the specified image and selection state, but no text.
JRadioButtonMenuItem(String, Icon, boolean) - Constructor for class javax.swing.JRadioButtonMenuItem
Creates a radio button menu item that has the specified text, image, and selection state.
JRadioButtonMenuItem.AccessibleJRadioButtonMenuItem - Class in javax.swing
This class implements accessibility support for the JRadioButtonMenuItem class.
JRadioButtonMenuItem.AccessibleJRadioButtonMenuItem() - Constructor for class javax.swing.JRadioButtonMenuItem.AccessibleJRadioButtonMenuItem
JRootPane - Class in javax.swing
A lightweight container used behind the scenes by JFrame, JDialog, JWindow, JApplet, and JInternalFrame.
JRootPane() - Constructor for class javax.swing.JRootPane
Creates a JRootPane, setting up its glassPane, layeredPane, and contentPane.
JRootPane.AccessibleJRootPane - Class in javax.swing
This class implements accessibility support for the JRootPane class.
JRootPane.AccessibleJRootPane() - Constructor for class javax.swing.JRootPane.AccessibleJRootPane
JRootPane.RootLayout - Class in javax.swing
A custom layout manager that is responsible for the layout of layeredPane, glassPane, and menuBar.
JRootPane.RootLayout() - Constructor for class javax.swing.JRootPane.RootLayout
JScrollBar - Class in javax.swing
An implementation of a scrollbar.
JScrollBar(int, int, int, int, int) - Constructor for class javax.swing.JScrollBar
Creates a scrollbar with the specified orientation, value, extent, minimum, and maximum.
JScrollBar(int) - Constructor for class javax.swing.JScrollBar
Creates a scrollbar with the specified orientation and the following initial values:
JScrollBar() - Constructor for class javax.swing.JScrollBar
Creates a vertical scrollbar with the following initial values:
JScrollBar.AccessibleJScrollBar - Class in javax.swing
This class implements accessibility support for the JScrollBar class.
JScrollBar.AccessibleJScrollBar() - Constructor for class javax.swing.JScrollBar.AccessibleJScrollBar
JScrollPane - Class in javax.swing
Provides a scrollable view of a lightweight component.
JScrollPane(Component, int, int) - Constructor for class javax.swing.JScrollPane
Creates a JScrollPane that displays the view component in a viewport whose view position can be controlled with a pair of scrollbars.
JScrollPane(Component) - Constructor for class javax.swing.JScrollPane
Creates a JScrollPane that displays the contents of the specified component, where both horizontal and vertical scrollbars appear whenever the component's contents are larger than the view.
JScrollPane(int, int) - Constructor for class javax.swing.JScrollPane
Creates an empty (no viewport view) JScrollPane with specified scrollbar policies.
JScrollPane() - Constructor for class javax.swing.JScrollPane
Creates an empty (no viewport view) JScrollPane where both horizontal and vertical scrollbars appear when needed.
JScrollPane.AccessibleJScrollPane - Class in javax.swing
This class implements accessibility support for the JScrollPane class.
JScrollPane.AccessibleJScrollPane() - Constructor for class javax.swing.JScrollPane.AccessibleJScrollPane
AccessibleJScrollPane constructor
JScrollPane.ScrollBar - Class in javax.swing
By default JScrollPane creates scrollbars that are instances of this class.
JScrollPane.ScrollBar(int) - Constructor for class javax.swing.JScrollPane.ScrollBar
Creates a scrollbar with the specified orientation.
JSeparator - Class in javax.swing
JSeparator provides a general purpose component for implementing divider lines - most commonly used as a divider between menu items that breaks them up into logical groupings.
JSeparator() - Constructor for class javax.swing.JSeparator
Creates a new horizontal separator.
JSeparator(int) - Constructor for class javax.swing.JSeparator
Creates a new separator with the specified horizontal or vertical orientation.
JSeparator.AccessibleJSeparator - Class in javax.swing
This class implements accessibility support for the JSeparator class.
JSeparator.AccessibleJSeparator() - Constructor for class javax.swing.JSeparator.AccessibleJSeparator
JSlider - Class in javax.swing
A component that lets the user graphically select a value by sliding a knob within a bounded interval.
JSlider() - Constructor for class javax.swing.JSlider
Creates a horizontal slider with the range 0 to 100 and an initial value of 50.
JSlider(int) - Constructor for class javax.swing.JSlider
Creates a slider using the specified orientation with the range 0 to 100 and an initial value of 50.
JSlider(int, int) - Constructor for class javax.swing.JSlider
Creates a horizontal slider using the specified min and max with an initial value equal to the average of the min plus max.
JSlider(int, int, int) - Constructor for class javax.swing.JSlider
Creates a horizontal slider using the specified min, max and value.
JSlider(int, int, int, int) - Constructor for class javax.swing.JSlider
Creates a slider with the specified orientation and the specified minimum, maximum, and initial values.
JSlider(BoundedRangeModel) - Constructor for class javax.swing.JSlider
Creates a horizontal slider using the specified BoundedRangeModel.
JSlider.AccessibleJSlider - Class in javax.swing
This class implements accessibility support for the JSlider class.
JSlider.AccessibleJSlider() - Constructor for class javax.swing.JSlider.AccessibleJSlider
JSpinner - Class in javax.swing
A single line input field that lets the user select a number or an object value from an ordered sequence.
JSpinner(SpinnerModel) - Constructor for class javax.swing.JSpinner
Constructs a spinner for the given model.
JSpinner() - Constructor for class javax.swing.JSpinner
Constructs a spinner with an Integer SpinnerNumberModel with initial value 0 and no minimum or maximum limits.
JSpinner.AccessibleJSpinner - Class in javax.swing
AccessibleJSpinner implements accessibility support for the JSpinner class.
JSpinner.AccessibleJSpinner() - Constructor for class javax.swing.JSpinner.AccessibleJSpinner
AccessibleJSpinner constructor
JSpinner.DateEditor - Class in javax.swing
An editor for a JSpinner whose model is a SpinnerDateModel.
JSpinner.DateEditor(JSpinner) - Constructor for class javax.swing.JSpinner.DateEditor
Construct a JSpinner editor that supports displaying and editing the value of a SpinnerDateModel with a JFormattedTextField.
JSpinner.DateEditor(JSpinner, String) - Constructor for class javax.swing.JSpinner.DateEditor
Construct a JSpinner editor that supports displaying and editing the value of a SpinnerDateModel with a JFormattedTextField.
JSpinner.DefaultEditor - Class in javax.swing
A simple base class for more specialized editors that displays a read-only view of the model's current value with a JFormattedTextField.
JSpinner.DefaultEditor(JSpinner) - Constructor for class javax.swing.JSpinner.DefaultEditor
Constructs an editor component for the specified JSpinner.
JSpinner.ListEditor - Class in javax.swing
An editor for a JSpinner whose model is a SpinnerListModel.
JSpinner.ListEditor(JSpinner) - Constructor for class javax.swing.JSpinner.ListEditor
Construct a JSpinner editor that supports displaying and editing the value of a SpinnerListModel with a JFormattedTextField.
JSpinner.NumberEditor - Class in javax.swing
An editor for a JSpinner whose model is a SpinnerNumberModel.
JSpinner.NumberEditor(JSpinner) - Constructor for class javax.swing.JSpinner.NumberEditor
Construct a JSpinner editor that supports displaying and editing the value of a SpinnerNumberModel with a JFormattedTextField.
JSpinner.NumberEditor(JSpinner, String) - Constructor for class javax.swing.JSpinner.NumberEditor
Construct a JSpinner editor that supports displaying and editing the value of a SpinnerNumberModel with a JFormattedTextField.
JSplitPane - Class in javax.swing
JSplitPane is used to divide two (and only two) Components.
JSplitPane() - Constructor for class javax.swing.JSplitPane
Creates a new JSplitPane configured to arrange the child components side-by-side horizontally, using two buttons for the components.
JSplitPane(int) - Constructor for class javax.swing.JSplitPane
Creates a new JSplitPane configured with the specified orientation.
JSplitPane(int, boolean) - Constructor for class javax.swing.JSplitPane
Creates a new JSplitPane with the specified orientation and redrawing style.
JSplitPane(int, Component, Component) - Constructor for class javax.swing.JSplitPane
Creates a new JSplitPane with the specified orientation and the specified components.
JSplitPane(int, boolean, Component, Component) - Constructor for class javax.swing.JSplitPane
Creates a new JSplitPane with the specified orientation and redrawing style, and with the specified components.
JSplitPane.AccessibleJSplitPane - Class in javax.swing
This class implements accessibility support for the JSplitPane class.
JSplitPane.AccessibleJSplitPane() - Constructor for class javax.swing.JSplitPane.AccessibleJSplitPane
JTabbedPane - Class in javax.swing
A component that lets the user switch between a group of components by clicking on a tab with a given title and/or icon.
JTabbedPane() - Constructor for class javax.swing.JTabbedPane
Creates an empty TabbedPane with a default tab placement of JTabbedPane.TOP.
JTabbedPane(int) - Constructor for class javax.swing.JTabbedPane
Creates an empty TabbedPane with the specified tab placement of either: JTabbedPane.TOP, JTabbedPane.BOTTOM, JTabbedPane.LEFT, or JTabbedPane.RIGHT.
JTabbedPane(int, int) - Constructor for class javax.swing.JTabbedPane
Creates an empty TabbedPane with the specified tab placement and tab layout policy.
JTabbedPane.AccessibleJTabbedPane - Class in javax.swing
This class implements accessibility support for the JTabbedPane class.
JTabbedPane.AccessibleJTabbedPane() - Constructor for class javax.swing.JTabbedPane.AccessibleJTabbedPane
Constructs an AccessibleJTabbedPane
JTabbedPane.ModelListener - Class in javax.swing
We pass ModelChanged events along to the listeners with the tabbedpane (instead of the model itself) as the event source.
JTabbedPane.ModelListener() - Constructor for class javax.swing.JTabbedPane.ModelListener
JTable - Class in javax.swing
The JTable is used to display and edit regular two-dimensional tables of cells.
JTable() - Constructor for class javax.swing.JTable
Constructs a default JTable that is initialized with a default data model, a default column model, and a default selection model.
JTable(TableModel) - Constructor for class javax.swing.JTable
Constructs a JTable that is initialized with dm as the data model, a default column model, and a default selection model.
JTable(TableModel, TableColumnModel) - Constructor for class javax.swing.JTable
Constructs a JTable that is initialized with dm as the data model, cm as the column model, and a default selection model.
JTable(TableModel, TableColumnModel, ListSelectionModel) - Constructor for class javax.swing.JTable
Constructs a JTable that is initialized with dm as the data model, cm as the column model, and sm as the selection model.
JTable(int, int) - Constructor for class javax.swing.JTable
Constructs a JTable with numRows and numColumns of empty cells using DefaultTableModel.
JTable(Vector, Vector) - Constructor for class javax.swing.JTable
Constructs a JTable to display the values in the Vector of Vectors, rowData, with column names, columnNames.
JTable(Object[][], Object[]) - Constructor for class javax.swing.JTable
Constructs a JTable to display the values in the two dimensional array, rowData, with column names, columnNames.
JTable.AccessibleJTable - Class in javax.swing
This class implements accessibility support for the JTable class.
JTable.AccessibleJTable() - Constructor for class javax.swing.JTable.AccessibleJTable
AccessibleJTable constructor
JTable.AccessibleJTable.AccessibleJTableCell - Class in javax.swing
The class provides an implementation of the Java Accessibility API appropriate to table cells.
JTable.AccessibleJTable.AccessibleJTableCell(JTable, int, int, int) - Constructor for class javax.swing.JTable.AccessibleJTable.AccessibleJTableCell
Constructs an AccessibleJTableHeaderEntry.
JTable.AccessibleJTable.AccessibleJTableModelChange - Class in javax.swing
JTable.AccessibleJTable.AccessibleJTableModelChange(int, int, int, int, int) - Constructor for class javax.swing.JTable.AccessibleJTable.AccessibleJTableModelChange
JTable.DropLocation - Class in javax.swing
A subclass of TransferHandler.DropLocation representing a drop location for a JTable.
JTable.PrintMode - Enum in javax.swing
Printing modes, used in printing JTables.
JTableHeader - Class in javax.swing.table
This is the object which manages the header of the JTable.
JTableHeader() - Constructor for class javax.swing.table.JTableHeader
Constructs a JTableHeader with a default TableColumnModel.
JTableHeader(TableColumnModel) - Constructor for class javax.swing.table.JTableHeader
Constructs a JTableHeader which is initialized with cm as the column model.
JTableHeader.AccessibleJTableHeader - Class in javax.swing.table
This class implements accessibility support for the JTableHeader class.
JTableHeader.AccessibleJTableHeader() - Constructor for class javax.swing.table.JTableHeader.AccessibleJTableHeader
JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry - Class in javax.swing.table
This class provides an implementation of the Java Accessibility API appropropriate for JTableHeader entries.
JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry(int, JTableHeader, JTable) - Constructor for class javax.swing.table.JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry
Constructs an AccessiblJTableHeaaderEntry
JTextArea - Class in javax.swing
A JTextArea is a multi-line area that displays plain text.
JTextArea() - Constructor for class javax.swing.JTextArea
Constructs a new TextArea.
JTextArea(String) - Constructor for class javax.swing.JTextArea
Constructs a new TextArea with the specified text displayed.
JTextArea(int, int) - Constructor for class javax.swing.JTextArea
Constructs a new empty TextArea with the specified number of rows and columns.
JTextArea(String, int, int) - Constructor for class javax.swing.JTextArea
Constructs a new TextArea with the specified text and number of rows and columns.
JTextArea(Document) - Constructor for class javax.swing.JTextArea
Constructs a new JTextArea with the given document model, and defaults for all of the other arguments (null, 0, 0).
JTextArea(Document, String, int, int) - Constructor for class javax.swing.JTextArea
Constructs a new JTextArea with the specified number of rows and columns, and the given model.
JTextArea.AccessibleJTextArea - Class in javax.swing
This class implements accessibility support for the JTextArea class.
JTextArea.AccessibleJTextArea() - Constructor for class javax.swing.JTextArea.AccessibleJTextArea
JTextComponent - Class in javax.swing.text
JTextComponent is the base class for swing text components.
JTextComponent() - Constructor for class javax.swing.text.JTextComponent
Creates a new JTextComponent.
JTextComponent.AccessibleJTextComponent - Class in javax.swing.text
This class implements accessibility support for the JTextComponent class.
JTextComponent.AccessibleJTextComponent() - Constructor for class javax.swing.text.JTextComponent.AccessibleJTextComponent
Constructs an AccessibleJTextComponent.
JTextComponent.DropLocation - Class in javax.swing.text
Represents a drop location for JTextComponents.
JTextComponent.KeyBinding - Class in javax.swing.text
Binding record for creating key bindings.
JTextComponent.KeyBinding(KeyStroke, String) - Constructor for class javax.swing.text.JTextComponent.KeyBinding
Creates a new key binding.
JTextField - Class in javax.swing
JTextField is a lightweight component that allows the editing of a single line of text.
JTextField() - Constructor for class javax.swing.JTextField
Constructs a new TextField.
JTextField(String) - Constructor for class javax.swing.JTextField
Constructs a new TextField initialized with the specified text.
JTextField(int) - Constructor for class javax.swing.JTextField
Constructs a new empty TextField with the specified number of columns.
JTextField(String, int) - Constructor for class javax.swing.JTextField
Constructs a new TextField initialized with the specified text and columns.
JTextField(Document, String, int) - Constructor for class javax.swing.JTextField
Constructs a new JTextField that uses the given text storage model and the given number of columns.
JTextField.AccessibleJTextField - Class in javax.swing
This class implements accessibility support for the JTextField class.
JTextField.AccessibleJTextField() - Constructor for class javax.swing.JTextField.AccessibleJTextField
JTextPane - Class in javax.swing
A text component that can be marked up with attributes that are represented graphically.
JTextPane() - Constructor for class javax.swing.JTextPane
Creates a new JTextPane.
JTextPane(StyledDocument) - Constructor for class javax.swing.JTextPane
Creates a new JTextPane, with a specified document model.
JToggleButton - Class in javax.swing
An implementation of a two-state button.
JToggleButton() - Constructor for class javax.swing.JToggleButton
Creates an initially unselected toggle button without setting the text or image.
JToggleButton(Icon) - Constructor for class javax.swing.JToggleButton
Creates an initially unselected toggle button with the specified image but no text.
JToggleButton(Icon, boolean) - Constructor for class javax.swing.JToggleButton
Creates a toggle button with the specified image and selection state, but no text.
JToggleButton(String) - Constructor for class javax.swing.JToggleButton
Creates an unselected toggle button with the specified text.
JToggleButton(String, boolean) - Constructor for class javax.swing.JToggleButton
Creates a toggle button with the specified text and selection state.
JToggleButton(Action) - Constructor for class javax.swing.JToggleButton
Creates a toggle button where properties are taken from the Action supplied.
JToggleButton(String, Icon) - Constructor for class javax.swing.JToggleButton
Creates a toggle button that has the specified text and image, and that is initially unselected.
JToggleButton(String, Icon, boolean) - Constructor for class javax.swing.JToggleButton
Creates a toggle button with the specified text, image, and selection state.
JToggleButton.AccessibleJToggleButton - Class in javax.swing
This class implements accessibility support for the JToggleButton class.
JToggleButton.AccessibleJToggleButton() - Constructor for class javax.swing.JToggleButton.AccessibleJToggleButton
JToggleButton.ToggleButtonModel - Class in javax.swing
The ToggleButton model
JToggleButton.ToggleButtonModel() - Constructor for class javax.swing.JToggleButton.ToggleButtonModel
Creates a new ToggleButton Model
JToolBar - Class in javax.swing
JToolBar provides a component that is useful for displaying commonly used Actions or controls.
JToolBar() - Constructor for class javax.swing.JToolBar
Creates a new tool bar; orientation defaults to HORIZONTAL.
JToolBar(int) - Constructor for class javax.swing.JToolBar
Creates a new tool bar with the specified orientation.
JToolBar(String) - Constructor for class javax.swing.JToolBar
Creates a new tool bar with the specified name.
JToolBar(String, int) - Constructor for class javax.swing.JToolBar
Creates a new tool bar with a specified name and orientation.
JToolBar.AccessibleJToolBar - Class in javax.swing
This class implements accessibility support for the JToolBar class.
JToolBar.AccessibleJToolBar() - Constructor for class javax.swing.JToolBar.AccessibleJToolBar
JToolBar.Separator - Class in javax.swing
A toolbar-specific separator.
JToolBar.Separator() - Constructor for class javax.swing.JToolBar.Separator
Creates a new toolbar separator with the default size as defined by the current look and feel.
JToolBar.Separator(Dimension) - Constructor for class javax.swing.JToolBar.Separator
Creates a new toolbar separator with the specified size.
JToolTip - Class in javax.swing
Used to display a "Tip" for a Component.
JToolTip() - Constructor for class javax.swing.JToolTip
Creates a tool tip.
JToolTip.AccessibleJToolTip - Class in javax.swing
This class implements accessibility support for the JToolTip class.
JToolTip.AccessibleJToolTip() - Constructor for class javax.swing.JToolTip.AccessibleJToolTip
JTree - Class in javax.swing
A control that displays a set of hierarchical data as an outline.
JTree() - Constructor for class javax.swing.JTree
Returns a JTree with a sample model.
JTree(Object[]) - Constructor for class javax.swing.JTree
Returns a JTree with each element of the specified array as the child of a new root node which is not displayed.
JTree(Vector<?>) - Constructor for class javax.swing.JTree
Returns a JTree with each element of the specified Vector as the child of a new root node which is not displayed.
JTree(Hashtable<?, ?>) - Constructor for class javax.swing.JTree
Returns a JTree created from a Hashtable which does not display with root.
JTree(TreeNode) - Constructor for class javax.swing.JTree
Returns a JTree with the specified TreeNode as its root, which displays the root node.
JTree(TreeNode, boolean) - Constructor for class javax.swing.JTree
Returns a JTree with the specified TreeNode as its root, which displays the root node and which decides whether a node is a leaf node in the specified manner.
JTree(TreeModel) - Constructor for class javax.swing.JTree
Returns an instance of JTree which displays the root node -- the tree is created using the specified data model.
JTree.AccessibleJTree - Class in javax.swing
This class implements accessibility support for the JTree class.
JTree.AccessibleJTree() - Constructor for class javax.swing.JTree.AccessibleJTree
JTree.AccessibleJTree.AccessibleJTreeNode - Class in javax.swing
This class implements accessibility support for the JTree child.
JTree.AccessibleJTree.AccessibleJTreeNode(JTree, TreePath, Accessible) - Constructor for class javax.swing.JTree.AccessibleJTree.AccessibleJTreeNode
Constructs an AccessibleJTreeNode
JTree.DropLocation - Class in javax.swing
A subclass of TransferHandler.DropLocation representing a drop location for a JTree.
JTree.DynamicUtilTreeNode - Class in javax.swing
DynamicUtilTreeNode can wrap vectors/hashtables/arrays/strings and create the appropriate children tree nodes as necessary.
JTree.DynamicUtilTreeNode(Object, Object) - Constructor for class javax.swing.JTree.DynamicUtilTreeNode
Creates a node with the specified object as its value and with the specified children.
JTree.EmptySelectionModel - Class in javax.swing
EmptySelectionModel is a TreeSelectionModel that does not allow anything to be selected.
JTree.EmptySelectionModel() - Constructor for class javax.swing.JTree.EmptySelectionModel
JTree.TreeModelHandler - Class in javax.swing
Listens to the model and updates the expandedState accordingly when nodes are removed, or changed.
JTree.TreeModelHandler() - Constructor for class javax.swing.JTree.TreeModelHandler
JTree.TreeSelectionRedirector - Class in javax.swing
Handles creating a new TreeSelectionEvent with the JTree as the source and passing it off to all the listeners.
JTree.TreeSelectionRedirector() - Constructor for class javax.swing.JTree.TreeSelectionRedirector
JULY - Static variable in class java.util.Calendar
Value of the Calendar.MONTH field indicating the seventh month of the year in the Gregorian and Julian calendars.
JULY - Static variable in class javax.xml.datatype.DatatypeConstants
Value for seventh month of year.
JUNE - Static variable in class java.util.Calendar
Value of the Calendar.MONTH field indicating the sixth month of the year in the Gregorian and Julian calendars.
JUNE - Static variable in class javax.xml.datatype.DatatypeConstants
Value for sixth month of year.
JUSTIFICATION - Static variable in class java.awt.font.TextAttribute
Attribute key for the justification of a paragraph.
JUSTIFICATION_FULL - Static variable in class java.awt.font.TextAttribute
Justify the line to the full requested width.
JUSTIFICATION_NONE - Static variable in class java.awt.font.TextAttribute
Do not allow the line to be justified.
JViewport - Class in javax.swing
The "viewport" or "porthole" through which you see the underlying information.
JViewport() - Constructor for class javax.swing.JViewport
Creates a JViewport.
JViewport.AccessibleJViewport - Class in javax.swing
This class implements accessibility support for the JViewport class.
JViewport.AccessibleJViewport() - Constructor for class javax.swing.JViewport.AccessibleJViewport
JViewport.ViewListener - Class in javax.swing
A listener for the view.
JViewport.ViewListener() - Constructor for class javax.swing.JViewport.ViewListener
JWindow - Class in javax.swing
A JWindow is a container that can be displayed anywhere on the user's desktop.
JWindow() - Constructor for class javax.swing.JWindow
Creates a window with no specified owner.
JWindow(GraphicsConfiguration) - Constructor for class javax.swing.JWindow
Creates a window with the specified GraphicsConfiguration of a screen device.
JWindow(Frame) - Constructor for class javax.swing.JWindow
Creates a window with the specified owner frame.
JWindow(Window) - Constructor for class javax.swing.JWindow
Creates a window with the specified owner window.
JWindow(Window, GraphicsConfiguration) - Constructor for class javax.swing.JWindow
Creates a window with the specified owner window and GraphicsConfiguration of a screen device.
JWindow.AccessibleJWindow - Class in javax.swing
This class implements accessibility support for the JWindow class.
JWindow.AccessibleJWindow() - Constructor for class javax.swing.JWindow.AccessibleJWindow
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类

提交错误或意见
有关更多的 API 参考资料和开发人员文档，请参阅 Java SE 开发人员文档. 该文档包含更详细的、面向开发人员的描述，以及总体概述、术语定义、使用技巧和工作代码示例。
版权所有 © 1993, 2011, Oracle 及其联盟会员。保留所有权利。
草案 ea-b138

ieca>DDn


K-Index

请注意：本 java api 1.7Beta 规范不是最终稳定版，未来随着版本的更迭，本规范可能有更新。
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _

K

K1Div2Luminance - Static variable in class javax.imageio.plugins.jpeg.JPEGQTable
The sample luminance quantization table given in the JPEG specification, table K.1, with all elements divided by 2.
K1Luminance - Static variable in class javax.imageio.plugins.jpeg.JPEGQTable
The sample luminance quantization table given in the JPEG specification, table K.1.
K2Chrominance - Static variable in class javax.imageio.plugins.jpeg.JPEGQTable
The sample chrominance quantization table given in the JPEG specification, table K.2.
K2Div2Chrominance - Static variable in class javax.imageio.plugins.jpeg.JPEGQTable
The sample chrominance quantization table given in the JPEG specification, table K.1, with all elements divided by 2.
KAITHI - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Kaithi" Unicode character block.
KAKU_0 - Static variable in class javax.print.attribute.standard.MediaSize.JIS
Specifies the JIS Kaku ("square") #0 envelope size, 287 mm by 382 mm.
KAKU_1 - Static variable in class javax.print.attribute.standard.MediaSize.JIS
Specifies the JIS Kaku ("square") #1 envelope size, 270 mm by 382 mm.
KAKU_2 - Static variable in class javax.print.attribute.standard.MediaSize.JIS
Specifies the JIS Kaku ("square") #2 envelope size, 240 mm by 332 mm.
KAKU_20 - Static variable in class javax.print.attribute.standard.MediaSize.JIS
Specifies the JIS Kaku ("square") #20 envelope size, 229 mm by 324 mm.
KAKU_3 - Static variable in class javax.print.attribute.standard.MediaSize.JIS
Specifies the JIS Kaku ("square") #3 envelope size, 216 mm by 277 mm.
KAKU_4 - Static variable in class javax.print.attribute.standard.MediaSize.JIS
Specifies the JIS Kaku ("square") #4 envelope size, 197 mm by 267 mm.
KAKU_5 - Static variable in class javax.print.attribute.standard.MediaSize.JIS
Specifies the JIS Kaku ("square") #5 envelope size, 190 mm by 240 mm.
KAKU_6 - Static variable in class javax.print.attribute.standard.MediaSize.JIS
Specifies the JIS Kaku ("square") #6 envelope size, 162 mm by 229 mm.
KAKU_7 - Static variable in class javax.print.attribute.standard.MediaSize.JIS
Specifies the JIS Kaku ("square") #7 envelope size, 142 mm by 205 mm.
KAKU_8 - Static variable in class javax.print.attribute.standard.MediaSize.JIS
Specifies the JIS Kaku ("square") #8 envelope size, 119 mm by 197 mm.
KAKU_A4 - Static variable in class javax.print.attribute.standard.MediaSize.JIS
Specifies the JIS Kaku ("square") A4 envelope size, 228 mm by 312 mm.
KANA_SUPPLEMENT - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Kana Supplement" Unicode character block.
KANBUN - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Kanbun" Unicode character block.
KANGXI_RADICALS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Kangxi Radicals" Unicode character block.
KANJI - Static variable in class java.awt.im.InputSubset
Constant for all Han characters used in writing Japanese, including a subset of the CJK unified ideographs as well as Japanese Han characters that may be defined as surrogate characters.
KANNADA - Static variable in class java.awt.font.NumericShaper
Identifies the KANNADA range and decimal base.
KANNADA - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Kannada" Unicode character block.
KATAKANA - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Katakana" Unicode character block.
KATAKANA_PHONETIC_EXTENSIONS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Katakana Phonetic Extensions" Unicode character block.
KAYAH_LI - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Kayah Li" Unicode character block.
KBD - Static variable in class javax.swing.text.html.HTML.Tag
KEEP - Static variable in interface java.util.jar.Pack200.Packer
The string "keep", a possible value for certain properties.
KEEP - Static variable in interface java.util.jar.Pack200.Unpacker
The string "keep", a possible value for certain properties.
KEEP_CURRENT_RESULT - Static variable in interface java.sql.Statement
The constant indicating that the current ResultSet object should not be closed when calling getMoreResults.
KEEP_FILE_ORDER - Static variable in interface java.util.jar.Pack200.Packer
If this property is set to Pack200.Packer.TRUE, the packer will transmit all elements in their original order within the source archive.
KerberosKey - Class in javax.security.auth.kerberos
This class encapsulates a long term secret key for a Kerberos principal.
KerberosKey(KerberosPrincipal, byte[], int, int) - Constructor for class javax.security.auth.kerberos.KerberosKey
Constructs a KerberosKey from the given bytes when the key type and key version number are known.
KerberosKey(KerberosPrincipal, char[], String) - Constructor for class javax.security.auth.kerberos.KerberosKey
Constructs a KerberosKey from a principal's password.
KerberosPrincipal - Class in javax.security.auth.kerberos
This class encapsulates a Kerberos principal.
KerberosPrincipal(String) - Constructor for class javax.security.auth.kerberos.KerberosPrincipal
Constructs a KerberosPrincipal from the provided string input.
KerberosPrincipal(String, int) - Constructor for class javax.security.auth.kerberos.KerberosPrincipal
Constructs a KerberosPrincipal from the provided string and name type input.
KerberosTicket - Class in javax.security.auth.kerberos
This class encapsulates a Kerberos ticket and associated information as viewed from the client's point of view.
KerberosTicket(byte[], KerberosPrincipal, KerberosPrincipal, byte[], int, boolean[], Date, Date, Date, Date, InetAddress[]) - Constructor for class javax.security.auth.kerberos.KerberosTicket
Constructs a KerberosTicket using credentials information that a client either receives from a KDC or reads from a cache.
Kernel - Class in java.awt.image
The Kernel class defines a matrix that describes how a specified pixel and its surrounding pixels affect the value computed for the pixel's position in the output image of a filtering operation.
Kernel(int, int, float[]) - Constructor for class java.awt.image.Kernel
Constructs a Kernel object from an array of floats.
KERNING - Static variable in class java.awt.font.TextAttribute
Attribute key to request kerning.
KERNING_ON - Static variable in class java.awt.font.TextAttribute
Request standard kerning.
key - Variable in class java.awt.Event
The key code of the key that was pressed in a keyboard event.
Key - Interface in java.security
The Key interface is the top-level interface for all keys.
key - Variable in class javax.accessibility.AccessibleBundle
The locale independent name of the state.
key - Variable in class javax.swing.text.JTextComponent.KeyBinding
The key.
KEY_ACTION - Static variable in class java.awt.Event
The user has pressed a non-ASCII action key.
KEY_ACTION_RELEASE - Static variable in class java.awt.Event
The user has released a non-ASCII action key.
KEY_ALPHA_INTERPOLATION - Static variable in class java.awt.RenderingHints
Alpha interpolation hint key.
KEY_ANTIALIASING - Static variable in class java.awt.RenderingHints
Antialiasing hint key.
KEY_COLOR_RENDERING - Static variable in class java.awt.RenderingHints
Color rendering hint key.
KEY_DITHERING - Static variable in class java.awt.RenderingHints
Dithering hint key.
KEY_EVENT_MASK - Static variable in class java.awt.AWTEvent
The event mask for selecting key events.
KEY_FIRST - Static variable in class java.awt.event.KeyEvent
The first number in the range of ids used for key events.
KEY_FRACTIONALMETRICS - Static variable in class java.awt.RenderingHints
Font fractional metrics hint key.
KEY_INTERPOLATION - Static variable in class java.awt.RenderingHints
Interpolation hint key.
KEY_LAST - Static variable in class java.awt.event.KeyEvent
The last number in the range of ids used for key events.
KEY_LOCATION_LEFT - Static variable in class java.awt.event.KeyEvent
A constant indicating that the key pressed or released is in the left key location (there is more than one possible location for this key).
KEY_LOCATION_NUMPAD - Static variable in class java.awt.event.KeyEvent
A constant indicating that the key event originated on the numeric keypad or with a virtual key corresponding to the numeric keypad.
KEY_LOCATION_RIGHT - Static variable in class java.awt.event.KeyEvent
A constant indicating that the key pressed or released is in the right key location (there is more than one possible location for this key).
KEY_LOCATION_STANDARD - Static variable in class java.awt.event.KeyEvent
A constant indicating that the key pressed or released is not distinguished as the left or right version of a key, and did not originate on the numeric keypad (or did not originate with a virtual key corresponding to the numeric keypad).
KEY_LOCATION_UNKNOWN - Static variable in class java.awt.event.KeyEvent
A constant indicating that the keyLocation is indeterminate or not relevant.
KEY_PRESS - Static variable in class java.awt.Event
The user has pressed a normal key.
KEY_PRESSED - Static variable in class java.awt.event.KeyEvent
The "key pressed" event.
KEY_RELEASE - Static variable in class java.awt.Event
The user has released a normal key.
KEY_RELEASED - Static variable in class java.awt.event.KeyEvent
The "key released" event.
KEY_RENDERING - Static variable in class java.awt.RenderingHints
Rendering hint key.
KEY_STROKE_CONTROL - Static variable in class java.awt.RenderingHints
Stroke normalization control hint key.
KEY_TEXT_ANTIALIASING - Static variable in class java.awt.RenderingHints
Text antialiasing hint key.
KEY_TEXT_LCD_CONTRAST - Static variable in class java.awt.RenderingHints
LCD text contrast rendering hint key.
KEY_TYPED - Static variable in class java.awt.event.KeyEvent
The "key typed" event.
KeyAdapter - Class in java.awt.event
An abstract adapter class for receiving keyboard events.
KeyAdapter() - Constructor for class java.awt.event.KeyAdapter
KeyAgreement - Class in javax.crypto
This class provides the functionality of a key agreement (or key exchange) protocol.
KeyAgreement(KeyAgreementSpi, Provider, String) - Constructor for class javax.crypto.KeyAgreement
Creates a KeyAgreement object.
KeyAgreementSpi - Class in javax.crypto
This class defines the Service Provider Interface (SPI) for the KeyAgreement class.
KeyAgreementSpi() - Constructor for class javax.crypto.KeyAgreementSpi
KeyAlreadyExistsException - Exception in javax.management.openmbean
This runtime exception is thrown to indicate that the index of a row to be added to a tabular data instance is already used to refer to another row in this tabular data instance.
KeyAlreadyExistsException() - Constructor for exception javax.management.openmbean.KeyAlreadyExistsException
A KeyAlreadyExistsException with no detail message.
KeyAlreadyExistsException(String) - Constructor for exception javax.management.openmbean.KeyAlreadyExistsException
A KeyAlreadyExistsException with a detail message.
KEYBOARD_DIVIDER_MOVE_OFFSET - Static variable in class javax.swing.plaf.basic.BasicSplitPaneUI
How far (relative) the divider does move when it is moved around by the cursor keys on the keyboard.
keyboardDownRightListener - Variable in class javax.swing.plaf.basic.BasicSplitPaneUI
Deprecated.
As of Java 2 platform v1.3.
keyboardEndListener - Variable in class javax.swing.plaf.basic.BasicSplitPaneUI
Deprecated.
As of Java 2 platform v1.3.
KeyboardFocusManager - Class in java.awt
The KeyboardFocusManager is responsible for managing the active and focused Windows, and the current focus owner.
KeyboardFocusManager() - Constructor for class java.awt.KeyboardFocusManager
Initializes a KeyboardFocusManager.
keyboardHomeListener - Variable in class javax.swing.plaf.basic.BasicSplitPaneUI
Deprecated.
As of Java 2 platform v1.3.
keyboardResizeToggleListener - Variable in class javax.swing.plaf.basic.BasicSplitPaneUI
Deprecated.
As of Java 2 platform v1.3.
keyboardUpLeftListener - Variable in class javax.swing.plaf.basic.BasicSplitPaneUI
Deprecated.
As of Java 2 platform v1.3.
keyDown(Event, int) - Method in class java.awt.Component
Deprecated.
As of JDK version 1.1, replaced by processKeyEvent(KeyEvent).
keyEqualsCharSet() - Method in exception javax.swing.text.ChangedCharSetException
KeyEvent - Class in java.awt.event
An event which indicates that a keystroke occurred in a component.
KeyEvent(Component, int, long, int, int, char, int) - Constructor for class java.awt.event.KeyEvent
Constructs a KeyEvent object.
KeyEvent(Component, int, long, int, int, char) - Constructor for class java.awt.event.KeyEvent
Constructs a KeyEvent object.
KeyEvent(Component, int, long, int, int) - Constructor for class java.awt.event.KeyEvent
Deprecated.
as of JDK1.1
KeyEventDispatcher - Interface in java.awt
A KeyEventDispatcher cooperates with the current KeyboardFocusManager in the targeting and dispatching of all KeyEvents.
KeyEventPostProcessor - Interface in java.awt
A KeyEventPostProcessor cooperates with the current KeyboardFocusManager in the final resolution of all unconsumed KeyEvents.
KeyException - Exception in java.security
This is the basic key exception.
KeyException() - Constructor for exception java.security.KeyException
Constructs a KeyException with no detail message.
KeyException(String) - Constructor for exception java.security.KeyException
Constructs a KeyException with the specified detail message.
KeyException(String, Throwable) - Constructor for exception java.security.KeyException
Creates a KeyException with the specified detail message and cause.
KeyException(Throwable) - Constructor for exception java.security.KeyException
Creates a KeyException with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).
KeyFactory - Class in java.security
Key factories are used to convert keys (opaque cryptographic keys of type Key) into key specifications (transparent representations of the underlying key material), and vice versa.
KeyFactory(KeyFactorySpi, Provider, String) - Constructor for class java.security.KeyFactory
Creates a KeyFactory object.
KeyFactorySpi - Class in java.security
This class defines the Service Provider Interface (SPI) for the KeyFactory class.
KeyFactorySpi() - Constructor for class java.security.KeyFactorySpi
keyFor(Selector) - Method in class java.nio.channels.SelectableChannel
Retrieves the key representing the channel's registration with the given selector.
keyFor(Selector) - Method in class java.nio.channels.spi.AbstractSelectableChannel
KeyGenerator - Class in javax.crypto
This class provides the functionality of a secret (symmetric) key generator.
KeyGenerator(KeyGeneratorSpi, Provider, String) - Constructor for class javax.crypto.KeyGenerator
Creates a KeyGenerator object.
KeyGeneratorSpi - Class in javax.crypto
This class defines the Service Provider Interface (SPI) for the KeyGenerator class.
KeyGeneratorSpi() - Constructor for class javax.crypto.KeyGeneratorSpi
KeyInfo - Interface in javax.xml.crypto.dsig.keyinfo
A representation of the XML KeyInfo element as defined in the W3C Recommendation for XML-Signature Syntax and Processing.
KeyInfoFactory - Class in javax.xml.crypto.dsig.keyinfo
A factory for creating KeyInfo objects from scratch or for unmarshalling a KeyInfo object from a corresponding XML representation.
KeyInfoFactory() - Constructor for class javax.xml.crypto.dsig.keyinfo.KeyInfoFactory
Default constructor, for invocation by subclasses.
KeyListener - Interface in java.awt.event
The listener interface for receiving keyboard events (keystrokes).
keyListener - Variable in class javax.swing.plaf.basic.BasicComboBoxUI
This protected field is implementation specific.
keyListener - Variable in class javax.swing.plaf.basic.BasicComboPopup
This protected field is implementation specific.
keyListener - Variable in class javax.swing.plaf.basic.BasicTableUI
KeyManagementException - Exception in java.security
This is the general key management exception for all operations dealing with key management.
KeyManagementException() - Constructor for exception java.security.KeyManagementException
Constructs a KeyManagementException with no detail message.
KeyManagementException(String) - Constructor for exception java.security.KeyManagementException
Constructs a KeyManagementException with the specified detail message.
KeyManagementException(String, Throwable) - Constructor for exception java.security.KeyManagementException
Creates a KeyManagementException with the specified detail message and cause.
KeyManagementException(Throwable) - Constructor for exception java.security.KeyManagementException
Creates a KeyManagementException with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).
KeyManager - Interface in javax.net.ssl
This is the base interface for JSSE key managers.
KeyManagerFactory - Class in javax.net.ssl
This class acts as a factory for key managers based on a source of key material.
KeyManagerFactory(KeyManagerFactorySpi, Provider, String) - Constructor for class javax.net.ssl.KeyManagerFactory
Creates a KeyManagerFactory object.
KeyManagerFactorySpi - Class in javax.net.ssl
This class defines the Service Provider Interface (SPI) for the KeyManagerFactory class.
KeyManagerFactorySpi() - Constructor for class javax.net.ssl.KeyManagerFactorySpi
Keymap - Interface in javax.swing.text
A collection of bindings of KeyStrokes to actions.
KeyName - Interface in javax.xml.crypto.dsig.keyinfo
A representation of the XML KeyName element as defined in the W3C Recommendation for XML-Signature Syntax and Processing.
KeyPair - Class in java.security
This class is a simple holder for a key pair (a public key and a private key).
KeyPair(PublicKey, PrivateKey) - Constructor for class java.security.KeyPair
Constructs a key pair from the given public key and private key.
KeyPairGenerator - Class in java.security
The KeyPairGenerator class is used to generate pairs of public and private keys.
KeyPairGenerator(String) - Constructor for class java.security.KeyPairGenerator
Creates a KeyPairGenerator object for the specified algorithm.
KeyPairGeneratorSpi - Class in java.security
This class defines the Service Provider Interface (SPI) for the KeyPairGenerator class, which is used to generate pairs of public and private keys.
KeyPairGeneratorSpi() - Constructor for class java.security.KeyPairGeneratorSpi
keyPress(int) - Method in class java.awt.Robot
Presses a given key.
keyPressed(KeyEvent) - Method in class java.awt.AWTEventMulticaster
Handles the keyPressed event by invoking the keyPressed methods on listener-a and listener-b.
keyPressed(KeyEvent) - Method in class java.awt.event.KeyAdapter
Invoked when a key has been pressed.
keyPressed(KeyEvent) - Method in interface java.awt.event.KeyListener
Invoked when a key has been pressed.
keyPressed(KeyEvent) - Method in class javax.swing.plaf.basic.BasicComboBoxUI.KeyHandler
keyPressed(KeyEvent) - Method in class javax.swing.plaf.basic.BasicTableUI.KeyHandler
keyPressed(KeyEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI.KeyHandler
keyRelease(int) - Method in class java.awt.Robot
Releases a given key.
keyReleased(KeyEvent) - Method in class java.awt.AWTEventMulticaster
Handles the keyReleased event by invoking the keyReleased methods on listener-a and listener-b.
keyReleased(KeyEvent) - Method in class java.awt.event.KeyAdapter
Invoked when a key has been released.
keyReleased(KeyEvent) - Method in interface java.awt.event.KeyListener
Invoked when a key has been released.
keyReleased(KeyEvent) - Method in class javax.swing.plaf.basic.BasicComboPopup.InvocationKeyHandler
keyReleased(KeyEvent) - Method in class javax.swing.plaf.basic.BasicTableUI.KeyHandler
keyReleased(KeyEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI.KeyHandler
KeyRep - Class in java.security
Standardized representation for serialized Key objects.
KeyRep(KeyRep.Type, String, String, byte[]) - Constructor for class java.security.KeyRep
Construct the alternate Key class.
KeyRep.Type - Enum in java.security
Key type.
keys() - Method in class java.nio.channels.Selector
Returns this selector's key set.
keys() - Method in class java.security.Provider
keys() - Method in class java.util.concurrent.ConcurrentHashMap
Returns an enumeration of the keys in this table.
keys() - Method in class java.util.Dictionary
Returns an enumeration of the keys in this dictionary.
keys() - Method in class java.util.Hashtable
Returns an enumeration of the keys in this hashtable.
keys() - Method in class java.util.prefs.AbstractPreferences
Implements the keys method as per the specification in Preferences.keys().
keys() - Method in class java.util.prefs.Preferences
Returns all of the keys that have an associated value in this preference node.
keys() - Method in class javax.swing.ActionMap
Returns the Action names that are bound in this ActionMap.
keys() - Method in class javax.swing.InputMap
Returns the KeyStrokes that are bound in this InputMap.
keySelectionManager - Variable in class javax.swing.JComboBox
This protected field is implementation specific.
KeySelector - Class in javax.xml.crypto
A selector that finds and returns a key using the data contained in a KeyInfo object.
KeySelector() - Constructor for class javax.xml.crypto.KeySelector
Default no-args constructor; intended for invocation by subclasses only.
KeySelector.Purpose - Class in javax.xml.crypto
The purpose of the key that is to be selected.
KeySelectorException - Exception in javax.xml.crypto
Indicates an exceptional condition thrown by a KeySelector.
KeySelectorException() - Constructor for exception javax.xml.crypto.KeySelectorException
Constructs a new KeySelectorException with null as its detail message.
KeySelectorException(String) - Constructor for exception javax.xml.crypto.KeySelectorException
Constructs a new KeySelectorException with the specified detail message.
KeySelectorException(String, Throwable) - Constructor for exception javax.xml.crypto.KeySelectorException
Constructs a new KeySelectorException with the specified detail message and cause.
KeySelectorException(Throwable) - Constructor for exception javax.xml.crypto.KeySelectorException
Constructs a new KeySelectorException with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).
KeySelectorResult - Interface in javax.xml.crypto
The result returned by the KeySelector.select method.
keySet() - Method in class java.awt.RenderingHints
Returns a Set view of the Keys contained in this RenderingHints.
keySet() - Method in class java.security.Provider
Returns an unmodifiable Set view of the property keys contained in this provider.
keySet() - Method in class java.util.AbstractMap
Returns a Set view of the keys contained in this map.
keySet() - Method in class java.util.concurrent.ConcurrentHashMap
Returns a Set view of the keys contained in this map.
keySet() - Method in interface java.util.concurrent.ConcurrentNavigableMap
Returns a NavigableSet view of the keys contained in this map.
keySet() - Method in class java.util.concurrent.ConcurrentSkipListMap
Returns a NavigableSet view of the keys contained in this map.
keySet() - Method in class java.util.EnumMap
Returns a Set view of the keys contained in this map.
keySet() - Method in class java.util.HashMap
Returns a Set view of the keys contained in this map.
keySet() - Method in class java.util.Hashtable
Returns a Set view of the keys contained in this map.
keySet() - Method in class java.util.IdentityHashMap
Returns an identity-based set view of the keys contained in this map.
keySet() - Method in class java.util.jar.Attributes
Returns a Set view of the attribute names (keys) contained in this Map.
keySet() - Method in interface java.util.Map
Returns a Set view of the keys contained in this map.
keySet() - Method in class java.util.ResourceBundle
Returns a Set of all keys contained in this ResourceBundle and its parent bundles.
keySet() - Method in interface java.util.SortedMap
Returns a Set view of the keys contained in this map.
keySet() - Method in class java.util.TreeMap
Returns a Set view of the keys contained in this map.
keySet() - Method in class java.util.WeakHashMap
Returns a Set view of the keys contained in this map.
keySet() - Method in class javax.management.openmbean.CompositeType
Returns an unmodifiable Set view of all the item names defined by this CompositeType instance.
keySet() - Method in interface javax.management.openmbean.TabularData
Returns a set view of the keys (ie the index values) of the CompositeData values (ie the rows) contained in this TabularData instance.
keySet() - Method in class javax.management.openmbean.TabularDataSupport
Returns a set view of the keys contained in the underlying map of this TabularDataSupport instance used to index the rows.
keySet() - Method in class javax.script.SimpleBindings
Returns a Set view of the keys contained in this map.
KeySpec - Interface in java.security.spec
A (transparent) specification of the key material that constitutes a cryptographic key.
keysSpi() - Method in class java.util.prefs.AbstractPreferences
Returns all of the keys that have an associated value in this preference node.
KeyStore - Class in java.security
This class represents a storage facility for cryptographic keys and certificates.
KeyStore(KeyStoreSpi, Provider, String) - Constructor for class java.security.KeyStore
Creates a KeyStore object of the given type, and encapsulates the given provider implementation (SPI object) in it.
KeyStore.Builder - Class in java.security
A description of a to-be-instantiated KeyStore object.
KeyStore.Builder() - Constructor for class java.security.KeyStore.Builder
Construct a new Builder.
KeyStore.CallbackHandlerProtection - Class in java.security
A ProtectionParameter encapsulating a CallbackHandler.
KeyStore.CallbackHandlerProtection(CallbackHandler) - Constructor for class java.security.KeyStore.CallbackHandlerProtection
Constructs a new CallbackHandlerProtection from a CallbackHandler.
KeyStore.Entry - Interface in java.security
A marker interface for KeyStore entry types.
KeyStore.LoadStoreParameter - Interface in java.security
A marker interface for KeyStore load and store parameters.
KeyStore.PasswordProtection - Class in java.security
A password-based implementation of ProtectionParameter.
KeyStore.PasswordProtection(char[]) - Constructor for class java.security.KeyStore.PasswordProtection
Creates a password parameter.
KeyStore.PrivateKeyEntry - Class in java.security
A KeyStore entry that holds a PrivateKey and corresponding certificate chain.
KeyStore.PrivateKeyEntry(PrivateKey, Certificate[]) - Constructor for class java.security.KeyStore.PrivateKeyEntry
Constructs a PrivateKeyEntry with a PrivateKey and corresponding certificate chain.
KeyStore.ProtectionParameter - Interface in java.security
A marker interface for keystore protection parameters.
KeyStore.SecretKeyEntry - Class in java.security
A KeyStore entry that holds a SecretKey.
KeyStore.SecretKeyEntry(SecretKey) - Constructor for class java.security.KeyStore.SecretKeyEntry
Constructs a SecretKeyEntry with a SecretKey.
KeyStore.TrustedCertificateEntry - Class in java.security
A KeyStore entry that holds a trusted Certificate.
KeyStore.TrustedCertificateEntry(Certificate) - Constructor for class java.security.KeyStore.TrustedCertificateEntry
Constructs a TrustedCertificateEntry with a trusted Certificate.
KeyStoreBuilderParameters - Class in javax.net.ssl
A parameters object for X509KeyManagers that encapsulates a List of KeyStore.Builders.
KeyStoreBuilderParameters(KeyStore.Builder) - Constructor for class javax.net.ssl.KeyStoreBuilderParameters
Construct new KeyStoreBuilderParameters from the specified KeyStore.Builder.
KeyStoreBuilderParameters(List<KeyStore.Builder>) - Constructor for class javax.net.ssl.KeyStoreBuilderParameters
Construct new KeyStoreBuilderParameters from a List of KeyStore.Builders.
KeyStoreException - Exception in java.security
This is the generic KeyStore exception.
KeyStoreException() - Constructor for exception java.security.KeyStoreException
Constructs a KeyStoreException with no detail message.
KeyStoreException(String) - Constructor for exception java.security.KeyStoreException
Constructs a KeyStoreException with the specified detail message.
KeyStoreException(String, Throwable) - Constructor for exception java.security.KeyStoreException
Creates a KeyStoreException with the specified detail message and cause.
KeyStoreException(Throwable) - Constructor for exception java.security.KeyStoreException
Creates a KeyStoreException with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).
KeyStoreSpi - Class in java.security
This class defines the Service Provider Interface (SPI) for the KeyStore class.
KeyStoreSpi() - Constructor for class java.security.KeyStoreSpi
KeyStroke - Class in javax.swing
A KeyStroke represents a key action on the keyboard, or equivalent input device.
keyTyped(KeyEvent) - Method in class java.awt.AWTEventMulticaster
Handles the keyTyped event by invoking the keyTyped methods on listener-a and listener-b.
keyTyped(KeyEvent) - Method in class java.awt.event.KeyAdapter
Invoked when a key has been typed.
keyTyped(KeyEvent) - Method in interface java.awt.event.KeyListener
Invoked when a key has been typed.
keyTyped(KeyEvent) - Method in class javax.swing.plaf.basic.BasicTableUI.KeyHandler
keyTyped(KeyEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI.KeyHandler
Invoked when a key has been typed.
keyUp(Event, int) - Method in class java.awt.Component
Deprecated.
As of JDK version 1.1, replaced by processKeyEvent(KeyEvent).
KeyValue - Interface in javax.xml.crypto.dsig.keyinfo
A representation of the XML KeyValue element as defined in the W3C Recommendation for XML-Signature Syntax and Processing.
KHAROSHTHI - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Kharoshthi" Unicode character block.
KHMER - Static variable in class java.awt.font.NumericShaper
Identifies the KHMER range and decimal base.
KHMER - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Khmer" Unicode character block.
KHMER_SYMBOLS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Khmer Symbols" Unicode character block.
kind() - Method in interface java.nio.file.WatchEvent
Returns the event kind.
kind - Variable in class javax.tools.SimpleJavaFileObject
The kind of this file object.
kind() - Method in class org.omg.CORBA.TypeCode
Retrieves the kind of this TypeCode object.
kind - Variable in class org.omg.CosNaming.NameComponent
KOREA - Static variable in class java.util.Locale
Useful constant for country.
KOREAN - Static variable in class java.util.Locale
Useful constant for language.
KRB_NT_PRINCIPAL - Static variable in class javax.security.auth.kerberos.KerberosPrincipal
user principal name type.
KRB_NT_SRV_HST - Static variable in class javax.security.auth.kerberos.KerberosPrincipal
service with host name as instance (telnet, rcommands) name type.
KRB_NT_SRV_INST - Static variable in class javax.security.auth.kerberos.KerberosPrincipal
service and other unique instance (krbtgt) name type.
KRB_NT_SRV_XHST - Static variable in class javax.security.auth.kerberos.KerberosPrincipal
service with host as remaining components name type.
KRB_NT_UID - Static variable in class javax.security.auth.kerberos.KerberosPrincipal
unique ID name type.
KRB_NT_UNKNOWN - Static variable in class javax.security.auth.kerberos.KerberosPrincipal
unknown name type.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类

提交错误或意见
有关更多的 API 参考资料和开发人员文档，请参阅 Java SE 开发人员文档. 该文档包含更详细的、面向开发人员的描述，以及总体概述、术语定义、使用技巧和工作代码示例。
版权所有 © 1993, 2011, Oracle 及其联盟会员。保留所有权利。
草案 ea-b138

istaatk>>>lc>>.f" x


L-Index

请注意：本 java api 1.7Beta 规范不是最终稳定版，未来随着版本的更迭，本规范可能有更新。
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _

L

Label - Class in java.awt
A Label object is a component for placing text in a container.
Label() - Constructor for class java.awt.Label
Constructs an empty label.
Label(String) - Constructor for class java.awt.Label
Constructs a new label with the specified string of text, left justified.
Label(String, int) - Constructor for class java.awt.Label
Constructs a new label that presents the specified string of text with the specified alignment.
LABEL - Static variable in class javax.accessibility.AccessibleRole
An object used to present an icon or short string in an interface.
LABEL - Static variable in class javax.swing.plaf.synth.Region
Label region.
label - Variable in class org.omg.CORBA.UnionMember
The label of the union member described by this UnionMember object.
Label.AccessibleAWTLabel - Class in java.awt
This class implements accessibility support for the Label class.
Label.AccessibleAWTLabel() - Constructor for class java.awt.Label.AccessibleAWTLabel
LABEL_FOR - Static variable in class javax.accessibility.AccessibleRelation
Indicates an object is a label for one or more target objects.
LABEL_FOR_PROPERTY - Static variable in class javax.accessibility.AccessibleRelation
Identifies that the target group for a label has changed
LABELED_BY - Static variable in class javax.accessibility.AccessibleRelation
Indicates an object is labeled by one or more target objects.
LABELED_BY_PROPERTY - Static variable in class javax.accessibility.AccessibleRelation
Identifies that the objects that are doing the labeling have changed
labelFor - Variable in class javax.swing.JLabel
labelRect - Variable in class javax.swing.plaf.basic.BasicSliderUI
labelsHaveSameBaselines() - Method in class javax.swing.plaf.basic.BasicSliderUI
Returns true if all the labels from the label table have the same baseline.
labelUI - Static variable in class javax.swing.plaf.basic.BasicLabelUI
The default BasicLabelUI instance.
LabelUI - Class in javax.swing.plaf
Pluggable look and feel interface for JLabel.
LabelUI() - Constructor for class javax.swing.plaf.LabelUI
LabelView - Class in javax.swing.text
A LabelView is a styled chunk of text that represents a view mapped over an element in the text model.
LabelView(Element) - Constructor for class javax.swing.text.LabelView
Constructs a new view wrapped on an element.
LANDSCAPE - Static variable in class java.awt.PageAttributes.OrientationRequestedType
The OrientationRequestedType instance to use for specifying a landscape orientation.
LANDSCAPE - Static variable in class java.awt.print.PageFormat
The origin is at the bottom left of the paper with x running bottom to top and y running left to right.
LANDSCAPE - Static variable in class javax.print.attribute.standard.OrientationRequested
The content will be imaged across the long edge of the medium.
LANG - Static variable in class javax.swing.text.html.HTML.Attribute
LANGUAGE - Static variable in class java.text.AttributedCharacterIterator.Attribute
Attribute key for the language of some text.
LANGUAGE - Static variable in interface javax.naming.Context
Constant that holds the name of the environment property for specifying the preferred language to use with the service.
LANGUAGE - Static variable in interface javax.script.ScriptEngine
Reserved key for a named value that is the full name of Scripting Language supported by the implementation.
LANGUAGE - Static variable in class javax.swing.text.html.HTML.Attribute
LANGUAGE_VERSION - Static variable in interface javax.script.ScriptEngine
Reserved key for the named value that identifies the version of the scripting language supported by the implementation.
LanguageCallback - Class in javax.security.auth.callback
Underlying security services instantiate and pass a LanguageCallback to the handle method of a CallbackHandler to retrieve the Locale used for localizing text.
LanguageCallback() - Constructor for class javax.security.auth.callback.LanguageCallback
Construct a LanguageCallback.
LAO - Static variable in class java.awt.font.NumericShaper
Identifies the LAO range and decimal base.
LAO - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Lao" Unicode character block.
LARGE_CAPACITY - Static variable in class javax.print.attribute.standard.MediaTray
The large capacity input tray in the printer.
LARGE_ICON_KEY - Static variable in interface javax.swing.Action
The key used for storing an Icon.
LARGE_KEY - Static variable in class javax.swing.plaf.nimbus.NimbusStyle
LARGE_MODEL_PROPERTY - Static variable in class javax.swing.JTree
Bound property name for largeModel.
LARGE_SCALE - Static variable in class javax.swing.plaf.nimbus.NimbusStyle
largeModel - Variable in class javax.swing.JTree
Is this tree a large model? This is a code-optimization setting.
largeModel - Variable in class javax.swing.plaf.basic.BasicTreeUI
True if doing optimizations for a largeModel.
last(Container) - Method in class java.awt.CardLayout
Flips to the last card of the container.
last() - Method in interface java.sql.ResultSet
Moves the cursor to the last row in this ResultSet object.
last() - Method in class java.text.BreakIterator
Returns the last boundary.
last() - Method in interface java.text.CharacterIterator
Sets the position to getEndIndex()-1 (getEndIndex() if the text is empty) and returns the character at that position.
last() - Method in class java.text.StringCharacterIterator
Implements CharacterIterator.last() for String.
last() - Method in class java.util.concurrent.ConcurrentSkipListSet
last() - Method in interface java.util.SortedSet
Returns the last (highest) element currently in this set.
last() - Method in class java.util.TreeSet
last() - Method in class javax.swing.text.Segment
Sets the position to getEndIndex()-1 (getEndIndex() if the text is empty) and returns the character at that position.
LAST_DIVIDER_LOCATION_PROPERTY - Static variable in class javax.swing.JSplitPane
Bound property for lastLocation.
LAST_LINE_END - Static variable in class java.awt.GridBagConstraints
Place the component in the corner of its display area where the last line of text on a page would normally end for the current ComponentOrientation.
LAST_LINE_START - Static variable in class java.awt.GridBagConstraints
Place the component in the corner of its display area where the last line of text on a page would normally start for the current ComponentOrientation.
lastAccessTime() - Method in interface java.nio.file.attribute.BasicFileAttributes
Returns the time of last access.
lastAlloc - Variable in class javax.swing.text.AsyncBoxView.ChildLocator
The last seen allocation (for repainting when changes are flushed upward).
lastColumn - Variable in class javax.swing.JTable.AccessibleJTable.AccessibleJTableModelChange
lastDividerLocation - Variable in class javax.swing.JSplitPane
Previous location of the split pane.
lastEdit() - Method in class javax.swing.undo.CompoundEdit
Returns the last UndoableEdit in edits, or null if edits is empty.
lastElement() - Method in class java.util.Vector
Returns the last component of the vector.
lastElement() - Method in class javax.swing.DefaultListModel
Returns the last component of the list.
lastEntry() - Method in class java.util.concurrent.ConcurrentSkipListMap
Returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
lastEntry() - Method in interface java.util.NavigableMap
Returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
lastEntry() - Method in class java.util.TreeMap
lastIndexOf(int) - Method in class java.lang.String
Returns the index within this string of the last occurrence of the specified character.
lastIndexOf(int, int) - Method in class java.lang.String
Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
lastIndexOf(String) - Method in class java.lang.String
Returns the index within this string of the last occurrence of the specified substring.
lastIndexOf(String, int) - Method in class java.lang.String
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
lastIndexOf(String) - Method in class java.lang.StringBuffer
lastIndexOf(String, int) - Method in class java.lang.StringBuffer
lastIndexOf(String) - Method in class java.lang.StringBuilder
lastIndexOf(String, int) - Method in class java.lang.StringBuilder
lastIndexOf(Object) - Method in class java.util.AbstractList
Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.
lastIndexOf(Object) - Method in class java.util.ArrayList
Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.
lastIndexOf(Object) - Method in class java.util.concurrent.CopyOnWriteArrayList
Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.
lastIndexOf(E, int) - Method in class java.util.concurrent.CopyOnWriteArrayList
Returns the index of the last occurrence of the specified element in this list, searching backwards from index, or returns -1 if the element is not found.
lastIndexOf(Object) - Method in class java.util.LinkedList
Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.
lastIndexOf(Object) - Method in interface java.util.List
Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.
lastIndexOf(Object) - Method in class java.util.Vector
Returns the index of the last occurrence of the specified element in this vector, or -1 if this vector does not contain the element.
lastIndexOf(Object, int) - Method in class java.util.Vector
Returns the index of the last occurrence of the specified element in this vector, searching backwards from index, or returns -1 if the element is not found.
lastIndexOf(Object) - Method in class javax.swing.DefaultListModel
Returns the index of the last occurrence of elem.
lastIndexOf(Object, int) - Method in class javax.swing.DefaultListModel
Searches backwards for elem, starting from the specified index, and returns an index to it.
lastIndexOfSubList(List<?>, List<?>) - Static method in class java.util.Collections
Returns the starting position of the last occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence.
lastKey() - Method in class java.util.concurrent.ConcurrentSkipListMap
lastKey() - Method in interface java.util.SortedMap
Returns the last (highest) key currently in this map.
lastKey() - Method in class java.util.TreeMap
lastModified() - Method in class java.io.File
Returns the time that the file denoted by this abstract pathname was last modified.
lastModifiedTime() - Method in interface java.nio.file.attribute.BasicFileAttributes
Returns the time of last modification.
LastOwnerException - Exception in java.security.acl
This is an exception that is thrown whenever an attempt is made to delete the last owner of an Access Control List.
LastOwnerException() - Constructor for exception java.security.acl.LastOwnerException
Constructs a LastOwnerException.
lastPageFirst() - Method in class java.awt.PrintJob
Returns true if the last page will be printed first.
lastPaintPosition - Variable in class javax.swing.JViewport
The last viewPosition that we've painted, so we know how much of the backing store image is valid.
lastPath - Variable in class javax.swing.tree.DefaultTreeCellEditor
Last path that was selected.
lastRow - Variable in class javax.swing.event.TableModelEvent
lastRow - Variable in class javax.swing.JTable.AccessibleJTable.AccessibleJTableModelChange
lastRow - Variable in class javax.swing.tree.DefaultTreeCellEditor
Row that was last passed into getTreeCellEditorComponent.
lastSelectedRow - Variable in class javax.swing.plaf.basic.BasicTreeUI
Index of the row that was last selected.
lastTabInRun(int, int) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI
lastValidOffset - Variable in class javax.swing.text.AsyncBoxView.ChildLocator
The location of the last offset calculation that is valid.
LATEST - Static variable in interface java.util.jar.Pack200.Packer
The string "latest", a possible value for certain properties.
latest() - Static method in enum javax.lang.model.SourceVersion
Returns the latest source version that can be modeled.
latestSupported() - Static method in enum javax.lang.model.SourceVersion
Returns the latest source version fully supported by the current execution environment.
LATIN - Static variable in class java.awt.im.InputSubset
Constant for all Latin characters, including the characters in the BASIC_LATIN, LATIN_1_SUPPLEMENT, LATIN_EXTENDED_A, LATIN_EXTENDED_B Unicode character blocks.
LATIN_1_SUPPLEMENT - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Latin-1 Supplement" Unicode character block.
LATIN_DIGITS - Static variable in class java.awt.im.InputSubset
Constant for the digits included in the BASIC_LATIN Unicode character block.
LATIN_EXTENDED_A - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Latin Extended-A" Unicode character block.
LATIN_EXTENDED_ADDITIONAL - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Latin Extended Additional" Unicode character block.
LATIN_EXTENDED_B - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Latin Extended-B" Unicode character block.
LATIN_EXTENDED_C - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Latin Extended-C" Unicode character block.
LATIN_EXTENDED_D - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Latin Extended-D" Unicode character block.
LAYER_PROPERTY - Static variable in class javax.swing.JLayeredPane
Bound property
LAYERED_PANE - Static variable in class javax.accessibility.AccessibleRole
A specialized pane that allows its children to be drawn in layers, providing a form of stacking order.
LAYERED_PANE_PROPERTY - Static variable in class javax.swing.JInternalFrame
Bound property name.
LayeredHighlighter - Class in javax.swing.text
LayeredHighlighter() - Constructor for class javax.swing.text.LayeredHighlighter
LayeredHighlighter.LayerPainter - Class in javax.swing.text
Layered highlight renderer.
LayeredHighlighter.LayerPainter() - Constructor for class javax.swing.text.LayeredHighlighter.LayerPainter
layeredPane - Variable in class javax.swing.JRootPane
The layered pane that manages the menu bar and content pane.
LayerUI<V extends Component> - Class in javax.swing.plaf
The base class for all JLayer's UI delegates.
LayerUI() - Constructor for class javax.swing.plaf.LayerUI
layout() - Method in class java.awt.Component
Deprecated.
As of JDK version 1.1, replaced by doLayout().
layout() - Method in class java.awt.Container
Deprecated.
As of JDK version 1.1, replaced by doLayout().
layout() - Method in class java.awt.ScrollPane
Deprecated.
As of JDK version 1.1, replaced by doLayout().
layout() - Method in class javax.swing.plaf.synth.SynthSliderUI
Lays out the slider.
layout(int, int) - Method in class javax.swing.text.BoxView
Perform layout on the box
layout(FlowView) - Method in class javax.swing.text.FlowView.FlowStrategy
Update the flow on the given FlowView.
layout(int, int) - Method in class javax.swing.text.FlowView
Lays out the children.
LAYOUT_LEFT_TO_RIGHT - Static variable in class java.awt.Font
A flag to layoutGlyphVector indicating that text is left-to-right as determined by Bidi analysis.
LAYOUT_NO_LIMIT_CONTEXT - Static variable in class java.awt.Font
A flag to layoutGlyphVector indicating that text in the char array after the indicated limit should not be examined.
LAYOUT_NO_START_CONTEXT - Static variable in class java.awt.Font
A flag to layoutGlyphVector indicating that text in the char array before the indicated start should not be examined.
LAYOUT_RIGHT_TO_LEFT - Static variable in class java.awt.Font
A flag to layoutGlyphVector indicating that text is right-to-left as determined by Bidi analysis.
layoutChanged(int) - Method in class javax.swing.text.BoxView
Invalidates the layout along an axis.
layoutCL(JLabel, FontMetrics, String, Icon, Rectangle, Rectangle, Rectangle) - Method in class javax.swing.plaf.basic.BasicLabelUI
Forwards the call to SwingUtilities.layoutCompoundLabel().
layoutColumns(int, int[], int[], SizeRequirements[]) - Method in class javax.swing.text.TableView
Lays out the columns to fit within the given target span.
layoutComboBox(Container, MetalComboBoxUI.MetalComboBoxLayoutManager) - Method in class javax.swing.plaf.metal.MetalComboBoxUI
layoutCompoundLabel(JComponent, FontMetrics, String, Icon, int, int, int, int, Rectangle, Rectangle, Rectangle, int) - Static method in class javax.swing.SwingUtilities
Compute and return the location of the icons origin, the location of origin of the text baseline, and a possibly clipped version of the compound labels string.
layoutCompoundLabel(FontMetrics, String, Icon, int, int, int, int, Rectangle, Rectangle, Rectangle, int) - Static method in class javax.swing.SwingUtilities
Compute and return the location of the icons origin, the location of origin of the text baseline, and a possibly clipped version of the compound labels string.
layoutContainer(Container) - Method in class java.awt.BorderLayout
Lays out the container argument using this border layout.
layoutContainer(Container) - Method in class java.awt.CardLayout
Lays out the specified container using this card layout.
layoutContainer(Container) - Method in class java.awt.FlowLayout
Lays out the container.
layoutContainer(Container) - Method in class java.awt.GridBagLayout
Lays out the specified container using this grid bag layout.
layoutContainer(Container) - Method in class java.awt.GridLayout
Lays out the specified container using this layout.
layoutContainer(Container) - Method in interface java.awt.LayoutManager
Lays out the specified container.
layoutContainer(Container) - Method in class javax.swing.BoxLayout
Called by the AWT when the specified container needs to be laid out.
layoutContainer(Container) - Method in class javax.swing.GroupLayout
Lays out the specified container.
layoutContainer(Container) - Method in class javax.swing.JRootPane.RootLayout
Instructs the layout manager to perform the layout for the specified container.
layoutContainer(Container) - Method in class javax.swing.JSpinner.DefaultEditor
Resize the one (and only) child to completely fill the area within the parents insets.
layoutContainer(Container) - Method in class javax.swing.OverlayLayout
Called by the AWT when the specified container needs to be laid out.
layoutContainer(Container) - Method in class javax.swing.plaf.basic.BasicComboBoxUI.ComboBoxLayoutManager
layoutContainer(Container) - Method in class javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout
layoutContainer(Container) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI.InternalFrameLayout
layoutContainer(Container) - Method in class javax.swing.plaf.basic.BasicOptionPaneUI.ButtonAreaLayout
layoutContainer(Container) - Method in class javax.swing.plaf.basic.BasicScrollBarUI
layoutContainer(Container) - Method in class javax.swing.plaf.basic.BasicSplitPaneDivider.DividerLayout
layoutContainer(Container) - Method in class javax.swing.plaf.basic.BasicSplitPaneUI.BasicHorizontalLayoutManager
Does the actual layout.
layoutContainer(Container) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI.TabbedPaneLayout
layoutContainer(Container) - Method in class javax.swing.plaf.metal.MetalComboBoxUI.MetalComboBoxLayoutManager
layoutContainer(Container) - Method in class javax.swing.ScrollPaneLayout
Lays out the scrollpane.
layoutContainer(Container) - Method in class javax.swing.SpringLayout
layoutContainer(Container) - Method in class javax.swing.ViewportLayout
Called by the AWT when the specified container needs to be laid out.
LayoutFocusTraversalPolicy - Class in javax.swing
A SortingFocusTraversalPolicy which sorts Components based on their size, position, and orientation.
LayoutFocusTraversalPolicy() - Constructor for class javax.swing.LayoutFocusTraversalPolicy
Constructs a LayoutFocusTraversalPolicy.
layoutGlyphVector(FontRenderContext, char[], int, int, int) - Method in class java.awt.Font
Returns a new GlyphVector object, performing full layout of the text if possible.
layoutHScrollbar(JScrollBar) - Method in class javax.swing.plaf.basic.BasicScrollBarUI
layoutInfo - Variable in class java.awt.GridBagLayout
This field holds the layout information for the gridbag.
layoutLabel(int, FontMetrics, int, String, Icon, Rectangle, Rectangle, Rectangle, boolean) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI
layoutMajorAxis(int, int, int[], int[]) - Method in class javax.swing.text.BoxView
Performs layout for the major axis of the box (i.e.
layoutMajorAxis(int, int, int[], int[]) - Method in class javax.swing.text.TableView.TableRow
Perform layout for the major axis of the box (i.e.
LayoutManager - Interface in java.awt
Defines the interface for classes that know how to lay out Containers.
layoutManager - Variable in class javax.swing.plaf.basic.BasicSplitPaneUI
LayoutManager that is created and placed into the split pane.
LayoutManager2 - Interface in java.awt
Defines an interface for classes that know how to layout Containers based on a layout constraints object.
layoutMinorAxis(int, int, int[], int[]) - Method in class javax.swing.text.BoxView
Performs layout for the minor axis of the box (i.e.
layoutMinorAxis(int, int, int[], int[]) - Method in class javax.swing.text.html.BlockView
Performs layout for the minor axis of the box (i.e.
layoutMinorAxis(int, int, int[], int[]) - Method in class javax.swing.text.TableView
Perform layout for the minor axis of the box (i.e.
layoutMinorAxis(int, int, int[], int[]) - Method in class javax.swing.text.TableView.TableRow
Perform layout for the minor axis of the box (i.e.
LayoutPath - Class in java.awt.font
LayoutPath provides a mapping between locations relative to the baseline and points in user space.
LayoutPath() - Constructor for class java.awt.font.LayoutPath
layoutPool - Variable in class javax.swing.text.FlowView
These are the views that represent the child elements of the element this view represents (The logical view to translate to a physical view).
LayoutQueue - Class in javax.swing.text
A queue of text layout tasks.
LayoutQueue() - Constructor for class javax.swing.text.LayoutQueue
Construct a layout queue.
layoutRow(FlowView, int, int) - Method in class javax.swing.text.FlowView.FlowStrategy
Creates a row of views that will fit within the layout span of the row.
layoutSpan - Variable in class javax.swing.text.FlowView
Default constraint against which the flow is created against.
LayoutStyle - Class in javax.swing
LayoutStyle provides information about how to position components.
LayoutStyle() - Constructor for class javax.swing.LayoutStyle
Creates a new LayoutStyle.
LayoutStyle.ComponentPlacement - Enum in javax.swing
ComponentPlacement is an enumeration of the possible ways two components can be placed relative to each other.
layoutText(SynthContext, FontMetrics, String, Icon, int, int, int, int, Rectangle, Rectangle, Rectangle, int) - Method in class javax.swing.plaf.synth.SynthGraphicsUtils
Lays out text and an icon returning, by reference, the location to place the icon and text.
layoutVScrollbar(JScrollBar) - Method in class javax.swing.plaf.basic.BasicScrollBarUI
lazilyLoadDesktopProperty(String) - Method in class java.awt.Toolkit
an opportunity to lazily evaluate desktop property values.
lazySet(boolean) - Method in class java.util.concurrent.atomic.AtomicBoolean
Eventually sets to the given value.
lazySet(int) - Method in class java.util.concurrent.atomic.AtomicInteger
Eventually sets to the given value.
lazySet(int, int) - Method in class java.util.concurrent.atomic.AtomicIntegerArray
Eventually sets the element at position i to the given value.
lazySet(T, int) - Method in class java.util.concurrent.atomic.AtomicIntegerFieldUpdater
Eventually sets the field of the given object managed by this updater to the given updated value.
lazySet(long) - Method in class java.util.concurrent.atomic.AtomicLong
Eventually sets to the given value.
lazySet(int, long) - Method in class java.util.concurrent.atomic.AtomicLongArray
Eventually sets the element at position i to the given value.
lazySet(T, long) - Method in class java.util.concurrent.atomic.AtomicLongFieldUpdater
Eventually sets the field of the given object managed by this updater to the given updated value.
lazySet(V) - Method in class java.util.concurrent.atomic.AtomicReference
Eventually sets to the given value.
lazySet(int, E) - Method in class java.util.concurrent.atomic.AtomicReferenceArray
Eventually sets the element at position i to the given value.
lazySet(T, V) - Method in class java.util.concurrent.atomic.AtomicReferenceFieldUpdater
Eventually sets the field of the given object managed by this updater to the given updated value.
LDAPCertStoreParameters - Class in java.security.cert
Parameters used as input for the LDAP CertStore algorithm.
LDAPCertStoreParameters(String, int) - Constructor for class java.security.cert.LDAPCertStoreParameters
Creates an instance of LDAPCertStoreParameters with the specified parameter values.
LDAPCertStoreParameters(String) - Constructor for class java.security.cert.LDAPCertStoreParameters
Creates an instance of LDAPCertStoreParameters with the specified server name and a default port of 389.
LDAPCertStoreParameters() - Constructor for class java.security.cert.LDAPCertStoreParameters
Creates an instance of LDAPCertStoreParameters with the default parameter values (server name "localhost", port 389).
LdapContext - Interface in javax.naming.ldap
This interface represents a context in which you can perform operations with LDAPv3-style controls and perform LDAPv3-style extended operations.
LdapName - Class in javax.naming.ldap
This class represents a distinguished name as specified by RFC 2253.
LdapName(String) - Constructor for class javax.naming.ldap.LdapName
Constructs an LDAP name from the given distinguished name.
LdapName(List<Rdn>) - Constructor for class javax.naming.ldap.LdapName
Constructs an LDAP name given its parsed RDN components.
LdapReferralException - Exception in javax.naming.ldap
This abstract class is used to represent an LDAP referral exception.
LdapReferralException(String) - Constructor for exception javax.naming.ldap.LdapReferralException
Constructs a new instance of LdapReferralException using the explanation supplied.
LdapReferralException() - Constructor for exception javax.naming.ldap.LdapReferralException
Constructs a new instance of LdapReferralException.
LE - Static variable in class javax.management.Query
A code representing the Query.leq(javax.management.ValueExp, javax.management.ValueExp) query.
LEAD_DOTS - Static variable in class javax.swing.text.TabStop
LEAD_EQUALS - Static variable in class javax.swing.text.TabStop
LEAD_HYPHENS - Static variable in class javax.swing.text.TabStop
LEAD_NONE - Static variable in class javax.swing.text.TabStop
LEAD_SELECTION_PATH_PROPERTY - Static variable in class javax.swing.JTree
Bound property name for leadSelectionPath.
LEAD_THICKLINE - Static variable in class javax.swing.text.TabStop
LEAD_UNDERLINE - Static variable in class javax.swing.text.TabStop
leadAnchorNotificationEnabled - Variable in class javax.swing.DefaultListSelectionModel
leadIndex - Variable in class javax.swing.tree.DefaultTreeSelectionModel
Index of the lead path in selection.
LEADING - Static variable in class java.awt.FlowLayout
This value indicates that each row of components should be justified to the leading edge of the container's orientation, for example, to the left in left-to-right orientations.
leading(int) - Static method in class java.awt.font.TextHitInfo
Creates a TextHitInfo on the leading edge of the character at the specified charIndex.
LEADING - Static variable in class javax.swing.border.TitledBorder
Position title text at the left side of the border line for left to right orientation, at the right side of the border line for right to left orientation.
LEADING - Static variable in interface javax.swing.SwingConstants
Identifies the leading edge of text for use with left-to-right and right-to-left languages.
leadPath - Variable in class javax.swing.tree.DefaultTreeSelectionModel
Last path that was added.
leadRow - Variable in class javax.swing.tree.DefaultTreeSelectionModel
Lead row.
leafIcon - Variable in class javax.swing.tree.DefaultTreeCellRenderer
Icon used to show leaf nodes.
Lease - Class in java.rmi.dgc
A lease contains a unique VM identifier and a lease duration.
Lease(VMID, long) - Constructor for class java.rmi.dgc.Lease
Constructs a lease with a specific VMID and lease duration.
leave(InetAddress) - Method in class java.net.DatagramSocketImpl
Leave the multicast group.
leaveGroup(SocketAddress, NetworkInterface) - Method in class java.net.DatagramSocketImpl
Leave the multicast group.
leaveGroup(InetAddress) - Method in class java.net.MulticastSocket
Leave a multicast group.
leaveGroup(SocketAddress, NetworkInterface) - Method in class java.net.MulticastSocket
Leave a multicast group on a specified local interface.
LEDGER - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for Ledger, 11 x 17 in.
LEDGER - Static variable in class javax.print.attribute.standard.MediaSize.Other
Specifies the ledger size, 11 inches by 17 inches.
LEDGER - Static variable in class javax.print.attribute.standard.MediaSizeName
ledger size .
LEFT - Static variable in class java.awt.Event
The Left Arrow key, a non-ASCII action key.
LEFT - Static variable in class java.awt.FlowLayout
This value indicates that each row of components should be left-justified.
left - Variable in class java.awt.Insets
The inset from the left.
LEFT - Static variable in class java.awt.Label
Indicates that the label should be left justified.
left - Variable in class javax.swing.border.EmptyBorder
LEFT - Static variable in class javax.swing.border.TitledBorder
Position title text at the left side of the border line.
LEFT - Static variable in class javax.swing.JSplitPane
Used to add a Component to the left of the other Component.
LEFT - Static variable in interface javax.swing.SwingConstants
Box-orientation constant used to specify the left side of a box.
LEFT_ALIGNMENT - Static variable in class java.awt.Component
Ease-of-use constant for getAlignmentX.
LEFT_JUSTIFY - Static variable in class java.util.FormattableFlags
Left-justifies the output.
LEFT_OUTER_JOIN - Static variable in interface javax.sql.rowset.JoinRowSet
An ANSI-style JOIN providing a left outer join between two tables.
LEFT_TO_RIGHT - Static variable in class java.awt.ComponentOrientation
Items run left to right and lines flow top to bottom Examples: English, French.
leftButton - Variable in class javax.swing.plaf.basic.BasicSplitPaneDivider
Button for quickly toggling the left component.
leftChildIndent - Variable in class javax.swing.plaf.basic.BasicTreeUI
Distance between left margin and where vertical dashes will be drawn.
leftComponent - Variable in class javax.swing.JSplitPane
The left or top component.
LeftIndent - Static variable in class javax.swing.text.StyleConstants
The amount to indent the left side of the paragraph.
leftKey - Variable in class javax.swing.plaf.basic.BasicSplitPaneUI
Deprecated.
As of Java 2 platform v1.3.
leftKey - Variable in class javax.swing.plaf.basic.BasicTabbedPaneUI
Deprecated.
As of Java 2 platform v1.3.
leftKey - Variable in class javax.swing.plaf.basic.BasicToolBarUI
Deprecated.
As of Java 2 platform v1.3.
leftToRightCache - Variable in class javax.swing.plaf.basic.BasicSliderUI
LEGAL - Static variable in class java.awt.PageAttributes.MediaType
An alias for NA_LEGAL.
LEGAL - Static variable in class javax.print.attribute.standard.MediaSize.NA
Specifies the North American legal size, 8.5 inches by 14 inches.
LEGAL_VALUES_FIELD - Static variable in class javax.management.JMX
The name of the legalValues field.
len - Variable in class java.util.zip.InflaterInputStream
Length of input buffer.
length() - Method in class java.io.File
Returns the length of the file denoted by this abstract pathname.
length - Variable in exception java.io.OptionalDataException
The number of bytes of primitive data available to be read in the current buffer.
length() - Method in class java.io.RandomAccessFile
Returns the length of this file.
length() - Method in interface java.lang.CharSequence
Returns the length of this character sequence.
length() - Method in class java.lang.String
Returns the length of this string.
length() - Method in class java.lang.StringBuffer
length() - Method in class java.nio.CharBuffer
Returns the length of this character buffer.
length() - Method in class java.nio.charset.CoderResult
Returns the length of the erroneous input described by this object (optional operation).
length() - Method in interface java.sql.Blob
Returns the number of bytes in the BLOB value designated by this Blob object.
length() - Method in interface java.sql.Clob
Retrieves the number of characters in the CLOB value designated by this Clob object.
length() - Method in class java.util.BitSet
Returns the "logical size" of this BitSet: the index of the highest set bit in the BitSet plus one.
length() - Method in class java.util.concurrent.atomic.AtomicIntegerArray
Returns the length of the array.
length() - Method in class java.util.concurrent.atomic.AtomicLongArray
Returns the length of the array.
length() - Method in class java.util.concurrent.atomic.AtomicReferenceArray
Returns the length of the array.
length() - Method in class javax.imageio.stream.FileCacheImageOutputStream
length() - Method in class javax.imageio.stream.FileImageInputStream
Returns the length of the underlying file, or -1 if it is unknown.
length() - Method in class javax.imageio.stream.FileImageOutputStream
length() - Method in interface javax.imageio.stream.ImageInputStream
Returns the total length of the stream, if known.
length() - Method in class javax.imageio.stream.ImageInputStreamImpl
Returns -1L to indicate that the stream has unknown length.
length() - Method in class javax.imageio.stream.MemoryCacheImageOutputStream
length - Variable in class javax.sound.midi.MidiMessage
The number of bytes in the MIDI message, including the status byte and any data bytes.
length() - Method in class javax.sql.rowset.serial.SerialBlob
Retrieves the number of bytes in this SerialBlob object's array of bytes.
length() - Method in class javax.sql.rowset.serial.SerialClob
Retrieves the number of characters in this SerialClob object's array of characters.
length() - Method in interface javax.swing.text.AbstractDocument.Content
Current length of the sequence of character content.
length() - Method in class javax.swing.text.GapContent
Returns the length of the content.
length() - Method in class javax.swing.text.Segment
Returns the length of this character sequence.
length() - Method in class javax.swing.text.StringContent
Returns the length of the content.
length() - Method in interface org.omg.CORBA.DynSequence
Deprecated.
Returns the length of the sequence represented by this DynFixed object.
length(int) - Method in interface org.omg.CORBA.DynSequence
Deprecated.
Sets the length of the sequence represented by this DynFixed object to the given argument.
length() - Method in class org.omg.CORBA.TypeCode
Returns the number of elements in the type described by this TypeCode object.
LEPCHA - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Lepcha" Unicode character block.
leq(ValueExp, ValueExp) - Static method in class javax.management.Query
Returns a query expression that represents a "less than or equal to" constraint on two values.
LESS_THAN_MIN_ROLE_DEGREE - Static variable in class javax.management.relation.RoleStatus
Problem type when trying to set a role value with less ObjectNames than the minimum expected cardinality.
LESSER - Static variable in class javax.xml.datatype.DatatypeConstants
Comparison result.
lessThanOrEquals(ResolutionSyntax) - Method in class javax.print.attribute.ResolutionSyntax
Determine whether this resolution attribute's value is less than or equal to the given resolution attribute's value.
LETTER - Static variable in class java.awt.PageAttributes.MediaType
An alias for NA_LETTER.
LETTER - Static variable in class javax.print.attribute.standard.MediaSize.NA
Specifies the North American letter size, 8.5 inches by 11 inches.
LETTER_NUMBER - Static variable in class java.lang.Character
General category "Nl" in the Unicode specification.
LETTER_SPACING - Static variable in class javax.swing.text.html.CSS.Attribute
LETTERLIKE_SYMBOLS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Letterlike Symbols" Unicode character block.
Level - Class in java.util.logging
The Level class defines a set of standard logging levels that can be used to control logging output.
Level(String, int) - Constructor for class java.util.logging.Level
Create a named Level with a given integer value.
Level(String, int, String) - Constructor for class java.util.logging.Level
Create a named Level with a given integer value and a given localization resource name.
LexicalHandler - Interface in org.xml.sax.ext
SAX2 extension handler for lexical events.
LI - Static variable in class javax.swing.text.html.HTML.Tag
LIFESPAN_POLICY_ID - Interface in org.omg.PortableServer
org/omg/PortableServer/LIFESPAN_POLICY_ID.java .
LifespanPolicy - Interface in org.omg.PortableServer
The LifespanPolicy specifies the lifespan of the objects implemented in the created POA.
LifespanPolicyOperations - Interface in org.omg.PortableServer
The LifespanPolicy specifies the lifespan of the objects implemented in the created POA.
LifespanPolicyValue - Class in org.omg.PortableServer
The LifespanPolicyValue can have the following values.
LifespanPolicyValue(int) - Constructor for class org.omg.PortableServer.LifespanPolicyValue
LIGATURE - Static variable in class java.awt.font.GlyphMetrics
Indicates a glyph that represents multiple characters as a ligature, for example 'fi' or 'ffi'.
LIGATURES - Static variable in class java.awt.font.TextAttribute
Attribute key for enabling optional ligatures.
LIGATURES_ON - Static variable in class java.awt.font.TextAttribute
Request standard optional ligatures.
LIGHT - Static variable in class javax.swing.plaf.metal.MetalIconFactory
LIGHT_GRAY - Static variable in class java.awt.Color
The color light gray.
lightGray - Static variable in class java.awt.Color
The color light gray.
lightHighlight - Variable in class javax.swing.plaf.basic.BasicBorders.ButtonBorder
lightHighlight - Variable in class javax.swing.plaf.basic.BasicBorders.FieldBorder
lightHighlight - Variable in class javax.swing.plaf.basic.BasicTabbedPaneUI
lightWeightPopupEnabled - Variable in class javax.swing.JComboBox
This protected field is implementation specific.
lightWeightPopupEnabled - Variable in class javax.swing.ToolTipManager
LIMBU - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Limbu" Unicode character block.
limit() - Method in class java.nio.Buffer
Returns this buffer's limit.
limit(int) - Method in class java.nio.Buffer
Sets this buffer's limit.
LimitExceededException - Exception in javax.naming
This exception is thrown when a method terminates abnormally due to a user or system specified limit.
LimitExceededException() - Constructor for exception javax.naming.LimitExceededException
Constructs a new instance of LimitExceededException with all name resolution fields and explanation initialized to null.
LimitExceededException(String) - Constructor for exception javax.naming.LimitExceededException
Constructs a new instance of LimitExceededException using an explanation.
LINE - Static variable in interface javax.accessibility.AccessibleExtendedText
Constant used to indicate that the part of the text that should be retrieved is a line of text.
Line - Interface in javax.sound.sampled
The Line interface represents a mono or multi-channel audio feed.
Line.Info - Class in javax.sound.sampled
A Line.Info object contains information about a line.
Line.Info(Class<?>) - Constructor for class javax.sound.sampled.Line.Info
Constructs an info object that describes a line of the specified class.
Line2D - Class in java.awt.geom
This Line2D represents a line segment in (x,y) coordinate space.
Line2D() - Constructor for class java.awt.geom.Line2D
This is an abstract class that cannot be instantiated directly.
Line2D.Double - Class in java.awt.geom
A line segment specified with double coordinates.
Line2D.Double() - Constructor for class java.awt.geom.Line2D.Double
Constructs and initializes a Line with coordinates (0, 0) -> (0, 0).
Line2D.Double(double, double, double, double) - Constructor for class java.awt.geom.Line2D.Double
Constructs and initializes a Line2D from the specified coordinates.
Line2D.Double(Point2D, Point2D) - Constructor for class java.awt.geom.Line2D.Double
Constructs and initializes a Line2D from the specified Point2D objects.
Line2D.Float - Class in java.awt.geom
A line segment specified with float coordinates.
Line2D.Float() - Constructor for class java.awt.geom.Line2D.Float
Constructs and initializes a Line with coordinates (0, 0) -> (0, 0).
Line2D.Float(float, float, float, float) - Constructor for class java.awt.geom.Line2D.Float
Constructs and initializes a Line from the specified coordinates.
Line2D.Float(Point2D, Point2D) - Constructor for class java.awt.geom.Line2D.Float
Constructs and initializes a Line2D from the specified Point2D objects.
LINE_AXIS - Static variable in class javax.swing.BoxLayout
Specifies that components should be laid out in the direction of a line of text as determined by the target container's ComponentOrientation property.
LINE_END - Static variable in class java.awt.BorderLayout
The component goes at the end of the line direction for the layout.
LINE_END - Static variable in class java.awt.GridBagConstraints
Place the component centered along the edge of its display area where lines of text would normally end for the current ComponentOrientation.
LINE_HEIGHT - Static variable in class javax.swing.text.html.CSS.Attribute
LINE_IN - Static variable in class javax.sound.sampled.Port.Info
A type of port that gets audio from a line-level audio input jack.
LINE_OUT - Static variable in class javax.sound.sampled.Port.Info
A type of port that sends audio to a line-level audio output jack.
LINE_SEPARATOR - Static variable in class java.lang.Character
General category "Zl" in the Unicode specification.
LINE_START - Static variable in class java.awt.BorderLayout
The component goes at the beginning of the line direction for the layout.
LINE_START - Static variable in class java.awt.GridBagConstraints
Place the component centered along the edge of its display area where lines of text would normally begin for the current ComponentOrientation.
LINEAR_B_IDEOGRAMS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Linear B Ideograms" Unicode character block.
LINEAR_B_SYLLABARY - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Linear B Syllabary" Unicode character block.
LinearGradientPaint - Class in java.awt
The LinearGradientPaint class provides a way to fill a Shape with a linear color gradient pattern.
LinearGradientPaint(float, float, float, float, float[], Color[]) - Constructor for class java.awt.LinearGradientPaint
Constructs a LinearGradientPaint with a default NO_CYCLE repeating method and SRGB color space.
LinearGradientPaint(float, float, float, float, float[], Color[], MultipleGradientPaint.CycleMethod) - Constructor for class java.awt.LinearGradientPaint
Constructs a LinearGradientPaint with a default SRGB color space.
LinearGradientPaint(Point2D, Point2D, float[], Color[]) - Constructor for class java.awt.LinearGradientPaint
Constructs a LinearGradientPaint with a default NO_CYCLE repeating method and SRGB color space.
LinearGradientPaint(Point2D, Point2D, float[], Color[], MultipleGradientPaint.CycleMethod) - Constructor for class java.awt.LinearGradientPaint
Constructs a LinearGradientPaint with a default SRGB color space.
LinearGradientPaint(Point2D, Point2D, float[], Color[], MultipleGradientPaint.CycleMethod, MultipleGradientPaint.ColorSpaceType, AffineTransform) - Constructor for class java.awt.LinearGradientPaint
Constructs a LinearGradientPaint.
LineBorder - Class in javax.swing.border
A class which implements a line border of arbitrary thickness and of a single color.
LineBorder(Color) - Constructor for class javax.swing.border.LineBorder
Creates a line border with the specified color and a thickness = 1.
LineBorder(Color, int) - Constructor for class javax.swing.border.LineBorder
Creates a line border with the specified color and thickness.
LineBorder(Color, int, boolean) - Constructor for class javax.swing.border.LineBorder
Creates a line border with the specified color, thickness, and corner shape.
LineBreakMeasurer - Class in java.awt.font
The LineBreakMeasurer class allows styled text to be broken into lines (or segments) that fit within a particular visual advance.
LineBreakMeasurer(AttributedCharacterIterator, FontRenderContext) - Constructor for class java.awt.font.LineBreakMeasurer
Constructs a LineBreakMeasurer for the specified text.
LineBreakMeasurer(AttributedCharacterIterator, BreakIterator, FontRenderContext) - Constructor for class java.awt.font.LineBreakMeasurer
Constructs a LineBreakMeasurer for the specified text.
lineColor - Variable in class javax.swing.border.LineBorder
LineEvent - Class in javax.sound.sampled
The LineEvent class encapsulates information that a line sends its listeners whenever the line opens, closes, starts, or stops.
LineEvent(Line, LineEvent.Type, long) - Constructor for class javax.sound.sampled.LineEvent
Constructs a new event of the specified type, originating from the specified line.
LineEvent.Type - Class in javax.sound.sampled
The LineEvent.Type inner class identifies what kind of event occurred on a line.
LineEvent.Type(String) - Constructor for class javax.sound.sampled.LineEvent.Type
Constructs a new event type.
lineLimitAttribute - Static variable in class javax.swing.text.PlainDocument
Name of the attribute that specifies the maximum length of a line, if there is a maximum length.
LineListener - Interface in javax.sound.sampled
Instances of classes that implement the LineListener interface can register to receive events when a line's status changes.
LineMetrics - Class in java.awt.font
The LineMetrics class allows access to the metrics needed to layout characters along a line and to layout of a set of lines.
LineMetrics() - Constructor for class java.awt.font.LineMetrics
lineno() - Method in class java.io.StreamTokenizer
Return the current line number.
LineNumberInputStream - Class in java.io
Deprecated.
This class incorrectly assumes that bytes adequately represent characters. As of JDK 1.1, the preferred way to operate on character streams is via the new character-stream classes, which include a class for counting line numbers.
LineNumberInputStream(InputStream) - Constructor for class java.io.LineNumberInputStream
Deprecated.
Constructs a newline number input stream that reads its input from the specified input stream.
LineNumberReader - Class in java.io
A buffered character-input stream that keeps track of line numbers.
LineNumberReader(Reader) - Constructor for class java.io.LineNumberReader
Create a new line-numbering reader, using the default input-buffer size.
LineNumberReader(Reader, int) - Constructor for class java.io.LineNumberReader
Create a new line-numbering reader, reading characters into a buffer of the given size.
lineSeparator() - Static method in class java.lang.System
Returns the system-dependent line separator string.
linesIntersect(double, double, double, double, double, double, double, double) - Static method in class java.awt.geom.Line2D
Tests if the line segment from (x1,y1) to (x2,y2) intersects the line segment from (x3,y3) to (x4,y4).
LineSpacing - Static variable in class javax.swing.text.StyleConstants
The amount of space between lines of the paragraph.
lineTo(double, double) - Method in class java.awt.geom.Path2D.Double
Adds a point to the path by drawing a straight line from the current coordinates to the new specified coordinates specified in double precision.
lineTo(double, double) - Method in class java.awt.geom.Path2D.Float
Adds a point to the path by drawing a straight line from the current coordinates to the new specified coordinates specified in double precision.
lineTo(float, float) - Method in class java.awt.geom.Path2D.Float
Adds a point to the path by drawing a straight line from the current coordinates to the new specified coordinates specified in float precision.
lineTo(double, double) - Method in class java.awt.geom.Path2D
Adds a point to the path by drawing a straight line from the current coordinates to the new specified coordinates specified in double precision.
lineToRect(Shape, int) - Method in class javax.swing.text.PlainView
Determine the rectangle that represents the given line.
LineUnavailableException - Exception in javax.sound.sampled
A LineUnavailableException is an exception indicating that a line cannot be opened because it is unavailable.
LineUnavailableException() - Constructor for exception javax.sound.sampled.LineUnavailableException
Constructs a LineUnavailableException that has null as its error detail message.
LineUnavailableException(String) - Constructor for exception javax.sound.sampled.LineUnavailableException
Constructs a LineUnavailableException that has the specified detail message.
LINK - Static variable in class javax.swing.text.html.HTML.Attribute
LINK - Static variable in class javax.swing.text.html.HTML.Tag
LINK - Static variable in class javax.swing.TransferHandler
An int representing a "link" transfer action.
LinkageError - Error in java.lang
Subclasses of LinkageError indicate that a class has some dependency on another class; however, the latter class has incompatibly changed after the compilation of the former class.
LinkageError() - Constructor for error java.lang.LinkageError
Constructs a LinkageError with no detail message.
LinkageError(String) - Constructor for error java.lang.LinkageError
Constructs a LinkageError with the specified detail message.
LinkageError(String, Throwable) - Constructor for error java.lang.LinkageError
Constructs a LinkageError with the specified detail message and cause.
LinkedBlockingDeque<E> - Class in java.util.concurrent
An optionally-bounded blocking deque based on linked nodes.
LinkedBlockingDeque() - Constructor for class java.util.concurrent.LinkedBlockingDeque
Creates a LinkedBlockingDeque with a capacity of Integer.MAX_VALUE.
LinkedBlockingDeque(int) - Constructor for class java.util.concurrent.LinkedBlockingDeque
Creates a LinkedBlockingDeque with the given (fixed) capacity.
LinkedBlockingDeque(Collection<? extends E>) - Constructor for class java.util.concurrent.LinkedBlockingDeque
Creates a LinkedBlockingDeque with a capacity of Integer.MAX_VALUE, initially containing the elements of the given collection, added in traversal order of the collection's iterator.
LinkedBlockingQueue<E> - Class in java.util.concurrent
An optionally-bounded blocking queue based on linked nodes.
LinkedBlockingQueue() - Constructor for class java.util.concurrent.LinkedBlockingQueue
Creates a LinkedBlockingQueue with a capacity of Integer.MAX_VALUE.
LinkedBlockingQueue(int) - Constructor for class java.util.concurrent.LinkedBlockingQueue
Creates a LinkedBlockingQueue with the given (fixed) capacity.
LinkedBlockingQueue(Collection<? extends E>) - Constructor for class java.util.concurrent.LinkedBlockingQueue
Creates a LinkedBlockingQueue with a capacity of Integer.MAX_VALUE, initially containing the elements of the given collection, added in traversal order of the collection's iterator.
LinkedHashMap<K,V> - Class in java.util
Hash table and linked list implementation of the Map interface, with predictable iteration order.
LinkedHashMap(int, float) - Constructor for class java.util.LinkedHashMap
Constructs an empty insertion-ordered LinkedHashMap instance with the specified initial capacity and load factor.
LinkedHashMap(int) - Constructor for class java.util.LinkedHashMap
Constructs an empty insertion-ordered LinkedHashMap instance with the specified initial capacity and a default load factor (0.75).
LinkedHashMap() - Constructor for class java.util.LinkedHashMap
Constructs an empty insertion-ordered LinkedHashMap instance with the default initial capacity (16) and load factor (0.75).
LinkedHashMap(Map<? extends K, ? extends V>) - Constructor for class java.util.LinkedHashMap
Constructs an insertion-ordered LinkedHashMap instance with the same mappings as the specified map.
LinkedHashMap(int, float, boolean) - Constructor for class java.util.LinkedHashMap
Constructs an empty LinkedHashMap instance with the specified initial capacity, load factor and ordering mode.
LinkedHashSet<E> - Class in java.util
Hash table and linked list implementation of the Set interface, with predictable iteration order.
LinkedHashSet(int, float) - Constructor for class java.util.LinkedHashSet
Constructs a new, empty linked hash set with the specified initial capacity and load factor.
LinkedHashSet(int) - Constructor for class java.util.LinkedHashSet
Constructs a new, empty linked hash set with the specified initial capacity and the default load factor (0.75).
LinkedHashSet() - Constructor for class java.util.LinkedHashSet
Constructs a new, empty linked hash set with the default initial capacity (16) and load factor (0.75).
LinkedHashSet(Collection<? extends E>) - Constructor for class java.util.LinkedHashSet
Constructs a new linked hash set with the same elements as the specified collection.
LinkedList<E> - Class in java.util
Doubly-linked list implementation of the List and Deque interfaces.
LinkedList() - Constructor for class java.util.LinkedList
Constructs an empty list.
LinkedList(Collection<? extends E>) - Constructor for class java.util.LinkedList
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.
LinkedTransferQueue<E> - Class in java.util.concurrent
An unbounded TransferQueue based on linked nodes.
LinkedTransferQueue() - Constructor for class java.util.concurrent.LinkedTransferQueue
Creates an initially empty LinkedTransferQueue.
LinkedTransferQueue(Collection<? extends E>) - Constructor for class java.util.concurrent.LinkedTransferQueue
Creates a LinkedTransferQueue initially containing the elements of the given collection, added in traversal order of the collection's iterator.
LinkException - Exception in javax.naming
This exception is used to describe problems encounter while resolving links.
LinkException(String) - Constructor for exception javax.naming.LinkException
Constructs a new instance of LinkException with an explanation All the other fields are initialized to null.
LinkException() - Constructor for exception javax.naming.LinkException
Constructs a new instance of LinkException.
linkExplanation - Variable in exception javax.naming.LinkException
Contains the exception of why resolution of the link failed.
LinkLoopException - Exception in javax.naming
This exception is thrown when a loop was detected will attempting to resolve a link, or an implementation specific limit on link counts has been reached.
LinkLoopException(String) - Constructor for exception javax.naming.LinkLoopException
Constructs a new instance of LinkLoopException with an explanation All the other fields are initialized to null.
LinkLoopException() - Constructor for exception javax.naming.LinkLoopException
Constructs a new instance of LinkLoopException.
LinkOption - Enum in java.nio.file
Defines the options as to how symbolic links are handled.
LinkPermission - Class in java.nio.file
The Permission class for link creation operations.
LinkPermission(String) - Constructor for class java.nio.file.LinkPermission
Constructs a LinkPermission with the specified name.
LinkPermission(String, String) - Constructor for class java.nio.file.LinkPermission
Constructs a LinkPermission with the specified name.
LinkRef - Class in javax.naming
This class represents a Reference whose contents is a name, called the link name, that is bound to an atomic name in a context.
LinkRef(Name) - Constructor for class javax.naming.LinkRef
Constructs a LinkRef for a name.
LinkRef(String) - Constructor for class javax.naming.LinkRef
Constructs a LinkRef for a string name.
linkRemainingName - Variable in exception javax.naming.LinkException
Contains the remaining link name that has not been resolved yet.
linkResolvedName - Variable in exception javax.naming.LinkException
Contains the part of the link that has been successfully resolved.
linkResolvedObj - Variable in exception javax.naming.LinkException
Contains the object to which resolution of the part of the link was successful.
linkSize(Component...) - Method in class javax.swing.GroupLayout
Forces the specified components to have the same size regardless of their preferred, minimum or maximum sizes.
linkSize(int, Component...) - Method in class javax.swing.GroupLayout
Forces the specified components to have the same size along the specified axis regardless of their preferred, minimum or maximum sizes.
list() - Method in class java.awt.Component
Prints a listing of this component to the standard system output stream System.out.
list(PrintStream) - Method in class java.awt.Component
Prints a listing of this component to the specified output stream.
list(PrintStream, int) - Method in class java.awt.Component
Prints out a list, starting at the specified indentation, to the specified print stream.
list(PrintWriter) - Method in class java.awt.Component
Prints a listing to the specified print writer.
list(PrintWriter, int) - Method in class java.awt.Component
Prints out a list, starting at the specified indentation, to the specified print writer.
list(PrintStream, int) - Method in class java.awt.Container
Prints a listing of this container to the specified output stream.
list(PrintWriter, int) - Method in class java.awt.Container
Prints out a list, starting at the specified indentation, to the specified print writer.
List - Class in java.awt
The List component presents the user with a scrolling list of text items.
List() - Constructor for class java.awt.List
Creates a new scrolling list.
List(int) - Constructor for class java.awt.List
Creates a new scrolling list initialized with the specified number of visible lines.
List(int, boolean) - Constructor for class java.awt.List
Creates a new scrolling list initialized to display the specified number of rows.
list() - Method in class java.io.File
Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
list(FilenameFilter) - Method in class java.io.File
Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
list() - Method in class java.lang.ThreadGroup
Prints information about this thread group to the standard output.
list() - Method in interface java.nio.file.attribute.UserDefinedFileAttributeView
Returns a list containing the names of the user-defined attributes.
list(String) - Static method in class java.rmi.Naming
Returns an array of the names bound in the registry.
list() - Method in interface java.rmi.registry.Registry
Returns an array of the names bound in this registry.
list(Enumeration<T>) - Static method in class java.util.Collections
Returns an array list containing the elements returned by the specified enumeration in the order they are returned by the enumeration.
List<E> - Interface in java.util
An ordered collection (also known as a sequence).
list(PrintStream) - Method in class java.util.Properties
Prints this property list out to the specified output stream.
list(PrintWriter) - Method in class java.util.Properties
Prints this property list out to the specified output stream.
LIST - Static variable in class javax.accessibility.AccessibleRole
An object that presents a list of objects to the user and allows the user to select one or more of them.
list(Name) - Method in interface javax.naming.Context
Enumerates the names bound in the named context, along with the class names of objects bound to them.
list(String) - Method in interface javax.naming.Context
Enumerates the names bound in the named context, along with the class names of objects bound to them.
list(String) - Method in class javax.naming.InitialContext
list(Name) - Method in class javax.naming.InitialContext
list - Variable in class javax.swing.plaf.basic.BasicComboPopup
This protected field is implementation specific.
list - Variable in class javax.swing.plaf.basic.BasicListUI
LIST - Static variable in class javax.swing.plaf.synth.Region
List region.
list(JavaFileManager.Location, String, Set<JavaFileObject.Kind>, boolean) - Method in class javax.tools.ForwardingJavaFileManager
list(JavaFileManager.Location, String, Set<JavaFileObject.Kind>, boolean) - Method in interface javax.tools.JavaFileManager
Lists all file objects matching the given criteria in the given location.
list(int, BindingListHolder, BindingIteratorHolder) - Method in class org.omg.CosNaming._NamingContextExtStub
The list operation allows a client to iterate through a set of bindings in a naming context.
list(int, BindingListHolder, BindingIteratorHolder) - Method in class org.omg.CosNaming._NamingContextStub
The list operation allows a client to iterate through a set of bindings in a naming context.
list(int, BindingListHolder, BindingIteratorHolder) - Method in interface org.omg.CosNaming.NamingContextOperations
The list operation allows a client to iterate through a set of bindings in a naming context.
List.AccessibleAWTList - Class in java.awt
This class implements accessibility support for the List class.
List.AccessibleAWTList() - Constructor for class java.awt.List.AccessibleAWTList
List.AccessibleAWTList.AccessibleAWTListChild - Class in java.awt
This class implements accessibility support for List children.
List.AccessibleAWTList.AccessibleAWTListChild(List, int) - Constructor for class java.awt.List.AccessibleAWTList.AccessibleAWTListChild
LIST_DESELECT - Static variable in class java.awt.Event
An item in a list has been deselected.
LIST_DIRECTORY - Static variable in enum java.nio.file.attribute.AclEntryPermission
Permission to list the entries of a directory (equal to AclEntryPermission.READ_DATA)
list_initial_services() - Method in class org.omg.CORBA.ORB
Returns a list of the initially available CORBA object references, such as "NameService" and "InterfaceRepository".
LIST_ITEM - Static variable in class javax.accessibility.AccessibleRole
An object that presents an element in a list.
LIST_SELECT - Static variable in class java.awt.Event
An item in a list has been selected.
LIST_STYLE - Static variable in class javax.swing.text.html.CSS.Attribute
LIST_STYLE_IMAGE - Static variable in class javax.swing.text.html.CSS.Attribute
LIST_STYLE_POSITION - Static variable in class javax.swing.text.html.CSS.Attribute
LIST_STYLE_TYPE - Static variable in class javax.swing.text.html.CSS.Attribute
listBindings(Name) - Method in interface javax.naming.Context
Enumerates the names bound in the named context, along with the objects bound to them.
listBindings(String) - Method in interface javax.naming.Context
Enumerates the names bound in the named context, along with the objects bound to them.
listBindings(String) - Method in class javax.naming.InitialContext
listBindings(Name) - Method in class javax.naming.InitialContext
listBox - Variable in class javax.swing.plaf.basic.BasicComboBoxUI
listBox - Variable in class javax.swing.plaf.metal.MetalComboBoxButton
ListCellRenderer<E> - Interface in javax.swing
Identifies components that can be used as "rubber stamps" to paint the cells in a JList.
ListDataEvent - Class in javax.swing.event
Defines an event that encapsulates changes to a list.
ListDataEvent(Object, int, int, int) - Constructor for class javax.swing.event.ListDataEvent
Constructs a ListDataEvent object.
ListDataListener - Interface in javax.swing.event
ListDataListener
listDataListener - Variable in class javax.swing.plaf.basic.BasicComboBoxUI
This protected field is implementation specific.
listDataListener - Variable in class javax.swing.plaf.basic.BasicComboPopup
This protected field is implementation specific.
listDataListener - Variable in class javax.swing.plaf.basic.BasicListUI
listen(int) - Method in class java.net.SocketImpl
Sets the maximum queue length for incoming connection indications (a request to connect) to the count argument.
listenerList - Variable in class javax.swing.AbstractCellEditor
listenerList - Variable in class javax.swing.AbstractListModel
listenerList - Variable in class javax.swing.AbstractSpinnerModel
The list of ChangeListeners for this model.
listenerList - Variable in class javax.swing.colorchooser.DefaultColorSelectionModel
listenerList - Variable in class javax.swing.DefaultBoundedRangeModel
The listeners waiting for model changes.
listenerList - Variable in class javax.swing.DefaultButtonModel
Stores the listeners on this model.
listenerList - Variable in class javax.swing.DefaultListSelectionModel
listenerList - Variable in class javax.swing.DefaultSingleSelectionModel
The collection of registered listeners
listenerList - Variable in class javax.swing.event.EventListenerList
listenerList - Variable in class javax.swing.JComponent
A list of event listeners for this component.
listenerList - Variable in class javax.swing.MenuSelectionManager
listenerList - Variable in class javax.swing.table.AbstractTableModel
List of listeners
listenerList - Variable in class javax.swing.table.DefaultTableColumnModel
List of TableColumnModelListener
listenerList - Variable in class javax.swing.text.AbstractDocument
The event listener list for the document.
listenerList - Variable in class javax.swing.text.DefaultCaret
The event listener list.
listenerList - Variable in class javax.swing.text.StyleContext.NamedStyle
The change listeners for the model.
listenerList - Variable in class javax.swing.Timer
listenerList - Variable in class javax.swing.tree.DefaultTreeModel
Listeners.
listenerList - Variable in class javax.swing.tree.DefaultTreeSelectionModel
Event listener list.
ListenerNotFoundException - Exception in javax.management
The specified MBean listener does not exist in the repository.
ListenerNotFoundException() - Constructor for exception javax.management.ListenerNotFoundException
Default constructor.
ListenerNotFoundException(String) - Constructor for exception javax.management.ListenerNotFoundException
Constructor that allows a specific error message to be specified.
listeners - Variable in class javax.swing.undo.UndoableEditSupport
listFiles() - Method in class java.io.File
Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.
listFiles(FilenameFilter) - Method in class java.io.File
Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
listFiles(FileFilter) - Method in class java.io.File
Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
listIterator() - Method in class java.util.AbstractList
Returns a list iterator over the elements in this list (in proper sequence).
listIterator(int) - Method in class java.util.AbstractList
Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
listIterator(int) - Method in class java.util.AbstractSequentialList
Returns a list iterator over the elements in this list (in proper sequence).
listIterator(int) - Method in class java.util.ArrayList
Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
listIterator() - Method in class java.util.ArrayList
Returns a list iterator over the elements in this list (in proper sequence).
listIterator() - Method in class java.util.concurrent.CopyOnWriteArrayList
Returns a list iterator over the elements in this list (in proper sequence).
listIterator(int) - Method in class java.util.concurrent.CopyOnWriteArrayList
Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
listIterator(int) - Method in class java.util.LinkedList
Returns a list-iterator of the elements in this list (in proper sequence), starting at the specified position in the list.
listIterator() - Method in interface java.util.List
Returns a list iterator over the elements in this list (in proper sequence).
listIterator(int) - Method in interface java.util.List
Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
ListIterator<E> - Interface in java.util
An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list.
listIterator(int) - Method in class java.util.Vector
Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
listIterator() - Method in class java.util.Vector
Returns a list iterator over the elements in this list (in proper sequence).
ListModel<E> - Interface in javax.swing
This interface defines the methods components like JList use to get the value of each cell in a list and the length of the list.
listMouseListener - Variable in class javax.swing.plaf.basic.BasicComboPopup
This protected field is implementation specific.
listMouseMotionListener - Variable in class javax.swing.plaf.basic.BasicComboPopup
This protected field is implementation specific.
ListResourceBundle - Class in java.util
ListResourceBundle is an abstract subclass of ResourceBundle that manages resources for a locale in a convenient and easy to use list.
ListResourceBundle() - Constructor for class java.util.ListResourceBundle
Sole constructor.
listRoots() - Static method in class java.io.File
List the available filesystem roots.
ListSelectionEvent - Class in javax.swing.event
An event that characterizes a change in selection.
ListSelectionEvent(Object, int, int, boolean) - Constructor for class javax.swing.event.ListSelectionEvent
Represents a change in selection status between firstIndex and lastIndex, inclusive.
ListSelectionListener - Interface in javax.swing.event
The listener that's notified when a lists selection value changes.
listSelectionListener - Variable in class javax.swing.plaf.basic.BasicComboPopup
This protected field is implementation specific.
listSelectionListener - Variable in class javax.swing.plaf.basic.BasicListUI
ListSelectionModel - Interface in javax.swing
This interface represents the current state of the selection for any of the components that display a list of values with stable indices.
listSelectionModel - Variable in class javax.swing.tree.DefaultTreeSelectionModel
Handles maintaining the list selection model.
ListUI - Class in javax.swing.plaf
The JList pluggable look and feel delegate.
ListUI() - Constructor for class javax.swing.plaf.ListUI
ListView - Class in javax.swing.text.html
A view implementation to display an html list
ListView(Element) - Constructor for class javax.swing.text.html.ListView
Creates a new view that represents a list element.
listViewIcon - Variable in class javax.swing.plaf.basic.BasicFileChooserUI
LISU - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Lisu" Unicode character block.
LITERAL - Static variable in class java.util.regex.Pattern
Enables literal parsing of the pattern.
LITTLE_ENDIAN - Static variable in class java.nio.ByteOrder
Constant denoting little-endian byte order.
LIVE_DRAG_MODE - Static variable in class javax.swing.JDesktopPane
Indicates that the entire contents of the item being dragged should appear inside the desktop pane.
LOAD - Static variable in class java.awt.FileDialog
This constant value indicates that the purpose of the file dialog window is to locate a file from which to read.
load(String) - Method in class java.lang.Runtime
Loads the specified filename as a dynamic library.
load(String) - Static method in class java.lang.System
Loads a code file with the specified filename from the local file system as a dynamic library.
load() - Method in class java.nio.MappedByteBuffer
Loads this buffer's content into physical memory.
load(InputStream, char[]) - Method in class java.security.KeyStore
Loads this KeyStore from the given input stream.
load(KeyStore.LoadStoreParameter) - Method in class java.security.KeyStore
Loads this keystore using the given LoadStoreParameter.
load(InputStream) - Method in class java.security.Provider
Reads a property list (key and element pairs) from the input stream.
load(Reader) - Method in class java.util.Properties
Reads a property list (key and element pairs) from the input character stream in a simple line-oriented format.
load(InputStream) - Method in class java.util.Properties
Reads a property list (key and element pairs) from the input byte stream.
load(Class<S>, ClassLoader) - Static method in class java.util.ServiceLoader
Creates a new service loader for the given service type and class loader.
load(Class<S>) - Static method in class java.util.ServiceLoader
Creates a new service loader for the given service type, using the current thread's context class loader.
load() - Method in class javax.management.modelmbean.RequiredModelMBean
Instantiates this MBean instance with the data found for the MBean in the persistent store.
load() - Method in interface javax.management.PersistentMBean
Instantiates thisMBean instance with the data found for the MBean in the persistent store.
load(InputStream, Class<?>) - Method in class javax.swing.plaf.synth.SynthLookAndFeel
Loads the set of SynthStyles that will be used by this SynthLookAndFeel.
load(URL) - Method in class javax.swing.plaf.synth.SynthLookAndFeel
Loads the set of SynthStyles that will be used by this SynthLookAndFeel.
LOAD_FILE - Static variable in class java.awt.Event
A file loading event.
loadAllInstruments(Soundbank) - Method in interface javax.sound.midi.Synthesizer
Loads onto the Synthesizer all instruments contained in the specified Soundbank.
loadChildren() - Method in class javax.swing.JTree.DynamicUtilTreeNode
Loads the children based on childValue.
loadChildren(ViewFactory) - Method in class javax.swing.text.AsyncBoxView
Loads all of the children to initialize the view.
loadChildren(ViewFactory) - Method in class javax.swing.text.CompositeView
Loads all of the children to initialize the view.
loadChildren(ViewFactory) - Method in class javax.swing.text.FlowView
Loads all of the children to initialize the view.
loadChildren(ViewFactory) - Method in class javax.swing.text.WrappedPlainView
Loads all of the children to initialize the view.
loadChildren(ViewFactory) - Method in class javax.swing.text.ZoneView
Loads all of the children to initialize the view.
loadClass(String) - Method in class java.lang.ClassLoader
Loads the class with the specified binary name.
loadClass(String, boolean) - Method in class java.lang.ClassLoader
Loads the class with the specified binary name.
loadClass(String) - Method in interface java.rmi.server.LoaderHandler
Deprecated.
no replacement
loadClass(URL, String) - Method in interface java.rmi.server.LoaderHandler
Deprecated.
no replacement
loadClass(String) - Static method in class java.rmi.server.RMIClassLoader
Deprecated.
replaced by loadClass(String,String) method
loadClass(URL, String) - Static method in class java.rmi.server.RMIClassLoader
Loads a class from a codebase URL.
loadClass(String, String) - Static method in class java.rmi.server.RMIClassLoader
Loads a class from a codebase URL path.
loadClass(String, String, ClassLoader) - Static method in class java.rmi.server.RMIClassLoader
Loads a class from a codebase URL path, optionally using the supplied loader.
loadClass(String, String, ClassLoader) - Method in class java.rmi.server.RMIClassLoaderSpi
Provides the implementation for
 RMIClassLoader.loadClass(URL,String),
 RMIClassLoader.loadClass(String,String), and
 RMIClassLoader.loadClass(String,String,ClassLoader).
loadClass(String) - Static method in class javax.management.DefaultLoaderRepository
Deprecated.
Go through the list of class loaders and try to load the requested class.
loadClass(String) - Method in interface javax.management.loading.ClassLoaderRepository
Load the given class name through the list of class loaders.
loadClass(String) - Static method in class javax.management.loading.DefaultLoaderRepository
Deprecated.
Go through the list of class loaders and try to load the requested class.
loadClass(String, ClassLoaderRepository) - Method in class javax.management.loading.MLet
Load a class, using the given ClassLoaderRepository if the class is not found in this MLet's URLs.
loadClass(String, String, ClassLoader) - Static method in class javax.rmi.CORBA.Util
Returns a class instance for the specified class.
loadClass(String, String, ClassLoader) - Method in interface javax.rmi.CORBA.UtilDelegate
Delegation call for Util.loadClass(java.lang.String, java.lang.String, java.lang.ClassLoader).
loadClassBefore(ClassLoader, String) - Method in interface javax.management.loading.ClassLoaderRepository
Load the given class name through the list of class loaders, stopping at the given one.
loadClassWithout(ClassLoader, String) - Static method in class javax.management.DefaultLoaderRepository
Deprecated.
Go through the list of class loaders but exclude the given class loader, then try to load the requested class.
loadClassWithout(ClassLoader, String) - Method in interface javax.management.loading.ClassLoaderRepository
Load the given class name through the list of class loaders, excluding the given one.
loadClassWithout(ClassLoader, String) - Static method in class javax.management.loading.DefaultLoaderRepository
Deprecated.
Go through the list of class loaders but exclude the given class loader, then try to load the requested class.
loadedChildren - Variable in class javax.swing.JTree.DynamicUtilTreeNode
Have the children been loaded yet?
LoaderHandler - Interface in java.rmi.server
Deprecated.
no replacement
loadFromXML(InputStream) - Method in class java.util.Properties
Loads all of the properties represented by the XML document on the specified input stream into this properties table.
loadImage(String) - Method in class java.beans.SimpleBeanInfo
This is a utility method to help in loading icon images.
loadImage(Image) - Method in class javax.swing.ImageIcon
Loads the image, returning only when the image is loaded.
LOADING - Static variable in class java.awt.MediaTracker
Flag indicating that media is currently being loaded.
loadInstalled(Class<S>) - Static method in class java.util.ServiceLoader
Creates a new service loader for the given service type, using the extension class loader.
loadInstrument(Instrument) - Method in interface javax.sound.midi.Synthesizer
Makes a particular instrument available for synthesis.
loadInstruments(Soundbank, Patch[]) - Method in interface javax.sound.midi.Synthesizer
Loads the instruments referenced by the specified patches, from the specified Soundbank.
loadKeyBindings(InputMap, Object[]) - Static method in class javax.swing.LookAndFeel
Populates an InputMap with the specified bindings.
loadKeymap(Keymap, JTextComponent.KeyBinding[], Action[]) - Static method in class javax.swing.text.JTextComponent
Loads a keymap with a bunch of bindings.
loadLibrary(String) - Method in class java.lang.Runtime
Loads the dynamic library with the specified library name.
loadLibrary(String) - Static method in class java.lang.System
Loads the system library specified by the libname argument.
loadProxyClass(String, String[], ClassLoader) - Static method in class java.rmi.server.RMIClassLoader
Loads a dynamic proxy class (see Proxy) that implements a set of interfaces with the given names from a codebase URL path.
loadProxyClass(String, String[], ClassLoader) - Method in class java.rmi.server.RMIClassLoaderSpi
Provides the implementation for RMIClassLoader.loadProxyClass(String,String[],ClassLoader).
loadRules(Reader, URL) - Method in class javax.swing.text.html.StyleSheet
Loads a set of rules that have been specified in terms of CSS1 grammar.
loadSystemColors(int[]) - Method in class java.awt.Toolkit
Fills in the integer array that is supplied as an argument with the current system color values.
loadSystemColors(UIDefaults, String[], boolean) - Method in class javax.swing.plaf.basic.BasicLookAndFeel
Populates table with the name-color pairs in systemColors.
localControl(boolean) - Method in interface javax.sound.midi.MidiChannel
Turns local control on or off.
locale - Variable in class java.beans.beancontext.BeanContextSupport
The current locale of this BeanContext.
locale() - Method in class java.util.Formatter
Returns the locale set by the construction of this formatter.
Locale - Class in java.util
A Locale object represents a specific geographical, political, or cultural region.
Locale(String, String, String) - Constructor for class java.util.Locale
Construct a locale from language, country and variant.
Locale(String, String) - Constructor for class java.util.Locale
Construct a locale from language and country.
Locale(String) - Constructor for class java.util.Locale
Construct a locale from a language code.
locale() - Method in class java.util.Scanner
Returns this scanner's locale.
locale - Variable in class javax.imageio.ImageReader
The current Locale to be used for localization, or null if none has been set.
locale - Variable in class javax.imageio.ImageWriteParam
A Locale to be used to localize compression type names and quality descriptions, or null to use a default Locale.
locale - Variable in class javax.imageio.ImageWriter
The current Locale to be used for localization, or null if none has been set.
Locale.Builder - Class in java.util
Builder is used to build instances of Locale from values configured by the setters.
Locale.Builder() - Constructor for class java.util.Locale.Builder
Constructs an empty Builder.
Locale.Category - Enum in java.util
Enum for locale categories.
LocaleNameProvider - Class in java.util.spi
An abstract class for service providers that provide localized names for the Locale class.
LocaleNameProvider() - Constructor for class java.util.spi.LocaleNameProvider
Sole constructor.
LocaleServiceProvider - Class in java.util.spi
This is the super class of all the locale sensitive service provider interfaces (SPIs).
LocaleServiceProvider() - Constructor for class java.util.spi.LocaleServiceProvider
Sole constructor.
LocalObject - Class in org.omg.CORBA
Used as a base class for implementation of a local IDL interface in the Java language mapping.
LocalObject() - Constructor for class org.omg.CORBA.LocalObject
Constructs a default LocalObject instance.
localPort - Variable in class java.net.DatagramSocketImpl
The local port number.
localport - Variable in class java.net.SocketImpl
The local port number to which this socket is connected.
locate(int, int) - Method in class java.awt.Component
Deprecated.
As of JDK version 1.1, replaced by getComponentAt(int, int).
locate(int, int) - Method in class java.awt.Container
Deprecated.
As of JDK version 1.1, replaced by getComponentAt(int, int).
LocateRegistry - Class in java.rmi.registry
LocateRegistry is used to obtain a reference to a bootstrap remote object registry on a particular host (including the local host), or to create a remote object registry that accepts calls on a specific port.
location() - Method in class java.awt.Component
Deprecated.
As of JDK version 1.1, replaced by getLocation().
location(int, int) - Method in class java.awt.GridBagLayout
Determines which cell in the layout grid contains the point specified by (x, y).
Location - Interface in javax.xml.stream
Provides information on the location of an event.
location - Variable in exception javax.xml.stream.XMLStreamException
LOCATION_FORWARD - Interface in org.omg.PortableInterceptor
org/omg/PortableInterceptor/LOCATION_FORWARD.java .
locationFor(String) - Static method in enum javax.tools.StandardLocation
Gets a location object with the given name.
locationToIndex(Point) - Method in class javax.swing.JList
Returns the cell index closest to the given location in the list's coordinate system.
locationToIndex(JList, Point) - Method in class javax.swing.plaf.basic.BasicListUI
Returns the cell index in the specified JList closest to the given location in the list's coordinate system.
locationToIndex(JList, Point) - Method in class javax.swing.plaf.ListUI
Returns the cell index in the specified JList closest to the given location in the list's coordinate system.
locationToIndex(JList, Point) - Method in class javax.swing.plaf.multi.MultiListUI
Invokes the locationToIndex method on each UI handled by this object.
locator - Variable in class javax.swing.text.AsyncBoxView
Object that manages the offsets of the children.
Locator - Interface in org.xml.sax
Interface for associating a SAX event with a document location.
Locator2 - Interface in org.xml.sax.ext
SAX2 extension to augment the entity information provided though a Locator.
Locator2Impl - Class in org.xml.sax.ext
SAX2 extension helper for holding additional Entity information, implementing the Locator2 interface.
Locator2Impl() - Constructor for class org.xml.sax.ext.Locator2Impl
Construct a new, empty Locator2Impl object.
Locator2Impl(Locator) - Constructor for class org.xml.sax.ext.Locator2Impl
Copy an existing Locator or Locator2 object.
LocatorImpl - Class in org.xml.sax.helpers
Provide an optional convenience implementation of Locator.
LocatorImpl() - Constructor for class org.xml.sax.helpers.LocatorImpl
Zero-argument constructor.
LocatorImpl(Locator) - Constructor for class org.xml.sax.helpers.LocatorImpl
Copy constructor.
locatorsUpdateCopy() - Method in interface java.sql.DatabaseMetaData
Indicates whether updates made to a LOB are made on a copy or directly to the LOB.
lock - Variable in class java.io.Reader
The object used to synchronize operations on this stream.
lock - Variable in class java.io.Writer
The object used to synchronize operations on this stream.
lock(long, long, boolean, A, CompletionHandler<FileLock, ? super A>) - Method in class java.nio.channels.AsynchronousFileChannel
Acquires a lock on the given region of this channel's file.
lock(A, CompletionHandler<FileLock, ? super A>) - Method in class java.nio.channels.AsynchronousFileChannel
Acquires an exclusive lock on this channel's file.
lock(long, long, boolean) - Method in class java.nio.channels.AsynchronousFileChannel
Acquires a lock on the given region of this channel's file.
lock() - Method in class java.nio.channels.AsynchronousFileChannel
Acquires an exclusive lock on this channel's file.
lock(long, long, boolean) - Method in class java.nio.channels.FileChannel
Acquires a lock on the given region of this channel's file.
lock() - Method in class java.nio.channels.FileChannel
Acquires an exclusive lock on this channel's file.
Lock - Interface in java.util.concurrent.locks
Lock implementations provide more extensive locking operations than can be obtained using synchronized methods and statements.
lock() - Method in interface java.util.concurrent.locks.Lock
Acquires the lock.
lock() - Method in class java.util.concurrent.locks.ReentrantLock
Acquires the lock.
lock() - Method in class java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock
Acquires the read lock.
lock() - Method in class java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock
Acquires the write lock.
lock - Variable in class java.util.prefs.AbstractPreferences
An object whose monitor is used to lock this node.
LockInfo - Class in java.lang.management
Information about a lock.
LockInfo(String, int) - Constructor for class java.lang.management.LockInfo
Constructs a LockInfo object.
lockInterruptibly() - Method in interface java.util.concurrent.locks.Lock
Acquires the lock unless the current thread is interrupted.
lockInterruptibly() - Method in class java.util.concurrent.locks.ReentrantLock
Acquires the lock unless the current thread is interrupted.
lockInterruptibly() - Method in class java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock
Acquires the read lock unless the current thread is interrupted.
lockInterruptibly() - Method in class java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock
Acquires the write lock unless the current thread is interrupted.
LockSupport - Class in java.util.concurrent.locks
Basic thread blocking primitives for creating locks and other synchronization classes.
log(double) - Static method in class java.lang.Math
Returns the natural logarithm (base e) of a double value.
log(double) - Static method in class java.lang.StrictMath
Returns the natural logarithm (base e) of a double value.
log(String) - Static method in class java.rmi.server.LogStream
Deprecated.
no replacement
log(LogRecord) - Method in class java.util.logging.Logger
Log a LogRecord.
log(Level, String) - Method in class java.util.logging.Logger
Log a message, with no arguments.
log(Level, String, Object) - Method in class java.util.logging.Logger
Log a message, with one object parameter.
log(Level, String, Object[]) - Method in class java.util.logging.Logger
Log a message, with an array of object arguments.
log(Level, String, Throwable) - Method in class java.util.logging.Logger
Log a message, with associated Throwable information.
log10(double) - Static method in class java.lang.Math
Returns the base 10 logarithm of a double value.
log10(double) - Static method in class java.lang.StrictMath
Returns the base 10 logarithm of a double value.
log1p(double) - Static method in class java.lang.Math
Returns the natural logarithm of the sum of the argument and 1.
log1p(double) - Static method in class java.lang.StrictMath
Returns the natural logarithm of the sum of the argument and 1.
LOG_OPTION - Static variable in class javax.swing.DebugGraphics
Log graphics operations.
Logger - Class in java.util.logging
A Logger object is used to log messages for a specific system or application component.
Logger(String, String) - Constructor for class java.util.logging.Logger
Protected method to construct a logger for a named subsystem.
LOGGING_MXBEAN_NAME - Static variable in class java.util.logging.LogManager
String representation of the ObjectName for the management interface for the logging facility.
LoggingMXBean - Interface in java.util.logging
The management interface for the logging facility.
LoggingPermission - Class in java.util.logging
The permission which the SecurityManager will check when code that is running with a SecurityManager calls one of the logging control methods (such as Logger.setLevel).
LoggingPermission(String, String) - Constructor for class java.util.logging.LoggingPermission
Creates a new LoggingPermission object.
LOGICAL_STYLE_ACTION - Static variable in class javax.swing.text.html.HTMLEditorKit
The logical style choice action identifier The logical style is passed in as an argument
LogicalHandler<C extends LogicalMessageContext> - Interface in javax.xml.ws.handler
The LogicalHandler extends Handler to provide typesafety for the message context parameter.
LogicalMessage - Interface in javax.xml.ws
The LogicalMessage interface represents a protocol agnostic XML message and contains methods that provide access to the payload of the message.
LogicalMessageContext - Interface in javax.xml.ws.handler
The LogicalMessageContext interface extends MessageContext to provide access to a the contained message as a protocol neutral LogicalMessage
login(Subject, CallbackHandler) - Method in class java.security.AuthProvider
Log in to this provider.
login() - Method in class javax.security.auth.login.LoginContext
Perform the authentication.
login() - Method in interface javax.security.auth.spi.LoginModule
Method to authenticate a Subject (phase 1).
LoginContext - Class in javax.security.auth.login
The LoginContext class describes the basic methods used to authenticate Subjects and provides a way to develop an application independent of the underlying authentication technology.
LoginContext(String) - Constructor for class javax.security.auth.login.LoginContext
Instantiate a new LoginContext object with a name.
LoginContext(String, Subject) - Constructor for class javax.security.auth.login.LoginContext
Instantiate a new LoginContext object with a name and a Subject object.
LoginContext(String, CallbackHandler) - Constructor for class javax.security.auth.login.LoginContext
Instantiate a new LoginContext object with a name and a CallbackHandler object.
LoginContext(String, Subject, CallbackHandler) - Constructor for class javax.security.auth.login.LoginContext
Instantiate a new LoginContext object with a name, a Subject to be authenticated, and a CallbackHandler object.
LoginContext(String, Subject, CallbackHandler, Configuration) - Constructor for class javax.security.auth.login.LoginContext
Instantiate a new LoginContext object with a name, a Subject to be authenticated, a CallbackHandler object, and a login Configuration.
LoginException - Exception in javax.security.auth.login
This is the basic login exception.
LoginException() - Constructor for exception javax.security.auth.login.LoginException
Constructs a LoginException with no detail message.
LoginException(String) - Constructor for exception javax.security.auth.login.LoginException
Constructs a LoginException with the specified detail message.
LoginModule - Interface in javax.security.auth.spi
LoginModule describes the interface implemented by authentication technology providers.
LogManager - Class in java.util.logging
There is a single global LogManager object that is used to maintain a set of shared state about Loggers and log services.
LogManager() - Constructor for class java.util.logging.LogManager
Protected constructor.
logout() - Method in class java.security.AuthProvider
Log out from this provider.
logout() - Method in class javax.security.auth.login.LoginContext
Logout the Subject.
logout() - Method in interface javax.security.auth.spi.LoginModule
Method which logs out a Subject.
logp(Level, String, String, String) - Method in class java.util.logging.Logger
Log a message, specifying source class and method, with no arguments.
logp(Level, String, String, String, Object) - Method in class java.util.logging.Logger
Log a message, specifying source class and method, with a single object parameter to the log message.
logp(Level, String, String, String, Object[]) - Method in class java.util.logging.Logger
Log a message, specifying source class and method, with an array of object arguments.
logp(Level, String, String, String, Throwable) - Method in class java.util.logging.Logger
Log a message, specifying source class and method, with associated Throwable information.
logrb(Level, String, String, String, String) - Method in class java.util.logging.Logger
Log a message, specifying source class, method, and resource bundle name with no arguments.
logrb(Level, String, String, String, String, Object) - Method in class java.util.logging.Logger
Log a message, specifying source class, method, and resource bundle name, with a single object parameter to the log message.
logrb(Level, String, String, String, String, Object[]) - Method in class java.util.logging.Logger
Log a message, specifying source class, method, and resource bundle name, with an array of object arguments.
logrb(Level, String, String, String, String, Throwable) - Method in class java.util.logging.Logger
Log a message, specifying source class, method, and resource bundle name, with associated Throwable information.
LogRecord - Class in java.util.logging
LogRecord objects are used to pass logging requests between the logging framework and individual log Handlers.
LogRecord(Level, String) - Constructor for class java.util.logging.LogRecord
Construct a LogRecord with the given level and message values.
LogStream - Class in java.rmi.server
Deprecated.
no replacement
logStream() - Static method in class javax.swing.DebugGraphics
Returns the stream to which the DebugGraphics logs drawing operations.
Long - Class in java.lang
The Long class wraps a value of the primitive type long in an object.
Long(long) - Constructor for class java.lang.Long
Constructs a newly allocated Long object that represents the specified long argument.
Long(String) - Constructor for class java.lang.Long
Constructs a newly allocated Long object that represents the long value indicated by the String parameter.
LONG - Static variable in class java.text.DateFormat
Constant for long style pattern.
LONG - Static variable in class java.util.Calendar
A style specifier for getDisplayName and getDisplayNames indicating a long name, such as "January".
LONG - Static variable in class java.util.TimeZone
A style specifier for getDisplayName() indicating a long name, such as "Pacific Standard Time."
LONG - Static variable in class javax.management.openmbean.SimpleType
The SimpleType instance describing values whose Java class name is java.lang.Long.
LONG_DESCRIPTION - Static variable in interface javax.swing.Action
The key used for storing a longer String description for the action, could be used for context-sensitive help.
longBitsToDouble(long) - Static method in class java.lang.Double
Returns the double value corresponding to a given bit representation.
LongBuffer - Class in java.nio
A long buffer.
LongHolder - Class in org.omg.CORBA
The Holder for Long.
LongHolder() - Constructor for class org.omg.CORBA.LongHolder
Constructs a new LongHolder object with its value field initialized to 0.
LongHolder(long) - Constructor for class org.omg.CORBA.LongHolder
Constructs a new LongHolder object with its value field initialized to the given long.
LongLongSeqHelper - Class in org.omg.CORBA
The Helper for LongLongSeq.
LongLongSeqHelper() - Constructor for class org.omg.CORBA.LongLongSeqHelper
LongLongSeqHolder - Class in org.omg.CORBA
The Holder for LongLongSeq.
LongLongSeqHolder() - Constructor for class org.omg.CORBA.LongLongSeqHolder
LongLongSeqHolder(long[]) - Constructor for class org.omg.CORBA.LongLongSeqHolder
LONGNVARCHAR - Static variable in class java.sql.Types
The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type LONGNVARCHAR.
LongSeqHelper - Class in org.omg.CORBA
The Helper for LongSeqHelper.
LongSeqHelper() - Constructor for class org.omg.CORBA.LongSeqHelper
LongSeqHolder - Class in org.omg.CORBA
The Holder for LongSeq.
LongSeqHolder() - Constructor for class org.omg.CORBA.LongSeqHolder
LongSeqHolder(int[]) - Constructor for class org.omg.CORBA.LongSeqHolder
longValue() - Method in class java.lang.Byte
Returns the value of this Byte as a long.
longValue() - Method in class java.lang.Double
Returns the value of this Double as a long (by casting to type long).
longValue() - Method in class java.lang.Float
Returns value of this Float as a long (by casting to type long).
longValue() - Method in class java.lang.Integer
Returns the value of this Integer as a long.
longValue() - Method in class java.lang.Long
Returns the value of this Long as a long value.
longValue() - Method in class java.lang.Number
Returns the value of the specified number as a long.
longValue() - Method in class java.lang.Short
Returns the value of this Short as a long.
longValue() - Method in class java.math.BigDecimal
Converts this BigDecimal to a long.
longValue() - Method in class java.math.BigInteger
Converts this BigInteger to a long.
longValue() - Method in class java.util.concurrent.atomic.AtomicInteger
longValue() - Method in class java.util.concurrent.atomic.AtomicLong
longValueExact() - Method in class java.math.BigDecimal
Converts this BigDecimal to a long, checking for lost information.
LONGVARBINARY - Static variable in class java.sql.Types
The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type LONGVARBINARY.
LONGVARCHAR - Static variable in class java.sql.Types
The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type LONGVARCHAR.
LookAndFeel - Class in javax.swing
LookAndFeel, as the name implies, encapsulates a look and feel.
LookAndFeel() - Constructor for class javax.swing.LookAndFeel
lookingAt() - Method in class java.util.regex.Matcher
Attempts to match the input sequence, starting at the beginning of the region, against the pattern.
lookup(Class<?>) - Static method in class java.io.ObjectStreamClass
Find the descriptor for a class that can be serialized.
lookup() - Static method in class java.lang.invoke.MethodHandles
Returns a lookup object on the caller, which has the capability to access any method handle that the caller has access to, including direct method handles to private fields and methods.
lookup(String) - Static method in class java.rmi.Naming
Returns a reference, a stub, for the remote object associated with the specified name.
lookup(String) - Method in interface java.rmi.registry.Registry
Returns the remote reference bound to the specified name in this registry.
lookup(Name) - Method in interface javax.naming.Context
Retrieves the named object.
lookup(String) - Method in interface javax.naming.Context
Retrieves the named object.
lookup(String) - Method in class javax.naming.InitialContext
lookup(Name) - Method in class javax.naming.InitialContext
lookup_value_factory(String) - Method in class org.omg.CORBA_2_3.ORB
lookupAny(Class<?>) - Static method in class java.io.ObjectStreamClass
Returns the descriptor for any class, regardless of whether it implements Serializable.
lookupClass() - Method in class java.lang.invoke.MethodHandles.Lookup
Tells which class is performing the lookup.
lookupConstraints(Component) - Method in class java.awt.GridBagLayout
Retrieves the constraints for the specified component.
lookupDefaultPrintService() - Static method in class javax.print.PrintServiceLookup
Locates the default print service for this environment.
lookupLink(Name) - Method in interface javax.naming.Context
Retrieves the named object, following links except for the terminal atomic component of the name.
lookupLink(String) - Method in interface javax.naming.Context
Retrieves the named object, following links except for the terminal atomic component of the name.
lookupLink(String) - Method in class javax.naming.InitialContext
lookupLink(Name) - Method in class javax.naming.InitialContext
lookupModes() - Method in class java.lang.invoke.MethodHandles.Lookup
Tells which access-protection classes of members this lookup object can produce.
lookupMultiDocPrintServices(DocFlavor[], AttributeSet) - Static method in class javax.print.PrintServiceLookup
Locates MultiDoc print Services capable of printing MultiDocs containing all the specified doc flavors.
lookupNamespaceURI(String) - Method in class javax.imageio.metadata.IIOMetadataNode
This DOM Level 3 method is not supported for IIOMetadataNode and will throw a DOMException.
lookupNamespaceURI(String) - Method in interface org.w3c.dom.Node
Look up the namespace URI associated to the given prefix, starting from this node.
LookupOp - Class in java.awt.image
This class implements a lookup operation from the source to the destination.
LookupOp(LookupTable, RenderingHints) - Constructor for class java.awt.image.LookupOp
Constructs a LookupOp object given the lookup table and a RenderingHints object, which might be null.
lookupPixel(int[], int[]) - Method in class java.awt.image.ByteLookupTable
Returns an array of samples of a pixel, translated with the lookup table.
lookupPixel(byte[], byte[]) - Method in class java.awt.image.ByteLookupTable
Returns an array of samples of a pixel, translated with the lookup table.
lookupPixel(int[], int[]) - Method in class java.awt.image.LookupTable
Returns an int array of components for one pixel.
lookupPixel(int[], int[]) - Method in class java.awt.image.ShortLookupTable
Returns an array of samples of a pixel, translated with the lookup table.
lookupPixel(short[], short[]) - Method in class java.awt.image.ShortLookupTable
Returns an array of samples of a pixel, translated with the lookup table.
lookupPrefix(String) - Method in class javax.imageio.metadata.IIOMetadataNode
This DOM Level 3 method is not supported for IIOMetadataNode and will throw a DOMException.
lookupPrefix(String) - Method in interface org.w3c.dom.Node
Look up the prefix associated to the given namespace URI, starting from this node.
lookupPrincipalByGroupName(String) - Method in class java.nio.file.attribute.UserPrincipalLookupService
Lookup a group principal by group name.
lookupPrincipalByName(String) - Method in class java.nio.file.attribute.UserPrincipalLookupService
Lookup a user principal by name.
lookupPrintServices() - Static method in class java.awt.print.PrinterJob
A convenience method which looks up 2D print services.
lookupPrintServices(DocFlavor, AttributeSet) - Static method in class javax.print.PrintServiceLookup
Locates print services capable of printing the specified DocFlavor.
lookupProviders(Class<T>, ClassLoader) - Static method in class javax.imageio.spi.ServiceRegistry
Searches for implementations of a particular service class using the given class loader.
lookupProviders(Class<T>) - Static method in class javax.imageio.spi.ServiceRegistry
Locates and incrementally instantiates the available providers of a given service using the context class loader.
lookupStreamPrintServiceFactories(DocFlavor, String) - Static method in class javax.print.StreamPrintServiceFactory
Locates factories for print services that can be used with a print job to output a stream of data in the format specified by outputMimeType.
lookupStreamPrintServices(String) - Static method in class java.awt.print.PrinterJob
A convenience method which locates factories for stream print services which can image 2D graphics.
LookupTable - Class in java.awt.image
This abstract class defines a lookup table object.
LookupTable(int, int) - Constructor for class java.awt.image.LookupTable
Constructs a new LookupTable from the number of components and an offset into the lookup table.
loop() - Method in interface java.applet.AudioClip
Starts playing this audio clip in a loop.
loop(int) - Method in interface javax.sound.sampled.Clip
Starts looping playback from the current position.
LOOP_CONTINUOUSLY - Static variable in interface javax.sound.midi.Sequencer
A value indicating that looping should continue indefinitely rather than complete after a specific number of loops.
LOOP_CONTINUOUSLY - Static variable in interface javax.sound.sampled.Clip
A value indicating that looping should continue indefinitely rather than complete after a specific number of loops.
LOST_FOCUS - Static variable in class java.awt.Event
A component lost the focus.
lostFocus(Event, Object) - Method in class java.awt.Component
Deprecated.
As of JDK version 1.1, replaced by processFocusEvent(FocusEvent).
lostOwnership(Clipboard, Transferable) - Method in interface java.awt.datatransfer.ClipboardOwner
Notifies this object that it is no longer the clipboard owner.
lostOwnership(Clipboard, Transferable) - Method in class java.awt.datatransfer.StringSelection
LOW_SURROGATES - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Low Surrogates" Unicode character block.
lower(E) - Method in class java.util.concurrent.ConcurrentSkipListSet
lower(E) - Method in interface java.util.NavigableSet
Returns the greatest element in this set strictly less than the given element, or null if there is no such element.
lower(E) - Method in class java.util.TreeSet
LOWER_LEADING_CORNER - Static variable in interface javax.swing.ScrollPaneConstants
Identifies the lower leading edge corner of the viewport.
LOWER_LEFT_CORNER - Static variable in interface javax.swing.ScrollPaneConstants
Identifies the lower left corner of the viewport.
LOWER_RIGHT_CORNER - Static variable in interface javax.swing.ScrollPaneConstants
Identifies the lower right corner of the viewport.
LOWER_TRAILING_CORNER - Static variable in interface javax.swing.ScrollPaneConstants
Identifies the lower trailing edge corner of the viewport.
LOWERCASE_LETTER - Static variable in class java.lang.Character
General category "Ll" in the Unicode specification.
lowerCaseMode(boolean) - Method in class java.io.StreamTokenizer
Determines whether or not word token are automatically lowercased.
LOWERED - Static variable in class javax.swing.border.BevelBorder
Lowered bevel type.
LOWERED - Static variable in class javax.swing.border.EtchedBorder
Lowered etched type.
lowerEntry(K) - Method in class java.util.concurrent.ConcurrentSkipListMap
Returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key.
lowerEntry(K) - Method in interface java.util.NavigableMap
Returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key.
lowerEntry(K) - Method in class java.util.TreeMap
lowerKey(K) - Method in class java.util.concurrent.ConcurrentSkipListMap
lowerKey(K) - Method in interface java.util.NavigableMap
Returns the greatest key strictly less than the given key, or null if there is no such key.
lowerKey(K) - Method in class java.util.TreeMap
lowerLeft - Variable in class javax.swing.JScrollPane
The component to display in the lower left corner.
lowerLeft - Variable in class javax.swing.ScrollPaneLayout
The component to display in the lower left corner.
lowerRight - Variable in class javax.swing.JScrollPane
The component to display in the lower right corner.
lowerRight - Variable in class javax.swing.ScrollPaneLayout
The component to display in the lower right corner.
lowestLayer() - Method in class javax.swing.JLayeredPane
Returns the lowest layer value from all current children.
lowestOneBit(int) - Static method in class java.lang.Integer
Returns an int value with at most a single one-bit, in the position of the lowest-order ("rightmost") one-bit in the specified int value.
lowestOneBit(long) - Static method in class java.lang.Long
Returns a long value with at most a single one-bit, in the position of the lowest-order ("rightmost") one-bit in the specified long value.
LOWSRC - Static variable in class javax.swing.text.html.HTML.Attribute
lowSurrogate(int) - Static method in class java.lang.Character
Returns the trailing surrogate (a low surrogate code unit) of the surrogate pair representing the specified supplementary character (Unicode code point) in the UTF-16 encoding.
LSException - Exception in org.w3c.dom.ls
Parser or write operations may throw an LSException if the processing is stopped.
LSException(short, String) - Constructor for exception org.w3c.dom.ls.LSException
LSInput - Interface in org.w3c.dom.ls
This interface represents an input source for data.
LSLoadEvent - Interface in org.w3c.dom.ls
This interface represents a load event object that signals the completion of a document load.
LSOutput - Interface in org.w3c.dom.ls
This interface represents an output destination for data.
LSParser - Interface in org.w3c.dom.ls
An interface to an object that is able to build, or augment, a DOM tree from various input sources.
LSParserFilter - Interface in org.w3c.dom.ls
LSParserFilters provide applications the ability to examine nodes as they are being constructed while parsing.
LSProgressEvent - Interface in org.w3c.dom.ls
This interface represents a progress event object that notifies the application about progress as a document is parsed.
LSResourceResolver - Interface in org.w3c.dom.ls
LSResourceResolver provides a way for applications to redirect references to external resources.
LSSerializer - Interface in org.w3c.dom.ls
A LSSerializer provides an API for serializing (writing) a DOM document out into XML.
LSSerializerFilter - Interface in org.w3c.dom.ls
LSSerializerFilters provide applications the ability to examine nodes as they are being serialized and decide what nodes should be serialized or not.
LT - Static variable in class javax.management.Query
A code representing the Query.lt(javax.management.ValueExp, javax.management.ValueExp) query.
lt(ValueExp, ValueExp) - Static method in class javax.management.Query
Returns a query expression that represents a "less than" constraint on two values.
lt(File, File) - Method in class javax.swing.plaf.basic.BasicDirectoryModel
LYCIAN - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Lycian" Unicode character block.
LYDIAN - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Lydian" Unicode character block.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类


M-Index

请注意：本 java api 1.7Beta 规范不是最终稳定版，未来随着版本的更迭，本规范可能有更新。
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _

M

Mac - Class in javax.crypto
This class provides the functionality of a "Message Authentication Code" (MAC) algorithm.
Mac(MacSpi, Provider, String) - Constructor for class javax.crypto.Mac
Creates a MAC object.
MacSpi - Class in javax.crypto
This class defines the Service Provider Interface (SPI) for the Mac class.
MacSpi() - Constructor for class javax.crypto.MacSpi
magenta - Static variable in class java.awt.Color
The color magenta.
MAGENTA - Static variable in class java.awt.Color
The color magenta.
MAHJONG_TILES - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Mahjong Tiles" Unicode character block.
mail() - Method in class java.awt.Desktop
Launches the mail composing window of the user default mail client.
mail(URI) - Method in class java.awt.Desktop
Launches the mail composing window of the user default mail client, filling the message fields specified by a mailto: URI.
MailcapCommandMap - Class in javax.activation
MailcapCommandMap extends the CommandMap abstract class.
MailcapCommandMap() - Constructor for class javax.activation.MailcapCommandMap
The default Constructor.
MailcapCommandMap(String) - Constructor for class javax.activation.MailcapCommandMap
Constructor that allows the caller to specify the path of a mailcap file.
MailcapCommandMap(InputStream) - Constructor for class javax.activation.MailcapCommandMap
Constructor that allows the caller to specify an InputStream containing a mailcap file.
MAIN - Static variable in class javax.print.attribute.standard.MediaTray
The main input tray in the printer.
MAIN_CLASS - Static variable in class java.util.jar.Attributes.Name
Name object for Main-Class manifest attribute used for launching applications packaged in JAR files.
MAIN_UIROLE - Static variable in class javax.print.ServiceUIFactory
Denotes a UI which performs the normal end user role.
major_version - Variable in class org.omg.IOP.Encoding
The major version of this Encoding format.
majorRequirementChange(AsyncBoxView.ChildState, float) - Method in class javax.swing.text.AsyncBoxView
Requirements changed along the major axis.
majorTickSpacing - Variable in class javax.swing.JSlider
The number of values between the major tick marks -- the larger marks that break up the minor tick marks.
make_object(String, byte[]) - Method in interface org.omg.PortableInterceptor.ObjectReferenceFactory
make_object creates a CORBA object reference according to the data in this template, with the given repository ID and object ID.
makeBounds(double, double, double, double) - Method in class java.awt.geom.Arc2D.Double
Constructs a Rectangle2D of the appropriate precision to hold the parameters calculated to be the framing rectangle of this arc.
makeBounds(double, double, double, double) - Method in class java.awt.geom.Arc2D.Float
Constructs a Rectangle2D of the appropriate precision to hold the parameters calculated to be the framing rectangle of this arc.
makeBounds(double, double, double, double) - Method in class java.awt.geom.Arc2D
Constructs a Rectangle2D of the appropriate precision to hold the parameters calculated to be the framing rectangle of this arc.
makeClient(String, Subject) - Method in class javax.management.remote.rmi.RMIIIOPServerImpl
Creates a new client connection as an RMI object exported through IIOP.
makeClient(String, Subject) - Method in class javax.management.remote.rmi.RMIJRMPServerImpl
Creates a new client connection as an RMI object exported through JRMP.
makeClient(String, Subject) - Method in class javax.management.remote.rmi.RMIServerImpl
Creates a new client connection.
makeComponentInputMap(JComponent, Object[]) - Static method in class javax.swing.LookAndFeel
Creates a ComponentInputMapUIResource from keys.
makeIcon(Class<?>, String) - Static method in class javax.swing.LookAndFeel
Creates and returns a UIDefault.LazyValue that loads an image.
makeInputMap(Object[]) - Static method in class javax.swing.LookAndFeel
Creates a InputMapUIResource from keys.
makeKeyBindings(Object[]) - Static method in class javax.swing.LookAndFeel
Convenience method for building an array of KeyBindings.
makeParser() - Static method in class org.xml.sax.helpers.ParserFactory
Deprecated.
Create a new SAX parser using the `org.xml.sax.parser' system property.
makeParser(String) - Static method in class org.xml.sax.helpers.ParserFactory
Deprecated.
Create a new SAX parser object using the class name provided.
makeTag(Element, boolean) - Method in class javax.swing.text.html.parser.Parser
Makes a TagElement.
makeTag(Element) - Method in class javax.swing.text.html.parser.Parser
makeVisible(int) - Method in class java.awt.List
Makes the item at the specified index visible.
makeVisible(TreePath) - Method in class javax.swing.JTree
Ensures that the node identified by path is currently viewable.
MALAYALAM - Static variable in class java.awt.font.NumericShaper
Identifies the MALAYALAM range and decimal base.
MALAYALAM - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Malayalam" Unicode character block.
malformedForLength(int) - Static method in class java.nio.charset.CoderResult
Static factory method that returns the unique object describing a malformed-input error of the given length.
malformedInputAction() - Method in class java.nio.charset.CharsetDecoder
Returns this decoder's current action for malformed-input errors.
malformedInputAction() - Method in class java.nio.charset.CharsetEncoder
Returns this encoder's current action for malformed-input errors.
MalformedInputException - Exception in java.nio.charset
Checked exception thrown when an input byte sequence is not legal for given charset, or an input character sequence is not a legal sixteen-bit Unicode sequence.
MalformedInputException(int) - Constructor for exception java.nio.charset.MalformedInputException
MalformedLinkException - Exception in javax.naming
This exception is thrown when a malformed link was encountered while resolving or constructing a link.
MalformedLinkException(String) - Constructor for exception javax.naming.MalformedLinkException
Constructs a new instance of MalformedLinkException with an explanation All the other fields are initialized to null.
MalformedLinkException() - Constructor for exception javax.naming.MalformedLinkException
Constructs a new instance of Malformed LinkException.
MalformedObjectNameException - Exception in javax.management
The format of the string does not correspond to a valid ObjectName.
MalformedObjectNameException() - Constructor for exception javax.management.MalformedObjectNameException
Default constructor.
MalformedObjectNameException(String) - Constructor for exception javax.management.MalformedObjectNameException
Constructor that allows a specific error message to be specified.
MalformedParameterizedTypeException - Exception in java.lang.reflect
Thrown when a semantically malformed parameterized type is encountered by a reflective method that needs to instantiate it.
MalformedParameterizedTypeException() - Constructor for exception java.lang.reflect.MalformedParameterizedTypeException
MalformedURLException - Exception in java.net
Thrown to indicate that a malformed URL has occurred.
MalformedURLException() - Constructor for exception java.net.MalformedURLException
Constructs a MalformedURLException with no detail message.
MalformedURLException(String) - Constructor for exception java.net.MalformedURLException
Constructs a MalformedURLException with the specified detail message.
managedBlock(ForkJoinPool.ManagedBlocker) - Static method in class java.util.concurrent.ForkJoinPool
Blocks in accord with the given blocker.
ManagementFactory - Class in java.lang.management
The ManagementFactory class is a factory class for getting managed beans for the Java platform.
ManagementPermission - Class in java.lang.management
The permission which the SecurityManager will check when code that is running with a SecurityManager calls methods defined in the management interface for the Java platform.
ManagementPermission(String) - Constructor for class java.lang.management.ManagementPermission
Constructs a ManagementPermission with the specified name.
ManagementPermission(String, String) - Constructor for class java.lang.management.ManagementPermission
Constructs a new ManagementPermission object.
manager_id() - Method in interface org.omg.PortableInterceptor.IORInfoOperations
Return the adapter manager id of the object adapter that was just created and is running IOR interceptors.
ManageReferralControl - Class in javax.naming.ldap
Requests that referral and other special LDAP objects be manipulated as normal LDAP objects.
ManageReferralControl() - Constructor for class javax.naming.ldap.ManageReferralControl
Constructs a critical ManageReferral control.
ManageReferralControl(boolean) - Constructor for class javax.naming.ldap.ManageReferralControl
Constructs a ManageReferral control.
ManagerFactoryParameters - Interface in javax.net.ssl
This class is the base interface for providing algorithm-specific information to a KeyManagerFactory or TrustManagerFactory.
MANAGES_DESCENDANTS - Static variable in class javax.accessibility.AccessibleState
Indicates this object is responsible for managing its subcomponents.
MANDAIC - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Mandaic" Unicode character block.
Manifest - Class in java.util.jar
The Manifest class is used to maintain Manifest entry names and their associated Attributes.
Manifest() - Constructor for class java.util.jar.Manifest
Constructs a new, empty Manifest.
Manifest(InputStream) - Constructor for class java.util.jar.Manifest
Constructs a new Manifest from the specified input stream.
Manifest(Manifest) - Constructor for class java.util.jar.Manifest
Constructs a new Manifest that is a copy of the specified Manifest.
Manifest - Interface in javax.xml.crypto.dsig
A representation of the XML Manifest element as defined in the W3C Recommendation for XML-Signature Syntax and Processing.
MANIFEST_NAME - Static variable in class java.util.jar.JarFile
The JAR manifest file name.
MANIFEST_VERSION - Static variable in class java.util.jar.Attributes.Name
Name object for Manifest-Version manifest attribute.
MANUAL - Static variable in class javax.print.attribute.standard.MediaTray
The manual feed input tray in the printer.
map(FileChannel.MapMode, long, long) - Method in class java.nio.channels.FileChannel
Maps a region of this channel's file directly into memory.
map - Variable in class java.util.jar.Attributes
The attribute name-value mappings.
Map<K,V> - Interface in java.util
An object that maps keys to values.
MAP - Static variable in class javax.swing.text.html.HTML.Tag
Map.Entry<K,V> - Interface in java.util
A map entry (key-value pair).
mapInputMethodHighlight(InputMethodHighlight) - Method in class java.awt.Toolkit
Returns a map of visual attributes for the abstract level description of the given input method highlight, or null if no mapping is found.
mapLibraryName(String) - Static method in class java.lang.System
Maps a library name into a platform-specific string representing a native library.
MappedByteBuffer - Class in java.nio
A direct byte buffer whose content is a memory-mapped region of a file.
mapRenderContext(int, RenderContext, ParameterBlock, RenderableImage) - Method in interface java.awt.image.renderable.ContextualRenderedImageFactory
Maps the operation's output RenderContext into a RenderContext for each of the operation's sources.
mapSystemException(SystemException) - Static method in class javax.rmi.CORBA.Util
Maps a SystemException to a RemoteException.
mapSystemException(SystemException) - Method in interface javax.rmi.CORBA.UtilDelegate
Delegation call for Util.mapSystemException(org.omg.CORBA.SystemException).
MARCH - Static variable in class java.util.Calendar
Value of the Calendar.MONTH field indicating the third month of the year in the Gregorian and Julian calendars.
MARCH - Static variable in class javax.xml.datatype.DatatypeConstants
Value for third month of year.
MARGIN - Static variable in class javax.swing.text.html.CSS.Attribute
MARGIN_BOTTOM - Static variable in class javax.swing.text.html.CSS.Attribute
MARGIN_CHANGED_PROPERTY - Static variable in class javax.swing.AbstractButton
Identifies a change in the button's margins.
MARGIN_LEFT - Static variable in class javax.swing.text.html.CSS.Attribute
MARGIN_RIGHT - Static variable in class javax.swing.text.html.CSS.Attribute
MARGIN_TOP - Static variable in class javax.swing.text.html.CSS.Attribute
MARGINHEIGHT - Static variable in class javax.swing.text.html.HTML.Attribute
MARGINWIDTH - Static variable in class javax.swing.text.html.HTML.Attribute
mark(int) - Method in class java.io.BufferedInputStream
See the general contract of the mark method of InputStream.
mark(int) - Method in class java.io.BufferedReader
Marks the present position in the stream.
mark - Variable in class java.io.ByteArrayInputStream
The currently marked position in the stream.
mark(int) - Method in class java.io.ByteArrayInputStream
Set the current marked position in the stream.
mark(int) - Method in class java.io.CharArrayReader
Marks the present position in the stream.
mark(int) - Method in class java.io.FilterInputStream
Marks the current position in this input stream.
mark(int) - Method in class java.io.FilterReader
Marks the present position in the stream.
mark(int) - Method in class java.io.InputStream
Marks the current position in this input stream.
mark(int) - Method in class java.io.LineNumberInputStream
Deprecated.
Marks the current position in this input stream.
mark(int) - Method in class java.io.LineNumberReader
Mark the present position in the stream.
mark(int) - Method in class java.io.PushbackInputStream
Marks the current position in this input stream.
mark(int) - Method in class java.io.PushbackReader
Marks the present position in the stream.
mark(int) - Method in class java.io.Reader
Marks the present position in the stream.
mark(int) - Method in class java.io.StringReader
Marks the present position in the stream.
mark() - Method in class java.nio.Buffer
Sets this buffer's mark at its position.
mark(int) - Method in class java.util.zip.DeflaterInputStream
This operation is not supported.
mark(int) - Method in class java.util.zip.InflaterInputStream
Marks the current position in this input stream.
mark() - Method in interface javax.imageio.stream.ImageInputStream
Marks a position in the stream to be returned to by a subsequent call to reset.
mark() - Method in class javax.imageio.stream.ImageInputStreamImpl
Pushes the current stream position onto a stack of marked positions.
mark(int) - Method in class javax.sound.sampled.AudioInputStream
Marks the current position in this audio input stream.
markCompletelyClean(JComponent) - Method in class javax.swing.RepaintManager
Mark a component completely clean.
markCompletelyDirty(JComponent) - Method in class javax.swing.RepaintManager
Mark a component completely dirty.
markedPos - Variable in class java.io.CharArrayReader
The position of mark in buffer.
MARKER_SUPPLY_EMPTY - Static variable in class javax.print.attribute.standard.PrinterStateReason
The device is out of at least one marker supply (e.g.
MARKER_SUPPLY_LOW - Static variable in class javax.print.attribute.standard.PrinterStateReason
The device is low on at least one marker supply (e.g.
MARKER_WASTE_ALMOST_FULL - Static variable in class javax.print.attribute.standard.PrinterStateReason
The device marker supply waste receptacle is almost full.
MARKER_WASTE_FULL - Static variable in class javax.print.attribute.standard.PrinterStateReason
The device marker supply waste receptacle is full.
markFirstTime(Element) - Method in class javax.swing.text.html.parser.Parser
Marks the first time a tag has been seen in a document
marklimit - Variable in class java.io.BufferedInputStream
The maximum read ahead allowed after a call to the mark method before subsequent calls to the reset method fail.
markpos - Variable in class java.io.BufferedInputStream
The value of the pos field at the time the last mark method was called.
markSupported() - Method in class java.io.BufferedInputStream
Tests if this input stream supports the mark and reset methods.
markSupported() - Method in class java.io.BufferedReader
Tells whether this stream supports the mark() operation, which it does.
markSupported() - Method in class java.io.ByteArrayInputStream
Tests if this InputStream supports mark/reset.
markSupported() - Method in class java.io.CharArrayReader
Tells whether this stream supports the mark() operation, which it does.
markSupported() - Method in class java.io.FilterInputStream
Tests if this input stream supports the mark and reset methods.
markSupported() - Method in class java.io.FilterReader
Tells whether this stream supports the mark() operation.
markSupported() - Method in class java.io.InputStream
Tests if this input stream supports the mark and reset methods.
markSupported() - Method in class java.io.PushbackInputStream
Tests if this input stream supports the mark and reset methods, which it does not.
markSupported() - Method in class java.io.PushbackReader
Tells whether this stream supports the mark() operation, which it does not.
markSupported() - Method in class java.io.Reader
Tells whether this stream supports the mark() operation.
markSupported() - Method in class java.io.StringReader
Tells whether this stream supports the mark() operation, which it does.
markSupported() - Method in class java.util.zip.DeflaterInputStream
Always returns false because this input stream does not support the mark() and reset() methods.
markSupported() - Method in class java.util.zip.InflaterInputStream
Tests if this input stream supports the mark and reset methods.
markSupported() - Method in class javax.crypto.CipherInputStream
Tests if this input stream supports the mark and reset methods, which it does not.
markSupported() - Method in class javax.sound.sampled.AudioInputStream
Tests whether this audio input stream supports the mark and reset methods.
marshal(String) - Method in class javax.xml.bind.annotation.adapters.CollapsedStringAdapter
No-op.
marshal(byte[]) - Method in class javax.xml.bind.annotation.adapters.HexBinaryAdapter
marshal(String) - Method in class javax.xml.bind.annotation.adapters.NormalizedStringAdapter
No-op.
marshal(BoundType) - Method in class javax.xml.bind.annotation.adapters.XmlAdapter
Convert a bound type to a value type.
marshal(ElementT, ValidationEventHandler) - Method in interface javax.xml.bind.annotation.DomHandler
This method is called when a JAXB provider needs to marshal an element to XML.
marshal(Element, ValidationEventHandler) - Method in class javax.xml.bind.annotation.W3CDomHandler
marshal(Object, XmlNode) - Method in class javax.xml.bind.Binder
Marshal a JAXB object tree to a new XML document.
marshal(Object, OutputStream) - Method in class javax.xml.bind.helpers.AbstractMarshallerImpl
marshal(Object, File) - Method in class javax.xml.bind.helpers.AbstractMarshallerImpl
marshal(Object, Writer) - Method in class javax.xml.bind.helpers.AbstractMarshallerImpl
marshal(Object, ContentHandler) - Method in class javax.xml.bind.helpers.AbstractMarshallerImpl
marshal(Object, Node) - Method in class javax.xml.bind.helpers.AbstractMarshallerImpl
marshal(Object, XMLEventWriter) - Method in class javax.xml.bind.helpers.AbstractMarshallerImpl
marshal(Object, XMLStreamWriter) - Method in class javax.xml.bind.helpers.AbstractMarshallerImpl
marshal(Object, File) - Static method in class javax.xml.bind.JAXB
Writes a Java object tree to XML and store it to the specified location.
marshal(Object, URL) - Static method in class javax.xml.bind.JAXB
Writes a Java object tree to XML and store it to the specified location.
marshal(Object, URI) - Static method in class javax.xml.bind.JAXB
Writes a Java object tree to XML and store it to the specified location.
marshal(Object, String) - Static method in class javax.xml.bind.JAXB
Writes a Java object tree to XML and store it to the specified location.
marshal(Object, OutputStream) - Static method in class javax.xml.bind.JAXB
Writes a Java object tree to XML and store it to the specified location.
marshal(Object, Writer) - Static method in class javax.xml.bind.JAXB
Writes a Java object tree to XML and store it to the specified location.
marshal(Object, Result) - Static method in class javax.xml.bind.JAXB
Writes a Java object tree to XML and store it to the specified location.
marshal(Object, Result) - Method in interface javax.xml.bind.Marshaller
Marshal the content tree rooted at jaxbElement into the specified javax.xml.transform.Result.
marshal(Object, OutputStream) - Method in interface javax.xml.bind.Marshaller
Marshal the content tree rooted at jaxbElement into an output stream.
marshal(Object, File) - Method in interface javax.xml.bind.Marshaller
Marshal the content tree rooted at jaxbElement into a file.
marshal(Object, Writer) - Method in interface javax.xml.bind.Marshaller
Marshal the content tree rooted at jaxbElement into a Writer.
marshal(Object, ContentHandler) - Method in interface javax.xml.bind.Marshaller
Marshal the content tree rooted at jaxbElement into SAX2 events.
marshal(Object, Node) - Method in interface javax.xml.bind.Marshaller
Marshal the content tree rooted at jaxbElement into a DOM tree.
marshal(Object, XMLStreamWriter) - Method in interface javax.xml.bind.Marshaller
Marshal the content tree rooted at jaxbElement into a XMLStreamWriter.
marshal(Object, XMLEventWriter) - Method in interface javax.xml.bind.Marshaller
Marshal the content tree rooted at jaxbElement into a XMLEventWriter.
marshal(XMLStructure, XMLCryptoContext) - Method in interface javax.xml.crypto.dsig.keyinfo.KeyInfo
Marshals the key info to XML.
marshal(DataOutputStream) - Method in interface org.omg.CORBA.CustomMarshal
Marshal method has to be implemented by the Customized Marshal class.
MARSHAL - Exception in org.omg.CORBA
A request or reply from the network is structurally invalid.
MARSHAL() - Constructor for exception org.omg.CORBA.MARSHAL
Constructs a MARSHAL exception with a default minor code of 0, a completion state of CompletionStatus.COMPLETED_NO, and a null description.
MARSHAL(String) - Constructor for exception org.omg.CORBA.MARSHAL
Constructs a MARSHAL exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.
MARSHAL(int, CompletionStatus) - Constructor for exception org.omg.CORBA.MARSHAL
Constructs a MARSHAL exception with the specified minor code and completion status.
MARSHAL(String, int, CompletionStatus) - Constructor for exception org.omg.CORBA.MARSHAL
Constructs a MARSHAL exception with the specified description message, minor code, and completion status.
MarshalException - Exception in java.rmi
A MarshalException is thrown if a java.io.IOException occurs while marshalling the remote call header, arguments or return value for a remote method call.
MarshalException(String) - Constructor for exception java.rmi.MarshalException
Constructs a MarshalException with the specified detail message.
MarshalException(String, Exception) - Constructor for exception java.rmi.MarshalException
Constructs a MarshalException with the specified detail message and nested exception.
MarshalException - Exception in javax.xml.bind
This exception indicates that an error has occurred while performing a marshal operation that the provider is unable to recover from.
MarshalException(String) - Constructor for exception javax.xml.bind.MarshalException
Construct a MarshalException with the specified detail message.
MarshalException(String, String) - Constructor for exception javax.xml.bind.MarshalException
Construct a MarshalException with the specified detail message and vendor specific errorCode.
MarshalException(Throwable) - Constructor for exception javax.xml.bind.MarshalException
Construct a MarshalException with a linkedException.
MarshalException(String, Throwable) - Constructor for exception javax.xml.bind.MarshalException
Construct a MarshalException with the specified detail message and linkedException.
MarshalException(String, String, Throwable) - Constructor for exception javax.xml.bind.MarshalException
Construct a MarshalException with the specified detail message, vendor specific errorCode, and linkedException.
MarshalException - Exception in javax.xml.crypto
Indicates an exceptional condition that occured during the XML marshalling or unmarshalling process.
MarshalException() - Constructor for exception javax.xml.crypto.MarshalException
Constructs a new MarshalException with null as its detail message.
MarshalException(String) - Constructor for exception javax.xml.crypto.MarshalException
Constructs a new MarshalException with the specified detail message.
MarshalException(String, Throwable) - Constructor for exception javax.xml.crypto.MarshalException
Constructs a new MarshalException with the specified detail message and cause.
MarshalException(Throwable) - Constructor for exception javax.xml.crypto.MarshalException
Constructs a new MarshalException with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).
MarshalledObject<T> - Class in java.rmi
A MarshalledObject contains a byte stream with the serialized representation of an object given to its constructor.
MarshalledObject(T) - Constructor for class java.rmi.MarshalledObject
Creates a new MarshalledObject that contains the serialized representation of the current state of the supplied object.
Marshaller - Interface in javax.xml.bind
The Marshaller class is responsible for governing the process of serializing Java content trees back into XML data.
Marshaller.Listener - Class in javax.xml.bind

Register an instance of an implementation of this class with a Marshaller to externally listen for marshal events.

Marshaller.Listener() - Constructor for class javax.xml.bind.Marshaller.Listener
marshalParams(XMLStructure, XMLCryptoContext) - Method in class javax.xml.crypto.dsig.TransformService
Marshals the algorithm-specific parameters.
MaskFormatter - Class in javax.swing.text
MaskFormatter is used to format and edit strings.
MaskFormatter() - Constructor for class javax.swing.text.MaskFormatter
Creates a MaskFormatter with no mask.
MaskFormatter(String) - Constructor for class javax.swing.text.MaskFormatter
Creates a MaskFormatter with the specified mask.
MASTER_GAIN - Static variable in class javax.sound.sampled.FloatControl.Type
Represents a control for the overall gain on a line.
match(DataFlavor) - Method in class java.awt.datatransfer.DataFlavor
Identical to DataFlavor.equals(DataFlavor).
match(Certificate) - Method in interface java.security.cert.CertSelector
Decides whether a Certificate should be selected.
match(CRL) - Method in interface java.security.cert.CRLSelector
Decides whether a CRL should be selected.
match(Certificate) - Method in class java.security.cert.X509CertSelector
Decides whether a Certificate should be selected.
match(CRL) - Method in class java.security.cert.X509CRLSelector
Decides whether a CRL should be selected.
match() - Method in class java.util.Scanner
Returns the match result of the last scanning operation performed by this scanner.
match(MimeType) - Method in class javax.activation.MimeType
Determine if the primary and sub type of this object is the same as what is in the given type.
match(String) - Method in class javax.activation.MimeType
Determine if the primary and sub type of this object is the same as the content type described in rawdata.
match(AttributeValueExp, StringValueExp) - Static method in class javax.management.Query
Returns a query expression that represents a matching constraint on a string argument.
Matcher - Class in java.util.regex
An engine that performs match operations on a character sequence by interpreting a Pattern.
matcher(CharSequence) - Method in class java.util.regex.Pattern
Creates a matcher that will match the given input against this pattern.
matches(String) - Method in class java.lang.String
Tells whether or not this string matches the given regular expression.
matches(Path) - Method in interface java.nio.file.PathMatcher
Tells if given path matches this matcher's pattern.
matches() - Method in class java.util.regex.Matcher
Attempts to match the entire region against the pattern.
matches(String, CharSequence) - Static method in class java.util.regex.Pattern
Compiles the given regular expression and attempts to match the given input against it.
matches(AudioFormat) - Method in class javax.sound.sampled.AudioFormat
Indicates whether this format matches the one specified.
matches(Line.Info) - Method in class javax.sound.sampled.DataLine.Info
Determines whether the specified info object matches this one.
matches(Line.Info) - Method in class javax.sound.sampled.Line.Info
Indicates whether the specified info object matches this one.
matches(Line.Info) - Method in class javax.sound.sampled.Port.Info
Indicates whether this info object specified matches this one.
matchNameAttribute(AttributeSet, HTML.Tag) - Method in class javax.swing.text.html.HTMLWriter
Returns true if the StyleConstants.NameAttribute is equal to the tag that is passed in as a parameter.
MatchResult - Interface in java.util.regex
The result of a match operation.
Math - Class in java.lang
The class Math contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.
MATH_SYMBOL - Static variable in class java.lang.Character
General category "Sm" in the Unicode specification.
MathContext - Class in java.math
Immutable objects which encapsulate the context settings which describe certain rules for numerical operators, such as those implemented by the BigDecimal class.
MathContext(int) - Constructor for class java.math.MathContext
Constructs a new MathContext with the specified precision and the HALF_UP rounding mode.
MathContext(int, RoundingMode) - Constructor for class java.math.MathContext
Constructs a new MathContext with a specified precision and rounding mode.
MathContext(String) - Constructor for class java.math.MathContext
Constructs a new MathContext from a string.
MATHEMATICAL_ALPHANUMERIC_SYMBOLS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Mathematical Alphanumeric Symbols" Unicode character block.
MATHEMATICAL_OPERATORS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Mathematical Operators" Unicode character block.
MatteBorder - Class in javax.swing.border
A class which provides a matte-like border of either a solid color or a tiled icon.
MatteBorder(int, int, int, int, Color) - Constructor for class javax.swing.border.MatteBorder
Creates a matte border with the specified insets and color.
MatteBorder(Insets, Color) - Constructor for class javax.swing.border.MatteBorder
Creates a matte border with the specified insets and color.
MatteBorder(int, int, int, int, Icon) - Constructor for class javax.swing.border.MatteBorder
Creates a matte border with the specified insets and tile icon.
MatteBorder(Insets, Icon) - Constructor for class javax.swing.border.MatteBorder
Creates a matte border with the specified insets and tile icon.
MatteBorder(Icon) - Constructor for class javax.swing.border.MatteBorder
Creates a matte border with the specified tile icon.
max(int, int) - Static method in class java.lang.Math
Returns the greater of two int values.
max(long, long) - Static method in class java.lang.Math
Returns the greater of two long values.
max(float, float) - Static method in class java.lang.Math
Returns the greater of two float values.
max(double, double) - Static method in class java.lang.Math
Returns the greater of two double values.
max(int, int) - Static method in class java.lang.StrictMath
Returns the greater of two int values.
max(long, long) - Static method in class java.lang.StrictMath
Returns the greater of two long values.
max(float, float) - Static method in class java.lang.StrictMath
Returns the greater of two float values.
max(double, double) - Static method in class java.lang.StrictMath
Returns the greater of two double values.
max(BigDecimal) - Method in class java.math.BigDecimal
Returns the maximum of this BigDecimal and val.
max(BigInteger) - Method in class java.math.BigInteger
Returns the maximum of this BigInteger and val.
max(Collection<? extends T>) - Static method in class java.util.Collections
Returns the maximum element of the given collection, according to the natural ordering of its elements.
max(Collection<? extends T>, Comparator<? super T>) - Static method in class java.util.Collections
Returns the maximum element of the given collection, according to the order induced by the specified comparator.
max(Spring, Spring) - Static method in class javax.swing.Spring
Returns max(s1, s2): a spring whose value is always greater than (or equal to) the values of both s1 and s2.
MAX_BUFFER - Static variable in class javax.security.sasl.Sasl
The name of a property that specifies the maximum size of the receive buffer in bytes of SaslClient/SaslServer.
MAX_CODE_POINT - Static variable in class java.lang.Character
The maximum value of a Unicode code point, constant U+10FFFF.
MAX_COUNT - Static variable in class javax.swing.plaf.synth.ColorType
Maximum number of ColorTypes.
MAX_EXPONENT - Static variable in class java.lang.Double
Maximum exponent a finite double variable may have.
MAX_EXPONENT - Static variable in class java.lang.Float
Maximum exponent a finite float variable may have.
MAX_HIGH_SURROGATE - Static variable in class java.lang.Character
The maximum value of a Unicode high-surrogate code unit in the UTF-16 encoding, constant '\uDBFF'.
MAX_KEY_LENGTH - Static variable in class java.util.prefs.Preferences
Maximum length of string allowed as a key (80 characters).
MAX_LOW_SURROGATE - Static variable in class java.lang.Character
The maximum value of a Unicode low-surrogate code unit in the UTF-16 encoding, constant '\uDFFF'.
MAX_NAME_LENGTH - Static variable in class java.util.prefs.Preferences
Maximum length of a node name (80 characters).
MAX_PRIORITY - Static variable in class java.lang.Thread
The maximum priority that a thread can have.
MAX_RADIX - Static variable in class java.lang.Character
The maximum radix available for conversion to and from strings.
MAX_SCROLL - Static variable in class javax.swing.plaf.basic.BasicSliderUI
MAX_SURROGATE - Static variable in class java.lang.Character
The maximum value of a Unicode surrogate code unit in the UTF-16 encoding, constant '\uDFFF'.
MAX_TIMEZONE_OFFSET - Static variable in class javax.xml.datatype.DatatypeConstants
W3C XML Schema max timezone offset is -14:00.
MAX_VALUE - Static variable in class java.lang.Byte
A constant holding the maximum value a byte can have, 27-1.
MAX_VALUE - Static variable in class java.lang.Character
The constant value of this field is the largest value of type char, '\uFFFF'.
MAX_VALUE - Static variable in class java.lang.Double
A constant holding the largest positive finite value of type double, (2-2-52)·21023.
MAX_VALUE - Static variable in class java.lang.Float
A constant holding the largest positive finite value of type float, (2-2-23)·2127.
MAX_VALUE - Static variable in class java.lang.Integer
A constant holding the maximum value an int can have, 231-1.
MAX_VALUE - Static variable in class java.lang.Long
A constant holding the maximum value a long can have, 263-1.
MAX_VALUE - Static variable in class java.lang.Short
A constant holding the maximum value a short can have, 215-1.
MAX_VALUE_FIELD - Static variable in class javax.management.JMX
The name of the maxValue field.
MAX_VALUE_LENGTH - Static variable in class java.util.prefs.Preferences
Maximum length of string allowed as a value (8192 characters).
MAXBQUALSIZE - Static variable in interface javax.transaction.xa.Xid
Maximum number of bytes returned by getBqual.
maxButton - Variable in class javax.swing.plaf.basic.BasicInternalFrameTitlePane
maxBytesPerChar() - Method in class java.nio.charset.CharsetEncoder
Returns the maximum number of bytes that will be produced for each character of input.
maxCharsPerByte() - Method in class java.nio.charset.CharsetDecoder
Returns the maximum number of characters that will be produced for each byte of input.
MAXGRIDSIZE - Static variable in class java.awt.GridBagLayout
This field is no longer used to reserve arrays and keeped for backward compatibility.
MAXGTRIDSIZE - Static variable in interface javax.transaction.xa.Xid
Maximum number of bytes returned by getGtrid.
maxIcon - Variable in class javax.swing.plaf.basic.BasicInternalFrameTitlePane
maximizable - Variable in class javax.swing.JInternalFrame
The frame can be expanded to the size of the desktop pane.
MAXIMIZE_CMD - Static variable in class javax.swing.plaf.basic.BasicInternalFrameTitlePane
maximizeAction - Variable in class javax.swing.plaf.basic.BasicInternalFrameTitlePane
MAXIMIZED_BOTH - Static variable in class java.awt.Frame
This state bit mask indicates that frame is fully maximized (that is both horizontally and vertically).
MAXIMIZED_HORIZ - Static variable in class java.awt.Frame
This state bit indicates that frame is maximized in the horizontal direction.
MAXIMIZED_VERT - Static variable in class java.awt.Frame
This state bit indicates that frame is maximized in the vertical direction.
maximizeFrame(JInternalFrame) - Method in class javax.swing.DefaultDesktopManager
Resizes the frame to fill its parents bounds.
maximizeFrame(JInternalFrame) - Method in interface javax.swing.DesktopManager
Generally, the frame should be resized to match it's parents bounds.
maximizeFrame(JInternalFrame) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI
This method is called when the user wants to maximize the frame.
maximizeKey - Variable in class javax.swing.plaf.basic.BasicDesktopPaneUI
Deprecated.
As of 1.3.
maximum - Variable in class javax.swing.SizeRequirements
The maximum size allowed.
maximumLayoutSize(Container) - Method in class java.awt.BorderLayout
Returns the maximum dimensions for this layout given the components in the specified target container.
maximumLayoutSize(Container) - Method in class java.awt.CardLayout
Returns the maximum dimensions for this layout given the components in the specified target container.
maximumLayoutSize(Container) - Method in class java.awt.GridBagLayout
Returns the maximum dimensions for this layout given the components in the specified target container.
maximumLayoutSize(Container) - Method in interface java.awt.LayoutManager2
Calculates the maximum size dimensions for the specified container, given the components it contains.
maximumLayoutSize(Container) - Method in class javax.swing.BoxLayout
Returns the maximum dimensions the target container can use to lay out the components it contains.
maximumLayoutSize(Container) - Method in class javax.swing.GroupLayout
Returns the maximum size for the specified container.
maximumLayoutSize(Container) - Method in class javax.swing.JRootPane.RootLayout
Returns the maximum amount of space the layout can use.
maximumLayoutSize(Container) - Method in class javax.swing.OverlayLayout
Returns the maximum dimensions needed to lay out the components contained in the specified target container.
maximumLayoutSize(Container) - Method in class javax.swing.plaf.basic.BasicSplitPaneUI.BasicHorizontalLayoutManager
Returns the maximum layout size, which is Integer.MAX_VALUE in both directions.
maximumLayoutSize(Container) - Method in class javax.swing.SpringLayout
maximumRowCount - Variable in class javax.swing.JComboBox
This protected field is implementation specific.
maximumThumbSize - Variable in class javax.swing.plaf.basic.BasicScrollBarUI
MAXLENGTH - Static variable in class javax.swing.text.html.HTML.Attribute
maxMemory() - Method in class java.lang.Runtime
Returns the maximum amount of memory that the Java virtual machine will attempt to use.
maxTabHeight - Variable in class javax.swing.plaf.basic.BasicTabbedPaneUI
maxTabWidth - Variable in class javax.swing.plaf.basic.BasicTabbedPaneUI
maxWidth - Variable in class javax.swing.table.TableColumn
The maximum width of the column.
MAY - Static variable in class java.util.Calendar
Value of the Calendar.MONTH field indicating the fifth month of the year in the Gregorian and Julian calendars.
MAY - Static variable in class javax.xml.datatype.DatatypeConstants
Value for fifth month of year.
maybeUpdateLayoutState() - Method in class javax.swing.plaf.basic.BasicListUI
If updateLayoutStateNeeded is non zero, call updateLayoutState() and reset updateLayoutStateNeeded.
MBeanAttributeInfo - Class in javax.management
Describes an MBean attribute exposed for management.
MBeanAttributeInfo(String, String, String, boolean, boolean, boolean) - Constructor for class javax.management.MBeanAttributeInfo
Constructs an MBeanAttributeInfo object.
MBeanAttributeInfo(String, String, String, boolean, boolean, boolean, Descriptor) - Constructor for class javax.management.MBeanAttributeInfo
Constructs an MBeanAttributeInfo object.
MBeanAttributeInfo(String, String, Method, Method) - Constructor for class javax.management.MBeanAttributeInfo
This constructor takes the name of a simple attribute, and Method objects for reading and writing the attribute.
MBeanConstructorInfo - Class in javax.management
Describes a constructor exposed by an MBean.
MBeanConstructorInfo(String, Constructor<?>) - Constructor for class javax.management.MBeanConstructorInfo
Constructs an MBeanConstructorInfo object.
MBeanConstructorInfo(String, String, MBeanParameterInfo[]) - Constructor for class javax.management.MBeanConstructorInfo
Constructs an MBeanConstructorInfo object.
MBeanConstructorInfo(String, String, MBeanParameterInfo[], Descriptor) - Constructor for class javax.management.MBeanConstructorInfo
Constructs an MBeanConstructorInfo object.
MBeanException - Exception in javax.management
Represents "user defined" exceptions thrown by MBean methods in the agent.
MBeanException(Exception) - Constructor for exception javax.management.MBeanException
Creates an MBeanException that wraps the actual java.lang.Exception.
MBeanException(Exception, String) - Constructor for exception javax.management.MBeanException
Creates an MBeanException that wraps the actual java.lang.Exception with a detail message.
MBeanFeatureInfo - Class in javax.management
Provides general information for an MBean descriptor object.
MBeanFeatureInfo(String, String) - Constructor for class javax.management.MBeanFeatureInfo
Constructs an MBeanFeatureInfo object.
MBeanFeatureInfo(String, String, Descriptor) - Constructor for class javax.management.MBeanFeatureInfo
Constructs an MBeanFeatureInfo object.
MBeanInfo - Class in javax.management
Describes the management interface exposed by an MBean; that is, the set of attributes and operations which are available for management operations.
MBeanInfo(String, String, MBeanAttributeInfo[], MBeanConstructorInfo[], MBeanOperationInfo[], MBeanNotificationInfo[]) - Constructor for class javax.management.MBeanInfo
Constructs an MBeanInfo.
MBeanInfo(String, String, MBeanAttributeInfo[], MBeanConstructorInfo[], MBeanOperationInfo[], MBeanNotificationInfo[], Descriptor) - Constructor for class javax.management.MBeanInfo
Constructs an MBeanInfo.
MBeanNotificationInfo - Class in javax.management
The MBeanNotificationInfo class is used to describe the characteristics of the different notification instances emitted by an MBean, for a given Java class of notification.
MBeanNotificationInfo(String[], String, String) - Constructor for class javax.management.MBeanNotificationInfo
Constructs an MBeanNotificationInfo object.
MBeanNotificationInfo(String[], String, String, Descriptor) - Constructor for class javax.management.MBeanNotificationInfo
Constructs an MBeanNotificationInfo object.
MBeanOperationInfo - Class in javax.management
Describes a management operation exposed by an MBean.
MBeanOperationInfo(String, Method) - Constructor for class javax.management.MBeanOperationInfo
Constructs an MBeanOperationInfo object.
MBeanOperationInfo(String, String, MBeanParameterInfo[], String, int) - Constructor for class javax.management.MBeanOperationInfo
Constructs an MBeanOperationInfo object.
MBeanOperationInfo(String, String, MBeanParameterInfo[], String, int, Descriptor) - Constructor for class javax.management.MBeanOperationInfo
Constructs an MBeanOperationInfo object.
MBeanParameterInfo - Class in javax.management
Describes an argument of an operation exposed by an MBean.
MBeanParameterInfo(String, String, String) - Constructor for class javax.management.MBeanParameterInfo
Constructs an MBeanParameterInfo object.
MBeanParameterInfo(String, String, String, Descriptor) - Constructor for class javax.management.MBeanParameterInfo
Constructs an MBeanParameterInfo object.
MBeanPermission - Class in javax.management
Permission controlling access to MBeanServer operations.
MBeanPermission(String, String) - Constructor for class javax.management.MBeanPermission
Create a new MBeanPermission object with the specified target name and actions.
MBeanPermission(String, String, ObjectName, String) - Constructor for class javax.management.MBeanPermission
Create a new MBeanPermission object with the specified target name (class name, member, object name) and actions.
MBeanRegistration - Interface in javax.management
Can be implemented by an MBean in order to carry out operations before and after being registered or unregistered from the MBean Server.
MBeanRegistrationException - Exception in javax.management
Wraps exceptions thrown by the preRegister(), preDeregister() methods of the MBeanRegistration interface.
MBeanRegistrationException(Exception) - Constructor for exception javax.management.MBeanRegistrationException
Creates an MBeanRegistrationException that wraps the actual java.lang.Exception.
MBeanRegistrationException(Exception, String) - Constructor for exception javax.management.MBeanRegistrationException
Creates an MBeanRegistrationException that wraps the actual java.lang.Exception with a detailed message.
MBeanServer - Interface in javax.management
This is the interface for MBean manipulation on the agent side.
MBeanServerBuilder - Class in javax.management
This class represents a builder that creates a default MBeanServer implementation.
MBeanServerBuilder() - Constructor for class javax.management.MBeanServerBuilder
Public default constructor.
MBeanServerConnection - Interface in javax.management
This interface represents a way to talk to an MBean server, whether local or remote.
MBeanServerDelegate - Class in javax.management
Represents the MBean server from the management point of view.
MBeanServerDelegate() - Constructor for class javax.management.MBeanServerDelegate
Create a MBeanServerDelegate object.
MBeanServerDelegateMBean - Interface in javax.management
Defines the management interface of an object of class MBeanServerDelegate.
MBeanServerFactory - Class in javax.management
Provides MBean server references.
MBeanServerForwarder - Interface in javax.management.remote
An object of this class implements the MBeanServer interface and wraps another object that also implements that interface.
MBeanServerInvocationHandler - Class in javax.management
InvocationHandler that forwards methods in an MBean's management interface through the MBean server to the MBean.
MBeanServerInvocationHandler(MBeanServerConnection, ObjectName) - Constructor for class javax.management.MBeanServerInvocationHandler
Invocation handler that forwards methods through an MBean server to a Standard MBean.
MBeanServerInvocationHandler(MBeanServerConnection, ObjectName, boolean) - Constructor for class javax.management.MBeanServerInvocationHandler
Invocation handler that can forward methods through an MBean server to a Standard MBean or MXBean.
MBeanServerNotification - Class in javax.management
Represents a notification emitted by the MBean Server through the MBeanServerDelegate MBean.
MBeanServerNotification(String, Object, long, ObjectName) - Constructor for class javax.management.MBeanServerNotification
Creates an MBeanServerNotification object specifying object names of the MBeans that caused the notification and the specified notification type.
MBeanServerNotificationFilter - Class in javax.management.relation
Filter for MBeanServerNotification.
MBeanServerNotificationFilter() - Constructor for class javax.management.relation.MBeanServerNotificationFilter
Creates a filter selecting all MBeanServerNotification notifications for all ObjectNames.
MBeanServerPermission - Class in javax.management
A Permission to perform actions related to MBeanServers.
MBeanServerPermission(String) - Constructor for class javax.management.MBeanServerPermission
Create a new MBeanServerPermission with the given name.
MBeanServerPermission(String, String) - Constructor for class javax.management.MBeanServerPermission
Create a new MBeanServerPermission with the given name.
MBeanTrustPermission - Class in javax.management
This permission represents "trust" in a signer or codebase.
MBeanTrustPermission(String) - Constructor for class javax.management.MBeanTrustPermission
Create a new MBeanTrustPermission with the given name.
MBeanTrustPermission(String, String) - Constructor for class javax.management.MBeanTrustPermission
Create a new MBeanTrustPermission with the given name.
MD - Static variable in interface javax.swing.text.html.parser.DTDConstants
Media - Class in javax.print.attribute.standard
Class Media is a printing attribute class that specifies the medium on which to print.
Media(int) - Constructor for class javax.print.attribute.standard.Media
Constructs a new media attribute specified by name.
MEDIA_EMPTY - Static variable in class javax.print.attribute.standard.PrinterStateReason
At least one input tray is empty.
MEDIA_JAM - Static variable in class javax.print.attribute.standard.PrinterStateReason
The device has a media jam.
MEDIA_LOW - Static variable in class javax.print.attribute.standard.PrinterStateReason
At least one input tray is low on media.
MEDIA_NEEDED - Static variable in class javax.print.attribute.standard.PrinterStateReason
A tray has run out of media.
MEDIA_TYPE - Static variable in class javax.xml.transform.OutputKeys
media-type = string.
MediaName - Class in javax.print.attribute.standard
Class MediaName is a subclass of Media, a printing attribute class (an enumeration) that specifies the media for a print job as a name.
MediaName(int) - Constructor for class javax.print.attribute.standard.MediaName
Constructs a new media name enumeration value with the given integer value.
MediaPrintableArea - Class in javax.print.attribute.standard
Class MediaPrintableArea is a printing attribute used to distinguish the printable and non-printable areas of media.
MediaPrintableArea(float, float, float, float, int) - Constructor for class javax.print.attribute.standard.MediaPrintableArea
Constructs a MediaPrintableArea object from floating point values.
MediaPrintableArea(int, int, int, int, int) - Constructor for class javax.print.attribute.standard.MediaPrintableArea
Constructs a MediaPrintableArea object from integer values.
MediaSize - Class in javax.print.attribute.standard
Class MediaSize is a two-dimensional size valued printing attribute class that indicates the dimensions of the medium in a portrait orientation, with the X dimension running along the bottom edge and the Y dimension running along the left edge.
MediaSize(float, float, int) - Constructor for class javax.print.attribute.standard.MediaSize
Construct a new media size attribute from the given floating-point values.
MediaSize(int, int, int) - Constructor for class javax.print.attribute.standard.MediaSize
Construct a new media size attribute from the given integer values.
MediaSize(float, float, int, MediaSizeName) - Constructor for class javax.print.attribute.standard.MediaSize
Construct a new media size attribute from the given floating-point values.
MediaSize(int, int, int, MediaSizeName) - Constructor for class javax.print.attribute.standard.MediaSize
Construct a new media size attribute from the given integer values.
MediaSize.Engineering - Class in javax.print.attribute.standard
Class MediaSize.Engineering includes MediaSize values for engineering media.
MediaSize.ISO - Class in javax.print.attribute.standard
Class MediaSize.ISO includes MediaSize values for ISO media.
MediaSize.JIS - Class in javax.print.attribute.standard
Class MediaSize.JIS includes MediaSize values for JIS (Japanese) media.
MediaSize.NA - Class in javax.print.attribute.standard
Class MediaSize.NA includes MediaSize values for North American media.
MediaSize.Other - Class in javax.print.attribute.standard
Class MediaSize.Other includes MediaSize values for miscellaneous media.
MediaSizeName - Class in javax.print.attribute.standard
Class MediaSizeName is a subclass of Media.
MediaSizeName(int) - Constructor for class javax.print.attribute.standard.MediaSizeName
Construct a new media size enumeration value with the given integer value.
MediaTracker - Class in java.awt
The MediaTracker class is a utility class to track the status of a number of media objects.
MediaTracker(Component) - Constructor for class java.awt.MediaTracker
Creates a media tracker to track images for a given component.
MediaTray - Class in javax.print.attribute.standard
Class MediaTray is a subclass of Media.
MediaTray(int) - Constructor for class javax.print.attribute.standard.MediaTray
Construct a new media tray enumeration value with the given integer value.
MEDIUM - Static variable in class java.text.DateFormat
Constant for medium style pattern.
MEETEI_MAYEK - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Meetei Mayek" Unicode character block.
Member - Interface in java.lang.reflect
Member is an interface that reflects identifying information about a single member (a field or a method) or a constructor.
member() - Method in interface org.omg.CORBA.DynUnion
Deprecated.
Returns a DynAny object reference that is used in order to insert/get a member of this union.
member() - Method in class org.omg.DynamicAny._DynUnionStub
Returns the currently active member.
member() - Method in interface org.omg.DynamicAny.DynUnionOperations
Returns the currently active member.
member_count() - Method in class org.omg.CORBA.TypeCode
Retrieves the number of members in the type described by this TypeCode object.
member_kind() - Method in interface org.omg.CORBA.DynUnion
Deprecated.
Returns the TCKind associated with the member of this union.
member_kind() - Method in class org.omg.DynamicAny._DynUnionStub
Returns the TCKind value of the currently active members TypeCode.
member_kind() - Method in interface org.omg.DynamicAny.DynUnionOperations
Returns the TCKind value of the currently active members TypeCode.
member_label(int) - Method in class org.omg.CORBA.TypeCode
Retrieves the label of the union member identified by the given index.
member_name() - Method in interface org.omg.CORBA.DynUnion
Deprecated.
Allows for the inspection of the name of this union member without checking the value of the discriminator.
member_name(String) - Method in interface org.omg.CORBA.DynUnion
Deprecated.
Allows for the assignment of the name of this union member.
member_name(int) - Method in class org.omg.CORBA.TypeCode
Retrieves the simple name of the member identified by the given index.
member_name() - Method in class org.omg.DynamicAny._DynUnionStub
Returns the name of the currently active member.
member_name() - Method in interface org.omg.DynamicAny.DynUnionOperations
Returns the name of the currently active member.
MEMBER_OF - Static variable in class javax.accessibility.AccessibleRelation
Indicates an object is a member of a group of one or more target objects.
MEMBER_OF_PROPERTY - Static variable in class javax.accessibility.AccessibleRelation
Identifies that group membership has changed.
member_type(int) - Method in class org.omg.CORBA.TypeCode
Retrieves the TypeCode object describing the type of the member identified by the given index.
member_visibility(int) - Method in class org.omg.CORBA.TypeCode
Returns the constant that indicates the visibility of the member at the given index.
members() - Method in interface java.security.acl.Group
Returns an enumeration of the members in the group.
MembershipKey - Class in java.nio.channels
A token representing the membership of an Internet Protocol (IP) multicast group.
MembershipKey() - Constructor for class java.nio.channels.MembershipKey
Initializes a new instance of this class.
MEMORY_COLLECTION_THRESHOLD_EXCEEDED - Static variable in class java.lang.management.MemoryNotificationInfo
Notification type denoting that the memory usage of a memory pool is greater than or equal to its collection usage threshold after the Java virtual machine has expended effort in recycling unused objects in that memory pool.
MEMORY_MANAGER_MXBEAN_DOMAIN_TYPE - Static variable in class java.lang.management.ManagementFactory
The domain name and the type key property in the ObjectName for a MemoryManagerMXBean.
MEMORY_MXBEAN_NAME - Static variable in class java.lang.management.ManagementFactory
String representation of the ObjectName for the MemoryMXBean.
MEMORY_POOL_MXBEAN_DOMAIN_TYPE - Static variable in class java.lang.management.ManagementFactory
The domain name and the type key property in the ObjectName for a MemoryPoolMXBean.
MEMORY_THRESHOLD_EXCEEDED - Static variable in class java.lang.management.MemoryNotificationInfo
Notification type denoting that the memory usage of a memory pool has reached or exceeded its usage threshold value.
MemoryCacheImageInputStream - Class in javax.imageio.stream
An implementation of ImageInputStream that gets its input from a regular InputStream.
MemoryCacheImageInputStream(InputStream) - Constructor for class javax.imageio.stream.MemoryCacheImageInputStream
Constructs a MemoryCacheImageInputStream that will read from a given InputStream.
MemoryCacheImageOutputStream - Class in javax.imageio.stream
An implementation of ImageOutputStream that writes its output to a regular OutputStream.
MemoryCacheImageOutputStream(OutputStream) - Constructor for class javax.imageio.stream.MemoryCacheImageOutputStream
Constructs a MemoryCacheImageOutputStream that will write to a given OutputStream.
MemoryHandler - Class in java.util.logging
Handler that buffers requests in a circular buffer in memory.
MemoryHandler() - Constructor for class java.util.logging.MemoryHandler
Create a MemoryHandler and configure it based on LogManager configuration properties.
MemoryHandler(Handler, int, Level) - Constructor for class java.util.logging.MemoryHandler
Create a MemoryHandler.
MemoryImageSource - Class in java.awt.image
This class is an implementation of the ImageProducer interface which uses an array to produce pixel values for an Image.
MemoryImageSource(int, int, ColorModel, byte[], int, int) - Constructor for class java.awt.image.MemoryImageSource
Constructs an ImageProducer object which uses an array of bytes to produce data for an Image object.
MemoryImageSource(int, int, ColorModel, byte[], int, int, Hashtable<?, ?>) - Constructor for class java.awt.image.MemoryImageSource
Constructs an ImageProducer object which uses an array of bytes to produce data for an Image object.
MemoryImageSource(int, int, ColorModel, int[], int, int) - Constructor for class java.awt.image.MemoryImageSource
Constructs an ImageProducer object which uses an array of integers to produce data for an Image object.
MemoryImageSource(int, int, ColorModel, int[], int, int, Hashtable<?, ?>) - Constructor for class java.awt.image.MemoryImageSource
Constructs an ImageProducer object which uses an array of integers to produce data for an Image object.
MemoryImageSource(int, int, int[], int, int) - Constructor for class java.awt.image.MemoryImageSource
Constructs an ImageProducer object which uses an array of integers in the default RGB ColorModel to produce data for an Image object.
MemoryImageSource(int, int, int[], int, int, Hashtable<?, ?>) - Constructor for class java.awt.image.MemoryImageSource
Constructs an ImageProducer object which uses an array of integers in the default RGB ColorModel to produce data for an Image object.
MemoryManagerMXBean - Interface in java.lang.management
The management interface for a memory manager.
MemoryMXBean - Interface in java.lang.management
The management interface for the memory system of the Java virtual machine.
MemoryNotificationInfo - Class in java.lang.management
The information about a memory notification.
MemoryNotificationInfo(String, MemoryUsage, long) - Constructor for class java.lang.management.MemoryNotificationInfo
Constructs a MemoryNotificationInfo object.
MemoryPoolMXBean - Interface in java.lang.management
The management interface for a memory pool.
MemoryType - Enum in java.lang.management
Types of memory pools.
MemoryUsage - Class in java.lang.management
A MemoryUsage object represents a snapshot of memory usage.
MemoryUsage(long, long, long, long) - Constructor for class java.lang.management.MemoryUsage
Constructs a MemoryUsage object.
Menu - Class in java.awt
A Menu object is a pull-down menu component that is deployed from a menu bar.
Menu() - Constructor for class java.awt.Menu
Constructs a new menu with an empty label.
Menu(String) - Constructor for class java.awt.Menu
Constructs a new menu with the specified label.
Menu(String, boolean) - Constructor for class java.awt.Menu
Constructs a new menu with the specified label, indicating whether the menu can be torn off.
MENU - Static variable in class java.awt.SystemColor
The array index for the SystemColor.menu system color.
menu - Static variable in class java.awt.SystemColor
The color rendered for the background of menus.
MENU - Static variable in class javax.accessibility.AccessibleRole
An object usually found inside a menu bar that contains a list of actions the user can choose from.
menu - Variable in class javax.swing.plaf.basic.BasicMenuUI.ChangeHandler
MENU - Static variable in class javax.swing.plaf.synth.Region
Menu region.
MENU - Static variable in class javax.swing.text.html.HTML.Tag
Menu.AccessibleAWTMenu - Class in java.awt
Inner class of Menu used to provide default support for accessibility.
Menu.AccessibleAWTMenu() - Constructor for class java.awt.Menu.AccessibleAWTMenu
MENU_BAR - Static variable in class javax.accessibility.AccessibleRole
An object usually drawn at the top of the primary dialog box of an application that contains a list of menus the user can choose from.
MENU_BAR - Static variable in class javax.swing.plaf.synth.Region
MenuBar region.
MENU_BAR_PROPERTY - Static variable in class javax.swing.JInternalFrame
Bound property name.
MENU_ITEM - Static variable in class javax.accessibility.AccessibleRole
An object usually contained in a menu that presents an action the user can choose.
MENU_ITEM - Static variable in class javax.swing.plaf.synth.Region
MenuItem region.
MENU_ITEM_ACCELERATOR - Static variable in class javax.swing.plaf.synth.Region
Accelerator region of a MenuItem.
MENU_TEXT - Static variable in class java.awt.SystemColor
The array index for the SystemColor.menuText system color.
MenuBar - Class in java.awt
The MenuBar class encapsulates the platform's concept of a menu bar bound to a frame.
MenuBar() - Constructor for class java.awt.MenuBar
Creates a new menu bar.
menuBar - Variable in class javax.swing.JRootPane
The menu bar.
menuBar - Variable in class javax.swing.plaf.basic.BasicInternalFrameTitlePane
menuBar - Variable in class javax.swing.plaf.basic.BasicMenuBarUI
MenuBar.AccessibleAWTMenuBar - Class in java.awt
Inner class of MenuBar used to provide default support for accessibility.
MenuBar.AccessibleAWTMenuBar() - Constructor for class java.awt.MenuBar.AccessibleAWTMenuBar
MenuBarUI - Class in javax.swing.plaf
Pluggable look and feel interface for JMenuBar.
MenuBarUI() - Constructor for class javax.swing.plaf.MenuBarUI
menuCanceled(MenuEvent) - Method in interface javax.swing.event.MenuListener
Invoked when the menu is canceled.
MenuComponent - Class in java.awt
The abstract class MenuComponent is the superclass of all menu-related components.
MenuComponent() - Constructor for class java.awt.MenuComponent
Creates a MenuComponent.
MenuComponent.AccessibleAWTMenuComponent - Class in java.awt
Inner class of MenuComponent used to provide default support for accessibility.
MenuComponent.AccessibleAWTMenuComponent() - Constructor for class java.awt.MenuComponent.AccessibleAWTMenuComponent
Although the class is abstract, this should be called by all sub-classes.
MenuContainer - Interface in java.awt
The super class of all menu related containers.
menuDeselected(MenuEvent) - Method in interface javax.swing.event.MenuListener
Invoked when the menu is deselected.
menuDragMouseDragged(MenuDragMouseEvent) - Method in interface javax.swing.event.MenuDragMouseListener
Invoked when the mouse is being dragged in a menu component's display area.
menuDragMouseEntered(MenuDragMouseEvent) - Method in interface javax.swing.event.MenuDragMouseListener
Invoked when the dragged mouse has entered a menu component's display area.
MenuDragMouseEvent - Class in javax.swing.event
MenuDragMouseEvent is used to notify interested parties that the menu element has received a MouseEvent forwarded to it under drag conditions.
MenuDragMouseEvent(Component, int, long, int, int, int, int, boolean, MenuElement[], MenuSelectionManager) - Constructor for class javax.swing.event.MenuDragMouseEvent
Constructs a MenuDragMouseEvent object.
MenuDragMouseEvent(Component, int, long, int, int, int, int, int, int, boolean, MenuElement[], MenuSelectionManager) - Constructor for class javax.swing.event.MenuDragMouseEvent
Constructs a MenuDragMouseEvent object.
menuDragMouseExited(MenuDragMouseEvent) - Method in interface javax.swing.event.MenuDragMouseListener
Invoked when the dragged mouse has left a menu component's display area.
MenuDragMouseListener - Interface in javax.swing.event
Defines a menu mouse-drag listener.
menuDragMouseListener - Variable in class javax.swing.plaf.basic.BasicMenuItemUI
menuDragMouseReleased(MenuDragMouseEvent) - Method in interface javax.swing.event.MenuDragMouseListener
Invoked when a dragged mouse is release in a menu component's display area.
MenuElement - Interface in javax.swing
Any component that can be placed into a menu should implement this interface.
MenuEvent - Class in javax.swing.event
MenuEvent is used to notify interested parties that the menu which is the event source has been posted, selected, or canceled.
MenuEvent(Object) - Constructor for class javax.swing.event.MenuEvent
Constructs a MenuEvent object.
MenuItem - Class in java.awt
All items in a menu must belong to the class MenuItem, or one of its subclasses.
MenuItem() - Constructor for class java.awt.MenuItem
Constructs a new MenuItem with an empty label and no keyboard shortcut.
MenuItem(String) - Constructor for class java.awt.MenuItem
Constructs a new MenuItem with the specified label and no keyboard shortcut.
MenuItem(String, MenuShortcut) - Constructor for class java.awt.MenuItem
Create a menu item with an associated keyboard shortcut.
menuItem - Variable in class javax.swing.plaf.basic.BasicMenuItemUI
MenuItem.AccessibleAWTMenuItem - Class in java.awt
Inner class of MenuItem used to provide default support for accessibility.
MenuItem.AccessibleAWTMenuItem() - Constructor for class java.awt.MenuItem.AccessibleAWTMenuItem
MenuItemUI - Class in javax.swing.plaf
Pluggable look and feel interface for JMenuItem.
MenuItemUI() - Constructor for class javax.swing.plaf.MenuItemUI
MenuKeyEvent - Class in javax.swing.event
MenuKeyEvent is used to notify interested parties that the menu element has received a KeyEvent forwarded to it in a menu tree.
MenuKeyEvent(Component, int, long, int, int, char, MenuElement[], MenuSelectionManager) - Constructor for class javax.swing.event.MenuKeyEvent
Constructs a MenuKeyEvent object.
MenuKeyListener - Interface in javax.swing.event
MenuKeyListener
menuKeyListener - Variable in class javax.swing.plaf.basic.BasicMenuItemUI
menuKeyPressed(MenuKeyEvent) - Method in interface javax.swing.event.MenuKeyListener
Invoked when a key has been pressed.
menuKeyReleased(MenuKeyEvent) - Method in interface javax.swing.event.MenuKeyListener
Invoked when a key has been released.
menuKeyTyped(MenuKeyEvent) - Method in interface javax.swing.event.MenuKeyListener
Invoked when a key has been typed.
MenuListener - Interface in javax.swing.event
Defines a listener for menu events.
menuListener - Variable in class javax.swing.plaf.basic.BasicMenuUI
menuSelected(MenuEvent) - Method in interface javax.swing.event.MenuListener
Invoked when a menu is selected.
menuSelectionChanged(boolean) - Method in class javax.swing.JMenu
Messaged when the menubar selection changes to activate or deactivate this menu.
menuSelectionChanged(boolean) - Method in class javax.swing.JMenuBar
Implemented to be a MenuElement -- does nothing.
menuSelectionChanged(boolean) - Method in class javax.swing.JMenuItem
Called by the MenuSelectionManager when the MenuElement is selected or unselected.
menuSelectionChanged(boolean) - Method in class javax.swing.JPopupMenu
Messaged when the menubar selection changes to activate or deactivate this menu.
menuSelectionChanged(boolean) - Method in interface javax.swing.MenuElement
Call by the MenuSelectionManager when the MenuElement is added or remove from the menu selection.
MenuSelectionManager - Class in javax.swing
A MenuSelectionManager owns the selection in menu hierarchy.
MenuSelectionManager() - Constructor for class javax.swing.MenuSelectionManager
MenuShortcut - Class in java.awt
The MenuShortcutclass represents a keyboard accelerator for a MenuItem.
MenuShortcut(int) - Constructor for class java.awt.MenuShortcut
Constructs a new MenuShortcut for the specified virtual keycode.
MenuShortcut(int, boolean) - Constructor for class java.awt.MenuShortcut
Constructs a new MenuShortcut for the specified virtual keycode.
menuText - Static variable in class java.awt.SystemColor
The color rendered for the text of menus.
mergeTree(String, Node) - Method in class javax.imageio.metadata.IIOMetadata
Alters the internal state of this IIOMetadata object from a tree of XML DOM Nodes whose syntax is defined by the given metadata format.
message - Variable in class javax.swing.JOptionPane
Message to display.
MESSAGE_OUTBOUND_PROPERTY - Static variable in interface javax.xml.ws.handler.MessageContext
Standard property: message direction, true for outbound messages, false for inbound.
MESSAGE_PROPERTY - Static variable in class javax.swing.JOptionPane
Bound property name for message.
MESSAGE_TYPE_PROPERTY - Static variable in class javax.swing.JOptionPane
Bound property name for type.
MessageContext - Interface in javax.xml.ws.handler
The interface MessageContext abstracts the message context that is processed by a handler in the handle method.
MessageContext.Scope - Enum in javax.xml.ws.handler
Property scope.
MessageDigest - Class in java.security
This MessageDigest class provides applications the functionality of a message digest algorithm, such as SHA-1 or SHA-256.
MessageDigest(String) - Constructor for class java.security.MessageDigest
Creates a message digest with the specified algorithm name.
MessageDigestSpi - Class in java.security
This class defines the Service Provider Interface (SPI) for the MessageDigest class, which provides the functionality of a message digest algorithm, such as MD5 or SHA.
MessageDigestSpi() - Constructor for class java.security.MessageDigestSpi
MessageFactory - Class in javax.xml.soap
A factory for creating SOAPMessage objects.
MessageFactory() - Constructor for class javax.xml.soap.MessageFactory
MessageFormat - Class in java.text
MessageFormat provides a means to produce concatenated messages in a language-neutral way.
MessageFormat(String) - Constructor for class java.text.MessageFormat
Constructs a MessageFormat for the default locale and the specified pattern.
MessageFormat(String, Locale) - Constructor for class java.text.MessageFormat
Constructs a MessageFormat for the specified locale and pattern.
MessageFormat.Field - Class in java.text
Defines constants that are used as attribute keys in the AttributedCharacterIterator returned from MessageFormat.formatToCharacterIterator.
MessageFormat.Field(String) - Constructor for class java.text.MessageFormat.Field
Creates a Field with the specified name.
MessageProp - Class in org.ietf.jgss
This is a utility class used within the per-message GSSContext methods to convey per-message properties.
MessageProp(boolean) - Constructor for class org.ietf.jgss.MessageProp
Constructor which sets the desired privacy state.
MessageProp(int, boolean) - Constructor for class org.ietf.jgss.MessageProp
Constructor which sets the values for the qop and privacy state.
Messager - Interface in javax.annotation.processing
A Messager provides the way for an annotation processor to report error messages, warnings, and other notices.
messageType - Variable in class javax.swing.JOptionPane
Message type.
meta(MetaMessage) - Method in interface javax.sound.midi.MetaEventListener
Invoked when a Sequencer has encountered and processed a MetaMessage in the Sequence it is processing.
META - Static variable in class javax.sound.midi.MetaMessage
Status byte for MetaMessage (0xFF, or 255), which is used in MIDI files.
META - Static variable in class javax.swing.text.html.HTML.Tag
meta - Variable in class javax.swing.text.html.parser.DTD
META_DOWN_MASK - Static variable in class java.awt.event.InputEvent
The Meta key extended modifier constant.
META_MASK - Static variable in class java.awt.event.ActionEvent
The meta modifier.
META_MASK - Static variable in class java.awt.event.InputEvent
The Meta key modifier constant.
META_MASK - Static variable in class java.awt.Event
This flag indicates that the Meta key was down when the event occurred.
metadata - Variable in class javax.imageio.IIOImage
An IIOMetadata object containing metadata associated with the image.
metadata(Element) - Method in class javax.xml.ws.wsaddressing.W3CEndpointReferenceBuilder
Adds the metadataElement to the W3CEndpointReference instance's wsa:Metadata element.
metaDown() - Method in class java.awt.Event
NOTE: The Event class is obsolete and is available only for backwards compatilibility.
MetaEventListener - Interface in javax.sound.midi
The MetaEventListener interface should be implemented by classes whose instances need to be notified when a Sequencer has processed a MetaMessage.
MetalBorders - Class in javax.swing.plaf.metal
Factory object that can vend Borders appropriate for the metal L & F.
MetalBorders() - Constructor for class javax.swing.plaf.metal.MetalBorders
MetalBorders.ButtonBorder - Class in javax.swing.plaf.metal
MetalBorders.ButtonBorder() - Constructor for class javax.swing.plaf.metal.MetalBorders.ButtonBorder
MetalBorders.Flush3DBorder - Class in javax.swing.plaf.metal
MetalBorders.Flush3DBorder() - Constructor for class javax.swing.plaf.metal.MetalBorders.Flush3DBorder
MetalBorders.InternalFrameBorder - Class in javax.swing.plaf.metal
MetalBorders.InternalFrameBorder() - Constructor for class javax.swing.plaf.metal.MetalBorders.InternalFrameBorder
MetalBorders.MenuBarBorder - Class in javax.swing.plaf.metal
MetalBorders.MenuBarBorder() - Constructor for class javax.swing.plaf.metal.MetalBorders.MenuBarBorder
MetalBorders.MenuItemBorder - Class in javax.swing.plaf.metal
MetalBorders.MenuItemBorder() - Constructor for class javax.swing.plaf.metal.MetalBorders.MenuItemBorder
MetalBorders.OptionDialogBorder - Class in javax.swing.plaf.metal
MetalBorders.OptionDialogBorder() - Constructor for class javax.swing.plaf.metal.MetalBorders.OptionDialogBorder
MetalBorders.PaletteBorder - Class in javax.swing.plaf.metal
Border for a Palette.
MetalBorders.PaletteBorder() - Constructor for class javax.swing.plaf.metal.MetalBorders.PaletteBorder
MetalBorders.PopupMenuBorder - Class in javax.swing.plaf.metal
MetalBorders.PopupMenuBorder() - Constructor for class javax.swing.plaf.metal.MetalBorders.PopupMenuBorder
MetalBorders.RolloverButtonBorder - Class in javax.swing.plaf.metal
MetalBorders.RolloverButtonBorder() - Constructor for class javax.swing.plaf.metal.MetalBorders.RolloverButtonBorder
MetalBorders.ScrollPaneBorder - Class in javax.swing.plaf.metal
MetalBorders.ScrollPaneBorder() - Constructor for class javax.swing.plaf.metal.MetalBorders.ScrollPaneBorder
MetalBorders.TableHeaderBorder - Class in javax.swing.plaf.metal
Border for a Table Header
MetalBorders.TableHeaderBorder() - Constructor for class javax.swing.plaf.metal.MetalBorders.TableHeaderBorder
MetalBorders.TextFieldBorder - Class in javax.swing.plaf.metal
MetalBorders.TextFieldBorder() - Constructor for class javax.swing.plaf.metal.MetalBorders.TextFieldBorder
MetalBorders.ToggleButtonBorder - Class in javax.swing.plaf.metal
MetalBorders.ToggleButtonBorder() - Constructor for class javax.swing.plaf.metal.MetalBorders.ToggleButtonBorder
MetalBorders.ToolBarBorder - Class in javax.swing.plaf.metal
MetalBorders.ToolBarBorder() - Constructor for class javax.swing.plaf.metal.MetalBorders.ToolBarBorder
MetalButtonUI - Class in javax.swing.plaf.metal
MetalButtonUI implementation
MetalButtonUI() - Constructor for class javax.swing.plaf.metal.MetalButtonUI
MetalCheckBoxIcon - Class in javax.swing.plaf.metal
CheckboxIcon implementation for OrganicCheckBoxUI
MetalCheckBoxIcon() - Constructor for class javax.swing.plaf.metal.MetalCheckBoxIcon
MetalCheckBoxUI - Class in javax.swing.plaf.metal
CheckboxUI implementation for MetalCheckboxUI
MetalCheckBoxUI() - Constructor for class javax.swing.plaf.metal.MetalCheckBoxUI
MetalComboBoxButton - Class in javax.swing.plaf.metal
JButton subclass to help out MetalComboBoxUI
MetalComboBoxButton(JComboBox, Icon, CellRendererPane, JList) - Constructor for class javax.swing.plaf.metal.MetalComboBoxButton
MetalComboBoxButton(JComboBox, Icon, boolean, CellRendererPane, JList) - Constructor for class javax.swing.plaf.metal.MetalComboBoxButton
MetalComboBoxEditor - Class in javax.swing.plaf.metal
The default editor for Metal editable combo boxes
MetalComboBoxEditor() - Constructor for class javax.swing.plaf.metal.MetalComboBoxEditor
MetalComboBoxEditor.UIResource - Class in javax.swing.plaf.metal
A subclass of BasicComboBoxEditor that implements UIResource.
MetalComboBoxEditor.UIResource() - Constructor for class javax.swing.plaf.metal.MetalComboBoxEditor.UIResource
MetalComboBoxIcon - Class in javax.swing.plaf.metal
This utility class draws the horizontal bars which indicate a MetalComboBox
MetalComboBoxIcon() - Constructor for class javax.swing.plaf.metal.MetalComboBoxIcon
MetalComboBoxUI - Class in javax.swing.plaf.metal
Metal UI for JComboBox
MetalComboBoxUI() - Constructor for class javax.swing.plaf.metal.MetalComboBoxUI
MetalComboBoxUI.MetalComboBoxLayoutManager - Class in javax.swing.plaf.metal
This inner class is marked "public" due to a compiler bug.
MetalComboBoxUI.MetalComboBoxLayoutManager() - Constructor for class javax.swing.plaf.metal.MetalComboBoxUI.MetalComboBoxLayoutManager
MetalComboBoxUI.MetalComboPopup - Class in javax.swing.plaf.metal
Deprecated.
As of Java 2 platform v1.4.
MetalComboBoxUI.MetalComboPopup(JComboBox) - Constructor for class javax.swing.plaf.metal.MetalComboBoxUI.MetalComboPopup
Deprecated.
MetalComboBoxUI.MetalPropertyChangeListener - Class in javax.swing.plaf.metal
This inner class is marked "public" due to a compiler bug.
MetalComboBoxUI.MetalPropertyChangeListener() - Constructor for class javax.swing.plaf.metal.MetalComboBoxUI.MetalPropertyChangeListener
MetalDesktopIconUI - Class in javax.swing.plaf.metal
Metal desktop icon.
MetalDesktopIconUI() - Constructor for class javax.swing.plaf.metal.MetalDesktopIconUI
MetalFileChooserUI - Class in javax.swing.plaf.metal
Metal L&F implementation of a FileChooser.
MetalFileChooserUI(JFileChooser) - Constructor for class javax.swing.plaf.metal.MetalFileChooserUI
MetalFileChooserUI.DirectoryComboBoxAction - Class in javax.swing.plaf.metal
Acts when DirectoryComboBox has changed the selected item.
MetalFileChooserUI.DirectoryComboBoxAction() - Constructor for class javax.swing.plaf.metal.MetalFileChooserUI.DirectoryComboBoxAction
MetalFileChooserUI.DirectoryComboBoxModel - Class in javax.swing.plaf.metal
Data model for a type-face selection combo-box.
MetalFileChooserUI.DirectoryComboBoxModel() - Constructor for class javax.swing.plaf.metal.MetalFileChooserUI.DirectoryComboBoxModel
MetalFileChooserUI.FileRenderer - Class in javax.swing.plaf.metal
MetalFileChooserUI.FileRenderer() - Constructor for class javax.swing.plaf.metal.MetalFileChooserUI.FileRenderer
MetalFileChooserUI.FilterComboBoxModel - Class in javax.swing.plaf.metal
Data model for a type-face selection combo-box.
MetalFileChooserUI.FilterComboBoxModel() - Constructor for class javax.swing.plaf.metal.MetalFileChooserUI.FilterComboBoxModel
MetalFileChooserUI.FilterComboBoxRenderer - Class in javax.swing.plaf.metal
Render different type sizes and styles.
MetalFileChooserUI.FilterComboBoxRenderer() - Constructor for class javax.swing.plaf.metal.MetalFileChooserUI.FilterComboBoxRenderer
MetalFileChooserUI.SingleClickListener - Class in javax.swing.plaf.metal
MetalFileChooserUI.SingleClickListener(JList) - Constructor for class javax.swing.plaf.metal.MetalFileChooserUI.SingleClickListener
MetalIconFactory - Class in javax.swing.plaf.metal
Factory object that vends Icons for the JavaTM look and feel (Metal).
MetalIconFactory() - Constructor for class javax.swing.plaf.metal.MetalIconFactory
MetalIconFactory.FileIcon16 - Class in javax.swing.plaf.metal
警告： Serialized objects of this class will not be compatible with future Swing releases.
MetalIconFactory.FileIcon16() - Constructor for class javax.swing.plaf.metal.MetalIconFactory.FileIcon16
MetalIconFactory.FolderIcon16 - Class in javax.swing.plaf.metal
警告： Serialized objects of this class will not be compatible with future Swing releases.
MetalIconFactory.FolderIcon16() - Constructor for class javax.swing.plaf.metal.MetalIconFactory.FolderIcon16
MetalIconFactory.PaletteCloseIcon - Class in javax.swing.plaf.metal
Defines an icon for Palette close
MetalIconFactory.PaletteCloseIcon() - Constructor for class javax.swing.plaf.metal.MetalIconFactory.PaletteCloseIcon
MetalIconFactory.TreeControlIcon - Class in javax.swing.plaf.metal
警告： Serialized objects of this class will not be compatible with future Swing releases.
MetalIconFactory.TreeControlIcon(boolean) - Constructor for class javax.swing.plaf.metal.MetalIconFactory.TreeControlIcon
MetalIconFactory.TreeFolderIcon - Class in javax.swing.plaf.metal
警告： Serialized objects of this class will not be compatible with future Swing releases.
MetalIconFactory.TreeFolderIcon() - Constructor for class javax.swing.plaf.metal.MetalIconFactory.TreeFolderIcon
MetalIconFactory.TreeLeafIcon - Class in javax.swing.plaf.metal
MetalIconFactory.TreeLeafIcon() - Constructor for class javax.swing.plaf.metal.MetalIconFactory.TreeLeafIcon
MetalInternalFrameTitlePane - Class in javax.swing.plaf.metal
Class that manages a JLF title bar
MetalInternalFrameTitlePane(JInternalFrame) - Constructor for class javax.swing.plaf.metal.MetalInternalFrameTitlePane
MetalInternalFrameUI - Class in javax.swing.plaf.metal
Metal implementation of JInternalFrame.
MetalInternalFrameUI(JInternalFrame) - Constructor for class javax.swing.plaf.metal.MetalInternalFrameUI
MetalLabelUI - Class in javax.swing.plaf.metal
A Windows L&F implementation of LabelUI.
MetalLabelUI() - Constructor for class javax.swing.plaf.metal.MetalLabelUI
metalLabelUI - Static variable in class javax.swing.plaf.metal.MetalLabelUI
The default MetalLabelUI instance.
MetalLookAndFeel - Class in javax.swing.plaf.metal
The Java Look and Feel, otherwise known as Metal.
MetalLookAndFeel() - Constructor for class javax.swing.plaf.metal.MetalLookAndFeel
MetalMenuBarUI - Class in javax.swing.plaf.metal
Metal implementation of MenuBarUI.
MetalMenuBarUI() - Constructor for class javax.swing.plaf.metal.MetalMenuBarUI
MetalPopupMenuSeparatorUI - Class in javax.swing.plaf.metal
A Metal L&F implementation of PopupMenuSeparatorUI.
MetalPopupMenuSeparatorUI() - Constructor for class javax.swing.plaf.metal.MetalPopupMenuSeparatorUI
MetalProgressBarUI - Class in javax.swing.plaf.metal
The Metal implementation of ProgressBarUI.
MetalProgressBarUI() - Constructor for class javax.swing.plaf.metal.MetalProgressBarUI
MetalRadioButtonUI - Class in javax.swing.plaf.metal
RadioButtonUI implementation for MetalRadioButtonUI
MetalRadioButtonUI() - Constructor for class javax.swing.plaf.metal.MetalRadioButtonUI
MetalRootPaneUI - Class in javax.swing.plaf.metal
Provides the metal look and feel implementation of RootPaneUI.
MetalRootPaneUI() - Constructor for class javax.swing.plaf.metal.MetalRootPaneUI
MetalScrollBarUI - Class in javax.swing.plaf.metal
Implementation of ScrollBarUI for the Metal Look and Feel
MetalScrollBarUI() - Constructor for class javax.swing.plaf.metal.MetalScrollBarUI
MetalScrollButton - Class in javax.swing.plaf.metal
JButton object for Metal scrollbar arrows.
MetalScrollButton(int, int, boolean) - Constructor for class javax.swing.plaf.metal.MetalScrollButton
MetalScrollPaneUI - Class in javax.swing.plaf.metal
A Metal L&F implementation of ScrollPaneUI.
MetalScrollPaneUI() - Constructor for class javax.swing.plaf.metal.MetalScrollPaneUI
MetalSeparatorUI - Class in javax.swing.plaf.metal
A Metal L&F implementation of SeparatorUI.
MetalSeparatorUI() - Constructor for class javax.swing.plaf.metal.MetalSeparatorUI
MetalSliderUI - Class in javax.swing.plaf.metal
A Java L&F implementation of SliderUI.
MetalSliderUI() - Constructor for class javax.swing.plaf.metal.MetalSliderUI
MetalSliderUI.MetalPropertyListener - Class in javax.swing.plaf.metal
MetalSliderUI.MetalPropertyListener() - Constructor for class javax.swing.plaf.metal.MetalSliderUI.MetalPropertyListener
MetalSplitPaneUI - Class in javax.swing.plaf.metal
Metal split pane.
MetalSplitPaneUI() - Constructor for class javax.swing.plaf.metal.MetalSplitPaneUI
MetalTabbedPaneUI - Class in javax.swing.plaf.metal
The Metal subclass of BasicTabbedPaneUI.
MetalTabbedPaneUI() - Constructor for class javax.swing.plaf.metal.MetalTabbedPaneUI
MetalTabbedPaneUI.TabbedPaneLayout - Class in javax.swing.plaf.metal
This inner class is marked "public" due to a compiler bug.
MetalTabbedPaneUI.TabbedPaneLayout() - Constructor for class javax.swing.plaf.metal.MetalTabbedPaneUI.TabbedPaneLayout
MetalTextFieldUI - Class in javax.swing.plaf.metal
Basis of a look and feel for a JTextField.
MetalTextFieldUI() - Constructor for class javax.swing.plaf.metal.MetalTextFieldUI
MetalTheme - Class in javax.swing.plaf.metal
MetalTheme provides the color palette and fonts used by the Java Look and Feel.
MetalTheme() - Constructor for class javax.swing.plaf.metal.MetalTheme
MetalToggleButtonUI - Class in javax.swing.plaf.metal
MetalToggleButton implementation
MetalToggleButtonUI() - Constructor for class javax.swing.plaf.metal.MetalToggleButtonUI
MetalToolBarUI - Class in javax.swing.plaf.metal
A Metal Look and Feel implementation of ToolBarUI.
MetalToolBarUI() - Constructor for class javax.swing.plaf.metal.MetalToolBarUI
MetalToolBarUI.MetalContainerListener - Class in javax.swing.plaf.metal
MetalToolBarUI.MetalContainerListener() - Constructor for class javax.swing.plaf.metal.MetalToolBarUI.MetalContainerListener
MetalToolBarUI.MetalDockingListener - Class in javax.swing.plaf.metal
MetalToolBarUI.MetalDockingListener(JToolBar) - Constructor for class javax.swing.plaf.metal.MetalToolBarUI.MetalDockingListener
MetalToolBarUI.MetalRolloverListener - Class in javax.swing.plaf.metal
MetalToolBarUI.MetalRolloverListener() - Constructor for class javax.swing.plaf.metal.MetalToolBarUI.MetalRolloverListener
MetalToolTipUI - Class in javax.swing.plaf.metal
A Metal L&F extension of BasicToolTipUI.
MetalToolTipUI() - Constructor for class javax.swing.plaf.metal.MetalToolTipUI
MetalTreeUI - Class in javax.swing.plaf.metal
The metal look and feel implementation of TreeUI.
MetalTreeUI() - Constructor for class javax.swing.plaf.metal.MetalTreeUI
MetaMessage - Class in javax.sound.midi
A MetaMessage is a MidiMessage that is not meaningful to synthesizers, but that can be stored in a MIDI file and interpreted by a sequencer program.
MetaMessage() - Constructor for class javax.sound.midi.MetaMessage
Constructs a new MetaMessage.
MetaMessage(int, byte[], int) - Constructor for class javax.sound.midi.MetaMessage
Constructs a new MetaMessage and sets the message parameters.
MetaMessage(byte[]) - Constructor for class javax.sound.midi.MetaMessage
Constructs a new MetaMessage.
Method - Class in java.lang.reflect
A Method provides information about, and access to, a single method on a class or interface.
方法 - Variable in class java.net.HttpURLConnection
The HTTP method (GET,POST,PUT,etc.).
方法 - Static variable in class javax.swing.text.html.HTML.Attribute
方法 - Static variable in class javax.xml.transform.OutputKeys
method = "xml" | "html" | "text" | expanded name.
METHOD_ATTRIBUTE_PFX - Static variable in interface java.util.jar.Pack200.Packer
When concatenated with a method attribute name, indicates the format of that attribute.
MethodDescriptor - Class in java.beans
A MethodDescriptor describes a particular method that a Java Bean supports for external access from other components.
MethodDescriptor(Method) - Constructor for class java.beans.MethodDescriptor
Constructs a MethodDescriptor from a Method.
MethodDescriptor(Method, ParameterDescriptor[]) - Constructor for class java.beans.MethodDescriptor
Constructs a MethodDescriptor from a Method providing descriptive information for each of the method's parameters.
MethodHandle - Class in java.lang.invoke
A method handle is a typed, directly executable reference to an underlying method, constructor, field, or similar low-level operation, with optional transformations of arguments or return values.
MethodHandles - Class in java.lang.invoke
This class consists exclusively of static methods that operate on or return method handles.
MethodHandles.Lookup - Class in java.lang.invoke
A lookup object is a factory for creating method handles, when the creation requires access checking.
methodModifiers() - Static method in class java.lang.reflect.修饰符
Return an int value OR-ing together the source language modifiers that can be applied to a method.
methodsIn(Iterable<? extends Element>) - Static method in class javax.lang.model.util.ElementFilter
Returns a list of methods in elements.
methodsIn(Set<? extends Element>) - Static method in class javax.lang.model.util.ElementFilter
Returns a set of methods in elements.
MethodType - Class in java.lang.invoke
A method type represents the arguments and return type accepted and returned by a method handle, or the arguments and return type passed and expected by a method handle caller.
methodType(Class<?>, Class<?>[]) - Static method in class java.lang.invoke.MethodType
Finds or creates an instance of the given method type.
methodType(Class<?>, List<Class<?>>) - Static method in class java.lang.invoke.MethodType
Finds or creates a method type with the given components.
methodType(Class<?>, Class<?>, Class<?>...) - Static method in class java.lang.invoke.MethodType
Finds or creates a method type with the given components.
methodType(Class<?>) - Static method in class java.lang.invoke.MethodType
Finds or creates a method type with the given components.
methodType(Class<?>, Class<?>) - Static method in class java.lang.invoke.MethodType
Finds or creates a method type with the given components.
methodType(Class<?>, MethodType) - Static method in class java.lang.invoke.MethodType
Finds or creates a method type with the given components.
metrics - Variable in class javax.swing.text.PlainView
Font metrics for the current font.
MGF1ParameterSpec - Class in java.security.spec
This class specifies the set of parameters used with mask generation function MGF1 in OAEP Padding and RSA-PSS signature scheme, as defined in the PKCS #1 v2.1 standard.
MGF1ParameterSpec(String) - Constructor for class java.security.spec.MGF1ParameterSpec
Constructs a parameter set for mask generation function MGF1 as defined in the PKCS #1 standard.
MICROPHONE - Static variable in class javax.sound.sampled.Port.Info
A type of port that gets audio from a built-in microphone or a microphone jack.
microsecondLength - Variable in class javax.sound.midi.MidiFileFormat
The duration of the MIDI file in microseconds.
MIDDLE - Static variable in class javax.print.attribute.standard.MediaTray
The middle input tray in the printe.
MIDI_SYNC - Static variable in class javax.sound.midi.Sequencer.SyncMode
A master or slave synchronization mode that specifies the use of MIDI clock messages.
MIDI_TIME_CODE - Static variable in class javax.sound.midi.Sequencer.SyncMode
A master or slave synchronization mode that specifies the use of MIDI Time Code.
MIDI_TIME_CODE - Static variable in class javax.sound.midi.ShortMessage
Status byte for MIDI Time Code Quarter Frame message (0xF1, or 241).
MidiChannel - Interface in javax.sound.midi
A MidiChannel object represents a single MIDI channel.
MidiDevice - Interface in javax.sound.midi
MidiDevice is the base interface for all MIDI devices.
MidiDevice.Info - Class in javax.sound.midi
A MidiDevice.Info object contains assorted data about a MidiDevice, including its name, the company who created it, and descriptive text.
MidiDevice.Info(String, String, String, String) - Constructor for class javax.sound.midi.MidiDevice.Info
Constructs a device info object.
MidiDeviceProvider - Class in javax.sound.midi.spi
A MidiDeviceProvider is a factory or provider for a particular type of MIDI device.
MidiDeviceProvider() - Constructor for class javax.sound.midi.spi.MidiDeviceProvider
MidiDeviceReceiver - Interface in javax.sound.midi
MidiDeviceReceiver is a Receiver which represents a MIDI input connector of a MidiDevice (see MidiDevice.getReceiver()).
MidiDeviceTransmitter - Interface in javax.sound.midi
MidiDeviceTransmitter is a Transmitter which represents a MIDI input connector of a MidiDevice (see MidiDevice.getTransmitter()).
MidiEvent - Class in javax.sound.midi
MIDI events contain a MIDI message and a corresponding time-stamp expressed in ticks, and can represent the MIDI event information stored in a MIDI file or a Sequence object.
MidiEvent(MidiMessage, long) - Constructor for class javax.sound.midi.MidiEvent
Constructs a new MidiEvent.
MidiFileFormat - Class in javax.sound.midi
A MidiFileFormat object encapsulates a MIDI file's type, as well as its length and timing information.
MidiFileFormat(int, float, int, int, long) - Constructor for class javax.sound.midi.MidiFileFormat
Constructs a MidiFileFormat.
MidiFileFormat(int, float, int, int, long, Map<String, Object>) - Constructor for class javax.sound.midi.MidiFileFormat
Construct a MidiFileFormat with a set of properties.
MidiFileReader - Class in javax.sound.midi.spi
A MidiFileReader supplies MIDI file-reading services.
MidiFileReader() - Constructor for class javax.sound.midi.spi.MidiFileReader
MidiFileWriter - Class in javax.sound.midi.spi
A MidiFileWriter supplies MIDI file-writing services.
MidiFileWriter() - Constructor for class javax.sound.midi.spi.MidiFileWriter
MidiMessage - Class in javax.sound.midi
MidiMessage is the base class for MIDI messages.
MidiMessage(byte[]) - Constructor for class javax.sound.midi.MidiMessage
Constructs a new MidiMessage.
MidiSystem - Class in javax.sound.midi
The MidiSystem class provides access to the installed MIDI system resources, including devices such as synthesizers, sequencers, and MIDI input and output ports.
MidiUnavailableException - Exception in javax.sound.midi
A MidiUnavailableException is thrown when a requested MIDI component cannot be opened or created because it is unavailable.
MidiUnavailableException() - Constructor for exception javax.sound.midi.MidiUnavailableException
Constructs a MidiUnavailableException that has null as its error detail message.
MidiUnavailableException(String) - Constructor for exception javax.sound.midi.MidiUnavailableException
Constructs a MidiUnavailableException with the specified detail message.
MILLISECOND - Static variable in class java.text.DateFormat.Field
Constant identifying the millisecond field.
MILLISECOND - Static variable in class java.util.Calendar
Field number for get and set indicating the millisecond within the second.
MILLISECOND_FIELD - Static variable in class java.text.DateFormat
Useful constant for MILLISECOND field alignment.
MimeHeader - Class in javax.xml.soap
An object that stores a MIME header name and its value.
MimeHeader(String, String) - Constructor for class javax.xml.soap.MimeHeader
Constructs a MimeHeader object initialized with the given name and value.
MimeHeaders - Class in javax.xml.soap
A container for MimeHeader objects, which represent the MIME headers present in a MIME part of a message.
MimeHeaders() - Constructor for class javax.xml.soap.MimeHeaders
Constructs a default MimeHeaders object initialized with an empty Vector object.
MimeType - Class in javax.activation
A Multipurpose Internet Mail Extension (MIME) type, as defined in RFC 2045 and 2046.
MimeType() - Constructor for class javax.activation.MimeType
Default constructor.
MimeType(String) - Constructor for class javax.activation.MimeType
Constructor that builds a MimeType from a String.
MimeType(String, String) - Constructor for class javax.activation.MimeType
Constructor that builds a MimeType with the given primary and sub type but has an empty parameter list.
MimeTypeParameterList - Class in javax.activation
A parameter list of a MimeType as defined in RFC 2045 and 2046.
MimeTypeParameterList() - Constructor for class javax.activation.MimeTypeParameterList
Default constructor.
MimeTypeParameterList(String) - Constructor for class javax.activation.MimeTypeParameterList
Constructs a new MimeTypeParameterList with the passed in data.
MimeTypeParseException - Exception in java.awt.datatransfer
A class to encapsulate MimeType parsing related exceptions
MimeTypeParseException() - Constructor for exception java.awt.datatransfer.MimeTypeParseException
Constructs a MimeTypeParseException with no specified detail message.
MimeTypeParseException(String) - Constructor for exception java.awt.datatransfer.MimeTypeParseException
Constructs a MimeTypeParseException with the specified detail message.
MimeTypeParseException - Exception in javax.activation
A class to encapsulate MimeType parsing related exceptions.
MimeTypeParseException() - Constructor for exception javax.activation.MimeTypeParseException
Constructs a MimeTypeParseException with no specified detail message.
MimeTypeParseException(String) - Constructor for exception javax.activation.MimeTypeParseException
Constructs a MimeTypeParseException with the specified detail message.
MIMETypes - Variable in class javax.imageio.spi.ImageReaderWriterSpi
An array of strings to be returned from getMIMETypes, initially null.
MimetypesFileTypeMap - Class in javax.activation
This class extends FileTypeMap and provides data typing of files via their file extension.
MimetypesFileTypeMap() - Constructor for class javax.activation.MimetypesFileTypeMap
The default constructor.
MimetypesFileTypeMap(String) - Constructor for class javax.activation.MimetypesFileTypeMap
Construct a MimetypesFileTypeMap with programmatic entries added from the named file.
MimetypesFileTypeMap(InputStream) - Constructor for class javax.activation.MimetypesFileTypeMap
Construct a MimetypesFileTypeMap with programmatic entries added from the InputStream.
min(int, int) - Static method in class java.lang.Math
Returns the smaller of two int values.
min(long, long) - Static method in class java.lang.Math
Returns the smaller of two long values.
min(float, float) - Static method in class java.lang.Math
Returns the smaller of two float values.
min(double, double) - Static method in class java.lang.Math
Returns the smaller of two double values.
min(int, int) - Static method in class java.lang.StrictMath
Returns the smaller of two int values.
min(long, long) - Static method in class java.lang.StrictMath
Returns the smaller of two long values.
min(float, float) - Static method in class java.lang.StrictMath
Returns the smaller of two float values.
min(double, double) - Static method in class java.lang.StrictMath
Returns the smaller of two double values.
min(BigDecimal) - Method in class java.math.BigDecimal
Returns the minimum of this BigDecimal and val.
min(BigInteger) - Method in class java.math.BigInteger
Returns the minimum of this BigInteger and val.
min(Collection<? extends T>) - Static method in class java.util.Collections
Returns the minimum element of the given collection, according to the natural ordering of its elements.
min(Collection<? extends T>, Comparator<? super T>) - Static method in class java.util.Collections
Returns the minimum element of the given collection, according to the order induced by the specified comparator.
MIN_CODE_POINT - Static variable in class java.lang.Character
The minimum value of a Unicode code point, constant U+0000.
MIN_EXPONENT - Static variable in class java.lang.Double
Minimum exponent a normalized double variable may have.
MIN_EXPONENT - Static variable in class java.lang.Float
Minimum exponent a normalized float variable may have.
MIN_HIGH_SURROGATE - Static variable in class java.lang.Character
The minimum value of a Unicode high-surrogate code unit in the UTF-16 encoding, constant '\uD800'.
MIN_LOW_SURROGATE - Static variable in class java.lang.Character
The minimum value of a Unicode low-surrogate code unit in the UTF-16 encoding, constant '\uDC00'.
MIN_NORMAL - Static variable in class java.lang.Double
A constant holding the smallest positive normal value of type double, 2-1022.
MIN_NORMAL - Static variable in class java.lang.Float
A constant holding the smallest positive normal value of type float, 2-126.
MIN_PRIORITY - Static variable in class java.lang.Thread
The minimum priority that a thread can have.
MIN_RADIX - Static variable in class java.lang.Character
The minimum radix available for conversion to and from strings.
MIN_SCROLL - Static variable in class javax.swing.plaf.basic.BasicSliderUI
MIN_SUPPLEMENTARY_CODE_POINT - Static variable in class java.lang.Character
The minimum value of a Unicode supplementary code point, constant U+10000.
MIN_SURROGATE - Static variable in class java.lang.Character
The minimum value of a Unicode surrogate code unit in the UTF-16 encoding, constant '\uD800'.
MIN_TIMEZONE_OFFSET - Static variable in class javax.xml.datatype.DatatypeConstants
W3C XML Schema min timezone offset is +14:00.
MIN_VALUE - Static variable in class java.lang.Byte
A constant holding the minimum value a byte can have, -27.
MIN_VALUE - Static variable in class java.lang.Character
The constant value of this field is the smallest value of type char, '\u0000'.
MIN_VALUE - Static variable in class java.lang.Double
A constant holding the smallest positive nonzero value of type double, 2-1074.
MIN_VALUE - Static variable in class java.lang.Float
A constant holding the smallest positive nonzero value of type float, 2-149.
MIN_VALUE - Static variable in class java.lang.Integer
A constant holding the minimum value an int can have, -231.
MIN_VALUE - Static variable in class java.lang.Long
A constant holding the minimum value a long can have, -263.
MIN_VALUE - Static variable in class java.lang.Short
A constant holding the minimum value a short can have, -215.
MIN_VALUE_FIELD - Static variable in class javax.management.JMX
The name of the minValue field.
MINI_KEY - Static variable in class javax.swing.plaf.nimbus.NimbusStyle
MINI_SCALE - Static variable in class javax.swing.plaf.nimbus.NimbusStyle
minIcon - Variable in class javax.swing.plaf.basic.BasicInternalFrameTitlePane
MinimalHTMLWriter - Class in javax.swing.text.html
MinimalHTMLWriter is a fallback writer used by the HTMLEditorKit to write out HTML for a document that is a not produced by the EditorKit.
MinimalHTMLWriter(Writer, StyledDocument) - Constructor for class javax.swing.text.html.MinimalHTMLWriter
Creates a new MinimalHTMLWriter.
MinimalHTMLWriter(Writer, StyledDocument, int, int) - Constructor for class javax.swing.text.html.MinimalHTMLWriter
Creates a new MinimalHTMLWriter.
minimizeFrame(JInternalFrame) - Method in class javax.swing.DefaultDesktopManager
Restores the frame back to its size and position prior to a maximizeFrame call.
minimizeFrame(JInternalFrame) - Method in interface javax.swing.DesktopManager
Generally, this indicates that the frame should be restored to it's size and position prior to a maximizeFrame() call.
minimizeFrame(JInternalFrame) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI
This method is called when the user wants to minimize the frame.
minimizeKey - Variable in class javax.swing.plaf.basic.BasicDesktopPaneUI
Deprecated.
As of 1.3.
minimum - Variable in class javax.swing.SizeRequirements
The minimum size required.
MinimumHeight - Static variable in class javax.swing.plaf.basic.BasicOptionPaneUI
minimumLayoutSize(Container) - Method in class java.awt.BorderLayout
Determines the minimum size of the target container using this layout manager.
minimumLayoutSize(Container) - Method in class java.awt.CardLayout
Calculates the minimum size for the specified panel.
minimumLayoutSize(Container) - Method in class java.awt.FlowLayout
Returns the minimum dimensions needed to layout the visible components contained in the specified target container.
minimumLayoutSize(Container) - Method in class java.awt.GridBagLayout
Determines the minimum size of the parent container using this grid bag layout.
minimumLayoutSize(Container) - Method in class java.awt.GridLayout
Determines the minimum size of the container argument using this grid layout.
minimumLayoutSize(Container) - Method in interface java.awt.LayoutManager
Calculates the minimum size dimensions for the specified container, given the components it contains.
minimumLayoutSize(Container) - Method in class javax.swing.BoxLayout
Returns the minimum dimensions needed to lay out the components contained in the specified target container.
minimumLayoutSize(Container) - Method in class javax.swing.GroupLayout
Returns the minimum size for the specified container.
minimumLayoutSize(Container) - Method in class javax.swing.JRootPane.RootLayout
Returns the minimum amount of space the layout needs.
minimumLayoutSize(Container) - Method in class javax.swing.JSpinner.DefaultEditor
Returns the minimum size of first (and only) child plus the size of the parents insets.
minimumLayoutSize(Container) - Method in class javax.swing.OverlayLayout
Returns the minimum dimensions needed to lay out the components contained in the specified target container.
minimumLayoutSize(Container) - Method in class javax.swing.plaf.basic.BasicComboBoxUI.ComboBoxLayoutManager
minimumLayoutSize(Container) - Method in class javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout
minimumLayoutSize(Container) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI.InternalFrameLayout
minimumLayoutSize(Container) - Method in class javax.swing.plaf.basic.BasicOptionPaneUI.ButtonAreaLayout
minimumLayoutSize(Container) - Method in class javax.swing.plaf.basic.BasicScrollBarUI
minimumLayoutSize(Container) - Method in class javax.swing.plaf.basic.BasicSplitPaneDivider.DividerLayout
minimumLayoutSize(Container) - Method in class javax.swing.plaf.basic.BasicSplitPaneUI.BasicHorizontalLayoutManager
Returns the minimum size needed to contain the children.
minimumLayoutSize(Container) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI.TabbedPaneLayout
minimumLayoutSize(Container) - Method in class javax.swing.ScrollPaneLayout
The minimum size of a ScrollPane is the size of the insets plus minimum size of the viewport, plus the scrollpane's viewportBorder insets, plus the minimum size of the visible headers, plus the minimum size of the scrollbars whose displayPolicy isn't NEVER.
minimumLayoutSize(Container) - Method in class javax.swing.SpringLayout
minimumLayoutSize(Container) - Method in class javax.swing.ViewportLayout
Returns the minimum dimensions needed to layout the components contained in the specified target container.
minimumSize() - Method in class java.awt.Component
Deprecated.
As of JDK version 1.1, replaced by getMinimumSize().
minimumSize() - Method in class java.awt.Container
Deprecated.
As of JDK version 1.1, replaced by getMinimumSize().
minimumSize(int) - Method in class java.awt.List
Deprecated.
As of JDK version 1.1, replaced by getMinimumSize(int).
minimumSize() - Method in class java.awt.List
Deprecated.
As of JDK version 1.1, replaced by getMinimumSize().
minimumSize(int, int) - Method in class java.awt.TextArea
Deprecated.
As of JDK version 1.1, replaced by getMinimumSize(int, int).
minimumSize() - Method in class java.awt.TextArea
Deprecated.
As of JDK version 1.1, replaced by getMinimumSize().
minimumSize(int) - Method in class java.awt.TextField
Deprecated.
As of JDK version 1.1, replaced by getMinimumSize(int).
minimumSize() - Method in class java.awt.TextField
Deprecated.
As of JDK version 1.1, replaced by getMinimumSize().
minimumSize - Variable in class javax.swing.plaf.basic.BasicOptionPaneUI
minimumThumbSize - Variable in class javax.swing.plaf.basic.BasicScrollBarUI
MinimumWidth - Static variable in class javax.swing.plaf.basic.BasicOptionPaneUI
minIndex - Variable in class javax.imageio.ImageReader
The smallest valid index for reading, initially 0.
minor - Variable in exception org.omg.CORBA.SystemException
The CORBA Exception minor code.
minor_version - Variable in class org.omg.IOP.Encoding
The minor version of this Encoding format.
minorRequirementChange(AsyncBoxView.ChildState) - Method in class javax.swing.text.AsyncBoxView
Requirements changed along the minor axis.
minorTickSpacing - Variable in class javax.swing.JSlider
The number of values between the minor tick marks -- the smaller marks that occur between the major tick marks.
minProgressivePass - Variable in class javax.imageio.ImageReadParam
The minimum index of a progressive pass to read from the source.
MINSIZE - Static variable in class java.awt.GridBagLayout
The smallest grid that can be laid out by the grid bag layout.
minTabWidth - Variable in class javax.swing.plaf.metal.MetalTabbedPaneUI
MINUS - Static variable in class javax.management.Query
A code representing the Query.minus(javax.management.ValueExp, javax.management.ValueExp) expression.
minus(ValueExp, ValueExp) - Static method in class javax.management.Query
Returns a binary expression representing the difference between two numeric values.
minus(Spring) - Static method in class javax.swing.Spring
Returns -s: a spring running in the opposite direction to s.
MINUTE - Static variable in class java.text.DateFormat.Field
Constant identifying the minute field.
MINUTE - Static variable in class java.util.Calendar
Field number for get and set indicating the minute within the hour.
MINUTE_FIELD - Static variable in class java.text.DateFormat
Useful constant for MINUTE field alignment.
MINUTES - Static variable in class javax.xml.datatype.DatatypeConstants
A constant that represents the minutes field.
minWidth - Variable in class javax.swing.table.TableColumn
The minimum width of the column.
minX - Variable in class java.awt.image.Raster
The X coordinate of the upper-left pixel of this Raster.
minY - Variable in class java.awt.image.Raster
The Y coordinate of the upper-left pixel of this Raster.
MirroredTypeException - Exception in javax.lang.model.type
Thrown when an application attempts to access the 类 object corresponding to a TypeMirror.
MirroredTypeException(TypeMirror) - Constructor for exception javax.lang.model.type.MirroredTypeException
Constructs a new MirroredTypeException for the specified type.
MirroredTypesException - Exception in javax.lang.model.type
Thrown when an application attempts to access a sequence of 类 objects each corresponding to a TypeMirror.
MirroredTypesException(List<? extends TypeMirror>) - Constructor for exception javax.lang.model.type.MirroredTypesException
Constructs a new MirroredTypesException for the specified types.
MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Miscellaneous Mathematical Symbols-A" Unicode character block.
MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Miscellaneous Mathematical Symbols-B" Unicode character block.
MISCELLANEOUS_SYMBOLS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Miscellaneous Symbols" Unicode character block.
MISCELLANEOUS_SYMBOLS_AND_ARROWS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Miscellaneous Symbols and Arrows" Unicode character block.
MISCELLANEOUS_SYMBOLS_AND_PICTOGRAPHS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Miscellaneous Symbols And Pictographs" Unicode character block.
MISCELLANEOUS_TECHNICAL - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Miscellaneous Technical" Unicode character block.
missing_node - Static variable in class org.omg.CosNaming.NamingContextPackage.NotFoundReason
MissingFormatArgumentException - Exception in java.util
Unchecked exception thrown when there is a format specifier which does not have a corresponding argument or if an argument index refers to an argument that does not exist.
MissingFormatArgumentException(String) - Constructor for exception java.util.MissingFormatArgumentException
Constructs an instance of this class with the unmatched format specifier.
MissingFormatWidthException - Exception in java.util
Unchecked exception thrown when the format width is required.
MissingFormatWidthException(String) - Constructor for exception java.util.MissingFormatWidthException
Constructs an instance of this class with the specified format specifier.
MissingResourceException - Exception in java.util
Signals that a resource is missing.
MissingResourceException(String, String, String) - Constructor for exception java.util.MissingResourceException
Constructs a MissingResourceException with the specified information.
Mixer - Interface in javax.sound.sampled
A mixer is an audio device with one or more lines.
Mixer.Info - Class in javax.sound.sampled
The Mixer.Info class represents information about an audio mixer, including the product's name, version, and vendor, along with a textual description.
Mixer.Info(String, String, String, String) - Constructor for class javax.sound.sampled.Mixer.Info
Constructs a mixer's info object, passing it the given textual information.
MixerProvider - Class in javax.sound.sampled.spi
A provider or factory for a particular mixer type.
MixerProvider() - Constructor for class javax.sound.sampled.spi.MixerProvider
mkdir() - Method in class java.io.File
Creates the directory named by this abstract pathname.
mkdirs() - Method in class java.io.File
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories.
MLet - Class in javax.management.loading
Allows you to instantiate and register one or several MBeans in the MBean server coming from a remote URL.
MLet() - Constructor for class javax.management.loading.MLet
Constructs a new MLet using the default delegation parent ClassLoader.
MLet(URL[]) - Constructor for class javax.management.loading.MLet
Constructs a new MLet for the specified URLs using the default delegation parent ClassLoader.
MLet(URL[], ClassLoader) - Constructor for class javax.management.loading.MLet
Constructs a new MLet for the given URLs.
MLet(URL[], ClassLoader, URLStreamHandlerFactory) - Constructor for class javax.management.loading.MLet
Constructs a new MLet for the specified URLs, parent class loader, and URLStreamHandlerFactory.
MLet(URL[], boolean) - Constructor for class javax.management.loading.MLet
Constructs a new MLet for the specified URLs using the default delegation parent ClassLoader.
MLet(URL[], ClassLoader, boolean) - Constructor for class javax.management.loading.MLet
Constructs a new MLet for the given URLs.
MLet(URL[], ClassLoader, URLStreamHandlerFactory, boolean) - Constructor for class javax.management.loading.MLet
Constructs a new MLet for the specified URLs, parent class loader, and URLStreamHandlerFactory.
MLetContent - Class in javax.management.loading
This class represents the contents of the MLET tag.
MLetContent(URL, Map<String, String>, List<String>, List<String>) - Constructor for class javax.management.loading.MLetContent
Creates an MLet instance initialized with attributes read from an MLET tag in an MLet text file.
MLetMBean - Interface in javax.management.loading
Exposes the remote management interface of the MLet MBean.
MM - Static variable in class javax.print.attribute.Size2DSyntax
Value to indicate units of millimeters (mm).
MM - Static variable in class javax.print.attribute.standard.MediaPrintableArea
Value to indicate units of millimeters (mm).
mnemonic - Variable in class javax.swing.DefaultButtonModel
The button's mnemonic.
MNEMONIC_CHANGED_PROPERTY - Static variable in class javax.swing.AbstractButton
Identifies a change to the button's mnemonic.
MNEMONIC_KEY - Static variable in interface javax.swing.Action
The key used for storing an Integer that corresponds to one of the KeyEvent key codes.
mod(BigInteger) - Method in class java.math.BigInteger
Returns a BigInteger whose value is (this mod m).
MODAL - Static variable in class javax.accessibility.AccessibleState
Indicates something must be done with this object before the user can interact with an object in a different window.
MODAL_LAYER - Static variable in class javax.swing.JLayeredPane
Convenience object defining the Modal layer.
modCount - Variable in class java.util.AbstractList
The number of times this list has been structurally modified.
mode - Variable in class org.omg.Dynamic.Parameter
MODE_ASYNCHRONOUS - Static variable in interface org.w3c.dom.ls.DOMImplementationLS
Create an asynchronous LSParser.
MODE_COPY_FROM_METADATA - Static variable in class javax.imageio.ImageWriteParam
A constant value that may be passed into methods such as setTilingMode, setProgressiveMode, or setCompressionMode to enable that feature for future writes.
MODE_DEFAULT - Static variable in class javax.imageio.ImageWriteParam
A constant value that may be passed into methods such as setTilingMode, setProgressiveMode, and setCompressionMode to enable that feature for future writes.
MODE_DISABLED - Static variable in class javax.imageio.ImageWriteParam
A constant value that may be passed into methods such as setTilingMode, setProgressiveMode, and setCompressionMode to disable a feature for future writes.
MODE_EXPLICIT - Static variable in class javax.imageio.ImageWriteParam
A constant value that may be passed into methods such as setTilingMode or setCompressionMode to enable a feature for future writes.
MODE_SYNCHRONOUS - Static variable in interface org.w3c.dom.ls.DOMImplementationLS
Create a synchronous LSParser.
model - Variable in class javax.swing.AbstractButton
The data model that determines the button's state.
model - Variable in class javax.swing.JProgressBar
The object that holds the data for the progress bar.
model - Variable in class javax.swing.JScrollBar
The model that represents the scrollbar's minimum, maximum, extent (aka "visibleAmount") and current value.
model - Variable in class javax.swing.JTabbedPane
The default selection model
MODEL - Static variable in interface javax.swing.text.html.parser.DTDConstants
MODEL_CHANGED_PROPERTY - Static variable in class javax.swing.AbstractButton
Identifies a change in the button model.
ModelAttribute - Static variable in class javax.swing.text.StyleConstants
Attribute used to identify the model for embedded objects that have a model view separation.
modelChanged - Static variable in class javax.swing.plaf.basic.BasicListUI
modelChanged() - Method in class javax.swing.plaf.basic.BasicTextUI
Flags model changes.
modelIndex - Variable in class javax.swing.table.TableColumn
The index of the column in the model which is to be displayed by this TableColumn.
modelListener - Variable in class javax.swing.plaf.basic.BasicScrollBarUI
ModelMBean - Interface in javax.management.modelmbean
This interface must be implemented by the ModelMBeans.
ModelMBeanAttributeInfo - Class in javax.management.modelmbean
The ModelMBeanAttributeInfo object describes an attribute of the ModelMBean.
ModelMBeanAttributeInfo(String, String, Method, Method) - Constructor for class javax.management.modelmbean.ModelMBeanAttributeInfo
Constructs a ModelMBeanAttributeInfo object with a default descriptor.
ModelMBeanAttributeInfo(String, String, Method, Method, Descriptor) - Constructor for class javax.management.modelmbean.ModelMBeanAttributeInfo
Constructs a ModelMBeanAttributeInfo object.
ModelMBeanAttributeInfo(String, String, String, boolean, boolean, boolean) - Constructor for class javax.management.modelmbean.ModelMBeanAttributeInfo
Constructs a ModelMBeanAttributeInfo object with a default descriptor.
ModelMBeanAttributeInfo(String, String, String, boolean, boolean, boolean, Descriptor) - Constructor for class javax.management.modelmbean.ModelMBeanAttributeInfo
Constructs a ModelMBeanAttributeInfo object.
ModelMBeanAttributeInfo(ModelMBeanAttributeInfo) - Constructor for class javax.management.modelmbean.ModelMBeanAttributeInfo
Constructs a new ModelMBeanAttributeInfo object from this ModelMBeanAttributeInfo Object.
ModelMBeanConstructorInfo - Class in javax.management.modelmbean
The ModelMBeanConstructorInfo object describes a constructor of the ModelMBean.
ModelMBeanConstructorInfo(String, Constructor<?>) - Constructor for class javax.management.modelmbean.ModelMBeanConstructorInfo
Constructs a ModelMBeanConstructorInfo object with a default descriptor.
ModelMBeanConstructorInfo(String, Constructor<?>, Descriptor) - Constructor for class javax.management.modelmbean.ModelMBeanConstructorInfo
Constructs a ModelMBeanConstructorInfo object.
ModelMBeanConstructorInfo(String, String, MBeanParameterInfo[]) - Constructor for class javax.management.modelmbean.ModelMBeanConstructorInfo
Constructs a ModelMBeanConstructorInfo object with a default descriptor.
ModelMBeanConstructorInfo(String, String, MBeanParameterInfo[], Descriptor) - Constructor for class javax.management.modelmbean.ModelMBeanConstructorInfo
Constructs a ModelMBeanConstructorInfo object.
ModelMBeanInfo - Interface in javax.management.modelmbean
This interface is implemented by the ModelMBeanInfo for every ModelMBean.
ModelMBeanInfoSupport - Class in javax.management.modelmbean
This class represents the meta data for ModelMBeans.
ModelMBeanInfoSupport(ModelMBeanInfo) - Constructor for class javax.management.modelmbean.ModelMBeanInfoSupport
Constructs a ModelMBeanInfoSupport which is a duplicate of the given ModelMBeanInfo.
ModelMBeanInfoSupport(String, String, ModelMBeanAttributeInfo[], ModelMBeanConstructorInfo[], ModelMBeanOperationInfo[], ModelMBeanNotificationInfo[]) - Constructor for class javax.management.modelmbean.ModelMBeanInfoSupport
Creates a ModelMBeanInfoSupport with the provided information, but the descriptor is a default.
ModelMBeanInfoSupport(String, String, ModelMBeanAttributeInfo[], ModelMBeanConstructorInfo[], ModelMBeanOperationInfo[], ModelMBeanNotificationInfo[], Descriptor) - Constructor for class javax.management.modelmbean.ModelMBeanInfoSupport
Creates a ModelMBeanInfoSupport with the provided information and the descriptor given in parameter.
ModelMBeanNotificationBroadcaster - Interface in javax.management.modelmbean
This interface must be implemented by the ModelMBeans.
ModelMBeanNotificationInfo - Class in javax.management.modelmbean
The ModelMBeanNotificationInfo object describes a notification emitted by a ModelMBean.
ModelMBeanNotificationInfo(String[], String, String) - Constructor for class javax.management.modelmbean.ModelMBeanNotificationInfo
Constructs a ModelMBeanNotificationInfo object with a default descriptor.
ModelMBeanNotificationInfo(String[], String, String, Descriptor) - Constructor for class javax.management.modelmbean.ModelMBeanNotificationInfo
Constructs a ModelMBeanNotificationInfo object.
ModelMBeanNotificationInfo(ModelMBeanNotificationInfo) - Constructor for class javax.management.modelmbean.ModelMBeanNotificationInfo
Constructs a new ModelMBeanNotificationInfo object from this ModelMBeanNotfication Object.
ModelMBeanOperationInfo - Class in javax.management.modelmbean
The ModelMBeanOperationInfo object describes a management operation of the ModelMBean.
ModelMBeanOperationInfo(String, Method) - Constructor for class javax.management.modelmbean.ModelMBeanOperationInfo
Constructs a ModelMBeanOperationInfo object with a default descriptor.
ModelMBeanOperationInfo(String, Method, Descriptor) - Constructor for class javax.management.modelmbean.ModelMBeanOperationInfo
Constructs a ModelMBeanOperationInfo object.
ModelMBeanOperationInfo(String, String, MBeanParameterInfo[], String, int) - Constructor for class javax.management.modelmbean.ModelMBeanOperationInfo
Constructs a ModelMBeanOperationInfo object with a default descriptor.
ModelMBeanOperationInfo(String, String, MBeanParameterInfo[], String, int, Descriptor) - Constructor for class javax.management.modelmbean.ModelMBeanOperationInfo
Constructs a ModelMBeanOperationInfo object.
ModelMBeanOperationInfo(ModelMBeanOperationInfo) - Constructor for class javax.management.modelmbean.ModelMBeanOperationInfo
Constructs a new ModelMBeanOperationInfo object from this ModelMBeanOperation Object.
modelStructureChanged() - Method in class javax.swing.DefaultRowSorter
Invoked when the underlying model structure has completely changed.
modelStructureChanged() - Method in class javax.swing.RowSorter
Invoked when the underlying model structure has completely changed.
modelToView(JTextComponent, int) - Method in class javax.swing.plaf.basic.BasicTextUI
Converts the given location in the model to a place in the view coordinate system.
modelToView(JTextComponent, int, Position.Bias) - Method in class javax.swing.plaf.basic.BasicTextUI
Converts the given location in the model to a place in the view coordinate system.
modelToView(JTextComponent, int) - Method in class javax.swing.plaf.multi.MultiTextUI
Invokes the modelToView method on each UI handled by this object.
modelToView(JTextComponent, int, Position.Bias) - Method in class javax.swing.plaf.multi.MultiTextUI
Invokes the modelToView method on each UI handled by this object.
modelToView(JTextComponent, int) - Method in class javax.swing.plaf.TextUI
Converts the given location in the model to a place in the view coordinate system.
modelToView(JTextComponent, int, Position.Bias) - Method in class javax.swing.plaf.TextUI
Converts the given location in the model to a place in the view coordinate system.
modelToView(int, Shape, Position.Bias) - Method in class javax.swing.text.AsyncBoxView
Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
modelToView(int, Shape, Position.Bias) - Method in class javax.swing.text.BoxView
Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
modelToView(int, Shape, Position.Bias) - Method in class javax.swing.text.ComponentView
Provides a mapping from the coordinate space of the model to that of the view.
modelToView(int, Shape, Position.Bias) - Method in class javax.swing.text.CompositeView
Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
modelToView(int, Position.Bias, int, Position.Bias, Shape) - Method in class javax.swing.text.CompositeView
Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
modelToView(int, Shape, Position.Bias) - Method in class javax.swing.text.FieldView
Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
modelToView(GlyphView, int, Position.Bias, Shape) - Method in class javax.swing.text.GlyphView.GlyphPainter
Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
modelToView(int, Shape, Position.Bias) - Method in class javax.swing.text.GlyphView
Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
modelToView(int, Shape, Position.Bias) - Method in class javax.swing.text.html.ImageView
Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
modelToView(int, Shape, Position.Bias) - Method in class javax.swing.text.IconView
Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
modelToView(int) - Method in class javax.swing.text.JTextComponent
Converts the given location in the model to a place in the view coordinate system.
modelToView(int, Shape, Position.Bias) - Method in class javax.swing.text.PasswordView
Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
modelToView(int, Shape, Position.Bias) - Method in class javax.swing.text.PlainView
Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it.
modelToView(int, Shape, Position.Bias) - Method in class javax.swing.text.View
Provides a mapping, for a given character, from the document model coordinate space to the view coordinate space.
modelToView(int, Position.Bias, int, Position.Bias, Shape) - Method in class javax.swing.text.View
Provides a mapping, for a given region, from the document model coordinate space to the view coordinate space.
modelToView(int, Shape) - Method in class javax.swing.text.View
Deprecated.
MODIFICATION - Static variable in interface org.w3c.dom.events.MutationEvent
The Attr was modified in place.
MODIFICATION_TIME - Static variable in interface java.util.jar.Pack200.Packer
If this property is set to the special string Pack200.Packer.LATEST, the packer will attempt to determine the latest modification time, among all the available entries in the original archive or the latest modification time of all the available entries in each segment.
ModificationItem - Class in javax.naming.directory
This class represents a modification item.
ModificationItem(int, Attribute) - Constructor for class javax.naming.directory.ModificationItem
Creates a new instance of ModificationItem.
修饰符 - Class in java.lang.reflect
The Modifier class provides static methods and constants to decode class and member access modifiers.
Modifier() - Constructor for class java.lang.reflect.修饰符
修饰符 - Enum in javax.lang.model.element
Represents a modifier on a program element such as a class, method, or field.
修饰符 - Variable in class javax.swing.text.html.parser.AttributeList
MODIFIER_LETTER - Static variable in class java.lang.Character
General category "Lm" in the Unicode specification.
MODIFIER_SYMBOL - Static variable in class java.lang.Character
General category "Sk" in the Unicode specification.
MODIFIER_TONE_LETTERS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Modifier Tone Letters" Unicode character block.
modifiers - Variable in class java.awt.Event
The state of the modifier keys.
modifyAttributes(Name, int, Attributes) - Method in interface javax.naming.directory.DirContext
Modifies the attributes associated with a named object.
modifyAttributes(String, int, Attributes) - Method in interface javax.naming.directory.DirContext
Modifies the attributes associated with a named object.
modifyAttributes(Name, ModificationItem[]) - Method in interface javax.naming.directory.DirContext
Modifies the attributes associated with a named object using an ordered list of modifications.
modifyAttributes(String, ModificationItem[]) - Method in interface javax.naming.directory.DirContext
Modifies the attributes associated with a named object using an ordered list of modifications.
modifyAttributes(String, int, Attributes) - Method in class javax.naming.directory.InitialDirContext
modifyAttributes(Name, int, Attributes) - Method in class javax.naming.directory.InitialDirContext
modifyAttributes(String, ModificationItem[]) - Method in class javax.naming.directory.InitialDirContext
modifyAttributes(Name, ModificationItem[]) - Method in class javax.naming.directory.InitialDirContext
modInverse(BigInteger) - Method in class java.math.BigInteger
Returns a BigInteger whose value is (this-1 mod m).
modPow(BigInteger, BigInteger) - Method in class java.math.BigInteger
Returns a BigInteger whose value is (thisexponent mod m).
MONARCH - Static variable in class java.awt.PageAttributes.MediaType
An alias for MONARCH_ENVELOPE.
MONARCH_ENVELOPE - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for Monarch Envelope, 3 7/8 x 7 1/2 in.
MONARCH_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSize.Other
Specifies the Monarch envelope size, 3.87 inch by 7.5 inch.
MONARCH_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSizeName
monarch envelope size .
MONDAY - Static variable in class java.util.Calendar
Value of the Calendar.DAY_OF_WEEK field indicating Monday.
MONGOLIAN - Static variable in class java.awt.font.NumericShaper
Identifies the MONGOLIAN range and decimal base.
MONGOLIAN - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Mongolian" Unicode character block.
Monitor - Class in javax.management.monitor
Defines the part common to all monitor MBeans.
Monitor() - Constructor for class javax.management.monitor.Monitor
MonitorInfo - Class in java.lang.management
Information about an object monitor lock.
MonitorInfo(String, int, int, StackTraceElement) - Constructor for class java.lang.management.MonitorInfo
Construct a MonitorInfo object.
MonitorMBean - Interface in javax.management.monitor
Exposes the remote management interface of monitor MBeans.
MonitorNotification - Class in javax.management.monitor
Provides definitions of the notifications sent by monitor MBeans.
MonitorSettingException - Exception in javax.management.monitor
Exception thrown by the monitor when a monitor setting becomes invalid while the monitor is running.
MonitorSettingException() - Constructor for exception javax.management.monitor.MonitorSettingException
Default constructor.
MonitorSettingException(String) - Constructor for exception javax.management.monitor.MonitorSettingException
Constructor that allows an error message to be specified.
MONOCHROME - Static variable in class java.awt.PageAttributes.ColorType
The ColorType instance to use for specifying monochrome printing.
MONOCHROME - Static variable in class javax.print.attribute.standard.Chromaticity
Monochrome printing.
MONOSPACED - Static variable in class java.awt.Font
A String constant for the canonical family name of the logical font "Monospaced".
MONTH - Static variable in class java.text.DateFormat.Field
Constant identifying the month field.
MONTH - Static variable in class java.util.Calendar
Field number for get and set indicating the month.
MONTH_FIELD - Static variable in class java.text.DateFormat
Useful constant for MONTH field alignment.
MONTHS - Static variable in class javax.xml.datatype.DatatypeConstants
A constant that represents the months field.
MORE_THAN_MAX_ROLE_DEGREE - Static variable in class javax.management.relation.RoleStatus
Problem type when trying to set a role value with more ObjectNames than the maximum expected cardinality.
MOUSE_CLICKED - Static variable in class java.awt.event.MouseEvent
The "mouse clicked" event.
MOUSE_DOWN - Static variable in class java.awt.Event
The user has pressed the mouse button.
MOUSE_DRAG - Static variable in class java.awt.Event
The user has moved the mouse with a button pressed.
MOUSE_DRAGGED - Static variable in class java.awt.event.MouseEvent
The "mouse dragged" event.
MOUSE_ENTER - Static variable in class java.awt.Event
The mouse has entered a component.
MOUSE_ENTERED - Static variable in class java.awt.event.MouseEvent
The "mouse entered" event.
MOUSE_EVENT_MASK - Static variable in class java.awt.AWTEvent
The event mask for selecting mouse events.
MOUSE_EXIT - Static variable in class java.awt.Event
The mouse has exited a component.
MOUSE_EXITED - Static variable in class java.awt.event.MouseEvent
The "mouse exited" event.
MOUSE_FIRST - Static variable in class java.awt.event.MouseEvent
The first number in the range of ids used for mouse events.
MOUSE_LAST - Static variable in class java.awt.event.MouseEvent
The last number in the range of ids used for mouse events.
MOUSE_MOTION_EVENT_MASK - Static variable in class java.awt.AWTEvent
The event mask for selecting mouse motion events.
MOUSE_MOVE - Static variable in class java.awt.Event
The mouse has moved with no button pressed.
MOUSE_MOVED - Static variable in class java.awt.event.MouseEvent
The "mouse moved" event.
MOUSE_OVER - Static variable in interface javax.swing.plaf.synth.SynthConstants
Primary state indicating the mouse is over the region.
MOUSE_PRESSED - Static variable in class java.awt.event.MouseEvent
The "mouse pressed" event.
MOUSE_RELEASED - Static variable in class java.awt.event.MouseEvent
The "mouse released" event.
MOUSE_UP - Static variable in class java.awt.Event
The user has released the mouse button.
MOUSE_WHEEL - Static variable in class java.awt.event.MouseEvent
The "mouse wheel" event.
MOUSE_WHEEL_EVENT_MASK - Static variable in class java.awt.AWTEvent
The event mask for selecting mouse wheel events.
MouseAdapter - Class in java.awt.event
An abstract adapter class for receiving mouse events.
MouseAdapter() - Constructor for class java.awt.event.MouseAdapter
mouseClicked(MouseEvent) - Method in class java.awt.AWTEventMulticaster
Handles the mouseClicked event by invoking the mouseClicked methods on listener-a and listener-b.
mouseClicked(MouseEvent) - Method in class java.awt.dnd.MouseDragGestureRecognizer
Invoked when the mouse has been clicked on a component.
mouseClicked(MouseEvent) - Method in class java.awt.event.MouseAdapter
Invoked when the mouse button has been clicked (pressed and released) on a component.
mouseClicked(MouseEvent) - Method in interface java.awt.event.MouseListener
Invoked when the mouse button has been clicked (pressed and released) on a component.
mouseClicked(MouseEvent) - Method in class javax.swing.plaf.basic.BasicButtonListener
mouseClicked(MouseEvent) - Method in class javax.swing.plaf.basic.BasicFileChooserUI.DoubleClickListener
mouseClicked(MouseEvent) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI.BorderListener
mouseClicked(MouseEvent) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI.GlassPaneDispatcher
mouseClicked(MouseEvent) - Method in class javax.swing.plaf.basic.BasicListUI.MouseInputHandler
mouseClicked(MouseEvent) - Method in class javax.swing.plaf.basic.BasicMenuItemUI.MouseInputHandler
mouseClicked(MouseEvent) - Method in class javax.swing.plaf.basic.BasicMenuUI.MouseInputHandler
mouseClicked(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTableHeaderUI.MouseInputHandler
mouseClicked(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTableUI.MouseInputHandler
mouseClicked(MouseEvent) - Method in class javax.swing.plaf.basic.BasicToolBarUI.DockingListener
mouseClicked(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI.MouseInputHandler
mouseClicked(MouseEvent) - Method in class javax.swing.text.DefaultCaret
Called when the mouse is clicked.
mouseClicked(MouseEvent) - Method in class javax.swing.text.html.HTMLEditorKit.LinkController
Called for a mouse click event.
mouseDown(Event, int, int) - Method in class java.awt.Component
Deprecated.
As of JDK version 1.1, replaced by processMouseEvent(MouseEvent).
mouseDrag(Event, int, int) - Method in class java.awt.Component
Deprecated.
As of JDK version 1.1, replaced by processMouseMotionEvent(MouseEvent).
mouseDragged(MouseEvent) - Method in class java.awt.AWTEventMulticaster
Handles the mouseDragged event by invoking the mouseDragged methods on listener-a and listener-b.
mouseDragged(MouseEvent) - Method in class java.awt.dnd.MouseDragGestureRecognizer
Invoked when a mouse button is pressed on a component.
mouseDragged(MouseEvent) - Method in class java.awt.event.MouseAdapter
Invoked when a mouse button is pressed on a component and then dragged.
mouseDragged(MouseEvent) - Method in class java.awt.event.MouseMotionAdapter
Invoked when a mouse button is pressed on a component and then dragged.
mouseDragged(MouseEvent) - Method in interface java.awt.event.MouseMotionListener
Invoked when a mouse button is pressed on a component and then dragged.
mouseDragged(MouseEvent) - Method in class javax.swing.plaf.basic.BasicButtonListener
mouseDragged(MouseEvent) - Method in class javax.swing.plaf.basic.BasicComboPopup.InvocationMouseMotionHandler
mouseDragged(MouseEvent) - Method in class javax.swing.plaf.basic.BasicDesktopIconUI.MouseInputHandler
mouseDragged(MouseEvent) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI.BorderListener
mouseDragged(MouseEvent) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI.GlassPaneDispatcher
mouseDragged(MouseEvent) - Method in class javax.swing.plaf.basic.BasicListUI.MouseInputHandler
mouseDragged(MouseEvent) - Method in class javax.swing.plaf.basic.BasicMenuItemUI.MouseInputHandler
mouseDragged(MouseEvent) - Method in class javax.swing.plaf.basic.BasicMenuUI.MouseInputHandler
Invoked when a mouse button is pressed on the menu and then dragged.
mouseDragged(MouseEvent) - Method in class javax.swing.plaf.basic.BasicScrollBarUI.TrackListener
Set the models value to the position of the thumb's top of Vertical scrollbar, or the left/right of Horizontal scrollbar in left-to-right/right-to-left scrollbar relative to the origin of the track.
mouseDragged(MouseEvent) - Method in class javax.swing.plaf.basic.BasicSliderUI.TrackListener
Set the models value to the position of the top/left of the thumb relative to the origin of the track.
mouseDragged(MouseEvent) - Method in class javax.swing.plaf.basic.BasicSplitPaneDivider.MouseHandler
If dragger is not null it is messaged with continueDrag.
mouseDragged(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTableHeaderUI.MouseInputHandler
mouseDragged(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTableUI.MouseInputHandler
mouseDragged(MouseEvent) - Method in class javax.swing.plaf.basic.BasicToolBarUI.DockingListener
mouseDragged(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI.MouseHandler
mouseDragged(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI.MouseInputHandler
mouseDragged(MouseEvent) - Method in class javax.swing.plaf.metal.MetalToolBarUI.MetalDockingListener
mouseDragged(MouseEvent) - Method in class javax.swing.text.DefaultCaret
Moves the caret position according to the mouse pointer's current location.
mouseDragged(MouseEvent) - Method in class javax.swing.text.html.HTMLEditorKit.LinkController
mouseDragged(MouseEvent) - Method in class javax.swing.ToolTipManager
Called when the mouse is pressed and dragged.
MouseDragGestureRecognizer - Class in java.awt.dnd
This abstract subclass of DragGestureRecognizer defines a DragGestureRecognizer for mouse-based gestures.
MouseDragGestureRecognizer(DragSource, Component, int, DragGestureListener) - Constructor for class java.awt.dnd.MouseDragGestureRecognizer
Construct a new MouseDragGestureRecognizer given the DragSource for the Component c, the Component to observe, the action(s) permitted for this drag operation, and the DragGestureListener to notify when a drag gesture is detected.
MouseDragGestureRecognizer(DragSource, Component, int) - Constructor for class java.awt.dnd.MouseDragGestureRecognizer
Construct a new MouseDragGestureRecognizer given the DragSource for the Component c, the Component to observe, and the action(s) permitted for this drag operation.
MouseDragGestureRecognizer(DragSource, Component) - Constructor for class java.awt.dnd.MouseDragGestureRecognizer
Construct a new MouseDragGestureRecognizer given the DragSource for the Component c, and the Component to observe.
MouseDragGestureRecognizer(DragSource) - Constructor for class java.awt.dnd.MouseDragGestureRecognizer
Construct a new MouseDragGestureRecognizer given the DragSource for the Component.
mouseEnter(Event, int, int) - Method in class java.awt.Component
Deprecated.
As of JDK version 1.1, replaced by processMouseEvent(MouseEvent).
mouseEntered(MouseEvent) - Method in class java.awt.AWTEventMulticaster
Handles the mouseEntered event by invoking the mouseEntered methods on listener-a and listener-b.
mouseEntered(MouseEvent) - Method in class java.awt.dnd.MouseDragGestureRecognizer
Invoked when the mouse enters a component.
mouseEntered(MouseEvent) - Method in class java.awt.event.MouseAdapter
Invoked when the mouse enters a component.
mouseEntered(MouseEvent) - Method in interface java.awt.event.MouseListener
Invoked when the mouse enters a component.
mouseEntered(MouseEvent) - Method in class javax.swing.plaf.basic.BasicButtonListener
mouseEntered(MouseEvent) - Method in class javax.swing.plaf.basic.BasicFileChooserUI.DoubleClickListener
The JList used for representing the files is created by subclasses, but the selection is monitored in this class.
mouseEntered(MouseEvent) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI.BorderListener
mouseEntered(MouseEvent) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI.GlassPaneDispatcher
mouseEntered(MouseEvent) - Method in class javax.swing.plaf.basic.BasicListUI.MouseInputHandler
mouseEntered(MouseEvent) - Method in class javax.swing.plaf.basic.BasicMenuItemUI.MouseInputHandler
mouseEntered(MouseEvent) - Method in class javax.swing.plaf.basic.BasicMenuUI.MouseInputHandler
Invoked when the cursor enters the menu.
mouseEntered(MouseEvent) - Method in class javax.swing.plaf.basic.BasicSplitPaneDivider.MouseHandler
Invoked when the mouse enters a component.
mouseEntered(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTableHeaderUI.MouseInputHandler
mouseEntered(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTableUI.MouseInputHandler
mouseEntered(MouseEvent) - Method in class javax.swing.plaf.basic.BasicToolBarUI.DockingListener
mouseEntered(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI.MouseInputHandler
mouseEntered(MouseEvent) - Method in class javax.swing.text.DefaultCaret
Called when the mouse enters a region.
mouseEntered(MouseEvent) - Method in class javax.swing.ToolTipManager
Called when the mouse enters the region of a component.
MouseEvent - Class in java.awt.event
An event which indicates that a mouse action occurred in a component.
MouseEvent(Component, int, long, int, int, int, int, boolean, int) - Constructor for class java.awt.event.MouseEvent
Constructs a MouseEvent object with the specified source component, type, time, modifiers, coordinates, click count, popupTrigger flag, and button number.
MouseEvent(Component, int, long, int, int, int, int, boolean) - Constructor for class java.awt.event.MouseEvent
Constructs a MouseEvent object with the specified source component, type, modifiers, coordinates, click count, and popupTrigger flag.
MouseEvent(Component, int, long, int, int, int, int, int, int, boolean, int) - Constructor for class java.awt.event.MouseEvent
Constructs a MouseEvent object with the specified source component, type, time, modifiers, coordinates, absolute coordinates, click count, popupTrigger flag, and button number.
MouseEvent - Interface in org.w3c.dom.events
The MouseEvent interface provides specific contextual information associated with Mouse events.
mouseExit(Event, int, int) - Method in class java.awt.Component
Deprecated.
As of JDK version 1.1, replaced by processMouseEvent(MouseEvent).
mouseExited(MouseEvent) - Method in class java.awt.AWTEventMulticaster
Handles the mouseExited event by invoking the mouseExited methods on listener-a and listener-b.
mouseExited(MouseEvent) - Method in class java.awt.dnd.MouseDragGestureRecognizer
Invoked when the mouse exits a component.
mouseExited(MouseEvent) - Method in class java.awt.event.MouseAdapter
Invoked when the mouse exits a component.
mouseExited(MouseEvent) - Method in interface java.awt.event.MouseListener
Invoked when the mouse exits a component.
mouseExited(MouseEvent) - Method in class javax.swing.plaf.basic.BasicButtonListener
mouseExited(MouseEvent) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI.BorderListener
mouseExited(MouseEvent) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI.GlassPaneDispatcher
mouseExited(MouseEvent) - Method in class javax.swing.plaf.basic.BasicListUI.MouseInputHandler
mouseExited(MouseEvent) - Method in class javax.swing.plaf.basic.BasicMenuItemUI.MouseInputHandler
mouseExited(MouseEvent) - Method in class javax.swing.plaf.basic.BasicMenuUI.MouseInputHandler
mouseExited(MouseEvent) - Method in class javax.swing.plaf.basic.BasicScrollBarUI.TrackListener
Invoked when the mouse exits the scrollbar.
mouseExited(MouseEvent) - Method in class javax.swing.plaf.basic.BasicSplitPaneDivider.MouseHandler
Invoked when the mouse exits a component.
mouseExited(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTableHeaderUI.MouseInputHandler
mouseExited(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTableUI.MouseInputHandler
mouseExited(MouseEvent) - Method in class javax.swing.plaf.basic.BasicToolBarUI.DockingListener
mouseExited(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI.MouseInputHandler
mouseExited(MouseEvent) - Method in class javax.swing.text.DefaultCaret
Called when the mouse exits a region.
mouseExited(MouseEvent) - Method in class javax.swing.ToolTipManager
Called when the mouse exits the region of a component.
mouseHandler - Variable in class javax.swing.plaf.basic.BasicSplitPaneDivider
Handles mouse events from both this class, and the split pane.
MouseInfo - Class in java.awt
MouseInfo provides methods for getting information about the mouse, such as mouse pointer location and the number of mouse buttons.
MouseInputAdapter - Class in javax.swing.event
An empty implementation of the MouseInputListener interface, provided as a convenience to simplify the task of creating listeners, by extending and implementing only the methods of interest.
MouseInputAdapter() - Constructor for class javax.swing.event.MouseInputAdapter
MouseInputListener - Interface in javax.swing.event
A listener implementing all the methods in both the MouseListener and MouseMotionListener interfaces.
mouseInputListener - Variable in class javax.swing.plaf.basic.BasicListUI
mouseInputListener - Variable in class javax.swing.plaf.basic.BasicMenuItemUI
mouseInputListener - Variable in class javax.swing.plaf.basic.BasicTableHeaderUI
mouseInputListener - Variable in class javax.swing.plaf.basic.BasicTableUI
MouseListener - Interface in java.awt.event
The listener interface for receiving "interesting" mouse events (press, release, click, enter, and exit) on a component.
mouseListener - Variable in class javax.swing.plaf.basic.BasicComboPopup
This protected field is implementation specific.
mouseListener - Variable in class javax.swing.plaf.basic.BasicTabbedPaneUI
MouseMotionAdapter - Class in java.awt.event
An abstract adapter class for receiving mouse motion events.
MouseMotionAdapter() - Constructor for class java.awt.event.MouseMotionAdapter
MouseMotionListener - Interface in java.awt.event
The listener interface for receiving mouse motion events on a component.
mouseMotionListener - Variable in class javax.swing.plaf.basic.BasicComboPopup
This protected field is implementation specific.
mouseMove(Event, int, int) - Method in class java.awt.Component
Deprecated.
As of JDK version 1.1, replaced by processMouseMotionEvent(MouseEvent).
mouseMove(int, int) - Method in class java.awt.Robot
Moves mouse pointer to given screen coordinates.
mouseMoved(MouseEvent) - Method in class java.awt.AWTEventMulticaster
Handles the mouseMoved event by invoking the mouseMoved methods on listener-a and listener-b.
mouseMoved(MouseEvent) - Method in class java.awt.dnd.MouseDragGestureRecognizer
Invoked when the mouse button has been moved on a component (with no buttons no down).
mouseMoved(MouseEvent) - Method in class java.awt.event.MouseAdapter
Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.
mouseMoved(MouseEvent) - Method in class java.awt.event.MouseMotionAdapter
Invoked when the mouse button has been moved on a component (with no buttons no down).
mouseMoved(MouseEvent) - Method in interface java.awt.event.MouseMotionListener
Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.
mouseMoved(MouseEvent) - Method in class javax.swing.plaf.basic.BasicButtonListener
mouseMoved(MouseEvent) - Method in class javax.swing.plaf.basic.BasicComboPopup.ListMouseMotionHandler
mouseMoved(MouseEvent) - Method in class javax.swing.plaf.basic.BasicDesktopIconUI.MouseInputHandler
mouseMoved(MouseEvent) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI.BorderListener
mouseMoved(MouseEvent) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI.GlassPaneDispatcher
mouseMoved(MouseEvent) - Method in class javax.swing.plaf.basic.BasicListUI.MouseInputHandler
mouseMoved(MouseEvent) - Method in class javax.swing.plaf.basic.BasicMenuItemUI.MouseInputHandler
mouseMoved(MouseEvent) - Method in class javax.swing.plaf.basic.BasicMenuUI.MouseInputHandler
mouseMoved(MouseEvent) - Method in class javax.swing.plaf.basic.BasicScrollBarUI.TrackListener
mouseMoved(MouseEvent) - Method in class javax.swing.plaf.basic.BasicSliderUI.TrackListener
mouseMoved(MouseEvent) - Method in class javax.swing.plaf.basic.BasicSplitPaneDivider.MouseHandler
Resets the cursor based on the orientation.
mouseMoved(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTableHeaderUI.MouseInputHandler
mouseMoved(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTableUI.MouseInputHandler
mouseMoved(MouseEvent) - Method in class javax.swing.plaf.basic.BasicToolBarUI.DockingListener
mouseMoved(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI.MouseHandler
Invoked when the mouse button has been moved on a component (with no buttons no down).
mouseMoved(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI.MouseInputHandler
mouseMoved(MouseEvent) - Method in class javax.swing.text.DefaultCaret
Called when the mouse is moved.
mouseMoved(MouseEvent) - Method in class javax.swing.text.html.HTMLEditorKit.LinkController
mouseMoved(MouseEvent) - Method in class javax.swing.ToolTipManager
Called when the mouse is moved.
mousePress(int) - Method in class java.awt.Robot
Presses one or more mouse buttons.
mousePressed(MouseEvent) - Method in class java.awt.AWTEventMulticaster
Handles the mousePressed event by invoking the mousePressed methods on listener-a and listener-b.
mousePressed(MouseEvent) - Method in class java.awt.dnd.MouseDragGestureRecognizer
Invoked when a mouse button has been pressed on a Component.
mousePressed(MouseEvent) - Method in class java.awt.event.MouseAdapter
Invoked when a mouse button has been pressed on a component.
mousePressed(MouseEvent) - Method in interface java.awt.event.MouseListener
Invoked when a mouse button has been pressed on a component.
mousePressed(MouseEvent) - Method in class javax.swing.plaf.basic.BasicButtonListener
mousePressed(MouseEvent) - Method in class javax.swing.plaf.basic.BasicComboPopup.InvocationMouseHandler
Responds to mouse-pressed events on the combo box.
mousePressed(MouseEvent) - Method in class javax.swing.plaf.basic.BasicComboPopup.ListMouseHandler
mousePressed(MouseEvent) - Method in class javax.swing.plaf.basic.BasicDesktopIconUI.MouseInputHandler
mousePressed(MouseEvent) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI.BorderListener
mousePressed(MouseEvent) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI.GlassPaneDispatcher
mousePressed(MouseEvent) - Method in class javax.swing.plaf.basic.BasicListUI.MouseInputHandler
mousePressed(MouseEvent) - Method in class javax.swing.plaf.basic.BasicMenuItemUI.MouseInputHandler
mousePressed(MouseEvent) - Method in class javax.swing.plaf.basic.BasicMenuUI.MouseInputHandler
Invoked when the mouse has been clicked on the menu.
mousePressed(MouseEvent) - Method in class javax.swing.plaf.basic.BasicScrollBarUI.ArrowButtonListener
mousePressed(MouseEvent) - Method in class javax.swing.plaf.basic.BasicScrollBarUI.TrackListener
If the mouse is pressed above the "thumb" component then reduce the scrollbars value by one page ("page up"), otherwise increase it by one page.
mousePressed(MouseEvent) - Method in class javax.swing.plaf.basic.BasicSliderUI.TrackListener
If the mouse is pressed above the "thumb" component then reduce the scrollbars value by one page ("page up"), otherwise increase it by one page.
mousePressed(MouseEvent) - Method in class javax.swing.plaf.basic.BasicSplitPaneDivider.MouseHandler
Starts the dragging session by creating the appropriate instance of DragController.
mousePressed(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI.MouseHandler
mousePressed(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTableHeaderUI.MouseInputHandler
mousePressed(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTableUI.MouseInputHandler
mousePressed(MouseEvent) - Method in class javax.swing.plaf.basic.BasicToolBarUI.DockingListener
mousePressed(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI.MouseHandler
Invoked when a mouse button has been pressed on a component.
mousePressed(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI.MouseInputHandler
mousePressed(MouseEvent) - Method in class javax.swing.plaf.metal.MetalToolBarUI.MetalDockingListener
mousePressed(MouseEvent) - Method in class javax.swing.text.DefaultCaret
If button 1 is pressed, this is implemented to request focus on the associated text component, and to set the caret position.
mousePressed(MouseEvent) - Method in class javax.swing.ToolTipManager
Called when the mouse is pressed.
mouseRelease(int) - Method in class java.awt.Robot
Releases one or more mouse buttons.
mouseReleased(MouseEvent) - Method in class java.awt.AWTEventMulticaster
Handles the mouseReleased event by invoking the mouseReleased methods on listener-a and listener-b.
mouseReleased(MouseEvent) - Method in class java.awt.dnd.MouseDragGestureRecognizer
Invoked when a mouse button has been released on a component.
mouseReleased(MouseEvent) - Method in class java.awt.event.MouseAdapter
Invoked when a mouse button has been released on a component.
mouseReleased(MouseEvent) - Method in interface java.awt.event.MouseListener
Invoked when a mouse button has been released on a component.
mouseReleased(MouseEvent) - Method in class javax.swing.plaf.basic.BasicButtonListener
mouseReleased(MouseEvent) - Method in class javax.swing.plaf.basic.BasicComboPopup.InvocationMouseHandler
Responds to the user terminating a click or drag that began on the combo box.
mouseReleased(MouseEvent) - Method in class javax.swing.plaf.basic.BasicComboPopup.ListMouseHandler
mouseReleased(MouseEvent) - Method in class javax.swing.plaf.basic.BasicDesktopIconUI.MouseInputHandler
mouseReleased(MouseEvent) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI.BorderListener
mouseReleased(MouseEvent) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI.GlassPaneDispatcher
mouseReleased(MouseEvent) - Method in class javax.swing.plaf.basic.BasicListUI.MouseInputHandler
mouseReleased(MouseEvent) - Method in class javax.swing.plaf.basic.BasicMenuItemUI.MouseInputHandler
mouseReleased(MouseEvent) - Method in class javax.swing.plaf.basic.BasicMenuUI.MouseInputHandler
Invoked when the mouse has been released on the menu.
mouseReleased(MouseEvent) - Method in class javax.swing.plaf.basic.BasicScrollBarUI.ArrowButtonListener
mouseReleased(MouseEvent) - Method in class javax.swing.plaf.basic.BasicScrollBarUI.TrackListener
mouseReleased(MouseEvent) - Method in class javax.swing.plaf.basic.BasicSliderUI.TrackListener
mouseReleased(MouseEvent) - Method in class javax.swing.plaf.basic.BasicSplitPaneDivider.MouseHandler
If dragger is not null it is messaged with completeDrag.
mouseReleased(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTableHeaderUI.MouseInputHandler
mouseReleased(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTableUI.MouseInputHandler
mouseReleased(MouseEvent) - Method in class javax.swing.plaf.basic.BasicToolBarUI.DockingListener
mouseReleased(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI.MouseHandler
mouseReleased(MouseEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI.MouseInputHandler
mouseReleased(MouseEvent) - Method in class javax.swing.text.DefaultCaret
Called when the mouse is released.
mouseReleased(MouseEvent) - Method in class javax.swing.text.html.FormView.MouseEventListener
mouseUp(Event, int, int) - Method in class java.awt.Component
Deprecated.
As of JDK version 1.1, replaced by processMouseEvent(MouseEvent).
mouseWheel(int) - Method in class java.awt.Robot
Rotates the scroll wheel on wheel-equipped mice.
MouseWheelEvent - Class in java.awt.event
An event which indicates that the mouse wheel was rotated in a component.
MouseWheelEvent(Component, int, long, int, int, int, int, boolean, int, int, int) - Constructor for class java.awt.event.MouseWheelEvent
Constructs a MouseWheelEvent object with the specified source component, type, modifiers, coordinates, scroll type, scroll amount, and wheel rotation.
MouseWheelEvent(Component, int, long, int, int, int, int, int, int, boolean, int, int, int) - Constructor for class java.awt.event.MouseWheelEvent
Constructs a MouseWheelEvent object with the specified source component, type, modifiers, coordinates, absolute coordinates, scroll type, scroll amount, and wheel rotation.
MouseWheelEvent(Component, int, long, int, int, int, int, int, int, boolean, int, int, int, double) - Constructor for class java.awt.event.MouseWheelEvent
Constructs a MouseWheelEvent object with the specified source component, type, modifiers, coordinates, absolute coordinates, scroll type, scroll amount, and wheel rotation.
MouseWheelListener - Interface in java.awt.event
The listener interface for receiving mouse wheel events on a component.
mouseWheelMoved(MouseWheelEvent) - Method in class java.awt.AWTEventMulticaster
Handles the mouseWheelMoved event by invoking the mouseWheelMoved methods on listener-a and listener-b.
mouseWheelMoved(MouseWheelEvent) - Method in class java.awt.event.MouseAdapter
Invoked when the mouse wheel is rotated.
mouseWheelMoved(MouseWheelEvent) - Method in interface java.awt.event.MouseWheelListener
Invoked when the mouse wheel is rotated.
mouseWheelMoved(MouseWheelEvent) - Method in class javax.swing.plaf.basic.BasicScrollPaneUI.MouseWheelHandler
Called when the mouse wheel is rotated while over a JScrollPane.
move(int, int) - Method in class java.awt.Component
Deprecated.
As of JDK version 1.1, replaced by setLocation(int, int).
move(int, int) - Method in class java.awt.Point
Moves this point to the specified location in the (x,y) coordinate plane.
move(int, int) - Method in class java.awt.Rectangle
Deprecated.
As of JDK version 1.1, replaced by setLocation(int, int).
move(Path, Path, CopyOption...) - Static method in class java.nio.file.Files
Move or rename a file to a target file.
move(T, SecureDirectoryStream<T>, T) - Method in interface java.nio.file.SecureDirectoryStream
Move a file from this directory to another directory.
move(Path, Path, CopyOption...) - Method in class java.nio.file.spi.FileSystemProvider
Move or rename a file to a target file.
MOVE - Static variable in class javax.swing.TransferHandler
An int representing a "move" transfer action.
MOVE_CMD - Static variable in class javax.swing.plaf.basic.BasicInternalFrameTitlePane
MOVE_CURSOR - Static variable in class java.awt.Cursor
The move cursor type.
MOVE_CURSOR - Static variable in class java.awt.Frame
Deprecated.
replaced by Cursor.MOVE_CURSOR.
moveAction - Variable in class javax.swing.plaf.basic.BasicInternalFrameTitlePane
moveAndRepaint(JComponent, int, int, int, int) - Method in class javax.swing.plaf.basic.BasicDesktopIconUI.MouseInputHandler
moveCaret(MouseEvent) - Method in class javax.swing.text.DefaultCaret
Tries to move the position of the caret from the coordinates of a mouse event, using viewToModel().
moveCaretPosition(int) - Method in class javax.swing.text.JTextComponent
Moves the caret to a new position, leaving behind a mark defined by the last time setCaretPosition was called.
moveColumn(int, int) - Method in class javax.swing.JTable
Moves the column column to the position currently occupied by the column targetColumn in the view.
moveColumn(int, int) - Method in class javax.swing.table.DefaultTableColumnModel
Moves the column and heading at columnIndex to newIndex.
moveColumn(int, int) - Method in interface javax.swing.table.TableColumnModel
Moves the column and its header at columnIndex to newIndex.
moveDot(int) - Method in interface javax.swing.text.Caret
Moves the caret position (dot) to some other position, leaving behind the mark.
moveDot(int) - Method in class javax.swing.text.DefaultCaret
Moves the caret position to the specified position, with a forward bias.
moveDot(int, Position.Bias) - Method in class javax.swing.text.DefaultCaret
Moves the caret position to the specified position, with the specified bias.
moveDot(int, Position.Bias) - Method in class javax.swing.text.NavigationFilter.FilterBypass
Moves the caret location, bypassing the NavigationFilter.
moveDot(NavigationFilter.FilterBypass, int, Position.Bias) - Method in class javax.swing.text.NavigationFilter
Invoked prior to the Caret moving the dot.
moveLeadSelectionIndex(int) - Method in class javax.swing.DefaultListSelectionModel
Set the lead selection index, leaving all selection values unchanged.
movePointLeft(int) - Method in class java.math.BigDecimal
Returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the left.
movePointRight(int) - Method in class java.math.BigDecimal
Returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the right.
moveRow(int, int, int) - Method in class javax.swing.table.DefaultTableModel
Moves one or more rows from the inclusive range start to end to the to position in the model.
moveTo(double, double) - Method in class java.awt.geom.Path2D.Double
Adds a point to the path by moving to the specified coordinates specified in double precision.
moveTo(double, double) - Method in class java.awt.geom.Path2D.Float
Adds a point to the path by moving to the specified coordinates specified in double precision.
moveTo(float, float) - Method in class java.awt.geom.Path2D.Float
Adds a point to the path by moving to the specified coordinates specified in float precision.
moveTo(double, double) - Method in class java.awt.geom.Path2D
Adds a point to the path by moving to the specified coordinates specified in double precision.
moveToBack() - Method in class javax.swing.JInternalFrame
Convenience method that moves this component to position -1 if its parent is a JLayeredPane.
moveToBack(Component) - Method in class javax.swing.JLayeredPane
Moves the component to the bottom of the components in its current layer (position -1).
moveToCurrentRow() - Method in interface java.sql.ResultSet
Moves the cursor to the remembered cursor position, usually the current row.
moveToFront() - Method in class javax.swing.JInternalFrame
Convenience method that moves this component to position 0 if its parent is a JLayeredPane.
moveToFront(Component) - Method in class javax.swing.JLayeredPane
Moves the component to the top of the components in its current layer (position 0).
moveToInsertRow() - Method in interface java.sql.ResultSet
Moves the cursor to the insert row.
MOVING_TO_PAUSED - Static variable in class javax.print.attribute.standard.PrinterStateReason
Someone has paused the printer, but the device(s) are taking an appreciable time to stop.
MS - Static variable in interface javax.swing.text.html.parser.DTDConstants
MTOM - Annotation Type in javax.xml.ws.soap
This feature represents the use of MTOM with a web service.
MTOMFeature - Class in javax.xml.ws.soap
This feature represents the use of MTOM with a web service.
MTOMFeature() - Constructor for class javax.xml.ws.soap.MTOMFeature
Create an MTOMFeature.
MTOMFeature(boolean) - Constructor for class javax.xml.ws.soap.MTOMFeature
Creates an MTOMFeature.
MTOMFeature(int) - Constructor for class javax.xml.ws.soap.MTOMFeature
Creates an MTOMFeature.
MTOMFeature(boolean, int) - Constructor for class javax.xml.ws.soap.MTOMFeature
Creates an MTOMFeature.
MULTI_LINE - Static variable in class javax.accessibility.AccessibleState
Indicates this (text) object can contain multiple lines of text
MULTI_SELECTION_ENABLED_CHANGED_PROPERTY - Static variable in class javax.swing.JFileChooser
Enables multiple-file selections.
MultiButtonUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine ButtonUIs.
MultiButtonUI() - Constructor for class javax.swing.plaf.multi.MultiButtonUI
MulticastChannel - Interface in java.nio.channels
A network channel that supports Internet Protocol (IP) multicasting.
MulticastSocket - Class in java.net
The multicast datagram socket class is useful for sending and receiving IP multicast packets.
MulticastSocket() - Constructor for class java.net.MulticastSocket
Create a multicast socket.
MulticastSocket(int) - Constructor for class java.net.MulticastSocket
Create a multicast socket and bind it to a specific port.
MulticastSocket(SocketAddress) - Constructor for class java.net.MulticastSocket
Create a MulticastSocket bound to the specified socket address.
MultiColorChooserUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine ColorChooserUIs.
MultiColorChooserUI() - Constructor for class javax.swing.plaf.multi.MultiColorChooserUI
MultiComboBoxUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine ComboBoxUIs.
MultiComboBoxUI() - Constructor for class javax.swing.plaf.multi.MultiComboBoxUI
MultiDesktopIconUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine DesktopIconUIs.
MultiDesktopIconUI() - Constructor for class javax.swing.plaf.multi.MultiDesktopIconUI
MultiDesktopPaneUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine DesktopPaneUIs.
MultiDesktopPaneUI() - Constructor for class javax.swing.plaf.multi.MultiDesktopPaneUI
MultiDoc - Interface in javax.print
Interface MultiDoc specifies the interface for an object that supplies more than one piece of print data for a Print Job.
MultiDocPrintJob - Interface in javax.print
Obtained from a MultiDocPrintService, a MultiDocPrintJob can print a specified collection of documents as a single print job with a set of job attributes.
MultiDocPrintService - Interface in javax.print
Interface MultiPrintService is the factory for a MultiDocPrintJob.
MultiFileChooserUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine FileChooserUIs.
MultiFileChooserUI() - Constructor for class javax.swing.plaf.multi.MultiFileChooserUI
MultiInternalFrameUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine InternalFrameUIs.
MultiInternalFrameUI() - Constructor for class javax.swing.plaf.multi.MultiInternalFrameUI
MultiLabelUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine LabelUIs.
MultiLabelUI() - Constructor for class javax.swing.plaf.multi.MultiLabelUI
MULTILINE - Static variable in class java.util.regex.Pattern
Enables multiline mode.
MultiListUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine ListUIs.
MultiListUI() - Constructor for class javax.swing.plaf.multi.MultiListUI
MultiLookAndFeel - Class in javax.swing.plaf.multi
A multiplexing look and feel that allows more than one UI to be associated with a component at the same time.
MultiLookAndFeel() - Constructor for class javax.swing.plaf.multi.MultiLookAndFeel
MultiMenuBarUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine MenuBarUIs.
MultiMenuBarUI() - Constructor for class javax.swing.plaf.multi.MultiMenuBarUI
MultiMenuItemUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine MenuItemUIs.
MultiMenuItemUI() - Constructor for class javax.swing.plaf.multi.MultiMenuItemUI
MultiOptionPaneUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine OptionPaneUIs.
MultiOptionPaneUI() - Constructor for class javax.swing.plaf.multi.MultiOptionPaneUI
MultiPanelUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine PanelUIs.
MultiPanelUI() - Constructor for class javax.swing.plaf.multi.MultiPanelUI
MultiPixelPackedSampleModel - Class in java.awt.image
The MultiPixelPackedSampleModel class represents one-banded images and can pack multiple one-sample pixels into one data element.
MultiPixelPackedSampleModel(int, int, int, int) - Constructor for class java.awt.image.MultiPixelPackedSampleModel
Constructs a MultiPixelPackedSampleModel with the specified data type, width, height and number of bits per pixel.
MultiPixelPackedSampleModel(int, int, int, int, int, int) - Constructor for class java.awt.image.MultiPixelPackedSampleModel
Constructs a MultiPixelPackedSampleModel with specified data type, width, height, number of bits per pixel, scanline stride and data bit offset.
MULTIPLE - Static variable in class javax.swing.text.html.HTML.Attribute
MULTIPLE_ID - Static variable in class org.omg.PortableServer.IdUniquenessPolicyValue
MULTIPLE_INTERVAL_SELECTION - Static variable in interface javax.swing.ListSelectionModel
A value for the selectionMode property: select one or more contiguous ranges of indices at a time.
MultipleComponentProfileHelper - Class in org.omg.IOP
An array of tagged components, forming a multiple component profile.
MultipleComponentProfileHelper() - Constructor for class org.omg.IOP.MultipleComponentProfileHelper
MultipleComponentProfileHolder - Class in org.omg.IOP
An array of tagged components, forming a multiple component profile.
MultipleComponentProfileHolder() - Constructor for class org.omg.IOP.MultipleComponentProfileHolder
MultipleComponentProfileHolder(TaggedComponent[]) - Constructor for class org.omg.IOP.MultipleComponentProfileHolder
MultipleDocumentHandling - Class in javax.print.attribute.standard
Class MultipleDocumentHandling is a printing attribute class, an enumeration, that controls finishing operations and the placement of one or more print-stream pages into impressions and onto media sheets.
MultipleDocumentHandling(int) - Constructor for class javax.print.attribute.standard.MultipleDocumentHandling
Construct a new multiple document handling enumeration value with the given integer value.
MultipleGradientPaint - Class in java.awt
This is the superclass for Paints which use a multiple color gradient to fill in their raster.
MultipleGradientPaint.ColorSpaceType - Enum in java.awt
The color space in which to perform the gradient interpolation.
MultipleGradientPaint.CycleMethod - Enum in java.awt
The method to use when painting outside the gradient bounds.
MultipleMaster - Interface in java.awt.font
The MultipleMaster interface represents Type 1 Multiple Master fonts.
multiply(BigDecimal) - Method in class java.math.BigDecimal
Returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()).
multiply(BigDecimal, MathContext) - Method in class java.math.BigDecimal
Returns a BigDecimal whose value is (this × multiplicand), with rounding according to the context settings.
multiply(BigInteger) - Method in class java.math.BigInteger
Returns a BigInteger whose value is (this * val).
multiply(int) - Method in class javax.xml.datatype.Duration
Computes a new duration whose value is factor times longer than the value of this duration.
multiply(BigDecimal) - Method in class javax.xml.datatype.Duration
Computes a new duration whose value is factor times longer than the value of this duration.
MultiPopupMenuUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine PopupMenuUIs.
MultiPopupMenuUI() - Constructor for class javax.swing.plaf.multi.MultiPopupMenuUI
MultiProgressBarUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine ProgressBarUIs.
MultiProgressBarUI() - Constructor for class javax.swing.plaf.multi.MultiProgressBarUI
MultiRootPaneUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine RootPaneUIs.
MultiRootPaneUI() - Constructor for class javax.swing.plaf.multi.MultiRootPaneUI
MultiScrollBarUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine ScrollBarUIs.
MultiScrollBarUI() - Constructor for class javax.swing.plaf.multi.MultiScrollBarUI
MultiScrollPaneUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine ScrollPaneUIs.
MultiScrollPaneUI() - Constructor for class javax.swing.plaf.multi.MultiScrollPaneUI
MULTISELECTABLE - Static variable in class javax.accessibility.AccessibleState
Indicates this object allows more than one of its children to be selected at the same time.
MultiSeparatorUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine SeparatorUIs.
MultiSeparatorUI() - Constructor for class javax.swing.plaf.multi.MultiSeparatorUI
MultiSliderUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine SliderUIs.
MultiSliderUI() - Constructor for class javax.swing.plaf.multi.MultiSliderUI
MultiSpinnerUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine SpinnerUIs.
MultiSpinnerUI() - Constructor for class javax.swing.plaf.multi.MultiSpinnerUI
MultiSplitPaneUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine SplitPaneUIs.
MultiSplitPaneUI() - Constructor for class javax.swing.plaf.multi.MultiSplitPaneUI
MultiTabbedPaneUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine TabbedPaneUIs.
MultiTabbedPaneUI() - Constructor for class javax.swing.plaf.multi.MultiTabbedPaneUI
MultiTableHeaderUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine TableHeaderUIs.
MultiTableHeaderUI() - Constructor for class javax.swing.plaf.multi.MultiTableHeaderUI
MultiTableUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine TableUIs.
MultiTableUI() - Constructor for class javax.swing.plaf.multi.MultiTableUI
MultiTextUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine TextUIs.
MultiTextUI() - Constructor for class javax.swing.plaf.multi.MultiTextUI
MultiToolBarUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine ToolBarUIs.
MultiToolBarUI() - Constructor for class javax.swing.plaf.multi.MultiToolBarUI
MultiToolTipUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine ToolTipUIs.
MultiToolTipUI() - Constructor for class javax.swing.plaf.multi.MultiToolTipUI
MultiTreeUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine TreeUIs.
MultiTreeUI() - Constructor for class javax.swing.plaf.multi.MultiTreeUI
MultiViewportUI - Class in javax.swing.plaf.multi
A multiplexing UI used to combine ViewportUIs.
MultiViewportUI() - Constructor for class javax.swing.plaf.multi.MultiViewportUI
MUSICAL_SYMBOLS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Musical Symbols" Unicode character block.
MutableAttributeSet - Interface in javax.swing.text
A generic interface for a mutable collection of unique attributes.
MutableCallSite - Class in java.lang.invoke
A MutableCallSite is a CallSite whose target variable behaves like an ordinary field.
MutableCallSite(MethodType) - Constructor for class java.lang.invoke.MutableCallSite
Creates a blank call site object with the given method type.
MutableCallSite(MethodHandle) - Constructor for class java.lang.invoke.MutableCallSite
Creates a call site object with an initial target method handle.
MutableComboBoxModel - Interface in javax.swing
A mutable version of ComboBoxModel.
MutableTreeNode - Interface in javax.swing.tree
Defines the requirements for a tree node object that can change -- by adding or removing child nodes, or by changing the contents of a user object stored in the node.
mutatesTo(Object, Object) - Method in class java.beans.DefaultPersistenceDelegate
If the number of arguments in the specified constructor is non-zero and the class of oldInstance explicitly declares an "equals" method this method returns the value of oldInstance.equals(newInstance).
mutatesTo(Object, Object) - Method in class java.beans.PersistenceDelegate
Returns true if an equivalent copy of oldInstance may be created by applying a series of statements to newInstance.
MutationEvent - Interface in org.w3c.dom.events
The MutationEvent interface provides specific contextual information associated with Mutation events.
MUTE - Static variable in class javax.sound.sampled.BooleanControl.Type
Represents a control for the mute status of a line.
MXBean - Annotation Type in javax.management
Annotation to mark an interface explicitly as being an MXBean interface, or as not being an MXBean interface.
MXBEAN_FIELD - Static variable in class javax.management.JMX
The name of the mxbean field.
MYANMAR - Static variable in class java.awt.font.NumericShaper
Identifies the MYANMAR range and decimal base.
MYANMAR - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Myanmar" Unicode character block.
MYANMAR_EXTENDED_A - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Myanmar Extended-A" Unicode character block.
myProps - Variable in class javax.naming.InitialContext
The environment associated with this InitialContext.
mySyntax - Variable in class javax.naming.CompoundName
Syntax properties for this compound name.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类


N-Index

请注意：本 java api 1.7Beta 规范不是最终稳定版，未来随着版本的更迭，本规范可能有更新。
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _

N

N - Static variable in class javax.swing.text.html.HTML.Attribute
N_RESIZE_CURSOR - Static variable in class java.awt.Cursor
The north-resize cursor type.
N_RESIZE_CURSOR - Static variable in class java.awt.Frame
Deprecated.
replaced by Cursor.N_RESIZE_CURSOR.
NA_10X13_ENVELOPE - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for North American 10 x 13 in.
NA_10x13_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSize.NA
Specifies the North American 10 inch by 13 inch envelope size.
NA_10X13_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSizeName
10x13 North American envelope size .
NA_10X14_ENVELOPE - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for North American 10 x 14 in.
NA_10x14_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSize.NA
Specifies the North American 10 inch by 14 inch envelope size.
NA_10X14_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSizeName
10x14North American envelope size .
NA_10X15_ENVELOPE - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for North American 10 x 15 in.
NA_10X15_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSize.NA
Specifies the North American 10 inch by 15 inch envelope size.
NA_10X15_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSizeName
10x15 North American envelope size.
NA_5X7 - Static variable in class javax.print.attribute.standard.MediaSize.NA
Specifies the North American 5 inch by 7 inch paper.
NA_5X7 - Static variable in class javax.print.attribute.standard.MediaSizeName
5x7 North American paper.
NA_6X9_ENVELOPE - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for North American 6 x 9 in.
NA_6X9_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSize.NA
Specifies the North American 6 inch by 9 inch envelope size.
NA_6X9_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSizeName
6x9 North American envelope size.
NA_7X9_ENVELOPE - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for North American 7 x 9 in.
NA_7X9_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSize.NA
Specifies the North American 7 inch by 9 inch envelope size.
NA_7X9_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSizeName
7x9 North American envelope size.
NA_8X10 - Static variable in class javax.print.attribute.standard.MediaSize.NA
Specifies the North American 8 inch by 10 inch paper.
NA_8X10 - Static variable in class javax.print.attribute.standard.MediaSizeName
8x10 North American paper.
NA_9X11_ENVELOPE - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for North American 9 x 11 in.
NA_9x11_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSize.NA
Specifies the North American 9 inch by 11 inch envelope size.
NA_9X11_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSizeName
9x11 North American envelope size.
NA_9X12_ENVELOPE - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for North American 9 x 12 in.
NA_9x12_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSize.NA
Specifies the North American 9 inch by 12 inch envelope size.
NA_9X12_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSizeName
9x12 North American envelope size.
NA_LEGAL - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for North American Legal, 8 1/2 x 14 in.
NA_LEGAL - Static variable in class javax.print.attribute.standard.MediaSizeName
legal size .
NA_LETTER - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for North American Letter, 8 1/2 x 11 in.
NA_LETTER - Static variable in class javax.print.attribute.standard.MediaSizeName
letter size.
NA_LETTER_TRANSPARENT - Static variable in class javax.print.attribute.standard.MediaName
letter transparency.
NA_LETTER_WHITE - Static variable in class javax.print.attribute.standard.MediaName
white letter paper.
NA_NUMBER_10_ENVELOPE - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for North American #10 Business Envelope, 4 1/8 x 9 1/2 in.
NA_NUMBER_10_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSize.NA
Specifies the North American Number 10 business envelope size, 4.125 inches by 9.5 inches.
NA_NUMBER_10_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSizeName
number 10 envelope size .
NA_NUMBER_11_ENVELOPE - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for North American #11 Business Envelope, 4 1/2 x 10 3/8 in.
NA_NUMBER_11_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSize.NA
Specifies the North American Number 11 business envelope size, 4.5 inches by 10.375 inches.
NA_NUMBER_11_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSizeName
number 11 envelope size .
NA_NUMBER_12_ENVELOPE - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for North American #12 Business Envelope, 4 3/4 x 11 in.
NA_NUMBER_12_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSize.NA
Specifies the North American Number 12 business envelope size, 4.75 inches by 11 inches.
NA_NUMBER_12_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSizeName
number 12 envelope size .
NA_NUMBER_14_ENVELOPE - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for North American #14 Business Envelope, 5 x 11 1/2 in.
NA_NUMBER_14_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSize.NA
Specifies the North American Number 14 business envelope size, 5 inches by 11.5 inches.
NA_NUMBER_14_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSizeName
number 14 envelope size .
NA_NUMBER_9_ENVELOPE - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for North American #9 Business Envelope, 3 7/8 x 8 7/8 in.
NA_NUMBER_9_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSize.NA
Specifies the North American Number 9 business envelope size, 3.875 inches by 8.875 inches.
NA_NUMBER_9_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSizeName
number 9 envelope size .
name - Variable in class java.awt.Cursor
The user-visible name of the cursor.
name - Variable in class java.awt.Font
The logical name of this Font, as passed to the constructor.
name() - Method in class java.lang.Enum
Returns the name of this enum constant, exactly as declared in its enum declaration.
name() - Method in interface java.net.ProtocolFamily
Returns the name of the protocol family.
name() - Method in interface java.net.SocketOption
Returns the name of the socket option.
name() - Method in class java.nio.charset.Charset
Returns this charset's canonical name.
name() - Method in interface java.nio.file.attribute.AclFileAttributeView
Returns the name of the attribute view.
name() - Method in interface java.nio.file.attribute.AttributeView
Returns the name of the attribute view.
name() - Method in interface java.nio.file.attribute.BasicFileAttributeView
Returns the name of the attribute view.
name() - Method in interface java.nio.file.attribute.DosFileAttributeView
Returns the name of the attribute view.
name() - Method in interface java.nio.file.attribute.FileAttribute
Returns the attribute name.
name() - Method in interface java.nio.file.attribute.FileOwnerAttributeView
Returns the name of the attribute view.
name() - Method in interface java.nio.file.attribute.PosixFileAttributeView
Returns the name of the attribute view.
name() - Method in interface java.nio.file.attribute.UserDefinedFileAttributeView
Returns the name of this attribute view.
name() - Method in class java.nio.file.FileStore
Returns the name of this file store.
name() - Method in interface java.nio.file.WatchEvent.Kind
Returns the name of the event kind.
name() - Method in interface java.nio.file.WatchEvent.Modifier
Returns the name of the modifier.
name - Variable in class java.sql.DriverPropertyInfo
The name of the property.
name() - Method in class java.util.prefs.AbstractPreferences
Implements the name method as per the specification in Preferences.name().
name() - Method in class java.util.prefs.Preferences
Returns this preference node's name, relative to its parent.
Name - Interface in javax.lang.model.element
An immutable sequence of characters.
name - Variable in class javax.management.MBeanFeatureInfo
The name of the feature.
Name - Interface in javax.naming
The Name interface represents a generic name -- an ordered sequence of components.
NAME - Static variable in interface javax.script.ScriptEngine
Reserved key for a named value that identifies the short name of the scripting language.
NAME - Static variable in interface javax.swing.Action
The key used for storing the String name for the action, used for a menu or button.
NAME - Static variable in class javax.swing.text.html.HTML.Attribute
name - Variable in class javax.swing.text.html.parser.AttributeList
name - Variable in class javax.swing.text.html.parser.DTD
NAME - Static variable in interface javax.swing.text.html.parser.DTDConstants
name - Variable in class javax.swing.text.html.parser.Element
name - Variable in class javax.swing.text.html.parser.Entity
name - Variable in class javax.xml.bind.JAXBElement
xml element tag name
Name - Interface in javax.xml.soap
A representation of an XML name.
name() - Method in class org.omg.CORBA.NamedValue
Retrieves the name for this NamedValue object.
name(byte[]) - Method in class org.omg.CORBA.Principal
Deprecated.
Deprecated by CORBA 2.2.
name() - Method in class org.omg.CORBA.Principal
Deprecated.
Deprecated by CORBA 2.2.
name - Variable in class org.omg.CORBA.StructMember
The name of the struct member described by this StructMember object.
name() - Method in class org.omg.CORBA.TypeCode
Retrieves the simple name identifying this TypeCode object within its enclosing scope.
name - Variable in class org.omg.CORBA.UnionMember
The name of the union member described by this UnionMember object.
name - Variable in class org.omg.CORBA.ValueMember
The name of the value member described by this ValueMember object.
name() - Method in interface org.omg.PortableInterceptor.InterceptorOperations
Returns the name of the interceptor.
name - Variable in exception org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName
The name for which there was already an interceptor registered.
name2type(String) - Static method in class javax.swing.text.html.parser.AttributeList
name2type(String) - Static method in class javax.swing.text.html.parser.Element
name2type(String) - Static method in class javax.swing.text.html.parser.Entity
Converts nm string to the corresponding entity type.
NAME_NOT_MN - Static variable in exception org.ietf.jgss.GSSException
Name contains multi-mechanism elements.
NameAlreadyBoundException - Exception in javax.naming
This exception is thrown by methods to indicate that a binding cannot be added because the name is already bound to another object.
NameAlreadyBoundException(String) - Constructor for exception javax.naming.NameAlreadyBoundException
Constructs a new instance of NameAlreadyBoundException using the explanation supplied.
NameAlreadyBoundException() - Constructor for exception javax.naming.NameAlreadyBoundException
Constructs a new instance of NameAlreadyBoundException.
NameAttribute - Static variable in interface javax.swing.text.AttributeSet
Attribute name used to name the collection of attributes.
NameAttribute - Static variable in class javax.swing.text.StyleConstants
Attribute name used to name the collection of attributes.
NameCallback - Class in javax.security.auth.callback
Underlying security services instantiate and pass a NameCallback to the handle method of a CallbackHandler to retrieve name information.
NameCallback(String) - Constructor for class javax.security.auth.callback.NameCallback
Construct a NameCallback with a prompt.
NameCallback(String, String) - Constructor for class javax.security.auth.callback.NameCallback
Construct a NameCallback with a prompt and default name.
NameClassPair - Class in javax.naming
This class represents the object name and class name pair of a binding found in a context.
NameClassPair(String, String) - Constructor for class javax.naming.NameClassPair
Constructs an instance of a NameClassPair given its name and class name.
NameClassPair(String, String, boolean) - Constructor for class javax.naming.NameClassPair
Constructs an instance of a NameClassPair given its name, class name, and whether it is relative to the listing context.
NameComponent - Class in org.omg.CosNaming
org/omg/CosNaming/NameComponent.java .
NameComponent() - Constructor for class org.omg.CosNaming.NameComponent
NameComponent(String, String) - Constructor for class org.omg.CosNaming.NameComponent
NameComponentHelper - Class in org.omg.CosNaming
org/omg/CosNaming/NameComponentHelper.java .
NameComponentHelper() - Constructor for class org.omg.CosNaming.NameComponentHelper
NameComponentHolder - Class in org.omg.CosNaming
org/omg/CosNaming/NameComponentHolder.java .
NameComponentHolder() - Constructor for class org.omg.CosNaming.NameComponentHolder
NameComponentHolder(NameComponent) - Constructor for class org.omg.CosNaming.NameComponentHolder
NamedNodeMap - Interface in org.w3c.dom
Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name.
NamedValue - Class in org.omg.CORBA
An object used in the DII and DSI to describe arguments and return values.
NamedValue() - Constructor for class org.omg.CORBA.NamedValue
NameDynAnyPair - Class in org.omg.DynamicAny
org/omg/DynamicAny/NameDynAnyPair.java .
NameDynAnyPair() - Constructor for class org.omg.DynamicAny.NameDynAnyPair
NameDynAnyPair(String, DynAny) - Constructor for class org.omg.DynamicAny.NameDynAnyPair
NameDynAnyPairHelper - Class in org.omg.DynamicAny
org/omg/DynamicAny/NameDynAnyPairHelper.java .
NameDynAnyPairHelper() - Constructor for class org.omg.DynamicAny.NameDynAnyPairHelper
NameDynAnyPairSeqHelper - Class in org.omg.DynamicAny
org/omg/DynamicAny/NameDynAnyPairSeqHelper.java .
NameDynAnyPairSeqHelper() - Constructor for class org.omg.DynamicAny.NameDynAnyPairSeqHelper
NameHelper - Class in org.omg.CosNaming
A name is a sequence of name components.
NameHelper() - Constructor for class org.omg.CosNaming.NameHelper
NameHolder - Class in org.omg.CosNaming
A name is a sequence of name components.
NameHolder() - Constructor for class org.omg.CosNaming.NameHolder
NameHolder(NameComponent[]) - Constructor for class org.omg.CosNaming.NameHolder
NameList - Interface in org.w3c.dom
The NameList interface provides the abstraction of an ordered collection of parallel pairs of name and namespace values (which could be null values), without defining or constraining how this collection is implemented.
NameNotFoundException - Exception in javax.naming
This exception is thrown when a component of the name cannot be resolved because it is not bound.
NameNotFoundException(String) - Constructor for exception javax.naming.NameNotFoundException
Constructs a new instance of NameNotFoundException using the explanation supplied.
NameNotFoundException() - Constructor for exception javax.naming.NameNotFoundException
Constructs a new instance of NameNotFoundException.
NameParser - Interface in javax.naming
This interface is used for parsing names from a hierarchical namespace.
names - Variable in class javax.imageio.spi.ImageReaderWriterSpi
An array of strings to be returned from getFormatNames, initially null.
NAMES - Static variable in interface javax.swing.text.html.parser.DTDConstants
Namespace - Interface in javax.xml.stream.events
An interface that contains information about a namespace.
NAMESPACE - Static variable in interface javax.xml.stream.XMLStreamConstants
Indicates the event is a namespace declaration
NAMESPACE_ERR - Static variable in exception org.w3c.dom.DOMException
If an attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
NamespaceChangeListener - Interface in javax.naming.event
Specifies the methods that a listener interested in namespace changes must implement.
NamespaceContext - Interface in javax.xml.namespace
Interface for read only XML Namespace context processing.
NamespaceSupport - Class in org.xml.sax.helpers
Encapsulate Namespace logic for use by applications using SAX, or internally by SAX drivers.
NamespaceSupport() - Constructor for class org.xml.sax.helpers.NamespaceSupport
Create a new Namespace support object.
nameUUIDFromBytes(byte[]) - Static method in class java.util.UUID
Static factory to retrieve a type 3 (name based) UUID based on the specified byte array.
NameValuePair - Class in org.omg.CORBA
Associates a name with a value that is an attribute of an IDL struct, and is used in the DynStruct APIs.
NameValuePair() - Constructor for class org.omg.CORBA.NameValuePair
Constructs an empty NameValuePair object.
NameValuePair(String, Any) - Constructor for class org.omg.CORBA.NameValuePair
Constructs a NameValuePair object that associates the given name with the given org.omg.CORBA.Any object.
NameValuePair - Class in org.omg.DynamicAny
org/omg/DynamicAny/NameValuePair.java .
NameValuePair() - Constructor for class org.omg.DynamicAny.NameValuePair
NameValuePair(String, Any) - Constructor for class org.omg.DynamicAny.NameValuePair
NameValuePairHelper - Class in org.omg.CORBA
The Helper for NameValuePair.
NameValuePairHelper() - Constructor for class org.omg.CORBA.NameValuePairHelper
NameValuePairHelper - Class in org.omg.DynamicAny
org/omg/DynamicAny/NameValuePairHelper.java .
NameValuePairHelper() - Constructor for class org.omg.DynamicAny.NameValuePairHelper
NameValuePairSeqHelper - Class in org.omg.DynamicAny
org/omg/DynamicAny/NameValuePairSeqHelper.java .
NameValuePairSeqHelper() - Constructor for class org.omg.DynamicAny.NameValuePairSeqHelper
Naming - Class in java.rmi
The Naming class provides methods for storing and obtaining references to remote objects in a remote object registry.
NamingContext - Interface in org.omg.CosNaming
A naming context is an object that contains a set of name bindings in which each name is unique.
NamingContextExt - Interface in org.omg.CosNaming
NamingContextExt is the extension of NamingContext which contains a set of name bindings in which each name is unique and is part of Interoperable Naming Service.
NamingContextExtHelper - Class in org.omg.CosNaming
NamingContextExt is the extension of NamingContext which contains a set of name bindings in which each name is unique and is part of Interoperable Naming Service.
NamingContextExtHelper() - Constructor for class org.omg.CosNaming.NamingContextExtHelper
NamingContextExtHolder - Class in org.omg.CosNaming
NamingContextExt is the extension of NamingContext which contains a set of name bindings in which each name is unique and is part of Interoperable Naming Service.
NamingContextExtHolder() - Constructor for class org.omg.CosNaming.NamingContextExtHolder
NamingContextExtHolder(NamingContextExt) - Constructor for class org.omg.CosNaming.NamingContextExtHolder
NamingContextExtOperations - Interface in org.omg.CosNaming
NamingContextExt is the extension of NamingContext which contains a set of name bindings in which each name is unique and is part of Interoperable Naming Service.
NamingContextExtPOA - Class in org.omg.CosNaming
NamingContextExt is the extension of NamingContext which contains a set of name bindings in which each name is unique and is part of Interoperable Naming Service.
NamingContextExtPOA() - Constructor for class org.omg.CosNaming.NamingContextExtPOA
NamingContextHelper - Class in org.omg.CosNaming
A naming context is an object that contains a set of name bindings in which each name is unique.
NamingContextHelper() - Constructor for class org.omg.CosNaming.NamingContextHelper
NamingContextHolder - Class in org.omg.CosNaming
A naming context is an object that contains a set of name bindings in which each name is unique.
NamingContextHolder() - Constructor for class org.omg.CosNaming.NamingContextHolder
NamingContextHolder(NamingContext) - Constructor for class org.omg.CosNaming.NamingContextHolder
NamingContextOperations - Interface in org.omg.CosNaming
A naming context is an object that contains a set of name bindings in which each name is unique.
NamingContextPOA - Class in org.omg.CosNaming
A naming context is an object that contains a set of name bindings in which each name is unique.
NamingContextPOA() - Constructor for class org.omg.CosNaming.NamingContextPOA
NamingEnumeration<T> - Interface in javax.naming
This interface is for enumerating lists returned by methods in the javax.naming and javax.naming.directory packages.
NamingEvent - Class in javax.naming.event
This class represents an event fired by a naming/directory service.
NamingEvent(EventContext, int, Binding, Binding, Object) - Constructor for class javax.naming.event.NamingEvent
Constructs an instance of NamingEvent.
NamingException - Exception in javax.naming
This is the superclass of all exceptions thrown by operations in the Context and DirContext interfaces.
NamingException(String) - Constructor for exception javax.naming.NamingException
Constructs a new NamingException with an explanation.
NamingException() - Constructor for exception javax.naming.NamingException
Constructs a new NamingException.
NamingExceptionEvent - Class in javax.naming.event
This class represents an event fired when the procedures/processes used to collect information for notifying listeners of NamingEvents threw a NamingException.
NamingExceptionEvent(EventContext, NamingException) - Constructor for class javax.naming.event.NamingExceptionEvent
Constructs an instance of NamingExceptionEvent using the context in which the NamingException was thrown and the exception that was thrown.
namingExceptionThrown(NamingExceptionEvent) - Method in interface javax.naming.event.NamingListener
Called when a naming exception is thrown while attempting to fire a NamingEvent.
NamingListener - Interface in javax.naming.event
This interface is the root of listener interfaces that handle NamingEvents.
NamingManager - Class in javax.naming.spi
This class contains methods for creating context objects and objects referred to by location information in the naming or directory service.
NamingSecurityException - Exception in javax.naming
This is the superclass of security-related exceptions thrown by operations in the Context and DirContext interfaces.
NamingSecurityException(String) - Constructor for exception javax.naming.NamingSecurityException
Constructs a new instance of NamingSecurityException using the explanation supplied.
NamingSecurityException() - Constructor for exception javax.naming.NamingSecurityException
Constructs a new instance of NamingSecurityException.
NaN - Static variable in class java.lang.Double
A constant holding a Not-a-Number (NaN) value of type double.
NaN - Static variable in class java.lang.Float
A constant holding a Not-a-Number (NaN) value of type float.
nanoTime() - Static method in class java.lang.System
Returns the current value of the running Java Virtual Machine's high-resolution time source, in nanoseconds.
narrow(Object, Class) - Method in interface javax.rmi.CORBA.PortableRemoteObjectDelegate
Delegation call for PortableRemoteObject.narrow(java.lang.Object, java.lang.Class).
narrow(Object, Class) - Static method in class javax.rmi.PortableRemoteObject
Checks to ensure that an object of a remote or abstract interface type can be cast to a desired type.
narrow(Object) - Static method in class org.omg.CORBA.CurrentHelper
narrow(Object) - Static method in class org.omg.CORBA.IDLTypeHelper
narrow(Object) - Static method in class org.omg.CORBA.PolicyHelper
narrow(Object) - Static method in class org.omg.CosNaming.BindingIteratorHelper
narrow(Object) - Static method in class org.omg.CosNaming.NamingContextExtHelper
narrow(Object) - Static method in class org.omg.CosNaming.NamingContextHelper
narrow(Object) - Static method in class org.omg.DynamicAny.DynAnyFactoryHelper
narrow(Object) - Static method in class org.omg.DynamicAny.DynAnyHelper
narrow(Object) - Static method in class org.omg.DynamicAny.DynArrayHelper
narrow(Object) - Static method in class org.omg.DynamicAny.DynEnumHelper
narrow(Object) - Static method in class org.omg.DynamicAny.DynFixedHelper
narrow(Object) - Static method in class org.omg.DynamicAny.DynSequenceHelper
narrow(Object) - Static method in class org.omg.DynamicAny.DynStructHelper
narrow(Object) - Static method in class org.omg.DynamicAny.DynUnionHelper
narrow(Object) - Static method in class org.omg.DynamicAny.DynValueHelper
narrow(Object) - Static method in class org.omg.IOP.CodecFactoryHelper
narrow(Object) - Static method in class org.omg.PortableInterceptor.CurrentHelper
narrow(Object) - Static method in class org.omg.PortableInterceptor.IORInterceptor_3_0Helper
narrow(Object) - Static method in class org.omg.PortableServer.CurrentHelper
narrow(Object) - Static method in class org.omg.PortableServer.POAHelper
narrow(Object) - Static method in class org.omg.PortableServer.ServantActivatorHelper
narrow(Object) - Static method in class org.omg.PortableServer.ServantLocatorHelper
NATIVE - Static variable in class java.awt.JobAttributes.DialogType
The DialogType instance to use for specifying the platform's native print dialog.
NATIVE - Static variable in class java.lang.reflect.修饰符
The int value representing the native modifier.
NATIVE - Static variable in class javax.print.attribute.standard.DialogTypeSelection
nativeImageMetadataFormatClassName - Variable in class javax.imageio.spi.ImageReaderWriterSpi
A String containing the class name of the native stream metadata format supported by this plug-in, initially null.
nativeImageMetadataFormatName - Variable in class javax.imageio.spi.ImageReaderWriterSpi
A String containing the name of the native stream metadata format supported by this plug-in, initially null.
nativeMetadataFormatClassName - Variable in class javax.imageio.metadata.IIOMetadata
The name of the class implementing IIOMetadataFormat and representing the native metadata format, initialized to null and set via the constructor.
nativeMetadataFormatName - Variable in class javax.imageio.metadata.IIOMetadata
The name of the native metadata format for this object, initialized to null and set via the constructor.
nativeOrder() - Static method in class java.nio.ByteOrder
Retrieves the native byte order of the underlying platform.
nativeSQL(String) - Method in interface java.sql.Connection
Converts the given SQL statement into the system's native SQL grammar.
nativeStreamMetadataFormatClassName - Variable in class javax.imageio.spi.ImageReaderWriterSpi
A String containing the class name of the native stream metadata format supported by this plug-in, initially null.
nativeStreamMetadataFormatName - Variable in class javax.imageio.spi.ImageReaderWriterSpi
A String containing the name of the native stream metadata format supported by this plug-in, initially null.
navigableKeySet() - Method in interface java.util.concurrent.ConcurrentNavigableMap
Returns a NavigableSet view of the keys contained in this map.
navigableKeySet() - Method in class java.util.concurrent.ConcurrentSkipListMap
navigableKeySet() - Method in interface java.util.NavigableMap
Returns a NavigableSet view of the keys contained in this map.
navigableKeySet() - Method in class java.util.TreeMap
NavigableMap<K,V> - Interface in java.util
A SortedMap extended with navigation methods returning the closest matches for given search targets.
NavigableSet<E> - Interface in java.util
A SortedSet extended with navigation methods reporting closest matches for given search targets.
navigateFocusedComp(int) - Method in class javax.swing.plaf.basic.BasicToolBarUI
navigateKey - Variable in class javax.swing.plaf.basic.BasicDesktopPaneUI
Deprecated.
As of 1.3.
navigateKey2 - Variable in class javax.swing.plaf.basic.BasicDesktopPaneUI
Deprecated.
As of 1.3.
navigateSelectedTab(int) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI
NavigationFilter - Class in javax.swing.text
NavigationFilter can be used to restrict where the cursor can be positioned.
NavigationFilter() - Constructor for class javax.swing.text.NavigationFilter
NavigationFilter.FilterBypass - Class in javax.swing.text
Used as a way to circumvent calling back into the caret to position the cursor.
NavigationFilter.FilterBypass() - Constructor for class javax.swing.text.NavigationFilter.FilterBypass
NCHAR - Static variable in class java.sql.Types
The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type NCHAR
NClob - Interface in java.sql
The mapping in the JavaTM programming language for the SQL NCLOB type.
NCLOB - Static variable in class java.sql.Types
The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type NCLOB.
ncontext - Static variable in class org.omg.CosNaming.BindingType
nCopies(int, T) - Static method in class java.util.Collections
Returns an immutable list consisting of n copies of the specified object.
NE_RESIZE_CURSOR - Static variable in class java.awt.Cursor
The north-east-resize cursor type.
NE_RESIZE_CURSOR - Static variable in class java.awt.Frame
Deprecated.
replaced by Cursor.NE_RESIZE_CURSOR.
needsCacheFile() - Method in class javax.imageio.spi.ImageInputStreamSpi
Returns true if the ImageInputStream implementation associated with this service provider requires the use of a cache File.
needsCacheFile() - Method in class javax.imageio.spi.ImageOutputStreamSpi
Returns true if the ImageOutputStream implementation associated with this service provider requires the use of a cache File.
needsDictionary() - Method in class java.util.zip.Inflater
Returns true if a preset dictionary is needed for decompression.
needsGui() - Method in class java.beans.beancontext.BeanContextSupport
This method is typically called from the environment in order to determine if the implementor "needs" a GUI.
needsGui() - Method in interface java.beans.Visibility
Determines whether this bean needs a GUI.
needsInput() - Method in class java.util.zip.Deflater
Returns true if the input data buffer is empty and setInput() should be called in order to provide more input.
needsInput() - Method in class java.util.zip.Inflater
Returns true if no data remains in the input buffer.
needsReload(String, Locale, String, ClassLoader, ResourceBundle, long) - Method in class java.util.ResourceBundle.Control
Determines if the expired bundle in the cache needs to be reloaded based on the loading time given by loadTime or some other criteria.
negate() - Method in class java.math.BigDecimal
Returns a BigDecimal whose value is (-this), and whose scale is this.scale().
negate(MathContext) - Method in class java.math.BigDecimal
Returns a BigDecimal whose value is (-this), with rounding according to the context settings.
negate() - Method in class java.math.BigInteger
Returns a BigInteger whose value is (-this).
negate() - Method in class javax.xml.datatype.Duration
Returns a new Duration object whose value is -this.
NEGATIVE_INFINITY - Static variable in class java.lang.Double
A constant holding the negative infinity of type double.
NEGATIVE_INFINITY - Static variable in class java.lang.Float
A constant holding the negative infinity of type float.
NEGATIVE_SCROLL - Static variable in class javax.swing.plaf.basic.BasicSliderUI
NegativeArraySizeException - Exception in java.lang
Thrown if an application tries to create an array with negative size.
NegativeArraySizeException() - Constructor for exception java.lang.NegativeArraySizeException
Constructs a NegativeArraySizeException with no detail message.
NegativeArraySizeException(String) - Constructor for exception java.lang.NegativeArraySizeException
Constructs a NegativeArraySizeException with the specified detail message.
negotiate() - Method in class javax.naming.ldap.StartTlsResponse
Negotiates a TLS session using the default SSL socket factory.
negotiate(SSLSocketFactory) - Method in class javax.naming.ldap.StartTlsResponse
Negotiates a TLS session using an SSL socket factory.
嵌套 - Variable in exception javax.xml.stream.XMLStreamException
NestingKind - Enum in javax.lang.model.element
The nesting kind of a type element.
NetPermission - Class in java.net
This class is for various network permissions.
NetPermission(String) - Constructor for class java.net.NetPermission
Creates a new NetPermission with the specified name.
NetPermission(String, String) - Constructor for class java.net.NetPermission
Creates a new NetPermission object with the specified name.
NetworkChannel - Interface in java.nio.channels
A channel to a network socket.
NetworkInterface - Class in java.net
This class represents a Network Interface made up of a name, and a list of IP addresses assigned to this interface.
networkInterface() - Method in class java.nio.channels.MembershipKey
Returns the network interface for which this membership key was created.
NEVER_UPDATE - Static variable in class javax.swing.text.DefaultCaret
Indicates that the caret should remain at the same absolute position in the document regardless of any document updates, except when the document length becomes less than the current caret position due to removal.
new_context() - Method in class org.omg.CosNaming._NamingContextExtStub
This operation returns a naming context implemented by the same naming server as the context on which the operation was invoked.
new_context() - Method in class org.omg.CosNaming._NamingContextStub
This operation returns a naming context implemented by the same naming server as the context on which the operation was invoked.
new_context() - Method in interface org.omg.CosNaming.NamingContextOperations
This operation returns a naming context implemented by the same naming server as the context on which the operation was invoked.
NEW_TAI_LUE - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "New Tai Lue" Unicode character block.
newAsynchronousFileChannel(Path, Set<? extends OpenOption>, ExecutorService, FileAttribute<?>...) - Method in class java.nio.file.spi.FileSystemProvider
Opens or creates a file for reading and/or writing, returning an asynchronous file channel to access the file.
newAttributes - Variable in class javax.swing.text.DefaultStyledDocument.AttributeUndoableEdit
newAudioClip(URL) - Static method in class java.applet.Applet
Get an audio clip from the given URL.
newBinding - Variable in class javax.naming.event.NamingEvent
Contains information about the object after the change.
newBufferedReader(Path, Charset) - Static method in class java.nio.file.Files
Opens a file for reading, returning a BufferedReader that may be used to read text from the file in an efficient manner.
newBufferedWriter(Path, Charset, OpenOption...) - Static method in class java.nio.file.Files
Opens or creates a file for writing, returning a BufferedWriter that may be used to write text to the file in an efficient manner.
newBuilder() - Static method in class java.nio.file.attribute.AclEntry
Constructs a new builder.
newBuilder(AclEntry) - Static method in class java.nio.file.attribute.AclEntry
Constructs a new builder with the components of an existing ACL entry.
newBundle(String, Locale, String, ClassLoader, boolean) - Method in class java.util.ResourceBundle.Control
Instantiates a resource bundle for the given bundle name of the given format and locale, using the given class loader if necessary.
newByteChannel(Path, Set<? extends OpenOption>, FileAttribute<?>...) - Static method in class java.nio.file.Files
Opens or creates a file, returning a seekable byte channel to access the file.
newByteChannel(Path, OpenOption...) - Static method in class java.nio.file.Files
Opens or creates a file, returning a seekable byte channel to access the file.
newByteChannel(T, Set<? extends OpenOption>, FileAttribute<?>...) - Method in interface java.nio.file.SecureDirectoryStream
Opens or creates a file in this directory, returning a seekable byte channel to access the file.
newByteChannel(Path, Set<? extends OpenOption>, FileAttribute<?>...) - Method in class java.nio.file.spi.FileSystemProvider
Opens or creates a file, returning a seekable byte channel to access the file.
newCachedThreadPool() - Static method in class java.util.concurrent.Executors
Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available.
newCachedThreadPool(ThreadFactory) - Static method in class java.util.concurrent.Executors
Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available, and uses the provided ThreadFactory to create new threads when needed.
newCall(RemoteObject, Operation[], int, long) - Method in interface java.rmi.server.RemoteRef
Deprecated.
1.2 style stubs no longer use this method. Instead of using a sequence of method calls on the stub's the remote reference (newCall, invoke, and done), a stub uses a single method, invoke(Remote, Method, Object[], int), on the remote reference to carry out parameter marshalling, remote method executing and unmarshalling of the return value.
newCanonicalizationMethod(String, C14NMethodParameterSpec) - Method in class javax.xml.crypto.dsig.XMLSignatureFactory
Creates a CanonicalizationMethod for the specified algorithm URI and parameters.
newCanonicalizationMethod(String, XMLStructure) - Method in class javax.xml.crypto.dsig.XMLSignatureFactory
Creates a CanonicalizationMethod for the specified algorithm URI and parameters.
newChannel(InputStream) - Static method in class java.nio.channels.Channels
Constructs a channel that reads bytes from the given stream.
newChannel(OutputStream) - Static method in class java.nio.channels.Channels
Constructs a channel that writes bytes to the given stream.
newClient(Object) - Method in interface javax.management.remote.rmi.RMIServer
Makes a new connection through this RMI connector.
newClient(Object) - Method in class javax.management.remote.rmi.RMIServerImpl
Creates a new client connection.
newClient(Object) - Method in class javax.management.remote.rmi.RMIServerImpl_Stub
newCondition() - Method in interface java.util.concurrent.locks.Lock
Returns a new Condition instance that is bound to this Lock instance.
newCondition() - Method in class java.util.concurrent.locks.ReentrantLock
Returns a Condition instance for use with this Lock instance.
newCondition() - Method in class java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock
Throws UnsupportedOperationException because ReadLocks do not support conditions.
newCondition() - Method in class java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock
Returns a Condition instance for use with this Lock instance.
newDataAvailable(TableModelEvent) - Method in class javax.swing.table.DefaultTableModel
Equivalent to fireTableChanged.
newDecoder() - Method in class java.nio.charset.Charset
Constructs a new decoder for this charset.
newDigestMethod(String, DigestMethodParameterSpec) - Method in class javax.xml.crypto.dsig.XMLSignatureFactory
Creates a DigestMethod for the specified algorithm URI and parameters.
newDirectoryStream(Path) - Static method in class java.nio.file.Files
Opens a directory, returning a DirectoryStream to iterate over all entries in the directory.
newDirectoryStream(Path, String) - Static method in class java.nio.file.Files
Opens a directory, returning a DirectoryStream to iterate over the entries in the directory.
newDirectoryStream(Path, DirectoryStream.Filter<? super Path>) - Static method in class java.nio.file.Files
Opens a directory, returning a DirectoryStream to iterate over the entries in the directory.
newDirectoryStream(T, LinkOption...) - Method in interface java.nio.file.SecureDirectoryStream
Opens the directory identified by the given path, returning a SecureDirectoryStream to iterate over the entries in the directory.
newDirectoryStream(Path, DirectoryStream.Filter<? super Path>) - Method in class java.nio.file.spi.FileSystemProvider
Opens a directory, returning a DirectoryStream to iterate over the entries in the directory.
newDocument() - Method in class javax.xml.parsers.DocumentBuilder
Obtain a new instance of a DOM Document object to build a DOM tree with.
newDocumentBuilder() - Method in class javax.xml.parsers.DocumentBuilderFactory
Creates a new instance of a DocumentBuilder using the currently configured parameters.
newDuration(String) - Method in class javax.xml.datatype.DatatypeFactory
Obtain a new instance of a Duration specifying the Duration as its string representation, "PnYnMnDTnHnMnS", as defined in XML Schema 1.0 section 3.2.6.1.
newDuration(long) - Method in class javax.xml.datatype.DatatypeFactory
Obtain a new instance of a Duration specifying the Duration as milliseconds.
newDuration(boolean, BigInteger, BigInteger, BigInteger, BigInteger, BigInteger, BigDecimal) - Method in class javax.xml.datatype.DatatypeFactory
Obtain a new instance of a Duration specifying the Duration as isPositive, years, months, days, hours, minutes, seconds.
newDuration(boolean, int, int, int, int, int, int) - Method in class javax.xml.datatype.DatatypeFactory
Obtain a new instance of a Duration specifying the Duration as isPositive, years, months, days, hours, minutes, seconds.
newDurationDayTime(String) - Method in class javax.xml.datatype.DatatypeFactory
Create a Duration of type xdt:dayTimeDuration by parsing its String representation, "PnDTnHnMnS", XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration.
newDurationDayTime(long) - Method in class javax.xml.datatype.DatatypeFactory
Create a Duration of type xdt:dayTimeDuration using the specified milliseconds as defined in XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration.
newDurationDayTime(boolean, BigInteger, BigInteger, BigInteger, BigInteger) - Method in class javax.xml.datatype.DatatypeFactory
Create a Duration of type xdt:dayTimeDuration using the specified day, hour, minute and second as defined in XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration.
newDurationDayTime(boolean, int, int, int, int) - Method in class javax.xml.datatype.DatatypeFactory
Create a Duration of type xdt:dayTimeDuration using the specified day, hour, minute and second as defined in XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration.
newDurationYearMonth(String) - Method in class javax.xml.datatype.DatatypeFactory
Create a Duration of type xdt:yearMonthDuration by parsing its String representation, "PnYnM", XQuery 1.0 and XPath 2.0 Data Model, xdt:yearMonthDuration.
newDurationYearMonth(long) - Method in class javax.xml.datatype.DatatypeFactory
Create a Duration of type xdt:yearMonthDuration using the specified milliseconds as defined in XQuery 1.0 and XPath 2.0 Data Model, xdt:yearMonthDuration.
newDurationYearMonth(boolean, BigInteger, BigInteger) - Method in class javax.xml.datatype.DatatypeFactory
Create a Duration of type xdt:yearMonthDuration using the specified year and month as defined in XQuery 1.0 and XPath 2.0 Data Model, xdt:yearMonthDuration.
newDurationYearMonth(boolean, int, int) - Method in class javax.xml.datatype.DatatypeFactory
Create a Duration of type xdt:yearMonthDuration using the specified year and month as defined in XQuery 1.0 and XPath 2.0 Data Model, xdt:yearMonthDuration.
newEncoder() - Method in class java.nio.charset.Charset
Constructs a new encoder for this charset.
newFactory() - Static method in class javax.sql.rowset.RowSetProvider
Creates a new instance of a RowSetFactory implementation.
newFactory(String, ClassLoader) - Static method in class javax.sql.rowset.RowSetProvider
Creates a new instance of a RowSetFactory from the specified factory class name.
newFactory() - Static method in class javax.xml.stream.XMLEventFactory
Create a new instance of the factory.
newFactory(String, ClassLoader) - Static method in class javax.xml.stream.XMLEventFactory
Create a new instance of the factory.
newFactory() - Static method in class javax.xml.stream.XMLInputFactory
Create a new instance of the factory.
newFactory(String, ClassLoader) - Static method in class javax.xml.stream.XMLInputFactory
Create a new instance of the factory.
newFactory() - Static method in class javax.xml.stream.XMLOutputFactory
Create a new instance of the factory.
newFactory(String, ClassLoader) - Static method in class javax.xml.stream.XMLOutputFactory
Create a new instance of the factory.
newFactory(String) - Method in class javax.xml.validation.SchemaFactoryLoader
Creates a new SchemaFactory object for the specified schema language.
newFileChannel(Path, Set<? extends OpenOption>, FileAttribute<?>...) - Method in class java.nio.file.spi.FileSystemProvider
Opens or creates a file for reading and/or writing, returning a file channel to access the file.
newFileSystem(URI, Map<String, ?>) - Static method in class java.nio.file.FileSystems
Constructs a new file system that is identified by a URI
newFileSystem(URI, Map<String, ?>, ClassLoader) - Static method in class java.nio.file.FileSystems
Constructs a new file system that is identified by a URI
newFileSystem(Path, ClassLoader) - Static method in class java.nio.file.FileSystems
Constructs a new FileSystem to access the contents of a file as a file system.
newFileSystem(URI, Map<String, ?>) - Method in class java.nio.file.spi.FileSystemProvider
Constructs a new FileSystem object identified by a URI.
newFileSystem(Path, Map<String, ?>) - Method in class java.nio.file.spi.FileSystemProvider
Constructs a new FileSystem to access the contents of a file as a file system.
newFixedThreadPool(int) - Static method in class java.util.concurrent.Executors
Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue.
newFixedThreadPool(int, ThreadFactory) - Static method in class java.util.concurrent.Executors
Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue, using the provided ThreadFactory to create new threads when needed.
newFolderIcon - Variable in class javax.swing.plaf.basic.BasicFileChooserUI
newInputStream(ReadableByteChannel) - Static method in class java.nio.channels.Channels
Constructs a stream that reads bytes from the given channel.
newInputStream(AsynchronousByteChannel) - Static method in class java.nio.channels.Channels
Constructs a stream that reads bytes from the given channel.
newInputStream(Path, OpenOption...) - Static method in class java.nio.file.Files
Opens a file, returning an input stream to read from the file.
newInputStream(Path, OpenOption...) - Method in class java.nio.file.spi.FileSystemProvider
Opens a file, returning an input stream to read from the file.
newInstance() - Method in class java.lang.类
Creates a new instance of the class represented by this 类 object.
newInstance(Class<?>, int) - Static method in class java.lang.reflect.Array
Creates a new array with the specified component type and length.
newInstance(Class<?>, int...) - Static method in class java.lang.reflect.Array
Creates a new array with the specified component type and dimensions.
newInstance(Object...) - Method in class java.lang.reflect.Constructor
Uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor's declaring class, with the specified initialization parameters.
newInstance(URL[], ClassLoader) - Static method in class java.net.URLClassLoader
Creates a new instance of URLClassLoader for the specified URLs and parent class loader.
newInstance(URL[]) - Static method in class java.net.URLClassLoader
Creates a new instance of URLClassLoader for the specified URLs and default parent class loader.
newInstance(ActivationID, ActivationDesc) - Method in class java.rmi.activation.ActivationGroup_Stub
Stub method for ActivationGroup.newInstance.
newInstance(ActivationID, ActivationDesc) - Method in interface java.rmi.activation.ActivationInstantiator
The activator calls an instantiator's newInstance method in order to recreate in that group an object with the activation identifier, id, and descriptor, desc.
newInstance(KeyStore, KeyStore.ProtectionParameter) - Static method in class java.security.KeyStore.Builder
Returns a new Builder that encapsulates the given KeyStore.
newInstance(String, Provider, File, KeyStore.ProtectionParameter) - Static method in class java.security.KeyStore.Builder
Returns a new Builder object.
newInstance(String, Provider, KeyStore.ProtectionParameter) - Static method in class java.security.KeyStore.Builder
Returns a new Builder object.
newInstance(Object) - Method in class java.security.Provider.Service
Return a new instance of the implementation described by this service.
newInstance(Control[]) - Method in class javax.naming.ldap.InitialLdapContext
newInstance(Control[]) - Method in interface javax.naming.ldap.LdapContext
Creates a new instance of this context initialized using request controls.
newInstance(String) - Static method in class javax.xml.bind.JAXBContext
Obtain a new instance of a JAXBContext class.
newInstance(String, ClassLoader) - Static method in class javax.xml.bind.JAXBContext
Obtain a new instance of a JAXBContext class.
newInstance(String, ClassLoader, Map<String, ?>) - Static method in class javax.xml.bind.JAXBContext
Obtain a new instance of a JAXBContext class.
newInstance(Class...) - Static method in class javax.xml.bind.JAXBContext
Obtain a new instance of a JAXBContext class.
newInstance(Class[], Map<String, ?>) - Static method in class javax.xml.bind.JAXBContext
Obtain a new instance of a JAXBContext class.
newInstance() - Static method in class javax.xml.datatype.DatatypeFactory
Obtain a new instance of a DatatypeFactory.
newInstance(String, ClassLoader) - Static method in class javax.xml.datatype.DatatypeFactory
Obtain a new instance of a DatatypeFactory from class name.
newInstance() - Static method in class javax.xml.parsers.DocumentBuilderFactory
Obtain a new instance of a DocumentBuilderFactory.
newInstance(String, ClassLoader) - Static method in class javax.xml.parsers.DocumentBuilderFactory
Obtain a new instance of a DocumentBuilderFactory from class name.
newInstance() - Static method in class javax.xml.parsers.SAXParserFactory
Obtain a new instance of a SAXParserFactory.
newInstance(String, ClassLoader) - Static method in class javax.xml.parsers.SAXParserFactory
Obtain a new instance of a SAXParserFactory from class name.
newInstance() - Static method in class javax.xml.soap.MessageFactory
Creates a new MessageFactory object that is an instance of the default implementation (SOAP 1.1), This method uses the following ordered lookup procedure to determine the MessageFactory implementation class to load: Use the javax.xml.soap.MessageFactory system property.
newInstance(String) - Static method in class javax.xml.soap.MessageFactory
Creates a new MessageFactory object that is an instance of the specified implementation.
newInstance() - Static method in class javax.xml.soap.SOAPConnectionFactory
Creates an instance of the default SOAPConnectionFactory object.
newInstance() - Static method in class javax.xml.soap.SOAPElementFactory
Deprecated.
Creates a new instance of SOAPElementFactory.
newInstance() - Static method in class javax.xml.soap.SOAPFactory
Creates a new SOAPFactory object that is an instance of the default implementation (SOAP 1.1), This method uses the following ordered lookup procedure to determine the SOAPFactory implementation class to load: Use the javax.xml.soap.SOAPFactory system property.
newInstance(String) - Static method in class javax.xml.soap.SOAPFactory
Creates a new SOAPFactory object that is an instance of the specified implementation, this method uses the SAAJMetaFactory to locate the implementation class and create the SOAPFactory instance.
newInstance() - Method in interface javax.xml.stream.util.XMLEventAllocator
This method creates an instance of the XMLEventAllocator.
newInstance() - Static method in class javax.xml.stream.XMLEventFactory
Create a new instance of the factory
newInstance(String, ClassLoader) - Static method in class javax.xml.stream.XMLEventFactory
Deprecated.
This method has been deprecated to maintain API consistency. All newInstance methods have been replaced with corresponding newFactory methods. The replacement XMLEventFactory.newFactory(java.lang.String, java.lang.ClassLoader) method defines no changes in behavior.
newInstance() - Static method in class javax.xml.stream.XMLInputFactory
Create a new instance of the factory.
newInstance(String, ClassLoader) - Static method in class javax.xml.stream.XMLInputFactory
Deprecated.
This method has been deprecated to maintain API consistency. All newInstance methods have been replaced with corresponding newFactory methods. The replacement XMLInputFactory.newFactory(java.lang.String, java.lang.ClassLoader) method defines no changes in behavior.
newInstance() - Static method in class javax.xml.stream.XMLOutputFactory
Create a new instance of the factory.
newInstance(String, ClassLoader) - Static method in class javax.xml.stream.XMLOutputFactory
Deprecated.
This method has been deprecated because it returns an instance of XMLInputFactory, which is of the wrong class. Use the new method XMLOutputFactory.newFactory(java.lang.String, java.lang.ClassLoader) instead.
newInstance() - Static method in class javax.xml.transform.TransformerFactory
Obtain a new instance of a TransformerFactory.
newInstance(String, ClassLoader) - Static method in class javax.xml.transform.TransformerFactory
Obtain a new instance of a TransformerFactory from factory class name.
newInstance(String) - Static method in class javax.xml.validation.SchemaFactory
Lookup an implementation of the SchemaFactory that supports the specified schema language and return it.
newInstance(String, String, ClassLoader) - Static method in class javax.xml.validation.SchemaFactory
Obtain a new instance of a SchemaFactory from class name.
newInstance() - Static method in class javax.xml.xpath.XPathFactory
Get a new XPathFactory instance using the default object model, XPathFactory.DEFAULT_OBJECT_MODEL_URI, the W3C DOM.
newInstance(String) - Static method in class javax.xml.xpath.XPathFactory
Get a new XPathFactory instance using the specified object model.
newInstance(String, String, ClassLoader) - Static method in class javax.xml.xpath.XPathFactory
Obtain a new instance of a XPathFactory from a factory class name.
newInstance() - Static method in class org.w3c.dom.bootstrap.DOMImplementationRegistry
Obtain a new instance of a DOMImplementationRegistry.
newJMXConnector(JMXServiceURL, Map<String, ?>) - Static method in class javax.management.remote.JMXConnectorFactory
Creates a connector client for the connector server at the given address.
newJMXConnector(JMXServiceURL, Map<String, ?>) - Method in interface javax.management.remote.JMXConnectorProvider
Creates a new connector client that is ready to connect to the connector server at the given address.
newJMXConnectorServer(JMXServiceURL, Map<String, ?>, MBeanServer) - Static method in class javax.management.remote.JMXConnectorServerFactory
Creates a connector server at the given address.
newJMXConnectorServer(JMXServiceURL, Map<String, ?>, MBeanServer) - Method in interface javax.management.remote.JMXConnectorServerProvider
Creates a new connector server at the given address.
newKeyInfo(List) - Method in class javax.xml.crypto.dsig.keyinfo.KeyInfoFactory
Creates a KeyInfo containing the specified list of key information types.
newKeyInfo(List, String) - Method in class javax.xml.crypto.dsig.keyinfo.KeyInfoFactory
Creates a KeyInfo containing the specified list of key information types and optional id.
newKeyName(String) - Method in class javax.xml.crypto.dsig.keyinfo.KeyInfoFactory
Creates a KeyName from the specified name.
newKeyValue(PublicKey) - Method in class javax.xml.crypto.dsig.keyinfo.KeyInfoFactory
Creates a KeyValue from the specified public key.
newLeadSelectionPath - Variable in class javax.swing.event.TreeSelectionEvent
leadSelectionPath after the paths changed, may be null.
newLine() - Method in class java.io.BufferedWriter
Writes a line separator.
NEWLINE - Static variable in class javax.swing.text.AbstractWriter
How the text packages models newlines.
newManifest(List) - Method in class javax.xml.crypto.dsig.XMLSignatureFactory
Creates a Manifest containing the specified list of References.
newManifest(List, String) - Method in class javax.xml.crypto.dsig.XMLSignatureFactory
Creates a Manifest containing the specified list of References and optional id.
newMBeanProxy(MBeanServerConnection, ObjectName, Class<T>) - Static method in class javax.management.JMX
Make a proxy for a Standard MBean in a local or remote MBean Server.
newMBeanProxy(MBeanServerConnection, ObjectName, Class<T>, boolean) - Static method in class javax.management.JMX
Make a proxy for a Standard MBean in a local or remote MBean Server that may also support the methods of NotificationEmitter.
newMBeanServer(String, MBeanServer, MBeanServerDelegate) - Method in class javax.management.MBeanServerBuilder
This method creates a new MBeanServer implementation object.
newMBeanServer() - Static method in class javax.management.MBeanServerFactory
Return a new object implementing the MBeanServer interface with a standard default domain name, without keeping an internal reference to this new object.
newMBeanServer(String) - Static method in class javax.management.MBeanServerFactory
Return a new object implementing the MBeanServer interface with the specified default domain name, without keeping an internal reference to this new object.
newMBeanServerDelegate() - Method in class javax.management.MBeanServerBuilder
This method creates a new MBeanServerDelegate for a new MBeanServer.
newMessageFactory(String) - Method in class javax.xml.soap.SAAJMetaFactory
Creates a MessageFactory object for the given String protocol.
newmodel - Variable in class java.awt.image.RGBImageFilter
The ColorModel with which to replace origmodel when the user calls substituteColorModel.
newMXBeanProxy(MBeanServerConnection, ObjectName, Class<T>) - Static method in class javax.management.JMX
Make a proxy for an MXBean in a local or remote MBean Server.
newMXBeanProxy(MBeanServerConnection, ObjectName, Class<T>, boolean) - Static method in class javax.management.JMX
Make a proxy for an MXBean in a local or remote MBean Server that may also support the methods of NotificationEmitter.
newNode - Variable in class java.util.prefs.AbstractPreferences
This field should be true if this node did not exist in the backing store prior to the creation of this object.
newOutputStream(WritableByteChannel) - Static method in class java.nio.channels.Channels
Constructs a stream that writes bytes to the given channel.
newOutputStream(AsynchronousByteChannel) - Static method in class java.nio.channels.Channels
Constructs a stream that writes bytes to the given channel.
newOutputStream(Path, OpenOption...) - Static method in class java.nio.file.Files
Opens or creates a file, returning an output stream that may be used to write bytes to the file.
newOutputStream(Path, OpenOption...) - Method in class java.nio.file.spi.FileSystemProvider
Opens or creates a file, returning an output stream that may be used to write bytes to the file.
newPacker() - Static method in class java.util.jar.Pack200
Obtain new instance of a class that implements Packer.
newPermissionCollection() - Method in class java.io.FilePermission
Returns a new PermissionCollection object for storing FilePermission objects.
newPermissionCollection() - Method in class java.net.SocketPermission
Returns a new PermissionCollection object for storing SocketPermission objects.
newPermissionCollection() - Method in class java.security.AllPermission
Returns a new PermissionCollection object for storing AllPermission objects.
newPermissionCollection() - Method in class java.security.BasicPermission
Returns a new PermissionCollection object for storing BasicPermission objects.
newPermissionCollection() - Method in class java.security.Permission
Returns an empty PermissionCollection for a given Permission object, or null if one is not defined.
newPermissionCollection() - Method in class java.security.UnresolvedPermission
Returns a new PermissionCollection object for storing UnresolvedPermission objects.
newPermissionCollection() - Method in class java.util.PropertyPermission
Returns a new PermissionCollection object for storing PropertyPermission objects.
newPermissionCollection() - Method in class javax.management.MBeanServerPermission
newPermissionCollection() - Method in class javax.security.auth.kerberos.DelegationPermission
Returns a PermissionCollection object for storing DelegationPermission objects.
newPermissionCollection() - Method in class javax.security.auth.kerberos.ServicePermission
Returns a PermissionCollection object for storing ServicePermission objects.
newPermissionCollection() - Method in class javax.security.auth.PrivateCredentialPermission
Return a homogeneous collection of PrivateCredentialPermissions in a PermissionCollection.
newPGPData(byte[]) - Method in class javax.xml.crypto.dsig.keyinfo.KeyInfoFactory
Creates a PGPData from the specified PGP public key identifier.
newPGPData(byte[], byte[], List) - Method in class javax.xml.crypto.dsig.keyinfo.KeyInfoFactory
Creates a PGPData from the specified PGP public key identifier, and optional key material packet and list of external elements.
newPGPData(byte[], List) - Method in class javax.xml.crypto.dsig.keyinfo.KeyInfoFactory
Creates a PGPData from the specified PGP key material packet and optional list of external elements.
newPixels() - Method in class java.awt.image.MemoryImageSource
Sends a whole new buffer of pixels to any ImageConsumers that are currently interested in the data for this image and notify them that an animation frame is complete.
newPixels(int, int, int, int) - Method in class java.awt.image.MemoryImageSource
Sends a rectangular region of the buffer of pixels to any ImageConsumers that are currently interested in the data for this image and notify them that an animation frame is complete.
newPixels(int, int, int, int, boolean) - Method in class java.awt.image.MemoryImageSource
Sends a rectangular region of the buffer of pixels to any ImageConsumers that are currently interested in the data for this image.
newPixels(byte[], ColorModel, int, int) - Method in class java.awt.image.MemoryImageSource
Changes to a new byte array to hold the pixels for this image.
newPixels(int[], ColorModel, int, int) - Method in class java.awt.image.MemoryImageSource
Changes to a new int array to hold the pixels for this image.
newPlatformMXBeanProxy(MBeanServerConnection, String, Class<T>) - Static method in class java.lang.management.ManagementFactory
Returns a proxy for a platform MXBean interface of a given MXBean name that forwards its method calls through the given MBeanServerConnection.
newProxyInstance(ClassLoader, Class<?>[], InvocationHandler) - Static method in class java.lang.reflect.Proxy
Returns an instance of a proxy class for the specified interfaces that dispatches method invocations to the specified invocation handler.
newProxyInstance(MBeanServerConnection, ObjectName, Class<T>, boolean) - Static method in class javax.management.MBeanServerInvocationHandler
Return a proxy that implements the given interface by forwarding its methods through the given MBean server to the named MBean.
newReader(ReadableByteChannel, CharsetDecoder, int) - Static method in class java.nio.channels.Channels
Constructs a reader that decodes bytes from the given channel using the given decoder.
newReader(ReadableByteChannel, String) - Static method in class java.nio.channels.Channels
Constructs a reader that decodes bytes from the given channel according to the named charset.
newReference(String, DigestMethod) - Method in class javax.xml.crypto.dsig.XMLSignatureFactory
Creates a Reference with the specified URI and digest method.
newReference(String, DigestMethod, List, String, String) - Method in class javax.xml.crypto.dsig.XMLSignatureFactory
Creates a Reference with the specified parameters.
newReference(String, DigestMethod, List, String, String, byte[]) - Method in class javax.xml.crypto.dsig.XMLSignatureFactory
Creates a Reference with the specified parameters and pre-calculated digest value.
newReference(String, DigestMethod, List, Data, List, String, String) - Method in class javax.xml.crypto.dsig.XMLSignatureFactory
Creates a Reference with the specified parameters.
newRetrievalMethod(String) - Method in class javax.xml.crypto.dsig.keyinfo.KeyInfoFactory
Creates a RetrievalMethod from the specified URI.
newRetrievalMethod(String, String, List) - Method in class javax.xml.crypto.dsig.keyinfo.KeyInfoFactory
Creates a RetrievalMethod from the specified parameters.
newRowsAdded(TableModelEvent) - Method in class javax.swing.table.DefaultTableModel
Ensures that the new rows have the correct number of columns.
NEWS - Static variable in class javax.print.attribute.standard.ReferenceUriSchemesSupported
USENET news.
newSAXParser() - Method in class javax.xml.parsers.SAXParserFactory
Creates a new instance of a SAXParser using the currently configured factory parameters.
newScheduledThreadPool(int) - Static method in class java.util.concurrent.Executors
Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.
newScheduledThreadPool(int, ThreadFactory) - Static method in class java.util.concurrent.Executors
Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.
newSchema(Source) - Method in class javax.xml.validation.SchemaFactory
Parses the specified source as a schema and returns it as a schema.
newSchema(File) - Method in class javax.xml.validation.SchemaFactory
Parses the specified File as a schema and returns it as a Schema.
newSchema(URL) - Method in class javax.xml.validation.SchemaFactory
Parses the specified URL as a schema and returns it as a Schema.
newSchema(Source[]) - Method in class javax.xml.validation.SchemaFactory
Parses the specified source(s) as a schema and returns it as a schema.
newSchema() - Method in class javax.xml.validation.SchemaFactory
Creates a special Schema object.
newSetFromMap(Map<E, Boolean>) - Static method in class java.util.Collections
Returns a set backed by the specified map.
newSignatureMethod(String, SignatureMethodParameterSpec) - Method in class javax.xml.crypto.dsig.XMLSignatureFactory
Creates a SignatureMethod for the specified algorithm URI and parameters.
newSignatureProperties(List, String) - Method in class javax.xml.crypto.dsig.XMLSignatureFactory
Creates a SignatureProperties containing the specified list of SignaturePropertys and optional id.
newSignatureProperty(List, String, String) - Method in class javax.xml.crypto.dsig.XMLSignatureFactory
Creates a SignatureProperty containing the specified list of XMLStructures, target URI and optional id.
newSignedInfo(CanonicalizationMethod, SignatureMethod, List) - Method in class javax.xml.crypto.dsig.XMLSignatureFactory
Creates a SignedInfo with the specified canonicalization and signature methods, and list of one or more references.
newSignedInfo(CanonicalizationMethod, SignatureMethod, List, String) - Method in class javax.xml.crypto.dsig.XMLSignatureFactory
Creates a SignedInfo with the specified parameters.
newSingleThreadExecutor() - Static method in class java.util.concurrent.Executors
Creates an Executor that uses a single worker thread operating off an unbounded queue.
newSingleThreadExecutor(ThreadFactory) - Static method in class java.util.concurrent.Executors
Creates an Executor that uses a single worker thread operating off an unbounded queue, and uses the provided ThreadFactory to create a new thread when needed.
newSingleThreadScheduledExecutor() - Static method in class java.util.concurrent.Executors
Creates a single-threaded executor that can schedule commands to run after a given delay, or to execute periodically.
newSingleThreadScheduledExecutor(ThreadFactory) - Static method in class java.util.concurrent.Executors
Creates a single-threaded executor that can schedule commands to run after a given delay, or to execute periodically.
newSOAPFactory(String) - Method in class javax.xml.soap.SAAJMetaFactory
Creates a SOAPFactory object for the given String protocol.
newTaskFor(Runnable, T) - Method in class java.util.concurrent.AbstractExecutorService
Returns a RunnableFuture for the given runnable and default value.
newTaskFor(Callable<T>) - Method in class java.util.concurrent.AbstractExecutorService
Returns a RunnableFuture for the given callable task.
newTaskFor(Runnable, T) - Method in class java.util.concurrent.ForkJoinPool
newTaskFor(Callable<T>) - Method in class java.util.concurrent.ForkJoinPool
newTemplates(Source) - Method in class javax.xml.transform.TransformerFactory
Process the Source into a Templates object, which is a a compiled representation of the source.
newTemplatesHandler() - Method in class javax.xml.transform.sax.SAXTransformerFactory
Get a TemplatesHandler object that can process SAX ContentHandler events into a Templates object.
newThread(ForkJoinPool) - Method in interface java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory
Returns a new worker thread operating in the given pool.
newThread(Runnable) - Method in interface java.util.concurrent.ThreadFactory
Constructs a new Thread.
newTransform(String, TransformParameterSpec) - Method in class javax.xml.crypto.dsig.XMLSignatureFactory
Creates a Transform for the specified algorithm URI and parameters.
newTransform(String, XMLStructure) - Method in class javax.xml.crypto.dsig.XMLSignatureFactory
Creates a Transform for the specified algorithm URI and parameters.
newTransformer() - Method in interface javax.xml.transform.Templates
Create a new transformation context for this Templates object.
newTransformer(Source) - Method in class javax.xml.transform.TransformerFactory
Process the Source into a Transformer Object.
newTransformer() - Method in class javax.xml.transform.TransformerFactory
Create a new Transformer that performs a copy of the Source to the Result.
newTransformerHandler(Source) - Method in class javax.xml.transform.sax.SAXTransformerFactory
Get a TransformerHandler object that can process SAX ContentHandler events into a Result, based on the transformation instructions specified by the argument.
newTransformerHandler(Templates) - Method in class javax.xml.transform.sax.SAXTransformerFactory
Get a TransformerHandler object that can process SAX ContentHandler events into a Result, based on the Templates argument.
newTransformerHandler() - Method in class javax.xml.transform.sax.SAXTransformerFactory
Get a TransformerHandler object that can process SAX ContentHandler events into a Result.
newUnpacker() - Static method in class java.util.jar.Pack200
Obtain new instance of a class that implements Unpacker.
newUpdater(Class<U>, String) - Static method in class java.util.concurrent.atomic.AtomicIntegerFieldUpdater
Creates and returns an updater for objects with the given field.
newUpdater(Class<U>, String) - Static method in class java.util.concurrent.atomic.AtomicLongFieldUpdater
Creates and returns an updater for objects with the given field.
newUpdater(Class<U>, Class<W>, String) - Static method in class java.util.concurrent.atomic.AtomicReferenceFieldUpdater
Creates and returns an updater for objects with the given field.
newValidator() - Method in class javax.xml.validation.Schema
Creates a new Validator for this Schema.
newValidatorHandler() - Method in class javax.xml.validation.Schema
Creates a new ValidatorHandler for this Schema.
newWatchService() - Method in class java.nio.file.FileSystem
Constructs a new WatchService (optional operation).
newWriter(WritableByteChannel, CharsetEncoder, int) - Static method in class java.nio.channels.Channels
Constructs a writer that encodes characters using the given encoder and writes the resulting bytes to the given channel.
newWriter(WritableByteChannel, String) - Static method in class java.nio.channels.Channels
Constructs a writer that encodes characters according to the named charset and writes the resulting bytes to the given channel.
newX509Data(List) - Method in class javax.xml.crypto.dsig.keyinfo.KeyInfoFactory
Creates a X509Data containing the specified list of X.509 content.
newX509IssuerSerial(String, BigInteger) - Method in class javax.xml.crypto.dsig.keyinfo.KeyInfoFactory
Creates an X509IssuerSerial from the specified X.500 issuer distinguished name and serial number.
newXMLFilter(Source) - Method in class javax.xml.transform.sax.SAXTransformerFactory
Create an XMLFilter that uses the given Source as the transformation instructions.
newXMLFilter(Templates) - Method in class javax.xml.transform.sax.SAXTransformerFactory
Create an XMLFilter, based on the Templates argument..
newXMLGregorianCalendar() - Method in class javax.xml.datatype.DatatypeFactory
Create a new instance of an XMLGregorianCalendar.
newXMLGregorianCalendar(String) - Method in class javax.xml.datatype.DatatypeFactory
Create a new XMLGregorianCalendar by parsing the String as a lexical representation.
newXMLGregorianCalendar(GregorianCalendar) - Method in class javax.xml.datatype.DatatypeFactory
Create an XMLGregorianCalendar from a GregorianCalendar.
newXMLGregorianCalendar(BigInteger, int, int, int, int, int, BigDecimal, int) - Method in class javax.xml.datatype.DatatypeFactory
Constructor allowing for complete value spaces allowed by W3C XML Schema 1.0 recommendation for xsd:dateTime and related builtin datatypes.
newXMLGregorianCalendar(int, int, int, int, int, int, int, int) - Method in class javax.xml.datatype.DatatypeFactory
Constructor of value spaces that a java.util.GregorianCalendar instance would need to convert to an XMLGregorianCalendar instance.
newXMLGregorianCalendarDate(int, int, int, int) - Method in class javax.xml.datatype.DatatypeFactory
Create a Java representation of XML Schema builtin datatype date or g*.
newXMLGregorianCalendarTime(int, int, int, int) - Method in class javax.xml.datatype.DatatypeFactory
Create a Java instance of XML Schema builtin datatype time.
newXMLGregorianCalendarTime(int, int, int, BigDecimal, int) - Method in class javax.xml.datatype.DatatypeFactory
Create a Java instance of XML Schema builtin datatype time.
newXMLGregorianCalendarTime(int, int, int, int, int) - Method in class javax.xml.datatype.DatatypeFactory
Create a Java instance of XML Schema builtin datatype time.
newXMLObject(List, String, String, String) - Method in class javax.xml.crypto.dsig.XMLSignatureFactory
Creates an XMLObject from the specified parameters.
newXMLSignature(SignedInfo, KeyInfo) - Method in class javax.xml.crypto.dsig.XMLSignatureFactory
Creates an XMLSignature and initializes it with the contents of the specified SignedInfo and KeyInfo objects.
newXMLSignature(SignedInfo, KeyInfo, List, String, String) - Method in class javax.xml.crypto.dsig.XMLSignatureFactory
Creates an XMLSignature and initializes it with the specified parameters.
newXPath() - Method in class javax.xml.xpath.XPathFactory
Return a new XPath using the underlying object model determined when the XPathFactory was instantiated.
next(Container) - Method in class java.awt.CardLayout
Flips to the next card of the specified container.
next() - Method in class java.awt.geom.FlatteningPathIterator
Moves the iterator to the next segment of the path forwards along the primary direction of traversal as long as there are more points in that direction.
next() - Method in interface java.awt.geom.PathIterator
Moves the iterator to the next segment of the path forwards along the primary direction of traversal as long as there are more points in that direction.
next() - Method in class java.beans.beancontext.BeanContextSupport.BCSIterator
next(int) - Method in class java.security.SecureRandom
Generates an integer containing the user-specified number of pseudo-random bits (right justified, with leading zeros).
next() - Method in interface java.sql.ResultSet
Moves the cursor froward one row from its current position.
next(int) - Method in class java.text.BreakIterator
Returns the nth boundary from the current boundary.
next() - Method in class java.text.BreakIterator
Returns the boundary following the current boundary.
next() - Method in interface java.text.CharacterIterator
Increments the iterator's index by one and returns the character at the new index.
next() - Method in class java.text.CollationElementIterator
Get the next collation element in the string.
next() - Method in class java.text.StringCharacterIterator
Implements CharacterIterator.next() for String.
next(int) - Method in class java.util.concurrent.ThreadLocalRandom
next() - Method in interface java.util.Iterator
Returns the next element in the iteration.
next() - Method in interface java.util.ListIterator
Returns the next element in the list and advances the cursor position.
next(int) - Method in class java.util.Random
Generates the next pseudorandom number.
next() - Method in class java.util.Scanner
Finds and returns the next complete token from this scanner.
next(String) - Method in class java.util.Scanner
Returns the next token if it matches the pattern constructed from the specified string.
next(Pattern) - Method in class java.util.Scanner
Returns the next token if it matches the specified pattern.
next() - Method in interface javax.naming.NamingEnumeration
Retrieves the next element in the enumeration.
next(int) - Method in class javax.print.attribute.SetOfIntegerSyntax
Determine the smallest integer in this set-of-integer attribute that is greater than the given value.
next() - Method in interface javax.print.MultiDoc
Go to the multidoc object that contains the next doc object in the sequence of doc objects.
下一个 - Static variable in interface javax.swing.SwingConstants
Identifies the next direction in a sequence.
next() - Method in class javax.swing.text.ElementIterator
Fetches the next Element.
next() - Method in class javax.swing.text.html.HTMLDocument.Iterator
Move the iterator forward to the next occurrence of the tag it represents.
下一个 - Variable in class javax.swing.text.html.parser.AttributeList
下一个 - Variable in class javax.swing.text.html.parser.ContentModel
The next content model (in a ',', '|' or '&' expression).
next() - Method in class javax.swing.text.Segment
Increments the iterator's index by one and returns the character at the new index.
next() - Method in class javax.xml.stream.util.EventReaderDelegate
next() - Method in class javax.xml.stream.util.StreamReaderDelegate
next() - Method in interface javax.xml.stream.XMLStreamReader
Get next parsing event - a processor may return all contiguous character data in a single chunk, or it may split it into several chunks.
next() - Method in interface org.omg.CORBA.DynAny
Deprecated.
Moves to the next component of this DynAny object.
next() - Method in class org.omg.DynamicAny._DynAnyStub
Advances the current position to the next component.
next() - Method in class org.omg.DynamicAny._DynArrayStub
Advances the current position to the next component.
next() - Method in class org.omg.DynamicAny._DynEnumStub
Advances the current position to the next component.
next() - Method in class org.omg.DynamicAny._DynFixedStub
Advances the current position to the next component.
next() - Method in class org.omg.DynamicAny._DynSequenceStub
Advances the current position to the next component.
next() - Method in class org.omg.DynamicAny._DynStructStub
Advances the current position to the next component.
next() - Method in class org.omg.DynamicAny._DynUnionStub
Advances the current position to the next component.
next() - Method in class org.omg.DynamicAny._DynValueStub
Advances the current position to the next component.
next() - Method in interface org.omg.DynamicAny.DynAnyOperations
Advances the current position to the next component.
next_n(int, BindingListHolder) - Method in class org.omg.CosNaming._BindingIteratorStub
This operation returns at most the requested number of bindings.
next_n(int, BindingListHolder) - Method in interface org.omg.CosNaming.BindingIteratorOperations
This operation returns at most the requested number of bindings.
next_one(BindingHolder) - Method in class org.omg.CosNaming._BindingIteratorStub
This operation returns the next binding.
next_one(BindingHolder) - Method in interface org.omg.CosNaming.BindingIteratorOperations
This operation returns the next binding.
nextAfter(double, double) - Static method in class java.lang.Math
Returns the floating-point number adjacent to the first argument in the direction of the second argument.
nextAfter(float, double) - Static method in class java.lang.Math
Returns the floating-point number adjacent to the first argument in the direction of the second argument.
nextAfter(double, double) - Static method in class java.lang.StrictMath
Returns the floating-point number adjacent to the first argument in the direction of the second argument.
nextAfter(float, double) - Static method in class java.lang.StrictMath
Returns the floating-point number adjacent to the first argument in the direction of the second argument.
nextBigDecimal() - Method in class java.util.Scanner
Scans the next token of the input as a BigDecimal.
nextBigInteger() - Method in class java.util.Scanner
Scans the next token of the input as a BigInteger.
nextBigInteger(int) - Method in class java.util.Scanner
Scans the next token of the input as a BigInteger.
nextBoolean() - Method in class java.util.Random
Returns the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence.
nextBoolean() - Method in class java.util.Scanner
Scans the next token of the input into a boolean value and returns that value.
nextByte() - Method in class java.util.Scanner
Scans the next token of the input as a byte.
nextByte(int) - Method in class java.util.Scanner
Scans the next token of the input as a byte.
nextBytes(byte[]) - Method in class java.security.SecureRandom
Generates a user-specified number of random bytes.
nextBytes(byte[]) - Method in class java.util.Random
Generates random bytes and places them into a user-supplied byte array.
nextClearBit(int) - Method in class java.util.BitSet
Returns the index of the first bit that is set to false that occurs on or after the specified starting index.
nextConflict() - Method in interface javax.sql.rowset.spi.SyncResolver
Moves the cursor down from its current position to the next row that contains a conflict value.
nextDouble(double) - Static method in class java.text.ChoiceFormat
Finds the least double greater than d.
nextDouble(double, boolean) - Static method in class java.text.ChoiceFormat
Finds the least double greater than d (if positive == true), or the greatest double less than d (if positive == false).
nextDouble(double) - Method in class java.util.concurrent.ThreadLocalRandom
Returns a pseudorandom, uniformly distributed double value between 0 (inclusive) and the specified value (exclusive).
nextDouble(double, double) - Method in class java.util.concurrent.ThreadLocalRandom
Returns a pseudorandom, uniformly distributed value between the given least value (inclusive) and bound (exclusive).
nextDouble() - Method in class java.util.Random
Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.
nextDouble() - Method in class java.util.Scanner
Scans the next token of the input as a double.
nextElement() - Method in interface java.util.Enumeration
Returns the next element of this enumeration if this enumeration object has at least one more element to provide.
nextElement() - Method in class java.util.StringTokenizer
Returns the same value as the nextToken method, except that its declared return value is Object rather than String.
nextEvent() - Method in class javax.xml.stream.util.EventReaderDelegate
nextEvent() - Method in interface javax.xml.stream.XMLEventReader
Get the next XMLEvent
nextFloat() - Method in class java.util.Random
Returns the next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this random number generator's sequence.
nextFloat() - Method in class java.util.Scanner
Scans the next token of the input as a float.
nextFocus() - Method in class java.awt.Component
Deprecated.
As of JDK version 1.1, replaced by transferFocus().
nextGaussian() - Method in class java.util.Random
Returns the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence.
nextIndex() - Method in interface java.util.ListIterator
Returns the index of the element that would be returned by a subsequent call to ListIterator.next().
nextInt(int, int) - Method in class java.util.concurrent.ThreadLocalRandom
Returns a pseudorandom, uniformly distributed value between the given least value (inclusive) and bound (exclusive).
nextInt() - Method in class java.util.Random
Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence.
nextInt(int) - Method in class java.util.Random
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.
nextInt() - Method in class java.util.Scanner
Scans the next token of the input as an int.
nextInt(int) - Method in class java.util.Scanner
Scans the next token of the input as an int.
nextLayout(float) - Method in class java.awt.font.LineBreakMeasurer
Returns the next layout, and updates the current position.
nextLayout(float, int, boolean) - Method in class java.awt.font.LineBreakMeasurer
Returns the next layout, and updates the current position.
nextLine() - Method in class java.util.Scanner
Advances this scanner past the current line and returns the input that was skipped.
nextLong(long) - Method in class java.util.concurrent.ThreadLocalRandom
Returns a pseudorandom, uniformly distributed value between 0 (inclusive) and the specified value (exclusive).
nextLong(long, long) - Method in class java.util.concurrent.ThreadLocalRandom
Returns a pseudorandom, uniformly distributed value between the given least value (inclusive) and bound (exclusive).
nextLong() - Method in class java.util.Random
Returns the next pseudorandom, uniformly distributed long value from this random number generator's sequence.
nextLong() - Method in class java.util.Scanner
Scans the next token of the input as a long.
nextLong(int) - Method in class java.util.Scanner
Scans the next token of the input as a long.
nextOffset(float) - Method in class java.awt.font.LineBreakMeasurer
Returns the position at the end of the next layout.
nextOffset(float, int, boolean) - Method in class java.awt.font.LineBreakMeasurer
Returns the position at the end of the next layout.
nextPage() - Method in interface javax.sql.rowset.CachedRowSet
Increments the current page of the CachedRowSet.
nextProbablePrime() - Method in class java.math.BigInteger
Returns the first integer greater than this BigInteger that is probably prime.
nextSetBit(int) - Method in class java.util.BitSet
Returns the index of the first bit that is set to true that occurs on or after the specified starting index.
nextShort() - Method in class java.util.Scanner
Scans the next token of the input as a short.
nextShort(int) - Method in class java.util.Scanner
Scans the next token of the input as a short.
nextTabStop(float, int) - Method in class javax.swing.text.ParagraphView
Returns the next tab stop position given a reference position.
nextTabStop(float, int) - Method in class javax.swing.text.PlainView
Returns the next tab stop position after a given reference position.
nextTabStop(float, int) - Method in interface javax.swing.text.TabExpander
Returns the next tab stop position given a reference position.
nextTabStop(float, int) - Method in class javax.swing.text.WrappedPlainView
Returns the next tab stop position after a given reference position.
nextTag() - Method in class javax.xml.stream.util.EventReaderDelegate
nextTag() - Method in class javax.xml.stream.util.StreamReaderDelegate
nextTag() - Method in interface javax.xml.stream.XMLEventReader
Skips any insignificant space events until a START_ELEMENT or END_ELEMENT is reached.
nextTag() - Method in interface javax.xml.stream.XMLStreamReader
Skips any white space (isWhiteSpace() returns true), COMMENT, or PROCESSING_INSTRUCTION, until a START_ELEMENT or END_ELEMENT is reached.
nextToken() - Method in class java.io.StreamTokenizer
Parses the next token from the input stream of this tokenizer.
nextToken() - Method in class java.util.StringTokenizer
Returns the next token from this string tokenizer.
nextToken(String) - Method in class java.util.StringTokenizer
Returns the next token in this string tokenizer's string.
nextUp(double) - Static method in class java.lang.Math
Returns the floating-point value adjacent to d in the direction of positive infinity.
nextUp(float) - Static method in class java.lang.Math
Returns the floating-point value adjacent to f in the direction of positive infinity.
nextUp(double) - Static method in class java.lang.StrictMath
Returns the floating-point value adjacent to d in the direction of positive infinity.
nextUp(float) - Static method in class java.lang.StrictMath
Returns the floating-point value adjacent to f in the direction of positive infinity.
nextWordAction - Static variable in class javax.swing.text.DefaultEditorKit
Name of the Action for moving the caret to the beginning of the next word.
nil - Variable in class javax.xml.bind.JAXBElement
true iff the xml element instance has xsi:nil="true".
NimbusLookAndFeel - Class in javax.swing.plaf.nimbus
The NimbusLookAndFeel class.
NimbusLookAndFeel() - Constructor for class javax.swing.plaf.nimbus.NimbusLookAndFeel
Create a new NimbusLookAndFeel.
NimbusStyle - Class in javax.swing.plaf.nimbus
A SynthStyle implementation used by Nimbus.
NKO - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "NKo" Unicode character block.
NMTOKEN - Static variable in interface javax.swing.text.html.parser.DTDConstants
NMTOKENS - Static variable in interface javax.swing.text.html.parser.DTDConstants
NNTP - Static variable in class javax.print.attribute.standard.ReferenceUriSchemesSupported
USENET news using Network News Transfer Protocol (NNTP).
NO - Static variable in class javax.security.auth.callback.ConfirmationCallback
NO option.
NO_COMPRESSION - Static variable in class java.util.zip.Deflater
Compression level for no compression.
NO_CONTEXT - Static variable in exception org.ietf.jgss.GSSException
Invalid security context.
NO_CRED - Static variable in exception org.ietf.jgss.GSSException
Invalid credentials.
NO_DATA_ALLOWED_ERR - Static variable in exception org.w3c.dom.DOMException
If data is specified for a Node which does not support data.
NO_DECOMPOSITION - Static variable in class java.text.Collator
Decomposition mode value.
NO_FIELDS - Static variable in class java.io.ObjectStreamClass
serialPersistentFields value indicating no serializable fields
NO_FLUSH - Static variable in class java.util.zip.Deflater
Compression flush mode used to achieve best compression result.
NO_GENERATED_KEYS - Static variable in interface java.sql.Statement
The constant indicating that generated keys should not be made available for retrieval.
NO_HIGHLIGHT - Static variable in class javax.swing.plaf.basic.BasicScrollBarUI
NO_IMPLEMENT - Exception in org.omg.CORBA
This exception indicates that even though the operation that was invoked exists (it has an IDL definition), no implementation for that operation exists.
NO_IMPLEMENT() - Constructor for exception org.omg.CORBA.NO_IMPLEMENT
Constructs a NO_IMPLEMENT exception with a default minor code of 0, a completion state of CompletionStatus.COMPLETED_NO, and a null description.
NO_IMPLEMENT(String) - Constructor for exception org.omg.CORBA.NO_IMPLEMENT
Constructs a NO_IMPLEMENT exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.
NO_IMPLEMENT(int, CompletionStatus) - Constructor for exception org.omg.CORBA.NO_IMPLEMENT
Constructs a NO_IMPLEMENT exception with the specified minor code and completion status.
NO_IMPLEMENT(String, int, CompletionStatus) - Constructor for exception org.omg.CORBA.NO_IMPLEMENT
Constructs a NO_IMPLEMENT exception with the specified description message, minor code, and completion status.
NO_IMPLICIT_ACTIVATION - Static variable in class org.omg.PortableServer.ImplicitActivationPolicyValue
NO_LOCATION - Static variable in annotation type javax.xml.bind.annotation.XmlSchema
The default value of the XmlSchema.location() attribute, which indicates that the schema generator will generate components in this namespace.
NO_MEMORY - Exception in org.omg.CORBA
Exception thrown when the ORB run time has run out of memory.
NO_MEMORY() - Constructor for exception org.omg.CORBA.NO_MEMORY
Constructs a NO_MEMORY exception with a default minor code of 0, a completion state of CompletionStatus.COMPLETED_NO, and a null description.
NO_MEMORY(String) - Constructor for exception org.omg.CORBA.NO_MEMORY
Constructs a NO_MEMORY exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.
NO_MEMORY(int, CompletionStatus) - Constructor for exception org.omg.CORBA.NO_MEMORY
Constructs a NO_MEMORY exception with the specified minor code and completion status.
NO_MEMORY(String, int, CompletionStatus) - Constructor for exception org.omg.CORBA.NO_MEMORY
Constructs a NO_MEMORY exception with the specified description message, minor code, and completion status.
NO_MODIFICATION_ALLOWED_ERR - Static variable in exception org.w3c.dom.DOMException
If an attempt is made to modify an object where modifications are not allowed.
NO_MORE_EVENTS - Static variable in class javax.print.event.PrintJobEvent
Not all print services may be capable of delivering interesting events, or even telling when a job is complete.
NO_OPTION - Static variable in class javax.swing.JOptionPane
Return value from class method if NO is chosen.
NO_ORIENTATION - Static variable in interface java.awt.Adjustable
Indicates that the Adjustable has no orientation.
NO_PERMISSION - Exception in org.omg.CORBA
Exception thrown when an invocation failed because the caller has insufficient privileges.
NO_PERMISSION() - Constructor for exception org.omg.CORBA.NO_PERMISSION
Constructs a NO_PERMISSION exception with a default minor code of 0 and a completion state of CompletionStatus.COMPLETED_NO, and a null description.
NO_PERMISSION(String) - Constructor for exception org.omg.CORBA.NO_PERMISSION
Constructs a NO_PERMISSION exception with the specified description, a minor code of 0, and a completion state of COMPLETED_NO.
NO_PERMISSION(int, CompletionStatus) - Constructor for exception org.omg.CORBA.NO_PERMISSION
Constructs a NO_PERMISSION exception with the specified minor code and completion status.
NO_PERMISSION(String, int, CompletionStatus) - Constructor for exception org.omg.CORBA.NO_PERMISSION
Constructs a NO_PERMISSION exception with the specified description message, minor code, and completion status.
NO_PROXY - Static variable in class java.net.Proxy
A proxy setting that represents a DIRECT connection, basically telling the protocol handler not to use any proxying.
NO_RESOURCES - Exception in org.omg.CORBA
Exception thrown when the ORB has encountered some general resource limitation.
NO_RESOURCES() - Constructor for exception org.omg.CORBA.NO_RESOURCES
Constructs a NO_RESOURCES exception with a default minor code of 0, a completion state of CompletionStatus.COMPLETED_NO, and a null description.
NO_RESOURCES(String) - Constructor for exception org.omg.CORBA.NO_RESOURCES
Constructs a NO_RESOURCES exception with the specified description, a minor code of 0, and a completion state of COMPLETED_NO.
NO_RESOURCES(int, CompletionStatus) - Constructor for exception org.omg.CORBA.NO_RESOURCES
Constructs a NO_RESOURCES exception with the specified minor code and completion status.
NO_RESOURCES(String, int, CompletionStatus) - Constructor for exception org.omg.CORBA.NO_RESOURCES
Constructs a NO_RESOURCES exception with the specified description message, minor code, and completion status.
NO_RESPONSE - Exception in org.omg.CORBA
This exception is raised if a client attempts to retrieve the result of a deferred synchronous call, but the response for the request is not yet available.
NO_RESPONSE() - Constructor for exception org.omg.CORBA.NO_RESPONSE
Constructs a NO_RESPONSE exception with a default minor code of 0, a completion state of CompletionStatus.COMPLETED_NO, and a null description.
NO_RESPONSE(String) - Constructor for exception org.omg.CORBA.NO_RESPONSE
Constructs a NO_RESPONSE exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.
NO_RESPONSE(int, CompletionStatus) - Constructor for exception org.omg.CORBA.NO_RESPONSE
Constructs a NO_RESPONSE exception with the specified minor code and completion status.
NO_RESPONSE(String, int, CompletionStatus) - Constructor for exception org.omg.CORBA.NO_RESPONSE
Constructs a NO_RESPONSE exception with the specified description message, minor code, and completion status.
NO_ROLE_WITH_NAME - Static variable in class javax.management.relation.RoleStatus
Problem type when trying to access an unknown role.
NO_ROW_CONFLICT - Static variable in interface javax.sql.rowset.spi.SyncResolver
Indicates that no conflict occured while the RowSet object was attempting to update, delete or insert a row in the data source.
NO_SUCH_PAGE - Static variable in interface java.awt.print.Printable
Returned from print to signify that the pageIndex is too large and that the requested page does not exist.
NO_SYNC - Static variable in class javax.sound.midi.Sequencer.SyncMode
A slave synchronization mode indicating that no timing information should be sent to the receiver.
nobject - Static variable in class org.omg.CosNaming.BindingType
NOBUTTON - Static variable in class java.awt.event.MouseEvent
Indicates no mouse buttons; used by MouseEvent.getButton().
NoClassDefFoundError - Error in java.lang
Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.
NoClassDefFoundError() - Constructor for error java.lang.NoClassDefFoundError
Constructs a NoClassDefFoundError with no detail message.
NoClassDefFoundError(String) - Constructor for error java.lang.NoClassDefFoundError
Constructs a NoClassDefFoundError with the specified detail message.
NoConnectionPendingException - Exception in java.nio.channels
Unchecked exception thrown when the finishConnect method of a SocketChannel is invoked without first successfully invoking its connect method.
NoConnectionPendingException() - Constructor for exception java.nio.channels.NoConnectionPendingException
Constructs an instance of this class.
NoContext - Exception in org.omg.PortableServer.CurrentPackage
org/omg/PortableServer/CurrentPackage/NoContext.java .
NoContext() - Constructor for exception org.omg.PortableServer.CurrentPackage.NoContext
NoContext(String) - Constructor for exception org.omg.PortableServer.CurrentPackage.NoContext
NoContextHelper - Class in org.omg.PortableServer.CurrentPackage
org/omg/PortableServer/CurrentPackage/NoContextHelper.java .
NoContextHelper() - Constructor for class org.omg.PortableServer.CurrentPackage.NoContextHelper
node(String) - Method in class java.util.prefs.AbstractPreferences
Implements the node method as per the specification in Preferences.node(String).
node(String) - Method in class java.util.prefs.Preferences
Returns the named preference node in the same tree as this node, creating it and any of its ancestors if they do not already exist.
node() - Method in class java.util.UUID
The node value associated with this UUID.
Node - Interface in javax.xml.soap
A representation of a node (element) in an XML document.
NODE - Static variable in class javax.xml.xpath.XPathConstants
The XPath 1.0 NodeSet data type.
Node - Interface in org.w3c.dom
The Node interface is the primary datatype for the entire Document Object Model.
NODE_ADOPTED - Static variable in interface org.w3c.dom.UserDataHandler
The node is adopted, using Document.adoptNode().
NODE_CLONED - Static variable in interface org.w3c.dom.UserDataHandler
The node is cloned, using Node.cloneNode().
NODE_DELETED - Static variable in interface org.w3c.dom.UserDataHandler
The node is deleted.
NODE_IMPORTED - Static variable in interface org.w3c.dom.UserDataHandler
The node is imported, using Document.importNode().
NODE_RENAMED - Static variable in interface org.w3c.dom.UserDataHandler
The node is renamed, using Document.renameNode().
nodeChanged(TreeNode) - Method in class javax.swing.tree.DefaultTreeModel
Invoke this method after you've changed how node is to be represented in the tree.
NodeChangeEvent - Class in java.util.prefs
An event emitted by a Preferences node to indicate that a child of that node has been added or removed.
NodeChangeEvent(Preferences, Preferences) - Constructor for class java.util.prefs.NodeChangeEvent
Constructs a new NodeChangeEvent instance.
NodeChangeListener - Interface in java.util.prefs
A listener for receiving preference node change events.
nodeDimensions - Variable in class javax.swing.plaf.basic.BasicTreeUI
Reponsible for telling the TreeState the size needed for a node.
nodeDimensions - Variable in class javax.swing.tree.AbstractLayoutCache
Object responsible for getting the size of a node.
nodeExists(String) - Method in class java.util.prefs.AbstractPreferences
Implements the nodeExists method as per the specification in Preferences.nodeExists(String).
nodeExists(String) - Method in class java.util.prefs.Preferences
Returns true if the named preference node exists in the same tree as this node.
NodeList - Interface in org.w3c.dom
The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented.
nodesChanged(TreeNode, int[]) - Method in class javax.swing.tree.DefaultTreeModel
Invoke this method after you've changed how the children identified by childIndicies are to be represented in the tree.
NODESET - Static variable in class javax.xml.xpath.XPathConstants
The XPath 1.0 NodeSet data type.
NodeSetData - Interface in javax.xml.crypto
An abstract representation of a Data type containing a node-set.
nodeStructureChanged(TreeNode) - Method in class javax.swing.tree.DefaultTreeModel
Invoke this method if you've totally changed the children of node and its childrens children...
nodesWereInserted(TreeNode, int[]) - Method in class javax.swing.tree.DefaultTreeModel
Invoke this method after you've inserted some TreeNodes into node.
nodesWereRemoved(TreeNode, int[], Object[]) - Method in class javax.swing.tree.DefaultTreeModel
Invoke this method after you've removed some TreeNodes from node.
noFocusBorder - Static variable in class javax.swing.DefaultListCellRenderer
noFocusBorder - Static variable in class javax.swing.plaf.basic.BasicComboBoxRenderer
An empty Border.
noFocusBorder - Static variable in class javax.swing.table.DefaultTableCellRenderer
NOFRAMES - Static variable in class javax.swing.text.html.HTML.Tag
NOHREF - Static variable in class javax.swing.text.html.HTML.Attribute
NoInitialContextException - Exception in javax.naming
This exception is thrown when no initial context implementation can be created.
NoInitialContextException() - Constructor for exception javax.naming.NoInitialContextException
Constructs an instance of NoInitialContextException.
NoInitialContextException(String) - Constructor for exception javax.naming.NoInitialContextException
Constructs an instance of NoInitialContextException with an explanation.
NON_CONTINUOUS_DIVIDER - Static variable in class javax.swing.plaf.basic.BasicSplitPaneUI
The divider used for non-continuous layout is added to the split pane with this object.
non_existent(Object) - Method in class org.omg.CORBA.portable.Delegate
Determines whether the server object for the object reference has been destroyed.
NON_EXISTENT - Interface in org.omg.PortableInterceptor
org/omg/PortableInterceptor/NON_EXISTENT.java .
non_existent(Servant) - Method in interface org.omg.PortableServer.portable.Delegate
This operation is used to check for the existence of the Object.
NON_RETAIN - Static variable in class org.omg.PortableServer.ServantRetentionPolicyValue
NON_SPACING_MARK - Static variable in class java.lang.Character
General category "Mn" in the Unicode specification.
nonContinuousLayoutDivider - Variable in class javax.swing.plaf.basic.BasicSplitPaneUI
Instance for the shadow of the divider when non continuous layout is being used.
NONCRITICAL - Static variable in interface javax.naming.ldap.Control
Indicates a non-critical control.
NONE - Static variable in class java.awt.GridBagConstraints
Do not resize the component.
NONE - Static variable in class java.awt.JobAttributes.DialogType
The DialogType instance to use for specifying no print dialog.
NONE - Static variable in class javax.print.attribute.standard.Compression
No compression is used.
NONE - Static variable in class javax.print.attribute.standard.Finishings
Perform no binding.
NONE - Static variable in class javax.print.attribute.standard.JobSheets
No job sheets are printed.
NONE - Static variable in class javax.swing.JRootPane
Constant used for the windowDecorationStyle property.
NONE - Static variable in class javax.swing.TransferHandler
An int representing no transfer action.
NONE_OPTION - Static variable in class javax.swing.DebugGraphics
Don't debug graphics operations.
noneOf(Class<E>) - Static method in class java.util.EnumSet
Creates an empty enum set with the specified element type.
NoninvertibleTransformException - Exception in java.awt.geom
The NoninvertibleTransformException class represents an exception that is thrown if an operation is performed requiring the inverse of an AffineTransform object but the AffineTransform is in a non-invertible state.
NoninvertibleTransformException(String) - Constructor for exception java.awt.geom.NoninvertibleTransformException
Constructs an instance of NoninvertibleTransformException with the specified detail message.
NonReadableChannelException - Exception in java.nio.channels
Unchecked exception thrown when an attempt is made to read from a channel that was not originally opened for reading.
NonReadableChannelException() - Constructor for exception java.nio.channels.NonReadableChannelException
Constructs an instance of this class.
NONUPDATABLE_VIEW_SYNC - Static variable in class javax.sql.rowset.spi.SyncProvider
Indicates that a SyncProvider implementation does not support synchronization between a RowSet object and the SQL VIEW used to populate it.
NonWritableChannelException - Exception in java.nio.channels
Unchecked exception thrown when an attempt is made to write to a channel that was not originally opened for writing.
NonWritableChannelException() - Constructor for exception java.nio.channels.NonWritableChannelException
Constructs an instance of this class.
NoPermissionException - Exception in javax.naming
This exception is thrown when attempting to perform an operation for which the client has no permission.
NoPermissionException(String) - Constructor for exception javax.naming.NoPermissionException
Constructs a new instance of NoPermissionException using an explanation.
NoPermissionException() - Constructor for exception javax.naming.NoPermissionException
Constructs a new instance of NoPermissionException.
NOPOS - Static variable in interface javax.tools.Diagnostic
Used to signal that no position is available.
NORESIZE - Static variable in class javax.swing.text.html.HTML.Attribute
NORM_PRIORITY - Static variable in class java.lang.Thread
The default priority that is assigned to a thread.
NORMAL - Static variable in class java.awt.Frame
Frame is in the "normal" state.
NORMAL - Static variable in class java.awt.PageAttributes.PrintQualityType
The PrintQualityType instance to use for specifying a normal print quality.
NORMAL - Static variable in class javax.print.attribute.standard.PrintQuality
Normal or intermediate quality on the printer.
normalize() - Method in class java.net.URI
Normalizes this URI's path.
normalize() - Method in interface java.nio.file.Path
Returns a path that is this path with redundant name elements eliminated.
normalize(CharSequence, Normalizer.Form) - Static method in class java.text.Normalizer
Normalize a sequence of char values.
normalize() - Method in class javax.imageio.metadata.IIOMetadataNode
Does nothing, since IIOMetadataNodes do not contain Text children.
normalize() - Method in class javax.xml.datatype.XMLGregorianCalendar
Normalize this instance to UTC.
normalize() - Method in interface org.w3c.dom.Node
Puts all Text nodes in the full depth of the sub-tree underneath this Node, including attribute nodes, into a "normal" form where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes.
normalizeDocument() - Method in interface org.w3c.dom.Document
This method acts as if the document was going through a save and load cycle, putting the document in a "normal" form.
NormalizedStringAdapter - Class in javax.xml.bind.annotation.adapters
XmlAdapter to handle xs:normalizedString.
NormalizedStringAdapter() - Constructor for class javax.xml.bind.annotation.adapters.NormalizedStringAdapter
normalizeMimeType(String) - Method in class java.awt.datatransfer.DataFlavor
Deprecated.
normalizeMimeType(String) - Method in class javax.activation.ActivationDataFlavor
Deprecated.
normalizeMimeTypeParameter(String, String) - Method in class java.awt.datatransfer.DataFlavor
Deprecated.
normalizeMimeTypeParameter(String, String) - Method in class javax.activation.ActivationDataFlavor
Deprecated.
Normalizer - Class in java.text
This class provides the method normalize which transforms Unicode text into an equivalent composed or decomposed form, allowing for easier sorting and searching of text.
Normalizer.Form - Enum in java.text
This enum provides constants of the four Unicode normalization forms that are described in Unicode Standard Annex #15 — Unicode Normalization Forms and two methods to access them.
normalizeTabRuns(int, int, int, int) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI.TabbedPaneLayout
normalizeTabRuns(int, int, int, int) - Method in class javax.swing.plaf.metal.MetalTabbedPaneUI.TabbedPaneLayout
normalizeWith(Calendar) - Method in class javax.xml.datatype.Duration
Converts the years and months fields into the days field by using a specific time instant as the reference point.
NoRouteToHostException - Exception in java.net
Signals that an error occurred while attempting to connect a socket to a remote address and port.
NoRouteToHostException(String) - Constructor for exception java.net.NoRouteToHostException
Constructs a new NoRouteToHostException with the specified detail message as to why the remote host cannot be reached.
NoRouteToHostException() - Constructor for exception java.net.NoRouteToHostException
Construct a new NoRouteToHostException with no detailed message.
NORTH - Static variable in class java.awt.BorderLayout
The north layout constraint (top of container).
NORTH - Static variable in class java.awt.GridBagConstraints
Put the component at the top of its display area, centered horizontally.
NORTH - Static variable in class javax.swing.SpringLayout
Specifies the top edge of a component's bounding rectangle.
NORTH - Static variable in interface javax.swing.SwingConstants
Compass-direction North (up).
NORTH_EAST - Static variable in interface javax.swing.SwingConstants
Compass-direction north-east (upper right).
NORTH_WEST - Static variable in interface javax.swing.SwingConstants
Compass-direction north west (upper left).
NORTHEAST - Static variable in class java.awt.GridBagConstraints
Put the component at the top-right corner of its display area.
northPane - Variable in class javax.swing.plaf.basic.BasicInternalFrameUI
NORTHWEST - Static variable in class java.awt.GridBagConstraints
Put the component at the top-left corner of its display area.
NoServant - Exception in org.omg.PortableServer.POAPackage
org/omg/PortableServer/POAPackage/NoServant.java .
NoServant() - Constructor for exception org.omg.PortableServer.POAPackage.NoServant
NoServant(String) - Constructor for exception org.omg.PortableServer.POAPackage.NoServant
NoServantHelper - Class in org.omg.PortableServer.POAPackage
org/omg/PortableServer/POAPackage/NoServantHelper.java .
NoServantHelper() - Constructor for class org.omg.PortableServer.POAPackage.NoServantHelper
NOSHADE - Static variable in class javax.swing.text.html.HTML.Attribute
NoSuchAlgorithmException - Exception in java.security
This exception is thrown when a particular cryptographic algorithm is requested but is not available in the environment.
NoSuchAlgorithmException() - Constructor for exception java.security.NoSuchAlgorithmException
Constructs a NoSuchAlgorithmException with no detail message.
NoSuchAlgorithmException(String) - Constructor for exception java.security.NoSuchAlgorithmException
Constructs a NoSuchAlgorithmException with the specified detail message.
NoSuchAlgorithmException(String, Throwable) - Constructor for exception java.security.NoSuchAlgorithmException
Creates a NoSuchAlgorithmException with the specified detail message and cause.
NoSuchAlgorithmException(Throwable) - Constructor for exception java.security.NoSuchAlgorithmException
Creates a NoSuchAlgorithmException with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).
NoSuchAttributeException - Exception in javax.naming.directory
This exception is thrown when attempting to access an attribute that does not exist.
NoSuchAttributeException(String) - Constructor for exception javax.naming.directory.NoSuchAttributeException
Constructs a new instance of NoSuchAttributeException using an explanation.
NoSuchAttributeException() - Constructor for exception javax.naming.directory.NoSuchAttributeException
Constructs a new instance of NoSuchAttributeException.
NoSuchElementException - Exception in java.util
Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.
NoSuchElementException() - Constructor for exception java.util.NoSuchElementException
Constructs a NoSuchElementException with null as its error message string.
NoSuchElementException(String) - Constructor for exception java.util.NoSuchElementException
Constructs a NoSuchElementException, saving a reference to the error message string s for later retrieval by the getMessage method.
NoSuchFieldError - Error in java.lang
Thrown if an application tries to access or modify a specified field of an object, and that object no longer has that field.
NoSuchFieldError() - Constructor for error java.lang.NoSuchFieldError
Constructs a NoSuchFieldError with no detail message.
NoSuchFieldError(String) - Constructor for error java.lang.NoSuchFieldError
Constructs a NoSuchFieldError with the specified detail message.
NoSuchFieldException - Exception in java.lang
Signals that the class doesn't have a field of a specified name.
NoSuchFieldException() - Constructor for exception java.lang.NoSuchFieldException
Constructor.
NoSuchFieldException(String) - Constructor for exception java.lang.NoSuchFieldException
Constructor with a detail message.
NoSuchFileException - Exception in java.nio.file
Checked exception thrown when an attempt is made to access a file that does not exist.
NoSuchFileException(String) - Constructor for exception java.nio.file.NoSuchFileException
Constructs an instance of this class.
NoSuchFileException(String, String, String) - Constructor for exception java.nio.file.NoSuchFileException
Constructs an instance of this class.
NoSuchMechanismException - Exception in javax.xml.crypto
This exception is thrown when a particular XML mechanism is requested but is not available in the environment.
NoSuchMechanismException() - Constructor for exception javax.xml.crypto.NoSuchMechanismException
Constructs a new NoSuchMechanismException with null as its detail message.
NoSuchMechanismException(String) - Constructor for exception javax.xml.crypto.NoSuchMechanismException
Constructs a new NoSuchMechanismException with the specified detail message.
NoSuchMechanismException(String, Throwable) - Constructor for exception javax.xml.crypto.NoSuchMechanismException
Constructs a new NoSuchMechanismException with the specified detail message and cause.
NoSuchMechanismException(Throwable) - Constructor for exception javax.xml.crypto.NoSuchMechanismException
Constructs a new NoSuchMechanismException with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).
NoSuchMethodError - Error in java.lang
Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.
NoSuchMethodError() - Constructor for error java.lang.NoSuchMethodError
Constructs a NoSuchMethodError with no detail message.
NoSuchMethodError(String) - Constructor for error java.lang.NoSuchMethodError
Constructs a NoSuchMethodError with the specified detail message.
NoSuchMethodException - Exception in java.lang
Thrown when a particular method cannot be found.
NoSuchMethodException() - Constructor for exception java.lang.NoSuchMethodException
Constructs a NoSuchMethodException without a detail message.
NoSuchMethodException(String) - Constructor for exception java.lang.NoSuchMethodException
Constructs a NoSuchMethodException with a detail message.
NoSuchObjectException - Exception in java.rmi
A NoSuchObjectException is thrown if an attempt is made to invoke a method on an object that no longer exists in the remote virtual machine.
NoSuchObjectException(String) - Constructor for exception java.rmi.NoSuchObjectException
Constructs a NoSuchObjectException with the specified detail message.
NoSuchPaddingException - Exception in javax.crypto
This exception is thrown when a particular padding mechanism is requested but is not available in the environment.
NoSuchPaddingException() - Constructor for exception javax.crypto.NoSuchPaddingException
Constructs a NoSuchPaddingException with no detail message.
NoSuchPaddingException(String) - Constructor for exception javax.crypto.NoSuchPaddingException
Constructs a NoSuchPaddingException with the specified detail message.
NoSuchProviderException - Exception in java.security
This exception is thrown when a particular security provider is requested but is not available in the environment.
NoSuchProviderException() - Constructor for exception java.security.NoSuchProviderException
Constructs a NoSuchProviderException with no detail message.
NoSuchProviderException(String) - Constructor for exception java.security.NoSuchProviderException
Constructs a NoSuchProviderException with the specified detail message.
not() - Method in class java.math.BigInteger
Returns a BigInteger whose value is (~this).
not(QueryExp) - Static method in class javax.management.Query
Returns a constraint that is the negation of its argument.
NOT_ACCEPTING_JOBS - Static variable in class javax.print.attribute.standard.PrinterIsAcceptingJobs
The printer is currently rejecting any jobs sent to it.
NOT_ATTEMPTED - Static variable in class javax.print.attribute.standard.PDLOverrideSupported
The printer makes no attempt to make the external job attribute values take precedence over embedded instructions in the documents' print data.
not_context - Static variable in class org.omg.CosNaming.NamingContextPackage.NotFoundReason
NOT_FOUND_ERR - Static variable in exception org.w3c.dom.DOMException
If an attempt is made to reference a Node in a context where it does not exist.
not_object - Static variable in class org.omg.CosNaming.NamingContextPackage.NotFoundReason
NOT_SPECIFIED - Static variable in class javax.sound.sampled.AudioSystem
An integer that stands for an unknown numeric value.
NOT_SUPPORTED - Static variable in class javax.print.attribute.standard.ColorSupported
The printer is not capable of any type of color printing.
NOT_SUPPORTED_ERR - Static variable in exception org.w3c.dom.DOMException
If the implementation does not support the requested type of object or operation.
NotActiveException - Exception in java.io
Thrown when serialization or deserialization is not active.
NotActiveException(String) - Constructor for exception java.io.NotActiveException
Constructor to create a new NotActiveException with the reason given.
NotActiveException() - Constructor for exception java.io.NotActiveException
Constructor to create a new NotActiveException without a reason.
NOTATION - Static variable in interface javax.swing.text.html.parser.DTDConstants
Notation - Interface in org.w3c.dom
This interface represents a notation declared in the DTD.
NOTATION_DECLARATION - Static variable in interface javax.xml.stream.XMLStreamConstants
Indicates a Notation
NOTATION_NODE - Static variable in interface org.w3c.dom.Node
The node is a Notation.
notationDecl(String, String, String) - Method in interface org.xml.sax.DTDHandler
Receive notification of a notation declaration event.
notationDecl(String, String, String) - Method in class org.xml.sax.HandlerBase
Deprecated.
Receive notification of a notation declaration.
notationDecl(String, String, String) - Method in class org.xml.sax.helpers.DefaultHandler
Receive notification of a notation declaration.
notationDecl(String, String, String) - Method in class org.xml.sax.helpers.XMLFilterImpl
Filter a notation declaration event.
NotationDeclaration - Interface in javax.xml.stream.events
An interface for handling Notation Declarations Receive notification of a notation declaration event.
NotBoundException - Exception in java.rmi
A NotBoundException is thrown if an attempt is made to lookup or unbind in the registry a name that has no associated binding.
NotBoundException() - Constructor for exception java.rmi.NotBoundException
Constructs a NotBoundException with no specified detail message.
NotBoundException(String) - Constructor for exception java.rmi.NotBoundException
Constructs a NotBoundException with the specified detail message.
NotCompliantMBeanException - Exception in javax.management
Exception which occurs when trying to register an object in the MBean server that is not a JMX compliant MBean.
NotCompliantMBeanException() - Constructor for exception javax.management.NotCompliantMBeanException
Default constructor.
NotCompliantMBeanException(String) - Constructor for exception javax.management.NotCompliantMBeanException
Constructor that allows a specific error message to be specified.
NotContextException - Exception in javax.naming
This exception is thrown when a naming operation proceeds to a point where a context is required to continue the operation, but the resolved object is not a context.
NotContextException(String) - Constructor for exception javax.naming.NotContextException
Constructs a new instance of NotContextException using an explanation.
NotContextException() - Constructor for exception javax.naming.NotContextException
Constructs a new instance of NotContextException.
NotDirectoryException - Exception in java.nio.file
Checked exception thrown when a file system operation, intended for a directory, fails because the file is not a directory.
NotDirectoryException(String) - Constructor for exception java.nio.file.NotDirectoryException
Constructs an instance of this class.
NOTE - Static variable in class java.awt.PageAttributes.MediaType
An alias for NA_LETTER.
note - Variable in class javax.sound.midi.VoiceStatus
The MIDI note that this voice is playing.
NOTE_OFF - Static variable in class javax.sound.midi.ShortMessage
Command value for Note Off message (0x80, or 128)
NOTE_ON - Static variable in class javax.sound.midi.ShortMessage
Command value for Note On message (0x90, or 144)
NotEmpty - Exception in org.omg.CosNaming.NamingContextPackage
org/omg/CosNaming/NamingContextPackage/NotEmpty.java .
NotEmpty() - Constructor for exception org.omg.CosNaming.NamingContextPackage.NotEmpty
NotEmpty(String) - Constructor for exception org.omg.CosNaming.NamingContextPackage.NotEmpty
NotEmptyHelper - Class in org.omg.CosNaming.NamingContextPackage
org/omg/CosNaming/NamingContextPackage/NotEmptyHelper.java .
NotEmptyHelper() - Constructor for class org.omg.CosNaming.NamingContextPackage.NotEmptyHelper
NotEmptyHolder - Class in org.omg.CosNaming.NamingContextPackage
org/omg/CosNaming/NamingContextPackage/NotEmptyHolder.java .
NotEmptyHolder() - Constructor for class org.omg.CosNaming.NamingContextPackage.NotEmptyHolder
NotEmptyHolder(NotEmpty) - Constructor for class org.omg.CosNaming.NamingContextPackage.NotEmptyHolder
noteOff(int, int) - Method in interface javax.sound.midi.MidiChannel
Turns the specified note off.
noteOff(int) - Method in interface javax.sound.midi.MidiChannel
Turns the specified note off.
noteOn(int, int) - Method in interface javax.sound.midi.MidiChannel
Starts the specified note sounding.
notExists(Path, LinkOption...) - Static method in class java.nio.file.Files
Tests whether the file located by this path does not exist.
notFilter(RowFilter<M, I>) - Static method in class javax.swing.RowFilter
Returns a RowFilter that includes entries if the supplied filter does not include the entry.
NotFound - Exception in org.omg.CosNaming.NamingContextPackage
org/omg/CosNaming/NamingContextPackage/NotFound.java .
NotFound() - Constructor for exception org.omg.CosNaming.NamingContextPackage.NotFound
NotFound(NotFoundReason, NameComponent[]) - Constructor for exception org.omg.CosNaming.NamingContextPackage.NotFound
NotFound(String, NotFoundReason, NameComponent[]) - Constructor for exception org.omg.CosNaming.NamingContextPackage.NotFound
NotFoundHelper - Class in org.omg.CosNaming.NamingContextPackage
org/omg/CosNaming/NamingContextPackage/NotFoundHelper.java .
NotFoundHelper() - Constructor for class org.omg.CosNaming.NamingContextPackage.NotFoundHelper
NotFoundHolder - Class in org.omg.CosNaming.NamingContextPackage
org/omg/CosNaming/NamingContextPackage/NotFoundHolder.java .
NotFoundHolder() - Constructor for class org.omg.CosNaming.NamingContextPackage.NotFoundHolder
NotFoundHolder(NotFound) - Constructor for class org.omg.CosNaming.NamingContextPackage.NotFoundHolder
NotFoundReason - Class in org.omg.CosNaming.NamingContextPackage
Indicates the reason for not able to resolve.
NotFoundReason(int) - Constructor for class org.omg.CosNaming.NamingContextPackage.NotFoundReason
NotFoundReasonHelper - Class in org.omg.CosNaming.NamingContextPackage
Indicates the reason for not able to resolve.
NotFoundReasonHelper() - Constructor for class org.omg.CosNaming.NamingContextPackage.NotFoundReasonHelper
NotFoundReasonHolder - Class in org.omg.CosNaming.NamingContextPackage
Indicates the reason for not able to resolve.
NotFoundReasonHolder() - Constructor for class org.omg.CosNaming.NamingContextPackage.NotFoundReasonHolder
NotFoundReasonHolder(NotFoundReason) - Constructor for class org.omg.CosNaming.NamingContextPackage.NotFoundReasonHolder
NotIdentifiableEvent - Interface in javax.xml.bind
This event indicates that a problem was encountered resolving an ID/IDREF.
NotIdentifiableEventImpl - Class in javax.xml.bind.helpers
Default implementation of the NotIdentifiableEvent interface.
NotIdentifiableEventImpl(int, String, ValidationEventLocator) - Constructor for class javax.xml.bind.helpers.NotIdentifiableEventImpl
Create a new NotIdentifiableEventImpl.
NotIdentifiableEventImpl(int, String, ValidationEventLocator, Throwable) - Constructor for class javax.xml.bind.helpers.NotIdentifiableEventImpl
Create a new NotIdentifiableEventImpl.
Notification - Class in javax.management
The Notification class represents a notification emitted by an MBean.
Notification(String, Object, long) - Constructor for class javax.management.Notification
Creates a Notification object.
Notification(String, Object, long, String) - Constructor for class javax.management.Notification
Creates a Notification object.
Notification(String, Object, long, long) - Constructor for class javax.management.Notification
Creates a Notification object.
Notification(String, Object, long, long, String) - Constructor for class javax.management.Notification
Creates a Notification object.
NotificationBroadcaster - Interface in javax.management
Interface implemented by an MBean that emits Notifications.
NotificationBroadcasterSupport - Class in javax.management
Provides an implementation of NotificationEmitter interface.
NotificationBroadcasterSupport() - Constructor for class javax.management.NotificationBroadcasterSupport
Constructs a NotificationBroadcasterSupport where each listener is invoked by the thread sending the notification.
NotificationBroadcasterSupport(Executor) - Constructor for class javax.management.NotificationBroadcasterSupport
Constructs a NotificationBroadcasterSupport where each listener is invoked using the given Executor.
NotificationBroadcasterSupport(MBeanNotificationInfo...) - Constructor for class javax.management.NotificationBroadcasterSupport
Constructs a NotificationBroadcasterSupport with information about the notifications that may be sent.
NotificationBroadcasterSupport(Executor, MBeanNotificationInfo...) - Constructor for class javax.management.NotificationBroadcasterSupport
Constructs a NotificationBroadcasterSupport with information about the notifications that may be sent, and where each listener is invoked using the given Executor.
NotificationEmitter - Interface in javax.management
Interface implemented by an MBean that emits Notifications.
NotificationFilter - Interface in javax.management
To be implemented by a any class acting as a notification filter.
NotificationFilterSupport - Class in javax.management
Provides an implementation of the NotificationFilter interface.
NotificationFilterSupport() - Constructor for class javax.management.NotificationFilterSupport
NotificationListener - Interface in javax.management
Should be implemented by an object that wants to receive notifications.
notificationReceived(UnsolicitedNotificationEvent) - Method in interface javax.naming.ldap.UnsolicitedNotificationListener
Called when an unsolicited notification has been received.
NotificationResult - Class in javax.management.remote
Result of a query for buffered notifications.
NotificationResult(long, long, TargetedNotification[]) - Constructor for class javax.management.remote.NotificationResult
Constructs a notification query result.
notifier - Variable in class java.awt.event.InvocationEvent
The (potentially null) Object whose notifyAll() method will be called immediately after the Runnable.run() method has returned or thrown an exception.
NOTIFS_LOST - Static variable in class javax.management.remote.JMXConnectionNotification
Notification type string for a connection that has possibly lost notifications.
notify() - Method in class java.lang.Object
Wakes up a single thread that is waiting on this object's monitor.
notifyAction - Static variable in class javax.swing.JTextField
Name of the action to send notification that the contents of the field have been accepted.
notifyAction(Action, KeyStroke, KeyEvent, Object, int) - Static method in class javax.swing.SwingUtilities
Invokes actionPerformed on action if action is enabled (and non-null).
notifyAll() - Method in class java.lang.Object
Wakes up all threads that are waiting on this object's monitor.
notifyClientWindowChange(Rectangle) - Method in interface java.awt.im.spi.InputMethod
Notifies this input method of changes in the client window location or state.
notifyCursorMoved() - Method in class javax.sql.rowset.BaseRowSet
Notifies all of the listeners registered with this RowSet object that its cursor has moved.
notifyObservers() - Method in class java.util.Observable
If this object has changed, as indicated by the hasChanged method, then notify all of its observers and then call the clearChanged method to indicate that this object has no longer changed.
notifyObservers(Object) - Method in class java.util.Observable
If this object has changed, as indicated by the hasChanged method, then notify all of its observers and then call the clearChanged method to indicate that this object has no longer changed.
notifyPathChange(Vector, TreePath) - Method in class javax.swing.tree.DefaultTreeSelectionModel
Deprecated.
As of JDK version 1.7
notifyRowChanged() - Method in class javax.sql.rowset.BaseRowSet
Notifies all of the listeners registered with this RowSet object that one of its rows has changed.
notifyRowSetChanged() - Method in class javax.sql.rowset.BaseRowSet
Notifies all of the listeners registered with this RowSet object that its entire contents have changed.
NotLinkException - Exception in java.nio.file
Checked exception thrown when a file system operation fails because a file is not a symbolic link.
NotLinkException(String) - Constructor for exception java.nio.file.NotLinkException
Constructs an instance of this class.
NotLinkException(String, String, String) - Constructor for exception java.nio.file.NotLinkException
Constructs an instance of this class.
NotOwnerException - Exception in java.security.acl
This is an exception that is thrown whenever the modification of an object (such as an Access Control List) is only allowed to be done by an owner of the object, but the Principal attempting the modification is not an owner.
NotOwnerException() - Constructor for exception java.security.acl.NotOwnerException
Constructs a NotOwnerException.
notSelectedTextColor - Variable in class javax.swing.plaf.basic.BasicInternalFrameTitlePane
notSelectedTitleColor - Variable in class javax.swing.plaf.basic.BasicInternalFrameTitlePane
NotSerializableException - Exception in java.io
Thrown when an instance is required to have a Serializable interface.
NotSerializableException(String) - Constructor for exception java.io.NotSerializableException
Constructs a NotSerializableException object with message string.
NotSerializableException() - Constructor for exception java.io.NotSerializableException
Constructs a NotSerializableException object.
NotYetBoundException - Exception in java.nio.channels
Unchecked exception thrown when an attempt is made to invoke an I/O operation upon a server socket channel that is not yet bound.
NotYetBoundException() - Constructor for exception java.nio.channels.NotYetBoundException
Constructs an instance of this class.
NotYetConnectedException - Exception in java.nio.channels
Unchecked exception thrown when an attempt is made to invoke an I/O operation upon a socket channel that is not yet connected.
NotYetConnectedException() - Constructor for exception java.nio.channels.NotYetConnectedException
Constructs an instance of this class.
NoType - Interface in javax.lang.model.type
A pseudo-type used where no actual type is appropriate.
NOVEMBER - Static variable in class java.util.Calendar
Value of the Calendar.MONTH field indicating the eleventh month of the year in the Gregorian and Julian calendars.
NOVEMBER - Static variable in class javax.xml.datatype.DatatypeConstants
Value for eleven month of year.
NOWRAP - Static variable in class javax.swing.text.html.HTML.Attribute
npoints - Variable in class java.awt.Polygon
The total number of points.
NS - Static variable in class javax.xml.ws.wsaddressing.W3CEndpointReference
NSDECL - Static variable in class org.xml.sax.helpers.NamespaceSupport
The namespace declaration URI as a constant.
NT_ANONYMOUS - Static variable in interface org.ietf.jgss.GSSName
Name type for representing an anonymous entity.
NT_EXPORT_NAME - Static variable in interface org.ietf.jgss.GSSName
Name type used to indicate an exported name produced by the export method.
NT_HOSTBASED_SERVICE - Static variable in interface org.ietf.jgss.GSSName
Oid indicating a host-based service name form.
NT_MACHINE_UID_NAME - Static variable in interface org.ietf.jgss.GSSName
Name type to indicate a numeric user identifier corresponding to a user on a local system.
NT_STRING_UID_NAME - Static variable in interface org.ietf.jgss.GSSName
Name type to indicate a string of digits representing the numeric user identifier of a user on a local system.
NT_USER_NAME - Static variable in interface org.ietf.jgss.GSSName
Name type to indicate a named user on a local system.
NULL - Static variable in class java.sql.Types
The constant in the Java programming language that identifies the generic SQL value NULL.
NULL_ATTRIBUTE_VALUE - Static variable in class javax.swing.text.html.HTML
NULL_NS_URI - Static variable in class javax.xml.XMLConstants
Namespace URI to use to represent that there is no Namespace.
NullCipher - Class in javax.crypto
The NullCipher class is a class that provides an "identity cipher" -- one that does not tranform the plaintext.
NullCipher() - Constructor for class javax.crypto.NullCipher
NULLORDER - Static variable in class java.text.CollationElementIterator
Null order which indicates the end of string is reached by the cursor.
nullPlusNonNullIsNull() - Method in interface java.sql.DatabaseMetaData
Retrieves whether this database supports concatenations between NULL and non-NULL values being NULL.
NullPointerException - Exception in java.lang
Thrown when an application attempts to use null in a case where an object is required.
NullPointerException() - Constructor for exception java.lang.NullPointerException
Constructs a NullPointerException with no detail message.
NullPointerException(String) - Constructor for exception java.lang.NullPointerException
Constructs a NullPointerException with the specified detail message.
nullsAreSortedAtEnd() - Method in interface java.sql.DatabaseMetaData
Retrieves whether NULL values are sorted at the end regardless of sort order.
nullsAreSortedAtStart() - Method in interface java.sql.DatabaseMetaData
Retrieves whether NULL values are sorted at the start regardless of sort order.
nullsAreSortedHigh() - Method in interface java.sql.DatabaseMetaData
Retrieves whether NULL values are sorted high.
nullsAreSortedLow() - Method in interface java.sql.DatabaseMetaData
Retrieves whether NULL values are sorted low.
NullType - Interface in javax.lang.model.type
Represents the null type.
NUM_COLORS - Static variable in class java.awt.SystemColor
The number of system colors in the array.
NUM_LOCK - Static variable in class java.awt.Event
The Num Lock key, a non-ASCII action key.
numBands - Variable in class java.awt.image.ComponentSampleModel
The number of bands in this ComponentSampleModel.
numBands - Variable in class java.awt.image.Raster
The number of bands in the Raster.
numBands - Variable in class java.awt.image.SampleModel
Number of bands of the image data that this SampleModel describes.
numBanks - Variable in class java.awt.image.ComponentSampleModel
The number of banks in this ComponentSampleModel.
Number - Class in java.lang
The abstract class Number is the superclass of classes BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and Short.
Number() - Constructor for class java.lang.Number
NUMBER - Static variable in interface javax.swing.text.html.parser.DTDConstants
NUMBER - Static variable in class javax.xml.xpath.XPathConstants
The XPath 1.0 number data type.
NUMBER_FORMS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Number Forms" Unicode character block.
numberFilter(RowFilter.ComparisonType, Number, int...) - Static method in class javax.swing.RowFilter
Returns a RowFilter that includes entries that have at least one Number value meeting the specified criteria.
numberFormat - Variable in class java.text.DateFormat
The number formatter that DateFormat uses to format numbers in dates and times.
NumberFormat - Class in java.text
NumberFormat is the abstract base class for all number formats.
NumberFormat() - Constructor for class java.text.NumberFormat
Sole constructor.
NumberFormat.Field - Class in java.text
Defines constants that are used as attribute keys in the AttributedCharacterIterator returned from NumberFormat.formatToCharacterIterator and as field identifiers in FieldPosition.
NumberFormat.Field(String) - Constructor for class java.text.NumberFormat.Field
Creates a Field instance with the specified name.
NumberFormatException - Exception in java.lang
Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
NumberFormatException() - Constructor for exception java.lang.NumberFormatException
Constructs a NumberFormatException with no detail message.
NumberFormatException(String) - Constructor for exception java.lang.NumberFormatException
Constructs a NumberFormatException with the specified detail message.
NumberFormatProvider - Class in java.text.spi
An abstract class for service providers that provide concrete implementations of the NumberFormat class.
NumberFormatProvider() - Constructor for class java.text.spi.NumberFormatProvider
Sole constructor.
NumberFormatter - Class in javax.swing.text
NumberFormatter subclasses InternationalFormatter adding special behavior for numbers.
NumberFormatter() - Constructor for class javax.swing.text.NumberFormatter
Creates a NumberFormatter with the a default NumberFormat instance obtained from NumberFormat.getNumberInstance().
NumberFormatter(NumberFormat) - Constructor for class javax.swing.text.NumberFormatter
Creates a NumberFormatter with the specified Format instance.
NumberOfDocuments - Class in javax.print.attribute.standard
Class NumberOfDocuments is an integer valued printing attribute that indicates the number of individual docs the printer has accepted for this job, regardless of whether the docs' print data has reached the printer or not.
NumberOfDocuments(int) - Constructor for class javax.print.attribute.standard.NumberOfDocuments
Construct a new number of documents attribute with the given integer value.
NumberOfInterveningJobs - Class in javax.print.attribute.standard
Class NumberOfInterveningJobs is an integer valued printing attribute that indicates the number of jobs that are ahead of this job in the relative chronological order of expected time to complete (i.e., the current scheduled order).
NumberOfInterveningJobs(int) - Constructor for class javax.print.attribute.standard.NumberOfInterveningJobs
Construct a new number of intervening jobs attribute with the given integer value.
numberOfLeadingZeros(int) - Static method in class java.lang.Integer
Returns the number of zero bits preceding the highest-order ("leftmost") one-bit in the two's complement binary representation of the specified int value.
numberOfLeadingZeros(long) - Static method in class java.lang.Long
Returns the number of zero bits preceding the highest-order ("leftmost") one-bit in the two's complement binary representation of the specified long value.
numberOfTrailingZeros(int) - Static method in class java.lang.Integer
Returns the number of zero bits following the lowest-order ("rightmost") one-bit in the two's complement binary representation of the specified int value.
numberOfTrailingZeros(long) - Static method in class java.lang.Long
Returns the number of zero bits following the lowest-order ("rightmost") one-bit in the two's complement binary representation of the specified long value.
NUMBERS - Static variable in interface javax.swing.text.html.parser.DTDConstants
NumberUp - Class in javax.print.attribute.standard
Class NumberUp is an integer valued printing attribute class that specifies the number of print-stream pages to impose upon a single side of an instance of a selected medium.
NumberUp(int) - Constructor for class javax.print.attribute.standard.NumberUp
Construct a new number up attribute with the given integer value.
NumberUpSupported - Class in javax.print.attribute.standard
Class NumberUpSupported is a printing attribute class, a set of integers, that gives the supported values for a NumberUp attribute.
NumberUpSupported(int[][]) - Constructor for class javax.print.attribute.standard.NumberUpSupported
Construct a new number up supported attribute with the given members.
NumberUpSupported(int) - Constructor for class javax.print.attribute.standard.NumberUpSupported
Construct a new number up supported attribute containing a single integer.
NumberUpSupported(int, int) - Constructor for class javax.print.attribute.standard.NumberUpSupported
Construct a new number up supported attribute containing a single range of integers.
numBuffers - Variable in class java.awt.Component.FlipBufferStrategy
The number of buffers
numDataElements - Variable in class java.awt.image.Raster
The number of DataBuffer data elements per pixel.
NUMERIC - Static variable in class java.sql.Types
The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type NUMERIC.
NUMERIC_SHAPING - Static variable in class java.awt.font.TextAttribute
Attribute key for converting ASCII decimal digits to other decimal ranges.
NumericShaper - Class in java.awt.font
The NumericShaper class is used to convert Latin-1 (European) digits to other Unicode decimal digits.
NumericShaper.Range - Enum in java.awt.font
A NumericShaper.Range represents a Unicode range of a script having its own decimal digits.
numProgressivePasses - Variable in class javax.imageio.ImageReadParam
The maximum number of progressive passes to read from the source.
NUTOKEN - Static variable in interface javax.swing.text.html.parser.DTDConstants
NUTOKENS - Static variable in interface javax.swing.text.html.parser.DTDConstants
nval - Variable in class java.io.StreamTokenizer
If the current token is a number, this field contains the value of that number.
NVARCHAR - Static variable in class java.sql.Types
The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type NVARCHAR.
NVList - Class in org.omg.CORBA
A modifiable list containing NamedValue objects.
NVList() - Constructor for class org.omg.CORBA.NVList
NW_RESIZE_CURSOR - Static variable in class java.awt.Cursor
The north-west-resize cursor type.
NW_RESIZE_CURSOR - Static variable in class java.awt.Frame
Deprecated.
replaced by Cursor.NW_RESIZE_CURSOR.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类

提交错误或意见
有关更多的 API 参考资料和开发人员文档，请参阅 Java SE 开发人员文档. 该文档包含更详细的、面向开发人员的描述，以及总体概述、术语定义、使用技巧和工作代码示例。
版权所有 © 1993, 2011, Oracle 及其联盟会员。保留所有权利。
草案 ea-b138

s>Panacnnna/xxE>/ njos


O-Index

请注意：本 java api 1.7Beta 规范不是最终稳定版，未来随着版本的更迭，本规范可能有更新。
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _

O

OAEPParameterSpec - Class in javax.crypto.spec
This class specifies the set of parameters used with OAEP Padding, as defined in the PKCS #1 standard.
OAEPParameterSpec(String, String, AlgorithmParameterSpec, PSource) - Constructor for class javax.crypto.spec.OAEPParameterSpec
Constructs a parameter set for OAEP padding as defined in the PKCS #1 standard using the specified message digest algorithm mdName, mask generation function algorithm mgfName, parameters for the mask generation function mgfSpec, and source of the encoding input P pSrc.
OBJ_ADAPTER - Exception in org.omg.CORBA
This exception typically indicates an administrative mismatch, for example, a server may have made an attempt to register itself with an implementation repository under a name that is already in use, or is unknown to the repository.
OBJ_ADAPTER() - Constructor for exception org.omg.CORBA.OBJ_ADAPTER
Constructs an OBJ_ADAPTER exception with a default minor code of 0, a completion state of CompletionStatus.COMPLETED_NO, and a null description.
OBJ_ADAPTER(String) - Constructor for exception org.omg.CORBA.OBJ_ADAPTER
Constructs an OBJ_ADAPTER exception with the specified description, a minor code of 0, and a completion state of COMPLETED_NO.
OBJ_ADAPTER(int, CompletionStatus) - Constructor for exception org.omg.CORBA.OBJ_ADAPTER
Constructs an OBJ_ADAPTER exception with the specified minor code and completion status.
OBJ_ADAPTER(String, int, CompletionStatus) - Constructor for exception org.omg.CORBA.OBJ_ADAPTER
Constructs an OBJ_ADAPTER exception with the specified description message, minor code, and completion status.
Object - Class in java.lang
Class Object is the root of the class hierarchy.
Object() - Constructor for class java.lang.Object
OBJECT - Static variable in class javax.swing.text.html.HTML.Tag
object - Variable in class javax.swing.undo.StateEdit
The object being edited
Object - Interface in org.omg.CORBA
The definition for a CORBA object reference.
OBJECT_ADDED - Static variable in class javax.naming.event.NamingEvent
Naming event type for indicating that a new object has been added.
OBJECT_CHANGED - Static variable in class javax.naming.event.NamingEvent
Naming event type for indicating that an object has been changed.
OBJECT_FACTORIES - Static variable in interface javax.naming.Context
Constant that holds the name of the environment property for specifying the list of object factories to use.
object_id() - Method in interface org.omg.PortableInterceptor.ServerRequestInfoOperations
Returns the opaque object_id describing the target of the operation invocation.
object_id(Servant) - Method in interface org.omg.PortableServer.portable.Delegate
The method _object_id() is equivalent to calling PortableServer::Current::get_object_id.
OBJECT_NOT_EXIST - Exception in org.omg.CORBA
Exception raised whenever an invocation on a deleted object was performed.
OBJECT_NOT_EXIST() - Constructor for exception org.omg.CORBA.OBJECT_NOT_EXIST
Constructs an OBJECT_NOT_EXIST exception with a default minor code of 0, a completion state of CompletionStatus.COMPLETED_NO, and a null description.
OBJECT_NOT_EXIST(String) - Constructor for exception org.omg.CORBA.OBJECT_NOT_EXIST
Constructs an OBJECT_NOT_EXIST exception with the specified description, a minor code of 0, and a completion state of COMPLETED_NO.
OBJECT_NOT_EXIST(int, CompletionStatus) - Constructor for exception org.omg.CORBA.OBJECT_NOT_EXIST
Constructs an OBJECT_NOT_EXIST exception with the specified minor code and completion status.
OBJECT_NOT_EXIST(String, int, CompletionStatus) - Constructor for exception org.omg.CORBA.OBJECT_NOT_EXIST
Constructs an OBJECT_NOT_EXIST exception with the specified description message, minor code, and completion status.
OBJECT_REMOVED - Static variable in class javax.naming.event.NamingEvent
Naming event type for indicating that an object has been removed.
OBJECT_RENAMED - Static variable in class javax.naming.event.NamingEvent
Naming event type for indicating that an object has been renamed.
OBJECT_SCOPE - Static variable in class javax.naming.directory.SearchControls
Search the named object.
OBJECT_SCOPE - Static variable in interface javax.naming.event.EventContext
Constant for expressing interest in events concerning the object named by the target.
object_to_string(Object) - Method in class org.omg.CORBA.ORB
Converts the given CORBA object reference to a string.
objectAdded(NamingEvent) - Method in interface javax.naming.event.NamespaceChangeListener
Called when an object has been added.
ObjectAlreadyActive - Exception in org.omg.PortableServer.POAPackage
org/omg/PortableServer/POAPackage/ObjectAlreadyActive.java .
ObjectAlreadyActive() - Constructor for exception org.omg.PortableServer.POAPackage.ObjectAlreadyActive
ObjectAlreadyActive(String) - Constructor for exception org.omg.PortableServer.POAPackage.ObjectAlreadyActive
ObjectAlreadyActiveHelper - Class in org.omg.PortableServer.POAPackage
org/omg/PortableServer/POAPackage/ObjectAlreadyActiveHelper.java .
ObjectAlreadyActiveHelper() - Constructor for class org.omg.PortableServer.POAPackage.ObjectAlreadyActiveHelper
objectChanged(NamingEvent) - Method in interface javax.naming.event.ObjectChangeListener
Called when an object has been changed.
ObjectChangeListener - Interface in javax.naming.event
Specifies the method that a listener of a NamingEvent with event type of OBJECT_CHANGED must implement.
ObjectFactory - Interface in javax.naming.spi
This interface represents a factory for creating an object.
ObjectFactoryBuilder - Interface in javax.naming.spi
This interface represents a builder that creates object factories.
ObjectHelper - Class in org.omg.CORBA
ObjectHelper() - Constructor for class org.omg.CORBA.ObjectHelper
ObjectHolder - Class in org.omg.CORBA
The Holder for Object.
ObjectHolder() - Constructor for class org.omg.CORBA.ObjectHolder
Constructs a new ObjectHolder object with its value field initialized to null.
ObjectHolder(Object) - Constructor for class org.omg.CORBA.ObjectHolder
Constructs a new ObjectHolder object with its value field initialized to the given Object.
ObjectIdHelper - Class in org.omg.PortableInterceptor
Type of an object id.
ObjectIdHelper() - Constructor for class org.omg.PortableInterceptor.ObjectIdHelper
ObjectIdHelper - Class in org.omg.PortableInterceptor.ORBInitInfoPackage
Object id, represented as a String
ObjectIdHelper() - Constructor for class org.omg.PortableInterceptor.ORBInitInfoPackage.ObjectIdHelper
ObjectImpl - Class in org.omg.CORBA.portable
The common base class for all stub classes; provides default implementations of the org.omg.CORBA.Object methods.
ObjectImpl() - Constructor for class org.omg.CORBA.portable.ObjectImpl
ObjectImpl - Class in org.omg.CORBA_2_3.portable
ObjectImpl class is the base class for all stubs.
ObjectImpl() - Constructor for class org.omg.CORBA_2_3.portable.ObjectImpl
ObjectInput - Interface in java.io
ObjectInput extends the DataInput interface to include the reading of objects.
ObjectInputStream - Class in java.io
An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream.
ObjectInputStream(InputStream) - Constructor for class java.io.ObjectInputStream
Creates an ObjectInputStream that reads from the specified InputStream.
ObjectInputStream() - Constructor for class java.io.ObjectInputStream
Provide a way for subclasses that are completely reimplementing ObjectInputStream to not have to allocate private data just used by this implementation of ObjectInputStream.
ObjectInputStream.GetField - Class in java.io
Provide access to the persistent fields read from the input stream.
ObjectInputStream.GetField() - Constructor for class java.io.ObjectInputStream.GetField
ObjectInputValidation - Interface in java.io
Callback interface to allow validation of objects within a graph.
ObjectInstance - Class in javax.management
Used to represent the object name of an MBean and its class name.
ObjectInstance(String, String) - Constructor for class javax.management.ObjectInstance
Allows an object instance to be created given a string representation of an object name and the full class name, including the package name.
ObjectInstance(ObjectName, String) - Constructor for class javax.management.ObjectInstance
Allows an object instance to be created given an object name and the full class name, including the package name.
ObjectName - Class in javax.management
Represents the object name of an MBean, or a pattern that can match the names of several MBeans.
ObjectName(String) - Constructor for class javax.management.ObjectName
Construct an object name from the given string.
ObjectName(String, String, String) - Constructor for class javax.management.ObjectName
Construct an object name with exactly one key property.
ObjectName(String, Hashtable<String, String>) - Constructor for class javax.management.ObjectName
Construct an object name with several key properties from a Hashtable.
OBJECTNAME - Static variable in class javax.management.openmbean.SimpleType
The SimpleType instance describing values whose Java class name is javax.management.ObjectName.
ObjectNotActive - Exception in org.omg.PortableServer.POAPackage
org/omg/PortableServer/POAPackage/ObjectNotActive.java .
ObjectNotActive() - Constructor for exception org.omg.PortableServer.POAPackage.ObjectNotActive
ObjectNotActive(String) - Constructor for exception org.omg.PortableServer.POAPackage.ObjectNotActive
ObjectNotActiveHelper - Class in org.omg.PortableServer.POAPackage
org/omg/PortableServer/POAPackage/ObjectNotActiveHelper.java .
ObjectNotActiveHelper() - Constructor for class org.omg.PortableServer.POAPackage.ObjectNotActiveHelper
ObjectOutput - Interface in java.io
ObjectOutput extends the DataOutput interface to include writing of objects.
ObjectOutputStream - Class in java.io
An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream.
ObjectOutputStream(OutputStream) - Constructor for class java.io.ObjectOutputStream
Creates an ObjectOutputStream that writes to the specified OutputStream.
ObjectOutputStream() - Constructor for class java.io.ObjectOutputStream
Provide a way for subclasses that are completely reimplementing ObjectOutputStream to not have to allocate private data just used by this implementation of ObjectOutputStream.
ObjectOutputStream.PutField - Class in java.io
Provide programmatic access to the persistent fields to be written to ObjectOutput.
ObjectOutputStream.PutField() - Constructor for class java.io.ObjectOutputStream.PutField
ObjectReferenceFactory - Interface in org.omg.PortableInterceptor
The object reference factory.
ObjectReferenceFactoryHelper - Class in org.omg.PortableInterceptor
The object reference factory.
ObjectReferenceFactoryHelper() - Constructor for class org.omg.PortableInterceptor.ObjectReferenceFactoryHelper
ObjectReferenceFactoryHolder - Class in org.omg.PortableInterceptor
The object reference factory.
ObjectReferenceFactoryHolder() - Constructor for class org.omg.PortableInterceptor.ObjectReferenceFactoryHolder
ObjectReferenceFactoryHolder(ObjectReferenceFactory) - Constructor for class org.omg.PortableInterceptor.ObjectReferenceFactoryHolder
ObjectReferenceTemplate - Interface in org.omg.PortableInterceptor
The object reference template.
ObjectReferenceTemplateHelper - Class in org.omg.PortableInterceptor
The object reference template.
ObjectReferenceTemplateHelper() - Constructor for class org.omg.PortableInterceptor.ObjectReferenceTemplateHelper
ObjectReferenceTemplateHolder - Class in org.omg.PortableInterceptor
The object reference template.
ObjectReferenceTemplateHolder() - Constructor for class org.omg.PortableInterceptor.ObjectReferenceTemplateHolder
ObjectReferenceTemplateHolder(ObjectReferenceTemplate) - Constructor for class org.omg.PortableInterceptor.ObjectReferenceTemplateHolder
ObjectReferenceTemplateSeqHelper - Class in org.omg.PortableInterceptor
Sequence of object reference templates is used for reporting state changes that do not occur on the adapter manager.
ObjectReferenceTemplateSeqHelper() - Constructor for class org.omg.PortableInterceptor.ObjectReferenceTemplateSeqHelper
ObjectReferenceTemplateSeqHolder - Class in org.omg.PortableInterceptor
Sequence of object reference templates is used for reporting state changes that do not occur on the adapter manager.
ObjectReferenceTemplateSeqHolder() - Constructor for class org.omg.PortableInterceptor.ObjectReferenceTemplateSeqHolder
ObjectReferenceTemplateSeqHolder(ObjectReferenceTemplate[]) - Constructor for class org.omg.PortableInterceptor.ObjectReferenceTemplateSeqHolder
objectRemoved(NamingEvent) - Method in interface javax.naming.event.NamespaceChangeListener
Called when an object has been removed.
objectRenamed(NamingEvent) - Method in interface javax.naming.event.NamespaceChangeListener
Called when an object has been renamed.
Objects - Class in java.util
This class consists of static utility methods for operating on objects.
ObjectStreamClass - Class in java.io
Serialization's descriptor for classes.
ObjectStreamConstants - Interface in java.io
Constants written into the Object Serialization Stream.
ObjectStreamException - Exception in java.io
Superclass of all exceptions specific to Object Stream classes.
ObjectStreamException(String) - Constructor for exception java.io.ObjectStreamException
Create an ObjectStreamException with the specified argument.
ObjectStreamException() - Constructor for exception java.io.ObjectStreamException
Create an ObjectStreamException.
ObjectStreamField - Class in java.io
A description of a Serializable field from a Serializable class.
ObjectStreamField(String, Class<?>) - Constructor for class java.io.ObjectStreamField
Create a Serializable field with the specified type.
ObjectStreamField(String, Class<?>, boolean) - Constructor for class java.io.ObjectStreamField
Creates an ObjectStreamField representing a serializable field with the given name and type.
ObjectView - Class in javax.swing.text.html
Component decorator that implements the view interface for <object> elements.
ObjectView(Element) - Constructor for class javax.swing.text.html.ObjectView
Creates a new ObjectView object.
ObjID - Class in java.rmi.server
An ObjID is used to identify a remote object exported to an RMI runtime.
ObjID() - Constructor for class java.rmi.server.ObjID
Generates a unique object identifier.
ObjID(int) - Constructor for class java.rmi.server.ObjID
Creates a "well-known" object identifier.
Observable - Class in java.util
This class represents an observable object, or "data" in the model-view paradigm.
Observable() - Constructor for class java.util.Observable
Construct an Observable with zero Observers.
OBSERVED_ATTRIBUTE_ERROR - Static variable in class javax.management.monitor.MonitorNotification
Notification type denoting that the observed attribute is not contained in the observed object.
OBSERVED_ATTRIBUTE_ERROR_NOTIFIED - Static variable in class javax.management.monitor.Monitor
Flag denoting that a notification has occurred after changing the observed attribute.
OBSERVED_ATTRIBUTE_TYPE_ERROR - Static variable in class javax.management.monitor.MonitorNotification
Notification type denoting that the type of the observed attribute is not correct.
OBSERVED_ATTRIBUTE_TYPE_ERROR_NOTIFIED - Static variable in class javax.management.monitor.Monitor
Flag denoting that a notification has occurred after changing the observed object or the observed attribute.
OBSERVED_OBJECT_ERROR - Static variable in class javax.management.monitor.MonitorNotification
Notification type denoting that the observed object is not registered in the MBean server.
OBSERVED_OBJECT_ERROR_NOTIFIED - Static variable in class javax.management.monitor.Monitor
Flag denoting that a notification has occurred after changing the observed object.
Observer - Interface in java.util
A class can implement the Observer interface when it wants to be informed of changes in observable objects.
observesDaylightTime() - Method in class java.util.SimpleTimeZone
Returns true if this SimpleTimeZone observes Daylight Saving Time.
observesDaylightTime() - Method in class java.util.TimeZone
Returns true if this TimeZone is currently in Daylight Saving Time, or if a transition from Standard Time to Daylight Saving Time occurs at any future time.
OceanTheme - Class in javax.swing.plaf.metal
The default theme for the MetalLookAndFeel.
OceanTheme() - Constructor for class javax.swing.plaf.metal.OceanTheme
Creates an instance of OceanTheme
OctetSeqHelper - Class in org.omg.CORBA
The Helper for OctetSeq.
OctetSeqHelper() - Constructor for class org.omg.CORBA.OctetSeqHelper
OctetSeqHolder - Class in org.omg.CORBA
The Holder for OctetSeq.
OctetSeqHolder() - Constructor for class org.omg.CORBA.OctetSeqHolder
OctetSeqHolder(byte[]) - Constructor for class org.omg.CORBA.OctetSeqHolder
OctetStreamData - Class in javax.xml.crypto
A representation of a Data type containing an octet stream.
OctetStreamData(InputStream) - Constructor for class javax.xml.crypto.OctetStreamData
Creates a new OctetStreamData.
OctetStreamData(InputStream, String, String) - Constructor for class javax.xml.crypto.OctetStreamData
Creates a new OctetStreamData.
OCTOBER - Static variable in class java.util.Calendar
Value of the Calendar.MONTH field indicating the tenth month of the year in the Gregorian and Julian calendars.
OCTOBER - Static variable in class javax.xml.datatype.DatatypeConstants
Value for tenth month of year.
oEnd - Variable in class javax.swing.text.html.parser.Element
of(char) - Static method in class java.lang.Character.UnicodeBlock
Returns the object representing the Unicode block containing the given character, or null if the character is not a member of a defined block.
of(int) - Static method in class java.lang.Character.UnicodeBlock
Returns the object representing the Unicode block containing the given character (Unicode code point), or null if the character is not a member of a defined block.
of(int) - Static method in enum java.lang.Character.UnicodeScript
Returns the enum constant representing the Unicode script of which the given character (Unicode code point) is assigned to.
of(E) - Static method in class java.util.EnumSet
Creates an enum set initially containing the specified element.
of(E, E) - Static method in class java.util.EnumSet
Creates an enum set initially containing the specified elements.
of(E, E, E) - Static method in class java.util.EnumSet
Creates an enum set initially containing the specified elements.
of(E, E, E, E) - Static method in class java.util.EnumSet
Creates an enum set initially containing the specified elements.
of(E, E, E, E, E) - Static method in class java.util.EnumSet
Creates an enum set initially containing the specified elements.
of(E, E...) - Static method in class java.util.EnumSet
Creates an enum set initially containing the specified elements.
of(String, String) - Static method in class javax.annotation.processing.Completions
Returns a completion of the value and message.
of(String) - Static method in class javax.annotation.processing.Completions
Returns a completion of the value and an empty message
ofCalendarField(int) - Static method in class java.text.DateFormat.Field
Returns the Field constant that corresponds to the Calendar constant calendarField.
OFF - Static variable in class java.util.logging.Level
OFF is a special level that can be used to turn off logging.
offendingNode - Variable in exception javax.imageio.metadata.IIOInvalidTreeException
The Node that led to the parsing error, or null.
offer(E) - Method in class java.util.ArrayDeque
Inserts the specified element at the end of this deque.
offer(E) - Method in class java.util.concurrent.ArrayBlockingQueue
Inserts the specified element at the tail of this queue if it is possible to do so immediately without exceeding the queue's capacity, returning true upon success and false if this queue is full.
offer(E, long, TimeUnit) - Method in class java.util.concurrent.ArrayBlockingQueue
Inserts the specified element at the tail of this queue, waiting up to the specified wait time for space to become available if the queue is full.
offer(E) - Method in interface java.util.concurrent.BlockingDeque
Inserts the specified element into the queue represented by this deque (in other words, at the tail of this deque) if it is possible to do so immediately without violating capacity restrictions, returning true upon success and false if no space is currently available.
offer(E, long, TimeUnit) - Method in interface java.util.concurrent.BlockingDeque
Inserts the specified element into the queue represented by this deque (in other words, at the tail of this deque), waiting up to the specified wait time if necessary for space to become available.
offer(E) - Method in interface java.util.concurrent.BlockingQueue
Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and false if no space is currently available.
offer(E, long, TimeUnit) - Method in interface java.util.concurrent.BlockingQueue
Inserts the specified element into this queue, waiting up to the specified wait time if necessary for space to become available.
offer(E) - Method in class java.util.concurrent.ConcurrentLinkedDeque
Inserts the specified element at the tail of this deque.
offer(E) - Method in class java.util.concurrent.ConcurrentLinkedQueue
Inserts the specified element at the tail of this queue.
offer(E) - Method in class java.util.concurrent.DelayQueue
Inserts the specified element into this delay queue.
offer(E, long, TimeUnit) - Method in class java.util.concurrent.DelayQueue
Inserts the specified element into this delay queue.
offer(E) - Method in class java.util.concurrent.LinkedBlockingDeque
offer(E, long, TimeUnit) - Method in class java.util.concurrent.LinkedBlockingDeque
offer(E, long, TimeUnit) - Method in class java.util.concurrent.LinkedBlockingQueue
Inserts the specified element at the tail of this queue, waiting if necessary up to the specified wait time for space to become available.
offer(E) - Method in class java.util.concurrent.LinkedBlockingQueue
Inserts the specified element at the tail of this queue if it is possible to do so immediately without exceeding the queue's capacity, returning true upon success and false if this queue is full.
offer(E, long, TimeUnit) - Method in class java.util.concurrent.LinkedTransferQueue
Inserts the specified element at the tail of this queue.
offer(E) - Method in class java.util.concurrent.LinkedTransferQueue
Inserts the specified element at the tail of this queue.
offer(E) - Method in class java.util.concurrent.PriorityBlockingQueue
Inserts the specified element into this priority queue.
offer(E, long, TimeUnit) - Method in class java.util.concurrent.PriorityBlockingQueue
Inserts the specified element into this priority queue.
offer(E, long, TimeUnit) - Method in class java.util.concurrent.SynchronousQueue
Inserts the specified element into this queue, waiting if necessary up to the specified wait time for another thread to receive it.
offer(E) - Method in class java.util.concurrent.SynchronousQueue
Inserts the specified element into this queue, if another thread is waiting to receive it.
offer(E) - Method in interface java.util.Deque
Inserts the specified element into the queue represented by this deque (in other words, at the tail of this deque) if it is possible to do so immediately without violating capacity restrictions, returning true upon success and false if no space is currently available.
offer(E) - Method in class java.util.LinkedList
Adds the specified element as the tail (last element) of this list.
offer(E) - Method in class java.util.PriorityQueue
Inserts the specified element into this priority queue.
offer(E) - Method in interface java.util.Queue
Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions.
offerFirst(E) - Method in class java.util.ArrayDeque
Inserts the specified element at the front of this deque.
offerFirst(E) - Method in interface java.util.concurrent.BlockingDeque
Inserts the specified element at the front of this deque if it is possible to do so immediately without violating capacity restrictions, returning true upon success and false if no space is currently available.
offerFirst(E, long, TimeUnit) - Method in interface java.util.concurrent.BlockingDeque
Inserts the specified element at the front of this deque, waiting up to the specified wait time if necessary for space to become available.
offerFirst(E) - Method in class java.util.concurrent.ConcurrentLinkedDeque
Inserts the specified element at the front of this deque.
offerFirst(E) - Method in class java.util.concurrent.LinkedBlockingDeque
offerFirst(E, long, TimeUnit) - Method in class java.util.concurrent.LinkedBlockingDeque
offerFirst(E) - Method in interface java.util.Deque
Inserts the specified element at the front of this deque unless it would violate capacity restrictions.
offerFirst(E) - Method in class java.util.LinkedList
Inserts the specified element at the front of this list.
offerLast(E) - Method in class java.util.ArrayDeque
Inserts the specified element at the end of this deque.
offerLast(E) - Method in interface java.util.concurrent.BlockingDeque
Inserts the specified element at the end of this deque if it is possible to do so immediately without violating capacity restrictions, returning true upon success and false if no space is currently available.
offerLast(E, long, TimeUnit) - Method in interface java.util.concurrent.BlockingDeque
Inserts the specified element at the end of this deque, waiting up to the specified wait time if necessary for space to become available.
offerLast(E) - Method in class java.util.concurrent.ConcurrentLinkedDeque
Inserts the specified element at the end of this deque.
offerLast(E) - Method in class java.util.concurrent.LinkedBlockingDeque
offerLast(E, long, TimeUnit) - Method in class java.util.concurrent.LinkedBlockingDeque
offerLast(E) - Method in interface java.util.Deque
Inserts the specified element at the end of this deque unless it would violate capacity restrictions.
offerLast(E) - Method in class java.util.LinkedList
Inserts the specified element at the end of this list.
offset - Variable in class java.awt.image.DataBuffer
Offset into default (first) bank from which to get the first element.
offset - Variable in class javax.swing.plaf.basic.BasicScrollBarUI.TrackListener
offset - Variable in class javax.swing.plaf.basic.BasicSliderUI.TrackListener
offset - Variable in class javax.swing.text.Segment
This is the offset into the array that the desired text begins.
offset - Variable in class javax.swing.tree.DefaultTreeCellEditor
Used in editing.
offset - Variable in exception org.omg.CORBA.portable.IndirectionException
Points to the stream's offset.
offsetByCodePoints(CharSequence, int, int) - Static method in class java.lang.Character
Returns the index within the given char sequence that is offset from the given index by codePointOffset code points.
offsetByCodePoints(char[], int, int, int, int) - Static method in class java.lang.Character
Returns the index within the given char subarray that is offset from the given index by codePointOffset code points.
offsetByCodePoints(int, int) - Method in class java.lang.String
Returns the index within this String that is offset from the given index by codePointOffset code points.
offsetByCodePoints(int, int) - Method in class java.lang.StringBuffer
offsetRequested() - Method in exception javax.swing.text.BadLocationException
Returns the offset into the document that was not legal.
offsets - Variable in class java.awt.image.DataBuffer
Offsets into all banks.
OGHAM - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Ogham" Unicode character block.
OID - Static variable in class javax.naming.ldap.ManageReferralControl
The ManageReferral control's assigned object identifier is 2.16.840.1.113730.3.4.2.
OID - Static variable in class javax.naming.ldap.PagedResultsControl
The paged-results control's assigned object identifier is 1.2.840.113556.1.4.319.
OID - Static variable in class javax.naming.ldap.PagedResultsResponseControl
The paged-results response control's assigned object identifier is 1.2.840.113556.1.4.319.
OID - Static variable in class javax.naming.ldap.SortControl
The server-side sort control's assigned object identifier is 1.2.840.113556.1.4.473.
OID - Static variable in class javax.naming.ldap.SortResponseControl
The server-side sort response control's assigned object identifier is 1.2.840.113556.1.4.474.
OID - Static variable in class javax.naming.ldap.StartTlsRequest
The StartTLS extended request's assigned object identifier is 1.3.6.1.4.1.1466.20037.
OID - Static variable in class javax.naming.ldap.StartTlsResponse
The StartTLS extended response's assigned object identifier is 1.3.6.1.4.1.1466.20037.
Oid - Class in org.ietf.jgss
This class represents Universal Object Identifiers (Oids) and their associated operations.
Oid(String) - Constructor for class org.ietf.jgss.Oid
Constructs an Oid object from a string representation of its integer components.
Oid(InputStream) - Constructor for class org.ietf.jgss.Oid
Creates an Oid object from its ASN.1 DER encoding.
Oid(byte[]) - Constructor for class org.ietf.jgss.Oid
Creates an Oid object from its ASN.1 DER encoding.
OK - Static variable in class javax.security.auth.callback.ConfirmationCallback
OK option.
OK_CANCEL_OPTION - Static variable in class javax.security.auth.callback.ConfirmationCallback
OK/CANCEL confirmation confirmation option.
OK_CANCEL_OPTION - Static variable in class javax.swing.JOptionPane
Type used for showConfirmDialog.
OK_OPTION - Static variable in class javax.swing.JOptionPane
Return value form class method if OK is chosen.
okToUseGui - Variable in class java.beans.beancontext.BeanContextSupport
A boolean indicating if this instance may now render a GUI.
okToUseGui() - Method in class java.beans.beancontext.BeanContextSupport
Notify this instance that it may now render a GUI
okToUseGui() - Method in interface java.beans.Visibility
This method instructs the bean that it is OK to use the Gui.
OL - Static variable in class javax.swing.text.html.HTML.Tag
OL_CHIKI - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Ol Chiki" Unicode character block.
OLD_ITALIC - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Old Italic" Unicode character block.
OLD_PERSIAN - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Old Persian" Unicode character block.
OLD_SOUTH_ARABIAN - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Old South Arabian" Unicode character block.
OLD_TOKEN - Static variable in exception org.ietf.jgss.GSSException
The token's validity period has expired.
OLD_TURKIC - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Old Turkic" Unicode character block.
oldBinding - Variable in class javax.naming.event.NamingEvent
Contains information about the object before the change.
oldBorderPainted - Variable in class javax.swing.plaf.basic.BasicMenuItemUI
oldLeadSelectionPath - Variable in class javax.swing.event.TreeSelectionEvent
leadSelectionPath before the paths changed, may be null.
OMGVMCID - Interface in org.omg.CORBA
The vendor minor code ID reserved for OMG.
OMIT_XML_DECLARATION - Static variable in class javax.xml.transform.OutputKeys
omit-xml-declaration = "yes" | "no".
omitEnd() - Method in class javax.swing.text.html.parser.Element
Return true if the end tag can be omitted.
omitStart() - Method in class javax.swing.text.html.parser.Element
Return true if the start tag can be omitted.
on(boolean) - Method in class java.security.DigestInputStream
Turns the digest function on or off.
on(boolean) - Method in class java.security.DigestOutputStream
Turns the digest function on or off.
onAdvance(int, int) - Method in class java.util.concurrent.Phaser
Overridable method to perform an action upon impending phase advance, and to control termination.
onDeregistration(ServiceRegistry, Class<?>) - Method in class javax.imageio.spi.IIOServiceProvider
A callback that will be whenever the Spi class has been deregistered from a ServiceRegistry.
onDeregistration(ServiceRegistry, Class<?>) - Method in interface javax.imageio.spi.RegisterableService
Called when an object implementing this interface is removed from the given category of the given registry.
ONE - Static variable in class java.math.BigDecimal
The value 1, with a scale of 0.
ONE - Static variable in class java.math.BigInteger
The BigInteger constant one.
ONE_DAY - Static variable in class javax.management.timer.Timer
Number of milliseconds in one day.
ONE_HOUR - Static variable in class javax.management.timer.Timer
Number of milliseconds in one hour.
ONE_MINUTE - Static variable in class javax.management.timer.Timer
Number of milliseconds in one minute.
ONE_SECOND - Static variable in class javax.management.timer.Timer
Number of milliseconds in one second.
ONE_SIDED - Static variable in class java.awt.JobAttributes.SidesType
The SidesType instance to use for specifying that consecutive job pages should be printed upon the same side of consecutive media sheets.
ONE_SIDED - Static variable in class javax.print.attribute.standard.Sides
Imposes each consecutive print-stream page upon the same side of consecutive media sheets.
ONE_TOUCH_EXPANDABLE_PROPERTY - Static variable in class javax.swing.JSplitPane
Bound property for oneTouchExpandable.
ONE_TOUCH_OFFSET - Static variable in class javax.swing.plaf.basic.BasicSplitPaneDivider
ONE_TOUCH_SIZE - Static variable in class javax.swing.plaf.basic.BasicSplitPaneDivider
Width or height of the divider based on orientation BasicSplitPaneUI adds two to this.
ONE_WEEK - Static variable in class javax.management.timer.Timer
Number of milliseconds in one week.
ONELEVEL_SCOPE - Static variable in class javax.naming.directory.SearchControls
Search one level of the named context.
ONELEVEL_SCOPE - Static variable in interface javax.naming.event.EventContext
Constant for expressing interest in events concerning objects in the context named by the target, excluding the context named by the target.
oneTouchExpandable - Variable in class javax.swing.JSplitPane
Is a little widget provided to quickly expand/collapse the split pane?
oneTouchExpandableChanged() - Method in class javax.swing.plaf.basic.BasicSplitPaneDivider
Messaged when the oneTouchExpandable value of the JSplitPane the receiver is contained in changes.
Oneway - Annotation Type in javax.jws
Indicates that the given @WebMethod has only an input message and no output.
onMalformedInput(CodingErrorAction) - Method in class java.nio.charset.CharsetDecoder
Changes this decoder's action for malformed-input errors.
onMalformedInput(CodingErrorAction) - Method in class java.nio.charset.CharsetEncoder
Changes this encoder's action for malformed-input errors.
onRegistration(ServiceRegistry, Class<?>) - Method in class javax.imageio.spi.IIOServiceProvider
A callback that will be called exactly once after the Spi class has been instantiated and registered in a ServiceRegistry.
onRegistration(ServiceRegistry, Class<?>) - Method in interface javax.imageio.spi.RegisterableService
Called when an object implementing this interface is added to the given category of the given registry.
onStart() - Method in class java.util.concurrent.ForkJoinWorkerThread
Initializes internal state after construction but before processing any tasks.
onTermination(Throwable) - Method in class java.util.concurrent.ForkJoinWorkerThread
Performs cleanup associated with termination of this worker thread.
onUnmappableCharacter(CodingErrorAction) - Method in class java.nio.charset.CharsetDecoder
Changes this decoder's action for unmappable-character errors.
onUnmappableCharacter(CodingErrorAction) - Method in class java.nio.charset.CharsetEncoder
Changes this encoder's action for unmappable-character errors.
OP_ACCEPT - Static variable in class java.nio.channels.SelectionKey
Operation-set bit for socket-accept operations.
OP_CONNECT - Static variable in class java.nio.channels.SelectionKey
Operation-set bit for socket-connect operations.
op_name() - Method in class org.omg.CORBA.ServerRequest
Deprecated.
use operation()
OP_READ - Static variable in class java.nio.channels.SelectionKey
Operation-set bit for read operations.
OP_WRITE - Static variable in class java.nio.channels.SelectionKey
Operation-set bit for write operations.
OPAQUE - Static variable in interface java.awt.Transparency
Represents image data that is guaranteed to be completely opaque, meaning that all pixels have an alpha value of 1.0.
OPAQUE - Static variable in class javax.accessibility.AccessibleState
Indicates this object paints every pixel within its rectangular region.
OPC_LIFE_OVER - Static variable in class javax.print.attribute.standard.PrinterStateReason
The optical photo conductor is no longer functioning.
OPC_NEAR_EOL - Static variable in class javax.print.attribute.standard.PrinterStateReason
The optical photo conductor is near end of life.
open(File) - Method in class java.awt.Desktop
Launches the associated application to open the file.
OPEN - Static variable in class java.awt.geom.Arc2D
The closure type for an open arc with no path segments connecting the two ends of the arc segment.
open(Path, Set<? extends OpenOption>, ExecutorService, FileAttribute<?>...) - Static method in class java.nio.channels.AsynchronousFileChannel
Opens or creates a file for reading and/or writing, returning an asynchronous file channel to access the file.
open(Path, OpenOption...) - Static method in class java.nio.channels.AsynchronousFileChannel
Opens or creates a file for reading and/or writing, returning an asynchronous file channel to access the file.
open(AsynchronousChannelGroup) - Static method in class java.nio.channels.AsynchronousServerSocketChannel
Opens an asynchronous server-socket channel.
open() - Static method in class java.nio.channels.AsynchronousServerSocketChannel
Opens an asynchronous server-socket channel.
open(AsynchronousChannelGroup) - Static method in class java.nio.channels.AsynchronousSocketChannel
Opens an asynchronous socket channel.
open() - Static method in class java.nio.channels.AsynchronousSocketChannel
Opens an asynchronous socket channel.
open() - Static method in class java.nio.channels.DatagramChannel
Opens a datagram channel.
open(ProtocolFamily) - Static method in class java.nio.channels.DatagramChannel
Opens a datagram channel.
open(Path, Set<? extends OpenOption>, FileAttribute<?>...) - Static method in class java.nio.channels.FileChannel
Opens or creates a file, returning a file channel to access the file.
open(Path, OpenOption...) - Static method in class java.nio.channels.FileChannel
Opens or creates a file, returning a file channel to access the file.
open() - Static method in class java.nio.channels.Pipe
Opens a pipe.
open() - Static method in class java.nio.channels.Selector
Opens a selector.
open() - Static method in class java.nio.channels.ServerSocketChannel
Opens a server-socket channel.
open() - Static method in class java.nio.channels.SocketChannel
Opens a socket channel.
open(SocketAddress) - Static method in class java.nio.channels.SocketChannel
Opens a socket channel and connects it to a remote address.
open() - Method in interface javax.sound.midi.MidiDevice
Opens the device, indicating that it should now acquire any system resources it requires and become operational.
open(AudioFormat, byte[], int, int) - Method in interface javax.sound.sampled.Clip
Opens the clip, meaning that it should acquire any required system resources and become operational.
open(AudioInputStream) - Method in interface javax.sound.sampled.Clip
Opens the clip with the format and audio data present in the provided audio input stream.
open() - Method in interface javax.sound.sampled.Line
Opens the line, indicating that it should acquire any required system resources and become operational.
OPEN - Static variable in class javax.sound.sampled.LineEvent.Type
A type of event that is sent when a line opens, reserving system resources for itself.
open(AudioFormat, int) - Method in interface javax.sound.sampled.SourceDataLine
Opens the line with the specified format and suggested buffer size, causing the line to acquire any required system resources and become operational.
open(AudioFormat) - Method in interface javax.sound.sampled.SourceDataLine
Opens the line with the specified format, causing the line to acquire any required system resources and become operational.
open(AudioFormat, int) - Method in interface javax.sound.sampled.TargetDataLine
Opens the line with the specified format and requested buffer size, causing the line to acquire any required system resources and become operational.
open(AudioFormat) - Method in interface javax.sound.sampled.TargetDataLine
Opens the line with the specified format, causing the line to acquire any required system resources and become operational.
OPEN_DELETE - Static variable in class java.util.zip.ZipFile
Mode flag to open a zip file and mark it for deletion.
OPEN_DIALOG - Static variable in class javax.swing.JFileChooser
Type value indicating that the JFileChooser supports an "Open" file operation.
OPEN_FAILURE - Static variable in class java.util.logging.ErrorManager
OPEN_FAILURE is used when an open of an output stream fails.
OPEN_READ - Static variable in class java.util.zip.ZipFile
Mode flag to open a zip file for reading.
OPEN_TYPE_FIELD - Static variable in class javax.management.JMX
The name of the openType field.
openAsynchronousChannelGroup(int, ThreadFactory) - Method in class java.nio.channels.spi.AsynchronousChannelProvider
Constructs a new asynchronous channel group with a fixed thread pool.
openAsynchronousChannelGroup(ExecutorService, int) - Method in class java.nio.channels.spi.AsynchronousChannelProvider
Constructs a new asynchronous channel group with the given thread pool.
openAsynchronousServerSocketChannel(AsynchronousChannelGroup) - Method in class java.nio.channels.spi.AsynchronousChannelProvider
Opens an asynchronous server-socket channel.
openAsynchronousSocketChannel(AsynchronousChannelGroup) - Method in class java.nio.channels.spi.AsynchronousChannelProvider
Opens an asynchronous socket channel.
openButtonMnemonic - Variable in class javax.swing.plaf.basic.BasicFileChooserUI
openButtonText - Variable in class javax.swing.plaf.basic.BasicFileChooserUI
openButtonToolTipText - Variable in class javax.swing.plaf.basic.BasicFileChooserUI
openConnection() - Method in class java.net.URL
Returns a URLConnection instance that represents a connection to the remote object referred to by the URL.
openConnection(Proxy) - Method in class java.net.URL
Same as URL.openConnection(), except that the connection will be made through the specified proxy; Protocol handlers that do not support proxing will ignore the proxy parameter and make a normal connection.
openConnection(URL) - Method in class java.net.URLStreamHandler
Opens a connection to the object referenced by the URL argument.
openConnection(URL, Proxy) - Method in class java.net.URLStreamHandler
Same as openConnection(URL), except that the connection will be made through the specified proxy; Protocol handlers that do not support proxying will ignore the proxy parameter and make a normal connection.
OpenDataException - Exception in javax.management.openmbean
This checked exception is thrown when an open type, an open data or an open MBean metadata info instance could not be constructed because one or more validity constraints were not met.
OpenDataException() - Constructor for exception javax.management.openmbean.OpenDataException
An OpenDataException with no detail message.
OpenDataException(String) - Constructor for exception javax.management.openmbean.OpenDataException
An OpenDataException with a detail message.
openDatagramChannel() - Method in class java.nio.channels.spi.SelectorProvider
Opens a datagram channel.
openDatagramChannel(ProtocolFamily) - Method in class java.nio.channels.spi.SelectorProvider
Opens a datagram channel.
OPENED - Static variable in class javax.management.remote.JMXConnectionNotification
Notification type string for a connection-opened notification.
openFrame(JInternalFrame) - Method in class javax.swing.DefaultDesktopManager
Normally this method will not be called.
openFrame(JInternalFrame) - Method in interface javax.swing.DesktopManager
If possible, display this frame in an appropriate location.
openIcon - Variable in class javax.swing.tree.DefaultTreeCellRenderer
Icon used to show non-leaf nodes that are expanded.
openInputStream() - Method in interface javax.tools.FileObject
Gets an InputStream for this file object.
openInputStream() - Method in class javax.tools.ForwardingFileObject
openInputStream() - Method in class javax.tools.SimpleJavaFileObject
This implementation always throws UnsupportedOperationException.
OpenMBeanAttributeInfo - Interface in javax.management.openmbean
Describes an attribute of an open MBean.
OpenMBeanAttributeInfoSupport - Class in javax.management.openmbean
Describes an attribute of an open MBean.
OpenMBeanAttributeInfoSupport(String, String, OpenType<?>, boolean, boolean, boolean) - Constructor for class javax.management.openmbean.OpenMBeanAttributeInfoSupport
Constructs an OpenMBeanAttributeInfoSupport instance, which describes the attribute of an open MBean with the specified name, openType and 描述, and the specified read/write access properties.
OpenMBeanAttributeInfoSupport(String, String, OpenType<?>, boolean, boolean, boolean, Descriptor) - Constructor for class javax.management.openmbean.OpenMBeanAttributeInfoSupport
Constructs an OpenMBeanAttributeInfoSupport instance, which describes the attribute of an open MBean with the specified name, openType, 描述, read/write access properties, and Descriptor.
OpenMBeanAttributeInfoSupport(String, String, OpenType<T>, boolean, boolean, boolean, T) - Constructor for class javax.management.openmbean.OpenMBeanAttributeInfoSupport
Constructs an OpenMBeanAttributeInfoSupport instance, which describes the attribute of an open MBean with the specified name, openType, 描述 and defaultValue, and the specified read/write access properties.
OpenMBeanAttributeInfoSupport(String, String, OpenType<T>, boolean, boolean, boolean, T, T[]) - Constructor for class javax.management.openmbean.OpenMBeanAttributeInfoSupport
Constructs an OpenMBeanAttributeInfoSupport instance, which describes the attribute of an open MBean with the specified name, openType, 描述, defaultValue and legalValues, and the specified read/write access properties.
OpenMBeanAttributeInfoSupport(String, String, OpenType<T>, boolean, boolean, boolean, T, Comparable<T>, Comparable<T>) - Constructor for class javax.management.openmbean.OpenMBeanAttributeInfoSupport
Constructs an OpenMBeanAttributeInfoSupport instance, which describes the attribute of an open MBean, with the specified name, openType, 描述, defaultValue, minValue and maxValue.
OpenMBeanConstructorInfo - Interface in javax.management.openmbean
Describes a constructor of an Open MBean.
OpenMBeanConstructorInfoSupport - Class in javax.management.openmbean
Describes a constructor of an Open MBean.
OpenMBeanConstructorInfoSupport(String, String, OpenMBeanParameterInfo[]) - Constructor for class javax.management.openmbean.OpenMBeanConstructorInfoSupport
Constructs an OpenMBeanConstructorInfoSupport instance, which describes the constructor of a class of open MBeans with the specified name, 描述 and signature.
OpenMBeanConstructorInfoSupport(String, String, OpenMBeanParameterInfo[], Descriptor) - Constructor for class javax.management.openmbean.OpenMBeanConstructorInfoSupport
Constructs an OpenMBeanConstructorInfoSupport instance, which describes the constructor of a class of open MBeans with the specified name, 描述, signature, and descriptor.
OpenMBeanInfo - Interface in javax.management.openmbean
Describes an Open MBean: an Open MBean is recognized as such if its getMBeanInfo() method returns an instance of a class which implements the OpenMBeanInfo interface, typically OpenMBeanInfoSupport.
OpenMBeanInfoSupport - Class in javax.management.openmbean
The OpenMBeanInfoSupport class describes the management information of an open MBean: it is a subclass of MBeanInfo, and it implements the OpenMBeanInfo interface.
OpenMBeanInfoSupport(String, String, OpenMBeanAttributeInfo[], OpenMBeanConstructorInfo[], OpenMBeanOperationInfo[], MBeanNotificationInfo[]) - Constructor for class javax.management.openmbean.OpenMBeanInfoSupport
Constructs an OpenMBeanInfoSupport instance, which describes a class of open MBeans with the specified className, 描述, openAttributes, openConstructors , openOperations and notifications.
OpenMBeanInfoSupport(String, String, OpenMBeanAttributeInfo[], OpenMBeanConstructorInfo[], OpenMBeanOperationInfo[], MBeanNotificationInfo[], Descriptor) - Constructor for class javax.management.openmbean.OpenMBeanInfoSupport
Constructs an OpenMBeanInfoSupport instance, which describes a class of open MBeans with the specified className, 描述, openAttributes, openConstructors , openOperations, notifications, and descriptor.
OpenMBeanOperationInfo - Interface in javax.management.openmbean
Describes an operation of an Open MBean.
OpenMBeanOperationInfoSupport - Class in javax.management.openmbean
Describes an operation of an Open MBean.
OpenMBeanOperationInfoSupport(String, String, OpenMBeanParameterInfo[], OpenType<?>, int) - Constructor for class javax.management.openmbean.OpenMBeanOperationInfoSupport
Constructs an OpenMBeanOperationInfoSupport instance, which describes the operation of a class of open MBeans, with the specified name, 描述, signature, returnOpenType and impact.
OpenMBeanOperationInfoSupport(String, String, OpenMBeanParameterInfo[], OpenType<?>, int, Descriptor) - Constructor for class javax.management.openmbean.OpenMBeanOperationInfoSupport
Constructs an OpenMBeanOperationInfoSupport instance, which describes the operation of a class of open MBeans, with the specified name, 描述, signature, returnOpenType, impact, and descriptor.
OpenMBeanParameterInfo - Interface in javax.management.openmbean
Describes a parameter used in one or more operations or constructors of an open MBean.
OpenMBeanParameterInfoSupport - Class in javax.management.openmbean
Describes a parameter used in one or more operations or constructors of an open MBean.
OpenMBeanParameterInfoSupport(String, String, OpenType<?>) - Constructor for class javax.management.openmbean.OpenMBeanParameterInfoSupport
Constructs an OpenMBeanParameterInfoSupport instance, which describes the parameter used in one or more operations or constructors of a class of open MBeans, with the specified name, openType and 描述.
OpenMBeanParameterInfoSupport(String, String, OpenType<?>, Descriptor) - Constructor for class javax.management.openmbean.OpenMBeanParameterInfoSupport
Constructs an OpenMBeanParameterInfoSupport instance, which describes the parameter used in one or more operations or constructors of a class of open MBeans, with the specified name, openType, 描述, and descriptor.
OpenMBeanParameterInfoSupport(String, String, OpenType<T>, T) - Constructor for class javax.management.openmbean.OpenMBeanParameterInfoSupport
Constructs an OpenMBeanParameterInfoSupport instance, which describes the parameter used in one or more operations or constructors of a class of open MBeans, with the specified name, openType, 描述 and defaultValue.
OpenMBeanParameterInfoSupport(String, String, OpenType<T>, T, T[]) - Constructor for class javax.management.openmbean.OpenMBeanParameterInfoSupport
Constructs an OpenMBeanParameterInfoSupport instance, which describes the parameter used in one or more operations or constructors of a class of open MBeans, with the specified name, openType, 描述, defaultValue and legalValues.
OpenMBeanParameterInfoSupport(String, String, OpenType<T>, T, Comparable<T>, Comparable<T>) - Constructor for class javax.management.openmbean.OpenMBeanParameterInfoSupport
Constructs an OpenMBeanParameterInfoSupport instance, which describes the parameter used in one or more operations or constructors of a class of open MBeans, with the specified name, openType, 描述, defaultValue, minValue and maxValue.
openMenuKey - Variable in class javax.swing.plaf.basic.BasicInternalFrameUI
Deprecated.
As of Java 2 platform v1.3.
OpenOption - Interface in java.nio.file
An object that configures how to open or create a file.
openOutputStream() - Method in interface javax.tools.FileObject
Gets an OutputStream for this file object.
openOutputStream() - Method in class javax.tools.ForwardingFileObject
openOutputStream() - Method in class javax.tools.SimpleJavaFileObject
This implementation always throws UnsupportedOperationException.
openPipe() - Method in class java.nio.channels.spi.SelectorProvider
Opens a pipe.
openReader(boolean) - Method in interface javax.tools.FileObject
Gets a reader for this object.
openReader(boolean) - Method in class javax.tools.ForwardingFileObject
openReader(boolean) - Method in class javax.tools.SimpleJavaFileObject
Wraps the result of SimpleJavaFileObject.getCharContent(boolean) in a Reader.
openSelector() - Method in class java.nio.channels.spi.SelectorProvider
Opens a selector.
openServerSocketChannel() - Method in class java.nio.channels.spi.SelectorProvider
Opens a server-socket channel.
openSocketChannel() - Method in class java.nio.channels.spi.SelectorProvider
Opens a socket channel.
openStream() - Method in class java.net.URL
Opens a connection to this URL and returns an InputStream for reading from that connection.
OpenType - Interface in java.awt.font
The OpenType interface represents OpenType and TrueType fonts.
OpenType<T> - Class in javax.management.openmbean
The OpenType class is the parent abstract class of all classes which describe the actual open type of open data values.
OpenType(String, String, String) - Constructor for class javax.management.openmbean.OpenType
Constructs an OpenType instance (actually a subclass instance as OpenType is abstract), checking for the validity of the given parameters.
openWriter() - Method in interface javax.tools.FileObject
Gets a Writer for this file object.
openWriter() - Method in class javax.tools.ForwardingFileObject
openWriter() - Method in class javax.tools.SimpleJavaFileObject
Wraps the result of openOutputStream in a Writer.
OPERATING_SYSTEM_MXBEAN_NAME - Static variable in class java.lang.management.ManagementFactory
String representation of the ObjectName for the OperatingSystemMXBean.
OperatingSystemMXBean - Interface in java.lang.management
The management interface for the operating system on which the Java virtual machine is running.
Operation - Class in java.rmi.server
Deprecated.
no replacement
Operation(String) - Constructor for class java.rmi.server.Operation
Deprecated.
no replacement
operation() - Method in class org.omg.CORBA.Request
Retrieves the name of the method to be invoked.
operation() - Method in class org.omg.CORBA.ServerRequest
Throws an org.omg.CORBA.NO_IMPLEMENT exception.
operation() - Method in interface org.omg.PortableInterceptor.RequestInfoOperations
Returns the name of the operation being invoked.
operation_context() - Method in interface org.omg.PortableInterceptor.RequestInfoOperations
Returns an array of String objects containing the contexts being sent on the request.
OperationNotSupportedException - Exception in javax.naming
This exception is thrown when a context implementation does not support the operation being invoked.
OperationNotSupportedException() - Constructor for exception javax.naming.OperationNotSupportedException
Constructs a new instance of OperationNotSupportedException.
OperationNotSupportedException(String) - Constructor for exception javax.naming.OperationNotSupportedException
Constructs a new instance of OperationNotSupportedException using an explanation.
OperationsException - Exception in javax.management
Represents exceptions thrown in the MBean server when performing operations on MBeans.
OperationsException() - Constructor for exception javax.management.OperationsException
Default constructor.
OperationsException(String) - Constructor for exception javax.management.OperationsException
Constructor that allows a specific error message to be specified.
OPTICAL_CHARACTER_RECOGNITION - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Optical Character Recognition" Unicode character block.
OPTION - Static variable in class javax.swing.text.html.HTML.Tag
Option - Class in javax.swing.text.html
Value for the ListModel used to represent <option> elements.
Option(AttributeSet) - Constructor for class javax.swing.text.html.Option
Creates a new Option object.
OPTION_PANE - Static variable in class javax.accessibility.AccessibleRole
A specialized pane whose primary use is inside a DIALOG
OPTION_PANE - Static variable in class javax.swing.plaf.synth.Region
OptionPane region.
OPTION_TYPE_PROPERTY - Static variable in class javax.swing.JOptionPane
Bound property name for optionType.
OPTIONAL - Static variable in class javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag
Optional LoginModule.
OptionalDataException - Exception in java.io
Exception indicating the failure of an object read operation due to unread primitive data, or the end of data belonging to a serialized object in the stream.
OptionChecker - Interface in javax.tools
Interface for recognizing options.
optionPane - Variable in class javax.swing.plaf.basic.BasicOptionPaneUI
JOptionPane that the receiver is providing the look and feel for.
OptionPaneUI - Class in javax.swing.plaf
Pluggable look and feel interface for JOptionPane.
OptionPaneUI() - Constructor for class javax.swing.plaf.OptionPaneUI
options - Variable in class javax.swing.JOptionPane
Options to display to the user.
OPTIONS_PROPERTY - Static variable in class javax.swing.JOptionPane
Bound property name for option.
optionType - Variable in class javax.swing.JOptionPane
Option type, one of DEFAULT_OPTION, YES_NO_OPTION, YES_NO_CANCEL_OPTION or OK_CANCEL_OPTION.
or(BigInteger) - Method in class java.math.BigInteger
Returns a BigInteger whose value is (this | val).
or(BitSet) - Method in class java.util.BitSet
Performs a logical OR of this bit set with the bit set argument.
or(QueryExp, QueryExp) - Static method in class javax.management.Query
Returns a query expression that is the disjunction of two other query expressions.
orange - Static variable in class java.awt.Color
The color orange.
ORANGE - Static variable in class java.awt.Color
The color orange.
orb() - Method in interface javax.rmi.CORBA.Tie
Returns the ORB for this tie.
orb(ORB) - Method in interface javax.rmi.CORBA.Tie
Sets the ORB for this tie.
ORB - Class in org.omg.CORBA
A class providing APIs for the CORBA Object Request Broker features.
ORB() - Constructor for class org.omg.CORBA.ORB
orb(Object) - Method in class org.omg.CORBA.portable.Delegate
Provides a reference to the orb associated with its parameter.
orb() - Method in class org.omg.CORBA.portable.InputStream
Returns the ORB that created this InputStream.
orb() - Method in class org.omg.CORBA.portable.OutputStream
Returns the ORB that created this OutputStream.
ORB - Class in org.omg.CORBA_2_3
A class extending org.omg.CORBA.ORB to make the ORB portable under the OMG CORBA version 2.3 specification.
ORB() - Constructor for class org.omg.CORBA_2_3.ORB
orb(Servant) - Method in interface org.omg.PortableServer.portable.Delegate
Convenience method that returns the instance of the ORB currently associated with the Servant.
ORB_CTRL_MODEL - Static variable in class org.omg.PortableServer.ThreadPolicyValue
orb_id() - Method in interface org.omg.PortableInterceptor.ObjectReferenceTemplate
orb_id() - Method in interface org.omg.PortableInterceptor.ORBInitInfoOperations
Returns the ID of the ORB being initialized.
orb_id() - Method in interface org.omg.PortableInterceptor.ServerRequestInfoOperations
Returns the ID that was used to create the ORB.
ORBIdHelper - Class in org.omg.PortableInterceptor
org/omg/PortableInterceptor/ORBIdHelper.java .
ORBIdHelper() - Constructor for class org.omg.PortableInterceptor.ORBIdHelper
ORBInitializer - Interface in org.omg.PortableInterceptor
Facilitates interceptor registration and ORB initialization.
ORBInitializerOperations - Interface in org.omg.PortableInterceptor
Facilitates interceptor registration and ORB initialization.
ORBInitInfo - Interface in org.omg.PortableInterceptor
Passed to each ORBInitializer, allowing it to to register interceptors and perform other duties while the ORB is initializing.
ORBInitInfoOperations - Interface in org.omg.PortableInterceptor
Passed to each ORBInitializer, allowing it to to register interceptors and perform other duties while the ORB is initializing.
order() - Method in class java.nio.ByteBuffer
Retrieves this buffer's byte order.
order(ByteOrder) - Method in class java.nio.ByteBuffer
Modifies this buffer's byte order.
order() - Method in class java.nio.CharBuffer
Retrieves this buffer's byte order.
order() - Method in class java.nio.DoubleBuffer
Retrieves this buffer's byte order.
order() - Method in class java.nio.FloatBuffer
Retrieves this buffer's byte order.
order() - Method in class java.nio.IntBuffer
Retrieves this buffer's byte order.
order() - Method in class java.nio.LongBuffer
Retrieves this buffer's byte order.
order() - Method in class java.nio.ShortBuffer
Retrieves this buffer's byte order.
ordered - Variable in class javax.naming.directory.BasicAttribute
A flag for recording whether this attribute's values are ordered.
ordinal() - Method in class java.lang.Enum
Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).
ordinaryChar(int) - Method in class java.io.StreamTokenizer
Specifies that the character argument is "ordinary" in this tokenizer.
ordinaryChars(int, int) - Method in class java.io.StreamTokenizer
Specifies that all characters c in the range low <= c <= high are "ordinary" in this tokenizer.
orFilter(Iterable<? extends RowFilter<? super M, ? super I>>) - Static method in class javax.swing.RowFilter
Returns a RowFilter that includes entries if any of the supplied filters includes the entry.
org.ietf.jgss - package org.ietf.jgss
This package presents a framework that allows application developers to make use of security services like authentication, data integrity and data confidentiality from a variety of underlying security mechanisms like Kerberos, using a unified API.
org.omg.CORBA - package org.omg.CORBA
Provides the mapping of the OMG CORBA APIs to the JavaTM programming language, including the class ORB, which is implemented so that a programmer can use it as a fully-functional Object Request Broker (ORB).
org.omg.CORBA.DynAnyPackage - package org.omg.CORBA.DynAnyPackage
Provides the exceptions used with the DynAny interface (InvalidValue, Invalid, InvalidSeq, and TypeMismatch).
org.omg.CORBA.ORBPackage - package org.omg.CORBA.ORBPackage
Provides the exception InvalidName, which is thrown by the method ORB.resolve_initial_references and the exception InconsistentTypeCode, which is thrown by the Dynamic Any creation methods in the ORB class.
org.omg.CORBA.portable - package org.omg.CORBA.portable
Provides a portability layer, that is, a set of ORB APIs that makes it possible for code generated by one vendor to run on another vendor's ORB.
org.omg.CORBA.TypeCodePackage - package org.omg.CORBA.TypeCodePackage
Provides the user-defined exceptions BadKind and Bounds, which are thrown by methods in in the class TypeCode.
org.omg.CORBA_2_3 - package org.omg.CORBA_2_3
The CORBA_2_3 package defines additions to existing CORBA interfaces in the Java[tm] Standard Edition 6. These changes occurred in recent revisions to the CORBA API defined by the OMG. The new methods were added to interfaces derived from the corresponding interfaces in the CORBA package. This provides backward compatibility and avoids breaking the JCK tests.
org.omg.CORBA_2_3.portable - package org.omg.CORBA_2_3.portable
Provides methods for the input and output of value types, and contains other updates to the org/omg/CORBA/portable package.
org.omg.CosNaming - package org.omg.CosNaming
Provides a naming service for Java IDL.
org.omg.CosNaming.NamingContextExtPackage - package org.omg.CosNaming.NamingContextExtPackage
This package contains the following classes, which are used in org.omg.CosNaming.NamingContextExt:
org.omg.CosNaming.NamingContextPackage - package org.omg.CosNaming.NamingContextPackage
This package contains Exception classes for the org.omg.CosNaming package.
org.omg.Dynamic - package org.omg.Dynamic
This package contains the Dynamic module specified in the OMG Portable Interceptor specification, http://cgi.omg.org/cgi-bin/doc?ptc/2000-08-06, section 21.9.
org.omg.DynamicAny - package org.omg.DynamicAny
Provides classes and interfaces that enable traversal of the data value associated with an any at runtime, and extraction of the primitive constituents of the data value.
org.omg.DynamicAny.DynAnyFactoryPackage - package org.omg.DynamicAny.DynAnyFactoryPackage
This package contains classes and exceptions from the DynAnyFactory interface of the DynamicAny module specified in the OMG The Common Object Request Broker: Architecture and Specification, http://cgi.omg.org/cgi-bin/doc?formal/99-10-07, section 9.2.2.
org.omg.DynamicAny.DynAnyPackage - package org.omg.DynamicAny.DynAnyPackage
This package contains classes and exceptions from the DynAny interface of the DynamicAny module specified in the OMG The Common Object Request Broker: Architecture and Specification, http://cgi.omg.org/cgi-bin/doc?formal/99-10-07, section 9.2.
org.omg.IOP - package org.omg.IOP
This package contains the IOP module specified in the OMG document The Common Object Request Broker: Architecture and Specification, http://cgi.omg.org/cgi-bin/doc?formal/99-10-07, section 13.6.
org.omg.IOP.CodecFactoryPackage - package org.omg.IOP.CodecFactoryPackage
This package contains the exceptions specified in the IOP::CodeFactory interface (as part of the Portable Interceptors spec).
org.omg.IOP.CodecPackage - package org.omg.IOP.CodecPackage
This package is generated from the IOP::Codec IDL interface definition.
org.omg.Messaging - package org.omg.Messaging
This package contains the Messaging module specified in the OMG CORBA Messaging specification, http://cgi.omg.org/cgi-bin/doc?formal/99-10-07.
org.omg.PortableInterceptor - package org.omg.PortableInterceptor
Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.
org.omg.PortableInterceptor.ORBInitInfoPackage - package org.omg.PortableInterceptor.ORBInitInfoPackage
This package contains the exceptions and typedefs from the ORBInitInfo local interface of the PortableInterceptor module specified in the OMG Portable Interceptor specification, http://cgi.omg.org/cgi-bin/doc?ptc/2000-08-06, section 21.7.2.
org.omg.PortableServer - package org.omg.PortableServer
Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.CurrentPackage - package org.omg.PortableServer.CurrentPackage
Provides method implementations with access to the identity of the object on which the method was invoked.
org.omg.PortableServer.POAManagerPackage - package org.omg.PortableServer.POAManagerPackage
Encapsulates the processing state of the POAs it is associated with.
org.omg.PortableServer.POAPackage - package org.omg.PortableServer.POAPackage
Allows programmers to construct object implementations that are portable between different ORB products.
org.omg.PortableServer.portable - package org.omg.PortableServer.portable
Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.ServantLocatorPackage - package org.omg.PortableServer.ServantLocatorPackage
Provides classes and interfaces for locating the servant.
org.omg.SendingContext - package org.omg.SendingContext
Provides support for the marshalling of value types.
org.omg.stub.java.rmi - package org.omg.stub.java.rmi
Contains RMI-IIOP Stubs for the Remote types that occur in the java.rmi package.
org.w3c.dom - package org.w3c.dom
Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.
org.w3c.dom.bootstrap - package org.w3c.dom.bootstrap
org.w3c.dom.events - package org.w3c.dom.events
org.w3c.dom.ls - package org.w3c.dom.ls
org.xml.sax - package org.xml.sax
This package provides the core SAX APIs.
org.xml.sax.ext - package org.xml.sax.ext
This package contains interfaces to SAX2 facilities that conformant SAX drivers won't necessarily support.
org.xml.sax.helpers - package org.xml.sax.helpers
This package contains "helper" classes, including support for bootstrapping SAX-based applications.
orientation - Variable in class javax.swing.JProgressBar
Whether the progress bar is horizontal or vertical.
orientation - Variable in class javax.swing.JScrollBar
orientation - Variable in class javax.swing.JSlider
Whether the slider is horizontal or vertical The default is horizontal.
orientation - Variable in class javax.swing.JSplitPane
How the views are split.
orientation - Variable in class javax.swing.plaf.basic.BasicSplitPaneDivider
Orientation of the JSplitPane.
Orientation - Static variable in class javax.swing.text.StyleConstants
Orientation for a paragraph.
ORIENTATION_PROPERTY - Static variable in class javax.swing.JSplitPane
Bound property name for orientation (horizontal or vertical).
OrientationRequested - Class in javax.print.attribute.standard
Class OrientationRequested is a printing attribute class, an enumeration, that indicates the desired orientation for printed print-stream pages; it does not describe the orientation of the client-supplied print-stream pages.
OrientationRequested(int) - Constructor for class javax.print.attribute.standard.OrientationRequested
Construct a new orientation requested enumeration value with the given integer value.
origin - Variable in class javax.swing.plaf.basic.BasicToolBarUI.DockingListener
ORIGINAL_TYPE_FIELD - Static variable in class javax.management.JMX
The name of the originalType field.
originalEx - Variable in exception org.omg.CORBA.portable.UnknownException
A throwable--the original exception that was wrapped in a CORBA UnknownException.
OriginateDirection - Static variable in class javax.swing.text.DefaultStyledDocument.ElementSpec
A possible value for getDirection.
originatingProvider - Variable in class javax.imageio.ImageReader
The ImageReaderSpi that instantiated this object, or null if its identity is not known or none exists.
originatingProvider - Variable in class javax.imageio.ImageWriter
The ImageWriterSpi that instantiated this object, or null if its identity is not known or none exists.
origmodel - Variable in class java.awt.image.RGBImageFilter
The ColorModel to be replaced by newmodel when the user calls substituteColorModel.
ORIYA - Static variable in class java.awt.font.NumericShaper
Identifies the ORIYA range and decimal base.
ORIYA - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Oriya" Unicode character block.
OSMANYA - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Osmanya" Unicode character block.
oStart - Variable in class javax.swing.text.html.parser.Element
OTHER - Static variable in class java.sql.Types
The constant in the Java programming language that indicates that the SQL type is database-specific and gets mapped to a Java object that can be accessed via the methods getObject and setObject.
OTHER - Static variable in class javax.print.attribute.standard.PrinterStateReason
The printer has detected an error other than ones listed below.
OTHER_LETTER - Static variable in class java.lang.Character
General category "Lo" in the Unicode specification.
OTHER_NUMBER - Static variable in class java.lang.Character
General category "No" in the Unicode specification.
OTHER_PUNCTUATION - Static variable in class java.lang.Character
General category "Po" in the Unicode specification.
OTHER_SYMBOL - Static variable in class java.lang.Character
General category "So" in the Unicode specification.
othersDeletesAreVisible(int) - Method in interface java.sql.DatabaseMetaData
Retrieves whether deletes made by others are visible.
othersInsertsAreVisible(int) - Method in interface java.sql.DatabaseMetaData
Retrieves whether inserts made by others are visible.
othersUpdatesAreVisible(int) - Method in interface java.sql.DatabaseMetaData
Retrieves whether updates made by others are visible.
out - Static variable in class java.io.FileDescriptor
A handle to the standard output stream.
out - Variable in class java.io.FilterOutputStream
The underlying output stream to be filtered.
out - Variable in class java.io.FilterWriter
The underlying character-output stream.
out - Variable in class java.io.PipedInputStream
The index of the position in the circular buffer at which the next byte of data will be read by this piped input stream.
out - Variable in class java.io.PrintWriter
The underlying character-output stream of this PrintWriter.
out - Static variable in class java.lang.System
The "standard" output stream.
out() - Method in class java.util.Formatter
Returns the destination for the output.
OUT_BOTTOM - Static variable in class java.awt.geom.Rectangle2D
The bitmask that indicates that a point lies below this Rectangle2D.
OUT_LEFT - Static variable in class java.awt.geom.Rectangle2D
The bitmask that indicates that a point lies to the left of this Rectangle2D.
OUT_RIGHT - Static variable in class java.awt.geom.Rectangle2D
The bitmask that indicates that a point lies to the right of this Rectangle2D.
OUT_TOP - Static variable in class java.awt.geom.Rectangle2D
The bitmask that indicates that a point lies above this Rectangle2D.
OUTBOUND_MESSAGE_ATTACHMENTS - Static variable in interface javax.xml.ws.handler.MessageContext
Standard property: Map of attachments to a message for the outbound message, key is the MIME Content-ID, value is a DataHandler.
outcode(double, double) - Method in class java.awt.geom.Rectangle2D.Double
Determines where the specified coordinates lie with respect to this Rectangle2D.
outcode(double, double) - Method in class java.awt.geom.Rectangle2D.Float
Determines where the specified coordinates lie with respect to this Rectangle2D.
outcode(double, double) - Method in class java.awt.geom.Rectangle2D
Determines where the specified coordinates lie with respect to this Rectangle2D.
outcode(Point2D) - Method in class java.awt.geom.Rectangle2D
Determines where the specified Point2D lies with respect to this Rectangle2D.
outcode(double, double) - Method in class java.awt.Rectangle
Determines where the specified coordinates lie with respect to this Rectangle2D.
OUTLINE_DRAG_MODE - Static variable in class javax.swing.JDesktopPane
Indicates that an outline only of the item being dragged should appear inside the desktop pane.
OutOfMemoryError - Error in java.lang
Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.
OutOfMemoryError() - Constructor for error java.lang.OutOfMemoryError
Constructs an OutOfMemoryError with no detail message.
OutOfMemoryError(String) - Constructor for error java.lang.OutOfMemoryError
Constructs an OutOfMemoryError with the specified detail message.
outpixbuf - Variable in class java.awt.image.ReplicateScaleFilter
A byte array initialized with a size of ReplicateScaleFilter.destWidth and used to deliver a row of pixel data to the ImageConsumer.
output - Variable in class javax.imageio.ImageWriter
The ImageOutputStream or other Object set by setOutput and retrieved by getOutput.
output(char[], int, int) - Method in class javax.swing.text.AbstractWriter
The last stop in writing out content.
output(char[], int, int) - Method in class javax.swing.text.html.HTMLWriter
This method is overriden to map any character entities, such as < to &lt;.
OUTPUT_AREA_ALMOST_FULL - Static variable in class javax.print.attribute.standard.PrinterStateReason
One or more output areas are almost full (e.g.
OUTPUT_AREA_FULL - Static variable in class javax.print.attribute.standard.PrinterStateReason
One or more output areas are full (e.g.
OUTPUT_TRAY_MISSING - Static variable in class javax.print.attribute.standard.PrinterStateReason
One or more output trays are not in the device.
outputClass - Variable in class javax.imageio.spi.ImageOutputStreamSpi
A 类 object indicating the legal object type for use by the createInputStreamInstance method.
OutputDeviceAssigned - Class in javax.print.attribute.standard
Class OutputDeviceAssigned is a printing attribute class, a text attribute, that identifies the output device to which the service has assigned this job.
OutputDeviceAssigned(String, Locale) - Constructor for class javax.print.attribute.standard.OutputDeviceAssigned
Constructs a new output device assigned attribute with the given device name and locale.
OutputKeys - Class in javax.xml.transform
Provides string constants that can be used to set output properties for a Transformer, or to retrieve output properties from a Transformer or Templates object.
OutputStream - Class in java.io
This abstract class is the superclass of all classes representing an output stream of bytes.
OutputStream() - Constructor for class java.io.OutputStream
OutputStream - Class in org.omg.CORBA.portable
OuputStream is the Java API for writing IDL types to CDR marshal streams.
OutputStream() - Constructor for class org.omg.CORBA.portable.OutputStream
OutputStream - Class in org.omg.CORBA_2_3.portable
OutputStream provides interface for writing of all of the mapped IDL type to the stream.
OutputStream() - Constructor for class org.omg.CORBA_2_3.portable.OutputStream
OutputStreamWriter - Class in java.io
An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset.
OutputStreamWriter(OutputStream, String) - Constructor for class java.io.OutputStreamWriter
Creates an OutputStreamWriter that uses the named charset.
OutputStreamWriter(OutputStream) - Constructor for class java.io.OutputStreamWriter
Creates an OutputStreamWriter that uses the default character encoding.
OutputStreamWriter(OutputStream, Charset) - Constructor for class java.io.OutputStreamWriter
Creates an OutputStreamWriter that uses the given charset.
OutputStreamWriter(OutputStream, CharsetEncoder) - Constructor for class java.io.OutputStreamWriter
Creates an OutputStreamWriter that uses the given charset encoder.
outputTypes - Variable in class javax.imageio.spi.ImageWriterSpi
An array of 类 objects to be returned from getOutputTypes, initially null.
outsideBorder - Variable in class javax.swing.border.CompoundBorder
OVER - Static variable in class java.awt.dnd.DragSourceContext
An int used by updateCurrentCursor() indicating that the Cursor is over a DropTarget.
OVERFLOW - Static variable in class java.nio.charset.CoderResult
Result object indicating overflow, meaning that there is insufficient room in the output buffer.
OVERFLOW - Static variable in class java.nio.file.StandardWatchEventKind
A special event to indicate that events may have been lost or discarded.
OverlappingFileLockException - Exception in java.nio.channels
Unchecked exception thrown when an attempt is made to acquire a lock on a region of a file that overlaps a region already locked by the same Java virtual machine, or when another thread is already waiting to lock an overlapping region of the same file.
OverlappingFileLockException() - Constructor for exception java.nio.channels.OverlappingFileLockException
Constructs an instance of this class.
overlaps(long, long) - Method in class java.nio.channels.FileLock
Tells whether or not this lock overlaps the given lock range.
OverlayLayout - Class in javax.swing
A layout manager to arrange components over the top of each other.
OverlayLayout(Container) - Constructor for class javax.swing.OverlayLayout
Constructs a layout manager that performs overlay arrangement of the children.
Override - Annotation Type in java.lang
Indicates that a method declaration is intended to override a method declaration in a supertype.
overrides(ExecutableElement, ExecutableElement, TypeElement) - Method in interface javax.lang.model.util.Elements
Tests whether one method, as a member of a given type, overrides another method.
ownDeletesAreVisible(int) - Method in interface java.sql.DatabaseMetaData
Retrieves whether a result set's own deletes are visible.
owner - Variable in class java.awt.datatransfer.Clipboard
owner() - Method in interface java.nio.file.attribute.PosixFileAttributes
Returns the owner of the file.
Owner - Interface in java.security.acl
Interface for managing owners of Access Control Lists (ACLs) or ACL configurations.
ownInsertsAreVisible(int) - Method in interface java.sql.DatabaseMetaData
Retrieves whether a result set's own inserts are visible.
owns(AbstractQueuedLongSynchronizer.ConditionObject) - Method in class java.util.concurrent.locks.AbstractQueuedLongSynchronizer
Queries whether the given ConditionObject uses this synchronizer as its lock.
owns(AbstractQueuedSynchronizer.ConditionObject) - Method in class java.util.concurrent.locks.AbstractQueuedSynchronizer
Queries whether the given ConditionObject uses this synchronizer as its lock.
ownUpdatesAreVisible(int) - Method in interface java.sql.DatabaseMetaData
Retrieves whether for the given type of ResultSet object, the result set's own updates are visible.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类

提交错误或意见
有关更多的 API 参考资料和开发人员文档，请参阅 Java SE 开发人员文档. 该文档包含更详细的、面向开发人员的描述，以及总体概述、术语定义、使用技巧和工作代码示例。
版权所有 © 1993, 2011, Oracle 及其联盟会员。保留所有权利。
草案 ea-b138

iins chdddMsnns/


P-Index

请注意：本 java api 1.7Beta 规范不是最终稳定版，未来随着版本的更迭，本规范可能有更新。
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _

P

P - Static variable in class javax.swing.text.html.HTML.Tag
p - Variable in class javax.swing.text.html.parser.DTD
pack() - Method in class java.awt.Window
Causes this Window to be sized to fit the preferred size and layouts of its subcomponents.
pack(JarFile, OutputStream) - Method in interface java.util.jar.Pack200.Packer
Takes a JarFile and converts it into a Pack200 archive.
pack(JarInputStream, OutputStream) - Method in interface java.util.jar.Pack200.Packer
Takes a JarInputStream and converts it into a Pack200 archive.
pack() - Method in class javax.swing.JInternalFrame
Causes subcomponents of this JInternalFrame to be laid out at their preferred size.
pack() - Method in class javax.swing.JPopupMenu
Lays out the container so that it uses the minimum space needed to display its contents.
Pack200 - Class in java.util.jar
Transforms a JAR file to or from a packed stream in Pack200 format.
Pack200.Packer - Interface in java.util.jar
The packer engine applies various transformations to the input JAR file, making the pack stream highly compressible by a compressor such as gzip or zip.
Pack200.Unpacker - Interface in java.util.jar
The unpacker engine converts the packed stream to a JAR file.
软件包 - Static variable in class java.lang.invoke.MethodHandles.Lookup
A single-bit mask representing 软件包 access (default access), which may contribute to the result of lookupModes.
软件包 - Class in java.lang
软件包 objects contain version information about the implementation and specification of a Java package.
PackageElement - Interface in javax.lang.model.element
Represents a package program element.
packagePrefix - Static variable in interface java.rmi.server.LoaderHandler
Deprecated.
软件包 of system LoaderHandler implementation.
packagePrefix - Static variable in interface java.rmi.server.RemoteRef
Initialize the server package prefix: assumes that the implementation of server ref classes (e.g., UnicastRef, UnicastServerRef) are located in the package defined by the prefix.
packagesIn(Iterable<? extends Element>) - Static method in class javax.lang.model.util.ElementFilter
Returns a list of packages in elements.
packagesIn(Set<? extends Element>) - Static method in class javax.lang.model.util.ElementFilter
Returns a set of packages in elements.
PackedColorModel - Class in java.awt.image
The PackedColorModel class is an abstract ColorModel class that works with pixel values which represent color and alpha information as separate samples and which pack all samples for a single pixel into a single int, short, or byte quantity.
PackedColorModel(ColorSpace, int, int[], int, boolean, int, int) - Constructor for class java.awt.image.PackedColorModel
Constructs a PackedColorModel from a color mask array, which specifies which bits in an int pixel representation contain each of the color samples, and an alpha mask.
PackedColorModel(ColorSpace, int, int, int, int, int, boolean, int, int) - Constructor for class java.awt.image.PackedColorModel
Constructs a PackedColorModel from the specified masks which indicate which bits in an int pixel representation contain the alpha, red, green and blue color samples.
padding - Variable in class javax.swing.plaf.basic.BasicComboBoxUI
If specified, these insets act as padding around the cell renderer when laying out and painting the "selected" item in the combo box.
padding - Variable in class javax.swing.plaf.basic.BasicOptionPaneUI.ButtonAreaLayout
PADDING - Static variable in class javax.swing.text.html.CSS.Attribute
PADDING_BOTTOM - Static variable in class javax.swing.text.html.CSS.Attribute
PADDING_LEFT - Static variable in class javax.swing.text.html.CSS.Attribute
PADDING_RIGHT - Static variable in class javax.swing.text.html.CSS.Attribute
PADDING_TOP - Static variable in class javax.swing.text.html.CSS.Attribute
padSelectedTab(int, int) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI.TabbedPaneLayout
padSelectedTab(int, int) - Method in class javax.swing.plaf.metal.MetalTabbedPaneUI.TabbedPaneLayout
padSpaceBetweenStrings - Static variable in class javax.swing.plaf.metal.MetalToolTipUI
padTabRun(int, int, int, int) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI.TabbedPaneLayout
PAGE_AXIS - Static variable in class javax.swing.BoxLayout
Specifies that components should be laid out in the direction that lines flow across a page as determined by the target container's ComponentOrientation property.
PAGE_END - Static variable in class java.awt.BorderLayout
The component comes after the last line of the layout's content.
PAGE_END - Static variable in class java.awt.GridBagConstraints
Place the component centered along the edge of its display area associated with the end of a page for the current ComponentOrientation.
PAGE_EXISTS - Static variable in interface java.awt.print.Printable
Returned from Printable.print(Graphics, PageFormat, int) to signify that the requested page was rendered.
PAGE_START - Static variable in class java.awt.BorderLayout
The component comes before the first line of the layout's content.
PAGE_START - Static variable in class java.awt.GridBagConstraints
Place the component centered along the edge of its display area associated with the start of a page for the current ComponentOrientation.
PAGE_TAB - Static variable in class javax.accessibility.AccessibleRole
An object that is a child of a page tab list.
PAGE_TAB_LIST - Static variable in class javax.accessibility.AccessibleRole
An object that presents a series of panels (or page tabs), one at a time, through some mechanism provided by the object.
Pageable - Interface in java.awt.print
The Pageable implementation represents a set of pages to be printed.
PAGEABLE - Static variable in class javax.print.DocFlavor.SERVICE_FORMATTED
Service formatted print data doc flavor with print data representation class name = "java.awt.print.Pageable" (pageable object).
PageAttributes - Class in java.awt
A set of attributes which control the output of a printed page.
PageAttributes() - Constructor for class java.awt.PageAttributes
Constructs a PageAttributes instance with default values for every attribute.
PageAttributes(PageAttributes) - Constructor for class java.awt.PageAttributes
Constructs a PageAttributes instance which is a copy of the supplied PageAttributes.
PageAttributes(PageAttributes.ColorType, PageAttributes.MediaType, PageAttributes.OrientationRequestedType, PageAttributes.OriginType, PageAttributes.PrintQualityType, int[]) - Constructor for class java.awt.PageAttributes
Constructs a PageAttributes instance with the specified values for every attribute.
PageAttributes.ColorType - Class in java.awt
A type-safe enumeration of possible color states.
PageAttributes.MediaType - Class in java.awt
A type-safe enumeration of possible paper sizes.
PageAttributes.OrientationRequestedType - Class in java.awt
A type-safe enumeration of possible orientations.
PageAttributes.OriginType - Class in java.awt
A type-safe enumeration of possible origins.
PageAttributes.PrintQualityType - Class in java.awt
A type-safe enumeration of possible print qualities.
pageDialog(PageFormat) - Method in class java.awt.print.PrinterJob
Displays a dialog that allows modification of a PageFormat instance.
pageDialog(PrintRequestAttributeSet) - Method in class java.awt.print.PrinterJob
A convenience method which displays a cross-platform page setup dialog.
pageDownAction - Static variable in class javax.swing.text.DefaultEditorKit
Name of the action to page down vertically.
PagedResultsControl - Class in javax.naming.ldap
Requests that the results of a search operation be returned by the LDAP server in batches of a specified size.
PagedResultsControl(int, boolean) - Constructor for class javax.naming.ldap.PagedResultsControl
Constructs a control to set the number of entries to be returned per page of results.
PagedResultsControl(int, byte[], boolean) - Constructor for class javax.naming.ldap.PagedResultsControl
Constructs a control to set the number of entries to be returned per page of results.
PagedResultsResponseControl - Class in javax.naming.ldap
Indicates the end of a batch of search results.
PagedResultsResponseControl(String, boolean, byte[]) - Constructor for class javax.naming.ldap.PagedResultsResponseControl
Constructs a paged-results response control.
PageFormat - Class in java.awt.print
The PageFormat class describes the size and orientation of a page to be printed.
PageFormat() - Constructor for class java.awt.print.PageFormat
Creates a default, portrait-oriented PageFormat.
PageRanges - Class in javax.print.attribute.standard
Class PageRanges is a printing attribute class, a set of integers, that identifies the range(s) of print-stream pages that the Printer object uses for each copy of each document which are to be printed.
PageRanges(int[][]) - Constructor for class javax.print.attribute.standard.PageRanges
Construct a new page ranges attribute with the given members.
PageRanges(String) - Constructor for class javax.print.attribute.standard.PageRanges
Construct a new page ranges attribute with the given members in string form.
PageRanges(int) - Constructor for class javax.print.attribute.standard.PageRanges
Construct a new page ranges attribute containing a single integer.
PageRanges(int, int) - Constructor for class javax.print.attribute.standard.PageRanges
Construct a new page ranges attribute containing a single range of integers.
PagesPerMinute - Class in javax.print.attribute.standard
Class PagesPerMinute is an integer valued printing attribute that indicates the nominal number of pages per minute to the nearest whole number which may be generated by this printer (e.g., simplex, black-and-white).
PagesPerMinute(int) - Constructor for class javax.print.attribute.standard.PagesPerMinute
Construct a new pages per minute attribute with the given integer value.
PagesPerMinuteColor - Class in javax.print.attribute.standard
Class PagesPerMinuteColor is an integer valued printing attribute that indicates the nominal number of pages per minute to the nearest whole number which may be generated by this printer when printing color (e.g., simplex, color).
PagesPerMinuteColor(int) - Constructor for class javax.print.attribute.standard.PagesPerMinuteColor
Construct a new pages per minute color attribute with the given integer value.
pageUpAction - Static variable in class javax.swing.text.DefaultEditorKit
Name of the action to page up vertically.
paint(Graphics) - Method in class java.awt.Canvas
Paints this canvas.
paint(Graphics) - Method in class java.awt.Component
Paints this component.
paint(Graphics) - Method in class java.awt.Container
Paints the container.
PAINT - Static variable in class java.awt.event.PaintEvent
The paint event type.
Paint - Interface in java.awt
This Paint interface defines how color patterns can be generated for Graphics2D operations.
paint(Graphics) - Method in class java.awt.Window
Paints the container.
paint(Graphics) - Method in class javax.swing.CellRendererPane
Shouldn't be called.
paint(Graphics) - Method in class javax.swing.colorchooser.AbstractColorChooserPanel
Draws the panel.
paint(Graphics) - Method in class javax.swing.JComponent
Invoked by Swing to draw components.
paint(Graphics) - Method in class javax.swing.JLayer
Delegates all painting to the LayerUI object.
paint(Graphics) - Method in class javax.swing.JLayeredPane
Paints this JLayeredPane within the specified graphics context.
paint(Graphics) - Method in class javax.swing.JViewport
Depending on whether the backingStore is enabled, either paint the image through the backing store or paint just the recently exposed part, using the backing store to "blit" the remainder.
paint(Graphics2D, T, int, int) - Method in interface javax.swing.Painter
Renders to the given Graphics2D object.
paint(Graphics) - Method in class javax.swing.plaf.basic.BasicArrowButton
paint(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicButtonUI
paint(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicComboBoxUI
paint(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicDesktopPaneUI
paint(Graphics) - Method in class javax.swing.plaf.basic.BasicInternalFrameTitlePane.SystemMenuBar
paint(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicLabelUI
Paints the label text with the foreground color, if the label is opaque then paints the entire background with the background color.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicListUI
Paint the rows that intersect the Graphics objects clipRect.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicMenuItemUI
paint(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicPopupMenuSeparatorUI
paint(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicProgressBarUI
Delegates painting to one of two methods: paintDeterminate or paintIndeterminate.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicRadioButtonUI
paint the radio button
paint(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicScrollBarUI
paint(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicScrollPaneUI
paint(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicSeparatorUI
paint(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicSliderUI
paint(Graphics) - Method in class javax.swing.plaf.basic.BasicSplitPaneDivider
Paints the divider.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicSplitPaneUI
paint(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI
paint(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicTableHeaderUI
paint(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicTableUI
Paint a representation of the table instance that was set in installUI().
paint(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicTextUI
Paints the interface.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicToggleButtonUI
paint(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicToolBarSeparatorUI
paint(Graphics) - Method in class javax.swing.plaf.basic.BasicToolBarUI.DragWindow
paint(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicToolTipUI
paint(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicTreeUI
paint(Graphics, JComponent) - Method in class javax.swing.plaf.ComponentUI
Paints the specified component appropriately for the look and feel.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.LayerUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.metal.MetalComboBoxUI
paint(Graphics, JComponent) - Method in class javax.swing.plaf.metal.MetalPopupMenuSeparatorUI
paint(Graphics, JComponent) - Method in class javax.swing.plaf.metal.MetalRadioButtonUI
paint(Graphics) - Method in class javax.swing.plaf.metal.MetalScrollButton
paint(Graphics, JComponent) - Method in class javax.swing.plaf.metal.MetalSeparatorUI
paint(Graphics, JComponent) - Method in class javax.swing.plaf.metal.MetalTabbedPaneUI
paint(Graphics, JComponent) - Method in class javax.swing.plaf.metal.MetalToolTipUI
paint(Graphics, JComponent) - Method in class javax.swing.plaf.metal.MetalTreeUI
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiButtonUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiColorChooserUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiComboBoxUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiDesktopIconUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiDesktopPaneUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiFileChooserUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiInternalFrameUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiLabelUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiListUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiMenuBarUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiMenuItemUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiOptionPaneUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiPanelUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiPopupMenuUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiProgressBarUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiRootPaneUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiScrollBarUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiScrollPaneUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiSeparatorUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiSliderUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiSpinnerUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiSplitPaneUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiTabbedPaneUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiTableHeaderUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiTableUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiTextUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiToolBarUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiToolTipUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiTreeUI
Invokes the paint method on each UI handled by this object.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiViewportUI
Invokes the paint method on each UI handled by this object.
paint(Graphics2D, JComponent, int, int) - Method in class javax.swing.plaf.nimbus.AbstractRegionPainter
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthButtonUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthButtonUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthColorChooserUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthColorChooserUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthComboBoxUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthComboBoxUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthDesktopIconUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthDesktopIconUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthDesktopPaneUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthDesktopPaneUI
Paints the specified component.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthEditorPaneUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthInternalFrameUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthInternalFrameUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthLabelUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthLabelUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthMenuBarUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthMenuBarUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthMenuItemUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthMenuItemUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthMenuUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthMenuUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthOptionPaneUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthOptionPaneUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthPanelUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthPanelUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthPopupMenuUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthPopupMenuUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthProgressBarUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthProgressBarUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthRootPaneUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthRootPaneUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthScrollBarUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthScrollBarUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthScrollPaneUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthScrollPaneUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthSeparatorUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthSeparatorUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthSliderUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthSliderUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthSpinnerUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthSpinnerUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthSplitPaneUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthSplitPaneUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthTabbedPaneUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthTabbedPaneUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthTableHeaderUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthTableHeaderUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthTableUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthTableUI
Paints the specified component.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthTextAreaUI
Paints the specified component.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthTextFieldUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthToolBarUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthToolBarUI
Paints the toolbar.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthToolTipUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthToolTipUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthTreeUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthTreeUI
Paints the specified component.
paint(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthViewportUI
Paints the specified component according to the Look and Feel.
paint(SynthContext, Graphics) - Method in class javax.swing.plaf.synth.SynthViewportUI
Paints the specified component.
paint(Graphics, Shape) - Method in class javax.swing.text.AsyncBoxView
Render the view using the given allocation and rendering surface.
paint(Graphics, Shape) - Method in class javax.swing.text.BoxView
Renders the BoxView using the given rendering surface and area on that surface.
paint(Graphics) - Method in interface javax.swing.text.Caret
Renders the caret.
paint(Graphics, Shape) - Method in class javax.swing.text.ComponentView
The real paint behavior occurs naturally from the association that the component has with its parent container (the same container hosting this view).
paint(Graphics) - Method in class javax.swing.text.DefaultCaret
Renders the caret as a vertical line.
paint(Graphics, int, int, Shape, JTextComponent) - Method in class javax.swing.text.DefaultHighlighter.DefaultHighlightPainter
Paints a highlight.
paint(Graphics) - Method in class javax.swing.text.DefaultHighlighter
Renders the highlights.
paint(Graphics, Shape) - Method in class javax.swing.text.FieldView
Renders using the given rendering surface and area on that surface.
paint(GlyphView, Graphics, Shape, int, int) - Method in class javax.swing.text.GlyphView.GlyphPainter
Paint the glyphs representing the given range.
paint(Graphics, Shape) - Method in class javax.swing.text.GlyphView
Renders a portion of a text style run.
paint(Graphics, int, int, Shape, JTextComponent) - Method in interface javax.swing.text.Highlighter.HighlightPainter
Renders the highlight.
paint(Graphics) - Method in interface javax.swing.text.Highlighter
Renders the highlights.
paint(Graphics, Shape) - Method in class javax.swing.text.html.BlockView
Renders using the given rendering surface and area on that surface.
paint(Graphics, Shape) - Method in class javax.swing.text.html.ImageView
Paints the View.
paint(Graphics, Shape) - Method in class javax.swing.text.html.ListView
Renders using the given rendering surface and area on that surface.
paint(Graphics, Shape) - Method in class javax.swing.text.html.ParagraphView
Renders using the given rendering surface and area on that surface.
paint(Graphics, float, float, float, float, View) - Method in class javax.swing.text.html.StyleSheet.BoxPainter
Paints the CSS box according to the attributes given.
paint(Graphics, float, float, float, float, View, int) - Method in class javax.swing.text.html.StyleSheet.ListPainter
Paints the CSS list decoration according to the attributes given.
paint(Graphics, Shape) - Method in class javax.swing.text.IconView
Paints the icon.
paint(Graphics, Shape) - Method in class javax.swing.text.ParagraphView
Renders using the given rendering surface and area on that surface.
paint(Graphics, Shape) - Method in class javax.swing.text.PlainView
Renders using the given rendering surface and area on that surface.
paint(Graphics, Shape) - Method in class javax.swing.text.View
Renders using the given rendering surface and area on that surface.
paint(Graphics, Shape) - Method in class javax.swing.text.WrappedPlainView
Renders using the given rendering surface and area on that surface.
paint(Graphics) - Method in class javax.swing.tree.DefaultTreeCellEditor.EditorContainer
Overrides Container.paint to paint the node's icon and use the selection color for the background.
paint(Graphics) - Method in class javax.swing.tree.DefaultTreeCellRenderer
Paints the value.
PAINT_EVENT_MASK - Static variable in class java.awt.AWTEvent
The event mask for selecting paint events.
PAINT_FIRST - Static variable in class java.awt.event.PaintEvent
Marks the first integer id for the range of paint event ids.
PAINT_LAST - Static variable in class java.awt.event.PaintEvent
Marks the last integer id for the range of paint event ids.
paintAll(Graphics) - Method in class java.awt.Component
Paints this component and all of its subcomponents.
paintArrowButtonBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of an arrow button.
paintArrowButtonBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of an arrow button.
paintArrowButtonForeground(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the foreground of an arrow button.
paintBackground(Graphics, JMenuItem, Color) - Method in class javax.swing.plaf.basic.BasicMenuItemUI
Draws the background of the menu item.
paintBackground(Graphics) - Method in class javax.swing.plaf.basic.BasicTextUI
Paints a background for the view.
paintBackground(Graphics) - Method in class javax.swing.plaf.synth.SynthEditorPaneUI
paintBackground(Graphics) - Method in class javax.swing.plaf.synth.SynthTextAreaUI
paintBackground(Graphics) - Method in class javax.swing.plaf.synth.SynthTextFieldUI
paintBorder(Graphics) - Method in class javax.swing.AbstractButton
Paint the button's border if BorderPainted property is true and the button has a border.
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.border.AbstractBorder
This default implementation does no painting.
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.border.BevelBorder
Paints the border for the specified component with the specified position and size.
paintBorder(Component, Graphics, int, int, int, int) - Method in interface javax.swing.border.Border
Paints the border for the specified component with the specified position and size.
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.border.CompoundBorder
Paints the compound border by painting the outside border with the specified position and size and then painting the inside border at the specified position and size offset by the insets of the outside border.
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.border.EmptyBorder
Does no drawing by default.
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.border.EtchedBorder
Paints the border for the specified component with the specified position and size.
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.border.LineBorder
Paints the border for the specified component with the specified position and size.
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.border.MatteBorder
Paints the matte border.
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.border.SoftBevelBorder
Paints the border for the specified component with the specified position and size.
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.border.StrokeBorder
Paints the border for the specified component with the specified position and size.
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.border.TitledBorder
Paints the border for the specified component with the specified position and size.
paintBorder(Graphics) - Method in class javax.swing.JComponent
Paints the component's border.
paintBorder(Graphics) - Method in class javax.swing.JMenuBar
Paints the menubar's border if BorderPainted property is true.
paintBorder(Graphics) - Method in class javax.swing.JPopupMenu
Paints the popup menu's border if the borderPainted property is true.
paintBorder - Variable in class javax.swing.JProgressBar
Whether to display a border around the progress bar.
paintBorder(Graphics) - Method in class javax.swing.JProgressBar
Paints the progress bar's border if the borderPainted property is true.
paintBorder(Graphics) - Method in class javax.swing.JToolBar
Paints the tool bar's border if the borderPainted property is true.
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.plaf.basic.BasicBorders.ButtonBorder
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.plaf.basic.BasicBorders.FieldBorder
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.plaf.basic.BasicBorders.MenuBarBorder
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.plaf.basic.BasicBorders.RadioButtonBorder
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.plaf.basic.BasicBorders.RolloverButtonBorder
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.plaf.basic.BasicBorders.SplitPaneBorder
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.plaf.basic.BasicBorders.ToggleButtonBorder
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.plaf.BorderUIResource
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.plaf.metal.MetalBorders.ButtonBorder
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.plaf.metal.MetalBorders.Flush3DBorder
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.plaf.metal.MetalBorders.InternalFrameBorder
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.plaf.metal.MetalBorders.MenuBarBorder
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.plaf.metal.MetalBorders.MenuItemBorder
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.plaf.metal.MetalBorders.OptionDialogBorder
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.plaf.metal.MetalBorders.PaletteBorder
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.plaf.metal.MetalBorders.PopupMenuBorder
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.plaf.metal.MetalBorders.RolloverButtonBorder
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.plaf.metal.MetalBorders.ScrollPaneBorder
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.plaf.metal.MetalBorders.TableHeaderBorder
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.plaf.metal.MetalBorders.TextFieldBorder
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.plaf.metal.MetalBorders.ToggleButtonBorder
paintBorder(Component, Graphics, int, int, int, int) - Method in class javax.swing.plaf.metal.MetalBorders.ToolBarBorder
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthButtonUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthCheckBoxMenuItemUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthCheckBoxUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthColorChooserUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthComboBoxUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthDesktopIconUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthDesktopPaneUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthEditorPaneUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthFormattedTextFieldUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthInternalFrameUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthLabelUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthListUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthMenuBarUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthMenuItemUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthMenuUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthOptionPaneUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPanelUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPasswordFieldUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPopupMenuUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthProgressBarUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthRadioButtonMenuItemUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthRadioButtonUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthRootPaneUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthScrollBarUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthScrollPaneUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthSeparatorUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthSliderUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthSpinnerUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthSplitPaneUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthTabbedPaneUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthTableHeaderUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthTableUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthTextAreaUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthTextFieldUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthTextPaneUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthToggleButtonUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthToolBarUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthToolTipUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthTreeUI
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in interface javax.swing.plaf.synth.SynthUI
Paints the border.
paintBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthViewportUI
Paints the border.
paintBottomTabBorder(int, Graphics, int, int, int, int, int, int, boolean) - Method in class javax.swing.plaf.metal.MetalTabbedPaneUI
paintButtonBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a button.
paintButtonBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a button.
paintButtonPressed(Graphics, AbstractButton) - Method in class javax.swing.plaf.basic.BasicButtonUI
paintButtonPressed(Graphics, AbstractButton) - Method in class javax.swing.plaf.metal.MetalButtonUI
paintButtonPressed(Graphics, AbstractButton) - Method in class javax.swing.plaf.metal.MetalToggleButtonUI
paintCell(Graphics, int, Rectangle, ListCellRenderer, ListModel, ListSelectionModel, int) - Method in class javax.swing.plaf.basic.BasicListUI
Paint one List cell: compute the relevant state, get the "rubber stamp" cell renderer component, and then use the CellRendererPane to paint it.
paintCheckBoxBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a check box.
paintCheckBoxBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a check box.
paintCheckBoxMenuItemBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a check box menu item.
paintCheckBoxMenuItemBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a check box menu item.
paintChild(Graphics, Rectangle, int) - Method in class javax.swing.text.BoxView
Paints a child.
paintChild(Graphics, Rectangle, int) - Method in class javax.swing.text.html.ListView
Paints one of the children; called by paint().
paintChildren(Graphics) - Method in class javax.swing.JComponent
Paints this component's children.
paintChildren(Graphics) - Method in class javax.swing.JSplitPane
Subclassed to message the UI with finishedPaintingChildren after super has been messaged, as well as painting the border.
paintChildren(Graphics) - Method in class javax.swing.text.AsyncBoxView.ChildLocator
Paint the children that intersect the clip area.
paintColorChooserBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a color chooser.
paintColorChooserBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a color chooser.
paintComboBoxBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a combo box.
paintComboBoxBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a combo box.
paintComponent(Graphics) - Method in class javax.swing.Box.Filler
Paints this Filler.
paintComponent(Graphics) - Method in class javax.swing.Box
Paints this Box.
paintComponent(Graphics, Component, Container, int, int, int, int, boolean) - Method in class javax.swing.CellRendererPane
Paint a cell renderer component c on graphics object g.
paintComponent(Graphics, Component, Container, int, int, int, int) - Method in class javax.swing.CellRendererPane
Calls this.paintComponent(g, c, p, x, y, w, h, false).
paintComponent(Graphics, Component, Container, Rectangle) - Method in class javax.swing.CellRendererPane
Calls this.paintComponent() with the rectangles x,y,width,height fields.
paintComponent(Graphics) - Method in class javax.swing.JComponent
Calls the UI delegate's paint method, if the UI delegate is non-null.
paintComponent(Graphics) - Method in class javax.swing.JInternalFrame
Overridden to allow optimized painting when the internal frame is being dragged.
paintComponent(Graphics) - Method in class javax.swing.JLayer
This method is empty, because all painting is done by JLayer.paint(Graphics) and ComponentUI.update(Graphics, JComponent) methods
paintComponent(Graphics) - Method in class javax.swing.plaf.basic.BasicInternalFrameTitlePane
paintComponent(Graphics) - Method in class javax.swing.plaf.metal.MetalComboBoxButton
paintComponent(Graphics) - Method in class javax.swing.plaf.metal.MetalInternalFrameTitlePane
paintComponent(Graphics, Component, Container, int, int, int, int) - Static method in class javax.swing.SwingUtilities
Paints a component to the specified Graphics.
paintComponent(Graphics, Component, Container, Rectangle) - Static method in class javax.swing.SwingUtilities
Paints a component to the specified Graphics.
paintComponents(Graphics) - Method in class java.awt.Container
Paints each of the components in this container.
paintContent(SynthContext, Graphics, Rectangle) - Method in class javax.swing.plaf.synth.SynthToolBarUI
Paints the toolbar content.
paintContentBorder(Graphics, int, int) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI
paintContentBorderBottomEdge(Graphics, int, int, int, int, int, int) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI
paintContentBorderBottomEdge(Graphics, int, int, int, int, int, int) - Method in class javax.swing.plaf.metal.MetalTabbedPaneUI
paintContentBorderLeftEdge(Graphics, int, int, int, int, int, int) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI
paintContentBorderLeftEdge(Graphics, int, int, int, int, int, int) - Method in class javax.swing.plaf.metal.MetalTabbedPaneUI
paintContentBorderRightEdge(Graphics, int, int, int, int, int, int) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI
paintContentBorderRightEdge(Graphics, int, int, int, int, int, int) - Method in class javax.swing.plaf.metal.MetalTabbedPaneUI
paintContentBorderTopEdge(Graphics, int, int, int, int, int, int) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI
paintContentBorderTopEdge(Graphics, int, int, int, int, int, int) - Method in class javax.swing.plaf.metal.MetalTabbedPaneUI
PaintContext - Interface in java.awt
The PaintContext interface defines the encapsulated and optimized environment to generate color patterns in device space for fill or stroke operations on a Graphics2D.
paintCurrentValue(Graphics, Rectangle, boolean) - Method in class javax.swing.plaf.basic.BasicComboBoxUI
Paints the currently selected item.
paintCurrentValue(Graphics, Rectangle, boolean) - Method in class javax.swing.plaf.metal.MetalComboBoxUI
If necessary paints the currently selected item.
paintCurrentValue(Graphics, Rectangle, boolean) - Method in class javax.swing.plaf.synth.SynthComboBoxUI
Paints the currently selected item.
paintCurrentValueBackground(Graphics, Rectangle, boolean) - Method in class javax.swing.plaf.basic.BasicComboBoxUI
Paints the background of the currently selected item.
paintCurrentValueBackground(Graphics, Rectangle, boolean) - Method in class javax.swing.plaf.metal.MetalComboBoxUI
If necessary paints the background of the currently selected item.
paintDecreaseHighlight(Graphics) - Method in class javax.swing.plaf.basic.BasicScrollBarUI
paintDesktopIconBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a desktop icon.
paintDesktopIconBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a desktop icon.
paintDesktopPaneBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a desktop pane.
paintDesktopPaneBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a desktop pane.
paintDeterminate(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicProgressBarUI
All purpose paint method that should do the right thing for almost all linear, determinate progress bars.
paintDeterminate(Graphics, JComponent) - Method in class javax.swing.plaf.metal.MetalProgressBarUI
Draws a bit of special highlighting on the progress bar.
paintDirtyRegions() - Method in class javax.swing.RepaintManager
Paint all of the components that have been marked dirty.
paintDisabledText(JLabel, Graphics, String, int, int) - Method in class javax.swing.plaf.basic.BasicLabelUI
Paint clippedText at textX, textY with background.lighter() and then shifted down and to the right by one pixel with background.darker().
paintDisabledText(JLabel, Graphics, String, int, int) - Method in class javax.swing.plaf.metal.MetalLabelUI
Just paint the text gray (Label.disabledForeground) rather than in the labels foreground color.
paintDragWindow(Graphics) - Method in class javax.swing.plaf.basic.BasicToolBarUI
Paints the contents of the window used for dragging.
paintDragWindow(Graphics) - Method in class javax.swing.plaf.synth.SynthToolBarUI
paintDropLine(Graphics) - Method in class javax.swing.plaf.basic.BasicTreeUI
Paints the drop line.
paintDropLine(Graphics) - Method in class javax.swing.plaf.synth.SynthTreeUI
paintEditorPaneBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of an editor pane.
paintEditorPaneBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of an editor pane.
paintEnabledText(JLabel, Graphics, String, int, int) - Method in class javax.swing.plaf.basic.BasicLabelUI
Paint clippedText at textX, textY with the labels foreground color.
Painter<T> - Interface in javax.swing
A painting delegate.
PaintEvent - Class in java.awt.event
The component-level paint event.
PaintEvent(Component, int, Rectangle) - Constructor for class java.awt.event.PaintEvent
Constructs a PaintEvent object with the specified source component and type.
paintExpandControl(Graphics, Rectangle, Insets, Rectangle, TreePath, int, boolean, boolean, boolean) - Method in class javax.swing.plaf.basic.BasicTreeUI
Paints the expand (toggle) part of a row.
paintExpandControl(Graphics, Rectangle, Insets, Rectangle, TreePath, int, boolean, boolean, boolean) - Method in class javax.swing.plaf.synth.SynthTreeUI
paintFileChooserBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a file chooser.
paintFileChooserBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a file chooser.
paintFocus(Graphics, AbstractButton, Rectangle, Rectangle, Rectangle) - Method in class javax.swing.plaf.basic.BasicButtonUI
paintFocus(Graphics, Rectangle, Dimension) - Method in class javax.swing.plaf.basic.BasicRadioButtonUI
paintFocus(Graphics) - Method in class javax.swing.plaf.basic.BasicSliderUI
paintFocus(Graphics, AbstractButton, Rectangle, Rectangle, Rectangle) - Method in class javax.swing.plaf.metal.MetalButtonUI
paintFocus(Graphics, Rectangle, Dimension) - Method in class javax.swing.plaf.metal.MetalRadioButtonUI
paintFocus(Graphics) - Method in class javax.swing.plaf.metal.MetalSliderUI
paintFocus(Graphics, AbstractButton, Rectangle, Rectangle, Rectangle) - Method in class javax.swing.plaf.metal.MetalToggleButtonUI
paintFocusIndicator(Graphics, int, Rectangle[], int, Rectangle, Rectangle, boolean) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI
paintFocusIndicator(Graphics, int, Rectangle[], int, Rectangle, Rectangle, boolean) - Method in class javax.swing.plaf.metal.MetalTabbedPaneUI
paintFormattedTextFieldBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a formatted text field.
paintFormattedTextFieldBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a formatted text field.
paintHighlightBelowTab() - Method in class javax.swing.plaf.metal.MetalTabbedPaneUI
paintHorizontalLabel(Graphics, int, Component) - Method in class javax.swing.plaf.basic.BasicSliderUI
Called for every label in the label table.
paintHorizontalLine(Graphics, JComponent, int, int, int) - Method in class javax.swing.plaf.basic.BasicTreeUI
Paints a horizontal line.
paintHorizontalLine(Graphics, JComponent, int, int, int) - Method in class javax.swing.plaf.synth.SynthTreeUI
paintHorizontalPartOfLeg(Graphics, Rectangle, Insets, Rectangle, TreePath, int, boolean, boolean, boolean) - Method in class javax.swing.plaf.basic.BasicTreeUI
Paints the horizontal part of the leg.
paintHorizontalPartOfLeg(Graphics, Rectangle, Insets, Rectangle, TreePath, int, boolean, boolean, boolean) - Method in class javax.swing.plaf.metal.MetalTreeUI
paintHorizontalPartOfLeg(Graphics, Rectangle, Insets, Rectangle, TreePath, int, boolean, boolean, boolean) - Method in class javax.swing.plaf.synth.SynthTreeUI
paintHorizontalSeparators(Graphics, JComponent) - Method in class javax.swing.plaf.metal.MetalTreeUI
paintIcon(Component, Graphics, int, int) - Method in interface javax.swing.Icon
Draw the icon at the specified location.
paintIcon(Component, Graphics, int, int) - Method in class javax.swing.ImageIcon
Paints the icon.
paintIcon(Graphics, JComponent, Rectangle) - Method in class javax.swing.plaf.basic.BasicButtonUI
paintIcon(Graphics, int, int, Icon, Rectangle, boolean) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI
paintIcon(Graphics, AbstractButton, Rectangle) - Method in class javax.swing.plaf.basic.BasicToggleButtonUI
paintIcon(Component, Graphics, int, int) - Method in class javax.swing.plaf.IconUIResource
paintIcon(Component, Graphics, int, int) - Method in class javax.swing.plaf.metal.MetalCheckBoxIcon
paintIcon(Component, Graphics, int, int) - Method in class javax.swing.plaf.metal.MetalComboBoxIcon
Paints the horizontal bars for the
paintIcon(Component, Graphics, int, int) - Method in class javax.swing.plaf.metal.MetalIconFactory.FileIcon16
paintIcon(Component, Graphics, int, int) - Method in class javax.swing.plaf.metal.MetalIconFactory.FolderIcon16
paintIcon(Component, Graphics, int, int) - Method in class javax.swing.plaf.metal.MetalIconFactory.PaletteCloseIcon
paintIcon(Component, Graphics, int, int) - Method in class javax.swing.plaf.metal.MetalIconFactory.TreeControlIcon
paintIcon(Graphics, AbstractButton, Rectangle) - Method in class javax.swing.plaf.metal.MetalToggleButtonUI
Paints the appropriate icon of the button b in the space iconRect.
paintImmediately(int, int, int, int) - Method in class javax.swing.JComponent
Paints the specified region in this component and all of its descendants that overlap the region, immediately.
paintImmediately(Rectangle) - Method in class javax.swing.JComponent
Paints the specified region now.
paintImmediately(int, int, int, int) - Method in class javax.swing.JLayer
Delegates its functionality to the LayerUI.paintImmediately(int, int, int, int, JLayer) method, if LayerUI is set.
paintImmediately(int, int, int, int, JLayer<? extends V>) - Method in class javax.swing.plaf.LayerUI
Paints the specified region in the JLayer this LayerUI is set to, immediately.
paintIncreaseHighlight(Graphics) - Method in class javax.swing.plaf.basic.BasicScrollBarUI
paintIndeterminate(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicProgressBarUI
All purpose paint method that should do the right thing for all linear bouncing-box progress bars.
paintIndeterminate(Graphics, JComponent) - Method in class javax.swing.plaf.metal.MetalProgressBarUI
Draws a bit of special highlighting on the progress bar and bouncing box.
paintInternalFrameBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of an internal frame.
paintInternalFrameBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of an internal frame.
paintInternalFrameTitlePaneBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of an internal frame title pane.
paintInternalFrameTitlePaneBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of an internal frame title pane.
paintLabelBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a label.
paintLabelBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a label.
paintLabels(Graphics) - Method in class javax.swing.plaf.basic.BasicSliderUI
paintLayer(Graphics, int, int, Shape, JTextComponent, View) - Method in class javax.swing.text.DefaultHighlighter.DefaultHighlightPainter
Paints a portion of a highlight.
paintLayer(Graphics, int, int, Shape, JTextComponent, View) - Method in class javax.swing.text.LayeredHighlighter.LayerPainter
paintLayeredHighlights(Graphics, int, int, Shape, JTextComponent, View) - Method in class javax.swing.text.DefaultHighlighter
When leaf Views (such as LabelView) are rendering they should call into this method.
paintLayeredHighlights(Graphics, int, int, Shape, JTextComponent, View) - Method in class javax.swing.text.LayeredHighlighter
When leaf Views (such as LabelView) are rendering they should call into this method.
paintLeftTabBorder(int, Graphics, int, int, int, int, int, int, boolean) - Method in class javax.swing.plaf.metal.MetalTabbedPaneUI
paintListBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a list.
paintListBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a list.
paintLoweredBevel(Component, Graphics, int, int, int, int) - Method in class javax.swing.border.BevelBorder
paintMajorTickForHorizSlider(Graphics, Rectangle, int) - Method in class javax.swing.plaf.basic.BasicSliderUI
paintMajorTickForHorizSlider(Graphics, Rectangle, int) - Method in class javax.swing.plaf.metal.MetalSliderUI
paintMajorTickForVertSlider(Graphics, Rectangle, int) - Method in class javax.swing.plaf.basic.BasicSliderUI
paintMajorTickForVertSlider(Graphics, Rectangle, int) - Method in class javax.swing.plaf.metal.MetalSliderUI
paintMe(Component, Graphics, int, int) - Method in class javax.swing.plaf.metal.MetalIconFactory.TreeControlIcon
paintMenuBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a menu.
paintMenuBarBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a menu bar.
paintMenuBarBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a menu bar.
paintMenuBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a menu.
paintMenuItem(Graphics, JComponent, Icon, Icon, Color, Color, int) - Method in class javax.swing.plaf.basic.BasicMenuItemUI
paintMenuItemBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a menu item.
paintMenuItemBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a menu item.
paintMinorTickForHorizSlider(Graphics, Rectangle, int) - Method in class javax.swing.plaf.basic.BasicSliderUI
paintMinorTickForHorizSlider(Graphics, Rectangle, int) - Method in class javax.swing.plaf.metal.MetalSliderUI
paintMinorTickForVertSlider(Graphics, Rectangle, int) - Method in class javax.swing.plaf.basic.BasicSliderUI
paintMinorTickForVertSlider(Graphics, Rectangle, int) - Method in class javax.swing.plaf.metal.MetalSliderUI
paintOptionPaneBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of an option pane.
paintOptionPaneBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of an option pane.
paintPalette(Graphics) - Method in class javax.swing.plaf.metal.MetalInternalFrameTitlePane
paintPanelBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a panel.
paintPanelBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a panel.
paintPasswordFieldBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a password field.
paintPasswordFieldBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a password field.
paintPopupMenuBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a popup menu.
paintPopupMenuBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a popup menu.
paintProgressBarBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a progress bar.
paintProgressBarBackground(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a progress bar.
paintProgressBarBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a progress bar.
paintProgressBarBorder(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a progress bar.
paintProgressBarForeground(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the foreground of a progress bar.
paintRadioButtonBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a radio button.
paintRadioButtonBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a radio button.
paintRadioButtonMenuItemBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a radio button menu item.
paintRadioButtonMenuItemBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a radio button menu item.
paintRaisedBevel(Component, Graphics, int, int, int, int) - Method in class javax.swing.border.BevelBorder
paintRightTabBorder(int, Graphics, int, int, int, int, int, int, boolean) - Method in class javax.swing.plaf.metal.MetalTabbedPaneUI
paintRootPaneBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a root pane.
paintRootPaneBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a root pane.
paintRow(Graphics, Rectangle, Insets, Rectangle, TreePath, int, boolean, boolean, boolean) - Method in class javax.swing.plaf.basic.BasicTreeUI
Paints the renderer part of a row.
paintSafely(Graphics) - Method in class javax.swing.plaf.basic.BasicTextUI
Paints the interface safely with a guarantee that the model won't change from the view of this thread.
paintScrollBarBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a scrollbar.
paintScrollBarBackground(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a scrollbar.
paintScrollBarBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a scrollbar.
paintScrollBarBorder(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a scrollbar.
paintScrollBarThumbBackground(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of the thumb of a scrollbar.
paintScrollBarThumbBorder(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of the thumb of a scrollbar.
paintScrollBarTrackBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of the track of a scrollbar.
paintScrollBarTrackBackground(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of the track of a scrollbar.
paintScrollBarTrackBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of the track of a scrollbar.
paintScrollBarTrackBorder(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of the track of a scrollbar.
paintScrollPaneBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a scroll pane.
paintScrollPaneBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a scroll pane.
paintSeparatorBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a separator.
paintSeparatorBackground(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a separator.
paintSeparatorBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a separator.
paintSeparatorBorder(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a separator.
paintSeparatorForeground(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the foreground of a separator.
paintSliderBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a slider.
paintSliderBackground(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a slider.
paintSliderBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a slider.
paintSliderBorder(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a slider.
paintSliderThumbBackground(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of the thumb of a slider.
paintSliderThumbBorder(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of the thumb of a slider.
paintSliderTrackBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of the track of a slider.
paintSliderTrackBackground(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of the track of a slider.
paintSliderTrackBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of the track of a slider.
paintSliderTrackBorder(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of the track of a slider.
paintSpinnerBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a spinner.
paintSpinnerBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a spinner.
paintSplitPaneBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a split pane.
paintSplitPaneBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a split pane.
paintSplitPaneDividerBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of the divider of a split pane.
paintSplitPaneDividerBackground(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of the divider of a split pane.
paintSplitPaneDividerForeground(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the foreground of the divider of a split pane.
paintSplitPaneDragDivider(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the divider, when the user is dragging the divider, of a split pane.
paintString - Variable in class javax.swing.JProgressBar
Whether to display a string of text on the progress bar.
paintString(Graphics, int, int, int, int, int, Insets) - Method in class javax.swing.plaf.basic.BasicProgressBarUI
paintTab(Graphics, int, Rectangle[], int, Rectangle, Rectangle) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI
paintTabArea(Graphics, int, int) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI
Paints the tabs in the tab area.
paintTabBackground(Graphics, int, int, int, int, int, int, boolean) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI
paintTabBackground(Graphics, int, int, int, int, int, int, boolean) - Method in class javax.swing.plaf.metal.MetalTabbedPaneUI
paintTabbedPaneBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a tabbed pane.
paintTabbedPaneBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a tabbed pane.
paintTabbedPaneContentBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of the area that contains the content of the selected tab of a tabbed pane.
paintTabbedPaneContentBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of the area that contains the content of the selected tab of a tabbed pane.
paintTabbedPaneTabAreaBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of the area behind the tabs of a tabbed pane.
paintTabbedPaneTabAreaBackground(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of the area behind the tabs of a tabbed pane.
paintTabbedPaneTabAreaBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of the area behind the tabs of a tabbed pane.
paintTabbedPaneTabAreaBorder(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of the area behind the tabs of a tabbed pane.
paintTabbedPaneTabBackground(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a tab of a tabbed pane.
paintTabbedPaneTabBackground(SynthContext, Graphics, int, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a tab of a tabbed pane.
paintTabbedPaneTabBorder(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a tab of a tabbed pane.
paintTabbedPaneTabBorder(SynthContext, Graphics, int, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a tab of a tabbed pane.
paintTabBorder(Graphics, int, int, int, int, int, int, boolean) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI
this function draws the border around each tab note that this function does now draw the background of the tab.
paintTabBorder(Graphics, int, int, int, int, int, int, boolean) - Method in class javax.swing.plaf.metal.MetalTabbedPaneUI
paintTableBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a table.
paintTableBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a table.
paintTableHeaderBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of the header of a table.
paintTableHeaderBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of the header of a table.
paintText(Graphics, JComponent, Rectangle, String) - Method in class javax.swing.plaf.basic.BasicButtonUI
As of Java 2 platform v 1.4 this method should not be used or overriden.
paintText(Graphics, AbstractButton, Rectangle, String) - Method in class javax.swing.plaf.basic.BasicButtonUI
Method which renders the text of the current button.
paintText(Graphics, JMenuItem, Rectangle, String) - Method in class javax.swing.plaf.basic.BasicMenuItemUI
Renders the text of the current menu item.
paintText(Graphics, int, Font, FontMetrics, int, String, Rectangle, boolean) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI
paintText(Graphics, JComponent, Rectangle, String) - Method in class javax.swing.plaf.metal.MetalButtonUI
paintText(Graphics, JComponent, Rectangle, String) - Method in class javax.swing.plaf.metal.MetalToggleButtonUI
paintText(SynthContext, Graphics, String, Rectangle, int) - Method in class javax.swing.plaf.synth.SynthGraphicsUtils
Paints text at the specified location.
paintText(SynthContext, Graphics, String, int, int, int) - Method in class javax.swing.plaf.synth.SynthGraphicsUtils
Paints text at the specified location.
paintText(SynthContext, Graphics, String, Icon, int, int, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthGraphicsUtils
Paints an icon and text.
paintText(SynthContext, Graphics, String) - Method in class javax.swing.plaf.synth.SynthProgressBarUI
Paints the component's text.
paintTextAreaBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a text area.
paintTextAreaBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a text area.
paintTextFieldBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a text field.
paintTextFieldBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a text field.
paintTextPaneBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a text pane.
paintTextPaneBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a text pane.
paintThumb(Graphics, JComponent, Rectangle) - Method in class javax.swing.plaf.basic.BasicScrollBarUI
paintThumb(Graphics) - Method in class javax.swing.plaf.basic.BasicSliderUI
paintThumb(Graphics, JComponent, Rectangle) - Method in class javax.swing.plaf.metal.MetalScrollBarUI
paintThumb(Graphics) - Method in class javax.swing.plaf.metal.MetalSliderUI
paintThumb(SynthContext, Graphics, Rectangle) - Method in class javax.swing.plaf.synth.SynthScrollBarUI
Paints the scrollbar thumb.
paintThumb(SynthContext, Graphics, Rectangle) - Method in class javax.swing.plaf.synth.SynthSliderUI
Paints the slider thumb.
paintTicks(Graphics) - Method in class javax.swing.plaf.basic.BasicSliderUI
paintTitleBackground(Graphics) - Method in class javax.swing.plaf.basic.BasicInternalFrameTitlePane
Invoked from paintComponent.
paintToggleButtonBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a toggle button.
paintToggleButtonBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a toggle button.
paintToolBarBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a tool bar.
paintToolBarBackground(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a tool bar.
paintToolBarBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a tool bar.
paintToolBarBorder(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a tool bar.
paintToolBarContentBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of the tool bar's content area.
paintToolBarContentBackground(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of the tool bar's content area.
paintToolBarContentBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of the content area of a tool bar.
paintToolBarContentBorder(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of the content area of a tool bar.
paintToolBarDragWindowBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of the window containing the tool bar when it has been detached from its primary frame.
paintToolBarDragWindowBackground(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of the window containing the tool bar when it has been detached from its primary frame.
paintToolBarDragWindowBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of the window containing the tool bar when it has been detached from it's primary frame.
paintToolBarDragWindowBorder(SynthContext, Graphics, int, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of the window containing the tool bar when it has been detached from it's primary frame.
paintToolTipBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a tool tip.
paintToolTipBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a tool tip.
paintTopTabBorder(int, Graphics, int, int, int, int, int, int, boolean) - Method in class javax.swing.plaf.metal.MetalTabbedPaneUI
paintTrack(Graphics, JComponent, Rectangle) - Method in class javax.swing.plaf.basic.BasicScrollBarUI
paintTrack(Graphics) - Method in class javax.swing.plaf.basic.BasicSliderUI
paintTrack(Graphics, JComponent, Rectangle) - Method in class javax.swing.plaf.metal.MetalScrollBarUI
paintTrack(Graphics) - Method in class javax.swing.plaf.metal.MetalSliderUI
paintTrack(SynthContext, Graphics, Rectangle) - Method in class javax.swing.plaf.synth.SynthScrollBarUI
Paints the scrollbar track.
paintTrack(SynthContext, Graphics, Rectangle) - Method in class javax.swing.plaf.synth.SynthSliderUI
Paints the slider track.
paintTreeBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of a tree.
paintTreeBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a tree.
paintTreeCellBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of the row containing a cell in a tree.
paintTreeCellBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of the row containing a cell in a tree.
paintTreeCellFocus(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the focus indicator for a cell in a tree when it has focus.
paintTriangle(Graphics, int, int, int, int, boolean) - Method in class javax.swing.plaf.basic.BasicArrowButton
Paints a triangle.
paintValue(Graphics, Rectangle) - Method in interface java.beans.PropertyEditor
Paint a representation of the value into a given area of screen real estate.
paintValue(Graphics, Rectangle) - Method in class java.beans.PropertyEditorSupport
Paint a representation of the value into a given area of screen real estate.
paintVerticalLabel(Graphics, int, Component) - Method in class javax.swing.plaf.basic.BasicSliderUI
Called for every label in the label table.
paintVerticalLine(Graphics, JComponent, int, int, int) - Method in class javax.swing.plaf.basic.BasicTreeUI
Paints a vertical line.
paintVerticalLine(Graphics, JComponent, int, int, int) - Method in class javax.swing.plaf.synth.SynthTreeUI
paintVerticalPartOfLeg(Graphics, Rectangle, Insets, TreePath) - Method in class javax.swing.plaf.basic.BasicTreeUI
Paints the vertical part of the leg.
paintVerticalPartOfLeg(Graphics, Rectangle, Insets, TreePath) - Method in class javax.swing.plaf.metal.MetalTreeUI
paintVerticalPartOfLeg(Graphics, Rectangle, Insets, TreePath) - Method in class javax.swing.plaf.synth.SynthTreeUI
paintViewportBackground(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the background of the viewport.
paintViewportBorder(SynthContext, Graphics, int, int, int, int) - Method in class javax.swing.plaf.synth.SynthPainter
Paints the border of a viewport.
PALETTE_LAYER - Static variable in class javax.swing.JLayeredPane
Convenience object defining the Palette layer.
paletteCloseIcon - Variable in class javax.swing.plaf.metal.MetalInternalFrameTitlePane
paletteTitleHeight - Variable in class javax.swing.plaf.metal.MetalInternalFrameTitlePane
PAN - Static variable in class javax.sound.sampled.FloatControl.Type
Represents a control for the relative pan (left-right positioning) of the signal.
Panel - Class in java.awt
Panel is the simplest container class.
Panel() - Constructor for class java.awt.Panel
Creates a new panel using the default layout manager.
Panel(LayoutManager) - Constructor for class java.awt.Panel
Creates a new panel with the specified layout manager.
PANEL - Static variable in class javax.accessibility.AccessibleRole
A generic container that is often used to group objects.
PANEL - Static variable in class javax.swing.plaf.synth.Region
Panel region.
Panel.AccessibleAWTPanel - Class in java.awt
This class implements accessibility support for the Panel class.
Panel.AccessibleAWTPanel() - Constructor for class java.awt.Panel.AccessibleAWTPanel
PANEL_UI - Static variable in class javax.print.ServiceUIFactory
Denotes a UI implemented as an AWT panel.
PanelUI - Class in javax.swing.plaf
Pluggable look and feel interface for Panel.
PanelUI() - Constructor for class javax.swing.plaf.PanelUI
Paper - Class in java.awt.print
The Paper class describes the physical characteristics of a piece of paper.
Paper() - Constructor for class java.awt.print.Paper
Creates a letter sized piece of paper with one inch margins.
PARA_INDENT_LEFT - Static variable in class javax.swing.text.html.HTMLEditorKit
The paragraph left indent action identifier
PARA_INDENT_RIGHT - Static variable in class javax.swing.text.html.HTMLEditorKit
The paragraph right indent action identifier
PARAGRAPH - Static variable in class javax.accessibility.AccessibleRole
A text paragraph
PARAGRAPH_SEPARATOR - Static variable in class java.lang.Character
General category "Zp" in the Unicode specification.
ParagraphElementName - Static variable in class javax.swing.text.AbstractDocument
Name of elements used to represent paragraphs
ParagraphView - Class in javax.swing.text.html
Displays the a paragraph, and uses css attributes for its configuration.
ParagraphView(Element) - Constructor for class javax.swing.text.html.ParagraphView
Constructs a ParagraphView for the given element.
ParagraphView - Class in javax.swing.text
View of a simple line-wrapping paragraph that supports multiple fonts, colors, components, icons, etc.
ParagraphView(Element) - Constructor for class javax.swing.text.ParagraphView
Constructs a ParagraphView for the given element.
PARAM - Static variable in class javax.swing.text.html.HTML.Tag
param - Variable in class javax.swing.text.html.parser.DTD
PARAM_IN - Static variable in class org.omg.CORBA.ParameterMode
PARAM_INOUT - Static variable in class org.omg.CORBA.ParameterMode
PARAM_OUT - Static variable in class org.omg.CORBA.ParameterMode
PARAMETER - Static variable in interface javax.swing.text.html.parser.DTDConstants
Parameter - Class in org.omg.Dynamic
org/omg/Dynamic/Parameter.java .
Parameter() - Constructor for class org.omg.Dynamic.Parameter
Parameter(Any, ParameterMode) - Constructor for class org.omg.Dynamic.Parameter
parameterArray() - Method in class java.lang.invoke.MethodType
Presents the parameter types as an array (a convenience method).
ParameterBlock - Class in java.awt.image.renderable
A ParameterBlock encapsulates all the information about sources and parameters (Objects) required by a RenderableImageOp, or other classes that process images.
ParameterBlock() - Constructor for class java.awt.image.renderable.ParameterBlock
A dummy constructor.
ParameterBlock(Vector<Object>) - Constructor for class java.awt.image.renderable.ParameterBlock
Constructs a ParameterBlock with a given Vector of sources.
ParameterBlock(Vector<Object>, Vector<Object>) - Constructor for class java.awt.image.renderable.ParameterBlock
Constructs a ParameterBlock with a given Vector of sources and Vector of parameters.
parameterCount() - Method in class java.lang.invoke.MethodType
Returns the number of parameter types in this method type.
ParameterDescriptor - Class in java.beans
The ParameterDescriptor class allows bean implementors to provide additional information on each of their parameters, beyond the low level type information provided by the java.lang.reflect.Method class.
ParameterDescriptor() - Constructor for class java.beans.ParameterDescriptor
Public default constructor.
Parameterizable - Interface in javax.lang.model.element
A mixin interface for an element that has type parameters.
ParameterizedType - Interface in java.lang.reflect
ParameterizedType represents a parameterized type such as Collection<String>.
parameterList() - Method in class java.lang.invoke.MethodType
Presents the parameter types as a list (a convenience method).
ParameterMetaData - Interface in java.sql
An object that can be used to get information about the types and properties for each parameter marker in a PreparedStatement object.
ParameterMode - Class in org.omg.CORBA
Enumeration of parameter modes for Parameter.
ParameterMode(int) - Constructor for class org.omg.CORBA.ParameterMode
ParameterModeHelper - Class in org.omg.CORBA
Enumeration of parameter modes for Parameter.
ParameterModeHelper() - Constructor for class org.omg.CORBA.ParameterModeHelper
ParameterModeHolder - Class in org.omg.CORBA
Enumeration of parameter modes for Parameter.
ParameterModeHolder() - Constructor for class org.omg.CORBA.ParameterModeHolder
ParameterModeHolder(ParameterMode) - Constructor for class org.omg.CORBA.ParameterModeHolder
parameterModeIn - Static variable in interface java.sql.ParameterMetaData
The constant indicating that the parameter's mode is IN.
parameterModeInOut - Static variable in interface java.sql.ParameterMetaData
The constant indicating that the parameter's mode is INOUT.
parameterModeOut - Static variable in interface java.sql.ParameterMetaData
The constant indicating that the parameter's mode is OUT.
parameterModeUnknown - Static variable in interface java.sql.ParameterMetaData
The constant indicating that the mode of the parameter is unknown.
parameterNoNulls - Static variable in interface java.sql.ParameterMetaData
The constant indicating that a parameter will not allow NULL values.
parameterNullable - Static variable in interface java.sql.ParameterMetaData
The constant indicating that a parameter will allow NULL values.
parameterNullableUnknown - Static variable in interface java.sql.ParameterMetaData
The constant indicating that the nullability of a parameter is unknown.
parameters - Variable in class java.awt.image.renderable.ParameterBlock
A Vector of non-source parameters, stored as arbitrary Objects.
parameterType(int) - Method in class java.lang.invoke.MethodType
Returns the parameter type at the specified index, within this method type.
params(NVList) - Method in class org.omg.CORBA.ServerRequest
Deprecated.
use the method arguments
paramString() - Method in class java.awt.AWTEvent
Returns a string representing the state of this Event.
paramString() - Method in class java.awt.Button
Returns a string representing the state of this Button.
paramString() - Method in class java.awt.Checkbox
Returns a string representing the state of this Checkbox.
paramString() - Method in class java.awt.CheckboxMenuItem
Returns a string representing the state of this CheckBoxMenuItem.
paramString() - Method in class java.awt.Choice
Returns a string representing the state of this Choice menu.
paramString() - Method in class java.awt.Component
Returns a string representing the state of this component.
paramString() - Method in class java.awt.Container
Returns a string representing the state of this Container.
paramString() - Method in class java.awt.Dialog
Returns a string representing the state of this dialog.
paramString() - Method in class java.awt.event.ActionEvent
Returns a parameter string identifying this action event.
paramString() - Method in class java.awt.event.AdjustmentEvent
paramString() - Method in class java.awt.event.ComponentEvent
Returns a parameter string identifying this event.
paramString() - Method in class java.awt.event.ContainerEvent
Returns a parameter string identifying this event.
paramString() - Method in class java.awt.event.FocusEvent
Returns a parameter string identifying this event.
paramString() - Method in class java.awt.event.HierarchyEvent
Returns a parameter string identifying this event.
paramString() - Method in class java.awt.event.InputMethodEvent
Returns a parameter string identifying this event.
paramString() - Method in class java.awt.event.InvocationEvent
Returns a parameter string identifying this event.
paramString() - Method in class java.awt.event.ItemEvent
Returns a parameter string identifying this item event.
paramString() - Method in class java.awt.event.KeyEvent
Returns a parameter string identifying this event.
paramString() - Method in class java.awt.event.MouseEvent
Returns a parameter string identifying this event.
paramString() - Method in class java.awt.event.MouseWheelEvent
Returns a parameter string identifying this event.
paramString() - Method in class java.awt.event.PaintEvent
paramString() - Method in class java.awt.Event
NOTE: The Event class is obsolete and is available only for backwards compatilibility.
paramString() - Method in class java.awt.event.TextEvent
Returns a parameter string identifying this text event.
paramString() - Method in class java.awt.event.WindowEvent
Returns a parameter string identifying this event.
paramString() - Method in class java.awt.FileDialog
Returns a string representing the state of this FileDialog window.
paramString() - Method in class java.awt.Frame
Returns a string representing the state of this Frame.
paramString() - Method in class java.awt.Label
Returns a string representing the state of this Label.
paramString() - Method in class java.awt.List
Returns the parameter string representing the state of this scrolling list.
paramString() - Method in class java.awt.Menu
Returns a string representing the state of this Menu.
paramString() - Method in class java.awt.MenuComponent
Returns a string representing the state of this MenuComponent.
paramString() - Method in class java.awt.MenuItem
Returns a string representing the state of this MenuItem.
paramString() - Method in class java.awt.MenuShortcut
Returns the parameter string representing the state of this MenuShortcut.
paramString() - Method in class java.awt.Scrollbar
Returns a string representing the state of this Scrollbar.
paramString() - Method in class java.awt.ScrollPane
Returns a string representing the state of this ScrollPane.
paramString() - Method in class java.awt.ScrollPaneAdjustable
Returns a string representing the state of this scrollbar.
paramString() - Method in class java.awt.TextArea
Returns a string representing the state of this TextArea.
paramString() - Method in class java.awt.TextComponent
Returns a string representing the state of this TextComponent.
paramString() - Method in class java.awt.TextField
Returns a string representing the state of this TextField.
paramString() - Method in class javax.swing.AbstractButton
Returns a string representation of this AbstractButton.
paramString() - Method in class javax.swing.event.InternalFrameEvent
Returns a parameter string identifying this event.
paramString() - Method in class javax.swing.JApplet
Returns a string representation of this JApplet.
paramString() - Method in class javax.swing.JButton
Returns a string representation of this JButton.
paramString() - Method in class javax.swing.JCheckBox
Returns a string representation of this JCheckBox.
paramString() - Method in class javax.swing.JCheckBoxMenuItem
Returns a string representation of this JCheckBoxMenuItem.
paramString() - Method in class javax.swing.JColorChooser
Returns a string representation of this JColorChooser.
paramString() - Method in class javax.swing.JComboBox
Returns a string representation of this JComboBox.
paramString() - Method in class javax.swing.JComponent
Returns a string representation of this JComponent.
paramString() - Method in class javax.swing.JDesktopPane
Returns a string representation of this JDesktopPane.
paramString() - Method in class javax.swing.JDialog
Returns a string representation of this JDialog.
paramString() - Method in class javax.swing.JEditorPane
Returns a string representation of this JEditorPane.
paramString() - Method in class javax.swing.JFileChooser
Returns a string representation of this JFileChooser.
paramString() - Method in class javax.swing.JFrame
Returns a string representation of this JFrame.
paramString() - Method in class javax.swing.JInternalFrame
Returns a string representation of this JInternalFrame.
paramString() - Method in class javax.swing.JLabel
Returns a string representation of this JLabel.
paramString() - Method in class javax.swing.JLayeredPane
Returns a string representation of this JLayeredPane.
paramString() - Method in class javax.swing.JList
Returns a String representation of this JList.
paramString() - Method in class javax.swing.JMenu
Returns a string representation of this JMenu.
paramString() - Method in class javax.swing.JMenuBar
Returns a string representation of this JMenuBar.
paramString() - Method in class javax.swing.JMenuItem
Returns a string representation of this JMenuItem.
paramString() - Method in class javax.swing.JOptionPane
Returns a string representation of this JOptionPane.
paramString() - Method in class javax.swing.JPanel
Returns a string representation of this JPanel.
paramString() - Method in class javax.swing.JPasswordField
Returns a string representation of this JPasswordField.
paramString() - Method in class javax.swing.JPopupMenu
Returns a string representation of this JPopupMenu.
paramString() - Method in class javax.swing.JProgressBar
Returns a string representation of this JProgressBar.
paramString() - Method in class javax.swing.JRadioButton
Returns a string representation of this JRadioButton.
paramString() - Method in class javax.swing.JRadioButtonMenuItem
Returns a string representation of this JRadioButtonMenuItem.
paramString() - Method in class javax.swing.JRootPane
Returns a string representation of this JRootPane.
paramString() - Method in class javax.swing.JScrollBar
Returns a string representation of this JScrollBar.
paramString() - Method in class javax.swing.JScrollPane
Returns a string representation of this JScrollPane.
paramString() - Method in class javax.swing.JSeparator
Returns a string representation of this JSeparator.
paramString() - Method in class javax.swing.JSlider
Returns a string representation of this JSlider.
paramString() - Method in class javax.swing.JSplitPane
Returns a string representation of this JSplitPane.
paramString() - Method in class javax.swing.JTabbedPane
Returns a string representation of this JTabbedPane.
paramString() - Method in class javax.swing.JTable
Returns a string representation of this table.
paramString() - Method in class javax.swing.JTextArea
Returns a string representation of this JTextArea.
paramString() - Method in class javax.swing.JTextField
Returns a string representation of this JTextField.
paramString() - Method in class javax.swing.JTextPane
Returns a string representation of this JTextPane.
paramString() - Method in class javax.swing.JToggleButton
Returns a string representation of this JToggleButton.
paramString() - Method in class javax.swing.JToolBar
Returns a string representation of this JToolBar.
paramString() - Method in class javax.swing.JToolTip
Returns a string representation of this JToolTip.
paramString() - Method in class javax.swing.JTree
Returns a string representation of this JTree.
paramString() - Method in class javax.swing.JViewport
Returns a string representation of this JViewport.
paramString() - Method in class javax.swing.JWindow
Returns a string representation of this JWindow.
paramString() - Method in class javax.swing.table.JTableHeader
Returns a string representation of this JTableHeader.
paramString() - Method in class javax.swing.text.JTextComponent
Returns a string representation of this JTextComponent.
parent - Variable in class java.awt.image.Raster
The parent of this Raster, or null.
parent() - Method in class java.util.prefs.AbstractPreferences
Implements the parent method as per the specification in Preferences.parent().
parent() - Method in class java.util.prefs.Preferences
Returns the parent of this preference node, or null if this is the root.
parent - Variable in class java.util.ResourceBundle
The parent bundle of this bundle.
parent - Variable in class javax.swing.tree.DefaultMutableTreeNode
this node's parent, or null if this node has no parent
parent() - Method in class org.omg.CORBA.Context
Retrieves the parent of this Context object.
PARENT_CHANGED - Static variable in class java.awt.event.HierarchyEvent
A change flag indicates that the HIERARCHY_CHANGED event was generated by a reparenting operation.
PARENT_WINDOW_OF - Static variable in class javax.accessibility.AccessibleRelation
Indicates that an object is a parent window of one or more objects.
PARENT_WINDOW_OF_PROPERTY - Static variable in class javax.accessibility.AccessibleRelation
Indicates the PARENT_WINDOW_OF relation between two or more objects has changed.
parentOf(ThreadGroup) - Method in class java.lang.ThreadGroup
Tests if this thread group is either the thread group argument or one of its ancestor thread groups.
parentTag - Variable in class javax.swing.text.html.HTMLEditorKit.InsertHTMLTextAction
Tag to check for in the document.
park(Object) - Static method in class java.util.concurrent.locks.LockSupport
Disables the current thread for thread scheduling purposes unless the permit is available.
park() - Static method in class java.util.concurrent.locks.LockSupport
Disables the current thread for thread scheduling purposes unless the permit is available.
parkNanos(Object, long) - Static method in class java.util.concurrent.locks.LockSupport
Disables the current thread for thread scheduling purposes, for up to the specified waiting time, unless the permit is available.
parkNanos(long) - Static method in class java.util.concurrent.locks.LockSupport
Disables the current thread for thread scheduling purposes, for up to the specified waiting time, unless the permit is available.
parkUntil(Object, long) - Static method in class java.util.concurrent.locks.LockSupport
Disables the current thread for thread scheduling purposes, until the specified deadline, unless the permit is available.
parkUntil(long) - Static method in class java.util.concurrent.locks.LockSupport
Disables the current thread for thread scheduling purposes, until the specified deadline, unless the permit is available.
parse(String) - Static method in class java.net.HttpCookie
Constructs cookies from set-cookie or set-cookie2 header string.
parse(String, ParsePosition) - Method in class java.text.ChoiceFormat
Parses a Number from the input text.
parse(String) - Method in class java.text.DateFormat
Parses text from the beginning of the given string to produce a date.
parse(String, ParsePosition) - Method in class java.text.DateFormat
Parse a date/time string according to the given parse position.
parse(String, ParsePosition) - Method in class java.text.DecimalFormat
Parses text from a string to produce a Number.
parse(String, ParsePosition) - Method in class java.text.MessageFormat
Parses the string.
parse(String) - Method in class java.text.MessageFormat
Parses text from the beginning of the given string to produce an object array.
parse(String, ParsePosition) - Method in class java.text.NumberFormat
Returns a Long if possible (e.g., within the range [Long.MIN_VALUE, Long.MAX_VALUE] and with no decimals), otherwise a Double.
parse(String) - Method in class java.text.NumberFormat
Parses text from the beginning of the given string to produce a number.
parse(String, ParsePosition) - Method in class java.text.SimpleDateFormat
Parses text from a string to produce a Date.
parse(String) - Static method in class java.util.Date
Deprecated.
As of JDK version 1.1, replaced by DateFormat.parse(String s).
parse(String) - Static method in class java.util.logging.Level
Parse a level name string into a Level.
parse(String) - Method in class javax.activation.MimeTypeParameterList
A routine for parsing the parameter list out of a String.
parse(String) - Method in interface javax.naming.NameParser
Parses a name into its components.
parse(Reader, HTMLEditorKit.ParserCallback, boolean) - Method in class javax.swing.text.html.HTMLEditorKit.Parser
Parse the given stream and drive the given callback with the results of the parse.
parse(Reader, HTMLEditorKit.ParserCallback, boolean) - Method in class javax.swing.text.html.parser.DocumentParser
parse(Reader) - Method in class javax.swing.text.html.parser.Parser
Parse an HTML stream, given a DTD.
parse(Reader, HTMLEditorKit.ParserCallback, boolean) - Method in class javax.swing.text.html.parser.ParserDelegator
parse(InputStream) - Method in class javax.xml.parsers.DocumentBuilder
Parse the content of the given InputStream as an XML document and return a new DOM Document object.
parse(InputStream, String) - Method in class javax.xml.parsers.DocumentBuilder
Parse the content of the given InputStream as an XML document and return a new DOM Document object.
parse(String) - Method in class javax.xml.parsers.DocumentBuilder
Parse the content of the given URI as an XML document and return a new DOM Document object.
parse(File) - Method in class javax.xml.parsers.DocumentBuilder
Parse the content of the given file as an XML document and return a new DOM Document object.
parse(InputSource) - Method in class javax.xml.parsers.DocumentBuilder
Parse the content of the given input source as an XML document and return a new DOM Document object.
parse(InputStream, HandlerBase) - Method in class javax.xml.parsers.SAXParser
Parse the content of the given InputStream instance as XML using the specified HandlerBase.
parse(InputStream, HandlerBase, String) - Method in class javax.xml.parsers.SAXParser
Parse the content of the given InputStream instance as XML using the specified HandlerBase.
parse(InputStream, DefaultHandler) - Method in class javax.xml.parsers.SAXParser
Parse the content of the given InputStream instance as XML using the specified DefaultHandler.
parse(InputStream, DefaultHandler, String) - Method in class javax.xml.parsers.SAXParser
Parse the content of the given InputStream instance as XML using the specified DefaultHandler.
parse(String, HandlerBase) - Method in class javax.xml.parsers.SAXParser
Parse the content described by the giving Uniform Resource Identifier (URI) as XML using the specified HandlerBase.
parse(String, DefaultHandler) - Method in class javax.xml.parsers.SAXParser
Parse the content described by the giving Uniform Resource Identifier (URI) as XML using the specified DefaultHandler.
parse(File, HandlerBase) - Method in class javax.xml.parsers.SAXParser
Parse the content of the file specified as XML using the specified HandlerBase.
parse(File, DefaultHandler) - Method in class javax.xml.parsers.SAXParser
Parse the content of the file specified as XML using the specified DefaultHandler.
parse(InputSource, HandlerBase) - Method in class javax.xml.parsers.SAXParser
Parse the content given InputSource as XML using the specified HandlerBase.
parse(InputSource, DefaultHandler) - Method in class javax.xml.parsers.SAXParser
Parse the content given InputSource as XML using the specified DefaultHandler.
parse(LSInput) - Method in interface org.w3c.dom.ls.LSParser
Parse an XML document from a resource identified by a LSInput.
parse(String) - Method in class org.xml.sax.helpers.ParserAdapter
Parse an XML document.
parse(InputSource) - Method in class org.xml.sax.helpers.ParserAdapter
Parse an XML document.
parse(InputSource) - Method in class org.xml.sax.helpers.XMLFilterImpl
Parse a document.
parse(String) - Method in class org.xml.sax.helpers.XMLFilterImpl
Parse a document.
parse(String) - Method in class org.xml.sax.helpers.XMLReaderAdapter
Parse the document.
parse(InputSource) - Method in class org.xml.sax.helpers.XMLReaderAdapter
Parse the document.
parse(InputSource) - Method in interface org.xml.sax.Parser
Deprecated.
Parse an XML document.
parse(String) - Method in interface org.xml.sax.Parser
Deprecated.
Parse an XML document from a system identifier (URI).
parse(InputSource) - Method in interface org.xml.sax.XMLReader
Parse an XML document.
parse(String) - Method in interface org.xml.sax.XMLReader
Parse an XML document from a system identifier (URI).
PARSE_ERR - Static variable in exception org.w3c.dom.ls.LSException
If an attempt was made to load a document, or an XML Fragment, using LSParser and the processing has been stopped.
parseAnySimpleType(String) - Static method in class javax.xml.bind.DatatypeConverter
Return a string containing the lexical representation of the simple type.
parseAnySimpleType(String) - Method in interface javax.xml.bind.DatatypeConverterInterface
Return a string containing the lexical representation of the simple type.
parseBase64Binary(String) - Static method in class javax.xml.bind.DatatypeConverter
Converts the string argument into an array of bytes.
parseBase64Binary(String) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts the string argument into an array of bytes.
parseBoolean(String) - Static method in class java.lang.Boolean
Parses the string argument as a boolean.
parseBoolean(String) - Static method in class javax.xml.bind.DatatypeConverter
Converts the string argument into a boolean value.
parseBoolean(String) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts the string argument into a boolean value.
parseBuffer - Variable in class javax.swing.text.html.HTMLDocument.HTMLReader
parseByte(String, int) - Static method in class java.lang.Byte
Parses the string argument as a signed byte in the radix specified by the second argument.
parseByte(String) - Static method in class java.lang.Byte
Parses the string argument as a signed decimal byte.
parseByte(String) - Static method in class javax.xml.bind.DatatypeConverter
Converts the string argument into a byte value.
parseByte(String) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts the string argument into a byte value.
ParseConversionEvent - Interface in javax.xml.bind
This event indicates that a problem was encountered while converting a string from the XML data into a value of the target Java data type.
ParseConversionEventImpl - Class in javax.xml.bind.helpers
Default implementation of the ParseConversionEvent interface.
ParseConversionEventImpl(int, String, ValidationEventLocator) - Constructor for class javax.xml.bind.helpers.ParseConversionEventImpl
Create a new ParseConversionEventImpl.
ParseConversionEventImpl(int, String, ValidationEventLocator, Throwable) - Constructor for class javax.xml.bind.helpers.ParseConversionEventImpl
Create a new ParseConversionEventImpl.
parseDate(String) - Static method in class javax.xml.bind.DatatypeConverter
Converts the string argument into a Calendar value.
parseDate(String) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts the string argument into a Calendar value.
parseDateTime(String) - Static method in class javax.xml.bind.DatatypeConverter
Converts the string argument into a Calendar value.
parseDateTime(String) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts the string argument into a Calendar value.
parseDecimal(String) - Static method in class javax.xml.bind.DatatypeConverter
Converts the string argument into a BigDecimal value.
parseDecimal(String) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts the string argument into a BigDecimal value.
parseDouble(String) - Static method in class java.lang.Double
Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.
parseDouble(String) - Static method in class javax.xml.bind.DatatypeConverter
Converts the string argument into a double value.
parseDouble(String) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts the string argument into a double value.
parseDTDMarkup() - Method in class javax.swing.text.html.parser.Parser
Parses th Document Declaration Type markup declaration.
ParseException - Exception in java.text
Signals that an error has been reached unexpectedly while parsing.
ParseException(String, int) - Constructor for exception java.text.ParseException
Constructs a ParseException with the specified detail message and offset.
parseFloat(String) - Static method in class java.lang.Float
Returns a new float initialized to the value represented by the specified String, as performed by the valueOf method of class Float.
parseFloat(String) - Static method in class javax.xml.bind.DatatypeConverter
Converts the string argument into a float value.
parseFloat(String) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts the string argument into a float value.
parseHexBinary(String) - Static method in class javax.xml.bind.DatatypeConverter
Converts the string argument into an array of bytes.
parseHexBinary(String) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts the string argument into an array of bytes.
parseInt(String, int) - Static method in class java.lang.Integer
Parses the string argument as a signed integer in the radix specified by the second argument.
parseInt(String) - Static method in class java.lang.Integer
Parses the string argument as a signed decimal integer.
parseInt(String) - Static method in class javax.xml.bind.DatatypeConverter
Convert the string argument into an int value.
parseInt(String) - Method in interface javax.xml.bind.DatatypeConverterInterface
Convert the string argument into an int value.
parseInteger(String) - Static method in class javax.xml.bind.DatatypeConverter
Convert the string argument into a BigInteger value.
parseInteger(String) - Method in interface javax.xml.bind.DatatypeConverterInterface
Convert the string argument into a BigInteger value.
parseLevel(String) - Static method in class java.rmi.server.LogStream
Deprecated.
no replacement
parseLong(String, int) - Static method in class java.lang.Long
Parses the string argument as a signed long in the radix specified by the second argument.
parseLong(String) - Static method in class java.lang.Long
Parses the string argument as a signed decimal long.
parseLong(String) - Static method in class javax.xml.bind.DatatypeConverter
Converts the string argument into a long value.
parseLong(String) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts the string argument into a long value.
parseMarkupDeclarations(StringBuffer) - Method in class javax.swing.text.html.parser.Parser
Parse markup declarations.
parseNumbers() - Method in class java.io.StreamTokenizer
Specifies that numbers should be parsed by this tokenizer.
parseObject(String, ParsePosition) - Method in class java.text.DateFormat
Parses text from a string to produce a Date.
parseObject(String, ParsePosition) - Method in class java.text.Format
Parses text from a string to produce an object.
parseObject(String) - Method in class java.text.Format
Parses text from the beginning of the given string to produce an object.
parseObject(String, ParsePosition) - Method in class java.text.MessageFormat
Parses text from a string to produce an object array.
parseObject(String, ParsePosition) - Method in class java.text.NumberFormat
Parses text from a string to produce a Number.
ParsePosition - Class in java.text
ParsePosition is a simple class used by Format and its subclasses to keep track of the current position during parsing.
ParsePosition(int) - Constructor for class java.text.ParsePosition
Create a new ParsePosition with the given initial index.
parseQName(String, NamespaceContext) - Static method in class javax.xml.bind.DatatypeConverter
Converts the string argument into a byte value.
parseQName(String, NamespaceContext) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts the string argument into a QName value.
Parser - Class in javax.swing.text.html.parser
A simple DTD-driven HTML parser.
Parser(DTD) - Constructor for class javax.swing.text.html.parser.Parser
Parser - Interface in org.xml.sax
Deprecated.
This interface has been replaced by the SAX2 XMLReader interface, which includes Namespace support.
ParserAdapter - Class in org.xml.sax.helpers
Adapt a SAX1 Parser as a SAX2 XMLReader.
ParserAdapter() - Constructor for class org.xml.sax.helpers.ParserAdapter
Construct a new parser adapter.
ParserAdapter(Parser) - Constructor for class org.xml.sax.helpers.ParserAdapter
Construct a new parser adapter.
ParserConfigurationException - Exception in javax.xml.parsers
Indicates a serious configuration error.
ParserConfigurationException() - Constructor for exception javax.xml.parsers.ParserConfigurationException
Create a new ParserConfigurationException with no detail mesage.
ParserConfigurationException(String) - Constructor for exception javax.xml.parsers.ParserConfigurationException
Create a new ParserConfigurationException with the String specified as an error message.
ParserDelegator - Class in javax.swing.text.html.parser
Responsible for starting up a new DocumentParser each time its parse method is invoked.
ParserDelegator() - Constructor for class javax.swing.text.html.parser.ParserDelegator
ParserFactory - Class in org.xml.sax.helpers
Deprecated.
This class works with the deprecated Parser interface.
parseServerAuthority() - Method in class java.net.URI
Attempts to parse this URI's authority component, if defined, into user-information, host, and port components.
parseShort(String, int) - Static method in class java.lang.Short
Parses the string argument as a signed short in the radix specified by the second argument.
parseShort(String) - Static method in class java.lang.Short
Parses the string argument as a signed decimal short.
parseShort(String) - Static method in class javax.xml.bind.DatatypeConverter
Converts the string argument into a short value.
parseShort(String) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts the string argument into a short value.
parseString(String) - Static method in class javax.xml.bind.DatatypeConverter
Convert the lexical XSD string argument into a String value.
parseString(String) - Method in interface javax.xml.bind.DatatypeConverterInterface
Convert the string argument into a string.
parseTime(String) - Static method in class javax.xml.bind.DatatypeConverter
Converts the string argument into a Calendar value.
parseTime(String) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts the string argument into a Calendar value.
parseUnsignedInt(String) - Static method in class javax.xml.bind.DatatypeConverter
Converts the string argument into a long value.
parseUnsignedInt(String) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts the string argument into a long value.
parseUnsignedShort(String) - Static method in class javax.xml.bind.DatatypeConverter
Converts the string argument into an int value.
parseUnsignedShort(String) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts the string argument into an int value.
parseURI(String) - Method in interface org.w3c.dom.ls.LSParser
Parse an XML document from a location identified by a URI reference [IETF RFC 2396].
parseURL(URL, String, int, int) - Method in class java.net.URLStreamHandler
Parses the string representation of a URL into a URL object.
parseWithContext(LSInput, Node, short) - Method in interface org.w3c.dom.ls.LSParser
Parse an XML fragment from a resource identified by a LSInput and insert the content into an existing document at the position specified with the context and action arguments.
PartialResultException - Exception in javax.naming
This exception is thrown to indicate that the result being returned or returned so far is partial, and that the operation cannot be completed.
PartialResultException(String) - Constructor for exception javax.naming.PartialResultException
Constructs a new instance of the exception using the explanation message specified.
PartialResultException() - Constructor for exception javax.naming.PartialResultException
Constructs a new instance of PartialResultException.
PASS - Static variable in interface java.util.jar.Pack200.Packer
The string "pass", a possible value for certain properties.
PASS_FILE_PFX - Static variable in interface java.util.jar.Pack200.Packer
Indicates that a file should be passed through bytewise, with no compression.
passComplete(ImageReader, BufferedImage) - Method in interface javax.imageio.event.IIOReadUpdateListener
Reports that the current read operation has completed a progressive pass.
passStarted(ImageReader, BufferedImage, int, int, int, int, int, int, int, int[]) - Method in interface javax.imageio.event.IIOReadUpdateListener
Reports that the current read operation is about to begin a progressive pass.
PASSWORD_FIELD - Static variable in class javax.swing.plaf.synth.Region
PasswordField region.
PASSWORD_PROPERTY - Static variable in interface javax.xml.ws.BindingProvider
Standard property: Password for authentication.
PASSWORD_TEXT - Static variable in class javax.accessibility.AccessibleRole
A text object used for passwords, or other places where the text contents is not shown visibly to the user
PasswordAuthentication - Class in java.net
The class PasswordAuthentication is a data holder that is used by Authenticator.
PasswordAuthentication(String, char[]) - Constructor for class java.net.PasswordAuthentication
Creates a new PasswordAuthentication object from the given user name and password.
PasswordCallback - Class in javax.security.auth.callback
Underlying security services instantiate and pass a PasswordCallback to the handle method of a CallbackHandler to retrieve password information.
PasswordCallback(String, boolean) - Constructor for class javax.security.auth.callback.PasswordCallback
Construct a PasswordCallback with a prompt and a boolean specifying whether the password should be displayed as it is being typed.
PasswordView - Class in javax.swing.text
Implements a View suitable for use in JPasswordField UI implementations.
PasswordView(Element) - Constructor for class javax.swing.text.PasswordView
Constructs a new view wrapped on an element.
paste(int) - Method in interface javax.accessibility.AccessibleEditableText
Pastes the text from the system clipboard into the text starting at the specified index.
paste(int) - Method in class javax.swing.JSpinner.AccessibleJSpinner
Pastes the text from the system clipboard into the text starting at the specified index.
paste(int) - Method in class javax.swing.text.JTextComponent.AccessibleJTextComponent
Pastes the text from the system clipboard into the text starting at the specified index.
paste() - Method in class javax.swing.text.JTextComponent
Transfers the contents of the system clipboard into the associated text model.
pasteAction - Static variable in class javax.swing.text.DefaultEditorKit
Name of the action to paste the contents of the system clipboard into the selected region, or before the caret if nothing is selected.
Patch - Class in javax.sound.midi
A Patch object represents a location, on a MIDI synthesizer, into which a single instrument is stored (loaded).
Patch(int, int) - Constructor for class javax.sound.midi.Patch
Constructs a new patch object from the specified bank and program numbers.
Path - Interface in java.nio.file
An object that may be used to locate a file in a file system.
path - Variable in class javax.swing.event.TreeExpansionEvent
Path to the value this event represents.
path - Variable in class javax.swing.event.TreeModelEvent
Path to the parent of the nodes that have changed.
Path2D - Class in java.awt.geom
The Path2D class provides a simple, yet flexible shape which represents an arbitrary geometric path.
Path2D.Double - Class in java.awt.geom
The Double class defines a geometric path with coordinates stored in double precision floating point.
Path2D.Double() - Constructor for class java.awt.geom.Path2D.Double
Constructs a new empty double precision Path2D object with a default winding rule of Path2D.WIND_NON_ZERO.
Path2D.Double(int) - Constructor for class java.awt.geom.Path2D.Double
Constructs a new empty double precision Path2D object with the specified winding rule to control operations that require the interior of the path to be defined.
Path2D.Double(int, int) - Constructor for class java.awt.geom.Path2D.Double
Constructs a new empty double precision Path2D object with the specified winding rule and the specified initial capacity to store path segments.
Path2D.Double(Shape) - Constructor for class java.awt.geom.Path2D.Double
Constructs a new double precision Path2D object from an arbitrary Shape object.
Path2D.Double(Shape, AffineTransform) - Constructor for class java.awt.geom.Path2D.Double
Constructs a new double precision Path2D object from an arbitrary Shape object, transformed by an AffineTransform object.
Path2D.Float - Class in java.awt.geom
The Float class defines a geometric path with coordinates stored in single precision floating point.
Path2D.Float() - Constructor for class java.awt.geom.Path2D.Float
Constructs a new empty single precision Path2D object with a default winding rule of Path2D.WIND_NON_ZERO.
Path2D.Float(int) - Constructor for class java.awt.geom.Path2D.Float
Constructs a new empty single precision Path2D object with the specified winding rule to control operations that require the interior of the path to be defined.
Path2D.Float(int, int) - Constructor for class java.awt.geom.Path2D.Float
Constructs a new empty single precision Path2D object with the specified winding rule and the specified initial capacity to store path segments.
Path2D.Float(Shape) - Constructor for class java.awt.geom.Path2D.Float
Constructs a new single precision Path2D object from an arbitrary Shape object.
Path2D.Float(Shape, AffineTransform) - Constructor for class java.awt.geom.Path2D.Float
Constructs a new single precision Path2D object from an arbitrary Shape object, transformed by an AffineTransform object.
PATH_INFO - Static variable in interface javax.xml.ws.handler.MessageContext
Standard property: Request Path Info
pathByAddingChild(Object) - Method in class javax.swing.tree.TreePath
Returns a new path containing all the elements of this path plus child.
pathFromAncestorEnumeration(TreeNode) - Method in class javax.swing.tree.DefaultMutableTreeNode
Creates and returns an enumeration that follows the path from ancestor to this node.
PathIterator - Interface in java.awt.geom
The PathIterator interface provides the mechanism for objects that implement the Shape interface to return the geometry of their boundary by allowing a caller to retrieve the path of that boundary a segment at a time.
PathMatcher - Interface in java.nio.file
An interface that is implemented by objects that perform match operations on paths.
Paths - Class in java.nio.file
This class consists exclusively of static methods that return a Path by converting a path string or URI.
paths - Variable in class javax.swing.event.TreeSelectionEvent
Paths this event represents.
pathSeparator - Static variable in class java.io.File
The system-dependent path-separator character, represented as a string for convenience.
pathSeparatorChar - Static variable in class java.io.File
The system-dependent path-separator character.
pathToPoint(Point2D, boolean, Point2D) - Method in class java.awt.font.LayoutPath
Convert a location relative to the path to a point in user coordinates.
pathWasCollapsed(TreePath) - Method in class javax.swing.plaf.basic.BasicTreeUI
Messaged from the VisibleTreeNode after it has collapsed.
pathWasExpanded(TreePath) - Method in class javax.swing.plaf.basic.BasicTreeUI
Messaged from the VisibleTreeNode after it has been expanded.
pattern() - Method in class java.util.regex.Matcher
Returns the pattern that is interpreted by this matcher.
Pattern - Class in java.util.regex
A compiled representation of a regular expression.
pattern() - Method in class java.util.regex.Pattern
Returns the regular expression from which this pattern was compiled.
PatternSyntaxException - Exception in java.util.regex
Unchecked exception thrown to indicate a syntax error in a regular-expression pattern.
PatternSyntaxException(String, String, int) - Constructor for exception java.util.regex.PatternSyntaxException
Constructs a new instance of this class.
PAUSE - Static variable in class java.awt.Event
The Pause key, a non-ASCII action key.
PAUSED - Static variable in class javax.print.attribute.standard.PrinterStateReason
Someone has paused the printer and the printer's PrinterState is STOPPED.
PBEKey - Interface in javax.crypto.interfaces
The interface to a PBE key.
PBEKeySpec - Class in javax.crypto.spec
A user-chosen password that can be used with password-based encryption (PBE).
PBEKeySpec(char[]) - Constructor for class javax.crypto.spec.PBEKeySpec
Constructor that takes a password.
PBEKeySpec(char[], byte[], int, int) - Constructor for class javax.crypto.spec.PBEKeySpec
Constructor that takes a password, salt, iteration count, and to-be-derived key length for generating PBEKey of variable-key-size PBE ciphers.
PBEKeySpec(char[], byte[], int) - Constructor for class javax.crypto.spec.PBEKeySpec
Constructor that takes a password, salt, iteration count for generating PBEKey of fixed-key-size PBE ciphers.
PBEParameterSpec - Class in javax.crypto.spec
This class specifies the set of parameters used with password-based encryption (PBE), as defined in the PKCS #5 standard.
PBEParameterSpec(byte[], int) - Constructor for class javax.crypto.spec.PBEParameterSpec
Constructs a parameter set for password-based encryption as defined in the PKCS #5 standard.
pcdata - Variable in class javax.swing.text.html.parser.DTD
PCL - Static variable in class javax.print.DocFlavor.BYTE_ARRAY
Doc flavor with MIME type = "application/vnd.hp-PCL", print data representation class name = "[B" (byte array).
PCL - Static variable in class javax.print.DocFlavor.INPUT_STREAM
Doc flavor with MIME type = "application/vnd.hp-PCL", print data representation class name = "java.io.InputStream" (byte stream).
PCL - Static variable in class javax.print.DocFlavor.URL
Doc flavor with MIME type = "application/vnd.hp-PCL", print data representation class name = "java.net.URL".
PCM_FLOAT - Static variable in class javax.sound.sampled.AudioFormat.Encoding
Specifies floating-point PCM data.
PCM_SIGNED - Static variable in class javax.sound.sampled.AudioFormat.Encoding
Specifies signed, linear PCM data.
PCM_UNSIGNED - Static variable in class javax.sound.sampled.AudioFormat.Encoding
Specifies unsigned, linear PCM data.
pcSupport - Variable in class java.beans.beancontext.BeanContextChildSupport
The PropertyChangeSupport associated with this BeanContextChildSupport.
PDF - Static variable in class javax.print.DocFlavor.BYTE_ARRAY
Doc flavor with MIME type = "application/pdf", print data representation class name = "[B" (byte array).
PDF - Static variable in class javax.print.DocFlavor.INPUT_STREAM
Doc flavor with MIME type = "application/pdf", print data representation class name = "java.io.InputStream" (byte stream).
PDF - Static variable in class javax.print.DocFlavor.URL
Doc flavor with MIME type = "application/pdf", print data representation class name = "java.net.URL".
PDLOverrideSupported - Class in javax.print.attribute.standard
Class PDLOverrideSupported is a printing attribute class, an enumeration, that expresses the printer's ability to attempt to override processing instructions embedded in documents' print data with processing instructions specified as attributes outside the print data.
PDLOverrideSupported(int) - Constructor for class javax.print.attribute.standard.PDLOverrideSupported
Construct a new PDL override supported enumeration value with the given integer value.
peek(InetAddress) - Method in class java.net.DatagramSocketImpl
Peek at the packet to see who it is from.
peek() - Method in class java.util.ArrayDeque
Retrieves, but does not remove, the head of the queue represented by this deque, or returns null if this deque is empty.
peek() - Method in class java.util.concurrent.ArrayBlockingQueue
peek() - Method in interface java.util.concurrent.BlockingDeque
Retrieves, but does not remove, the head of the queue represented by this deque (in other words, the first element of this deque), or returns null if this deque is empty.
peek() - Method in class java.util.concurrent.ConcurrentLinkedDeque
peek() - Method in class java.util.concurrent.ConcurrentLinkedQueue
peek() - Method in class java.util.concurrent.DelayQueue
Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
peek() - Method in class java.util.concurrent.LinkedBlockingDeque
peek() - Method in class java.util.concurrent.LinkedBlockingQueue
peek() - Method in class java.util.concurrent.LinkedTransferQueue
peek() - Method in class java.util.concurrent.PriorityBlockingQueue
peek() - Method in class java.util.concurrent.SynchronousQueue
Always returns null.
peek() - Method in interface java.util.Deque
Retrieves, but does not remove, the head of the queue represented by this deque (in other words, the first element of this deque), or returns null if this deque is empty.
peek() - Method in class java.util.LinkedList
Retrieves, but does not remove, the head (first element) of this list.
peek() - Method in class java.util.PriorityQueue
peek() - Method in interface java.util.Queue
Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
peek() - Method in class java.util.Stack
Looks at the object at the top of this stack without removing it from the stack.
peek() - Method in class javax.xml.stream.util.EventReaderDelegate
peek() - Method in interface javax.xml.stream.XMLEventReader
Check the next XMLEvent without reading it from the stream.
peekData(DatagramPacket) - Method in class java.net.DatagramSocketImpl
Peek at the packet to see who it is from.
peekEvent() - Method in class java.awt.EventQueue
Returns the first event on the EventQueue without removing it.
peekEvent(int) - Method in class java.awt.EventQueue
Returns the first event with the specified id, if any.
peekFirst() - Method in class java.util.ArrayDeque
peekFirst() - Method in class java.util.concurrent.ConcurrentLinkedDeque
peekFirst() - Method in class java.util.concurrent.LinkedBlockingDeque
peekFirst() - Method in interface java.util.Deque
Retrieves, but does not remove, the first element of this deque, or returns null if this deque is empty.
peekFirst() - Method in class java.util.LinkedList
Retrieves, but does not remove, the first element of this list, or returns null if this list is empty.
peekLast() - Method in class java.util.ArrayDeque
peekLast() - Method in class java.util.concurrent.ConcurrentLinkedDeque
peekLast() - Method in class java.util.concurrent.LinkedBlockingDeque
peekLast() - Method in interface java.util.Deque
Retrieves, but does not remove, the last element of this deque, or returns null if this deque is empty.
peekLast() - Method in class java.util.LinkedList
Retrieves, but does not remove, the last element of this list, or returns null if this list is empty.
peekNextLocalTask() - Static method in class java.util.concurrent.ForkJoinTask
Returns, but does not unschedule or execute, a task queued by the current thread but not yet executed, if one is immediately available.
PENDING - Static variable in class javax.print.attribute.standard.JobState
The job is a candidate to start processing, but is not yet processing.
PENDING_HELD - Static variable in class javax.print.attribute.standard.JobState
The job is not a candidate for processing for any number of reasons but will return to the PENDING state as soon as the reasons are no longer present.
PERCENT - Static variable in class java.text.NumberFormat.Field
Constant identifying the percent field.
perform_work() - Method in class org.omg.CORBA.ORB
Performs an implementation-dependent unit of work if called by the main thread.
performDefaultLayout() - Method in class java.awt.font.GlyphVector
Assigns default positions to each glyph in this GlyphVector.
PERMILLE - Static variable in class java.text.NumberFormat.Field
Constant identifying the permille field.
Permission - Interface in java.security.acl
This interface represents a permission, such as that used to grant a particular type of access to a resource.
Permission - Class in java.security
Abstract class for representing access to a system resource.
Permission(String) - Constructor for class java.security.Permission
Constructs a permission with the specified name.
PermissionCollection - Class in java.security
Abstract class representing a collection of Permission objects.
PermissionCollection() - Constructor for class java.security.PermissionCollection
permissions() - Method in class java.nio.file.attribute.AclEntry
Returns a copy of the permissions component.
permissions() - Method in interface java.nio.file.attribute.PosixFileAttributes
Returns the permissions of the file.
permissions() - Method in interface java.security.acl.AclEntry
Returns an enumeration of the permissions in this ACL entry.
Permissions - Class in java.security
This class represents a heterogeneous collection of Permissions.
Permissions() - Constructor for class java.security.Permissions
Creates a new Permissions object containing no PermissionCollections.
permits(Set<CryptoPrimitive>, String, AlgorithmParameters) - Method in interface java.security.AlgorithmConstraints
Determines whether an algorithm is granted permission for the specified cryptographic primitives.
permits(Set<CryptoPrimitive>, Key) - Method in interface java.security.AlgorithmConstraints
Determines whether a key is granted permission for the specified cryptographic primitives.
permits(Set<CryptoPrimitive>, String, Key, AlgorithmParameters) - Method in interface java.security.AlgorithmConstraints
Determines whether an algorithm and the corresponding key are granted permission for the specified cryptographic primitives.
permuteArguments(MethodHandle, MethodType, int...) - Static method in class java.lang.invoke.MethodHandles
Produces a method handle which adapts the calling sequence of the given method handle to a new type, by reordering the arguments.
PERSIST - Static variable in class javax.swing.JFormattedTextField
Constant identifying that when focus is lost, the edited value should be left.
PERSIST_STORE - Exception in org.omg.CORBA
This exception indicates a persistent storage failure, for example, failure to establish a database connection or corruption of a database.
PERSIST_STORE() - Constructor for exception org.omg.CORBA.PERSIST_STORE
Constructs a PERSIST_STORE exception with a default minor code of 0, a completion state of CompletionStatus.COMPLETED_NO, and a null description.
PERSIST_STORE(String) - Constructor for exception org.omg.CORBA.PERSIST_STORE
Constructs a PERSIST_STORE exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.
PERSIST_STORE(int, CompletionStatus) - Constructor for exception org.omg.CORBA.PERSIST_STORE
Constructs a PERSIST_STORE exception with the specified minor code and completion status.
PERSIST_STORE(String, int, CompletionStatus) - Constructor for exception org.omg.CORBA.PERSIST_STORE
Constructs a PERSIST_STORE exception with the specified description message, minor code, and completion status.
PersistenceDelegate - Class in java.beans
The PersistenceDelegate class takes the responsibility for expressing the state of an instance of a given class in terms of the methods in the class's public API.
PersistenceDelegate() - Constructor for class java.beans.PersistenceDelegate
PERSISTENT - Static variable in class org.omg.PortableServer.LifespanPolicyValue
PersistentMBean - Interface in javax.management
This class is the interface to be implemented by MBeans that are meant to be persistent.
PERSONAL - Static variable in class java.awt.PageAttributes.MediaType
An alias for PERSONAL_ENVELOPE.
PERSONAL_ENVELOPE - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for 6 3/4 envelope, 3 5/8 x 6 1/2 in.
PERSONAL_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSize.Other
Specifies the Personal envelope size, 3.625 inch by 6.5 inch.
PERSONAL_ENVELOPE - Static variable in class javax.print.attribute.standard.MediaSizeName
personal envelope size .
PGDN - Static variable in class java.awt.Event
The Page Down key, a non-ASCII action key.
PGPData - Interface in javax.xml.crypto.dsig.keyinfo
A representation of the XML PGPData element as defined in the W3C Recommendation for XML-Signature Syntax and Processing.
PGUP - Static variable in class java.awt.Event
The Page Up key, a non-ASCII action key.
PHAGS_PA - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Phags-pa" Unicode character block.
PHAISTOS_DISC - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Phaistos Disc" Unicode character block.
PhantomReference<T> - Class in java.lang.ref
Phantom reference objects, which are enqueued after the collector determines that their referents may otherwise be reclaimed.
PhantomReference(T, ReferenceQueue<? super T>) - Constructor for class java.lang.ref.PhantomReference
Creates a new phantom reference that refers to the given object and is registered with the given queue.
Phaser - Class in java.util.concurrent
A reusable synchronization barrier, similar in functionality to CyclicBarrier and CountDownLatch but supporting more flexible usage.
Phaser() - Constructor for class java.util.concurrent.Phaser
Creates a new phaser with no initially registered parties, no parent, and initial phase number 0.
Phaser(int) - Constructor for class java.util.concurrent.Phaser
Creates a new phaser with the given number of registered unarrived parties, no parent, and initial phase number 0.
Phaser(Phaser) - Constructor for class java.util.concurrent.Phaser
Equivalent to Phaser(parent, 0).
Phaser(Phaser, int) - Constructor for class java.util.concurrent.Phaser
Creates a new phaser with the given parent and number of registered unarrived parties.
PHOENICIAN - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Phoenician" Unicode character block.
PHONETIC_EXTENSIONS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Phonetic Extensions" Unicode character block.
PHONETIC_EXTENSIONS_SUPPLEMENT - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Phonetic Extensions Supplement" Unicode character block.
PHYSICAL - Static variable in class java.awt.PageAttributes.OriginType
The OriginType instance to use for specifying a physical origin.
PI - Static variable in class java.lang.Math
The double value that is closer than any other to pi, the ratio of the circumference of a circle to its diameter.
PI - Static variable in class java.lang.StrictMath
The double value that is closer than any other to pi, the ratio of the circumference of a circle to its diameter.
PI - Static variable in interface javax.swing.text.html.parser.DTDConstants
PI_DISABLE_OUTPUT_ESCAPING - Static variable in interface javax.xml.transform.Result
The name of the processing instruction that is sent if the result tree disables output escaping.
PI_ENABLE_OUTPUT_ESCAPING - Static variable in interface javax.xml.transform.Result
The name of the processing instruction that is sent if the result tree enables output escaping at some point after having received a PI_DISABLE_OUTPUT_ESCAPING processing instruction.
PIE - Static variable in class java.awt.geom.Arc2D
The closure type for an arc closed by drawing straight line segments from the start of the arc segment to the center of the full ellipse and from that point to the end of the arc segment.
pink - Static variable in class java.awt.Color
The color pink.
PINK - Static variable in class java.awt.Color
The color pink.
PIPE - Static variable in class java.lang.ProcessBuilder.Redirect
Indicates that subprocess I/O will be connected to the current Java process over a pipe.
Pipe - Class in java.nio.channels
A pair of channels that implements a unidirectional pipe.
Pipe() - Constructor for class java.nio.channels.Pipe
Initializes a new instance of this class.
Pipe.SinkChannel - Class in java.nio.channels
A channel representing the writable end of a Pipe.
Pipe.SinkChannel(SelectorProvider) - Constructor for class java.nio.channels.Pipe.SinkChannel
Initializes a new instance of this class.
Pipe.SourceChannel - Class in java.nio.channels
A channel representing the readable end of a Pipe.
Pipe.SourceChannel(SelectorProvider) - Constructor for class java.nio.channels.Pipe.SourceChannel
Constructs a new instance of this class.
PIPE_SIZE - Static variable in class java.io.PipedInputStream
The default size of the pipe's circular input buffer.
PipedInputStream - Class in java.io
A piped input stream should be connected to a piped output stream; the piped input stream then provides whatever data bytes are written to the piped output stream.
PipedInputStream(PipedOutputStream) - Constructor for class java.io.PipedInputStream
Creates a PipedInputStream so that it is connected to the piped output stream src.
PipedInputStream(PipedOutputStream, int) - Constructor for class java.io.PipedInputStream
Creates a PipedInputStream so that it is connected to the piped output stream src and uses the specified pipe size for the pipe's buffer.
PipedInputStream() - Constructor for class java.io.PipedInputStream
Creates a PipedInputStream so that it is not yet connected.
PipedInputStream(int) - Constructor for class java.io.PipedInputStream
Creates a PipedInputStream so that it is not yet connected and uses the specified pipe size for the pipe's buffer.
PipedOutputStream - Class in java.io
A piped output stream can be connected to a piped input stream to create a communications pipe.
PipedOutputStream(PipedInputStream) - Constructor for class java.io.PipedOutputStream
Creates a piped output stream connected to the specified piped input stream.
PipedOutputStream() - Constructor for class java.io.PipedOutputStream
Creates a piped output stream that is not yet connected to a piped input stream.
PipedReader - Class in java.io
Piped character-input streams.
PipedReader(PipedWriter) - Constructor for class java.io.PipedReader
Creates a PipedReader so that it is connected to the piped writer src.
PipedReader(PipedWriter, int) - Constructor for class java.io.PipedReader
Creates a PipedReader so that it is connected to the piped writer src and uses the specified pipe size for the pipe's buffer.
PipedReader() - Constructor for class java.io.PipedReader
Creates a PipedReader so that it is not yet connected.
PipedReader(int) - Constructor for class java.io.PipedReader
Creates a PipedReader so that it is not yet connected and uses the specified pipe size for the pipe's buffer.
PipedWriter - Class in java.io
Piped character-output streams.
PipedWriter(PipedReader) - Constructor for class java.io.PipedWriter
Creates a piped writer connected to the specified piped reader.
PipedWriter() - Constructor for class java.io.PipedWriter
Creates a piped writer that is not yet connected to a piped reader.
PITCH_BEND - Static variable in class javax.sound.midi.ShortMessage
Command value for Pitch Bend message (0xE0, or 224)
pixel_bits - Variable in class java.awt.image.ColorModel
The total number of bits in the pixel.
PixelGrabber - Class in java.awt.image
The PixelGrabber class implements an ImageConsumer which can be attached to an Image or ImageProducer object to retrieve a subset of the pixels in that image.
PixelGrabber(Image, int, int, int, int, int[], int, int) - Constructor for class java.awt.image.PixelGrabber
Create a PixelGrabber object to grab the (x, y, w, h) rectangular section of pixels from the specified image into the given array.
PixelGrabber(ImageProducer, int, int, int, int, int[], int, int) - Constructor for class java.awt.image.PixelGrabber
Create a PixelGrabber object to grab the (x, y, w, h) rectangular section of pixels from the image produced by the specified ImageProducer into the given array.
PixelGrabber(Image, int, int, int, int, boolean) - Constructor for class java.awt.image.PixelGrabber
Create a PixelGrabber object to grab the (x, y, w, h) rectangular section of pixels from the specified image.
PixelInterleavedSampleModel - Class in java.awt.image
This class represents image data which is stored in a pixel interleaved fashion and for which each sample of a pixel occupies one data element of the DataBuffer.
PixelInterleavedSampleModel(int, int, int, int, int, int[]) - Constructor for class java.awt.image.PixelInterleavedSampleModel
Constructs a PixelInterleavedSampleModel with the specified parameters.
pixelStride - Variable in class java.awt.image.ComponentSampleModel
Pixel stride (in data array elements) of the region of image data described by this ComponentSampleModel.
PKCS8EncodedKeySpec - Class in java.security.spec
This class represents the ASN.1 encoding of a private key, encoded according to the ASN.1 type PrivateKeyInfo.
PKCS8EncodedKeySpec(byte[]) - Constructor for class java.security.spec.PKCS8EncodedKeySpec
Creates a new PKCS8EncodedKeySpec with the given encoded key.
PKIXBuilderParameters - Class in java.security.cert
Parameters used as input for the PKIX CertPathBuilder algorithm.
PKIXBuilderParameters(Set<TrustAnchor>, CertSelector) - Constructor for class java.security.cert.PKIXBuilderParameters
Creates an instance of PKIXBuilderParameters with the specified Set of most-trusted CAs.
PKIXBuilderParameters(KeyStore, CertSelector) - Constructor for class java.security.cert.PKIXBuilderParameters
Creates an instance of PKIXBuilderParameters that populates the set of most-trusted CAs from the trusted certificate entries contained in the specified KeyStore.
PKIXCertPathBuilderResult - Class in java.security.cert
This class represents the successful result of the PKIX certification path builder algorithm.
PKIXCertPathBuilderResult(CertPath, TrustAnchor, PolicyNode, PublicKey) - Constructor for class java.security.cert.PKIXCertPathBuilderResult
Creates an instance of PKIXCertPathBuilderResult containing the specified parameters.
PKIXCertPathChecker - Class in java.security.cert
An abstract class that performs one or more checks on an X509Certificate.
PKIXCertPathChecker() - Constructor for class java.security.cert.PKIXCertPathChecker
Default constructor.
PKIXCertPathValidatorResult - Class in java.security.cert
This class represents the successful result of the PKIX certification path validation algorithm.
PKIXCertPathValidatorResult(TrustAnchor, PolicyNode, PublicKey) - Constructor for class java.security.cert.PKIXCertPathValidatorResult
Creates an instance of PKIXCertPathValidatorResult containing the specified parameters.
PKIXParameters - Class in java.security.cert
Parameters used as input for the PKIX CertPathValidator algorithm.
PKIXParameters(Set<TrustAnchor>) - Constructor for class java.security.cert.PKIXParameters
Creates an instance of PKIXParameters with the specified Set of most-trusted CAs.
PKIXParameters(KeyStore) - Constructor for class java.security.cert.PKIXParameters
Creates an instance of PKIXParameters that populates the set of most-trusted CAs from the trusted certificate entries contained in the specified KeyStore.
PKIXReason - Enum in java.security.cert
The PKIXReason enumerates the potential PKIX-specific reasons that an X.509 certification path may be invalid according to the PKIX (RFC 3280) standard.
PLAIN - Static variable in class java.awt.Font
The plain style constant.
PLAIN_DIALOG - Static variable in class javax.swing.JRootPane
Constant used for the windowDecorationStyle property.
PLAIN_MESSAGE - Static variable in class javax.swing.JOptionPane
No icon is used.
PlainDocument - Class in javax.swing.text
A plain document that maintains no character attributes.
PlainDocument() - Constructor for class javax.swing.text.PlainDocument
Constructs a plain text document.
PlainDocument(AbstractDocument.Content) - Constructor for class javax.swing.text.PlainDocument
Constructs a plain text document.
plainTextFlavor - Static variable in class java.awt.datatransfer.DataFlavor
Deprecated.
as of 1.3. Use DataFlavor.getReaderForText(Transferable) instead of Transferable.getTransferData(DataFlavor.plainTextFlavor).
PlainView - Class in javax.swing.text
Implements View interface for a simple multi-line text view that has text in one font and color.
PlainView(Element) - Constructor for class javax.swing.text.PlainView
Constructs a new PlainView wrapped on an element.
PlatformLoggingMXBean - Interface in java.lang.management
The management interface for the logging facility.
PlatformManagedObject - Interface in java.lang.management
A platform managed object is a JMX MXBean for monitoring and managing a component in the Java platform.
play(URL) - Method in class java.applet.Applet
Plays the audio clip at the specified absolute URL.
play(URL, String) - Method in class java.applet.Applet
Plays the audio clip given the URL and a specifier that is relative to it.
play() - Method in interface java.applet.AudioClip
Starts playing this audio clip.
PLAYING_CARDS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Playing Cards" Unicode character block.
playSound(Action) - Method in class javax.swing.plaf.basic.BasicLookAndFeel
If necessary, invokes actionPerformed on audioAction to play a sound.
pluginClassName - Variable in class javax.imageio.spi.ImageReaderWriterSpi
A String containing the name of the associated plug-in class, initially null.
plus() - Method in class java.math.BigDecimal
Returns a BigDecimal whose value is (+this), and whose scale is this.scale().
plus(MathContext) - Method in class java.math.BigDecimal
Returns a BigDecimal whose value is (+this), with rounding according to the context settings.
PLUS - Static variable in class javax.management.Query
A code representing the Query.plus(javax.management.ValueExp, javax.management.ValueExp) expression.
plus(ValueExp, ValueExp) - Static method in class javax.management.Query
Returns a binary expression representing the sum of two numeric values, or the concatenation of two string values.
PM - Static variable in class java.util.Calendar
Value of the Calendar.AM_PM field indicating the period of the day from noon to just before midnight.
PNG - Static variable in class javax.print.DocFlavor.BYTE_ARRAY
Doc flavor with MIME type = "image/png", print data representation class name = "[B" (byte array).
PNG - Static variable in class javax.print.DocFlavor.INPUT_STREAM
Doc flavor with MIME type = "image/png", print data representation class name = "java.io.InputStream" (byte stream).
PNG - Static variable in class javax.print.DocFlavor.URL
Doc flavor with MIME type = "image/png", print data representation class name = "java.net.URL".
POA - Interface in org.omg.PortableServer
A POA object manages the implementation of a collection of objects.
poa(Servant) - Method in interface org.omg.PortableServer.portable.Delegate
The method _poa() is equivalent to calling PortableServer::Current:get_POA.
POAHelper - Class in org.omg.PortableServer
A POA object manages the implementation of a collection of objects.
POAHelper() - Constructor for class org.omg.PortableServer.POAHelper
POAManager - Interface in org.omg.PortableServer
Each POA object has an associated POAManager object.
POAManagerOperations - Interface in org.omg.PortableServer
Each POA object has an associated POAManager object.
POAOperations - Interface in org.omg.PortableServer
A POA object manages the implementation of a collection of objects.
Point - Class in java.awt
A point representing a location in (x,y) coordinate space, specified in integer precision.
Point() - Constructor for class java.awt.Point
Constructs and initializes a point at the origin (0, 0) of the coordinate space.
Point(Point) - Constructor for class java.awt.Point
Constructs and initializes a point with the same location as the specified Point object.
Point(int, int) - Constructor for class java.awt.Point
Constructs and initializes a point at the specified (x,y) location in the coordinate space.
Point2D - Class in java.awt.geom
The Point2D class defines a point representing a location in (x,y) coordinate space.
Point2D() - Constructor for class java.awt.geom.Point2D
This is an abstract class that cannot be instantiated directly.
Point2D.Double - Class in java.awt.geom
The Double class defines a point specified in double precision.
Point2D.Double() - Constructor for class java.awt.geom.Point2D.Double
Constructs and initializes a Point2D with coordinates (0, 0).
Point2D.Double(double, double) - Constructor for class java.awt.geom.Point2D.Double
Constructs and initializes a Point2D with the specified coordinates.
Point2D.Float - Class in java.awt.geom
The Float class defines a point specified in float precision.
Point2D.Float() - Constructor for class java.awt.geom.Point2D.Float
Constructs and initializes a Point2D with coordinates (0, 0).
Point2D.Float(float, float) - Constructor for class java.awt.geom.Point2D.Float
Constructs and initializes a Point2D with the specified coordinates.
POINT_INFINITY - Static variable in class java.security.spec.ECPoint
This defines the point at infinity.
PointerInfo - Class in java.awt
A class that describes the pointer position.
pointSize - Variable in class java.awt.Font
The point size of this Font in float.
pointToPath(Point2D, Point2D) - Method in class java.awt.font.LayoutPath
Convert a point in user space to a location relative to the path.
Policy - Class in java.security
A Policy object is responsible for determining whether code executing in the Java runtime environment has permission to perform a security-sensitive operation.
Policy() - Constructor for class java.security.Policy
Policy - Class in javax.security.auth
Deprecated.
as of JDK version 1.4 -- Replaced by java.security.Policy. java.security.Policy has a method:
      public PermissionCollection getPermissions
          (java.security.ProtectionDomain pd)
and ProtectionDomain has a constructor:
      public ProtectionDomain
          (CodeSource cs,
           PermissionCollection permissions,
           ClassLoader loader,
           Principal[] principals)
These two APIs provide callers the means to query the Policy for Principal-based Permission entries.
Policy() - Constructor for class javax.security.auth.Policy
Deprecated.
Sole constructor.
Policy - Interface in org.omg.CORBA
Interfaces derived from the Policy interface allow an ORB or CORBA service access to certain choices that affect its operation.
Policy.Parameters - Interface in java.security
This represents a marker interface for Policy parameters.
POLICY_FORWARD_SECRECY - Static variable in class javax.security.sasl.Sasl
The name of a property that specifies whether mechanisms that implement forward secrecy between sessions are required.
POLICY_NOACTIVE - Static variable in class javax.security.sasl.Sasl
The name of a property that specifies whether mechanisms susceptible to active (non-dictionary) attacks are not permitted.
POLICY_NOANONYMOUS - Static variable in class javax.security.sasl.Sasl
The name of a property that specifies whether mechanisms that accept anonymous login are not permitted.
POLICY_NODICTIONARY - Static variable in class javax.security.sasl.Sasl
The name of a property that specifies whether mechanisms susceptible to passive dictionary attacks are not permitted.
POLICY_NOPLAINTEXT - Static variable in class javax.security.sasl.Sasl
The name of a property that specifies whether mechanisms susceptible to simple plain passive attacks (e.g., "PLAIN") are not permitted.
POLICY_PASS_CREDENTIALS - Static variable in class javax.security.sasl.Sasl
The name of a property that specifies whether mechanisms that pass client credentials are required.
policy_type() - Method in class org.omg.CORBA._PolicyStub
Returns the constant value that corresponds to the type of the policy object.
policy_type() - Method in interface org.omg.CORBA.PolicyOperations
Returns the constant value that corresponds to the type of the policy object.
PolicyError - Exception in org.omg.CORBA
A user exception thrown when a policy error occurs.
PolicyError() - Constructor for exception org.omg.CORBA.PolicyError
Constructs a default PolicyError user exception with no reason code and an empty reason detail message.
PolicyError(short) - Constructor for exception org.omg.CORBA.PolicyError
Constructs a PolicyError user exception initialized with the given reason code and an empty reason detail message.
PolicyError(String, short) - Constructor for exception org.omg.CORBA.PolicyError
Constructs a PolicyError user exception initialized with the given reason detail message and reason code.
PolicyErrorCodeHelper - Class in org.omg.CORBA
Encapsulates a reason a Policy may be invalid.
PolicyErrorCodeHelper() - Constructor for class org.omg.CORBA.PolicyErrorCodeHelper
PolicyErrorHelper - Class in org.omg.CORBA
Thrown to indicate problems with parameter values passed to the ORB.create_policy operation.
PolicyErrorHelper() - Constructor for class org.omg.CORBA.PolicyErrorHelper
PolicyErrorHolder - Class in org.omg.CORBA
Thrown to indicate problems with parameter values passed to the ORB.create_policy operation.
PolicyErrorHolder() - Constructor for class org.omg.CORBA.PolicyErrorHolder
PolicyErrorHolder(PolicyError) - Constructor for class org.omg.CORBA.PolicyErrorHolder
PolicyFactory - Interface in org.omg.PortableInterceptor
Enables policy types to be constructed using CORBA.ORB.create_policy.
PolicyFactoryOperations - Interface in org.omg.PortableInterceptor
Enables policy types to be constructed using CORBA.ORB.create_policy.
PolicyHelper - Class in org.omg.CORBA
The Helper for Policy.
PolicyHelper() - Constructor for class org.omg.CORBA.PolicyHelper
PolicyHolder - Class in org.omg.CORBA
The Holder for Policy.
PolicyHolder() - Constructor for class org.omg.CORBA.PolicyHolder
PolicyHolder(Policy) - Constructor for class org.omg.CORBA.PolicyHolder
PolicyListHelper - Class in org.omg.CORBA
The Helper for PolicyList.
PolicyListHelper() - Constructor for class org.omg.CORBA.PolicyListHelper
PolicyListHolder - Class in org.omg.CORBA
The Holder for PolicyList.
PolicyListHolder() - Constructor for class org.omg.CORBA.PolicyListHolder
PolicyListHolder(Policy[]) - Constructor for class org.omg.CORBA.PolicyListHolder
PolicyNode - Interface in java.security.cert
An immutable valid policy tree node as defined by the PKIX certification path validation algorithm.
PolicyOperations - Interface in org.omg.CORBA
Provides the operations for a Policy object.
PolicyQualifierInfo - Class in java.security.cert
An immutable policy qualifier represented by the ASN.1 PolicyQualifierInfo structure.
PolicyQualifierInfo(byte[]) - Constructor for class java.security.cert.PolicyQualifierInfo
Creates an instance of PolicyQualifierInfo from the encoded bytes.
PolicySpi - Class in java.security
This class defines the Service Provider Interface (SPI) for the Policy class.
PolicySpi() - Constructor for class java.security.PolicySpi
PolicyTypeHelper - Class in org.omg.CORBA
The Helper for PolicyType.
PolicyTypeHelper() - Constructor for class org.omg.CORBA.PolicyTypeHelper
poll() - Method in class java.lang.ref.ReferenceQueue
Polls this queue to see if a reference object is available.
poll() - Method in interface java.nio.file.WatchService
Retrieves and removes the next watch key, or null if none are present.
poll(long, TimeUnit) - Method in interface java.nio.file.WatchService
Retrieves and removes the next watch key, waiting if necessary up to the specified wait time if none are yet present.
poll() - Method in class java.util.ArrayDeque
Retrieves and removes the head of the queue represented by this deque (in other words, the first element of this deque), or returns null if this deque is empty.
poll() - Method in class java.util.concurrent.ArrayBlockingQueue
poll(long, TimeUnit) - Method in class java.util.concurrent.ArrayBlockingQueue
poll() - Method in interface java.util.concurrent.BlockingDeque
Retrieves and removes the head of the queue represented by this deque (in other words, the first element of this deque), or returns null if this deque is empty.
poll(long, TimeUnit) - Method in interface java.util.concurrent.BlockingDeque
Retrieves and removes the head of the queue represented by this deque (in other words, the first element of this deque), waiting up to the specified wait time if necessary for an element to become available.
poll(long, TimeUnit) - Method in interface java.util.concurrent.BlockingQueue
Retrieves and removes the head of this queue, waiting up to the specified wait time if necessary for an element to become available.
poll() - Method in interface java.util.concurrent.CompletionService
Retrieves and removes the Future representing the next completed task or null if none are present.
poll(long, TimeUnit) - Method in interface java.util.concurrent.CompletionService
Retrieves and removes the Future representing the next completed task, waiting if necessary up to the specified wait time if none are yet present.
poll() - Method in class java.util.concurrent.ConcurrentLinkedDeque
poll() - Method in class java.util.concurrent.ConcurrentLinkedQueue
poll() - Method in class java.util.concurrent.DelayQueue
Retrieves and removes the head of this queue, or returns null if this queue has no elements with an expired delay.
poll(long, TimeUnit) - Method in class java.util.concurrent.DelayQueue
Retrieves and removes the head of this queue, waiting if necessary until an element with an expired delay is available on this queue, or the specified wait time expires.
poll() - Method in class java.util.concurrent.ExecutorCompletionService
poll(long, TimeUnit) - Method in class java.util.concurrent.ExecutorCompletionService
poll() - Method in class java.util.concurrent.LinkedBlockingDeque
poll(long, TimeUnit) - Method in class java.util.concurrent.LinkedBlockingDeque
poll(long, TimeUnit) - Method in class java.util.concurrent.LinkedBlockingQueue
poll() - Method in class java.util.concurrent.LinkedBlockingQueue
poll(long, TimeUnit) - Method in class java.util.concurrent.LinkedTransferQueue
poll() - Method in class java.util.concurrent.LinkedTransferQueue
poll() - Method in class java.util.concurrent.PriorityBlockingQueue
poll(long, TimeUnit) - Method in class java.util.concurrent.PriorityBlockingQueue
poll(long, TimeUnit) - Method in class java.util.concurrent.SynchronousQueue
Retrieves and removes the head of this queue, waiting if necessary up to the specified wait time, for another thread to insert it.
poll() - Method in class java.util.concurrent.SynchronousQueue
Retrieves and removes the head of this queue, if another thread is currently making an element available.
poll() - Method in interface java.util.Deque
Retrieves and removes the head of the queue represented by this deque (in other words, the first element of this deque), or returns null if this deque is empty.
poll() - Method in class java.util.LinkedList
Retrieves and removes the head (first element) of this list.
poll() - Method in class java.util.PriorityQueue
poll() - Method in interface java.util.Queue
Retrieves and removes the head of this queue, or returns null if this queue is empty.
poll_next_response() - Method in class org.omg.CORBA.ORB
Finds out if any of the deferred (asynchronous) invocations have a response yet.
poll_response() - Method in class org.omg.CORBA.Request
Allows the user to determine whether a response has been received for the invocation triggered earlier with the send_deferred method.
pollEvents() - Method in interface java.nio.file.WatchKey
Retrieves and removes all pending events for this watch key, returning a List of the events that were retrieved.
pollFirst() - Method in class java.util.ArrayDeque
pollFirst(long, TimeUnit) - Method in interface java.util.concurrent.BlockingDeque
Retrieves and removes the first element of this deque, waiting up to the specified wait time if necessary for an element to become available.
pollFirst() - Method in class java.util.concurrent.ConcurrentLinkedDeque
pollFirst() - Method in class java.util.concurrent.ConcurrentSkipListSet
pollFirst() - Method in class java.util.concurrent.LinkedBlockingDeque
pollFirst(long, TimeUnit) - Method in class java.util.concurrent.LinkedBlockingDeque
pollFirst() - Method in interface java.util.Deque
Retrieves and removes the first element of this deque, or returns null if this deque is empty.
pollFirst() - Method in class java.util.LinkedList
Retrieves and removes the first element of this list, or returns null if this list is empty.
pollFirst() - Method in interface java.util.NavigableSet
Retrieves and removes the first (lowest) element, or returns null if this set is empty.
pollFirst() - Method in class java.util.TreeSet
pollFirstEntry() - Method in class java.util.concurrent.ConcurrentSkipListMap
Removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty.
pollFirstEntry() - Method in interface java.util.NavigableMap
Removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty.
pollFirstEntry() - Method in class java.util.TreeMap
pollLast() - Method in class java.util.ArrayDeque
pollLast(long, TimeUnit) - Method in interface java.util.concurrent.BlockingDeque
Retrieves and removes the last element of this deque, waiting up to the specified wait time if necessary for an element to become available.
pollLast() - Method in class java.util.concurrent.ConcurrentLinkedDeque
pollLast() - Method in class java.util.concurrent.ConcurrentSkipListSet
pollLast() - Method in class java.util.concurrent.LinkedBlockingDeque
pollLast(long, TimeUnit) - Method in class java.util.concurrent.LinkedBlockingDeque
pollLast() - Method in interface java.util.Deque
Retrieves and removes the last element of this deque, or returns null if this deque is empty.
pollLast() - Method in class java.util.LinkedList
Retrieves and removes the last element of this list, or returns null if this list is empty.
pollLast() - Method in interface java.util.NavigableSet
Retrieves and removes the last (highest) element, or returns null if this set is empty.
pollLast() - Method in class java.util.TreeSet
pollLastEntry() - Method in class java.util.concurrent.ConcurrentSkipListMap
Removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
pollLastEntry() - Method in interface java.util.NavigableMap
Removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
pollLastEntry() - Method in class java.util.TreeMap
pollNextLocalTask() - Static method in class java.util.concurrent.ForkJoinTask
Unschedules and returns, without executing, the next task queued by the current thread but not yet executed.
pollSubmission() - Method in class java.util.concurrent.ForkJoinPool
Removes and returns the next unexecuted submission if one is available.
pollTask() - Static method in class java.util.concurrent.ForkJoinTask
Unschedules and returns, without executing, the next task queued by the current thread but not yet executed, if one is available, or if not available, a task that was forked by some other thread, if available.
POLY_PRESSURE - Static variable in class javax.sound.midi.ShortMessage
Command value for Polyphonic Key Pressure (Aftertouch) message (0xA0, or 160)
Polygon - Class in java.awt
The Polygon class encapsulates a description of a closed, two-dimensional region within a coordinate space.
Polygon() - Constructor for class java.awt.Polygon
Creates an empty polygon.
Polygon(int[], int[], int) - Constructor for class java.awt.Polygon
Constructs and initializes a Polygon from the specified parameters.
PooledConnection - Interface in javax.sql
An object that provides hooks for connection pool management.
pop() - Method in class java.awt.EventQueue
Stops dispatching events using this EventQueue.
pop() - Method in class java.util.ArrayDeque
Pops an element from the stack represented by this deque.
pop() - Method in class java.util.concurrent.ConcurrentLinkedDeque
pop() - Method in class java.util.concurrent.LinkedBlockingDeque
pop() - Method in interface java.util.Deque
Pops an element from the stack represented by this deque.
pop() - Method in class java.util.LinkedList
Pops an element from the stack represented by this list.
pop() - Method in class java.util.Stack
Removes the object at the top of this stack and returns that object as the value of this function.
popCharacterStyle() - Method in class javax.swing.text.html.HTMLDocument.HTMLReader
Pops a previously pushed character style off the stack to return to a previous style.
popContext() - Method in class org.xml.sax.helpers.NamespaceSupport
Revert to the previous Namespace context.
populate(ResultSet) - Method in interface javax.sql.rowset.CachedRowSet
Populates this CachedRowSet object with data from the given ResultSet object.
populate(ResultSet, int) - Method in interface javax.sql.rowset.CachedRowSet
Populates this CachedRowSet object with data from the given ResultSet object.
popup - Variable in class javax.swing.plaf.basic.BasicComboBoxUI
Popup - Class in javax.swing
Popups are used to display a Component to the user, typically on top of all the other Components in a particular containment hierarchy.
Popup(Component, Component, int, int) - Constructor for class javax.swing.Popup
Creates a Popup for the Component owner containing the Component contents.
Popup() - Constructor for class javax.swing.Popup
Creates a Popup.
POPUP_LAYER - Static variable in class javax.swing.JLayeredPane
Convenience object defining the Popup layer.
POPUP_MENU - Static variable in class javax.accessibility.AccessibleRole
A temporary window that is usually used to offer the user a list of choices, and then hides when the user selects one of those choices.
POPUP_MENU - Static variable in class javax.swing.plaf.synth.Region
PopupMenu region.
POPUP_MENU_SEPARATOR - Static variable in class javax.swing.plaf.synth.Region
PopupMenuSeparator region.
PopupFactory - Class in javax.swing
PopupFactory, as the name implies, is used to obtain instances of Popups.
PopupFactory() - Constructor for class javax.swing.PopupFactory
popupKeyListener - Variable in class javax.swing.plaf.basic.BasicComboBoxUI
popupListener - Variable in class javax.swing.JMenu
The window-closing listener for the popup.
PopupMenu - Class in java.awt
A class that implements a menu which can be dynamically popped up at a specified position within a component.
PopupMenu() - Constructor for class java.awt.PopupMenu
Creates a new popup menu with an empty name.
PopupMenu(String) - Constructor for class java.awt.PopupMenu
Creates a new popup menu with the specified name.
popupMenu - Variable in class javax.swing.plaf.basic.BasicPopupMenuUI
PopupMenu.AccessibleAWTPopupMenu - Class in java.awt
Inner class of PopupMenu used to provide default support for accessibility.
PopupMenu.AccessibleAWTPopupMenu() - Constructor for class java.awt.PopupMenu.AccessibleAWTPopupMenu
popupMenuCanceled(PopupMenuEvent) - Method in interface javax.swing.event.PopupMenuListener
This method is called when the popup menu is canceled
PopupMenuEvent - Class in javax.swing.event
PopupMenuEvent only contains the source of the event which is the JPoupMenu sending the event
PopupMenuEvent(Object) - Constructor for class javax.swing.event.PopupMenuEvent
Constructs a PopupMenuEvent object.
PopupMenuListener - Interface in javax.swing.event
A popup menu listener
PopupMenuUI - Class in javax.swing.plaf
Pluggable look and feel interface for JPopupMenu.
PopupMenuUI() - Constructor for class javax.swing.plaf.PopupMenuUI
popupMenuWillBecomeInvisible(PopupMenuEvent) - Method in interface javax.swing.event.PopupMenuListener
This method is called before the popup menu becomes invisible Note that a JPopupMenu can become invisible any time
popupMenuWillBecomeVisible(PopupMenuEvent) - Method in interface javax.swing.event.PopupMenuListener
This method is called before the popup menu becomes visible
popupMouseListener - Variable in class javax.swing.plaf.basic.BasicComboBoxUI
popupMouseMotionListener - Variable in class javax.swing.plaf.basic.BasicComboBoxUI
port - Variable in class java.net.SocketImpl
The port number on the remote host to which this socket is connected.
Port - Interface in javax.sound.sampled
Ports are simple lines for input or output of audio to or from audio devices.
Port.Info - Class in javax.sound.sampled
The Port.Info class extends Line.Info with additional information specific to ports, including the port's name and whether it is a source or a target for its mixer.
Port.Info(Class<?>, String, boolean) - Constructor for class javax.sound.sampled.Port.Info
Constructs a port's info object from the information given.
PortableRemoteObject - Class in javax.rmi
Server implementation objects may either inherit from javax.rmi.PortableRemoteObject or they may implement a remote interface and then use the exportObject method to register themselves as a server object.
PortableRemoteObject() - Constructor for class javax.rmi.PortableRemoteObject
Initializes the object by calling exportObject(this).
PortableRemoteObjectDelegate - Interface in javax.rmi.CORBA
Supports delegation for method implementations in PortableRemoteObject.
PortInfo - Interface in javax.xml.ws.handler
The PortInfo interface is used by a HandlerResolver to query information about the port it is being asked to create a handler chain for.
PORTRAIT - Static variable in class java.awt.PageAttributes.OrientationRequestedType
The OrientationRequestedType instance to use for specifying a portrait orientation.
PORTRAIT - Static variable in class java.awt.print.PageFormat
The origin is at the top left of the paper with x running to the right and y running down the paper.
PORTRAIT - Static variable in class javax.print.attribute.standard.OrientationRequested
The content will be imaged across the short edge of the medium.
PortUnreachableException - Exception in java.net
Signals that an ICMP Port Unreachable message has been received on a connected datagram.
PortUnreachableException(String) - Constructor for exception java.net.PortUnreachableException
Constructs a new PortUnreachableException with a detail message.
PortUnreachableException() - Constructor for exception java.net.PortUnreachableException
Construct a new PortUnreachableException with no detailed message.
pos - Variable in class java.io.BufferedInputStream
The current position in the buffer.
pos - Variable in class java.io.ByteArrayInputStream
The index of the next character to read from the input stream buffer.
pos - Variable in class java.io.CharArrayReader
The current buffer position.
pos - Variable in class java.io.PushbackInputStream
The position within the pushback buffer from which the next byte will be read.
pos - Variable in class java.io.StringBufferInputStream
Deprecated.
The index of the next character to read from the input stream buffer.
position() - Method in class java.nio.Buffer
Returns this buffer's position.
position(int) - Method in class java.nio.Buffer
Sets this buffer's position.
position() - Method in class java.nio.channels.FileChannel
Returns this channel's file position.
position(long) - Method in class java.nio.channels.FileChannel
Sets this channel's file position.
position() - Method in class java.nio.channels.FileLock
Returns the position within the file of the first byte of the locked region.
position() - Method in interface java.nio.channels.SeekableByteChannel
Returns this channel's position.
position(long) - Method in interface java.nio.channels.SeekableByteChannel
Sets this channel's position.
position(byte[], long) - Method in interface java.sql.Blob
Retrieves the byte position at which the specified byte array pattern begins within the BLOB value that this Blob object represents.
position(Blob, long) - Method in interface java.sql.Blob
Retrieves the byte position in the BLOB value designated by this Blob object at which pattern begins.
position(String, long) - Method in interface java.sql.Clob
Retrieves the character position at which the specified substring searchstr appears in the SQL CLOB value represented by this Clob object.
position(Clob, long) - Method in interface java.sql.Clob
Retrieves the character position at which the specified Clob object searchstr appears in this Clob object.
position(byte[], long) - Method in class javax.sql.rowset.serial.SerialBlob
Returns the position in this SerialBlob object where the given pattern of bytes begins, starting the search at the specified position.
position(Blob, long) - Method in class javax.sql.rowset.serial.SerialBlob
Returns the position in this SerialBlob object where the given Blob object begins, starting the search at the specified position.
position(String, long) - Method in class javax.sql.rowset.serial.SerialClob
Returns the position in this SerialClob object where the given String object begins, starting the search at the specified position.
position(Clob, long) - Method in class javax.sql.rowset.serial.SerialClob
Returns the position in this SerialClob object where the given Clob signature begins, starting the search at the specified position.
Position - Interface in javax.swing.text
Represents a location within a document.
Position.Bias - Class in javax.swing.text
A typesafe enumeration to indicate bias to a position in the model.
positionCaret(MouseEvent) - Method in class javax.swing.text.DefaultCaret
Tries to set the position of the caret from the coordinates of a mouse event, using viewToModel().
positionForMouseEvent(MouseEvent) - Method in class javax.swing.plaf.basic.BasicSplitPaneDivider.DragController
Returns the new position to put the divider at based on the passed in MouseEvent.
positionForMouseEvent(MouseEvent) - Method in class javax.swing.plaf.basic.BasicSplitPaneDivider.VerticalDragController
Returns the new position to put the divider at based on the passed in MouseEvent.
positionToElement(int) - Method in class javax.swing.text.AbstractDocument.BranchElement
Gets the child element that contains the given model position.
POSITIVE_INFINITY - Static variable in class java.lang.Double
A constant holding the positive infinity of type double.
POSITIVE_INFINITY - Static variable in class java.lang.Float
A constant holding the positive infinity of type float.
POSITIVE_SCROLL - Static variable in class javax.swing.plaf.basic.BasicSliderUI
PosixFileAttributes - Interface in java.nio.file.attribute
File attributes associated with files on file systems used by operating systems that implement the Portable Operating System Interface (POSIX) family of standards.
PosixFileAttributeView - Interface in java.nio.file.attribute
A file attribute view that provides a view of the file attributes commonly associated with files on file systems used by operating systems that implement the Portable Operating System Interface (POSIX) family of standards.
PosixFilePermission - Enum in java.nio.file.attribute
Defines the bits for use with the permissions attribute.
PosixFilePermissions - Class in java.nio.file.attribute
This class consists exclusively of static methods that operate on sets of PosixFilePermission objects.
post_init(ORBInitInfo) - Method in interface org.omg.PortableInterceptor.ORBInitializerOperations
Called during ORB initialization.
postActionEvent() - Method in class javax.swing.JTextField
Processes action events occurring on this textfield by dispatching them to any registered ActionListener objects.
postClosingEvent(JInternalFrame) - Method in class javax.swing.plaf.basic.BasicInternalFrameTitlePane
Post a WINDOW_CLOSING-like event to the frame, so that it can be treated like a regular Frame.
PostConstruct - Annotation Type in javax.annotation
The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization.
postDeregister() - Method in class javax.management.loading.MLet
Allows the m-let to perform any operations needed after having been unregistered in the MBean server.
postDeregister() - Method in interface javax.management.MBeanRegistration
Allows the MBean to perform any operations needed after having been unregistered in the MBean server.
postDeregister() - Method in class javax.management.modelmbean.RequiredModelMBean
Allows the MBean to perform any operations needed after having been unregistered in the MBean server.
postDeregister() - Method in class javax.management.monitor.Monitor
Allows the monitor MBean to perform any operations needed after having been unregistered by the MBean server.
postDeregister() - Method in class javax.management.relation.RelationService
postDeregister() - Method in class javax.management.relation.RelationSupport
postDeregister() - Method in class javax.management.remote.JMXConnectorServer
postDeregister() - Method in class javax.management.StandardMBean
Allows the MBean to perform any operations needed after having been unregistered in the MBean server.
postDeregister() - Method in class javax.management.timer.Timer
Allows the timer MBean to perform any operations needed after having been unregistered by the MBean server.
postEdit(UndoableEdit) - Method in class javax.swing.undo.UndoableEditSupport
DEADLOCK WARNING: Calling this method may call undoableEditHappened in all listeners.
postEvent(Event) - Method in class java.awt.Component
Deprecated.
As of JDK version 1.1, replaced by dispatchEvent(AWTEvent).
postEvent(AWTEvent) - Method in class java.awt.EventQueue
Posts a 1.1-style event to the EventQueue.
postEvent(Event) - Method in class java.awt.MenuComponent
Deprecated.
As of JDK version 1.1, replaced by dispatchEvent.
postEvent(Event) - Method in interface java.awt.MenuContainer
Deprecated.
As of JDK version 1.1 replaced by dispatchEvent(AWTEvent).
postEvent(Event) - Method in class java.awt.Window
Deprecated.
As of JDK version 1.1 replaced by dispatchEvent(AWTEvent).
postinvoke(byte[], POA, String, Object, Servant) - Method in class org.omg.PortableServer._ServantLocatorStub
This operation is invoked whenener a servant completes a request.
postinvoke(byte[], POA, String, Object, Servant) - Method in interface org.omg.PortableServer.ServantLocatorOperations
This operation is invoked whenener a servant completes a request.
postorderEnumeration() - Method in class javax.swing.tree.DefaultMutableTreeNode
Creates and returns an enumeration that traverses the subtree rooted at this node in postorder.
postProcessKeyEvent(KeyEvent) - Method in class java.awt.DefaultKeyboardFocusManager
This method will be called by dispatchKeyEvent.
postProcessKeyEvent(KeyEvent) - Method in class java.awt.KeyboardFocusManager
This method will be called by dispatchKeyEvent.
postProcessKeyEvent(KeyEvent) - Method in interface java.awt.KeyEventPostProcessor
This method is called by the current KeyboardFocusManager, requesting that this KeyEventPostProcessor perform any necessary post-processing which should be part of the KeyEvent's final resolution.
postRegister(Boolean) - Method in class javax.management.loading.MLet
Allows the m-let to perform any operations needed after having been registered in the MBean server or after the registration has failed.
postRegister(Boolean) - Method in interface javax.management.MBeanRegistration
Allows the MBean to perform any operations needed after having been registered in the MBean server or after the registration has failed.
postRegister(Boolean) - Method in class javax.management.modelmbean.RequiredModelMBean
Allows the MBean to perform any operations needed after having been registered in the MBean server or after the registration has failed.
postRegister(Boolean) - Method in class javax.management.monitor.Monitor
Allows the monitor MBean to perform any operations needed after having been registered in the MBean server or after the registration has failed.
postRegister(Boolean) - Method in class javax.management.relation.RelationService
postRegister(Boolean) - Method in class javax.management.relation.RelationSupport
postRegister(Boolean) - Method in class javax.management.remote.JMXConnectorServer
postRegister(Boolean) - Method in class javax.management.StandardMBean
Allows the MBean to perform any operations needed after having been registered in the MBean server or after the registration has failed.
postRegister(Boolean) - Method in class javax.management.timer.Timer
Allows the timer MBean to perform any operations needed after having been registered in the MBean server or after the registration has failed.
postRemoveUpdate(AbstractDocument.DefaultDocumentEvent) - Method in class javax.swing.text.AbstractDocument
Updates any document structure as a result of text removal.
POSTSCRIPT - Static variable in class javax.print.DocFlavor.BYTE_ARRAY
Doc flavor with MIME type = "application/postscript", print data representation class name = "[B" (byte array).
POSTSCRIPT - Static variable in class javax.print.DocFlavor.INPUT_STREAM
Doc flavor with MIME type = "application/postscript", print data representation class name = "java.io.InputStream" (byte stream).
POSTSCRIPT - Static variable in class javax.print.DocFlavor.URL
Doc flavor with MIME type = "application/postscript", print data representation class name = "java.net.URL".
postState - Variable in class javax.swing.undo.StateEdit
The state information after the edit
POSTURE - Static variable in class java.awt.font.TextAttribute
Attribute key for the posture of a font.
POSTURE_OBLIQUE - Static variable in class java.awt.font.TextAttribute
The standard italic posture.
POSTURE_REGULAR - Static variable in class java.awt.font.TextAttribute
The standard posture, upright.
postVisitDirectory(T, IOException) - Method in interface java.nio.file.FileVisitor
Invoked for a directory after entries in the directory, and all of their descendants, have been visited.
postVisitDirectory(T, IOException) - Method in class java.nio.file.SimpleFileVisitor
Invoked for a directory after entries in the directory, and all of their descendants, have been visited.
pow(double, double) - Static method in class java.lang.Math
Returns the value of the first argument raised to the power of the second argument.
pow(double, double) - Static method in class java.lang.StrictMath
Returns the value of the first argument raised to the power of the second argument.
pow(int) - Method in class java.math.BigDecimal
Returns a BigDecimal whose value is (thisn), The power is computed exactly, to unlimited precision.
pow(int, MathContext) - Method in class java.math.BigDecimal
Returns a BigDecimal whose value is (thisn).
pow(int) - Method in class java.math.BigInteger
Returns a BigInteger whose value is (thisexponent).
PPQ - Static variable in class javax.sound.midi.Sequence
The tempo-based timing type, for which the resolution is expressed in pulses (ticks) per quarter note.
PRC - Static variable in class java.util.Locale
Useful constant for country.
PRE - Static variable in class javax.swing.text.html.HTML.Tag
pre_init(ORBInitInfo) - Method in interface org.omg.PortableInterceptor.ORBInitializerOperations
Called during ORB initialization.
preceding(int) - Method in class java.text.BreakIterator
Returns the last boundary preceding the specified character offset.
precision() - Method in class java.math.BigDecimal
Returns the precision of this BigDecimal.
preConcatenate(AffineTransform) - Method in class java.awt.geom.AffineTransform
Concatenates an AffineTransform Tx to this AffineTransform Cx in a less commonly used way such that Tx modifies the coordinate transformation relative to the absolute pixel space rather than relative to the existing user space.
preConcatenateTransform(AffineTransform) - Method in class java.awt.image.renderable.RenderContext
Modifies the current user-to-device transform by prepending another transform.
preConcetenateTransform(AffineTransform) - Method in class java.awt.image.renderable.RenderContext
Deprecated.
replaced by preConcatenateTransform(AffineTransform).
preContent(char[]) - Method in class javax.swing.text.html.HTMLDocument.HTMLReader
Adds the given content that was encountered in a PRE element.
predefined - Static variable in class java.awt.Cursor
Deprecated.
As of JDK version 1.7, the Cursor.getPredefinedCursor(int) method should be used instead.
preDeregister() - Method in class javax.management.loading.MLet
Allows the m-let to perform any operations it needs before being unregistered by the MBean server.
preDeregister() - Method in interface javax.management.MBeanRegistration
Allows the MBean to perform any operations it needs before being unregistered by the MBean server.
preDeregister() - Method in class javax.management.modelmbean.RequiredModelMBean
Allows the MBean to perform any operations it needs before being unregistered by the MBean server.
preDeregister() - Method in class javax.management.monitor.Monitor
Allows the monitor MBean to perform any operations it needs before being unregistered by the MBean server.
preDeregister() - Method in class javax.management.relation.RelationService
preDeregister() - Method in class javax.management.relation.RelationSupport
preDeregister() - Method in class javax.management.remote.JMXConnectorServer
Called by an MBean server when this connector server is unregistered from that MBean server.
preDeregister() - Method in class javax.management.StandardMBean
Allows the MBean to perform any operations it needs before being unregistered by the MBean server.
preDeregister() - Method in class javax.management.timer.Timer
Allows the timer MBean to perform any operations it needs before being unregistered by the MBean server.
PreDestroy - Annotation Type in javax.annotation
The PreDestroy annotation is used on methods as a callback notification to signal that the instance is in the process of being removed by the container.
Predicate - Interface in javax.sql.rowset
The standard interface that provides the framework for all FilteredRowSet objects to describe their filters.
preferenceChange(PreferenceChangeEvent) - Method in interface java.util.prefs.PreferenceChangeListener
This method gets called when a preference is added, removed or when its value is changed.
preferenceChanged(boolean, boolean) - Method in class javax.swing.text.AsyncBoxView.ChildState
Mark preferences changed for this child.
preferenceChanged(View, boolean, boolean) - Method in class javax.swing.text.AsyncBoxView
Child views can call this on the parent to indicate that the preference has changed and should be reconsidered for layout.
preferenceChanged(View, boolean, boolean) - Method in class javax.swing.text.BoxView
This is called by a child to indicate its preferred span has changed.
preferenceChanged(View, boolean, boolean) - Method in class javax.swing.text.View
Child views can call this on the parent to indicate that the preference has changed and should be reconsidered for layout.
PreferenceChangeEvent - Class in java.util.prefs
An event emitted by a Preferences node to indicate that a preference has been added, removed or has had its value changed.
PreferenceChangeEvent(Preferences, String, String) - Constructor for class java.util.prefs.PreferenceChangeEvent
Constructs a new PreferenceChangeEvent instance.
PreferenceChangeListener - Interface in java.util.prefs
A listener for receiving preference change events.
Preferences - Class in java.util.prefs
A node in a hierarchical collection of preference data.
Preferences() - Constructor for class java.util.prefs.Preferences
Sole constructor.
PreferencesFactory - Interface in java.util.prefs
A factory object that generates Preferences objects.
preferLocaleFonts() - Method in class java.awt.GraphicsEnvironment
Indicates a preference for locale-specific fonts in the mapping of logical fonts to physical fonts.
preferProportionalFonts() - Method in class java.awt.GraphicsEnvironment
Indicates a preference for proportional over non-proportional (e.g.
PREFERRED - Static variable in class java.awt.GraphicsConfigTemplate
Value used for "Enum" (Integer) type.
preferred - Variable in class javax.swing.SizeRequirements
The preferred (natural) size.
PREFERRED_SIZE - Static variable in class javax.swing.GroupLayout
Indicates the preferred size from the component or gap should be used for a particular range value.
preferredLayoutSize(Container) - Method in class java.awt.BorderLayout
Determines the preferred size of the target container using this layout manager, based on the components in the container.
preferredLayoutSize(Container) - Method in class java.awt.CardLayout
Determines the preferred size of the container argument using this card layout.
preferredLayoutSize(Container) - Method in class java.awt.FlowLayout
Returns the preferred dimensions for this layout given the visible components in the specified target container.
preferredLayoutSize(Container) - Method in class java.awt.GridBagLayout
Determines the preferred size of the parent container using this grid bag layout.
preferredLayoutSize(Container) - Method in class java.awt.GridLayout
Determines the preferred size of the container argument using this grid layout.
preferredLayoutSize(Container) - Method in interface java.awt.LayoutManager
Calculates the preferred size dimensions for the specified container, given the components it contains.
preferredLayoutSize(Container) - Method in class javax.swing.BoxLayout
Returns the preferred dimensions for this layout, given the components in the specified target container.
preferredLayoutSize(Container) - Method in class javax.swing.GroupLayout
Returns the preferred size for the specified container.
preferredLayoutSize(Container) - Method in class javax.swing.JRootPane.RootLayout
Returns the amount of space the layout would like to have.
preferredLayoutSize(Container) - Method in class javax.swing.JSpinner.DefaultEditor
Returns the preferred size of first (and only) child plus the size of the parents insets.
preferredLayoutSize(Container) - Method in class javax.swing.OverlayLayout
Returns the preferred dimensions for this layout given the components in the specified target container.
preferredLayoutSize(Container) - Method in class javax.swing.plaf.basic.BasicComboBoxUI.ComboBoxLayoutManager
preferredLayoutSize(Container) - Method in class javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout
preferredLayoutSize(Container) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI.InternalFrameLayout
preferredLayoutSize(Container) - Method in class javax.swing.plaf.basic.BasicOptionPaneUI.ButtonAreaLayout
preferredLayoutSize(Container) - Method in class javax.swing.plaf.basic.BasicScrollBarUI
preferredLayoutSize(Container) - Method in class javax.swing.plaf.basic.BasicSplitPaneDivider.DividerLayout
preferredLayoutSize(Container) - Method in class javax.swing.plaf.basic.BasicSplitPaneUI.BasicHorizontalLayoutManager
Returns the preferred size needed to contain the children.
preferredLayoutSize(Container) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI.TabbedPaneLayout
preferredLayoutSize(Container) - Method in class javax.swing.plaf.basic.DefaultMenuLayout
preferredLayoutSize(Container) - Method in class javax.swing.ScrollPaneLayout
The preferred size of a ScrollPane is the size of the insets, plus the preferred size of the viewport, plus the preferred size of the visible headers, plus the preferred size of the scrollbars that will appear given the current view and the current scrollbar displayPolicies.
preferredLayoutSize(Container) - Method in class javax.swing.SpringLayout
preferredLayoutSize(Container) - Method in class javax.swing.ViewportLayout
Returns the preferred dimensions for this layout given the components in the specified target container.
preferredMinSize - Variable in class javax.swing.plaf.basic.BasicTreeUI
Minimum preferred size.
preferredSize() - Method in class java.awt.Component
Deprecated.
As of JDK version 1.1, replaced by getPreferredSize().
preferredSize() - Method in class java.awt.Container
Deprecated.
As of JDK version 1.1, replaced by getPreferredSize().
PREFERREDSIZE - Static variable in class java.awt.GridBagLayout
The preferred grid size that can be laid out by the grid bag layout.
preferredSize(int) - Method in class java.awt.List
Deprecated.
As of JDK version 1.1, replaced by getPreferredSize(int).
preferredSize() - Method in class java.awt.List
Deprecated.
As of JDK version 1.1, replaced by getPreferredSize().
preferredSize(int, int) - Method in class java.awt.TextArea
Deprecated.
As of JDK version 1.1, replaced by getPreferredSize(int, int).
preferredSize() - Method in class java.awt.TextArea
Deprecated.
As of JDK version 1.1, replaced by getPreferredSize().
preferredSize(int) - Method in class java.awt.TextField
Deprecated.
As of JDK version 1.1, replaced by getPreferredSize(int).
preferredSize() - Method in class java.awt.TextField
Deprecated.
As of JDK version 1.1, replaced by getPreferredSize().
preferredSize - Variable in class javax.swing.plaf.basic.BasicTreeUI
Size needed to completely display all the nodes.
preferredTabAreaHeight(int, int) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI.TabbedPaneLayout
preferredTabAreaWidth(int, int) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI.TabbedPaneLayout
preferredTileSizes - Variable in class javax.imageio.ImageWriteParam
An array of preferred tile size range pairs.
preferredViewportSize - Variable in class javax.swing.JTable
Used by the Scrollable interface to determine the initial visible area.
preinvoke(byte[], POA, String, CookieHolder) - Method in class org.omg.PortableServer._ServantLocatorStub
This operations is used to get a servant that will be used to process the request that caused preinvoke to be called.
preinvoke(byte[], POA, String, CookieHolder) - Method in interface org.omg.PortableServer.ServantLocatorOperations
This operations is used to get a servant that will be used to process the request that caused preinvoke to be called.
preorderEnumeration() - Method in class javax.swing.tree.DefaultMutableTreeNode
Creates and returns an enumeration that traverses the subtree rooted at this node in preorder.
prepare(Xid) - Method in interface javax.transaction.xa.XAResource
Ask the resource manager to prepare for a transaction commit of the transaction specified in xid.
prepareCall(String) - Method in interface java.sql.Connection
Creates a CallableStatement object for calling database stored procedures.
prepareCall(String, int, int) - Method in interface java.sql.Connection
Creates a CallableStatement object that will generate ResultSet objects with the given type and concurrency.
prepareCall(String, int, int, int) - Method in interface java.sql.Connection
Creates a CallableStatement object that will generate ResultSet objects with the given type and concurrency.
PreparedStatement - Interface in java.sql
An object that represents a precompiled SQL statement.
prepareEditor(TableCellEditor, int, int) - Method in class javax.swing.JTable
Prepares the editor by querying the data model for the value and selection state of the cell at row, column.
prepareForDragging() - Method in class javax.swing.plaf.basic.BasicSplitPaneDivider
Message to prepare for dragging.
prepareForEditing() - Method in class javax.swing.tree.DefaultTreeCellEditor
Invoked just before editing is to start.
prepareForUIInstall() - Method in class javax.swing.plaf.basic.BasicTreeUI
Invoked after the tree instance variable has been set, but before any defaults/listeners have been installed.
prepareForUIUninstall() - Method in class javax.swing.plaf.basic.BasicTreeUI
prepareImage(Image, ImageObserver) - Method in class java.awt.Component
Prepares an image for rendering on this component.
prepareImage(Image, int, int, ImageObserver) - Method in class java.awt.Component
Prepares an image for rendering on this component at the specified width and height.
prepareImage(Image, int, int, ImageObserver) - Method in class java.awt.Toolkit
Prepares an image for rendering.
prepareInsertEmpty(int, ImageTypeSpecifier, int, int, IIOMetadata, List<? extends BufferedImage>, ImageWriteParam) - Method in class javax.imageio.ImageWriter
Begins the insertion of a new image with undefined pixel values into an existing image stream.
prepareRenderer(TableCellRenderer, int, int) - Method in class javax.swing.JTable
Prepares the renderer by querying the data model for the value and selection state of the cell at row, column.
prepareReplacePixels(int, Rectangle) - Method in class javax.imageio.ImageWriter
Prepares the writer to handle a series of calls to the replacePixels methods.
prepareStatement(String) - Method in interface java.sql.Connection
Creates a PreparedStatement object for sending parameterized SQL statements to the database.
prepareStatement(String, int, int) - Method in interface java.sql.Connection
Creates a PreparedStatement object that will generate ResultSet objects with the given type and concurrency.
prepareStatement(String, int, int, int) - Method in interface java.sql.Connection
Creates a PreparedStatement object that will generate ResultSet objects with the given type, concurrency, and holdability.
prepareStatement(String, int) - Method in interface java.sql.Connection
Creates a default PreparedStatement object that has the capability to retrieve auto-generated keys.
prepareStatement(String, int[]) - Method in interface java.sql.Connection
Creates a default PreparedStatement object capable of returning the auto-generated keys designated by the given array.
prepareStatement(String, String[]) - Method in interface java.sql.Connection
Creates a default PreparedStatement object capable of returning the auto-generated keys designated by the given array.
prepareWriteEmpty(IIOMetadata, ImageTypeSpecifier, int, int, IIOMetadata, List<? extends BufferedImage>, ImageWriteParam) - Method in class javax.imageio.ImageWriter
Begins the writing of a complete image stream, consisting of a single image with undefined pixel values and associated metadata and thumbnails, to the output.
prepareWriteSequence(IIOMetadata) - Method in class javax.imageio.ImageWriter
Prepares a stream to accept a series of subsequent writeToSequence calls, using the provided stream metadata object.
preRegister(MBeanServer, ObjectName) - Method in class javax.management.loading.MLet
Allows the m-let to perform any operations it needs before being registered in the MBean server.
preRegister(MBeanServer, ObjectName) - Method in interface javax.management.MBeanRegistration
Allows the MBean to perform any operations it needs before being registered in the MBean Server.
preRegister(MBeanServer, ObjectName) - Method in class javax.management.modelmbean.RequiredModelMBean
Allows the MBean to perform any operations it needs before being registered in the MBean server.
preRegister(MBeanServer, ObjectName) - Method in class javax.management.monitor.Monitor
Allows the monitor MBean to perform any operations it needs before being registered in the MBean server.
preRegister(MBeanServer, ObjectName) - Method in class javax.management.relation.RelationService
preRegister(MBeanServer, ObjectName) - Method in class javax.management.relation.RelationSupport
preRegister(MBeanServer, ObjectName) - Method in class javax.management.remote.JMXConnectorServer
Called by an MBean server when this connector server is registered in that MBean server.
preRegister(MBeanServer, ObjectName) - Method in class javax.management.StandardMBean
Allows the MBean to perform any operations it needs before being registered in the MBean server.
preRegister(MBeanServer, ObjectName) - Method in class javax.management.timer.Timer
Allows the timer MBean to perform any operations it needs before being registered in the MBean server.
PresentationDirection - Class in javax.print.attribute.standard
Class PresentationDirection is a printing attribute class, an enumeration, that is used in conjunction with the NumberUp attribute to indicate the layout of multiple print-stream pages to impose upon a single side of an instance of a selected medium.
PRESSED - Static variable in class javax.accessibility.AccessibleState
Indicates this object is currently pressed.
PRESSED - Static variable in class javax.swing.DefaultButtonModel
Identifies the "pressed" bit in the bitmask, which indicates that the button is pressed.
PRESSED - Static variable in interface javax.swing.plaf.synth.SynthConstants
Primary state indicating the region is in a pressed state.
PRESSED_ICON_CHANGED_PROPERTY - Static variable in class javax.swing.AbstractButton
Identifies a change to the icon used when the button has been pressed.
prestartAllCoreThreads() - Method in class java.util.concurrent.ThreadPoolExecutor
Starts all core threads, causing them to idly wait for work.
prestartCoreThread() - Method in class java.util.concurrent.ThreadPoolExecutor
Starts a core thread, causing it to idly wait for work.
preState - Variable in class javax.swing.undo.StateEdit
The state information prior to the edit
preventDefault() - Method in interface org.w3c.dom.events.Event
If an event is cancelable, the preventDefault method is used to signify that the event is to be canceled, meaning any default action normally taken by the implementation as a result of the event will not occur.
PREVIEW_PANEL_PROPERTY - Static variable in class javax.swing.JColorChooser
The preview panel property name.
previewListener - Variable in class javax.swing.plaf.basic.BasicColorChooserUI
previous(Container) - Method in class java.awt.CardLayout
Flips to the previous card of the specified container.
previous() - Method in interface java.sql.ResultSet
Moves the cursor to the previous row in this ResultSet object.
previous() - Method in class java.text.BreakIterator
Returns the boundary preceding the current boundary.
previous() - Method in interface java.text.CharacterIterator
Decrements the iterator's index by one and returns the character at the new index.
previous() - Method in class java.text.CollationElementIterator
Get the previous collation element in the string.
previous() - Method in class java.text.StringCharacterIterator
Implements CharacterIterator.previous() for String.
previous() - Method in interface java.util.ListIterator
Returns the previous element in the list and moves the cursor position backwards.
PREVIOUS - Static variable in interface javax.swing.SwingConstants
Identifies the previous direction in a sequence.
previous() - Method in class javax.swing.text.ElementIterator
Fetches the previous Element.
previous() - Method in class javax.swing.text.Segment
Decrements the iterator's index by one and returns the character at the new index.
previousClearBit(int) - Method in class java.util.BitSet
Returns the index of the nearest bit that is set to false that occurs on or before the specified starting index.
previousConflict() - Method in interface javax.sql.rowset.spi.SyncResolver
Moves the cursor up from its current position to the previous conflict row in this SyncResolver object.
previousDouble(double) - Static method in class java.text.ChoiceFormat
Finds the greatest double less than d.
previousIndex() - Method in interface java.util.ListIterator
Returns the index of the element that would be returned by a subsequent call to ListIterator.previous().
previousPage() - Method in interface javax.sql.rowset.CachedRowSet
Decrements the current page of the CachedRowSet.
previousSetBit(int) - Method in class java.util.BitSet
Returns the index of the nearest bit that is set to true that occurs on or before the specified starting index.
previousWordAction - Static variable in class javax.swing.text.DefaultEditorKit
Name of the Action for moving the caret to the beginning of the previous word.
preVisitDirectory(T, BasicFileAttributes) - Method in interface java.nio.file.FileVisitor
Invoked for a directory before entries in the directory are visited.
preVisitDirectory(T, BasicFileAttributes) - Method in class java.nio.file.SimpleFileVisitor
Invoked for a directory before entries in the directory are visited.
PRIMARY - Static variable in class java.text.Collator
Collator strength value.
primaryOrder(int) - Static method in class java.text.CollationElementIterator
Return the primary component of a collation element.
PrimitiveType - Interface in javax.lang.model.type
Represents a primitive type.
principal() - Method in class java.nio.file.attribute.AclEntry
Returns the principal component.
Principal - Interface in java.security
This interface represents the abstract notion of a principal, which can be used to represent any entity, such as an individual, a corporation, and a login id.
Principal - Class in org.omg.CORBA
Deprecated.
Deprecated by CORBA 2.2.
Principal() - Constructor for class org.omg.CORBA.Principal
Deprecated.
PrincipalHolder - Class in org.omg.CORBA
Deprecated.
Deprecated by CORBA 2.2.
PrincipalHolder() - Constructor for class org.omg.CORBA.PrincipalHolder
Deprecated.
Constructs a new PrincipalHolder object with its value field initialized to null.
PrincipalHolder(Principal) - Constructor for class org.omg.CORBA.PrincipalHolder
Deprecated.
Constructs a new PrincipalHolder object with its value field initialized to the given Principal object.
print(Graphics) - Method in class java.awt.Component
Prints this component.
print(Graphics) - Method in class java.awt.Container
Prints the container.
print(File) - Method in class java.awt.Desktop
Prints a file with the native desktop printing facility, using the associated application's print command.
print(Graphics, PageFormat, int) - Method in interface java.awt.print.Printable
Prints the page at the specified index into the specified Graphics context in the specified format.
print() - Method in class java.awt.print.PrinterJob
Prints a set of pages.
print(PrintRequestAttributeSet) - Method in class java.awt.print.PrinterJob
Prints a set of pages using the settings in the attribute set.
print(boolean) - Method in class java.io.PrintStream
Prints a boolean value.
print(char) - Method in class java.io.PrintStream
Prints a character.
print(int) - Method in class java.io.PrintStream
Prints an integer.
print(long) - Method in class java.io.PrintStream
Prints a long integer.
print(float) - Method in class java.io.PrintStream
Prints a floating-point number.
print(double) - Method in class java.io.PrintStream
Prints a double-precision floating-point number.
print(char[]) - Method in class java.io.PrintStream
Prints an array of characters.
print(String) - Method in class java.io.PrintStream
Prints a string.
print(Object) - Method in class java.io.PrintStream
Prints an object.
print(boolean) - Method in class java.io.PrintWriter
Prints a boolean value.
print(char) - Method in class java.io.PrintWriter
Prints a character.
print(int) - Method in class java.io.PrintWriter
Prints an integer.
print(long) - Method in class java.io.PrintWriter
Prints a long integer.
print(float) - Method in class java.io.PrintWriter
Prints a floating-point number.
print(double) - Method in class java.io.PrintWriter
Prints a double-precision floating-point number.
print(char[]) - Method in class java.io.PrintWriter
Prints an array of characters.
print(String) - Method in class java.io.PrintWriter
Prints a string.
print(Object) - Method in class java.io.PrintWriter
Prints an object.
print(Doc, PrintRequestAttributeSet) - Method in interface javax.print.DocPrintJob
Prints a document with the specified job attributes.
print(MultiDoc, PrintRequestAttributeSet) - Method in interface javax.print.MultiDocPrintJob
Print a MultiDoc with the specified job attributes.
print(Graphics) - Method in class javax.swing.JComponent
Invoke this method to print the component to the specified Graphics.
print() - Method in class javax.swing.JTable
A convenience method that displays a printing dialog, and then prints this JTable in mode PrintMode.FIT_WIDTH, with no header or footer text.
print(JTable.PrintMode) - Method in class javax.swing.JTable
A convenience method that displays a printing dialog, and then prints this JTable in the given printing mode, with no header or footer text.
print(JTable.PrintMode, MessageFormat, MessageFormat) - Method in class javax.swing.JTable
A convenience method that displays a printing dialog, and then prints this JTable in the given printing mode, with the specified header and footer text.
print(JTable.PrintMode, MessageFormat, MessageFormat, boolean, PrintRequestAttributeSet, boolean) - Method in class javax.swing.JTable
Prints this table, as specified by the fully featured print method, with the default printer specified as the print service.
print(JTable.PrintMode, MessageFormat, MessageFormat, boolean, PrintRequestAttributeSet, boolean, PrintService) - Method in class javax.swing.JTable
Prints this JTable.
print() - Method in class javax.swing.text.JTextComponent
A convenience print method that displays a print dialog, and then prints this JTextComponent in interactive mode with no header or footer text.
print(MessageFormat, MessageFormat) - Method in class javax.swing.text.JTextComponent
A convenience print method that displays a print dialog, and then prints this JTextComponent in interactive mode with the specified header and footer text.
print(MessageFormat, MessageFormat, boolean, PrintService, PrintRequestAttributeSet, boolean) - Method in class javax.swing.text.JTextComponent
Prints the content of this JTextComponent.
PRINT_SCREEN - Static variable in class java.awt.Event
The Print Screen key, a non-ASCII action key.
PRINTABLE - Static variable in class java.awt.PageAttributes.OriginType
The OriginType instance to use for specifying a printable origin.
Printable - Interface in java.awt.print
The Printable interface is implemented by the print methods of the current page painter, which is called by the printing system to render a page.
PRINTABLE - Static variable in class javax.print.DocFlavor.SERVICE_FORMATTED
Service formatted print data doc flavor with print data representation class name = "java.awt.print.Printable" (printable object).
printAll(Graphics) - Method in class java.awt.Component
Prints this component and all of its subcomponents.
printAll(Graphics) - Method in class javax.swing.JComponent
Invoke this method to print the component.
printAnySimpleType(String) - Static method in class javax.xml.bind.DatatypeConverter
Converts a string value into a string.
printAnySimpleType(String) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts a string value into a string.
printBase64Binary(byte[]) - Static method in class javax.xml.bind.DatatypeConverter
Converts an array of bytes into a string.
printBase64Binary(byte[]) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts an array of bytes into a string.
printBoolean(boolean) - Static method in class javax.xml.bind.DatatypeConverter
Converts a boolean value into a string.
printBoolean(boolean) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts a boolean value into a string.
printBorder(Graphics) - Method in class javax.swing.JComponent
Prints the component's border.
printByte(byte) - Static method in class javax.xml.bind.DatatypeConverter
Converts a byte value into a string.
printByte(byte) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts a byte value into a string.
printChildren(Graphics) - Method in class javax.swing.JComponent
Prints this component's children.
printComponent(Graphics) - Method in class javax.swing.JComponent
This is invoked during a printing operation.
printComponents(Graphics) - Method in class java.awt.Container
Prints each of the components in this container.
printComponents(Graphics) - Method in class java.awt.ScrollPane
Prints the component in this scroll pane.
PrintConversionEvent - Interface in javax.xml.bind
This event indicates that a problem was encountered while converting data from the Java content tree into its lexical representation.
PrintConversionEventImpl - Class in javax.xml.bind.helpers
Default implementation of the PrintConversionEvent interface.
PrintConversionEventImpl(int, String, ValidationEventLocator) - Constructor for class javax.xml.bind.helpers.PrintConversionEventImpl
Create a new PrintConversionEventImpl.
PrintConversionEventImpl(int, String, ValidationEventLocator, Throwable) - Constructor for class javax.xml.bind.helpers.PrintConversionEventImpl
Create a new PrintConversionEventImpl.
printDataTransferCompleted(PrintJobEvent) - Method in class javax.print.event.PrintJobAdapter
Called to notify the client that data has been successfully transferred to the print service, and the client may free local resources allocated for that data.
printDataTransferCompleted(PrintJobEvent) - Method in interface javax.print.event.PrintJobListener
Called to notify the client that data has been successfully transferred to the print service, and the client may free local resources allocated for that data.
printDate(Calendar) - Static method in class javax.xml.bind.DatatypeConverter
Converts a Calendar value into a string.
printDate(Calendar) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts a Calendar value into a string.
printDateTime(Calendar) - Static method in class javax.xml.bind.DatatypeConverter
Converts a Calendar value into a string.
printDateTime(Calendar) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts a Calendar value into a string.
printDecimal(BigDecimal) - Static method in class javax.xml.bind.DatatypeConverter
Converts a BigDecimal value into a string.
printDecimal(BigDecimal) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts a BigDecimal value into a string.
printDialog() - Method in class java.awt.print.PrinterJob
Presents a dialog to the user for changing the properties of the print job.
printDialog(PrintRequestAttributeSet) - Method in class java.awt.print.PrinterJob
A convenience method which displays a cross-platform print dialog for all services which are capable of printing 2D graphics using the Pageable interface.
printDialog(GraphicsConfiguration, int, int, PrintService[], PrintService, DocFlavor, PrintRequestAttributeSet) - Static method in class javax.print.ServiceUI
Presents a dialog to the user for selecting a print service (printer).
printDouble(double) - Static method in class javax.xml.bind.DatatypeConverter
Converts a double value into a string.
printDouble(double) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts a double value into a string.
printElements(Writer, Element...) - Method in interface javax.lang.model.util.Elements
Prints a representation of the elements to the given writer in the specified order.
PRINTER - Static variable in class java.awt.JobAttributes.DestinationType
The DestinationType instance to use for specifying print to printer.
PRINTER_STOPPED - Static variable in class javax.print.attribute.standard.JobStateReason
The value of the printer's PrinterState attribute ia STOPPED.
PRINTER_STOPPED_PARTLY - Static variable in class javax.print.attribute.standard.JobStateReason
The value of the printer's PrinterStateReasons attribute contains a PrinterStateReason value of STOPPED_PARTLY.
PrinterAbortException - Exception in java.awt.print
The PrinterAbortException class is a subclass of PrinterException and is used to indicate that a user or application has terminated the print job while it was in the process of printing.
PrinterAbortException() - Constructor for exception java.awt.print.PrinterAbortException
Constructs a new PrinterAbortException with no detail message.
PrinterAbortException(String) - Constructor for exception java.awt.print.PrinterAbortException
Constructs a new PrinterAbortException with the specified detail message.
PrinterException - Exception in java.awt.print
The PrinterException class and its subclasses are used to indicate that an exceptional condition has occurred in the print system.
PrinterException() - Constructor for exception java.awt.print.PrinterException
Constructs a new PrinterException object without a detail message.
PrinterException(String) - Constructor for exception java.awt.print.PrinterException
Constructs a new PrinterException object with the specified detail message.
PrinterGraphics - Interface in java.awt.print
The PrinterGraphics interface is implemented by Graphics objects that are passed to Printable objects to render a page.
PrinterInfo - Class in javax.print.attribute.standard
Class PrinterInfo is a printing attribute class, a text attribute, that provides descriptive information about a printer.
PrinterInfo(String, Locale) - Constructor for class javax.print.attribute.standard.PrinterInfo
Constructs a new printer info attribute with the given information string and locale.
PrinterIOException - Exception in java.awt.print
The PrinterIOException class is a subclass of PrinterException and is used to indicate that an IO error of some sort has occurred while printing.
PrinterIOException(IOException) - Constructor for exception java.awt.print.PrinterIOException
Constructs a new PrinterIOException with the string representation of the specified IOException.
PrinterIsAcceptingJobs - Class in javax.print.attribute.standard
Class PrinterIsAcceptingJobs is a printing attribute class, an enumeration, that indicates whether the printer is currently able to accept jobs.
PrinterIsAcceptingJobs(int) - Constructor for class javax.print.attribute.standard.PrinterIsAcceptingJobs
Construct a new printer is accepting jobs enumeration value with the given integer value.
PrinterJob - Class in java.awt.print
The PrinterJob class is the principal class that controls printing.
PrinterJob() - Constructor for class java.awt.print.PrinterJob
A PrinterJob object should be created using the static getPrinterJob method.
PrinterLocation - Class in javax.print.attribute.standard
Class PrinterLocation is a printing attribute class, a text attribute, that identifies the location of the device.
PrinterLocation(String, Locale) - Constructor for class javax.print.attribute.standard.PrinterLocation
Constructs a new printer location attribute with the given location and locale.
PrinterMakeAndModel - Class in javax.print.attribute.standard
Class PrinterMakeAndModel is a printing attribute class, a text attribute, that the make and model of the printer.
PrinterMakeAndModel(String, Locale) - Constructor for class javax.print.attribute.standard.PrinterMakeAndModel
Constructs a new printer make and model attribute with the given make and model string and locale.
PrinterMessageFromOperator - Class in javax.print.attribute.standard
Class PrinterMessageFromOperator is a printing attribute class, a text attribute, that provides a message from an operator, system administrator, or "intelligent" process to indicate to the end user information about or status of the printer, such as why it is unavailable or when it is expected to be available.
PrinterMessageFromOperator(String, Locale) - Constructor for class javax.print.attribute.standard.PrinterMessageFromOperator
Constructs a new printer message from operator attribute with the given message and locale.
PrinterMoreInfo - Class in javax.print.attribute.standard
Class PrinterMoreInfo is a printing attribute class, a URI, that is used to obtain more information about this specific printer.
PrinterMoreInfo(URI) - Constructor for class javax.print.attribute.standard.PrinterMoreInfo
Constructs a new printer more info attribute with the specified URI.
PrinterMoreInfoManufacturer - Class in javax.print.attribute.standard
Class PrinterMoreInfoManufacturer is a printing attribute class, a URI, that is used to obtain more information about this type of device.
PrinterMoreInfoManufacturer(URI) - Constructor for class javax.print.attribute.standard.PrinterMoreInfoManufacturer
Constructs a new printer more info manufacturer attribute with the specified URI.
PrinterName - Class in javax.print.attribute.standard
Class PrinterName is a printing attribute class, a text attribute, that specifies the name of a printer.
PrinterName(String, Locale) - Constructor for class javax.print.attribute.standard.PrinterName
Constructs a new printer name attribute with the given name and locale.
PrinterResolution - Class in javax.print.attribute.standard
Class PrinterResolution is a printing attribute class that specifies an exact resolution supported by a printer or to be used for a print job.
PrinterResolution(int, int, int) - Constructor for class javax.print.attribute.standard.PrinterResolution
Construct a new printer resolution attribute from the given items.
PrinterState - Class in javax.print.attribute.standard
Class PrinterState is a printing attribute class, an enumeration, that identifies the current state of a printer.
PrinterState(int) - Constructor for class javax.print.attribute.standard.PrinterState
Construct a new printer state enumeration value with the given integer value.
PrinterStateReason - Class in javax.print.attribute.standard
Class PrinterStateReason is a printing attribute class, an enumeration, that provides additional information about the printer's current state, i.e., information that augments the value of the printer's PrinterState attribute.
PrinterStateReason(int) - Constructor for class javax.print.attribute.standard.PrinterStateReason
Construct a new printer state reason enumeration value with the given integer value.
PrinterStateReasons - Class in javax.print.attribute.standard
Class PrinterStateReasons is a printing attribute class, a set of enumeration values, that provides additional information about the printer's current state, i.e., information that augments the value of the printer's PrinterState attribute.
PrinterStateReasons() - Constructor for class javax.print.attribute.standard.PrinterStateReasons
Construct a new, empty printer state reasons attribute; the underlying hash map has the default initial capacity and load factor.
PrinterStateReasons(int) - Constructor for class javax.print.attribute.standard.PrinterStateReasons
super a new, empty printer state reasons attribute; the underlying hash map has the given initial capacity and the default load factor.
PrinterStateReasons(int, float) - Constructor for class javax.print.attribute.standard.PrinterStateReasons
Construct a new, empty printer state reasons attribute; the underlying hash map has the given initial capacity and load factor.
PrinterStateReasons(Map<PrinterStateReason, Severity>) - Constructor for class javax.print.attribute.standard.PrinterStateReasons
Construct a new printer state reasons attribute that contains the same PrinterStateReason-to-Severity mappings as the given map.
printerStateReasonSet(Severity) - Method in class javax.print.attribute.standard.PrinterStateReasons
Obtain an unmodifiable set view of the individual printer state reason attributes at the given severity level in this PrinterStateReasons attribute.
PrinterURI - Class in javax.print.attribute.standard
Class PrinterURI is a printing attribute class, a URI, that specifies the globally unique name of a printer.
PrinterURI(URI) - Constructor for class javax.print.attribute.standard.PrinterURI
Constructs a new PrinterURI attribute with the specified URI.
PrintEvent - Class in javax.print.event
Class PrintEvent is the super class of all Print Service API events.
PrintEvent(Object) - Constructor for class javax.print.event.PrintEvent
Constructs a PrintEvent object.
PrintException - Exception in javax.print
Class PrintException encapsulates a printing-related error condition that occurred while using a Print Service instance.
PrintException() - Constructor for exception javax.print.PrintException
Construct a print exception with no detail message.
PrintException(String) - Constructor for exception javax.print.PrintException
Construct a print exception with the given detail message.
PrintException(Exception) - Constructor for exception javax.print.PrintException
Construct a print exception chaining the supplied exception.
PrintException(String, Exception) - Constructor for exception javax.print.PrintException
Construct a print exception with the given detail message and chained exception.
printf(String, Object...) - Method in class java.io.Console
A convenience method to write a formatted string to this console's output stream using the specified format string and arguments.
printf(String, Object...) - Method in class java.io.PrintStream
A convenience method to write a formatted string to this output stream using the specified format string and arguments.
printf(Locale, String, Object...) - Method in class java.io.PrintStream
A convenience method to write a formatted string to this output stream using the specified format string and arguments.
printf(String, Object...) - Method in class java.io.PrintWriter
A convenience method to write a formatted string to this writer using the specified format string and arguments.
printf(Locale, String, Object...) - Method in class java.io.PrintWriter
A convenience method to write a formatted string to this writer using the specified format string and arguments.
printFloat(float) - Static method in class javax.xml.bind.DatatypeConverter
Converts a float value into a string.
printFloat(float) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts a float value into a string.
PrintGraphics - Interface in java.awt
An abstract class which provides a print graphics context for a page.
printHexBinary(byte[]) - Static method in class javax.xml.bind.DatatypeConverter
Converts an array of bytes into a string.
printHexBinary(byte[]) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts an array of bytes into a string.
printInt(int) - Static method in class javax.xml.bind.DatatypeConverter
Converts an int value into a string.
printInt(int) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts an int value into a string.
printInteger(BigInteger) - Static method in class javax.xml.bind.DatatypeConverter
Converts a BigInteger value into a string.
printInteger(BigInteger) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts a BigInteger value into a string.
PrintJob - Class in java.awt
An abstract class which initiates and executes a print job.
PrintJob() - Constructor for class java.awt.PrintJob
PrintJobAdapter - Class in javax.print.event
An abstract adapter class for receiving print job events.
PrintJobAdapter() - Constructor for class javax.print.event.PrintJobAdapter
PrintJobAttribute - Interface in javax.print.attribute
PrintJobAttribute is a tagging interface which a printing attribute class implements to indicate the attribute describes the status of a Print Job or some other characteristic of a Print Job.
PrintJobAttributeEvent - Class in javax.print.event
Class PrintJobAttributeEvent encapsulates an event a PrintService reports to let the client know that one or more printing attributes for a PrintJob have changed.
PrintJobAttributeEvent(DocPrintJob, PrintJobAttributeSet) - Constructor for class javax.print.event.PrintJobAttributeEvent
Constructs a PrintJobAttributeEvent object.
PrintJobAttributeListener - Interface in javax.print.event
Implementations of this interface are attached to a DocPrintJob to monitor the status of attribute changes associated with the print job.
PrintJobAttributeSet - Interface in javax.print.attribute
Interface PrintJobAttributeSet specifies the interface for a set of print job attributes, i.e.
printJobCanceled(PrintJobEvent) - Method in class javax.print.event.PrintJobAdapter
Called to notify the client that the job was canceled by user or program.
printJobCanceled(PrintJobEvent) - Method in interface javax.print.event.PrintJobListener
Called to notify the client that the job was canceled by a user or a program.
printJobCompleted(PrintJobEvent) - Method in class javax.print.event.PrintJobAdapter
Called to notify the client that the job completed successfully.
printJobCompleted(PrintJobEvent) - Method in interface javax.print.event.PrintJobListener
Called to notify the client that the job completed successfully.
PrintJobEvent - Class in javax.print.event
Class PrintJobEvent encapsulates common events a print job reports to let a listener know of progress in the processing of the DocPrintJob.
PrintJobEvent(DocPrintJob, int) - Constructor for class javax.print.event.PrintJobEvent
Constructs a PrintJobEvent object.
printJobFailed(PrintJobEvent) - Method in class javax.print.event.PrintJobAdapter
Called to notify the client that the job failed to complete successfully and will have to be resubmitted.
printJobFailed(PrintJobEvent) - Method in interface javax.print.event.PrintJobListener
Called to notify the client that the job failed to complete successfully and will have to be resubmitted.
PrintJobListener - Interface in javax.print.event
Implementations of this listener interface should be attached to a DocPrintJob to monitor the status of the printer job.
printJobNoMoreEvents(PrintJobEvent) - Method in class javax.print.event.PrintJobAdapter
Called to notify the client that no more events will be delivered.
printJobNoMoreEvents(PrintJobEvent) - Method in interface javax.print.event.PrintJobListener
Called to notify the client that no more events will be delivered.
printJobRequiresAttention(PrintJobEvent) - Method in class javax.print.event.PrintJobAdapter
Called to notify the client that some possibly user rectifiable problem occurs (eg printer out of paper).
printJobRequiresAttention(PrintJobEvent) - Method in interface javax.print.event.PrintJobListener
Called to notify the client that an error has occurred that the user might be able to fix.
println() - Method in class java.io.PrintStream
Terminates the current line by writing the line separator string.
println(boolean) - Method in class java.io.PrintStream
Prints a boolean and then terminate the line.
println(char) - Method in class java.io.PrintStream
Prints a character and then terminate the line.
println(int) - Method in class java.io.PrintStream
Prints an integer and then terminate the line.
println(long) - Method in class java.io.PrintStream
Prints a long and then terminate the line.
println(float) - Method in class java.io.PrintStream
Prints a float and then terminate the line.
println(double) - Method in class java.io.PrintStream
Prints a double and then terminate the line.
println(char[]) - Method in class java.io.PrintStream
Prints an array of characters and then terminate the line.
println(String) - Method in class java.io.PrintStream
Prints a String and then terminate the line.
println(Object) - Method in class java.io.PrintStream
Prints an Object and then terminate the line.
println() - Method in class java.io.PrintWriter
Terminates the current line by writing the line separator string.
println(boolean) - Method in class java.io.PrintWriter
Prints a boolean value and then terminates the line.
println(char) - Method in class java.io.PrintWriter
Prints a character and then terminates the line.
println(int) - Method in class java.io.PrintWriter
Prints an integer and then terminates the line.
println(long) - Method in class java.io.PrintWriter
Prints a long integer and then terminates the line.
println(float) - Method in class java.io.PrintWriter
Prints a floating-point number and then terminates the line.
println(double) - Method in class java.io.PrintWriter
Prints a double-precision floating-point number and then terminates the line.
println(char[]) - Method in class java.io.PrintWriter
Prints an array of characters and then terminates the line.
println(String) - Method in class java.io.PrintWriter
Prints a String and then terminates the line.
println(Object) - Method in class java.io.PrintWriter
Prints an Object and then terminates the line.
println(String) - Static method in class java.sql.DriverManager
Prints a message to the current JDBC log stream.
printLong(long) - Static method in class javax.xml.bind.DatatypeConverter
Converts A long value into a string.
printLong(long) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts a long value into a string.
printMessage(Diagnostic.Kind, CharSequence) - Method in interface javax.annotation.processing.Messager
Prints a message of the specified kind.
printMessage(Diagnostic.Kind, CharSequence, Element) - Method in interface javax.annotation.processing.Messager
Prints a message of the specified kind at the location of the element.
printMessage(Diagnostic.Kind, CharSequence, Element, AnnotationMirror) - Method in interface javax.annotation.processing.Messager
Prints a message of the specified kind at the location of the annotation mirror of the annotated element.
printMessage(Diagnostic.Kind, CharSequence, Element, AnnotationMirror, AnnotationValue) - Method in interface javax.annotation.processing.Messager
Prints a message of the specified kind at the location of the annotation value inside the annotation mirror of the annotated element.
printQName(QName, NamespaceContext) - Static method in class javax.xml.bind.DatatypeConverter
Converts a QName instance into a string.
printQName(QName, NamespaceContext) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts a QName instance into a string.
PrintQuality - Class in javax.print.attribute.standard
Class PrintQuality is a printing attribute class, an enumeration, that specifies the print quality that the printer uses for the job.
PrintQuality(int) - Constructor for class javax.print.attribute.standard.PrintQuality
Construct a new print quality enumeration value with the given integer value.
PrintRequestAttribute - Interface in javax.print.attribute
Interface PrintRequestAttribute is a tagging interface which a printing attribute class implements to indicate the attribute denotes a requested setting for a print job.
PrintRequestAttributeSet - Interface in javax.print.attribute
Interface PrintRequestAttributeSet specifies the interface for a set of print request attributes, i.e.
PrintService - Interface in javax.print
Interface PrintService is the factory for a DocPrintJob.
PrintServiceAttribute - Interface in javax.print.attribute
Interface PrintServiceAttribute is a tagging interface which a printing attribute class implements to indicate the attribute describes the status of a Print Service or some other characteristic of a Print Service.
PrintServiceAttributeEvent - Class in javax.print.event
Class PrintServiceAttributeEvent encapsulates an event a Print Service instance reports to let the client know of changes in the print service state.
PrintServiceAttributeEvent(PrintService, PrintServiceAttributeSet) - Constructor for class javax.print.event.PrintServiceAttributeEvent
Constructs a PrintServiceAttributeEvent object.
PrintServiceAttributeListener - Interface in javax.print.event
Implementations of this listener interface are attached to a PrintService to monitor the status of the print service.
PrintServiceAttributeSet - Interface in javax.print.attribute
Interface PrintServiceAttributeSet specifies the interface for a set of print job attributes, i.e.
PrintServiceLookup - Class in javax.print
Implementations of this class provide lookup services for print services (typically equivalent to printers) of a particular type.
PrintServiceLookup() - Constructor for class javax.print.PrintServiceLookup
printShort(short) - Static method in class javax.xml.bind.DatatypeConverter
Converts a short value into a string.
printShort(short) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts a short value into a string.
printStackTrace() - Method in class java.lang.Throwable
Prints this throwable and its backtrace to the standard error stream.
printStackTrace(PrintStream) - Method in class java.lang.Throwable
Prints this throwable and its backtrace to the specified print stream.
printStackTrace(PrintWriter) - Method in class java.lang.Throwable
Prints this throwable and its backtrace to the specified print writer.
printStackTrace(PrintStream) - Method in exception javax.xml.bind.JAXBException
Prints this JAXBException and its stack trace (including the stack trace of the linkedException if it is non-null) to the PrintStream.
printStackTrace() - Method in exception javax.xml.bind.JAXBException
Prints this JAXBException and its stack trace (including the stack trace of the linkedException if it is non-null) to System.err.
printStackTrace(PrintWriter) - Method in exception javax.xml.bind.JAXBException
Prints this JAXBException and its stack trace (including the stack trace of the linkedException if it is non-null) to the PrintWriter.
printStackTrace(PrintStream) - Method in exception javax.xml.bind.TypeConstraintException
Prints this TypeConstraintException and its stack trace (including the stack trace of the linkedException if it is non-null) to the PrintStream.
printStackTrace() - Method in exception javax.xml.bind.TypeConstraintException
Prints this TypeConstraintException and its stack trace (including the stack trace of the linkedException if it is non-null) to System.err.
printStackTrace() - Method in exception javax.xml.crypto.dsig.TransformException
Prints this TransformException, its backtrace and the cause's backtrace to the standard error stream.
printStackTrace(PrintStream) - Method in exception javax.xml.crypto.dsig.TransformException
Prints this TransformException, its backtrace and the cause's backtrace to the specified print stream.
printStackTrace(PrintWriter) - Method in exception javax.xml.crypto.dsig.TransformException
Prints this TransformException, its backtrace and the cause's backtrace to the specified print writer.
printStackTrace() - Method in exception javax.xml.crypto.dsig.XMLSignatureException
Prints this XMLSignatureException, its backtrace and the cause's backtrace to the standard error stream.
printStackTrace(PrintStream) - Method in exception javax.xml.crypto.dsig.XMLSignatureException
Prints this XMLSignatureException, its backtrace and the cause's backtrace to the specified print stream.
printStackTrace(PrintWriter) - Method in exception javax.xml.crypto.dsig.XMLSignatureException
Prints this XMLSignatureException, its backtrace and the cause's backtrace to the specified print writer.
printStackTrace() - Method in exception javax.xml.crypto.KeySelectorException
Prints this KeySelectorException, its backtrace and the cause's backtrace to the standard error stream.
printStackTrace(PrintStream) - Method in exception javax.xml.crypto.KeySelectorException
Prints this KeySelectorException, its backtrace and the cause's backtrace to the specified print stream.
printStackTrace(PrintWriter) - Method in exception javax.xml.crypto.KeySelectorException
Prints this KeySelectorException, its backtrace and the cause's backtrace to the specified print writer.
printStackTrace() - Method in exception javax.xml.crypto.MarshalException
Prints this MarshalException, its backtrace and the cause's backtrace to the standard error stream.
printStackTrace(PrintStream) - Method in exception javax.xml.crypto.MarshalException
Prints this MarshalException, its backtrace and the cause's backtrace to the specified print stream.
printStackTrace(PrintWriter) - Method in exception javax.xml.crypto.MarshalException
Prints this MarshalException, its backtrace and the cause's backtrace to the specified print writer.
printStackTrace() - Method in exception javax.xml.crypto.NoSuchMechanismException
Prints this NoSuchMechanismException, its backtrace and the cause's backtrace to the standard error stream.
printStackTrace(PrintStream) - Method in exception javax.xml.crypto.NoSuchMechanismException
Prints this NoSuchMechanismException, its backtrace and the cause's backtrace to the specified print stream.
printStackTrace(PrintWriter) - Method in exception javax.xml.crypto.NoSuchMechanismException
Prints this NoSuchMechanismException, its backtrace and the cause's backtrace to the specified print writer.
printStackTrace() - Method in exception javax.xml.crypto.URIReferenceException
Prints this URIReferenceException, its backtrace and the cause's backtrace to the standard error stream.
printStackTrace(PrintStream) - Method in exception javax.xml.crypto.URIReferenceException
Prints this URIReferenceException, its backtrace and the cause's backtrace to the specified print stream.
printStackTrace(PrintWriter) - Method in exception javax.xml.crypto.URIReferenceException
Prints this URIReferenceException, its backtrace and the cause's backtrace to the specified print writer.
printStackTrace() - Method in exception javax.xml.transform.TransformerException
Print the the trace of methods from where the error originated.
printStackTrace(PrintStream) - Method in exception javax.xml.transform.TransformerException
Print the the trace of methods from where the error originated.
printStackTrace(PrintWriter) - Method in exception javax.xml.transform.TransformerException
Print the the trace of methods from where the error originated.
printStackTrace(PrintStream) - Method in exception javax.xml.xpath.XPathException
Print stack trace to specified PrintStream.
printStackTrace() - Method in exception javax.xml.xpath.XPathException
Print stack trace to System.err.
printStackTrace(PrintWriter) - Method in exception javax.xml.xpath.XPathException
Print stack trace to specified PrintWriter.
PrintStream - Class in java.io
A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently.
PrintStream(OutputStream) - Constructor for class java.io.PrintStream
Creates a new print stream.
PrintStream(OutputStream, boolean) - Constructor for class java.io.PrintStream
Creates a new print stream.
PrintStream(OutputStream, boolean, String) - Constructor for class java.io.PrintStream
Creates a new print stream.
PrintStream(String) - Constructor for class java.io.PrintStream
Creates a new print stream, without automatic line flushing, with the specified file name.
PrintStream(String, String) - Constructor for class java.io.PrintStream
Creates a new print stream, without automatic line flushing, with the specified file name and charset.
PrintStream(File) - Constructor for class java.io.PrintStream
Creates a new print stream, without automatic line flushing, with the specified file.
PrintStream(File, String) - Constructor for class java.io.PrintStream
Creates a new print stream, without automatic line flushing, with the specified file and charset.
printString(String) - Static method in class javax.xml.bind.DatatypeConverter
Converts the string argument into a string.
printString(String) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts the string argument into a string.
printTime(Calendar) - Static method in class javax.xml.bind.DatatypeConverter
Converts a Calendar value into a string.
printTime(Calendar) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts a Calendar value into a string.
printUnsignedInt(long) - Static method in class javax.xml.bind.DatatypeConverter
Converts a long value into a string.
printUnsignedInt(long) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts a long value into a string.
printUnsignedShort(int) - Static method in class javax.xml.bind.DatatypeConverter
Converts an int value into a string.
printUnsignedShort(int) - Method in interface javax.xml.bind.DatatypeConverterInterface
Converts an int value into a string.
PrintWriter - Class in java.io
Prints formatted representations of objects to a text-output stream.
PrintWriter(Writer) - Constructor for class java.io.PrintWriter
Creates a new PrintWriter, without automatic line flushing.
PrintWriter(Writer, boolean) - Constructor for class java.io.PrintWriter
Creates a new PrintWriter.
PrintWriter(OutputStream) - Constructor for class java.io.PrintWriter
Creates a new PrintWriter, without automatic line flushing, from an existing OutputStream.
PrintWriter(OutputStream, boolean) - Constructor for class java.io.PrintWriter
Creates a new PrintWriter from an existing OutputStream.
PrintWriter(String) - Constructor for class java.io.PrintWriter
Creates a new PrintWriter, without automatic line flushing, with the specified file name.
PrintWriter(String, String) - Constructor for class java.io.PrintWriter
Creates a new PrintWriter, without automatic line flushing, with the specified file name and charset.
PrintWriter(File) - Constructor for class java.io.PrintWriter
Creates a new PrintWriter, without automatic line flushing, with the specified file.
PrintWriter(File, String) - Constructor for class java.io.PrintWriter
Creates a new PrintWriter, without automatic line flushing, with the specified file and charset.
PRIOR - Static variable in class java.awt.BufferCapabilities.FlipContents
When flip contents are PRIOR, the contents of the back buffer are the prior contents of the front buffer (a true page flip).
PRIORITY_INTERCHAR - Static variable in class java.awt.font.GlyphJustificationInfo
The second lowest justification priority.
PRIORITY_KASHIDA - Static variable in class java.awt.font.GlyphJustificationInfo
The highest justification priority.
PRIORITY_NONE - Static variable in class java.awt.font.GlyphJustificationInfo
The lowest justification priority.
PRIORITY_WHITESPACE - Static variable in class java.awt.font.GlyphJustificationInfo
The second highest justification priority.
PriorityBlockingQueue<E> - Class in java.util.concurrent
An unbounded blocking queue that uses the same ordering rules as class PriorityQueue and supplies blocking retrieval operations.
PriorityBlockingQueue() - Constructor for class java.util.concurrent.PriorityBlockingQueue
Creates a PriorityBlockingQueue with the default initial capacity (11) that orders its elements according to their natural ordering.
PriorityBlockingQueue(int) - Constructor for class java.util.concurrent.PriorityBlockingQueue
Creates a PriorityBlockingQueue with the specified initial capacity that orders its elements according to their natural ordering.
PriorityBlockingQueue(int, Comparator<? super E>) - Constructor for class java.util.concurrent.PriorityBlockingQueue
Creates a PriorityBlockingQueue with the specified initial capacity that orders its elements according to the specified comparator.
PriorityBlockingQueue(Collection<? extends E>) - Constructor for class java.util.concurrent.PriorityBlockingQueue
Creates a PriorityBlockingQueue containing the elements in the specified collection.
PriorityQueue<E> - Class in java.util
An unbounded priority queue based on a priority heap.
PriorityQueue() - Constructor for class java.util.PriorityQueue
Creates a PriorityQueue with the default initial capacity (11) that orders its elements according to their natural ordering.
PriorityQueue(int) - Constructor for class java.util.PriorityQueue
Creates a PriorityQueue with the specified initial capacity that orders its elements according to their natural ordering.
PriorityQueue(int, Comparator<? super E>) - Constructor for class java.util.PriorityQueue
Creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified comparator.
PriorityQueue(Collection<? extends E>) - Constructor for class java.util.PriorityQueue
Creates a PriorityQueue containing the elements in the specified collection.
PriorityQueue(PriorityQueue<? extends E>) - Constructor for class java.util.PriorityQueue
Creates a PriorityQueue containing the elements in the specified priority queue.
PriorityQueue(SortedSet<? extends E>) - Constructor for class java.util.PriorityQueue
Creates a PriorityQueue containing the elements in the specified sorted set.
PRIVATE - Static variable in class java.lang.invoke.MethodHandles.Lookup
A single-bit mask representing private access, which may contribute to the result of lookupModes.
PRIVATE - Static variable in class java.lang.reflect.修饰符
The int value representing the private modifier.
PRIVATE - Static variable in class java.nio.channels.FileChannel.MapMode
Mode for a private (copy-on-write) mapping.
PRIVATE_KEY - Static variable in class javax.crypto.Cipher
Constant used to indicate the to-be-unwrapped key is a "private key".
PRIVATE_MEMBER - Interface in org.omg.CORBA
Constant to define a private member in the ValueMember class.
PRIVATE_USE - Static variable in class java.lang.Character
General category "Co" in the Unicode specification.
PRIVATE_USE_AREA - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Private Use Area" Unicode character block.
PRIVATE_USE_EXTENSION - Static variable in class java.util.Locale
The key for the private use extension ('x').
PrivateClassLoader - Interface in javax.management.loading
Marker interface indicating that a ClassLoader should not be added to the ClassLoaderRepository.
PrivateCredentialPermission - Class in javax.security.auth
This class is used to protect access to private Credentials belonging to a particular Subject.
PrivateCredentialPermission(String, String) - Constructor for class javax.security.auth.PrivateCredentialPermission
Creates a new PrivateCredentialPermission with the specified name.
PrivateKey - Interface in java.security
A private key.
PrivateMLet - Class in javax.management.loading
An MLet that is not added to the ClassLoaderRepository.
PrivateMLet(URL[], boolean) - Constructor for class javax.management.loading.PrivateMLet
Constructs a new PrivateMLet for the specified URLs using the default delegation parent ClassLoader.
PrivateMLet(URL[], ClassLoader, boolean) - Constructor for class javax.management.loading.PrivateMLet
Constructs a new PrivateMLet for the given URLs.
PrivateMLet(URL[], ClassLoader, URLStreamHandlerFactory, boolean) - Constructor for class javax.management.loading.PrivateMLet
Constructs a new PrivateMLet for the specified URLs, parent class loader, and URLStreamHandlerFactory.
PrivilegedAction<T> - Interface in java.security
A computation to be performed with privileges enabled.
PrivilegedActionException - Exception in java.security
This exception is thrown by doPrivileged(PrivilegedExceptionAction) and doPrivileged(PrivilegedExceptionAction, AccessControlContext context) to indicate that the action being performed threw a checked exception.
PrivilegedActionException(Exception) - Constructor for exception java.security.PrivilegedActionException
Constructs a new PrivilegedActionException "wrapping" the specific Exception.
privilegedCallable(Callable<T>) - Static method in class java.util.concurrent.Executors
Returns a Callable object that will, when called, execute the given callable under the current access control context.
privilegedCallableUsingCurrentClassLoader(Callable<T>) - Static method in class java.util.concurrent.Executors
Returns a Callable object that will, when called, execute the given callable under the current access control context, with the current context class loader as the context class loader.
PrivilegedExceptionAction<T> - Interface in java.security
A computation to be performed with privileges enabled, that throws one or more checked exceptions.
privilegedThreadFactory() - Static method in class java.util.concurrent.Executors
Returns a thread factory used to create new threads that have the same permissions as the current thread.
probablePrime(int, Random) - Static method in class java.math.BigInteger
Returns a positive BigInteger that is probably prime, with the specified bitLength.
probeContentType(Path) - Static method in class java.nio.file.Files
Probes the content type of a file.
probeContentType(Path) - Method in class java.nio.file.spi.FileTypeDetector
Probes the given file to guess its content type.
procedureColumnIn - Static variable in interface java.sql.DatabaseMetaData
Indicates that the column stores IN parameters.
procedureColumnInOut - Static variable in interface java.sql.DatabaseMetaData
Indicates that the column stores INOUT parameters.
procedureColumnOut - Static variable in interface java.sql.DatabaseMetaData
Indicates that the column stores OUT parameters.
procedureColumnResult - Static variable in interface java.sql.DatabaseMetaData
Indicates that the column stores results.
procedureColumnReturn - Static variable in interface java.sql.DatabaseMetaData
Indicates that the column stores return values.
procedureColumnUnknown - Static variable in interface java.sql.DatabaseMetaData
Indicates that type of the column is unknown.
procedureNoNulls - Static variable in interface java.sql.DatabaseMetaData
Indicates that NULL values are not allowed.
procedureNoResult - Static variable in interface java.sql.DatabaseMetaData
Indicates that the procedure does not return a result.
procedureNullable - Static variable in interface java.sql.DatabaseMetaData
Indicates that NULL values are allowed.
procedureNullableUnknown - Static variable in interface java.sql.DatabaseMetaData
Indicates that whether NULL values are allowed is unknown.
procedureResultUnknown - Static variable in interface java.sql.DatabaseMetaData
Indicates that it is not known whether the procedure returns a result.
procedureReturnsResult - Static variable in interface java.sql.DatabaseMetaData
Indicates that the procedure returns a result.
Process - Class in java.lang
The ProcessBuilder.start() and Runtime.exec methods create a native process and return an instance of a subclass of Process that can be used to control the process and obtain information about it.
Process() - Constructor for class java.lang.Process
process(Set<? extends TypeElement>, RoundEnvironment) - Method in class javax.annotation.processing.AbstractProcessor
Processes a set of annotation types on type elements originating from the prior round and returns whether or not these annotations are claimed by this processor.
process(Set<? extends TypeElement>, RoundEnvironment) - Method in interface javax.annotation.processing.Processor
Processes a set of annotation types on type elements originating from the prior round and returns whether or not these annotations are claimed by this processor.
process(List<V>) - Method in class javax.swing.SwingWorker
Receives data chunks from the publish method asynchronously on the Event Dispatch Thread.
processActionEvent(ActionEvent) - Method in class java.awt.Button
Processes action events occurring on this button by dispatching them to any registered ActionListener objects.
processActionEvent(ActionEvent) - Method in class java.awt.List
Processes action events occurring on this component by dispatching them to any registered ActionListener objects.
processActionEvent(ActionEvent) - Method in class java.awt.MenuItem
Processes action events occurring on this menu item, by dispatching them to any registered ActionListener objects.
processActionEvent(ActionEvent) - Method in class java.awt.TextField
Processes action events occurring on this text field by dispatching them to any registered ActionListener objects.
processAdjustmentEvent(AdjustmentEvent) - Method in class java.awt.Scrollbar
Processes adjustment events occurring on this scrollbar by dispatching them to any registered AdjustmentListener objects.
ProcessBuilder - Class in java.lang
This class is used to create operating system processes.
ProcessBuilder(List<String>) - Constructor for class java.lang.ProcessBuilder
Constructs a process builder with the specified operating system program and arguments.
ProcessBuilder(String...) - Constructor for class java.lang.ProcessBuilder
Constructs a process builder with the specified operating system program and arguments.
ProcessBuilder.Redirect - Class in java.lang
Represents a source of subprocess input or a destination of subprocess output.
ProcessBuilder.Redirect.Type - Enum in java.lang
The type of a ProcessBuilder.Redirect.
processComponentEvent(ComponentEvent) - Method in class java.awt.Component
Processes component events occurring on this component by dispatching them to any registered ComponentListener objects.
processComponentEvent(ComponentEvent, JLayer<? extends V>) - Method in class javax.swing.plaf.LayerUI
Processes component events occurring on the JLayer or any of its subcomponents.
processComponentKeyEvent(KeyEvent) - Method in class javax.swing.JComponent
Processes any key events that the component itself recognizes.
processContainerEvent(ContainerEvent) - Method in class java.awt.Container
Processes container events occurring on this container by dispatching them to any registered ContainerListener objects.
processEvent(AWTEvent) - Method in class java.awt.Button
Processes events on this button.
processEvent(AWTEvent) - Method in class java.awt.Checkbox
Processes events on this check box.
processEvent(AWTEvent) - Method in class java.awt.CheckboxMenuItem
Processes events on this check box menu item.
processEvent(AWTEvent) - Method in class java.awt.Choice
Processes events on this choice.
processEvent(AWTEvent) - Method in class java.awt.Component
Processes events occurring on this component.
processEvent(AWTEvent) - Method in class java.awt.Container
Processes events on this container.
processEvent(AWTEvent) - Method in class java.awt.List
Processes events on this scrolling list.
processEvent(AWTEvent) - Method in class java.awt.MenuComponent
Processes events occurring on this menu component.
processEvent(AWTEvent) - Method in class java.awt.MenuItem
Processes events on this menu item.
processEvent(AWTEvent) - Method in class java.awt.Scrollbar
Processes events on this scroll bar.
processEvent(AWTEvent) - Method in class java.awt.TextComponent
Processes events on this text component.
processEvent(AWTEvent) - Method in class java.awt.TextField
Processes events on this text field.
processEvent(AWTEvent) - Method in class java.awt.Window
Processes events on this window.
processFocusEvent(FocusEvent) - Method in class java.awt.Component
Processes focus events occurring on this component by dispatching them to any registered FocusListener objects.
processFocusEvent(FocusEvent) - Method in class javax.swing.JFormattedTextField
Processes any focus events, such as FocusEvent.FOCUS_GAINED or FocusEvent.FOCUS_LOST.
processFocusEvent(FocusEvent) - Method in class javax.swing.JPopupMenu
processFocusEvent(FocusEvent, JLayer<? extends V>) - Method in class javax.swing.plaf.LayerUI
Processes focus events occurring on the JLayer or any of its subcomponents.
processHierarchyBoundsEvent(HierarchyEvent) - Method in class java.awt.Component
Processes hierarchy bounds events occurring on this component by dispatching them to any registered HierarchyBoundsListener objects.
processHierarchyBoundsEvent(HierarchyEvent, JLayer<? extends V>) - Method in class javax.swing.plaf.LayerUI
Processes hierarchy bounds event occurring on the JLayer or any of its subcomponents.
processHierarchyEvent(HierarchyEvent) - Method in class java.awt.Component
Processes hierarchy events occurring on this component by dispatching them to any registered HierarchyListener objects.
processHierarchyEvent(HierarchyEvent, JLayer<? extends V>) - Method in class javax.swing.plaf.LayerUI
Processes hierarchy event occurring on the JLayer or any of its subcomponents.
processHTMLFrameHyperlinkEvent(HTMLFrameHyperlinkEvent) - Method in class javax.swing.text.html.HTMLDocument
Processes HyperlinkEvents that are generated by documents in an HTML frame.
processImageComplete() - Method in class javax.imageio.ImageReader
Broadcasts the completion of an image read to all registered IIOReadProgressListeners by calling their imageComplete method.
processImageComplete() - Method in class javax.imageio.ImageWriter
Broadcasts the completion of an image write to all registered IIOWriteProgressListeners by calling their imageComplete method.
processImageProgress(float) - Method in class javax.imageio.ImageReader
Broadcasts the current percentage of image completion to all registered IIOReadProgressListeners by calling their imageProgress method.
processImageProgress(float) - Method in class javax.imageio.ImageWriter
Broadcasts the current percentage of image completion to all registered IIOWriteProgressListeners by calling their imageProgress method.
processImageStarted(int) - Method in class javax.imageio.ImageReader
Broadcasts the start of an image read to all registered IIOReadProgressListeners by calling their imageStarted method.
processImageStarted(int) - Method in class javax.imageio.ImageWriter
Broadcasts the start of an image write to all registered IIOWriteProgressListeners by calling their imageStarted method.
processImageUpdate(BufferedImage, int, int, int, int, int, int, int[]) - Method in class javax.imageio.ImageReader
Broadcasts the update of a set of samples to all registered IIOReadUpdateListeners by calling their imageUpdate method.
PROCESSING - Static variable in class javax.print.attribute.standard.JobState
The job is processing.
PROCESSING - Static variable in class javax.print.attribute.standard.PrinterState
Indicates that jobs are processing; new jobs will wait before processing.
PROCESSING_INSTRUCTION - Static variable in interface javax.xml.stream.XMLStreamConstants
Indicates an event is a processing instruction
PROCESSING_INSTRUCTION_NODE - Static variable in interface org.w3c.dom.Node
The node is a ProcessingInstruction.
PROCESSING_STOPPED - Static variable in class javax.print.attribute.standard.JobState
The job has stopped while processing for any number of reasons and will return to the PROCESSING state as soon as the reasons are no longer present.
PROCESSING_TO_STOP_POINT - Static variable in class javax.print.attribute.standard.JobStateReason
The requester has canceled the job or the printer has aborted the job, but the printer is still performing some actions on the job until a specified stop point occurs or job termination/cleanup is completed.
processingEnv - Variable in class javax.annotation.processing.AbstractProcessor
Processing environment providing by the tool framework.
ProcessingEnvironment - Interface in javax.annotation.processing
An annotation processing tool framework will provide an annotation processor with an object implementing this interface so the processor can use facilities provided by the framework to write new files, report error messages, and find other utilities.
ProcessingInstruction - Interface in javax.xml.stream.events
An interface that describes the data found in processing instructions
ProcessingInstruction - Interface in org.w3c.dom
The ProcessingInstruction interface represents a "processing instruction", used in XML as a way to keep processor-specific information in the text of the document.
processingInstruction(String, String) - Method in interface org.xml.sax.ContentHandler
Receive notification of a processing instruction.
processingInstruction(String, String) - Method in interface org.xml.sax.DocumentHandler
Deprecated.
Receive notification of a processing instruction.
processingInstruction(String, String) - Method in class org.xml.sax.HandlerBase
Deprecated.
Receive notification of a processing instruction.
processingInstruction(String, String) - Method in class org.xml.sax.helpers.DefaultHandler
Receive notification of a processing instruction.
processingInstruction(String, String) - Method in class org.xml.sax.helpers.ParserAdapter
Adapter implementation method; do not call.
processingInstruction(String, String) - Method in class org.xml.sax.helpers.XMLFilterImpl
Filter a processing instruction event.
processingInstruction(String, String) - Method in class org.xml.sax.helpers.XMLReaderAdapter
Adapt a SAX2 processing instruction event.
processingOver() - Method in interface javax.annotation.processing.RoundEnvironment
Returns true if types generated by this round will not be subject to a subsequent round of annotation processing; returns false otherwise.
processInputMethodEvent(InputMethodEvent) - Method in class java.awt.Component
Processes input method events occurring on this component by dispatching them to any registered InputMethodListener objects.
processInputMethodEvent(InputMethodEvent) - Method in class javax.swing.JFormattedTextField
Processes any input method events, such as InputMethodEvent.INPUT_METHOD_TEXT_CHANGED or InputMethodEvent.CARET_POSITION_CHANGED.
processInputMethodEvent(InputMethodEvent, JLayer<? extends V>) - Method in class javax.swing.plaf.LayerUI
Processes input event occurring on the JLayer or any of its subcomponents.
processInputMethodEvent(InputMethodEvent) - Method in class javax.swing.text.JTextComponent
processItemEvent(ItemEvent) - Method in class java.awt.Checkbox
Processes item events occurring on this check box by dispatching them to any registered ItemListener objects.
processItemEvent(ItemEvent) - Method in class java.awt.CheckboxMenuItem
Processes item events occurring on this check box menu item by dispatching them to any registered ItemListener objects.
processItemEvent(ItemEvent) - Method in class java.awt.Choice
Processes item events occurring on this Choice menu by dispatching them to any registered ItemListener objects.
processItemEvent(ItemEvent) - Method in class java.awt.List
Processes item events occurring on this list by dispatching them to any registered ItemListener objects.
processKeyBinding(KeyStroke, KeyEvent, int, boolean) - Method in class javax.swing.JComponent
Invoked to process the key bindings for ks as the result of the KeyEvent e.
processKeyBinding(KeyStroke, KeyEvent, int, boolean) - Method in class javax.swing.JMenuBar
Subclassed to check all the child menus.
processKeyBinding(KeyStroke, KeyEvent, int, boolean) - Method in class javax.swing.JTable
processKeyBindings(KeyEvent) - Static method in class javax.swing.SwingUtilities
Process the key bindings for the Component associated with event.
processKeyEvent(KeyEvent) - Method in class java.awt.Component
Processes key events occurring on this component by dispatching them to any registered KeyListener objects.
processKeyEvent(Component, KeyEvent) - Method in class java.awt.DefaultKeyboardFocusManager
This method initiates a focus traversal operation if and only if the KeyEvent represents a focus traversal key for the specified focusedComponent.
processKeyEvent(Component, KeyEvent) - Method in class java.awt.KeyboardFocusManager
This method initiates a focus traversal operation if and only if the KeyEvent represents a focus traversal key for the specified focusedComponent.
processKeyEvent(KeyEvent) - Method in class javax.swing.JComboBox
Handles KeyEvents, looking for the Tab key.
processKeyEvent(KeyEvent) - Method in class javax.swing.JComponent
Overrides processKeyEvent to process events.
processKeyEvent(KeyEvent) - Method in class javax.swing.JMenu
Processes key stroke events such as mnemonics and accelerators.
processKeyEvent(KeyEvent, MenuElement[], MenuSelectionManager) - Method in class javax.swing.JMenuBar
Implemented to be a MenuElement -- does nothing.
processKeyEvent(KeyEvent, MenuElement[], MenuSelectionManager) - Method in class javax.swing.JMenuItem
Processes a key event forwarded from the MenuSelectionManager and changes the menu selection, if necessary, by using MenuSelectionManager's API.
processKeyEvent(KeyEvent) - Method in class javax.swing.JPopupMenu
Processes key stroke events such as mnemonics and accelerators.
processKeyEvent(KeyEvent, MenuElement[], MenuSelectionManager) - Method in class javax.swing.JPopupMenu
Processes a key event forwarded from the MenuSelectionManager and changes the menu selection, if necessary, by using MenuSelectionManager's API.
processKeyEvent(KeyEvent, MenuElement[], MenuSelectionManager) - Method in interface javax.swing.MenuElement
Process a key event.
processKeyEvent(KeyEvent) - Method in class javax.swing.MenuSelectionManager
When a MenuElement receives an event from a KeyListener, it should never process the event directly.
processKeyEvent(KeyEvent, JLayer<? extends V>) - Method in class javax.swing.plaf.LayerUI
Processes key events occurring on the JLayer or any of its subcomponents.
processMenuDragMouseEvent(MenuDragMouseEvent) - Method in class javax.swing.JMenuItem
Handles mouse drag in a menu.
processMenuKeyEvent(MenuKeyEvent) - Method in class javax.swing.JMenuItem
Handles a keystroke in a menu.
processMouseEvent(MouseEvent) - Method in class java.awt.Component
Processes mouse events occurring on this component by dispatching them to any registered MouseListener objects.
processMouseEvent(MouseEvent) - Method in class javax.swing.JComponent
Processes mouse events occurring on this component by dispatching them to any registered MouseListener objects, refer to Component.processMouseEvent(MouseEvent) for a complete description of this method.
processMouseEvent(MouseEvent, MenuElement[], MenuSelectionManager) - Method in class javax.swing.JMenuBar
Implemented to be a MenuElement -- does nothing.
processMouseEvent(MouseEvent, MenuElement[], MenuSelectionManager) - Method in class javax.swing.JMenuItem
Processes a mouse event forwarded from the MenuSelectionManager and changes the menu selection, if necessary, by using the MenuSelectionManager's API.
processMouseEvent(MouseEvent, MenuElement[], MenuSelectionManager) - Method in class javax.swing.JPopupMenu
This method is required to conform to the MenuElement interface, but it not implemented.
processMouseEvent(MouseEvent, MenuElement[], MenuSelectionManager) - Method in interface javax.swing.MenuElement
Processes a mouse event.
processMouseEvent(MouseEvent) - Method in class javax.swing.MenuSelectionManager
When a MenuElement receives an event from a MouseListener, it should never process the event directly.
processMouseEvent(JMenuItem, MouseEvent, MenuElement[], MenuSelectionManager) - Method in class javax.swing.plaf.basic.BasicCheckBoxMenuItemUI
processMouseEvent(JMenuItem, MouseEvent, MenuElement[], MenuSelectionManager) - Method in class javax.swing.plaf.basic.BasicRadioButtonMenuItemUI
processMouseEvent(MouseEvent, JLayer<? extends V>) - Method in class javax.swing.plaf.LayerUI
Processes mouse events occurring on the JLayer or any of its subcomponents.
processMouseMotionEvent(MouseEvent) - Method in class java.awt.Component
Processes mouse motion events occurring on this component by dispatching them to any registered MouseMotionListener objects.
processMouseMotionEvent(MouseEvent) - Method in class javax.swing.JComponent
Processes mouse motion events, such as MouseEvent.MOUSE_DRAGGED.
processMouseMotionEvent(MouseEvent, JLayer<? extends V>) - Method in class javax.swing.plaf.LayerUI
Processes mouse motion event occurring on the JLayer or any of its subcomponents.
processMouseWheelEvent(MouseWheelEvent) - Method in class java.awt.Component
Processes mouse wheel events occurring on this component by dispatching them to any registered MouseWheelListener objects.
processMouseWheelEvent(MouseWheelEvent) - Method in class java.awt.ScrollPane
Process mouse wheel events that are delivered to this ScrollPane by scrolling an appropriate amount.
processMouseWheelEvent(MouseWheelEvent, JLayer<? extends V>) - Method in class javax.swing.plaf.LayerUI
Processes mouse wheel event occurring on the JLayer or any of its subcomponents.
processName(String, String[], boolean) - Method in class org.xml.sax.helpers.NamespaceSupport
Process a raw XML qualified name, after all declarations in the current context have been handled by declarePrefix().
Processor - Interface in javax.annotation.processing
The interface for an annotation processor.
processPassComplete(BufferedImage) - Method in class javax.imageio.ImageReader
Broadcasts the end of a progressive pass to all registered IIOReadUpdateListeners by calling their passComplete method.
processPassStarted(BufferedImage, int, int, int, int, int, int, int, int[]) - Method in class javax.imageio.ImageReader
Broadcasts the beginning of a progressive pass to all registered IIOReadUpdateListeners by calling their passStarted method.
processReadAborted() - Method in class javax.imageio.ImageReader
Broadcasts that the read has been aborted to all registered IIOReadProgressListeners by calling their readAborted method.
processSequenceComplete() - Method in class javax.imageio.ImageReader
Broadcasts the completion of an sequence of image reads to all registered IIOReadProgressListeners by calling their sequenceComplete method.
processSequenceStarted(int) - Method in class javax.imageio.ImageReader
Broadcasts the start of an sequence of image reads to all registered IIOReadProgressListeners by calling their sequenceStarted method.
processTextEvent(TextEvent) - Method in class java.awt.TextComponent
Processes text events occurring on this text component by dispatching them to any registered TextListener objects.
processThumbnailComplete() - Method in class javax.imageio.ImageReader
Broadcasts the completion of a thumbnail read to all registered IIOReadProgressListeners by calling their thumbnailComplete method.
processThumbnailComplete() - Method in class javax.imageio.ImageWriter
Broadcasts the completion of a thumbnail write to all registered IIOWriteProgressListeners by calling their thumbnailComplete method.
processThumbnailPassComplete(BufferedImage) - Method in class javax.imageio.ImageReader
Broadcasts the end of a thumbnail progressive pass to all registered IIOReadUpdateListeners by calling their thumbnailPassComplete method.
processThumbnailPassStarted(BufferedImage, int, int, int, int, int, int, int, int[]) - Method in class javax.imageio.ImageReader
Broadcasts the beginning of a thumbnail progressive pass to all registered IIOReadUpdateListeners by calling their thumbnailPassStarted method.
processThumbnailProgress(float) - Method in class javax.imageio.ImageReader
Broadcasts the current percentage of thumbnail completion to all registered IIOReadProgressListeners by calling their thumbnailProgress method.
processThumbnailProgress(float) - Method in class javax.imageio.ImageWriter
Broadcasts the current percentage of thumbnail completion to all registered IIOWriteProgressListeners by calling their thumbnailProgress method.
processThumbnailStarted(int, int) - Method in class javax.imageio.ImageReader
Broadcasts the start of a thumbnail read to all registered IIOReadProgressListeners by calling their thumbnailStarted method.
processThumbnailStarted(int, int) - Method in class javax.imageio.ImageWriter
Broadcasts the start of a thumbnail write to all registered IIOWriteProgressListeners by calling their thumbnailStarted method.
processThumbnailUpdate(BufferedImage, int, int, int, int, int, int, int[]) - Method in class javax.imageio.ImageReader
Broadcasts the update of a set of samples in a thumbnail image to all registered IIOReadUpdateListeners by calling their thumbnailUpdate method.
processWarningOccurred(String) - Method in class javax.imageio.ImageReader
Broadcasts a warning message to all registered IIOReadWarningListeners by calling their warningOccurred method.
processWarningOccurred(String, String) - Method in class javax.imageio.ImageReader
Broadcasts a localized warning message to all registered IIOReadWarningListeners by calling their warningOccurred method with a string taken from a ResourceBundle.
processWarningOccurred(int, String) - Method in class javax.imageio.ImageWriter
Broadcasts a warning message to all registered IIOWriteWarningListeners by calling their warningOccurred method.
processWarningOccurred(int, String, String) - Method in class javax.imageio.ImageWriter
Broadcasts a localized warning message to all registered IIOWriteWarningListeners by calling their warningOccurred method with a string taken from a ResourceBundle.
processWindowEvent(WindowEvent) - Method in class java.awt.Window
Processes window events occurring on this window by dispatching them to any registered WindowListener objects.
processWindowEvent(WindowEvent) - Method in class javax.swing.JDialog
Handles window events depending on the state of the defaultCloseOperation property.
processWindowEvent(WindowEvent) - Method in class javax.swing.JFrame
Processes window events occurring on this component.
processWindowFocusEvent(WindowEvent) - Method in class java.awt.Window
Processes window focus event occuring on this window by dispatching them to any registered WindowFocusListener objects.
processWindowStateEvent(WindowEvent) - Method in class java.awt.Window
Processes window state event occuring on this window by dispatching them to any registered WindowStateListener objects.
processWriteAborted() - Method in class javax.imageio.ImageWriter
Broadcasts that the write has been aborted to all registered IIOWriteProgressListeners by calling their writeAborted method.
profile_data - Variable in class org.omg.IOP.TaggedProfile
The associated profile data.
ProfileDataException - Exception in java.awt.color
This exception is thrown when an error occurs in accessing or processing an ICC_Profile object.
ProfileDataException(String) - Constructor for exception java.awt.color.ProfileDataException
Constructs a ProfileDataException with the specified detail message.
ProfileIdHelper - Class in org.omg.IOP
Profile ID
ProfileIdHelper() - Constructor for class org.omg.IOP.ProfileIdHelper
profiles - Variable in class org.omg.IOP.IOR
An array of tagged profiles associated with this object reference.
program - Variable in class javax.sound.midi.VoiceStatus
The program number of the instrument that this voice is currently using.
PROGRAM_CHANGE - Static variable in class javax.sound.midi.ShortMessage
Command value for Program Change message (0xC0, or 192)
programChange(int) - Method in interface javax.sound.midi.MidiChannel
Changes a program (patch).
programChange(int, int) - Method in interface javax.sound.midi.MidiChannel
Changes the program using bank and program (patch) numbers.
PROGRESS - Static variable in interface java.util.jar.Pack200.Packer
The unpacker's progress as a percentage, as periodically updated by the unpacker.
PROGRESS - Static variable in interface java.util.jar.Pack200.Unpacker
The unpacker's progress as a percentage, as periodically updated by the unpacker.
PROGRESS_BAR - Static variable in class javax.accessibility.AccessibleRole
An object used to indicate how much of a task has been completed.
PROGRESS_BAR - Static variable in class javax.swing.plaf.synth.Region
ProgressBar region.
PROGRESS_MONITOR - Static variable in class javax.accessibility.AccessibleRole
A role indicating the object monitors the progress of some operation.
progressBar - Variable in class javax.swing.plaf.basic.BasicProgressBarUI
ProgressBarUI - Class in javax.swing.plaf
Pluggable look and feel interface for JProgressBar.
ProgressBarUI() - Constructor for class javax.swing.plaf.ProgressBarUI
progressiveMode - Variable in class javax.imageio.ImageWriteParam
The mode controlling progressive encoding, which must be set to one of the four MODE_* values, except MODE_EXPLICIT.
progressListeners - Variable in class javax.imageio.ImageReader
A List of currently registered IIOReadProgressListeners, initialized by default to null, which is synonymous with an empty List.
progressListeners - Variable in class javax.imageio.ImageWriter
A List of currently registered IIOWriteProgressListeners, initialized by default null, which is synonymous with an empty List.
ProgressMonitor - Class in javax.swing
A class to monitor the progress of some operation.
ProgressMonitor(Component, Object, String, int, int) - Constructor for class javax.swing.ProgressMonitor
Constructs a graphic object that shows progress, typically by filling in a rectangular bar as the process nears completion.
ProgressMonitor.AccessibleProgressMonitor - Class in javax.swing
AccessibleProgressMonitor implements accessibility support for the ProgressMonitor class.
ProgressMonitor.AccessibleProgressMonitor() - Constructor for class javax.swing.ProgressMonitor.AccessibleProgressMonitor
AccessibleProgressMonitor constructor
ProgressMonitorInputStream - Class in javax.swing
Monitors the progress of reading from some InputStream.
ProgressMonitorInputStream(Component, Object, InputStream) - Constructor for class javax.swing.ProgressMonitorInputStream
Constructs an object to monitor the progress of an input stream.
progressString - Variable in class javax.swing.JProgressBar
An optional string that can be displayed on the progress bar.
PROMPT - Static variable in class javax.swing.text.html.HTML.Attribute
propagatedFrom - Variable in class java.beans.beancontext.BeanContextEvent
The BeanContext from which this event was propagated
PROPERTIES - Static variable in interface java.awt.image.ImageObserver
This flag in the infoflags argument to imageUpdate indicates that the properties of the image are now available.
properties() - Method in interface java.util.jar.Pack200.Packer
Get the set of this engine's properties.
properties() - Method in interface java.util.jar.Pack200.Unpacker
Get the set of this engine's properties.
Properties - Class in java.util
The Properties class represents a persistent set of properties.
Properties() - Constructor for class java.util.Properties
Creates an empty property list with no default values.
Properties(Properties) - Constructor for class java.util.Properties
Creates an empty property list with the specified defaults.
properties() - Method in class javax.sound.midi.MidiFileFormat
Obtain an unmodifiable map of properties.
properties() - Method in class javax.sound.sampled.AudioFileFormat
Obtain an unmodifiable map of properties.
properties() - Method in class javax.sound.sampled.AudioFormat
Obtain an unmodifiable map of properties.
PROPERTY - Static variable in class org.w3c.dom.bootstrap.DOMImplementationRegistry
The system property to specify the DOMImplementationSource class names.
propertyChange(PropertyChangeEvent) - Method in class java.beans.beancontext.BeanContextSupport
subclasses may envelope to monitor child property changes.
propertyChange(PropertyChangeEvent) - Method in interface java.beans.PropertyChangeListener
This method gets called when a bound property is changed.
propertyChange(PropertyChangeEvent) - Method in class java.beans.PropertyChangeListenerProxy
Forwards the property change event to the listener delegate.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.JLayer
This method gets called when a bound property is changed.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.JList.AccessibleJList
Property Change Listener change method.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.JPopupMenu.AccessibleJPopupMenu
This method gets called when a bound property is changed.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.JScrollPane.AccessibleJScrollPane
This method gets called when a bound property is changed.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.JSpinner.DefaultEditor
Called by the JFormattedTextField PropertyChangeListener.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.JTable.AccessibleJTable
Track changes to selection model, column model, etc.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicButtonListener
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicColorChooserUI.PropertyHandler
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicComboBoxUI.PropertyChangeHandler
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicComboPopup.PropertyChangeHandler
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicDirectoryModel
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicEditorPaneUI
This method gets called when a bound property is changed on the associated JTextComponent.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicInternalFrameTitlePane.PropertyChangeHandler
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI.InternalFramePropertyChangeListener
Detects changes in state from the JInternalFrame and handles actions.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicLabelUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicListUI.PropertyChangeHandler
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicOptionPaneUI.PropertyChangeHandler
If the source of the PropertyChangeEvent e equals the optionPane and is one of the ICON_PROPERTY, MESSAGE_PROPERTY, OPTIONS_PROPERTY or INITIAL_VALUE_PROPERTY, validateComponent is invoked.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicRootPaneUI
Invoked when a property changes on the root pane.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicScrollBarUI.PropertyChangeHandler
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicScrollPaneUI.PropertyChangeHandler
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicSliderUI.PropertyChangeHandler
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicSplitPaneDivider
Property change event, presumably from the JSplitPane, will message updateOrientation if necessary.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicSplitPaneUI.PropertyHandler
Messaged from the JSplitPane the receiver is contained in.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI.PropertyChangeHandler
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicTextAreaUI
This method gets called when a bound property is changed on the associated JTextComponent.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicTextPaneUI
This method gets called when a bound property is changed on the associated JTextComponent.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicTextUI
This method gets called when a bound property is changed on the associated JTextComponent.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicToolBarUI.PropertyListener
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI.PropertyChangeHandler
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI.SelectionModelPropertyChangeHandler
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.metal.MetalComboBoxUI.MetalPropertyChangeListener
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.metal.MetalFileChooserUI.FilterComboBoxModel
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.metal.MetalRootPaneUI
Invoked when a property changes.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.metal.MetalSliderUI.MetalPropertyListener
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.metal.MetalTextFieldUI
This method gets called when a bound property is changed on the associated JTextComponent.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthButtonUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthColorChooserUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthComboBoxUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthDesktopIconUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthDesktopPaneUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthEditorPaneUI
This method gets called when a bound property is changed on the associated JTextComponent.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthInternalFrameUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthLabelUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthListUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthMenuBarUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthMenuItemUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthMenuUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthOptionPaneUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthPanelUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthPopupMenuUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthProgressBarUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthRootPaneUI
Invoked when a property changes on the root pane.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthScrollBarUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthScrollPaneUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthSeparatorUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthSliderUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthSpinnerUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthSplitPaneUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthTabbedPaneUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthTableHeaderUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthTableUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthTextAreaUI
This method gets called when a bound property is changed on the associated JTextComponent.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthTextFieldUI
This method gets called when a bound property is changed on the associated JTextComponent.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthTextPaneUI
This method gets called when a bound property is changed on the associated JTextComponent.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthToolBarUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthToolTipUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthTreeUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthViewportUI
propertyChange(PropertyChangeEvent) - Method in class javax.swing.ProgressMonitor.AccessibleProgressMonitor
This method gets called when a bound property is changed.
propertyChange(PropertyChangeEvent) - Method in class javax.swing.table.DefaultTableColumnModel
Property Change Listener change method.
PropertyChangeEvent - Class in java.beans
A "PropertyChange" event gets delivered whenever a bean changes a "bound" or "constrained" property.
PropertyChangeEvent(Object, String, Object, Object) - Constructor for class java.beans.PropertyChangeEvent
Constructs a new PropertyChangeEvent.
PropertyChangeListener - Interface in java.beans
A "PropertyChange" event gets fired whenever a bean changes a "bound" property.
propertyChangeListener - Variable in class javax.swing.plaf.basic.BasicColorChooserUI
propertyChangeListener - Variable in class javax.swing.plaf.basic.BasicComboBoxUI
This protected field is implementation specific.
propertyChangeListener - Variable in class javax.swing.plaf.basic.BasicComboPopup
This protected field is implementation specific.
propertyChangeListener - Variable in class javax.swing.plaf.basic.BasicInternalFrameTitlePane
propertyChangeListener - Variable in class javax.swing.plaf.basic.BasicInternalFrameUI
propertyChangeListener - Variable in class javax.swing.plaf.basic.BasicListUI
propertyChangeListener - Variable in class javax.swing.plaf.basic.BasicMenuItemUI
PropertyChangeListener returned from createPropertyChangeListener.
propertyChangeListener - Variable in class javax.swing.plaf.basic.BasicOptionPaneUI
propertyChangeListener - Variable in class javax.swing.plaf.basic.BasicScrollBarUI
propertyChangeListener - Variable in class javax.swing.plaf.basic.BasicSliderUI
propertyChangeListener - Variable in class javax.swing.plaf.basic.BasicSplitPaneUI
Instance of the PropertyChangeListener for this JSplitPane.
propertyChangeListener - Variable in class javax.swing.plaf.basic.BasicTabbedPaneUI
PropertyChangeListenerProxy - Class in java.beans
A class which extends the EventListenerProxy specifically for adding a PropertyChangeListener with a "bound" property.
PropertyChangeListenerProxy(String, PropertyChangeListener) - Constructor for class java.beans.PropertyChangeListenerProxy
Constructor which binds the PropertyChangeListener to a specific property.
PropertyChangeSupport - Class in java.beans
This is a utility class that can be used by beans that support bound properties.
PropertyChangeSupport(Object) - Constructor for class java.beans.PropertyChangeSupport
Constructs a PropertyChangeSupport object.
PropertyDescriptor - Class in java.beans
A PropertyDescriptor describes one property that a Java Bean exports via a pair of accessor methods.
PropertyDescriptor(String, Class<?>) - Constructor for class java.beans.PropertyDescriptor
Constructs a PropertyDescriptor for a property that follows the standard Java convention by having getFoo and setFoo accessor methods.
PropertyDescriptor(String, Class<?>, String, String) - Constructor for class java.beans.PropertyDescriptor
This constructor takes the name of a simple property, and method names for reading and writing the property.
PropertyDescriptor(String, Method, Method) - Constructor for class java.beans.PropertyDescriptor
This constructor takes the name of a simple property, and Method objects for reading and writing the property.
PropertyEditor - Interface in java.beans
A PropertyEditor class provides support for GUIs that want to allow users to edit a property value of a given type.
PropertyEditorManager - Class in java.beans
The PropertyEditorManager can be used to locate a property editor for any given type name.
PropertyEditorManager() - Constructor for class java.beans.PropertyEditorManager
PropertyEditorSupport - Class in java.beans
This is a support class to help build property editors.
PropertyEditorSupport() - Constructor for class java.beans.PropertyEditorSupport
Constructs a PropertyEditorSupport object.
PropertyEditorSupport(Object) - Constructor for class java.beans.PropertyEditorSupport
Constructs a PropertyEditorSupport object.
PropertyException - Exception in javax.xml.bind
This exception indicates that an error was encountered while getting or setting a property.
PropertyException(String) - Constructor for exception javax.xml.bind.PropertyException
Construct a PropertyException with the specified detail message.
PropertyException(String, String) - Constructor for exception javax.xml.bind.PropertyException
Construct a PropertyException with the specified detail message and vendor specific errorCode.
PropertyException(Throwable) - Constructor for exception javax.xml.bind.PropertyException
Construct a PropertyException with a linkedException.
PropertyException(String, Throwable) - Constructor for exception javax.xml.bind.PropertyException
Construct a PropertyException with the specified detail message and linkedException.
PropertyException(String, String, Throwable) - Constructor for exception javax.xml.bind.PropertyException
Construct a PropertyException with the specified detail message, vendor specific errorCode, and linkedException.
PropertyException(String, Object) - Constructor for exception javax.xml.bind.PropertyException
Construct a PropertyException whose message field is set based on the name of the property and value.toString().
propertyKey - Static variable in class javax.swing.plaf.basic.BasicHTML
Key to use for the html renderer when stored as a client property of a JComponent.
propertyListener - Variable in class javax.swing.plaf.basic.BasicToolBarUI
PROPERTYNAME - Static variable in interface java.beans.DesignMode
The standard value of the propertyName as fired from a BeanContext or other source of PropertyChangeEvents.
propertyNames() - Method in class java.util.Properties
Returns an enumeration of all the keys in this property list, including distinct keys in the default property list if a key of the same name has not already been found from the main properties list.
PropertyPermission - Class in java.util
This class is for property permissions.
PropertyPermission(String, String) - Constructor for class java.util.PropertyPermission
Creates a new PropertyPermission object with the specified name.
PropertyResourceBundle - Class in java.util
PropertyResourceBundle is a concrete subclass of ResourceBundle that manages resources for a locale using a set of static strings from a property file.
PropertyResourceBundle(InputStream) - Constructor for class java.util.PropertyResourceBundle
Creates a property resource bundle from an InputStream.
PropertyResourceBundle(Reader) - Constructor for class java.util.PropertyResourceBundle
Creates a property resource bundle from a Reader.
PropertyVetoException - Exception in java.beans
A PropertyVetoException is thrown when a proposed change to a property represents an unacceptable value.
PropertyVetoException(String, PropertyChangeEvent) - Constructor for exception java.beans.PropertyVetoException
Constructs a PropertyVetoException with a detailed message.
PROTECTED - Static variable in class java.lang.invoke.MethodHandles.Lookup
A single-bit mask representing protected access, which may contribute to the result of lookupModes.
PROTECTED - Static variable in class java.lang.reflect.修饰符
The int value representing the protected modifier.
ProtectionDomain - Class in java.security
This ProtectionDomain class encapsulates the characteristics of a domain, which encloses a set of classes whose instances are granted a set of permissions when being executed on behalf of a given set of Principals.
ProtectionDomain(CodeSource, PermissionCollection) - Constructor for class java.security.ProtectionDomain
Creates a new ProtectionDomain with the given CodeSource and Permissions.
ProtectionDomain(CodeSource, PermissionCollection, ClassLoader, Principal[]) - Constructor for class java.security.ProtectionDomain
Creates a new ProtectionDomain qualified by the given CodeSource, Permissions, ClassLoader and array of Principals.
PROTOCOL_PROVIDER_CLASS_LOADER - Static variable in class javax.management.remote.JMXConnectorFactory
Name of the attribute that specifies the class loader for loading protocol providers.
PROTOCOL_PROVIDER_CLASS_LOADER - Static variable in class javax.management.remote.JMXConnectorServerFactory
Name of the attribute that specifies the class loader for loading protocol providers.
PROTOCOL_PROVIDER_PACKAGES - Static variable in class javax.management.remote.JMXConnectorFactory
Name of the attribute that specifies the provider packages that are consulted when looking for the handler for a protocol.
PROTOCOL_PROVIDER_PACKAGES - Static variable in class javax.management.remote.JMXConnectorServerFactory
Name of the attribute that specifies the provider packages that are consulted when looking for the handler for a protocol.
PROTOCOL_VERSION_1 - Static variable in interface java.io.ObjectStreamConstants
A Stream Protocol Version.
PROTOCOL_VERSION_2 - Static variable in interface java.io.ObjectStreamConstants
A Stream Protocol Version.
ProtocolException - Exception in java.net
Thrown to indicate that there is an error in the underlying protocol, such as a TCP error.
ProtocolException(String) - Constructor for exception java.net.ProtocolException
Constructs a new ProtocolException with the specified detail message.
ProtocolException() - Constructor for exception java.net.ProtocolException
Constructs a new ProtocolException with no detail message.
ProtocolException - Exception in javax.xml.ws
The ProtocolException class is a base class for exceptions related to a specific protocol binding.
ProtocolException() - Constructor for exception javax.xml.ws.ProtocolException
Constructs a new protocol exception with null as its detail message.
ProtocolException(String) - Constructor for exception javax.xml.ws.ProtocolException
Constructs a new protocol exception with the specified detail message.
ProtocolException(String, Throwable) - Constructor for exception javax.xml.ws.ProtocolException
Constructs a new runtime exception with the specified detail message and cause.
ProtocolException(Throwable) - Constructor for exception javax.xml.ws.ProtocolException
Constructs a new runtime exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).
ProtocolFamily - Interface in java.net
Represents a family of communication protocols.
prototypeCellValueChanged - Static variable in class javax.swing.plaf.basic.BasicListUI
provideErrorFeedback(Component) - Method in class javax.swing.LookAndFeel
Invoked when the user attempts an invalid operation, such as pasting into an uneditable JTextField that has focus.
provideErrorFeedback(Component) - Method in class javax.swing.plaf.metal.MetalLookAndFeel
Invoked when the user attempts an invalid operation, such as pasting into an uneditable JTextField that has focus.
provider() - Method in class java.nio.channels.AsynchronousChannelGroup
Returns the provider that created this channel group.
provider() - Method in class java.nio.channels.AsynchronousServerSocketChannel
Returns the provider that created this channel.
provider() - Method in class java.nio.channels.AsynchronousSocketChannel
Returns the provider that created this channel.
provider() - Method in class java.nio.channels.SelectableChannel
Returns the provider that created this channel.
provider() - Method in class java.nio.channels.Selector
Returns the provider that created this channel.
provider() - Method in class java.nio.channels.spi.AbstractSelectableChannel
Returns the provider that created this channel.
provider() - Method in class java.nio.channels.spi.AbstractSelector
Returns the provider that created this channel.
provider() - Static method in class java.nio.channels.spi.AsynchronousChannelProvider
Returns the system-wide default asynchronous channel provider for this invocation of the Java virtual machine.
provider() - Static method in class java.nio.channels.spi.SelectorProvider
Returns the system-wide default selector provider for this invocation of the Java virtual machine.
provider() - Method in class java.nio.file.FileSystem
Returns the provider that created this file system.
Provider - Class in java.security
This class represents a "provider" for the Java Security API, where a provider implements some or all parts of Java Security.
Provider(String, double, String) - Constructor for class java.security.Provider
Constructs a provider with the specified name, version number, and information.
Provider<T> - Interface in javax.xml.ws
Service endpoints may implement the Provider interface as a dynamic alternative to an SEI.
Provider - Class in javax.xml.ws.spi
Service provider for ServiceDelegate and Endpoint objects.
Provider() - Constructor for class javax.xml.ws.spi.Provider
Creates a new instance of Provider
provider() - Static method in class javax.xml.ws.spi.Provider
Creates a new provider object.
Provider.Service - Class in java.security
The description of a security service.
Provider.Service(Provider, String, String, String, List<String>, Map<String, String>) - Constructor for class java.security.Provider.Service
Construct a new service.
PROVIDER_URL - Static variable in interface javax.naming.Context
Constant that holds the name of the environment property for specifying configuration information for the service provider to use.
ProviderException - Exception in java.security
A runtime exception for Provider exceptions (such as misconfiguration errors or unrecoverable internal errors), which may be subclassed by Providers to throw specialized, provider-specific runtime errors.
ProviderException() - Constructor for exception java.security.ProviderException
Constructs a ProviderException with no detail message.
ProviderException(String) - Constructor for exception java.security.ProviderException
Constructs a ProviderException with the specified detail message.
ProviderException(String, Throwable) - Constructor for exception java.security.ProviderException
Creates a ProviderException with the specified detail message and cause.
ProviderException(Throwable) - Constructor for exception java.security.ProviderException
Creates a ProviderException with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).
ProviderMismatchException - Exception in java.nio.file
Unchecked exception thrown when an attempt is made to invoke a method on an object created by one file system provider with a parameter created by a different file system provider.
ProviderMismatchException() - Constructor for exception java.nio.file.ProviderMismatchException
Constructs an instance of this class.
ProviderMismatchException(String) - Constructor for exception java.nio.file.ProviderMismatchException
Constructs an instance of this class.
ProviderNotFoundException - Exception in java.nio.file
Runtime exception thrown when a provider of the required type cannot be found.
ProviderNotFoundException() - Constructor for exception java.nio.file.ProviderNotFoundException
Constructs an instance of this class.
ProviderNotFoundException(String) - Constructor for exception java.nio.file.ProviderNotFoundException
Constructs an instance of this class.
proxy - Variable in class java.beans.beancontext.BeanContextServicesSupport
Delegate for the BeanContextServiceProvider.
Proxy - Class in java.lang.reflect
Proxy provides static methods for creating dynamic proxy classes and instances, and it is also the superclass of all dynamic proxy classes created by those methods.
Proxy(InvocationHandler) - Constructor for class java.lang.reflect.Proxy
Constructs a new Proxy instance from a subclass (typically, a dynamic proxy class) with the specified value for its invocation handler.
Proxy - Class in java.net
This class represents a proxy setting, typically a type (http, socks) and a socket address.
Proxy(Proxy.Type, SocketAddress) - Constructor for class java.net.Proxy
Creates an entry representing a PROXY connection.
Proxy.Type - Enum in java.net
Represents the proxy type.
ProxySelector - Class in java.net
Selects the proxy server to use, if any, when connecting to the network resource referenced by a URL.
ProxySelector() - Constructor for class java.net.ProxySelector
PseudoColumnUsage - Enum in java.sql
Enumeration for pseudo/hidden column usage.
PSource - Class in javax.crypto.spec
This class specifies the source for encoding input P in OAEP Padding, as defined in the PKCS #1 standard.
PSource(String) - Constructor for class javax.crypto.spec.PSource
Constructs a source of the encoding input P for OAEP padding as defined in the PKCS #1 standard using the specified PSource algorithm.
PSource.PSpecified - Class in javax.crypto.spec
This class is used to explicitly specify the value for encoding input P in OAEP Padding.
PSource.PSpecified(byte[]) - Constructor for class javax.crypto.spec.PSource.PSpecified
Constructs the source explicitly with the specified value p as the encoding input P.
PSSParameterSpec - Class in java.security.spec
This class specifies a parameter spec for RSA-PSS signature scheme, as defined in the PKCS#1 v2.1 standard.
PSSParameterSpec(String, String, AlgorithmParameterSpec, int, int) - Constructor for class java.security.spec.PSSParameterSpec
Creates a new PSSParameterSpec as defined in the PKCS #1 standard using the specified message digest, mask generation function, parameters for mask generation function, salt length, and trailer field values.
PSSParameterSpec(int) - Constructor for class java.security.spec.PSSParameterSpec
Creates a new PSSParameterSpec using the specified salt length and other default values as defined in PKCS#1.
ptLineDist(double, double, double, double, double, double) - Static method in class java.awt.geom.Line2D
Returns the distance from a point to a line.
ptLineDist(double, double) - Method in class java.awt.geom.Line2D
Returns the distance from a point to this line.
ptLineDist(Point2D) - Method in class java.awt.geom.Line2D
Returns the distance from a Point2D to this line.
ptLineDistSq(double, double, double, double, double, double) - Static method in class java.awt.geom.Line2D
Returns the square of the distance from a point to a line.
ptLineDistSq(double, double) - Method in class java.awt.geom.Line2D
Returns the square of the distance from a point to this line.
ptLineDistSq(Point2D) - Method in class java.awt.geom.Line2D
Returns the square of the distance from a specified Point2D to this line.
ptSegDist(double, double, double, double, double, double) - Static method in class java.awt.geom.Line2D
Returns the distance from a point to a line segment.
ptSegDist(double, double) - Method in class java.awt.geom.Line2D
Returns the distance from a point to this line segment.
ptSegDist(Point2D) - Method in class java.awt.geom.Line2D
Returns the distance from a Point2D to this line segment.
ptSegDistSq(double, double, double, double, double, double) - Static method in class java.awt.geom.Line2D
Returns the square of the distance from a point to a line segment.
ptSegDistSq(double, double) - Method in class java.awt.geom.Line2D
Returns the square of the distance from a point to this line segment.
ptSegDistSq(Point2D) - Method in class java.awt.geom.Line2D
Returns the square of the distance from a Point2D to this line segment.
PUBLIC - Static variable in class java.lang.invoke.MethodHandles.Lookup
A single-bit mask representing public access, which may contribute to the result of lookupModes.
PUBLIC - Static variable in interface java.lang.reflect.Member
Identifies the set of all public members of a class or interface, including inherited members.
PUBLIC - Static variable in class java.lang.reflect.修饰符
The int value representing the public modifier.
PUBLIC - Static variable in interface javax.swing.text.html.parser.DTDConstants
PUBLIC_KEY - Static variable in class javax.crypto.Cipher
Constant used to indicate the to-be-unwrapped key is a "public key".
PUBLIC_MEMBER - Interface in org.omg.CORBA
Constant to define a public member in the ValueMember class.
PUBLIC_XML_SCHEMA - Static variable in interface javax.sql.rowset.WebRowSet
The public identifier for the XML Schema definition that defines the XML tags and their valid values for a WebRowSet implementation.
PublicKey - Interface in java.security
A public key.
publicLookup() - Static method in class java.lang.invoke.MethodHandles
Returns a lookup object which is trusted minimally.
publish(LogRecord) - Method in class java.util.logging.ConsoleHandler
Publish a LogRecord.
publish(LogRecord) - Method in class java.util.logging.FileHandler
Format and publish a LogRecord.
publish(LogRecord) - Method in class java.util.logging.Handler
Publish a LogRecord.
publish(LogRecord) - Method in class java.util.logging.MemoryHandler
Store a LogRecord in an internal buffer.
publish(LogRecord) - Method in class java.util.logging.SocketHandler
Format and publish a LogRecord.
publish(LogRecord) - Method in class java.util.logging.StreamHandler
Format and publish a LogRecord.
publish(V...) - Method in class javax.swing.SwingWorker
Sends data chunks to the SwingWorker.process(java.util.List) method.
publish(String) - Method in class javax.xml.ws.Endpoint
Publishes this endpoint at the given address.
publish(String, Object) - Static method in class javax.xml.ws.Endpoint
Creates and publishes an endpoint for the specified implementor object at the given address.
publish(String, Object, WebServiceFeature...) - Static method in class javax.xml.ws.Endpoint
Creates and publishes an endpoint for the specified implementor object at the given address.
publish(Object) - Method in class javax.xml.ws.Endpoint
Publishes this endpoint at the provided server context.
publish(HttpContext) - Method in class javax.xml.ws.Endpoint
Publishes this endpoint at the provided server context.
purge() - Method in class java.util.concurrent.ThreadPoolExecutor
Tries to remove from the work queue all Future tasks that have been cancelled.
purge() - Method in class java.util.Timer
Removes all cancelled tasks from this timer's task queue.
purgeRelations() - Method in class javax.management.relation.RelationService
Purges the relations.
purgeRelations() - Method in interface javax.management.relation.RelationServiceMBean
Purges the relations.
push(EventQueue) - Method in class java.awt.EventQueue
Replaces the existing EventQueue with the specified one.
push(E) - Method in class java.util.ArrayDeque
Pushes an element onto the stack represented by this deque.
push(E) - Method in interface java.util.concurrent.BlockingDeque
Pushes an element onto the stack represented by this deque.
push(E) - Method in class java.util.concurrent.ConcurrentLinkedDeque
push(E) - Method in class java.util.concurrent.LinkedBlockingDeque
push(E) - Method in interface java.util.Deque
Pushes an element onto the stack represented by this deque (in other words, at the head of this deque) if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.
push(E) - Method in class java.util.LinkedList
Pushes an element onto the stack represented by this list.
push() - Method in class java.util.logging.MemoryHandler
Push any buffered output to the target Handler.
push(E) - Method in class java.util.Stack
Pushes an item onto the top of this stack.
PUSH_BUTTON - Static variable in class javax.accessibility.AccessibleRole
An object the user can manipulate to tell the application to do something.
pushBack() - Method in class java.io.StreamTokenizer
Causes the next call to the nextToken method of this tokenizer to return the current value in the ttype field, and not to modify the value in the nval or sval field.
PushbackInputStream - Class in java.io
A PushbackInputStream adds functionality to another input stream, namely the ability to "push back" or "unread" one byte.
PushbackInputStream(InputStream, int) - Constructor for class java.io.PushbackInputStream
Creates a PushbackInputStream with a pushback buffer of the specified size, and saves its argument, the input stream in, for later use.
PushbackInputStream(InputStream) - Constructor for class java.io.PushbackInputStream
Creates a PushbackInputStream and saves its argument, the input stream in, for later use.
PushbackReader - Class in java.io
A character-stream reader that allows characters to be pushed back into the stream.
PushbackReader(Reader, int) - Constructor for class java.io.PushbackReader
Creates a new pushback reader with a pushback buffer of the given size.
PushbackReader(Reader) - Constructor for class java.io.PushbackReader
Creates a new pushback reader with a one-character pushback buffer.
pushCharacterStyle() - Method in class javax.swing.text.html.HTMLDocument.HTMLReader
Pushes the current character style on a stack in preparation for forming a new nested character style.
pushContext() - Method in class org.xml.sax.helpers.NamespaceSupport
Start a new Namespace context.
put(Object, Object) - Method in class java.awt.RenderingHints
Maps the specified key to the specified value in this RenderingHints object.
put(String, boolean) - Method in class java.io.ObjectOutputStream.PutField
Put the value of the named boolean field into the persistent field.
put(String, byte) - Method in class java.io.ObjectOutputStream.PutField
Put the value of the named byte field into the persistent field.
put(String, char) - Method in class java.io.ObjectOutputStream.PutField
Put the value of the named char field into the persistent field.
put(String, short) - Method in class java.io.ObjectOutputStream.PutField
Put the value of the named short field into the persistent field.
put(String, int) - Method in class java.io.ObjectOutputStream.PutField
Put the value of the named int field into the persistent field.
put(String, long) - Method in class java.io.ObjectOutputStream.PutField
Put the value of the named long field into the persistent field.
put(String, float) - Method in class java.io.ObjectOutputStream.PutField
Put the value of the named float field into the persistent field.
put(String, double) - Method in class java.io.ObjectOutputStream.PutField
Put the value of the named double field into the persistent field.
put(String, Object) - Method in class java.io.ObjectOutputStream.PutField
Put the value of the named Object field into the persistent field.
put(URI, Map<String, List<String>>) - Method in class java.net.CookieHandler
Sets all the applicable cookies, examples are response header fields that are named Set-Cookie2, present in the response headers into a cookie cache.
put(URI, Map<String, List<String>>) - Method in class java.net.CookieManager
put(URI, URLConnection) - Method in class java.net.ResponseCache
The protocol handler calls this method after a resource has been retrieved, and the ResponseCache must decide whether or not to store the resource in its cache.
put(byte) - Method in class java.nio.ByteBuffer
Relative put method (optional operation).
put(int, byte) - Method in class java.nio.ByteBuffer
Absolute put method (optional operation).
put(ByteBuffer) - Method in class java.nio.ByteBuffer
Relative bulk put method (optional operation).
put(byte[], int, int) - Method in class java.nio.ByteBuffer
Relative bulk put method (optional operation).
put(byte[]) - Method in class java.nio.ByteBuffer
Relative bulk put method (optional operation).
put(char) - Method in class java.nio.CharBuffer
Relative put method (optional operation).
put(int, char) - Method in class java.nio.CharBuffer
Absolute put method (optional operation).
put(CharBuffer) - Method in class java.nio.CharBuffer
Relative bulk put method (optional operation).
put(char[], int, int) - Method in class java.nio.CharBuffer
Relative bulk put method (optional operation).
put(char[]) - Method in class java.nio.CharBuffer
Relative bulk put method (optional operation).
put(String, int, int) - Method in class java.nio.CharBuffer
Relative bulk put method (optional operation).
put(String) - Method in class java.nio.CharBuffer
Relative bulk put method (optional operation).
put(double) - Method in class java.nio.DoubleBuffer
Relative put method (optional operation).
put(int, double) - Method in class java.nio.DoubleBuffer
Absolute put method (optional operation).
put(DoubleBuffer) - Method in class java.nio.DoubleBuffer
Relative bulk put method (optional operation).
put(double[], int, int) - Method in class java.nio.DoubleBuffer
Relative bulk put method (optional operation).
put(double[]) - Method in class java.nio.DoubleBuffer
Relative bulk put method (optional operation).
put(float) - Method in class java.nio.FloatBuffer
Relative put method (optional operation).
put(int, float) - Method in class java.nio.FloatBuffer
Absolute put method (optional operation).
put(FloatBuffer) - Method in class java.nio.FloatBuffer
Relative bulk put method (optional operation).
put(float[], int, int) - Method in class java.nio.FloatBuffer
Relative bulk put method (optional operation).
put(float[]) - Method in class java.nio.FloatBuffer
Relative bulk put method (optional operation).
put(int) - Method in class java.nio.IntBuffer
Relative put method (optional operation).
put(int, int) - Method in class java.nio.IntBuffer
Absolute put method (optional operation).
put(IntBuffer) - Method in class java.nio.IntBuffer
Relative bulk put method (optional operation).
put(int[], int, int) - Method in class java.nio.IntBuffer
Relative bulk put method (optional operation).
put(int[]) - Method in class java.nio.IntBuffer
Relative bulk put method (optional operation).
put(long) - Method in class java.nio.LongBuffer
Relative put method (optional operation).
put(int, long) - Method in class java.nio.LongBuffer
Absolute put method (optional operation).
put(LongBuffer) - Method in class java.nio.LongBuffer
Relative bulk put method (optional operation).
put(long[], int, int) - Method in class java.nio.LongBuffer
Relative bulk put method (optional operation).
put(long[]) - Method in class java.nio.LongBuffer
Relative bulk put method (optional operation).
put(short) - Method in class java.nio.ShortBuffer
Relative put method (optional operation).
put(int, short) - Method in class java.nio.ShortBuffer
Absolute put method (optional operation).
put(ShortBuffer) - Method in class java.nio.ShortBuffer
Relative bulk put method (optional operation).
put(short[], int, int) - Method in class java.nio.ShortBuffer
Relative bulk put method (optional operation).
put(short[]) - Method in class java.nio.ShortBuffer
Relative bulk put method (optional operation).
put(Object, Object) - Method in class java.security.Provider
Sets the key property to have the specified value.
put(K, V) - Method in class java.util.AbstractMap
Associates the specified value with the specified key in this map (optional operation).
put(E) - Method in class java.util.concurrent.ArrayBlockingQueue
Inserts the specified element at the tail of this queue, waiting for space to become available if the queue is full.
put(E) - Method in interface java.util.concurrent.BlockingDeque
Inserts the specified element into the queue represented by this deque (in other words, at the tail of this deque), waiting if necessary for space to become available.
put(E) - Method in interface java.util.concurrent.BlockingQueue
Inserts the specified element into this queue, waiting if necessary for space to become available.
put(K, V) - Method in class java.util.concurrent.ConcurrentHashMap
Maps the specified key to the specified value in this table.
put(K, V) - Method in class java.util.concurrent.ConcurrentSkipListMap
Associates the specified value with the specified key in this map.
put(E) - Method in class java.util.concurrent.DelayQueue
Inserts the specified element into this delay queue.
put(E) - Method in class java.util.concurrent.LinkedBlockingDeque
put(E) - Method in class java.util.concurrent.LinkedBlockingQueue
Inserts the specified element at the tail of this queue, waiting if necessary for space to become available.
put(E) - Method in class java.util.concurrent.LinkedTransferQueue
Inserts the specified element at the tail of this queue.
put(E) - Method in class java.util.concurrent.PriorityBlockingQueue
Inserts the specified element into this priority queue.
put(E) - Method in class java.util.concurrent.SynchronousQueue
Adds the specified element to this queue, waiting if necessary for another thread to receive it.
put(K, V) - Method in class java.util.Dictionary
Maps the specified key to the specified value in this dictionary.
put(K, V) - Method in class java.util.EnumMap
Associates the specified value with the specified key in this map.
put(K, V) - Method in class java.util.HashMap
Associates the specified value with the specified key in this map.
put(K, V) - Method in class java.util.Hashtable
Maps the specified key to the specified value in this hashtable.
put(K, V) - Method in class java.util.IdentityHashMap
Associates the specified value with the specified key in this identity hash map.
put(Object, Object) - Method in class java.util.jar.Attributes
Associates the specified value with the specified attribute name (key) in this Map.
put(K, V) - Method in interface java.util.Map
Associates the specified value with the specified key in this map (optional operation).
put(String, String) - Method in class java.util.prefs.AbstractPreferences
Implements the put method as per the specification in Preferences.put(String,String).
put(String, String) - Method in class java.util.prefs.Preferences
Associates the specified value with the specified key in this preference node.
put(K, V) - Method in class java.util.TreeMap
Associates the specified value with the specified key in this map.
put(K, V) - Method in class java.util.WeakHashMap
Associates the specified value with the specified key in this map.
put(CompositeData) - Method in interface javax.management.openmbean.TabularData
Adds value to this TabularData instance.
put(Object, Object) - Method in class javax.management.openmbean.TabularDataSupport
This method simply calls put((CompositeData) value) and therefore ignores its key parameter which can be null.
put(CompositeData) - Method in class javax.management.openmbean.TabularDataSupport
put(String, Object) - Method in interface javax.naming.directory.Attributes
Adds a new attribute to the attribute set.
put(Attribute) - Method in interface javax.naming.directory.Attributes
Adds a new attribute to the attribute set.
put(String, Object) - Method in class javax.naming.directory.BasicAttributes
put(Attribute) - Method in class javax.naming.directory.BasicAttributes
put(PrinterStateReason, Severity) - Method in class javax.print.attribute.standard.PrinterStateReasons
Adds the given printer state reason to this printer state reasons attribute, associating it with the given severity level.
put(String, Object) - Method in class javax.script.AbstractScriptEngine
Sets the specified value with the specified key in the ENGINE_SCOPE Bindings of the protected context field.
put(String, Object) - Method in interface javax.script.Bindings
Set a named value.
put(String, Object) - Method in interface javax.script.ScriptEngine
Sets a key/value pair in the state of the ScriptEngine that may either create a Java Language Binding to be used in the execution of scripts or be used in some other way, depending on whether the key is reserved.
put(String, Object) - Method in class javax.script.ScriptEngineManager
Sets the specified key/value pair in the Global Scope.
put(String, Object) - Method in class javax.script.SimpleBindings
Sets the specified key/value in the underlying map field.
put(Object, Action) - Method in class javax.swing.ActionMap
Adds a binding for key to action.
put(KeyStroke, Object) - Method in class javax.swing.ComponentInputMap
Adds a binding for keyStroke to actionMapKey.
put(KeyStroke, Object) - Method in class javax.swing.InputMap
Adds a binding for keyStroke to actionMapKey.
put(Object, Object) - Method in class javax.swing.UIDefaults
Sets the value of key to value for all locales.
put(Object, Object) - Static method in class javax.swing.UIManager
Stores an object in the developer defaults.
put(Object, Object) - Method in class javax.xml.crypto.dom.DOMCryptoContext
This implementation uses an internal HashMap to map the key to the specified object.
put(Object, Object) - Method in interface javax.xml.crypto.XMLCryptoContext
Associates the specified value with the specified key in this context.
putAll(Map<?, ?>) - Method in class java.awt.RenderingHints
Copies all of the mappings from the specified Map to this RenderingHints.
putAll(Map<?, ?>) - Method in class java.security.Provider
Copies all of the mappings from the specified Map to this provider.
putAll(Map<? extends K, ? extends V>) - Method in class java.util.AbstractMap
Copies all of the mappings from the specified map to this map (optional operation).
putAll(Map<? extends K, ? extends V>) - Method in class java.util.concurrent.ConcurrentHashMap
Copies all of the mappings from the specified map to this one.
putAll(Map<? extends K, ? extends V>) - Method in class java.util.EnumMap
Copies all of the mappings from the specified map to this map.
putAll(Map<? extends K, ? extends V>) - Method in class java.util.HashMap
Copies all of the mappings from the specified map to this map.
putAll(Map<? extends K, ? extends V>) - Method in class java.util.Hashtable
Copies all of the mappings from the specified map to this hashtable.
putAll(Map<? extends K, ? extends V>) - Method in class java.util.IdentityHashMap
Copies all of the mappings from the specified map to this map.
putAll(Map<?, ?>) - Method in class java.util.jar.Attributes
Copies all of the attribute name-value mappings from the specified Attributes to this Map.
putAll(Map<? extends K, ? extends V>) - Method in interface java.util.Map
Copies all of the mappings from the specified map to this map (optional operation).
putAll(Map<? extends K, ? extends V>) - Method in class java.util.TreeMap
Copies all of the mappings from the specified map to this map.
putAll(Map<? extends K, ? extends V>) - Method in class java.util.WeakHashMap
Copies all of the mappings from the specified map to this map.
putAll(CompositeData[]) - Method in interface javax.management.openmbean.TabularData
Add all the elements in values to this TabularData instance.
putAll(Map<?, ?>) - Method in class javax.management.openmbean.TabularDataSupport
Add all the values contained in the specified map t to this TabularData instance.
putAll(CompositeData[]) - Method in class javax.management.openmbean.TabularDataSupport
Add all the elements in values to this TabularData instance.
putAll(Map<? extends String, ? extends Object>) - Method in interface javax.script.Bindings
Adds all the mappings in a given Map to this Bindings.
putAll(Map<? extends String, ? extends Object>) - Method in class javax.script.SimpleBindings
putAll is implemented using Map.putAll.
putBoolean(String, boolean) - Method in class java.util.prefs.AbstractPreferences
Implements the putBoolean method as per the specification in Preferences.putBoolean(String,boolean).
putBoolean(String, boolean) - Method in class java.util.prefs.Preferences
Associates a string representing the specified boolean value with the specified key in this preference node.
putByteArray(String, byte[]) - Method in class java.util.prefs.AbstractPreferences
Implements the putByteArray method as per the specification in Preferences.putByteArray(String,byte[]).
putByteArray(String, byte[]) - Method in class java.util.prefs.Preferences
Associates a string representing the specified byte array with the specified key in this preference node.
putChar(char) - Method in class java.nio.ByteBuffer
Relative put method for writing a char value (optional operation).
putChar(int, char) - Method in class java.nio.ByteBuffer
Absolute put method for writing a char value (optional operation).
putClientProperty(Object, Object) - Method in class javax.swing.JComponent
Adds an arbitrary key/value "client property" to this component.
putConstraint(String, Component, int, String, Component) - Method in class javax.swing.SpringLayout
Links edge e1 of component c1 to edge e2 of component c2, with a fixed distance between the edges.
putConstraint(String, Component, Spring, String, Component) - Method in class javax.swing.SpringLayout
Links edge e1 of component c1 to edge e2 of component c2.
putDefaults(Object[]) - Method in class javax.swing.UIDefaults
Puts all of the key/value pairs in the database and unconditionally generates one PropertyChangeEvent.
putDouble(double) - Method in class java.nio.ByteBuffer
Relative put method for writing a double value (optional operation).
putDouble(int, double) - Method in class java.nio.ByteBuffer
Absolute put method for writing a double value (optional operation).
putDouble(String, double) - Method in class java.util.prefs.AbstractPreferences
Implements the putDouble method as per the specification in Preferences.putDouble(String,double).
putDouble(String, double) - Method in class java.util.prefs.Preferences
Associates a string representing the specified double value with the specified key in this preference node.
putDTDHash(String, DTD) - Static method in class javax.swing.text.html.parser.DTD
putFields() - Method in class java.io.ObjectOutputStream
Retrieve the object used to buffer persistent fields to be written to the stream.
putFirst(E) - Method in interface java.util.concurrent.BlockingDeque
Inserts the specified element at the front of this deque, waiting if necessary for space to become available.
putFirst(E) - Method in class java.util.concurrent.LinkedBlockingDeque
putFloat(float) - Method in class java.nio.ByteBuffer
Relative put method for writing a float value (optional operation).
putFloat(int, float) - Method in class java.nio.ByteBuffer
Absolute put method for writing a float value (optional operation).
putFloat(String, float) - Method in class java.util.prefs.AbstractPreferences
Implements the putFloat method as per the specification in Preferences.putFloat(String,float).
putFloat(String, float) - Method in class java.util.prefs.Preferences
Associates a string representing the specified float value with the specified key in this preference node.
putIfAbsent(K, V) - Method in class java.util.concurrent.ConcurrentHashMap
If the specified key is not already associated with a value, associate it with the given value.
putIfAbsent(K, V) - Method in interface java.util.concurrent.ConcurrentMap
If the specified key is not already associated with a value, associate it with the given value.
putIfAbsent(K, V) - Method in class java.util.concurrent.ConcurrentSkipListMap
If the specified key is not already associated with a value, associate it with the given value.
putInt(int) - Method in class java.nio.ByteBuffer
Relative put method for writing an int value (optional operation).
putInt(int, int) - Method in class java.nio.ByteBuffer
Absolute put method for writing an int value (optional operation).
putInt(String, int) - Method in class java.util.prefs.AbstractPreferences
Implements the putInt method as per the specification in Preferences.putInt(String,int).
putInt(String, int) - Method in class java.util.prefs.Preferences
Associates a string representing the specified int value with the specified key in this preference node.
putLast(E) - Method in interface java.util.concurrent.BlockingDeque
Inserts the specified element at the end of this deque, waiting if necessary for space to become available.
putLast(E) - Method in class java.util.concurrent.LinkedBlockingDeque
putLayer(JComponent, int) - Static method in class javax.swing.JLayeredPane
Sets the layer property on a JComponent.
putLong(long) - Method in class java.nio.ByteBuffer
Relative put method for writing a long value (optional operation).
putLong(int, long) - Method in class java.nio.ByteBuffer
Absolute put method for writing a long value (optional operation).
putLong(String, long) - Method in class java.util.prefs.AbstractPreferences
Implements the putLong method as per the specification in Preferences.putLong(String,long).
putLong(String, long) - Method in class java.util.prefs.Preferences
Associates a string representing the specified long value with the specified key in this preference node.
putNamespacePrefix(String, String) - Method in class javax.xml.crypto.dom.DOMCryptoContext
This implementation uses an internal HashMap to map the URI to the specified prefix.
putNamespacePrefix(String, String) - Method in interface javax.xml.crypto.XMLCryptoContext
Maps the specified namespace URI to the specified prefix.
putNextEntry(ZipEntry) - Method in class java.util.jar.JarOutputStream
Begins writing a new JAR file entry and positions the stream to the start of the entry data.
putNextEntry(ZipEntry) - Method in class java.util.zip.ZipOutputStream
Begins writing a new ZIP file entry and positions the stream to the start of the entry data.
putProperty(Object, Object) - Method in class javax.swing.text.AbstractDocument
A convenience method for storing up a property value.
putProperty(Object, Object) - Method in interface javax.swing.text.Document
Associates a property with the document.
putService(Provider.Service) - Method in class java.security.Provider
Add a service.
putShort(short) - Method in class java.nio.ByteBuffer
Relative put method for writing a short value (optional operation).
putShort(int, short) - Method in class java.nio.ByteBuffer
Absolute put method for writing a short value (optional operation).
putSpi(String, String) - Method in class java.util.prefs.AbstractPreferences
Put the given key-value association into this preference node.
putValue(String, String) - Method in class java.util.jar.Attributes
Associates the specified value with the specified attribute name, specified as a String.
putValue(String, Object) - Method in interface javax.net.ssl.SSLSession
Binds the specified value object into the session's application layer data with the given name.
putValue(String, Object) - Method in class javax.swing.AbstractAction
Sets the Value associated with the specified key.
putValue(String, Object) - Method in interface javax.swing.Action
Sets one of this object's properties using the associated key.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类


Q-Index

请注意：本 java api 1.7Beta 规范不是最终稳定版，未来随着版本的更迭，本规范可能有更新。
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _

Q

QName - Class in javax.xml.namespace
QName represents a qualified name as defined in the XML specifications: XML Schema Part2: Datatypes specification, Namespaces in XML, Namespaces in XML Errata.
QName(String, String) - Constructor for class javax.xml.namespace.QName
QName constructor specifying the Namespace URI and local part.
QName(String, String, String) - Constructor for class javax.xml.namespace.QName
QName constructor specifying the Namespace URI, local part and prefix.
QName(String) - Constructor for class javax.xml.namespace.QName
QName constructor specifying the local part.
QOP - Static variable in class javax.security.sasl.Sasl
The name of a property that specifies the quality-of-protection to use.
QuadCurve2D - Class in java.awt.geom
The QuadCurve2D class defines a quadratic parametric curve segment in (x,y) coordinate space.
QuadCurve2D() - Constructor for class java.awt.geom.QuadCurve2D
This is an abstract class that cannot be instantiated directly.
QuadCurve2D.Double - Class in java.awt.geom
A quadratic parametric curve segment specified with double coordinates.
QuadCurve2D.Double() - Constructor for class java.awt.geom.QuadCurve2D.Double
Constructs and initializes a QuadCurve2D with coordinates (0, 0, 0, 0, 0, 0).
QuadCurve2D.Double(double, double, double, double, double, double) - Constructor for class java.awt.geom.QuadCurve2D.Double
Constructs and initializes a QuadCurve2D from the specified double coordinates.
QuadCurve2D.Float - Class in java.awt.geom
A quadratic parametric curve segment specified with float coordinates.
QuadCurve2D.Float() - Constructor for class java.awt.geom.QuadCurve2D.Float
Constructs and initializes a QuadCurve2D with coordinates (0, 0, 0, 0, 0, 0).
QuadCurve2D.Float(float, float, float, float, float, float) - Constructor for class java.awt.geom.QuadCurve2D.Float
Constructs and initializes a QuadCurve2D from the specified float coordinates.
quadrantRotate(int) - Method in class java.awt.geom.AffineTransform
Concatenates this transform with a transform that rotates coordinates by the specified number of quadrants.
quadrantRotate(int, double, double) - Method in class java.awt.geom.AffineTransform
Concatenates this transform with a transform that rotates coordinates by the specified number of quadrants around the specified anchor point.
quadTo(double, double, double, double) - Method in class java.awt.geom.Path2D.Double
Adds a curved segment, defined by two new points, to the path by drawing a Quadratic curve that intersects both the current coordinates and the specified coordinates (x2,y2), using the specified point (x1,y1) as a quadratic parametric control point.
quadTo(double, double, double, double) - Method in class java.awt.geom.Path2D.Float
Adds a curved segment, defined by two new points, to the path by drawing a Quadratic curve that intersects both the current coordinates and the specified coordinates (x2,y2), using the specified point (x1,y1) as a quadratic parametric control point.
quadTo(float, float, float, float) - Method in class java.awt.geom.Path2D.Float
Adds a curved segment, defined by two new points, to the path by drawing a Quadratic curve that intersects both the current coordinates and the specified coordinates (x2,y2), using the specified point (x1,y1) as a quadratic parametric control point.
quadTo(double, double, double, double) - Method in class java.awt.geom.Path2D
Adds a curved segment, defined by two new points, to the path by drawing a Quadratic curve that intersects both the current coordinates and the specified coordinates (x2,y2), using the specified point (x1,y1) as a quadratic parametric control point.
QualifiedNameable - Interface in javax.lang.model.element
A mixin interface for an element that has a qualified name.
QUARTO - Static variable in class java.awt.PageAttributes.MediaType
The MediaType instance for Quarto, 215 x 275 mm.
QUARTO - Static variable in class javax.print.attribute.standard.MediaSize.Other
Specifies the quarto size, 8.5 inches by 10.83 inches.
QUARTO - Static variable in class javax.print.attribute.standard.MediaSizeName
quarto size .
Query - Class in javax.management
Constructs query object constraints.
Query() - Constructor for class javax.management.Query
Basic constructor.
QUERY_STRING - Static variable in interface javax.xml.ws.handler.MessageContext
Standard property: Query string for request.
QueryEval - Class in javax.management
Allows a query to be performed in the context of a specific MBean server.
QueryEval() - Constructor for class javax.management.QueryEval
QueryExp - Interface in javax.management
Represents relational constraints similar to database query "where clauses".
queryMBeans(ObjectName, QueryExp) - Method in interface javax.management.MBeanServer
Gets MBeans controlled by the MBean server.
queryMBeans(ObjectName, QueryExp) - Method in interface javax.management.MBeanServerConnection
Gets MBeans controlled by the MBean server.
queryMBeans(ObjectName, MarshalledObject, Subject) - Method in interface javax.management.remote.rmi.RMIConnection
Handles the method MBeanServerConnection.queryMBeans(ObjectName, QueryExp).
queryMBeans(ObjectName, MarshalledObject, Subject) - Method in class javax.management.remote.rmi.RMIConnectionImpl
queryMBeans(ObjectName, MarshalledObject, Subject) - Method in class javax.management.remote.rmi.RMIConnectionImpl_Stub
queryNames(ObjectName, QueryExp) - Method in interface javax.management.MBeanServer
Gets the names of MBeans controlled by the MBean server.
queryNames(ObjectName, QueryExp) - Method in interface javax.management.MBeanServerConnection
Gets the names of MBeans controlled by the MBean server.
queryNames(ObjectName, MarshalledObject, Subject) - Method in interface javax.management.remote.rmi.RMIConnection
Handles the method MBeanServerConnection.queryNames(ObjectName, QueryExp).
queryNames(ObjectName, MarshalledObject, Subject) - Method in class javax.management.remote.rmi.RMIConnectionImpl
queryNames(ObjectName, MarshalledObject, Subject) - Method in class javax.management.remote.rmi.RMIConnectionImpl_Stub
QUESTION_DIALOG - Static variable in class javax.swing.JRootPane
Constant used for the windowDecorationStyle property.
QUESTION_MESSAGE - Static variable in class javax.swing.JOptionPane
Used for questions.
Queue<E> - Interface in java.util
A collection designed for holding elements prior to processing.
QUEUED_IN_DEVICE - Static variable in class javax.print.attribute.standard.JobStateReason
The job has been forwarded to a device or print system that is unable to send back status.
QueuedJobCount - Class in javax.print.attribute.standard
Class QueuedJobCount is an integer valued printing attribute that indicates the number of jobs in the printer whose JobState is either PENDING, PENDING_HELD, PROCESSING, or PROCESSING_STOPPED.
QueuedJobCount(int) - Constructor for class javax.print.attribute.standard.QueuedJobCount
Construct a new queued job count attribute with the given integer value.
quietlyInvoke() - Method in class java.util.concurrent.ForkJoinTask
Commences performing this task and awaits its completion if necessary, without returning its result or throwing its exception.
quietlyJoin() - Method in class java.util.concurrent.ForkJoinTask
Joins this task, without returning its result or throwing its exception.
quote(String) - Static method in class java.util.regex.Pattern
Returns a literal pattern String for the specified String.
quote(String) - Static method in class javax.management.ObjectName
Returns a quoted form of the given String, suitable for inclusion in an ObjectName.
quoteChar(int) - Method in class java.io.StreamTokenizer
Specifies that matching pairs of this character delimit string constants in this tokenizer.
quoteReplacement(String) - Static method in class java.util.regex.Matcher
Returns a literal replacement String for the specified String.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类

提交错误或意见
有关更多的 API 参考资料和开发人员文档，请参阅 Java SE 开发人员文档. 该文档包含更详细的、面向开发人员的描述，以及总体概述、术语定义、使用技巧和工作代码示例。
版权所有 © 1993, 2011, Oracle 及其联盟会员。保留所有权利。
草案 ea-b138

rtiilateee eaassjc/


R-Index

请注意：本 java api 1.7Beta 规范不是最终稳定版，未来随着版本的更迭，本规范可能有更新。
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _

R

RadialGradientPaint - Class in java.awt
The RadialGradientPaint class provides a way to fill a shape with a circular radial color gradient pattern.
RadialGradientPaint(float, float, float, float[], Color[]) - Constructor for class java.awt.RadialGradientPaint
Constructs a RadialGradientPaint with a default NO_CYCLE repeating method and SRGB color space, using the center as the focus point.
RadialGradientPaint(Point2D, float, float[], Color[]) - Constructor for class java.awt.RadialGradientPaint
Constructs a RadialGradientPaint with a default NO_CYCLE repeating method and SRGB color space, using the center as the focus point.
RadialGradientPaint(float, float, float, float[], Color[], MultipleGradientPaint.CycleMethod) - Constructor for class java.awt.RadialGradientPaint
Constructs a RadialGradientPaint with a default SRGB color space, using the center as the focus point.
RadialGradientPaint(Point2D, float, float[], Color[], MultipleGradientPaint.CycleMethod) - Constructor for class java.awt.RadialGradientPaint
Constructs a RadialGradientPaint with a default SRGB color space, using the center as the focus point.
RadialGradientPaint(float, float, float, float, float, float[], Color[], MultipleGradientPaint.CycleMethod) - Constructor for class java.awt.RadialGradientPaint
Constructs a RadialGradientPaint with a default SRGB color space.
RadialGradientPaint(Point2D, float, Point2D, float[], Color[], MultipleGradientPaint.CycleMethod) - Constructor for class java.awt.RadialGradientPaint
Constructs a RadialGradientPaint with a default SRGB color space.
RadialGradientPaint(Point2D, float, Point2D, float[], Color[], MultipleGradientPaint.CycleMethod, MultipleGradientPaint.ColorSpaceType, AffineTransform) - Constructor for class java.awt.RadialGradientPaint
Constructs a RadialGradientPaint.
RadialGradientPaint(Rectangle2D, float[], Color[], MultipleGradientPaint.CycleMethod) - Constructor for class java.awt.RadialGradientPaint
Constructs a RadialGradientPaint with a default SRGB color space.
RADIO_BUTTON - Static variable in class javax.accessibility.AccessibleRole
A specialized check box that will cause other radio buttons in the same group to become unchecked when this one is checked.
RADIO_BUTTON - Static variable in class javax.swing.plaf.synth.Region
RadioButton region.
RADIO_BUTTON_MENU_ITEM - Static variable in class javax.swing.plaf.synth.Region
RegionButtonMenuItem region.
radix() - Method in class java.util.Scanner
Returns this scanner's default radix.
RAISED - Static variable in class javax.swing.border.BevelBorder
Raised bevel type.
RAISED - Static variable in class javax.swing.border.EtchedBorder
Raised etched type.
random() - Static method in class java.lang.Math
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
random() - Static method in class java.lang.StrictMath
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
Random - Class in java.util
An instance of this class is used to generate a stream of pseudorandom numbers.
Random() - Constructor for class java.util.Random
Creates a new random number generator.
Random(long) - Constructor for class java.util.Random
Creates a new random number generator using a single long seed.
RandomAccess - Interface in java.util
Marker interface used by List implementations to indicate that they support fast (generally constant time) random access.
RandomAccessFile - Class in java.io
Instances of this class support both reading and writing to a random access file.
RandomAccessFile(String, String) - Constructor for class java.io.RandomAccessFile
Creates a random access file stream to read from, and optionally to write to, a file with the specified name.
RandomAccessFile(File, String) - Constructor for class java.io.RandomAccessFile
Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument.
RANDOMPIXELORDER - Static variable in interface java.awt.image.ImageConsumer
The pixels will be delivered in a random order.
randomUUID() - Static method in class java.util.UUID
Static factory to retrieve a type 4 (pseudo randomly generated) UUID.
RANGE - Static variable in class java.awt.JobAttributes.DefaultSelectionType
The DefaultSelectionType instance to use for specifying that a range of pages of the job should be printed.
range(E, E) - Static method in class java.util.EnumSet
Creates an enum set initially containing all of the elements in the range defined by the two specified endpoints.
Raster - Class in java.awt.image
A class representing a rectangular array of pixels.
Raster(SampleModel, Point) - Constructor for class java.awt.image.Raster
Constructs a Raster with the given SampleModel.
Raster(SampleModel, DataBuffer, Point) - Constructor for class java.awt.image.Raster
Constructs a Raster with the given SampleModel and DataBuffer.
Raster(SampleModel, DataBuffer, Rectangle, Point, Raster) - Constructor for class java.awt.image.Raster
Constructs a Raster with the given SampleModel, DataBuffer, and parent.
raster - Variable in class javax.imageio.IIOImage
The Raster being referenced.
RasterFormatException - Exception in java.awt.image
The RasterFormatException is thrown if there is invalid layout information in the Raster.
RasterFormatException(String) - Constructor for exception java.awt.image.RasterFormatException
Constructs a new RasterFormatException with the specified message.
RasterOp - Interface in java.awt.image
This interface describes single-input/single-output operations performed on Raster objects.
RAW_SEND_SIZE - Static variable in class javax.security.sasl.Sasl
The name of a property that specifies the maximum size of the raw send buffer in bytes of SaslClient/SaslServer.
RAW_TEXT - Static variable in class java.awt.im.InputMethodHighlight
Constant for the raw text state.
RAW_X509_CERTIFICATE_TYPE - Static variable in interface javax.xml.crypto.dsig.keyinfo.X509Data
URI identifying the binary (ASN.1 DER) X.509 Certificate KeyInfo type: http://www.w3.org/2000/09/xmldsig#rawX509Certificate.
RC2ParameterSpec - Class in javax.crypto.spec
This class specifies the parameters used with the RC2 algorithm.
RC2ParameterSpec(int) - Constructor for class javax.crypto.spec.RC2ParameterSpec
Constructs a parameter set for RC2 from the given effective key size (in bits).
RC2ParameterSpec(int, byte[]) - Constructor for class javax.crypto.spec.RC2ParameterSpec
Constructs a parameter set for RC2 from the given effective key size (in bits) and an 8-byte IV.
RC2ParameterSpec(int, byte[], int) - Constructor for class javax.crypto.spec.RC2ParameterSpec
Constructs a parameter set for RC2 from the given effective key size (in bits) and IV.
RC5ParameterSpec - Class in javax.crypto.spec
This class specifies the parameters used with the RC5 algorithm.
RC5ParameterSpec(int, int, int) - Constructor for class javax.crypto.spec.RC5ParameterSpec
Constructs a parameter set for RC5 from the given version, number of rounds and word size (in bits).
RC5ParameterSpec(int, int, int, byte[]) - Constructor for class javax.crypto.spec.RC5ParameterSpec
Constructs a parameter set for RC5 from the given version, number of rounds, word size (in bits), and IV.
RC5ParameterSpec(int, int, int, byte[], int) - Constructor for class javax.crypto.spec.RC5ParameterSpec
Constructs a parameter set for RC5 from the given version, number of rounds, word size (in bits), and IV.
RCDATA - Static variable in interface javax.swing.text.html.parser.DTDConstants
RCSID - Static variable in class javax.swing.undo.StateEdit
RCSID - Static variable in interface javax.swing.undo.StateEditable
Resource ID for this class.
Rdn - Class in javax.naming.ldap
This class represents a relative distinguished name, or RDN, which is a component of a distinguished name as specified by RFC 2253.
Rdn(Attributes) - Constructor for class javax.naming.ldap.Rdn
Constructs an Rdn from the given attribute set.
Rdn(String) - Constructor for class javax.naming.ldap.Rdn
Constructs an Rdn from the given string.
Rdn(Rdn) - Constructor for class javax.naming.ldap.Rdn
Constructs an Rdn from the given rdn.
Rdn(String, Object) - Constructor for class javax.naming.ldap.Rdn
Constructs an Rdn from the given attribute type and value.
read() - Method in class java.io.BufferedInputStream
See the general contract of the read method of InputStream.
read(byte[], int, int) - Method in class java.io.BufferedInputStream
Reads bytes from this byte-input stream into the specified byte array, starting at the given offset.
read() - Method in class java.io.BufferedReader
Reads a single character.
read(char[], int, int) - Method in class java.io.BufferedReader
Reads characters into a portion of an array.
read() - Method in class java.io.ByteArrayInputStream
Reads the next byte of data from this input stream.
read(byte[], int, int) - Method in class java.io.ByteArrayInputStream
Reads up to len bytes of data into an array of bytes from this input stream.
read() - Method in class java.io.CharArrayReader
Reads a single character.
read(char[], int, int) - Method in class java.io.CharArrayReader
Reads characters into a portion of an array.
read(byte[]) - Method in class java.io.DataInputStream
Reads some number of bytes from the contained input stream and stores them into the buffer array b.
read(byte[], int, int) - Method in class java.io.DataInputStream
Reads up to len bytes of data from the contained input stream into an array of bytes.
read() - Method in class java.io.FileInputStream
Reads a byte of data from this input stream.
read(byte[]) - Method in class java.io.FileInputStream
Reads up to b.length bytes of data from this input stream into an array of bytes.
read(byte[], int, int) - Method in class java.io.FileInputStream
Reads up to len bytes of data from this input stream into an array of bytes.
read() - Method in class java.io.FilterInputStream
Reads the next byte of data from this input stream.
read(byte[]) - Method in class java.io.FilterInputStream
Reads up to byte.length bytes of data from this input stream into an array of bytes.
read(byte[], int, int) - Method in class java.io.FilterInputStream
Reads up to len bytes of data from this input stream into an array of bytes.
read() - Method in class java.io.FilterReader
Reads a single character.
read(char[], int, int) - Method in class java.io.FilterReader
Reads characters into a portion of an array.
read() - Method in class java.io.InputStream
Reads the next byte of data from the input stream.
read(byte[]) - Method in class java.io.InputStream
Reads some number of bytes from the input stream and stores them into the buffer array b.
read(byte[], int, int) - Method in class java.io.InputStream
Reads up to len bytes of data from the input stream into an array of bytes.
read() - Method in class java.io.InputStreamReader
Reads a single character.
read(char[], int, int) - Method in class java.io.InputStreamReader
Reads characters into a portion of an array.
read() - Method in class java.io.LineNumberInputStream
Deprecated.
Reads the next byte of data from this input stream.
read(byte[], int, int) - Method in class java.io.LineNumberInputStream
Deprecated.
Reads up to len bytes of data from this input stream into an array of bytes.
read() - Method in class java.io.LineNumberReader
Read a single character.
read(char[], int, int) - Method in class java.io.LineNumberReader
Read characters into a portion of an array.
read() - Method in interface java.io.ObjectInput
Reads a byte of data.
read(byte[]) - Method in interface java.io.ObjectInput
Reads into an array of bytes.
read(byte[], int, int) - Method in interface java.io.ObjectInput
Reads into an array of bytes.
read() - Method in class java.io.ObjectInputStream
Reads a byte of data.
read(byte[], int, int) - Method in class java.io.ObjectInputStream
Reads into an array of bytes.
read() - Method in class java.io.PipedInputStream
Reads the next byte of data from this piped input stream.
read(byte[], int, int) - Method in class java.io.PipedInputStream
Reads up to len bytes of data from this piped input stream into an array of bytes.
read() - Method in class java.io.PipedReader
Reads the next character of data from this piped stream.
read(char[], int, int) - Method in class java.io.PipedReader
Reads up to len characters of data from this piped stream into an array of characters.
read() - Method in class java.io.PushbackInputStream
Reads the next byte of data from this input stream.
read(byte[], int, int) - Method in class java.io.PushbackInputStream
Reads up to len bytes of data from this input stream into an array of bytes.
read() - Method in class java.io.PushbackReader
Reads a single character.
read(char[], int, int) - Method in class java.io.PushbackReader
Reads characters into a portion of an array.
read() - Method in class java.io.RandomAccessFile
Reads a byte of data from this file.
read(byte[], int, int) - Method in class java.io.RandomAccessFile
Reads up to len bytes of data from this file into an array of bytes.
read(byte[]) - Method in class java.io.RandomAccessFile
Reads up to b.length bytes of data from this file into an array of bytes.
read(CharBuffer) - Method in class java.io.Reader
Attempts to read characters into the specified character buffer.
read() - Method in class java.io.Reader
Reads a single character.
read(char[]) - Method in class java.io.Reader
Reads characters into an array.
read(char[], int, int) - Method in class java.io.Reader
Reads characters into a portion of an array.
read() - Method in class java.io.SequenceInputStream
Reads the next byte of data from this input stream.
read(byte[], int, int) - Method in class java.io.SequenceInputStream
Reads up to len bytes of data from this input stream into an array of bytes.
read() - Method in class java.io.StringBufferInputStream
Deprecated.
Reads the next byte of data from this input stream.
read(byte[], int, int) - Method in class java.io.StringBufferInputStream
Deprecated.
Reads up to len bytes of data from this input stream into an array of bytes.
read() - Method in class java.io.StringReader
Reads a single character.
read(char[], int, int) - Method in class java.io.StringReader
Reads characters into a portion of an array.
read(CharBuffer) - Method in interface java.lang.Readable
Attempts to read characters into the specified character buffer.
read(ByteBuffer, A, CompletionHandler<Integer, ? super A>) - Method in interface java.nio.channels.AsynchronousByteChannel
Reads a sequence of bytes from this channel into the given buffer.
read(ByteBuffer) - Method in interface java.nio.channels.AsynchronousByteChannel
Reads a sequence of bytes from this channel into the given buffer.
read(ByteBuffer, long, A, CompletionHandler<Integer, ? super A>) - Method in class java.nio.channels.AsynchronousFileChannel
Reads a sequence of bytes from this channel into the given buffer, starting at the given file position.
read(ByteBuffer, long) - Method in class java.nio.channels.AsynchronousFileChannel
Reads a sequence of bytes from this channel into the given buffer, starting at the given file position.
read(ByteBuffer, long, TimeUnit, A, CompletionHandler<Integer, ? super A>) - Method in class java.nio.channels.AsynchronousSocketChannel
Reads a sequence of bytes from this channel into the given buffer.
read(ByteBuffer, A, CompletionHandler<Integer, ? super A>) - Method in class java.nio.channels.AsynchronousSocketChannel
read(ByteBuffer) - Method in class java.nio.channels.AsynchronousSocketChannel
read(ByteBuffer[], int, int, long, TimeUnit, A, CompletionHandler<Long, ? super A>) - Method in class java.nio.channels.AsynchronousSocketChannel
Reads a sequence of bytes from this channel into a subsequence of the given buffers.
read(ByteBuffer) - Method in class java.nio.channels.DatagramChannel
Reads a datagram from this channel.
read(ByteBuffer[], int, int) - Method in class java.nio.channels.DatagramChannel
Reads a datagram from this channel.
read(ByteBuffer[]) - Method in class java.nio.channels.DatagramChannel
Reads a datagram from this channel.
read(ByteBuffer) - Method in class java.nio.channels.FileChannel
Reads a sequence of bytes from this channel into the given buffer.
read(ByteBuffer[], int, int) - Method in class java.nio.channels.FileChannel
Reads a sequence of bytes from this channel into a subsequence of the given buffers.
read(ByteBuffer[]) - Method in class java.nio.channels.FileChannel
Reads a sequence of bytes from this channel into the given buffers.
read(ByteBuffer, long) - Method in class java.nio.channels.FileChannel
Reads a sequence of bytes from this channel into the given buffer, starting at the given file position.
read(ByteBuffer) - Method in interface java.nio.channels.ReadableByteChannel
Reads a sequence of bytes from this channel into the given buffer.
read(ByteBuffer[], int, int) - Method in interface java.nio.channels.ScatteringByteChannel
Reads a sequence of bytes from this channel into a subsequence of the given buffers.
read(ByteBuffer[]) - Method in interface java.nio.channels.ScatteringByteChannel
Reads a sequence of bytes from this channel into the given buffers.
read(ByteBuffer) - Method in interface java.nio.channels.SeekableByteChannel
Reads a sequence of bytes from this channel into the given buffer.
read(ByteBuffer) - Method in class java.nio.channels.SocketChannel
read(ByteBuffer[], int, int) - Method in class java.nio.channels.SocketChannel
read(ByteBuffer[]) - Method in class java.nio.channels.SocketChannel
read(CharBuffer) - Method in class java.nio.CharBuffer
Attempts to read characters into the specified character buffer.
read(String, ByteBuffer) - Method in interface java.nio.file.attribute.UserDefinedFileAttributeView
Read the value of a user-defined attribute into a buffer.
read(ObjectInput) - Static method in class java.rmi.server.ObjID
Constructs and returns a new ObjID instance by unmarshalling a binary representation from an ObjectInput instance.
read(DataInput) - Static method in class java.rmi.server.UID
Constructs and returns a new UID instance by unmarshalling a binary representation from an DataInput instance.
read() - Method in class java.security.DigestInputStream
Reads a byte, and updates the message digest (if the digest function is on).
read(byte[], int, int) - Method in class java.security.DigestInputStream
Reads into a byte array, and updates the message digest (if the digest function is on).
read(byte[], int, int) - Method in class java.util.jar.JarInputStream
Reads from the current JAR file entry into an array of bytes.
read(InputStream) - Method in class java.util.jar.Manifest
Reads the Manifest from the specified InputStream.
read() - Method in class java.util.zip.CheckedInputStream
Reads a byte.
read(byte[], int, int) - Method in class java.util.zip.CheckedInputStream
Reads into an array of bytes.
read() - Method in class java.util.zip.DeflaterInputStream
Reads a single byte of compressed data from the input stream.
read(byte[], int, int) - Method in class java.util.zip.DeflaterInputStream
Reads compressed data into a byte array.
read(byte[], int, int) - Method in class java.util.zip.GZIPInputStream
Reads uncompressed data into an array of bytes.
read() - Method in class java.util.zip.InflaterInputStream
Reads a byte of uncompressed data.
read(byte[], int, int) - Method in class java.util.zip.InflaterInputStream
Reads uncompressed data into an array of bytes.
read(byte[], int, int) - Method in class java.util.zip.ZipInputStream
Reads from the current ZIP entry into an array of bytes.
read() - Method in class javax.crypto.CipherInputStream
Reads the next byte of data from this input stream.
read(byte[]) - Method in class javax.crypto.CipherInputStream
Reads up to b.length bytes of data from this input stream into an array of bytes.
read(byte[], int, int) - Method in class javax.crypto.CipherInputStream
Reads up to len bytes of data from this input stream into an array of bytes.
read(File) - Static method in class javax.imageio.ImageIO
Returns a BufferedImage as the result of decoding a supplied File with an ImageReader chosen automatically from among those currently registered.
read(InputStream) - Static method in class javax.imageio.ImageIO
Returns a BufferedImage as the result of decoding a supplied InputStream with an ImageReader chosen automatically from among those currently registered.
read(URL) - Static method in class javax.imageio.ImageIO
Returns a BufferedImage as the result of decoding a supplied URL with an ImageReader chosen automatically from among those currently registered.
read(ImageInputStream) - Static method in class javax.imageio.ImageIO
Returns a BufferedImage as the result of decoding a supplied ImageInputStream with an ImageReader chosen automatically from among those currently registered.
read(int) - Method in class javax.imageio.ImageReader
Reads the image indexed by imageIndex and returns it as a complete BufferedImage, using a default ImageReadParam.
read(int, ImageReadParam) - Method in class javax.imageio.ImageReader
Reads the image indexed by imageIndex and returns it as a complete BufferedImage, using a supplied ImageReadParam.
read() - Method in class javax.imageio.stream.FileCacheImageInputStream
read(byte[], int, int) - Method in class javax.imageio.stream.FileCacheImageInputStream
read() - Method in class javax.imageio.stream.FileCacheImageOutputStream
read(byte[], int, int) - Method in class javax.imageio.stream.FileCacheImageOutputStream
read() - Method in class javax.imageio.stream.FileImageInputStream
read(byte[], int, int) - Method in class javax.imageio.stream.FileImageInputStream
read() - Method in class javax.imageio.stream.FileImageOutputStream
read(byte[], int, int) - Method in class javax.imageio.stream.FileImageOutputStream
read() - Method in interface javax.imageio.stream.ImageInputStream
Reads a single byte from the stream and returns it as an integer between 0 and 255.
read(byte[]) - Method in interface javax.imageio.stream.ImageInputStream
Reads up to b.length bytes from the stream, and stores them into b starting at index 0.
read(byte[], int, int) - Method in interface javax.imageio.stream.ImageInputStream
Reads up to len bytes from the stream, and stores them into b starting at index off.
read() - Method in class javax.imageio.stream.ImageInputStreamImpl
Reads a single byte from the stream and returns it as an int between 0 and 255.
read(byte[]) - Method in class javax.imageio.stream.ImageInputStreamImpl
A convenience method that calls read(b, 0, b.length).
read(byte[], int, int) - Method in class javax.imageio.stream.ImageInputStreamImpl
Reads up to len bytes from the stream, and stores them into b starting at index off.
read() - Method in class javax.imageio.stream.MemoryCacheImageInputStream
read(byte[], int, int) - Method in class javax.imageio.stream.MemoryCacheImageInputStream
read() - Method in class javax.imageio.stream.MemoryCacheImageOutputStream
read(byte[], int, int) - Method in class javax.imageio.stream.MemoryCacheImageOutputStream
read() - Method in class javax.sound.sampled.AudioInputStream
Reads the next byte of data from the audio input stream.
read(byte[]) - Method in class javax.sound.sampled.AudioInputStream
Reads some number of bytes from the audio input stream and stores them into the buffer array b.
read(byte[], int, int) - Method in class javax.sound.sampled.AudioInputStream
Reads up to a specified maximum number of bytes of data from the audio stream, putting them into the given byte array.
read(byte[], int, int) - Method in interface javax.sound.sampled.TargetDataLine
Reads audio data from the data line's input buffer.
read(InputStream, Object) - Method in class javax.swing.JEditorPane
This method initializes from a stream.
read() - Method in class javax.swing.ProgressMonitorInputStream
Overrides FilterInputStream.read to update the progress monitor after the read.
read(byte[]) - Method in class javax.swing.ProgressMonitorInputStream
Overrides FilterInputStream.read to update the progress monitor after the read.
read(byte[], int, int) - Method in class javax.swing.ProgressMonitorInputStream
Overrides FilterInputStream.read to update the progress monitor after the read.
read(InputStream, Document, int) - Method in class javax.swing.text.DefaultEditorKit
Inserts content from the given stream which is expected to be in a format appropriate for this kind of content handler.
read(Reader, Document, int) - Method in class javax.swing.text.DefaultEditorKit
Inserts content from the given stream, which will be treated as plain text.
read(InputStream, Document, int) - Method in class javax.swing.text.EditorKit
Inserts content from the given stream which is expected to be in a format appropriate for this kind of content handler.
read(Reader, Document, int) - Method in class javax.swing.text.EditorKit
Inserts content from the given stream which is expected to be in a format appropriate for this kind of content handler.
read(Reader, Document, int) - Method in class javax.swing.text.html.HTMLEditorKit
Inserts content from the given stream.
read(DataInputStream) - Method in class javax.swing.text.html.parser.DTD
Recreates a DTD from an archived format.
read(Reader, Object) - Method in class javax.swing.text.JTextComponent
Initializes from a stream.
read(InputStream, Document, int) - Method in class javax.swing.text.rtf.RTFEditorKit
Insert content from the given stream which is expected to be in a format appropriate for this kind of content handler.
read(Reader, Document, int) - Method in class javax.swing.text.rtf.RTFEditorKit
Insert content from the given stream, which will be treated as plain text.
read(InputStream) - Static method in class org.omg.CORBA.AnySeqHelper
read(InputStream) - Static method in class org.omg.CORBA.BooleanSeqHelper
read(InputStream) - Static method in class org.omg.CORBA.CharSeqHelper
read(InputStream) - Static method in class org.omg.CORBA.CompletionStatusHelper
read(InputStream) - Static method in class org.omg.CORBA.CurrentHelper
read(InputStream) - Static method in class org.omg.CORBA.DefinitionKindHelper
read(InputStream) - Static method in class org.omg.CORBA.DoubleSeqHelper
read(InputStream) - Static method in class org.omg.CORBA.FieldNameHelper
read(InputStream) - Static method in class org.omg.CORBA.FloatSeqHelper
read(InputStream) - Static method in class org.omg.CORBA.IdentifierHelper
read(InputStream) - Static method in class org.omg.CORBA.IDLTypeHelper
read(InputStream) - Static method in class org.omg.CORBA.LongLongSeqHelper
read(InputStream) - Static method in class org.omg.CORBA.LongSeqHelper
read(InputStream) - Static method in class org.omg.CORBA.NameValuePairHelper
read(InputStream) - Static method in class org.omg.CORBA.ObjectHelper
read(InputStream) - Static method in class org.omg.CORBA.OctetSeqHelper
read(InputStream) - Static method in class org.omg.CORBA.ParameterModeHelper
read(InputStream) - Static method in class org.omg.CORBA.PolicyErrorCodeHelper
read(InputStream) - Static method in class org.omg.CORBA.PolicyErrorHelper
read(InputStream) - Static method in class org.omg.CORBA.PolicyHelper
read(InputStream) - Static method in class org.omg.CORBA.PolicyListHelper
read(InputStream) - Static method in class org.omg.CORBA.PolicyTypeHelper
read() - Method in class org.omg.CORBA.portable.InputStream
read(InputStream) - Static method in class org.omg.CORBA.RepositoryIdHelper
read(InputStream) - Static method in class org.omg.CORBA.ServiceDetailHelper
read(InputStream) - Static method in class org.omg.CORBA.ServiceInformationHelper
read(InputStream) - Static method in class org.omg.CORBA.SetOverrideTypeHelper
read(InputStream) - Static method in class org.omg.CORBA.ShortSeqHelper
read(InputStream) - Static method in class org.omg.CORBA.StringSeqHelper
read(InputStream) - Static method in class org.omg.CORBA.StringValueHelper
read(InputStream) - Static method in class org.omg.CORBA.StructMemberHelper
read(InputStream) - Static method in class org.omg.CORBA.ULongLongSeqHelper
read(InputStream) - Static method in class org.omg.CORBA.ULongSeqHelper
read(InputStream) - Static method in class org.omg.CORBA.UnionMemberHelper
read(InputStream) - Static method in class org.omg.CORBA.UnknownUserExceptionHelper
read(InputStream) - Static method in class org.omg.CORBA.UShortSeqHelper
read(InputStream) - Static method in class org.omg.CORBA.ValueBaseHelper
read(InputStream) - Static method in class org.omg.CORBA.ValueMemberHelper
read(InputStream) - Static method in class org.omg.CORBA.VersionSpecHelper
read(InputStream) - Static method in class org.omg.CORBA.VisibilityHelper
read(InputStream) - Static method in class org.omg.CORBA.WCharSeqHelper
read(InputStream) - Static method in class org.omg.CORBA.WrongTransactionHelper
read(InputStream) - Static method in class org.omg.CORBA.WStringSeqHelper
read(InputStream) - Static method in class org.omg.CORBA.WStringValueHelper
read(InputStream) - Static method in class org.omg.CosNaming.BindingHelper
read(InputStream) - Static method in class org.omg.CosNaming.BindingIteratorHelper
read(InputStream) - Static method in class org.omg.CosNaming.BindingListHelper
read(InputStream) - Static method in class org.omg.CosNaming.BindingTypeHelper
read(InputStream) - Static method in class org.omg.CosNaming.IstringHelper
read(InputStream) - Static method in class org.omg.CosNaming.NameComponentHelper
read(InputStream) - Static method in class org.omg.CosNaming.NameHelper
read(InputStream) - Static method in class org.omg.CosNaming.NamingContextExtHelper
read(InputStream) - Static method in class org.omg.CosNaming.NamingContextExtPackage.AddressHelper
read(InputStream) - Static method in class org.omg.CosNaming.NamingContextExtPackage.InvalidAddressHelper
read(InputStream) - Static method in class org.omg.CosNaming.NamingContextExtPackage.StringNameHelper
read(InputStream) - Static method in class org.omg.CosNaming.NamingContextExtPackage.URLStringHelper
read(InputStream) - Static method in class org.omg.CosNaming.NamingContextHelper
read(InputStream) - Static method in class org.omg.CosNaming.NamingContextPackage.AlreadyBoundHelper
read(InputStream) - Static method in class org.omg.CosNaming.NamingContextPackage.CannotProceedHelper
read(InputStream) - Static method in class org.omg.CosNaming.NamingContextPackage.InvalidNameHelper
read(InputStream) - Static method in class org.omg.CosNaming.NamingContextPackage.NotEmptyHelper
read(InputStream) - Static method in class org.omg.CosNaming.NamingContextPackage.NotFoundHelper
read(InputStream) - Static method in class org.omg.CosNaming.NamingContextPackage.NotFoundReasonHelper
read(InputStream) - Static method in class org.omg.DynamicAny.AnySeqHelper
read(InputStream) - Static method in class org.omg.DynamicAny.DynAnyFactoryHelper
read(InputStream) - Static method in class org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCodeHelper
read(InputStream) - Static method in class org.omg.DynamicAny.DynAnyHelper
read(InputStream) - Static method in class org.omg.DynamicAny.DynAnyPackage.InvalidValueHelper
read(InputStream) - Static method in class org.omg.DynamicAny.DynAnyPackage.TypeMismatchHelper
read(InputStream) - Static method in class org.omg.DynamicAny.DynAnySeqHelper
read(InputStream) - Static method in class org.omg.DynamicAny.DynArrayHelper
read(InputStream) - Static method in class org.omg.DynamicAny.DynEnumHelper
read(InputStream) - Static method in class org.omg.DynamicAny.DynFixedHelper
read(InputStream) - Static method in class org.omg.DynamicAny.DynSequenceHelper
read(InputStream) - Static method in class org.omg.DynamicAny.DynStructHelper
read(InputStream) - Static method in class org.omg.DynamicAny.DynUnionHelper
read(InputStream) - Static method in class org.omg.DynamicAny.DynValueHelper
read(InputStream) - Static method in class org.omg.DynamicAny.FieldNameHelper
read(InputStream) - Static method in class org.omg.DynamicAny.NameDynAnyPairHelper
read(InputStream) - Static method in class org.omg.DynamicAny.NameDynAnyPairSeqHelper
read(InputStream) - Static method in class org.omg.DynamicAny.NameValuePairHelper
read(InputStream) - Static method in class org.omg.DynamicAny.NameValuePairSeqHelper
read(InputStream) - Static method in class org.omg.IOP.CodecFactoryHelper
read(InputStream) - Static method in class org.omg.IOP.CodecFactoryPackage.UnknownEncodingHelper
read(InputStream) - Static method in class org.omg.IOP.CodecPackage.FormatMismatchHelper
read(InputStream) - Static method in class org.omg.IOP.CodecPackage.InvalidTypeForEncodingHelper
read(InputStream) - Static method in class org.omg.IOP.CodecPackage.TypeMismatchHelper
read(InputStream) - Static method in class org.omg.IOP.ComponentIdHelper
read(InputStream) - Static method in class org.omg.IOP.IORHelper
read(InputStream) - Static method in class org.omg.IOP.MultipleComponentProfileHelper
read(InputStream) - Static method in class org.omg.IOP.ProfileIdHelper
read(InputStream) - Static method in class org.omg.IOP.ServiceContextHelper
read(InputStream) - Static method in class org.omg.IOP.ServiceContextListHelper
read(InputStream) - Static method in class org.omg.IOP.ServiceIdHelper
read(InputStream) - Static method in class org.omg.IOP.TaggedComponentHelper
read(InputStream) - Static method in class org.omg.IOP.TaggedProfileHelper
read(InputStream) - Static method in class org.omg.Messaging.SyncScopeHelper
read(InputStream) - Static method in class org.omg.PortableInterceptor.AdapterManagerIdHelper
read(InputStream) - Static method in class org.omg.PortableInterceptor.AdapterNameHelper
read(InputStream) - Static method in class org.omg.PortableInterceptor.AdapterStateHelper
read(InputStream) - Static method in class org.omg.PortableInterceptor.CurrentHelper
read(InputStream) - Static method in class org.omg.PortableInterceptor.ForwardRequestHelper
read(InputStream) - Static method in class org.omg.PortableInterceptor.InvalidSlotHelper
read(InputStream) - Static method in class org.omg.PortableInterceptor.IORInterceptor_3_0Helper
read(InputStream) - Static method in class org.omg.PortableInterceptor.ObjectIdHelper
read(InputStream) - Static method in class org.omg.PortableInterceptor.ObjectReferenceFactoryHelper
read(InputStream) - Static method in class org.omg.PortableInterceptor.ObjectReferenceTemplateHelper
read(InputStream) - Static method in class org.omg.PortableInterceptor.ObjectReferenceTemplateSeqHelper
read(InputStream) - Static method in class org.omg.PortableInterceptor.ORBIdHelper
read(InputStream) - Static method in class org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateNameHelper
read(InputStream) - Static method in class org.omg.PortableInterceptor.ORBInitInfoPackage.InvalidNameHelper
read(InputStream) - Static method in class org.omg.PortableInterceptor.ORBInitInfoPackage.ObjectIdHelper
read(InputStream) - Static method in class org.omg.PortableInterceptor.ServerIdHelper
read(InputStream) - Static method in class org.omg.PortableServer.CurrentHelper
read(InputStream) - Static method in class org.omg.PortableServer.CurrentPackage.NoContextHelper
read(InputStream) - Static method in class org.omg.PortableServer.ForwardRequestHelper
read(InputStream) - Static method in class org.omg.PortableServer.POAHelper
read(InputStream) - Static method in class org.omg.PortableServer.POAManagerPackage.AdapterInactiveHelper
read(InputStream) - Static method in class org.omg.PortableServer.POAPackage.AdapterAlreadyExistsHelper
read(InputStream) - Static method in class org.omg.PortableServer.POAPackage.AdapterNonExistentHelper
read(InputStream) - Static method in class org.omg.PortableServer.POAPackage.InvalidPolicyHelper
read(InputStream) - Static method in class org.omg.PortableServer.POAPackage.NoServantHelper
read(InputStream) - Static method in class org.omg.PortableServer.POAPackage.ObjectAlreadyActiveHelper
read(InputStream) - Static method in class org.omg.PortableServer.POAPackage.ObjectNotActiveHelper
read(InputStream) - Static method in class org.omg.PortableServer.POAPackage.ServantAlreadyActiveHelper
read(InputStream) - Static method in class org.omg.PortableServer.POAPackage.ServantNotActiveHelper
read(InputStream) - Static method in class org.omg.PortableServer.POAPackage.WrongAdapterHelper
read(InputStream) - Static method in class org.omg.PortableServer.POAPackage.WrongPolicyHelper
read(InputStream) - Static method in class org.omg.PortableServer.ServantActivatorHelper
read(InputStream) - Static method in class org.omg.PortableServer.ServantLocatorHelper
read_Abstract() - Method in interface org.omg.CORBA.DataInputStream
Reads an IDL Abstract interface from the input stream.
read_abstract_interface() - Method in class org.omg.CORBA_2_3.portable.InputStream
Unmarshal the value object or a suitable stub object.
read_abstract_interface(Class) - Method in class org.omg.CORBA_2_3.portable.InputStream
Unmarshal the class object or the stub class corresponding to the passed type.
read_any() - Method in interface org.omg.CORBA.DataInputStream
Reads an IDL Any value from the input stream.
read_any() - Method in class org.omg.CORBA.portable.InputStream
Reads an Any from this input stream.
read_any_array(AnySeqHolder, int, int) - Method in interface org.omg.CORBA.DataInputStream
Reads array of IDL Anys from offset for length elements from the input stream.
read_boolean() - Method in interface org.omg.CORBA.DataInputStream
Reads an IDL boolean value from the input stream.
read_boolean() - Method in class org.omg.CORBA.portable.InputStream
Reads a boolean value from this input stream.
read_boolean_array(BooleanSeqHolder, int, int) - Method in interface org.omg.CORBA.DataInputStream
Reads array of IDL booleans from offset for length elements from the input stream.
read_boolean_array(boolean[], int, int) - Method in class org.omg.CORBA.portable.InputStream
Reads an array of booleans from this input stream.
read_char() - Method in interface org.omg.CORBA.DataInputStream
Reads an IDL character value from the input stream.
read_char() - Method in class org.omg.CORBA.portable.InputStream
Reads a char value from this input stream.
read_char_array(CharSeqHolder, int, int) - Method in interface org.omg.CORBA.DataInputStream
Reads array of IDL characters from offset for length elements from the input stream.
read_char_array(char[], int, int) - Method in class org.omg.CORBA.portable.InputStream
Reads an array of chars from this input stream.
read_Context() - Method in class org.omg.CORBA.portable.InputStream
Reads a CORBA context from the stream.
read_double() - Method in interface org.omg.CORBA.DataInputStream
Reads an IDL double from the input stream.
read_double() - Method in class org.omg.CORBA.portable.InputStream
Reads a double value from this input stream.
read_double_array(DoubleSeqHolder, int, int) - Method in interface org.omg.CORBA.DataInputStream
Reads array of IDL doubles from offset for length elements from the input stream.
read_double_array(double[], int, int) - Method in class org.omg.CORBA.portable.InputStream
Reads an array of doubles from this input stream.
read_fixed() - Method in class org.omg.CORBA.portable.InputStream
Reads a BigDecimal number.
read_float() - Method in interface org.omg.CORBA.DataInputStream
Reads an IDL float from the input stream.
read_float() - Method in class org.omg.CORBA.portable.InputStream
Reads a float value from this input stream.
read_float_array(FloatSeqHolder, int, int) - Method in interface org.omg.CORBA.DataInputStream
Reads array of IDL floats from offset for length elements from the input stream.
read_float_array(float[], int, int) - Method in class org.omg.CORBA.portable.InputStream
Reads an array of floats from this input stream.
read_long() - Method in interface org.omg.CORBA.DataInputStream
Reads an IDL long from the input stream.
read_long() - Method in class org.omg.CORBA.portable.InputStream
Reads a CORBA long (that is, Java int) value from this input stream.
read_long_array(LongSeqHolder, int, int) - Method in interface org.omg.CORBA.DataInputStream
Reads array of IDL longs from offset for length elements from the input stream.
read_long_array(int[], int, int) - Method in class org.omg.CORBA.portable.InputStream
Reads an array of CORBA longs (that is, Java ints) from this input stream.
read_longlong() - Method in interface org.omg.CORBA.DataInputStream
Reads an IDL long long from the input stream.
read_longlong() - Method in class org.omg.CORBA.portable.InputStream
Reads a CORBA longlong (that is, Java long) value from this input stream.
read_longlong_array(LongLongSeqHolder, int, int) - Method in interface org.omg.CORBA.DataInputStream
Reads array of IDL long longs from offset for length elements from the input stream.
read_longlong_array(long[], int, int) - Method in class org.omg.CORBA.portable.InputStream
Reads an array of CORBA longlongs (that is, Java longs) from this input stream.
read_Object() - Method in interface org.omg.CORBA.DataInputStream
Reads an IDL CORBA::Object from the input stream.
read_Object() - Method in class org.omg.CORBA.portable.InputStream
Reads a CORBA object from this input stream.
read_Object(Class) - Method in class org.omg.CORBA.portable.InputStream
Unmarshals an object and returns a CORBA Object, which is an instance of the class passed as its argument.
read_octet() - Method in interface org.omg.CORBA.DataInputStream
Reads an IDL octet value from the input stream.
read_octet() - Method in class org.omg.CORBA.portable.InputStream
Reads an octet (that is, a byte) value from this input stream.
read_octet_array(OctetSeqHolder, int, int) - Method in interface org.omg.CORBA.DataInputStream
Reads array of IDL octets from offset for length elements from the input stream.
read_octet_array(byte[], int, int) - Method in class org.omg.CORBA.portable.InputStream
Reads an array of octets (that is, bytes) from this input stream.
READ_ONLY - Static variable in class java.nio.channels.FileChannel.MapMode
Mode for a read-only mapping.
read_Principal() - Method in class org.omg.CORBA.portable.InputStream
Deprecated.
Deprecated by CORBA 2.2.
read_short() - Method in interface org.omg.CORBA.DataInputStream
Reads an IDL short from the input stream.
read_short() - Method in class org.omg.CORBA.portable.InputStream
Reads a short value from this input stream.
read_short_array(ShortSeqHolder, int, int) - Method in interface org.omg.CORBA.DataInputStream
Reads array of IDL shorts from offset for length elements from the input stream.
read_short_array(short[], int, int) - Method in class org.omg.CORBA.portable.InputStream
Reads an array of shorts from this input stream.
read_string() - Method in interface org.omg.CORBA.DataInputStream
Reads an IDL string from the input stream.
read_string() - Method in class org.omg.CORBA.portable.InputStream
Reads a string value from this input stream.
read_TypeCode() - Method in interface org.omg.CORBA.DataInputStream
Reads an IDL typecode from the input stream.
read_TypeCode() - Method in class org.omg.CORBA.portable.InputStream
Reads a TypeCode from this input stream.
read_ulong() - Method in interface org.omg.CORBA.DataInputStream
Reads an IDL unsigned long from the input stream.
read_ulong() - Method in class org.omg.CORBA.portable.InputStream
Reads an unsigned CORBA long (that is, Java int) value from this input stream.
read_ulong_array(ULongSeqHolder, int, int) - Method in interface org.omg.CORBA.DataInputStream
Reads array of IDL unsigned longs from offset for length elements from the input stream.
read_ulong_array(int[], int, int) - Method in class org.omg.CORBA.portable.InputStream
Reads an array of unsigned CORBA longs (that is, Java ints) from this input stream.
read_ulonglong() - Method in interface org.omg.CORBA.DataInputStream
Reads an unsigned IDL long long from the input stream.
read_ulonglong() - Method in class org.omg.CORBA.portable.InputStream
Reads a CORBA unsigned longlong (that is, Java long) value from this input stream.
read_ulonglong_array(ULongLongSeqHolder, int, int) - Method in interface org.omg.CORBA.DataInputStream
Reads array of IDL unsigned long longs from offset for length elements from the input stream.
read_ulonglong_array(long[], int, int) - Method in class org.omg.CORBA.portable.InputStream
Reads an array of unsigned CORBA longlongs (that is, Java longs) from this input stream.
read_ushort() - Method in interface org.omg.CORBA.DataInputStream
Reads an IDL unsigned short from the input stream.
read_ushort() - Method in class org.omg.CORBA.portable.InputStream
Reads a unsigned short value from this input stream.
read_ushort_array(UShortSeqHolder, int, int) - Method in interface org.omg.CORBA.DataInputStream
Reads array of IDL unsigned shorts from offset for length elements from the input stream.
read_ushort_array(short[], int, int) - Method in class org.omg.CORBA.portable.InputStream
Reads an array of unsigned shorts from this input stream.
read_value(InputStream, TypeCode) - Method in class org.omg.CORBA.Any
Reads off (unmarshals) the value of an Any object from the given input stream using the given typecode.
read_Value() - Method in interface org.omg.CORBA.DataInputStream
Reads an IDL value type from the input stream.
read_value(InputStream) - Method in interface org.omg.CORBA.portable.BoxedValueHelper
read_value(InputStream) - Method in interface org.omg.CORBA.portable.ValueFactory
Is called by the ORB runtime while in the process of unmarshaling a value type.
read_value(InputStream) - Method in class org.omg.CORBA.StringValueHelper
read_value(InputStream) - Method in class org.omg.CORBA.WStringValueHelper
read_value() - Method in class org.omg.CORBA_2_3.portable.InputStream
Unmarshalls a value type from the input stream.
read_value(Class) - Method in class org.omg.CORBA_2_3.portable.InputStream
Unmarshalls a value type from the input stream.
read_value(BoxedValueHelper) - Method in class org.omg.CORBA_2_3.portable.InputStream
Unmarshalls a value type from the input stream.
read_value(String) - Method in class org.omg.CORBA_2_3.portable.InputStream
Unmarshalls a value type from the input stream.
read_value(Serializable) - Method in class org.omg.CORBA_2_3.portable.InputStream
Unmarshalls a value type from the input stream.
read_wchar() - Method in interface org.omg.CORBA.DataInputStream
Reads an IDL wide character value from the input stream.
read_wchar() - Method in class org.omg.CORBA.portable.InputStream
Reads a wide char value from this input stream.
read_wchar_array(WCharSeqHolder, int, int) - Method in interface org.omg.CORBA.DataInputStream
Reads array of IDL wide characters from offset for length elements from the input stream.
read_wchar_array(char[], int, int) - Method in class org.omg.CORBA.portable.InputStream
Reads an array of wide chars from this input stream.
READ_WRITE - Static variable in class java.nio.channels.FileChannel.MapMode
Mode for a read/write mapping.
read_wstring() - Method in interface org.omg.CORBA.DataInputStream
Reads an IDL wide string from the input stream.
read_wstring() - Method in class org.omg.CORBA.portable.InputStream
Reads a wide string value from this input stream.
Readable - Interface in java.lang
A Readable is a source of characters.
ReadableByteChannel - Interface in java.nio.channels
A channel that can read bytes.
readAborted(ImageReader) - Method in interface javax.imageio.event.IIOReadProgressListener
Reports that a read has been aborted via the reader's abort method.
readAll(int, ImageReadParam) - Method in class javax.imageio.ImageReader
Reads the image indexed by imageIndex and returns an IIOImage containing the image, thumbnails, and associated image metadata, using a supplied ImageReadParam.
readAll(Iterator<? extends ImageReadParam>) - Method in class javax.imageio.ImageReader
Returns an Iterator containing all the images, thumbnails, and metadata, starting at the index given by getMinIndex, from the input source in the form of IIOImage objects.
readAllBytes(Path) - Static method in class java.nio.file.Files
Read all the bytes from a file.
readAllLines(Path, Charset) - Static method in class java.nio.file.Files
Read all lines from a file.
readAny(InputStream) - Static method in class javax.rmi.CORBA.Util
Reads a java.lang.Object as a CORBA any.
readAny(InputStream) - Method in interface javax.rmi.CORBA.UtilDelegate
Delegation call for Util.readAny(org.omg.CORBA.portable.InputStream).
readArray() - Method in interface java.sql.SQLInput
Reads an SQL ARRAY value from the stream and returns it as an Array object in the Java programming language.
readArray() - Method in class javax.sql.rowset.serial.SQLInputImpl
Reads an SQL ARRAY value from the stream and returns it as an Array object in the Java programming language.
readAsciiStream() - Method in interface java.sql.SQLInput
Reads the next attribute in the stream and returns it as a stream of ASCII characters.
readAsciiStream() - Method in class javax.sql.rowset.serial.SQLInputImpl
Returns the next attribute in this SQLInputImpl object as a stream of ASCII characters.
readAsRenderedImage(int, ImageReadParam) - Method in class javax.imageio.ImageReader
Returns a RenderedImage object that contains the contents of the image indexed by imageIndex.
readAttributes() - Method in interface java.nio.file.attribute.BasicFileAttributeView
Reads the basic file attributes as a bulk operation.
readAttributes() - Method in interface java.nio.file.attribute.DosFileAttributeView
readAttributes() - Method in interface java.nio.file.attribute.PosixFileAttributeView
readAttributes(Path, Class<A>, LinkOption...) - Static method in class java.nio.file.Files
Reads a file's attributes as a bulk operation.
readAttributes(Path, String, LinkOption...) - Static method in class java.nio.file.Files
Reads a set of file attributes as a bulk operation.
readAttributes(Path, Class<A>, LinkOption...) - Method in class java.nio.file.spi.FileSystemProvider
Reads a file's attributes as a bulk operation.
readAttributes(Path, String, LinkOption...) - Method in class java.nio.file.spi.FileSystemProvider
Reads a set of file attributes as a bulk operation.
readAttributes(ObjectInputStream, MutableAttributeSet) - Method in class javax.swing.text.StyleContext
Context-specific handling of reading in attributes
readAttributeSet(ObjectInputStream, MutableAttributeSet) - Static method in class javax.swing.text.StyleContext
Reads a set of attributes from the given object input stream that have been previously written out with writeAttributeSet.
readBigDecimal() - Method in interface java.sql.SQLInput
Reads the next attribute in the stream and returns it as a java.math.BigDecimal object in the Java programming language.
readBigDecimal() - Method in class javax.sql.rowset.serial.SQLInputImpl
Retrieves the next attribute in this SQLInputImpl object as a java.math.BigDecimal.
readBinaryStream() - Method in interface java.sql.SQLInput
Reads the next attribute in the stream and returns it as a stream of uninterpreted bytes.
readBinaryStream() - Method in class javax.sql.rowset.serial.SQLInputImpl
Returns the next attribute in this SQLInputImpl object as a stream of uninterpreted bytes.
readBit() - Method in interface javax.imageio.stream.ImageInputStream
Reads a single bit from the stream and returns it as an int with the value 0 or 1.
readBit() - Method in class javax.imageio.stream.ImageInputStreamImpl
readBits(int) - Method in interface javax.imageio.stream.ImageInputStream
Reads a bitstring from the stream and returns it as a long, with the first bit read becoming the most significant bit of the output.
readBits(int) - Method in class javax.imageio.stream.ImageInputStreamImpl
readBlob() - Method in interface java.sql.SQLInput
Reads an SQL BLOB value from the stream and returns it as a Blob object in the Java programming language.
readBlob() - Method in class javax.sql.rowset.serial.SQLInputImpl
Retrieves the BLOB value at the head of this SQLInputImpl object as a Blob object in the Java programming language.
readBoolean() - Method in interface java.io.DataInput
Reads one input byte and returns true if that byte is nonzero, false if that byte is zero.
readBoolean() - Method in class java.io.DataInputStream
See the general contract of the readBoolean method of DataInput.
readBoolean() - Method in class java.io.ObjectInputStream
Reads in a boolean.
readBoolean() - Method in class java.io.RandomAccessFile
Reads a boolean from this file.
readBoolean() - Method in interface java.sql.SQLInput
Reads the next attribute in the stream and returns it as a boolean in the Java programming language.
readBoolean() - Method in interface javax.imageio.stream.ImageInputStream
Reads a byte from the stream and returns a boolean value of true if it is nonzero, false if it is zero.
readBoolean() - Method in class javax.imageio.stream.ImageInputStreamImpl
readBoolean() - Method in class javax.sql.rowset.serial.SQLInputImpl
Retrieves the next attribute in this SQLInputImpl object as a boolean in the Java programming language.
readByte() - Method in interface java.io.DataInput
Reads and returns one input byte.
readByte() - Method in class java.io.DataInputStream
See the general contract of the readByte method of DataInput.
readByte() - Method in class java.io.ObjectInputStream
Reads an 8 bit byte.
readByte() - Method in class java.io.RandomAccessFile
Reads a signed eight-bit value from this file.
readByte() - Method in interface java.sql.SQLInput
Reads the next attribute in the stream and returns it as a byte in the Java programming language.
readByte() - Method in interface javax.imageio.stream.ImageInputStream
Reads a byte from the stream and returns it as a byte value.
readByte() - Method in class javax.imageio.stream.ImageInputStreamImpl
readByte() - Method in class javax.sql.rowset.serial.SQLInputImpl
Retrieves the next attribute in this SQLInputImpl object as a byte in the Java programming language.
readBytes() - Method in interface java.sql.SQLInput
Reads the next attribute in the stream and returns it as an array of bytes in the Java programming language.
readBytes(IIOByteBuffer, int) - Method in interface javax.imageio.stream.ImageInputStream
Reads up to len bytes from the stream, and modifies the supplied IIOByteBuffer to indicate the byte array, offset, and length where the data may be found.
readBytes(IIOByteBuffer, int) - Method in class javax.imageio.stream.ImageInputStreamImpl
readBytes() - Method in class javax.sql.rowset.serial.SQLInputImpl
Retrieves the next attribute in this SQLInputImpl object as an array of bytes.
readChar() - Method in interface java.io.DataInput
Reads two input bytes and returns a char value.
readChar() - Method in class java.io.DataInputStream
See the general contract of the readChar method of DataInput.
readChar() - Method in class java.io.ObjectInputStream
Reads a 16 bit char.
readChar() - Method in class java.io.RandomAccessFile
Reads a character from this file.
readChar() - Method in interface javax.imageio.stream.ImageInputStream
Equivalent to readUnsignedShort, except that the result is returned using the char datatype.
readChar() - Method in class javax.imageio.stream.ImageInputStreamImpl
readCharacterStream() - Method in interface java.sql.SQLInput
Reads the next attribute in the stream and returns it as a stream of Unicode characters.
readCharacterStream() - Method in class javax.sql.rowset.serial.SQLInputImpl
Retrieves the next attribute in this SQLInputImpl object as a stream of Unicode characters.
readChildren(ObjectInputStream) - Method in class java.beans.beancontext.BeanContextSupport
When an instance of this class is used as a delegate for the implementation of the BeanContext protocols (and its subprotocols) there exists a 'chicken and egg' problem during deserialization
readClassDescriptor() - Method in class java.io.ObjectInputStream
Read a class descriptor from the serialization stream.
readClob() - Method in interface java.sql.SQLInput
Reads an SQL CLOB value from the stream and returns it as a Clob object in the Java programming language.
readClob() - Method in class javax.sql.rowset.serial.SQLInputImpl
Retrieves the CLOB value at the head of this SQLInputImpl object as a Clob object in the Java programming language.
readConfiguration() - Method in class java.util.logging.LogManager
Reinitialize the logging properties and reread the logging configuration.
readConfiguration(InputStream) - Method in class java.util.logging.LogManager
Reinitialize the logging properties and reread the logging configuration from the given stream, which should be in java.util.Properties format.
readData(RowSetInternal) - Method in interface javax.sql.RowSetReader
Reads the new contents of the calling RowSet object.
readDate() - Method in interface java.sql.SQLInput
Reads the next attribute in the stream and returns it as a java.sql.Date object.
readDate() - Method in class javax.sql.rowset.serial.SQLInputImpl
Retrieves the next attribute in this SQLInputImpl as a java.sql.Date object.
readDouble() - Method in interface java.io.DataInput
Reads eight input bytes and returns a double value.
readDouble() - Method in class java.io.DataInputStream
See the general contract of the readDouble method of DataInput.
readDouble() - Method in class java.io.ObjectInputStream
Reads a 64 bit double.
readDouble() - Method in class java.io.RandomAccessFile
Reads a double from this file.
readDouble() - Method in interface java.sql.SQLInput
Reads the next attribute in the stream and returns it as a double in the Java programming language.
readDouble() - Method in interface javax.imageio.stream.ImageInputStream
Reads 8 bytes from the stream, and (conceptually) concatenates them according to the current byte order and returns the result as a double.
readDouble() - Method in class javax.imageio.stream.ImageInputStreamImpl
readDouble() - Method in class javax.sql.rowset.serial.SQLInputImpl
Retrieves the next attribute in this SQLInputImpl object as a double in the Java programming language.
readEndpointReference(Source) - Method in class javax.xml.ws.spi.Provider
read an EndpointReference from the infoset contained in eprInfoset.
reader() - Method in class java.io.Console
Retrieves the unique Reader object associated with this console.
Reader - Class in java.io
Abstract class for reading character streams.
Reader() - Constructor for class java.io.Reader
Creates a new character-stream reader whose critical sections will synchronize on the reader itself.
Reader(Object) - Constructor for class java.io.Reader
Creates a new character-stream reader whose critical sections will synchronize on the given object.
reader - Variable in class javax.script.SimpleScriptContext
This is the reader to be used for input from scripts.
readerSpiNames - Variable in class javax.imageio.spi.ImageWriterSpi
An array of strings to be returned from getImageReaderSpiNames, initially null.
readerSupportsThumbnails() - Method in class javax.imageio.ImageReader
Returns true if the image format understood by this reader supports thumbnail preview images associated with it.
readExternal(ObjectInput) - Method in class java.awt.datatransfer.DataFlavor
Restores this DataFlavor from a Serialized state.
readExternal(ObjectInput) - Method in interface java.io.Externalizable
The object implements the readExternal method to restore its contents by calling the methods of DataInput for primitive types and readObject for objects, strings and arrays.
readExternal(ObjectInput) - Method in class javax.activation.MimeType
The object implements the readExternal method to restore its contents by calling the methods of DataInput for primitive types and readObject for objects, strings and arrays.
readExternal(ObjectInput) - Method in class javax.management.loading.MLet
Restore this MLet's contents from the given ObjectInput.
readFields() - Method in class java.io.ObjectInputStream
Reads the persistent fields from the stream and makes them available by name.
readFloat() - Method in interface java.io.DataInput
Reads four input bytes and returns a float value.
readFloat() - Method in class java.io.DataInputStream
See the general contract of the readFloat method of DataInput.
readFloat() - Method in class java.io.ObjectInputStream
Reads a 32 bit float.
readFloat() - Method in class java.io.RandomAccessFile
Reads a float from this file.
readFloat() - Method in interface java.sql.SQLInput
Reads the next attribute in the stream and returns it as a float in the Java programming language.
readFloat() - Method in interface javax.imageio.stream.ImageInputStream
Reads 4 bytes from the stream, and (conceptually) concatenates them according to the current byte order and returns the result as a float.
readFloat() - Method in class javax.imageio.stream.ImageInputStreamImpl
readFloat() - Method in class javax.sql.rowset.serial.SQLInputImpl
Retrieves the next attribute in this SQLInputImpl object as a float in the Java programming language.
readFrom(Source) - Static method in class javax.xml.ws.EndpointReference
Factory method to read an EndpointReference from the infoset contained in eprInfoset.
readFully(byte[]) - Method in interface java.io.DataInput
Reads some bytes from an input stream and stores them into the buffer array b.
readFully(byte[], int, int) - Method in interface java.io.DataInput
Reads len bytes from an input stream.
readFully(byte[]) - Method in class java.io.DataInputStream
See the general contract of the readFully method of DataInput.
readFully(byte[], int, int) - Method in class java.io.DataInputStream
See the general contract of the readFully method of DataInput.
readFully(byte[]) - Method in class java.io.ObjectInputStream
Reads bytes, blocking until all bytes are read.
readFully(byte[], int, int) - Method in class java.io.ObjectInputStream
Reads bytes, blocking until all bytes are read.
readFully(byte[]) - Method in class java.io.RandomAccessFile
Reads b.length bytes from this file into the byte array, starting at the current file pointer.
readFully(byte[], int, int) - Method in class java.io.RandomAccessFile
Reads exactly len bytes from this file into the byte array, starting at the current file pointer.
readFully(byte[], int, int) - Method in interface javax.imageio.stream.ImageInputStream
Reads len bytes from the stream, and stores them into b starting at index off.
readFully(byte[]) - Method in interface javax.imageio.stream.ImageInputStream
Reads b.length bytes from the stream, and stores them into b starting at index 0.
readFully(short[], int, int) - Method in interface javax.imageio.stream.ImageInputStream
Reads len shorts (signed 16-bit integers) from the stream according to the current byte order, and stores them into s starting at index off.
readFully(char[], int, int) - Method in interface javax.imageio.stream.ImageInputStream
Reads len chars (unsigned 16-bit integers) from the stream according to the current byte order, and stores them into c starting at index off.
readFully(int[], int, int) - Method in interface javax.imageio.stream.ImageInputStream
Reads len ints (signed 32-bit integers) from the stream according to the current byte order, and stores them into i starting at index off.
readFully(long[], int, int) - Method in interface javax.imageio.stream.ImageInputStream
Reads len longs (signed 64-bit integers) from the stream according to the current byte order, and stores them into l starting at index off.
readFully(float[], int, int) - Method in interface javax.imageio.stream.ImageInputStream
Reads len floats (32-bit IEEE single-precision floats) from the stream according to the current byte order, and stores them into f starting at index off.
readFully(double[], int, int) - Method in interface javax.imageio.stream.ImageInputStream
Reads len doubles (64-bit IEEE double-precision floats) from the stream according to the current byte order, and stores them into d starting at index off.
readFully(byte[], int, int) - Method in class javax.imageio.stream.ImageInputStreamImpl
readFully(byte[]) - Method in class javax.imageio.stream.ImageInputStreamImpl
readFully(short[], int, int) - Method in class javax.imageio.stream.ImageInputStreamImpl
readFully(char[], int, int) - Method in class javax.imageio.stream.ImageInputStreamImpl
readFully(int[], int, int) - Method in class javax.imageio.stream.ImageInputStreamImpl
readFully(long[], int, int) - Method in class javax.imageio.stream.ImageInputStreamImpl
readFully(float[], int, int) - Method in class javax.imageio.stream.ImageInputStreamImpl
readFully(double[], int, int) - Method in class javax.imageio.stream.ImageInputStreamImpl
READING - Static variable in class java.text.AttributedCharacterIterator.Attribute
Attribute key for the reading of some text.
readInt() - Method in interface java.io.DataInput
Reads four input bytes and returns an int value.
readInt() - Method in class java.io.DataInputStream
See the general contract of the readInt method of DataInput.
readInt() - Method in class java.io.ObjectInputStream
Reads a 32 bit int.
readInt() - Method in class java.io.RandomAccessFile
Reads a signed 32-bit integer from this file.
readInt() - Method in interface java.sql.SQLInput
Reads the next attribute in the stream and returns it as an int in the Java programming language.
readInt() - Method in interface javax.imageio.stream.ImageInputStream
Reads 4 bytes from the stream, and (conceptually) concatenates them according to the current byte order and returns the result as an int.
readInt() - Method in class javax.imageio.stream.ImageInputStreamImpl
readInt() - Method in class javax.sql.rowset.serial.SQLInputImpl
Retrieves the next attribute in this SQLInputImpl object as an int in the Java programming language.
readLine() - Method in class java.io.BufferedReader
Reads a line of text.
readLine(String, Object...) - Method in class java.io.Console
Provides a formatted prompt, then reads a single line of text from the console.
readLine() - Method in class java.io.Console
Reads a single line of text from the console.
readLine() - Method in interface java.io.DataInput
Reads the next line of text from the input stream.
readLine() - Method in class java.io.DataInputStream
Deprecated.
This method does not properly convert bytes to characters. As of JDK 1.1, the preferred way to read lines of text is via the BufferedReader.readLine() method. Programs that use the DataInputStream class to read lines can be converted to use the BufferedReader class by replacing code of the form:
     DataInputStream d = new DataInputStream(in);
with:
     BufferedReader d
          = new BufferedReader(new InputStreamReader(in));
readLine() - Method in class java.io.LineNumberReader
Read a line of text.
readLine() - Method in class java.io.ObjectInputStream
Deprecated.
This method does not properly convert bytes to characters. see DataInputStream for the details and alternatives.
readLine() - Method in class java.io.RandomAccessFile
Reads the next line of text from this file.
readLine() - Method in interface javax.imageio.stream.ImageInputStream
Reads the next line of text from the input stream.
readLine() - Method in class javax.imageio.stream.ImageInputStreamImpl
readLock() - Method in interface java.util.concurrent.locks.ReadWriteLock
Returns the lock used for reading.
readLock() - Method in class java.util.concurrent.locks.ReentrantReadWriteLock
readLock() - Method in class javax.swing.text.AbstractDocument
Acquires a lock to begin reading some state from the document.
readLong() - Method in interface java.io.DataInput
Reads eight input bytes and returns a long value.
readLong() - Method in class java.io.DataInputStream
See the general contract of the readLong method of DataInput.
readLong() - Method in class java.io.ObjectInputStream
Reads a 64 bit long.
readLong() - Method in class java.io.RandomAccessFile
Reads a signed 64-bit integer from this file.
readLong() - Method in interface java.sql.SQLInput
Reads the next attribute in the stream and returns it as a long in the Java programming language.
readLong() - Method in interface javax.imageio.stream.ImageInputStream
Reads 8 bytes from the stream, and (conceptually) concatenates them according to the current byte order and returns the result as a long.
readLong() - Method in class javax.imageio.stream.ImageInputStreamImpl
readLong() - Method in class javax.sql.rowset.serial.SQLInputImpl
Retrieves the next attribute in this SQLInputImpl object as a long in the Java programming language.
readNClob() - Method in interface java.sql.SQLInput
Reads an SQL NCLOB value from the stream and returns it as a NClob object in the Java programming language.
readNClob() - Method in class javax.sql.rowset.serial.SQLInputImpl
Reads an SQL NCLOB value from the stream and returns it as a Clob object in the Java programming language.
readNString() - Method in interface java.sql.SQLInput
Reads the next attribute in the stream and returns it as a String in the Java programming language.
readNString() - Method in class javax.sql.rowset.serial.SQLInputImpl
Reads the next attribute in the stream and returns it as a String in the Java programming language.
readObject() - Method in class java.beans.XMLDecoder
Reads the next object from the underlying input stream.
readObject() - Method in interface java.io.ObjectInput
Read and return an object.
readObject() - Method in class java.io.ObjectInputStream
Read an object from the ObjectInputStream.
readObject() - Method in interface java.sql.SQLInput
Reads the datum at the head of the stream and returns it as an Object in the Java programming language.
readObject(Stub, ObjectInputStream) - Method in interface javax.rmi.CORBA.StubDelegate
Delegation call for Stub.readObject(java.io.ObjectInputStream).
readObject() - Method in class javax.sql.rowset.serial.SQLInputImpl
Retrieves the value at the head of this SQLInputImpl object as an Object in the Java programming language.
readObjectOverride() - Method in class java.io.ObjectInputStream
This method is called by trusted subclasses of ObjectOutputStream that constructed ObjectOutputStream using the protected no-arg constructor.
readOnlyAction - Static variable in class javax.swing.text.DefaultEditorKit
Name of the action to set the editor into read-only mode.
ReadOnlyBufferException - Exception in java.nio
Unchecked exception thrown when a content-mutation method such as put or compact is invoked upon a read-only buffer.
ReadOnlyBufferException() - Constructor for exception java.nio.ReadOnlyBufferException
Constructs an instance of this class.
ReadOnlyFileSystemException - Exception in java.nio.file
Unchecked exception thrown when an attempt is made to update an object associated with a read-only FileSystem.
ReadOnlyFileSystemException() - Constructor for exception java.nio.file.ReadOnlyFileSystemException
Constructs an instance of this class.
readPassword(String, Object...) - Method in class java.io.Console
Provides a formatted prompt, then reads a password or passphrase from the console with echoing disabled.
readPassword() - Method in class java.io.Console
Reads a password or passphrase from the console with echoing disabled
ReadPendingException - Exception in java.nio.channels
Unchecked exception thrown when an attempt is made to read from an asynchronous socket channel and a previous read has not completed.
ReadPendingException() - Constructor for exception java.nio.channels.ReadPendingException
Constructs an instance of this class.
readRaster(int, ImageReadParam) - Method in class javax.imageio.ImageReader
Returns a new Raster object containing the raw pixel data from the image stream, without any color conversion applied.
readRef() - Method in interface java.sql.SQLInput
Reads an SQL REF value from the stream and returns it as a Ref object in the Java programming language.
readRef() - Method in class javax.sql.rowset.serial.SQLInputImpl
Retrieves the value at the head of this SQLInputImpl object as a Ref object in the Java programming language.
readResolve() - Method in class java.awt.AWTKeyStroke
Returns a cached instance of AWTKeyStroke (or a subclass of AWTKeyStroke) which is equal to this instance.
readResolve() - Method in class java.awt.color.ICC_Profile
Resolves instances being deserialized into instances registered with CMM.
readResolve() - Method in class java.awt.font.TextAttribute
Resolves instances being deserialized to the predefined constants.
readResolve() - Method in class java.security.cert.Certificate.CertificateRep
Resolve the Certificate Object.
readResolve() - Method in class java.security.cert.CertPath.CertPathRep
Returns a CertPath constructed from the type and data.
readResolve() - Method in class java.security.KeyRep
Resolve the Key object.
readResolve() - Method in class java.text.AttributedCharacterIterator.Attribute
Resolves instances being deserialized to the predefined constants.
readResolve() - Method in class java.text.DateFormat.Field
Resolves instances being deserialized to the predefined constants.
readResolve() - Method in class java.text.MessageFormat.Field
Resolves instances being deserialized to the predefined constants.
readResolve() - Method in class java.text.NumberFormat.Field
Resolves instances being deserialized to the predefined constants.
readResolve() - Method in class javax.management.openmbean.SimpleType
Replace an object read from an ObjectInputStream with the unique instance for that value.
readResolve() - Method in class javax.print.attribute.EnumSyntax
During object input, convert this deserialized enumeration instance to the proper enumeration value defined in the enumeration attribute class.
readRowId() - Method in interface java.sql.SQLInput
Reads an SQL ROWID value from the stream and returns it as a RowId object in the Java programming language.
readRowId() - Method in class javax.sql.rowset.serial.SQLInputImpl
Reads an SQL ROWID value from the stream and returns it as a RowId object in the Java programming language.
readShort() - Method in interface java.io.DataInput
Reads two input bytes and returns a short value.
readShort() - Method in class java.io.DataInputStream
See the general contract of the readShort method of DataInput.
readShort() - Method in class java.io.ObjectInputStream
Reads a 16 bit short.
readShort() - Method in class java.io.RandomAccessFile
Reads a signed 16-bit number from this file.
readShort() - Method in interface java.sql.SQLInput
Reads the next attribute in the stream and returns it as a short in the Java programming language.
readShort() - Method in interface javax.imageio.stream.ImageInputStream
Reads two bytes from the stream, and (conceptually) concatenates them according to the current byte order, and returns the result as a short value.
readShort() - Method in class javax.imageio.stream.ImageInputStreamImpl
readShort() - Method in class javax.sql.rowset.serial.SQLInputImpl
Retrieves the next attribute in this SQLInputImpl object as a short in the Java programming language.
readSQL(SQLInput, String) - Method in interface java.sql.SQLData
Populates this object with data read from the database.
readSQLXML() - Method in interface java.sql.SQLInput
Reads an SQL XML value from the stream and returns it as a SQLXML object in the Java programming language.
readSQLXML() - Method in class javax.sql.rowset.serial.SQLInputImpl
Reads an SQL XML value from the stream and returns it as a SQLXML object in the Java programming language.
readStreamHeader() - Method in class java.io.ObjectInputStream
The readStreamHeader method is provided to allow subclasses to read and verify their own stream headers.
readString() - Method in interface java.sql.SQLInput
Reads the next attribute in the stream and returns it as a String in the Java programming language.
readString() - Method in class javax.sql.rowset.serial.SQLInputImpl
Retrieves the next attribute in this SQLInputImpl object as a String in the Java programming language.
readSymbolicLink(Path) - Static method in class java.nio.file.Files
Reads the target of a symbolic link (optional operation).
readSymbolicLink(Path) - Method in class java.nio.file.spi.FileSystemProvider
Reads the target of a symbolic link.
readThumbnail(int, int) - Method in class javax.imageio.ImageReader
Returns the thumbnail preview image indexed by thumbnailIndex, associated with the image indexed by ImageIndex as a BufferedImage.
readTile(int, int, int) - Method in class javax.imageio.ImageReader
Reads the tile indicated by the tileX and tileY arguments, returning it as a BufferedImage.
readTileRaster(int, int, int) - Method in class javax.imageio.ImageReader
Returns a new Raster object containing the raw pixel data from the tile, without any color conversion applied.
readTime() - Method in interface java.sql.SQLInput
Reads the next attribute in the stream and returns it as a java.sql.Time object.
readTime() - Method in class javax.sql.rowset.serial.SQLInputImpl
Retrieves the next attribute in this SQLInputImpl object as a java.sql.Time object.
readTimestamp() - Method in interface java.sql.SQLInput
Reads the next attribute in the stream and returns it as a java.sql.Timestamp object.
readTimestamp() - Method in class javax.sql.rowset.serial.SQLInputImpl
Retrieves the next attribute in this SQLInputImpl object as a java.sql.Timestamp object.
readUnlock() - Method in class javax.swing.text.AbstractDocument
Does a read unlock.
readUnshared() - Method in class java.io.ObjectInputStream
Reads an "unshared" object from the ObjectInputStream.
readUnsignedByte() - Method in interface java.io.DataInput
Reads one input byte, zero-extends it to type int, and returns the result, which is therefore in the range 0 through 255.
readUnsignedByte() - Method in class java.io.DataInputStream
See the general contract of the readUnsignedByte method of DataInput.
readUnsignedByte() - Method in class java.io.ObjectInputStream
Reads an unsigned 8 bit byte.
readUnsignedByte() - Method in class java.io.RandomAccessFile
Reads an unsigned eight-bit number from this file.
readUnsignedByte() - Method in interface javax.imageio.stream.ImageInputStream
Reads a byte from the stream, and (conceptually) converts it to an int, masks it with 0xff in order to strip off any sign-extension bits, and returns it as a byte value.
readUnsignedByte() - Method in class javax.imageio.stream.ImageInputStreamImpl
readUnsignedInt() - Method in interface javax.imageio.stream.ImageInputStream
Reads 4 bytes from the stream, and (conceptually) concatenates them according to the current byte order, converts the result to a long, masks it with 0xffffffffL in order to strip off any sign-extension bits, and returns the result as an unsigned long value.
readUnsignedInt() - Method in class javax.imageio.stream.ImageInputStreamImpl
readUnsignedShort() - Method in interface java.io.DataInput
Reads two input bytes and returns an int value in the range 0 through 65535.
readUnsignedShort() - Method in class java.io.DataInputStream
See the general contract of the readUnsignedShort method of DataInput.
readUnsignedShort() - Method in class java.io.ObjectInputStream
Reads an unsigned 16 bit short.
readUnsignedShort() - Method in class java.io.RandomAccessFile
Reads an unsigned 16-bit number from this file.
readUnsignedShort() - Method in interface javax.imageio.stream.ImageInputStream
Reads two bytes from the stream, and (conceptually) concatenates them according to the current byte order, converts the resulting value to an int, masks it with 0xffff in order to strip off any sign-extension buts, and returns the result as an unsigned int value.
readUnsignedShort() - Method in class javax.imageio.stream.ImageInputStreamImpl
readURL() - Method in interface java.sql.SQLInput
Reads an SQL DATALINK value from the stream and returns it as a java.net.URL object in the Java programming language.
readURL() - Method in class javax.sql.rowset.serial.SQLInputImpl
Reads an SQL DATALINK value from the stream and returns it as an URL object in the Java programming language.
readUTF() - Method in interface java.io.DataInput
Reads in a string that has been encoded using a modified UTF-8 format.
readUTF() - Method in class java.io.DataInputStream
See the general contract of the readUTF method of DataInput.
readUTF(DataInput) - Static method in class java.io.DataInputStream
Reads from the stream in a representation of a Unicode character string encoded in modified UTF-8 format; this string of characters is then returned as a String.
readUTF() - Method in class java.io.ObjectInputStream
Reads a String in modified UTF-8 format.
readUTF() - Method in class java.io.RandomAccessFile
Reads in a string from this file.
readUTF() - Method in interface javax.imageio.stream.ImageInputStream
Reads in a string that has been encoded using a modified UTF-8 format.
readUTF() - Method in class javax.imageio.stream.ImageInputStreamImpl
readValue(InputStream, int, Class, String, RunTime) - Method in interface javax.rmi.CORBA.ValueHandler
Reads a value from the stream using Java semantics.
ReadWriteLock - Interface in java.util.concurrent.locks
A ReadWriteLock maintains a pair of associated locks, one for read-only operations and one for writing.
readXML(WebRowSet, Reader) - Method in interface javax.sql.rowset.spi.XmlReader
Reads and parses the given WebRowSet object from the given input stream in XML format.
readXml(Reader) - Method in interface javax.sql.rowset.WebRowSet
Reads a WebRowSet object in its XML format from the given Reader object.
readXml(InputStream) - Method in interface javax.sql.rowset.WebRowSet
Reads a stream based XML input to populate this WebRowSet object.
ready() - Method in class java.io.BufferedReader
Tells whether this stream is ready to be read.
ready() - Method in class java.io.CharArrayReader
Tells whether this stream is ready to be read.
ready() - Method in class java.io.FilterReader
Tells whether this stream is ready to be read.
ready() - Method in class java.io.InputStreamReader
Tells whether this stream is ready to be read.
ready() - Method in class java.io.PipedReader
Tell whether this stream is ready to be read.
ready() - Method in class java.io.PushbackReader
Tells whether this stream is ready to be read.
ready() - Method in class java.io.Reader
Tells whether this stream is ready to be read.
ready() - Method in class java.io.StringReader
Tells whether this stream is ready to be read.
readyOps() - Method in class java.nio.channels.SelectionKey
Retrieves this key's ready-operation set.
REAL - Static variable in class java.sql.Types
The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type REAL.
realEditor - Variable in class javax.swing.tree.DefaultTreeCellEditor
Editor handling the editing.
RealmCallback - Class in javax.security.sasl
This callback is used by SaslClient and SaslServer to retrieve realm information.
RealmCallback(String) - Constructor for class javax.security.sasl.RealmCallback
Constructs a RealmCallback with a prompt.
RealmCallback(String, String) - Constructor for class javax.security.sasl.RealmCallback
Constructs a RealmCallback with a prompt and default realm information.
RealmChoiceCallback - Class in javax.security.sasl
This callback is used by SaslClient and SaslServer to obtain a realm given a list of realm choices.
RealmChoiceCallback(String, String[], int, boolean) - Constructor for class javax.security.sasl.RealmChoiceCallback
Constructs a RealmChoiceCallback with a prompt, a list of choices and a default choice.
realSource - Variable in class javax.swing.undo.UndoableEditSupport
reason - Variable in exception org.omg.CORBA.PolicyError
The reason for the PolicyError exception being thrown.
rebind(String, Remote) - Static method in class java.rmi.Naming
Rebinds the specified name to a new remote object.
rebind(String, Remote) - Method in interface java.rmi.registry.Registry
Replaces the binding for the specified name in this registry with the supplied remote reference.
rebind(Name, Object) - Method in interface javax.naming.Context
Binds a name to an object, overwriting any existing binding.
rebind(String, Object) - Method in interface javax.naming.Context
Binds a name to an object, overwriting any existing binding.
rebind(Name, Object, Attributes) - Method in interface javax.naming.directory.DirContext
Binds a name to an object, along with associated attributes, overwriting any existing binding.
rebind(String, Object, Attributes) - Method in interface javax.naming.directory.DirContext
Binds a name to an object, along with associated attributes, overwriting any existing binding.
rebind(String, Object, Attributes) - Method in class javax.naming.directory.InitialDirContext
rebind(Name, Object, Attributes) - Method in class javax.naming.directory.InitialDirContext
rebind(String, Object) - Method in class javax.naming.InitialContext
rebind(Name, Object) - Method in class javax.naming.InitialContext
REBIND - Exception in org.omg.CORBA
REBIND is raised when the current effective RebindPolicy, has a value of NO_REBIND or NO_RECONNECT and an invocation on a bound object reference results in a LocateReply message with status OBJECT_FORWARD or a Reply message with status LOCATION_FORWARD.
REBIND() - Constructor for exception org.omg.CORBA.REBIND
Constructs an REBIND exception with minor code set to 0 and CompletionStatus set to COMPLETED_NO.
REBIND(String) - Constructor for exception org.omg.CORBA.REBIND
Constructs an REBIND exception with the specified message.
REBIND(int, CompletionStatus) - Constructor for exception org.omg.CORBA.REBIND
Constructs an REBIND exception with the specified minor code and completion status.
REBIND(String, int, CompletionStatus) - Constructor for exception org.omg.CORBA.REBIND
Constructs an REBIND exception with the specified message, minor code, and completion status.
rebind(NameComponent[], Object) - Method in class org.omg.CosNaming._NamingContextExtStub
Creates a binding of a name and an object in the naming context even if the name is already bound in the context.
rebind(NameComponent[], Object) - Method in class org.omg.CosNaming._NamingContextStub
Creates a binding of a name and an object in the naming context even if the name is already bound in the context.
rebind(NameComponent[], Object) - Method in interface org.omg.CosNaming.NamingContextOperations
Creates a binding of a name and an object in the naming context even if the name is already bound in the context.
rebind_context(NameComponent[], NamingContext) - Method in class org.omg.CosNaming._NamingContextExtStub
Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context.
rebind_context(NameComponent[], NamingContext) - Method in class org.omg.CosNaming._NamingContextStub
Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context.
rebind_context(NameComponent[], NamingContext) - Method in interface org.omg.CosNaming.NamingContextOperations
Creates a binding of a name and a naming context in the naming context even if the name is already bound in the context.
recalculateIfInsetsChanged() - Method in class javax.swing.plaf.basic.BasicSliderUI
recalculateIfInsetsChanged() - Method in class javax.swing.plaf.synth.SynthSliderUI
recalculateIfOrientationChanged() - Method in class javax.swing.plaf.basic.BasicSliderUI
recalcWidthCache() - Method in class javax.swing.table.DefaultTableColumnModel
Recalculates the total combined width of all columns.
receive(int) - Method in class java.io.PipedInputStream
Receives a byte of data.
receive(DatagramPacket) - Method in class java.net.DatagramSocket
Receives a datagram packet from this socket.
receive(DatagramPacket) - Method in class java.net.DatagramSocketImpl
Receive the datagram packet.
receive(ByteBuffer) - Method in class java.nio.channels.DatagramChannel
Receives a datagram via this channel.
receive_exception(ClientRequestInfo) - Method in interface org.omg.PortableInterceptor.ClientRequestInterceptorOperations
Indicates to the interceptor that an exception occurred.
receive_other(ClientRequestInfo) - Method in interface org.omg.PortableInterceptor.ClientRequestInterceptorOperations
Allows an Interceptor to query the information available when a request results in something other than a normal reply or an exception.
receive_reply(ClientRequestInfo) - Method in interface org.omg.PortableInterceptor.ClientRequestInterceptorOperations
Allows an Interceptor to query the information on a reply after it is returned from the server and before control is returned to the client.
receive_request(ServerRequestInfo) - Method in interface org.omg.PortableInterceptor.ServerRequestInterceptorOperations
Allows an Interceptor to query request information after all the information, including operation parameters, are available.
receive_request_service_contexts(ServerRequestInfo) - Method in interface org.omg.PortableInterceptor.ServerRequestInterceptorOperations
Allows the interceptor to process service context information.
received_exception() - Method in interface org.omg.PortableInterceptor.ClientRequestInfoOperations
Returns an any which contains the exception to be returned to the client.
received_exception_id() - Method in interface org.omg.PortableInterceptor.ClientRequestInfoOperations
Returns the repository id of the exception to be returned to the client.
Receiver - Interface in javax.sound.midi
A Receiver receives MidiEvent objects and typically does something useful in response, such as interpreting them to generate sound or raw MIDI output.
reclaim(AttributeSet) - Method in interface javax.swing.text.AbstractDocument.AttributeContext
Reclaims an attribute set.
reclaim(AttributeSet) - Method in class javax.swing.text.StyleContext
Returns a set no longer needed by the MutableAttributeSet implmentation.
reconnect(Control[]) - Method in class javax.naming.ldap.InitialLdapContext
reconnect(Control[]) - Method in interface javax.naming.ldap.LdapContext
Reconnects to the LDAP server using the supplied controls and this context's environment.
reconvert() - Method in class java.awt.im.InputContext
Asks the current input method to reconvert text from the current client component.
reconvert() - Method in interface java.awt.im.spi.InputMethod
Starts the reconversion operation.
recordDisable(Track) - Method in interface javax.sound.midi.Sequencer
Disables recording to the specified track.
recordEnable(Track, int) - Method in interface javax.sound.midi.Sequencer
Prepares the specified track for recording events received on a particular channel.
recover(int) - Method in interface javax.transaction.xa.XAResource
Obtains a list of prepared transaction branches from a resource manager.
Rectangle - Class in java.awt
A Rectangle specifies an area in a coordinate space that is enclosed by the Rectangle object's upper-left point (x,y) in the coordinate space, its width, and its height.
Rectangle() - Constructor for class java.awt.Rectangle
Constructs a new Rectangle whose upper-left corner is at (0, 0) in the coordinate space, and whose width and height are both zero.
Rectangle(Rectangle) - Constructor for class java.awt.Rectangle
Constructs a new Rectangle, initialized to match the values of the specified Rectangle.
Rectangle(int, int, int, int) - Constructor for class java.awt.Rectangle
Constructs a new Rectangle whose upper-left corner is specified as (x,y) and whose width and height are specified by the arguments of the same name.
Rectangle(int, int) - Constructor for class java.awt.Rectangle
Constructs a new Rectangle whose upper-left corner is at (0, 0) in the coordinate space, and whose width and height are specified by the arguments of the same name.
Rectangle(Point, Dimension) - Constructor for class java.awt.Rectangle
Constructs a new Rectangle whose upper-left corner is specified by the Point argument, and whose width and height are specified by the Dimension argument.
Rectangle(Point) - Constructor for class java.awt.Rectangle
Constructs a new Rectangle whose upper-left corner is the specified Point, and whose width and height are both zero.
Rectangle(Dimension) - Constructor for class java.awt.Rectangle
Constructs a new Rectangle whose top left corner is (0, 0) and whose width and height are specified by the Dimension argument.
Rectangle2D - Class in java.awt.geom
The Rectangle2D class describes a rectangle defined by a location (x,y) and dimension (w x h).
Rectangle2D() - Constructor for class java.awt.geom.Rectangle2D
This is an abstract class that cannot be instantiated directly.
Rectangle2D.Double - Class in java.awt.geom
The Double class defines a rectangle specified in double coordinates.
Rectangle2D.Double() - Constructor for class java.awt.geom.Rectangle2D.Double
Constructs a new Rectangle2D, initialized to location (0, 0) and size (0, 0).
Rectangle2D.Double(double, double, double, double) - Constructor for class java.awt.geom.Rectangle2D.Double
Constructs and initializes a Rectangle2D from the specified double coordinates.
Rectangle2D.Float - Class in java.awt.geom
The Float class defines a rectangle specified in float coordinates.
Rectangle2D.Float() - Constructor for class java.awt.geom.Rectangle2D.Float
Constructs a new Rectangle2D, initialized to location (0.0, 0.0) and size (0.0, 0.0).
Rectangle2D.Float(float, float, float, float) - Constructor for class java.awt.geom.Rectangle2D.Float
Constructs and initializes a Rectangle2D from the specified float coordinates.
rectangleForCurrentValue() - Method in class javax.swing.plaf.basic.BasicComboBoxUI
Returns the area that is reserved for drawing the currently selected item.
RectangularShape - Class in java.awt.geom
RectangularShape is the base class for a number of Shape objects whose geometry is defined by a rectangular frame.
RectangularShape() - Constructor for class java.awt.geom.RectangularShape
This is an abstract class that cannot be instantiated directly.
rects - Variable in class javax.swing.plaf.basic.BasicTabbedPaneUI
RecursiveAction - Class in java.util.concurrent
A recursive resultless ForkJoinTask.
RecursiveAction() - Constructor for class java.util.concurrent.RecursiveAction
RecursiveTask<V> - Class in java.util.concurrent
A recursive result-bearing ForkJoinTask.
RecursiveTask() - Constructor for class java.util.concurrent.RecursiveTask
recycleNode() - Method in interface javax.xml.soap.Node
Notifies the implementation that this Node object is no longer being used by the application and that the implementation is free to reuse this object for nodes that may be created later.
red - Static variable in class java.awt.Color
The color red.
RED - Static variable in class java.awt.Color
The color red.
REDCOMPONENT - Static variable in class java.awt.color.ICC_ProfileRGB
Used to get a gamma value or TRC for the red component.
redefineClasses(ClassDefinition...) - Method in interface java.lang.instrument.Instrumentation
Redefine the supplied set of classes using the supplied class files.
redirectError(ProcessBuilder.Redirect) - Method in class java.lang.ProcessBuilder
Sets this process builder's standard error destination.
redirectError(File) - Method in class java.lang.ProcessBuilder
Sets this process builder's standard error destination to a file.
redirectError() - Method in class java.lang.ProcessBuilder
Returns this process builder's standard error destination.
redirectErrorStream() - Method in class java.lang.ProcessBuilder
Tells whether this process builder merges standard error and standard output.
redirectErrorStream(boolean) - Method in class java.lang.ProcessBuilder
Sets this process builder's redirectErrorStream property.
redirectInput(ProcessBuilder.Redirect) - Method in class java.lang.ProcessBuilder
Sets this process builder's standard input source.
redirectInput(File) - Method in class java.lang.ProcessBuilder
Sets this process builder's standard input source to a file.
redirectInput() - Method in class java.lang.ProcessBuilder
Returns this process builder's standard input source.
redirectOutput(ProcessBuilder.Redirect) - Method in class java.lang.ProcessBuilder
Sets this process builder's standard output destination.
redirectOutput(File) - Method in class java.lang.ProcessBuilder
Sets this process builder's standard output destination to a file.
redirectOutput() - Method in class java.lang.ProcessBuilder
Returns this process builder's standard output destination.
redispatchEvent(Component, AWTEvent) - Method in class java.awt.KeyboardFocusManager
Redispatches an AWTEvent in such a way that the AWT event dispatcher will not recursively request that the KeyboardFocusManager, or any installed KeyEventDispatchers, dispatch the event again.
redo() - Method in class javax.swing.text.AbstractDocument.DefaultDocumentEvent
Redoes a change.
redo() - Method in class javax.swing.text.AbstractDocument.ElementEdit
Redoes a change.
redo() - Method in class javax.swing.text.DefaultStyledDocument.AttributeUndoableEdit
Redoes a change.
redo() - Method in class javax.swing.undo.AbstractUndoableEdit
Throws CannotRedoException if canRedo returns false.
redo() - Method in class javax.swing.undo.CompoundEdit
Sends redo to all contained UndoableEdits in the order in which they were added.
redo() - Method in class javax.swing.undo.StateEdit
Tells the edited object to apply the state after the edit
redo() - Method in interface javax.swing.undo.UndoableEdit
Re-applies the edit.
redo() - Method in class javax.swing.undo.UndoManager
Redoes the appropriate edits.
RedoName - Static variable in class javax.swing.undo.AbstractUndoableEdit
String returned by getRedoPresentationName; as of Java 2 platform v1.3.1 this field is no longer used.
redoTo(UndoableEdit) - Method in class javax.swing.undo.UndoManager
Redoes all changes from the index of the next edit to edit, updating the index of the next edit appropriately.
reducePermits(int) - Method in class java.util.concurrent.Semaphore
Shrinks the number of available permits by the indicated reduction.
ReentrantLock - Class in java.util.concurrent.locks
A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.
ReentrantLock() - Constructor for class java.util.concurrent.locks.ReentrantLock
Creates an instance of ReentrantLock.
ReentrantLock(boolean) - Constructor for class java.util.concurrent.locks.ReentrantLock
Creates an instance of ReentrantLock with the given fairness policy.
ReentrantReadWriteLock - Class in java.util.concurrent.locks
An implementation of ReadWriteLock supporting similar semantics to ReentrantLock.
ReentrantReadWriteLock() - Constructor for class java.util.concurrent.locks.ReentrantReadWriteLock
Creates a new ReentrantReadWriteLock with default (nonfair) ordering properties.
ReentrantReadWriteLock(boolean) - Constructor for class java.util.concurrent.locks.ReentrantReadWriteLock
Creates a new ReentrantReadWriteLock with the given fairness policy.
ReentrantReadWriteLock.ReadLock - Class in java.util.concurrent.locks
The lock returned by method ReentrantReadWriteLock.readLock().
ReentrantReadWriteLock.ReadLock(ReentrantReadWriteLock) - Constructor for class java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock
Constructor for use by subclasses
ReentrantReadWriteLock.WriteLock - Class in java.util.concurrent.locks
The lock returned by method ReentrantReadWriteLock.writeLock().
ReentrantReadWriteLock.WriteLock(ReentrantReadWriteLock) - Constructor for class java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock
Constructor for use by subclasses
ref - Variable in class java.rmi.server.RemoteObject
The object's remote reference.
Ref - Interface in java.sql
The mapping in the Java programming language of an SQL REF value, which is a reference to an SQL structured type value in the database.
REF - Static variable in class java.sql.Types
The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type REF.
REF_MBEAN_NOT_REGISTERED - Static variable in class javax.management.relation.RoleStatus
Problem type when trying to set a role value including the ObjectName of a MBean not registered in the MBean Server.
REF_MBEAN_OF_INCORRECT_CLASS - Static variable in class javax.management.relation.RoleStatus
Problem type when trying to set a role value including the ObjectName of a MBean not of the class expected for that role.
RefAddr - Class in javax.naming
This class represents the address of a communications end-point.
RefAddr(String) - Constructor for class javax.naming.RefAddr
Constructs a new instance of RefAddr using its address type.
Reference<T> - Class in java.lang.ref
Abstract base class for reference objects.
Reference - Class in javax.naming
This class represents a reference to an object that is found outside of the naming/directory system.
Reference(String) - Constructor for class javax.naming.Reference
Constructs a new reference for an object with class name 'className'.
Reference(String, RefAddr) - Constructor for class javax.naming.Reference
Constructs a new reference for an object with class name 'className' and an address.
Reference(String, String, String) - Constructor for class javax.naming.Reference
Constructs a new reference for an object with class name 'className', and the class name and location of the object's factory.
Reference(String, RefAddr, String, String) - Constructor for class javax.naming.Reference
Constructs a new reference for an object with class name 'className', the class name and location of the object's factory, and the address for the object.
Reference - Interface in javax.xml.crypto.dsig
A representation of the Reference element as defined in the W3C Recommendation for XML-Signature Syntax and Processing.
REFERENCE_PARAMETERS - Static variable in interface javax.xml.ws.handler.MessageContext
Standard property: WS Addressing Reference Parameters.
reference_to_id(Object) - Method in interface org.omg.PortableServer.POAOperations
This operation returns the Object Id value encapsulated by the specified reference.
reference_to_servant(Object) - Method in interface org.omg.PortableServer.POAOperations
If the POA has the RETAIN policy and the specified object is present in the Active Object Map, this operation returns the servant associated with that object in the Active Object Map.
Referenceable - Interface in javax.naming
This interface is implemented by an object that can provide a Reference to itself.
referenceParameter(Element) - Method in class javax.xml.ws.wsaddressing.W3CEndpointReferenceBuilder
Adds the referenceParameter to the W3CEndpointReference instance wsa:ReferenceParameters element.
ReferenceQueue<T> - Class in java.lang.ref
Reference queues, to which registered reference objects are appended by the garbage collector after the appropriate reachability changes are detected.
ReferenceQueue() - Constructor for class java.lang.ref.ReferenceQueue
Constructs a new reference-object queue.
ReferenceType - Interface in javax.lang.model.type
Represents a reference type.
ReferenceUriSchemesSupported - Class in javax.print.attribute.standard
Class ReferenceUriSchemesSupported is a printing attribute class an enumeration, that indicates a "URI scheme," such as "http:" or "ftp:", that a printer can use to retrieve print data stored at a URI location.
ReferenceUriSchemesSupported(int) - Constructor for class javax.print.attribute.standard.ReferenceUriSchemesSupported
Construct a new reference URI scheme enumeration value with the given integer value.
REFERRAL - Static variable in interface javax.naming.Context
Constant that holds the name of the environment property for specifying how referrals encountered by the service provider are to be processed.
ReferralException - Exception in javax.naming
This abstract class is used to represent a referral exception, which is generated in response to a referral such as that returned by LDAP v3 servers.
ReferralException(String) - Constructor for exception javax.naming.ReferralException
Constructs a new instance of ReferralException using the explanation supplied.
ReferralException() - Constructor for exception javax.naming.ReferralException
Constructs a new instance of ReferralException.
ReflectionException - Exception in javax.management
Represents exceptions thrown in the MBean server when using the java.lang.reflect classes to invoke methods on MBeans.
ReflectionException(Exception) - Constructor for exception javax.management.ReflectionException
Creates a ReflectionException that wraps the actual java.lang.Exception.
ReflectionException(Exception, String) - Constructor for exception javax.management.ReflectionException
Creates a ReflectionException that wraps the actual java.lang.Exception with a detail message.
ReflectiveOperationException - Exception in java.lang
Common superclass of exceptions thrown by reflective operations in core reflection.
ReflectiveOperationException() - Constructor for exception java.lang.ReflectiveOperationException
Constructs a new exception with null as its detail message.
ReflectiveOperationException(String) - Constructor for exception java.lang.ReflectiveOperationException
Constructs a new exception with the specified detail message.
ReflectiveOperationException(String, Throwable) - Constructor for exception java.lang.ReflectiveOperationException
Constructs a new exception with the specified detail message and cause.
ReflectiveOperationException(Throwable) - Constructor for exception java.lang.ReflectiveOperationException
Constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).
ReflectPermission - Class in java.lang.reflect
The Permission class for reflective operations.
ReflectPermission(String) - Constructor for class java.lang.reflect.ReflectPermission
Constructs a ReflectPermission with the specified name.
ReflectPermission(String, String) - Constructor for class java.lang.reflect.ReflectPermission
Constructs a ReflectPermission with the specified name and actions.
refresh() - Method in class java.security.Policy
Refreshes/reloads the policy configuration.
refresh() - Method in class javax.security.auth.kerberos.KerberosTicket
Extends the validity period of this ticket.
refresh() - Method in class javax.security.auth.login.Configuration
Refresh and reload the Configuration.
refresh() - Method in class javax.security.auth.Policy
Deprecated.
Refresh and reload the Policy.
refresh() - Method in interface javax.security.auth.Refreshable
Update or extend the validity period for this Object.
REFRESH_RATE_UNKNOWN - Static variable in class java.awt.DisplayMode
Value of the refresh rate if not known.
Refreshable - Interface in javax.security.auth
Objects such as credentials may optionally implement this interface to provide the capability to refresh itself.
RefreshFailedException - Exception in javax.security.auth
Signals that a refresh operation failed.
RefreshFailedException() - Constructor for exception javax.security.auth.RefreshFailedException
Constructs a RefreshFailedException with no detail message.
RefreshFailedException(String) - Constructor for exception javax.security.auth.RefreshFailedException
Constructs a RefreshFailedException with the specified detail message.
refreshRow() - Method in interface java.sql.ResultSet
Refreshes the current row with its most recent value in the database.
regexFilter(String, int...) - Static method in class javax.swing.RowFilter
Returns a RowFilter that uses a regular expression to determine which entries to include.
region(int, int) - Method in class java.util.regex.Matcher
Sets the limits of this matcher's region.
Region - Class in javax.swing.plaf.synth
A distinct rendering area of a Swing component.
Region(String, String, boolean) - Constructor for class javax.swing.plaf.synth.Region
Creates a Region with the specified name.
regionEnd() - Method in class java.util.regex.Matcher
Reports the end index (exclusive) of this matcher's region.
regionMatches(int, String, int, int) - Method in class java.lang.String
Tests if two string regions are equal.
regionMatches(boolean, int, String, int, int) - Method in class java.lang.String
Tests if two string regions are equal.
regionStart() - Method in class java.util.regex.Matcher
Reports the start index of this matcher's region.
register(Selector, int, Object) - Method in class java.nio.channels.SelectableChannel
Registers this channel with the given selector, returning a selection key.
register(Selector, int) - Method in class java.nio.channels.SelectableChannel
Registers this channel with the given selector, returning a selection key.
register(Selector, int, Object) - Method in class java.nio.channels.spi.AbstractSelectableChannel
Registers this channel with the given selector, returning a selection key.
register(AbstractSelectableChannel, int, Object) - Method in class java.nio.channels.spi.AbstractSelector
Registers the given channel with this selector.
register(WatchService, WatchEvent.Kind<?>[], WatchEvent.Modifier...) - Method in interface java.nio.file.Path
Registers the file located by this path with a watch service.
register(WatchService, WatchEvent.Kind<?>...) - Method in interface java.nio.file.Path
Registers the file located by this path with a watch service.
register(WatchService, WatchEvent.Kind<?>[], WatchEvent.Modifier...) - Method in interface java.nio.file.Watchable
Registers an object with a watch service.
register(WatchService, WatchEvent.Kind<?>...) - Method in interface java.nio.file.Watchable
Registers an object with a watch service.
register(ActivationDesc) - Static method in class java.rmi.activation.Activatable
Register an object descriptor for an activatable remote object so that is can be activated on demand.
register() - Method in class java.util.concurrent.Phaser
Adds a new unarrived party to this phaser.
register(Region, String) - Method in class javax.swing.plaf.nimbus.NimbusLookAndFeel
Registers a third party component with the NimbusLookAndFeel.
register_initial_reference(String, Object) - Method in interface org.omg.PortableInterceptor.ORBInitInfoOperations
Identical to ORB.register_initial_reference.
register_policy_factory(int, PolicyFactory) - Method in interface org.omg.PortableInterceptor.ORBInitInfoOperations
Registers a PolicyFactory for the given PolicyType.
register_value_factory(String, ValueFactory) - Method in class org.omg.CORBA_2_3.ORB
RegisterableService - Interface in javax.imageio.spi
An optional interface that may be provided by service provider objects that will be registered with a ServiceRegistry.
registerApplicationClasspathSpis() - Method in class javax.imageio.spi.IIORegistry
Registers all available service providers found on the application class path, using the default ClassLoader.
registerAsParallelCapable() - Static method in class java.lang.ClassLoader
Registers the caller as parallel capable.
registerComponent(JComponent) - Method in class javax.swing.ToolTipManager
Registers a component for tooltip management.
registerDriver(Driver) - Static method in class java.sql.DriverManager
Registers the given driver with the DriverManager.
registerEditor(Class<?>, Class<?>) - Static method in class java.beans.PropertyEditorManager
Registers an editor class to edit values of the given target class.
registerEditorKitForContentType(String, String) - Static method in class javax.swing.JEditorPane
Establishes the default bindings of type to classname.
registerEditorKitForContentType(String, String, ClassLoader) - Static method in class javax.swing.JEditorPane
Establishes the default bindings of type to classname.
registerEngineExtension(String, ScriptEngineFactory) - Method in class javax.script.ScriptEngineManager
Registers a ScriptEngineFactory to handle an extension.
registerEngineMimeType(String, ScriptEngineFactory) - Method in class javax.script.ScriptEngineManager
Registers a ScriptEngineFactory to handle a mime type.
registerEngineName(String, ScriptEngineFactory) - Method in class javax.script.ScriptEngineManager
Registers a ScriptEngineFactory to handle a language name.
registerFont(Font) - Method in class java.awt.GraphicsEnvironment
Registers a created Fontin this GraphicsEnvironment.
registerGroup(ActivationGroupDesc) - Method in interface java.rmi.activation.ActivationSystem
Register the activation group.
registerKeyboardAction(ActionListener, String, KeyStroke, int) - Method in class javax.swing.JComponent
This method is now obsolete, please use a combination of getActionMap() and getInputMap() for similiar behavior.
registerKeyboardAction(ActionListener, KeyStroke, int) - Method in class javax.swing.JComponent
This method is now obsolete, please use a combination of getActionMap() and getInputMap() for similiar behavior.
registerKeyboardActions() - Method in class javax.swing.plaf.basic.BasicDesktopPaneUI
registerListeners() - Method in class java.awt.dnd.DragGestureRecognizer
register this DragGestureRecognizer's Listeners with the Component subclasses must override this method
registerListeners() - Method in class java.awt.dnd.MouseDragGestureRecognizer
register this DragGestureRecognizer's Listeners with the Component
registerMBean(Object, ObjectName) - Method in interface javax.management.MBeanServer
Registers a pre-existing object as an MBean with the MBean server.
registerObject(ActivationDesc) - Method in interface java.rmi.activation.ActivationSystem
The registerObject method is used to register an activation descriptor, desc, and obtain an activation identifier for a activatable remote object.
registerOutParameter(int, int) - Method in interface java.sql.CallableStatement
Registers the OUT parameter in ordinal position parameterIndex to the JDBC type sqlType.
registerOutParameter(int, int, int) - Method in interface java.sql.CallableStatement
Registers the parameter in ordinal position parameterIndex to be of JDBC type sqlType.
registerOutParameter(int, int, String) - Method in interface java.sql.CallableStatement
Registers the designated output parameter.
registerOutParameter(String, int) - Method in interface java.sql.CallableStatement
Registers the OUT parameter named parameterName to the JDBC type sqlType.
registerOutParameter(String, int, int) - Method in interface java.sql.CallableStatement
Registers the parameter named parameterName to be of JDBC type sqlType.
registerOutParameter(String, int, String) - Method in interface java.sql.CallableStatement
Registers the designated output parameter.
registerProvider(String) - Static method in class javax.sql.rowset.spi.SyncFactory
Adds the the given synchronization provider to the factory register.
registerService(PrintService) - Static method in class javax.print.PrintServiceLookup
Allows an application to directly register an instance of a class which implements a print service.
registerServiceProvider(T, Class<T>) - Method in class javax.imageio.spi.ServiceRegistry
Adds a service provider object to the registry.
registerServiceProvider(Object) - Method in class javax.imageio.spi.ServiceRegistry
Adds a service provider object to the registry.
registerServiceProvider(PrintServiceLookup) - Static method in class javax.print.PrintServiceLookup
Allows an application to explicitly register a class that implements lookup services.
registerServiceProviders(Iterator<?>) - Method in class javax.imageio.spi.ServiceRegistry
Adds a set of service provider objects, taken from an Iterator to the registry.
registerStaticAttributeKey(Object) - Static method in class javax.swing.text.StyleContext
Registers an object as a static object that is being used as a key in attribute sets.
registerSubclass(Class<?>) - Static method in class java.awt.AWTKeyStroke
Registers a new class which the factory methods in AWTKeyStroke will use when generating new instances of AWTKeyStrokes.
registerTag(HTML.Tag, HTMLDocument.HTMLReader.TagAction) - Method in class javax.swing.text.html.HTMLDocument.HTMLReader
Registers a handler for the given tag.
registerTarget(Tie, Remote) - Static method in class javax.rmi.CORBA.Util
Registers a target for a tie.
registerTarget(Tie, Remote) - Method in interface javax.rmi.CORBA.UtilDelegate
Delegation call for Util.registerTarget(javax.rmi.CORBA.Tie, java.rmi.Remote).
registerValidation(ObjectInputValidation, int) - Method in class java.io.ObjectInputStream
Register an object to be validated before the graph is returned.
REGISTRATION_NOTIFICATION - Static variable in class javax.management.MBeanServerNotification
Notification type denoting that an MBean has been registered.
Registry - Interface in java.rmi.registry
Registry is a remote interface to a simple remote object registry that provides methods for storing and retrieving remote object references bound with arbitrary string names.
REGISTRY_ID - Static variable in class java.rmi.server.ObjID
Object number for well-known ObjID of the registry.
REGISTRY_PORT - Static variable in interface java.rmi.registry.Registry
Well known port for registry.
RegistryHandler - Interface in java.rmi.registry
Deprecated.
no replacement
registryImpl(int) - Method in interface java.rmi.registry.RegistryHandler
Deprecated.
no replacement. As of the Java 2 platform v1.2, RMI no longer uses the RegistryHandler to obtain the registry's implementation.
registryStub(String, int) - Method in interface java.rmi.registry.RegistryHandler
Deprecated.
no replacement. As of the Java 2 platform v1.2, RMI no longer uses the RegistryHandler to obtain the registry's stub.
rehash() - Method in class java.util.Hashtable
Increases the capacity of and internally reorganizes this hashtable, in order to accommodate and access its entries more efficiently.
reinitialize() - Method in class java.util.concurrent.ForkJoinTask
Resets the internal bookkeeping state of this task, allowing a subsequent fork.
REJANG - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Rejang" Unicode character block.
rejectDrag() - Method in class java.awt.dnd.DropTargetContext
reject the Drag.
rejectDrag() - Method in class java.awt.dnd.DropTargetDragEvent
Rejects the drag as a result of examining either the dropAction or the available DataFlavor types.
rejectDrop() - Method in class java.awt.dnd.DropTargetContext
called to signal that the drop is unacceptable.
rejectDrop() - Method in class java.awt.dnd.DropTargetDropEvent
reject the Drop.
rejectedExecution(Runnable, ThreadPoolExecutor) - Method in interface java.util.concurrent.RejectedExecutionHandler
Method that may be invoked by a ThreadPoolExecutor when execute cannot accept a task.
rejectedExecution(Runnable, ThreadPoolExecutor) - Method in class java.util.concurrent.ThreadPoolExecutor.AbortPolicy
Always throws RejectedExecutionException.
rejectedExecution(Runnable, ThreadPoolExecutor) - Method in class java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy
Executes task r in the caller's thread, unless the executor has been shut down, in which case the task is discarded.
rejectedExecution(Runnable, ThreadPoolExecutor) - Method in class java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy
Obtains and ignores the next task that the executor would otherwise execute, if one is immediately available, and then retries execution of task r, unless the executor is shut down, in which case task r is instead discarded.
rejectedExecution(Runnable, ThreadPoolExecutor) - Method in class java.util.concurrent.ThreadPoolExecutor.DiscardPolicy
Does nothing, which has the effect of discarding task r.
RejectedExecutionException - Exception in java.util.concurrent
Exception thrown by an Executor when a task cannot be accepted for execution.
RejectedExecutionException() - Constructor for exception java.util.concurrent.RejectedExecutionException
Constructs a RejectedExecutionException with no detail message.
RejectedExecutionException(String) - Constructor for exception java.util.concurrent.RejectedExecutionException
Constructs a RejectedExecutionException with the specified detail message.
RejectedExecutionException(String, Throwable) - Constructor for exception java.util.concurrent.RejectedExecutionException
Constructs a RejectedExecutionException with the specified detail message and cause.
RejectedExecutionException(Throwable) - Constructor for exception java.util.concurrent.RejectedExecutionException
Constructs a RejectedExecutionException with the specified cause.
RejectedExecutionHandler - Interface in java.util.concurrent
A handler for tasks that cannot be executed by a ThreadPoolExecutor.
rejectedSetBCOnce - Variable in class java.beans.beancontext.BeanContextChildSupport
A flag indicating that there has been at least one PropertyChangeVetoException thrown for the attempted setBeanContext operation.
REL - Static variable in class javax.swing.text.html.HTML.Attribute
Relation - Interface in javax.management.relation
This interface has to be implemented by any MBean class expected to represent a relation managed using the Relation Service.
RELATION_BASIC_CREATION - Static variable in class javax.management.relation.RelationNotification
Type for the creation of an internal relation.
RELATION_BASIC_REMOVAL - Static variable in class javax.management.relation.RelationNotification
Type for the removal from the Relation Service of an internal relation.
RELATION_BASIC_UPDATE - Static variable in class javax.management.relation.RelationNotification
Type for an update of an internal relation.
RELATION_MBEAN_CREATION - Static variable in class javax.management.relation.RelationNotification
Type for the relation MBean added into the Relation Service.
RELATION_MBEAN_REMOVAL - Static variable in class javax.management.relation.RelationNotification
Type for the removal from the Relation Service of a relation MBean.
RELATION_MBEAN_UPDATE - Static variable in class javax.management.relation.RelationNotification
Type for the update of a relation MBean.
RelationException - Exception in javax.management.relation
This class is the superclass of any exception which can be raised during relation management.
RelationException() - Constructor for exception javax.management.relation.RelationException
Default constructor, no message put in exception.
RelationException(String) - Constructor for exception javax.management.relation.RelationException
Constructor with given message put in exception.
RelationNotFoundException - Exception in javax.management.relation
This exception is raised when there is no relation for a given relation id in a Relation Service.
RelationNotFoundException() - Constructor for exception javax.management.relation.RelationNotFoundException
Default constructor, no message put in exception.
RelationNotFoundException(String) - Constructor for exception javax.management.relation.RelationNotFoundException
Constructor with given message put in exception.
RelationNotification - Class in javax.management.relation
A notification of a change in the Relation Service.
RelationNotification(String, Object, long, long, String, String, String, ObjectName, List<ObjectName>) - Constructor for class javax.management.relation.RelationNotification
Creates a notification for either a relation creation (RelationSupport object created internally in the Relation Service, or an MBean added as a relation) or for a relation removal from the Relation Service.
RelationNotification(String, Object, long, long, String, String, String, ObjectName, String, List<ObjectName>, List<ObjectName>) - Constructor for class javax.management.relation.RelationNotification
Creates a notification for a role update in a relation.
relations - Variable in class javax.accessibility.AccessibleRelationSet
Each entry in the Vector represents an AccessibleRelation.
RelationService - Class in javax.management.relation
The Relation Service is in charge of creating and deleting relation types and relations, of handling the consistency and of providing query mechanisms.
RelationService(boolean) - Constructor for class javax.management.relation.RelationService
Constructor.
RelationServiceMBean - Interface in javax.management.relation
The Relation Service is in charge of creating and deleting relation types and relations, of handling the consistency and of providing query mechanisms.
RelationServiceNotRegisteredException - Exception in javax.management.relation
This exception is raised when an access is done to the Relation Service and that one is not registered.
RelationServiceNotRegisteredException() - Constructor for exception javax.management.relation.RelationServiceNotRegisteredException
Default constructor, no message put in exception.
RelationServiceNotRegisteredException(String) - Constructor for exception javax.management.relation.RelationServiceNotRegisteredException
Constructor with given message put in exception.
RelationSupport - Class in javax.management.relation
A RelationSupport object is used internally by the Relation Service to represent simple relations (only roles, no properties or methods), with an unlimited number of roles, of any relation type.
RelationSupport(String, ObjectName, String, RoleList) - Constructor for class javax.management.relation.RelationSupport
Creates a RelationSupport object.
RelationSupport(String, ObjectName, MBeanServer, String, RoleList) - Constructor for class javax.management.relation.RelationSupport
Creates a RelationSupport object.
RelationSupportMBean - Interface in javax.management.relation
A RelationSupport object is used internally by the Relation Service to represent simple relations (only roles, no properties or methods), with an unlimited number of roles, of any relation type.
RelationType - Interface in javax.management.relation
The RelationType interface has to be implemented by any class expected to represent a relation type.
RelationTypeNotFoundException - Exception in javax.management.relation
This exception is raised when there is no relation type with given name in Relation Service.
RelationTypeNotFoundException() - Constructor for exception javax.management.relation.RelationTypeNotFoundException
Default constructor, no message put in exception.
RelationTypeNotFoundException(String) - Constructor for exception javax.management.relation.RelationTypeNotFoundException
Constructor with given message put in exception.
RelationTypeSupport - Class in javax.management.relation
A RelationTypeSupport object implements the RelationType interface.
RelationTypeSupport(String, RoleInfo[]) - Constructor for class javax.management.relation.RelationTypeSupport
Constructor where all role definitions are dynamically created and passed as parameter.
RelationTypeSupport(String) - Constructor for class javax.management.relation.RelationTypeSupport
Constructor to be used for subclasses.
RELATIVE - Static variable in class java.awt.GridBagConstraints
Specifies that this component is the next-to-last component in its column or row (gridwidth, gridheight), or that this component be placed next to the previously added component (gridx, gridy).
relative(int) - Method in interface java.sql.ResultSet
Moves the cursor a relative number of rows, either positive or negative.
relativeCCW(double, double, double, double, double, double) - Static method in class java.awt.geom.Line2D
Returns an indicator of where the specified point (px,py) lies with respect to the line segment from (x1,y1) to (x2,y2).
relativeCCW(double, double) - Method in class java.awt.geom.Line2D
Returns an indicator of where the specified point (px,py) lies with respect to this line segment.
relativeCCW(Point2D) - Method in class java.awt.geom.Line2D
Returns an indicator of where the specified Point2D lies with respect to this line segment.
relativize(URI) - Method in class java.net.URI
Relativizes the given URI against this URI.
relativize(Path) - Method in interface java.nio.file.Path
Constructs a relative path between this path and a given path.
RELAXNG_NS_URI - Static variable in class javax.xml.XMLConstants
RELAX NG Namespace URI.
release() - Method in class java.nio.channels.FileLock
Releases this lock.
release(long) - Method in class java.util.concurrent.locks.AbstractQueuedLongSynchronizer
Releases in exclusive mode.
release(int) - Method in class java.util.concurrent.locks.AbstractQueuedSynchronizer
Releases in exclusive mode.
release() - Method in class java.util.concurrent.Semaphore
Releases a permit, returning it to the semaphore.
release(int) - Method in class java.util.concurrent.Semaphore
Releases the given number of permits, returning them to the semaphore.
release() - Method in interface javax.sql.rowset.CachedRowSet
Releases the current contents of this CachedRowSet object and sends a rowSetChanged event to all registered listeners.
release(Object) - Method in class org.omg.CORBA.portable.Delegate
Releases resources associated with the object reference provided.
releaseBeanContextResources() - Method in class java.beans.beancontext.BeanContextChildSupport
This method may be overridden by subclasses to provide their own release behaviors.
releaseBeanContextResources() - Method in class java.beans.beancontext.BeanContextServicesSupport
called from setBeanContext to notify a BeanContextChild to release resources obtained from the nesting BeanContext.
releaseInputStream() - Method in interface java.rmi.server.RemoteCall
Deprecated.
no replacement
releaseMBeanServer(MBeanServer) - Static method in class javax.management.MBeanServerFactory
Remove internal MBeanServerFactory references to a created MBeanServer.
releaseOutputStream() - Method in interface java.rmi.server.RemoteCall
Deprecated.
no replacement
releaseReply(Object, InputStream) - Method in class org.omg.CORBA.portable.Delegate
releaseReply may optionally be called by a stub to release a reply stream back to the ORB when the unmarshaling has completed.
releaseSavepoint(Savepoint) - Method in interface java.sql.Connection
Removes the specified Savepoint and subsequent Savepoint objects from the current transaction.
releaseService(BeanContextServices, Object, Object) - Method in interface java.beans.beancontext.BeanContextServiceProvider
Invoked by BeanContextServices, this method releases a nested BeanContextChild's (or any arbitrary object associated with a BeanContextChild) reference to the specified service.
releaseService(BeanContextChild, Object, Object) - Method in interface java.beans.beancontext.BeanContextServices
Releases a BeanContextChild's (or any arbitrary object associated with a BeanContextChild) reference to the specified service by calling releaseService() on the underlying BeanContextServiceProvider.
releaseService(BeanContextServices, Object, Object) - Method in class java.beans.beancontext.BeanContextServicesSupport.BCSSProxyServiceProvider
releaseService(BeanContextChild, Object, Object) - Method in class java.beans.beancontext.BeanContextServicesSupport
release a service
releaseShared(long) - Method in class java.util.concurrent.locks.AbstractQueuedLongSynchronizer
Releases in shared mode.
releaseShared(int) - Method in class java.util.concurrent.locks.AbstractQueuedSynchronizer
Releases in shared mode.
releaseWritableTile(int, int) - Method in class java.awt.image.BufferedImage
Relinquishes permission to write to a tile.
releaseWritableTile(int, int) - Method in interface java.awt.image.WritableRenderedImage
Relinquishes the right to write to a tile.
reload() - Method in class java.util.ServiceLoader
Clear this loader's provider cache so that all providers will be reloaded.
reload() - Method in class javax.swing.tree.DefaultTreeModel
Invoke this method if you've modified the TreeNodes upon which this model depends.
reload(TreeNode) - Method in class javax.swing.tree.DefaultTreeModel
Invoke this method if you've modified the TreeNodes upon which this model depends.
REMAINDER - Static variable in class java.awt.GridBagConstraints
Specifies that this component is the last component in its column or row.
remainder(BigDecimal) - Method in class java.math.BigDecimal
Returns a BigDecimal whose value is (this % divisor).
remainder(BigDecimal, MathContext) - Method in class java.math.BigDecimal
Returns a BigDecimal whose value is (this % divisor), with rounding according to the context settings.
remainder(BigInteger) - Method in class java.math.BigInteger
Returns a BigInteger whose value is (this % val).
remaining() - Method in class java.nio.Buffer
Returns the number of elements between the current position and the limit.
remainingCapacity() - Method in class java.util.concurrent.ArrayBlockingQueue
Returns the number of additional elements that this queue can ideally (in the absence of memory or resource constraints) accept without blocking.
remainingCapacity() - Method in interface java.util.concurrent.BlockingQueue
Returns the number of additional elements that this queue can ideally (in the absence of memory or resource constraints) accept without blocking, or Integer.MAX_VALUE if there is no intrinsic limit.
remainingCapacity() - Method in class java.util.concurrent.DelayQueue
Always returns Integer.MAX_VALUE because a DelayQueue is not capacity constrained.
remainingCapacity() - Method in class java.util.concurrent.LinkedBlockingDeque
Returns the number of additional elements that this deque can ideally (in the absence of memory or resource constraints) accept without blocking.
remainingCapacity() - Method in class java.util.concurrent.LinkedBlockingQueue
Returns the number of additional elements that this queue can ideally (in the absence of memory or resource constraints) accept without blocking.
remainingCapacity() - Method in class java.util.concurrent.LinkedTransferQueue
Always returns Integer.MAX_VALUE because a LinkedTransferQueue is not capacity constrained.
remainingCapacity() - Method in class java.util.concurrent.PriorityBlockingQueue
Always returns Integer.MAX_VALUE because a PriorityBlockingQueue is not capacity constrained.
remainingCapacity() - Method in class java.util.concurrent.SynchronousQueue
Always returns zero.
remainingName - Variable in exception javax.naming.NamingException
Contains the remaining name that has not been resolved yet.
remainingName - Variable in class javax.naming.spi.ResolveResult
Field containing the remaining name yet to be resolved.
remainingNewName - Variable in exception javax.naming.CannotProceedException
Contains the remaining unresolved part of the second "name" argument to Context.rename().
remapInstrument(Instrument, Instrument) - Method in interface javax.sound.midi.Synthesizer
Remaps an instrument.
RemarshalException - Exception in org.omg.CORBA.portable
This class is used for reporting locate forward exceptions and object forward GIOP messages back to the ORB.
RemarshalException() - Constructor for exception org.omg.CORBA.portable.RemarshalException
Constructs a RemarshalException.
Remote - Interface in java.rmi
The Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine.
RemoteCall - Interface in java.rmi.server
Deprecated.
no replacement.
remoteEquals(RemoteRef) - Method in interface java.rmi.server.RemoteRef
Compares two remote objects for equality.
RemoteException - Exception in java.rmi
A RemoteException is the common superclass for a number of communication-related exceptions that may occur during the execution of a remote method call.
RemoteException() - Constructor for exception java.rmi.RemoteException
Constructs a RemoteException.
RemoteException(String) - Constructor for exception java.rmi.RemoteException
Constructs a RemoteException with the specified detail message.
RemoteException(String, Throwable) - Constructor for exception java.rmi.RemoteException
Constructs a RemoteException with the specified detail message and cause.
remoteHashCode() - Method in interface java.rmi.server.RemoteRef
Returns a hashcode for a remote object.
RemoteObject - Class in java.rmi.server
The RemoteObject class implements the java.lang.Object behavior for remote objects.
RemoteObject() - Constructor for class java.rmi.server.RemoteObject
Creates a remote object.
RemoteObject(RemoteRef) - Constructor for class java.rmi.server.RemoteObject
Creates a remote object, initialized with the specified remote reference.
RemoteObjectInvocationHandler - Class in java.rmi.server
An implementation of the InvocationHandler interface for use with Java Remote Method Invocation (Java RMI).
RemoteObjectInvocationHandler(RemoteRef) - Constructor for class java.rmi.server.RemoteObjectInvocationHandler
Creates a new RemoteObjectInvocationHandler constructed with the specified RemoteRef.
RemoteRef - Interface in java.rmi.server
RemoteRef represents the handle for a remote object.
RemoteServer - Class in java.rmi.server
The RemoteServer class is the common superclass to server implementations and provides the framework to support a wide range of remote reference semantics.
RemoteServer() - Constructor for class java.rmi.server.RemoteServer
Constructs a RemoteServer.
RemoteServer(RemoteRef) - Constructor for class java.rmi.server.RemoteServer
Constructs a RemoteServer with the given reference type.
RemoteStub - Class in java.rmi.server
The RemoteStub class is the common superclass to client stubs and provides the framework to support a wide range of remote reference semantics.
RemoteStub() - Constructor for class java.rmi.server.RemoteStub
Constructs a RemoteStub.
RemoteStub(RemoteRef) - Constructor for class java.rmi.server.RemoteStub
Constructs a RemoteStub, with the specified remote reference.
remoteToString() - Method in interface java.rmi.server.RemoteRef
Returns a String that represents the reference of this remote object.
REMOVAL - Static variable in interface org.w3c.dom.events.MutationEvent
The Attr was just removed.
remove(EventListener) - Method in class java.awt.AWTEventMulticaster
Removes a listener from this multicaster.
remove(ComponentListener, ComponentListener) - Static method in class java.awt.AWTEventMulticaster
Removes the old component-listener from component-listener-l and returns the resulting multicast listener.
remove(ContainerListener, ContainerListener) - Static method in class java.awt.AWTEventMulticaster
Removes the old container-listener from container-listener-l and returns the resulting multicast listener.
remove(FocusListener, FocusListener) - Static method in class java.awt.AWTEventMulticaster
Removes the old focus-listener from focus-listener-l and returns the resulting multicast listener.
remove(KeyListener, KeyListener) - Static method in class java.awt.AWTEventMulticaster
Removes the old key-listener from key-listener-l and returns the resulting multicast listener.
remove(MouseListener, MouseListener) - Static method in class java.awt.AWTEventMulticaster
Removes the old mouse-listener from mouse-listener-l and returns the resulting multicast listener.
remove(MouseMotionListener, MouseMotionListener) - Static method in class java.awt.AWTEventMulticaster
Removes the old mouse-motion-listener from mouse-motion-listener-l and returns the resulting multicast listener.
remove(WindowListener, WindowListener) - Static method in class java.awt.AWTEventMulticaster
Removes the old window-listener from window-listener-l and returns the resulting multicast listener.
remove(WindowStateListener, WindowStateListener) - Static method in class java.awt.AWTEventMulticaster
Removes the old window-state-listener from window-state-listener-l and returns the resulting multicast listener.
remove(WindowFocusListener, WindowFocusListener) - Static method in class java.awt.AWTEventMulticaster
Removes the old window-focus-listener from window-focus-listener-l and returns the resulting multicast listener.
remove(ActionListener, ActionListener) - Static method in class java.awt.AWTEventMulticaster
Removes the old action-listener from action-listener-l and returns the resulting multicast listener.
remove(ItemListener, ItemListener) - Static method in class java.awt.AWTEventMulticaster
Removes the old item-listener from item-listener-l and returns the resulting multicast listener.
remove(AdjustmentListener, AdjustmentListener) - Static method in class java.awt.AWTEventMulticaster
Removes the old adjustment-listener from adjustment-listener-l and returns the resulting multicast listener.
remove(TextListener, TextListener) - Static method in class java.awt.AWTEventMulticaster
remove(InputMethodListener, InputMethodListener) - Static method in class java.awt.AWTEventMulticaster
Removes the old input-method-listener from input-method-listener-l and returns the resulting multicast listener.
remove(HierarchyListener, HierarchyListener) - Static method in class java.awt.AWTEventMulticaster
Removes the old hierarchy-listener from hierarchy-listener-l and returns the resulting multicast listener.
remove(HierarchyBoundsListener, HierarchyBoundsListener) - Static method in class java.awt.AWTEventMulticaster
Removes the old hierarchy-bounds-listener from hierarchy-bounds-listener-l and returns the resulting multicast listener.
remove(MouseWheelListener, MouseWheelListener) - Static method in class java.awt.AWTEventMulticaster
Removes the old mouse-wheel-listener from mouse-wheel-listener-l and returns the resulting multicast listener.
remove(String) - Method in class java.awt.Choice
Removes the first occurrence of item from the Choice menu.
remove(int) - Method in class java.awt.Choice
Removes an item from the choice menu at the specified position.
remove(MenuComponent) - Method in class java.awt.Component
Removes the specified popup menu from the component.
remove(int) - Method in class java.awt.Container
Removes the component, specified by index, from this container.
remove(Component) - Method in class java.awt.Container
Removes the specified component from this container.
remove(MenuComponent) - Method in class java.awt.Frame
Removes the specified menu bar from this frame.
remove(String) - Method in class java.awt.List
Removes the first occurrence of an item from the list.
remove(int) - Method in class java.awt.List
Removes the item at the specified position from this scrolling list.
remove(int) - Method in class java.awt.Menu
Removes the menu item at the specified index from this menu.
remove(MenuComponent) - Method in class java.awt.Menu
Removes the specified menu item from this menu.
remove(int) - Method in class java.awt.MenuBar
Removes the menu located at the specified index from this menu bar.
remove(MenuComponent) - Method in class java.awt.MenuBar
Removes the specified menu component from this menu bar.
remove(MenuComponent) - Method in interface java.awt.MenuContainer
remove(Object) - Method in class java.awt.RenderingHints
Removes the key and its corresponding value from this RenderingHints object.
remove(TrayIcon) - Method in class java.awt.SystemTray
Removes the specified TrayIcon from the SystemTray.
remove() - Method in class java.beans.beancontext.BeanContextSupport.BCSIterator
remove(Object) - Method in class java.beans.beancontext.BeanContextSupport
Removes a child from this BeanContext.
remove(Object, boolean) - Method in class java.beans.beancontext.BeanContextSupport
internal remove used when removal caused by unexpected setBeanContext or by remove() invocation.
remove(Object) - Method in class java.beans.Encoder
Removes the entry for this instance, returning the old entry.
remove(Class<?>) - Method in class java.lang.ClassValue
Removes the associated value for the given class.
remove(long) - Method in class java.lang.ref.ReferenceQueue
Removes the next reference object in this queue, blocking until either one becomes available or the given timeout period expires.
remove() - Method in class java.lang.ref.ReferenceQueue
Removes the next reference object in this queue, blocking until one becomes available.
remove() - Method in class java.lang.ThreadLocal
Removes the current thread's value for this thread-local variable.
remove(URI, HttpCookie) - Method in interface java.net.CookieStore
Remove a cookie from store.
remove(Object) - Method in class java.security.Provider
Removes the key property (and its corresponding value).
remove(Object) - Method in class java.util.AbstractCollection
Removes a single instance of the specified element from this collection, if it is present (optional operation).
remove(int) - Method in class java.util.AbstractList
Removes the element at the specified position in this list (optional operation).
remove(Object) - Method in class java.util.AbstractMap
Removes the mapping for a key from this map if it is present (optional operation).
remove() - Method in class java.util.AbstractQueue
Retrieves and removes the head of this queue.
remove(int) - Method in class java.util.AbstractSequentialList
Removes the element at the specified position in this list (optional operation).
remove() - Method in class java.util.ArrayDeque
Retrieves and removes the head of the queue represented by this deque.
remove(Object) - Method in class java.util.ArrayDeque
Removes a single instance of the specified element from this deque.
remove(int) - Method in class java.util.ArrayList
Removes the element at the specified position in this list.
remove(Object) - Method in class java.util.ArrayList
Removes the first occurrence of the specified element from this list, if it is present.
remove(Object) - Method in interface java.util.Collection
Removes a single instance of the specified element from this collection, if it is present (optional operation).
remove(Object) - Method in class java.util.concurrent.ArrayBlockingQueue
Removes a single instance of the specified element from this queue, if it is present.
remove() - Method in interface java.util.concurrent.BlockingDeque
Retrieves and removes the head of the queue represented by this deque (in other words, the first element of this deque).
remove(Object) - Method in interface java.util.concurrent.BlockingDeque
Removes the first occurrence of the specified element from this deque.
remove(Object) - Method in interface java.util.concurrent.BlockingQueue
Removes a single instance of the specified element from this queue, if it is present.
remove(Object) - Method in class java.util.concurrent.ConcurrentHashMap
Removes the key (and its corresponding value) from this map.
remove(Object, Object) - Method in class java.util.concurrent.ConcurrentHashMap
Removes the entry for a key only if currently mapped to a given value.
remove() - Method in class java.util.concurrent.ConcurrentLinkedDeque
remove(Object) - Method in class java.util.concurrent.ConcurrentLinkedDeque
Removes the first element e such that o.equals(e), if such an element exists in this deque.
remove(Object) - Method in class java.util.concurrent.ConcurrentLinkedQueue
Removes a single instance of the specified element from this queue, if it is present.
remove(Object, Object) - Method in interface java.util.concurrent.ConcurrentMap
Removes the entry for a key only if currently mapped to a given value.
remove(Object) - Method in class java.util.concurrent.ConcurrentSkipListMap
Removes the mapping for the specified key from this map if present.
remove(Object, Object) - Method in class java.util.concurrent.ConcurrentSkipListMap
Removes the entry for a key only if currently mapped to a given value.
remove(Object) - Method in class java.util.concurrent.ConcurrentSkipListSet
Removes the specified element from this set if it is present.
remove(int) - Method in class java.util.concurrent.CopyOnWriteArrayList
Removes the element at the specified position in this list.
remove(Object) - Method in class java.util.concurrent.CopyOnWriteArrayList
Removes the first occurrence of the specified element from this list, if it is present.
remove(Object) - Method in class java.util.concurrent.CopyOnWriteArraySet
Removes the specified element from this set if it is present.
remove(Object) - Method in class java.util.concurrent.DelayQueue
Removes a single instance of the specified element from this queue, if it is present, whether or not it has expired.
remove() - Method in class java.util.concurrent.LinkedBlockingDeque
Retrieves and removes the head of the queue represented by this deque.
remove(Object) - Method in class java.util.concurrent.LinkedBlockingDeque
Removes the first occurrence of the specified element from this deque.
remove(Object) - Method in class java.util.concurrent.LinkedBlockingQueue
Removes a single instance of the specified element from this queue, if it is present.
remove(Object) - Method in class java.util.concurrent.LinkedTransferQueue
Removes a single instance of the specified element from this queue, if it is present.
remove(Object) - Method in class java.util.concurrent.PriorityBlockingQueue
Removes a single instance of the specified element from this queue, if it is present.
remove(Object) - Method in class java.util.concurrent.SynchronousQueue
Always returns false.
remove(Runnable) - Method in class java.util.concurrent.ThreadPoolExecutor
Removes this task from the executor's internal queue if it is present, thus causing it not to be run if it has not already started.
remove() - Method in interface java.util.Deque
Retrieves and removes the head of the queue represented by this deque (in other words, the first element of this deque).
remove(Object) - Method in interface java.util.Deque
Removes the first occurrence of the specified element from this deque.
remove(Object) - Method in class java.util.Dictionary
Removes the key (and its corresponding value) from this dictionary.
remove(Object) - Method in class java.util.EnumMap
Removes the mapping for this key from this map if present.
remove(Object) - Method in class java.util.HashMap
Removes the mapping for the specified key from this map if present.
remove(Object) - Method in class java.util.HashSet
Removes the specified element from this set if it is present.
remove(Object) - Method in class java.util.Hashtable
Removes the key (and its corresponding value) from this hashtable.
remove(Object) - Method in class java.util.IdentityHashMap
Removes the mapping for this key from this map if present.
remove() - Method in interface java.util.Iterator
Removes from the underlying collection the last element returned by this iterator (optional operation).
remove(Object) - Method in class java.util.jar.Attributes
Removes the attribute with the specified name (key) from this Map.
remove(Object) - Method in class java.util.LinkedList
Removes the first occurrence of the specified element from this list, if it is present.
remove(int) - Method in class java.util.LinkedList
Removes the element at the specified position in this list.
remove() - Method in class java.util.LinkedList
Retrieves and removes the head (first element) of this list.
remove(Object) - Method in interface java.util.List
Removes the first occurrence of the specified element from this list, if it is present (optional operation).
remove(int) - Method in interface java.util.List
Removes the element at the specified position in this list (optional operation).
remove() - Method in interface java.util.ListIterator
Removes from the list the last element that was returned by ListIterator.next() or ListIterator.previous() (optional operation).
remove(Object) - Method in interface java.util.Map
Removes the mapping for a key from this map if it is present (optional operation).
remove(String) - Method in class java.util.prefs.AbstractPreferences
Implements the remove(String) method as per the specification in Preferences.remove(String).
remove(String) - Method in class java.util.prefs.Preferences
Removes the value associated with the specified key in this preference node, if any.
remove(Object) - Method in class java.util.PriorityQueue
Removes a single instance of the specified element from this queue, if it is present.
remove() - Method in interface java.util.Queue
Retrieves and removes the head of this queue.
remove() - Method in class java.util.Scanner
The remove operation is not supported by this implementation of Iterator.
remove(Object) - Method in interface java.util.Set
Removes the specified element from this set if it is present (optional operation).
remove(Object) - Method in class java.util.TreeMap
Removes the mapping for this key from this TreeMap if present.
remove(Object) - Method in class java.util.TreeSet
Removes the specified element from this set if it is present.
remove(Object) - Method in class java.util.Vector
Removes the first occurrence of the specified element in this Vector If the Vector does not contain the element, it is unchanged.
remove(int) - Method in class java.util.Vector
Removes the element at the specified position in this Vector.
remove(Object) - Method in class java.util.WeakHashMap
Removes the mapping for a key from this weak hash map if it is present.
remove(AccessibleRelation) - Method in class javax.accessibility.AccessibleRelationSet
Removes a relation from the current relation set.
remove(AccessibleState) - Method in class javax.accessibility.AccessibleStateSet
Removes a state from the current state set.
remove(String) - Method in class javax.activation.MimeTypeParameterList
Remove any value associated with the given name.
remove(Object[]) - Method in interface javax.management.openmbean.TabularData
Removes the CompositeData value whose index is key from this TabularData instance, and returns the removed value, or returns null if there is no value whose index is key.
remove(Object) - Method in class javax.management.openmbean.TabularDataSupport
This method simply calls remove((Object[]) key).
remove(Object[]) - Method in class javax.management.openmbean.TabularDataSupport
Removes the CompositeData value whose index is key from this TabularData instance, and returns the removed value, or returns null if there is no value whose index is key.
remove(int) - Method in class javax.naming.CompositeName
Deletes a component from this composite name.
remove(int) - Method in class javax.naming.CompoundName
Deletes a component from this compound name.
remove(Object) - Method in interface javax.naming.directory.Attribute
Removes a specified value from the attribute.
remove(int) - Method in interface javax.naming.directory.Attribute
Removes an attribute value from the ordered list of attribute values.
remove(String) - Method in interface javax.naming.directory.Attributes
Removes the attribute with the attribute id 'attrID' from the attribute set.
remove(Object) - Method in class javax.naming.directory.BasicAttribute
Removes a specified value from this attribute.
remove(int) - Method in class javax.naming.directory.BasicAttribute
remove(String) - Method in class javax.naming.directory.BasicAttributes
remove(int) - Method in class javax.naming.ldap.LdapName
Removes a component from this LDAP name.
remove(int) - Method in interface javax.naming.Name
Removes a component from this name.
remove(int) - Method in class javax.naming.Reference
Deletes the address at index posn from the list of addresses.
remove(Class<?>) - Method in interface javax.print.attribute.AttributeSet
Removes any attribute for this category from this attribute set if present.
remove(Attribute) - Method in interface javax.print.attribute.AttributeSet
Removes the specified attribute from this attribute set if present.
remove(Class<?>) - Method in class javax.print.attribute.HashAttributeSet
Removes any attribute for this category from this attribute set if present.
remove(Attribute) - Method in class javax.print.attribute.HashAttributeSet
Removes the specified attribute from this attribute set if present.
remove(Object) - Method in interface javax.script.Bindings
Removes the mapping for this key from this map if it is present (optional operation).
remove(Object) - Method in class javax.script.SimpleBindings
Removes the mapping for this key from this map if it is present (optional operation).
remove(MidiEvent) - Method in class javax.sound.midi.Track
Removes the specified event from the track.
remove(Object) - Method in class javax.swing.ActionMap
Removes the binding for key from this ActionMap.
remove(AbstractButton) - Method in class javax.swing.ButtonGroup
Removes the button from the group.
remove(KeyStroke) - Method in class javax.swing.ComponentInputMap
Removes the binding for key from this object.
remove(int) - Method in class javax.swing.DefaultListModel
Removes the element at the specified position in this list.
REMOVE - Static variable in class javax.swing.event.DocumentEvent.EventType
Remove type.
remove(Class<T>, T) - Method in class javax.swing.event.EventListenerList
Removes the listener as a listener of the specified type.
remove(KeyStroke) - Method in class javax.swing.InputMap
Removes the binding for key from this InputMap.
remove(Component) - Method in class javax.swing.JApplet
Removes the specified component from the container.
remove(int) - Method in class javax.swing.JDesktopPane
Remove the indexed component from this pane.
remove(Component) - Method in class javax.swing.JDialog
Removes the specified component from the container.
remove(Component) - Method in class javax.swing.JFrame
Removes the specified component from the container.
remove(Component) - Method in class javax.swing.JInternalFrame
Removes the specified component from the container.
remove(Component) - Method in class javax.swing.JLayer
Removes the specified component from this container.
remove(int) - Method in class javax.swing.JLayeredPane
Remove the indexed component from this pane.
remove(JMenuItem) - Method in class javax.swing.JMenu
Removes the specified menu item from this menu.
remove(int) - Method in class javax.swing.JMenu
Removes the menu item at the specified index from this menu.
remove(Component) - Method in class javax.swing.JMenu
Removes the component c from this menu.
remove(int) - Method in class javax.swing.JPopupMenu
Removes the component at the specified index from this popup menu.
remove(Component) - Method in class javax.swing.JSplitPane
Removes the child component, component from the pane.
remove(int) - Method in class javax.swing.JSplitPane
Removes the Component at the specified index.
remove(Component) - Method in class javax.swing.JTabbedPane
Removes the specified Component from the JTabbedPane.
remove(int) - Method in class javax.swing.JTabbedPane
Removes the tab and component which corresponds to the specified index.
remove(Component) - Method in class javax.swing.JViewport
Removes the Viewports one lightweight child.
remove(Component) - Method in class javax.swing.JWindow
Removes the specified component from the container.
remove(int, int) - Method in interface javax.swing.text.AbstractDocument.Content
Removes some portion of the sequence.
remove(int, int) - Method in class javax.swing.text.AbstractDocument
Removes some content from the document.
remove(int, int, AbstractDocument.DefaultDocumentEvent) - Method in class javax.swing.text.DefaultStyledDocument.ElementBuffer
Removes content.
remove(int, int) - Method in interface javax.swing.text.Document
Removes a portion of the content of the document.
remove(int, int) - Method in class javax.swing.text.DocumentFilter.FilterBypass
Removes the specified region of text, bypassing the DocumentFilter.
remove(DocumentFilter.FilterBypass, int, int) - Method in class javax.swing.text.DocumentFilter
Invoked prior to removal of the specified region in the specified Document.
remove(int, int) - Method in class javax.swing.text.GapContent
Removes part of the content.
remove(int, int) - Method in class javax.swing.text.StringContent
Removes part of the content.
remove(int) - Method in class javax.swing.text.View
Removes one of the children at the given position.
remove(int) - Method in class javax.swing.tree.DefaultMutableTreeNode
Removes the child at the specified index from this node's children and sets that node's parent to null.
remove(MutableTreeNode) - Method in class javax.swing.tree.DefaultMutableTreeNode
Removes aChild from this node's child array, giving it a null parent.
remove(int) - Method in interface javax.swing.tree.MutableTreeNode
Removes the child at index from the receiver.
remove(MutableTreeNode) - Method in interface javax.swing.tree.MutableTreeNode
Removes node from the receiver.
remove() - Method in class javax.xml.stream.util.EventReaderDelegate
remove(int) - Method in class org.omg.CORBA.ContextList
Removes the String object at the given index.
remove(int) - Method in class org.omg.CORBA.ExceptionList
Removes the TypeCode object at the given index.
remove(int) - Method in class org.omg.CORBA.NVList
Removes the NamedValue object at the given index.
REMOVE_ATTRIBUTE - Static variable in interface javax.naming.directory.DirContext
This constant specifies to delete the specified attribute values from the attribute.
removeAccessibleSelection(int) - Method in class java.awt.List.AccessibleAWTList
Removes the specified selected item in the object from the object's selection.
removeAccessibleSelection(int) - Method in class java.awt.MenuComponent.AccessibleAWTMenuComponent
Removes the specified child of the object from the object's selection.
removeAccessibleSelection(int) - Method in interface javax.accessibility.AccessibleSelection
Removes the specified child of the object from the object's selection.
removeAccessibleSelection(int) - Method in class javax.swing.JComboBox.AccessibleJComboBox
Removes the specified child of the object from the object's selection.
removeAccessibleSelection(int) - Method in class javax.swing.JList.AccessibleJList
Removes the specified selected item in the object from the object's selection.
removeAccessibleSelection(int) - Method in class javax.swing.JMenu.AccessibleJMenu
Removes the nth item from the selection.
removeAccessibleSelection(int) - Method in class javax.swing.JMenuBar.AccessibleJMenuBar
Removes the nth selected item in the object from the object's selection.
removeAccessibleSelection(int) - Method in class javax.swing.JTabbedPane.AccessibleJTabbedPane
removeAccessibleSelection(int) - Method in class javax.swing.JTable.AccessibleJTable
Removes the specified child of the object from the object's selection.
removeAccessibleSelection(int) - Method in class javax.swing.JTree.AccessibleJTree.AccessibleJTreeNode
Removes the specified selected item in the object from the object's selection.
removeAccessibleSelection(int) - Method in class javax.swing.JTree.AccessibleJTree
Removes the specified selected item in the object from the object's selection.
removeActionListener(ActionListener) - Method in class java.awt.Button
Removes the specified action listener so that it no longer receives action events from this button.
removeActionListener(ActionListener) - Method in class java.awt.List
Removes the specified action listener so that it no longer receives action events from this list.
removeActionListener(ActionListener) - Method in class java.awt.MenuItem
Removes the specified action listener so it no longer receives action events from this menu item.
removeActionListener(ActionListener) - Method in class java.awt.TextField
Removes the specified action listener so that it no longer receives action events from this text field.
removeActionListener(ActionListener) - Method in class java.awt.TrayIcon
Removes the specified action listener.
removeActionListener(ActionListener) - Method in class javax.swing.AbstractButton
Removes an ActionListener from the button.
removeActionListener(ActionListener) - Method in interface javax.swing.ButtonModel
Removes an ActionListener from the model.
removeActionListener(ActionListener) - Method in interface javax.swing.ComboBoxEditor
Remove an ActionListener
removeActionListener(ActionListener) - Method in class javax.swing.DefaultButtonModel
Removes an ActionListener from the model.
removeActionListener(ActionListener) - Method in class javax.swing.JComboBox
Removes an ActionListener.
removeActionListener(ActionListener) - Method in class javax.swing.JFileChooser
Removes an ActionListener from the file chooser.
removeActionListener(ActionListener) - Method in class javax.swing.JTextField
Removes the specified action listener so that it no longer receives action events from this textfield.
removeActionListener(ActionListener) - Method in class javax.swing.plaf.basic.BasicComboBoxEditor
removeActionListener(ActionListener) - Method in class javax.swing.Timer
Removes the specified action listener from the Timer.
removeAdjustmentListener(AdjustmentListener) - Method in interface java.awt.Adjustable
Removes an adjustment listener.
removeAdjustmentListener(AdjustmentListener) - Method in class java.awt.Scrollbar
Removes the specified adjustment listener so that it no longer receives instances of AdjustmentEvent from this scroll bar.
removeAdjustmentListener(AdjustmentListener) - Method in class java.awt.ScrollPaneAdjustable
Removes the specified adjustment listener so that it no longer receives adjustment events from this ScrollPaneAdjustable.
removeAdjustmentListener(AdjustmentListener) - Method in class javax.swing.JScrollBar
Removes an AdjustmentEvent listener.
removeAll() - Method in class java.awt.Choice
Removes all items from the choice menu.
removeAll() - Method in class java.awt.Container
Removes all the components from this container.
removeAll() - Method in class java.awt.List
Removes all items from this list.
removeAll() - Method in class java.awt.Menu
Removes all items from this menu.
removeAll(Collection) - Method in class java.beans.beancontext.BeanContextSupport
remove all specified children (Unsupported) implementations must synchronized on the hierarchy lock and "children" protected field
removeAll() - Method in interface java.net.CookieStore
Remove all cookies in this cookie store.
removeAll(Collection<?>) - Method in class java.util.AbstractCollection
Removes all of this collection's elements that are also contained in the specified collection (optional operation).
removeAll(Collection<?>) - Method in class java.util.AbstractSet
Removes from this set all of its elements that are contained in the specified collection (optional operation).
removeAll(Collection<?>) - Method in class java.util.ArrayList
Removes from this list all of its elements that are contained in the specified collection.
removeAll(Collection<?>) - Method in interface java.util.Collection
Removes all of this collection's elements that are also contained in the specified collection (optional operation).
removeAll(Collection<?>) - Method in class java.util.concurrent.ConcurrentSkipListSet
Removes from this set all of its elements that are contained in the specified collection.
removeAll(Collection<?>) - Method in class java.util.concurrent.CopyOnWriteArrayList
Removes from this list all of its elements that are contained in the specified collection.
removeAll(Collection<?>) - Method in class java.util.concurrent.CopyOnWriteArraySet
Removes from this set all of its elements that are contained in the specified collection.
removeAll(Collection<?>) - Method in class java.util.concurrent.SynchronousQueue
Always returns false.
removeAll(Collection<?>) - Method in interface java.util.List
Removes from this list all of its elements that are contained in the specified collection (optional operation).
removeAll(Collection<?>) - Method in interface java.util.Set
Removes from this set all of its elements that are contained in the specified collection (optional operation).
removeAll(Collection<?>) - Method in class java.util.Vector
Removes from this Vector all of its elements that are contained in the specified Collection.
removeAll() - Method in class javax.swing.JDesktopPane
Removes all the components from this container.
removeAll() - Method in class javax.swing.JLayer
Removes all the components from this container.
removeAll() - Method in class javax.swing.JLayeredPane
Removes all the components from this container.
removeAll() - Method in class javax.swing.JMenu
Removes all menu items from this menu.
removeAll() - Method in class javax.swing.JSplitPane
Removes all the child components from the split pane.
removeAll() - Method in class javax.swing.JTabbedPane
Removes all the tabs and their corresponding components from the tabbedpane.
removeAll() - Method in class javax.swing.text.View
Removes all of the children.
removeAllAttachments() - Method in class javax.xml.soap.SOAPMessage
Removes all AttachmentPart objects that have been added to this SOAPMessage object.
removeAllChildren() - Method in class javax.swing.tree.DefaultMutableTreeNode
Removes all of this node's children, setting their parents to null.
removeAllElements() - Method in class java.util.Vector
Removes all components from this vector and sets its size to zero.
removeAllElements() - Method in class javax.swing.DefaultComboBoxModel
Empties the list.
removeAllElements() - Method in class javax.swing.DefaultListModel
Removes all components from this list and sets its size to zero.
removeAllFaultSubcodes() - Method in interface javax.xml.soap.SOAPFault
Removes any Subcodes that may be contained by this SOAPFault.
removeAllHeaders() - Method in class javax.xml.soap.MimeHeaders
Removes all the header entries from this MimeHeaders object.
removeAllHighlights() - Method in class javax.swing.text.DefaultHighlighter
Removes all highlights.
removeAllHighlights() - Method in interface javax.swing.text.Highlighter
Removes all highlights this highlighter is responsible for.
removeAllIIOReadProgressListeners() - Method in class javax.imageio.ImageReader
Removes all currently registered IIOReadProgressListener objects.
removeAllIIOReadUpdateListeners() - Method in class javax.imageio.ImageReader
Removes all currently registered IIOReadUpdateListener objects.
removeAllIIOReadWarningListeners() - Method in class javax.imageio.ImageReader
Removes all currently registered IIOReadWarningListener objects.
removeAllIIOWriteProgressListeners() - Method in class javax.imageio.ImageWriter
Removes all currently registered IIOWriteProgressListener objects.
removeAllIIOWriteWarningListeners() - Method in class javax.imageio.ImageWriter
Removes all currently registered IIOWriteWarningListener objects.
removeAllItems() - Method in class javax.swing.JComboBox
Removes all items from the item list.
removeAllMimeHeaders() - Method in class javax.xml.soap.AttachmentPart
Removes all the MIME header entries.
removeAllMimeHeaders() - Method in class javax.xml.soap.SOAPPart
Removes all the MimeHeader objects for this SOAPEnvelope object.
removeAllNotifications() - Method in class javax.management.timer.Timer
Removes all the timer notifications from the list of notifications and resets the counter used to update the timer notification identifiers.
removeAllNotifications() - Method in interface javax.management.timer.TimerMBean
Removes all the timer notifications from the list of notifications and resets the counter used to update the timer notification identifiers.
removeAncestorListener(AncestorListener) - Method in class javax.swing.JComponent
Unregisters listener so that it will no longer receive AncestorEvents.
removeAttachments(MimeHeaders) - Method in class javax.xml.soap.SOAPMessage
Removes all the AttachmentPart objects that have header entries that match the specified headers.
removeAttribute(String, String) - Method in class javax.imageio.metadata.IIOMetadataFormatImpl
Removes an attribute from a previously defined element.
removeAttribute(String) - Method in class javax.imageio.metadata.IIOMetadataNode
removeAttribute(String, int) - Method in interface javax.script.ScriptContext
Remove an attribute in a given scope.
removeAttribute(String, int) - Method in class javax.script.SimpleScriptContext
Remove an attribute in a given scope.
removeAttribute(Object) - Method in class javax.swing.text.AbstractDocument.AbstractElement
Removes an attribute from the set.
removeAttribute(AttributeSet, Object) - Method in interface javax.swing.text.AbstractDocument.AttributeContext
Removes an attribute from the set.
removeAttribute(AttributeSet, Object) - Method in class javax.swing.text.html.StyleSheet
Removes an attribute from the set.
removeAttribute(Object) - Method in interface javax.swing.text.MutableAttributeSet
Removes an attribute with the given name.
removeAttribute(Object) - Method in class javax.swing.text.SimpleAttributeSet
Removes an attribute from the list.
removeAttribute(Object) - Method in class javax.swing.text.StyleContext.NamedStyle
Removes an attribute from the set.
removeAttribute(AttributeSet, Object) - Method in class javax.swing.text.StyleContext
Removes an attribute from the set.
removeAttribute(Name) - Method in interface javax.xml.soap.SOAPElement
Removes the attribute with the specified name.
removeAttribute(QName) - Method in interface javax.xml.soap.SOAPElement
Removes the attribute with the specified qname.
removeAttribute(String) - Method in interface org.w3c.dom.Element
Removes an attribute by name.
removeAttribute(int) - Method in class org.xml.sax.ext.Attributes2Impl
removeAttribute(String) - Method in class org.xml.sax.helpers.AttributeListImpl
Deprecated.
Remove an attribute from the list.
removeAttribute(int) - Method in class org.xml.sax.helpers.AttributesImpl
Remove an attribute from the list.
removeAttributeChangeNotificationListener(NotificationListener, String) - Method in interface javax.management.modelmbean.ModelMBeanNotificationBroadcaster
Removes a listener for attributeChangeNotifications from the RequiredModelMBean.
removeAttributeChangeNotificationListener(NotificationListener, String) - Method in class javax.management.modelmbean.RequiredModelMBean
removeAttributeNode(Attr) - Method in class javax.imageio.metadata.IIOMetadataNode
removeAttributeNode(Attr) - Method in interface org.w3c.dom.Element
Removes the specified attribute node.
removeAttributeNS(String, String) - Method in class javax.imageio.metadata.IIOMetadataNode
Equivalent to removeAttribute(localName).
removeAttributeNS(String, String) - Method in interface org.w3c.dom.Element
Removes an attribute by local name and namespace URI.
removeAttributes(Enumeration<?>) - Method in class javax.swing.text.AbstractDocument.AbstractElement
Removes a set of attributes for the element.
removeAttributes(AttributeSet) - Method in class javax.swing.text.AbstractDocument.AbstractElement
Removes a set of attributes for the element.
removeAttributes(AttributeSet, Enumeration<?>) - Method in interface javax.swing.text.AbstractDocument.AttributeContext
Removes a set of attributes for the element.
removeAttributes(AttributeSet, AttributeSet) - Method in interface javax.swing.text.AbstractDocument.AttributeContext
Removes a set of attributes for the element.
removeAttributes(AttributeSet, Enumeration<?>) - Method in class javax.swing.text.html.StyleSheet
Removes a set of attributes for the element.
removeAttributes(AttributeSet, AttributeSet) - Method in class javax.swing.text.html.StyleSheet
Removes a set of attributes.
removeAttributes(Enumeration<?>) - Method in interface javax.swing.text.MutableAttributeSet
Removes an attribute set with the given names.
removeAttributes(AttributeSet) - Method in interface javax.swing.text.MutableAttributeSet
Removes a set of attributes with the given name.
removeAttributes(Enumeration<?>) - Method in class javax.swing.text.SimpleAttributeSet
Removes a set of attributes from the list.
removeAttributes(AttributeSet) - Method in class javax.swing.text.SimpleAttributeSet
Removes a set of attributes from the list.
removeAttributes(Enumeration<?>) - Method in class javax.swing.text.StyleContext.NamedStyle
Removes a set of attributes for the element.
removeAttributes(AttributeSet) - Method in class javax.swing.text.StyleContext.NamedStyle
Removes a set of attributes for the element.
removeAttributes(AttributeSet, Enumeration<?>) - Method in class javax.swing.text.StyleContext
Removes a set of attributes for the element.
removeAttributes(AttributeSet, AttributeSet) - Method in class javax.swing.text.StyleContext
Removes a set of attributes for the element.
removeAuxiliaryLookAndFeel(LookAndFeel) - Static method in class javax.swing.UIManager
Removes a LookAndFeel from the list of auxiliary look and feels.
removeAWTEventListener(AWTEventListener) - Method in class java.awt.Toolkit
Removes an AWTEventListener from receiving dispatched AWTEvents.
removeBeanContextMembershipListener(BeanContextMembershipListener) - Method in interface java.beans.beancontext.BeanContext
Removes the specified BeanContextMembershipListener so that it no longer receives BeanContextMembershipEvents when the child Component(s) are added or removed.
removeBeanContextMembershipListener(BeanContextMembershipListener) - Method in class java.beans.beancontext.BeanContextSupport
Removes a BeanContextMembershipListener
removeBeanContextServicesListener(BeanContextServicesListener) - Method in interface java.beans.beancontext.BeanContextServices
Removes a BeanContextServicesListener from this BeanContext
removeBeanContextServicesListener(BeanContextServicesListener) - Method in class java.beans.beancontext.BeanContextServicesSupport
remove a BeanContextServicesListener
removeBindings() - Method in interface javax.swing.text.Keymap
Removes all bindings from the keymap.
removeCaretListener(CaretListener) - Method in class javax.swing.text.JTextComponent
Removes a caret listener.
removeCellEditorListener(CellEditorListener) - Method in class javax.swing.AbstractCellEditor
Removes a CellEditorListener from the listener list.
removeCellEditorListener(CellEditorListener) - Method in interface javax.swing.CellEditor
Removes a listener from the list that's notified
removeCellEditorListener(CellEditorListener) - Method in class javax.swing.tree.DefaultTreeCellEditor
Removes the previously added CellEditorListener.
removeCertificate(Certificate) - Method in class java.security.Identity
Deprecated.
Removes a certificate from this identity.
removeChangeListener(ChangeListener) - Method in class javax.swing.AbstractButton
Removes a ChangeListener from the button.
removeChangeListener(ChangeListener) - Method in class javax.swing.AbstractSpinnerModel
Removes a ChangeListener from the model's listener list.
removeChangeListener(ChangeListener) - Method in interface javax.swing.BoundedRangeModel
Removes a ChangeListener from the model's listener list.
removeChangeListener(ChangeListener) - Method in interface javax.swing.ButtonModel
Removes a ChangeListener from the model.
removeChangeListener(ChangeListener) - Method in interface javax.swing.colorchooser.ColorSelectionModel
Removes listener as a listener to changes in the model.
removeChangeListener(ChangeListener) - Method in class javax.swing.colorchooser.DefaultColorSelectionModel
Removes a ChangeListener from the model.
removeChangeListener(ChangeListener) - Method in class javax.swing.DefaultBoundedRangeModel
Removes a ChangeListener.
removeChangeListener(ChangeListener) - Method in class javax.swing.DefaultButtonModel
Removes a ChangeListener from the model.
removeChangeListener(ChangeListener) - Method in class javax.swing.DefaultSingleSelectionModel
Removes a ChangeListener from the button.
removeChangeListener(ChangeListener) - Method in class javax.swing.JProgressBar
Removes a ChangeListener from the progress bar.
removeChangeListener(ChangeListener) - Method in class javax.swing.JSlider
Removes a ChangeListener from the slider.
removeChangeListener(ChangeListener) - Method in class javax.swing.JSpinner
Removes a ChangeListener from this spinner.
removeChangeListener(ChangeListener) - Method in class javax.swing.JTabbedPane
Removes a ChangeListener from this tabbedpane.
removeChangeListener(ChangeListener) - Method in class javax.swing.JViewport
Removes a ChangeListener from the list that's notified each time the views size, position, or the viewports extent size has changed.
removeChangeListener(ChangeListener) - Method in class javax.swing.MenuSelectionManager
Removes a ChangeListener from the button.
removeChangeListener(ChangeListener) - Method in interface javax.swing.SingleSelectionModel
Removes listener as a listener to changes in the model.
removeChangeListener(ChangeListener) - Method in interface javax.swing.SpinnerModel
Removes a ChangeListener from the model's listener list.
removeChangeListener(ChangeListener) - Method in interface javax.swing.text.Caret
Removes a listener that was tracking caret position changes.
removeChangeListener(ChangeListener) - Method in class javax.swing.text.DefaultCaret
Removes a listener that was tracking caret position changes.
removeChangeListener(ChangeListener) - Method in interface javax.swing.text.Style
Removes a listener that was tracking attribute changes.
removeChangeListener(ChangeListener) - Method in class javax.swing.text.StyleContext.NamedStyle
Removes a change listener.
removeChangeListener(ChangeListener) - Method in class javax.swing.text.StyleContext
Removes a listener that was tracking styles being added or removed.
removeChild(Node) - Method in class javax.imageio.metadata.IIOMetadataNode
Removes the child node indicated by oldChild from the list of children, and returns it.
removeChild(Node) - Method in interface org.w3c.dom.Node
Removes the child node indicated by oldChild from the list of children, and returns it.
removeChoosableFileFilter(FileFilter) - Method in class javax.swing.JFileChooser
Removes a filter from the list of user choosable file filters.
removeChooserPanel(AbstractColorChooserPanel) - Method in class javax.swing.JColorChooser
Removes the Color Panel specified.
removeColumn(TableColumn) - Method in class javax.swing.JTable
Removes aColumn from this JTable's array of columns.
removeColumn(TableColumn) - Method in class javax.swing.table.DefaultTableColumnModel
Deletes the column from the tableColumns array.
removeColumn(TableColumn) - Method in interface javax.swing.table.TableColumnModel
Deletes the TableColumn column from the tableColumns array.
removeColumnModelListener(TableColumnModelListener) - Method in class javax.swing.table.DefaultTableColumnModel
Removes a listener for table column model events.
removeColumnModelListener(TableColumnModelListener) - Method in interface javax.swing.table.TableColumnModel
Removes a listener for table column model events.
removeColumnSelectionInterval(int, int) - Method in class javax.swing.JTable
Deselects the columns from index0 to index1, inclusive.
removeComponentListener(ComponentListener) - Method in class java.awt.Component
Removes the specified component listener so that it no longer receives component events from this component.
removeConnectionEventListener(ConnectionEventListener) - Method in interface javax.sql.PooledConnection
Removes the given event listener from the list of components that will be notified when an event occurs on this PooledConnection object.
removeConnectionNotificationListener(NotificationListener) - Method in interface javax.management.remote.JMXConnector
Removes a listener from the list to be informed of changes in status.
removeConnectionNotificationListener(NotificationListener, NotificationFilter, Object) - Method in interface javax.management.remote.JMXConnector
Removes a listener from the list to be informed of changes in status.
removeConnectionNotificationListener(NotificationListener) - Method in class javax.management.remote.rmi.RMIConnector
removeConnectionNotificationListener(NotificationListener, NotificationFilter, Object) - Method in class javax.management.remote.rmi.RMIConnector
removeConsumer(ImageConsumer) - Method in class java.awt.image.FilteredImageSource
Removes an ImageConsumer from the list of consumers interested in data for this image.
removeConsumer(ImageConsumer) - Method in interface java.awt.image.ImageProducer
Removes the specified ImageConsumer object from the list of consumers currently registered to receive image data.
removeConsumer(ImageConsumer) - Method in class java.awt.image.MemoryImageSource
Removes an ImageConsumer from the list of consumers interested in data for this image.
removeConsumer(ImageConsumer) - Method in class java.awt.image.renderable.RenderableImageProducer
Remove an ImageConsumer from the list of consumers interested in data for this image.
removeContainerListener(ContainerListener) - Method in class java.awt.Container
Removes the specified container listener so it no longer receives container events from this container.
removeContents() - Method in interface javax.xml.soap.SOAPElement
Detaches all children of this SOAPElement.
removeControlButtons() - Method in class javax.swing.plaf.metal.MetalFileChooserUI
removeControllerEventListener(ControllerEventListener, int[]) - Method in interface javax.sound.midi.Sequencer
Removes a controller event listener's interest in one or more types of controller event.
removeDescendantSelectedPaths(TreePath, boolean) - Method in class javax.swing.JTree
Removes any paths in the selection that are descendants of path.
removeDescendantToggledPaths(Enumeration<TreePath>) - Method in class javax.swing.JTree
Removes any descendants of the TreePaths in toRemove that have been expanded.
removeDocumentListener(DocumentListener) - Method in class javax.swing.text.AbstractDocument
Removes a document listener.
removeDocumentListener(DocumentListener) - Method in class javax.swing.text.DefaultStyledDocument
Removes a document listener.
removeDocumentListener(DocumentListener) - Method in interface javax.swing.text.Document
Unregisters the given observer from the notification list so it will no longer receive change updates.
removeDragGestureListener(DragGestureListener) - Method in class java.awt.dnd.DragGestureRecognizer
unregister the current DragGestureListener
removeDragSourceListener(DragSourceListener) - Method in class java.awt.dnd.DragSource
Removes the specified DragSourceListener from this DragSource.
removeDragSourceListener(DragSourceListener) - Method in class java.awt.dnd.DragSourceContext
Removes the specified DragSourceListener from this DragSourceContext.
removeDragSourceMotionListener(DragSourceMotionListener) - Method in class java.awt.dnd.DragSource
Removes the specified DragSourceMotionListener from this DragSource.
removeDropTargetListener(DropTargetListener) - Method in class java.awt.dnd.DropTarget
Removes the current DropTargetListener (UNICAST SOURCE).
removeEditor() - Method in class javax.swing.JTable
Discards the editor object and frees the real estate it used for cell rendering.
removeEditor() - Method in class javax.swing.plaf.basic.BasicComboBoxUI
This public method is implementation specific and should be private.
removeEldestEntry(Map.Entry<K, V>) - Method in class java.util.LinkedHashMap
Returns true if this map should remove its eldest entry.
removeElement(Object) - Method in class java.util.Vector
Removes the first (lowest-indexed) occurrence of the argument from this vector.
removeElement(String) - Method in class javax.imageio.metadata.IIOMetadataFormatImpl
Removes an element from the format.
removeElement(Object) - Method in class javax.swing.DefaultComboBoxModel
removeElement(Object) - Method in class javax.swing.DefaultListModel
Removes the first (lowest-indexed) occurrence of the argument from this list.
removeElement(Object) - Method in interface javax.swing.MutableComboBoxModel
Removes an item from the model.
removeElement(Element) - Method in class javax.swing.text.DefaultStyledDocument
Removes an element from this document.
removeElementAt(int) - Method in class java.util.Vector
Deletes the component at the specified index.
removeElementAt(int) - Method in class javax.swing.DefaultComboBoxModel
removeElementAt(int) - Method in class javax.swing.DefaultListModel
Deletes the component at the specified index.
removeElementAt(int) - Method in interface javax.swing.MutableComboBoxModel
Removes an item at a specific index.
removeEntries(int, int) - Method in class javax.swing.SizeSequence
Removes a contiguous group of entries from this SizeSequence.
removeEntry(Principal, AclEntry) - Method in interface java.security.acl.Acl
Removes an ACL entry from this ACL.
removeEventListener(String, EventListener, boolean) - Method in interface org.w3c.dom.events.EventTarget
This method allows the removal of event listeners from the event target.
removeField(String) - Method in interface javax.management.Descriptor
Removes a field from the descriptor.
removeField(String) - Method in class javax.management.ImmutableDescriptor
Removes a field from the descriptor.
removeField(String) - Method in class javax.management.modelmbean.DescriptorSupport
removeFirst() - Method in class java.util.ArrayDeque
removeFirst() - Method in class java.util.concurrent.ConcurrentLinkedDeque
removeFirst() - Method in class java.util.concurrent.LinkedBlockingDeque
removeFirst() - Method in interface java.util.Deque
Retrieves and removes the first element of this deque.
removeFirst() - Method in class java.util.LinkedList
Removes and returns the first element from this list.
removeFirstOccurrence(Object) - Method in class java.util.ArrayDeque
Removes the first occurrence of the specified element in this deque (when traversing the deque from head to tail).
removeFirstOccurrence(Object) - Method in interface java.util.concurrent.BlockingDeque
Removes the first occurrence of the specified element from this deque.
removeFirstOccurrence(Object) - Method in class java.util.concurrent.ConcurrentLinkedDeque
Removes the first element e such that o.equals(e), if such an element exists in this deque.
removeFirstOccurrence(Object) - Method in class java.util.concurrent.LinkedBlockingDeque
removeFirstOccurrence(Object) - Method in interface java.util.Deque
Removes the first occurrence of the specified element from this deque.
removeFirstOccurrence(Object) - Method in class java.util.LinkedList
Removes the first occurrence of the specified element in this list (when traversing the list from head to tail).
removeFlavorListener(FlavorListener) - Method in class java.awt.datatransfer.Clipboard
Removes the specified FlavorListener so that it no longer receives FlavorEvents from this Clipboard.
removeFocusListener(FocusListener) - Method in class java.awt.Component.AccessibleAWTComponent
Removes the specified focus listener so it no longer receives focus events from this component.
removeFocusListener(FocusListener) - Method in class java.awt.Component
Removes the specified focus listener so that it no longer receives focus events from this component.
removeFocusListener(FocusListener) - Method in class java.awt.List.AccessibleAWTList.AccessibleAWTListChild
Removes the specified focus listener so it no longer receives focus events from this component.
removeFocusListener(FocusListener) - Method in class java.awt.MenuComponent.AccessibleAWTMenuComponent
Removes the specified focus listener so it no longer receives focus events from this component.
removeFocusListener(FocusListener) - Method in interface javax.accessibility.AccessibleComponent
Removes the specified focus listener so it no longer receives focus events from this component.
removeFocusListener(FocusListener) - Method in class javax.swing.JList.AccessibleJList.AccessibleJListChild
removeFocusListener(FocusListener) - Method in class javax.swing.JTable.AccessibleJTable.AccessibleJTableCell
removeFocusListener(FocusListener) - Method in class javax.swing.JTree.AccessibleJTree.AccessibleJTreeNode
removeFocusListener(FocusListener) - Method in class javax.swing.table.JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry
removeFromEnvironment(String) - Method in interface javax.naming.Context
Removes an environment property from the environment of this context.
removeFromEnvironment(String) - Method in class javax.naming.InitialContext
removeFromParent() - Method in class javax.swing.tree.DefaultMutableTreeNode
Removes the subtree rooted at this node from the tree, giving this node a null parent.
removeFromParent() - Method in interface javax.swing.tree.MutableTreeNode
Removes the receiver from its parent.
removeFromSource() - Method in class javax.swing.plaf.basic.BasicTreeUI.MouseInputHandler
removeHandler(Handler) - Method in class java.util.logging.Logger
Remove a log Handler.
removeHandshakeCompletedListener(HandshakeCompletedListener) - Method in class javax.net.ssl.SSLSocket
Removes a previously registered handshake completion listener.
removeHeader(String) - Method in class javax.xml.soap.MimeHeaders
Remove all MimeHeader objects whose name matches the given name.
removeHierarchyBoundsListener(HierarchyBoundsListener) - Method in class java.awt.Component
Removes the specified hierarchy bounds listener so that it no longer receives hierarchy bounds events from this component.
removeHierarchyListener(HierarchyListener) - Method in class java.awt.Component
Removes the specified hierarchy listener so that it no longer receives hierarchy changed events from this component.
removeHighlight(Object) - Method in class javax.swing.text.DefaultHighlighter
Removes a highlight from the view.
removeHighlight(Object) - Method in interface javax.swing.text.Highlighter
Removes a highlight from the view.
removeHyperlinkListener(HyperlinkListener) - Method in class javax.swing.JEditorPane
Removes a hyperlink listener.
removeIconFor(JInternalFrame) - Method in class javax.swing.DefaultDesktopManager
Convenience method to remove the desktopIcon of f is necessary.
removeIdentity(Identity) - Method in class java.security.IdentityScope
Deprecated.
Removes an identity from this identity scope.
removeIIOReadProgressListener(IIOReadProgressListener) - Method in class javax.imageio.ImageReader
Removes an IIOReadProgressListener from the list of registered progress listeners.
removeIIOReadUpdateListener(IIOReadUpdateListener) - Method in class javax.imageio.ImageReader
Removes an IIOReadUpdateListener from the list of registered update listeners.
removeIIOReadWarningListener(IIOReadWarningListener) - Method in class javax.imageio.ImageReader
Removes an IIOReadWarningListener from the list of registered error listeners.
removeIIOWriteProgressListener(IIOWriteProgressListener) - Method in class javax.imageio.ImageWriter
Removes an IIOWriteProgressListener from the list of registered progress listeners.
removeIIOWriteWarningListener(IIOWriteWarningListener) - Method in class javax.imageio.ImageWriter
Removes an IIOWriteWarningListener from the list of registered warning listeners.
removeImage(Image) - Method in class java.awt.MediaTracker
Removes the specified image from this media tracker.
removeImage(Image, int) - Method in class java.awt.MediaTracker
Removes the specified image from the specified tracking ID of this media tracker.
removeImage(Image, int, int, int) - Method in class java.awt.MediaTracker
Removes the specified image with the specified width, height, and ID from this media tracker.
removeImage(int) - Method in class javax.imageio.ImageWriter
Removes an image from the stream.
removeIndexInterval(int, int) - Method in class javax.swing.DefaultListSelectionModel
Remove the indices in the interval index0,index1 (inclusive) from the selection model.
removeIndexInterval(int, int) - Method in interface javax.swing.ListSelectionModel
Remove the indices in the interval index0,index1 (inclusive) from the selection model.
removeInputMethodListener(InputMethodListener) - Method in class java.awt.Component
Removes the specified input method listener so that it no longer receives input method events from this component.
removeInternal(EventListener, EventListener) - Static method in class java.awt.AWTEventMulticaster
Returns the resulting multicast listener after removing the old listener from listener-l.
removeInternalFrameListener(InternalFrameListener) - Method in class javax.swing.JInternalFrame
Removes the specified internal frame listener so that it no longer receives internal frame events from this internal frame.
removeInvalidComponent(JComponent) - Method in class javax.swing.RepaintManager
Remove a component from the list of invalid components.
removeItem(Object) - Method in class javax.swing.JComboBox
Removes an item from the item list.
removeItemAt(int) - Method in class javax.swing.JComboBox
Removes the item at anIndex This method works only if the JComboBox uses a mutable data model.
removeItemListener(ItemListener) - Method in class java.awt.Checkbox
Removes the specified item listener so that the item listener no longer receives item events from this check box.
removeItemListener(ItemListener) - Method in class java.awt.CheckboxMenuItem
Removes the specified item listener so that it no longer receives item events from this check box menu item.
removeItemListener(ItemListener) - Method in class java.awt.Choice
Removes the specified item listener so that it no longer receives item events from this Choice menu.
removeItemListener(ItemListener) - Method in interface java.awt.ItemSelectable
Removes an item listener.
removeItemListener(ItemListener) - Method in class java.awt.List
Removes the specified item listener so that it no longer receives item events from this list.
removeItemListener(ItemListener) - Method in class javax.swing.AbstractButton
Removes an ItemListener from the button.
removeItemListener(ItemListener) - Method in interface javax.swing.ButtonModel
Removes an ItemListener from the model.
removeItemListener(ItemListener) - Method in class javax.swing.DefaultButtonModel
Removes an ItemListener from the model.
removeItemListener(ItemListener) - Method in class javax.swing.JComboBox
Removes an ItemListener.
removeKeyEventDispatcher(KeyEventDispatcher) - Method in class java.awt.KeyboardFocusManager
Removes a KeyEventDispatcher which was previously added to this KeyboardFocusManager's dispatcher chain.
removeKeyEventPostProcessor(KeyEventPostProcessor) - Method in class java.awt.KeyboardFocusManager
Removes a previously added KeyEventPostProcessor from this KeyboardFocusManager's post-processor chain.
removeKeyListener(KeyListener) - Method in class java.awt.Component
Removes the specified key listener so that it no longer receives key events from this component.
removeKeymap(String) - Static method in class javax.swing.text.JTextComponent
Removes a named keymap previously added to the document.
removeKeyStrokeBinding(KeyStroke) - Method in interface javax.swing.text.Keymap
Removes a binding from the keymap.
removeLast() - Method in class java.util.ArrayDeque
removeLast() - Method in class java.util.concurrent.ConcurrentLinkedDeque
removeLast() - Method in class java.util.concurrent.LinkedBlockingDeque
removeLast() - Method in interface java.util.Deque
Retrieves and removes the last element of this deque.
removeLast() - Method in class java.util.LinkedList
Removes and returns the last element from this list.
removeLastOccurrence(Object) - Method in class java.util.ArrayDeque
Removes the last occurrence of the specified element in this deque (when traversing the deque from head to tail).
removeLastOccurrence(Object) - Method in interface java.util.concurrent.BlockingDeque
Removes the last occurrence of the specified element from this deque.
removeLastOccurrence(Object) - Method in class java.util.concurrent.ConcurrentLinkedDeque
Removes the last element e such that o.equals(e), if such an element exists in this deque.
removeLastOccurrence(Object) - Method in class java.util.concurrent.LinkedBlockingDeque
removeLastOccurrence(Object) - Method in interface java.util.Deque
Removes the last occurrence of the specified element from this deque.
removeLastOccurrence(Object) - Method in class java.util.LinkedList
Removes the last occurrence of the specified element in this list (when traversing the list from head to tail).
removeLayoutComponent(Component) - Method in class java.awt.BorderLayout
Removes the specified component from this border layout.
removeLayoutComponent(Component) - Method in class java.awt.CardLayout
Removes the specified component from the layout.
removeLayoutComponent(Component) - Method in class java.awt.FlowLayout
Removes the specified component from the layout.
removeLayoutComponent(Component) - Method in class java.awt.GridBagLayout
Removes the specified component from this layout.
removeLayoutComponent(Component) - Method in class java.awt.GridLayout
Removes the specified component from the layout.
removeLayoutComponent(Component) - Method in interface java.awt.LayoutManager
Removes the specified component from the layout.
removeLayoutComponent(Component) - Method in class javax.swing.BoxLayout
Not used by this class.
removeLayoutComponent(Component) - Method in class javax.swing.GroupLayout
Notification that a Component has been removed from the parent container.
removeLayoutComponent(Component) - Method in class javax.swing.JRootPane.RootLayout
removeLayoutComponent(Component) - Method in class javax.swing.JSpinner.DefaultEditor
This LayoutManager method does nothing.
removeLayoutComponent(Component) - Method in class javax.swing.OverlayLayout
Removes the specified component from the layout.
removeLayoutComponent(Component) - Method in class javax.swing.plaf.basic.BasicComboBoxUI.ComboBoxLayoutManager
removeLayoutComponent(Component) - Method in class javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout
removeLayoutComponent(Component) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI.InternalFrameLayout
removeLayoutComponent(Component) - Method in class javax.swing.plaf.basic.BasicOptionPaneUI.ButtonAreaLayout
removeLayoutComponent(Component) - Method in class javax.swing.plaf.basic.BasicScrollBarUI
removeLayoutComponent(Component) - Method in class javax.swing.plaf.basic.BasicSplitPaneDivider.DividerLayout
removeLayoutComponent(Component) - Method in class javax.swing.plaf.basic.BasicSplitPaneUI.BasicHorizontalLayoutManager
Removes the specified component from our knowledge.
removeLayoutComponent(Component) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI.TabbedPaneLayout
removeLayoutComponent(Component) - Method in class javax.swing.ScrollPaneLayout
Removes the specified component from the layout.
removeLayoutComponent(Component) - Method in class javax.swing.SpringLayout
Removes the constraints associated with the specified component.
removeLayoutComponent(Component) - Method in class javax.swing.ViewportLayout
Removes the specified component from the layout.
removeLineListener(LineListener) - Method in interface javax.sound.sampled.Line
Removes the specified listener from this line's list of listeners.
removeListDataListener(ListDataListener) - Method in class javax.swing.AbstractListModel
Removes a listener from the list that's notified each time a change to the data model occurs.
removeListDataListener(ListDataListener) - Method in interface javax.swing.ListModel
Removes a listener from the list that's notified each time a change to the data model occurs.
removeListeners() - Method in class javax.swing.plaf.metal.MetalComboBoxUI
Deprecated.
As of Java 2 platform v1.4.
removeListSelectionListener(ListSelectionListener) - Method in class javax.swing.DefaultListSelectionModel
Remove a listener from the list that's notified each time a change to the selection occurs.
removeListSelectionListener(ListSelectionListener) - Method in class javax.swing.JList
Removes a selection listener from the list.
removeListSelectionListener(ListSelectionListener) - Method in interface javax.swing.ListSelectionModel
Remove a listener from the list that's notified each time a change to the selection occurs.
removeMember(Principal) - Method in interface java.security.acl.Group
Removes the specified member from the group.
removeMenuDragMouseListener(MenuDragMouseListener) - Method in class javax.swing.JMenuItem
Removes a MenuDragMouseListener from the menu item.
removeMenuKeyListener(MenuKeyListener) - Method in class javax.swing.JMenuItem
Removes a MenuKeyListener from the menu item.
removeMenuKeyListener(MenuKeyListener) - Method in class javax.swing.JPopupMenu
Removes a MenuKeyListener from the popup menu.
removeMenuListener(MenuListener) - Method in class javax.swing.JMenu
Removes a listener for menu events.
removeMetaEventListener(MetaEventListener) - Method in interface javax.sound.midi.Sequencer
Removes the specified meta-event listener from this sequencer's list of registered listeners, if in fact the listener is registered.
removeMimeHeader(String) - Method in class javax.xml.soap.AttachmentPart
Removes all MIME headers that match the given name.
removeMimeHeader(String) - Method in class javax.xml.soap.SOAPPart
Removes all MIME headers that match the given name.
removeMouseListener(MouseListener) - Method in class java.awt.Component
Removes the specified mouse listener so that it no longer receives mouse events from this component.
removeMouseListener(MouseListener) - Method in class java.awt.TrayIcon
Removes the specified mouse listener.
removeMouseMotionListener(MouseMotionListener) - Method in class java.awt.Component
Removes the specified mouse motion listener so that it no longer receives mouse motion events from this component.
removeMouseMotionListener(MouseMotionListener) - Method in class java.awt.TrayIcon
Removes the specified mouse-motion listener.
removeMouseWheelListener(MouseWheelListener) - Method in class java.awt.Component
Removes the specified mouse wheel listener so that it no longer receives mouse wheel events from this component.
removeNamedItem(String) - Method in interface org.w3c.dom.NamedNodeMap
Removes a node specified by name.
removeNamedItemNS(String, String) - Method in interface org.w3c.dom.NamedNodeMap
Removes a node specified by local name and namespace URI.
removeNamespaceDeclaration(String) - Method in interface javax.xml.soap.SOAPElement
Removes the namespace declaration corresponding to the given prefix.
removeNamingListener(NamingListener) - Method in interface javax.naming.event.EventContext
Removes a listener from receiving naming events fired by this EventContext.
removeNode() - Method in class java.util.prefs.AbstractPreferences
Implements the removeNode() method as per the specification in Preferences.removeNode().
removeNode() - Method in class java.util.prefs.Preferences
Removes this preference node and all of its descendants, invalidating any preferences contained in the removed nodes.
removeNodeChangeListener(NodeChangeListener) - Method in class java.util.prefs.AbstractPreferences
removeNodeChangeListener(NodeChangeListener) - Method in class java.util.prefs.Preferences
Removes the specified NodeChangeListener, so it no longer receives change events.
removeNodeFromParent(MutableTreeNode) - Method in class javax.swing.tree.DefaultTreeModel
Message this to remove node from its parent.
removeNodeSpi() - Method in class java.util.prefs.AbstractPreferences
Removes this preference node, invalidating it and any preferences that it contains.
removeNotification(Integer) - Method in class javax.management.timer.Timer
Removes the timer notification corresponding to the specified identifier from the list of notifications.
removeNotification(Integer) - Method in interface javax.management.timer.TimerMBean
Removes the timer notification corresponding to the specified identifier from the list of notifications.
removeNotificationListener(ObjectName, ObjectName) - Method in interface javax.management.MBeanServer
removeNotificationListener(ObjectName, ObjectName, NotificationFilter, Object) - Method in interface javax.management.MBeanServer
removeNotificationListener(ObjectName, NotificationListener) - Method in interface javax.management.MBeanServer
removeNotificationListener(ObjectName, NotificationListener, NotificationFilter, Object) - Method in interface javax.management.MBeanServer
removeNotificationListener(ObjectName, ObjectName) - Method in interface javax.management.MBeanServerConnection
Removes a listener from a registered MBean.
removeNotificationListener(ObjectName, ObjectName, NotificationFilter, Object) - Method in interface javax.management.MBeanServerConnection
Removes a listener from a registered MBean.
removeNotificationListener(ObjectName, NotificationListener) - Method in interface javax.management.MBeanServerConnection
Removes a listener from a registered MBean.
removeNotificationListener(ObjectName, NotificationListener, NotificationFilter, Object) - Method in interface javax.management.MBeanServerConnection
Removes a listener from a registered MBean.
removeNotificationListener(NotificationListener, NotificationFilter, Object) - Method in class javax.management.MBeanServerDelegate
removeNotificationListener(NotificationListener) - Method in class javax.management.MBeanServerDelegate
removeNotificationListener(NotificationListener) - Method in class javax.management.modelmbean.RequiredModelMBean
Removes a listener for Notifications from the RequiredModelMBean.
removeNotificationListener(NotificationListener, NotificationFilter, Object) - Method in class javax.management.modelmbean.RequiredModelMBean
removeNotificationListener(NotificationListener) - Method in interface javax.management.NotificationBroadcaster
Removes a listener from this MBean.
removeNotificationListener(NotificationListener) - Method in class javax.management.NotificationBroadcasterSupport
removeNotificationListener(NotificationListener, NotificationFilter, Object) - Method in class javax.management.NotificationBroadcasterSupport
removeNotificationListener(NotificationListener, NotificationFilter, Object) - Method in interface javax.management.NotificationEmitter
Removes a listener from this MBean.
removeNotificationListener(ObjectName, ObjectName, Subject) - Method in interface javax.management.remote.rmi.RMIConnection
Handles the method MBeanServerConnection.removeNotificationListener(ObjectName, ObjectName).
removeNotificationListener(ObjectName, ObjectName, MarshalledObject, MarshalledObject, Subject) - Method in interface javax.management.remote.rmi.RMIConnection
Handles the method MBeanServerConnection.removeNotificationListener(ObjectName, ObjectName, NotificationFilter, Object).
removeNotificationListener(ObjectName, ObjectName, Subject) - Method in class javax.management.remote.rmi.RMIConnectionImpl
removeNotificationListener(ObjectName, ObjectName, MarshalledObject, MarshalledObject, Subject) - Method in class javax.management.remote.rmi.RMIConnectionImpl
removeNotificationListener(ObjectName, ObjectName, MarshalledObject, MarshalledObject, Subject) - Method in class javax.management.remote.rmi.RMIConnectionImpl_Stub
removeNotificationListener(ObjectName, ObjectName, Subject) - Method in class javax.management.remote.rmi.RMIConnectionImpl_Stub
removeNotificationListener(NotificationListener) - Method in class javax.management.StandardEmitterMBean
removeNotificationListener(NotificationListener, NotificationFilter, Object) - Method in class javax.management.StandardEmitterMBean
removeNotificationListeners(ObjectName, Integer[], Subject) - Method in interface javax.management.remote.rmi.RMIConnection
Handles the removeNotificationListener(ObjectName, NotificationListener) and removeNotificationListener(ObjectName, NotificationListener, NotificationFilter, Object) methods.
removeNotificationListeners(ObjectName, Integer[], Subject) - Method in class javax.management.remote.rmi.RMIConnectionImpl
removeNotificationListeners(ObjectName, Integer[], Subject) - Method in class javax.management.remote.rmi.RMIConnectionImpl_Stub
removeNotifications(String) - Method in class javax.management.timer.Timer
Removes all the timer notifications corresponding to the specified type from the list of notifications.
removeNotifications(String) - Method in interface javax.management.timer.TimerMBean
Removes all the timer notifications corresponding to the specified type from the list of notifications.
removeNotify() - Method in class java.awt.Component
Makes this Component undisplayable by destroying it native screen resource.
removeNotify() - Method in class java.awt.Container
Makes this Container undisplayable by removing its connection to its native screen resource.
removeNotify(ComponentPeer) - Method in class java.awt.dnd.DropTarget
Notify the DropTarget that it has been disassociated from a Component This method is usually called from java.awt.Component.removeNotify() of the Component associated with this DropTarget to notify the DropTarget that a ComponentPeer has been disassociated with that Component.
removeNotify() - Method in class java.awt.dnd.DropTargetContext
Called when disassociated with the DropTargetContextPeer.
removeNotify() - Method in class java.awt.Frame
Makes this Frame undisplayable by removing its connection to its native screen resource.
removeNotify(Component) - Method in class java.awt.im.InputContext
Notifies the input context that a client component has been removed from its containment hierarchy, or that input method support has been disabled for the component.
removeNotify() - Method in interface java.awt.im.spi.InputMethod
Notifies the input method that a client component has been removed from its containment hierarchy, or that input method support has been disabled for the component.
removeNotify() - Method in class java.awt.List
Removes the peer for this list.
removeNotify() - Method in class java.awt.Menu
Removes the menu's peer.
removeNotify() - Method in class java.awt.MenuBar
Removes the menu bar's peer.
removeNotify() - Method in class java.awt.MenuComponent
Removes the menu component's peer.
removeNotify() - Method in class java.awt.TextComponent
Removes the TextComponent's peer.
removeNotify() - Method in class java.awt.Window
Makes this Container undisplayable by removing its connection to its native screen resource.
removeNotify() - Method in class javax.swing.AbstractButton
Notifies this component that it no longer has a parent component.
removeNotify() - Method in class javax.swing.JButton
Overrides JComponent.removeNotify to check if this button is currently set as the default button on the RootPane, and if so, sets the RootPane's default button to null to ensure the RootPane doesn't hold onto an invalid button reference.
removeNotify() - Method in class javax.swing.JComponent
Notifies this component that it no longer has a parent component.
removeNotify() - Method in class javax.swing.JLayer
Notifies this component that it no longer has a parent component.
removeNotify() - Method in class javax.swing.JMenuBar
Overrides JComponent.removeNotify to unregister this menu bar with the current keyboard manager.
removeNotify() - Method in class javax.swing.JRootPane
Notifies this component that it no longer has a parent component.
removeNotify() - Method in class javax.swing.JTable
Calls the unconfigureEnclosingScrollPane method.
removeNotify() - Method in class javax.swing.text.JTextComponent
removeObjectValue(String) - Method in class javax.imageio.metadata.IIOMetadataFormatImpl
Disallows an Object reference from being stored in nodes implementing the named element.
removeObservedObject(ObjectName) - Method in class javax.management.monitor.Monitor
Removes the specified object from the set of observed MBeans.
removeObservedObject(ObjectName) - Method in interface javax.management.monitor.MonitorMBean
Removes the specified object from the set of observed MBeans.
removeParameter(String) - Method in class javax.activation.MimeType
Remove any value associated with the given name.
removeParameters() - Method in class java.awt.image.renderable.ParameterBlock
Clears the list of parameters.
removePermission(Permission) - Method in interface java.security.acl.AclEntry
Removes the specified permission from this ACL entry.
removePopupMenuListener(PopupMenuListener) - Method in class javax.swing.JComboBox
Removes a PopupMenuListener.
removePopupMenuListener(PopupMenuListener) - Method in class javax.swing.JPopupMenu
Removes a PopupMenu listener.
removePreferenceChangeListener(PreferenceChangeListener) - Method in class java.util.prefs.AbstractPreferences
removePreferenceChangeListener(PreferenceChangeListener) - Method in class java.util.prefs.Preferences
Removes the specified preference change listener, so it no longer receives preference change events.
removePrintJobAttributeListener(PrintJobAttributeListener) - Method in interface javax.print.DocPrintJob
Removes an attribute listener from this print job.
removePrintJobListener(PrintJobListener) - Method in interface javax.print.DocPrintJob
Removes a listener from this print job.
removePrintServiceAttributeListener(PrintServiceAttributeListener) - Method in interface javax.print.PrintService
Removes the print-service listener from this print service.
removePropertyChangeListener(PropertyChangeListener) - Method in class java.awt.Component.AccessibleAWTComponent
Remove a PropertyChangeListener from the listener list.
removePropertyChangeListener(PropertyChangeListener) - Method in class java.awt.Component
Removes a PropertyChangeListener from the listener list.
removePropertyChangeListener(String, PropertyChangeListener) - Method in class java.awt.Component
Removes a PropertyChangeListener from the listener list for a specific property.
removePropertyChangeListener(PropertyChangeListener) - Method in class java.awt.KeyboardFocusManager
Removes a PropertyChangeListener from the listener list.
removePropertyChangeListener(String, PropertyChangeListener) - Method in class java.awt.KeyboardFocusManager
Removes a PropertyChangeListener from the listener list for a specific property.
removePropertyChangeListener(String, PropertyChangeListener) - Method in class java.awt.SystemTray
Removes a PropertyChangeListener from the listener list for a specific property.
removePropertyChangeListener(String, PropertyChangeListener) - Method in class java.awt.Toolkit
Removes the specified property change listener for the named desktop property.
removePropertyChangeListener(String, PropertyChangeListener) - Method in interface java.beans.beancontext.BeanContextChild
Removes a PropertyChangeListener from this BeanContextChild so that it no longer receives PropertyChangeEvents when the specified property is changed.
removePropertyChangeListener(String, PropertyChangeListener) - Method in class java.beans.beancontext.BeanContextChildSupport
Remove a PropertyChangeListener for a specific property.
removePropertyChangeListener(PropertyChangeListener) - Method in interface java.beans.Customizer
Remove a listener for the PropertyChange event.
removePropertyChangeListener(PropertyChangeListener) - Method in class java.beans.PropertyChangeSupport
Remove a PropertyChangeListener from the listener list.
removePropertyChangeListener(String, PropertyChangeListener) - Method in class java.beans.PropertyChangeSupport
Remove a PropertyChangeListener for a specific property.
removePropertyChangeListener(PropertyChangeListener) - Method in interface java.beans.PropertyEditor
Removes a listener for the value change.
removePropertyChangeListener(PropertyChangeListener) - Method in class java.beans.PropertyEditorSupport
Removes a listener for the value change.
removePropertyChangeListener(PropertyChangeListener) - Method in interface java.util.jar.Pack200.Packer
Remove a listener for PropertyChange events, added by the Pack200.Packer.addPropertyChangeListener(java.beans.PropertyChangeListener).
removePropertyChangeListener(PropertyChangeListener) - Method in interface java.util.jar.Pack200.Unpacker
Remove a listener for PropertyChange events, added by the Pack200.Unpacker.addPropertyChangeListener(java.beans.PropertyChangeListener).
removePropertyChangeListener(PropertyChangeListener) - Method in class java.util.logging.LogManager
Removes an event listener for property change events.
removePropertyChangeListener(PropertyChangeListener) - Method in class javax.accessibility.AccessibleContext
Removes a PropertyChangeListener from the listener list.
removePropertyChangeListener(PropertyChangeListener) - Method in class javax.swing.AbstractAction
Removes a PropertyChangeListener from the listener list.
removePropertyChangeListener(PropertyChangeListener) - Method in interface javax.swing.Action
Removes a PropertyChange listener.
removePropertyChangeListener(PropertyChangeListener) - Method in class javax.swing.JComponent.AccessibleJComponent
Removes a PropertyChangeListener from the listener list.
removePropertyChangeListener(PropertyChangeListener) - Method in class javax.swing.JList.AccessibleJList.AccessibleJListChild
removePropertyChangeListener(PropertyChangeListener) - Method in class javax.swing.JTable.AccessibleJTable.AccessibleJTableCell
Removes a PropertyChangeListener from the listener list.
removePropertyChangeListener(PropertyChangeListener) - Method in class javax.swing.JTree.AccessibleJTree.AccessibleJTreeNode
Remove a PropertyChangeListener from the listener list.
removePropertyChangeListener(PropertyChangeListener) - Method in class javax.swing.JTree.EmptySelectionModel
This is overriden to do nothing; EmptySelectionModel does not allow a selection.
removePropertyChangeListener(PropertyChangeListener) - Method in class javax.swing.plaf.basic.BasicDirectoryModel
Removes a PropertyChangeListener from the listener list.
removePropertyChangeListener(PropertyChangeListener) - Method in class javax.swing.plaf.LayerUI
Removes a PropertyChangeListener from the listener list.
removePropertyChangeListener(String, PropertyChangeListener) - Method in class javax.swing.plaf.LayerUI
Removes a PropertyChangeListener from the listener list for a specific property.
removePropertyChangeListener(PropertyChangeListener) - Method in class javax.swing.SwingWorker
Removes a PropertyChangeListener from the listener list.
removePropertyChangeListener(PropertyChangeListener) - Method in class javax.swing.table.JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry
removePropertyChangeListener(PropertyChangeListener) - Method in class javax.swing.table.TableColumn
Removes a PropertyChangeListener from the listener list.
removePropertyChangeListener(PropertyChangeListener) - Method in class javax.swing.tree.DefaultTreeSelectionModel
Removes a PropertyChangeListener from the listener list.
removePropertyChangeListener(PropertyChangeListener) - Method in interface javax.swing.tree.TreeSelectionModel
Removes a PropertyChangeListener from the listener list.
removePropertyChangeListener(PropertyChangeListener) - Method in class javax.swing.UIDefaults
Removes a PropertyChangeListener from the listener list.
removePropertyChangeListener(PropertyChangeListener) - Static method in class javax.swing.UIManager
Removes a PropertyChangeListener from the listener list.
removeProvider(String) - Static method in class java.security.Security
Removes the provider with the specified name.
removeRange(int, int) - Method in class java.util.AbstractList
Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.
removeRange(int, int) - Method in class java.util.ArrayList
Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.
removeRange(int, int) - Method in class java.util.Vector
Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.
removeRange(int, int) - Method in class javax.swing.DefaultListModel
Deletes the components at the specified range of indexes.
removeRedundantState() - Method in class javax.swing.undo.StateEdit
Remove redundant key/values in state hashtables.
removeRelation(String) - Method in class javax.management.relation.RelationService
Removes given relation from the Relation Service.
removeRelation(String) - Method in interface javax.management.relation.RelationServiceMBean
Removes given relation from the Relation Service.
removeRelationType(String) - Method in class javax.management.relation.RelationService
Removes given relation type from Relation Service.
removeRelationType(String) - Method in interface javax.management.relation.RelationServiceMBean
Removes given relation type from Relation Service.
removeResourceBundle(String) - Method in class javax.swing.UIDefaults
Removes a resource bundle from the list of resource bundles that are searched for localized defaults.
removeRow(int) - Method in class javax.swing.table.DefaultTableModel
Removes the row at row from the model.
removeRowSelectionInterval(int, int) - Method in class javax.swing.JTable
Deselects the rows from index0 to index1, inclusive.
removeRowSetListener(RowSetListener) - Method in class javax.sql.rowset.BaseRowSet
Removes the designated object from this RowSet object's list of listeners.
removeRowSetListener(RowSetListener) - Method in interface javax.sql.RowSet
Removes the specified listener from the list of components that will be notified when an event occurs on this RowSet object.
removeRowSorterListener(RowSorterListener) - Method in class javax.swing.RowSorter
Removes a RowSorterListener.
removeSelectionInterval(int, int) - Method in class javax.swing.DefaultListSelectionModel
Changes the selection to be the set difference of the current selection and the indices between index0 and index1 inclusive.
removeSelectionInterval(int, int) - Method in class javax.swing.JList
Sets the selection to be the set difference of the specified interval and the current selection.
removeSelectionInterval(int, int) - Method in class javax.swing.JTree
Removes the specified rows (inclusive) from the selection.
removeSelectionInterval(int, int) - Method in interface javax.swing.ListSelectionModel
Changes the selection to be the set difference of the current selection and the indices between index0 and index1 inclusive.
removeSelectionPath(TreePath) - Method in class javax.swing.JTree
Removes the node identified by the specified path from the current selection.
removeSelectionPath(TreePath) - Method in class javax.swing.tree.DefaultTreeSelectionModel
Removes path from the selection.
removeSelectionPath(TreePath) - Method in interface javax.swing.tree.TreeSelectionModel
Removes path from the selection.
removeSelectionPaths(TreePath[]) - Method in class javax.swing.JTree.EmptySelectionModel
This is overriden to do nothing; EmptySelectionModel does not allow a selection.
removeSelectionPaths(TreePath[]) - Method in class javax.swing.JTree
Removes the nodes identified by the specified paths from the current selection.
removeSelectionPaths(TreePath[]) - Method in class javax.swing.tree.DefaultTreeSelectionModel
Removes paths from the selection.
removeSelectionPaths(TreePath[]) - Method in interface javax.swing.tree.TreeSelectionModel
Removes paths from the selection.
removeSelectionRow(int) - Method in class javax.swing.JTree
Removes the row at the index row from the current selection.
removeSelectionRows(int[]) - Method in class javax.swing.JTree
Removes the rows that are selected at each of the specified rows.
removeService(Provider.Service) - Method in class java.security.Provider
Remove a service previously added using putService().
removeShutdownHook(Thread) - Method in class java.lang.Runtime
De-registers a previously-registered virtual-machine shutdown hook.
removeSources() - Method in class java.awt.image.renderable.ParameterBlock
Clears the list of source images.
removeSpi(String) - Method in class java.util.prefs.AbstractPreferences
Remove the association (if any) for the specified key at this preference node.
removeStatementEventListener(StatementEventListener) - Method in interface javax.sql.PooledConnection
Removes the specified StatementEventListener from the list of components that will be notified when the driver detects that a PreparedStatement has been closed or is invalid.
removeStyle(String) - Method in class javax.swing.JTextPane
Removes a named non-null style previously added to the document.
removeStyle(String) - Method in class javax.swing.text.DefaultStyledDocument
Removes a named style previously added to the document.
removeStyle(String) - Method in class javax.swing.text.html.StyleSheet
Removes a named style previously added to the document.
removeStyle(String) - Method in class javax.swing.text.StyleContext
Removes a named style previously added to the document.
removeStyle(String) - Method in interface javax.swing.text.StyledDocument
Removes a named style previously added to the document.
removeStyleSheet(StyleSheet) - Method in class javax.swing.text.html.StyleSheet
Removes the StyleSheet ss from those of the receiver.
removeTabAt(int) - Method in class javax.swing.JTabbedPane
Removes the tab at index.
removeTableModelListener(TableModelListener) - Method in class javax.swing.table.AbstractTableModel
Removes a listener from the list that's notified each time a change to the data model occurs.
removeTableModelListener(TableModelListener) - Method in interface javax.swing.table.TableModel
Removes a listener from the list that is notified each time a change to the data model occurs.
removeTextListener(TextListener) - Method in class java.awt.TextComponent
Removes the specified text event listener so that it no longer receives text events from this text component If l is null, no exception is thrown and no action is performed.
removeTileObserver(TileObserver) - Method in class java.awt.image.BufferedImage
Removes a tile observer.
removeTileObserver(TileObserver) - Method in interface java.awt.image.WritableRenderedImage
Removes an observer.
removeTransformer(ClassFileTransformer) - Method in interface java.lang.instrument.Instrumentation
Unregisters the supplied transformer.
removeTreeExpansionListener(TreeExpansionListener) - Method in class javax.swing.JTree
Removes a listener for TreeExpansion events.
removeTreeModelListener(TreeModelListener) - Method in class javax.swing.tree.DefaultTreeModel
Removes a listener previously added with addTreeModelListener().
removeTreeModelListener(TreeModelListener) - Method in interface javax.swing.tree.TreeModel
Removes a listener previously added with addTreeModelListener.
removeTreeSelectionListener(TreeSelectionListener) - Method in class javax.swing.JTree.EmptySelectionModel
This is overriden to do nothing; EmptySelectionModel does not allow a selection.
removeTreeSelectionListener(TreeSelectionListener) - Method in class javax.swing.JTree
Removes a TreeSelection listener.
removeTreeSelectionListener(TreeSelectionListener) - Method in class javax.swing.tree.DefaultTreeSelectionModel
Removes x from the list of listeners that are notified each time the set of selected TreePaths changes.
removeTreeSelectionListener(TreeSelectionListener) - Method in interface javax.swing.tree.TreeSelectionModel
Removes x from the list of listeners that are notified each time the set of selected TreePaths changes.
removeTreeWillExpandListener(TreeWillExpandListener) - Method in class javax.swing.JTree
Removes a listener for TreeWillExpand events.
removeUndoableEditListener(UndoableEditListener) - Method in class javax.swing.text.AbstractDocument
Removes an undo listener.
removeUndoableEditListener(UndoableEditListener) - Method in interface javax.swing.text.Document
Unregisters the given observer from the notification list so it will no longer receive updates.
removeUndoableEditListener(UndoableEditListener) - Method in class javax.swing.undo.UndoableEditSupport
Removes an UndoableEditListener.
removeUnicodeLocaleAttribute(String) - Method in class java.util.Locale.Builder
Removes a unicode locale attribute, if present, otherwise has no effect.
removeUpdate(DocumentEvent) - Method in interface javax.swing.event.DocumentListener
Gives notification that a portion of the document has been removed.
removeUpdate(AbstractDocument.DefaultDocumentEvent) - Method in class javax.swing.text.AbstractDocument
Updates any document structure as a result of text removal.
removeUpdate() - Method in class javax.swing.text.DefaultStyledDocument.ElementBuffer
Updates the element structure in response to a removal from the associated sequence in the document.
removeUpdate(AbstractDocument.DefaultDocumentEvent) - Method in class javax.swing.text.DefaultStyledDocument
Updates document structure as a result of text removal.
removeUpdate(DocumentEvent, Shape, ViewFactory) - Method in class javax.swing.text.FieldView
Gives notification that something was removed from the document in a location that this view is responsible for.
removeUpdate(FlowView, DocumentEvent, Rectangle) - Method in class javax.swing.text.FlowView.FlowStrategy
Gives notification that something was removed from the document in a location that the given flow view is responsible for.
removeUpdate(DocumentEvent, Shape, ViewFactory) - Method in class javax.swing.text.FlowView
Gives notification that something was removed from the document in a location that this view is responsible for.
removeUpdate(DocumentEvent, Shape, ViewFactory) - Method in class javax.swing.text.GlyphView
Gives notification that something was removed from the document in a location that this view is responsible for.
removeUpdate(DocumentEvent, Shape, ViewFactory) - Method in class javax.swing.text.html.InlineView
Gives notification that something was removed from the document in a location that this view is responsible for.
removeUpdate(DocumentEvent) - Method in class javax.swing.text.JTextComponent.AccessibleJTextComponent
Handles document remove (fire appropriate property change event, which is AccessibleContext.ACCESSIBLE_TEXT_PROPERTY).
removeUpdate(AbstractDocument.DefaultDocumentEvent) - Method in class javax.swing.text.PlainDocument
Updates any document structure as a result of text removal.
removeUpdate(DocumentEvent, Shape, ViewFactory) - Method in class javax.swing.text.PlainView
Gives notification that something was removed from the document in a location that this view is responsible for.
removeUpdate(DocumentEvent, Shape, ViewFactory) - Method in class javax.swing.text.View
Gives notification that something was removed from the document in a location that this view is responsible for.
removeUpdate(DocumentEvent, Shape, ViewFactory) - Method in class javax.swing.text.WrappedPlainView
Gives notification that something was removed from the document in a location that this view is responsible for.
removeUpdate(DocumentEvent, Shape, ViewFactory) - Method in class javax.swing.text.ZoneView
Gives notification that something was removed from the document in a location that this view is responsible for.
removeValue(String) - Method in interface javax.net.ssl.SSLSession
Removes the object bound to the given name in the session's application layer data.
removeVetoableChangeListener(VetoableChangeListener) - Method in class java.awt.KeyboardFocusManager
Removes a VetoableChangeListener from the listener list.
removeVetoableChangeListener(String, VetoableChangeListener) - Method in class java.awt.KeyboardFocusManager
Removes a VetoableChangeListener from the listener list for a specific property.
removeVetoableChangeListener(String, VetoableChangeListener) - Method in interface java.beans.beancontext.BeanContextChild
Removes a VetoableChangeListener from this BeanContextChild so that it no longer receives events when the specified property changes.
removeVetoableChangeListener(String, VetoableChangeListener) - Method in class java.beans.beancontext.BeanContextChildSupport
Removes a VetoableChangeListener.
removeVetoableChangeListener(VetoableChangeListener) - Method in class java.beans.VetoableChangeSupport
Remove a VetoableChangeListener from the listener list.
removeVetoableChangeListener(String, VetoableChangeListener) - Method in class java.beans.VetoableChangeSupport
Remove a VetoableChangeListener for a specific property.
removeVetoableChangeListener(VetoableChangeListener) - Method in class javax.swing.JComponent
Removes a VetoableChangeListener from the listener list.
removeWindowFocusListener(WindowFocusListener) - Method in class java.awt.Window
Removes the specified window focus listener so that it no longer receives window events from this window.
removeWindowListener(WindowListener) - Method in class java.awt.Window
Removes the specified window listener so that it no longer receives window events from this window.
removeWindowStateListener(WindowStateListener) - Method in class java.awt.Window
Removes the specified window state listener so that it no longer receives window events from this window.
rename(Name, Name) - Method in interface javax.naming.Context
Binds a new name to the object bound to an old name, and unbinds the old name.
rename(String, String) - Method in interface javax.naming.Context
Binds a new name to the object bound to an old name, and unbinds the old name.
rename(String, String) - Method in class javax.naming.InitialContext
rename(Name, Name) - Method in class javax.naming.InitialContext
renameFile(File, File) - Method in class javax.swing.plaf.basic.BasicDirectoryModel
Renames a file in the underlying file system.
renameNode(Node, String, String) - Method in interface org.w3c.dom.Document
Rename an existing node of type ELEMENT_NODE or ATTRIBUTE_NODE.
renameTo(File) - Method in class java.io.File
Renames the file denoted by this abstract pathname.
render(Runnable) - Method in class javax.swing.text.AbstractDocument
This allows the model to be safely rendered in the presence of currency, if the model supports being updated asynchronously.
render(Runnable) - Method in interface javax.swing.text.Document
Allows the model to be safely rendered in the presence of concurrency, if the model supports being updated asynchronously.
RENDERABLE_IMAGE - Static variable in class javax.print.DocFlavor.SERVICE_FORMATTED
Service formatted print data doc flavor with print data representation class name = "java.awt.image.renderable.RenderableImage" (renderable image object).
RenderableImage - Interface in java.awt.image.renderable
A RenderableImage is a common interface for rendering-independent images (a notion which subsumes resolution independence).
RenderableImageOp - Class in java.awt.image.renderable
This class handles the renderable aspects of an operation with help from its associated instance of a ContextualRenderedImageFactory.
RenderableImageOp(ContextualRenderedImageFactory, ParameterBlock) - Constructor for class java.awt.image.renderable.RenderableImageOp
Constructs a RenderedImageOp given a ContextualRenderedImageFactory object, and a ParameterBlock containing RenderableImage sources and other parameters.
RenderableImageProducer - Class in java.awt.image.renderable
An adapter class that implements ImageProducer to allow the asynchronous production of a RenderableImage.
RenderableImageProducer(RenderableImage, RenderContext) - Constructor for class java.awt.image.renderable.RenderableImageProducer
Constructs a new RenderableImageProducer from a RenderableImage and a RenderContext.
RenderContext - Class in java.awt.image.renderable
A RenderContext encapsulates the information needed to produce a specific rendering from a RenderableImage.
RenderContext(AffineTransform, Shape, RenderingHints) - Constructor for class java.awt.image.renderable.RenderContext
Constructs a RenderContext with a given transform.
RenderContext(AffineTransform) - Constructor for class java.awt.image.renderable.RenderContext
Constructs a RenderContext with a given transform.
RenderContext(AffineTransform, RenderingHints) - Constructor for class java.awt.image.renderable.RenderContext
Constructs a RenderContext with a given transform and rendering hints.
RenderContext(AffineTransform, Shape) - Constructor for class java.awt.image.renderable.RenderContext
Constructs a RenderContext with a given transform and area of interest.
RenderedImage - Interface in java.awt.image
RenderedImage is a common interface for objects which contain or can produce image data in the form of Rasters.
RenderedImageFactory - Interface in java.awt.image.renderable
The RenderedImageFactory interface (often abbreviated RIF) is intended to be implemented by classes that wish to act as factories to produce different renderings, for example by executing a series of BufferedImageOps on a set of sources, depending on a specific set of parameters, properties, and rendering hints.
renderer - Variable in class javax.swing.JComboBox
This protected field is implementation specific.
Renderer - Interface in javax.swing
Defines the requirements for an object responsible for "rendering" (displaying) a value.
renderer - Variable in class javax.swing.tree.DefaultTreeCellEditor
Renderer, used to get border and offsets from.
rendererPane - Variable in class javax.swing.plaf.basic.BasicListUI
rendererPane - Variable in class javax.swing.plaf.basic.BasicTableHeaderUI
rendererPane - Variable in class javax.swing.plaf.basic.BasicTableUI
rendererPane - Variable in class javax.swing.plaf.basic.BasicTreeUI
Used to paint the TreeCellRenderer.
rendererPane - Variable in class javax.swing.plaf.metal.MetalComboBoxButton
RenderingHints - Class in java.awt
The RenderingHints class defines and manages collections of keys and associated values which allow an application to provide input into the choice of algorithms used by other classes which perform rendering and image manipulation services.
RenderingHints(Map<RenderingHints.Key, ?>) - Constructor for class java.awt.RenderingHints
Constructs a new object with keys and values initialized from the specified Map object which may be null.
RenderingHints(RenderingHints.Key, Object) - Constructor for class java.awt.RenderingHints
Constructs a new object with the specified key/value pair.
RenderingHints.Key - Class in java.awt
Defines the base type of all keys used along with the RenderingHints class to control various algorithm choices in the rendering and imaging pipelines.
RenderingHints.Key(int) - Constructor for class java.awt.RenderingHints.Key
Construct a key using the indicated private key.
reorderingAllowed - Variable in class javax.swing.table.JTableHeader
If true, reordering of columns are allowed by the user; the default is true.
reorderVisually(byte[], int, Object[], int, int) - Static method in class java.text.Bidi
Reorder the objects in the array into visual order based on their levels.
repaint() - Method in class java.awt.Component
Repaints this component.
repaint(long) - Method in class java.awt.Component
Repaints the component.
repaint(int, int, int, int) - Method in class java.awt.Component
Repaints the specified rectangle of this component.
repaint(long, int, int, int, int) - Method in class java.awt.Component
Repaints the specified rectangle of this component within tm milliseconds.
repaint() - Method in class javax.swing.DefaultListCellRenderer
Overridden for performance reasons.
repaint(long, int, int, int, int) - Method in class javax.swing.DefaultListCellRenderer
Overridden for performance reasons.
repaint(Rectangle) - Method in class javax.swing.DefaultListCellRenderer
Overridden for performance reasons.
repaint(long, int, int, int, int) - Method in class javax.swing.JApplet
Repaints the specified rectangle of this component within time milliseconds.
repaint(long, int, int, int, int) - Method in class javax.swing.JComponent
Adds the specified region to the dirty region list if the component is showing.
repaint(Rectangle) - Method in class javax.swing.JComponent
Adds the specified region to the dirty region list if the component is showing.
repaint(long, int, int, int, int) - Method in class javax.swing.JDialog
Repaints the specified rectangle of this component within time milliseconds.
repaint(long, int, int, int, int) - Method in class javax.swing.JFrame
Repaints the specified rectangle of this component within time milliseconds.
repaint(long, int, int, int, int) - Method in class javax.swing.JViewport
Always repaint in the parents coordinate system to make sure only one paint is performed by the RepaintManager.
repaint(long, int, int, int, int) - Method in class javax.swing.JWindow
Repaints the specified rectangle of this component within time milliseconds.
repaint(long, int, int, int, int) - Method in class javax.swing.table.DefaultTableCellRenderer
Overridden for performance reasons.
repaint(Rectangle) - Method in class javax.swing.table.DefaultTableCellRenderer
Overridden for performance reasons.
repaint() - Method in class javax.swing.table.DefaultTableCellRenderer
Overridden for performance reasons.
repaint() - Method in class javax.swing.text.DefaultCaret
Cause the caret to be painted.
repaint(long, int, int, int, int) - Method in class javax.swing.tree.DefaultTreeCellRenderer
Overridden for performance reasons.
repaint(Rectangle) - Method in class javax.swing.tree.DefaultTreeCellRenderer
Overridden for performance reasons.
repaint() - Method in class javax.swing.tree.DefaultTreeCellRenderer
Overridden for performance reasons.
repaintCellFocus() - Method in class javax.swing.plaf.basic.BasicListUI.FocusHandler
RepaintManager - Class in javax.swing
This class manages repaint requests, allowing the number of repaints to be minimized, for example by collapsing multiple requests into a single repaint for members of a component tree.
RepaintManager() - Constructor for class javax.swing.RepaintManager
Create a new RepaintManager instance.
repeatKeyAction - Variable in class javax.swing.plaf.basic.BasicTreeUI.KeyHandler
Key code that is being generated for.
replace(char, char) - Method in class java.lang.String
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
replace(CharSequence, CharSequence) - Method in class java.lang.String
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
replace(int, int, String) - Method in class java.lang.StringBuffer
replace(int, int, String) - Method in class java.lang.StringBuilder
REPLACE - Static variable in class java.nio.charset.CodingErrorAction
Action indicating that a coding error is to be handled by dropping the erroneous input, appending the coder's replacement value to the output buffer, and resuming the coding operation.
replace(K, V, V) - Method in class java.util.concurrent.ConcurrentHashMap
Replaces the entry for a key only if currently mapped to a given value.
replace(K, V) - Method in class java.util.concurrent.ConcurrentHashMap
Replaces the entry for a key only if currently mapped to some value.
replace(K, V, V) - Method in interface java.util.concurrent.ConcurrentMap
Replaces the entry for a key only if currently mapped to a given value.
replace(K, V) - Method in interface java.util.concurrent.ConcurrentMap
Replaces the entry for a key only if currently mapped to some value.
replace(K, V, V) - Method in class java.util.concurrent.ConcurrentSkipListMap
Replaces the entry for a key only if currently mapped to a given value.
replace(K, V) - Method in class java.util.concurrent.ConcurrentSkipListMap
Replaces the entry for a key only if currently mapped to some value.
replace(Component, Component) - Method in class javax.swing.GroupLayout
Replaces an existing component with a new one.
replace(int, int, Element[]) - Method in class javax.swing.text.AbstractDocument.BranchElement
Replaces content with a new set of elements.
replace(int, int, String, AttributeSet) - Method in class javax.swing.text.AbstractDocument
Deletes the region of text from offset to offset + length, and replaces it with text.
replace(int, int, View[]) - Method in class javax.swing.text.AsyncBoxView
Calls the superclass to update the child views, and updates the status records for the children.
replace(int, int, View[]) - Method in class javax.swing.text.BoxView
Invalidates the layout and resizes the cache of requests/allocations.
replace(int, int, View[]) - Method in class javax.swing.text.CompositeView
Replaces child views.
replace(int, int, String, AttributeSet) - Method in class javax.swing.text.DocumentFilter.FilterBypass
Deletes the region of text from offset to offset + length, and replaces it with text.
replace(DocumentFilter.FilterBypass, int, int, String, AttributeSet) - Method in class javax.swing.text.DocumentFilter
Invoked prior to replacing a region of text in the specified Document.
replace(int, int, View[]) - Method in class javax.swing.text.TableView
Change the child views.
replace(int, int, View[]) - Method in class javax.swing.text.TableView.TableRow
Change the child views.
replace(int, int, View[]) - Method in class javax.swing.text.View
Replaces child views.
REPLACE_ATTRIBUTE - Static variable in interface javax.naming.directory.DirContext
This constant specifies to replace an attribute with specified values.
replaceAll(String, String) - Method in class java.lang.String
Replaces each substring of this string that matches the given regular expression with the given replacement.
replaceAll(List<T>, T, T) - Static method in class java.util.Collections
Replaces all occurrences of one specified value in a list with another.
replaceAll(String) - Method in class java.util.regex.Matcher
Replaces every subsequence of the input sequence that matches the pattern with the given replacement string.
replaceChild(Node, Node) - Method in class javax.imageio.metadata.IIOMetadataNode
Replaces the child node oldChild with newChild in the list of children, and returns the oldChild node.
replaceChild(Node, Node) - Method in interface org.w3c.dom.Node
Replaces the child node oldChild with newChild in the list of children, and returns the oldChild node.
replaceData(int, int, String) - Method in interface org.w3c.dom.CharacterData
Replace the characters starting at the specified 16-bit unit offset with the specified string.
replaceEdit(UndoableEdit) - Method in class javax.swing.undo.AbstractUndoableEdit
This default implementation returns false.
replaceEdit(UndoableEdit) - Method in interface javax.swing.undo.UndoableEdit
Returns true if this UndoableEdit should replace anEdit.
replaceEditor(JComponent, JComponent) - Method in class javax.swing.plaf.basic.BasicSpinnerUI
Called by the PropertyChangeListener when the JSpinner editor property changes.
replaceEditor(JComponent, JComponent) - Method in class javax.swing.plaf.synth.SynthSpinnerUI
Called by the PropertyChangeListener when the JSpinner editor property changes.
replaceFirst(String, String) - Method in class java.lang.String
Replaces the first substring of this string that matches the given regular expression with the given replacement.
replaceFirst(String) - Method in class java.util.regex.Matcher
Replaces the first subsequence of the input sequence that matches the pattern with the given replacement string.
replaceImageMetadata(int, IIOMetadata) - Method in class javax.imageio.ImageWriter
Replaces the image metadata associated with an existing image.
replaceItem(String, int) - Method in class java.awt.List
Replaces the item at the specified index in the scrolling list with the new string.
replacement() - Method in class java.nio.charset.CharsetDecoder
Returns this decoder's replacement value.
replacement() - Method in class java.nio.charset.CharsetEncoder
Returns this encoder's replacement value.
replaceObject(Object) - Method in class java.io.ObjectOutputStream
This method will allow trusted subclasses of ObjectOutputStream to substitute one object for another during serialization.
replacePane(JComponent, JComponent) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI
Installs necessary mouse handlers on newPane and adds it to the frame.
replacePixels(RenderedImage, ImageWriteParam) - Method in class javax.imageio.ImageWriter
Replaces a portion of an image already present in the output with a portion of the given image.
replacePixels(Raster, ImageWriteParam) - Method in class javax.imageio.ImageWriter
Replaces a portion of an image already present in the output with a portion of the given Raster.
replaceRange(String, int, int) - Method in class java.awt.TextArea
Replaces text between the indicated start and end positions with the specified replacement text.
replaceRange(String, int, int) - Method in class javax.swing.JTextArea
Replaces text from the indicated start to end position with the new text specified.
replaceSelection(String) - Method in class javax.swing.JEditorPane
Replaces the currently selected content with new content represented by the given string.
replaceSelection(String) - Method in class javax.swing.JTextPane
Replaces the currently selected content with new content represented by the given string.
replaceSelection(String) - Method in class javax.swing.text.JTextComponent
Replaces the currently selected content with new content represented by the given string.
replaceStreamMetadata(IIOMetadata) - Method in class javax.imageio.ImageWriter
Replaces the stream metadata in the output with new information.
replaceText(String, int, int) - Method in class java.awt.TextArea
Deprecated.
As of JDK version 1.1, replaced by replaceRange(String, int, int).
replaceText(int, int, String) - Method in interface javax.accessibility.AccessibleEditableText
Replaces the text between two indices with the specified string.
replaceText(int, int, String) - Method in class javax.swing.JSpinner.AccessibleJSpinner
Replaces the text between two indices with the specified string.
replaceText(int, int, String) - Method in class javax.swing.text.JTextComponent.AccessibleJTextComponent
Replaces the text between two indices with the specified string.
replaceUIActionMap(JComponent, ActionMap) - Static method in class javax.swing.SwingUtilities
Convenience method to change the UI ActionMap for component to uiActionMap.
replaceUIInputMap(JComponent, int, InputMap) - Static method in class javax.swing.SwingUtilities
Convenience method to change the UI InputMap for component to uiInputMap.
replaceWholeText(String) - Method in interface org.w3c.dom.Text
Replaces the text of the current node and all logically-adjacent text nodes with the specified text.
replaceWith(String) - Method in class java.nio.charset.CharsetDecoder
Changes this decoder's replacement value.
replaceWith(byte[]) - Method in class java.nio.charset.CharsetEncoder
Changes this encoder's replacement value.
ReplicateScaleFilter - Class in java.awt.image
An ImageFilter class for scaling images using the simplest algorithm.
ReplicateScaleFilter(int, int) - Constructor for class java.awt.image.ReplicateScaleFilter
Constructs a ReplicateScaleFilter that scales the pixels from its source Image as specified by the width and height parameters.
reply_status() - Method in interface org.omg.PortableInterceptor.RequestInfoOperations
Describes the state of the result of the operation invocation.
REPORT - Static variable in class java.nio.charset.CodingErrorAction
Action indicating that a coding error is to be reported, either by returning a CoderResult object or by throwing a CharacterCodingException, whichever is appropriate for the method implementing the coding process.
REPORT - Static variable in class javax.print.attribute.standard.Severity
Indicates that the PrinterStateReason is a "report" (least severe).
report(Diagnostic<? extends S>) - Method in class javax.tools.DiagnosticCollector
report(Diagnostic<? extends S>) - Method in interface javax.tools.DiagnosticListener
Invoked when a problem is found.
report(String, String, Object, Location) - Method in interface javax.xml.stream.XMLReporter
Report the desired message in an application specific format.
REPORTER - Static variable in class javax.xml.stream.XMLInputFactory
The property used to set/get the implementation of the XMLReporter interface
reportError(String, Exception, int) - Method in class java.util.logging.Handler
Protected convenience method to report an error to this Handler's ErrorManager.
RepositoryIdHelper - Class in org.omg.CORBA
The Helper for RepositoryId.
RepositoryIdHelper() - Constructor for class org.omg.CORBA.RepositoryIdHelper
request(Object, String) - Method in class org.omg.CORBA.portable.Delegate
Creates a Request instance for use in the Dynamic Invocation Interface.
request(Object, String, boolean) - Method in class org.omg.CORBA.portable.Delegate
request is called by a stub to obtain an OutputStream for marshaling arguments.
Request - Class in org.omg.CORBA
An object containing the information necessary for invoking a method.
Request() - Constructor for class org.omg.CORBA.Request
REQUEST_CIPHER_SUITE - Static variable in class javax.xml.ws.spi.http.HttpExchange
Standard property: cipher suite value when the request is received over HTTPS
request_id() - Method in interface org.omg.PortableInterceptor.RequestInfoOperations
Returns an id that uniquely identifies an active request/reply sequence.
REQUEST_KEY_SIZE - Static variable in class javax.xml.ws.spi.http.HttpExchange
Standard property: bit size of the algorithm when the request is received over HTTPS
REQUEST_PROCESSING_POLICY_ID - Interface in org.omg.PortableServer
org/omg/PortableServer/REQUEST_PROCESSING_POLICY_ID.java .
REQUEST_X509CERTIFICATE - Static variable in class javax.xml.ws.spi.http.HttpExchange
Standard property: A SSL certificate, if any, associated with the request
requestAnonymity(boolean) - Method in interface org.ietf.jgss.GSSContext
Requests that the initiator's identity not be disclosed to the acceptor.
requestConf(boolean) - Method in interface org.ietf.jgss.GSSContext
Requests that data confidentiality be enabled for the wrap method.
requestCredDeleg(boolean) - Method in interface org.ietf.jgss.GSSContext
Requests that the initiator's credentials be delegated to the acceptor during context establishment.
requestDefaultFocus() - Method in class javax.swing.JComponent
Deprecated.
As of 1.4, replaced by FocusTraversalPolicy.getDefaultComponent(Container).requestFocus()
requestFocus() - Method in class java.awt.Component.AccessibleAWTComponent
Requests focus for this object.
requestFocus() - Method in class java.awt.Component
Requests that this Component get the input focus, and that this Component's top-level ancestor become the focused Window.
requestFocus(boolean) - Method in class java.awt.Component
Requests that this Component get the input focus, and that this Component's top-level ancestor become the focused Window.
requestFocus() - Method in class java.awt.List.AccessibleAWTList.AccessibleAWTListChild
Requests focus for this object.
requestFocus() - Method in class java.awt.MenuComponent.AccessibleAWTMenuComponent
Requests focus for this object.
requestFocus() - Method in interface javax.accessibility.AccessibleComponent
Requests focus for this object.
requestFocus() - Method in class javax.swing.JComponent
Requests that this Component gets the input focus.
requestFocus(boolean) - Method in class javax.swing.JComponent
Requests that this Component gets the input focus.
requestFocus() - Method in class javax.swing.JList.AccessibleJList.AccessibleJListChild
requestFocus() - Method in class javax.swing.JTable.AccessibleJTable.AccessibleJTableCell
requestFocus() - Method in class javax.swing.JTree.AccessibleJTree.AccessibleJTreeNode
requestFocus() - Method in class javax.swing.plaf.basic.BasicInternalFrameTitlePane.SystemMenuBar
requestFocus() - Method in class javax.swing.table.JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry
requestFocusInWindow() - Method in class java.awt.Component
Requests that this Component get the input focus, if this Component's top-level ancestor is already the focused Window.
requestFocusInWindow(boolean) - Method in class java.awt.Component
Requests that this Component get the input focus, if this Component's top-level ancestor is already the focused Window.
requestFocusInWindow() - Method in class javax.swing.JComponent
Requests that this Component gets the input focus.
requestFocusInWindow(boolean) - Method in class javax.swing.JComponent
Requests that this Component gets the input focus.
RequestInfo - Interface in org.omg.PortableInterceptor
Request Information, accessible to Interceptors.
RequestInfoOperations - Interface in org.omg.PortableInterceptor
Request Information, accessible to Interceptors.
RequestingUserName - Class in javax.print.attribute.standard
Class RequestingUserName is a printing attribute class, a text attribute, that specifies the name of the end user that submitted the print job.
RequestingUserName(String, Locale) - Constructor for class javax.print.attribute.standard.RequestingUserName
Constructs a new requesting user name attribute with the given user name and locale.
requestInteg(boolean) - Method in interface org.ietf.jgss.GSSContext
Requests that data integrity be enabled for the wrap and getMICmethods.
requestLifetime(int) - Method in interface org.ietf.jgss.GSSContext
Requests a lifetime in seconds for the context.
requestMutualAuth(boolean) - Method in interface org.ietf.jgss.GSSContext
Requests that mutual authentication be done during context establishment.
requestPasswordAuthentication(InetAddress, int, String, String, String) - Static method in class java.net.Authenticator
Ask the authenticator that has been registered with the system for a password.
requestPasswordAuthentication(String, InetAddress, int, String, String, String) - Static method in class java.net.Authenticator
Ask the authenticator that has been registered with the system for a password.
requestPasswordAuthentication(String, InetAddress, int, String, String, String, URL, Authenticator.RequestorType) - Static method in class java.net.Authenticator
Ask the authenticator that has been registered with the system for a password.
RequestProcessingPolicy - Interface in org.omg.PortableServer
This policy specifies how requests are processed by the created POA.
RequestProcessingPolicyOperations - Interface in org.omg.PortableServer
This policy specifies how requests are processed by the created POA.
RequestProcessingPolicyValue - Class in org.omg.PortableServer
The RequestProcessingPolicyValue can have the following values.
RequestProcessingPolicyValue(int) - Constructor for class org.omg.PortableServer.RequestProcessingPolicyValue
requestReplayDet(boolean) - Method in interface org.ietf.jgss.GSSContext
Requests that replay detection be enabled for the per-message security services after context establishment.
requestSequenceDet(boolean) - Method in interface org.ietf.jgss.GSSContext
Requests that sequence checking be enabled for the per-message security services after context establishment.
requestTopDownLeftRightResend(ImageConsumer) - Method in class java.awt.image.FilteredImageSource
Requests that a given ImageConsumer have the image data delivered one more time in top-down, left-right order.
requestTopDownLeftRightResend(ImageConsumer) - Method in interface java.awt.image.ImageProducer
Requests, on behalf of the ImageConsumer, that the ImageProducer attempt to resend the image data one more time in TOPDOWNLEFTRIGHT order so that higher quality conversion algorithms which depend on receiving pixels in order can be used to produce a better output version of the image.
requestTopDownLeftRightResend(ImageConsumer) - Method in class java.awt.image.MemoryImageSource
Requests that a given ImageConsumer have the image data delivered one more time in top-down, left-right order.
requestTopDownLeftRightResend(ImageConsumer) - Method in class java.awt.image.renderable.RenderableImageProducer
Requests that a given ImageConsumer have the image data delivered one more time in top-down, left-right order.
RequestWrapper - Annotation Type in javax.xml.ws
Used to annotate methods in the Service Endpoint Interface with the request wrapper bean to be used at runtime.
require(int, String, String) - Method in class javax.xml.stream.util.StreamReaderDelegate
require(int, String, String) - Method in interface javax.xml.stream.XMLStreamReader
Test if the current event is of the given type and if the namespace and name match the current namespace and name of the current event.
REQUIRED - Static variable in class java.awt.GraphicsConfigTemplate
Value used for "Enum" (Integer) type.
required - Variable in class java.sql.DriverPropertyInfo
The required field is true if a value must be supplied for this property during Driver.connect and false otherwise.
REQUIRED - Static variable in class javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag
Required LoginModule.
REQUIRED - Static variable in interface javax.swing.text.html.parser.DTDConstants
required - Variable in class javax.xml.ws.soap.AddressingFeature
If addressing is enabled, this property determines whether the endpoint requires WS-Addressing.
RequiredModelMBean - Class in javax.management.modelmbean
This class is the implementation of a ModelMBean.
RequiredModelMBean() - Constructor for class javax.management.modelmbean.RequiredModelMBean
Constructs an RequiredModelMBean with an empty ModelMBeanInfo.
RequiredModelMBean(ModelMBeanInfo) - Constructor for class javax.management.modelmbean.RequiredModelMBean
Constructs a RequiredModelMBean object using ModelMBeanInfo passed in.
requireEnd() - Method in class java.util.regex.Matcher
Returns true if more input could change a positive match into a negative one.
requireNonNull(T) - Static method in class java.util.Objects
Checks that the specified object reference is not null.
requireNonNull(T, String) - Static method in class java.util.Objects
Checks that the specified object reference is not null and throws a customized NullPointerException if it is.
REQUIRES_ATTENTION - Static variable in class javax.print.event.PrintJobEvent
The print service indicates that a - possibly transient - problem may require external intervention before the print service can continue.
requiresBidi(char[], int, int) - Static method in class java.text.Bidi
Return true if the specified text requires bidi analysis.
REQUISITE - Static variable in class javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag
Requisite LoginModule.
RescaleOp - Class in java.awt.image
This class performs a pixel-by-pixel rescaling of the data in the source image by multiplying the sample values for each pixel by a scale factor and then adding an offset.
RescaleOp(float[], float[], RenderingHints) - Constructor for class java.awt.image.RescaleOp
Constructs a new RescaleOp with the desired scale factors and offsets.
RescaleOp(float, float, RenderingHints) - Constructor for class java.awt.image.RescaleOp
Constructs a new RescaleOp with the desired scale factor and offset.
rescanCurrentDirectory() - Method in class javax.swing.JFileChooser
Tells the UI to rescan its files list from the current directory.
rescanCurrentDirectory(JFileChooser) - Method in class javax.swing.plaf.basic.BasicFileChooserUI
rescanCurrentDirectory(JFileChooser) - Method in class javax.swing.plaf.FileChooserUI
rescanCurrentDirectory(JFileChooser) - Method in class javax.swing.plaf.metal.MetalFileChooserUI
rescanCurrentDirectory(JFileChooser) - Method in class javax.swing.plaf.multi.MultiFileChooserUI
Invokes the rescanCurrentDirectory method on each UI handled by this object.
resendTopDownLeftRight(ImageProducer) - Method in class java.awt.image.ImageFilter
Responds to a request for a TopDownLeftRight (TDLR) ordered resend of the pixel data from an ImageConsumer.
RESERVED_ID_MAX - Static variable in class java.awt.AWTEvent
The maximum value for reserved AWT event IDs.
RESERVED_UIROLE - Static variable in class javax.print.ServiceUIFactory
Not a valid role but role id's greater than this may be used for private roles supported by a service.
reset() - Method in class java.awt.geom.Area
Removes all of the geometry from this Area and restores it to an empty area.
reset() - Method in class java.awt.geom.Path2D
Resets the path to empty.
reset() - Method in class java.awt.Polygon
Resets this Polygon object to an empty polygon.
reset() - Method in class java.io.BufferedInputStream
See the general contract of the reset method of InputStream.
reset() - Method in class java.io.BufferedReader
Resets the stream to the most recent mark.
reset() - Method in class java.io.ByteArrayInputStream
Resets the buffer to the marked position.
reset() - Method in class java.io.ByteArrayOutputStream
Resets the count field of this byte array output stream to zero, so that all currently accumulated output in the output stream is discarded.
reset() - Method in class java.io.CharArrayReader
Resets the stream to the most recent mark, or to the beginning if it has never been marked.
reset() - Method in class java.io.CharArrayWriter
Resets the buffer so that you can use it again without throwing away the already allocated buffer.
reset() - Method in class java.io.FilterInputStream
Repositions this stream to the position at the time the mark method was last called on this input stream.
reset() - Method in class java.io.FilterReader
Resets the stream.
reset() - Method in class java.io.InputStream
Repositions this stream to the position at the time the mark method was last called on this input stream.
reset() - Method in class java.io.LineNumberInputStream
Deprecated.
Repositions this stream to the position at the time the mark method was last called on this input stream.
reset() - Method in class java.io.LineNumberReader
Reset the stream to the most recent mark.
reset() - Method in class java.io.ObjectOutputStream
Reset will disregard the state of any objects already written to the stream.
reset() - Method in class java.io.PushbackInputStream
Repositions this stream to the position at the time the mark method was last called on this input stream.
reset() - Method in class java.io.PushbackReader
Resets the stream.
reset() - Method in class java.io.Reader
Resets the stream.
reset() - Method in class java.io.StringBufferInputStream
Deprecated.
Resets the input stream to begin reading from the first character of this input stream's underlying buffer.
reset() - Method in class java.io.StringReader
Resets the stream to the most recent mark, or to the beginning of the string if it has never been marked.
reset() - Method in class java.nio.Buffer
Resets this buffer's position to the previously-marked position.
reset() - Method in class java.nio.charset.CharsetDecoder
Resets this decoder, clearing any internal state.
reset() - Method in class java.nio.charset.CharsetEncoder
Resets this encoder, clearing any internal state.
reset() - Method in interface java.nio.file.WatchKey
Resets this watch key.
reset() - Method in class java.security.MessageDigest
Resets the digest for further use.
reset() - Method in class java.text.CollationElementIterator
Resets the cursor to the beginning of the string.
reset() - Method in class java.util.concurrent.CyclicBarrier
Resets the barrier to its initial state.
reset() - Method in class java.util.logging.LogManager
Reset the logging configuration.
reset() - Method in class java.util.regex.Matcher
Resets this matcher.
reset(CharSequence) - Method in class java.util.regex.Matcher
Resets this matcher with a new input sequence.
reset() - Method in class java.util.Scanner
Resets this scanner.
reset() - Method in class java.util.zip.Adler32
Resets the checksum to initial value.
reset() - Method in interface java.util.zip.Checksum
Resets the checksum to its initial value.
reset() - Method in class java.util.zip.CRC32
Resets CRC-32 to initial value.
reset() - Method in class java.util.zip.Deflater
Resets deflater so that a new set of input data can be processed.
reset() - Method in class java.util.zip.DeflaterInputStream
This operation is not supported.
reset() - Method in class java.util.zip.Inflater
Resets inflater so that a new set of input data can be processed.
reset() - Method in class java.util.zip.InflaterInputStream
Repositions this stream to the position at the time the mark method was last called on this input stream.
reset() - Method in class javax.crypto.Mac
Resets this Mac object.
reset() - Method in class javax.imageio.ImageReader
Restores the ImageReader to its initial state.
reset() - Method in class javax.imageio.ImageWriter
Restores the ImageWriter to its initial state.
reset() - Method in class javax.imageio.metadata.IIOMetadata
Resets all the data stored in this object to default values, usually to the state this object was in immediately after construction, though the precise semantics are plug-in specific.
reset() - Method in interface javax.imageio.stream.ImageInputStream
Returns the stream pointer to its previous position, including the bit offset, at the time of the most recent unmatched call to mark.
reset() - Method in class javax.imageio.stream.ImageInputStreamImpl
Resets the current stream byte and bit positions from the stack of marked positions.
reset() - Method in class javax.sound.sampled.AudioInputStream
Repositions this audio input stream to the position it had at the time its mark method was last invoked.
reset() - Method in class javax.swing.ProgressMonitorInputStream
Overrides FilterInputStream.reset to reset the progress monitor as well as the stream.
RESET - Static variable in class javax.swing.text.html.FormView
Deprecated.
As of 1.3, value comes from UIManager UIManager property FormView.resetButtonText
reset() - Method in class javax.xml.bind.util.ValidationEventCollector
Clear all collected errors and warnings.
reset() - Method in class javax.xml.datatype.XMLGregorianCalendar
Reset this XMLGregorianCalendar to its original values.
reset() - Method in class javax.xml.parsers.DocumentBuilder
Reset this DocumentBuilder to its original configuration.
reset() - Method in class javax.xml.parsers.SAXParser
Reset this SAXParser to its original configuration.
reset() - Method in class javax.xml.transform.Transformer
Reset this Transformer to its original configuration.
reset() - Method in class javax.xml.validation.Validator
Reset this Validator to its original configuration.
reset() - Method in interface javax.xml.xpath.XPath
Reset this XPath to its original configuration.
reset() - Method in class org.xml.sax.helpers.NamespaceSupport
Reset this Namespace support object for reuse.
RESET_FLAGS_ALREADY_NOTIFIED - Static variable in class javax.management.monitor.Monitor
This flag is used to reset the alreadyNotifieds monitor attribute.
resetAllControllers() - Method in interface javax.sound.midi.MidiChannel
Resets all the implemented controllers to their default values.
resetChoosableFileFilters() - Method in class javax.swing.JFileChooser
Resets the choosable file filter list to its starting state.
resetInputValue() - Method in class javax.swing.plaf.basic.BasicOptionPaneUI
Sets the input value in the option pane the receiver is providing the look and feel for based on the value in the inputComponent.
resetKeyboardActions() - Method in class javax.swing.JComponent
Unregisters all the bindings in the first tier InputMaps and ActionMap.
resetLayoutManager() - Method in class javax.swing.plaf.basic.BasicSplitPaneUI
Resets the layout manager based on orientation and messages it with invalidateLayout to pull in appropriate Components.
resetMarksAtZero() - Method in class javax.swing.text.GapContent
Resets all the marks that have an offset of 0 to have an index of zero as well.
resetPeakThreadCount() - Method in interface java.lang.management.ThreadMXBean
Resets the peak thread count to the current number of live threads.
resetPeakUsage() - Method in interface java.lang.management.MemoryPoolMXBean
Resets the peak memory usage statistic of this memory pool to the current memory usage.
resetRecognizer() - Method in class java.awt.dnd.DragGestureRecognizer
Reset the Recognizer, if its currently recognizing a gesture, ignore it.
resetRowSelection() - Method in class javax.swing.tree.DefaultTreeSelectionModel
Updates this object's mapping from TreePath to rows.
resetRowSelection() - Method in interface javax.swing.tree.TreeSelectionModel
Updates this object's mapping from TreePaths to rows.
resetSizeAt(int) - Method in class javax.swing.plaf.basic.BasicSplitPaneUI.BasicHorizontalLayoutManager
Resets the size of the Component at the passed in location.
resetSyntax() - Method in class java.io.StreamTokenizer
Resets this tokenizer's syntax table so that all characters are "ordinary." See the ordinaryChar method for more information on a character being ordinary.
resetToPreferredSizes() - Method in class javax.swing.JSplitPane
Lays out the JSplitPane layout based on the preferred size of the children components.
resetToPreferredSizes() - Method in class javax.swing.plaf.basic.BasicSplitPaneUI.BasicHorizontalLayoutManager
Marks the receiver so that the next time this instance is laid out it'll ask for the preferred sizes.
resetToPreferredSizes(JSplitPane) - Method in class javax.swing.plaf.basic.BasicSplitPaneUI
Messaged to reset the preferred sizes.
resetToPreferredSizes(JSplitPane) - Method in class javax.swing.plaf.multi.MultiSplitPaneUI
Invokes the resetToPreferredSizes method on each UI handled by this object.
resetToPreferredSizes(JSplitPane) - Method in class javax.swing.plaf.SplitPaneUI
Messaged to relayout the JSplitPane based on the preferred size of the children components.
resetViewPort() - Method in class javax.swing.JScrollPane.AccessibleJScrollPane
reshape(int, int, int, int) - Method in class java.awt.Component
Deprecated.
As of JDK version 1.1, replaced by setBounds(int, int, int, int).
reshape(int, int, int, int) - Method in class java.awt.Rectangle
Deprecated.
As of JDK version 1.1, replaced by setBounds(int, int, int, int).
reshape(int, int, int, int) - Method in class java.awt.Window
Deprecated.
As of JDK version 1.1, replaced by setBounds(int, int, int, int).
reshape(int, int, int, int) - Method in class javax.swing.JComponent
Deprecated.
As of JDK 5, replaced by Component.setBounds(int, int, int, int).

Moves and resizes this component.

reshape(int, int, int, int) - Method in class javax.swing.JInternalFrame
Moves and resizes this component.
reshape(int, int, int, int) - Method in class javax.swing.JViewport
Sets the bounds of this viewport.
RESIZABLE - Static variable in class javax.accessibility.AccessibleState
Indicates the size of this object is not fixed.
resizable - Variable in class javax.swing.JInternalFrame
The frame's size can be changed.
resize(int, int) - Method in class java.applet.Applet
Requests that this applet be resized.
resize(Dimension) - Method in class java.applet.Applet
Requests that this applet be resized.
resize(int, int) - Method in class java.awt.Component
Deprecated.
As of JDK version 1.1, replaced by setSize(int, int).
resize(Dimension) - Method in class java.awt.Component
Deprecated.
As of JDK version 1.1, replaced by setSize(Dimension).
resize(int, int) - Method in class java.awt.Rectangle
Deprecated.
As of JDK version 1.1, replaced by setSize(int, int).
RESIZE_NONE - Variable in class javax.swing.plaf.basic.BasicInternalFrameUI.BorderListener
RESIZE_WEIGHT_PROPERTY - Static variable in class javax.swing.JSplitPane
Bound property for weight.
resizeAndRepaint() - Method in class javax.swing.JTable
Equivalent to revalidate followed by repaint.
resizeAndRepaint() - Method in class javax.swing.table.JTableHeader
Sizes the header and marks it as needing display.
resizedPostingDisableCount - Variable in class javax.swing.table.TableColumn
Deprecated.
as of Java 2 platform v1.3
resizeFrame(JComponent, int, int, int, int) - Method in class javax.swing.DefaultDesktopManager
Calls setBoundsForFrame with the new values.
resizeFrame(JComponent, int, int, int, int) - Method in interface javax.swing.DesktopManager
The user has resized the component.
resizingAllowed - Variable in class javax.swing.table.JTableHeader
If true, resizing of columns are allowed by the user; the default is true.
resizingColumn - Variable in class javax.swing.table.JTableHeader
The index of the column being resized.
resolution - Variable in class javax.sound.midi.MidiFileFormat
The timing resolution of the MIDI file.
resolution - Variable in class javax.sound.midi.Sequence
The timing resolution of the sequence.
ResolutionSyntax - Class in javax.print.attribute
Class ResolutionSyntax is an abstract base class providing the common implementation of all attributes denoting a printer resolution.
ResolutionSyntax(int, int, int) - Constructor for class javax.print.attribute.ResolutionSyntax
Construct a new resolution attribute from the given items.
resolve(URI) - Method in class java.net.URI
Resolves the given URI against this URI.
resolve(String) - Method in class java.net.URI
Constructs a new URI by parsing the given string and then resolving it against this URI.
resolve(Path) - Method in interface java.nio.file.Path
Resolve the given path against this path.
resolve(String) - Method in interface java.nio.file.Path
Converts a given path string to a Path and resolves it against this Path in exactly the manner specified by the resolve method.
resolve(String, String) - Method in interface javax.xml.transform.URIResolver
Called by the processor when it encounters an xsl:include, xsl:import, or document() function.
resolve(NameComponent[]) - Method in class org.omg.CosNaming._NamingContextExtStub
The resolve operation is the process of retrieving an object bound to a name in a given context.
resolve(NameComponent[]) - Method in class org.omg.CosNaming._NamingContextStub
The resolve operation is the process of retrieving an object bound to a name in a given context.
resolve(NameComponent[]) - Method in interface org.omg.CosNaming.NamingContextOperations
The resolve operation is the process of retrieving an object bound to a name in a given context.
resolve_initial_references(String) - Method in class org.omg.CORBA.ORB
Resolves a specific object reference from the set of available initial service names.
resolve_initial_references(String) - Method in interface org.omg.PortableInterceptor.ORBInitInfoOperations
Identical to ORB.resolve_initial_references.
resolve_str(String) - Method in class org.omg.CosNaming._NamingContextExtStub
This operation resolves the Stringified name into the object reference.
resolve_str(String) - Method in interface org.omg.CosNaming.NamingContextExtOperations
This operation resolves the Stringified name into the object reference.
ResolveAttribute - Static variable in interface javax.swing.text.AttributeSet
Attribute name used to identify the resolving parent set of attributes, if one is defined.
ResolveAttribute - Static variable in class javax.swing.text.StyleConstants
Attribute name used to identifiy the resolving parent set of attributes, if one is defined.
resolveClass(ObjectStreamClass) - Method in class java.io.ObjectInputStream
Load the local class equivalent of the specified stream class description.
resolveClass(Class<?>) - Method in class java.lang.ClassLoader
Links the specified class.
resolvedName - Variable in exception javax.naming.NamingException
Contains the part of the name that has been successfully resolved.
resolvedObj - Variable in exception javax.naming.NamingException
Contains the object to which resolution of the part of the name was successful.
resolvedObj - Variable in class javax.naming.spi.ResolveResult
Field containing the Object that was resolved to successfully.
resolveEntity(String, String, String, String) - Method in interface javax.xml.stream.XMLResolver
Retrieves a resource.
resolveEntity(String, String) - Method in interface org.xml.sax.EntityResolver
Allow the application to resolve external entities.
resolveEntity(String, String, String, String) - Method in class org.xml.sax.ext.DefaultHandler2
Tells the parser to resolve the systemId against the baseURI and read the entity text from that resulting absolute URI.
resolveEntity(String, String) - Method in class org.xml.sax.ext.DefaultHandler2
Invokes EntityResolver2.resolveEntity() with null entity name and base URI.
resolveEntity(String, String, String, String) - Method in interface org.xml.sax.ext.EntityResolver2
Allows applications to map references to external entities into input sources, or tell the parser it should use conventional URI resolution.
resolveEntity(String, String) - Method in class org.xml.sax.HandlerBase
Deprecated.
Resolve an external entity.
resolveEntity(String, String) - Method in class org.xml.sax.helpers.DefaultHandler
Resolve an external entity.
resolveEntity(String, String) - Method in class org.xml.sax.helpers.XMLFilterImpl
Filter an external entity resolution.
resolveFunction(QName, int) - Method in interface javax.xml.xpath.XPathFunctionResolver
Find a function in the set of available functions.
resolveObject(Object) - Method in class java.io.ObjectInputStream
This method will allow trusted subclasses of ObjectInputStream to substitute one object for another during deserialization.
resolveProxyClass(String[]) - Method in class java.io.ObjectInputStream
Returns a proxy class that implements the interfaces named in a proxy class descriptor; subclasses may implement this method to read custom data from the stream along with the descriptors for dynamic proxy classes, allowing them to use an alternate loading mechanism for the interfaces and the proxy class.
Resolver - Interface in javax.naming.spi
This interface represents an "intermediate context" for name resolution.
RESOLVER - Static variable in class javax.xml.stream.XMLInputFactory
The property used to set/get the implementation of the XMLResolver
resolveResource(String, String, String, String, String) - Method in interface org.w3c.dom.ls.LSResourceResolver
Allow the application to resolve external resources.
ResolveResult - Class in javax.naming.spi
This class represents the result of resolution of a name.
ResolveResult() - Constructor for class javax.naming.spi.ResolveResult
Constructs an instance of ResolveResult with the resolved object and remaining name both initialized to null.
ResolveResult(Object, String) - Constructor for class javax.naming.spi.ResolveResult
Constructs a new instance of ResolveResult consisting of the resolved object and the remaining unresolved component.
ResolveResult(Object, Name) - Constructor for class javax.naming.spi.ResolveResult
Constructs a new instance of ResolveResult consisting of the resolved Object and the remaining name.
resolveSibling(Path) - Method in interface java.nio.file.Path
Resolves the given path against this path's parent path.
resolveSibling(String) - Method in interface java.nio.file.Path
Converts a given path string to a Path and resolves it against this path's parent path in exactly the manner specified by the resolveSibling method.
resolveToClass(Name, Class<? extends Context>) - Method in interface javax.naming.spi.Resolver
Partially resolves a name.
resolveToClass(String, Class<? extends Context>) - Method in interface javax.naming.spi.Resolver
Partially resolves a name.
resolveVariable(QName) - Method in interface javax.xml.xpath.XPathVariableResolver
Find a variable in the set of available variables.
Resource - Annotation Type in javax.annotation
The Resource annotation marks a resource that is needed by the application.
Resource.AuthenticationType - Enum in javax.annotation
The two possible authentication types for a resource.
ResourceBundle - Class in java.util
Resource bundles contain locale-specific objects.
ResourceBundle() - Constructor for class java.util.ResourceBundle
Sole constructor.
ResourceBundle.Control - Class in java.util
ResourceBundle.Control defines a set of callback methods that are invoked by the ResourceBundle.getBundle factory methods during the bundle loading process.
ResourceBundle.Control() - Constructor for class java.util.ResourceBundle.Control
Sole constructor.
Resources - Annotation Type in javax.annotation
This class is used to allow multiple resources declarations.
RESOURCES_ARE_NOT_READY - Static variable in class javax.print.attribute.standard.JobStateReason
At least one of the resources needed by the job, such as media, fonts, resource objects, etc., is not ready on any of the physical printers for which the job is a candidate.
RespectBinding - Annotation Type in javax.xml.ws
This feature clarifies the use of the wsdl:binding in a JAX-WS runtime.
RespectBindingFeature - Class in javax.xml.ws
This feature clarifies the use of the wsdl:binding in a JAX-WS runtime.
RespectBindingFeature() - Constructor for class javax.xml.ws.RespectBindingFeature
Creates an RespectBindingFeature.
RespectBindingFeature(boolean) - Constructor for class javax.xml.ws.RespectBindingFeature
Creates an RespectBindingFeature
Response<T> - Interface in javax.xml.ws
The Response interface provides methods used to obtain the payload and context of a message sent in response to an operation invocation.
response_expected() - Method in interface org.omg.PortableInterceptor.RequestInfoOperations
Indicates whether a response is expected.
ResponseCache - Class in java.net
Represents implementations of URLConnection caches.
ResponseCache() - Constructor for class java.net.ResponseCache
responseCode() - Method in exception java.net.HttpRetryException
Returns the http response code
responseCode - Variable in class java.net.HttpURLConnection
An int representing the three digit HTTP Status-Code.
ResponseHandler - Interface in org.omg.CORBA.portable
This interface is supplied by an ORB to a servant at invocation time and allows the servant to later retrieve an OutputStream for returning the invocation results.
responseMessage - Variable in class java.net.HttpURLConnection
The HTTP response message.
ResponseWrapper - Annotation Type in javax.xml.ws
Used to annotate methods in the Service Endpoint Interface with the response wrapper bean to be used at runtime.
rest_of_name - Variable in exception org.omg.CosNaming.NamingContextPackage.CannotProceed
rest_of_name - Variable in exception org.omg.CosNaming.NamingContextPackage.NotFound
restart() - Method in class javax.swing.Timer
Restarts the Timer, canceling any pending firings and causing it to fire with its initial delay.
RESTORE_CMD - Static variable in class javax.swing.plaf.basic.BasicInternalFrameTitlePane
restoreAction - Variable in class javax.swing.plaf.basic.BasicInternalFrameTitlePane
restoreComposedText() - Method in class javax.swing.text.JTextComponent
Restores composed text previously saved by saveComposedText.
restoreOriginal() - Method in interface javax.sql.rowset.CachedRowSet
Restores this CachedRowSet object to its original value, that is, its value before the last set of changes.
restoreState(Hashtable<?, ?>) - Method in interface javax.swing.undo.StateEditable
Upon receiving this message the receiver should extract any relevant state out of state.
restoreSubcomponentFocus() - Method in class javax.swing.JInternalFrame
Requests the internal frame to restore focus to the last subcomponent that had focus.
Result - Interface in javax.xml.transform
An object that implements this interface contains the information needed to build a transformation result tree.
result() - Method in class org.omg.CORBA.Request
Retrieves the NamedValue object containing the return value for the method.
result(Any) - Method in class org.omg.CORBA.ServerRequest
Deprecated.
use the method set_result
result() - Method in interface org.omg.PortableInterceptor.RequestInfoOperations
Returns an any containing the result of the operation invocation.
ResultSet - Interface in java.sql
A table of data representing a database result set, which is usually generated by executing a statement that queries the database.
ResultSetMetaData - Interface in java.sql
An object that can be used to get information about the types and properties of the columns in a ResultSet object.
resume() - Method in class java.lang.Thread
Deprecated.
This method exists solely for use with Thread.suspend(), which has been deprecated because it is deadlock-prone. For more information, see Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?.
resume() - Method in class java.lang.ThreadGroup
Deprecated.
This method is used solely in conjunction with Thread.suspend and ThreadGroup.suspend, both of which have been deprecated, as they are inherently deadlock-prone. See Thread.suspend() for details.
RETAIN - Static variable in class org.omg.PortableServer.ServantRetentionPolicyValue
retainAll(Collection) - Method in class java.beans.beancontext.BeanContextSupport
retain only specified children (Unsupported) implementations must synchronized on the hierarchy lock and "children" protected field
retainAll(Collection<?>) - Method in class java.util.AbstractCollection
Retains only the elements in this collection that are contained in the specified collection (optional operation).
retainAll(Collection<?>) - Method in class java.util.ArrayList
Retains only the elements in this list that are contained in the specified collection.
retainAll(Collection<?>) - Method in interface java.util.Collection
Retains only the elements in this collection that are contained in the specified collection (optional operation).
retainAll(Collection<?>) - Method in class java.util.concurrent.CopyOnWriteArrayList
Retains only the elements in this list that are contained in the specified collection.
retainAll(Collection<?>) - Method in class java.util.concurrent.CopyOnWriteArraySet
Retains only the elements in this set that are contained in the specified collection.
retainAll(Collection<?>) - Method in class java.util.concurrent.SynchronousQueue
Always returns false.
retainAll(Collection<?>) - Method in interface java.util.List
Retains only the elements in this list that are contained in the specified collection (optional operation).
retainAll(Collection<?>) - Method in interface java.util.Set
Retains only the elements in this set that are contained in the specified collection (optional operation).
retainAll(Collection<?>) - Method in class java.util.Vector
Retains only the elements in this Vector that are contained in the specified Collection.
Retention - Annotation Type in java.lang.annotation
Indicates how long annotations with the annotated type are to be retained.
RetentionPolicy - Enum in java.lang.annotation
Annotation retention policy.
retransformClasses(Class<?>...) - Method in interface java.lang.instrument.Instrumentation
Retransform the supplied set of classes.
RetrievalMethod - Interface in javax.xml.crypto.dsig.keyinfo
A representation of the XML RetrievalMethod element as defined in the W3C Recommendation for XML-Signature Syntax and Processing.
retrieveAllRoles() - Method in interface javax.management.relation.Relation
Returns all roles in the relation without checking read mode.
retrieveAllRoles() - Method in class javax.management.relation.RelationSupport
Returns all roles in the relation without checking read mode.
retryReferral() - Method in exception javax.naming.ReferralException
Retries the referral currently being processed.
RETURN_GENERATED_KEYS - Static variable in interface java.sql.Statement
The constant indicating that generated keys should be made available for retrieval.
return_value() - Method in class org.omg.CORBA.Request
Returns the Any object that contains the value for the result of the method.
returnType() - Method in class java.lang.invoke.MethodType
Returns the return type of this method type.
REUSE - Static variable in class javax.security.sasl.Sasl
The name of a property that specifies whether to reuse previously authenticated session information.
REV - Static variable in class javax.swing.text.html.HTML.Attribute
revalidate() - Method in class java.awt.Component.BltBufferStrategy
Restore the drawing buffer if it has been lost
revalidate() - Method in class java.awt.Component.FlipBufferStrategy
Restore the drawing buffer if it has been lost
revalidate() - Method in class javax.swing.DefaultListCellRenderer
Overridden for performance reasons.
revalidate() - Method in class javax.swing.JComponent
Supports deferred automatic layout.
revalidate() - Method in class javax.swing.table.DefaultTableCellRenderer
Overridden for performance reasons.
revalidate() - Method in class javax.swing.tree.DefaultTreeCellRenderer
Overridden for performance reasons.
REVERB - Static variable in class javax.sound.sampled.EnumControl.Type
Represents a control over a set of possible reverberation settings.
REVERB_RETURN - Static variable in class javax.sound.sampled.FloatControl.Type
Represents a control for the post-reverb gain on a line.
REVERB_SEND - Static variable in class javax.sound.sampled.FloatControl.Type
Represents a control for the pre-reverb gain on a line.
ReverbType - Class in javax.sound.sampled
The ReverbType class provides methods for accessing various reverberation settings to be applied to an audio signal.
ReverbType(String, int, float, int, float, int) - Constructor for class javax.sound.sampled.ReverbType
Constructs a new reverb type that has the specified reverberation parameter values.
reverse(int) - Static method in class java.lang.Integer
Returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified int value.
reverse(long) - Static method in class java.lang.Long
Returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified long value.
reverse() - Method in class java.lang.StringBuffer
reverse() - Method in class java.lang.StringBuilder
reverse(List<?>) - Static method in class java.util.Collections
Reverses the order of the elements in the specified list.
REVERSE_LANDSCAPE - Static variable in class java.awt.print.PageFormat
The origin is at the top right of the paper with x running top to bottom and y running right to left.
REVERSE_LANDSCAPE - Static variable in class javax.print.attribute.standard.OrientationRequested
The content will be imaged across the long edge of the medium, but in the opposite manner from landscape.
REVERSE_PORTRAIT - Static variable in class javax.print.attribute.standard.OrientationRequested
The content will be imaged across the short edge of the medium, but in the opposite manner from portrait.
reverseBytes(char) - Static method in class java.lang.Character
Returns the value obtained by reversing the order of the bytes in the specified char value.
reverseBytes(int) - Static method in class java.lang.Integer
Returns the value obtained by reversing the order of the bytes in the two's complement representation of the specified int value.
reverseBytes(long) - Static method in class java.lang.Long
Returns the value obtained by reversing the order of the bytes in the two's complement representation of the specified long value.
reverseBytes(short) - Static method in class java.lang.Short
Returns the value obtained by reversing the order of the bytes in the two's complement representation of the specified short value.
reverseOrder() - Static method in class java.util.Collections
Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
reverseOrder(Comparator<T>) - Static method in class java.util.Collections
Returns a comparator that imposes the reverse ordering of the specified comparator.
REVERT - Static variable in class javax.swing.JFormattedTextField
Constant identifying that when focus is lost, editing value should be reverted to current value set on the JFormattedTextField.
revokeService(Class, BeanContextServiceProvider, boolean) - Method in interface java.beans.beancontext.BeanContextServices
BeanContextServiceProviders wishing to remove a currently registered service from this context may do so via invocation of this method.
revokeService(Class, BeanContextServiceProvider, boolean) - Method in class java.beans.beancontext.BeanContextServicesSupport
remove a service
rewind() - Method in class java.nio.Buffer
Rewinds this buffer.
rewind() - Method in interface org.omg.CORBA.DynAny
Deprecated.
Moves the internal pointer to the first component.
rewind() - Method in class org.omg.DynamicAny._DynAnyStub
Is equivalent to seek(0).
rewind() - Method in class org.omg.DynamicAny._DynArrayStub
Is equivalent to seek(0).
rewind() - Method in class org.omg.DynamicAny._DynEnumStub
Is equivalent to seek(0).
rewind() - Method in class org.omg.DynamicAny._DynFixedStub
Is equivalent to seek(0).
rewind() - Method in class org.omg.DynamicAny._DynSequenceStub
Is equivalent to seek(0).
rewind() - Method in class org.omg.DynamicAny._DynStructStub
Is equivalent to seek(0).
rewind() - Method in class org.omg.DynamicAny._DynUnionStub
Is equivalent to seek(0).
rewind() - Method in class org.omg.DynamicAny._DynValueStub
Is equivalent to seek(0).
rewind() - Method in interface org.omg.DynamicAny.DynAnyOperations
Is equivalent to seek(0).
RFC1779 - Static variable in class javax.security.auth.x500.X500Principal
RFC 1779 String format of Distinguished Names.
RFC2253 - Static variable in class javax.security.auth.x500.X500Principal
RFC 2253 String format of Distinguished Names.
RGBImageFilter - Class in java.awt.image
This class provides an easy way to create an ImageFilter which modifies the pixels of an image in the default RGB ColorModel.
RGBImageFilter() - Constructor for class java.awt.image.RGBImageFilter
RGBtoHSB(int, int, int, float[]) - Static method in class java.awt.Color
Converts the components of a color, as specified by the default RGB model, to an equivalent set of values for hue, saturation, and brightness that are the three components of the HSB model.
RIGHT - Static variable in class java.awt.Event
The Right Arrow key, a non-ASCII action key.
RIGHT - Static variable in class java.awt.FlowLayout
This value indicates that each row of components should be right-justified.
right - Variable in class java.awt.Insets
The inset from the right.
RIGHT - Static variable in class java.awt.Label
Indicates that the label should be right justified.
right - Variable in class javax.swing.border.EmptyBorder
RIGHT - Static variable in class javax.swing.border.TitledBorder
Position title text at the right side of the border line.
RIGHT - Static variable in class javax.swing.JSplitPane
Used to add a Component to the right of the other Component.
RIGHT - Static variable in interface javax.swing.SwingConstants
Box-orientation constant used to specify the right side of a box.
RIGHT_ALIGNMENT - Static variable in class java.awt.Component
Ease-of-use constant for getAlignmentX.
RIGHT_OUTER_JOIN - Static variable in interface javax.sql.rowset.JoinRowSet
An ANSI-style JOIN providing a right outer join between two tables.
RIGHT_TO_LEFT - Static variable in class java.awt.ComponentOrientation
Items run right to left and lines flow top to bottom Examples: Arabic, Hebrew.
rightButton - Variable in class javax.swing.plaf.basic.BasicSplitPaneDivider
Button for quickly toggling the right component.
rightChildIndent - Variable in class javax.swing.plaf.basic.BasicTreeUI
Distance to add to leftChildIndent to determine where cell contents will be drawn.
rightComponent - Variable in class javax.swing.JSplitPane
The right or bottom component.
RightIndent - Static variable in class javax.swing.text.StyleConstants
The amount to indent the right side of the paragraph.
rightKey - Variable in class javax.swing.plaf.basic.BasicSplitPaneUI
Deprecated.
As of Java 2 platform v1.3.
rightKey - Variable in class javax.swing.plaf.basic.BasicTabbedPaneUI
Deprecated.
As of Java 2 platform v1.3.
rightKey - Variable in class javax.swing.plaf.basic.BasicToolBarUI
Deprecated.
As of Java 2 platform v1.3.
rint(double) - Static method in class java.lang.Math
Returns the double value that is closest in value to the argument and is equal to a mathematical integer.
rint(double) - Static method in class java.lang.StrictMath
Returns the double value that is closest in value to the argument and is equal to a mathematical integer.
RIPEMD160 - Static variable in interface javax.xml.crypto.dsig.DigestMethod
The RIPEMD-160 digest method algorithm URI.
RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE - Static variable in class javax.management.remote.rmi.RMIConnectorServer
Name of the attribute that specifies the RMIClientSocketFactory for the RMI objects created in conjunction with this connector.
RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE - Static variable in class javax.management.remote.rmi.RMIConnectorServer
Name of the attribute that specifies the RMIServerSocketFactory for the RMI objects created in conjunction with this connector.
RMIClassLoader - Class in java.rmi.server
RMIClassLoader comprises static methods to support dynamic class loading with RMI.
RMIClassLoaderSpi - Class in java.rmi.server
RMIClassLoaderSpi is the service provider interface for RMIClassLoader.
RMIClassLoaderSpi() - Constructor for class java.rmi.server.RMIClassLoaderSpi
RMIClientSocketFactory - Interface in java.rmi.server
An RMIClientSocketFactory instance is used by the RMI runtime in order to obtain client sockets for RMI calls.
RMIConnection - Interface in javax.management.remote.rmi
RMI object used to forward an MBeanServer request from a client to its MBeanServer implementation on the server side.
RMIConnectionImpl - Class in javax.management.remote.rmi
Implementation of the RMIConnection interface.
RMIConnectionImpl(RMIServerImpl, String, ClassLoader, Subject, Map<String, ?>) - Constructor for class javax.management.remote.rmi.RMIConnectionImpl
Constructs a new RMIConnection.
RMIConnectionImpl_Stub - Class in javax.management.remote.rmi
RMIConnectionImpl_Stub(RemoteRef) - Constructor for class javax.management.remote.rmi.RMIConnectionImpl_Stub
RMIConnector - Class in javax.management.remote.rmi
A connection to a remote RMI connector.
RMIConnector(JMXServiceURL, Map<String, ?>) - Constructor for class javax.management.remote.rmi.RMIConnector
Constructs an RMIConnector that will connect the RMI connector server with the given address.
RMIConnector(RMIServer, Map<String, ?>) - Constructor for class javax.management.remote.rmi.RMIConnector
Constructs an RMIConnector using the given RMI stub.
RMIConnectorServer - Class in javax.management.remote.rmi
A JMX API connector server that creates RMI-based connections from remote clients.
RMIConnectorServer(JMXServiceURL, Map<String, ?>) - Constructor for class javax.management.remote.rmi.RMIConnectorServer
Makes an RMIConnectorServer.
RMIConnectorServer(JMXServiceURL, Map<String, ?>, MBeanServer) - Constructor for class javax.management.remote.rmi.RMIConnectorServer
Makes an RMIConnectorServer for the given MBean server.
RMIConnectorServer(JMXServiceURL, Map<String, ?>, RMIServerImpl, MBeanServer) - Constructor for class javax.management.remote.rmi.RMIConnectorServer
Makes an RMIConnectorServer for the given MBean server.
RMICustomMaxStreamFormat - Interface in org.omg.IOP
org/omg/IOP/RMICustomMaxStreamFormat.java .
RMIFailureHandler - Interface in java.rmi.server
An RMIFailureHandler can be registered via the RMISocketFactory.setFailureHandler call.
RMIIIOPServerImpl - Class in javax.management.remote.rmi
An RMIServerImpl that is exported through IIOP and that creates client connections as RMI objects exported through IIOP.
RMIIIOPServerImpl(Map<String, ?>) - Constructor for class javax.management.remote.rmi.RMIIIOPServerImpl
Creates a new RMIServerImpl.
RMIJRMPServerImpl - Class in javax.management.remote.rmi
An RMIServer object that is exported through JRMP and that creates client connections as RMI objects exported through JRMP.
RMIJRMPServerImpl(int, RMIClientSocketFactory, RMIServerSocketFactory, Map<String, ?>) - Constructor for class javax.management.remote.rmi.RMIJRMPServerImpl
Creates a new RMIServer object that will be exported on the given port using the given socket factories.
RMISecurityException - Exception in java.rmi
Deprecated.
Use SecurityException instead. Application code should never directly reference this class, and RMISecurityManager no longer throws this subclass of java.lang.SecurityException.
RMISecurityException(String) - Constructor for exception java.rmi.RMISecurityException
Deprecated.
no replacement
RMISecurityException(String, String) - Constructor for exception java.rmi.RMISecurityException
Deprecated.
no replacement
RMISecurityManager - Class in java.rmi
A subclass of SecurityManager used by RMI applications that use downloaded code.
RMISecurityManager() - Constructor for class java.rmi.RMISecurityManager
Constructs a new RMISecurityManager.
RMIServer - Interface in javax.management.remote.rmi
RMI object used to establish connections to an RMI connector.
RMIServerImpl - Class in javax.management.remote.rmi
An RMI object representing a connector server.
RMIServerImpl(Map<String, ?>) - Constructor for class javax.management.remote.rmi.RMIServerImpl
Constructs a new RMIServerImpl.
RMIServerImpl_Stub - Class in javax.management.remote.rmi
RMIServerImpl_Stub(RemoteRef) - Constructor for class javax.management.remote.rmi.RMIServerImpl_Stub
RMIServerSocketFactory - Interface in java.rmi.server
An RMIServerSocketFactory instance is used by the RMI runtime in order to obtain server sockets for RMI calls.
RMISocketFactory - Class in java.rmi.server
An RMISocketFactory instance is used by the RMI runtime in order to obtain client and server sockets for RMI calls.
RMISocketFactory() - Constructor for class java.rmi.server.RMISocketFactory
Constructs an RMISocketFactory.
Robot - Class in java.awt
This class is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed.
Robot() - Constructor for class java.awt.Robot
Constructs a Robot object in the coordinate system of the primary screen.
Robot(GraphicsDevice) - Constructor for class java.awt.Robot
Creates a Robot for the given screen device.
Role - Class in javax.management.relation
Represents a role: includes a role name and referenced MBeans (via their ObjectNames).
Role(String, List<ObjectName>) - Constructor for class javax.management.relation.Role
Make a new Role object.
ROLE_CARDINALITY_INFINITY - Static variable in class javax.management.relation.RoleInfo
To specify an unlimited cardinality.
ROLE_NOT_READABLE - Static variable in class javax.management.relation.RoleStatus
Problem type when trying to read a non-readable attribute.
ROLE_NOT_WRITABLE - Static variable in class javax.management.relation.RoleStatus
Problem type when trying to update a non-writable attribute.
RoleInfo - Class in javax.management.relation
A RoleInfo object summarises a role in a relation type.
RoleInfo(String, String, boolean, boolean, int, int, String) - Constructor for class javax.management.relation.RoleInfo
Constructor.
RoleInfo(String, String, boolean, boolean) - Constructor for class javax.management.relation.RoleInfo
Constructor.
RoleInfo(String, String) - Constructor for class javax.management.relation.RoleInfo
Constructor.
RoleInfo(RoleInfo) - Constructor for class javax.management.relation.RoleInfo
Copy constructor.
RoleInfoNotFoundException - Exception in javax.management.relation
This exception is raised when there is no role info with given name in a given relation type.
RoleInfoNotFoundException() - Constructor for exception javax.management.relation.RoleInfoNotFoundException
Default constructor, no message put in exception.
RoleInfoNotFoundException(String) - Constructor for exception javax.management.relation.RoleInfoNotFoundException
Constructor with given message put in exception.
RoleList - Class in javax.management.relation
A RoleList represents a list of roles (Role objects).
RoleList() - Constructor for class javax.management.relation.RoleList
Constructs an empty RoleList.
RoleList(int) - Constructor for class javax.management.relation.RoleList
Constructs an empty RoleList with the initial capacity specified.
RoleList(List<Role>) - Constructor for class javax.management.relation.RoleList
Constructs a RoleList containing the elements of the List specified, in the order in which they are returned by the List's iterator.
RoleNotFoundException - Exception in javax.management.relation
This exception is raised when a role in a relation does not exist, or is not readable, or is not settable.
RoleNotFoundException() - Constructor for exception javax.management.relation.RoleNotFoundException
Default constructor, no message put in exception.
RoleNotFoundException(String) - Constructor for exception javax.management.relation.RoleNotFoundException
Constructor with given message put in exception.
RoleResult - Class in javax.management.relation
Represents the result of a multiple access to several roles of a relation (either for reading or writing).
RoleResult(RoleList, RoleUnresolvedList) - Constructor for class javax.management.relation.RoleResult
Constructor.
RoleStatus - Class in javax.management.relation
This class describes the various problems which can be encountered when accessing a role.
RoleStatus() - Constructor for class javax.management.relation.RoleStatus
RoleUnresolved - Class in javax.management.relation
Represents an unresolved role: a role not retrieved from a relation due to a problem.
RoleUnresolved(String, List<ObjectName>, int) - Constructor for class javax.management.relation.RoleUnresolved
Constructor.
RoleUnresolvedList - Class in javax.management.relation
A RoleUnresolvedList represents a list of RoleUnresolved objects, representing roles not retrieved from a relation due to a problem encountered when trying to access (read or write) the roles.
RoleUnresolvedList() - Constructor for class javax.management.relation.RoleUnresolvedList
Constructs an empty RoleUnresolvedList.
RoleUnresolvedList(int) - Constructor for class javax.management.relation.RoleUnresolvedList
Constructs an empty RoleUnresolvedList with the initial capacity specified.
RoleUnresolvedList(List<RoleUnresolved>) - Constructor for class javax.management.relation.RoleUnresolvedList
Constructs a RoleUnresolvedList containing the elements of the List specified, in the order in which they are returned by the List's iterator.
roleValueToString(List<ObjectName>) - Static method in class javax.management.relation.Role
Returns a string for the given role value.
roll(int, boolean) - Method in class java.util.Calendar
Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields.
roll(int, int) - Method in class java.util.Calendar
Adds the specified (signed) amount to the specified calendar field without changing larger fields.
roll(int, boolean) - Method in class java.util.GregorianCalendar
Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields.
roll(int, int) - Method in class java.util.GregorianCalendar
Adds a signed amount to the specified calendar field without changing larger fields.
rollback() - Method in interface java.sql.Connection
Undoes all changes made in the current transaction and releases any database locks currently held by this Connection object.
rollback(Savepoint) - Method in interface java.sql.Connection
Undoes all changes made after the given Savepoint object was set.
rollback() - Method in interface javax.sql.rowset.CachedRowSet
Each CachedRowSet object's SyncProvider contains a Connection object from the original ResultSet or JDBC properties passed to it.
rollback(Savepoint) - Method in interface javax.sql.rowset.CachedRowSet
Each CachedRowSet object's SyncProvider contains a Connection object from the original ResultSet or JDBC properties passed to it.
rollback() - Method in interface javax.sql.rowset.JdbcRowSet
Each JdbcRowSet contains a Connection object from the original ResultSet or JDBC properties passed to it.
rollback(Savepoint) - Method in interface javax.sql.rowset.JdbcRowSet
Each JdbcRowSet contains a Connection object from the original ResultSet or JDBC properties passed to it.
rollback() - Method in interface javax.sql.rowset.spi.TransactionalWriter
Undoes all changes made in the current transaction.
rollback(Savepoint) - Method in interface javax.sql.rowset.spi.TransactionalWriter
Undoes all changes made in the current transaction made prior to the given Savepoint object.
rollback(Xid) - Method in interface javax.transaction.xa.XAResource
Informs the resource manager to roll back work done on behalf of a transaction branch.
ROLLOVER - Static variable in class javax.swing.DefaultButtonModel
Identifies the "rollover" bit in the bitmask, which indicates that the mouse is over the button.
ROLLOVER_ENABLED_CHANGED_PROPERTY - Static variable in class javax.swing.AbstractButton
Identifies a change from rollover enabled to disabled or back to enabled.
ROLLOVER_ICON_CHANGED_PROPERTY - Static variable in class javax.swing.AbstractButton
Identifies a change to the icon used when the cursor is over the button.
ROLLOVER_SELECTED_ICON_CHANGED_PROPERTY - Static variable in class javax.swing.AbstractButton
Identifies a change to the icon used when the cursor is over the button and it has been selected.
rolloverColumnUpdated(int, int) - Method in class javax.swing.plaf.basic.BasicTableHeaderUI
This method gets called every time when a rollover column in the table header is updated.
rolloverColumnUpdated(int, int) - Method in class javax.swing.plaf.synth.SynthTableHeaderUI
rolloverListener - Variable in class javax.swing.plaf.metal.MetalToolBarUI
This protected field is implemenation specific.
ROMAN_BASELINE - Static variable in class java.awt.font.GraphicAttribute
Aligns origin of graphic to roman baseline of line.
ROMAN_BASELINE - Static variable in class java.awt.Font
The baseline used in most Roman scripts when laying out text.
ROOT - Static variable in class java.util.Locale
Useful constant for the root locale.
root - Variable in class javax.swing.tree.DefaultTreeModel
Root of the tree.
ROOT_PANE - Static variable in class javax.accessibility.AccessibleRole
A specialized pane that has a glass pane and a layered pane as its children.
ROOT_PANE - Static variable in class javax.swing.plaf.synth.Region
RootPane region.
ROOT_PANE_PROPERTY - Static variable in class javax.swing.JInternalFrame
Bound property name.
ROOT_VISIBLE_PROPERTY - Static variable in class javax.swing.JTree
Bound property name for rootVisible.
rootException - Variable in exception javax.naming.NamingException
Contains the original exception that caused this NamingException to be thrown.
rootPane - Variable in class javax.swing.JApplet
rootPane - Variable in class javax.swing.JDialog
rootPane - Variable in class javax.swing.JFrame
The JRootPane instance that manages the contentPane and optional menuBar for this frame, as well as the glassPane.
rootPane - Variable in class javax.swing.JInternalFrame
The JRootPane instance that manages the content pane and optional menu bar for this internal frame, as well as the glass pane.
rootPane - Variable in class javax.swing.JWindow
The JRootPane instance that manages the contentPane and optional menuBar for this frame, as well as the glassPane.
rootPaneCheckingEnabled - Variable in class javax.swing.JApplet
If true then calls to add and setLayout will be forwarded to the contentPane.
rootPaneCheckingEnabled - Variable in class javax.swing.JDialog
If true then calls to add and setLayout will be forwarded to the contentPane.
rootPaneCheckingEnabled - Variable in class javax.swing.JFrame
If true then calls to add and setLayout will be forwarded to the contentPane.
rootPaneCheckingEnabled - Variable in class javax.swing.JInternalFrame
If true then calls to add and setLayout will be forwarded to the contentPane.
rootPaneCheckingEnabled - Variable in class javax.swing.JWindow
If true then calls to add and setLayout will be forwarded to the contentPane.
RootPaneContainer - Interface in javax.swing
This interface is implemented by components that have a single JRootPane child: JDialog, JFrame, JWindow, JApplet, JInternalFrame.
RootPaneUI - Class in javax.swing.plaf
Pluggable look and feel interface for JRootPane.
RootPaneUI() - Constructor for class javax.swing.plaf.RootPaneUI
rootVisible - Variable in class javax.swing.JTree
True if the root node is displayed, false if its children are the highest visible nodes.
rootVisible - Variable in class javax.swing.tree.AbstractLayoutCache
True if the root node is displayed, false if its children are the highest visible nodes.
rotate(double) - Method in class java.awt.geom.AffineTransform
Concatenates this transform with a rotation transformation.
rotate(double, double, double) - Method in class java.awt.geom.AffineTransform
Concatenates this transform with a transform that rotates coordinates around an anchor point.
rotate(double, double) - Method in class java.awt.geom.AffineTransform
Concatenates this transform with a transform that rotates coordinates according to a rotation vector.
rotate(double, double, double, double) - Method in class java.awt.geom.AffineTransform
Concatenates this transform with a transform that rotates coordinates around an anchor point according to a rotation vector.
rotate(double) - Method in class java.awt.Graphics2D
Concatenates the current Graphics2D Transform with a rotation transform.
rotate(double, double, double) - Method in class java.awt.Graphics2D
Concatenates the current Graphics2D Transform with a translated rotation transform.
rotate(List<?>, int) - Static method in class java.util.Collections
Rotates the elements in the specified list by the specified distance.
rotateInsets(Insets, Insets, int) - Static method in class javax.swing.plaf.basic.BasicTabbedPaneUI
rotateLeft(int, int) - Static method in class java.lang.Integer
Returns the value obtained by rotating the two's complement binary representation of the specified int value left by the specified number of bits.
rotateLeft(long, int) - Static method in class java.lang.Long
Returns the value obtained by rotating the two's complement binary representation of the specified long value left by the specified number of bits.
rotateRight(int, int) - Static method in class java.lang.Integer
Returns the value obtained by rotating the two's complement binary representation of the specified int value right by the specified number of bits.
rotateRight(long, int) - Static method in class java.lang.Long
Returns the value obtained by rotating the two's complement binary representation of the specified long value right by the specified number of bits.
rotateTabRuns(int, int) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI.TabbedPaneLayout
rotateTabRuns(int, int) - Method in class javax.swing.plaf.metal.MetalTabbedPaneUI.TabbedPaneLayout
round(float) - Static method in class java.lang.Math
Returns the closest int to the argument.
round(double) - Static method in class java.lang.Math
Returns the closest long to the argument.
round(float) - Static method in class java.lang.StrictMath
Returns the closest int to the argument.
round(double) - Static method in class java.lang.StrictMath
Returns the closest long to the argument.
round(MathContext) - Method in class java.math.BigDecimal
Returns a BigDecimal rounded according to the MathContext settings.
ROUND_CEILING - Static variable in class java.math.BigDecimal
Rounding mode to round towards positive infinity.
ROUND_DOWN - Static variable in class java.math.BigDecimal
Rounding mode to round towards zero.
ROUND_FLOOR - Static variable in class java.math.BigDecimal
Rounding mode to round towards negative infinity.
ROUND_HALF_DOWN - Static variable in class java.math.BigDecimal
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.
ROUND_HALF_EVEN - Static variable in class java.math.BigDecimal
Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.
ROUND_HALF_UP - Static variable in class java.math.BigDecimal
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.
ROUND_UNNECESSARY - Static variable in class java.math.BigDecimal
Rounding mode to assert that the requested operation has an exact result, hence no rounding is necessary.
ROUND_UP - Static variable in class java.math.BigDecimal
Rounding mode to round away from zero.
roundedCorners - Variable in class javax.swing.border.LineBorder
RoundEnvironment - Interface in javax.annotation.processing
An annotation processing tool framework will provide an annotation processor with an object implementing this interface so that the processor can query for information about a round of annotation processing.
RoundingMode - Enum in java.math
Specifies a rounding behavior for numerical operations capable of discarding precision.
RoundRectangle2D - Class in java.awt.geom
The RoundRectangle2D class defines a rectangle with rounded corners defined by a location (x,y), a dimension (w x h), and the width and height of an arc with which to round the corners.
RoundRectangle2D() - Constructor for class java.awt.geom.RoundRectangle2D
This is an abstract class that cannot be instantiated directly.
RoundRectangle2D.Double - Class in java.awt.geom
The Double class defines a rectangle with rounded corners all specified in double coordinates.
RoundRectangle2D.Double() - Constructor for class java.awt.geom.RoundRectangle2D.Double
Constructs a new RoundRectangle2D, initialized to location (0.0, 0.0), size (0.0, 0.0), and corner arcs of radius 0.0.
RoundRectangle2D.Double(double, double, double, double, double, double) - Constructor for class java.awt.geom.RoundRectangle2D.Double
Constructs and initializes a RoundRectangle2D from the specified double coordinates.
RoundRectangle2D.Float - Class in java.awt.geom
The Float class defines a rectangle with rounded corners all specified in float coordinates.
RoundRectangle2D.Float() - Constructor for class java.awt.geom.RoundRectangle2D.Float
Constructs a new RoundRectangle2D, initialized to location (0.0, 0.0), size (0.0, 0.0), and corner arcs of radius 0.0.
RoundRectangle2D.Float(float, float, float, float, float, float) - Constructor for class java.awt.geom.RoundRectangle2D.Float
Constructs and initializes a RoundRectangle2D from the specified float coordinates.
ROW_HEADER - Static variable in class javax.accessibility.AccessibleRole
The header for a row of data.
ROW_HEADER - Static variable in interface javax.swing.ScrollPaneConstants
Identifies the area along the left side of the viewport between the upper left corner and the lower left corner.
ROW_HEIGHT_PROPERTY - Static variable in class javax.swing.JTree
Bound property name for rowHeight.
rowAtPoint(Point) - Method in class javax.swing.JTable
Returns the index of the row that point lies in, or -1 if the result is not in the range [0, getRowCount()-1].
rowChanged(RowSetEvent) - Method in interface javax.sql.RowSetListener
Notifies registered listeners that a RowSet object has had a change in one of its rows.
rowDeleted() - Method in interface java.sql.ResultSet
Retrieves whether a row has been deleted.
RowFilter<M,I> - Class in javax.swing
RowFilter is used to filter out entries from the model so that they are not shown in the view.
RowFilter() - Constructor for class javax.swing.RowFilter
RowFilter.ComparisonType - Enum in javax.swing
Enumeration of the possible comparison values supported by some of the default RowFilters.
RowFilter.Entry<M,I> - Class in javax.swing
An Entry object is passed to instances of RowFilter, allowing the filter to get the value of the entry's data, and thus to determine whether the entry should be shown.
RowFilter.Entry() - Constructor for class javax.swing.RowFilter.Entry
Creates an Entry.
rowHead - Variable in class javax.swing.ScrollPaneLayout
The row header child.
rowHeader - Variable in class javax.swing.JScrollPane
The row header child.
rowHeight - Variable in class javax.swing.JTable
The height in pixels of each row in the table.
rowHeight - Variable in class javax.swing.JTree
Height to use for each display row.
rowHeight - Variable in class javax.swing.tree.AbstractLayoutCache
Height to use for each row.
rowHeights - Variable in class java.awt.GridBagLayout
This field holds the overrides to the row minimum heights.
RowId - Interface in java.sql
The representation (mapping) in the Java programming language of an SQL ROWID value.
ROWID - Static variable in class java.sql.Types
The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type ROWID
RowIdLifetime - Enum in java.sql
Enumeration for RowId life-time values.
rowInserted() - Method in interface java.sql.ResultSet
Retrieves whether the current row has had an insertion.
rowMapper - Variable in class javax.swing.tree.DefaultTreeSelectionModel
Provides a row for a given path.
RowMapper - Interface in javax.swing.tree
Defines the requirements for an object that translates paths in the tree into display rows.
rowMargin - Variable in class javax.swing.JTable
The height in pixels of the margin between the cells in each row.
ROWS - Static variable in class javax.swing.text.html.HTML.Attribute
rowsDeleted(int, int) - Method in class javax.swing.DefaultRowSorter
Invoked when rows have been deleted from the underlying model in the specified range (inclusive).
rowsDeleted(int, int) - Method in class javax.swing.RowSorter
Invoked when rows have been deleted from the underlying model in the specified range (inclusive).
rowSelectionAllowed - Variable in class javax.swing.JTable
True if row selection is allowed in this table.
RowSet - Interface in javax.sql
The interface that adds support to the JDBC API for the JavaBeansTM component model.
ROWSET_SYNC_PROVIDER - Static variable in class javax.sql.rowset.spi.SyncFactory
The standard property-id for a synchronization provider implementation name.
ROWSET_SYNC_PROVIDER_VERSION - Static variable in class javax.sql.rowset.spi.SyncFactory
The standard property-id for a synchronization provider implementation version tag.
ROWSET_SYNC_VENDOR - Static variable in class javax.sql.rowset.spi.SyncFactory
The standard property-id for a synchronization provider implementation vendor name.
rowSetChanged(RowSetEvent) - Method in interface javax.sql.RowSetListener
Notifies registered listeners that a RowSet object in the given RowSetEvent object has changed its entire contents.
RowSetEvent - Class in javax.sql
An Event object generated when an event occurs to a RowSet object.
RowSetEvent(RowSet) - Constructor for class javax.sql.RowSetEvent
Constructs a RowSetEvent object initialized with the given RowSet object.
RowSetFactory - Interface in javax.sql.rowset
An interface that defines the implementation of a factory that is used to obtain different types of RowSet implementations.
RowSetInternal - Interface in javax.sql
The interface that a RowSet object implements in order to present itself to a RowSetReader or RowSetWriter object.
RowSetListener - Interface in javax.sql
An interface that must be implemented by a component that wants to be notified when a significant event happens in the life of a RowSet object.
RowSetMetaData - Interface in javax.sql
An object that contains information about the columns in a RowSet object.
RowSetMetaDataImpl - Class in javax.sql.rowset
Provides implementations for the methods that set and get metadata information about a RowSet object's columns.
RowSetMetaDataImpl() - Constructor for class javax.sql.rowset.RowSetMetaDataImpl
rowSetPopulated(RowSetEvent, int) - Method in interface javax.sql.rowset.CachedRowSet
Notifies registered listeners that a RowSet object in the given RowSetEvent object has populated a number of additional rows.
RowSetProvider - Class in javax.sql.rowset
A factory API that enables applications to obtain a RowSetFactory implementation that can be used to create different types of RowSet implementations.
RowSetProvider() - Constructor for class javax.sql.rowset.RowSetProvider
RowSetReader - Interface in javax.sql
The facility that a disconnected RowSet object calls on to populate itself with rows of data.
RowSetWarning - Exception in javax.sql.rowset
An extension of SQLException that provides information about database warnings set on RowSet objects.
RowSetWarning(String) - Constructor for exception javax.sql.rowset.RowSetWarning
Constructs a RowSetWarning object with the given value for the reason; SQLState defaults to null, and vendorCode defaults to 0.
RowSetWarning() - Constructor for exception javax.sql.rowset.RowSetWarning
Constructs a default RowSetWarning object.
RowSetWarning(String, String) - Constructor for exception javax.sql.rowset.RowSetWarning
Constructs a RowSetWarning object initialized with the given values for the reason and SQLState.
RowSetWarning(String, String, int) - Constructor for exception javax.sql.rowset.RowSetWarning
Constructs a fully specified RowSetWarning object initialized with the given values for the reason, SQLState and vendorCode.
RowSetWriter - Interface in javax.sql
An object that implements the RowSetWriter interface, called a writer.
rowsInserted(int, int) - Method in class javax.swing.DefaultRowSorter
Invoked when rows have been inserted into the underlying model in the specified range (inclusive).
rowsInserted(int, int) - Method in class javax.swing.RowSorter
Invoked when rows have been inserted into the underlying model in the specified range (inclusive).
RowSorter<M> - Class in javax.swing
RowSorter provides the basis for sorting and filtering.
RowSorter() - Constructor for class javax.swing.RowSorter
Creates a RowSorter.
RowSorter.SortKey - Class in javax.swing
SortKey describes the sort order for a particular column.
RowSorter.SortKey(int, SortOrder) - Constructor for class javax.swing.RowSorter.SortKey
Creates a SortKey for the specified column with the specified sort order.
RowSorterEvent - Class in javax.swing.event
RowSorterEvent provides notification of changes to a RowSorter.
RowSorterEvent(RowSorter) - Constructor for class javax.swing.event.RowSorterEvent
Creates a RowSorterEvent of type SORT_ORDER_CHANGED.
RowSorterEvent(RowSorter, RowSorterEvent.Type, int[]) - Constructor for class javax.swing.event.RowSorterEvent
Creates a RowSorterEvent.
RowSorterEvent.Type - Enum in javax.swing.event
Enumeration of the types of RowSorterEvents.
RowSorterListener - Interface in javax.swing.event
RowSorterListeners are notified of changes to a RowSorter.
ROWSPAN - Static variable in class javax.swing.text.html.HTML.Attribute
rowsRemoved(TableModelEvent) - Method in class javax.swing.table.DefaultTableModel
Equivalent to fireTableChanged.
rowsUpdated(int, int) - Method in class javax.swing.DefaultRowSorter
Invoked when rows have been changed in the underlying model between the specified range (inclusive).
rowsUpdated(int, int, int) - Method in class javax.swing.DefaultRowSorter
Invoked when the column in the rows have been updated in the underlying model between the specified range.
rowsUpdated(int, int) - Method in class javax.swing.RowSorter
Invoked when rows have been changed in the underlying model between the specified range (inclusive).
rowsUpdated(int, int, int) - Method in class javax.swing.RowSorter
Invoked when the column in the rows have been updated in the underlying model between the specified range.
rowUpdated() - Method in interface java.sql.ResultSet
Retrieves whether the current row has been updated.
rowWeights - Variable in class java.awt.GridBagLayout
This field holds the overrides to the row weights.
RSA_SHA1 - Static variable in interface javax.xml.crypto.dsig.SignatureMethod
The RSAwithSHA1 (PKCS #1) signature method algorithm URI.
RSA_TYPE - Static variable in interface javax.xml.crypto.dsig.keyinfo.KeyValue
URI identifying the RSA KeyValue KeyInfo type: http://www.w3.org/2000/09/xmldsig#RSAKeyValue.
RSAKey - Interface in java.security.interfaces
The interface to an RSA public or private key.
RSAKeyGenParameterSpec - Class in java.security.spec
This class specifies the set of parameters used to generate an RSA key pair.
RSAKeyGenParameterSpec(int, BigInteger) - Constructor for class java.security.spec.RSAKeyGenParameterSpec
Constructs a new RSAParameterSpec object from the given keysize and public-exponent value.
RSAMultiPrimePrivateCrtKey - Interface in java.security.interfaces
The interface to an RSA multi-prime private key, as defined in the PKCS#1 v2.1, using the Chinese Remainder Theorem (CRT) information values.
RSAMultiPrimePrivateCrtKeySpec - Class in java.security.spec
This class specifies an RSA multi-prime private key, as defined in the PKCS#1 v2.1, using the Chinese Remainder Theorem (CRT) information values for efficiency.
RSAMultiPrimePrivateCrtKeySpec(BigInteger, BigInteger, BigInteger, BigInteger, BigInteger, BigInteger, BigInteger, BigInteger, RSAOtherPrimeInfo[]) - Constructor for class java.security.spec.RSAMultiPrimePrivateCrtKeySpec
Creates a new RSAMultiPrimePrivateCrtKeySpec given the modulus, publicExponent, privateExponent, primeP, primeQ, primeExponentP, primeExponentQ, crtCoefficient, and otherPrimeInfo as defined in PKCS#1 v2.1.
RSAOtherPrimeInfo - Class in java.security.spec
This class represents the triplet (prime, exponent, and coefficient) inside RSA's OtherPrimeInfo structure, as defined in the PKCS#1 v2.1.
RSAOtherPrimeInfo(BigInteger, BigInteger, BigInteger) - Constructor for class java.security.spec.RSAOtherPrimeInfo
Creates a new RSAOtherPrimeInfo given the prime, primeExponent, and crtCoefficient as defined in PKCS#1.
RSAPrivateCrtKey - Interface in java.security.interfaces
The interface to an RSA private key, as defined in the PKCS#1 standard, using the Chinese Remainder Theorem (CRT) information values.
RSAPrivateCrtKeySpec - Class in java.security.spec
This class specifies an RSA private key, as defined in the PKCS#1 standard, using the Chinese Remainder Theorem (CRT) information values for efficiency.
RSAPrivateCrtKeySpec(BigInteger, BigInteger, BigInteger, BigInteger, BigInteger, BigInteger, BigInteger, BigInteger) - Constructor for class java.security.spec.RSAPrivateCrtKeySpec
Creates a new RSAPrivateCrtKeySpec given the modulus, publicExponent, privateExponent, primeP, primeQ, primeExponentP, primeExponentQ, and crtCoefficient as defined in PKCS#1.
RSAPrivateKey - Interface in java.security.interfaces
The interface to an RSA private key.
RSAPrivateKeySpec - Class in java.security.spec
This class specifies an RSA private key.
RSAPrivateKeySpec(BigInteger, BigInteger) - Constructor for class java.security.spec.RSAPrivateKeySpec
Creates a new RSAPrivateKeySpec.
RSAPublicKey - Interface in java.security.interfaces
The interface to an RSA public key.
RSAPublicKeySpec - Class in java.security.spec
This class specifies an RSA public key.
RSAPublicKeySpec(BigInteger, BigInteger) - Constructor for class java.security.spec.RSAPublicKeySpec
Creates a new RSAPublicKeySpec.
RTFEditorKit - Class in javax.swing.text.rtf
This is the default implementation of RTF editing functionality.
RTFEditorKit() - Constructor for class javax.swing.text.rtf.RTFEditorKit
Constructs an RTFEditorKit.
RuleBasedCollator - Class in java.text
The RuleBasedCollator class is a concrete subclass of Collator that provides a simple, data-driven, table collator.
RuleBasedCollator(String) - Constructor for class java.text.RuleBasedCollator
RuleBasedCollator constructor.
RULER - Static variable in class javax.accessibility.AccessibleRole
A ruler is an object used to measure distance
RUMI_NUMERAL_SYMBOLS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Rumi Numeral Symbols" Unicode character block.
run() - Method in class java.awt.image.renderable.RenderableImageProducer
The runnable method for this class.
run() - Method in interface java.lang.Runnable
When an object implementing interface Runnable is used to create a thread, starting the thread causes the object's run method to be called in that separately executing thread.
run() - Method in class java.lang.Thread
If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.
run() - Method in interface java.security.PrivilegedAction
Performs the computation.
run() - Method in interface java.security.PrivilegedExceptionAction
Performs the computation.
run() - Method in class java.util.concurrent.ForkJoinWorkerThread
This method is required to be public, but should never be called explicitly.
run() - Method in class java.util.concurrent.FutureTask
Sets this Future to the result of its computation unless it has been cancelled.
run() - Method in interface java.util.concurrent.RunnableFuture
Sets this Future to the result of its computation unless it has been cancelled.
run() - Method in class java.util.TimerTask
The action to be performed by this timer task.
run() - Method in class javax.swing.SwingWorker
Sets this Future to the result of computation unless it has been cancelled.
run() - Method in class javax.swing.text.AsyncBoxView.ChildState
Update the child state.
run(InputStream, OutputStream, OutputStream, String...) - Method in interface javax.tools.Tool
Run the tool with the given I/O channels and arguments.
run() - Method in class org.omg.CORBA.ORB
This operation blocks the current thread until the ORB has completed the shutdown process, initiated when some thread calls shutdown.
RUN_DIRECTION - Static variable in class java.awt.font.TextAttribute
Attribute key for the run direction of the line.
RUN_DIRECTION_LTR - Static variable in class java.awt.font.TextAttribute
Left-to-right run direction.
RUN_DIRECTION_RTL - Static variable in class java.awt.font.TextAttribute
Right-to-left run direction.
runAndReset() - Method in class java.util.concurrent.FutureTask
Executes the computation without setting its result, and then resets this Future to initial state, failing to do so if the computation encounters an exception or is cancelled.
runCount - Variable in class javax.swing.plaf.basic.BasicTabbedPaneUI
runFinalization() - Method in class java.lang.Runtime
Runs the finalization methods of any objects pending finalization.
runFinalization() - Static method in class java.lang.System
Runs the finalization methods of any objects pending finalization.
runFinalizersOnExit(boolean) - Static method in class java.lang.Runtime
Deprecated.
This method is inherently unsafe. It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock.
runFinalizersOnExit(boolean) - Static method in class java.lang.System
Deprecated.
This method is inherently unsafe. It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock.
RUNIC - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Runic" Unicode character block.
runnable - Variable in class java.awt.event.InvocationEvent
The Runnable whose run() method will be called.
Runnable - Interface in java.lang
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.
RunnableFuture<V> - Interface in java.util.concurrent
A Future that is Runnable.
RunnableScheduledFuture<V> - Interface in java.util.concurrent
A ScheduledFuture that is Runnable.
Runtime - Class in java.lang
Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running.
RunTime - Interface in org.omg.SendingContext
Defines the base class that represents the Sending Context of a request.
RUNTIME_ERROR - Static variable in class javax.management.monitor.MonitorNotification
Notification type denoting that a non-predefined error type has occurred when trying to get the value of the observed attribute.
RUNTIME_ERROR_NOTIFIED - Static variable in class javax.management.monitor.Monitor
Flag denoting that a notification has occurred after changing the observed object or the observed attribute.
RUNTIME_MXBEAN_NAME - Static variable in class java.lang.management.ManagementFactory
String representation of the ObjectName for the RuntimeMXBean.
RuntimeErrorException - Exception in javax.management
When a java.lang.Error occurs in the agent it should be caught and re-thrown as a RuntimeErrorException.
RuntimeErrorException(Error) - Constructor for exception javax.management.RuntimeErrorException
Default constructor.
RuntimeErrorException(Error, String) - Constructor for exception javax.management.RuntimeErrorException
Constructor that allows a specific error message to be specified.
RuntimeException - Exception in java.lang
RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine.
RuntimeException() - Constructor for exception java.lang.RuntimeException
Constructs a new runtime exception with null as its detail message.
RuntimeException(String) - Constructor for exception java.lang.RuntimeException
Constructs a new runtime exception with the specified detail message.
RuntimeException(String, Throwable) - Constructor for exception java.lang.RuntimeException
Constructs a new runtime exception with the specified detail message and cause.
RuntimeException(Throwable) - Constructor for exception java.lang.RuntimeException
Constructs a new runtime exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).
RuntimeMBeanException - Exception in javax.management
Represents runtime exceptions thrown by MBean methods in the agent.
RuntimeMBeanException(RuntimeException) - Constructor for exception javax.management.RuntimeMBeanException
Creates a RuntimeMBeanException that wraps the actual java.lang.RuntimeException.
RuntimeMBeanException(RuntimeException, String) - Constructor for exception javax.management.RuntimeMBeanException
Creates a RuntimeMBeanException that wraps the actual java.lang.RuntimeException with a detailed message.
RuntimeMXBean - Interface in java.lang.management
The management interface for the runtime system of the Java virtual machine.
RunTimeOperations - Interface in org.omg.SendingContext
Defines operations on the base class that represents the Sending Context of a request.
RuntimeOperationsException - Exception in javax.management
Represents runtime exceptions thrown in the agent when performing operations on MBeans.
RuntimeOperationsException(RuntimeException) - Constructor for exception javax.management.RuntimeOperationsException
Creates a RuntimeOperationsException that wraps the actual java.lang.RuntimeException.
RuntimeOperationsException(RuntimeException, String) - Constructor for exception javax.management.RuntimeOperationsException
Creates a RuntimeOperationsException that wraps the actual java.lang.RuntimeException with a detailed message.
RuntimePermission - Class in java.lang
This class is for runtime permissions.
RuntimePermission(String) - Constructor for class java.lang.RuntimePermission
Creates a new RuntimePermission with the specified name.
RuntimePermission(String, String) - Constructor for class java.lang.RuntimePermission
Creates a new RuntimePermission object with the specified name.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类


S-Index

请注意：本 java api 1.7Beta 规范不是最终稳定版，未来随着版本的更迭，本规范可能有更新。

概述

软件包

类

使用

树

已过时

Index

帮助

Java™ Platform
Standard Ed. 7
草案 ea-b138

Prev Letter

Next Letter

框架

无框架

所有的类

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _
S

S - Static variable in class javax.swing.text.html.HTML.Tag

S_RESIZE_CURSOR - Static variable in class java.awt.Cursor

The south-resize cursor type.

S_RESIZE_CURSOR - Static variable in class java.awt.Frame

Deprecated.
replaced by Cursor.S_RESIZE_CURSOR.

SAAJMetaFactory - Class in javax.xml.soap

The access point for the implementation classes of the factories defined in the SAAJ API.

SAAJMetaFactory() - Constructor for class javax.xml.soap.SAAJMetaFactory

SAAJResult - Class in javax.xml.soap

Acts as a holder for the results of a JAXP transformation or a JAXB marshalling, in the form of a SAAJ tree.

SAAJResult() - Constructor for class javax.xml.soap.SAAJResult

Creates a SAAJResult that will present results in the form of a SAAJ tree that supports the default (SOAP 1.1) protocol.

SAAJResult(String) - Constructor for class javax.xml.soap.SAAJResult

Creates a SAAJResult that will present results in the form of a SAAJ tree that supports the specified protocol.

SAAJResult(SOAPMessage) - Constructor for class javax.xml.soap.SAAJResult

Creates a SAAJResult that will write the results into the SOAPPart of the supplied SOAPMessage.

SAAJResult(SOAPElement) - Constructor for class javax.xml.soap.SAAJResult

Creates a SAAJResult that will write the results as a child node of the SOAPElement specified.

SADDLE_STITCH - Static variable in class javax.print.attribute.standard.Finishings

Bind the document(s) with one or more staples (wire stitches) along the middle fold.

SafeVarargs - Annotation Type in java.lang

A programmer assertion that the body of the annotated method or constructor does not perform potentially unsafe operations on its varargs parameter.

SAMARITAN - Static variable in class java.lang.Character.UnicodeBlock

Constant for the "Samaritan" Unicode character block.

sameFile(URL) - Method in class java.net.URL

Compares two URLs, excluding the fragment component.

sameFile(URL, URL) - Method in class java.net.URLStreamHandler

Compare two urls to see whether they refer to the same file, i.e., having the same protocol, host, port, and path.

SAMP - Static variable in class javax.swing.text.html.HTML.Tag

SAMPLE_RATE - Static variable in class javax.sound.sampled.FloatControl.Type

Represents a control that changes the sample rate of audio playback.

sampleModel - Variable in class java.awt.image.Raster

The SampleModel that describes how pixels from this Raster are stored in the DataBuffer.

SampleModel - Class in java.awt.image

This abstract class defines an interface for extracting samples of pixels in an image.

SampleModel(int, int, int, int) - Constructor for class java.awt.image.SampleModel

Constructs a SampleModel with the specified parameters.

sampleModel - Variable in class javax.imageio.ImageTypeSpecifier

A SampleModel to be used as a prototype.

sampleModelTranslateX - Variable in class java.awt.image.Raster

The X translation from the coordinate space of the Raster's SampleModel to that of the Raster.

sampleModelTranslateY - Variable in class java.awt.image.Raster

The Y translation from the coordinate space of the Raster's SampleModel to that of the Raster.

sampleRate - Variable in class javax.sound.sampled.AudioFormat

The number of samples played or recorded per second, for sounds that have this format.

sampleSizeInBits - Variable in class javax.sound.sampled.AudioFormat

The number of bits in each sample of a sound that has this format.

SANS_SERIF - Static variable in class java.awt.Font

A String constant for the canonical family name of the logical font "SansSerif".

Sasl - Class in javax.security.sasl

A static class for creating SASL clients and servers.

SaslClient - Interface in javax.security.sasl

Performs SASL authentication as a client.

SaslClientFactory - Interface in javax.security.sasl

An interface for creating instances of SaslClient.

SaslException - Exception in javax.security.sasl

This class represents an error that has occurred when using SASL.

SaslException() - Constructor for exception javax.security.sasl.SaslException

Constructs a new instance of SaslException.

SaslException(String) - Constructor for exception javax.security.sasl.SaslException

Constructs a new instance of SaslException with a detailed message.

SaslException(String, Throwable) - Constructor for exception javax.security.sasl.SaslException

Constructs a new instance of SaslException with a detailed message and a root exception.

SaslServer - Interface in javax.security.sasl

Performs SASL authentication as a server.

SaslServerFactory - Interface in javax.security.sasl

An interface for creating instances of SaslServer.

SATURDAY - Static variable in class java.util.Calendar

Value of the Calendar.DAY_OF_WEEK field indicating Saturday.

SAURASHTRA - Static variable in class java.lang.Character.UnicodeBlock

Constant for the "Saurashtra" Unicode character block.

save(ObjectOutputStream, String, EventListener) - Static method in class java.awt.AWTEventMulticaster

SAVE - Static variable in class java.awt.FileDialog

This constant value indicates that the purpose of the file dialog window is to locate a file to which to write.

save(OutputStream, String) - Method in class java.util.Properties

Deprecated.
This method does not throw an IOException if an I/O error occurs while saving the property list. The preferred way to save a properties list is via the store(OutputStream out, String comments) method or the storeToXML(OutputStream os, String comment) method.

SAVE_DIALOG - Static variable in class javax.swing.JFileChooser

Type value indicating that the JFileChooser supports a "Save" file operation.

SAVE_FILE - Static variable in class java.awt.Event

A file saving event.

saveButtonMnemonic - Variable in class javax.swing.plaf.basic.BasicFileChooserUI

saveButtonText - Variable in class javax.swing.plaf.basic.BasicFileChooserUI

saveButtonToolTipText - Variable in class javax.swing.plaf.basic.BasicFileChooserUI

saveChanges() - Method in class javax.xml.soap.SOAPMessage

Updates this SOAPMessage object with all the changes that have been made to it.

saveComposedText(int) - Method in class javax.swing.text.JTextComponent

Saves composed text around the specified position.

saveInternal(ObjectOutputStream, String) - Method in class java.awt.AWTEventMulticaster

Savepoint - Interface in java.sql

The representation of a savepoint, which is a point within the current transaction that can be referenced from the Connection.rollback method.

saveRequired() - Method in class javax.xml.soap.SOAPMessage

Indicates whether this SOAPMessage object needs to have the method saveChanges called on it.

SAXException - Exception in org.xml.sax

Encapsulate a general SAX error or warning.

SAXException() - Constructor for exception org.xml.sax.SAXException

Create a new SAXException.

SAXException(String) - Constructor for exception org.xml.sax.SAXException

Create a new SAXException.

SAXException(Exception) - Constructor for exception org.xml.sax.SAXException

Create a new SAXException wrapping an existing exception.

SAXException(String, Exception) - Constructor for exception org.xml.sax.SAXException

Create a new SAXException from an existing exception.

SAXNotRecognizedException - Exception in org.xml.sax

Exception class for an unrecognized identifier.

SAXNotRecognizedException() - Constructor for exception org.xml.sax.SAXNotRecognizedException

Default constructor.

SAXNotRecognizedException(String) - Constructor for exception org.xml.sax.SAXNotRecognizedException

Construct a new exception with the given message.

SAXNotSupportedException - Exception in org.xml.sax

Exception class for an unsupported operation.

SAXNotSupportedException() - Constructor for exception org.xml.sax.SAXNotSupportedException

Construct a new exception with no message.

SAXNotSupportedException(String) - Constructor for exception org.xml.sax.SAXNotSupportedException

Construct a new exception with the given message.

SAXParseException - Exception in org.xml.sax

Encapsulate an XML parse error or warning.

SAXParseException(String, Locator) - Constructor for exception org.xml.sax.SAXParseException

Create a new SAXParseException from a message and a Locator.

SAXParseException(String, Locator, Exception) - Constructor for exception org.xml.sax.SAXParseException

Wrap an existing exception in a SAXParseException.

SAXParseException(String, String, String, int, int) - Constructor for exception org.xml.sax.SAXParseException

Create a new SAXParseException.

SAXParseException(String, String, String, int, int, Exception) - Constructor for exception org.xml.sax.SAXParseException

Create a new SAXParseException with an embedded exception.

SAXParser - Class in javax.xml.parsers

Defines the API that wraps an XMLReader implementation class.

SAXParser() - Constructor for class javax.xml.parsers.SAXParser

Protected constructor to prevent instaniation.

SAXParserFactory - Class in javax.xml.parsers

Defines a factory API that enables applications to configure and obtain a SAX based parser to parse XML documents.

SAXParserFactory() - Constructor for class javax.xml.parsers.SAXParserFactory

Protected constructor to force use of SAXParserFactory.newInstance().

SAXResult - Class in javax.xml.transform.sax

Acts as an holder for a transformation Result.

SAXResult() - Constructor for class javax.xml.transform.sax.SAXResult

Zero-argument default constructor.

SAXResult(ContentHandler) - Constructor for class javax.xml.transform.sax.SAXResult

Create a SAXResult that targets a SAX2 ContentHandler.

SAXSource - Class in javax.xml.transform.sax

Acts as an holder for SAX-style Source.

SAXSource() - Constructor for class javax.xml.transform.sax.SAXSource

Zero-argument default constructor.

SAXSource(XMLReader, InputSource) - Constructor for class javax.xml.transform.sax.SAXSource

Create a SAXSource, using an XMLReader and a SAX InputSource.

SAXSource(InputSource) - Constructor for class javax.xml.transform.sax.SAXSource

Create a SAXSource, using a SAX InputSource.

SAXTransformerFactory - Class in javax.xml.transform.sax

This class extends TransformerFactory to provide SAX-specific factory methods.

SAXTransformerFactory() - Constructor for class javax.xml.transform.sax.SAXTransformerFactory

The default constructor is protected on purpose.

SC_BLOCK_DATA - Static variable in interface java.io.ObjectStreamConstants

Bit mask for ObjectStreamClass flag.

SC_ENUM - Static variable in interface java.io.ObjectStreamConstants

Bit mask for ObjectStreamClass flag.

SC_EXTERNALIZABLE - Static variable in interface java.io.ObjectStreamConstants

Bit mask for ObjectStreamClass flag.

SC_SERIALIZABLE - Static variable in interface java.io.ObjectStreamConstants

Bit mask for ObjectStreamClass flag.

SC_WRITE_METHOD - Static variable in interface java.io.ObjectStreamConstants

Bit mask for ObjectStreamClass flag.

scalb(double, int) - Static method in class java.lang.Math

Return d × 2scaleFactor rounded as if performed by a single correctly rounded floating-point multiply to a member of the double value set.

scalb(float, int) - Static method in class java.lang.Math

Return f × 2scaleFactor rounded as if performed by a single correctly rounded floating-point multiply to a member of the float value set.

scalb(double, int) - Static method in class java.lang.StrictMath

Return d × 2scaleFactor rounded as if performed by a single correctly rounded floating-point multiply to a member of the double value set.

scalb(float, int) - Static method in class java.lang.StrictMath

Return f × 2scaleFactor rounded as if performed by a single correctly rounded floating-point multiply to a member of the float value set.

scale(double, double) - Method in class java.awt.geom.AffineTransform

Concatenates this transform with a scaling transformation.

scale(double, double) - Method in class java.awt.Graphics2D

Concatenates the current Graphics2D Transform with a scaling transformation Subsequent rendering is resized according to the specified scaling factors relative to the previous scaling.

scale() - Method in class java.math.BigDecimal

Returns the scale of this BigDecimal.

scale(Spring, float) - Static method in class javax.swing.Spring

Returns a spring whose minimum, preferred, maximum and value properties are each multiples of the properties of the argument spring, s.

SCALE_AREA_AVERAGING - Static variable in class java.awt.Image

Use the Area Averaging image scaling algorithm.

SCALE_DEFAULT - Static variable in class java.awt.Image

Use the default image-scaling algorithm.

SCALE_FAST - Static variable in class java.awt.Image

Choose an image-scaling algorithm that gives higher priority to scaling speed than smoothness of the scaled image.

SCALE_REPLICATE - Static variable in class java.awt.Image

Use the image scaling algorithm embodied in the ReplicateScaleFilter class.

SCALE_SMOOTH - Static variable in class java.awt.Image

Choose an image-scaling algorithm that gives higher priority to image smoothness than scaling speed.

scaleByPowerOfTen(int) - Method in class java.math.BigDecimal

Returns a BigDecimal whose numerical value is equal to (this * 10n).

scan(Iterable<? extends Element>, P) - Method in class javax.lang.model.util.ElementScanner6

Iterates over the given elements and calls scan(Element, P) on each one.

scan(Element, P) - Method in class javax.lang.model.util.ElementScanner6

Processes an element by calling e.accept(this, p); this method may be overridden by subclasses.

scan(Element) - Method in class javax.lang.model.util.ElementScanner6

Convenience method equivalent to v.scan(e, null).

scanForPlugins() - Static method in class javax.imageio.ImageIO

Scans for plug-ins on the application class path, loads their service provider classes, and registers a service provider instance for each one found with the IIORegistry.

scanlineStride - Variable in class java.awt.image.ComponentSampleModel

Line stride (in data array elements) of the region of image data described by this ComponentSampleModel.

Scanner - Class in java.util

A simple text scanner which can parse primitive types and strings using regular expressions.

Scanner(Readable) - Constructor for class java.util.Scanner

Constructs a new Scanner that produces values scanned from the specified source.

Scanner(InputStream) - Constructor for class java.util.Scanner

Constructs a new Scanner that produces values scanned from the specified input stream.

Scanner(InputStream, String) - Constructor for class java.util.Scanner

Constructs a new Scanner that produces values scanned from the specified input stream.

Scanner(File) - Constructor for class java.util.Scanner

Constructs a new Scanner that produces values scanned from the specified file.

Scanner(File, String) - Constructor for class java.util.Scanner

Constructs a new Scanner that produces values scanned from the specified file.

Scanner(Path) - Constructor for class java.util.Scanner

Constructs a new Scanner that produces values scanned from the specified file.

Scanner(Path, String) - Constructor for class java.util.Scanner

Constructs a new Scanner that produces values scanned from the specified file.

Scanner(String) - Constructor for class java.util.Scanner

Constructs a new Scanner that produces values scanned from the specified string.

Scanner(ReadableByteChannel) - Constructor for class java.util.Scanner

Constructs a new Scanner that produces values scanned from the specified channel.

Scanner(ReadableByteChannel, String) - Constructor for class java.util.Scanner

Constructs a new Scanner that produces values scanned from the specified channel.

ScatteringByteChannel - Interface in java.nio.channels

A channel that can read bytes into a sequence of buffers.

schedule(Runnable, long, TimeUnit) - Method in interface java.util.concurrent.ScheduledExecutorService

Creates and executes a one-shot action that becomes enabled after the given delay.

schedule(Callable<V>, long, TimeUnit) - Method in interface java.util.concurrent.ScheduledExecutorService

Creates and executes a ScheduledFuture that becomes enabled after the given delay.

schedule(Runnable, long, TimeUnit) - Method in class java.util.concurrent.ScheduledThreadPoolExecutor

schedule(Callable<V>, long, TimeUnit) - Method in class java.util.concurrent.ScheduledThreadPoolExecutor

schedule(TimerTask, long) - Method in class java.util.Timer

Schedules the specified task for execution after the specified delay.

schedule(TimerTask, Date) - Method in class java.util.Timer

Schedules the specified task for execution at the specified time.

schedule(TimerTask, long, long) - Method in class java.util.Timer

Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay.

schedule(TimerTask, Date, long) - Method in class java.util.Timer

Schedules the specified task for repeated fixed-delay execution, beginning at the specified time.

scheduleAtFixedRate(Runnable, long, long, TimeUnit) - Method in interface java.util.concurrent.ScheduledExecutorService

Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay then initialDelay+period, then initialDelay + 2 * period, and so on.

scheduleAtFixedRate(Runnable, long, long, TimeUnit) - Method in class java.util.concurrent.ScheduledThreadPoolExecutor

scheduleAtFixedRate(TimerTask, long, long) - Method in class java.util.Timer

Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay.

scheduleAtFixedRate(TimerTask, Date, long) - Method in class java.util.Timer

Schedules the specified task for repeated fixed-rate execution, beginning at the specified time.

scheduledExecutionTime() - Method in class java.util.TimerTask

Returns the scheduled execution time of the most recent actual execution of this task.

ScheduledExecutorService - Interface in java.util.concurrent

An ExecutorService that can schedule commands to run after a given delay, or to execute periodically.

ScheduledFuture<V> - Interface in java.util.concurrent

A delayed result-bearing action that can be cancelled.

ScheduledThreadPoolExecutor - Class in java.util.concurrent

A ThreadPoolExecutor that can additionally schedule commands to run after a given delay, or to execute periodically.

ScheduledThreadPoolExecutor(int) - Constructor for class java.util.concurrent.ScheduledThreadPoolExecutor

Creates a new ScheduledThreadPoolExecutor with the given core pool size.

ScheduledThreadPoolExecutor(int, ThreadFactory) - Constructor for class java.util.concurrent.ScheduledThreadPoolExecutor

Creates a new ScheduledThreadPoolExecutor with the given initial parameters.

ScheduledThreadPoolExecutor(int, RejectedExecutionHandler) - Constructor for class java.util.concurrent.ScheduledThreadPoolExecutor

Creates a new ScheduledThreadPoolExecutor with the given initial parameters.

ScheduledThreadPoolExecutor(int, ThreadFactory, RejectedExecutionHandler) - Constructor for class java.util.concurrent.ScheduledThreadPoolExecutor

Creates a new ScheduledThreadPoolExecutor with the given initial parameters.

scheduleWithFixedDelay(Runnable, long, long, TimeUnit) - Method in interface java.util.concurrent.ScheduledExecutorService

Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next.

scheduleWithFixedDelay(Runnable, long, long, TimeUnit) - Method in class java.util.concurrent.ScheduledThreadPoolExecutor

Schema - Class in javax.xml.validation

Immutable in-memory representation of grammar.

Schema() - Constructor for class javax.xml.validation.Schema

Constructor for the derived class.

SCHEMA_SYSTEM_ID - Static variable in interface javax.sql.rowset.WebRowSet

The URL for the XML Schema definition file that defines the XML tags and their valid values for a WebRowSet implementation.

SchemaFactory - Class in javax.xml.validation

Factory that creates Schema objects. Entry-point to the validation API.

SchemaFactory() - Constructor for class javax.xml.validation.SchemaFactory

Constructor for derived classes.

SchemaFactoryLoader - Class in javax.xml.validation

Factory that creates SchemaFactory.

SchemaFactoryLoader() - Constructor for class javax.xml.validation.SchemaFactoryLoader

A do-nothing constructor.

SchemaOutputResolver - Class in javax.xml.bind

Controls where a JAXB implementation puts the generates schema files.

SchemaOutputResolver() - Constructor for class javax.xml.bind.SchemaOutputResolver

SchemaViolationException - Exception in javax.naming.directory

This exception is thrown when a method in some ways violates the schema.

SchemaViolationException() - Constructor for exception javax.naming.directory.SchemaViolationException

Constructs a new instance of SchemaViolationException.

SchemaViolationException(String) - Constructor for exception javax.naming.directory.SchemaViolationException

Constructs a new instance of SchemaViolationException using the explanation supplied.

scope - Variable in class javax.xml.bind.JAXBElement

Scope of xml element declaration representing this xml element instance.

SCRIPT - Static variable in class javax.swing.text.html.HTML.Tag

ScriptContext - Interface in javax.script

The interface whose implementing classes are used to connect Script Engines with objects, such as scoped Bindings, in hosting applications.

ScriptEngine - Interface in javax.script

ScriptEngine is the fundamental interface whose methods must be fully functional in every implementation of this specification.

ScriptEngineFactory - Interface in javax.script

ScriptEngineFactory is used to describe and instantiate ScriptEngines.

ScriptEngineManager - Class in javax.script

The ScriptEngineManager implements a discovery and instantiation mechanism for ScriptEngine classes and also maintains a collection of key/value pairs storing state shared by all engines created by the Manager.

ScriptEngineManager() - Constructor for class javax.script.ScriptEngineManager

If the thread context ClassLoader can be accessed by the caller, then the effect of calling this constructor is the same as calling ScriptEngineManager(Thread.currentThread().getContextClassLoader()).

ScriptEngineManager(ClassLoader) - Constructor for class javax.script.ScriptEngineManager

This constructor loads the implementations of ScriptEngineFactory visible to the given ClassLoader using the service provider mechanism.

If loader is null, the script engine factories that are bundled with the platform and that are in the usual extension directories (installed extensions) are loaded.

ScriptException - Exception in javax.script

The generic Exception class for the Scripting APIs.

ScriptException(String) - Constructor for exception javax.script.ScriptException

Creates a ScriptException with a String to be used in its message.

ScriptException(Exception) - Constructor for exception javax.script.ScriptException

Creates a ScriptException wrapping an Exception thrown by an underlying interpreter.

ScriptException(String, String, int) - Constructor for exception javax.script.ScriptException

Creates a ScriptException with message, filename and linenumber to be used in error messages.

ScriptException(String, String, int, int) - Constructor for exception javax.script.ScriptException

ScriptException constructor specifying message, filename, line number and column number.

SCROLL_ABSOLUTE - Static variable in class java.awt.Event

The user has moved the bubble (thumb) in a scroll bar, moving to an "absolute" position, rather than to an offset from the last postion.

SCROLL_BAR - Static variable in class javax.accessibility.AccessibleRole

An object usually used to allow a user to incrementally view a large amount of data.

SCROLL_BAR - Static variable in class javax.swing.plaf.synth.Region

ScrollBar region.

SCROLL_BAR_THUMB - Static variable in class javax.swing.plaf.synth.Region

Thumb of the ScrollBar.

SCROLL_BAR_TRACK - Static variable in class javax.swing.plaf.synth.Region

Track of the ScrollBar.

SCROLL_BEGIN - Static variable in class java.awt.Event

The scroll begin event.

SCROLL_DOWN - Static variable in class javax.swing.plaf.basic.BasicComboPopup

SCROLL_END - Static variable in class java.awt.Event

The scroll end event.

SCROLL_LINE_DOWN - Static variable in class java.awt.Event

The user has activated the line down area of a scroll bar.

SCROLL_LINE_UP - Static variable in class java.awt.Event

The user has activated the line up area of a scroll bar.

SCROLL_LOCK - Static variable in class java.awt.Event

The Scroll Lock key, a non-ASCII action key.

SCROLL_PAGE_DOWN - Static variable in class java.awt.Event

The user has activated the page down area of a scroll bar.

SCROLL_PAGE_UP - Static variable in class java.awt.Event

The user has activated the page up area of a scroll bar.

SCROLL_PANE - Static variable in class javax.accessibility.AccessibleRole

An object that allows a user to incrementally view a large amount of information.

SCROLL_PANE - Static variable in class javax.swing.plaf.synth.Region

ScrollPane region.

SCROLL_TAB_LAYOUT - Static variable in class javax.swing.JTabbedPane

Tab layout policy for providing a subset of available tabs when all the tabs will not fit within a single run.

SCROLL_UP - Static variable in class javax.swing.plaf.basic.BasicComboPopup

Scrollable - Interface in javax.swing

An interface that provides information to a scrolling container like JScrollPane.

Scrollbar - Class in java.awt

The Scrollbar class embodies a scroll bar, a familiar user-interface object.

Scrollbar() - Constructor for class java.awt.Scrollbar

Constructs a new vertical scroll bar.

Scrollbar(int) - Constructor for class java.awt.Scrollbar

Constructs a new scroll bar with the specified orientation.

Scrollbar(int, int, int, int, int) - Constructor for class java.awt.Scrollbar

Constructs a new scroll bar with the specified orientation, initial value, visible amount, and minimum and maximum values.

SCROLLBAR - Static variable in class java.awt.SystemColor

The array index for the SystemColor.scrollbar system color.

scrollbar - Static variable in class java.awt.SystemColor

The color rendered for the background of scrollbars.

scrollbar - Variable in class javax.swing.plaf.basic.BasicScrollBarUI

scrollBar - Variable in class javax.swing.plaf.basic.BasicTreeUI.ComponentHandler

ScrollBar that is being adjusted.

Scrollbar.AccessibleAWTScrollBar - Class in java.awt

This class implements accessibility support for the Scrollbar class.

Scrollbar.AccessibleAWTScrollBar() - Constructor for class java.awt.Scrollbar.AccessibleAWTScrollBar

SCROLLBARS_ALWAYS - Static variable in class java.awt.ScrollPane

Specifies that horizontal/vertical scrollbars should always be shown regardless of the respective sizes of the scrollpane and child.

SCROLLBARS_AS_NEEDED - Static variable in class java.awt.ScrollPane

Specifies that horizontal/vertical scrollbar should be shown only when the size of the child exceeds the size of the scrollpane in the horizontal/vertical dimension.

SCROLLBARS_BOTH - Static variable in class java.awt.TextArea

Create and display both vertical and horizontal scrollbars.

SCROLLBARS_HORIZONTAL_ONLY - Static variable in class java.awt.TextArea

Create and display horizontal scrollbar only.

SCROLLBARS_NEVER - Static variable in class java.awt.ScrollPane

Specifies that horizontal/vertical scrollbars should never be shown regardless of the respective sizes of the scrollpane and child.

SCROLLBARS_NONE - Static variable in class java.awt.TextArea

Do not create or display any scrollbars for the text area.

SCROLLBARS_VERTICAL_ONLY - Static variable in class java.awt.TextArea

Create and display vertical scrollbar only.

ScrollBarUI - Class in javax.swing.plaf

Pluggable look and feel interface for JScrollBar.

ScrollBarUI() - Constructor for class javax.swing.plaf.ScrollBarUI

scrollBarWidth - Variable in class javax.swing.plaf.basic.BasicScrollBarUI

Hint as to what width (when vertical) or height (when horizontal) should be.

scrollBarWidth - Variable in class javax.swing.plaf.metal.MetalScrollBarUI

scrollByBlock(int) - Method in class javax.swing.plaf.basic.BasicScrollBarUI

scrollByBlock(int) - Method in class javax.swing.plaf.basic.BasicSliderUI

scrollByUnit(int) - Method in class javax.swing.plaf.basic.BasicScrollBarUI

scrollByUnit(int) - Method in class javax.swing.plaf.basic.BasicSliderUI

scrollDirection - Variable in class javax.swing.plaf.basic.BasicComboPopup

scrollDueToClickInTrack(int) - Method in class javax.swing.plaf.basic.BasicSliderUI

This function is called when a mousePressed was detected in the track, not in the thumb.

scrollDueToClickInTrack(int) - Method in class javax.swing.plaf.metal.MetalSliderUI

scroller - Variable in class javax.swing.plaf.basic.BasicComboPopup

This protected field is implementation specific.

SCROLLING - Static variable in class javax.swing.text.html.HTML.Attribute

scrollListener - Variable in class javax.swing.plaf.basic.BasicScrollBarUI

scrollListener - Variable in class javax.swing.plaf.basic.BasicSliderUI

ScrollPane - Class in java.awt

A container class which implements automatic horizontal and/or vertical scrolling for a single child component.

ScrollPane() - Constructor for class java.awt.ScrollPane

Create a new scrollpane container with a scrollbar display policy of "as needed".

ScrollPane(int) - Constructor for class java.awt.ScrollPane

Create a new scrollpane container.

scrollpane - Variable in class javax.swing.plaf.basic.BasicScrollPaneUI

ScrollPane.AccessibleAWTScrollPane - Class in java.awt

This class implements accessibility support for the ScrollPane class.

ScrollPane.AccessibleAWTScrollPane() - Constructor for class java.awt.ScrollPane.AccessibleAWTScrollPane

ScrollPaneAdjustable - Class in java.awt

This class represents the state of a horizontal or vertical scrollbar of a ScrollPane.

ScrollPaneConstants - Interface in javax.swing

Constants used with the JScrollPane component.

ScrollPaneLayout - Class in javax.swing

The layout manager used by JScrollPane.

ScrollPaneLayout() - Constructor for class javax.swing.ScrollPaneLayout

ScrollPaneLayout.UIResource - Class in javax.swing

The UI resource version of ScrollPaneLayout.

ScrollPaneLayout.UIResource() - Constructor for class javax.swing.ScrollPaneLayout.UIResource

ScrollPaneUI - Class in javax.swing.plaf

Pluggable look and feel interface for JScrollPane.

ScrollPaneUI() - Constructor for class javax.swing.plaf.ScrollPaneUI

scrollPathToVisible(TreePath) - Method in class javax.swing.JTree

Makes sure all the path components in path are expanded (except for the last path component) and scrolls so that the node identified by the path is displayed.

scrollRectToVisible(Rectangle) - Method in class javax.swing.JComponent

Forwards the scrollRectToVisible() message to the JComponent's parent.

scrollRectToVisible(Rectangle) - Method in class javax.swing.JTextField

Scrolls the field left or right.

scrollRectToVisible(Rectangle) - Method in class javax.swing.JViewport

Scrolls the view so that Rectangle within the view becomes visible.

scrollRowToVisible(int) - Method in class javax.swing.JTree

Scrolls the item identified by row until it is displayed.

SCROLLS_ON_EXPAND_PROPERTY - Static variable in class javax.swing.JTree

Bound property name for scrollsOnExpand.

scrollsOnExpand - Variable in class javax.swing.JTree

If true, when a node is expanded, as many of the descendants are scrolled to be visible.

scrollTimer - Variable in class javax.swing.plaf.basic.BasicScrollBarUI

scrollTimer - Variable in class javax.swing.plaf.basic.BasicSliderUI

scrollToReference(String) - Method in class javax.swing.JEditorPane

Scrolls the view to the given reference location (that is, the value returned by the UL.getRef method for the URL being displayed).

scrollUnderway - Variable in class javax.swing.JViewport

The scrollUnderway flag is used for components like JList.

SDATA - Static variable in interface javax.swing.text.html.parser.DTDConstants

SE_RESIZE_CURSOR - Static variable in class java.awt.Cursor

The south-east-resize cursor type.

SE_RESIZE_CURSOR - Static variable in class java.awt.Frame

Deprecated.
replaced by Cursor.SE_RESIZE_CURSOR.

SEALED - Static variable in class java.util.jar.Attributes.Name

Name object for Sealed manifest attribute used for sealing.

SealedObject - Class in javax.crypto

This class enables a programmer to create an object and protect its confidentiality with a cryptographic algorithm.

SealedObject(Serializable, Cipher) - Constructor for class javax.crypto.SealedObject

Constructs a SealedObject from any Serializable object.

SealedObject(SealedObject) - Constructor for class javax.crypto.SealedObject

Constructs a SealedObject object from the passed-in SealedObject.

search(Object) - Method in class java.util.Stack

Returns the 1-based position where an object is on this stack.

search(Name, Attributes, String[]) - Method in interface javax.naming.directory.DirContext

Searches in a single context for objects that contain a specified set of attributes, and retrieves selected attributes.

search(String, Attributes, String[]) - Method in interface javax.naming.directory.DirContext

Searches in a single context for objects that contain a specified set of attributes, and retrieves selected attributes.

search(Name, Attributes) - Method in interface javax.naming.directory.DirContext

Searches in a single context for objects that contain a specified set of attributes.

search(String, Attributes) - Method in interface javax.naming.directory.DirContext

Searches in a single context for objects that contain a specified set of attributes.

search(Name, String, SearchControls) - Method in interface javax.naming.directory.DirContext

Searches in the named context or object for entries that satisfy the given search filter.

search(String, String, SearchControls) - Method in interface javax.naming.directory.DirContext

Searches in the named context or object for entries that satisfy the given search filter.

search(Name, String, Object[], SearchControls) - Method in interface javax.naming.directory.DirContext

Searches in the named context or object for entries that satisfy the given search filter.

search(String, String, Object[], SearchControls) - Method in interface javax.naming.directory.DirContext

Searches in the named context or object for entries that satisfy the given search filter.

search(String, Attributes) - Method in class javax.naming.directory.InitialDirContext

search(Name, Attributes) - Method in class javax.naming.directory.InitialDirContext

search(String, Attributes, String[]) - Method in class javax.naming.directory.InitialDirContext

search(Name, Attributes, String[]) - Method in class javax.naming.directory.InitialDirContext

search(String, String, SearchControls) - Method in class javax.naming.directory.InitialDirContext

search(Name, String, SearchControls) - Method in class javax.naming.directory.InitialDirContext

search(String, String, Object[], SearchControls) - Method in class javax.naming.directory.InitialDirContext

search(Name, String, Object[], SearchControls) - Method in class javax.naming.directory.InitialDirContext

SearchControls - Class in javax.naming.directory

This class encapsulates factors that determine scope of search and what gets returned as a result of the search.

SearchControls() - Constructor for class javax.naming.directory.SearchControls

Constructs a search constraints using defaults.

SearchControls(int, long, int, String[], boolean, boolean) - Constructor for class javax.naming.directory.SearchControls

Constructs a search constraints using arguments.

SearchResult - Class in javax.naming.directory

This class represents an item in the NamingEnumeration returned as a result of the DirContext.search() methods.

SearchResult(String, Object, Attributes) - Constructor for class javax.naming.directory.SearchResult

Constructs a search result using the result's name, its bound object, and its attributes.

SearchResult(String, Object, Attributes, boolean) - Constructor for class javax.naming.directory.SearchResult

Constructs a search result using the result's name, its bound object, and its attributes, and whether the name is relative.

SearchResult(String, String, Object, Attributes) - Constructor for class javax.naming.directory.SearchResult

Constructs a search result using the result's name, its class name, its bound object, and its attributes.

SearchResult(String, String, Object, Attributes, boolean) - Constructor for class javax.naming.directory.SearchResult

Constructs a search result using the result's name, its class name, its bound object, its attributes, and whether the name is relative.

SECOND - Static variable in class java.text.DateFormat.Field

Constant identifying the second field.

SECOND - Static variable in class java.util.Calendar

Field number for get and set indicating the second within the minute.

SECOND_FIELD - Static variable in class java.text.DateFormat

Useful constant for SECOND field alignment.

SECONDARY - Static variable in class java.text.Collator

Collator strength value.

SecondaryLoop - Interface in java.awt

A helper interface to run the nested event loop.

secondaryOrder(int) - Static method in class java.text.CollationElementIterator

Return the secondary component of a collation element.

SECONDS - Static variable in class javax.xml.datatype.DatatypeConstants

A constant that represents the seconds field.

SECRET_KEY - Static variable in class javax.crypto.Cipher

Constant used to indicate the to-be-unwrapped key is a "secret key".

SecretKey - Interface in javax.crypto

A secret (symmetric) key.

SecretKeyFactory - Class in javax.crypto

This class represents a factory for secret keys.

SecretKeyFactory(SecretKeyFactorySpi, Provider, String) - Constructor for class javax.crypto.SecretKeyFactory

Creates a SecretKeyFactory object.

SecretKeyFactorySpi - Class in javax.crypto

This class defines the Service Provider Interface (SPI) for the SecretKeyFactory class.

SecretKeyFactorySpi() - Constructor for class javax.crypto.SecretKeyFactorySpi

SecretKeySpec - Class in javax.crypto.spec

This class specifies a secret key in a provider-independent fashion.

SecretKeySpec(byte[], String) - Constructor for class javax.crypto.spec.SecretKeySpec

Constructs a secret key from the given byte array.

SecretKeySpec(byte[], int, int, String) - Constructor for class javax.crypto.spec.SecretKeySpec

Constructs a secret key from the given byte array, using the first len bytes of key, starting at offset inclusive.

SectionElementName - Static variable in class javax.swing.text.AbstractDocument

Name of elements used to hold sections (lines/paragraphs).

SecureCacheResponse - Class in java.net

Represents a cache response originally retrieved through secure means, such as TLS.

SecureCacheResponse() - Constructor for class java.net.SecureCacheResponse

SecureClassLoader - Class in java.security

This class extends ClassLoader with additional support for defining classes with an associated code source and permissions which are retrieved by the system policy by default.

SecureClassLoader(ClassLoader) - Constructor for class java.security.SecureClassLoader

Creates a new SecureClassLoader using the specified parent class loader for delegation.

SecureClassLoader() - Constructor for class java.security.SecureClassLoader

Creates a new SecureClassLoader using the default parent class loader for delegation.

SecureDirectoryStream<T> - Interface in java.nio.file

A DirectoryStream that defines operations on files that are located relative to an open directory.

SecureRandom - Class in java.security

This class provides a cryptographically strong random number generator (RNG).

SecureRandom() - Constructor for class java.security.SecureRandom

Constructs a secure random number generator (RNG) implementing the default random number algorithm.

SecureRandom(byte[]) - Constructor for class java.security.SecureRandom

Constructs a secure random number generator (RNG) implementing the default random number algorithm.

SecureRandom(SecureRandomSpi, Provider) - Constructor for class java.security.SecureRandom

Creates a SecureRandom object.

SecureRandomSpi - Class in java.security

This class defines the Service Provider Interface (SPI) for the SecureRandom class.

SecureRandomSpi() - Constructor for class java.security.SecureRandomSpi

Security - Class in java.security

This class centralizes all security properties and common security methods.

SECURITY_AUTHENTICATION - Static variable in interface javax.naming.Context

Constant that holds the name of the environment property for specifying the security level to use.

SECURITY_CREDENTIALS - Static variable in interface javax.naming.Context

Constant that holds the name of the environment property for specifying the credentials of the principal for authenticating the caller to the service.

SECURITY_PRINCIPAL - Static variable in interface javax.naming.Context

Constant that holds the name of the environment property for specifying the identity of the principal for authenticating the caller to the service.

SECURITY_PROTOCOL - Static variable in interface javax.naming.Context

Constant that holds the name of the environment property for specifying the security protocol to use.

SecurityException - Exception in java.lang

Thrown by the security manager to indicate a security violation.

SecurityException() - Constructor for exception java.lang.SecurityException

Constructs a SecurityException with no detail message.

SecurityException(String) - Constructor for exception java.lang.SecurityException

Constructs a SecurityException with the specified detail message.

SecurityException(String, Throwable) - Constructor for exception java.lang.SecurityException

Creates a SecurityException with the specified detail message and cause.

SecurityException(Throwable) - Constructor for exception java.lang.SecurityException

Creates a SecurityException with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).

SecurityManager - Class in java.lang

The security manager is a class that allows applications to implement a security policy.

SecurityManager() - Constructor for class java.lang.SecurityManager

Constructs a new SecurityManager.

SecurityPermission - Class in java.security

This class is for security permissions.

SecurityPermission(String) - Constructor for class java.security.SecurityPermission

Creates a new SecurityPermission with the specified name.

SecurityPermission(String, String) - Constructor for class java.security.SecurityPermission

Creates a new SecurityPermission object with the specified name.

seek(long) - Method in class java.io.RandomAccessFile

Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.

seek(long) - Method in class javax.imageio.stream.FileCacheImageOutputStream

Sets the current stream position and resets the bit offset to 0.

seek(long) - Method in class javax.imageio.stream.FileImageInputStream

seek(long) - Method in class javax.imageio.stream.FileImageOutputStream

Sets the current stream position and resets the bit offset to 0.

seek(long) - Method in interface javax.imageio.stream.ImageInputStream

Sets the current stream position to the desired location.

seek(long) - Method in class javax.imageio.stream.ImageInputStreamImpl

seek(int) - Method in interface org.omg.CORBA.DynAny

Deprecated.

Moves the internal pointer to the given index.

seek(int) - Method in class org.omg.DynamicAny._DynAnyStub

Sets the current position to index.

seek(int) - Method in class org.omg.DynamicAny._DynArrayStub

Sets the current position to index.

seek(int) - Method in class org.omg.DynamicAny._DynEnumStub

Sets the current position to index.

seek(int) - Method in class org.omg.DynamicAny._DynFixedStub

Sets the current position to index.

seek(int) - Method in class org.omg.DynamicAny._DynSequenceStub

Sets the current position to index.

seek(int) - Method in class org.omg.DynamicAny._DynStructStub

Sets the current position to index.

seek(int) - Method in class org.omg.DynamicAny._DynUnionStub

Sets the current position to index.

seek(int) - Method in class org.omg.DynamicAny._DynValueStub

Sets the current position to index.

seek(int) - Method in interface org.omg.DynamicAny.DynAnyOperations

Sets the current position to index.

SeekableByteChannel - Interface in java.nio.channels

A byte channel that maintains a current position and allows the position to be changed.

seekForwardOnly - Variable in class javax.imageio.ImageReader

true if the current input source has been marked as allowing only forward seeking by setInput.

SEG_CLOSE - Static variable in interface java.awt.geom.PathIterator

The segment type constant that specifies that the preceding subpath should be closed by appending a line segment back to the point corresponding to the most recent SEG_MOVETO.

SEG_CUBICTO - Static variable in interface java.awt.geom.PathIterator

The segment type constant for the set of 3 points that specify a cubic parametric curve to be drawn from the most recently specified point.

SEG_LINETO - Static variable in interface java.awt.geom.PathIterator

The segment type constant for a point that specifies the end point of a line to be drawn from the most recently specified point.

SEG_MOVETO - Static variable in interface java.awt.geom.PathIterator

The segment type constant for a point that specifies the starting location for a new subpath.

SEG_QUADTO - Static variable in interface java.awt.geom.PathIterator

The segment type constant for the pair of points that specify a quadratic parametric curve to be drawn from the most recently specified point.

Segment - Class in javax.swing.text

A segment of a character array representing a fragment of text.

Segment() - Constructor for class javax.swing.text.Segment

Creates a new segment.

Segment(char[], int, int) - Constructor for class javax.swing.text.Segment

Creates a new segment referring to an existing array.

SEGMENT_LIMIT - Static variable in interface java.util.jar.Pack200.Packer

This property is a numeral giving the estimated target size N (in bytes) of each archive segment.

select(int) - Method in class java.awt.Choice

Sets the selected item in this Choice menu to be the item at the specified position.

select(String) - Method in class java.awt.Choice

Sets the selected item in this Choice menu to be the item whose name is equal to the specified string.

select(int) - Method in class java.awt.List

Selects the item at the specified index in the scrolling list.

select(int, int) - Method in class java.awt.TextComponent

Selects the text between the specified start and end positions.

select(URI) - Method in class java.net.ProxySelector

Selects all the applicable proxies based on the protocol to access the resource with and a destination address to access the resource at.

select(long) - Method in class java.nio.channels.Selector

Selects a set of keys whose corresponding channels are ready for I/O operations.

select() - Method in class java.nio.channels.Selector

Selects a set of keys whose corresponding channels are ready for I/O operations.

SELECT - Static variable in class javax.swing.text.html.HTML.Tag

select(int, int) - Method in class javax.swing.text.JTextComponent

Selects the text between the specified start and end positions.

select(KeyInfo, KeySelector.Purpose, AlgorithmMethod, XMLCryptoContext) - Method in class javax.xml.crypto.KeySelector

Attempts to find a key that satisfies the specified constraints.

SELECTABLE - Static variable in class javax.accessibility.AccessibleState

Indicates this object is the child of an object that allows its children to be selected, and that this child is one of those children that can be selected.

SelectableChannel - Class in java.nio.channels

A channel that can be multiplexed via a Selector.

SelectableChannel() - Constructor for class java.nio.channels.SelectableChannel

Initializes a new instance of this class.

selectAdjacentRunTab(int, int, int) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI

selectAll() - Method in class java.awt.TextComponent

Selects all the text in this text component.

selectAll() - Method in interface javax.swing.ComboBoxEditor

Ask the editor to start editing and to select everything

selectAll() - Method in class javax.swing.JTable

Selects all rows, columns, and cells in the table.

selectAll() - Method in class javax.swing.plaf.basic.BasicComboBoxEditor

selectAll() - Method in class javax.swing.text.JTextComponent

Selects all the text in the TextComponent.

selectAllAccessibleSelection() - Method in class java.awt.List.AccessibleAWTList

Causes every selected item in the object to be selected if the object supports multiple selections.

selectAllAccessibleSelection() - Method in class java.awt.MenuComponent.AccessibleAWTMenuComponent

Causes every child of the object to be selected if the object supports multiple selections.

selectAllAccessibleSelection() - Method in interface javax.accessibility.AccessibleSelection

Causes every child of the object to be selected if the object supports multiple selections.

selectAllAccessibleSelection() - Method in class javax.swing.JComboBox.AccessibleJComboBox

Causes every child of the object to be selected if the object supports multiple selections.

selectAllAccessibleSelection() - Method in class javax.swing.JList.AccessibleJList

Causes every selected item in the object to be selected if the object supports multiple selections.

selectAllAccessibleSelection() - Method in class javax.swing.JMenu.AccessibleJMenu

Normally causes every selected item in the object to be selected if the object supports multiple selections.

selectAllAccessibleSelection() - Method in class javax.swing.JMenuBar.AccessibleJMenuBar

Normally causes every selected item in the object to be selected if the object supports multiple selections.

selectAllAccessibleSelection() - Method in class javax.swing.JTabbedPane.AccessibleJTabbedPane

selectAllAccessibleSelection() - Method in class javax.swing.JTable.AccessibleJTable

Causes every child of the object to be selected, but only if the JTable supports multiple selections, and if individual cell selection is enabled.

selectAllAccessibleSelection() - Method in class javax.swing.JTree.AccessibleJTree.AccessibleJTreeNode

Causes every selected item in the object to be selected if the object supports multiple selections.

selectAllAccessibleSelection() - Method in class javax.swing.JTree.AccessibleJTree

Causes every selected item in the object to be selected if the object supports multiple selections.

selectAllAction - Static variable in class javax.swing.text.DefaultEditorKit

Name of the Action for selecting the entire document

selectBestTextFlavor(DataFlavor[]) - Static method in class java.awt.datatransfer.DataFlavor

Selects the best text DataFlavor from an array of DataFlavors.

selectColor - Variable in class javax.swing.plaf.metal.MetalButtonUI

selectColor - Variable in class javax.swing.plaf.metal.MetalRadioButtonUI

selectColor - Variable in class javax.swing.plaf.metal.MetalTabbedPaneUI

selectColor - Variable in class javax.swing.plaf.metal.MetalToggleButtonUI

selectContent(AttributeSet) - Method in class javax.swing.text.html.HTMLWriter

Writes out the content of the SELECT form element.

SELECTED - Static variable in class java.awt.event.ItemEvent

This state-change value indicates that an item was selected.

SELECTED - Static variable in class javax.accessibility.AccessibleState

Indicates this object is the child of an object that allows its children to be selected, and that this child is one of those children that has been selected.

SELECTED - Static variable in class javax.swing.DefaultButtonModel

Identifies the "selected" bit in the bitmask, which indicates that the button has been selected.

SELECTED - Static variable in interface javax.swing.plaf.synth.SynthConstants

Indicates the region is selected.

SELECTED - Static variable in class javax.swing.text.html.HTML.Attribute

selected - Variable in class javax.swing.tree.DefaultTreeCellRenderer

Is the value currently selected.

SELECTED_CONVERTED_TEXT_HIGHLIGHT - Static variable in class java.awt.im.InputMethodHighlight

Constant for the default highlight for selected converted text.

SELECTED_FILE_CHANGED_PROPERTY - Static variable in class javax.swing.JFileChooser

Identifies change in user's single-file selection.

SELECTED_FILES_CHANGED_PROPERTY - Static variable in class javax.swing.JFileChooser

Identifies change in user's multiple-file selection.

SELECTED_ICON_CHANGED_PROPERTY - Static variable in class javax.swing.AbstractButton

Identifies a change to the icon used when the button has been selected.

SELECTED_KEY - Static variable in interface javax.swing.Action

The key used for storing a Boolean that corresponds to the selected state.

SELECTED_RAW_TEXT_HIGHLIGHT - Static variable in class java.awt.im.InputMethodHighlight

Constant for the default highlight for selected raw text.

selectedItemChanged() - Method in class javax.swing.JComboBox

This protected method is implementation specific.

selectedItemReminder - Variable in class javax.swing.JComboBox

This protected field is implementation specific.

selectedKeys() - Method in class java.nio.channels.Selector

Returns this selector's selected-key set.

selectedRun - Variable in class javax.swing.plaf.basic.BasicTabbedPaneUI

selectedTabPadInsets - Variable in class javax.swing.plaf.basic.BasicTabbedPaneUI

selectedTextColor - Variable in class javax.swing.plaf.basic.BasicInternalFrameTitlePane

selectedTitleColor - Variable in class javax.swing.plaf.basic.BasicInternalFrameTitlePane

selectFrame(boolean) - Method in class javax.swing.JDesktopPane

Selects the next JInternalFrame in this desktop pane.

selectHighlight - Variable in class javax.swing.plaf.metal.MetalTabbedPaneUI

selectInitialValue() - Method in class javax.swing.JOptionPane

Requests that the initial value be selected, which will set focus to the initial value.

selectInitialValue(JOptionPane) - Method in class javax.swing.plaf.basic.BasicOptionPaneUI

If inputComponent is non-null, the focus is requested on that, otherwise request focus on the default value

selectInitialValue(JOptionPane) - Method in class javax.swing.plaf.multi.MultiOptionPaneUI

Invokes the selectInitialValue method on each UI handled by this object.

selectInitialValue(JOptionPane) - Method in class javax.swing.plaf.OptionPaneUI

Requests the component representing the default value to have focus.

selectInputMethod(Locale) - Method in class java.awt.im.InputContext

Attempts to select an input method or keyboard layout that supports the given locale, and returns a value indicating whether such an input method or keyboard layout has been successfully selected.

SELECTION - Static variable in class java.awt.JobAttributes.DefaultSelectionType

The DefaultSelectionType instance to use for specifying that the current selection should be printed.

selection - Variable in class javax.swing.tree.DefaultTreeSelectionModel

Paths that are currently selected.

SELECTION_MODE_PROPERTY - Static variable in class javax.swing.tree.DefaultTreeSelectionModel

Property name for selectionMode.

SELECTION_MODEL_PROPERTY - Static variable in class javax.swing.JColorChooser

The selection model property name.

SELECTION_MODEL_PROPERTY - Static variable in class javax.swing.JTree

Bound property name for selectionModel.

SELECTION_VALUES_PROPERTY - Static variable in class javax.swing.JOptionPane

Bound property name for selectionValues.

selectionBackground - Variable in class javax.swing.JTable

The background color of selected cells.

selectionBackground - Variable in class javax.swing.plaf.basic.BasicMenuItemUI

selectionBackwardAction - Static variable in class javax.swing.text.DefaultEditorKit

Name of the Action for extending the selection by moving the caret logically backward one position.

selectionBeginAction - Static variable in class javax.swing.text.DefaultEditorKit

Name of the Action for moving the caret to the beginning of the document.

selectionBeginLineAction - Static variable in class javax.swing.text.DefaultEditorKit

Name of the Action for moving the caret to the beginning of a line, extending the selection.

selectionBeginParagraphAction - Static variable in class javax.swing.text.DefaultEditorKit

Name of the Action for moving the caret to the beginning of a paragraph, extending the selection.

selectionBeginWordAction - Static variable in class javax.swing.text.DefaultEditorKit

Name of the Action for moving the caret to the beginning of a word, extending the selection.

selectionDownAction - Static variable in class javax.swing.text.DefaultEditorKit

Name of the Action for moving the caret logically downward one position, extending the selection.

selectionEndAction - Static variable in class javax.swing.text.DefaultEditorKit

Name of the Action for moving the caret to the end of the document.

selectionEndLineAction - Static variable in class javax.swing.text.DefaultEditorKit

Name of the Action for moving the caret to the end of a line, extending the selection.

selectionEndParagraphAction - Static variable in class javax.swing.text.DefaultEditorKit

Name of the Action for moving the caret to the end of a paragraph, extending the selection.

selectionEndWordAction - Static variable in class javax.swing.text.DefaultEditorKit

Name of the Action for moving the caret to the end of a word, extending the selection.

selectionForeground - Variable in class javax.swing.JTable

The foreground color of selected cells.

selectionForeground - Variable in class javax.swing.plaf.basic.BasicMenuItemUI

selectionForKey(char, ComboBoxModel) - Method in interface javax.swing.JComboBox.KeySelectionManager

Given aKey and the model, returns the row that should become selected.

selectionForwardAction - Static variable in class javax.swing.text.DefaultEditorKit

Name of the Action for extending the selection by moving the caret logically forward one position.

SelectionKey - Class in java.nio.channels

A token representing the registration of a SelectableChannel with a Selector.

SelectionKey() - Constructor for class java.nio.channels.SelectionKey

Constructs an instance of this class.

selectionMode - Variable in class javax.swing.tree.DefaultTreeSelectionModel

Mode for the selection, will be either SINGLE_TREE_SELECTION, CONTIGUOUS_TREE_SELECTION or DISCONTIGUOUS_TREE_SELECTION.

selectionModel - Variable in class javax.swing.JTable

The ListSelectionModel of the table, used to keep track of row selections.

selectionModel - Variable in class javax.swing.JTree

Models the set of selected nodes in this tree.

selectionModel - Variable in class javax.swing.table.DefaultTableColumnModel

Model for keeping track of column selections

selectionModelChanged - Static variable in class javax.swing.plaf.basic.BasicListUI

selectionNextWordAction - Static variable in class javax.swing.text.DefaultEditorKit

Name of the Action for moving the selection to the beginning of the next word, extending the selection.

selectionPreviousWordAction - Static variable in class javax.swing.text.DefaultEditorKit

Name of the Action for moving the selection to the beginning of the previous word, extending the selection.

selectionRedirector - Variable in class javax.swing.JTree

Creates a new event and passed it off the selectionListeners.

selectionUpAction - Static variable in class javax.swing.text.DefaultEditorKit

Name of the Action for moving the caret logically upward one position, extending the selection.

selectionValues - Variable in class javax.swing.JOptionPane

Array of values the user can choose from.

selectLineAction - Static variable in class javax.swing.text.DefaultEditorKit

Name of the Action for selecting a line around the caret.

selectNextIndex() - Method in class javax.swing.plaf.basic.BasicListUI

Selected the previous row and force it to be visible.

selectNextPossibleValue() - Method in class javax.swing.plaf.basic.BasicComboBoxUI

Selects the next item in the list.

selectNextTab(int) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI

selectNextTabInRun(int) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI

selectNow() - Method in class java.nio.channels.Selector

Selects a set of keys whose corresponding channels are ready for I/O operations.

selector() - Method in class java.nio.channels.SelectionKey

Returns the selector for which this key was created.

Selector - Class in java.nio.channels

A multiplexor of SelectableChannel objects.

Selector() - Constructor for class java.nio.channels.Selector

Initializes a new instance of this class.

SelectorProvider - Class in java.nio.channels.spi

Service-provider class for selectors and selectable channels.

SelectorProvider() - Constructor for class java.nio.channels.spi.SelectorProvider

Initializes a new instance of this class.

selectParagraphAction - Static variable in class javax.swing.text.DefaultEditorKit

Name of the Action for selecting a paragraph around the caret.

selectPathForEvent(TreePath, MouseEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI

Messaged to update the selection based on a MouseEvent over a particular row.

selectPreviousIndex() - Method in class javax.swing.plaf.basic.BasicListUI

Selected the previous row and force it to be visible.

selectPreviousPossibleValue() - Method in class javax.swing.plaf.basic.BasicComboBoxUI

Selects the previous item in the list.

selectPreviousTab(int) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI

selectPreviousTabInRun(int) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI

selectText(int, int) - Method in interface javax.accessibility.AccessibleEditableText

Selects the text between two indices.

selectText(int, int) - Method in class javax.swing.JSpinner.AccessibleJSpinner

Selects the text between two indices.

selectText(int, int) - Method in class javax.swing.text.JTextComponent.AccessibleJTextComponent

Selects the text between two indices.

selectWithKeyChar(char) - Method in class javax.swing.JComboBox

Selects the list item that corresponds to the specified keyboard character and returns true, if there is an item corresponding to that character.

selectWordAction - Static variable in class javax.swing.text.DefaultEditorKit

Name of the Action for selecting a word around the caret.

Semaphore - Class in java.util.concurrent

A counting semaphore.

Semaphore(int) - Constructor for class java.util.concurrent.Semaphore

Creates a Semaphore with the given number of permits and nonfair fairness setting.

Semaphore(int, boolean) - Constructor for class java.util.concurrent.Semaphore

Creates a Semaphore with the given number of permits and the given fairness setting.

send(DatagramPacket) - Method in class java.net.DatagramSocket

Sends a datagram packet from this socket.

send(DatagramPacket) - Method in class java.net.DatagramSocketImpl

Sends a datagram packet.

send(DatagramPacket, byte) - Method in class java.net.MulticastSocket

Deprecated.
Use the following code or its equivalent instead: ...... int ttl = mcastSocket.getTimeToLive(); mcastSocket.setTimeToLive(newttl); mcastSocket.send(p); mcastSocket.setTimeToLive(ttl); ......

send(ByteBuffer, SocketAddress) - Method in class java.nio.channels.DatagramChannel

Sends a datagram via this channel.

send(MidiMessage, long) - Method in interface javax.sound.midi.Receiver

Sends a MIDI message and time-stamp to this receiver.

send_deferred() - Method in class org.omg.CORBA.Request

Makes an asynchronous invocation on the request.

send_exception(ServerRequestInfo) - Method in interface org.omg.PortableInterceptor.ServerRequestInterceptorOperations

Allows an Interceptor to query the exception information and modify the reply service context before the exception is thrown to the client.

send_multiple_requests_deferred(Request[]) - Method in class org.omg.CORBA.ORB

Sends multiple dynamic (DII) requests asynchronously.

send_multiple_requests_oneway(Request[]) - Method in class org.omg.CORBA.ORB

Sends multiple dynamic (DII) requests asynchronously without expecting any responses.

send_oneway() - Method in class org.omg.CORBA.Request

Makes a oneway invocation on the request.

send_other(ServerRequestInfo) - Method in interface org.omg.PortableInterceptor.ServerRequestInterceptorOperations

Allows an Interceptor to query the information available when a request results in something other than a normal reply or an exception.

send_poll(ClientRequestInfo) - Method in interface org.omg.PortableInterceptor.ClientRequestInterceptorOperations

Allows an Interceptor to query information during a Time-Independent Invocation (TII) polling get reply sequence.

send_reply(ServerRequestInfo) - Method in interface org.omg.PortableInterceptor.ServerRequestInterceptorOperations

Allows an Interceptor to query reply information and modify the reply service context after the target operation has been invoked and before the reply is returned to the client.

send_request(ClientRequestInfo) - Method in interface org.omg.PortableInterceptor.ClientRequestInterceptorOperations

Allows an Interceptor to query request information and modify the service context before the request is sent to the server.

sendAttributeChangeNotification(AttributeChangeNotification) - Method in interface javax.management.modelmbean.ModelMBeanNotificationBroadcaster

Sends an attributeChangeNotification which is passed in to the registered attributeChangeNotification listeners on the ModelMBean.

sendAttributeChangeNotification(Attribute, Attribute) - Method in interface javax.management.modelmbean.ModelMBeanNotificationBroadcaster

Sends an attributeChangeNotification which contains the old value and new value for the attribute to the registered AttributeChangeNotification listeners on the ModelMBean.

sendAttributeChangeNotification(AttributeChangeNotification) - Method in class javax.management.modelmbean.RequiredModelMBean

sendAttributeChangeNotification(Attribute, Attribute) - Method in class javax.management.modelmbean.RequiredModelMBean

sending_exception() - Method in interface org.omg.PortableInterceptor.ServerRequestInfoOperations

Returns an any which contains the exception to be returned to the client.

sendNotification(Notification) - Method in class javax.management.MBeanServerDelegate

Enables the MBean server to send a notification.

sendNotification(Notification) - Method in interface javax.management.modelmbean.ModelMBeanNotificationBroadcaster

Sends a Notification which is passed in to the registered Notification listeners on the ModelMBean as a jmx.modelmbean.generic notification.

sendNotification(String) - Method in interface javax.management.modelmbean.ModelMBeanNotificationBroadcaster

Sends a Notification which contains the text string that is passed in to the registered Notification listeners on the ModelMBean.

sendNotification(Notification) - Method in class javax.management.modelmbean.RequiredModelMBean

sendNotification(String) - Method in class javax.management.modelmbean.RequiredModelMBean

sendNotification(Notification) - Method in class javax.management.NotificationBroadcasterSupport

Sends a notification.

sendNotification(Notification) - Method in class javax.management.StandardEmitterMBean

Sends a notification.

sendRelationCreationNotification(String) - Method in class javax.management.relation.RelationService

Sends a notification (RelationNotification) for a relation creation.

sendRelationCreationNotification(String) - Method in interface javax.management.relation.RelationServiceMBean

Sends a notification (RelationNotification) for a relation creation.

sendRelationRemovalNotification(String, List<ObjectName>) - Method in class javax.management.relation.RelationService

Sends a notification (RelationNotification) for a relation removal.

sendRelationRemovalNotification(String, List<ObjectName>) - Method in interface javax.management.relation.RelationServiceMBean

Sends a notification (RelationNotification) for a relation removal.

sendRoleUpdateNotification(String, Role, List<ObjectName>) - Method in class javax.management.relation.RelationService

Sends a notification (RelationNotification) for a role update in the given relation.

sendRoleUpdateNotification(String, Role, List<ObjectName>) - Method in interface javax.management.relation.RelationServiceMBean

Sends a notification (RelationNotification) for a role update in the given relation.

sendUrgentData(int) - Method in class java.net.Socket

Send one byte of urgent data on the socket.

sendUrgentData(int) - Method in class java.net.SocketImpl

Send one byte of urgent data on the socket.

SENTENCE - Static variable in interface javax.accessibility.AccessibleText

Constant used to indicate that the part of the text that should be retrieved is a sentence.

SEPARATE_DOCUMENTS_COLLATED_COPIES - Static variable in class java.awt.JobAttributes.MultipleDocumentHandlingType

The MultipleDocumentHandlingType instance to use for specifying that the job should be divided into separate, collated copies.

SEPARATE_DOCUMENTS_COLLATED_COPIES - Static variable in class javax.print.attribute.standard.MultipleDocumentHandling

Separate documents collated copies -- see above for further information.

SEPARATE_DOCUMENTS_UNCOLLATED_COPIES - Static variable in class java.awt.JobAttributes.MultipleDocumentHandlingType

The MultipleDocumentHandlingType instance to use for specifying that the job should be divided into separate, uncollated copies.

SEPARATE_DOCUMENTS_UNCOLLATED_COPIES - Static variable in class javax.print.attribute.standard.MultipleDocumentHandling

Separate documents uncollated copies -- see above for further information.

separator - Static variable in class java.io.File

The system-dependent default name-separator character, represented as a string for convenience.

SEPARATOR - Static variable in class javax.accessibility.AccessibleRole

An object usually contained in a menu to provide a visual and logical separation of the contents in a menu.

SEPARATOR - Static variable in class javax.swing.plaf.synth.Region

Separator region.

separatorChar - Static variable in class java.io.File

The system-dependent default name-separator character.

SeparatorUI - Class in javax.swing.plaf

Pluggable look and feel interface for JSeparator.

SeparatorUI() - Constructor for class javax.swing.plaf.SeparatorUI

SEPTEMBER - Static variable in class java.util.Calendar

Value of the Calendar.MONTH field indicating the ninth month of the year in the Gregorian and Julian calendars.

SEPTEMBER - Static variable in class javax.xml.datatype.DatatypeConstants

Value for ninth month of year.

Sequence - Class in javax.sound.midi

A Sequence is a data structure containing musical information (often an entire song or composition) that can be played back by a Sequencer object.

Sequence(float, int) - Constructor for class javax.sound.midi.Sequence

Constructs a new MIDI sequence with the specified timing division type and timing resolution.

Sequence(float, int, int) - Constructor for class javax.sound.midi.Sequence

Constructs a new MIDI sequence with the specified timing division type, timing resolution, and number of tracks.

sequenceComplete(ImageReader) - Method in interface javax.imageio.event.IIOReadProgressListener

Reports that a sequence of read operationshas completed.

SequenceInputStream - Class in java.io

A SequenceInputStream represents the logical concatenation of other input streams.

SequenceInputStream(Enumeration<? extends InputStream>) - Constructor for class java.io.SequenceInputStream

Initializes a newly created SequenceInputStream by remembering the argument, which must be an Enumeration that produces objects whose run-time type is InputStream.

SequenceInputStream(InputStream, InputStream) - Constructor for class java.io.SequenceInputStream

Initializes a newly created SequenceInputStream by remembering the two arguments, which will be read in order, first s1 and then s2, to provide the bytes to be read from this SequenceInputStream.

Sequencer - Interface in javax.sound.midi

A hardware or software device that plays back a MIDI sequence is known as a sequencer.

Sequencer.SyncMode - Class in javax.sound.midi

A SyncMode object represents one of the ways in which a MIDI sequencer's notion of time can be synchronized with a master or slave device.

Sequencer.SyncMode(String) - Constructor for class javax.sound.midi.Sequencer.SyncMode

Constructs a synchronization mode.

sequenceStarted(ImageReader, int) - Method in interface javax.imageio.event.IIOReadProgressListener

Reports that a sequence of read operations is beginning.

SerialArray - Class in javax.sql.rowset.serial

A serialized version of an Array object, which is the mapping in the Java programming language of an SQL ARRAY value.

SerialArray(Array, Map<String, Class<?>>) - Constructor for class javax.sql.rowset.serial.SerialArray

Constructs a new SerialArray object from the given Array object, using the given type map for the custom mapping of each element when the elements are SQL UDTs.

SerialArray(Array) - Constructor for class javax.sql.rowset.serial.SerialArray

Constructs a new SerialArray object from the given Array object.

SerialBlob - Class in javax.sql.rowset.serial

A serialized mapping in the Java programming language of an SQL BLOB value.

SerialBlob(byte[]) - Constructor for class javax.sql.rowset.serial.SerialBlob

Constructs a SerialBlob object that is a serialized version of the given byte array.

SerialBlob(Blob) - Constructor for class javax.sql.rowset.serial.SerialBlob

Constructs a SerialBlob object that is a serialized version of the given Blob object.

SerialClob - Class in javax.sql.rowset.serial

A serialized mapping in the Java programming language of an SQL CLOB value.

SerialClob(char[]) - Constructor for class javax.sql.rowset.serial.SerialClob

Constructs a SerialClob object that is a serialized version of the given char array.

SerialClob(Clob) - Constructor for class javax.sql.rowset.serial.SerialClob

Constructs a SerialClob object that is a serialized version of the given Clob object.

SerialDatalink - Class in javax.sql.rowset.serial

A serialized mapping in the Java programming language of an SQL DATALINK value.

SerialDatalink(URL) - Constructor for class javax.sql.rowset.serial.SerialDatalink

Constructs a new SerialDatalink object from the given java.net.URL object.

SerialException - Exception in javax.sql.rowset.serial

Indicates and an error with the serialization or de-serialization of SQL types such as BLOB, CLOB, STRUCT or ARRAY in addition to SQL types such as DATALINK and JAVAOBJECT

SerialException() - Constructor for exception javax.sql.rowset.serial.SerialException

Creates a new SerialException without a message.

SerialException(String) - Constructor for exception javax.sql.rowset.serial.SerialException

Creates a new SerialException with the specified message.

serializable - Variable in class java.beans.beancontext.BeanContextServicesSupport

The number of instances of a serializable BeanContextServceProvider.

Serializable - Interface in java.io

Serializability of a class is enabled by the class implementing the java.io.Serializable interface.

SerializablePermission - Class in java.io

This class is for Serializable permissions.

SerializablePermission(String) - Constructor for class java.io.SerializablePermission

Creates a new SerializablePermission with the specified name.

SerializablePermission(String, String) - Constructor for class java.io.SerializablePermission

Creates a new SerializablePermission object with the specified name.

serialize(ObjectOutputStream, Collection) - Method in class java.beans.beancontext.BeanContextSupport

Used by writeObject to serialize a Collection.

SERIALIZE_ERR - Static variable in exception org.w3c.dom.ls.LSException

If an attempt was made to serialize a Node using LSSerializer and the processing has been stopped.

SerialJavaObject - Class in javax.sql.rowset.serial

A serializable mapping in the Java programming language of an SQL JAVA_OBJECT value.

SerialJavaObject(Object) - Constructor for class javax.sql.rowset.serial.SerialJavaObject

Constructor for SerialJavaObject helper class.

SerialRef - Class in javax.sql.rowset.serial

A serialized mapping of a Ref object, which is the mapping in the Java programming language of an SQL REF value.

SerialRef(Ref) - Constructor for class javax.sql.rowset.serial.SerialRef

Constructs a SerialRef object from the given Ref object.

SerialStruct - Class in javax.sql.rowset.serial

A serialized mapping in the Java programming language of an SQL structured type.

SerialStruct(Struct, Map<String, Class<?>>) - Constructor for class javax.sql.rowset.serial.SerialStruct

Constructs a SerialStruct object from the given Struct object, using the given java.util.Map object for custom mapping the SQL structured type or any of its attributes that are SQL structured types.

SerialStruct(SQLData, Map<String, Class<?>>) - Constructor for class javax.sql.rowset.serial.SerialStruct

Constructs a SerialStruct object from the given SQLData object, using the given type map to custom map it to a class in the Java programming language.

serialVersionUID - Static variable in interface java.rmi.server.RemoteRef

indicate compatibility with JDK 1.1.x version of class.

serialVersionUID - Static variable in interface java.rmi.server.ServerRef

indicate compatibility with JDK 1.1.x version of class.

serialVersionUID - Static variable in interface java.security.interfaces.DSAPrivateKey

The class fingerprint that is set to indicate serialization compatibility with a previous version of the class.

serialVersionUID - Static variable in interface java.security.interfaces.DSAPublicKey

The class fingerprint that is set to indicate serialization compatibility with a previous version of the class.

serialVersionUID - Static variable in interface java.security.interfaces.ECPrivateKey

The class fingerprint that is set to indicate serialization compatibility.

serialVersionUID - Static variable in interface java.security.interfaces.ECPublicKey

The class fingerprint that is set to indicate serialization compatibility.

serialVersionUID - Static variable in interface java.security.interfaces.RSAMultiPrimePrivateCrtKey

serialVersionUID - Static variable in interface java.security.interfaces.RSAPrivateCrtKey

serialVersionUID - Static variable in interface java.security.interfaces.RSAPrivateKey

serialVersionUID - Static variable in interface java.security.interfaces.RSAPublicKey

serialVersionUID - Static variable in interface java.security.Key

The class fingerprint that is set to indicate serialization compatibility with a previous version of the class.

serialVersionUID - Static variable in interface java.security.PrivateKey

The class fingerprint that is set to indicate serialization compatibility with a previous version of the class.

serialVersionUID - Static variable in interface java.security.PublicKey

The class fingerprint that is set to indicate serialization compatibility with a previous version of the class.

serialVersionUID - Static variable in interface javax.crypto.interfaces.DHPrivateKey

The class fingerprint that is set to indicate serialization compatibility since J2SE 1.4.

serialVersionUID - Static variable in interface javax.crypto.interfaces.DHPublicKey

The class fingerprint that is set to indicate serialization compatibility since J2SE 1.4.

serialVersionUID - Static variable in interface javax.crypto.interfaces.PBEKey

The class fingerprint that is set to indicate serialization compatibility since J2SE 1.4.

serialVersionUID - Static variable in interface javax.crypto.SecretKey

The class fingerprint that is set to indicate serialization compatibility since J2SE 1.4.

serialVersionUID - Static variable in interface javax.naming.directory.Attribute

Use serialVersionUID from JNDI 1.1.1 for interoperability.

serialVersionUID - Static variable in interface javax.naming.Name

The class fingerprint that is set to indicate serialization compatibility with a previous version of the class.

SERIF - Static variable in class java.awt.Font

A String constant for the canonical family name of the logical font "Serif".

servant - Variable in class org.omg.CORBA.portable.ServantObject

The real servant.

Servant - Class in org.omg.PortableServer

Defines the native Servant type.

Servant() - Constructor for class org.omg.PortableServer.Servant

servant_postinvoke(Object, ServantObject) - Method in class org.omg.CORBA.portable.Delegate

servant_postinvoke() is invoked by the local stub after the operation has been invoked on the local servant.

servant_preinvoke(Object, String, Class) - Method in class org.omg.CORBA.portable.Delegate

Returns a Java reference to the servant which should be used for this request.

SERVANT_RETENTION_POLICY_ID - Interface in org.omg.PortableServer

org/omg/PortableServer/SERVANT_RETENTION_POLICY_ID.java .

servant_to_id(Servant) - Method in interface org.omg.PortableServer.POAOperations

This operation has four possible behaviors.

servant_to_reference(Servant) - Method in interface org.omg.PortableServer.POAOperations

This operation requires the RETAIN policy and either the UNIQUE_ID or IMPLICIT_ACTIVATION policies if invoked outside the context of an operation dispatched by this POA.

ServantActivator - Interface in org.omg.PortableServer

When the POA has the RETAIN policy it uses servant managers that are ServantActivators.

ServantActivatorHelper - Class in org.omg.PortableServer

When the POA has the RETAIN policy it uses servant managers that are ServantActivators.

ServantActivatorHelper() - Constructor for class org.omg.PortableServer.ServantActivatorHelper

ServantActivatorOperations - Interface in org.omg.PortableServer

When the POA has the RETAIN policy it uses servant managers that are ServantActivators.

ServantActivatorPOA - Class in org.omg.PortableServer

When the POA has the RETAIN policy it uses servant managers that are ServantActivators.

ServantActivatorPOA() - Constructor for class org.omg.PortableServer.ServantActivatorPOA

ServantAlreadyActive - Exception in org.omg.PortableServer.POAPackage

org/omg/PortableServer/POAPackage/ServantAlreadyActive.java .

ServantAlreadyActive() - Constructor for exception org.omg.PortableServer.POAPackage.ServantAlreadyActive

ServantAlreadyActive(String) - Constructor for exception org.omg.PortableServer.POAPackage.ServantAlreadyActive

ServantAlreadyActiveHelper - Class in org.omg.PortableServer.POAPackage

org/omg/PortableServer/POAPackage/ServantAlreadyActiveHelper.java .

ServantAlreadyActiveHelper() - Constructor for class org.omg.PortableServer.POAPackage.ServantAlreadyActiveHelper

ServantLocator - Interface in org.omg.PortableServer

When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.

ServantLocatorHelper - Class in org.omg.PortableServer

When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.

ServantLocatorHelper() - Constructor for class org.omg.PortableServer.ServantLocatorHelper

ServantLocatorOperations - Interface in org.omg.PortableServer

When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.

ServantLocatorPOA - Class in org.omg.PortableServer

When the POA has the NON_RETAIN policy it uses servant managers that are ServantLocators.

ServantLocatorPOA() - Constructor for class org.omg.PortableServer.ServantLocatorPOA

ServantManager - Interface in org.omg.PortableServer

A servant manager supplies a POA with the ability to activate objects on demand when the POA receives a request targeted at an inactive object.

ServantManagerOperations - Interface in org.omg.PortableServer

A servant manager supplies a POA with the ability to activate objects on demand when the POA receives a request targeted at an inactive object.

ServantNotActive - Exception in org.omg.PortableServer.POAPackage

org/omg/PortableServer/POAPackage/ServantNotActive.java .

ServantNotActive() - Constructor for exception org.omg.PortableServer.POAPackage.ServantNotActive

ServantNotActive(String) - Constructor for exception org.omg.PortableServer.POAPackage.ServantNotActive

ServantNotActiveHelper - Class in org.omg.PortableServer.POAPackage

org/omg/PortableServer/POAPackage/ServantNotActiveHelper.java .

ServantNotActiveHelper() - Constructor for class org.omg.PortableServer.POAPackage.ServantNotActiveHelper

ServantObject - Class in org.omg.CORBA.portable

This class is part of the local stub API, the purpose of which is to provide high performance calls for collocated clients and servers (i.e.

ServantObject() - Constructor for class org.omg.CORBA.portable.ServantObject

ServantRetentionPolicy - Interface in org.omg.PortableServer

This policy specifies whether the created POA retains active servants in an Active Object Map.

ServantRetentionPolicyOperations - Interface in org.omg.PortableServer

This policy specifies whether the created POA retains active servants in an Active Object Map.

ServantRetentionPolicyValue - Class in org.omg.PortableServer

ServantRetentionPolicyValue can have the following values.

ServantRetentionPolicyValue(int) - Constructor for class org.omg.PortableServer.ServantRetentionPolicyValue

server - Variable in class javax.management.monitor.Monitor

Reference to the MBean server.

SERVER_AUTH - Static variable in class javax.security.sasl.Sasl

The name of a property that specifies whether the server must authenticate to the client.

server_id() - Method in interface org.omg.PortableInterceptor.ObjectReferenceTemplate

server_id() - Method in interface org.omg.PortableInterceptor.ServerRequestInfoOperations

Returns the server ID that was specified on ORB::init using the -ORBServerId argument.

ServerCloneException - Exception in java.rmi.server

A ServerCloneException is thrown if a remote exception occurs during the cloning of a UnicastRemoteObject.

ServerCloneException(String) - Constructor for exception java.rmi.server.ServerCloneException

Constructs a ServerCloneException with the specified detail message.

ServerCloneException(String, Exception) - Constructor for exception java.rmi.server.ServerCloneException

Constructs a ServerCloneException with the specified detail message and cause.

ServerError - Exception in java.rmi

A ServerError is thrown as a result of a remote method invocation when an Error is thrown while processing the invocation on the server, either while unmarshalling the arguments, executing the remote method itself, or marshalling the return value.

ServerError(String, Error) - Constructor for exception java.rmi.ServerError

Constructs a ServerError with the specified detail message and nested error.

ServerException - Exception in java.rmi

A ServerException is thrown as a result of a remote method invocation when a RemoteException is thrown while processing the invocation on the server, either while unmarshalling the arguments or executing the remote method itself.

ServerException(String) - Constructor for exception java.rmi.ServerException

Constructs a ServerException with the specified detail message.

ServerException(String, Exception) - Constructor for exception java.rmi.ServerException

Constructs a ServerException with the specified detail message and nested exception.

ServerIdHelper - Class in org.omg.PortableInterceptor

org/omg/PortableInterceptor/ServerIdHelper.java .

ServerIdHelper() - Constructor for class org.omg.PortableInterceptor.ServerIdHelper

ServerNotActiveException - Exception in java.rmi.server

An ServerNotActiveException is an Exception thrown during a call to RemoteServer.getClientHost if the getClientHost method is called outside of servicing a remote method call.

ServerNotActiveException() - Constructor for exception java.rmi.server.ServerNotActiveException

Constructs an ServerNotActiveException with no specified detail message.

ServerNotActiveException(String) - Constructor for exception java.rmi.server.ServerNotActiveException

Constructs an ServerNotActiveException with the specified detail message.

ServerRef - Interface in java.rmi.server

A ServerRef represents the server-side handle for a remote object implementation.

ServerRequest - Class in org.omg.CORBA

An object that captures the explicit state of a request for the Dynamic Skeleton Interface (DSI).

ServerRequest() - Constructor for class org.omg.CORBA.ServerRequest

ServerRequestInfo - Interface in org.omg.PortableInterceptor

Request Information, accessible to server-side request interceptors.

ServerRequestInfoOperations - Interface in org.omg.PortableInterceptor

Request Information, accessible to server-side request interceptors.

ServerRequestInterceptor - Interface in org.omg.PortableInterceptor

Server-side request interceptor.

ServerRequestInterceptorOperations - Interface in org.omg.PortableInterceptor

Server-side request interceptor.

ServerRuntimeException - Exception in java.rmi

Deprecated.
no replacement

ServerRuntimeException(String, Exception) - Constructor for exception java.rmi.ServerRuntimeException

Deprecated.
no replacement

ServerSocket - Class in java.net

This class implements server sockets.

ServerSocket() - Constructor for class java.net.ServerSocket

Creates an unbound server socket.

ServerSocket(int) - Constructor for class java.net.ServerSocket

Creates a server socket, bound to the specified port.

ServerSocket(int, int) - Constructor for class java.net.ServerSocket

Creates a server socket and binds it to the specified local port number, with the specified backlog.

ServerSocket(int, int, InetAddress) - Constructor for class java.net.ServerSocket

Create a server with the specified port, listen backlog, and local IP address to bind to.

ServerSocketChannel - Class in java.nio.channels

A selectable channel for stream-oriented listening sockets.

ServerSocketChannel(SelectorProvider) - Constructor for class java.nio.channels.ServerSocketChannel

Initializes a new instance of this class.

ServerSocketFactory - Class in javax.net

This class creates server sockets.

ServerSocketFactory() - Constructor for class javax.net.ServerSocketFactory

Creates a server socket factory.

Service - Class in javax.xml.ws

Service objects provide the client view of a Web service.

Service(URL, QName) - Constructor for class javax.xml.ws.Service

Service(URL, QName, WebServiceFeature...) - Constructor for class javax.xml.ws.Service

Service.Mode - Enum in javax.xml.ws

The orientation of a dynamic client or service.

service_detail - Variable in class org.omg.CORBA.ServiceDetail

The data describing the ORB service that this ServiceDetail object represents.

service_detail_type - Variable in class org.omg.CORBA.ServiceDetail

The type of the ORB service that this ServiceDetail object represents.

service_details - Variable in class org.omg.CORBA.ServiceInformation

Array of ServiceDetails giving more details about the service.

SERVICE_OFF_LINE - Static variable in class javax.print.attribute.standard.JobStateReason

The printer is off-line and accepting no jobs.

service_options - Variable in class org.omg.CORBA.ServiceInformation

Array of ints representing service options.

serviceAvailable(BeanContextServiceAvailableEvent) - Method in class java.beans.beancontext.BeanContextChildSupport

A new service is available from the nesting BeanContext.

serviceAvailable(BeanContextServiceAvailableEvent) - Method in interface java.beans.beancontext.BeanContextServicesListener

The service named has been registered.

serviceAvailable(BeanContextServiceAvailableEvent) - Method in class java.beans.beancontext.BeanContextServicesSupport

BeanContextServicesListener callback, propagates event to all currently registered listeners and BeanContextServices children, if this BeanContextService does not already implement this service itself.

serviceClass - Variable in class java.beans.beancontext.BeanContextServiceAvailableEvent

A 类 reference to the newly available service

serviceClass - Variable in class java.beans.beancontext.BeanContextServiceRevokedEvent

A 类 reference to the service that is being revoked.

ServiceConfigurationError - Error in java.util

Error thrown when something goes wrong while loading a service provider.

ServiceConfigurationError(String) - Constructor for error java.util.ServiceConfigurationError

Constructs a new instance with the specified message.

ServiceConfigurationError(String, Throwable) - Constructor for error java.util.ServiceConfigurationError

Constructs a new instance with the specified message and cause.

ServiceContext - Class in org.omg.IOP

org/omg/IOP/ServiceContext.java .

ServiceContext() - Constructor for class org.omg.IOP.ServiceContext

ServiceContext(int, byte[]) - Constructor for class org.omg.IOP.ServiceContext

ServiceContextHelper - Class in org.omg.IOP

org/omg/IOP/ServiceContextHelper.java .

ServiceContextHelper() - Constructor for class org.omg.IOP.ServiceContextHelper

ServiceContextHolder - Class in org.omg.IOP

org/omg/IOP/ServiceContextHolder.java .

ServiceContextHolder() - Constructor for class org.omg.IOP.ServiceContextHolder

ServiceContextHolder(ServiceContext) - Constructor for class org.omg.IOP.ServiceContextHolder

ServiceContextListHelper - Class in org.omg.IOP

An array of service contexts, forming a service context list.

ServiceContextListHelper() - Constructor for class org.omg.IOP.ServiceContextListHelper

ServiceContextListHolder - Class in org.omg.IOP

An array of service contexts, forming a service context list.

ServiceContextListHolder() - Constructor for class org.omg.IOP.ServiceContextListHolder

ServiceContextListHolder(ServiceContext[]) - Constructor for class org.omg.IOP.ServiceContextListHolder

ServiceDelegate - Class in javax.xml.ws.spi

Service delegates are used internally by Service objects to allow pluggability of JAX-WS implementations.

ServiceDelegate() - Constructor for class javax.xml.ws.spi.ServiceDelegate

ServiceDetail - Class in org.omg.CORBA

An object that represents an ORB service: its service_detail_type field contains the type of the ORB service, and its service_detail field contains a description of the ORB service.

ServiceDetail() - Constructor for class org.omg.CORBA.ServiceDetail

Constructs a ServiceDetail object with 0 for the type of ORB service and an empty description.

ServiceDetail(int, byte[]) - Constructor for class org.omg.CORBA.ServiceDetail

Constructs a ServiceDetail object with the given ORB service type and the given description.

ServiceDetailHelper - Class in org.omg.CORBA

ServiceDetailHelper() - Constructor for class org.omg.CORBA.ServiceDetailHelper

ServiceIdHelper - Class in org.omg.IOP

A service id, represented as an int

ServiceIdHelper() - Constructor for class org.omg.IOP.ServiceIdHelper

ServiceInformation - Class in org.omg.CORBA

An IDL struct in the CORBA module that stores information about a CORBA service available in the ORB implementation and is obtained from the ORB.get_service_information method.

ServiceInformation() - Constructor for class org.omg.CORBA.ServiceInformation

Constructs a ServiceInformation object with empty service_options and service_details.

ServiceInformation(int[], ServiceDetail[]) - Constructor for class org.omg.CORBA.ServiceInformation

Constructs a ServiceInformation object with the given service_options and service_details.

ServiceInformationHelper - Class in org.omg.CORBA

ServiceInformationHelper() - Constructor for class org.omg.CORBA.ServiceInformationHelper

ServiceInformationHolder - Class in org.omg.CORBA

The Holder for ServiceInformation.

ServiceInformationHolder() - Constructor for class org.omg.CORBA.ServiceInformationHolder

Constructs a new ServiceInformationHolder object with its value field initialized to null.

ServiceInformationHolder(ServiceInformation) - Constructor for class org.omg.CORBA.ServiceInformationHolder

Constructs a new ServiceInformationHolder object with its value field initialized to the given ServiceInformation object.

ServiceLoader<S> - Class in java.util

A simple service-provider loading facility.

ServiceMode - Annotation Type in javax.xml.ws

Used to indicate whether a Provider implementation wishes to work with entire protocol messages or just with protocol message payloads.

serviceName(QName) - Method in class javax.xml.ws.wsaddressing.W3CEndpointReferenceBuilder

Sets the serviceName as the wsam:ServiceName element in the wsa:Metadata element.

ServiceNotFoundException - Exception in javax.management

Represents exceptions raised when a requested service is not supported.

ServiceNotFoundException() - Constructor for exception javax.management.ServiceNotFoundException

Default constructor.

ServiceNotFoundException(String) - Constructor for exception javax.management.ServiceNotFoundException

Constructor that allows a specific error message to be specified.

ServicePermission - Class in javax.security.auth.kerberos

This class is used to protect Kerberos services and the credentials necessary to access those services.

ServicePermission(String, String) - Constructor for class javax.security.auth.kerberos.ServicePermission

Create a new ServicePermission with the specified servicePrincipal and action.

serviceProvider - Variable in class java.beans.beancontext.BeanContextServicesSupport.BCSSServiceProvider

ServiceRegistry - Class in javax.imageio.spi

A registry for service provider instances.

ServiceRegistry(Iterator<Class<?>>) - Constructor for class javax.imageio.spi.ServiceRegistry

Constructs a ServiceRegistry instance with a set of categories taken from the categories argument.

ServiceRegistry.Filter - Interface in javax.imageio.spi

A simple filter interface used by ServiceRegistry.getServiceProviders to select providers matching an arbitrary criterion.

serviceRevoked(BeanContextServiceRevokedEvent) - Method in class java.beans.beancontext.BeanContextChildSupport

A service provided by the nesting BeanContext has been revoked.

serviceRevoked(BeanContextServiceRevokedEvent) - Method in interface java.beans.beancontext.BeanContextServiceRevokedListener

The service named has been revoked.

serviceRevoked(BeanContextServiceRevokedEvent) - Method in class java.beans.beancontext.BeanContextServicesSupport.BCSSProxyServiceProvider

serviceRevoked(BeanContextServiceRevokedEvent) - Method in class java.beans.beancontext.BeanContextServicesSupport

BeanContextServicesListener callback, propagates event to all currently registered listeners and BeanContextServices children, if this BeanContextService does not already implement this service itself.

services - Variable in class java.beans.beancontext.BeanContextServicesSupport

all accesses to the protected transient HashMap services field should be synchronized on that object

ServiceUI - Class in javax.print

This class is a collection of UI convenience methods which provide a graphical user dialog for browsing print services looked up through the Java Print Service API.

ServiceUI() - Constructor for class javax.print.ServiceUI

ServiceUIFactory - Class in javax.print

Services may optionally provide UIs which allow different styles of interaction in different roles.

ServiceUIFactory() - Constructor for class javax.print.ServiceUIFactory

ServiceUnavailableException - Exception in javax.naming

This exception is thrown when attempting to communicate with a directory or naming service and that service is not available.

ServiceUnavailableException(String) - Constructor for exception javax.naming.ServiceUnavailableException

Constructs a new instance of ServiceUnavailableException using an explanation.

ServiceUnavailableException() - Constructor for exception javax.naming.ServiceUnavailableException

Constructs a new instance of ServiceUnavailableException.

SERVLET_CONTEXT - Static variable in interface javax.xml.ws.handler.MessageContext

Standard property: servlet context object.

SERVLET_REQUEST - Static variable in interface javax.xml.ws.handler.MessageContext

Standard property: servlet request object.

SERVLET_RESPONSE - Static variable in interface javax.xml.ws.handler.MessageContext

Standard property: servlet response object.

SESSION_MAINTAIN_PROPERTY - Static variable in interface javax.xml.ws.BindingProvider

Standard property: This boolean property is used by a service client to indicate whether or not it wants to participate in a session with a service endpoint.

set(Object, int) - Method in class java.awt.image.renderable.ParameterBlock

Replaces an Object in the list of parameters.

set(byte, int) - Method in class java.awt.image.renderable.ParameterBlock

Replaces an Object in the list of parameters with a Byte.

set(char, int) - Method in class java.awt.image.renderable.ParameterBlock

Replaces an Object in the list of parameters with a Character.

set(short, int) - Method in class java.awt.image.renderable.ParameterBlock

Replaces an Object in the list of parameters with a Short.

set(int, int) - Method in class java.awt.image.renderable.ParameterBlock

Replaces an Object in the list of parameters with an Integer.

set(long, int) - Method in class java.awt.image.renderable.ParameterBlock

Replaces an Object in the list of parameters with a Long.

set(float, int) - Method in class java.awt.image.renderable.ParameterBlock

Replaces an Object in the list of parameters with a Float.

set(double, int) - Method in class java.awt.image.renderable.ParameterBlock

Replaces an Object in the list of parameters with a Double.

set(int, int, int, int) - Method in class java.awt.Insets

Set top, left, bottom, and right to the specified values

set(JobAttributes) - Method in class java.awt.JobAttributes

Sets all of the attributes of this JobAttributes to the same values as the attributes of obj.

set(PageAttributes) - Method in class java.awt.PageAttributes

Sets all of the attributes of this PageAttributes to the same values as the attributes of obj.

set(Object, int, Object) - Static method in class java.lang.reflect.Array

Sets the value of the indexed component of the specified array object to the specified new value.

set(Object, Object) - Method in class java.lang.reflect.字段

Sets the field represented by this Field object on the specified object argument to the specified new value.

set(T) - Method in class java.lang.ThreadLocal

Sets the current thread's copy of this thread-local variable to the specified value.

set(String, String, int, String, String) - Method in class java.net.URL

Sets the fields of the URL.

set(String, String, int, String, String, String, String, String) - Method in class java.net.URL

Sets the specified 8 fields of the URL.

set(int, E) - Method in class java.util.AbstractList

Replaces the element at the specified position in this list with the specified element (optional operation).

set(int, E) - Method in class java.util.AbstractSequentialList

Replaces the element at the specified position in this list with the specified element (optional operation).

set(int, E) - Method in class java.util.ArrayList

Replaces the element at the specified position in this list with the specified element.

set(int) - Method in class java.util.BitSet

Sets the bit at the specified index to true.

set(int, boolean) - Method in class java.util.BitSet

Sets the bit at the specified index to the specified value.

set(int, int) - Method in class java.util.BitSet

Sets the bits from the specified fromIndex (inclusive) to the specified toIndex (exclusive) to true.

set(int, int, boolean) - Method in class java.util.BitSet

Sets the bits from the specified fromIndex (inclusive) to the specified toIndex (exclusive) to the specified value.

set(int, int) - Method in class java.util.Calendar

Sets the given calendar field to the given value.

set(int, int, int) - Method in class java.util.Calendar

Sets the values for the calendar fields YEAR, MONTH, and DAY_OF_MONTH.

set(int, int, int, int, int) - Method in class java.util.Calendar

Sets the values for the calendar fields YEAR, MONTH, DAY_OF_MONTH, HOUR_OF_DAY, and MINUTE.

set(int, int, int, int, int, int) - Method in class java.util.Calendar

Sets the values for the fields YEAR, MONTH, DAY_OF_MONTH, HOUR, MINUTE, and SECOND.

set(boolean) - Method in class java.util.concurrent.atomic.AtomicBoolean

Unconditionally sets to the given value.

set(int) - Method in class java.util.concurrent.atomic.AtomicInteger

Sets to the given value.

set(int, int) - Method in class java.util.concurrent.atomic.AtomicIntegerArray

Sets the element at position i to the given value.

set(T, int) - Method in class java.util.concurrent.atomic.AtomicIntegerFieldUpdater

Sets the field of the given object managed by this updater to the given updated value.

set(long) - Method in class java.util.concurrent.atomic.AtomicLong

Sets to the given value.

set(int, long) - Method in class java.util.concurrent.atomic.AtomicLongArray

Sets the element at position i to the given value.

set(T, long) - Method in class java.util.concurrent.atomic.AtomicLongFieldUpdater

Sets the field of the given object managed by this updater to the given updated value.

set(V, boolean) - Method in class java.util.concurrent.atomic.AtomicMarkableReference

Unconditionally sets the value of both the reference and mark.

set(V) - Method in class java.util.concurrent.atomic.AtomicReference

Sets to the given value.

set(int, E) - Method in class java.util.concurrent.atomic.AtomicReferenceArray

Sets the element at position i to the given value.

set(T, V) - Method in class java.util.concurrent.atomic.AtomicReferenceFieldUpdater

Sets the field of the given object managed by this updater to the given updated value.

set(V, int) - Method in class java.util.concurrent.atomic.AtomicStampedReference

Unconditionally sets the value of both the reference and stamp.

set(int, E) - Method in class java.util.concurrent.CopyOnWriteArrayList

Replaces the element at the specified position in this list with the specified element.

set(V) - Method in class java.util.concurrent.FutureTask

Sets the result of this Future to the given value unless this future has already been set or has been cancelled.

set(int, E) - Method in class java.util.LinkedList

Replaces the element at the specified position in this list with the specified element.

set(int, E) - Method in interface java.util.List

Replaces the element at the specified position in this list with the specified element (optional operation).

set(E) - Method in interface java.util.ListIterator

Replaces the last element returned by ListIterator.next() or ListIterator.previous() with the specified element (optional operation).

Set<E> - Interface in java.util

A collection that contains no duplicate elements.

set(int, E) - Method in class java.util.Vector

Replaces the element at the specified position in this Vector with the specified element.

set(String, String) - Method in class javax.activation.MimeTypeParameterList

Set the value to be associated with the given name, replacing any previous association.

set(int, Attribute) - Method in class javax.management.AttributeList

Sets the element at the position specified to be the attribute specified.

set(int, Object) - Method in class javax.management.AttributeList

Replaces the element at the specified position in this list with the specified element.

set(int, Role) - Method in class javax.management.relation.RoleList

Sets the element at the position specified to be the role specified.

set(int, Object) - Method in class javax.management.relation.RoleList

set(int, RoleUnresolved) - Method in class javax.management.relation.RoleUnresolvedList

Sets the element at the position specified to be the unresolved role specified.

set(int, Object) - Method in class javax.management.relation.RoleUnresolvedList

set(int, Object) - Method in interface javax.naming.directory.Attribute

Sets an attribute value in the ordered list of attribute values.

set(int, Object) - Method in class javax.naming.directory.BasicAttribute

set(int, E) - Method in class javax.swing.DefaultListModel

Replaces the element at the specified position in this list with the specified element.

set2DigitYearStart(Date) - Method in class java.text.SimpleDateFormat

Sets the 100-year period 2-digit years will be interpreted as being in to begin on the date the user specifies.

set_as_default() - Method in interface org.omg.CORBA.DynUnion

Deprecated.

Determines whether the discriminator associated with this union has been assigned a valid default value.

set_as_default(boolean) - Method in interface org.omg.CORBA.DynUnion

Deprecated.

Determines whether the discriminator associated with this union gets assigned a valid default value.

set_as_string(String) - Method in class org.omg.DynamicAny._DynEnumStub

Sets the value of the DynEnum to the enumerated value whose IDL identifier is passed in the value parameter.

set_as_string(String) - Method in interface org.omg.DynamicAny.DynEnumOperations

Sets the value of the DynEnum to the enumerated value whose IDL identifier is passed in the value parameter.

set_as_ulong(int) - Method in class org.omg.DynamicAny._DynEnumStub

Sets the value of the DynEnum as the enumerated value's ordinal value.

set_as_ulong(int) - Method in interface org.omg.DynamicAny.DynEnumOperations

Sets the value of the DynEnum as the enumerated value's ordinal value.

set_boxed_value(Any) - Method in interface org.omg.DynamicAny.DynValueBoxOperations

Replaces the boxed value with the specified value.

set_boxed_value_as_dyn_any(DynAny) - Method in interface org.omg.DynamicAny.DynValueBoxOperations

Replaces the boxed value with the value contained in the parameter.

set_delegate(Object) - Method in class org.omg.CORBA_2_3.ORB

set_discriminator(DynAny) - Method in class org.omg.DynamicAny._DynUnionStub

Sets the discriminator of the DynUnion to the specified value.

set_discriminator(DynAny) - Method in interface org.omg.DynamicAny.DynUnionOperations

Sets the discriminator of the DynUnion to the specified value.

set_elements(Any[]) - Method in interface org.omg.CORBA.DynArray

Deprecated.

Sets the value of this DynArray object to the given array.

set_elements(Any[]) - Method in interface org.omg.CORBA.DynSequence

Deprecated.

Sets the values of all elements in this sequence with the given array.

set_elements(Any[]) - Method in class org.omg.DynamicAny._DynArrayStub

Sets the DynArray to contain the passed elements.

set_elements(Any[]) - Method in class org.omg.DynamicAny._DynSequenceStub

Sets the elements of a sequence.

set_elements(Any[]) - Method in interface org.omg.DynamicAny.DynArrayOperations

Sets the DynArray to contain the passed elements.

set_elements(Any[]) - Method in interface org.omg.DynamicAny.DynSequenceOperations

Sets the elements of a sequence.

set_elements_as_dyn_any(DynAny[]) - Method in class org.omg.DynamicAny._DynArrayStub

Sets the DynArray to contain the passed elements.

set_elements_as_dyn_any(DynAny[]) - Method in class org.omg.DynamicAny._DynSequenceStub

Sets the elements of a sequence using DynAnys.

set_elements_as_dyn_any(DynAny[]) - Method in interface org.omg.DynamicAny.DynArrayOperations

Sets the DynArray to contain the passed elements.

set_elements_as_dyn_any(DynAny[]) - Method in interface org.omg.DynamicAny.DynSequenceOperations

Sets the elements of a sequence using DynAnys.

set_exception(Any) - Method in class org.omg.CORBA.ServerRequest

Throws an org.omg.CORBA.NO_IMPLEMENT exception.

set_length(int) - Method in class org.omg.DynamicAny._DynSequenceStub

Sets the length of the sequence.

set_length(int) - Method in interface org.omg.DynamicAny.DynSequenceOperations

Sets the length of the sequence.

set_members(NameValuePair[]) - Method in interface org.omg.CORBA.DynStruct

Deprecated.

Set the members of the struct.

set_members(NameValuePair[]) - Method in interface org.omg.CORBA.DynValue

Deprecated.

Sets the members of the value object this DynValue object represents to the given array of NameValuePair objects.

set_members(NameValuePair[]) - Method in class org.omg.DynamicAny._DynStructStub

Initializes the struct data value associated with a DynStruct object from a sequence of NameValuePairs.

set_members(NameValuePair[]) - Method in class org.omg.DynamicAny._DynValueStub

Initializes the value type's members from a sequence of NameValuePairs.

set_members(NameValuePair[]) - Method in interface org.omg.DynamicAny.DynStructOperations

Initializes the struct data value associated with a DynStruct object from a sequence of NameValuePairs.

set_members(NameValuePair[]) - Method in interface org.omg.DynamicAny.DynValueOperations

Initializes the value type's members from a sequence of NameValuePairs.

set_members_as_dyn_any(NameDynAnyPair[]) - Method in class org.omg.DynamicAny._DynStructStub

Initializes the struct data value associated with a DynStruct object from a sequence of NameDynAnyPairs.

set_members_as_dyn_any(NameDynAnyPair[]) - Method in class org.omg.DynamicAny._DynValueStub

Initializes the value type's members from a sequence of NameDynAnyPairs.

set_members_as_dyn_any(NameDynAnyPair[]) - Method in interface org.omg.DynamicAny.DynStructOperations

Initializes the struct data value associated with a DynStruct object from a sequence of NameDynAnyPairs.

set_members_as_dyn_any(NameDynAnyPair[]) - Method in interface org.omg.DynamicAny.DynValueOperations

Initializes the value type's members from a sequence of NameDynAnyPairs.

set_one_value(String, Any) - Method in class org.omg.CORBA.Context

Creates a NamedValue object and adds it to this Context object.

SET_OVERRIDE - Static variable in class org.omg.CORBA.SetOverrideType

The SetOverrideType constant for the enum value SET_OVERRIDE.

set_parameters(String[], Properties) - Method in class org.omg.CORBA.ORB

Allows the ORB implementation to be initialized with the given parameters and properties.

set_parameters(Applet, Properties) - Method in class org.omg.CORBA.ORB

Allows the ORB implementation to be initialized with the given applet and parameters.

set_policy_override(Object, Policy[], SetOverrideType) - Method in class org.omg.CORBA.portable.Delegate

Associates the policies passed in with a newly created object reference that it returns.

set_result(Any) - Method in class org.omg.CORBA.ServerRequest

Throws an org.omg.CORBA.NO_IMPLEMENT exception.

set_return_type(TypeCode) - Method in class org.omg.CORBA.Request

Sets the typecode for the return value of the method.

set_servant(Servant) - Method in interface org.omg.PortableServer.POAOperations

This operation registers the specified servant with the POA as the default servant.

set_servant_manager(ServantManager) - Method in interface org.omg.PortableServer.POAOperations

This operation sets the default servant manager associated with the POA.

set_slot(int, Any) - Method in interface org.omg.PortableInterceptor.CurrentOperations

Sets data in a slot.

set_slot(int, Any) - Method in interface org.omg.PortableInterceptor.ServerRequestInfoOperations

Allows an Interceptor to set a slot in the PortableInterceptor.Current that is in the scope of the request.

set_to_default_member() - Method in class org.omg.DynamicAny._DynUnionStub

Sets the discriminator to a value that is consistent with the value of the default case of a union.

set_to_default_member() - Method in interface org.omg.DynamicAny.DynUnionOperations

Sets the discriminator to a value that is consistent with the value of the default case of a union.

set_to_no_active_member() - Method in class org.omg.DynamicAny._DynUnionStub

Sets the discriminator to a value that does not correspond to any of the unions case labels.

set_to_no_active_member() - Method in interface org.omg.DynamicAny.DynUnionOperations

Sets the discriminator to a value that does not correspond to any of the unions case labels.

set_to_null() - Method in class org.omg.DynamicAny._DynValueStub

Changes the representation of a DynValueCommon to a null value type.

set_to_null() - Method in interface org.omg.DynamicAny.DynValueCommonOperations

Changes the representation of a DynValueCommon to a null value type.

set_to_value() - Method in class org.omg.DynamicAny._DynValueStub

Replaces a null value type with a newly constructed value.

set_to_value() - Method in interface org.omg.DynamicAny.DynValueCommonOperations

Replaces a null value type with a newly constructed value.

set_value(byte[]) - Method in interface org.omg.CORBA.DynFixed

Deprecated.

Sets the given fixed type instance as the value for this DynFixed object.

set_value(String) - Method in class org.omg.DynamicAny._DynFixedStub

Sets the value of the DynFixed.

set_value(String) - Method in interface org.omg.DynamicAny.DynFixedOperations

Sets the value of the DynFixed.

set_values(NVList) - Method in class org.omg.CORBA.Context

I Sets one or more property values in this Context object.

setAccelerationPriority(float) - Method in class java.awt.Image

Sets a hint for this image about how important acceleration is.

setAccelerator(KeyStroke) - Method in class javax.swing.JMenu

setAccelerator is not defined for JMenu.

setAccelerator(KeyStroke) - Method in class javax.swing.JMenuItem

Sets the key combination which invokes the menu item's action listeners without navigating the menu hierarchy.

setAcceptAllFileFilterUsed(boolean) - Method in class javax.swing.JFileChooser

Determines whether the AcceptAll FileFilter is used as an available choice in the choosable filter list.

setAccessible(AccessibleObject[], boolean) - Static method in class java.lang.reflect.AccessibleObject

Convenience method to set the accessible flag for an array of objects with a single security check (for efficiency).

setAccessible(boolean) - Method in class java.lang.reflect.AccessibleObject

Set the accessible flag for this object to the indicated boolean value.

setAccessibleCaption(Accessible) - Method in interface javax.accessibility.AccessibleTable

Sets the caption for the table.

setAccessibleCaption(Accessible) - Method in class javax.swing.JTable.AccessibleJTable

Sets the caption for the table.

setAccessibleColumnDescription(int, Accessible) - Method in interface javax.accessibility.AccessibleTable

Sets the description text of the specified column in the table.

setAccessibleColumnDescription(int, Accessible) - Method in class javax.swing.JTable.AccessibleJTable

Sets the description text of the specified column of the table.

setAccessibleColumnHeader(AccessibleTable) - Method in interface javax.accessibility.AccessibleTable

Sets the column headers.

setAccessibleColumnHeader(AccessibleTable) - Method in class javax.swing.JTable.AccessibleJTable

Sets the column headers as an AccessibleTable.

setAccessibleDescription(String) - Method in class javax.accessibility.AccessibleContext

Sets the accessible description of this object.

setAccessibleDescription(String) - Method in class javax.swing.JList.AccessibleJList.AccessibleJListChild

setAccessibleDescription(String) - Method in class javax.swing.JTable.AccessibleJTable.AccessibleJTableCell

Sets the accessible description of this object.

setAccessibleDescription(String) - Method in class javax.swing.JTree.AccessibleJTree.AccessibleJTreeNode

Set the accessible description of this object.

setAccessibleDescription(String) - Method in class javax.swing.table.JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry

setAccessibleIconDescription(String) - Method in interface javax.accessibility.AccessibleIcon

Sets the description of the icon.

setAccessibleIconDescription(String) - Method in class javax.swing.ImageIcon.AccessibleImageIcon

Sets the description of the icon.

setAccessibleName(String) - Method in class javax.accessibility.AccessibleContext

Sets the localized accessible name of this object.

setAccessibleName(String) - Method in class javax.swing.JList.AccessibleJList.AccessibleJListChild

setAccessibleName(String) - Method in class javax.swing.JTable.AccessibleJTable.AccessibleJTableCell

Sets the localized accessible name of this object.

setAccessibleName(String) - Method in class javax.swing.JTree.AccessibleJTree.AccessibleJTreeNode

Set the localized accessible name of this object.

setAccessibleName(String) - Method in class javax.swing.table.JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry

setAccessibleParent(Accessible) - Method in class javax.accessibility.AccessibleContext

Sets the Accessible parent of this object.

setAccessibleRowDescription(int, Accessible) - Method in interface javax.accessibility.AccessibleTable

Sets the description text of the specified row of the table.

setAccessibleRowDescription(int, Accessible) - Method in class javax.swing.JTable.AccessibleJTable

Sets the description text of the specified row of the table.

setAccessibleRowHeader(AccessibleTable) - Method in interface javax.accessibility.AccessibleTable

Sets the row headers.

setAccessibleRowHeader(AccessibleTable) - Method in class javax.swing.JTable.AccessibleJTable

Sets the row headers as an AccessibleTable.

setAccessibleSummary(Accessible) - Method in interface javax.accessibility.AccessibleTable

Sets the summary description of the table

setAccessibleSummary(Accessible) - Method in class javax.swing.JTable.AccessibleJTable

Sets the summary description of the table.

setAccessory(JComponent) - Method in class javax.swing.JFileChooser

Sets the accessory component.

setAcl(List<AclEntry>) - Method in interface java.nio.file.attribute.AclFileAttributeView

Updates (replace) the access control list.

setAction(Action) - Method in class javax.swing.AbstractButton

Sets the Action.

setAction(Action) - Method in class javax.swing.JComboBox

Sets the Action for the ActionEvent source.

setAction(Action) - Method in class javax.swing.JTextField

Sets the Action for the ActionEvent source.

setActionCommand(String) - Method in class java.awt.Button

Sets the command name for the action event fired by this button.

setActionCommand(String) - Method in class java.awt.MenuItem

Sets the command name of the action event that is fired by this menu item.

setActionCommand(String) - Method in class java.awt.TrayIcon

Sets the command name for the action event fired by this tray icon.

setActionCommand(String) - Method in class javax.swing.AbstractButton

Sets the action command for this button.

setActionCommand(String) - Method in interface javax.swing.ButtonModel

Sets the action command string that gets sent as part of the ActionEvent when the button is triggered.

setActionCommand(String) - Method in class javax.swing.DefaultButtonModel

Sets the action command string that gets sent as part of the ActionEvent when the button is triggered.

setActionCommand(String) - Method in class javax.swing.JComboBox

Sets the action command that should be included in the event sent to action listeners.

setActionCommand(String) - Method in class javax.swing.JTextField

Sets the command string used for action events.

setActionCommand(String) - Method in class javax.swing.Timer

Sets the string that will be delivered as the action command in ActionEvents fired by this timer.

setActionMap(ActionMap) - Method in class javax.swing.JComponent

Sets the ActionMap to am.

setActivationDesc(ActivationID, ActivationDesc) - Method in interface java.rmi.activation.ActivationSystem

Set the activation descriptor, desc for the object with the activation identifier, id.

setActivationGroupDesc(ActivationGroupID, ActivationGroupDesc) - Method in interface java.rmi.activation.ActivationSystem

Set the activation group descriptor, desc for the object with the activation group identifier, id.

setActive(boolean) - Method in class java.awt.dnd.DropTarget

Sets the DropTarget active if true, inactive if false.

setActor(String) - Method in interface javax.xml.soap.SOAPHeaderElement

Sets the actor associated with this SOAPHeaderElement object to the specified actor.

setAdapter(XmlAdapter) - Method in class javax.xml.bind.helpers.AbstractMarshallerImpl

setAdapter(Class<A>, A) - Method in class javax.xml.bind.helpers.AbstractMarshallerImpl

setAdapter(XmlAdapter) - Method in class javax.xml.bind.helpers.AbstractUnmarshallerImpl

setAdapter(Class<A>, A) - Method in class javax.xml.bind.helpers.AbstractUnmarshallerImpl

setAdapter(XmlAdapter) - Method in interface javax.xml.bind.Marshaller

Associates a configured instance of XmlAdapter with this marshaller.

setAdapter(Class<A>, A) - Method in interface javax.xml.bind.Marshaller

Associates a configured instance of XmlAdapter with this marshaller.

setAdapter(XmlAdapter) - Method in interface javax.xml.bind.Unmarshaller

Associates a configured instance of XmlAdapter with this unmarshaller.

setAdapter(Class<A>, A) - Method in interface javax.xml.bind.Unmarshaller

Associates a configured instance of XmlAdapter with this unmarshaller.

setAddress(InetAddress) - Method in class java.net.DatagramPacket

Sets the IP address of the machine to which this datagram is being sent.

setAlgorithmConstraints(AlgorithmConstraints) - Method in class javax.net.ssl.SSLParameters

Sets the cryptographic algorithm constraints, which will be used in addition to any configured by the runtime environment.

setAlignment(int) - Method in class java.awt.FlowLayout

Sets the alignment for this layout.

setAlignment(int) - Method in class java.awt.Label

Sets the alignment for this label to the specified alignment.

setAlignment(MutableAttributeSet, int) - Static method in class javax.swing.text.StyleConstants

Sets alignment.

setAlignmentX(float) - Method in class javax.swing.JComponent

Sets the the vertical alignment.

setAlignmentY(float) - Method in class javax.swing.JComponent

Sets the the horizontal alignment.

setAlignOnBaseline(boolean) - Method in class java.awt.FlowLayout

Sets whether or not components should be vertically aligned along their baseline.

setAllocation(Shape) - Method in class javax.swing.text.AsyncBoxView.ChildLocator

Copy the currently allocated shape into the Rectangle used to store the current allocation.

setAllowsChildren(boolean) - Method in class javax.swing.tree.DefaultMutableTreeNode

Determines whether or not this node is allowed to have children.

setAllowsInvalid(boolean) - Method in class javax.swing.text.DefaultFormatter

Sets whether or not the value being edited is allowed to be invalid for a length of time (that is, stringToValue throws a ParseException).

setAllowUserInteraction(boolean) - Method in class java.net.URLConnection

Set the value of the allowUserInteraction field of this URLConnection.

setAltName(Name) - Method in exception javax.naming.CannotProceedException

Sets the altName field of this exception.

setAltNameCtx(Context) - Method in exception javax.naming.CannotProceedException

Sets the altNameCtx field of this exception.

setAlwaysOnTop(boolean) - Method in class java.awt.Window

Sets whether this window should always be above other windows.

setAmPmStrings(String[]) - Method in class java.text.DateFormatSymbols

Sets ampm strings.

setAnchorSelectionIndex(int) - Method in class javax.swing.DefaultListSelectionModel

Set the anchor selection index, leaving all selection values unchanged.

setAnchorSelectionIndex(int) - Method in interface javax.swing.ListSelectionModel

Set the anchor selection index.

setAnchorSelectionPath(TreePath) - Method in class javax.swing.JTree

Sets the path identified as the anchor.

setAngleExtent(double) - Method in class java.awt.geom.Arc2D.Double

Sets the angular extent of this arc to the specified double value.

setAngleExtent(double) - Method in class java.awt.geom.Arc2D.Float

Sets the angular extent of this arc to the specified double value.

setAngleExtent(double) - Method in class java.awt.geom.Arc2D

Sets the angular extent of this arc to the specified double value.

setAngles(double, double, double, double) - Method in class java.awt.geom.Arc2D

Sets the starting angle and angular extent of this arc using two sets of coordinates.

setAngles(Point2D, Point2D) - Method in class java.awt.geom.Arc2D

Sets the starting angle and angular extent of this arc using two points.

setAngleStart(double) - Method in class java.awt.geom.Arc2D.Double

Sets the starting angle of this arc to the specified double value.

setAngleStart(double) - Method in class java.awt.geom.Arc2D.Float

Sets the starting angle of this arc to the specified double value.

setAngleStart(double) - Method in class java.awt.geom.Arc2D

Sets the starting angle of this arc to the specified double value.

setAngleStart(Point2D) - Method in class java.awt.geom.Arc2D

Sets the starting angle of this arc to the angle that the specified point defines relative to the center of this arc.

setAnimated(boolean) - Method in class java.awt.image.MemoryImageSource

Changes this memory image into a multi-frame animation or a single-frame static image depending on the animated parameter.

setAnimationIndex(int) - Method in class javax.swing.plaf.basic.BasicProgressBarUI

Sets the index of the current animation frame to the specified value and requests that the progress bar be repainted.

setAnimationIndex(int) - Method in class javax.swing.plaf.synth.SynthProgressBarUI

setAnyPolicyInhibited(boolean) - Method in class java.security.cert.PKIXParameters

Sets state to determine if the any policy OID should be processed if it is included in a certificate.

setApproveButtonMnemonic(int) - Method in class javax.swing.JFileChooser

Sets the approve button's mnemonic using a numeric keycode.

setApproveButtonMnemonic(char) - Method in class javax.swing.JFileChooser

Sets the approve button's mnemonic using a character.

setApproveButtonText(String) - Method in class javax.swing.JFileChooser

Sets the text used in the ApproveButton in the FileChooserUI.

setApproveButtonToolTipText(String) - Method in class javax.swing.JFileChooser

Sets the tooltip text used in the ApproveButton.

setArc(double, double, double, double, double, double, int) - Method in class java.awt.geom.Arc2D.Double

Sets the location, size, angular extents, and closure type of this arc to the specified double values.

setArc(double, double, double, double, double, double, int) - Method in class java.awt.geom.Arc2D.Float

Sets the location, size, angular extents, and closure type of this arc to the specified double values.

setArc(double, double, double, double, double, double, int) - Method in class java.awt.geom.Arc2D

Sets the location, size, angular extents, and closure type of this arc to the specified double values.

setArc(Point2D, Dimension2D, double, double, int) - Method in class java.awt.geom.Arc2D

Sets the location, size, angular extents, and closure type of this arc to the specified values.

setArc(Rectangle2D, double, double, int) - Method in class java.awt.geom.Arc2D

Sets the location, size, angular extents, and closure type of this arc to the specified values.

setArc(Arc2D) - Method in class java.awt.geom.Arc2D

Sets this arc to be the same as the specified arc.

setArcByCenter(double, double, double, double, double, int) - Method in class java.awt.geom.Arc2D

Sets the position, bounds, angular extents, and closure type of this arc to the specified values.

setArcByTangent(Point2D, Point2D, Point2D, double) - Method in class java.awt.geom.Arc2D

Sets the position, bounds, and angular extents of this arc to the specified value.

setArchive(boolean) - Method in interface java.nio.file.attribute.DosFileAttributeView

Updates the value of the archive attribute.

setArcType(int) - Method in class java.awt.geom.Arc2D

Sets the closure type of this arc to the specified value: OPEN, CHORD, or PIE.

setAreaOfInterest(Shape) - Method in class java.awt.image.renderable.RenderContext

Sets the current area of interest.

setArmed(boolean) - Method in interface javax.swing.ButtonModel

Marks the button as armed or unarmed.

setArmed(boolean) - Method in class javax.swing.DefaultButtonModel

Marks the button as armed or unarmed.

setArmed(boolean) - Method in class javax.swing.JMenuItem

Identifies the menu item as "armed".

setArray(int, Array) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given java.sql.Array object.

setArray(int, Array) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to an Array object in the Java programming language.

setArray(int, Array) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command with the given Array value.

setAsciiStream(String, InputStream, int) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given input stream, which will have the specified number of bytes.

setAsciiStream(String, InputStream, long) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given input stream, which will have the specified number of bytes.

setAsciiStream(String, InputStream) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given input stream.

setAsciiStream(long) - Method in interface java.sql.Clob

Retrieves a stream to be used to write Ascii characters to the CLOB value that this Clob object represents, starting at position pos.

setAsciiStream(int, InputStream, int) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given input stream, which will have the specified number of bytes.

setAsciiStream(int, InputStream, long) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given input stream, which will have the specified number of bytes.

setAsciiStream(int, InputStream) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given input stream.

setAsciiStream(int, InputStream, int) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.io.InputStream object, which will have the specified number of bytes.

setAsciiStream(int, InputStream) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter in this RowSet object's command to the given input stream.

setAsciiStream(String, InputStream, int) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given input stream, which will have the specified number of bytes.

setAsciiStream(String, InputStream) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given input stream.

setAsciiStream(long) - Method in class javax.sql.rowset.serial.SerialClob

Retrieves a stream to be used to write Ascii characters to the CLOB value that this SerialClob object represents, starting at position pos.

setAsciiStream(int, InputStream, int) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command to the given java.io.InputStream value.

setAsciiStream(String, InputStream, int) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given input stream, which will have the specified number of bytes.

setAsciiStream(int, InputStream) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command to the given input stream.

setAsciiStream(String, InputStream) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given input stream.

setAsksAllowsChildren(boolean) - Method in class javax.swing.tree.DefaultTreeModel

Sets whether or not to test leafness by asking getAllowsChildren() or isLeaf() to the TreeNodes.

setAsText(String) - Method in interface java.beans.PropertyEditor

Set the property value by parsing a given String.

setAsText(String) - Method in class java.beans.PropertyEditorSupport

Sets the property value by parsing a given String.

setAsynchronousLoadPriority(int) - Method in class javax.swing.text.AbstractDocument

Sets the asynchronous loading priority.

setAttachmentMarshaller(AttachmentMarshaller) - Method in class javax.xml.bind.helpers.AbstractMarshallerImpl

setAttachmentMarshaller(AttachmentMarshaller) - Method in interface javax.xml.bind.Marshaller

Associate a context that enables binary data within an XML document to be transmitted as XML-binary optimized attachment.

setAttachmentUnmarshaller(AttachmentUnmarshaller) - Method in class javax.xml.bind.helpers.AbstractUnmarshallerImpl

setAttachmentUnmarshaller(AttachmentUnmarshaller) - Method in interface javax.xml.bind.Unmarshaller

Associate a context that resolves cid's, content-id URIs, to binary data passed as attachments.

setAttribute(Path, String, Object, LinkOption...) - Static method in class java.nio.file.Files

Sets the value of a file attribute.

setAttribute(Path, String, Object, LinkOption...) - Method in class java.nio.file.spi.FileSystemProvider

Sets the value of a file attribute.

setAttribute(String, String) - Method in class javax.imageio.metadata.IIOMetadataNode

setAttribute(Attribute) - Method in interface javax.management.DynamicMBean

Set the value of a specific attribute of the Dynamic MBean.

setAttribute(ObjectName, Attribute) - Method in interface javax.management.MBeanServer

setAttribute(ObjectName, Attribute) - Method in interface javax.management.MBeanServerConnection

Sets the value of a specific attribute of a named MBean.

setAttribute(Attribute) - Method in class javax.management.modelmbean.RequiredModelMBean

Sets the value of a specific attribute of a named ModelMBean.

setAttribute(ObjectName, MarshalledObject, Subject) - Method in interface javax.management.remote.rmi.RMIConnection

Handles the method MBeanServerConnection.setAttribute(ObjectName, Attribute).

setAttribute(ObjectName, MarshalledObject, Subject) - Method in class javax.management.remote.rmi.RMIConnectionImpl

setAttribute(ObjectName, MarshalledObject, Subject) - Method in class javax.management.remote.rmi.RMIConnectionImpl_Stub

setAttribute(Attribute) - Method in class javax.management.StandardMBean

setAttribute(String, Object, int) - Method in interface javax.script.ScriptContext

Sets the value of an attribute in a given scope.

setAttribute(String, Object, int) - Method in class javax.script.SimpleScriptContext

Sets the value of an attribute in a given scope.

setAttribute(String, Object) - Method in class javax.xml.parsers.DocumentBuilderFactory

Allows the user to set specific attributes on the underlying implementation.

setAttribute(String, Object) - Method in class javax.xml.transform.TransformerFactory

Allows the user to set specific attributes on the underlying implementation.

setAttribute(String, String) - Method in interface org.w3c.dom.Element

Adds a new attribute.

setAttribute(int, String, String, String, String, String) - Method in class org.xml.sax.helpers.AttributesImpl

Set an attribute in the list.

setAttributeList(AttributeList) - Method in class org.xml.sax.helpers.AttributeListImpl

Deprecated.

Set the attribute list, discarding previous contents.

setAttributeNode(Attr) - Method in class javax.imageio.metadata.IIOMetadataNode

setAttributeNode(Attr) - Method in interface org.w3c.dom.Element

Adds a new attribute node.

setAttributeNodeNS(Attr) - Method in class javax.imageio.metadata.IIOMetadataNode

Equivalent to setAttributeNode(newAttr).

setAttributeNodeNS(Attr) - Method in interface org.w3c.dom.Element

Adds a new attribute.

setAttributeNS(String, String, String) - Method in class javax.imageio.metadata.IIOMetadataNode

Equivalent to setAttribute(qualifiedName, value).

setAttributeNS(String, String, String) - Method in interface org.w3c.dom.Element

Adds a new attribute.

setAttributes(int, int, AttributeSet) - Method in interface javax.accessibility.AccessibleEditableText

Sets attributes for the text between two indices.

setAttributes(AttributeList) - Method in interface javax.management.DynamicMBean

Sets the values of several attributes of the Dynamic MBean.

setAttributes(ObjectName, AttributeList) - Method in interface javax.management.MBeanServer

setAttributes(ObjectName, AttributeList) - Method in interface javax.management.MBeanServerConnection

Sets the values of several attributes of a named MBean.

setAttributes(AttributeList) - Method in class javax.management.modelmbean.RequiredModelMBean

Sets the values of an array of attributes of this ModelMBean.

setAttributes(ObjectName, MarshalledObject, Subject) - Method in interface javax.management.remote.rmi.RMIConnection

Handles the method MBeanServerConnection.setAttributes(ObjectName, AttributeList).

setAttributes(ObjectName, MarshalledObject, Subject) - Method in class javax.management.remote.rmi.RMIConnectionImpl

setAttributes(ObjectName, MarshalledObject, Subject) - Method in class javax.management.remote.rmi.RMIConnectionImpl_Stub

setAttributes(AttributeList) - Method in class javax.management.StandardMBean

setAttributes(Attributes) - Method in class javax.naming.directory.SearchResult

Sets the attributes of this search result to attrs.

setAttributes(int, int, AttributeSet) - Method in class javax.swing.JSpinner.AccessibleJSpinner

Sets attributes for the text between two indices.

setAttributes(int, int, AttributeSet) - Method in class javax.swing.text.JTextComponent.AccessibleJTextComponent

Sets attributes for the text between two indices.

setAttributes(Attributes) - Method in class org.xml.sax.ext.Attributes2Impl

Copy an entire Attributes object.

setAttributes(Attributes) - Method in class org.xml.sax.helpers.AttributesImpl

Copy an entire Attributes object.

setAuthorityKeyIdentifier(byte[]) - Method in class java.security.cert.X509CertSelector

Sets the authorityKeyIdentifier criterion.

setAuthorized(boolean) - Method in class javax.security.sasl.AuthorizeCallback

Sets whether the authorization is allowed.

setAuthorizedID(String) - Method in class javax.security.sasl.AuthorizeCallback

Sets the id of the authorized entity.

setAutoCommit(boolean) - Method in interface java.sql.Connection

Sets this connection's auto-commit mode to the given state.

setAutoCommit(boolean) - Method in interface javax.sql.rowset.JdbcRowSet

Each JdbcRowSet contains a Connection object from the original ResultSet or JDBC properties passed to it.

setAutoCreateColumnsFromModel(boolean) - Method in class javax.swing.JTable

Sets this table's autoCreateColumnsFromModel flag.

setAutoCreateContainerGaps(boolean) - Method in class javax.swing.GroupLayout

Sets whether a gap between the container and components that touch the border of the container should automatically be created.

setAutoCreateGaps(boolean) - Method in class javax.swing.GroupLayout

Sets whether a gap between components should automatically be created.

setAutoCreateRowSorter(boolean) - Method in class javax.swing.JTable

Specifies whether a RowSorter should be created for the table whenever its model changes.

setAutoDelay(int) - Method in class java.awt.Robot

Sets the number of milliseconds this Robot sleeps after generating an event.

setAutoFormSubmission(boolean) - Method in class javax.swing.text.html.HTMLEditorKit

Specifies if an html form submission is processed automatically or only FormSubmitEvent is fired.

setAutoIncrement(int, boolean) - Method in class javax.sql.rowset.RowSetMetaDataImpl

Sets whether the designated column is automatically numbered, thus read-only, to the given boolean value.

setAutoIncrement(int, boolean) - Method in interface javax.sql.RowSetMetaData

Sets whether the designated column is automatically numbered, The default is for a RowSet object's columns not to be automatically numbered.

setAutoRequestFocus(boolean) - Method in class java.awt.Window

Sets whether this window should receive focus on subsequently being shown (with a call to setVisible(true)), or being moved to the front (with a call to Window.toFront()).

setAutoResizeMode(int) - Method in class javax.swing.JTable

Sets the table's auto resize mode when the table is resized.

setAutoscrolls(boolean) - Method in class javax.swing.JComponent

Sets the autoscrolls property.

setAutoWaitForIdle(boolean) - Method in class java.awt.Robot

Sets whether this Robot automatically invokes waitForIdle after generating an event.

setAxis(int) - Method in class javax.swing.text.BoxView

Sets the tile axis property.

setBackground(Color) - Method in class java.awt.Component.AccessibleAWTComponent

Sets the background color of this object.

setBackground(Color) - Method in class java.awt.Component

Sets the background color of this component.

setBackground(Color) - Method in class java.awt.Dialog

Sets the background color of this window.

setBackground(Color) - Method in class java.awt.Frame

Sets the background color of this window.

setBackground(Color) - Method in class java.awt.Graphics2D

Sets the background color for the Graphics2D context.

setBackground(Color) - Method in class java.awt.List.AccessibleAWTList.AccessibleAWTListChild

Set the background color of this object.

setBackground(Color) - Method in class java.awt.MenuComponent.AccessibleAWTMenuComponent

Sets the background color of this object.

setBackground(Color) - Method in class java.awt.TextComponent

Sets the background color of this text component.

setBackground(Color) - Method in class java.awt.Window

Sets the background color of this window.

setBackground(Color) - Method in interface javax.accessibility.AccessibleComponent

Sets the background color of this object.

setBackground(Color) - Method in class javax.swing.JComponent

Sets the background color of this component.

setBackground(Color) - Method in class javax.swing.JList.AccessibleJList.AccessibleJListChild

setBackground(Color) - Method in class javax.swing.JTable.AccessibleJTable.AccessibleJTableCell

Sets the background color of this object.

setBackground(Color) - Method in class javax.swing.JTree.AccessibleJTree.AccessibleJTreeNode

Set the background color of this object.

setBackground(Color) - Method in class javax.swing.table.DefaultTableCellRenderer

Overrides JComponent.setBackground to assign the unselected-background color to the specified color.

setBackground(Color) - Method in class javax.swing.table.JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry

setBackground(Color) - Method in class javax.swing.text.LabelView

Sets the background color for the view.

setBackground(MutableAttributeSet, Color) - Static method in class javax.swing.text.StyleConstants

Sets the background color.

setBackground(Color) - Method in class javax.swing.tree.DefaultTreeCellRenderer

Subclassed to map ColorUIResources to null.

setBackgroundAt(int, Color) - Method in class javax.swing.JTabbedPane

Sets the background color at index to background which can be null, in which case the tab's background color will default to the background color of the tabbedpane.

setBackgroundNonSelectionColor(Color) - Method in class javax.swing.tree.DefaultTreeCellRenderer

Sets the background color to be used for non selected nodes.

setBackgroundSelectionColor(Color) - Method in class javax.swing.tree.DefaultTreeCellRenderer

Sets the color to use for the background if node is selected.

setBackingStoreEnabled(boolean) - Method in class javax.swing.JViewport

Deprecated.
As of Java 2 platform v1.3, replaced by setScrollMode().

setBase(URL) - Method in class javax.swing.text.html.HTMLDocument

Sets the location to resolve relative URLs against.

setBase(URL) - Method in class javax.swing.text.html.StyleSheet

Sets the base.

setBase64Content(InputStream, String) - Method in class javax.xml.soap.AttachmentPart

Sets the content of this attachment part from the Base64 source InputStream and sets the value of the Content-Type header to the value contained in contentType, This method would first decode the base64 input and write the resulting raw bytes to the attachment.

setBaseFontSize(int) - Method in class javax.swing.text.html.StyleSheet

Sets the base font size, with valid values between 1 and 7.

setBaseFontSize(String) - Method in class javax.swing.text.html.StyleSheet

Sets the base font size from the passed in String.

setBaseURI(String) - Method in class javax.xml.crypto.dom.DOMCryptoContext

setBaseURI(String) - Method in interface javax.xml.crypto.XMLCryptoContext

Sets the base URI.

setBaseURI(String) - Method in interface org.w3c.dom.ls.LSInput

The base URI to be used (see section 5.1.4 in [IETF RFC 2396]) for resolving a relative systemId to an absolute URI.

setBasicConstraints(int) - Method in class java.security.cert.X509CertSelector

Sets the basic constraints constraint.

setBasicSplitPaneUI(BasicSplitPaneUI) - Method in class javax.swing.plaf.basic.BasicSplitPaneDivider

Sets the SplitPaneUI that is using the receiver.

setBeanContext(BeanContext) - Method in interface java.beans.beancontext.BeanContextChild

Objects that implement this interface, shall fire a java.beans.PropertyChangeEvent, with parameters: propertyName "beanContext", oldValue (the previous nesting BeanContext instance, or null), newValue (the current nesting BeanContext instance, or null).

setBeanContext(BeanContext) - Method in class java.beans.beancontext.BeanContextChildSupport

Sets the BeanContext for this BeanContextChildSupport.

setBeanInfoSearchPath(String[]) - Static method in class java.beans.Introspector

Change the list of package names that will be used for finding BeanInfo classes.

setBeginIndex(int) - Method in class java.text.FieldPosition

Sets the begin index.

setBidiLevel(MutableAttributeSet, int) - Static method in class javax.swing.text.StyleConstants

Sets the BidiLevel.

setBigDecimal(String, BigDecimal) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given java.math.BigDecimal value.

setBigDecimal(int, BigDecimal) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given java.math.BigDecimal value.

setBigDecimal(int, BigDecimal) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.lang.BigDecimal value.

setBigDecimal(String, BigDecimal) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.math.BigDecimal value.

setBigDecimal(int, BigDecimal) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command to the given java.math.BigDeciaml value.

setBigDecimal(String, BigDecimal) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given java.math.BigDecimal value.

setBinaryStream(long) - Method in interface java.sql.Blob

Retrieves a stream that can be used to write to the BLOB value that this Blob object represents.

setBinaryStream(String, InputStream, int) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given input stream, which will have the specified number of bytes.

setBinaryStream(String, InputStream, long) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given input stream, which will have the specified number of bytes.

setBinaryStream(String, InputStream) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given input stream.

setBinaryStream(int, InputStream, int) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given input stream, which will have the specified number of bytes.

setBinaryStream(int, InputStream, long) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given input stream, which will have the specified number of bytes.

setBinaryStream(int, InputStream) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given input stream.

setBinaryStream() - Method in interface java.sql.SQLXML

Retrieves a stream that can be used to write the XML value that this SQLXML instance represents.

setBinaryStream(int, InputStream, int) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.io.InputStream object, which will have the specified number of bytes.

setBinaryStream(int, InputStream) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter in this RowSet object's command to the given input stream.

setBinaryStream(String, InputStream, int) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given input stream, which will have the specified number of bytes.

setBinaryStream(String, InputStream) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given input stream.

setBinaryStream(long) - Method in class javax.sql.rowset.serial.SerialBlob

Retrieves a stream that can be used to write to the BLOB value that this Blob object represents.

setBinaryStream(int, InputStream, int) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command to the given java.io.InputStream value.

setBinaryStream(String, InputStream, int) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given input stream, which will have the specified number of bytes.

setBinaryStream(int, InputStream) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command to the given input stream.

setBinaryStream(String, InputStream) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given input stream.

setBindings(Bindings, int) - Method in class javax.script.AbstractScriptEngine

Sets the Bindings with the corresponding scope value in the context field.

setBindings(Bindings, int) - Method in interface javax.script.ScriptContext

Associates a Bindings instance with a particular scope in this ScriptContext.

setBindings(Bindings, int) - Method in interface javax.script.ScriptEngine

Sets a scope of named values to be used by scripts.

setBindings(Bindings) - Method in class javax.script.ScriptEngineManager

setBindings stores the specified Bindings in the globalScope field.

setBindings(Bindings, int) - Method in class javax.script.SimpleScriptContext

Sets a Bindings of attributes for the given scope.

setBit(int) - Method in class java.math.BigInteger

Returns a BigInteger whose value is equivalent to this BigInteger with the designated bit set.

setBitOffset(int) - Method in interface javax.imageio.stream.ImageInputStream

Sets the bit offset to an integer between 0 and 7, inclusive.

setBitOffset(int) - Method in class javax.imageio.stream.ImageInputStreamImpl

setBlinkRate(int) - Method in interface javax.swing.text.Caret

Sets the blink rate of the caret.

setBlinkRate(int) - Method in class javax.swing.text.DefaultCaret

Sets the caret blink rate.

setBlob(String, InputStream, long) - Method in interface java.sql.CallableStatement

Sets the designated parameter to a InputStream object.

setBlob(String, Blob) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given java.sql.Blob object.

setBlob(String, InputStream) - Method in interface java.sql.CallableStatement

Sets the designated parameter to a InputStream object.

setBlob(int, Blob) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given java.sql.Blob object.

setBlob(int, InputStream, long) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to a InputStream object.

setBlob(int, InputStream) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to a InputStream object.

setBlob(int, Blob) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given Blob object in the Java programming language.

setBlob(int, InputStream, long) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to a InputStream object.

setBlob(int, InputStream) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to a InputStream object.

setBlob(String, InputStream, long) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to a InputStream object.

setBlob(String, Blob) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.sql.Blob object.

setBlob(String, InputStream) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to a InputStream object.

setBlob(int, Blob) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command with the given Blob value.

setBlob(int, InputStream, long) - Method in interface javax.sql.RowSet

Sets the designated parameter to a InputStream object.

setBlob(int, InputStream) - Method in interface javax.sql.RowSet

Sets the designated parameter to a InputStream object.

setBlob(String, InputStream, long) - Method in interface javax.sql.RowSet

Sets the designated parameter to a InputStream object.

setBlob(String, Blob) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given java.sql.Blob object.

setBlob(String, InputStream) - Method in interface javax.sql.RowSet

Sets the designated parameter to a InputStream object.

setBlockIncrement(int) - Method in interface java.awt.Adjustable

Sets the block value increment for the adjustable object.

setBlockIncrement(int) - Method in class java.awt.Scrollbar

Sets the block increment for this scroll bar.

setBlockIncrement(int) - Method in class java.awt.ScrollPaneAdjustable

setBlockIncrement(int) - Method in class javax.swing.JScrollBar

Sets the blockIncrement property.

setBlockIncrement(int) - Method in class javax.swing.JScrollPane.ScrollBar

Messages super to set the value, and resets the blockIncrementSet instance variable to true.

setBold(MutableAttributeSet, boolean) - Static method in class javax.swing.text.StyleConstants

Sets the bold attribute.

setBoolean(Object, int, boolean) - Static method in class java.lang.reflect.Array

Sets the value of the indexed component of the specified array object to the specified boolean value.

setBoolean(Object, boolean) - Method in class java.lang.reflect.字段

Sets the value of a field as a boolean on the specified object.

setBoolean(String, boolean) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given Java boolean value.

setBoolean(int, boolean) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given Java boolean value.

setBoolean(int, boolean) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given boolean in the Java programming language.

setBoolean(String, boolean) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given Java boolean value.

setBoolean(int, boolean) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command to the given Java boolean value.

setBoolean(String, boolean) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given Java boolean value.

setBorder(Border) - Method in class javax.swing.border.TitledBorder

Sets the border of the titled border.

setBorder(Border) - Method in class javax.swing.JComponent

Sets the border of this component.

setBorder(Border) - Method in class javax.swing.JLayer

A non-null border, or non-zero insets, isn't supported, to prevent the geometry of this component from becoming complex enough to inhibit subclassing of LayerUI class.

setBorder(Border) - Method in class javax.swing.JViewport

The viewport "scrolls" its child (called the "view") by the normal parent/child clipping (typically the view is moved in the opposite direction of the scroll).

setBorder(Border) - Method in class javax.swing.plaf.basic.BasicSplitPaneDivider

Sets the border of this component.

setBorder(Border) - Method in class javax.swing.tree.DefaultTreeCellEditor.DefaultTextField

Sets the border of this component.

setBorderColor(Color) - Method in class javax.swing.plaf.basic.BasicToolBarUI.DragWindow

setBorderPainted(boolean) - Method in class javax.swing.AbstractButton

Sets the borderPainted property.

setBorderPainted(boolean) - Method in class javax.swing.JMenuBar

Sets whether the border should be painted.

setBorderPainted(boolean) - Method in class javax.swing.JPopupMenu

Sets whether the border should be painted.

setBorderPainted(boolean) - Method in class javax.swing.JProgressBar

Sets the borderPainted property, which is true if the progress bar should paint its border.

setBorderPainted(boolean) - Method in class javax.swing.JToolBar

Sets the borderPainted property, which is true if the border should be painted.

setBorderPaintedFlat(boolean) - Method in class javax.swing.JCheckBox

Sets the borderPaintedFlat property, which gives a hint to the look and feel as to the appearance of the check box border.

setBorderSelectionColor(Color) - Method in class javax.swing.tree.DefaultTreeCellEditor

Sets the color to use for the border.

setBorderSelectionColor(Color) - Method in class javax.swing.tree.DefaultTreeCellRenderer

Sets the color to use for the border.

setBorderToNonRollover(Component) - Method in class javax.swing.plaf.basic.BasicToolBarUI

Sets the border of the component to have a non-rollover border which was created by the BasicToolBarUI.createNonRolloverBorder() method.

setBorderToNonRollover(Component) - Method in class javax.swing.plaf.metal.MetalToolBarUI

setBorderToNonRollover(Component) - Method in class javax.swing.plaf.synth.SynthToolBarUI

This implementation does nothing, because the rollover property of the JToolBar class is not used in the Synth Look and Feel.

setBorderToNormal(Component) - Method in class javax.swing.plaf.basic.BasicToolBarUI

Sets the border of the component to have a normal border.

setBorderToNormal(Component) - Method in class javax.swing.plaf.synth.SynthToolBarUI

This implementation does nothing, because the rollover property of the JToolBar class is not used in the Synth Look and Feel.

setBorderToRollover(Component) - Method in class javax.swing.plaf.basic.BasicToolBarUI

Sets the border of the component to have a rollover border which was created by the BasicToolBarUI.createRolloverBorder() method.

setBorderToRollover(Component) - Method in class javax.swing.plaf.synth.SynthToolBarUI

This implementation does nothing, because the rollover property of the JToolBar class is not used in the Synth Look and Feel.

setBottomComponent(Component) - Method in class javax.swing.JSplitPane

Sets the component below, or to the right of the divider.

setBottomInset(float) - Method in class javax.swing.text.AsyncBoxView

Set the bottom part of the margin around the view.

setBound(boolean) - Method in class java.beans.PropertyDescriptor

Updates to "bound" properties will cause a "PropertyChange" event to get fired when the property is changed.

setBounds(Rectangle) - Method in class java.awt.Component.AccessibleAWTComponent

Sets the bounds of this object in the form of a Rectangle object.

setBounds(int, int, int, int) - Method in class java.awt.Component

Moves and resizes this component.

setBounds(Rectangle) - Method in class java.awt.Component

Moves and resizes this component to conform to the new bounding rectangle r.

setBounds(Rectangle) - Method in class java.awt.List.AccessibleAWTList.AccessibleAWTListChild

Sets the bounds of this object in the form of a Rectangle object.

setBounds(Rectangle) - Method in class java.awt.MenuComponent.AccessibleAWTMenuComponent

Sets the bounds of this object in the form of a Rectangle object.

setBounds(Rectangle) - Method in class java.awt.Rectangle

Sets the bounding Rectangle of this Rectangle to match the specified Rectangle.

setBounds(int, int, int, int) - Method in class java.awt.Rectangle

Sets the bounding Rectangle of this Rectangle to the specified x, y, width, and height.

setBounds(int, int, int, int) - Method in class java.awt.Window

Moves and resizes this component.

setBounds(Rectangle) - Method in class java.awt.Window

Moves and resizes this component to conform to the new bounding rectangle r.

setBounds(Rectangle) - Method in interface javax.accessibility.AccessibleComponent

Sets the bounds of this object in the form of a Rectangle object.

setBounds(Rectangle) - Method in class javax.swing.JList.AccessibleJList.AccessibleJListChild

setBounds(Rectangle) - Method in class javax.swing.JTable.AccessibleJTable.AccessibleJTableCell

setBounds(Rectangle) - Method in class javax.swing.JTree.AccessibleJTree.AccessibleJTreeNode

setBounds(Rectangle) - Method in class javax.swing.table.JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry

setBoundsForFrame(JComponent, int, int, int, int) - Method in class javax.swing.DefaultDesktopManager

This moves the JComponent and repaints the damaged areas.

setBoundsForFrame(JComponent, int, int, int, int) - Method in interface javax.swing.DesktopManager

This is a primitive reshape method.

setBroadcast(boolean) - Method in class java.net.DatagramSocket

Enable/disable SO_BROADCAST.

setBuilder(DocumentBuilder) - Method in class javax.xml.bind.annotation.W3CDomHandler

setButtonIcons() - Method in class javax.swing.plaf.basic.BasicInternalFrameTitlePane

setByte(Object, int, byte) - Static method in class java.lang.reflect.Array

Sets the value of the indexed component of the specified array object to the specified byte value.

setByte(Object, byte) - Method in class java.lang.reflect.字段

Sets the value of a field as a byte on the specified object.

setByte(String, byte) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given Java byte value.

setByte(int, byte) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given Java byte value.

setByte(int, byte) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given byte in the Java programming language.

setByte(String, byte) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given Java byte value.

setByte(int, byte) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command to the given Java byte value.

setByte(String, byte) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given Java byte value.

setByteOrder(ByteOrder) - Method in interface javax.imageio.stream.ImageInputStream

Sets the desired byte order for future reads of data values from this stream.

setByteOrder(ByteOrder) - Method in class javax.imageio.stream.ImageInputStreamImpl

setBytes(long, byte[]) - Method in interface java.sql.Blob

Writes the given array of bytes to the BLOB value that this Blob object represents, starting at position pos, and returns the number of bytes written.

setBytes(long, byte[], int, int) - Method in interface java.sql.Blob

Writes all or part of the given byte array to the BLOB value that this Blob object represents and returns the number of bytes written.

setBytes(String, byte[]) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given Java array of bytes.

setBytes(int, byte[]) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given Java array of bytes.

setBytes(int, byte[]) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given array of bytes.

setBytes(String, byte[]) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given Java array of bytes.

setBytes(long, byte[]) - Method in class javax.sql.rowset.serial.SerialBlob

Writes the given array of bytes to the BLOB value that this Blob object represents, starting at position pos, and returns the number of bytes written.

setBytes(long, byte[], int, int) - Method in class javax.sql.rowset.serial.SerialBlob

Writes all or part of the given byte array to the BLOB value that this Blob object represents and returns the number of bytes written.

setBytes(int, byte[]) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command to the given Java array of byte values.

setBytes(String, byte[]) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given Java array of bytes.

setByteStream(InputStream) - Method in interface org.w3c.dom.ls.LSInput

An attribute of a language and binding dependent type that represents a stream of bytes.

setByteStream(OutputStream) - Method in interface org.w3c.dom.ls.LSOutput

An attribute of a language and binding dependent type that represents a writable stream of bytes.

setByteStream(InputStream) - Method in class org.xml.sax.InputSource

Set the byte stream for this input source.

setCacheDirectory(File) - Static method in class javax.imageio.ImageIO

Sets the directory where cache files are to be created.

setCalendar(Calendar) - Method in class java.text.DateFormat

Set the calendar to be used by this date format.

setCalendarField(int) - Method in class javax.swing.SpinnerDateModel

Changes the size of the date value change computed by the nextValue and previousValue methods.

setCallbackHandler(CallbackHandler) - Method in class java.security.AuthProvider

Set a CallbackHandler.

setCanWrapLines(boolean) - Method in class javax.swing.text.AbstractWriter

Sets whether or not lines can be wrapped.

setCaret(Caret) - Method in class javax.swing.text.JTextComponent

Sets the caret to be used.

setCaretColor(Color) - Method in class javax.swing.text.JTextComponent

Sets the current color used to render the caret.

setCaretPosition(int) - Method in class java.awt.TextComponent

Sets the position of the text insertion caret.

setCaretPosition(int) - Method in class javax.swing.text.JTextComponent

Sets the position of the text insertion caret for the TextComponent.

setCaseSensitive(int, boolean) - Method in class javax.sql.rowset.RowSetMetaDataImpl

Sets whether the name of the designated column is case sensitive to the given boolean.

setCaseSensitive(int, boolean) - Method in interface javax.sql.RowSetMetaData

Sets whether the designated column is case sensitive.

setCatalog(String) - Method in interface java.sql.Connection

Sets the given catalog name in order to select a subspace of this Connection object's database in which to work.

setCatalogName(int, String) - Method in class javax.sql.rowset.RowSetMetaDataImpl

Sets the catalog name of the table from which the designated column was derived to catalogName.

setCatalogName(int, String) - Method in interface javax.sql.RowSetMetaData

Sets the designated column's table's catalog name, if any, to the given String.

setCellEditor(TableCellEditor) - Method in class javax.swing.JTable

Sets the active cell editor.

setCellEditor(TreeCellEditor) - Method in class javax.swing.JTree

Sets the cell editor.

setCellEditor(TreeCellEditor) - Method in class javax.swing.plaf.basic.BasicTreeUI

Sets the cell editor.

setCellEditor(TableCellEditor) - Method in class javax.swing.table.TableColumn

Sets the editor to used by when a cell in this column is edited.

setCellLength(int) - Method in class javax.swing.plaf.basic.BasicProgressBarUI

setCellRenderer(ListCellRenderer<? super E>) - Method in class javax.swing.JList

Sets the delegate that is used to paint each cell in the list.

setCellRenderer(TreeCellRenderer) - Method in class javax.swing.JTree

Sets the TreeCellRenderer that will be used to draw each cell.

setCellRenderer(TreeCellRenderer) - Method in class javax.swing.plaf.basic.BasicTreeUI

Sets the TreeCellRenderer to tcr.

setCellRenderer(TableCellRenderer) - Method in class javax.swing.table.TableColumn

Sets the TableCellRenderer used by JTable to draw individual values for this column.

setCellSelectionEnabled(boolean) - Method in class javax.swing.JTable

Sets whether this table allows both a column selection and a row selection to exist simultaneously.

setCellSpacing(int) - Method in class javax.swing.plaf.basic.BasicProgressBarUI

setCentersChildren(boolean) - Method in class javax.swing.plaf.basic.BasicOptionPaneUI.ButtonAreaLayout

setCertificate(X509Certificate) - Method in class java.security.cert.X509CertSelector

Sets the certificateEquals criterion.

setCertificateChecking(X509Certificate) - Method in class java.security.cert.X509CRLSelector

Sets the certificate being checked.

setCertificateEntry(String, Certificate) - Method in class java.security.KeyStore

Assigns the given trusted certificate to the given alias.

setCertificateValid(Date) - Method in class java.security.cert.X509CertSelector

Sets the certificateValid criterion.

setCertifiedText(boolean) - Method in interface org.w3c.dom.ls.LSInput

If set to true, assume that the input is certified (see section 2.13 in [XML 1.1]) when parsing [XML 1.1].

setCertPathCheckers(List<PKIXCertPathChecker>) - Method in class java.security.cert.PKIXParameters

Sets a List of additional certification path checkers.

setCertStores(List<CertStore>) - Method in class java.security.cert.PKIXParameters

Sets the list of CertStores to be used in finding certificates and CRLs.

setChanged() - Method in class java.util.Observable

Marks this Observable object as having been changed; the hasChanged method will now return true.

setChannelBinding(ChannelBinding) - Method in interface org.ietf.jgss.GSSContext

Sets the channel bindings to be used during context establishment.

setChannelPressure(int) - Method in interface javax.sound.midi.MidiChannel

Reacts to a change in the keyboard pressure.

setChar(Object, int, char) - Static method in class java.lang.reflect.Array

Sets the value of the indexed component of the specified array object to the specified char value.

setChar(Object, char) - Method in class java.lang.reflect.字段

Sets the value of a field as a char on the specified object.

setCharacterAttributes(AttributeSet, boolean) - Method in class javax.swing.JTextPane

Applies the given attributes to character content.

setCharacterAttributes(int, int, AttributeSet, boolean) - Method in class javax.swing.text.DefaultStyledDocument

Sets attributes for some part of the document.

setCharacterAttributes(int, int, AttributeSet, boolean) - Method in interface javax.swing.text.StyledDocument

Changes the content element attributes used for the given range of existing content in the document.

setCharacterAttributes(JEditorPane, AttributeSet, boolean) - Method in class javax.swing.text.StyledEditorKit.StyledTextAction

Applies the given attributes to character content.

setCharacterStream(String, Reader, int) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given Reader object, which is the given number of characters long.

setCharacterStream(String, Reader, long) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given Reader object, which is the given number of characters long.

setCharacterStream(String, Reader) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given Reader object.

setCharacterStream(long) - Method in interface java.sql.Clob

Retrieves a stream to be used to write a stream of Unicode characters to the CLOB value that this Clob object represents, at position pos.

setCharacterStream(int, Reader, int) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given Reader object, which is the given number of characters long.

setCharacterStream(int, Reader, long) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given Reader object, which is the given number of characters long.

setCharacterStream(int, Reader) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given Reader object.

setCharacterStream() - Method in interface java.sql.SQLXML

Retrieves a stream to be used to write the XML value that this SQLXML instance represents.

setCharacterStream(int, Reader, int) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.io.Reader object, which will have the specified number of characters.

setCharacterStream(int, Reader) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter in this RowSet object's command to the given Reader object.

setCharacterStream(String, Reader, int) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given Reader object, which is the given number of characters long.

setCharacterStream(String, Reader) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given Reader object.

setCharacterStream(long) - Method in class javax.sql.rowset.serial.SerialClob

Retrieves a stream to be used to write a stream of Unicode characters to the CLOB value that this SerialClob object represents, at position pos.

setCharacterStream(int, Reader, int) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command to the given java.io.Reader value.

setCharacterStream(String, Reader, int) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given Reader object, which is the given number of characters long.

setCharacterStream(int, Reader) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command to the given Reader object.

setCharacterStream(String, Reader) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given Reader object.

setCharacterStream(Reader) - Method in interface org.w3c.dom.ls.LSInput

An attribute of a language and binding dependent type that represents a stream of 16-bit units.

setCharacterStream(Writer) - Method in interface org.w3c.dom.ls.LSOutput

An attribute of a language and binding dependent type that represents a writable stream to which 16-bit units can be output.

setCharacterStream(Reader) - Method in class org.xml.sax.InputSource

Set the character stream for this input source.

setCharacterSubsets(Character.Subset[]) - Method in class java.awt.im.InputContext

Sets the subsets of the Unicode character set that input methods of this input context should be allowed to input.

setCharacterSubsets(Character.Subset[]) - Method in interface java.awt.im.spi.InputMethod

Sets the subsets of the Unicode character set that this input method is allowed to input.

setCharAt(int, char) - Method in class java.lang.StringBuffer

setCheckboxGroup(CheckboxGroup) - Method in class java.awt.Checkbox

Sets this check box's group to the specified check box group.

setChoices(double[], String[]) - Method in class java.text.ChoiceFormat

Set the choices to be used in formatting.

setChooserPanels(AbstractColorChooserPanel[]) - Method in class javax.swing.JColorChooser

Specifies the Color Panels used to choose a color value.

setChunkedStreamingMode(int) - Method in class java.net.HttpURLConnection

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is not known in advance.

setCipherSuites(String[]) - Method in class javax.net.ssl.SSLParameters

Sets the array of ciphersuites.

setClassAssertionStatus(String, boolean) - Method in class java.lang.ClassLoader

Sets the desired assertion status for the named top-level class in this class loader and any nested classes contained therein.

setClassName(String) - Method in class javax.naming.NameClassPair

Sets the class name of this binding.

setClickCountToStart(int) - Method in class javax.swing.DefaultCellEditor

Specifies the number of clicks needed to start editing.

setClientInfo(String, String) - Method in interface java.sql.Connection

Sets the value of the client info property specified by name to the value specified by value.

setClientInfo(Properties) - Method in interface java.sql.Connection

Sets the value of the connection's client info properties.

setClip(int, int, int, int) - Method in class java.awt.Graphics

Sets the current clip to the rectangle specified by the given coordinates.

setClip(Shape) - Method in class java.awt.Graphics

Sets the current clipping area to an arbitrary clip shape.

setClip(int, int, int, int) - Method in class javax.swing.DebugGraphics

Overrides Graphics.setClip.

setClip(Shape) - Method in class javax.swing.DebugGraphics

Overrides Graphics.setClip.

setClob(String, Reader, long) - Method in interface java.sql.CallableStatement

Sets the designated parameter to a Reader object.

setClob(String, Clob) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given java.sql.Clob object.

setClob(String, Reader) - Method in interface java.sql.CallableStatement

Sets the designated parameter to a Reader object.

setClob(int, Clob) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given java.sql.Clob object.

setClob(int, Reader, long) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to a Reader object.

setClob(int, Reader) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to a Reader object.

setClob(int, Clob) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given Clob object in the Java programming language.

setClob(int, Reader, long) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to a Reader object.

setClob(int, Reader) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to a Reader object.

setClob(String, Reader, long) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to a Reader object.

setClob(String, Clob) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.sql.Clob object.

setClob(String, Reader) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to a Reader object.

setClob(int, Clob) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command with the given Clob value.

setClob(int, Reader, long) - Method in interface javax.sql.RowSet

Sets the designated parameter to a Reader object.

setClob(int, Reader) - Method in interface javax.sql.RowSet

Sets the designated parameter to a Reader object.

setClob(String, Reader, long) - Method in interface javax.sql.RowSet

Sets the designated parameter to a Reader object.

setClob(String, Clob) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given java.sql.Clob object.

setClob(String, Reader) - Method in interface javax.sql.RowSet

Sets the designated parameter to a Reader object.

setClosable(boolean) - Method in class javax.swing.JInternalFrame

Sets whether this JInternalFrame can be closed by some user action.

setClosed(boolean) - Method in class javax.swing.JInternalFrame

Closes this internal frame if the argument is true.

setClosedIcon(Icon) - Method in class javax.swing.tree.DefaultTreeCellRenderer

Sets the icon used to represent non-leaf nodes that are not expanded.

setCoalesce(boolean) - Method in class javax.swing.Timer

Sets whether the Timer coalesces multiple pending ActionEvent firings.

setCoalescing(boolean) - Method in class javax.xml.parsers.DocumentBuilderFactory

Specifies that the parser produced by this code will convert CDATA nodes to Text nodes and append it to the adjacent (if any) text node.

setCollapsedIcon(Icon) - Method in class javax.swing.plaf.basic.BasicTreeUI

setCollectionUsageThreshold(long) - Method in interface java.lang.management.MemoryPoolMXBean

Sets the collection usage threshold of this memory pool to the given threshold value.

setColor(Color) - Method in class java.awt.Graphics

Sets this graphics context's current color to the specified color.

setColor(PageAttributes.ColorType) - Method in class java.awt.PageAttributes

Specifies whether pages using these attributes will be rendered in color or monochrome.

setColor(Color) - Method in class javax.swing.DebugGraphics

Sets the color to be used for drawing and filling lines and shapes.

setColor(Color) - Method in class javax.swing.JColorChooser

Sets the current color of the color chooser to the specified color.

setColor(int, int, int) - Method in class javax.swing.JColorChooser

Sets the current color of the color chooser to the specified RGB color.

setColor(int) - Method in class javax.swing.JColorChooser

Sets the current color of the color chooser to the specified color.

setColorModel(ColorModel) - Method in class java.awt.image.BufferedImageFilter

Filters the information provided in the setColorModel method of the ImageConsumer interface.

setColorModel(ColorModel) - Method in interface java.awt.image.ImageConsumer

Sets the ColorModel object used for the majority of the pixels reported using the setPixels method calls.

setColorModel(ColorModel) - Method in class java.awt.image.ImageFilter

Filter the information provided in the setColorModel method of the ImageConsumer interface.

setColorModel(ColorModel) - Method in class java.awt.image.PixelGrabber

The setColorModel method is part of the ImageConsumer API which this class must implement to retrieve the pixels.

setColorModel(ColorModel) - Method in class java.awt.image.RGBImageFilter

If the ColorModel is an IndexColorModel and the subclass has set the canFilterIndexColorModel flag to true, we substitute a filtered version of the color model here and wherever that original ColorModel object appears in the setPixels methods.

setColumnCount(int) - Method in class javax.sql.rowset.RowSetMetaDataImpl

Sets to the given number the number of columns in the RowSet object for which this RowSetMetaDataImpl object was created.

setColumnCount(int) - Method in interface javax.sql.RowSetMetaData

Sets the number of columns in the RowSet object to the given number.

setColumnCount(int) - Method in class javax.swing.table.DefaultTableModel

Sets the number of columns in the model.

setColumnDisplaySize(int, int) - Method in class javax.sql.rowset.RowSetMetaDataImpl

Sets the normal maximum number of chars in the designated column to the given number.

setColumnDisplaySize(int, int) - Method in interface javax.sql.RowSetMetaData

Sets the designated column's normal maximum width in chars to the given int.

setColumnHeader(JViewport) - Method in class javax.swing.JScrollPane

Removes the old columnHeader, if it exists; if the new columnHeader isn't null, syncs the x coordinate of its viewPosition with the viewport (if there is one) and then adds it to the scroll pane.

setColumnHeaderView(Component) - Method in class javax.swing.JScrollPane

Creates a column-header viewport if necessary, sets its view, and then adds the column-header viewport to the scrollpane.

setColumnIdentifiers(Vector) - Method in class javax.swing.table.DefaultTableModel

Replaces the column identifiers in the model.

setColumnIdentifiers(Object[]) - Method in class javax.swing.table.DefaultTableModel

Replaces the column identifiers in the model.

setColumnLabel(int, String) - Method in class javax.sql.rowset.RowSetMetaDataImpl

Sets the suggested column label for use in printouts and displays, if any, to label.

setColumnLabel(int, String) - Method in interface javax.sql.RowSetMetaData

Sets the suggested column title for use in printouts and displays, if any, to the given String.

setColumnMargin(int) - Method in class javax.swing.table.DefaultTableColumnModel

Sets the column margin to newMargin.

setColumnMargin(int) - Method in interface javax.swing.table.TableColumnModel

Sets the TableColumn's column margin to newMargin.

setColumnModel(TableColumnModel) - Method in class javax.swing.JTable

Sets the column model for this table to newModel and registers for listener notifications from the new column model.

setColumnModel(TableColumnModel) - Method in class javax.swing.table.JTableHeader

Sets the column model for this table to newModel and registers for listener notifications from the new column model.

setColumnName(int, String) - Method in class javax.sql.rowset.RowSetMetaDataImpl

Sets the column name of the designated column to the given name.

setColumnName(int, String) - Method in interface javax.sql.RowSetMetaData

Sets the name of the designated column to the given String.

setColumnNumber(int) - Method in class javax.xml.bind.helpers.ValidationEventLocatorImpl

Set the columnNumber field on this event locator.

setColumnNumber(int) - Method in class org.xml.sax.helpers.LocatorImpl

Set the column number for this locator (1-based).

setColumns(int) - Method in class java.awt.GridLayout

Sets the number of columns in this layout to the specified value.

setColumns(int) - Method in class java.awt.TextArea

Sets the number of columns for this text area.

setColumns(int) - Method in class java.awt.TextField

Sets the number of columns in this text field.

setColumns(int) - Method in class javax.swing.JTextArea

Sets the number of columns for this TextArea.

setColumns(int) - Method in class javax.swing.JTextField

Sets the number of columns in this TextField, and then invalidate the layout.

setColumnSelectionAllowed(boolean) - Method in class javax.swing.JTable

Sets whether the columns in this model can be selected.

setColumnSelectionAllowed(boolean) - Method in class javax.swing.table.DefaultTableColumnModel

Sets whether column selection is allowed.

setColumnSelectionAllowed(boolean) - Method in interface javax.swing.table.TableColumnModel

Sets whether the columns in this model may be selected.

setColumnSelectionInterval(int, int) - Method in class javax.swing.JTable

Selects the columns from index0 to index1, inclusive.

setColumnType(int, int) - Method in class javax.sql.rowset.RowSetMetaDataImpl

Sets the SQL type code for values stored in the designated column to the given type code from the class java.sql.Types.

setColumnType(int, int) - Method in interface javax.sql.RowSetMetaData

Sets the designated column's SQL type to the one given.

setColumnTypeName(int, String) - Method in class javax.sql.rowset.RowSetMetaDataImpl

Sets the type name used by the data source for values stored in the designated column to the given type name.

setColumnTypeName(int, String) - Method in interface javax.sql.RowSetMetaData

Sets the designated column's type name that is specific to the data source, if any, to the given String.

setComboBox(JComboBox) - Method in class javax.swing.plaf.metal.MetalComboBoxButton

setComboIcon(Icon) - Method in class javax.swing.plaf.metal.MetalComboBoxButton

setCommand(String) - Method in class javax.sql.rowset.BaseRowSet

Sets this RowSet object's command property to the given String object and clears the parameters, if any, that were set for the previous command.

setCommand(String) - Method in interface javax.sql.RowSet

Sets this RowSet object's command property to the given SQL query.

setCommandContext(String, DataHandler) - Method in interface javax.activation.CommandObject

Initialize the Command with the verb it is requested to handle and the DataHandler that describes the data it will operate on.

setCommandMap(CommandMap) - Method in class javax.activation.DataHandler

Set the CommandMap for use by this DataHandler.

setComment(String) - Method in class java.net.HttpCookie

Specifies a comment that describes a cookie's purpose.

setComment(String) - Method in class java.util.zip.ZipEntry

Sets the optional comment string for the entry.

setComment(String) - Method in class java.util.zip.ZipOutputStream

Sets the ZIP file comment.

setCommentURL(String) - Method in class java.net.HttpCookie

Specifies a comment url that describes a cookie's purpose.

setCommitsOnValidEdit(boolean) - Method in class javax.swing.text.DefaultFormatter

Sets when edits are published back to the JFormattedTextField.

setComparator(int, Comparator<?>) - Method in class javax.swing.DefaultRowSorter

Sets the Comparator to use when sorting the specified column.

setComparator(Comparator<? super Component>) - Method in class javax.swing.SortingFocusTraversalPolicy

Sets the Comparator which will be used to sort the Components in a focus traversal cycle.

setComponent(Component) - Method in class java.awt.dnd.DragGestureRecognizer

set the Component that the DragGestureRecognizer is associated with registerListeners() and unregisterListeners() are called as a side effect as appropriate.

setComponent(Component) - Method in class java.awt.dnd.DropTarget

Note: this interface is required to permit the safe association of a DropTarget with a Component in one of two ways, either: component.setDropTarget(droptarget); or droptarget.setComponent(component);

setComponent(JComponent) - Method in class javax.swing.JToolTip

Specifies the component that the tooltip describes.

setComponent(MutableAttributeSet, Component) - Static method in class javax.swing.text.StyleConstants

Sets the component attribute.

setComponentAt(int, Component) - Method in class javax.swing.JTabbedPane

Sets the component at index to component.

setComponentOrientation(ComponentOrientation) - Method in class java.awt.Component

Sets the language-sensitive orientation that is to be used to order the elements or text within this component.

setComponentOrientation(ComponentOrientation) - Method in class javax.swing.JMenu

setComponentOrientation(ComponentOrientation) - Method in class javax.swing.JScrollPane

Sets the orientation for the vertical and horizontal scrollbars as determined by the ComponentOrientation argument.

setComponentOrientation(ComponentOrientation) - Method in class javax.swing.text.JTextComponent

setComponentPopupMenu(JPopupMenu) - Method in class javax.swing.JComponent

Sets the JPopupMenu for this JComponent.

setComponentToSize(Component, int, int, Insets, Dimension) - Method in class javax.swing.plaf.basic.BasicSplitPaneUI.BasicHorizontalLayoutManager

Sets the width of the component c to be size, placing its x location at location, y to the insets.top and height to the containersize.height less the top and bottom insets.

setComponentZOrder(Component, int) - Method in class java.awt.Container

Moves the specified component to the specified z-order index in the container.

setComponentZOrder(Component, int) - Method in class javax.swing.JDesktopPane

Moves the specified component to the specified z-order index in the container.

setComposite(Composite) - Method in class java.awt.Graphics2D

Sets the Composite for the Graphics2D context.

setCompositionEnabled(boolean) - Method in class java.awt.im.InputContext

Enables or disables the current input method for composition, depending on the value of the parameter enable.

setCompositionEnabled(boolean) - Method in interface java.awt.im.spi.InputMethod

Enables or disables this input method for composition, depending on the value of the parameter enable.

setCompressedSize(long) - Method in class java.util.zip.ZipEntry

Sets the size of the compressed entry data.

setCompressionMode(int) - Method in class javax.imageio.ImageWriteParam

Specifies whether compression is to be performed, and if so how compression parameters are to be determined.

setCompressionQuality(float) - Method in class javax.imageio.ImageWriteParam

Sets the compression quality to a value between 0 and 1.

setCompressionType(String) - Method in class javax.imageio.ImageWriteParam

Sets the compression type to one of the values indicated by getCompressionTypes.

setConcurrency(int) - Method in class javax.sql.rowset.BaseRowSet

Sets the concurrency for this RowSet object to the specified concurrency.

setConcurrency(int) - Method in interface javax.sql.RowSet

Sets the concurrency of this RowSet object to the given concurrency level.

setConfiguration(Configuration) - Static method in class javax.security.auth.login.Configuration

Set the login Configuration.

setConnectTimeout(int) - Method in class java.net.URLConnection

Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection.

setConstrained(boolean) - Method in class java.beans.PropertyDescriptor

Attempted updates to "Constrained" properties will cause a "VetoableChange" event to get fired when the property is changed.

setConstraint(String, Spring) - Method in class javax.swing.SpringLayout.Constraints

Sets the spring controlling the specified edge.

setConstraints(Component, GridBagConstraints) - Method in class java.awt.GridBagLayout

Sets the constraints for the specified component in this layout.

setContent(Object, String) - Method in class javax.xml.soap.AttachmentPart

Sets the content of this attachment part to that of the given Object and sets the value of the Content-Type header to the given type.

setContent(Source) - Method in class javax.xml.soap.SOAPPart

Sets the content of the SOAPEnvelope object with the data from the given Source object.

setContentAreaFilled(boolean) - Method in class javax.swing.AbstractButton

Sets the contentAreaFilled property.

setContentDescription(String) - Method in class javax.xml.soap.SOAPMessage

Sets the description of this SOAPMessage object's content with the given description.

setContentHandler(ContentHandler) - Method in class javax.xml.validation.ValidatorHandler

Sets the ContentHandler which receives the augmented validation result.

setContentHandler(ContentHandler) - Method in class org.xml.sax.helpers.ParserAdapter

Set the content handler.

setContentHandler(ContentHandler) - Method in class org.xml.sax.helpers.XMLFilterImpl

Set the content event handler.

setContentHandler(ContentHandler) - Method in interface org.xml.sax.XMLReader

Allow an application to register a content event handler.

setContentHandlerFactory(ContentHandlerFactory) - Static method in class java.net.URLConnection

Sets the ContentHandlerFactory of an application.

setContentId(String) - Method in class javax.xml.soap.AttachmentPart

Sets the MIME header whose name is "Content-ID" with the given value.

setContentId(String) - Method in class javax.xml.soap.SOAPPart

Sets the value of the MIME header named "Content-Id" to the given String.

setContentLocation(String) - Method in class javax.xml.soap.AttachmentPart

Sets the MIME header whose name is "Content-Location" with the given value.

setContentLocation(String) - Method in class javax.xml.soap.SOAPPart

Sets the value of the MIME header "Content-Location" to the given String.

setContentPane(Container) - Method in class javax.swing.JApplet

Sets the contentPane property.

setContentPane(Container) - Method in class javax.swing.JDialog

Sets the contentPane property.

setContentPane(Container) - Method in class javax.swing.JFrame

Sets the contentPane property.

setContentPane(Container) - Method in class javax.swing.JInternalFrame

Sets this JInternalFrame's contentPane property.

setContentPane(Container) - Method in class javax.swing.JRootPane

Sets the content pane -- the container that holds the components parented by the root pane.

setContentPane(Container) - Method in class javax.swing.JWindow

Sets the contentPane property for this window.

setContentPane(Container) - Method in interface javax.swing.RootPaneContainer

The "contentPane" is the primary container for application specific components.

setContents(Transferable, ClipboardOwner) - Method in class java.awt.datatransfer.Clipboard

Sets the current contents of the clipboard to the specified transferable object and registers the specified clipboard owner as the owner of the new contents.

setContentType(String) - Method in class javax.swing.JEditorPane

Sets the type of content that this editor handles.

setContentType(String) - Method in class javax.xml.soap.AttachmentPart

Sets the MIME header whose name is "Content-Type" with the given value.

setContext(ScriptContext) - Method in class javax.script.AbstractScriptEngine

Sets the value of the protected context field to the specified ScriptContext.

setContext(ScriptContext) - Method in interface javax.script.ScriptEngine

Sets the default ScriptContext of the ScriptEngine whose Bindings, Reader and Writers are used for script executions when no ScriptContext is specified.

setContextClassLoader(ClassLoader) - Method in class java.lang.Thread

Sets the context ClassLoader for this Thread.

setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean) - Method in class java.util.concurrent.ScheduledThreadPoolExecutor

Sets the policy on whether to continue executing existing periodic tasks even when this executor has been shutdown.

setContinuousLayout(boolean) - Method in class javax.swing.JSplitPane

Sets the value of the continuousLayout property, which must be true for the child components to be continuously redisplayed and laid out during user intervention.

setContinuousLayout(boolean) - Method in class javax.swing.plaf.basic.BasicSplitPaneUI

Turn continuous layout on/off.

setControlButtonsAreShown(boolean) - Method in class javax.swing.JFileChooser

Sets the property that indicates whether the approve and cancel buttons are shown in the file chooser.

setController(IIOParamController) - Method in class javax.imageio.IIOParam

Sets the IIOParamController to be used to provide settings for this IIOParam object when the activateController method is called, overriding any default controller.

setController(IIOMetadataController) - Method in class javax.imageio.metadata.IIOMetadata

Sets the IIOMetadataController to be used to provide settings for this IIOMetadata object when the activateController method is called, overriding any default controller.

setCookiePolicy(CookiePolicy) - Method in class java.net.CookieManager

To set the cookie policy of this cookie manager.

setCopies(int) - Method in class java.awt.JobAttributes

Specifies the number of copies the application should render for jobs using these attributes.

setCopies(int) - Method in class java.awt.print.PrinterJob

Sets the number of copies to be printed.

setCopiesToDefault() - Method in class java.awt.JobAttributes

Sets the number of copies the application should render for jobs using these attributes to the default.

setCorePoolSize(int) - Method in class java.util.concurrent.ThreadPoolExecutor

Sets the core number of threads.

setCorner(String, Component) - Method in class javax.swing.JScrollPane

Adds a child that will appear in one of the scroll panes corners, if there's room.

setCountLimit(long) - Method in class javax.naming.directory.SearchControls

Sets the maximum number of entries to be returned as a result of the search.

setCrc(long) - Method in class java.util.zip.ZipEntry

Sets the CRC-32 checksum of the uncompressed entry data.

setCurrency(Currency) - Method in class java.text.DecimalFormat

Sets the currency used by this number format when formatting currency values.

setCurrency(Currency) - Method in class java.text.DecimalFormatSymbols

Sets the currency of these DecimalFormatSymbols.

setCurrency(Currency) - Method in class java.text.NumberFormat

Sets the currency used by this number format when formatting currency values.

setCurrency(int, boolean) - Method in class javax.sql.rowset.RowSetMetaDataImpl

Sets whether a value stored in the designated column is a cash value to the given boolean.

setCurrency(int, boolean) - Method in interface javax.sql.RowSetMetaData

Sets whether the designated column is a cash value.

setCurrencySymbol(String) - Method in class java.text.DecimalFormatSymbols

Sets the currency symbol for the currency of these DecimalFormatSymbols in their locale.

setCurrent(Checkbox) - Method in class java.awt.CheckboxGroup

Deprecated.
As of JDK version 1.1, replaced by setSelectedCheckbox(Checkbox).

setCurrentAccessibleValue(Number) - Method in class java.awt.Button.AccessibleAWTButton

Set the value of this object as a Number.

setCurrentAccessibleValue(Number) - Method in class java.awt.Checkbox.AccessibleAWTCheckbox

Set the value of this object as a Number.

setCurrentAccessibleValue(Number) - Method in class java.awt.CheckboxMenuItem.AccessibleAWTCheckboxMenuItem

Set the value of this object as a Number.

setCurrentAccessibleValue(Number) - Method in class java.awt.MenuItem.AccessibleAWTMenuItem

Set the value of this object as a Number.

setCurrentAccessibleValue(Number) - Method in class java.awt.Scrollbar.AccessibleAWTScrollBar

Set the value of this object as a Number.

setCurrentAccessibleValue(Number) - Method in interface javax.accessibility.AccessibleValue

Set the value of this object as a Number.

setCurrentAccessibleValue(Number) - Method in class javax.swing.AbstractButton.AccessibleAbstractButton

Set the value of this object as a Number.

setCurrentAccessibleValue(Number) - Method in class javax.swing.JInternalFrame.AccessibleJInternalFrame

Set the value of this object as a Number.

setCurrentAccessibleValue(Number) - Method in class javax.swing.JInternalFrame.JDesktopIcon.AccessibleJDesktopIcon

Sets the value of this object as a Number.

setCurrentAccessibleValue(Number) - Method in class javax.swing.JProgressBar.AccessibleJProgressBar

Sets the value of this object as a Number.

setCurrentAccessibleValue(Number) - Method in class javax.swing.JScrollBar.AccessibleJScrollBar

Set the value of this object as a Number.

setCurrentAccessibleValue(Number) - Method in class javax.swing.JSlider.AccessibleJSlider

Set the value of this object as a Number.

setCurrentAccessibleValue(Number) - Method in class javax.swing.JSpinner.AccessibleJSpinner

Set the value of this object as a Number.

setCurrentAccessibleValue(Number) - Method in class javax.swing.JSplitPane.AccessibleJSplitPane

Sets the value of this object as a Number.

setCurrentDirectory(File) - Method in class javax.swing.JFileChooser

Sets the current directory.

setCurrentKeyboardFocusManager(KeyboardFocusManager) - Static method in class java.awt.KeyboardFocusManager

Sets the current KeyboardFocusManager instance for the calling thread's context.

setCurrentLineLength(int) - Method in class javax.swing.text.AbstractWriter

Sets the current line length.

setCurrentManager(FocusManager) - Static method in class javax.swing.FocusManager

Sets the current KeyboardFocusManager instance for the calling thread's context.

setCurrentManager(RepaintManager) - Static method in class javax.swing.RepaintManager

Set the RepaintManager that should be used for the calling thread.

setCurrentTheme(MetalTheme) - Static method in class javax.swing.plaf.metal.MetalLookAndFeel

Set the theme used by MetalLookAndFeel.

setCursor(Cursor) - Method in class java.awt.Component.AccessibleAWTComponent

Sets the Cursor of this object.

setCursor(Cursor) - Method in class java.awt.Component

Sets the cursor image to the specified cursor.

setCursor(Cursor) - Method in class java.awt.dnd.DragSourceContext

Sets the cursor for this drag operation to the specified Cursor.

setCursor(int) - Method in class java.awt.Frame

Deprecated.
As of JDK version 1.1, replaced by Component.setCursor(Cursor).

setCursor(Cursor) - Method in class java.awt.List.AccessibleAWTList.AccessibleAWTListChild

Set the Cursor of this object.

setCursor(Cursor) - Method in class java.awt.MenuComponent.AccessibleAWTMenuComponent

Sets the Cursor of this object.

setCursor(Cursor) - Method in class java.awt.Window

Set the cursor image to a specified cursor.

setCursor(Cursor) - Method in interface javax.accessibility.AccessibleComponent

Sets the Cursor of this object.

setCursor(Cursor) - Method in class javax.swing.JInternalFrame

Sets the cursor image to the specified cursor.

setCursor(Cursor) - Method in class javax.swing.JList.AccessibleJList.AccessibleJListChild

setCursor(Cursor) - Method in class javax.swing.JTable.AccessibleJTable.AccessibleJTableCell

Sets the Cursor of this object.

setCursor(Cursor) - Method in class javax.swing.JTree.AccessibleJTree.AccessibleJTreeNode

setCursor(Cursor) - Method in class javax.swing.table.JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry

setCursorName(String) - Method in interface java.sql.Statement

Sets the SQL cursor name to the given String, which will be used by subsequent Statement object execute methods.

setCurve(double, double, double, double, double, double, double, double) - Method in class java.awt.geom.CubicCurve2D.Double

Sets the location of the end points and control points of this curve to the specified double coordinates.

setCurve(double, double, double, double, double, double, double, double) - Method in class java.awt.geom.CubicCurve2D.Float

Sets the location of the end points and control points of this curve to the specified double coordinates.

setCurve(float, float, float, float, float, float, float, float) - Method in class java.awt.geom.CubicCurve2D.Float

Sets the location of the end points and control points of this curve to the specified float coordinates.

setCurve(double, double, double, double, double, double, double, double) - Method in class java.awt.geom.CubicCurve2D

Sets the location of the end points and control points of this curve to the specified double coordinates.

setCurve(double[], int) - Method in class java.awt.geom.CubicCurve2D

Sets the location of the end points and control points of this curve to the double coordinates at the specified offset in the specified array.

setCurve(Point2D, Point2D, Point2D, Point2D) - Method in class java.awt.geom.CubicCurve2D

Sets the location of the end points and control points of this curve to the specified Point2D coordinates.

setCurve(Point2D[], int) - Method in class java.awt.geom.CubicCurve2D

Sets the location of the end points and control points of this curve to the coordinates of the Point2D objects at the specified offset in the specified array.

setCurve(CubicCurve2D) - Method in class java.awt.geom.CubicCurve2D

Sets the location of the end points and control points of this curve to the same as those in the specified CubicCurve2D.

setCurve(double, double, double, double, double, double) - Method in class java.awt.geom.QuadCurve2D.Double

Sets the location of the end points and control point of this curve to the specified double coordinates.

setCurve(double, double, double, double, double, double) - Method in class java.awt.geom.QuadCurve2D.Float

Sets the location of the end points and control point of this curve to the specified double coordinates.

setCurve(float, float, float, float, float, float) - Method in class java.awt.geom.QuadCurve2D.Float

Sets the location of the end points and control point of this curve to the specified float coordinates.

setCurve(double, double, double, double, double, double) - Method in class java.awt.geom.QuadCurve2D

Sets the location of the end points and control point of this curve to the specified double coordinates.

setCurve(double[], int) - Method in class java.awt.geom.QuadCurve2D

Sets the location of the end points and control points of this QuadCurve2D to the double coordinates at the specified offset in the specified array.

setCurve(Point2D, Point2D, Point2D) - Method in class java.awt.geom.QuadCurve2D

Sets the location of the end points and control point of this QuadCurve2D to the specified Point2D coordinates.

setCurve(Point2D[], int) - Method in class java.awt.geom.QuadCurve2D

Sets the location of the end points and control points of this QuadCurve2D to the coordinates of the Point2D objects at the specified offset in the specified array.

setCurve(QuadCurve2D) - Method in class java.awt.geom.QuadCurve2D

Sets the location of the end points and control point of this QuadCurve2D to the same as those in the specified QuadCurve2D.

setDaemon(boolean) - Method in class java.lang.Thread

Marks this thread as either a daemon thread or a user thread.

setDaemon(boolean) - Method in class java.lang.ThreadGroup

Changes the daemon status of this thread group.

setData(int, byte[]) - Method in class java.awt.color.ICC_Profile

Sets a particular tagged data element in the profile from a byte array.

setData(Raster) - Method in class java.awt.image.BufferedImage

Sets a rectangular region of the image to the contents of the specified Raster r, which is assumed to be in the same coordinate space as the BufferedImage.

setData(Raster) - Method in interface java.awt.image.WritableRenderedImage

Sets a rect of the image to the contents of the Raster r, which is assumed to be in the same coordinate space as the WritableRenderedImage.

setData(byte[], int, int) - Method in class java.net.DatagramPacket

Set the data buffer for this packet.

setData(byte[]) - Method in class java.net.DatagramPacket

Set the data buffer for this packet.

setData(byte[]) - Method in class javax.imageio.stream.IIOByteBuffer

Updates the array reference that will be returned by subsequent calls to the getData method.

setData(String) - Method in interface org.w3c.dom.CharacterData

The character data of the node that implements this interface.

setData(String) - Method in interface org.w3c.dom.ProcessingInstruction

The content of this processing instruction.

setDataContentHandlerFactory(DataContentHandlerFactory) - Static method in class javax.activation.DataHandler

Sets the DataContentHandlerFactory.

setDataElements(int, int, Object, DataBuffer) - Method in class java.awt.image.BandedSampleModel

Sets the data for a single pixel in the specified DataBuffer from a primitive array of type TransferType.

setDataElements(int, int, Object, DataBuffer) - Method in class java.awt.image.ComponentSampleModel

Sets the data for a single pixel in the specified DataBuffer from a primitive array of type TransferType.

setDataElements(int, int, Object, DataBuffer) - Method in class java.awt.image.MultiPixelPackedSampleModel

Sets the data for a single pixel in the specified DataBuffer from a primitive array of type TransferType.

setDataElements(int, int, Object, DataBuffer) - Method in class java.awt.image.SampleModel

Sets the data for a single pixel in the specified DataBuffer from a primitive array of type TransferType.

setDataElements(int, int, int, int, Object, DataBuffer) - Method in class java.awt.image.SampleModel

Sets the data for a rectangle of pixels in the specified DataBuffer from a primitive array of type TransferType.

setDataElements(int, int, Object, DataBuffer) - Method in class java.awt.image.SinglePixelPackedSampleModel

Sets the data for a single pixel in the specified DataBuffer from a primitive array of type TransferType.

setDataElements(int, int, Object) - Method in class java.awt.image.WritableRaster

Sets the data for a single pixel from a primitive array of type TransferType.

setDataElements(int, int, Raster) - Method in class java.awt.image.WritableRaster

Sets the data for a rectangle of pixels from an input Raster.

setDataElements(int, int, int, int, Object) - Method in class java.awt.image.WritableRaster

Sets the data for a rectangle of pixels from a primitive array of type TransferType.

setDatagramSocketImplFactory(DatagramSocketImplFactory) - Static method in class java.net.DatagramSocket

Sets the datagram socket implementation factory for the application.

setDataHandler(DataHandler) - Method in class javax.xml.soap.AttachmentPart

Sets the given DataHandler object as the data handler for this AttachmentPart object.

setDataSourceLock(int) - Method in class javax.sql.rowset.spi.SyncProvider

Sets a lock on the underlying data source at the level indicated by datasource_lock.

setDataSourceName(String) - Method in class javax.sql.rowset.BaseRowSet

Sets the DataSource name property for this RowSet object to the given logical name and sets this RowSet object's Url property to null.

setDataSourceName(String) - Method in interface javax.sql.RowSet

Sets the data source name property for this RowSet object to the given String.

setDatatypeConverter(DatatypeConverterInterface) - Static method in class javax.xml.bind.DatatypeConverter

This method is for JAXB provider use only.

setDataVector(Vector, Vector) - Method in class javax.swing.table.DefaultTableModel

Replaces the current dataVector instance variable with the new Vector of rows, dataVector.

setDataVector(Object[][], Object[]) - Method in class javax.swing.table.DefaultTableModel

Replaces the value in the dataVector instance variable with the values in the array dataVector.

setDate(Date) - Method in class java.security.cert.PKIXParameters

Sets the time for which the validity of the certification path should be determined.

setDate(String, Date) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given java.sql.Date value using the default time zone of the virtual machine that is running the application.

setDate(String, Date, Calendar) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given java.sql.Date value, using the given Calendar object.

setDate(int, Date) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given java.sql.Date value using the default time zone of the virtual machine that is running the application.

setDate(int, Date, Calendar) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given java.sql.Date value, using the given Calendar object.

setDate(int) - Method in class java.sql.Time

Deprecated.

setDate(int) - Method in class java.util.Date

Deprecated.
As of JDK version 1.1, replaced by Calendar.set(Calendar.DAY_OF_MONTH, int date).

setDate(int, Date) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.sql.Date value.

setDate(int, Date, Calendar) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.sql.Date object.

setDate(String, Date) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.sql.Date value using the default time zone of the virtual machine that is running the application.

setDate(String, Date, Calendar) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.sql.Date value, using the given Calendar object.

setDate(int, Date) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command to the given java.sql.Date value.

setDate(int, Date, Calendar) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command with the given java.sql.Date value.

setDate(String, Date) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given java.sql.Date value using the default time zone of the virtual machine that is running the application.

setDate(String, Date, Calendar) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given java.sql.Date value, using the given Calendar object.

setDateAndTime(Date) - Method in class java.security.cert.X509CRLSelector

Sets the dateAndTime criterion.

setDateFormatSymbols(DateFormatSymbols) - Method in class java.text.SimpleDateFormat

Sets the date and time format symbols of this date format.

setDay(int) - Method in class javax.xml.datatype.XMLGregorianCalendar

Set days in month.

setDebugGraphicsOptions(int) - Method in class javax.swing.JComponent

Enables or disables diagnostic information about every graphics operation performed within the component or one of its children.

setDebugOptions(int) - Method in class javax.swing.DebugGraphics

Enables/disables diagnostic information about every graphics operation.

setDecimalFormatSymbols(DecimalFormatSymbols) - Method in class java.text.DecimalFormat

Sets the decimal format symbols, which is generally not changed by the programmer or user.

setDecimalSeparator(char) - Method in class java.text.DecimalFormatSymbols

Sets the character used for decimal sign.

setDecimalSeparatorAlwaysShown(boolean) - Method in class java.text.DecimalFormat

Allows you to set the behavior of the decimal separator with integers.

setDeclared(int, boolean) - Method in class org.xml.sax.ext.Attributes2Impl

Assign a value to the "declared" flag of a specific attribute.

setDecodeTables(JPEGQTable[], JPEGHuffmanTable[], JPEGHuffmanTable[]) - Method in class javax.imageio.plugins.jpeg.JPEGImageReadParam

Sets the quantization and Huffman tables to use in decoding abbreviated streams.

setDecomposition(int) - Method in class java.text.Collator

Set the decomposition mode of this Collator.

setDefault(Authenticator) - Static method in class java.net.Authenticator

Sets the authenticator that will be used by the networking code when a proxy or an HTTP server asks for authentication.

setDefault(CookieHandler) - Static method in class java.net.CookieHandler

Sets (or unsets) the system-wide cookie handler.

setDefault(ProxySelector) - Static method in class java.net.ProxySelector

Sets (or unsets) the system-wide proxy selector.

setDefault(ResponseCache) - Static method in class java.net.ResponseCache

Sets (or unsets) the system-wide cache.

setDefault(Locale) - Static method in class java.util.Locale

Sets the default locale for this instance of the Java Virtual Machine.

setDefault(Locale.Category, Locale) - Static method in class java.util.Locale

Sets the default locale for the specified Category for this instance of the Java Virtual Machine.

setDefault(TimeZone) - Static method in class java.util.TimeZone

Sets the TimeZone that is returned by the getDefault method.

setDefault(SSLContext) - Static method in class javax.net.ssl.SSLContext

Sets the default SSL context.

setDefaultAction(Action) - Method in interface javax.swing.text.Keymap

Set the default action to fire if a key is typed.

setDefaultActions(int) - Method in class java.awt.dnd.DropTarget

Sets the default acceptable actions for this DropTarget

setDefaultAllowUserInteraction(boolean) - Static method in class java.net.URLConnection

Sets the default value of the allowUserInteraction field for all future URLConnection objects to the specified value.

setDefaultAssertionStatus(boolean) - Method in class java.lang.ClassLoader

Sets the default assertion status for this class loader.

setDefaultButton(JButton) - Method in class javax.swing.JRootPane

Sets the defaultButton property, which determines the current default button for this JRootPane.

setDefaultCapable(boolean) - Method in class javax.swing.JButton

Sets the defaultCapable property, which determines whether this button can be made the default button for its root pane.

setDefaultClassLoader(ClassLoader) - Method in class javax.management.remote.rmi.RMIServerImpl

Sets the default ClassLoader for this connector server.

setDefaultCloseOperation(int) - Method in class javax.swing.JDialog

Sets the operation that will happen by default when the user initiates a "close" on this dialog.

setDefaultCloseOperation(int) - Method in class javax.swing.JFrame

Sets the operation that will happen by default when the user initiates a "close" on this frame.

setDefaultCloseOperation(int) - Method in class javax.swing.JInternalFrame

Sets the operation that will happen by default when the user initiates a "close" on this internal frame.

setDefaultCommandMap(CommandMap) - Static method in class javax.activation.CommandMap

Set the default CommandMap.

setDefaultCursor(Cursor) - Method in class javax.swing.text.html.HTMLEditorKit

Sets the default cursor.

setDefaultDTD() - Static method in class javax.swing.text.html.parser.ParserDelegator

setDefaultEditor(Class<?>, TableCellEditor) - Method in class javax.swing.JTable

Sets a default cell editor to be used if no editor has been set in a TableColumn.

setDefaultFileTypeMap(FileTypeMap) - Static method in class javax.activation.FileTypeMap

Sets the default FileTypeMap for the system.

setDefaultFocusTraversalKeys(int, Set<? extends AWTKeyStroke>) - Method in class java.awt.KeyboardFocusManager

Sets the default focus traversal keys for a given traversal operation.

setDefaultFocusTraversalPolicy(FocusTraversalPolicy) - Method in class java.awt.KeyboardFocusManager

Sets the default FocusTraversalPolicy.

setDefaultFormatter(JFormattedTextField.AbstractFormatter) - Method in class javax.swing.text.DefaultFormatterFactory

Sets the JFormattedTextField.AbstractFormatter to use as a last resort, eg in case a display, edit or null JFormattedTextField.AbstractFormatter has not been specified.

setDefaultHostnameVerifier(HostnameVerifier) - Static method in class javax.net.ssl.HttpsURLConnection

Sets the default HostnameVerifier inherited by a new instance of this class.

setDefaultLightWeightPopupEnabled(boolean) - Static method in class javax.swing.JPopupMenu

Sets the default value of the lightWeightPopupEnabled property.

setDefaultLocale(Locale) - Static method in class javax.swing.JComponent

Sets the default locale used to initialize each JComponent's locale property upon creation.

setDefaultLocale(Locale) - Method in class javax.swing.UIDefaults

Sets the default locale.

setDefaultLookAndFeelDecorated(boolean) - Static method in class javax.swing.JDialog

Provides a hint as to whether or not newly created JDialogs should have their Window decorations (such as borders, widgets to close the window, title...) provided by the current look and feel.

setDefaultLookAndFeelDecorated(boolean) - Static method in class javax.swing.JFrame

Provides a hint as to whether or not newly created JFrames should have their Window decorations (such as borders, widgets to close the window, title...) provided by the current look and feel.

setDefaultNamespace(String) - Method in interface javax.xml.stream.XMLEventWriter

Binds a URI to the default namespace This URI is bound in the scope of the current START_ELEMENT / END_ELEMENT pair.

setDefaultNamespace(String) - Method in interface javax.xml.stream.XMLStreamWriter

Binds a URI to the default namespace This URI is bound in the scope of the current START_ELEMENT / END_ELEMENT pair.

setDefaultNamespacePrefix(String) - Method in class javax.xml.crypto.dom.DOMCryptoContext

setDefaultNamespacePrefix(String) - Method in interface javax.xml.crypto.XMLCryptoContext

Sets the default namespace prefix.

setDefaultQueue(LayoutQueue) - Static method in class javax.swing.text.LayoutQueue

Set the default layout queue.

setDefaultRenderer(Class<?>, TableCellRenderer) - Method in class javax.swing.JTable

Sets a default cell renderer to be used if no renderer has been set in a TableColumn.

setDefaultRenderer(TableCellRenderer) - Method in class javax.swing.table.JTableHeader

Sets the default renderer to be used when no headerRenderer is defined by a TableColumn.

setDefaultRequestProperty(String, String) - Static method in class java.net.URLConnection

Deprecated.
The instance specific setRequestProperty method should be used after an appropriate instance of URLConnection is obtained. Invoking this method will have no effect.

setDefaultSelection(JobAttributes.DefaultSelectionType) - Method in class java.awt.JobAttributes

Specifies whether, for jobs using these attributes, the application should print all pages, the range specified by the return value of getPageRanges, or the current selection.

setDefaultSSLSocketFactory(SSLSocketFactory) - Static method in class javax.net.ssl.HttpsURLConnection

Sets the default SSLSocketFactory inherited by new instances of this class.

setDefaultStream(PrintStream) - Static method in class java.rmi.server.LogStream

Deprecated.
no replacement

setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler) - Static method in class java.lang.Thread

Set the default handler invoked when a thread abruptly terminates due to an uncaught exception, and no other handler has been defined for that thread.

setDefaultUseCaches(boolean) - Method in class java.net.URLConnection

Sets the default value of the useCaches field to the specified value.

setDelay(int) - Method in class javax.swing.JMenu

Sets the suggested delay before the menu's PopupMenu is popped up or down.

setDelay(int) - Method in class javax.swing.Timer

Sets the Timer's between-event delay, the number of milliseconds between successive action events.

setDerefLinkFlag(boolean) - Method in class javax.naming.directory.SearchControls

Enables/disables link dereferencing during the search.

setDescription(String) - Method in class javax.swing.ImageIcon

Sets the description of the image.

setDescriptor(Descriptor) - Method in interface javax.management.DescriptorAccess

Sets Descriptor (full replace).

setDescriptor(Descriptor) - Method in class javax.management.modelmbean.ModelMBeanAttributeInfo

Sets associated Descriptor (full replace) for the ModelMBeanAttributeDescriptor.

setDescriptor(Descriptor) - Method in class javax.management.modelmbean.ModelMBeanConstructorInfo

Sets associated Descriptor (full replace) of ModelMBeanConstructorInfo.

setDescriptor(Descriptor, String) - Method in interface javax.management.modelmbean.ModelMBeanInfo

Sets descriptors in the info array of type inDescriptorType for the ModelMBean.

setDescriptor(Descriptor, String) - Method in class javax.management.modelmbean.ModelMBeanInfoSupport

setDescriptor(Descriptor) - Method in class javax.management.modelmbean.ModelMBeanNotificationInfo

Sets associated Descriptor (full replace) for the ModelMBeanNotificationInfo If the new Descriptor is null, then the associated Descriptor reverts to a default descriptor.

setDescriptor(Descriptor) - Method in class javax.management.modelmbean.ModelMBeanOperationInfo

Sets associated Descriptor (full replace) for the ModelMBeanOperationInfo If the new Descriptor is null, then the associated Descriptor reverts to a default descriptor.

setDescriptors(Descriptor[]) - Method in interface javax.management.modelmbean.ModelMBeanInfo

Adds or replaces descriptors in the ModelMBeanInfo.

setDescriptors(Descriptor[]) - Method in class javax.management.modelmbean.ModelMBeanInfoSupport

setDesignTime(boolean) - Method in class java.beans.beancontext.BeanContextSupport

Sets the new design time value for this BeanContext.

setDesignTime(boolean) - Static method in class java.beans.Beans

Used to indicate whether of not we are running in an application builder environment.

setDesignTime(boolean) - Method in interface java.beans.DesignMode

Sets the "value" of the "designTime" property.

setDesktopIcon(JInternalFrame.JDesktopIcon) - Method in class javax.swing.JInternalFrame

Sets the JDesktopIcon associated with this JInternalFrame.

setDesktopManager(DesktopManager) - Method in class javax.swing.JDesktopPane

Sets the DesktopManger that will handle desktop-specific UI actions.

setDesktopProperty(String, Object) - Method in class java.awt.Toolkit

Sets the named desktop property to the specified value and fires a property change event to notify any listeners that the value has changed.

setDestination(JobAttributes.DestinationType) - Method in class java.awt.JobAttributes

Specifies whether output will be to a printer or a file for jobs using these attributes.

setDestination(BufferedImage) - Method in class javax.imageio.ImageReadParam

Supplies a BufferedImage to be used as the destination for decoded pixel data.

setDestinationBands(int[]) - Method in class javax.imageio.ImageReadParam

Sets the indices of the destination bands where data will be placed.

setDestinationOffset(Point) - Method in class javax.imageio.IIOParam

Specifies the offset in the destination image at which future decoded pixels are to be placed, when reading, or where a region will be written, when writing.

setDestinationType(ImageTypeSpecifier) - Method in class javax.imageio.IIOParam

Sets the desired image type for the destination image, using an ImageTypeSpecifier.

setDestinationType(ImageTypeSpecifier) - Method in class javax.imageio.ImageReadParam

setDialog(JobAttributes.DialogType) - Method in class java.awt.JobAttributes

Specifies whether, for jobs using these attributes, the user should see a print dialog in which to modify the print settings, and which type of print dialog should be displayed.

setDialogTitle(String) - Method in class javax.swing.JFileChooser

Sets the string that goes in the JFileChooser window's title bar.

setDialogType(int) - Method in class javax.swing.JFileChooser

Sets the type of this dialog.

setDictionary(byte[], int, int) - Method in class java.util.zip.Deflater

Sets preset dictionary for compression.

setDictionary(byte[]) - Method in class java.util.zip.Deflater

Sets preset dictionary for compression.

setDictionary(byte[], int, int) - Method in class java.util.zip.Inflater

Sets the preset dictionary to the given array of bytes.

setDictionary(byte[]) - Method in class java.util.zip.Inflater

Sets the preset dictionary to the given array of bytes.

setDifferenceMode(boolean) - Method in class javax.management.monitor.CounterMonitor

Sets the difference mode flag value common to all observed MBeans.

setDifferenceMode(boolean) - Method in interface javax.management.monitor.CounterMonitorMBean

Sets the difference mode flag value.

setDifferenceMode(boolean) - Method in class javax.management.monitor.GaugeMonitor

Sets the difference mode flag value common to all observed MBeans.

setDifferenceMode(boolean) - Method in interface javax.management.monitor.GaugeMonitorMBean

Sets the difference mode flag value.

setDigit(char) - Method in class java.text.DecimalFormatSymbols

Sets the character used for a digit in a pattern.

setDimensions(int, int) - Method in class java.awt.image.BufferedImageFilter

Filters the information provided in the setDimensions method of the ImageConsumer interface.

setDimensions(int, int) - Method in class java.awt.image.CropImageFilter

Override the source image's dimensions and pass the dimensions of the rectangular cropped region to the ImageConsumer.

setDimensions(int, int) - Method in interface java.awt.image.ImageConsumer

The dimensions of the source image are reported using the setDimensions method call.

setDimensions(int, int) - Method in class java.awt.image.ImageFilter

Filters the information provided in the setDimensions method of the ImageConsumer interface.

setDimensions(int, int) - Method in class java.awt.image.PixelGrabber

The setDimensions method is part of the ImageConsumer API which this class must implement to retrieve the pixels.

setDimensions(int, int) - Method in class java.awt.image.ReplicateScaleFilter

Override the dimensions of the source image and pass the dimensions of the new scaled size to the ImageConsumer.

setDirection(int) - Method in class javax.swing.plaf.basic.BasicArrowButton

Sets the direction of the arrow.

setDirection(int) - Method in class javax.swing.plaf.basic.BasicScrollBarUI.ScrollListener

setDirection(int) - Method in class javax.swing.plaf.basic.BasicSliderUI.ScrollListener

setDirection(short) - Method in class javax.swing.text.DefaultStyledDocument.ElementSpec

Sets the direction.

setDirectory(String) - Method in class java.awt.FileDialog

Sets the directory of this file dialog window to be the specified directory.

setDirectory(File) - Method in class javax.swing.plaf.basic.BasicFileChooserUI

Property to remember the directory that is currently selected in the UI.

setDirectoryName(String) - Method in class javax.swing.plaf.basic.BasicFileChooserUI

setDirectoryName(String) - Method in class javax.swing.plaf.metal.MetalFileChooserUI

setDirectorySelected(boolean) - Method in class javax.swing.plaf.basic.BasicFileChooserUI

Property to remember whether a directory is currently selected in the UI.

setDirectorySelected(boolean) - Method in class javax.swing.plaf.metal.MetalFileChooserUI

Property to remember whether a directory is currently selected in the UI.

setDisabledIcon(Icon) - Method in class javax.swing.AbstractButton

Sets the disabled icon for the button.

setDisabledIcon(Icon) - Method in class javax.swing.JLabel

Set the icon to be displayed if this JLabel is "disabled" (JLabel.setEnabled(false)).

setDisabledIconAt(int, Icon) - Method in class javax.swing.JTabbedPane

Sets the disabled icon at index to icon which can be null.

setDisabledSelectedIcon(Icon) - Method in class javax.swing.AbstractButton

Sets the disabled selection icon for the button.

setDisabledTextColor(Color) - Method in class javax.swing.text.JTextComponent

Sets the current color used to render the disabled text.

setDiscard(boolean) - Method in class java.net.HttpCookie

Specify whether user agent should discard the cookie unconditionally.

setDismissDelay(int) - Method in class javax.swing.ToolTipManager

Specifies the dismissal delay value.

setDisplayedMnemonic(int) - Method in class javax.swing.JLabel

Specify a keycode that indicates a mnemonic key.

setDisplayedMnemonic(char) - Method in class javax.swing.JLabel

Specifies the displayedMnemonic as a char value.

setDisplayedMnemonicIndex(int) - Method in class javax.swing.AbstractButton

Provides a hint to the look and feel as to which character in the text should be decorated to represent the mnemonic.

setDisplayedMnemonicIndex(int) - Method in class javax.swing.JLabel

Provides a hint to the look and feel as to which character in the text should be decorated to represent the mnemonic.

setDisplayedMnemonicIndexAt(int, int) - Method in class javax.swing.JTabbedPane

Provides a hint to the look and feel as to which character in the text should be decorated to represent the mnemonic.

setDisplayFormatter(JFormattedTextField.AbstractFormatter) - Method in class javax.swing.text.DefaultFormatterFactory

Sets the JFormattedTextField.AbstractFormatter to use if the JFormattedTextField is not being edited and either the value is not-null, or the value is null and a null formatter has has not been specified.

setDisplayMode(DisplayMode) - Method in class java.awt.GraphicsDevice

Sets the display mode of this graphics device.

setDisplayName(String) - Method in class java.beans.FeatureDescriptor

Sets the localized display name of this feature.

setDividerLocation(double) - Method in class javax.swing.JSplitPane

Sets the divider location as a percentage of the JSplitPane's size.

setDividerLocation(int) - Method in class javax.swing.JSplitPane

Sets the location of the divider.

setDividerLocation(JSplitPane, int) - Method in class javax.swing.plaf.basic.BasicSplitPaneUI

Sets the location of the divider to location.

setDividerLocation(JSplitPane, int) - Method in class javax.swing.plaf.multi.MultiSplitPaneUI

Invokes the setDividerLocation method on each UI handled by this object.

setDividerLocation(JSplitPane, int) - Method in class javax.swing.plaf.SplitPaneUI

Sets the location of the divider to location.

setDividerSize(int) - Method in class javax.swing.JSplitPane

Sets the size of the divider.

setDividerSize(int) - Method in class javax.swing.plaf.basic.BasicSplitPaneDivider

Sets the size of the divider to newSize.

setDockingColor(Color) - Method in class javax.swing.plaf.basic.BasicToolBarUI

Sets the color displayed when over a docking area

setDocument(Document) - Method in class javax.swing.JFormattedTextField

Associates the editor with a text document.

setDocument(Document) - Method in class javax.swing.JTextField

Associates the editor with a text document.

setDocument(Document) - Method in class javax.swing.JTextPane

Associates the editor with a text document.

setDocument(Document) - Method in class javax.swing.text.JTextComponent

Associates the editor with a text document.

setDocumentFilter(DocumentFilter) - Method in class javax.swing.text.AbstractDocument

Sets the DocumentFilter.

setDocumentHandler(DocumentHandler) - Method in class org.xml.sax.helpers.XMLReaderAdapter

Register the SAX1 document event handler.

setDocumentHandler(DocumentHandler) - Method in interface org.xml.sax.Parser

Deprecated.

Allow an application to register a document event handler.

setDocumentLocator(Locator) - Method in interface org.xml.sax.ContentHandler

Receive an object for locating the origin of SAX document events.

setDocumentLocator(Locator) - Method in interface org.xml.sax.DocumentHandler

Deprecated.

Receive an object for locating the origin of SAX document events.

setDocumentLocator(Locator) - Method in class org.xml.sax.HandlerBase

Deprecated.

Receive a Locator object for document events.

setDocumentLocator(Locator) - Method in class org.xml.sax.helpers.DefaultHandler

Receive a Locator object for document events.

setDocumentLocator(Locator) - Method in class org.xml.sax.helpers.ParserAdapter

Adapter implementation method; do not call.

setDocumentLocator(Locator) - Method in class org.xml.sax.helpers.XMLFilterImpl

Filter a new document locator event.

setDocumentLocator(Locator) - Method in class org.xml.sax.helpers.XMLReaderAdapter

Set a document locator.

setDocumentProperties(Dictionary<Object, Object>) - Method in class javax.swing.text.AbstractDocument

Replaces the document properties dictionary for this document.

setDocumentURI(String) - Method in interface org.w3c.dom.Document

The location of the document or null if undefined or if the Document was created using DOMImplementation.createDocument.

setDoInput(boolean) - Method in class java.net.URLConnection

Sets the value of the doInput field for this URLConnection to the specified value.

setDomain(String) - Method in class java.net.HttpCookie

Specifies the domain within which this cookie should be presented.

setDoOutput(boolean) - Method in class java.net.URLConnection

Sets the value of the doOutput field for this URLConnection to the specified value.

setDot(int) - Method in interface javax.swing.text.Caret

Sets the caret position to some position.

setDot(int) - Method in class javax.swing.text.DefaultCaret

Sets the caret position and mark to the specified position, with a forward bias.

setDot(int, Position.Bias) - Method in class javax.swing.text.DefaultCaret

Sets the caret position and mark to the specified position, with the specified bias.

setDot(int, Position.Bias) - Method in class javax.swing.text.NavigationFilter.FilterBypass

Sets the caret location, bypassing the NavigationFilter.

setDot(NavigationFilter.FilterBypass, int, Position.Bias) - Method in class javax.swing.text.NavigationFilter

Invoked prior to the Caret setting the dot.

setDouble(Object, int, double) - Static method in class java.lang.reflect.Array

Sets the value of the indexed component of the specified array object to the specified double value.

setDouble(Object, double) - Method in class java.lang.reflect.字段

Sets the value of a field as a double on the specified object.

setDouble(String, double) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given Java double value.

setDouble(int, double) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given Java double value.

setDouble(int, double) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given double in the Java programming language.

setDouble(String, double) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given Java double value.

setDouble(int, double) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command to the given Java double value.

setDouble(String, double) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given Java double value.

setDoubleBuffered(boolean) - Method in class javax.swing.JComponent

Sets whether this component should use a buffer to paint.

setDoubleBuffered(boolean) - Method in class javax.swing.JRootPane

Sets whether this component should use a buffer to paint.

setDoubleBufferingEnabled(boolean) - Method in class javax.swing.RepaintManager

Enables or disables double buffering in this RepaintManager.

setDoubleBufferMaximumSize(Dimension) - Method in class javax.swing.RepaintManager

Set the maximum double buffer size.

setDragEnabled(boolean) - Method in class javax.swing.JColorChooser

Sets the dragEnabled property, which must be true to enable automatic drag handling (the first part of drag and drop) on this component.

setDragEnabled(boolean) - Method in class javax.swing.JFileChooser

Sets the dragEnabled property, which must be true to enable automatic drag handling (the first part of drag and drop) on this component.

setDragEnabled(boolean) - Method in class javax.swing.JList

Turns on or off automatic drag handling.

setDragEnabled(boolean) - Method in class javax.swing.JTable

Turns on or off automatic drag handling.

setDragEnabled(boolean) - Method in class javax.swing.JTree

Turns on or off automatic drag handling.

setDragEnabled(boolean) - Method in class javax.swing.text.JTextComponent

Turns on or off automatic drag handling.

setDraggedColumn(TableColumn) - Method in class javax.swing.table.JTableHeader

Sets the header's draggedColumn to aColumn.

setDraggedDistance(int) - Method in class javax.swing.table.JTableHeader

Sets the header's draggedDistance to distance.

setDragImage(Image) - Method in class javax.swing.TransferHandler

Sets the drag image parameter.

setDragImageOffset(Point) - Method in class javax.swing.TransferHandler

Sets an anchor offset for the image to drag.

setDragMode(int) - Method in class javax.swing.JDesktopPane

Sets the "dragging style" used by the desktop pane.

setDragOffset(Point) - Method in class javax.swing.plaf.metal.MetalToolBarUI

setDrawsLayeredHighlights(boolean) - Method in class javax.swing.text.DefaultHighlighter

If true, highlights are drawn as the Views draw the text.

setDropAction(int) - Method in class javax.swing.TransferHandler.TransferSupport

Sets the drop action for the transfer - which must represent a drop - to the given action, instead of the default user drop action.

setDropMode(DropMode) - Method in class javax.swing.JList

Sets the drop mode for this component.

setDropMode(DropMode) - Method in class javax.swing.JTable

Sets the drop mode for this component.

setDropMode(DropMode) - Method in class javax.swing.JTree

Sets the drop mode for this component.

setDropMode(DropMode) - Method in class javax.swing.text.JTextComponent

Sets the drop mode for this component.

setDropTarget(DropTarget) - Method in class java.awt.Component

Associate a DropTarget with this component.

setDSTSavings(int) - Method in class java.util.SimpleTimeZone

Sets the amount of time in milliseconds that the clock is advanced during daylight saving time.

setDTDHandler(DTDHandler) - Method in class org.xml.sax.helpers.ParserAdapter

Set the DTD handler.

setDTDHandler(DTDHandler) - Method in class org.xml.sax.helpers.XMLFilterImpl

Set the DTD event handler.

setDTDHandler(DTDHandler) - Method in class org.xml.sax.helpers.XMLReaderAdapter

Register the DTD event handler.

setDTDHandler(DTDHandler) - Method in interface org.xml.sax.Parser

Deprecated.

Allow an application to register a DTD event handler.

setDTDHandler(DTDHandler) - Method in interface org.xml.sax.XMLReader

Allow an application to register a DTD event handler.

setDynamicLayout(boolean) - Method in class java.awt.Toolkit

Controls whether the layout of Containers is validated dynamically during resizing, or statically, after resizing is complete.

setEastPane(JComponent) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI

setEchoChar(char) - Method in class java.awt.TextField

Sets the echo character for this text field.

setEchoChar(char) - Method in class javax.swing.JPasswordField

Sets the echo character for this JPasswordField.

setEchoCharacter(char) - Method in class java.awt.TextField

Deprecated.
As of JDK version 1.1, replaced by setEchoChar(char).

setEditable(boolean) - Method in class java.awt.TextComponent

Sets the flag that determines whether or not this text component is editable.

setEditable(boolean) - Method in class javax.swing.JComboBox

Determines whether the JComboBox field is editable.

setEditable(boolean) - Method in class javax.swing.JTree

Determines whether the tree is editable.

setEditable(boolean) - Method in class javax.swing.plaf.basic.BasicTreeUI

Configures the receiver to allow, or not allow, editing.

setEditable(boolean) - Method in class javax.swing.text.JTextComponent

Sets the specified boolean to indicate whether or not this TextComponent should be editable.

setEditFormatter(JFormattedTextField.AbstractFormatter) - Method in class javax.swing.text.DefaultFormatterFactory

Sets the JFormattedTextField.AbstractFormatter to use if the JFormattedTextField is being edited and either the value is not-null, or the value is null and a null formatter has has not been specified.

setEditingColumn(int) - Method in class javax.swing.JTable

Sets the editingColumn variable.

setEditingRow(int) - Method in class javax.swing.JTable

Sets the editingRow variable.

setEditor(ComboBoxEditor) - Method in class javax.swing.JComboBox

Sets the editor used to paint and edit the selected item in the JComboBox field.

setEditor(JComponent) - Method in class javax.swing.JSpinner

Changes the JComponent that displays the current value of the SpinnerModel.

setEditorKit(EditorKit) - Method in class javax.swing.JEditorPane

Sets the currently installed kit for handling content.

setEditorKit(EditorKit) - Method in class javax.swing.JTextPane

Sets the currently installed kit for handling content.

setEditorKitForContentType(String, EditorKit) - Method in class javax.swing.JEditorPane

Directly sets the editor kit to use for the given type.

setEditorSearchPath(String[]) - Static method in class java.beans.PropertyEditorManager

Change the list of package names that will be used for finding property editors.

setEditValid(boolean) - Method in class javax.swing.JFormattedTextField.AbstractFormatter

Invoke this to update the editValid property of the JFormattedTextField.

setElem(int, int) - Method in class java.awt.image.DataBuffer

Sets the requested data array element in the first (default) bank from the given integer.

setElem(int, int, int) - Method in class java.awt.image.DataBuffer

Sets the requested data array element in the specified bank from the given integer.

setElem(int, int) - Method in class java.awt.image.DataBufferByte

Sets the requested data array element in the first (default) bank to the specified value.

setElem(int, int, int) - Method in class java.awt.image.DataBufferByte

Sets the requested data array element in the specified bank from the given integer.

setElem(int, int) - Method in class java.awt.image.DataBufferDouble

Sets the requested data array element in the first (default) bank to the given int.

setElem(int, int, int) - Method in class java.awt.image.DataBufferDouble

Sets the requested data array element in the specified bank to the given int.

setElem(int, int) - Method in class java.awt.image.DataBufferFloat

Sets the requested data array element in the first (default) bank to the given int.

setElem(int, int, int) - Method in class java.awt.image.DataBufferFloat

Sets the requested data array element in the specified bank to the given int.

setElem(int, int) - Method in class java.awt.image.DataBufferInt

Sets the requested data array element in the first (default) bank to the specified value.

setElem(int, int, int) - Method in class java.awt.image.DataBufferInt

Sets the requested data array element in the specified bank to the integer value i.

setElem(int, int) - Method in class java.awt.image.DataBufferShort

Sets the requested data array element in the first (default) bank to the specified value.

setElem(int, int, int) - Method in class java.awt.image.DataBufferShort

Sets the requested data array element in the specified bank from the given integer.

setElem(int, int) - Method in class java.awt.image.DataBufferUShort

Sets the requested data array element in the first (default) bank to the specified value.

setElem(int, int, int) - Method in class java.awt.image.DataBufferUShort

Sets the requested data array element in the specified bank from the given integer.

setElemDouble(int, double) - Method in class java.awt.image.DataBuffer

Sets the requested data array element in the first (default) bank from the given double.

setElemDouble(int, int, double) - Method in class java.awt.image.DataBuffer

Sets the requested data array element in the specified bank from the given double.

setElemDouble(int, double) - Method in class java.awt.image.DataBufferDouble

Sets the requested data array element in the first (default) bank to the given double.

setElemDouble(int, int, double) - Method in class java.awt.image.DataBufferDouble

Sets the requested data array element in the specified bank to the given double.

setElemDouble(int, double) - Method in class java.awt.image.DataBufferFloat

Sets the requested data array element in the first (default) bank to the given double.

setElemDouble(int, int, double) - Method in class java.awt.image.DataBufferFloat

Sets the requested data array element in the specified bank to the given double.

setElementAt(E, int) - Method in class java.util.Vector

Sets the component at the specified index of this vector to be the specified object.

setElementAt(E, int) - Method in class javax.swing.DefaultListModel

Sets the component at the specified index of this list to be the specified element.

setElementQName(QName) - Method in interface javax.xml.soap.SOAPElement

Changes the name of this Element to newName if possible.

setElemFloat(int, float) - Method in class java.awt.image.DataBuffer

Sets the requested data array element in the first (default) bank from the given float.

setElemFloat(int, int, float) - Method in class java.awt.image.DataBuffer

Sets the requested data array element in the specified bank from the given float.

setElemFloat(int, float) - Method in class java.awt.image.DataBufferDouble

Sets the requested data array element in the first (default) bank to the given float.

setElemFloat(int, int, float) - Method in class java.awt.image.DataBufferDouble

Sets the requested data array element in the specified bank to the given float.

setElemFloat(int, float) - Method in class java.awt.image.DataBufferFloat

Sets the requested data array element in the first (default) bank to the given float.

setElemFloat(int, int, float) - Method in class java.awt.image.DataBufferFloat

Sets the requested data array element in the specified bank to the given float.

setEnabled(boolean) - Method in class java.awt.Component.AccessibleAWTComponent

Sets the enabled state of the object.

setEnabled(boolean) - Method in class java.awt.Component

Enables or disables this component, depending on the value of the parameter b.

setEnabled(boolean) - Method in class java.awt.List.AccessibleAWTList.AccessibleAWTListChild

Set the enabled state of the object.

setEnabled(boolean) - Method in class java.awt.MenuComponent.AccessibleAWTMenuComponent

Sets the enabled state of the object.

setEnabled(boolean) - Method in class java.awt.MenuItem

Sets whether or not this menu item can be chosen.

setEnabled(boolean) - Method in interface javax.accessibility.AccessibleComponent

Sets the enabled state of the object.

setEnabled(boolean) - Method in class javax.swing.AbstractAction

Sets whether the Action is enabled.

setEnabled(boolean) - Method in class javax.swing.AbstractButton

Enables (or disables) the button.

setEnabled(boolean) - Method in interface javax.swing.Action

Sets the enabled state of the Action.

setEnabled(boolean) - Method in interface javax.swing.ButtonModel

Enables or disables the button.

setEnabled(boolean) - Method in class javax.swing.DefaultButtonModel

Enables or disables the button.

setEnabled(boolean) - Method in class javax.swing.JComboBox

Enables the combo box so that items can be selected.

setEnabled(boolean) - Method in class javax.swing.JComponent

Sets whether or not this component is enabled.

setEnabled(boolean) - Method in class javax.swing.JList.AccessibleJList.AccessibleJListChild

setEnabled(boolean) - Method in class javax.swing.JMenuItem

Enables or disables the menu item.

setEnabled(boolean) - Method in class javax.swing.JScrollBar

Enables the component so that the knob position can be changed.

setEnabled(boolean) - Method in class javax.swing.JTable.AccessibleJTable.AccessibleJTableCell

Sets the enabled state of the object.

setEnabled(boolean) - Method in class javax.swing.JTree.AccessibleJTree.AccessibleJTreeNode

setEnabled(boolean) - Method in class javax.swing.plaf.metal.MetalComboBoxButton

setEnabled(boolean) - Method in class javax.swing.table.JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry

setEnabled(boolean) - Method in class javax.swing.ToolTipManager

Enables or disables the tooltip.

setEnabledAt(int, boolean) - Method in class javax.swing.JTabbedPane

Sets whether or not the tab at index is enabled.

setEnabledCipherSuites(String[]) - Method in class javax.naming.ldap.StartTlsResponse

Overrides the default list of cipher suites enabled for use on the TLS connection.

setEnabledCipherSuites(String[]) - Method in class javax.net.ssl.SSLEngine

Sets the cipher suites enabled for use on this engine.

setEnabledCipherSuites(String[]) - Method in class javax.net.ssl.SSLServerSocket

Sets the cipher suites enabled for use by accepted connections.

setEnabledCipherSuites(String[]) - Method in class javax.net.ssl.SSLSocket

Sets the cipher suites enabled for use on this connection.

setEnabledProtocols(String[]) - Method in class javax.net.ssl.SSLEngine

Set the protocol versions enabled for use on this engine.

setEnabledProtocols(String[]) - Method in class javax.net.ssl.SSLServerSocket

Controls which particular protocols are enabled for use by accepted connections.

setEnabledProtocols(String[]) - Method in class javax.net.ssl.SSLSocket

Sets the protocol versions enabled for use on this connection.

setEnableSessionCreation(boolean) - Method in class javax.net.ssl.SSLEngine

Controls whether new SSL sessions may be established by this engine.

setEnableSessionCreation(boolean) - Method in class javax.net.ssl.SSLServerSocket

Controls whether new SSL sessions may be established by the sockets which are created from this server socket.

setEnableSessionCreation(boolean) - Method in class javax.net.ssl.SSLSocket

Controls whether new SSL sessions may be established by this socket.

setEncodeTables(JPEGQTable[], JPEGHuffmanTable[], JPEGHuffmanTable[]) - Method in class javax.imageio.plugins.jpeg.JPEGImageWriteParam

Sets the quantization and Huffman tables to use in encoding abbreviated streams.

setEncoding(String) - Method in class java.util.logging.Handler

Set the character encoding used by this Handler.

setEncoding(String) - Method in class java.util.logging.StreamHandler

Set (or change) the character encoding used by this Handler.

setEncoding(String) - Method in class javax.xml.bind.helpers.AbstractMarshallerImpl

Convenience method for setting the output encoding.

setEncoding(String) - Method in interface org.w3c.dom.ls.LSInput

The character encoding, if known.

setEncoding(String) - Method in interface org.w3c.dom.ls.LSOutput

The character encoding to use for the output.

setEncoding(String) - Method in class org.xml.sax.ext.Locator2Impl

Assigns the current value of the encoding property.

setEncoding(String) - Method in class org.xml.sax.InputSource

Set the character encoding, if known.

setEncodingStyle(String) - Method in interface javax.xml.soap.SOAPElement

Sets the encoding style for this SOAPElement object to one specified.

setEnd(Comparable) - Method in class javax.swing.SpinnerDateModel

Changes the upper limit for Dates in this sequence.

setEndIndex(int) - Method in class java.text.FieldPosition

Sets the end index.

setEndpointContext(EndpointContext) - Method in class javax.xml.ws.Endpoint

By settng a EndpointContext, JAX-WS runtime knows about addresses of other endpoints in an application.

setEndpointIdentificationAlgorithm(String) - Method in class javax.net.ssl.SSLParameters

Sets the endpoint identification algorithm.

setEndRule(int, int, int, int) - Method in class java.util.SimpleTimeZone

Sets the daylight saving time end rule.

setEndRule(int, int, int) - Method in class java.util.SimpleTimeZone

Sets the daylight saving time end rule to a fixed date within a month.

setEndRule(int, int, int, int, boolean) - Method in class java.util.SimpleTimeZone

Sets the daylight saving time end rule to a weekday before or after the given date within a month, e.g., the first Monday on or after the 8th.

setEntityResolver(EntityResolver) - Method in class javax.xml.parsers.DocumentBuilder

Specify the EntityResolver to be used to resolve entities present in the XML document to be parsed.

setEntityResolver(EntityResolver) - Method in class org.xml.sax.helpers.ParserAdapter

Set the entity resolver.

setEntityResolver(EntityResolver) - Method in class org.xml.sax.helpers.XMLFilterImpl

Set the entity resolver.

setEntityResolver(EntityResolver) - Method in class org.xml.sax.helpers.XMLReaderAdapter

Register the entity resolver.

setEntityResolver(EntityResolver) - Method in interface org.xml.sax.Parser

Deprecated.

Allow an application to register a custom entity resolver.

setEntityResolver(EntityResolver) - Method in interface org.xml.sax.XMLReader

Allow an application to register an entity resolver.

setEntry(String, KeyStore.Entry, KeyStore.ProtectionParameter) - Method in class java.security.KeyStore

Saves a keystore Entry under the specified alias.

setEnvironment(Hashtable<?, ?>) - Method in exception javax.naming.CannotProceedException

Sets the environment that will be returned when getEnvironment() is called.

setEras(String[]) - Method in class java.text.DateFormatSymbols

Sets era strings.

setErr(PrintStream) - Static method in class java.lang.System

Reassigns the "standard" error output stream.

setError() - Method in class java.io.PrintStream

Sets the error state of the stream to true.

setError() - Method in class java.io.PrintWriter

Indicates that an error has occurred.

setErrorHandler(ErrorHandler) - Method in class javax.xml.parsers.DocumentBuilder

Specify the ErrorHandler to be used by the parser.

setErrorHandler(ErrorHandler) - Method in class javax.xml.validation.SchemaFactory

Sets the ErrorHandler to receive errors encountered during the newSchema method invocation.

setErrorHandler(ErrorHandler) - Method in class javax.xml.validation.Validator

Sets the ErrorHandler to receive errors encountered during the validate method invocation.

setErrorHandler(ErrorHandler) - Method in class javax.xml.validation.ValidatorHandler

Sets the ErrorHandler to receive errors encountered during the validation.

setErrorHandler(ErrorHandler) - Method in class org.xml.sax.helpers.ParserAdapter

Set the error handler.

setErrorHandler(ErrorHandler) - Method in class org.xml.sax.helpers.XMLFilterImpl

Set the error event handler.

setErrorHandler(ErrorHandler) - Method in class org.xml.sax.helpers.XMLReaderAdapter

Register the error event handler.

setErrorHandler(ErrorHandler) - Method in interface org.xml.sax.Parser

Deprecated.

Allow an application to register an error event handler.

setErrorHandler(ErrorHandler) - Method in interface org.xml.sax.XMLReader

Allow an application to register an error event handler.

setErrorIndex(int) - Method in class java.text.ParsePosition

Set the index at which a parse error occurred.

setErrorListener(ErrorListener) - Method in class javax.xml.transform.Transformer

Set the error event listener in effect for the transformation.

setErrorListener(ErrorListener) - Method in class javax.xml.transform.TransformerFactory

Set the error event listener for the TransformerFactory, which is used for the processing of transformation instructions, and not for the transformation itself.

setErrorManager(ErrorManager) - Method in class java.util.logging.Handler

Define an ErrorManager for this Handler.

setErrorWriter(Writer) - Method in interface javax.script.ScriptContext

Sets the Writer used to display error output.

setErrorWriter(Writer) - Method in class javax.script.SimpleScriptContext

Sets the Writer used to display error output.

setEscapeProcessing(boolean) - Method in interface java.sql.Statement

Sets escape processing on or off.

setEscapeProcessing(boolean) - Method in class javax.sql.rowset.BaseRowSet

Sets to the given boolean whether or not the driver will scan for escape syntax and do escape substitution before sending SQL statements to the database.

setEscapeProcessing(boolean) - Method in interface javax.sql.RowSet

Sets escape processing for this RowSet object on or off.

setEstimatedMajorSpan(boolean) - Method in class javax.swing.text.AsyncBoxView

Set the estimatedMajorSpan property that determines if the major span should be treated as being estimated.

setEventAllocator(XMLEventAllocator) - Method in class javax.xml.stream.XMLInputFactory

Set a user defined event allocator for events

setEventHandler(ValidationEventHandler) - Method in class javax.xml.bind.Binder

Allow an application to register a ValidationEventHandler.

setEventHandler(ValidationEventHandler) - Method in class javax.xml.bind.helpers.AbstractMarshallerImpl

setEventHandler(ValidationEventHandler) - Method in class javax.xml.bind.helpers.AbstractUnmarshallerImpl

Allow an application to register a validation event handler.

setEventHandler(ValidationEventHandler) - Method in interface javax.xml.bind.Marshaller

Allow an application to register a validation event handler.

setEventHandler(ValidationEventHandler) - Method in interface javax.xml.bind.Unmarshaller

Allow an application to register a ValidationEventHandler.

setEventHandler(ValidationEventHandler) - Method in interface javax.xml.bind.Validator

Deprecated.
since JAXB2.0

setException(Throwable) - Method in class java.util.concurrent.FutureTask

Causes this future to report an ExecutionException with the given throwable as its cause, unless this Future has already been set or has been cancelled.

setExceptionListener(ExceptionListener) - Method in class java.beans.Encoder

Sets the exception handler for this stream to exceptionListener.

setExceptionListener(ExceptionListener) - Method in class java.beans.XMLDecoder

Sets the exception handler for this stream to exceptionListener.

setExclusiveOwnerThread(Thread) - Method in class java.util.concurrent.locks.AbstractOwnableSynchronizer

Sets the thread that currently owns exclusive access.

setExecutable(boolean, boolean) - Method in class java.io.File

Sets the owner's or everybody's execute permission for this abstract pathname.

setExecutable(boolean) - Method in class java.io.File

A convenience method to set the owner's execute permission for this abstract pathname.

setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean) - Method in class java.util.concurrent.ScheduledThreadPoolExecutor

Sets the policy on whether to execute existing delayed tasks even when this executor has been shutdown.

setExecutor(Executor) - Method in class javax.xml.ws.Endpoint

Sets the executor for this Endpoint instance.

setExecutor(Executor) - Method in class javax.xml.ws.Service

Sets the executor for this Service instance.

setExecutor(Executor) - Method in class javax.xml.ws.spi.ServiceDelegate

Sets the executor for this Service instance.

setExpandedIcon(Icon) - Method in class javax.swing.plaf.basic.BasicTreeUI

setExpandedState(TreePath, boolean) - Method in class javax.swing.JTree

Sets the expanded state of this JTree.

setExpandedState(TreePath, boolean) - Method in class javax.swing.tree.AbstractLayoutCache

Marks the path path expanded state to isExpanded.

setExpandedState(TreePath, boolean) - Method in class javax.swing.tree.FixedHeightLayoutCache

Marks the path path expanded state to isExpanded.

setExpandedState(TreePath, boolean) - Method in class javax.swing.tree.VariableHeightLayoutCache

Marks the path path expanded state to isExpanded.

setExpandEntityReferences(boolean) - Method in class javax.xml.parsers.DocumentBuilderFactory

Specifies that the parser produced by this code will expand entity reference nodes.

setExpandsSelectedPaths(boolean) - Method in class javax.swing.JTree

Configures the expandsSelectedPaths property.

setExpert(boolean) - Method in class java.beans.FeatureDescriptor

The "expert" flag is used to distinguish between features that are intended for expert users from those that are intended for normal users.

setExplicitPolicyRequired(boolean) - Method in class java.security.cert.PKIXParameters

Sets the ExplicitPolicyRequired flag.

setExponentSeparator(String) - Method in class java.text.DecimalFormatSymbols

Sets the string used to separate the mantissa from the exponent.

setExtendedKeyUsage(Set<String>) - Method in class java.security.cert.X509CertSelector

Sets the extendedKeyUsage criterion.

setExtendedState(int) - Method in class java.awt.Frame

Sets the state of this frame.

setExtension(char, String) - Method in class java.util.Locale.Builder

Sets the extension for the given key.

setExtent(int) - Method in interface javax.swing.BoundedRangeModel

Sets the model's extent.

setExtent(int) - Method in class javax.swing.DefaultBoundedRangeModel

Sets the extent to n after ensuring that n is greater than or equal to zero and falls within the model's constraints:

setExtent(int) - Method in class javax.swing.JSlider

Sets the size of the range "covered" by the knob.

setExtentSize(Dimension) - Method in class javax.swing.JViewport

Sets the size of the visible part of the view using view coordinates.

setExtra(byte[]) - Method in class java.util.zip.ZipEntry

Sets the optional extra field data for the entry.

setFailureHandler(RMIFailureHandler) - Static method in class java.rmi.server.RMISocketFactory

Sets the failure handler to be called by the RMI runtime if server socket creation fails.

setFaultActor(String) - Method in interface javax.xml.soap.SOAPFault

Sets this SOAPFault object with the given fault actor.

setFaultCode(Name) - Method in interface javax.xml.soap.SOAPFault

Sets this SOAPFault object with the given fault code.

setFaultCode(QName) - Method in interface javax.xml.soap.SOAPFault

Sets this SOAPFault object with the given fault code.

setFaultCode(String) - Method in interface javax.xml.soap.SOAPFault

Sets this SOAPFault object with the give fault code.

setFaultNode(String) - Method in interface javax.xml.soap.SOAPFault

Creates or replaces any existing Node element value for this SOAPFault object.

setFaultRole(String) - Method in interface javax.xml.soap.SOAPFault

Creates or replaces any existing Role element value for this SOAPFault object.

setFaultString(String) - Method in interface javax.xml.soap.SOAPFault

Sets the fault string for this SOAPFault object to the given string.

setFaultString(String, Locale) - Method in interface javax.xml.soap.SOAPFault

Sets the fault string for this SOAPFault object to the given string and localized to the given locale.

setFeature(String, boolean) - Method in class javax.xml.parsers.DocumentBuilderFactory

Set a feature for this DocumentBuilderFactory and DocumentBuilders created by this factory.

setFeature(String, boolean) - Method in class javax.xml.parsers.SAXParserFactory

Sets the particular feature in the underlying implementation of org.xml.sax.XMLReader.

setFeature(String, boolean) - Method in class javax.xml.transform.TransformerFactory

Set a feature for this TransformerFactory and Transformers or Templates created by this factory.

setFeature(String, boolean) - Method in class javax.xml.validation.SchemaFactory

Set a feature for this SchemaFactory, Schemas created by this factory, and by extension, Validators and ValidatorHandlers created by those Schemas.

setFeature(String, boolean) - Method in class javax.xml.validation.Validator

Set the value of a feature flag.

setFeature(String, boolean) - Method in class javax.xml.validation.ValidatorHandler

Set a feature for this ValidatorHandler.

setFeature(String, boolean) - Method in class javax.xml.xpath.XPathFactory

Set a feature for this XPathFactory and XPaths created by this factory.

setFeature(String, boolean) - Method in class org.xml.sax.helpers.ParserAdapter

Set a feature flag for the parser.

setFeature(String, boolean) - Method in class org.xml.sax.helpers.XMLFilterImpl

Set the value of a feature.

setFeature(String, boolean) - Method in interface org.xml.sax.XMLReader

Set the value of a feature flag.

setFetchDirection(int) - Method in interface java.sql.ResultSet

Gives a hint as to the direction in which the rows in this ResultSet object will be processed.

setFetchDirection(int) - Method in interface java.sql.Statement

Gives the driver a hint as to the direction in which rows will be processed in ResultSet objects created using this Statement object.

setFetchDirection(int) - Method in class javax.sql.rowset.BaseRowSet

Gives the driver a performance hint as to the direction in which the rows in this RowSet object will be processed.

setFetchSize(int) - Method in interface java.sql.ResultSet

Gives the JDBC driver a hint as to the number of rows that should be fetched from the database when more rows are needed for this ResultSet object.

setFetchSize(int) - Method in interface java.sql.Statement

Gives the JDBC driver a hint as to the number of rows that should be fetched from the database when more rows are needed for ResultSet objects genrated by this Statement.

setFetchSize(int) - Method in class javax.sql.rowset.BaseRowSet

Sets the fetch size for this RowSet object to the given number of rows.

setField(String, Object) - Method in interface javax.management.Descriptor

Sets the value for a specific field name.

setField(String, Object) - Method in class javax.management.ImmutableDescriptor

This operation is unsupported since this class is immutable.

setField(String, Object) - Method in class javax.management.modelmbean.DescriptorSupport

setFields(String[], Object[]) - Method in interface javax.management.Descriptor

Sets all fields in the field names array to the new value with the same index in the field values array.

setFields(String[], Object[]) - Method in class javax.management.ImmutableDescriptor

This operation is unsupported since this class is immutable.

setFields(String[], Object[]) - Method in class javax.management.modelmbean.DescriptorSupport

setFile(String) - Method in class java.awt.FileDialog

Sets the selected file for this file dialog window to be the specified file.

setFileFilter(FileFilter) - Method in class javax.swing.JFileChooser

Sets the current file filter.

setFileHidingEnabled(boolean) - Method in class javax.swing.JFileChooser

Sets file hiding on or off.

setFileName(String) - Method in class java.awt.JobAttributes

Specifies the file name for the output file for jobs using these attributes.

setFileName(String) - Method in class javax.swing.plaf.basic.BasicFileChooserUI

setFileName(String) - Method in class javax.swing.plaf.metal.MetalFileChooserUI

setFilenameFilter(FilenameFilter) - Method in class java.awt.FileDialog

Sets the filename filter for this file dialog window to the specified filter.

setFileNameMap(FileNameMap) - Static method in class java.net.URLConnection

Sets the FileNameMap.

setFileSelectionMode(int) - Method in class javax.swing.JFileChooser

Sets the JFileChooser to allow the user to just select files, just select directories, or select both files and directories.

setFileSystemView(FileSystemView) - Method in class javax.swing.JFileChooser

Sets the file system view that the JFileChooser uses for accessing and creating file system resources, such as finding the floppy drive and getting a list of root drives.

setFileTypeMap(FileTypeMap) - Method in class javax.activation.FileDataSource

Set the FileTypeMap to use with this FileDataSource

setFileView(FileView) - Method in class javax.swing.JFileChooser

Sets the file view to used to retrieve UI information, such as the icon that represents a file or the type description of a file.

setFillsViewportHeight(boolean) - Method in class javax.swing.JTable

Sets whether or not this table is always made large enough to fill the height of an enclosing viewport.

setFilter(Filter) - Method in class java.util.logging.Handler

Set a Filter to control output on this Handler.

setFilter(Filter) - Method in class java.util.logging.Logger

Set a filter to control output on this Logger.

setFilter(Predicate) - Method in interface javax.sql.rowset.FilteredRowSet

Applies the given Predicate object to this FilteredRowSet object.

setFilter(LSParserFilter) - Method in interface org.w3c.dom.ls.LSParser

When a filter is provided, the implementation will call out to the filter as it is constructing the DOM tree structure.

setFilter(LSSerializerFilter) - Method in interface org.w3c.dom.ls.LSSerializer

When the application provides a filter, the serializer will call out to the filter before serializing each Node.

setFirstDayOfWeek(int) - Method in class java.util.Calendar

Sets what the first day of the week is; e.g., SUNDAY in the U.S., MONDAY in France.

setFirstLineIndent(float) - Method in class javax.swing.text.ParagraphView

Sets the indent on the first line.

setFirstLineIndent(MutableAttributeSet, float) - Static method in class javax.swing.text.StyleConstants

Sets the first line indent.

setFixedCellHeight(int) - Method in class javax.swing.JList

Sets a fixed value to be used for the height of every cell in the list.

setFixedCellWidth(int) - Method in class javax.swing.JList

Sets a fixed value to be used for the width of every cell in the list.

setFixedLengthStreamingMode(int) - Method in class java.net.HttpURLConnection

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance.

setFixedLengthStreamingMode(long) - Method in class java.net.HttpURLConnection

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance.

setFlags(Set<AclEntryFlag>) - Method in class java.nio.file.attribute.AclEntry.Builder

Sets the flags component of this builder.

setFlags(AclEntryFlag...) - Method in class java.nio.file.attribute.AclEntry.Builder

Sets the flags component of this builder.

setFlashColor(Color) - Static method in class javax.swing.DebugGraphics

Sets the Color used to flash drawing operations.

setFlashCount(int) - Static method in class javax.swing.DebugGraphics

Sets the number of times that drawing operations will flash.

setFlashTime(int) - Static method in class javax.swing.DebugGraphics

Sets the time delay of drawing operation flashing.

setFlavorMap(FlavorMap) - Method in class java.awt.dnd.DropTarget

Sets the FlavorMap associated with this DropTarget.

setFlavorsForNative(String, DataFlavor[]) - Method in class java.awt.datatransfer.SystemFlavorMap

Discards the current mappings for the specified String native, and creates new mappings to the specified DataFlavors.

setFloat(Object, int, float) - Static method in class java.lang.reflect.Array

Sets the value of the indexed component of the specified array object to the specified float value.

setFloat(Object, float) - Method in class java.lang.reflect.字段

Sets the value of a field as a float on the specified object.

setFloat(String, float) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given Java float value.

setFloat(int, float) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given Java float value.

setFloat(int, float) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given float in the Java programming language.

setFloat(String, float) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given Java float value.

setFloat(int, float) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command to the given Java float value.

setFloat(String, float) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given Java float value.

setFloatable(boolean) - Method in class javax.swing.JToolBar

Sets the floatable property, which must be true for the user to move the tool bar.

setFloating(boolean, Point) - Method in class javax.swing.plaf.basic.BasicToolBarUI

setFloatingColor(Color) - Method in class javax.swing.plaf.basic.BasicToolBarUI

Sets the color displayed when over a floating area

setFloatingLocation(int, int) - Method in class javax.swing.plaf.basic.BasicToolBarUI

setFocusable(boolean) - Method in class java.awt.Component

Sets the focusable state of this Component to the specified value.

setFocusableWindowState(boolean) - Method in class java.awt.Window

Sets whether this Window can become the focused Window if it meets the other requirements outlined in isFocusableWindow.

setFocusAccelerator(char) - Method in class javax.swing.text.JTextComponent

Sets the key accelerator that will cause the receiving text component to get the focus.

setFocusCycleRoot(boolean) - Method in class java.awt.Container

Sets whether this Container is the root of a focus traversal cycle.

setFocusCycleRoot(boolean) - Method in class java.awt.Window

Does nothing because Windows must always be roots of a focus traversal cycle.

setFocusCycleRoot(boolean) - Method in class javax.swing.JInternalFrame

Does nothing because JInternalFrames must always be roots of a focus traversal cycle.

setFocusLostBehavior(int) - Method in class javax.swing.JFormattedTextField

Sets the behavior when focus is lost.

setFocusPainted(boolean) - Method in class javax.swing.AbstractButton

Sets the paintFocus property, which must be true for the focus state to be painted.

setFocusTraversalKeys(int, Set<? extends AWTKeyStroke>) - Method in class java.awt.Component

Sets the focus traversal keys for a given traversal operation for this Component.

setFocusTraversalKeys(int, Set<? extends AWTKeyStroke>) - Method in class java.awt.Container

Sets the focus traversal keys for a given traversal operation for this Container.

setFocusTraversalKeys(int, Set<? extends AWTKeyStroke>) - Method in class javax.swing.JComponent

Sets the focus traversal keys for a given traversal operation for this Component.

setFocusTraversalKeysEnabled(boolean) - Method in class java.awt.Component

Sets whether focus traversal keys are enabled for this Component.

setFocusTraversalPolicy(FocusTraversalPolicy) - Method in class java.awt.Container

Sets the focus traversal policy that will manage keyboard traversal of this Container's children, if this Container is a focus cycle root.

setFocusTraversalPolicyProvider(boolean) - Method in class java.awt.Container

Sets whether this container will be used to provide focus traversal policy.

setFollowRedirects(boolean) - Static method in class java.net.HttpURLConnection

Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this class.

setFont(Font) - Method in class java.awt.Component.AccessibleAWTComponent

Sets the Font of this object.

setFont(Font) - Method in class java.awt.Component

Sets the font of this component.

setFont(Font) - Method in class java.awt.Container

Sets the font of this container.

setFont(Font) - Method in class java.awt.Graphics

Sets this graphics context's font to the specified font.

setFont(Font) - Method in class java.awt.List.AccessibleAWTList.AccessibleAWTListChild

Set the Font of this object.

setFont(Font) - Method in class java.awt.MenuComponent.AccessibleAWTMenuComponent

Sets the Font of this object.

setFont(Font) - Method in class java.awt.MenuComponent

Sets the font to be used for this menu component to the specified font.

setFont(Font) - Method in interface javax.accessibility.AccessibleComponent

Sets the Font of this object.

setFont(Font) - Method in class javax.swing.DebugGraphics

Sets the Font used for text drawing operations.

setFont(Font) - Method in class javax.swing.JComponent

Sets the font for this component.

setFont(Font) - Method in class javax.swing.JList.AccessibleJList.AccessibleJListChild

setFont(Font) - Method in class javax.swing.JSlider

Sets the font for this component.

setFont(Font) - Method in class javax.swing.JTable.AccessibleJTable.AccessibleJTableCell

Sets the Font of this object.

setFont(Font) - Method in class javax.swing.JTextArea

Sets the current font.

setFont(Font) - Method in class javax.swing.JTextField

Sets the current font.

setFont(Font) - Method in class javax.swing.JTree.AccessibleJTree.AccessibleJTreeNode

setFont(Font) - Method in class javax.swing.table.JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry

setFont(Font) - Method in class javax.swing.tree.DefaultTreeCellEditor

Sets the font to edit with.

setFont(Font) - Method in class javax.swing.tree.DefaultTreeCellRenderer

Subclassed to map FontUIResources to null.

setFontFamily(MutableAttributeSet, String) - Static method in class javax.swing.text.StyleConstants

Sets the font attribute.

setFontSize(MutableAttributeSet, int) - Static method in class javax.swing.text.StyleConstants

Sets the font size attribute.

setForeground(Color) - Method in class java.awt.Component.AccessibleAWTComponent

Sets the foreground color of this object.

setForeground(Color) - Method in class java.awt.Component

Sets the foreground color of this component.

setForeground(Color) - Method in class java.awt.List.AccessibleAWTList.AccessibleAWTListChild

Set the foreground color of this object.

setForeground(Color) - Method in class java.awt.MenuComponent.AccessibleAWTMenuComponent

Sets the foreground color of this object.

setForeground(Color) - Method in interface javax.accessibility.AccessibleComponent

Sets the foreground color of this object.

setForeground(Color) - Method in class javax.swing.JComponent

Sets the foreground color of this component.

setForeground(Color) - Method in class javax.swing.JList.AccessibleJList.AccessibleJListChild

setForeground(Color) - Method in class javax.swing.JTable.AccessibleJTable.AccessibleJTableCell

Sets the foreground color of this object.

setForeground(Color) - Method in class javax.swing.JTree.AccessibleJTree.AccessibleJTreeNode

setForeground(Color) - Method in class javax.swing.table.DefaultTableCellRenderer

Overrides JComponent.setForeground to assign the unselected-foreground color to the specified color.

setForeground(Color) - Method in class javax.swing.table.JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry

setForeground(MutableAttributeSet, Color) - Static method in class javax.swing.text.StyleConstants

Sets the foreground color.

setForegroundAt(int, Color) - Method in class javax.swing.JTabbedPane

Sets the foreground color at index to foreground which can be null, in which case the tab's foreground color will default to the foreground color of this tabbedpane.

setFormat(int, Format) - Method in class java.text.MessageFormat

Sets the format to use for the format element with the given format element index within the previously set pattern string.

setFormat(DateFormat) - Method in class javax.swing.text.DateFormatter

Sets the format that dictates the legal values that can be edited and displayed.

setFormat(Format) - Method in class javax.swing.text.InternationalFormatter

Sets the format that dictates the legal values that can be edited and displayed.

setFormat(Format) - Method in class javax.swing.text.NumberFormatter

Sets the format that dictates the legal values that can be edited and displayed.

setFormatByArgumentIndex(int, Format) - Method in class java.text.MessageFormat

Sets the format to use for the format elements within the previously set pattern string that use the given argument index.

setFormats(Format[]) - Method in class java.text.MessageFormat

Sets the formats to use for the format elements in the previously set pattern string.

setFormatsByArgumentIndex(Format[]) - Method in class java.text.MessageFormat

Sets the formats to use for the values passed into format methods or returned from parse methods.

setFormattedOutput(boolean) - Method in class javax.xml.bind.helpers.AbstractMarshallerImpl

Convenience method for setting the formatted output flag.

setFormatter(Formatter) - Method in class java.util.logging.Handler

Set a Formatter.

setFormatter(JFormattedTextField.AbstractFormatter) - Method in class javax.swing.JFormattedTextField

Sets the current AbstractFormatter.

setFormatterFactory(JFormattedTextField.AbstractFormatterFactory) - Method in class javax.swing.JFormattedTextField

Sets the AbstractFormatterFactory.

setFractionalSecond(BigDecimal) - Method in class javax.xml.datatype.XMLGregorianCalendar

Set fractional seconds.

setFragment(boolean) - Method in class javax.xml.bind.helpers.AbstractMarshallerImpl

Convenience method for setting the fragment flag.

setFrame(double, double, double, double) - Method in class java.awt.geom.Arc2D

Sets the location and size of the framing rectangle of this Shape to the specified rectangular values.

setFrame(double, double, double, double) - Method in class java.awt.geom.Ellipse2D.Double

Sets the location and size of the framing rectangle of this Shape to the specified rectangular values.

setFrame(float, float, float, float) - Method in class java.awt.geom.Ellipse2D.Float

Sets the location and size of the framing rectangle of this Shape to the specified rectangular values.

setFrame(double, double, double, double) - Method in class java.awt.geom.Ellipse2D.Float

Sets the location and size of the framing rectangle of this Shape to the specified rectangular values.

setFrame(double, double, double, double) - Method in class java.awt.geom.Rectangle2D

Sets the location and size of the outer bounds of this Rectangle2D to the specified rectangular values.

setFrame(double, double, double, double) - Method in class java.awt.geom.RectangularShape

Sets the location and size of the framing rectangle of this Shape to the specified rectangular values.

setFrame(Point2D, Dimension2D) - Method in class java.awt.geom.RectangularShape

Sets the location and size of the framing rectangle of this Shape to the specified Point2D and Dimension2D, respectively.

setFrame(Rectangle2D) - Method in class java.awt.geom.RectangularShape

Sets the framing rectangle of this Shape to be the specified Rectangle2D.

setFrame(double, double, double, double) - Method in class java.awt.geom.RoundRectangle2D

Sets the location and size of the framing rectangle of this Shape to the specified rectangular values.

setFrameFromCenter(double, double, double, double) - Method in class java.awt.geom.RectangularShape

Sets the framing rectangle of this Shape based on the specified center point coordinates and corner point coordinates.

setFrameFromCenter(Point2D, Point2D) - Method in class java.awt.geom.RectangularShape

Sets the framing rectangle of this Shape based on a specified center Point2D and corner Point2D.

setFrameFromDiagonal(double, double, double, double) - Method in class java.awt.geom.RectangularShape

Sets the diagonal of the framing rectangle of this Shape based on the two specified coordinates.

setFrameFromDiagonal(Point2D, Point2D) - Method in class java.awt.geom.RectangularShape

Sets the diagonal of the framing rectangle of this Shape based on two specified Point2D objects.

setFrameIcon(Icon) - Method in class javax.swing.JInternalFrame

Sets an image to be displayed in the titlebar of this internal frame (usually in the top-left corner).

setFramePosition(int) - Method in interface javax.sound.sampled.Clip

Sets the media position in sample frames.

setFreeStanding(boolean) - Method in class javax.swing.plaf.metal.MetalScrollButton

setFromPage(int) - Method in class java.awt.JobAttributes

Specifies, for jobs using these attributes, the first page to be printed, if a range of pages is to be printed.

setFromTree(String, Node) - Method in class javax.imageio.metadata.IIOMetadata

Sets the internal state of this IIOMetadata object from a tree of XML DOM Nodes whose syntax is defined by the given metadata format.

setFullBufferUpdates(boolean) - Method in class java.awt.image.MemoryImageSource

Specifies whether this animated memory image should always be updated by sending the complete buffer of pixels whenever there is a change.

setFullScreenWindow(Window) - Method in class java.awt.GraphicsDevice

Enter full-screen mode, or return to windowed mode.

setGlassPane(Component) - Method in class javax.swing.JApplet

Sets the glassPane property.

setGlassPane(Component) - Method in class javax.swing.JDialog

Sets the glassPane property.

setGlassPane(Component) - Method in class javax.swing.JFrame

Sets the glassPane property.

setGlassPane(Component) - Method in class javax.swing.JInternalFrame

Sets this JInternalFrame's glassPane property.

setGlassPane(JPanel) - Method in class javax.swing.JLayer

Sets the JLayer's glassPane component, which can be null.

setGlassPane(Component) - Method in class javax.swing.JRootPane

Sets a specified Component to be the glass pane for this root pane.

setGlassPane(Component) - Method in class javax.swing.JWindow

Sets the glassPane property.

setGlassPane(Component) - Method in interface javax.swing.RootPaneContainer

The glassPane is always the first child of the rootPane and the rootPanes layout manager ensures that it's always as big as the rootPane.

setGlobalActiveWindow(Window) - Method in class java.awt.KeyboardFocusManager

Sets the active Window.

setGlobalCurrentFocusCycleRoot(Container) - Method in class java.awt.KeyboardFocusManager

Sets the current focus cycle root.

setGlobalFocusedWindow(Window) - Method in class java.awt.KeyboardFocusManager

Sets the focused Window.

setGlobalFocusOwner(Component) - Method in class java.awt.KeyboardFocusManager

Sets the focus owner.

setGlobalPermanentFocusOwner(Component) - Method in class java.awt.KeyboardFocusManager

Sets the permanent focus owner.

setGlyphPainter(GlyphView.GlyphPainter) - Method in class javax.swing.text.GlyphView

Sets the painter to use for rendering glyphs.

setGlyphPosition(int, Point2D) - Method in class java.awt.font.GlyphVector

Sets the position of the specified glyph within this GlyphVector.

setGlyphTransform(int, AffineTransform) - Method in class java.awt.font.GlyphVector

Sets the transform of the specified glyph within this GlyphVector.

setGranularityPeriod(long) - Method in class javax.management.monitor.Monitor

Sets the granularity period (in milliseconds).

setGranularityPeriod(long) - Method in interface javax.management.monitor.MonitorMBean

Sets the granularity period (in milliseconds).

setGregorianChange(Date) - Method in class java.util.GregorianCalendar

Sets the GregorianCalendar change date.

setGridColor(Color) - Method in class javax.swing.JTable

Sets the color used to draw grid lines to gridColor and redisplays.

setGridLocation(int, int) - Method in class javax.swing.text.TableView.TableCell

Deprecated.

Sets the grid location.

setGroup(GroupPrincipal) - Method in interface java.nio.file.attribute.PosixFileAttributeView

Updates the file group-owner.

setGroup(ButtonGroup) - Method in interface javax.swing.ButtonModel

Identifies the group the button belongs to -- needed for radio buttons, which are mutually exclusive within their group.

setGroup(ButtonGroup) - Method in class javax.swing.DefaultButtonModel

Identifies the group the button belongs to -- needed for radio buttons, which are mutually exclusive within their group.

setGroupingSeparator(char) - Method in class java.text.DecimalFormatSymbols

Sets the character used for thousands separator.

setGroupingSize(int) - Method in class java.text.DecimalFormat

Set the grouping size.

setGroupingUsed(boolean) - Method in class java.text.NumberFormat

Set whether or not grouping will be used in this format.

setGuiAvailable(boolean) - Static method in class java.beans.Beans

Used to indicate whether of not we are running in an environment where GUI interaction is available.

setHandler(ContentHandler) - Method in class javax.xml.transform.sax.SAXResult

Set the target to be a SAX2 ContentHandler.

setHandler(HttpHandler) - Method in class javax.xml.ws.spi.http.HttpContext

JAX-WS runtime sets its handler during Endpoint.publish(HttpContext) to handle HTTP requests for this context.

setHandlerChain(List<Handler>) - Method in interface javax.xml.ws.Binding

Sets the handler chain for the protocol binding instance.

setHandlerResolver(HandlerResolver) - Method in class javax.xml.ws.Service

Sets the HandlerResolver for this Service instance.

setHandlerResolver(HandlerResolver) - Method in class javax.xml.ws.spi.ServiceDelegate

Sets the HandlerResolver for this Service instance.

setHashColor(Color) - Method in class javax.swing.plaf.basic.BasicTreeUI

setHeader(String, String) - Method in class javax.xml.soap.MimeHeaders

Replaces the current value of the first header entry whose name matches the given name with the given value, adding a new header if no existing header name matches.

setHeaderRenderer(TableCellRenderer) - Method in class javax.swing.table.TableColumn

Sets the TableCellRenderer used to draw the TableColumn's header to headerRenderer.

setHeaderValue(Object) - Method in class javax.swing.table.TableColumn

Sets the Object whose string representation will be used as the value for the headerRenderer.

setHeight(Spring) - Method in class javax.swing.SpringLayout.Constraints

Sets the height property, which controls the height of a component.

setHelpMenu(Menu) - Method in class java.awt.MenuBar

Sets the specified menu to be this menu bar's help menu.

setHelpMenu(JMenu) - Method in class javax.swing.JMenuBar

Sets the help menu that appears when the user selects the "help" option in the menu bar.

setHgap(int) - Method in class java.awt.BorderLayout

Sets the horizontal gap between components.

setHgap(int) - Method in class java.awt.CardLayout

Sets the horizontal gap between components.

setHgap(int) - Method in class java.awt.FlowLayout

Sets the horizontal gap between components and between the components and the borders of the Container.

setHgap(int) - Method in class java.awt.GridLayout

Sets the horizontal gap between components to the specified value.

setHidden(boolean) - Method in class java.beans.FeatureDescriptor

The "hidden" flag is used to identify features that are intended only for tool use, and which should not be exposed to humans.

setHidden(boolean) - Method in interface java.nio.file.attribute.DosFileAttributeView

Updates the value of the hidden attribute.

setHideActionText(boolean) - Method in class javax.swing.AbstractButton

Sets the hideActionText property, which determines whether the button displays text from the Action.

setHighlighter(Highlighter) - Method in class javax.swing.text.JTextComponent

Sets the highlighter to be used.

setHints(int) - Method in class java.awt.image.AreaAveragingScaleFilter

Detect if the data is being delivered with the necessary hints to allow the averaging algorithm to do its work.

setHints(int) - Method in interface java.awt.image.ImageConsumer

Sets the hints that the ImageConsumer uses to process the pixels delivered by the ImageProducer.

setHints(int) - Method in class java.awt.image.ImageFilter

Filters the information provided in the setHints method of the ImageConsumer interface.

setHints(int) - Method in class java.awt.image.PixelGrabber

The setHints method is part of the ImageConsumer API which this class must implement to retrieve the pixels.

setHoldability(int) - Method in interface java.sql.Connection

Changes the default holdability of ResultSet objects created using this Connection object to the given holdability.

setHonorsVisibility(boolean) - Method in class javax.swing.GroupLayout

Sets whether component visiblity is considered when sizing and positioning components.

setHonorsVisibility(Component, Boolean) - Method in class javax.swing.GroupLayout

Sets whether the component's visiblity is considered for sizing and positioning.

setHorizontalAlignment(int) - Method in class javax.swing.AbstractButton

Sets the horizontal alignment of the icon and text.

setHorizontalAlignment(int) - Method in class javax.swing.JLabel

Sets the alignment of the label's contents along the X axis.

setHorizontalAlignment(int) - Method in class javax.swing.JTextField

Sets the horizontal alignment of the text.

setHorizontalGroup(GroupLayout.Group) - Method in class javax.swing.GroupLayout

Sets the Group that positions and sizes components along the horizontal axis.

setHorizontalScrollBar(JScrollBar) - Method in class javax.swing.JScrollPane

Adds the scrollbar that controls the viewport's horizontal view position to the scrollpane.

setHorizontalScrollBarPolicy(int) - Method in class javax.swing.JScrollPane

Determines when the horizontal scrollbar appears in the scrollpane.

setHorizontalScrollBarPolicy(int) - Method in class javax.swing.ScrollPaneLayout

Sets the horizontal scrollbar-display policy.

setHorizontalTextPosition(int) - Method in class javax.swing.AbstractButton

Sets the horizontal position of the text relative to the icon.

setHorizontalTextPosition(int) - Method in class javax.swing.JLabel

Sets the horizontal position of the label's text, relative to its image.

setHostnameVerifier(HostnameVerifier) - Method in class javax.naming.ldap.StartTlsResponse

Sets the hostname verifier used by negotiate() after the TLS handshake has completed and the default hostname verification has failed.

setHostnameVerifier(HostnameVerifier) - Method in class javax.net.ssl.HttpsURLConnection

Sets the HostnameVerifier for this instance.

setHour(int) - Method in class javax.xml.datatype.XMLGregorianCalendar

Set hours.

setHours(int) - Method in class java.sql.Date

Deprecated.

setHours(int) - Method in class java.util.Date

Deprecated.
As of JDK version 1.1, replaced by Calendar.set(Calendar.HOUR_OF_DAY, int hours).

setHttpOnly(boolean) - Method in class java.net.HttpCookie

Indicates whether the cookie should be considered HTTP Only.

setHumanPresentableName(String) - Method in class java.awt.datatransfer.DataFlavor

Sets the human presentable name for the data format that this DataFlavor represents.

setHumanPresentableName(String) - Method in class javax.activation.ActivationDataFlavor

Set the human presentable name.

setIcon(Icon) - Method in class javax.swing.AbstractButton

Sets the button's default icon.

setIcon(boolean) - Method in class javax.swing.JInternalFrame

Iconifies or de-iconifies this internal frame, if the look and feel supports iconification.

setIcon(Icon) - Method in class javax.swing.JLabel

Defines the icon this component will display.

setIcon(Icon) - Method in class javax.swing.JOptionPane

Sets the icon to display.

setIcon(MutableAttributeSet, Icon) - Static method in class javax.swing.text.StyleConstants

Sets the icon attribute.

setIconAt(int, Icon) - Method in class javax.swing.JTabbedPane

Sets the icon at index to icon which can be null.

setIconifiable(boolean) - Method in class javax.swing.JInternalFrame

Sets the iconable property, which must be true for the user to be able to make the JInternalFrame an icon.

setIconImage(Image) - Method in class java.awt.Frame

Sets the image to be displayed as the icon for this window.

setIconImage(Image) - Method in class java.awt.Window

Sets the image to be displayed as the icon for this window.

setIconImage(Image) - Method in class javax.swing.JFrame

Sets the image to be displayed as the icon for this window.

setIconImages(List<? extends Image>) - Method in class java.awt.Window

Sets the sequence of images to be displayed as the icon for this window.

setIconOnly(boolean) - Method in class javax.swing.plaf.metal.MetalComboBoxButton

setIconTextGap(int) - Method in class javax.swing.AbstractButton

If both the icon and text properties are set, this property defines the space between them.

setIconTextGap(int) - Method in class javax.swing.JLabel

If both the icon and text properties are set, this property defines the space between them.

setID(String) - Method in class java.util.TimeZone

Sets the time zone ID.

setIdAttribute(String, boolean) - Method in class javax.imageio.metadata.IIOMetadataNode

This DOM Level 3 method is not supported for IIOMetadataNode and will throw a DOMException.

setIdAttribute(String, boolean) - Method in interface org.w3c.dom.Element

If the parameter isId is true, this method declares the specified attribute to be a user-determined ID attribute .

setIdAttributeNode(Attr, boolean) - Method in class javax.imageio.metadata.IIOMetadataNode

This DOM Level 3 method is not supported for IIOMetadataNode and will throw a DOMException.

setIdAttributeNode(Attr, boolean) - Method in interface org.w3c.dom.Element

If the parameter isId is true, this method declares the specified attribute to be a user-determined ID attribute .

setIdAttributeNS(String, String, boolean) - Method in class javax.imageio.metadata.IIOMetadataNode

This DOM Level 3 method is not supported for IIOMetadataNode and will throw a DOMException.

setIdAttributeNS(Element, String, String) - Method in class javax.xml.crypto.dom.DOMCryptoContext

Registers the element's attribute specified by the namespace URI and local name to be of type ID.

setIdAttributeNS(String, String, boolean) - Method in interface org.w3c.dom.Element

If the parameter isId is true, this method declares the specified attribute to be a user-determined ID attribute .

setIdentifier(Object) - Method in class javax.swing.table.TableColumn

Sets the TableColumn's identifier to anIdentifier.

setIfModifiedSince(long) - Method in class java.net.URLConnection

Sets the value of the ifModifiedSince field of this URLConnection to the specified value.

setIgnoreRepaint(boolean) - Method in class java.awt.Component

Sets whether or not paint messages received from the operating system should be ignored.

setIgnoringComments(boolean) - Method in class javax.xml.parsers.DocumentBuilderFactory

Specifies that the parser produced by this code will ignore comments.

setIgnoringElementContentWhitespace(boolean) - Method in class javax.xml.parsers.DocumentBuilderFactory

Specifies that the parsers created by this factory must eliminate whitespace in element content (sometimes known loosely as 'ignorable whitespace') when parsing XML documents (see XML Rec 2.10).

setImage(Image) - Method in class java.awt.TrayIcon

Sets the image for this TrayIcon.

setImage(Image) - Method in class javax.swing.ImageIcon

Sets the image displayed by this icon.

setImageableArea(double, double, double, double) - Method in class java.awt.print.Paper

Sets the imageable area of this Paper.

setImageAutoSize(boolean) - Method in class java.awt.TrayIcon

Sets the auto-size property.

setImageObserver(ImageObserver) - Method in class javax.swing.ImageIcon

Sets the image observer for the image.

setImageURL(URL) - Method in class java.awt.SplashScreen

Changes the splash screen image.

setImplementation(Object) - Method in class javax.management.StandardMBean

Replace the implementation object wrapped in this object.

setImplicitDownCycleTraversal(boolean) - Method in class java.awt.ContainerOrderFocusTraversalPolicy

Sets whether this ContainerOrderFocusTraversalPolicy transfers focus down-cycle implicitly.

setImplicitDownCycleTraversal(boolean) - Method in class javax.swing.SortingFocusTraversalPolicy

Sets whether this SortingFocusTraversalPolicy transfers focus down-cycle implicitly.

setIn(InputStream) - Static method in class java.lang.System

Reassigns the "standard" input stream.

setInDefaultEventSet(boolean) - Method in class java.beans.EventSetDescriptor

Marks an event set as being in the "default" set (or not).

setIndentSpace(int) - Method in class javax.swing.text.AbstractWriter

Enables subclasses to specify how many spaces an indent maps to.

setIndeterminate(boolean) - Method in class javax.swing.JProgressBar

Sets the indeterminate property of the progress bar, which determines whether the progress bar is in determinate or indeterminate mode.

setIndex(int) - Method in interface java.text.CharacterIterator

Sets the position to the specified position in the text and returns that character.

setIndex(int) - Method in class java.text.ParsePosition

Set the current parse position.

setIndex(int) - Method in class java.text.StringCharacterIterator

Implements CharacterIterator.setIndex() for String.

setIndex(int) - Method in class javax.swing.text.Segment

Sets the position to the specified position in the text and returns that character.

setIndexedReadMethod(Method) - Method in class java.beans.IndexedPropertyDescriptor

Sets the method that should be used to read an indexed property value.

setIndexedWriteMethod(Method) - Method in class java.beans.IndexedPropertyDescriptor

Sets the method that should be used to write an indexed property value.

setInfinity(String) - Method in class java.text.DecimalFormatSymbols

Sets the string used to represent infinity.

setInfo(String) - Method in class java.security.Identity

Deprecated.

Specifies a general information string for this identity.

setInheritsPopupMenu(boolean) - Method in class javax.swing.JComponent

Sets whether or not getComponentPopupMenu should delegate to the parent if this component does not have a JPopupMenu assigned to it.

setInitialContextFactoryBuilder(InitialContextFactoryBuilder) - Static method in class javax.naming.spi.NamingManager

Sets the InitialContextFactory builder to be builder.

setInitialDelay(int) - Method in class javax.swing.Timer

Sets the Timer's initial delay, the time in milliseconds to wait after the timer is started before firing the first event.

setInitialDelay(int) - Method in class javax.swing.ToolTipManager

Specifies the initial delay value.

setInitialPolicies(Set<String>) - Method in class java.security.cert.PKIXParameters

Sets the Set of initial policy identifiers (OID strings), indicating that any one of these policies would be acceptable to the certificate user for the purposes of certification path processing.

setInitialSelectionValue(Object) - Method in class javax.swing.JOptionPane

Sets the input value that is initially displayed as selected to the user.

setInitialValue(Object) - Method in class javax.swing.JOptionPane

Sets the initial value that is to be enabled -- the Component that has the focus when the pane is initially displayed.

setInitThreshold(Number) - Method in class javax.management.monitor.CounterMonitor

Sets the initial threshold value common to all observed objects.

setInitThreshold(Number) - Method in interface javax.management.monitor.CounterMonitorMBean

Sets the initial threshold value common to all observed MBeans.

setInnerHTML(Element, String) - Method in class javax.swing.text.html.HTMLDocument

Replaces the children of the given element with the contents specified as an HTML string.

setInput(byte[], int, int) - Method in class java.util.zip.Deflater

Sets input data for compression.

setInput(byte[]) - Method in class java.util.zip.Deflater

Sets input data for compression.

setInput(byte[], int, int) - Method in class java.util.zip.Inflater

Sets input data for decompression.

setInput(byte[]) - Method in class java.util.zip.Inflater

Sets input data for decompression.

setInput(Object, boolean, boolean) - Method in class javax.imageio.ImageReader

Sets the input source to use to the given ImageInputStream or other Object.

setInput(Object, boolean) - Method in class javax.imageio.ImageReader

Sets the input source to use to the given ImageInputStream or other Object.

setInput(Object) - Method in class javax.imageio.ImageReader

Sets the input source to use to the given ImageInputStream or other Object.

setInputMap(int, InputMap) - Method in class javax.swing.JComponent

Sets the InputMap to use under the condition condition to map.

setInputMethodContext(InputMethodContext) - Method in interface java.awt.im.spi.InputMethod

Sets the input method context, which is used to dispatch input method events to the client component and to request information from the client component.

setInputSource(InputSource) - Method in class javax.xml.transform.sax.SAXSource

Set the SAX InputSource to be used for the Source.

setInputStream(InputStream) - Method in class javax.xml.transform.stream.StreamSource

Set the byte stream to be used as input.

setInputValue(Object) - Method in class javax.swing.JOptionPane

Sets the input value that was selected or input by the user.

setInputVerifier(InputVerifier) - Method in class javax.swing.JComponent

Sets the input verifier for this component.

setInsets(short, short, short, short) - Method in class javax.swing.text.CompositeView

Sets the insets for the view.

setInstalledLookAndFeels(UIManager.LookAndFeelInfo[]) - Static method in class javax.swing.UIManager

Sets the set of available look and feels.

setInstance(LayoutStyle) - Static method in class javax.swing.LayoutStyle

Sets the shared instance of LayoutStyle.

setInstanceFollowRedirects(boolean) - Method in class java.net.HttpURLConnection

Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this HttpURLConnection instance.

setInt(Object, int, int) - Static method in class java.lang.reflect.Array

Sets the value of the indexed component of the specified array object to the specified int value.

setInt(Object, int) - Method in class java.lang.reflect.字段

Sets the value of a field as an int on the specified object.

setInt(String, int) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given Java int value.

setInt(int, int) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given Java int value.

setInt(int, int) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to an int in the Java programming language.

setInt(String, int) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given Java int value.

setInt(int, int) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command to the given Java int value.

setInt(String, int) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given Java int value.

setIntercellSpacing(Dimension) - Method in class javax.swing.JTable

Sets the rowMargin and the columnMargin -- the height and width of the space between cells -- to intercellSpacing.

setInterface(InetAddress) - Method in class java.net.MulticastSocket

Set the multicast network interface used by methods whose behavior would be affected by the value of the network interface.

setInternalFrame(JInternalFrame) - Method in class javax.swing.JInternalFrame.JDesktopIcon

Sets the JInternalFrame with which this DesktopIcon is associated.

setInternationalCurrencySymbol(String) - Method in class java.text.DecimalFormatSymbols

Sets the ISO 4217 currency code of the currency of these DecimalFormatSymbols.

setInvalidCharacters(String) - Method in class javax.swing.text.MaskFormatter

Allows for further restricting of the characters that can be input.

setInverted(boolean) - Method in class javax.swing.JSlider

Specify true to reverse the value-range shown for the slider and false to put the value range in the normal order.

setInvoker(Component) - Method in class javax.swing.JPopupMenu

Sets the invoker of this popup menu -- the component in which the popup menu menu is to be displayed.

setInvokesStopCellEditing(boolean) - Method in class javax.swing.JTree

Determines what happens when editing is interrupted by selecting another node in the tree, a change in the tree's data, or by some other means.

setIssuer(X500Principal) - Method in class java.security.cert.X509CertSelector

Sets the issuer criterion.

setIssuer(String) - Method in class java.security.cert.X509CertSelector

Denigrated, use X509CertSelector.setIssuer(X500Principal) or X509CertSelector.setIssuer(byte[]) instead.

setIssuer(byte[]) - Method in class java.security.cert.X509CertSelector

Sets the issuer criterion.

setIssuerNames(Collection<?>) - Method in class java.security.cert.X509CRLSelector

Note: use X509CRLSelector.setIssuers(Collection) instead or only specify the byte array form of distinguished names when using this method.

setIssuers(Collection<X500Principal>) - Method in class java.security.cert.X509CRLSelector

Sets the issuerNames criterion.

setItalic(MutableAttributeSet, boolean) - Static method in class javax.swing.text.StyleConstants

Sets the italic attribute.

setItem(Object) - Method in interface javax.swing.ComboBoxEditor

Set the item that should be edited.

setItem(Object) - Method in class javax.swing.plaf.basic.BasicComboBoxEditor

Sets the item that should be edited.

setJMenuBar(JMenuBar) - Method in class javax.swing.JApplet

Sets the menubar for this applet.

setJMenuBar(JMenuBar) - Method in class javax.swing.JDialog

Sets the menubar for this dialog.

setJMenuBar(JMenuBar) - Method in class javax.swing.JFrame

Sets the menubar for this frame.

setJMenuBar(JMenuBar) - Method in class javax.swing.JInternalFrame

Sets the menuBar property for this JInternalFrame.

setJMenuBar(JMenuBar) - Method in class javax.swing.JRootPane

Adds or changes the menu bar used in the layered pane.

setJNDIContext(Context) - Static method in class javax.sql.rowset.spi.SyncFactory

Sets the initial JNDI context from which SyncProvider implementations can be retrieved from a JNDI namespace

setJobName(String) - Method in class java.awt.print.PrinterJob

Sets the name of the document to be printed.

setJoinType(int) - Method in interface javax.sql.rowset.JoinRowSet

Allow the application to adjust the type of JOIN imposed on tables contained within the JoinRowSet object instance.

setJustification(int) - Method in class javax.swing.text.ParagraphView

Sets the type of justification.

setKeepAlive(boolean) - Method in class java.net.Socket

Enable/disable SO_KEEPALIVE.

setKeepAliveTime(long, TimeUnit) - Method in class java.util.concurrent.ThreadPoolExecutor

Sets the time limit for which threads may remain idle before being terminated.

setKeyBindingActive(boolean) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI

setKeyBindingRegistered(boolean) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI

setKeyChar(char) - Method in class java.awt.event.KeyEvent

Set the keyChar value to indicate a logical character.

setKeyCode(int) - Method in class java.awt.event.KeyEvent

Set the keyCode value to indicate a physical key.

setKeyColumns(int[]) - Method in interface javax.sql.rowset.CachedRowSet

Sets this CachedRowSet object's keyCols field with the given array of column numbers, which forms a key for uniquely identifying a row in this CachedRowSet object.

setKeyEntry(String, Key, char[], Certificate[]) - Method in class java.security.KeyStore

Assigns the given key to the given alias, protecting it with the given password.

setKeyEntry(String, byte[], Certificate[]) - Method in class java.security.KeyStore

Assigns the given key (that has already been protected) to the given alias.

setKeymap(Keymap) - Method in class javax.swing.text.JTextComponent

Sets the keymap to use for binding events to actions.

setKeyPair(KeyPair) - Method in class java.security.Signer

Deprecated.

Sets the key pair (public key and private key) for this signer.

setKeySelectionManager(JComboBox.KeySelectionManager) - Method in class javax.swing.JComboBox

Sets the object that translates a keyboard character into a list selection.

setKeySelector(KeySelector) - Method in class javax.xml.crypto.dom.DOMCryptoContext

setKeySelector(KeySelector) - Method in interface javax.xml.crypto.XMLCryptoContext

Sets the key selector for finding a key.

setKeyUsage(boolean[]) - Method in class java.security.cert.X509CertSelector

Sets the keyUsage criterion.

setLabel(String) - Method in class java.awt.Button

Sets the button's label to be the specified string.

setLabel(String) - Method in class java.awt.Checkbox

Sets this check box's label to be the string argument.

setLabel(String) - Method in class java.awt.MenuItem

Sets the label for this menu item to the specified label.

setLabel(String) - Method in class javax.swing.AbstractButton

Deprecated.
- Replaced by setText(text)

setLabel(String) - Method in class javax.swing.JPopupMenu

Sets the popup menu's label.

setLabel(String) - Method in class javax.swing.text.html.Option

Sets the label to be used for the option.

setLabelFor(Component) - Method in class javax.swing.JLabel

Set the component this is labelling.

setLabelTable(Dictionary) - Method in class javax.swing.JSlider

Used to specify what label will be drawn at any given value.

setLanguage(String) - Method in class java.util.Locale.Builder

Sets the language.

setLanguageTag(String) - Method in class java.util.Locale.Builder

Resets the Builder to match the provided IETF BCP 47 language tag.

setLargeModel(boolean) - Method in class javax.swing.JTree

Specifies whether the UI should use a large model.

setLargeModel(boolean) - Method in class javax.swing.plaf.basic.BasicTreeUI

Updates the componentListener, if necessary.

setLastDividerLocation(int) - Method in class javax.swing.JSplitPane

Sets the last location the divider was at to newLastLocation.

setLastDragLocation(int) - Method in class javax.swing.plaf.basic.BasicSplitPaneUI

Set the last drag location of the JSplitPane.

setLastModified(long) - Method in class java.io.File

Sets the last-modified time of the file or directory named by this abstract pathname.

setLastModifiedTime(Path, FileTime) - Static method in class java.nio.file.Files

Updates a file's last modified time attribute.

setLayer(Integer) - Method in class javax.swing.JInternalFrame

Convenience method for setting the layer attribute of this component.

setLayer(int) - Method in class javax.swing.JInternalFrame

Convenience method for setting the layer attribute of this component.

setLayer(Component, int) - Method in class javax.swing.JLayeredPane

Sets the layer attribute on the specified component, making it the bottommost component in that layer.

setLayer(Component, int, int) - Method in class javax.swing.JLayeredPane

Sets the layer attribute for the specified component and also sets its position within that layer.

setLayeredPane(JLayeredPane) - Method in class javax.swing.JApplet

Sets the layeredPane property.

setLayeredPane(JLayeredPane) - Method in class javax.swing.JDialog

Sets the layeredPane property.

setLayeredPane(JLayeredPane) - Method in class javax.swing.JFrame

Sets the layeredPane property.

setLayeredPane(JLayeredPane) - Method in class javax.swing.JInternalFrame

Sets this JInternalFrame's layeredPane property.

setLayeredPane(JLayeredPane) - Method in class javax.swing.JRootPane

Sets the layered pane for the root pane.

setLayeredPane(JLayeredPane) - Method in class javax.swing.JWindow

Sets the layeredPane property.

setLayeredPane(JLayeredPane) - Method in interface javax.swing.RootPaneContainer

A Container that manages the contentPane and in some cases a menu bar.

setLayerEventMask(long) - Method in class javax.swing.JLayer

Enables the events from JLayer and all its descendants defined by the specified event mask parameter to be delivered to the LayerUI.eventDispatched(AWTEvent, JLayer) method.

setLayout(LayoutManager) - Method in class java.awt.Container

Sets the layout manager for this container.

setLayout(LayoutManager) - Method in class java.awt.ScrollPane

Sets the layout manager for this container.

setLayout(LayoutManager) - Method in class javax.swing.AbstractButton

Sets the layout manager for this container, refer to Container.setLayout(LayoutManager) for a complete description of this method.

setLayout(LayoutManager) - Method in class javax.swing.Box

Throws an AWTError, since a Box can use only a BoxLayout.

setLayout(LayoutManager) - Method in class javax.swing.JApplet

Sets the LayoutManager.

setLayout(LayoutManager) - Method in class javax.swing.JDialog

Sets the LayoutManager.

setLayout(LayoutManager) - Method in class javax.swing.JFrame

Sets the LayoutManager.

setLayout(LayoutManager) - Method in class javax.swing.JInternalFrame

Ensures that, by default, the layout of this component cannot be set.

setLayout(LayoutManager) - Method in class javax.swing.JLayer

Sets the layout manager for this container.

setLayout(LayoutManager) - Method in class javax.swing.JScrollPane

Sets the layout manager for this JScrollPane.

setLayout(LayoutManager) - Method in class javax.swing.JToolBar

setLayout(LayoutManager) - Method in class javax.swing.JWindow

Sets the LayoutManager.

setLayoutOrientation(int) - Method in class javax.swing.JList

Defines the way list cells are layed out.

setLayoutStyle(LayoutStyle) - Method in class javax.swing.GroupLayout

Sets the LayoutStyle used to calculate the preferred gaps between components.

setLeadAnchorNotificationEnabled(boolean) - Method in class javax.swing.DefaultListSelectionModel

Sets the value of the leadAnchorNotificationEnabled flag.

setLeadSelectionIndex(int) - Method in class javax.swing.DefaultListSelectionModel

Sets the lead selection index, ensuring that values between the anchor and the new lead are either all selected or all deselected.

setLeadSelectionIndex(int) - Method in interface javax.swing.ListSelectionModel

Set the lead selection index.

setLeadSelectionPath(TreePath) - Method in class javax.swing.JTree

Sets the path identifies as the lead.

setLeafIcon(Icon) - Method in class javax.swing.tree.DefaultTreeCellRenderer

Sets the icon used to represent leaf nodes.

setLeftChildIndent(int) - Method in class javax.swing.plaf.basic.BasicTreeUI

setLeftComponent(Component) - Method in class javax.swing.JSplitPane

Sets the component to the left (or above) the divider.

setLeftIndent(MutableAttributeSet, float) - Static method in class javax.swing.text.StyleConstants

Sets left indent.

setLeftInset(float) - Method in class javax.swing.text.AsyncBoxView

Set the left part of the margin around the view.

setLength(long) - Method in class java.io.RandomAccessFile

Sets the length of this file.

setLength(int) - Method in class java.lang.StringBuffer

setLength(int) - Method in class java.net.DatagramPacket

Set the length for this packet.

setLength(int) - Method in class javax.imageio.stream.IIOByteBuffer

Updates the value that will be returned by subsequent calls to the getLength method.

setLenient(boolean) - Method in class java.text.DateFormat

Specify whether or not date/time parsing is to be lenient.

setLenient(boolean) - Method in class java.util.Calendar

Specifies whether or not date/time interpretation is to be lenient.

setLevel(Level) - Method in class java.util.logging.Handler

Set the log level specifying which message levels will be logged by this Handler.

setLevel(Level) - Method in class java.util.logging.Logger

Set the log level specifying which message levels will be logged by this logger.

setLevel(Level) - Method in class java.util.logging.LogRecord

Set the logging message level, for example Level.SEVERE.

setLevel(int) - Method in class java.util.zip.Deflater

Sets the current compression level to the specified value.

setLevel(int) - Method in class java.util.zip.ZipOutputStream

Sets the compression level for subsequent entries which are DEFLATED.

setLexicalHandler(LexicalHandler) - Method in class javax.xml.transform.sax.SAXResult

Set the SAX2 LexicalHandler for the output.

setLibraryDirectory(String) - Method in class javax.management.loading.MLet

Sets the directory used by the library loader for storing native libraries before they are loaded into memory.

setLibraryDirectory(String) - Method in interface javax.management.loading.MLetMBean

Sets the directory used by the library loader for storing native libraries before they are loaded into memory.

setLightWeightPopupEnabled(boolean) - Method in class javax.swing.JComboBox

Sets the lightWeightPopupEnabled property, which provides a hint as to whether or not a lightweight Component should be used to contain the JComboBox, versus a heavyweight Component such as a Panel or a Window.

setLightWeightPopupEnabled(boolean) - Method in class javax.swing.JPopupMenu

Sets the value of the lightWeightPopupEnabled property, which by default is true.

setLightWeightPopupEnabled(boolean) - Method in class javax.swing.ToolTipManager

When displaying the JToolTip, the ToolTipManager chooses to use a lightweight JPanel if it fits.

setLimit(int) - Method in class javax.swing.undo.UndoManager

Sets the maximum number of edits this UndoManager holds.

setLine(double, double, double, double) - Method in class java.awt.geom.Line2D.Double

Sets the location of the end points of this Line2D to the specified double coordinates.

setLine(double, double, double, double) - Method in class java.awt.geom.Line2D.Float

Sets the location of the end points of this Line2D to the specified double coordinates.

setLine(float, float, float, float) - Method in class java.awt.geom.Line2D.Float

Sets the location of the end points of this Line2D to the specified float coordinates.

setLine(double, double, double, double) - Method in class java.awt.geom.Line2D

Sets the location of the end points of this Line2D to the specified double coordinates.

setLine(Point2D, Point2D) - Method in class java.awt.geom.Line2D

Sets the location of the end points of this Line2D to the specified Point2D coordinates.

setLine(Line2D) - Method in class java.awt.geom.Line2D

Sets the location of the end points of this Line2D to the same as those end points of the specified Line2D.

setLineIncrement(int) - Method in class java.awt.Scrollbar

Deprecated.
As of JDK version 1.1, replaced by setUnitIncrement(int).

setLineLength(int) - Method in class javax.swing.text.AbstractWriter

Enables subclasses to set the number of characters they want written per line.

setLineNumber(int) - Method in class java.io.LineNumberInputStream

Deprecated.

Sets the line number to the specified argument.

setLineNumber(int) - Method in class java.io.LineNumberReader

Set the current line number.

setLineNumber(int) - Method in class javax.xml.bind.helpers.ValidationEventLocatorImpl

Set the lineNumber field on this event locator.

setLineNumber(int) - Method in class org.xml.sax.helpers.LocatorImpl

Set the line number for this locator (1-based).

setLineSeparator(String) - Method in class javax.swing.text.AbstractWriter

Sets the String used to reprsent newlines.

setLineSpacing(float) - Method in class javax.swing.text.ParagraphView

Sets the line spacing.

setLineSpacing(MutableAttributeSet, float) - Static method in class javax.swing.text.StyleConstants

Sets line spacing.

setLineWrap(boolean) - Method in class javax.swing.JTextArea

Sets the line-wrapping policy of the text area.

setLinkCursor(Cursor) - Method in class javax.swing.text.html.HTMLEditorKit

Sets the cursor to use over links.

setLinkedException(Throwable) - Method in class javax.xml.bind.helpers.ValidationEventImpl

Set the linked exception field of this event.

setLinkedException(Throwable) - Method in exception javax.xml.bind.JAXBException

Add a linked Exception.

setLinkedException(Throwable) - Method in exception javax.xml.bind.TypeConstraintException

Add a linked Exception.

setLinkExplanation(String) - Method in exception javax.naming.LinkException

Sets the explanation associated with the problem encounter when resolving a link.

setLinkRemainingName(Name) - Method in exception javax.naming.LinkException

Sets the remaining link name field of this exception.

setLinkResolvedName(Name) - Method in exception javax.naming.LinkException

Sets the resolved link name field of this exception.

setLinkResolvedObj(Object) - Method in exception javax.naming.LinkException

Sets the link resolved object field of this exception.

setList(List<?>) - Method in class javax.swing.SpinnerListModel

Changes the list that defines this sequence and resets the index of the models value to zero.

setListData(E[]) - Method in class javax.swing.JList

Constructs a read-only ListModel from an array of items, and calls setModel with this model.

setListData(Vector<? extends E>) - Method in class javax.swing.JList

Constructs a read-only ListModel from a Vector and calls setModel with this model.

setListener(Marshaller.Listener) - Method in class javax.xml.bind.helpers.AbstractMarshallerImpl

setListener(Unmarshaller.Listener) - Method in class javax.xml.bind.helpers.AbstractUnmarshallerImpl

setListener(Marshaller.Listener) - Method in interface javax.xml.bind.Marshaller

Register marshal event callback Marshaller.Listener with this Marshaller.

setListener(Unmarshaller.Listener) - Method in interface javax.xml.bind.Unmarshaller

Register unmarshal event callback Unmarshaller.Listener with this Unmarshaller.

setLoadsSynchronously(boolean) - Method in class javax.swing.text.html.ImageView

Sets how the image is loaded.

setLocale(Locale) - Method in class java.awt.Component

Sets the locale of this component.

setLocale(Locale) - Method in interface java.awt.im.spi.InputMethod

Attempts to set the input locale.

setLocale(Locale) - Method in class java.beans.beancontext.BeanContextSupport

Sets the locale of this BeanContext.

setLocale(Locale) - Method in class java.text.MessageFormat

Sets the locale to be used when creating or comparing subformats.

setLocale(Locale) - Method in class java.util.Locale.Builder

Resets the Builder to match the provided locale.

setLocale(Locale) - Method in class javax.imageio.ImageReader

Sets the current Locale of this ImageReader to the given value.

setLocale(Locale) - Method in class javax.imageio.ImageWriter

Sets the current Locale of this ImageWriter to the given value.

setLocale(Locale) - Method in class javax.security.auth.callback.LanguageCallback

Set the retrieved Locale.

setLocale(Locale) - Method in interface javax.tools.JavaCompiler.CompilationTask

Set the locale to be applied when formatting diagnostics and other localized data.

setLocale(Locale) - Method in class org.xml.sax.helpers.XMLReaderAdapter

Set the locale for error reporting.

setLocale(Locale) - Method in interface org.xml.sax.Parser

Deprecated.

Allow an application to request a locale for errors and warnings.

setLocalName(int, String) - Method in class org.xml.sax.helpers.AttributesImpl

Set the local name of a specific attribute.

setLocalPatternChars(String) - Method in class java.text.DateFormatSymbols

Sets localized date-time pattern characters.

setLocation(Point) - Method in class java.awt.Component.AccessibleAWTComponent

Sets the location of the object relative to the parent.

setLocation(int, int) - Method in class java.awt.Component

Moves this component to a new location.

setLocation(Point) - Method in class java.awt.Component

Moves this component to a new location.

setLocation(double, double) - Method in class java.awt.geom.Point2D.Double

Sets the location of this Point2D to the specified double coordinates.

setLocation(double, double) - Method in class java.awt.geom.Point2D.Float

Sets the location of this Point2D to the specified double coordinates.

setLocation(float, float) - Method in class java.awt.geom.Point2D.Float

Sets the location of this Point2D to the specified float coordinates.

setLocation(double, double) - Method in class java.awt.geom.Point2D

Sets the location of this Point2D to the specified double coordinates.

setLocation(Point2D) - Method in class java.awt.geom.Point2D

Sets the location of this Point2D to the same coordinates as the specified Point2D object.

setLocation(Point) - Method in class java.awt.List.AccessibleAWTList.AccessibleAWTListChild

Sets the location of the object relative to the parent.

setLocation(Point) - Method in class java.awt.MenuComponent.AccessibleAWTMenuComponent

Sets the location of the object relative to the parent.

setLocation(Point) - Method in class java.awt.Point

Sets the location of the point to the specified location.

setLocation(int, int) - Method in class java.awt.Point

Changes the point to have the specified location.

setLocation(double, double) - Method in class java.awt.Point

Sets the location of this point to the specified double coordinates.

setLocation(Point) - Method in class java.awt.Rectangle

Moves this Rectangle to the specified location.

setLocation(int, int) - Method in class java.awt.Rectangle

Moves this Rectangle to the specified location.

setLocation(Point) - Method in interface javax.accessibility.AccessibleComponent

Sets the location of the object relative to the parent.

setLocation(Point) - Method in class javax.swing.JList.AccessibleJList.AccessibleJListChild

setLocation(int, int) - Method in class javax.swing.JPopupMenu

Sets the location of the upper left corner of the popup menu using x, y coordinates.

setLocation(Point) - Method in class javax.swing.JTable.AccessibleJTable.AccessibleJTableCell

Sets the location of the object relative to the parent.

setLocation(Point) - Method in class javax.swing.JTree.AccessibleJTree.AccessibleJTreeNode

setLocation(Point) - Method in class javax.swing.table.JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry

setLocation(JavaFileManager.Location, Iterable<? extends File>) - Method in interface javax.tools.StandardJavaFileManager

Associates the given path with the given location.

setLocation(Location) - Method in class javax.xml.stream.XMLEventFactory

This method allows setting of the Location on each event that is created by this factory.

setLocationByPlatform(boolean) - Method in class java.awt.Window

Sets whether this Window should appear at the default location for the native windowing system or at the current location (returned by getLocation) the next time the Window is made visible.

setLocationRelativeTo(Component) - Method in class java.awt.Window

Sets the location of the window relative to the specified component according to the following scenarios.

setLocator(ValidationEventLocator) - Method in class javax.xml.bind.helpers.ValidationEventImpl

Set the locator object for this event.

setLocator(SourceLocator) - Method in exception javax.xml.transform.TransformerException

Method setLocator sets an instance of a SourceLocator object that specifies where an error occured.

setLockingKeyState(int, boolean) - Method in class java.awt.Toolkit

Sets the state of the given locking key on the keyboard.

setLog(OutputStream) - Static method in class java.rmi.server.RemoteServer

Log RMI calls to the output stream out.

setLogger(Logger) - Static method in class javax.sql.rowset.spi.SyncFactory

Sets the logging object to be used by the SyncProvider implementation provided by the SyncFactory.

setLogger(Logger, Level) - Static method in class javax.sql.rowset.spi.SyncFactory

Sets the logging object that is used by SyncProvider implementations provided by the SyncFactory SPI.

setLoggerLevel(String, String) - Method in interface java.lang.management.PlatformLoggingMXBean

Sets the specified logger to the specified new level.

setLoggerLevel(String, String) - Method in interface java.util.logging.LoggingMXBean

Sets the specified logger to the specified new level.

setLoggerName(String) - Method in class java.util.logging.LogRecord

Set the source Logger's name.

setLogicalStyle(Style) - Method in class javax.swing.JTextPane

Sets the logical style to use for the paragraph at the current caret position.

setLogicalStyle(int, Style) - Method in class javax.swing.text.DefaultStyledDocument

Sets the logical style to use for the paragraph at the given position.

setLogicalStyle(int, Style) - Method in interface javax.swing.text.StyledDocument

Sets the logical style to use for the paragraph at the given position.

setLoginTimeout(int) - Static method in class java.sql.DriverManager

Sets the maximum time in seconds that a driver will wait while attempting to connect to a database.

setLoginTimeout(int) - Method in interface javax.sql.CommonDataSource

Sets the maximum time in seconds that this data source will wait while attempting to connect to a database.

setLogStream(PrintStream) - Static method in class java.sql.DriverManager

Deprecated.

setLogStream(PrintStream) - Static method in class javax.swing.DebugGraphics

Sets the stream to which the DebugGraphics logs drawing operations.

setLogTimers(boolean) - Static method in class javax.swing.Timer

Enables or disables the timer log.

setLogWriter(PrintWriter) - Static method in class java.sql.DriverManager

Sets the logging/tracing PrintWriter object that is used by the DriverManager and all drivers.

setLogWriter(PrintWriter) - Method in interface javax.sql.CommonDataSource

Sets the log writer for this DataSource object to the given java.io.PrintWriter object.

setLong(Object, int, long) - Static method in class java.lang.reflect.Array

Sets the value of the indexed component of the specified array object to the specified long value.

setLong(Object, long) - Method in class java.lang.reflect.字段

Sets the value of a field as a long on the specified object.

setLong(String, long) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given Java long value.

setLong(int, long) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given Java long value.

setLong(int, long) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given long in the Java programming language.

setLong(String, long) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given Java long value.

setLong(int, long) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command to the given Java long value.

setLong(String, long) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given Java long value.

setLookAndFeel(LookAndFeel) - Static method in class javax.swing.UIManager

Sets the current look and feel to newLookAndFeel.

setLookAndFeel(String) - Static method in class javax.swing.UIManager

Loads the LookAndFeel specified by the given class name, using the current thread's context class loader, and passes it to setLookAndFeel(LookAndFeel).

setLoopbackMode(boolean) - Method in class java.net.MulticastSocket

Disable/Enable local loopback of multicast datagrams The option is used by the platform's networking code as a hint for setting whether multicast data will be looped back to the local socket.

setLoopCount(int) - Method in interface javax.sound.midi.Sequencer

Sets the number of repetitions of the loop for playback.

setLoopEndPoint(long) - Method in interface javax.sound.midi.Sequencer

Sets the last MIDI tick that will be played in the loop.

setLoopPoints(int, int) - Method in interface javax.sound.sampled.Clip

Sets the first and last sample frames that will be played in the loop.

setLoopStartPoint(long) - Method in interface javax.sound.midi.Sequencer

Sets the first MIDI tick that will be played in the loop.

setMagicCaretPosition(Point) - Method in interface javax.swing.text.Caret

Set the current caret visual location.

setMagicCaretPosition(Point) - Method in class javax.swing.text.DefaultCaret

Saves the current caret position.

setMajorOffset(float) - Method in class javax.swing.text.AsyncBoxView.ChildState

This method should only be called by the ChildLocator, it is simply a convenient place to hold the cached location.

setMajorTickSpacing(int) - Method in class javax.swing.JSlider

This method sets the major tick spacing.

setManagedResource(Object, String) - Method in interface javax.management.modelmbean.ModelMBean

Sets the instance handle of the object against which to execute all methods in this ModelMBean management interface (MBeanInfo and Descriptors).

setManagedResource(Object, String) - Method in class javax.management.modelmbean.RequiredModelMBean

Sets the instance handle of the object against which to execute all methods in this ModelMBean management interface (MBeanInfo and Descriptors).

setMargin(Insets) - Method in class javax.swing.AbstractButton

Sets space for margin between the button's border and the label.

setMargin(Insets) - Method in class javax.swing.JMenuBar

Sets the margin between the menubar's border and its menus.

setMargin(Insets) - Method in class javax.swing.JToolBar

Sets the margin between the tool bar's border and its buttons.

setMargin(Insets) - Method in class javax.swing.text.JTextComponent

Sets margin space between the text component's border and its text.

setMask(String) - Method in class javax.swing.text.MaskFormatter

Sets the mask dictating the legal characters.

setMasterSyncMode(Sequencer.SyncMode) - Method in interface javax.sound.midi.Sequencer

Sets the source of timing information used by this sequencer.

setMatchAllSubjectAltNames(boolean) - Method in class java.security.cert.X509CertSelector

Enables/disables matching all of the subjectAlternativeNames specified in the setSubjectAlternativeNames or addSubjectAlternativeName methods.

setMatchColumn(int) - Method in interface javax.sql.rowset.Joinable

Sets the designated column as the match column for this RowSet object.

setMatchColumn(int[]) - Method in interface javax.sql.rowset.Joinable

Sets the designated columns as the match column for this RowSet object.

setMatchColumn(String) - Method in interface javax.sql.rowset.Joinable

Sets the designated column as the match column for this RowSet object.

setMatchColumn(String[]) - Method in interface javax.sql.rowset.Joinable

Sets the designated columns as the match column for this RowSet object.

setMaxAge(long) - Method in class java.net.HttpCookie

Sets the maximum age of the cookie in seconds.

setMaxCRLNumber(BigInteger) - Method in class java.security.cert.X509CRLSelector

Sets the maxCRLNumber criterion.

setMaxFieldSize(int) - Method in interface java.sql.Statement

Sets the limit for the maximum number of bytes that can be returned for character and binary column values in a ResultSet object produced by this Statement object.

setMaxFieldSize(int) - Method in class javax.sql.rowset.BaseRowSet

Sets the maximum number of bytes that can be used for a column value in this RowSet object to the given number.

setMaxFieldSize(int) - Method in interface javax.sql.RowSet

Sets the maximum number of bytes that can be returned for a column value to the given number of bytes.

setMaximizable(boolean) - Method in class javax.swing.JInternalFrame

Sets the maximizable property, which determines whether the JInternalFrame can be maximized by some user action.

setMaximizedBounds(Rectangle) - Method in class java.awt.Frame

Sets the maximized bounds for this frame.

setMaximum(int) - Method in interface java.awt.Adjustable

Sets the maximum value of the adjustable object.

setMaximum(int) - Method in class java.awt.Scrollbar

Sets the maximum value of this scroll bar.

setMaximum(int) - Method in class java.awt.ScrollPaneAdjustable

This method should NOT be called by user code.

setMaximum(int) - Method in interface javax.swing.BoundedRangeModel

Sets the model's maximum to newMaximum.

setMaximum(int) - Method in class javax.swing.DefaultBoundedRangeModel

Sets the maximum to n after ensuring that n that the other three properties obey the model's constraints:

setMaximum(boolean) - Method in class javax.swing.JInternalFrame

Maximizes and restores this internal frame.

setMaximum(int) - Method in class javax.swing.JProgressBar

Sets the progress bar's maximum value (stored in the progress bar's data model) to n.

setMaximum(int) - Method in class javax.swing.JScrollBar

Sets the model's maximum property.

setMaximum(int) - Method in class javax.swing.JSlider

Sets the slider's maximum value to maximum.

setMaximum(int) - Method in class javax.swing.ProgressMonitor

Specifies the maximum value.

setMaximum(Comparable) - Method in class javax.swing.SpinnerNumberModel

Changes the upper bound for numbers in this sequence.

setMaximum(Comparable) - Method in class javax.swing.text.InternationalFormatter

Sets the maximum permissible value.

setMaximumFractionDigits(int) - Method in class java.text.DecimalFormat

Sets the maximum number of digits allowed in the fraction portion of a number.

setMaximumFractionDigits(int) - Method in class java.text.NumberFormat

Sets the maximum number of digits allowed in the fraction portion of a number.

setMaximumIntegerDigits(int) - Method in class java.text.DecimalFormat

Sets the maximum number of digits allowed in the integer portion of a number.

setMaximumIntegerDigits(int) - Method in class java.text.NumberFormat

Sets the maximum number of digits allowed in the integer portion of a number.

setMaximumPoolSize(int) - Method in class java.util.concurrent.ThreadPoolExecutor

Sets the maximum allowed number of threads.

setMaximumRowCount(int) - Method in class javax.swing.JComboBox

Sets the maximum number of rows the JComboBox displays.

setMaximumSize(Dimension) - Method in class java.awt.Component

Sets the maximum size of this component to a constant value.

setMaximumSize(Dimension) - Method in class javax.swing.JComponent

Sets the maximum size of this component to a constant value.

setMaximumZoneSize(int) - Method in class javax.swing.text.ZoneView

Set the desired maximum zone size.

setMaxPage(int) - Method in class java.awt.JobAttributes

Specifies the maximum value the user can specify as the last page to be printed for jobs using these attributes.

setMaxPathLength(int) - Method in class java.security.cert.PKIXBuilderParameters

Sets the value of the maximum number of non-self-issued intermediate certificates that may exist in a certification path.

setMaxPriority(int) - Method in class java.lang.ThreadGroup

Sets the maximum priority of the group.

setMaxRows(int) - Method in interface java.sql.Statement

Sets the limit for the maximum number of rows that any ResultSet object generated by this Statement object can contain to the given number.

setMaxRows(int) - Method in class javax.sql.rowset.BaseRowSet

Sets the maximum number of rows that this RowSet object may contain to the given number.

setMaxRows(int) - Method in interface javax.sql.RowSet

Sets the maximum number of rows that this RowSet object can contain to the specified number.

setMaxSortKeys(int) - Method in class javax.swing.DefaultRowSorter

Sets the maximum number of sort keys.

setMaxWidth(int) - Method in class javax.swing.table.TableColumn

Sets the TableColumn's maximum width to maxWidth or, if maxWidth is less than the minimum width, to the minimum width.

setMaxZonesLoaded(int) - Method in class javax.swing.text.ZoneView

Sets the current setting of the number of zones allowed to be loaded at the same time.

setMBeanDescriptor(Descriptor) - Method in interface javax.management.modelmbean.ModelMBeanInfo

Sets the ModelMBean's descriptor.

setMBeanDescriptor(Descriptor) - Method in class javax.management.modelmbean.ModelMBeanInfoSupport

setMBeanServer(MBeanServer) - Method in class javax.management.AttributeValueExp

Deprecated.
This method has no effect. The MBean Server used to obtain an attribute value is QueryEval.getMBeanServer().

setMBeanServer(MBeanServer) - Method in class javax.management.ObjectName

setMBeanServer(MBeanServer) - Method in class javax.management.QueryEval

Sets the MBean server on which the query is to be performed.

setMBeanServer(MBeanServer) - Method in interface javax.management.QueryExp

Sets the MBean server on which the query is to be performed.

setMBeanServer(MBeanServer) - Method in interface javax.management.remote.MBeanServerForwarder

Sets the MBeanServer object to which requests will be forwarded after treatment by this object.

setMBeanServer(MBeanServer) - Method in class javax.management.remote.rmi.RMIServerImpl

Sets the MBeanServer to which this connector server is attached.

setMBeanServer(MBeanServer) - Method in class javax.management.StringValueExp

Deprecated.

setMBeanServer(MBeanServer) - Method in interface javax.management.ValueExp

Deprecated.
This method is not needed because a ValueExp can access the MBean server in which it is being evaluated by using QueryEval.getMBeanServer().

setMBeanServerForwarder(MBeanServerForwarder) - Method in class javax.management.remote.JMXConnectorServer

setMBeanServerForwarder(MBeanServerForwarder) - Method in interface javax.management.remote.JMXConnectorServerMBean

Inserts an object that intercepts requests for the MBean server that arrive through this connector server.

setMBeanServerForwarder(MBeanServerForwarder) - Method in class javax.management.remote.rmi.RMIConnectorServer

setMedia(PageAttributes.MediaType) - Method in class java.awt.PageAttributes

Specifies the desired paper size for pages using these attributes.

setMediaToDefault() - Method in class java.awt.PageAttributes

Sets the paper size for pages using these attributes to the default size for the default locale.

setMenuBar(MenuBar) - Method in class java.awt.Frame

Sets the menu bar for this frame to the specified menu bar.

setMenuBar(JMenuBar) - Method in class javax.swing.JInternalFrame

Deprecated.
As of Swing version 1.0.3 replaced by setJMenuBar(JMenuBar m).

setMenuBar(JMenuBar) - Method in class javax.swing.JRootPane

Deprecated.
As of Swing version 1.0.3 replaced by setJMenuBar(JMenuBar menu).

setMenuLocation(int, int) - Method in class javax.swing.JMenu

Sets the location of the popup component.

setMessage(String) - Method in class java.util.logging.LogRecord

Set the "raw" log message, before localization or formatting.

setMessage(int, byte[], int) - Method in class javax.sound.midi.MetaMessage

Sets the message parameters for a MetaMessage.

setMessage(byte[], int) - Method in class javax.sound.midi.MidiMessage

Sets the data for the MIDI message.

setMessage(int) - Method in class javax.sound.midi.ShortMessage

Sets the parameters for a MIDI message that takes no data bytes.

setMessage(int, int, int) - Method in class javax.sound.midi.ShortMessage

Sets the parameters for a MIDI message that takes one or two data bytes.

setMessage(int, int, int, int) - Method in class javax.sound.midi.ShortMessage

Sets the short message parameters for a channel message which takes up to two data bytes.

setMessage(byte[], int) - Method in class javax.sound.midi.SysexMessage

Sets the data for the system exclusive message.

setMessage(int, byte[], int) - Method in class javax.sound.midi.SysexMessage

Sets the data for the system exclusive message.

setMessage(Object) - Method in class javax.swing.JOptionPane

Sets the option pane's message-object.

setMessage(String) - Method in class javax.xml.bind.helpers.ValidationEventImpl

Set the message field of this event.

setMessage(SOAPMessage) - Method in interface javax.xml.ws.handler.soap.SOAPMessageContext

Sets the SOAPMessage in this message context

setMessageDigest(MessageDigest) - Method in class java.security.DigestInputStream

Associates the specified message digest with this stream.

setMessageDigest(MessageDigest) - Method in class java.security.DigestOutputStream

Associates the specified message digest with this stream.

setMessageType(int) - Method in class javax.swing.JOptionPane

Sets the option pane's message type.

setMetadata(IIOMetadata) - Method in class javax.imageio.IIOImage

Sets the IIOMetadata to a new object, or null.

setMetaData(RowSetMetaData) - Method in interface javax.sql.rowset.CachedRowSet

Sets the metadata for this CachedRowSet object with the given RowSetMetaData object.

setMetaData(RowSetMetaData) - Method in interface javax.sql.RowSetInternal

Sets the given RowSetMetaData object as the RowSetMetaData object for this RowSet object.

setMetadata(List<Source>) - Method in class javax.xml.ws.Endpoint

Sets the metadata for this endpoint.

setMethod(int) - Method in class java.util.zip.ZipEntry

Sets the compression method for the entry.

setMethod(int) - Method in class java.util.zip.ZipOutputStream

Sets the default compression method for subsequent entries.

setMicrosecondPosition(long) - Method in interface javax.sound.midi.Sequencer

Sets the current position in the sequence, expressed in microseconds

setMicrosecondPosition(long) - Method in interface javax.sound.sampled.Clip

Sets the media position in microseconds.

setMillis(long) - Method in class java.util.logging.LogRecord

Set event time.

setMillisecond(int) - Method in class javax.xml.datatype.XMLGregorianCalendar

Set milliseconds.

setMillisToDecideToPopup(int) - Method in class javax.swing.ProgressMonitor

Specifies the amount of time to wait before deciding whether or not to popup a progress monitor.

setMillisToPopup(int) - Method in class javax.swing.ProgressMonitor

Specifies the amount of time it will take for the popup to appear.

setMimeHeader(String, String) - Method in class javax.xml.soap.AttachmentPart

Changes the first header entry that matches the given name to the given value, adding a new header if no existing header matches.

setMimeHeader(String, String) - Method in class javax.xml.soap.SOAPPart

Changes the first header entry that matches the given header name so that its value is the given value, adding a new header with the given name and value if no existing header is a match.

setMinCRLNumber(BigInteger) - Method in class java.security.cert.X509CRLSelector

Sets the minCRLNumber criterion.

setMinimalDaysInFirstWeek(int) - Method in class java.util.Calendar

Sets what the minimal days required in the first week of the year are; For example, if the first week is defined as one that contains the first day of the first month of a year, call this method with value 1.

setMinimum(int) - Method in interface java.awt.Adjustable

Sets the minimum value of the adjustable object.

setMinimum(int) - Method in class java.awt.Scrollbar

Sets the minimum value of this scroll bar.

setMinimum(int) - Method in class java.awt.ScrollPaneAdjustable

This method should NOT be called by user code.

setMinimum(int) - Method in interface javax.swing.BoundedRangeModel

Sets the model's minimum to newMinimum.

setMinimum(int) - Method in class javax.swing.DefaultBoundedRangeModel

Sets the minimum to n after ensuring that n that the other three properties obey the model's constraints:

setMinimum(int) - Method in class javax.swing.JProgressBar

Sets the progress bar's minimum value (stored in the progress bar's data model) to n.

setMinimum(int) - Method in class javax.swing.JScrollBar

Sets the model's minimum property.

setMinimum(int) - Method in class javax.swing.JSlider

Sets the slider's minimum value to minimum.

setMinimum(int) - Method in class javax.swing.ProgressMonitor

Specifies the minimum value.

setMinimum(Comparable) - Method in class javax.swing.SpinnerNumberModel

Changes the lower bound for numbers in this sequence.

setMinimum(Comparable) - Method in class javax.swing.text.InternationalFormatter

Sets the minimum permissible value.

setMinimumFractionDigits(int) - Method in class java.text.DecimalFormat

Sets the minimum number of digits allowed in the fraction portion of a number.

setMinimumFractionDigits(int) - Method in class java.text.NumberFormat

Sets the minimum number of digits allowed in the fraction portion of a number.

setMinimumIntegerDigits(int) - Method in class java.text.DecimalFormat

Sets the minimum number of digits allowed in the integer portion of a number.

setMinimumIntegerDigits(int) - Method in class java.text.NumberFormat

Sets the minimum number of digits allowed in the integer portion of a number.

setMinimumSize(Dimension) - Method in class java.awt.Component

Sets the minimum size of this component to a constant value.

setMinimumSize(Dimension) - Method in class java.awt.Window

Sets the minimum size of this window to a constant value.

setMinimumSize(Dimension) - Method in class javax.swing.JComponent

Sets the minimum size of this component to a constant value.

setMinor(int, String) - Method in exception org.ietf.jgss.GSSException

Used by the exception thrower to set the mechanism level minor error code and its string explanation.

setMinorTickSpacing(int) - Method in class javax.swing.JSlider

This method sets the minor tick spacing.

setMinPage(int) - Method in class java.awt.JobAttributes

Specifies the minimum value the user can specify as the first page to be printed for jobs using these attributes.

setMinusSign(char) - Method in class java.text.DecimalFormatSymbols

Sets the character used to represent minus sign.

setMinute(int) - Method in class javax.xml.datatype.XMLGregorianCalendar

Set minutes.

setMinutes(int) - Method in class java.sql.Date

Deprecated.

setMinutes(int) - Method in class java.util.Date

Deprecated.
As of JDK version 1.1, replaced by Calendar.set(Calendar.MINUTE, int minutes).

setMinWidth(int) - Method in class javax.swing.table.TableColumn

Sets the TableColumn's minimum width to minWidth, adjusting the new minimum width if necessary to ensure that 0 <= minWidth <= maxWidth.

setMnemonic(int) - Method in class javax.swing.AbstractButton

Sets the keyboard mnemonic on the current model.

setMnemonic(char) - Method in class javax.swing.AbstractButton

This method is now obsolete, please use setMnemonic(int) to set the mnemonic for a button.

setMnemonic(int) - Method in interface javax.swing.ButtonModel

Sets the keyboard mnemonic (shortcut key or accelerator key) for the button.

setMnemonic(int) - Method in class javax.swing.DefaultButtonModel

Sets the keyboard mnemonic (shortcut key or accelerator key) for the button.

setMnemonicAt(int, int) - Method in class javax.swing.JTabbedPane

Sets the keyboard mnemonic for accessing the specified tab.

setModal(boolean) - Method in class java.awt.Dialog

Specifies whether this dialog should be modal.

setModalExclusionType(Dialog.ModalExclusionType) - Method in class java.awt.Window

Specifies the modal exclusion type for this window.

setModalityType(Dialog.ModalityType) - Method in class java.awt.Dialog

Sets the modality type for this dialog.

setMode(int) - Method in class java.awt.FileDialog

Sets the mode of the file dialog.

setModel(ButtonModel) - Method in class javax.swing.AbstractButton

Sets the model that this button represents.

setModel(ComboBoxModel) - Method in class javax.swing.JComboBox

Sets the data model that the JComboBox uses to obtain the list of items.

setModel(ListModel<E>) - Method in class javax.swing.JList

Sets the model that represents the contents or "value" of the list, notifies property change listeners, and then clears the list's selection.

setModel(ButtonModel) - Method in class javax.swing.JMenu

Sets the data model for the "menu button" -- the label that the user clicks to open or close the menu.

setModel(ButtonModel) - Method in class javax.swing.JMenuItem

Sets the model that this button represents.

setModel(BoundedRangeModel) - Method in class javax.swing.JProgressBar

Sets the data model used by the JProgressBar.

setModel(BoundedRangeModel) - Method in class javax.swing.JScrollBar

Sets the model that handles the scrollbar's four fundamental properties: minimum, maximum, value, extent.

setModel(BoundedRangeModel) - Method in class javax.swing.JSlider

Sets the BoundedRangeModel that handles the slider's three fundamental properties: minimum, maximum, value.

setModel(SpinnerModel) - Method in class javax.swing.JSpinner

Changes the model that represents the value of this spinner.

setModel(SingleSelectionModel) - Method in class javax.swing.JTabbedPane

Sets the model to be used with this tabbedpane.

setModel(TableModel) - Method in class javax.swing.JTable

Sets the data model for this table to newModel and registers with it for listener notifications from the new data model.

setModel(TreeModel) - Method in class javax.swing.JTree

Sets the TreeModel that will provide the data.

setModel(TreeModel) - Method in class javax.swing.plaf.basic.BasicTreeUI

Sets the TreeModel.

setModel(M) - Method in class javax.swing.table.TableRowSorter

Sets the TableModel to use as the underlying model for this TableRowSorter.

setModel(TreeModel) - Method in class javax.swing.tree.AbstractLayoutCache

Sets the TreeModel that will provide the data.

setModel(TreeModel) - Method in class javax.swing.tree.FixedHeightLayoutCache

Sets the TreeModel that will provide the data.

setModel(TreeModel) - Method in class javax.swing.tree.VariableHeightLayoutCache

Sets the TreeModel that will provide the data.

setModelIndex(int) - Method in class javax.swing.table.TableColumn

Sets the model index for this column.

setModelMBeanInfo(ModelMBeanInfo) - Method in interface javax.management.modelmbean.ModelMBean

Initializes a ModelMBean object using ModelMBeanInfo passed in.

setModelMBeanInfo(ModelMBeanInfo) - Method in class javax.management.modelmbean.RequiredModelMBean

Initializes a ModelMBean object using ModelMBeanInfo passed in.

setModelWrapper(DefaultRowSorter.ModelWrapper<M, I>) - Method in class javax.swing.DefaultRowSorter

Sets the model wrapper providing the data that is being sorted and filtered.

setModifiers(int) - Method in class java.awt.event.KeyEvent

Deprecated.
as of JDK1.1.4

setModulus(Number) - Method in class javax.management.monitor.CounterMonitor

Sets the modulus value common to all observed MBeans.

setModulus(Number) - Method in interface javax.management.monitor.CounterMonitorMBean

Sets the modulus value.

setMonetaryDecimalSeparator(char) - Method in class java.text.DecimalFormatSymbols

Sets the monetary decimal separator.

setMono(boolean) - Method in interface javax.sound.midi.MidiChannel

Turns mono mode on or off.

setMonth(int) - Method in class java.sql.Time

Deprecated.

setMonth(int) - Method in class java.util.Date

Deprecated.
As of JDK version 1.1, replaced by Calendar.set(Calendar.MONTH, int month).

setMonth(int) - Method in class javax.xml.datatype.XMLGregorianCalendar

Set month.

setMonths(String[]) - Method in class java.text.DateFormatSymbols

Sets month strings.

setMouseOver(boolean) - Method in class javax.swing.plaf.basic.BasicSplitPaneDivider

Sets whether or not the mouse is currently over the divider.

setMTOMEnabled(boolean) - Method in interface javax.xml.ws.soap.SOAPBinding

Enables or disables use of MTOM.

setMultiClickThreshhold(long) - Method in class javax.swing.AbstractButton

Sets the amount of time (in milliseconds) required between mouse press events for the button to generate the corresponding action events.

setMultipleDocumentHandling(JobAttributes.MultipleDocumentHandlingType) - Method in class java.awt.JobAttributes

Specifies the handling of multiple copies, including collation, for jobs using these attributes.

setMultipleDocumentHandlingToDefault() - Method in class java.awt.JobAttributes

Sets the handling of multiple copies, including collation, for jobs using these attributes to the default.

setMultipleMode(boolean) - Method in class java.awt.FileDialog

Enables or disables multiple file selection for the file dialog.

setMultipleMode(boolean) - Method in class java.awt.List

Sets the flag that determines whether this list allows multiple selections.

setMultipleSelections(boolean) - Method in class java.awt.List

Deprecated.
As of JDK version 1.1, replaced by setMultipleMode(boolean).

setMultiplier(int) - Method in class java.text.DecimalFormat

Sets the multiplier for use in percent, per mille, and similar formats.

setMultiSelectionEnabled(boolean) - Method in class javax.swing.JFileChooser

Sets the file chooser to allow multiple file selections.

setMustUnderstand(boolean) - Method in interface javax.xml.soap.SOAPHeaderElement

Sets the mustUnderstand attribute for this SOAPHeaderElement object to be either true or false.

setMute(boolean) - Method in interface javax.sound.midi.MidiChannel

Sets the mute state for this channel.

setName(String) - Method in class java.awt.Component

Sets the name of the component to the specified string.

setName(String) - Method in class java.awt.MenuComponent

Sets the name of the component to the specified string.

setName(String) - Method in class java.beans.FeatureDescriptor

Sets the programmatic name of this feature.

setName(String) - Method in class java.lang.Thread

Changes the name of this thread to be equal to the argument name.

setName(Principal, String) - Method in interface java.security.acl.Acl

Sets the name of this ACL.

setName(String) - Method in class javax.naming.NameClassPair

Sets the name of this binding.

setName(String) - Method in class javax.security.auth.callback.NameCallback

Set the retrieved name.

setName(String) - Method in class javax.swing.text.StyleContext.NamedStyle

Changes the name of the style.

setNameConstraints(byte[]) - Method in class java.security.cert.X509CertSelector

Sets the name constraints criterion.

setNamedItem(Node) - Method in interface org.w3c.dom.NamedNodeMap

Adds a node using its nodeName attribute.

setNamedItemNS(Node) - Method in interface org.w3c.dom.NamedNodeMap

Adds a node using its namespaceURI and localName.

setNameInNamespace(String) - Method in class javax.naming.NameClassPair

Sets the full name of this binding.

setNamespaceAware(boolean) - Method in class javax.xml.parsers.DocumentBuilderFactory

Specifies that the parser produced by this code will provide support for XML namespaces.

setNamespaceAware(boolean) - Method in class javax.xml.parsers.SAXParserFactory

Specifies that the parser produced by this code will provide support for XML namespaces.

setNamespaceContext(NamespaceContext) - Method in interface javax.xml.stream.XMLEventWriter

Sets the current namespace context for prefix and uri bindings.

setNamespaceContext(NamespaceContext) - Method in interface javax.xml.stream.XMLStreamWriter

Sets the current namespace context for prefix and uri bindings.

setNamespaceContext(NamespaceContext) - Method in interface javax.xml.xpath.XPath

Establish a namespace context.

setNamespaceDeclUris(boolean) - Method in class org.xml.sax.helpers.NamespaceSupport

Controls whether namespace declaration attributes are placed into the NSDECL namespace by processName().

setNaN(String) - Method in class java.text.DecimalFormatSymbols

Sets the string used to represent "not a number".

setNanos(int) - Method in class java.sql.Timestamp

Sets this Timestamp object's nanos field to the given value.

setNativeMethodPrefix(ClassFileTransformer, String) - Method in interface java.lang.instrument.Instrumentation

This method modifies the failure handling of native method resolution by allowing retry with a prefix applied to the name.

setNativesForFlavor(DataFlavor, String[]) - Method in class java.awt.datatransfer.SystemFlavorMap

Discards the current mappings for the specified DataFlavor and all DataFlavors equal to the specified DataFlavor, and creates new mappings to the specified String natives.

setNavigationFilter(NavigationFilter) - Method in class javax.swing.text.JTextComponent

Sets the NavigationFilter.

setNCharacterStream(String, Reader, long) - Method in interface java.sql.CallableStatement

Sets the designated parameter to a Reader object.

setNCharacterStream(String, Reader) - Method in interface java.sql.CallableStatement

Sets the designated parameter to a Reader object.

setNCharacterStream(int, Reader, long) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to a Reader object.

setNCharacterStream(int, Reader) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to a Reader object.

setNCharacterStream(int, Reader) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter in this RowSet object's command to a Reader object.

setNCharacterStream(int, Reader, long) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to a Reader object.

setNCharacterStream(String, Reader, long) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to a Reader object.

setNCharacterStream(String, Reader) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to a Reader object.

setNCharacterStream(int, Reader) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command to a Reader object.

setNCharacterStream(int, Reader, long) - Method in interface javax.sql.RowSet

Sets the designated parameter to a Reader object.

setNCharacterStream(String, Reader, long) - Method in interface javax.sql.RowSet

Sets the designated parameter to a Reader object.

setNCharacterStream(String, Reader) - Method in interface javax.sql.RowSet

Sets the designated parameter to a Reader object.

setNClob(String, NClob) - Method in interface java.sql.CallableStatement

Sets the designated parameter to a java.sql.NClob object.

setNClob(String, Reader, long) - Method in interface java.sql.CallableStatement

Sets the designated parameter to a Reader object.

setNClob(String, Reader) - Method in interface java.sql.CallableStatement

Sets the designated parameter to a Reader object.

setNClob(int, NClob) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to a java.sql.NClob object.

setNClob(int, Reader, long) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to a Reader object.

setNClob(int, Reader) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to a Reader object.

setNClob(String, NClob) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to a java.sql.NClob object.

setNClob(String, Reader, long) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to a Reader object.

setNClob(String, Reader) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to a Reader object.

setNClob(int, Reader, long) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to a Reader object.

setNClob(int, NClob) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to a java.sql.NClob object.

setNClob(int, Reader) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to a Reader object.

setNClob(String, NClob) - Method in interface javax.sql.RowSet

Sets the designated parameter to a java.sql.NClob object.

setNClob(String, Reader, long) - Method in interface javax.sql.RowSet

Sets the designated parameter to a Reader object.

setNClob(String, Reader) - Method in interface javax.sql.RowSet

Sets the designated parameter to a Reader object.

setNClob(int, Reader, long) - Method in interface javax.sql.RowSet

Sets the designated parameter to a Reader object.

setNClob(int, NClob) - Method in interface javax.sql.RowSet

Sets the designated parameter to a java.sql.NClob object.

setNClob(int, Reader) - Method in interface javax.sql.RowSet

Sets the designated parameter to a Reader object.

setNeedClientAuth(boolean) - Method in class javax.net.ssl.SSLEngine

Configures the engine to require client authentication.

setNeedClientAuth(boolean) - Method in class javax.net.ssl.SSLParameters

Sets whether client authentication should be required.

setNeedClientAuth(boolean) - Method in class javax.net.ssl.SSLServerSocket

Controls whether accepted server-mode SSLSockets will be initially configured to require client authentication.

setNeedClientAuth(boolean) - Method in class javax.net.ssl.SSLSocket

Configures the socket to require client authentication.

setNegativePermissions() - Method in interface java.security.acl.AclEntry

Sets this ACL entry to be a negative one.

setNegativePrefix(String) - Method in class java.text.DecimalFormat

Set the negative prefix.

setNegativeSuffix(String) - Method in class java.text.DecimalFormat

Set the negative suffix.

setNetworkInterface(NetworkInterface) - Method in class java.net.MulticastSocket

Specify the network interface for outgoing multicast datagrams sent on this socket.

setNetworkTimeout(Executor, int) - Method in interface java.sql.Connection

Sets the maximum period a Connection or objects created from the Connection will wait for the database to reply to any one request.

setNewLine(String) - Method in interface org.w3c.dom.ls.LSSerializer

The end-of-line sequence of characters to be used in the XML being written out.

setNextException(SQLException) - Method in exception java.sql.SQLException

Adds an SQLException object to the end of the chain.

setNextFocusableComponent(Component) - Method in class javax.swing.JComponent

Deprecated.
As of 1.4, replaced by FocusTraversalPolicy

setNextSibling(Node) - Method in class javax.xml.crypto.dsig.dom.DOMSignContext

Sets the next sibling node.

setNextSibling(Node) - Method in class javax.xml.transform.dom.DOMResult

Set the child node before which the result nodes will be inserted.

setNextWarning(SQLWarning) - Method in exception java.sql.SQLWarning

Adds a SQLWarning object to the end of the chain.

setNextWarning(RowSetWarning) - Method in exception javax.sql.rowset.RowSetWarning

Sets warning as the next warning, that is, the warning chained to this RowSetWarning object.

setNil(boolean) - Method in class javax.xml.bind.JAXBElement

Set whether this element has nil content.

setNode(Node) - Method in class javax.xml.bind.helpers.ValidationEventLocatorImpl

Set the Node field on this event locator.

setNode(Node) - Method in class javax.xml.crypto.dsig.dom.DOMValidateContext

Sets the node.

setNode(Node) - Method in class javax.xml.transform.dom.DOMResult

Set the node that will contain the result DOM tree.

setNode(Node) - Method in class javax.xml.transform.dom.DOMSource

Set the node that will represents a Source DOM tree.

setNodeDimensions(AbstractLayoutCache.NodeDimensions) - Method in class javax.swing.tree.AbstractLayoutCache

Sets the renderer that is responsible for drawing nodes in the tree and which is threfore responsible for calculating the dimensions of individual nodes.

setNodeDimensions(AbstractLayoutCache.NodeDimensions) - Method in class javax.swing.tree.VariableHeightLayoutCache

Sets the renderer that is responsible for drawing nodes in the tree.

setNodeValue(String) - Method in class javax.imageio.metadata.IIOMetadataNode

Sets the String value associated with this node.

setNodeValue(String) - Method in interface org.w3c.dom.Node

The value of this node, depending on its type; see the table above.

setNonContinuousLayoutDivider(Component) - Method in class javax.swing.plaf.basic.BasicSplitPaneUI

Sets the divider to use when the splitPane is configured to not continuously layout.

setNonContinuousLayoutDivider(Component, boolean) - Method in class javax.swing.plaf.basic.BasicSplitPaneUI

Sets the divider to use.

setNoNSSchemaLocation(String) - Method in class javax.xml.bind.helpers.AbstractMarshallerImpl

Convenience method for setting the noNamespaceSchemaLocation.

setNormalBounds(Rectangle) - Method in class javax.swing.JInternalFrame

Sets the normal bounds for this internal frame, the bounds that this internal frame would be restored to from its maximized state.

setNorthPane(JComponent) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI

setNote(String) - Method in class javax.swing.ProgressMonitor

Specifies the additional note that is displayed along with the progress message.

setNotify(boolean) - Method in class javax.management.monitor.CounterMonitor

Sets the notification's on/off switch value common to all observed MBeans.

setNotify(boolean) - Method in interface javax.management.monitor.CounterMonitorMBean

Sets the notification's on/off switch value.

setNotifyDiffer(boolean) - Method in class javax.management.monitor.StringMonitor

Sets the differing notification's on/off switch value common to all observed MBeans.

setNotifyDiffer(boolean) - Method in interface javax.management.monitor.StringMonitorMBean

Sets the differing notification's on/off switch value.

setNotifyHigh(boolean) - Method in class javax.management.monitor.GaugeMonitor

Sets the high notification's on/off switch value common to all observed MBeans.

setNotifyHigh(boolean) - Method in interface javax.management.monitor.GaugeMonitorMBean

Sets the high notification's on/off switch value.

setNotifyLow(boolean) - Method in class javax.management.monitor.GaugeMonitor

Sets the low notification's on/off switch value common to all observed MBeans.

setNotifyLow(boolean) - Method in interface javax.management.monitor.GaugeMonitorMBean

Sets the low notification's on/off switch value.

setNotifyMatch(boolean) - Method in class javax.management.monitor.StringMonitor

Sets the matching notification's on/off switch value common to all observed MBeans.

setNotifyMatch(boolean) - Method in interface javax.management.monitor.StringMonitorMBean

Sets the matching notification's on/off switch value.

setNString(String, String) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given String object.

setNString(int, String) - Method in interface java.sql.PreparedStatement

Sets the designated paramter to the given String object.

setNString(int, String) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated paramter to the given String object.

setNString(String, String) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated paramter to the given String object.

setNString(int, String) - Method in interface javax.sql.RowSet

Sets the designated paramter to the given String object.

setNString(String, String) - Method in interface javax.sql.RowSet

Sets the designated paramter to the given String object.

setNull(String, int) - Method in interface java.sql.CallableStatement

Sets the designated parameter to SQL NULL.

setNull(String, int, String) - Method in interface java.sql.CallableStatement

Sets the designated parameter to SQL NULL.

setNull(int, int) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to SQL NULL.

setNull(int, int, String) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to SQL NULL.

setNull(int, int) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to SQL NULL.

setNull(int, int, String) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to SQL NULL.

setNull(String, int) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to SQL NULL.

setNull(String, int, String) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to SQL NULL.

setNull(int, int) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's SQL command to SQL NULL.

setNull(String, int) - Method in interface javax.sql.RowSet

Sets the designated parameter to SQL NULL.

setNull(int, int, String) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's SQL command to SQL NULL.

setNull(String, int, String) - Method in interface javax.sql.RowSet

Sets the designated parameter to SQL NULL.

setNullable(int, int) - Method in class javax.sql.rowset.RowSetMetaDataImpl

Sets whether a value stored in the designated column can be set to NULL to the given constant from the interface ResultSetMetaData.

setNullable(int, int) - Method in interface javax.sql.RowSetMetaData

Sets whether the designated column's value can be set to NULL.

setNullFormatter(JFormattedTextField.AbstractFormatter) - Method in class javax.swing.text.DefaultFormatterFactory

Sets the formatter to use if the value of the JFormattedTextField is null.

setNumberFormat(NumberFormat) - Method in class java.text.DateFormat

Allows you to set the number formatter.

setNumRows(int) - Method in class javax.swing.table.DefaultTableModel

Obsolete as of Java 2 platform v1.3.

setObject(Object) - Method in interface java.beans.Customizer

Set the object to be customized.

setObject(String, Object, int, int) - Method in interface java.sql.CallableStatement

Sets the value of the designated parameter with the given object.

setObject(String, Object, int) - Method in interface java.sql.CallableStatement

Sets the value of the designated parameter with the given object.

setObject(String, Object) - Method in interface java.sql.CallableStatement

Sets the value of the designated parameter with the given object.

setObject(int, Object, int) - Method in interface java.sql.PreparedStatement

Sets the value of the designated parameter with the given object.

setObject(int, Object) - Method in interface java.sql.PreparedStatement

Sets the value of the designated parameter using the given object.

setObject(int, Object, int, int) - Method in interface java.sql.PreparedStatement

Sets the value of the designated parameter with the given object.

setObject(Object) - Method in interface java.sql.Ref

Sets the structured type value that this Ref object references to the given instance of Object.

setObject(Object) - Method in class javax.naming.Binding

Sets the object associated with this binding.

setObject(int, Object, int, int) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to an Object in the Java programming language.

setObject(int, Object, int) - Method in class javax.sql.rowset.BaseRowSet

Sets the value of the designated parameter with the given Object value.

setObject(int, Object) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to an Object in the Java programming language.

setObject(String, Object, int, int) - Method in class javax.sql.rowset.BaseRowSet

Sets the value of the designated parameter with the given object.

setObject(String, Object, int) - Method in class javax.sql.rowset.BaseRowSet

Sets the value of the designated parameter with the given object.

setObject(String, Object) - Method in class javax.sql.rowset.BaseRowSet

Sets the value of the designated parameter with the given object.

setObject(Object) - Method in class javax.sql.rowset.serial.SerialRef

Sets the SQL structured type that this SerialRef object references to the given Object object.

setObject(int, Object, int, int) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command with the given Java Object.

setObject(String, Object, int, int) - Method in interface javax.sql.RowSet

Sets the value of the designated parameter with the given object.

setObject(int, Object, int) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command with a Java Object.

setObject(String, Object, int) - Method in interface javax.sql.RowSet

Sets the value of the designated parameter with the given object.

setObject(String, Object) - Method in interface javax.sql.RowSet

Sets the value of the designated parameter with the given object.

setObject(int, Object) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command with a Java Object.

setObject(Object) - Method in class javax.xml.bind.helpers.ValidationEventLocatorImpl

Set the Object field on this event locator.

setObjectFactoryBuilder(ObjectFactoryBuilder) - Static method in class javax.naming.spi.NamingManager

The ObjectFactoryBuilder determines the policy used when trying to load object factories.

setObservedAttribute(String) - Method in class javax.management.monitor.Monitor

Sets the attribute to observe.

setObservedAttribute(String) - Method in interface javax.management.monitor.MonitorMBean

Sets the attribute to observe.

setObservedObject(ObjectName) - Method in class javax.management.monitor.Monitor

Deprecated.
As of JMX 1.2, replaced by Monitor.addObservedObject(javax.management.ObjectName)

setObservedObject(ObjectName) - Method in interface javax.management.monitor.MonitorMBean

Deprecated.
As of JMX 1.2, replaced by MonitorMBean.addObservedObject(javax.management.ObjectName)

setOffset(int) - Method in class java.io.ObjectStreamField

Offset within instance data.

setOffset(int) - Method in class java.text.CollationElementIterator

Sets the iterator to point to the collation element corresponding to the specified character (the parameter is a CHARACTER offset in the original string, not an offset into its corresponding sequence of collation elements).

setOffset(int) - Method in class javax.imageio.stream.IIOByteBuffer

Updates the value that will be returned by subsequent calls to the getOffset method.

setOffset(Number) - Method in class javax.management.monitor.CounterMonitor

Sets the offset value common to all observed MBeans.

setOffset(Number) - Method in interface javax.management.monitor.CounterMonitorMBean

Sets the offset value.

setOffset(Point) - Method in class javax.swing.plaf.basic.BasicToolBarUI.DragWindow

setOffset(int) - Method in class javax.xml.bind.helpers.ValidationEventLocatorImpl

Set the offset field on this event locator.

SetOfIntegerSyntax - Class in javax.print.attribute

Class SetOfIntegerSyntax is an abstract base class providing the common implementation of all attributes whose value is a set of nonnegative integers.

SetOfIntegerSyntax(String) - Constructor for class javax.print.attribute.SetOfIntegerSyntax

Construct a new set-of-integer attribute with the given members in string form.

SetOfIntegerSyntax(int[][]) - Constructor for class javax.print.attribute.SetOfIntegerSyntax

Construct a new set-of-integer attribute with the given members in array form.

SetOfIntegerSyntax(int) - Constructor for class javax.print.attribute.SetOfIntegerSyntax

Construct a new set-of-integer attribute containing a single integer.

SetOfIntegerSyntax(int, int) - Constructor for class javax.print.attribute.SetOfIntegerSyntax

Construct a new set-of-integer attribute containing a single range of integers.

setOmni(boolean) - Method in interface javax.sound.midi.MidiChannel

Turns omni mode on or off.

setOneTouchExpandable(boolean) - Method in class javax.swing.JSplitPane

Sets the value of the oneTouchExpandable property, which must be true for the JSplitPane to provide a UI widget on the divider to quickly expand/collapse the divider.

setOOBInline(boolean) - Method in class java.net.Socket

Enable/disable OOBINLINE (receipt of TCP urgent data) By default, this option is disabled and TCP urgent data received on a socket is silently discarded.

setOpacity(float) - Method in class java.awt.Dialog

Sets the opacity of the window.

setOpacity(float) - Method in class java.awt.Frame

Sets the opacity of the window.

setOpacity(float) - Method in class java.awt.Window

Sets the opacity of the window.

setOpaque(boolean) - Method in class javax.swing.JComponent

If true the component paints every pixel within its bounds.

setOpenIcon(Icon) - Method in class javax.swing.tree.DefaultTreeCellRenderer

Sets the icon used to represent non-leaf nodes that are expanded.

setOptimizeHuffmanTables(boolean) - Method in class javax.imageio.plugins.jpeg.JPEGImageWriteParam

Tells the writer to generate optimized Huffman tables for the image as part of the writing process.

setOption(int, Object) - Method in interface java.net.SocketOptions

Enable/disable the option specified by optID.

setOption(SocketOption<T>, T) - Method in class java.nio.channels.AsynchronousServerSocketChannel

setOption(SocketOption<T>, T) - Method in class java.nio.channels.AsynchronousSocketChannel

setOption(SocketOption<T>, T) - Method in class java.nio.channels.DatagramChannel

setOption(SocketOption<T>, T) - Method in interface java.nio.channels.NetworkChannel

Sets the value of a socket option.

setOption(SocketOption<T>, T) - Method in class java.nio.channels.ServerSocketChannel

setOption(SocketOption<T>, T) - Method in class java.nio.channels.SocketChannel

setOptions(Object[]) - Method in class javax.swing.JOptionPane

Sets the options this pane displays.

setOptionType(int) - Method in class javax.swing.JOptionPane

Sets the options to display.

setOrdering(Class<T>, T, T) - Method in class javax.imageio.spi.ServiceRegistry

Sets a pairwise ordering between two service provider objects within a given category.

setOrientation(int) - Method in class java.awt.print.PageFormat

Sets the page orientation.

setOrientation(int) - Method in class java.awt.Scrollbar

Sets the orientation for this scroll bar.

setOrientation(int) - Method in class javax.swing.JProgressBar

Sets the progress bar's orientation to newOrientation, which must be SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.

setOrientation(int) - Method in class javax.swing.JScrollBar

Set the scrollbar's orientation to either VERTICAL or HORIZONTAL.

setOrientation(int) - Method in class javax.swing.JSeparator

Sets the orientation of the separator.

setOrientation(int) - Method in class javax.swing.JSlider

Set the slider's orientation to either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.

setOrientation(int) - Method in class javax.swing.JSplitPane

Sets the orientation, or how the splitter is divided.

setOrientation(int) - Method in class javax.swing.JToolBar

Sets the orientation of the tool bar.

setOrientation(int) - Method in class javax.swing.plaf.basic.BasicSplitPaneUI

Set the orientation for the JSplitPane.

setOrientation(int) - Method in class javax.swing.plaf.basic.BasicToolBarUI.DragWindow

setOrientation(int) - Method in class javax.swing.plaf.basic.BasicToolBarUI

setOrientationRequested(PageAttributes.OrientationRequestedType) - Method in class java.awt.PageAttributes

Specifies the print orientation for pages using these attributes.

setOrientationRequested(int) - Method in class java.awt.PageAttributes

Specifies the print orientation for pages using these attributes.

setOrientationRequestedToDefault() - Method in class java.awt.PageAttributes

Sets the print orientation for pages using these attributes to the default.

setOrigin(PageAttributes.OriginType) - Method in class java.awt.PageAttributes

Specifies whether drawing at (0, 0) to pages using these attributes draws at the upper-left corner of the physical page, or at the upper-left corner of the printable area.

setOriginalRow() - Method in interface javax.sql.rowset.CachedRowSet

Sets the current row in this CachedRowSet object as the original row.

setOut(PrintStream) - Static method in class java.lang.System

Reassigns the "standard" output stream.

setOuterHTML(Element, String) - Method in class javax.swing.text.html.HTMLDocument

Replaces the given element in the parent with the contents specified as an HTML string.

setOutput(Object) - Method in class javax.imageio.ImageWriter

Sets the destination to the given ImageOutputStream or other Object.

setOutputProperties(Properties) - Method in class javax.xml.transform.Transformer

Set the output properties for the transformation.

setOutputProperty(String, String) - Method in class javax.xml.transform.Transformer

Set an output property that will be in effect for the transformation.

setOutputStream(OutputStream) - Method in class java.rmi.server.LogStream

Deprecated.
no replacement

setOutputStream(OutputStream) - Method in class java.util.logging.StreamHandler

Change the output stream.

setOutputStream(OutputStream) - Method in class javax.xml.transform.stream.StreamResult

Set the ByteStream that is to be written to.

SetOverrideType - Class in org.omg.CORBA

The mapping of a CORBA enum tagging SET_OVERRIDE and ADD_OVERRIDE, which indicate whether policies should replace the existing policies of an Object or be added to them.

SetOverrideType(int) - Constructor for class org.omg.CORBA.SetOverrideType

Constructs a SetOverrideType instance from an int.

SetOverrideTypeHelper - Class in org.omg.CORBA

The Helper for SetOverrideType.

SetOverrideTypeHelper() - Constructor for class org.omg.CORBA.SetOverrideTypeHelper

setOverwriteMode(boolean) - Method in class javax.swing.text.DefaultFormatter

Configures the behavior when inserting characters.

setOwner(Object) - Method in class java.beans.XMLDecoder

Sets the owner of this decoder to owner.

setOwner(Object) - Method in class java.beans.XMLEncoder

Sets the owner of this encoder to owner.

setOwner(UserPrincipal) - Method in interface java.nio.file.attribute.FileOwnerAttributeView

Updates the file owner.

setOwner(Path, UserPrincipal) - Static method in class java.nio.file.Files

Updates the file owner.

setPackageAssertionStatus(String, boolean) - Method in class java.lang.ClassLoader

Sets the package default assertion status for the named package.

setPadding(int) - Method in class javax.swing.plaf.basic.BasicOptionPaneUI.ButtonAreaLayout

setPage(int, Printable, PageFormat) - Method in class java.awt.print.Book

Sets the PageFormat and the Painter for a specified page number.

setPage(URL) - Method in class javax.swing.JEditorPane

Sets the current URL being displayed.

setPage(String) - Method in class javax.swing.JEditorPane

Sets the current URL being displayed.

setPageable(Pageable) - Method in class java.awt.print.PrinterJob

Queries document for the number of pages and the PageFormat and Printable for each page held in the Pageable instance, document.

setPageIncrement(int) - Method in class java.awt.Scrollbar

Deprecated.
As of JDK version 1.1, replaced by setBlockIncrement().

setPageRanges(int[][]) - Method in class java.awt.JobAttributes

Specifies, for jobs using these attributes, the ranges of pages to be printed, if a range of pages is to be printed.

setPageSize(int) - Method in interface javax.sql.rowset.CachedRowSet

Sets the CachedRowSet object's page-size.

setPaint(Paint) - Method in class java.awt.Graphics2D

Sets the Paint attribute for the Graphics2D context.

setPaintLabels(boolean) - Method in class javax.swing.JSlider

Determines whether labels are painted on the slider.

setPaintMode() - Method in class java.awt.Graphics

Sets the paint mode of this graphics context to overwrite the destination with this graphics context's current color.

setPaintMode() - Method in class javax.swing.DebugGraphics

Overrides Graphics.setPaintMode.

setPaintTicks(boolean) - Method in class javax.swing.JSlider

Determines whether tick marks are painted on the slider.

setPaintTrack(boolean) - Method in class javax.swing.JSlider

Determines whether the track is painted on the slider.

setPalette(boolean) - Method in class javax.swing.plaf.metal.MetalInternalFrameTitlePane

setPalette(boolean) - Method in class javax.swing.plaf.metal.MetalInternalFrameUI

setPaper(Paper) - Method in class java.awt.print.PageFormat

Sets the Paper object for this PageFormat.

setParagraphAttributes(AttributeSet, boolean) - Method in class javax.swing.JTextPane

Applies the given attributes to paragraphs.

setParagraphAttributes(int, int, AttributeSet, boolean) - Method in class javax.swing.text.DefaultStyledDocument

Sets attributes for a paragraph.

setParagraphAttributes(int, int, AttributeSet, boolean) - Method in class javax.swing.text.html.HTMLDocument

Sets attributes for a paragraph.

setParagraphAttributes(int, int, AttributeSet, boolean) - Method in interface javax.swing.text.StyledDocument

Sets paragraph attributes.

setParagraphAttributes(JEditorPane, AttributeSet, boolean) - Method in class javax.swing.text.StyledEditorKit.StyledTextAction

Applies the given attributes to paragraphs.

setParagraphInsets(AttributeSet) - Method in class javax.swing.text.CompositeView

Sets the insets from the paragraph attributes specified in the given attributes.

setParameter(String, Object) - Method in class java.security.Signature

Deprecated.
Use setParameter.

setParameter(AlgorithmParameterSpec) - Method in class java.security.Signature

Initializes this signature engine with the specified parameter set.

setParameter(String, String) - Method in class javax.activation.MimeType

Set the value to be associated with the given name, replacing any previous association.

setParameter(String, Object) - Method in class javax.xml.transform.Transformer

Add a parameter for the transformation.

setParameter(String, Object) - Method in interface org.w3c.dom.DOMConfiguration

Set the value of a parameter.

setParameterBlock(ParameterBlock) - Method in class java.awt.image.renderable.RenderableImageOp

Change the current ParameterBlock of the operation, allowing editing of image rendering chains.

setParameters(Vector<Object>) - Method in class java.awt.image.renderable.ParameterBlock

Sets the entire Vector of parameters to a given Vector.

setParameters(Object[]) - Method in class java.util.logging.LogRecord

Set the parameters to the log message.

setParent(Logger) - Method in class java.util.logging.Logger

Set the parent for this Logger.

setParent(ResourceBundle) - Method in class java.util.ResourceBundle

Sets the parent bundle of this bundle.

setParent(ActionMap) - Method in class javax.swing.ActionMap

Sets this ActionMap's parent.

setParent(InputMap) - Method in class javax.swing.ComponentInputMap

Sets the parent, which must be a ComponentInputMap associated with the same component as this ComponentInputMap.

setParent(InputMap) - Method in class javax.swing.InputMap

Sets this InputMap's parent.

setParent(View) - Method in class javax.swing.text.AsyncBoxView

Sets the parent of the view.

setParent(View) - Method in class javax.swing.text.ComponentView

Sets the parent for a child view.

setParent(View) - Method in class javax.swing.text.CompositeView

Sets the parent of the view.

setParent(View) - Method in class javax.swing.text.FlowView

Sets the parent of the view.

setParent(View) - Method in class javax.swing.text.html.BlockView

Establishes the parent view for this view.

setParent(View) - Method in class javax.swing.text.html.ImageView

Establishes the parent view for this view.

setParent(View) - Method in class javax.swing.text.html.ParagraphView

Establishes the parent view for this view.

setParent(View) - Method in class javax.swing.text.View

Establishes the parent view for this view.

setParent(MutableTreeNode) - Method in class javax.swing.tree.DefaultMutableTreeNode

Sets this node's parent to newParent but does not change the parent's child array.

setParent(MutableTreeNode) - Method in interface javax.swing.tree.MutableTreeNode

Sets the parent of the receiver to newParent.

setParent(Node) - Method in class javax.xml.crypto.dsig.dom.DOMSignContext

Sets the parent node.

setParent(XMLEventReader) - Method in class javax.xml.stream.util.EventReaderDelegate

Set the parent of this instance.

setParent(XMLStreamReader) - Method in class javax.xml.stream.util.StreamReaderDelegate

Set the parent of this instance.

setParent(XMLReader) - Method in class org.xml.sax.helpers.XMLFilterImpl

Set the parent reader.

setParent(XMLReader) - Method in interface org.xml.sax.XMLFilter

Set the parent reader.

setParentElement(SOAPElement) - Method in interface javax.xml.soap.Node

Sets the parent of this Node object to the given SOAPElement object.

setParseBigDecimal(boolean) - Method in class java.text.DecimalFormat

Sets whether the DecimalFormat.parse(java.lang.String, java.text.ParsePosition) method returns BigDecimal.

setParseIntegerOnly(boolean) - Method in class java.text.NumberFormat

Sets whether or not numbers should be parsed as integers only.

setParser(HTMLEditorKit.Parser) - Method in class javax.swing.text.html.HTMLDocument

Sets the parser that is used by the methods that insert html into the existing document, such as setInnerHTML, and setOuterHTML.

setPartialReturn(boolean) - Method in class javax.swing.text.Segment

Flag to indicate that partial returns are valid.

setPassword(char[]) - Method in class javax.security.auth.callback.PasswordCallback

Set the retrieved password.

setPassword(String) - Method in class javax.sql.rowset.BaseRowSet

Sets the password used to create a database connection for this RowSet object to the given String object.

setPassword(String) - Method in interface javax.sql.RowSet

Sets the database password for this RowSet object to the given String.

setPath(String) - Method in class java.net.HttpCookie

Specifies a path for the cookie to which the client should return the cookie.

setPathToNames(Collection<List<?>>) - Method in class java.security.cert.X509CertSelector

Sets the pathToNames criterion.

setPatternSeparator(char) - Method in class java.text.DecimalFormatSymbols

Sets the character used to separate positive and negative subpatterns in a pattern.

setPayload(Source) - Method in interface javax.xml.ws.LogicalMessage

Sets the message payload

setPayload(Object, JAXBContext) - Method in interface javax.xml.ws.LogicalMessage

Sets the message payload

setPercent(char) - Method in class java.text.DecimalFormatSymbols

Sets the character used for percent sign.

setPerformancePreferences(int, int, int) - Method in class java.net.ServerSocket

Sets performance preferences for this ServerSocket.

setPerformancePreferences(int, int, int) - Method in class java.net.Socket

Sets performance preferences for this socket.

setPerformancePreferences(int, int, int) - Method in class java.net.SocketImpl

Sets performance preferences for this socket.

setPerMill(char) - Method in class java.text.DecimalFormatSymbols

Sets the character used for per mille sign.

setPermissions(Set<AclEntryPermission>) - Method in class java.nio.file.attribute.AclEntry.Builder

Sets the permissions component of this builder.

setPermissions(AclEntryPermission...) - Method in class java.nio.file.attribute.AclEntry.Builder

Sets the permissions component of this builder.

setPermissions(Set<PosixFilePermission>) - Method in interface java.nio.file.attribute.PosixFileAttributeView

Updates the file permissions.

setPersistenceDelegate(Class<?>, PersistenceDelegate) - Method in class java.beans.Encoder

Associates the specified persistence delegate with the given type.

setPitchBend(int) - Method in interface javax.sound.midi.MidiChannel

Changes the pitch offset for all notes on this channel.

setPixel(int, int, int[], DataBuffer) - Method in class java.awt.image.BandedSampleModel

Sets a pixel in the DataBuffer using an int array of samples for input.

setPixel(int, int, int[], DataBuffer) - Method in class java.awt.image.ComponentSampleModel

Sets a pixel in the DataBuffer using an int array of samples for input.

setPixel(int, int, int[], DataBuffer) - Method in class java.awt.image.MultiPixelPackedSampleModel

Sets a pixel in the DataBuffer using an int array for input.

setPixel(int, int, int[], DataBuffer) - Method in class java.awt.image.SampleModel

Sets a pixel in the DataBuffer using an int array of samples for input.

setPixel(int, int, float[], DataBuffer) - Method in class java.awt.image.SampleModel

Sets a pixel in the DataBuffer using a float array of samples for input.

setPixel(int, int, double[], DataBuffer) - Method in class java.awt.image.SampleModel

Sets a pixel in the DataBuffer using a double array of samples for input.

setPixel(int, int, int[], DataBuffer) - Method in class java.awt.image.SinglePixelPackedSampleModel

Sets a pixel in the DataBuffer using an int array of samples for input.

setPixel(int, int, int[]) - Method in class java.awt.image.WritableRaster

Sets a pixel in the DataBuffer using an int array of samples for input.

setPixel(int, int, float[]) - Method in class java.awt.image.WritableRaster

Sets a pixel in the DataBuffer using a float array of samples for input.

setPixel(int, int, double[]) - Method in class java.awt.image.WritableRaster

Sets a pixel in the DataBuffer using a double array of samples for input.

setPixels(int, int, int, int, ColorModel, byte[], int, int) - Method in class java.awt.image.AreaAveragingScaleFilter

Combine the components for the delivered byte pixels into the accumulation arrays and send on any averaged data for rows of pixels that are complete.

setPixels(int, int, int, int, ColorModel, int[], int, int) - Method in class java.awt.image.AreaAveragingScaleFilter

Combine the components for the delivered int pixels into the accumulation arrays and send on any averaged data for rows of pixels that are complete.

setPixels(int, int, int, int, int[], DataBuffer) - Method in class java.awt.image.BandedSampleModel

Sets all samples for a rectangle of pixels from an int array containing one sample per array element.

setPixels(int, int, int, int, ColorModel, byte[], int, int) - Method in class java.awt.image.BufferedImageFilter

Filters the information provided in the setPixels method of the ImageConsumer interface which takes an array of bytes.

setPixels(int, int, int, int, ColorModel, int[], int, int) - Method in class java.awt.image.BufferedImageFilter

Filters the information provided in the setPixels method of the ImageConsumer interface which takes an array of integers.

setPixels(int, int, int, int, int[], DataBuffer) - Method in class java.awt.image.ComponentSampleModel

Sets all samples for a rectangle of pixels from an int array containing one sample per array element.

setPixels(int, int, int, int, ColorModel, byte[], int, int) - Method in class java.awt.image.CropImageFilter

Determine whether the delivered byte pixels intersect the region to be extracted and passes through only that subset of pixels that appear in the output region.

setPixels(int, int, int, int, ColorModel, int[], int, int) - Method in class java.awt.image.CropImageFilter

Determine if the delivered int pixels intersect the region to be extracted and pass through only that subset of pixels that appear in the output region.

setPixels(int, int, int, int, ColorModel, byte[], int, int) - Method in interface java.awt.image.ImageConsumer

Delivers the pixels of the image with one or more calls to this method.

setPixels(int, int, int, int, ColorModel, int[], int, int) - Method in interface java.awt.image.ImageConsumer

The pixels of the image are delivered using one or more calls to the setPixels method.

setPixels(int, int, int, int, ColorModel, byte[], int, int) - Method in class java.awt.image.ImageFilter

Filters the information provided in the setPixels method of the ImageConsumer interface which takes an array of bytes.

setPixels(int, int, int, int, ColorModel, int[], int, int) - Method in class java.awt.image.ImageFilter

Filters the information provided in the setPixels method of the ImageConsumer interface which takes an array of integers.

setPixels(int, int, int, int, ColorModel, byte[], int, int) - Method in class java.awt.image.PixelGrabber

The setPixels method is part of the ImageConsumer API which this class must implement to retrieve the pixels.

setPixels(int, int, int, int, ColorModel, int[], int, int) - Method in class java.awt.image.PixelGrabber

The setPixels method is part of the ImageConsumer API which this class must implement to retrieve the pixels.

setPixels(int, int, int, int, ColorModel, byte[], int, int) - Method in class java.awt.image.ReplicateScaleFilter

Choose which rows and columns of the delivered byte pixels are needed for the destination scaled image and pass through just those rows and columns that are needed, replicated as necessary.

setPixels(int, int, int, int, ColorModel, int[], int, int) - Method in class java.awt.image.ReplicateScaleFilter

Choose which rows and columns of the delivered int pixels are needed for the destination scaled image and pass through just those rows and columns that are needed, replicated as necessary.

setPixels(int, int, int, int, ColorModel, byte[], int, int) - Method in class java.awt.image.RGBImageFilter

If the ColorModel object is the same one that has already been converted, then simply passes the pixels through with the converted ColorModel.

setPixels(int, int, int, int, ColorModel, int[], int, int) - Method in class java.awt.image.RGBImageFilter

If the ColorModel object is the same one that has already been converted, then simply passes the pixels through with the converted ColorModel, otherwise converts the buffer of integer pixels to the default RGB ColorModel and passes the converted buffer to the filterRGBPixels method to be converted one by one.

setPixels(int, int, int, int, int[], DataBuffer) - Method in class java.awt.image.SampleModel

Sets all samples for a rectangle of pixels from an int array containing one sample per array element.

setPixels(int, int, int, int, float[], DataBuffer) - Method in class java.awt.image.SampleModel

Sets all samples for a rectangle of pixels from a float array containing one sample per array element.

setPixels(int, int, int, int, double[], DataBuffer) - Method in class java.awt.image.SampleModel

Sets all samples for a rectangle of pixels from a double array containing one sample per array element.

setPixels(int, int, int, int, int[], DataBuffer) - Method in class java.awt.image.SinglePixelPackedSampleModel

Sets all samples for a rectangle of pixels from an int array containing one sample per array element.

setPixels(int, int, int, int, int[]) - Method in class java.awt.image.WritableRaster

Sets all samples for a rectangle of pixels from an int array containing one sample per array element.

setPixels(int, int, int, int, float[]) - Method in class java.awt.image.WritableRaster

Sets all samples for a rectangle of pixels from a float array containing one sample per array element.

setPixels(int, int, int, int, double[]) - Method in class java.awt.image.WritableRaster

Sets all samples for a rectangle of pixels from a double array containing one sample per array element.

setPlaceholder(String) - Method in class javax.swing.text.MaskFormatter

Sets the string to use if the value does not completely fill in the mask.

setPlaceholderCharacter(char) - Method in class javax.swing.text.MaskFormatter

Sets the character to use in place of characters that are not present in the value, ie the user must fill them in.

setPolicy(Set<String>) - Method in class java.security.cert.X509CertSelector

Sets the policy constraint.

setPolicy(Policy) - Static method in class java.security.Policy

Sets the system-wide Policy object.

setPolicy(Policy) - Static method in class javax.security.auth.Policy

Deprecated.

Sets the system-wide Policy object.

setPolicyMappingInhibited(boolean) - Method in class java.security.cert.PKIXParameters

Sets the PolicyMappingInhibited flag.

setPolicyQualifiersRejected(boolean) - Method in class java.security.cert.PKIXParameters

Sets the PolicyQualifiersRejected flag.

setPolyPressure(int, int) - Method in interface javax.sound.midi.MidiChannel

Reacts to a change in the specified note's key pressure.

setPoolable(boolean) - Method in interface java.sql.Statement

Requests that a Statement be pooled or not pooled.

setPopupMenu(PopupMenu) - Method in class java.awt.TrayIcon

Sets the popup menu for this TrayIcon.

setPopupMenuVisible(boolean) - Method in class javax.swing.JMenu

Sets the visibility of the menu's popup.

setPopupSize(Dimension) - Method in class javax.swing.JPopupMenu

Sets the size of the Popup window using a Dimension object.

setPopupSize(int, int) - Method in class javax.swing.JPopupMenu

Sets the size of the Popup window to the specified width and height.

setPopupVisible(boolean) - Method in class javax.swing.JComboBox

Sets the visibility of the popup.

setPopupVisible(JComboBox, boolean) - Method in class javax.swing.plaf.basic.BasicComboBoxUI

Hides the popup.

setPopupVisible(JComboBox, boolean) - Method in class javax.swing.plaf.ComboBoxUI

Set the visiblity of the popup

setPopupVisible(JComboBox, boolean) - Method in class javax.swing.plaf.multi.MultiComboBoxUI

Invokes the setPopupVisible method on each UI handled by this object.

setPort(int) - Method in class java.net.DatagramPacket

Sets the port number on the remote host to which this datagram is being sent.

setPortlist(String) - Method in class java.net.HttpCookie

Specify the portlist of the cookie, which restricts the port(s) to which a cookie may be sent back in a Cookie header.

setPosition(int) - Method in class java.awt.font.LineBreakMeasurer

Sets the current position of this LineBreakMeasurer.

setPosition(Component, int) - Method in class javax.swing.JLayeredPane

Moves the component to position within its current layer, where 0 is the topmost position within the layer and -1 is the bottommost position.

setPositivePrefix(String) - Method in class java.text.DecimalFormat

Set the positive prefix.

setPositiveSuffix(String) - Method in class java.text.DecimalFormat

Set the positive suffix.

setPosixFilePermissions(Path, Set<PosixFilePermission>) - Static method in class java.nio.file.Files

Sets a file's POSIX permissions.

setPrecision(int, int) - Method in class javax.sql.rowset.RowSetMetaDataImpl

Sets the total number of decimal digits in a value stored in the designated column to the given number.

setPrecision(int, int) - Method in interface javax.sql.RowSetMetaData

Sets the designated column's number of decimal digits to the given int.

setPreferred(boolean) - Method in class java.beans.FeatureDescriptor

The "preferred" flag is used to identify features that are particularly important for presenting to humans.

setPreferredMinSize(Dimension) - Method in class javax.swing.plaf.basic.BasicTreeUI

Sets the preferred minimum size.

setPreferredScrollableViewportSize(Dimension) - Method in class javax.swing.JTable

Sets the preferred size of the viewport for this table.

setPreferredSize(Dimension) - Method in class java.awt.Component

Sets the preferred size of this component to a constant value.

setPreferredSize(Dimension) - Method in class javax.swing.JComponent

Sets the preferred size of this component.

setPreferredWidth(int) - Method in class javax.swing.table.TableColumn

Sets this column's preferred width to preferredWidth.

setPrefix(String) - Method in class javax.imageio.metadata.IIOMetadataNode

Does nothing, since namespaces are not supported.

setPrefix(String, String) - Method in interface javax.xml.stream.XMLEventWriter

Sets the prefix the uri is bound to.

setPrefix(String, String) - Method in interface javax.xml.stream.XMLStreamWriter

Sets the prefix the uri is bound to.

setPrefix(String) - Method in interface org.w3c.dom.Node

The namespace prefix of this node, or null if it is unspecified.

setPreservesUnknownTags(boolean) - Method in class javax.swing.text.html.HTMLDocument

Determines how unknown tags are handled by the parser.

setPressed(boolean) - Method in interface javax.swing.ButtonModel

Sets the button to pressed or unpressed.

setPressed(boolean) - Method in class javax.swing.DefaultButtonModel

Sets the button to pressed or unpressed.

setPressed(boolean) - Method in class javax.swing.JToggleButton.ToggleButtonModel

Sets the pressed state of the toggle button.

setPressedIcon(Icon) - Method in class javax.swing.AbstractButton

Sets the pressed icon for the button.

setPreviewPanel(JComponent) - Method in class javax.swing.JColorChooser

Sets the current preview panel.

setPreviousBounds(JInternalFrame, Rectangle) - Method in class javax.swing.DefaultDesktopManager

Stores the bounds of the component just before a maximize call.

setPrimaryType(String) - Method in class javax.activation.MimeType

Set the primary type for this object to the given String.

setPrincipal(UserPrincipal) - Method in class java.nio.file.attribute.AclEntry.Builder

Sets the principal component of this builder.

setPrincipal(Principal) - Method in interface java.security.acl.AclEntry

Specifies the principal for which permissions are granted or denied by this ACL entry.

setPrintable(Printable) - Method in class java.awt.print.PrinterJob

Calls painter to render the pages.

setPrintable(Printable, PageFormat) - Method in class java.awt.print.PrinterJob

Calls painter to render the pages in the specified format.

setPrinter(String) - Method in class java.awt.JobAttributes

Specifies the destination printer for jobs using these attributes.

setPrinterResolution(int[]) - Method in class java.awt.PageAttributes

Specifies the desired print resolution for pages using these attributes.

setPrinterResolution(int) - Method in class java.awt.PageAttributes

Specifies the desired cross feed and feed print resolutions in dots per inch for pages using these attributes.

setPrinterResolutionToDefault() - Method in class java.awt.PageAttributes

Sets the printer resolution for pages using these attributes to the default.

setPrintQuality(PageAttributes.PrintQualityType) - Method in class java.awt.PageAttributes

Specifies the print quality for pages using these attributes.

setPrintQuality(int) - Method in class java.awt.PageAttributes

Specifies the print quality for pages using these attributes.

setPrintQualityToDefault() - Method in class java.awt.PageAttributes

Sets the print quality for pages using these attributes to the default.

setPrintService(PrintService) - Method in class java.awt.print.PrinterJob

Associate this PrinterJob with a new PrintService.

setPriority(int) - Method in class java.lang.Thread

Changes the priority of this thread.

setPrivacy(boolean) - Method in class org.ietf.jgss.MessageProp

Sets the privacy state.

setPrivateKeyValid(Date) - Method in class java.security.cert.X509CertSelector

Sets the privateKeyValid criterion.

setProblemType(int) - Method in class javax.management.relation.RoleUnresolved

Sets problem type.

setProcessors(Iterable<? extends Processor>) - Method in interface javax.tools.JavaCompiler.CompilationTask

Sets processors (for annotation processing).

setProgress(int) - Method in class javax.swing.ProgressMonitor

Indicate the progress of the operation being monitored.

setProgress(int) - Method in class javax.swing.SwingWorker

Sets the progress bound property.

setProgressiveMode(int) - Method in class javax.imageio.ImageWriteParam

Specifies that the writer is to write the image out in a progressive mode such that the stream will contain a series of scans of increasing quality.

setPropagatedFrom(BeanContext) - Method in class java.beans.beancontext.BeanContextEvent

Sets the BeanContext from which this event was propagated.

setPropagationId(Object) - Method in class java.beans.PropertyChangeEvent

Sets the propagationId object for the event.

setProperties(Hashtable<?, ?>) - Method in class java.awt.image.CropImageFilter

Passes along the properties from the source object after adding a property indicating the cropped region.

setProperties(Hashtable<?, ?>) - Method in interface java.awt.image.ImageConsumer

Sets the extensible list of properties associated with this image.

setProperties(Hashtable<?, ?>) - Method in class java.awt.image.ImageFilter

Passes the properties from the source object along after adding a property indicating the stream of filters it has been run through.

setProperties(Hashtable<?, ?>) - Method in class java.awt.image.PixelGrabber

The setProperties method is part of the ImageConsumer API which this class must implement to retrieve the pixels.

setProperties(Hashtable<?, ?>) - Method in class java.awt.image.ReplicateScaleFilter

Passes along the properties from the source object after adding a property indicating the scale applied.

setProperties(Properties) - Static method in class java.lang.System

Sets the system properties to the Properties argument.

setProperties(Map<String, Object>) - Method in class javax.xml.ws.Endpoint

Sets the property bag for this Endpoint instance.

setPropertiesFromAttributes() - Method in class javax.swing.text.html.BlockView

Update any cached values that come from attributes.

setPropertiesFromAttributes() - Method in class javax.swing.text.html.ImageView

Update any cached values that come from attributes.

setPropertiesFromAttributes() - Method in class javax.swing.text.html.InlineView

Set the cached properties from the attributes.

setPropertiesFromAttributes() - Method in class javax.swing.text.html.ListView

setPropertiesFromAttributes() - Method in class javax.swing.text.html.ParagraphView

Sets up the paragraph from css attributes instead of the values found in StyleConstants (i.e.

setPropertiesFromAttributes() - Method in class javax.swing.text.LabelView

Sets the cached properties from the attributes.

setPropertiesFromAttributes() - Method in class javax.swing.text.ParagraphView

Set the cached properties from the attributes.

setProperty(String, String) - Static method in class java.lang.System

Sets the system property indicated by the specified key.

setProperty(String, String) - Static method in class java.security.Security

Sets a security property value.

setProperty(String, String) - Method in class java.util.Properties

Calls the Hashtable method put.

setProperty(String, Object) - Method in class javax.xml.bind.Binder

Set the particular property in the underlying implementation of Binder.

setProperty(String, Object) - Method in class javax.xml.bind.helpers.AbstractMarshallerImpl

Default implementation of the setProperty method handles the four defined properties in Marshaller.

setProperty(String, Object) - Method in class javax.xml.bind.helpers.AbstractUnmarshallerImpl

Default implementation of the setProperty method always throws PropertyException since there are no required properties.

setProperty(String, Object) - Method in interface javax.xml.bind.Marshaller

Set the particular property in the underlying implementation of Marshaller.

setProperty(String, Object) - Method in interface javax.xml.bind.Unmarshaller

Set the particular property in the underlying implementation of Unmarshaller.

setProperty(String, Object) - Method in interface javax.xml.bind.Validator

Deprecated.
since JAXB2.0

setProperty(String, Object) - Method in class javax.xml.crypto.dom.DOMCryptoContext

This implementation uses an internal HashMap to map the name to the specified object.

setProperty(String, Object) - Method in interface javax.xml.crypto.XMLCryptoContext

Sets the specified property.

setProperty(String, Object) - Method in class javax.xml.parsers.SAXParser

Sets the particular property in the underlying implementation of XMLReader.

setProperty(String, Object) - Method in class javax.xml.soap.SOAPMessage

Associates the specified value with the specified property.

setProperty(String, Object) - Method in class javax.xml.stream.XMLInputFactory

Allows the user to set specific feature/property on the underlying implementation.

setProperty(String, Object) - Method in class javax.xml.stream.XMLOutputFactory

Allows the user to set specific features/properties on the underlying implementation.

setProperty(String, Object) - Method in class javax.xml.validation.SchemaFactory

Set the value of a property.

setProperty(String, Object) - Method in class javax.xml.validation.Validator

Set the value of a property.

setProperty(String, Object) - Method in class javax.xml.validation.ValidatorHandler

Set the value of a property.

setProperty(String, Object) - Method in class org.xml.sax.helpers.ParserAdapter

Set a parser property.

setProperty(String, Object) - Method in class org.xml.sax.helpers.XMLFilterImpl

Set the value of a property.

setProperty(String, Object) - Method in interface org.xml.sax.XMLReader

Set the value of a property.

setPropertyEditorClass(Class<?>) - Method in class java.beans.PropertyDescriptor

Normally PropertyEditors will be found using the PropertyEditorManager.

setProtocols(String[]) - Method in class javax.net.ssl.SSLParameters

Sets the array of protocols.

setPrototypeCellValue(E) - Method in class javax.swing.JList

Sets the prototypeCellValue property, and then (if the new value is non-null), computes the fixedCellWidth and fixedCellHeight properties by requesting the cell renderer component for the given value (and index 0) from the cell renderer, and using that component's preferred size.

setPrototypeDisplayValue(Object) - Method in class javax.swing.JComboBox

Sets the prototype display value used to calculate the size of the display for the UI portion.

setPublicId(String) - Method in class javax.xml.transform.stream.StreamSource

Set the public identifier for this Source.

setPublicId(String) - Method in interface org.w3c.dom.ls.LSInput

The public identifier for this input source.

setPublicId(String) - Method in class org.xml.sax.helpers.LocatorImpl

Set the public identifier for this locator.

setPublicId(String) - Method in class org.xml.sax.InputSource

Set the public identifier for this input source.

setPublicKey(PublicKey) - Method in class java.security.Identity

Deprecated.

Sets this identity's public key.

setPurgeFlag(boolean) - Method in class javax.management.relation.RelationService

Sets the flag to indicate if when a notification is received for the unregistration of an MBean referenced in a relation, if an immediate "purge" of the relations (look for the relations no longer valid) has to be performed , or if that will be performed only when the purgeRelations method will be explicitly called.

setPurgeFlag(boolean) - Method in interface javax.management.relation.RelationServiceMBean

Sets the flag to indicate if when a notification is received for the unregistration of an MBean referenced in a relation, if an immediate "purge" of the relations (look for the relations no longer valid) has to be performed, or if that will be performed only when the purgeRelations method is explicitly called.

setPushLevel(Level) - Method in class java.util.logging.MemoryHandler

Set the pushLevel.

setQName(int, String) - Method in class org.xml.sax.helpers.AttributesImpl

Set the qualified name of a specific attribute.

setQOP(int) - Method in class org.ietf.jgss.MessageProp

Sets the QOP value.

setQueryTimeout(int) - Method in interface java.sql.Statement

Sets the number of seconds the driver will wait for a Statement object to execute to the given number of seconds.

setQueryTimeout(int) - Method in class javax.sql.rowset.BaseRowSet

Sets to the given number the maximum number of seconds the driver will wait for a query to execute.

setQueryTimeout(int) - Method in interface javax.sql.RowSet

Sets the maximum time the driver will wait for a statement to execute to the given number of seconds.

setRangeProperties(int, int, int, int, boolean) - Method in interface javax.swing.BoundedRangeModel

This method sets all of the model's data with a single method call.

setRangeProperties(int, int, int, int, boolean) - Method in class javax.swing.DefaultBoundedRangeModel

Sets all of the BoundedRangeModel properties after forcing the arguments to obey the usual constraints:

setRaster(Raster) - Method in class javax.imageio.IIOImage

Sets the current Raster.

setRawContent(InputStream, String) - Method in class javax.xml.soap.AttachmentPart

Sets the content of this attachment part to that contained by the InputStream content and sets the value of the Content-Type header to the value contained in contentType.

setRawContentBytes(byte[], int, int, String) - Method in class javax.xml.soap.AttachmentPart

Sets the content of this attachment part to that contained by the byte[] array content and sets the value of the Content-Type header to the value contained in contentType.

setRawOffset(int) - Method in class java.util.SimpleTimeZone

Sets the base time zone offset to GMT.

setRawOffset(int) - Method in class java.util.TimeZone

Sets the base time zone offset to GMT.

setRawResult(V) - Method in class java.util.concurrent.ForkJoinTask

Forces the given value to be returned as a result.

setRawResult(Void) - Method in class java.util.concurrent.RecursiveAction

Requires null completion value.

setRawResult(V) - Method in class java.util.concurrent.RecursiveTask

setReadable(boolean, boolean) - Method in class java.io.File

Sets the owner's or everybody's read permission for this abstract pathname.

setReadable(boolean) - Method in class java.io.File

A convenience method to set the owner's read permission for this abstract pathname.

setReader(Reader) - Method in interface javax.script.ScriptContext

Sets the Reader for scripts to read input .

setReader(Reader) - Method in class javax.script.SimpleScriptContext

Sets the Reader for scripts to read input .

setReader(Reader) - Method in class javax.xml.transform.stream.StreamSource

Set the input to be a character reader.

setReadMethod(Method) - Method in class java.beans.PropertyDescriptor

Sets the method that should be used to read the property value.

setReadOnly() - Method in class java.io.File

Marks the file or directory named by this abstract pathname so that only read operations are allowed.

setReadOnly(boolean) - Method in interface java.nio.file.attribute.DosFileAttributeView

Updates the value of the read-only attribute.

setReadOnly() - Method in class java.security.PermissionCollection

Marks this PermissionCollection object as "readonly".

setReadOnly(boolean) - Method in interface java.sql.Connection

Puts this connection in read-only mode as a hint to the driver to enable database optimizations.

setReadOnly() - Method in class javax.security.auth.Subject

Set this Subject to be read-only.

setReadOnly(boolean) - Method in class javax.sql.rowset.BaseRowSet

Sets this RowSet object's readOnly property to the given boolean.

setReadOnly(boolean) - Method in interface javax.sql.RowSet

Sets whether this RowSet object is read-only to the given boolean.

setReadTimeout(int) - Method in class java.net.URLConnection

Sets the read timeout to a specified timeout, in milliseconds.

setReceiveBufferSize(int) - Method in class java.net.DatagramSocket

Sets the SO_RCVBUF option to the specified value for this DatagramSocket.

setReceiveBufferSize(int) - Method in class java.net.ServerSocket

Sets a default proposed value for the SO_RCVBUF option for sockets accepted from this ServerSocket.

setReceiveBufferSize(int) - Method in class java.net.Socket

Sets the SO_RCVBUF option to the specified value for this Socket.

setReceiver(Receiver) - Method in interface javax.sound.midi.Transmitter

Sets the receiver to which this transmitter will deliver MIDI messages.

setRect(double, double, double, double) - Method in class java.awt.geom.Rectangle2D.Double

Sets the location and size of this Rectangle2D to the specified double values.

setRect(Rectangle2D) - Method in class java.awt.geom.Rectangle2D.Double

Sets this Rectangle2D to be the same as the specified Rectangle2D.

setRect(float, float, float, float) - Method in class java.awt.geom.Rectangle2D.Float

Sets the location and size of this Rectangle2D to the specified float values.

setRect(double, double, double, double) - Method in class java.awt.geom.Rectangle2D.Float

Sets the location and size of this Rectangle2D to the specified double values.

setRect(Rectangle2D) - Method in class java.awt.geom.Rectangle2D.Float

Sets this Rectangle2D to be the same as the specified Rectangle2D.

setRect(double, double, double, double) - Method in class java.awt.geom.Rectangle2D

Sets the location and size of this Rectangle2D to the specified double values.

setRect(Rectangle2D) - Method in class java.awt.geom.Rectangle2D

Sets this Rectangle2D to be the same as the specified Rectangle2D.

setRect(Raster) - Method in class java.awt.image.WritableRaster

Copies pixels from Raster srcRaster to this WritableRaster.

setRect(int, int, Raster) - Method in class java.awt.image.WritableRaster

Copies pixels from Raster srcRaster to this WritableRaster.

setRect(double, double, double, double) - Method in class java.awt.Rectangle

Sets the bounds of this Rectangle to the integer bounds which encompass the specified x, y, width, and height.

setRef(RemoteStub, RemoteRef) - Static method in class java.rmi.server.RemoteStub

Deprecated.
no replacement. The setRef method is not needed since RemoteStubs can be created with the RemoteStub(RemoteRef) constructor.

setRef(int, Ref) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given REF(<structured-type>) value.

setRef(int, Ref) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given Ref object in the Java programming language.

setRef(int, Ref) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command with the given Ref value.

setRegion(String) - Method in class java.util.Locale.Builder

Sets the region.

setRejectedExecutionHandler(RejectedExecutionHandler) - Method in class java.util.concurrent.ThreadPoolExecutor

Sets a new handler for unexecutable tasks.

setRelationServiceManagementFlag(Boolean) - Method in class javax.management.relation.RelationSupport

setRelationServiceManagementFlag(Boolean) - Method in interface javax.management.relation.RelationSupportMBean

Specifies whether this relation is handled by the Relation Service.

setRelative(boolean) - Method in class javax.naming.NameClassPair

Sets whether the name of this binding is relative to the target context (which is named by the first parameter of the list() method).

setRelay(boolean) - Method in interface javax.xml.soap.SOAPHeaderElement

Sets the relay attribute for this SOAPHeaderElement to be either true or false.

setRemainingName(Name) - Method in exception javax.naming.NamingException

Sets the remaining name field of this exception.

setRemainingName(Name) - Method in class javax.naming.spi.ResolveResult

Sets the remaining name field of this result to name.

setRemainingNewName(Name) - Method in exception javax.naming.CannotProceedException

Sets the "remaining new name" field of this exception.

setRemoveOnCancelPolicy(boolean) - Method in class java.util.concurrent.ScheduledThreadPoolExecutor

Sets the policy on whether cancelled tasks should be immediately removed from the work queue at time of cancellation.

setRenderContext(RenderContext) - Method in class java.awt.image.renderable.RenderableImageProducer

Sets a new RenderContext to use for the next startProduction() call.

setRenderedImage(RenderedImage) - Method in class javax.imageio.IIOImage

Sets the current RenderedImage.

setRenderer(ListCellRenderer) - Method in class javax.swing.JComboBox

Sets the renderer that paints the list items and the item selected from the list in the JComboBox field.

setRenderingHint(RenderingHints.Key, Object) - Method in class java.awt.Graphics2D

Sets the value of a single preference for the rendering algorithms.

setRenderingHints(Map<?, ?>) - Method in class java.awt.Graphics2D

Replaces the values of all preferences for the rendering algorithms with the specified hints.

setRenderingHints(RenderingHints) - Method in class java.awt.image.renderable.RenderContext

Sets the rendering hints of this RenderContext.

setReorderingAllowed(boolean) - Method in class javax.swing.table.JTableHeader

Sets whether the user can drag column headers to reorder columns.

setRepeats(boolean) - Method in class javax.swing.Timer

If flag is false, instructs the Timer to send only one action event to its listeners.

setRequestControls(Control[]) - Method in class javax.naming.ldap.InitialLdapContext

setRequestControls(Control[]) - Method in interface javax.naming.ldap.LdapContext

Sets the request controls for methods subsequently invoked on this context.

setRequestFocusEnabled(boolean) - Method in class javax.swing.JComponent

Provides a hint as to whether or not this JComponent should get focus.

setRequestMethod(String) - Method in class java.net.HttpURLConnection

Set the method for the URL request, one of: GET POST HEAD OPTIONS PUT DELETE TRACE are legal, subject to protocol restrictions.

setRequestProperty(String, String) - Method in class java.net.URLConnection

Sets the general request property.

setReshowDelay(int) - Method in class javax.swing.ToolTipManager

Used to specify the amount of time before the user has to wait initialDelay milliseconds before a tooltip will be shown.

setResizable(boolean) - Method in class java.awt.Dialog

Sets whether this dialog is resizable by the user.

setResizable(boolean) - Method in class java.awt.Frame

Sets whether this frame is resizable by the user.

setResizable(boolean) - Method in class javax.swing.JInternalFrame

Sets whether the JInternalFrame can be resized by some user action.

setResizable(boolean) - Method in class javax.swing.table.TableColumn

Sets whether this column can be resized.

setResizeWeight(double) - Method in class javax.swing.JSplitPane

Specifies how to distribute extra space when the size of the split pane changes.

setResizingAllowed(boolean) - Method in class javax.swing.table.JTableHeader

Sets whether the user can resize columns by dragging between headers.

setResizingColumn(TableColumn) - Method in class javax.swing.table.JTableHeader

Sets the header's resizingColumn to aColumn.

setResolvedName(Name) - Method in exception javax.naming.NamingException

Sets the resolved name field of this exception.

setResolvedObj(Object) - Method in exception javax.naming.NamingException

Sets the resolved object field of this exception.

setResolvedObj(Object) - Method in class javax.naming.spi.ResolveResult

Sets the resolved Object field of this result to obj.

setResolvedValue(int, Object) - Method in interface javax.sql.rowset.spi.SyncResolver

Sets obj as the value in column index in the current row of the RowSet object that is being synchronized.

setResolvedValue(String, Object) - Method in interface javax.sql.rowset.spi.SyncResolver

Sets obj as the value in column columnName in the current row of the RowSet object that is being synchronized.

setResolveParent(AttributeSet) - Method in class javax.swing.text.AbstractDocument.AbstractElement

Sets the resolving parent.

setResolveParent(Keymap) - Method in interface javax.swing.text.Keymap

Sets the parent keymap, which will be used to resolve key-bindings.

setResolveParent(AttributeSet) - Method in interface javax.swing.text.MutableAttributeSet

Sets the resolving parent.

setResolveParent(AttributeSet) - Method in class javax.swing.text.SimpleAttributeSet

Sets the resolving parent.

setResolveParent(AttributeSet) - Method in class javax.swing.text.StyleContext.NamedStyle

Sets the resolving parent.

setResourceBaseName(String) - Method in class javax.imageio.metadata.IIOMetadataFormatImpl

Sets a new base name for locating ResourceBundles containing descriptions of elements and attributes for this format.

setResourceBundle(ResourceBundle) - Method in class java.util.logging.LogRecord

Set the localization resource bundle.

setResourceBundleName(String) - Method in class java.util.logging.LogRecord

Set the localization resource bundle name.

setResourceResolver(LSResourceResolver) - Method in class javax.xml.validation.SchemaFactory

Sets the LSResourceResolver to customize resource resolution when parsing schemas.

setResourceResolver(LSResourceResolver) - Method in class javax.xml.validation.Validator

Sets the LSResourceResolver to customize resource resolution while in a validation episode.

setResourceResolver(LSResourceResolver) - Method in class javax.xml.validation.ValidatorHandler

Sets the LSResourceResolver to customize resource resolution while in a validation episode.

setResult(Class<T>) - Method in interface java.sql.SQLXML

Returns a Result for setting the XML value designated by this SQLXML instance.

setResult(Result) - Method in interface javax.xml.transform.sax.TransformerHandler

Set the Result associated with this TransformerHandler to be used for the transformation.

setReturningAttributes(String[]) - Method in class javax.naming.directory.SearchControls

Specifies the attributes that will be returned as part of the search.

setReturningObjFlag(boolean) - Method in class javax.naming.directory.SearchControls

Enables/disables returning objects returned as part of the result.

setReuseAddress(boolean) - Method in class java.net.DatagramSocket

Enable/disable the SO_REUSEADDR socket option.

setReuseAddress(boolean) - Method in class java.net.ServerSocket

Enable/disable the SO_REUSEADDR socket option.

setReuseAddress(boolean) - Method in class java.net.Socket

Enable/disable the SO_REUSEADDR socket option.

setRevocationEnabled(boolean) - Method in class java.security.cert.PKIXParameters

Sets the RevocationEnabled flag.

setRGB(int, int, int) - Method in class java.awt.image.BufferedImage

Sets a pixel in this BufferedImage to the specified RGB value.

setRGB(int, int, int, int, int[], int, int) - Method in class java.awt.image.BufferedImage

Sets an array of integer pixels in the default RGB color model (TYPE_INT_ARGB) and default sRGB color space, into a portion of the image data.

setRightChildIndent(int) - Method in class javax.swing.plaf.basic.BasicTreeUI

setRightComponent(Component) - Method in class javax.swing.JSplitPane

Sets the component to the right (or below) the divider.

setRightIndent(MutableAttributeSet, float) - Static method in class javax.swing.text.StyleConstants

Sets right indent.

setRightInset(float) - Method in class javax.swing.text.AsyncBoxView

Set the right part of the margin around the view.

setRole(Role) - Method in interface javax.management.relation.Relation

Sets the given role.

setRole(String, Role) - Method in class javax.management.relation.RelationService

Sets the given role in given relation.

setRole(String, Role) - Method in interface javax.management.relation.RelationServiceMBean

Sets the given role in given relation.

setRole(Role) - Method in class javax.management.relation.RelationSupport

Sets the given role.

setRole(String) - Method in interface javax.xml.soap.SOAPHeaderElement

Sets the Role associated with this SOAPHeaderElement object to the specified Role.

setRoleName(String) - Method in class javax.management.relation.Role

Sets role name.

setRoleName(String) - Method in class javax.management.relation.RoleUnresolved

Sets role name.

setRoles(RoleList) - Method in interface javax.management.relation.Relation

Sets the given roles.

setRoles(String, RoleList) - Method in class javax.management.relation.RelationService

Sets the given roles in given relation.

setRoles(String, RoleList) - Method in interface javax.management.relation.RelationServiceMBean

Sets the given roles in given relation.

setRoles(RoleList) - Method in class javax.management.relation.RelationSupport

Sets the given roles.

setRoles(RoleList) - Method in class javax.management.relation.RoleResult

Sets list of roles successfully accessed.

setRoles(Set<String>) - Method in interface javax.xml.ws.soap.SOAPBinding

Sets the roles played by the SOAP binding instance.

setRolesUnresolved(RoleUnresolvedList) - Method in class javax.management.relation.RoleResult

Sets list of roles unsuccessfully accessed.

setRoleValue(List<ObjectName>) - Method in class javax.management.relation.Role

Sets role value.

setRoleValue(List<ObjectName>) - Method in class javax.management.relation.RoleUnresolved

Sets role value.

setRollover(boolean) - Method in interface javax.swing.ButtonModel

Sets or clears the button's rollover state

setRollover(boolean) - Method in class javax.swing.DefaultButtonModel

Sets or clears the button's rollover state

setRollover(boolean) - Method in class javax.swing.JToolBar

Sets the rollover state of this toolbar.

setRolloverBorders(boolean) - Method in class javax.swing.plaf.basic.BasicToolBarUI

Sets the flag for enabling rollover borders on the toolbar and it will also install the apropriate border depending on the state of the flag.

setRolloverEnabled(boolean) - Method in class javax.swing.AbstractButton

Sets the rolloverEnabled property, which must be true for rollover effects to occur.

setRolloverIcon(Icon) - Method in class javax.swing.AbstractButton

Sets the rollover icon for the button.

setRolloverSelectedIcon(Icon) - Method in class javax.swing.AbstractButton

Sets the rollover selected icon for the button.

setRolloverTab(int) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI

Sets the tab the mouse is currently over to index.

setRolloverTab(int) - Method in class javax.swing.plaf.synth.SynthTabbedPaneUI

setRoot(TreeNode) - Method in class javax.swing.tree.DefaultTreeModel

Sets the root to root.

setRootCause(Throwable) - Method in exception javax.naming.NamingException

Records the root cause of this NamingException.

setRootFrame(Frame) - Static method in class javax.swing.JOptionPane

Sets the frame to use for class methods in which a frame is not provided.

setRootPane(JRootPane) - Method in class javax.swing.JApplet

Sets the rootPane property.

setRootPane(JRootPane) - Method in class javax.swing.JDialog

Sets the rootPane property.

setRootPane(JRootPane) - Method in class javax.swing.JFrame

Sets the rootPane property.

setRootPane(JRootPane) - Method in class javax.swing.JInternalFrame

Sets the rootPane property for this JInternalFrame.

setRootPane(JRootPane) - Method in class javax.swing.JWindow

Sets the new rootPane object for this window.

setRootPaneCheckingEnabled(boolean) - Method in class javax.swing.JApplet

Sets whether calls to add and setLayout are forwarded to the contentPane.

setRootPaneCheckingEnabled(boolean) - Method in class javax.swing.JDialog

Sets whether calls to add and setLayout are forwarded to the contentPane.

setRootPaneCheckingEnabled(boolean) - Method in class javax.swing.JFrame

Sets whether calls to add and setLayout are forwarded to the contentPane.

setRootPaneCheckingEnabled(boolean) - Method in class javax.swing.JInternalFrame

Sets whether calls to add and setLayout are forwarded to the contentPane.

setRootPaneCheckingEnabled(boolean) - Method in class javax.swing.JWindow

Sets whether calls to add and setLayout are forwarded to the contentPane.

setRootVisible(boolean) - Method in class javax.swing.JTree

Determines whether or not the root node from the TreeModel is visible.

setRootVisible(boolean) - Method in class javax.swing.plaf.basic.BasicTreeUI

Sets the root to being visible.

setRootVisible(boolean) - Method in class javax.swing.tree.AbstractLayoutCache

Determines whether or not the root node from the TreeModel is visible.

setRootVisible(boolean) - Method in class javax.swing.tree.FixedHeightLayoutCache

Determines whether or not the root node from the TreeModel is visible.

setRootVisible(boolean) - Method in class javax.swing.tree.VariableHeightLayoutCache

Determines whether or not the root node from the TreeModel is visible.

setRoundingMode(RoundingMode) - Method in class java.text.DecimalFormat

Sets the RoundingMode used in this DecimalFormat.

setRoundingMode(RoundingMode) - Method in class java.text.NumberFormat

Sets the RoundingMode used in this NumberFormat.

setRoundRect(double, double, double, double, double, double) - Method in class java.awt.geom.RoundRectangle2D.Double

Sets the location, size, and corner radii of this RoundRectangle2D to the specified double values.

setRoundRect(RoundRectangle2D) - Method in class java.awt.geom.RoundRectangle2D.Double

Sets this RoundRectangle2D to be the same as the specified RoundRectangle2D.

setRoundRect(float, float, float, float, float, float) - Method in class java.awt.geom.RoundRectangle2D.Float

Sets the location, size, and corner radii of this RoundRectangle2D to the specified float values.

setRoundRect(double, double, double, double, double, double) - Method in class java.awt.geom.RoundRectangle2D.Float

Sets the location, size, and corner radii of this RoundRectangle2D to the specified double values.

setRoundRect(RoundRectangle2D) - Method in class java.awt.geom.RoundRectangle2D.Float

Sets this RoundRectangle2D to be the same as the specified RoundRectangle2D.

setRoundRect(double, double, double, double, double, double) - Method in class java.awt.geom.RoundRectangle2D

Sets the location, size, and corner radii of this RoundRectangle2D to the specified double values.

setRoundRect(RoundRectangle2D) - Method in class java.awt.geom.RoundRectangle2D

Sets this RoundRectangle2D to be the same as the specified RoundRectangle2D.

setRowCount(int) - Method in class javax.swing.table.DefaultTableModel

Sets the number of rows in the model.

setRowFilter(RowFilter<? super M, ? super I>) - Method in class javax.swing.DefaultRowSorter

Sets the filter that determines which rows, if any, should be hidden from the view.

setRowHeader(JViewport) - Method in class javax.swing.JScrollPane

Removes the old rowHeader, if it exists; if the new rowHeader isn't null, syncs the y coordinate of its viewPosition with the viewport (if there is one) and then adds it to the scroll pane.

setRowHeaderView(Component) - Method in class javax.swing.JScrollPane

Creates a row-header viewport if necessary, sets its view and then adds the row-header viewport to the scrollpane.

setRowHeight(int) - Method in class javax.swing.JTable

Sets the height, in pixels, of all cells to rowHeight, revalidates, and repaints.

setRowHeight(int, int) - Method in class javax.swing.JTable

Sets the height for row to rowHeight, revalidates, and repaints.

setRowHeight(int) - Method in class javax.swing.JTree

Sets the height of each cell, in pixels.

setRowHeight(int) - Method in class javax.swing.plaf.basic.BasicTreeUI

Sets the row height, this is forwarded to the treeState.

setRowHeight(int) - Method in class javax.swing.tree.AbstractLayoutCache

Sets the height of each cell.

setRowHeight(int) - Method in class javax.swing.tree.FixedHeightLayoutCache

Sets the height of each cell.

setRowHeight(int) - Method in class javax.swing.tree.VariableHeightLayoutCache

Sets the height of each cell.

setRowId(String, RowId) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given java.sql.RowId object.

setRowId(int, RowId) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given java.sql.RowId object.

setRowId(int, RowId) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.sql.RowId object.

setRowId(String, RowId) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.sql.RowId object.

setRowId(int, RowId) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given java.sql.RowId object.

setRowId(String, RowId) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given java.sql.RowId object.

setRowMapper(RowMapper) - Method in class javax.swing.JTree.EmptySelectionModel

This is overriden to do nothing; EmptySelectionModel does not allow a selection.

setRowMapper(RowMapper) - Method in class javax.swing.tree.DefaultTreeSelectionModel

Sets the RowMapper instance.

setRowMapper(RowMapper) - Method in interface javax.swing.tree.TreeSelectionModel

Sets the RowMapper instance.

setRowMargin(int) - Method in class javax.swing.JTable

Sets the amount of empty space between cells in adjacent rows.

setRows(int) - Method in class java.awt.GridLayout

Sets the number of rows in this layout to the specified value.

setRows(int) - Method in class java.awt.TextArea

Sets the number of rows for this text area.

setRows(int) - Method in class javax.swing.JTextArea

Sets the number of rows for this TextArea.

setRowSelectionAllowed(boolean) - Method in class javax.swing.JTable

Sets whether the rows in this model can be selected.

setRowSelectionInterval(int, int) - Method in class javax.swing.JTable

Selects the rows from index0 to index1, inclusive.

setRowSorter(RowSorter<? extends TableModel>) - Method in class javax.swing.JTable

Sets the RowSorter.

setSample(int, int, int, int, DataBuffer) - Method in class java.awt.image.BandedSampleModel

Sets a sample in the specified band for the pixel located at (x,y) in the DataBuffer using an int for input.

setSample(int, int, int, float, DataBuffer) - Method in class java.awt.image.BandedSampleModel

Sets a sample in the specified band for the pixel located at (x,y) in the DataBuffer using a float for input.

setSample(int, int, int, double, DataBuffer) - Method in class java.awt.image.BandedSampleModel

Sets a sample in the specified band for the pixel located at (x,y) in the DataBuffer using a double for input.

setSample(int, int, int, int, DataBuffer) - Method in class java.awt.image.ComponentSampleModel

Sets a sample in the specified band for the pixel located at (x,y) in the DataBuffer using an int for input.

setSample(int, int, int, float, DataBuffer) - Method in class java.awt.image.ComponentSampleModel

Sets a sample in the specified band for the pixel located at (x,y) in the DataBuffer using a float for input.

setSample(int, int, int, double, DataBuffer) - Method in class java.awt.image.ComponentSampleModel

Sets a sample in the specified band for the pixel located at (x,y) in the DataBuffer using a double for input.

setSample(int, int, int, int, DataBuffer) - Method in class java.awt.image.MultiPixelPackedSampleModel

Sets a sample in the specified band for the pixel located at (x, y) in the DataBuffer using an int for input.

setSample(int, int, int, int, DataBuffer) - Method in class java.awt.image.SampleModel

Sets a sample in the specified band for the pixel located at (x,y) in the DataBuffer using an int for input.

setSample(int, int, int, float, DataBuffer) - Method in class java.awt.image.SampleModel

Sets a sample in the specified band for the pixel located at (x,y) in the DataBuffer using a float for input.

setSample(int, int, int, double, DataBuffer) - Method in class java.awt.image.SampleModel

Sets a sample in the specified band for the pixel located at (x,y) in the DataBuffer using a double for input.

setSample(int, int, int, int, DataBuffer) - Method in class java.awt.image.SinglePixelPackedSampleModel

Sets a sample in the specified band for the pixel located at (x,y) in the DataBuffer using an int for input.

setSample(int, int, int, int) - Method in class java.awt.image.WritableRaster

Sets a sample in the specified band for the pixel located at (x,y) in the DataBuffer using an int for input.

setSample(int, int, int, float) - Method in class java.awt.image.WritableRaster

Sets a sample in the specified band for the pixel located at (x,y) in the DataBuffer using a float for input.

setSample(int, int, int, double) - Method in class java.awt.image.WritableRaster

Sets a sample in the specified band for the pixel located at (x,y) in the DataBuffer using a double for input.

setSamples(int, int, int, int, int, int[], DataBuffer) - Method in class java.awt.image.BandedSampleModel

Sets the samples in the specified band for the specified rectangle of pixels from an int array containing one sample per data array element.

setSamples(int, int, int, int, int, int[], DataBuffer) - Method in class java.awt.image.ComponentSampleModel

Sets the samples in the specified band for the specified rectangle of pixels from an int array containing one sample per data array element.

setSamples(int, int, int, int, int, int[], DataBuffer) - Method in class java.awt.image.SampleModel

Sets the samples in the specified band for the specified rectangle of pixels from an int array containing one sample per array element.

setSamples(int, int, int, int, int, float[], DataBuffer) - Method in class java.awt.image.SampleModel

Sets the samples in the specified band for the specified rectangle of pixels from a float array containing one sample per array element.

setSamples(int, int, int, int, int, double[], DataBuffer) - Method in class java.awt.image.SampleModel

Sets the samples in the specified band for the specified rectangle of pixels from a double array containing one sample per array element.

setSamples(int, int, int, int, int, int[], DataBuffer) - Method in class java.awt.image.SinglePixelPackedSampleModel

Sets the samples in the specified band for the specified rectangle of pixels from an int array containing one sample per array element.

setSamples(int, int, int, int, int, int[]) - Method in class java.awt.image.WritableRaster

Sets the samples in the specified band for the specified rectangle of pixels from an int array containing one sample per array element.

setSamples(int, int, int, int, int, float[]) - Method in class java.awt.image.WritableRaster

Sets the samples in the specified band for the specified rectangle of pixels from a float array containing one sample per array element.

setSamples(int, int, int, int, int, double[]) - Method in class java.awt.image.WritableRaster

Sets the samples in the specified band for the specified rectangle of pixels from a double array containing one sample per array element.

setSavepoint() - Method in interface java.sql.Connection

Creates an unnamed savepoint in the current transaction and returns the new Savepoint object that represents it.

setSavepoint(String) - Method in interface java.sql.Connection

Creates a savepoint with the given name in the current transaction and returns the new Savepoint object that represents it.

setScale(int, RoundingMode) - Method in class java.math.BigDecimal

Returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal's unscaled value by the appropriate power of ten to maintain its overall value.

setScale(int, int) - Method in class java.math.BigDecimal

Returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal's unscaled value by the appropriate power of ten to maintain its overall value.

setScale(int) - Method in class java.math.BigDecimal

Returns a BigDecimal whose scale is the specified value, and whose value is numerically equal to this BigDecimal's.

setScale(int, int) - Method in class javax.sql.rowset.RowSetMetaDataImpl

Sets the number of digits to the right of the decimal point in a value stored in the designated column to the given number.

setScale(int, int) - Method in interface javax.sql.RowSetMetaData

Sets the designated column's number of digits to the right of the decimal point to the given int.

setSchema(String) - Method in interface java.sql.Connection

Sets the given schema name to access.

setSchema(Schema) - Method in class javax.xml.bind.Binder

Specifies whether marshal, unmarshal and update methods performs validation on their XML content.

setSchema(Schema) - Method in class javax.xml.bind.helpers.AbstractMarshallerImpl

setSchema(Schema) - Method in class javax.xml.bind.helpers.AbstractUnmarshallerImpl

setSchema(Schema) - Method in interface javax.xml.bind.Marshaller

Specify the JAXP 1.3 Schema object that should be used to validate subsequent marshal operations against.

setSchema(Schema) - Method in interface javax.xml.bind.Unmarshaller

Specify the JAXP 1.3 Schema object that should be used to validate subsequent unmarshal operations against.

setSchema(Schema) - Method in class javax.xml.parsers.DocumentBuilderFactory

Set the Schema to be used by parsers created from this factory.

setSchema(Schema) - Method in class javax.xml.parsers.SAXParserFactory

Set the Schema to be used by parsers created from this factory.

setSchemaLocation(String) - Method in class javax.xml.bind.helpers.AbstractMarshallerImpl

Convenience method for setting the schemaLocation.

setSchemaName(int, String) - Method in class javax.sql.rowset.RowSetMetaDataImpl

Sets the designated column's table's schema name, if any, to schemaName.

setSchemaName(int, String) - Method in interface javax.sql.RowSetMetaData

Sets the name of the designated column's table's schema, if any, to the given String.

setScope(String, MessageContext.Scope) - Method in interface javax.xml.ws.handler.MessageContext

Sets the scope of a property.

setScript(String) - Method in class java.util.Locale.Builder

Sets the script.

setScrollByBlock(boolean) - Method in class javax.swing.plaf.basic.BasicScrollBarUI.ScrollListener

setScrollByBlock(boolean) - Method in class javax.swing.plaf.basic.BasicSliderUI.ScrollListener

setScrollMode(int) - Method in class javax.swing.JViewport

Used to control the method of scrolling the viewport contents.

setScrollOffset(int) - Method in class javax.swing.JTextField

Sets the scroll offset, in pixels.

setScrollPosition(int, int) - Method in class java.awt.ScrollPane

Scrolls to the specified position within the child component.

setScrollPosition(Point) - Method in class java.awt.ScrollPane

Scrolls to the specified position within the child component.

setScrollsOnExpand(boolean) - Method in class javax.swing.JTree

Sets the scrollsOnExpand property, which determines whether the tree might scroll to show previously hidden children.

setSearchable(int, boolean) - Method in class javax.sql.rowset.RowSetMetaDataImpl

Sets whether a value stored in the designated column can be used in a WHERE clause to the given boolean value.

setSearchable(int, boolean) - Method in interface javax.sql.RowSetMetaData

Sets whether the designated column can be used in a where clause.

setSearchScope(int) - Method in class javax.naming.directory.SearchControls

Sets the search scope to one of: OBJECT_SCOPE, ONELEVEL_SCOPE, SUBTREE_SCOPE.

setSecond(int) - Method in class javax.xml.datatype.XMLGregorianCalendar

Set seconds.

setSeconds(int) - Method in class java.sql.Date

Deprecated.

setSeconds(int) - Method in class java.util.Date

Deprecated.
As of JDK version 1.1, replaced by Calendar.set(Calendar.SECOND, int seconds).

setSecure(boolean) - Method in class java.net.HttpCookie

Indicates whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL.

setSecurityManager(SecurityManager) - Static method in class java.lang.System

Sets the System security.

setSeed(byte[]) - Method in class java.security.SecureRandom

Reseeds this random object.

setSeed(long) - Method in class java.security.SecureRandom

Reseeds this random object, using the eight bytes contained in the given long seed.

setSeed(long) - Method in class java.util.concurrent.ThreadLocalRandom

Throws UnsupportedOperationException.

setSeed(long) - Method in class java.util.Random

Sets the seed of this random number generator using a single long seed.

setSelected(boolean) - Method in class javax.swing.AbstractButton

Sets the state of the button.

setSelected(ButtonModel, boolean) - Method in class javax.swing.ButtonGroup

Sets the selected value for the ButtonModel.

setSelected(boolean) - Method in interface javax.swing.ButtonModel

Selects or deselects the button.

setSelected(boolean) - Method in class javax.swing.DefaultButtonModel

Selects or deselects the button.

setSelected(boolean) - Method in class javax.swing.JInternalFrame

Selects or deselects the internal frame if it's showing.

setSelected(boolean) - Method in class javax.swing.JMenu

Sets the selection status of the menu.

setSelected(Component) - Method in class javax.swing.JMenuBar

Sets the currently selected component, producing a a change to the selection model.

setSelected(Component) - Method in class javax.swing.JPopupMenu

Sets the currently selected component, This will result in a change to the selection model.

setSelected(boolean) - Method in class javax.swing.JToggleButton.ToggleButtonModel

Sets the selected state of the button.

setSelectedCheckbox(Checkbox) - Method in class java.awt.CheckboxGroup

Sets the currently selected check box in this group to be the specified check box.

setSelectedColor(Color) - Method in interface javax.swing.colorchooser.ColorSelectionModel

Sets the selected color to color.

setSelectedColor(Color) - Method in class javax.swing.colorchooser.DefaultColorSelectionModel

Sets the selected color to color.

setSelectedComponent(Component) - Method in class javax.swing.JTabbedPane

Sets the selected component for this tabbedpane.

setSelectedFile(File) - Method in class javax.swing.JFileChooser

Sets the selected file.

setSelectedFiles(File[]) - Method in class javax.swing.JFileChooser

Sets the list of selected files if the file chooser is set to allow multiple selection.

setSelectedFrame(JInternalFrame) - Method in class javax.swing.JDesktopPane

Sets the currently active JInternalFrame in this JDesktopPane.

setSelectedIcon(Icon) - Method in class javax.swing.AbstractButton

Sets the selected icon for the button.

setSelectedIndex(int) - Method in class javax.security.auth.callback.ChoiceCallback

Set the selected choice.

setSelectedIndex(int) - Method in class javax.security.auth.callback.ConfirmationCallback

Set the selected confirmation option.

setSelectedIndex(int) - Method in class javax.swing.DefaultSingleSelectionModel

setSelectedIndex(int) - Method in class javax.swing.JComboBox

Selects the item at index anIndex.

setSelectedIndex(int) - Method in class javax.swing.JList

Selects a single cell.

setSelectedIndex(int) - Method in class javax.swing.JTabbedPane

Sets the selected index for this tabbedpane.

setSelectedIndex(int) - Method in interface javax.swing.SingleSelectionModel

Sets the model's selected index to index.

setSelectedIndexes(int[]) - Method in class javax.security.auth.callback.ChoiceCallback

Set the selected choices.

setSelectedIndices(int[]) - Method in class javax.swing.JList

Changes the selection to be the set of indices specified by the given array.

setSelectedItem(Object) - Method in interface javax.swing.ComboBoxModel

Set the selected item.

setSelectedItem(Object) - Method in class javax.swing.DefaultComboBoxModel

Set the value of the selected item.

setSelectedItem(Object) - Method in class javax.swing.JComboBox

Sets the selected item in the combo box display area to the object in the argument.

setSelectedItem(Object) - Method in class javax.swing.plaf.metal.MetalFileChooserUI.DirectoryComboBoxModel

setSelectedItem(Object) - Method in class javax.swing.plaf.metal.MetalFileChooserUI.FilterComboBoxModel

setSelectedPath(MenuElement[]) - Method in class javax.swing.MenuSelectionManager

Changes the selection in the menu hierarchy.

setSelectedTextColor(Color) - Method in class javax.swing.text.JTextComponent

Sets the current color used to render the selected text.

setSelectedValue(Object, boolean) - Method in class javax.swing.JList

Selects the specified object from the list.

setSelection(boolean) - Method in class javax.swing.text.html.Option

Sets the selected state.

setSelectionBackground(Color) - Method in class javax.swing.JList

Sets the color used to draw the background of selected items, which cell renderers can use fill selected cells.

setSelectionBackground(Color) - Method in class javax.swing.JTable

Sets the background color for selected cells.

setSelectionColor(Color) - Method in class javax.swing.text.JTextComponent

Sets the current color used to render the selection.

setSelectionEnd(int) - Method in class java.awt.TextComponent

Sets the selection end for this text component to the specified position.

setSelectionEnd(int) - Method in class javax.swing.text.JTextComponent

Sets the selection end to the specified position.

setSelectionForeground(Color) - Method in class javax.swing.JList

Sets the color used to draw the foreground of selected items, which cell renderers can use to render text and graphics.

setSelectionForeground(Color) - Method in class javax.swing.JTable

Sets the foreground color for selected cells.

setSelectionInterval(int, int) - Method in class javax.swing.DefaultListSelectionModel

Changes the selection to be between index0 and index1 inclusive.

setSelectionInterval(int, int) - Method in class javax.swing.JList

Selects the specified interval.

setSelectionInterval(int, int) - Method in class javax.swing.JTree

Selects the rows in the specified interval (inclusive).

setSelectionInterval(int, int) - Method in interface javax.swing.ListSelectionModel

Changes the selection to be between index0 and index1 inclusive.

setSelectionMode(int) - Method in class javax.swing.DefaultListSelectionModel

Sets the selection mode.

setSelectionMode(int) - Method in class javax.swing.JList

Sets the selection mode for the list.

setSelectionMode(int) - Method in class javax.swing.JTable

Sets the table's selection mode to allow only single selections, a single contiguous interval, or multiple intervals.

setSelectionMode(int) - Method in class javax.swing.JTree.EmptySelectionModel

This is overriden to do nothing; EmptySelectionModel does not allow a selection.

setSelectionMode(int) - Method in interface javax.swing.ListSelectionModel

Sets the selection mode.

setSelectionMode(int) - Method in class javax.swing.tree.DefaultTreeSelectionModel

Sets the selection model, which must be one of SINGLE_TREE_SELECTION, CONTIGUOUS_TREE_SELECTION or DISCONTIGUOUS_TREE_SELECTION.

setSelectionMode(int) - Method in interface javax.swing.tree.TreeSelectionModel

Sets the selection model, which must be one of SINGLE_TREE_SELECTION, CONTIGUOUS_TREE_SELECTION or DISCONTIGUOUS_TREE_SELECTION.

setSelectionModel(ColorSelectionModel) - Method in class javax.swing.JColorChooser

Sets the model containing the selected color.

setSelectionModel(ListSelectionModel) - Method in class javax.swing.JList

Sets the selectionModel for the list to a non-null ListSelectionModel implementation.

setSelectionModel(SingleSelectionModel) - Method in class javax.swing.JMenuBar

Sets the model object to handle single selections.

setSelectionModel(SingleSelectionModel) - Method in class javax.swing.JPopupMenu

Sets the model object to handle single selections.

setSelectionModel(ListSelectionModel) - Method in class javax.swing.JTable

Sets the row selection model for this table to newModel and registers for listener notifications from the new selection model.

setSelectionModel(TreeSelectionModel) - Method in class javax.swing.JTree

Sets the tree's selection model.

setSelectionModel(TreeSelectionModel) - Method in class javax.swing.plaf.basic.BasicTreeUI

Resets the selection model.

setSelectionModel(ListSelectionModel) - Method in class javax.swing.table.DefaultTableColumnModel

Sets the selection model for this TableColumnModel to newModel and registers for listener notifications from the new selection model.

setSelectionModel(ListSelectionModel) - Method in interface javax.swing.table.TableColumnModel

Sets the selection model.

setSelectionModel(TreeSelectionModel) - Method in class javax.swing.tree.AbstractLayoutCache

Sets the TreeSelectionModel used to manage the selection to new LSM.

setSelectionPath(TreePath) - Method in class javax.swing.JTree

Selects the node identified by the specified path.

setSelectionPath(TreePath) - Method in class javax.swing.tree.DefaultTreeSelectionModel

Sets the selection to path.

setSelectionPath(TreePath) - Method in interface javax.swing.tree.TreeSelectionModel

Sets the selection to path.

setSelectionPaths(TreePath[]) - Method in class javax.swing.JTree.EmptySelectionModel

This is overriden to do nothing; EmptySelectionModel does not allow a selection.

setSelectionPaths(TreePath[]) - Method in class javax.swing.JTree

Selects the nodes identified by the specified array of paths.

setSelectionPaths(TreePath[]) - Method in class javax.swing.tree.DefaultTreeSelectionModel

Sets the selection.

setSelectionPaths(TreePath[]) - Method in interface javax.swing.tree.TreeSelectionModel

Sets the selection to path.

setSelectionRow(int) - Method in class javax.swing.JTree

Selects the node at the specified row in the display.

setSelectionRows(int[]) - Method in class javax.swing.JTree

Selects the nodes corresponding to each of the specified rows in the display.

setSelectionStart(int) - Method in class java.awt.TextComponent

Sets the selection start for this text component to the specified position.

setSelectionStart(int) - Method in class javax.swing.text.JTextComponent

Sets the selection start to the specified position.

setSelectionValues(Object[]) - Method in class javax.swing.JOptionPane

Sets the input selection values for a pane that provides the user with a list of items to choose from.

setSelectionVisible(boolean) - Method in interface javax.swing.text.Caret

Sets the visibility of the selection

setSelectionVisible(boolean) - Method in class javax.swing.text.DefaultCaret

Changes the selection visibility.

setSendBufferSize(int) - Method in class java.net.DatagramSocket

Sets the SO_SNDBUF option to the specified value for this DatagramSocket.

setSendBufferSize(int) - Method in class java.net.Socket

Sets the SO_SNDBUF option to the specified value for this Socket.

setSendPastNotifications(boolean) - Method in class javax.management.timer.Timer

Sets the flag indicating whether the timer sends past notifications or not.

setSendPastNotifications(boolean) - Method in interface javax.management.timer.TimerMBean

Sets the flag indicating whether the timer sends past notifications or not.

setSeparatorSize(Dimension) - Method in class javax.swing.JToolBar.Separator

Sets the size of the separator.

setSequence(Sequence) - Method in interface javax.sound.midi.Sequencer

Sets the current sequence on which the sequencer operates.

setSequence(InputStream) - Method in interface javax.sound.midi.Sequencer

Sets the current sequence on which the sequencer operates.

setSequenceNumber(long) - Method in class java.util.logging.LogRecord

Set the sequence number.

setSequenceNumber(long) - Method in class javax.management.Notification

Set the notification sequence number.

setSerialNumber(BigInteger) - Method in class java.security.cert.X509CertSelector

Sets the serialNumber criterion.

setSessionCacheSize(int) - Method in interface javax.net.ssl.SSLSessionContext

Sets the size of the cache used for storing SSLSession objects grouped under this SSLSessionContext.

setSessionTimeout(int) - Method in interface javax.net.ssl.SSLSessionContext

Sets the timeout limit for SSLSession objects grouped under this SSLSessionContext.

setSeverity(int) - Method in class javax.xml.bind.helpers.ValidationEventImpl

Set the severity field of this event.

setShape(Shape) - Method in class java.awt.Dialog

Sets the shape of the window.

setShape(Shape) - Method in class java.awt.Frame

Sets the shape of the window.

setShape(Shape) - Method in class java.awt.Window

Sets the shape of the window.

setSharedInstance(PopupFactory) - Static method in class javax.swing.PopupFactory

Sets the PopupFactory that will be used to obtain Popups.

setShort(Object, int, short) - Static method in class java.lang.reflect.Array

Sets the value of the indexed component of the specified array object to the specified short value.

setShort(Object, short) - Method in class java.lang.reflect.字段

Sets the value of a field as a short on the specified object.

setShort(String, short) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given Java short value.

setShort(int, short) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given Java short value.

setShort(int, short) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given short in the Java programming language.

setShort(String, short) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given Java short value.

setShort(int, short) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command to the given Java short value.

setShort(String, short) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given Java short value.

setShortcut(MenuShortcut) - Method in class java.awt.MenuItem

Set the MenuShortcut object associated with this menu item.

setShortDescription(String) - Method in class java.beans.FeatureDescriptor

You can associate a short descriptive string with a feature.

setShortMonths(String[]) - Method in class java.text.DateFormatSymbols

Sets short month strings.

setShortWeekdays(String[]) - Method in class java.text.DateFormatSymbols

Sets short weekday strings.

setShowDeleted(boolean) - Method in class javax.sql.rowset.BaseRowSet

Sets the property showDeleted to the given boolean value, which determines whether rows marked for deletion appear in the set of current rows.

setShowDeleted(boolean) - Method in interface javax.sql.rowset.CachedRowSet

Sets the property showDeleted to the given boolean value, which determines whether rows marked for deletion appear in the set of current rows.

setShowDeleted(boolean) - Method in interface javax.sql.rowset.JdbcRowSet

Sets the property showDeleted to the given boolean value.

setShowDropLocation(boolean) - Method in class javax.swing.TransferHandler.TransferSupport

Sets whether or not the drop location should be visually indicated for the transfer - which must represent a drop.

setShowGrid(boolean) - Method in class javax.swing.JTable

Sets whether the table draws grid lines around cells.

setShowHorizontalLines(boolean) - Method in class javax.swing.JTable

Sets whether the table draws horizontal lines between cells.

setShowsRootHandles(boolean) - Method in class javax.swing.JTree

Sets the value of the showsRootHandles property, which specifies whether the node handles should be displayed.

setShowsRootHandles(boolean) - Method in class javax.swing.plaf.basic.BasicTreeUI

Determines whether the node handles are to be displayed.

setShowVerticalLines(boolean) - Method in class javax.swing.JTable

Sets whether the table draws vertical lines between cells.

setSides(JobAttributes.SidesType) - Method in class java.awt.JobAttributes

Specifies how consecutive pages should be imposed upon the sides of the print medium for jobs using these attributes.

setSidesToDefault() - Method in class java.awt.JobAttributes

Sets how consecutive pages should be imposed upon the sides of the print medium for jobs using these attributes to the default.

setSigned(int, boolean) - Method in class javax.sql.rowset.RowSetMetaDataImpl

Sets whether a value stored in the designated column is a signed number to the given boolean.

setSigned(int, boolean) - Method in interface javax.sql.RowSetMetaData

Sets whether the designated column is a signed number.

setSigners(Class<?>, Object[]) - Method in class java.lang.ClassLoader

Sets the signers of a class.

setSigProvider(String) - Method in class java.security.cert.PKIXParameters

Sets the signature provider's name.

setSize(Dimension) - Method in class java.awt.Component.AccessibleAWTComponent

Resizes this object so that it has width and height.

setSize(int, int) - Method in class java.awt.Component

Resizes this component so that it has width width and height height.

setSize(Dimension) - Method in class java.awt.Component

Resizes this component so that it has width d.width and height d.height.

setSize(double, double) - Method in class java.awt.Dimension

Sets the size of this Dimension object to the specified width and height in double precision.

setSize(Dimension) - Method in class java.awt.Dimension

Sets the size of this Dimension object to the specified size.

setSize(int, int) - Method in class java.awt.Dimension

Sets the size of this Dimension object to the specified width and height.

setSize(double, double) - Method in class java.awt.geom.Dimension2D

Sets the size of this Dimension object to the specified width and height.

setSize(Dimension2D) - Method in class java.awt.geom.Dimension2D

Sets the size of this Dimension2D object to match the specified size.

setSize(Dimension) - Method in class java.awt.List.AccessibleAWTList.AccessibleAWTListChild

Resizes this object so that it has width and height.

setSize(Dimension) - Method in class java.awt.MenuComponent.AccessibleAWTMenuComponent

Resizes this object.

setSize(double, double) - Method in class java.awt.print.Paper

Sets the width and height of this Paper object, which represents the properties of the page onto which printing occurs.

setSize(Dimension) - Method in class java.awt.Rectangle

Sets the size of this Rectangle to match the specified Dimension.

setSize(int, int) - Method in class java.awt.Rectangle

Sets the size of this Rectangle to the specified width and height.

setSize(Dimension) - Method in class java.awt.Window

Resizes this component so that it has width d.width and height d.height.

setSize(int, int) - Method in class java.awt.Window

Resizes this component so that it has width width and height height.

setSize(int) - Method in class java.util.Vector

Sets the size of this vector.

setSize(long) - Method in class java.util.zip.ZipEntry

Sets the uncompressed size of the entry data.

setSize(Dimension) - Method in interface javax.accessibility.AccessibleComponent

Resizes this object so that it has width and height.

setSize(int) - Method in class javax.swing.DefaultListModel

Sets the size of this list.

setSize(Dimension) - Method in class javax.swing.JList.AccessibleJList.AccessibleJListChild

setSize(Dimension) - Method in class javax.swing.JTable.AccessibleJTable.AccessibleJTableCell

setSize(Dimension) - Method in class javax.swing.JTree.AccessibleJTree.AccessibleJTreeNode

setSize(int, int) - Method in class javax.swing.SizeSequence

Sets the size of the specified entry.

setSize(Dimension) - Method in class javax.swing.table.JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry

setSize(float, float) - Method in class javax.swing.text.AsyncBoxView

Sets the size of the view.

setSize(float, float) - Method in class javax.swing.text.BoxView

Sets the size of the view.

setSize(float, float) - Method in class javax.swing.text.html.ImageView

Sets the size of the view.

setSize(float, float) - Method in class javax.swing.text.PlainView

Sets the size of the view.

setSize(float, float) - Method in class javax.swing.text.View

Sets the size of the view.

setSize(float, float) - Method in class javax.swing.text.WrappedPlainView

Sets the size of the view.

setSizes(int[]) - Method in class javax.swing.plaf.basic.BasicSplitPaneUI.BasicHorizontalLayoutManager

Sets the sizes to newSizes.

setSizes(int[]) - Method in class javax.swing.SizeSequence

Resets this SizeSequence object, using the data in the sizes argument.

setSlaveSyncMode(Sequencer.SyncMode) - Method in interface javax.sound.midi.Sequencer

Sets the slave synchronization mode for the sequencer.

setSnapToTicks(boolean) - Method in class javax.swing.JSlider

Specifying true makes the knob (and the data value it represents) resolve to the closest tick mark next to where the user positioned the knob.

setSocketAddress(SocketAddress) - Method in class java.net.DatagramPacket

Sets the SocketAddress (usually IP address + port number) of the remote host to which this datagram is being sent.

setSocketFactory(SocketImplFactory) - Static method in class java.net.ServerSocket

Sets the server socket implementation factory for the application.

setSocketFactory(RMISocketFactory) - Static method in class java.rmi.server.RMISocketFactory

Set the global socket factory from which RMI gets sockets (if the remote object is not associated with a specific client and/or server socket factory).

setSocketImplFactory(SocketImplFactory) - Static method in class java.net.Socket

Sets the client socket implementation factory for the application.

setSoLinger(boolean, int) - Method in class java.net.Socket

Enable/disable SO_LINGER with the specified linger time in seconds.

setSolo(boolean) - Method in interface javax.sound.midi.MidiChannel

Sets the solo state for this channel.

setSortable(int, boolean) - Method in class javax.swing.DefaultRowSorter

Sets whether or not the specified column is sortable.

setSortKeys(List<? extends RowSorter.SortKey>) - Method in class javax.swing.DefaultRowSorter

Sets the sort keys.

setSortKeys(List<? extends RowSorter.SortKey>) - Method in class javax.swing.RowSorter

Sets the current sort keys.

setSortsOnUpdates(boolean) - Method in class javax.swing.DefaultRowSorter

If true, specifies that a sort should happen when the underlying model is updated (rowsUpdated is invoked).

setSoTimeout(int) - Method in class java.net.DatagramSocket

Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds.

setSoTimeout(int) - Method in class java.net.ServerSocket

Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds.

setSoTimeout(int) - Method in class java.net.Socket

Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds.

setSource(Object) - Method in class java.awt.AWTEvent

Retargets an event to a new source.

setSource(Object, int) - Method in class java.awt.image.renderable.ParameterBlock

Replaces an entry in the list of source with a new source.

setSource(Object) - Method in class java.beans.PropertyEditorSupport

Sets the source bean.

setSource(Object) - Method in class javax.management.Notification

Sets the source.

setSourceActions(int) - Method in class java.awt.dnd.DragGestureRecognizer

This method sets the permitted source drag action(s) for this Drag and Drop operation.

setSourceBands(int[]) - Method in class javax.imageio.IIOParam

Sets the indices of the source bands to be used.

setSourceClassName(String) - Method in class java.util.logging.LogRecord

Set the name of the class that (allegedly) issued the logging request.

setSourceMethodName(String) - Method in class java.util.logging.LogRecord

Set the name of the method that (allegedly) issued the logging request.

setSourceProgressivePasses(int, int) - Method in class javax.imageio.ImageReadParam

Sets the range of progressive passes that will be decoded.

setSourceRegion(Rectangle) - Method in class javax.imageio.IIOParam

Sets the source region of interest.

setSourceRenderSize(Dimension) - Method in class javax.imageio.ImageReadParam

If the image is able to be rendered at an arbitrary size, sets the source width and height to the supplied values.

setSources(Vector<Object>) - Method in class java.awt.image.renderable.ParameterBlock

Sets the entire Vector of sources to a given Vector.

setSourceSubsampling(int, int, int, int) - Method in class javax.imageio.IIOParam

Specifies a decimation subsampling to apply on I/O.

setSouthPane(JComponent) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI

setSpaceAbove(MutableAttributeSet, float) - Static method in class javax.swing.text.StyleConstants

Sets space above.

setSpaceBelow(MutableAttributeSet, float) - Static method in class javax.swing.text.StyleConstants

Sets space below.

setSpecified(int, boolean) - Method in class org.xml.sax.ext.Attributes2Impl

Assign a value to the "specified" flag of a specific attribute.

setSQLXML(String, SQLXML) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given java.sql.SQLXML object.

setSQLXML(int, SQLXML) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given java.sql.SQLXML object.

setSQLXML(int, SQLXML) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.sql.SQLXML object.

setSQLXML(String, SQLXML) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.sql.SQLXML object.

setSQLXML(int, SQLXML) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given java.sql.SQLXML object.

setSQLXML(String, SQLXML) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given java.sql.SQLXML object.

setSSLParameters(SSLParameters) - Method in class javax.net.ssl.SSLEngine

Applies SSLParameters to this engine.

setSSLParameters(SSLParameters) - Method in class javax.net.ssl.SSLServerSocket

Applies SSLParameters to newly accepted connections.

setSSLParameters(SSLParameters) - Method in class javax.net.ssl.SSLSocket

Applies SSLParameters to this socket.

setSSLSocketFactory(SSLSocketFactory) - Method in class javax.net.ssl.HttpsURLConnection

Sets the SSLSocketFactory to be used when this instance creates sockets for secure https URL connections.

setStackTrace(StackTraceElement[]) - Method in class java.lang.Throwable

Sets the stack trace elements that will be returned by Throwable.getStackTrace() and printed by Throwable.printStackTrace() and related methods.

setStart(Comparable) - Method in class javax.swing.SpinnerDateModel

Changes the lower limit for Dates in this sequence.

setStartRule(int, int, int, int) - Method in class java.util.SimpleTimeZone

Sets the daylight saving time start rule.

setStartRule(int, int, int) - Method in class java.util.SimpleTimeZone

Sets the daylight saving time start rule to a fixed date within a month.

setStartRule(int, int, int, int, boolean) - Method in class java.util.SimpleTimeZone

Sets the daylight saving time start rule to a weekday before or after the given date within a month, e.g., the first Monday on or after the 8th.

setStartYear(int) - Method in class java.util.SimpleTimeZone

Sets the daylight saving time starting year.

setState(boolean) - Method in class java.awt.Checkbox

Sets the state of this check box to the specified state.

setState(boolean) - Method in class java.awt.CheckboxMenuItem

Sets this check box menu item to the specifed state.

setState(int) - Method in class java.awt.Frame

Sets the state of this frame (obsolete).

setState(long) - Method in class java.util.concurrent.locks.AbstractQueuedLongSynchronizer

Sets the value of synchronization state.

setState(int) - Method in class java.util.concurrent.locks.AbstractQueuedSynchronizer

Sets the value of synchronization state.

setState(boolean) - Method in class javax.swing.JCheckBoxMenuItem

Sets the selected-state of the item.

setStatus(int) - Method in class javax.xml.ws.spi.http.HttpExchange

Sets the HTTP status code for the response.

setStepSize(Number) - Method in class javax.swing.SpinnerNumberModel

Changes the size of the value change computed by the getNextValue and getPreviousValue methods.

setStrategy(int) - Method in class java.util.zip.Deflater

Sets the compression strategy to the specified value.

setStream(String, InputStream) - Method in interface java.applet.AppletContext

Associates the specified stream with the specified key in this applet context.

setStrength(int) - Method in class java.text.Collator

Sets this Collator's strength property.

setStrictErrorChecking(boolean) - Method in interface org.w3c.dom.Document

An attribute specifying whether error checking is enforced or not.

setStrikeThrough(boolean) - Method in class javax.swing.text.LabelView

Sets whether or not the view has a strike/line through it.

setStrikeThrough(MutableAttributeSet, boolean) - Static method in class javax.swing.text.StyleConstants

Sets the strikethrough attribute.

setString(String, String) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given Java String value.

setString(long, String) - Method in interface java.sql.Clob

Writes the given Java String to the CLOB value that this Clob object designates at the position pos.

setString(long, String, int, int) - Method in interface java.sql.Clob

Writes len characters of str, starting at character offset, to the CLOB value that this Clob represents.

setString(int, String) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given Java String value.

setString(String) - Method in interface java.sql.SQLXML

Sets the XML value designated by this SQLXML instance to the given String representation.

setString(int, String) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given String value.

setString(String, String) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given Java String value.

setString(long, String) - Method in class javax.sql.rowset.serial.SerialClob

Writes the given Java String to the CLOB value that this SerialClob object represents, at the position pos.

setString(long, String, int, int) - Method in class javax.sql.rowset.serial.SerialClob

Writes len characters of str, starting at character offset, to the CLOB value that this Clob represents.

setString(int, String) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command to the given Java String value.

setString(String, String) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given Java String value.

setString(String) - Method in class javax.swing.JProgressBar

Sets the value of the progress string.

setStringConverter(TableStringConverter) - Method in class javax.swing.table.TableRowSorter

Sets the object responsible for converting values from the model to strings.

setStringData(String) - Method in interface org.w3c.dom.ls.LSInput

String data to parse.

setStringPainted(boolean) - Method in class javax.swing.JProgressBar

Sets the value of the stringPainted property, which determines whether the progress bar should render a progress string.

setStringToCompare(String) - Method in class javax.management.monitor.StringMonitor

Sets the string to compare with the observed attribute common to all observed MBeans.

setStringToCompare(String) - Method in interface javax.management.monitor.StringMonitorMBean

Sets the string to compare with the observed attribute.

setStroke(Stroke) - Method in class java.awt.Graphics2D

Sets the Stroke for the Graphics2D context.

setStub(AppletStub) - Method in class java.applet.Applet

Sets this applet's stub.

setStyledDocument(StyledDocument) - Method in class javax.swing.JTextPane

Associates the editor with a text document.

setStyleFactory(SynthStyleFactory) - Static method in class javax.swing.plaf.synth.SynthLookAndFeel

Sets the SynthStyleFactory that the UI classes provided by synth will use to obtain a SynthStyle.

setStyleSheet(StyleSheet) - Method in class javax.swing.text.html.HTMLEditorKit

Set the set of styles to be used to render the various HTML elements.

setSubject(X500Principal) - Method in class java.security.cert.X509CertSelector

Sets the subject criterion.

setSubject(String) - Method in class java.security.cert.X509CertSelector

Denigrated, use X509CertSelector.setSubject(X500Principal) or X509CertSelector.setSubject(byte[]) instead.

setSubject(byte[]) - Method in class java.security.cert.X509CertSelector

Sets the subject criterion.

setSubjectAlternativeNames(Collection<List<?>>) - Method in class java.security.cert.X509CertSelector

Sets the subjectAlternativeNames criterion.

setSubjectKeyIdentifier(byte[]) - Method in class java.security.cert.X509CertSelector

Sets the subjectKeyIdentifier criterion.

setSubjectPublicKey(PublicKey) - Method in class java.security.cert.X509CertSelector

Sets the subjectPublicKey criterion.

setSubjectPublicKey(byte[]) - Method in class java.security.cert.X509CertSelector

Sets the subjectPublicKey criterion.

setSubjectPublicKeyAlgID(String) - Method in class java.security.cert.X509CertSelector

Sets the subjectPublicKeyAlgID criterion.

setSubscript(boolean) - Method in class javax.swing.text.LabelView

Sets whether or not the view represents a subscript.

setSubscript(MutableAttributeSet, boolean) - Static method in class javax.swing.text.StyleConstants

Sets the subscript attribute.

setSubType(String) - Method in class javax.activation.MimeType

Set the subtype for this object to the given String.

setSuperscript(boolean) - Method in class javax.swing.text.LabelView

Sets whether or not the view represents a superscript.

setSuperscript(MutableAttributeSet, boolean) - Static method in class javax.swing.text.StyleConstants

Sets the superscript attribute.

setSupplementaryStates(boolean, boolean, boolean, boolean, int, String) - Method in class org.ietf.jgss.MessageProp

This method sets the state for the supplementary information flags and the minor status in MessageProp.

setSurrendersFocusOnKeystroke(boolean) - Method in class javax.swing.JTable

Sets whether editors in this JTable get the keyboard focus when an editor is activated as a result of the JTable forwarding keyboard events for a cell.

setSyncAllWidths(boolean) - Method in class javax.swing.plaf.basic.BasicOptionPaneUI.ButtonAreaLayout

setSyncProvider(String) - Method in interface javax.sql.rowset.CachedRowSet

Sets the SyncProvider objec for this CachedRowSet object to the one specified.

setSyncResolver(SyncResolver) - Method in exception javax.sql.rowset.spi.SyncProviderException

Sets the SyncResolver object for this SyncProviderException object to the one supplied.

setSystem(boolean) - Method in interface java.nio.file.attribute.DosFileAttributeView

Updates the value of the system attribute.

setSystem(ActivationSystem) - Static method in class java.rmi.activation.ActivationGroup

Set the activation system for the VM.

setSystemId(String) - Method in class javax.xml.transform.dom.DOMResult

Set the systemId that may be used in association with the node.

setSystemId(String) - Method in class javax.xml.transform.dom.DOMSource

Set the base ID (URL or system ID) from where URLs will be resolved.

setSystemId(String) - Method in interface javax.xml.transform.Result

Set the system identifier for this Result.

setSystemId(String) - Method in class javax.xml.transform.sax.SAXResult

Method setSystemId Set the systemID that may be used in association with the ContentHandler.

setSystemId(String) - Method in class javax.xml.transform.sax.SAXSource

Set the system identifier for this Source.

setSystemId(String) - Method in interface javax.xml.transform.sax.TemplatesHandler

Set the base ID (URI or system ID) for the Templates object created by this builder.

setSystemId(String) - Method in interface javax.xml.transform.sax.TransformerHandler

Set the base ID (URI or system ID) from where relative URLs will be resolved.

setSystemId(String) - Method in interface javax.xml.transform.Source

Set the system identifier for this Source.

setSystemId(String) - Method in class javax.xml.transform.stax.StAXResult

In the context of a StAXResult, it is not appropriate to explicitly set the system identifier.

setSystemId(String) - Method in class javax.xml.transform.stax.StAXSource

In the context of a StAXSource, it is not appropriate to explicitly set the system identifier.

setSystemId(String) - Method in class javax.xml.transform.stream.StreamResult

Set the systemID that may be used in association with the byte or character stream, or, if neither is set, use this value as a writeable URI (probably a file name).

setSystemId(File) - Method in class javax.xml.transform.stream.StreamResult

Set the system ID from a File reference.

setSystemId(String) - Method in class javax.xml.transform.stream.StreamSource

Set the system identifier for this Source.

setSystemId(File) - Method in class javax.xml.transform.stream.StreamSource

Set the system ID from a File reference.

setSystemId(String) - Method in interface org.w3c.dom.ls.LSInput

The system identifier, a URI reference [IETF RFC 2396], for this input source.

setSystemId(String) - Method in interface org.w3c.dom.ls.LSOutput

The system identifier, a URI reference [IETF RFC 2396], for this output destination.

setSystemId(String) - Method in class org.xml.sax.helpers.LocatorImpl

Set the system identifier for this locator.

setSystemId(String) - Method in class org.xml.sax.InputSource

Set the system identifier for this input source.

setSystemScope(IdentityScope) - Static method in class java.security.IdentityScope

Deprecated.

Sets the system's identity scope.

setTabComponentAt(int, Component) - Method in class javax.swing.JTabbedPane

Sets the component that is responsible for rendering the title for the specified tab.

setTabLayoutPolicy(int) - Method in class javax.swing.JTabbedPane

Sets the policy which the tabbedpane will use in laying out the tabs when all the tabs will not fit within a single run.

setTable(JTable) - Method in class javax.swing.table.JTableHeader

Sets the table associated with this header.

setTableHeader(JTableHeader) - Method in class javax.swing.JTable

Sets the tableHeader working with this JTable to newHeader.

setTableName(String) - Method in interface javax.sql.rowset.CachedRowSet

Sets the identifier for the table from which this CachedRowSet object was derived to the given table name.

setTableName(int, String) - Method in class javax.sql.rowset.RowSetMetaDataImpl

Sets the name of the table from which the designated column was derived to the given table name.

setTableName(int, String) - Method in interface javax.sql.RowSetMetaData

Sets the designated column's table name, if any, to the given String.

setTabPlacement(int) - Method in class javax.swing.JTabbedPane

Sets the tab placement for this tabbedpane.

setTabSet(MutableAttributeSet, TabSet) - Static method in class javax.swing.text.StyleConstants

Sets the TabSet.

setTabSize(int) - Method in class javax.swing.JTextArea

Sets the number of characters to expand tabs to.

setTarget(MethodHandle) - Method in class java.lang.invoke.CallSite

Updates the target method of this call site, according to the behavior defined by this call site's specific class.

setTarget(MethodHandle) - Method in class java.lang.invoke.ConstantCallSite

Always throws an UnsupportedOperationException.

setTarget(MethodHandle) - Method in class java.lang.invoke.MutableCallSite

Updates the target method of this call site, as a normal variable.

setTarget(MethodHandle) - Method in class java.lang.invoke.VolatileCallSite

Updates the target method of this call site, as a volatile variable.

setTarget(Object) - Method in class javax.accessibility.AccessibleRelation

Sets the target object for this relation

setTarget(Object[]) - Method in class javax.accessibility.AccessibleRelation

Sets the target objects for this relation

setTarget(Remote) - Method in interface javax.rmi.CORBA.Tie

Called by Util.registerTarget(javax.rmi.CORBA.Tie, java.rmi.Remote) to set the target for this tie.

setTargetActions(int) - Method in class java.awt.dnd.DropTargetContext

This method sets the current actions acceptable to this DropTarget.

setTargetCertConstraints(CertSelector) - Method in class java.security.cert.PKIXParameters

Sets the required constraints on the target certificate.

setTcpNoDelay(boolean) - Method in class java.net.Socket

Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm).

setTempoFactor(float) - Method in interface javax.sound.midi.Sequencer

Scales the sequencer's actual playback tempo by the factor provided.

setTempoInBPM(float) - Method in interface javax.sound.midi.Sequencer

Sets the tempo in beats per minute.

setTempoInMPQ(float) - Method in interface javax.sound.midi.Sequencer

Sets the tempo in microseconds per quarter note.

setText(String) - Method in class java.awt.Label

Sets the text for this label to the specified text.

setText(String) - Method in class java.awt.TextComponent

Sets the text that is presented by this text component to be the specified text.

setText(String) - Method in class java.awt.TextField

Sets the text that is presented by this text component to be the specified text.

setText(String) - Method in class java.text.BreakIterator

Set a new text string to be scanned.

setText(CharacterIterator) - Method in class java.text.BreakIterator

Set a new text for scanning.

setText(String) - Method in class java.text.CollationElementIterator

Set a new string over which to iterate.

setText(CharacterIterator) - Method in class java.text.CollationElementIterator

Set a new string over which to iterate.

setText(String) - Method in class java.text.StringCharacterIterator

Reset this iterator to point to a new string.

setText(String) - Method in class javax.security.auth.callback.TextInputCallback

Set the retrieved text.

setText(String) - Method in class javax.swing.AbstractButton

Sets the button's text.

setText(String) - Method in class javax.swing.JEditorPane

Sets the text of this TextComponent to the specified content, which is expected to be in the format of the content type of this editor.

setText(String) - Method in class javax.swing.JLabel

Defines the single line of text this component will display.

setText(String) - Method in class javax.swing.text.JTextComponent

Sets the text of this TextComponent to the specified text.

setTextContent(String) - Method in class javax.imageio.metadata.IIOMetadataNode

This DOM Level 3 method is not supported for IIOMetadataNode and will throw a DOMException.

setTextContent(String) - Method in interface org.w3c.dom.Node

This attribute returns the text content of this node and its descendants.

setTextContents(String) - Method in interface javax.accessibility.AccessibleEditableText

Sets the text contents to the specified string.

setTextContents(String) - Method in class javax.swing.JSpinner.AccessibleJSpinner

Sets the text contents to the specified string.

setTextContents(String) - Method in class javax.swing.text.JTextComponent.AccessibleJTextComponent

Sets the text contents to the specified string.

setTextNonSelectionColor(Color) - Method in class javax.swing.tree.DefaultTreeCellRenderer

Sets the color the text is drawn with when the node isn't selected.

setTextSelectionColor(Color) - Method in class javax.swing.tree.DefaultTreeCellRenderer

Sets the color the text is drawn with when the node is selected.

setTextShiftOffset() - Method in class javax.swing.plaf.basic.BasicButtonUI

setThreadContentionMonitoringEnabled(boolean) - Method in interface java.lang.management.ThreadMXBean

Enables or disables thread contention monitoring.

setThreadCpuTimeEnabled(boolean) - Method in interface java.lang.management.ThreadMXBean

Enables or disables thread CPU time measurement.

setThreadFactory(ThreadFactory) - Method in class java.util.concurrent.ThreadPoolExecutor

Sets the thread factory used to create new threads.

setThreadID(int) - Method in class java.util.logging.LogRecord

Set an identifier for the thread where the message originated.

setThreshold(Number) - Method in class javax.management.monitor.CounterMonitor

Deprecated.
As of JMX 1.2, replaced by CounterMonitor.setInitThreshold(java.lang.Number)

setThreshold(Number) - Method in interface javax.management.monitor.CounterMonitorMBean

Deprecated.
As of JMX 1.2, replaced by CounterMonitorMBean.setInitThreshold(java.lang.Number)

setThresholds(Number, Number) - Method in class javax.management.monitor.GaugeMonitor

Sets the high and the low threshold values common to all observed MBeans.

setThresholds(Number, Number) - Method in interface javax.management.monitor.GaugeMonitorMBean

Sets the high and the low threshold values.

setThrown(Throwable) - Method in class java.util.logging.LogRecord

Set a throwable associated with the log event.

setThumbBounds(int, int, int, int) - Method in class javax.swing.plaf.basic.BasicScrollBarUI

Set the bounds of the thumb and force a repaint that includes the old thumbBounds and the new one.

setThumbBounds(int, int, int, int) - Method in class javax.swing.plaf.metal.MetalScrollBarUI

This is overridden only to increase the invalid area.

setThumbLocation(int, int) - Method in class javax.swing.plaf.basic.BasicSliderUI

setThumbLocation(int, int) - Method in class javax.swing.plaf.synth.SynthSliderUI

setThumbnails(List<? extends BufferedImage>) - Method in class javax.imageio.IIOImage

Sets the list of thumbnails to a new List of BufferedImages, or to null.

setThumbRollover(boolean) - Method in class javax.swing.plaf.basic.BasicScrollBarUI

Sets whether or not the mouse is currently over the thumb.

setThumbRollover(boolean) - Method in class javax.swing.plaf.synth.SynthScrollBarUI

setTick(long) - Method in class javax.sound.midi.MidiEvent

Sets the time-stamp for the event, in MIDI ticks

setTickPosition(long) - Method in interface javax.sound.midi.Sequencer

Sets the current sequencer position in MIDI ticks

setTiling(int, int, int, int) - Method in class javax.imageio.ImageWriteParam

Specifies that the image should be tiled in the output stream.

setTilingMode(int) - Method in class javax.imageio.ImageWriteParam

Determines whether the image will be tiled in the output stream and, if it will, how the tiling parameters will be determined.

setTime(String, Time) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given java.sql.Time value.

setTime(String, Time, Calendar) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given java.sql.Time value, using the given Calendar object.

setTime(long) - Method in class java.sql.Date

Sets an existing Date object using the given milliseconds time value.

setTime(int, Time) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given java.sql.Time value.

setTime(int, Time, Calendar) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given java.sql.Time value, using the given Calendar object.

setTime(long) - Method in class java.sql.Time

Sets a Time object using a milliseconds time value.

setTime(long) - Method in class java.sql.Timestamp

Sets this Timestamp object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.

setTime(Date) - Method in class java.util.Calendar

Sets this Calendar's time with the given Date.

setTime(long) - Method in class java.util.Date

Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.

setTime(long) - Method in class java.util.zip.ZipEntry

Sets the modification time of the entry.

setTime(int, Time) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.sql.Time value.

setTime(int, Time, Calendar) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.sql.Time object.

setTime(String, Time) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.sql.Time value.

setTime(String, Time, Calendar) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.sql.Time value, using the given Calendar object.

setTime(int, Time) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command to the given java.sql.Time value.

setTime(int, Time, Calendar) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command with the given java.sql.Time value.

setTime(String, Time) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given java.sql.Time value.

setTime(String, Time, Calendar) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given java.sql.Time value, using the given Calendar object.

setTime(int, int, int) - Method in class javax.xml.datatype.XMLGregorianCalendar

Set time as one unit.

setTime(int, int, int, BigDecimal) - Method in class javax.xml.datatype.XMLGregorianCalendar

Set time as one unit, including the optional infinite precision fractional seconds.

setTime(int, int, int, int) - Method in class javax.xml.datatype.XMLGregorianCalendar

Set time as one unit, including optional milliseconds.

setTimeInMillis(long) - Method in class java.util.Calendar

Sets this Calendar's current time from the given long value.

setTimeLimit(int) - Method in class javax.naming.directory.SearchControls

Sets the time limit of these SearchControls in milliseconds.

setTimes(FileTime, FileTime, FileTime) - Method in interface java.nio.file.attribute.BasicFileAttributeView

Updates any or all of the file's last modified time, last access time, and create time attributes.

setTimestamp(String, Timestamp) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given java.sql.Timestamp value.

setTimestamp(String, Timestamp, Calendar) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given java.sql.Timestamp value, using the given Calendar object.

setTimestamp(int, Timestamp) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given java.sql.Timestamp value.

setTimestamp(int, Timestamp, Calendar) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given java.sql.Timestamp value, using the given Calendar object.

setTimeStamp(long) - Method in class javax.management.Notification

Set the notification timestamp.

setTimestamp(int, Timestamp) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.sql.Timestamp value.

setTimestamp(int, Timestamp, Calendar) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.sql.Timestamp object.

setTimestamp(String, Timestamp) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.sql.Timestamp value.

setTimestamp(String, Timestamp, Calendar) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.sql.Timestamp value, using the given Calendar object.

setTimestamp(int, Timestamp) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command to the given java.sql.Timestamp value.

setTimestamp(String, Timestamp) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given java.sql.Timestamp value.

setTimestamp(int, Timestamp, Calendar) - Method in interface javax.sql.RowSet

Sets the designated parameter in this RowSet object's command with the given java.sql.Timestamp value.

setTimestamp(String, Timestamp, Calendar) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given java.sql.Timestamp value, using the given Calendar object.

setTimeToLive(int) - Method in class java.net.DatagramSocketImpl

Set the TTL (time-to-live) option.

setTimeToLive(int) - Method in class java.net.MulticastSocket

Set the default time-to-live for multicast packets sent out on this MulticastSocket in order to control the scope of the multicasts.

setTimeZone(TimeZone) - Method in class java.text.DateFormat

Sets the time zone for the calendar of this DateFormat object.

setTimeZone(TimeZone) - Method in class java.util.Calendar

Sets the time zone with the given time zone value.

setTimeZone(TimeZone) - Method in class java.util.GregorianCalendar

setTimezone(int) - Method in class javax.xml.datatype.XMLGregorianCalendar

Set the number of minutes in the timezone offset.

setTipText(String) - Method in class javax.swing.JToolTip

Sets the text to show when the tool tip is displayed.

setTitle(String) - Method in class java.awt.Dialog

Sets the title of the Dialog.

setTitle(String) - Method in class java.awt.Frame

Sets the title for this frame to the specified string.

setTitle(String) - Method in class javax.swing.border.TitledBorder

Sets the title of the titled border.

setTitle(String) - Method in class javax.swing.JInternalFrame

Sets the JInternalFrame title.

setTitleAt(int, String) - Method in class javax.swing.JTabbedPane

Sets the title at index to title which can be null.

setTitleColor(Color) - Method in class javax.swing.border.TitledBorder

Sets the title-color of the titled border.

setTitleFont(Font) - Method in class javax.swing.border.TitledBorder

Sets the title-font of the titled border.

setTitleJustification(int) - Method in class javax.swing.border.TitledBorder

Sets the title-justification of the titled border.

setTitlePosition(int) - Method in class javax.swing.border.TitledBorder

Sets the title-position of the titled border.

setToggleClickCount(int) - Method in class javax.swing.JTree

Sets the number of mouse clicks before a node will expand or close.

setToIdentity() - Method in class java.awt.geom.AffineTransform

Resets this transform to the Identity transform.

setTokenThreshold(int) - Method in class javax.swing.text.html.HTMLDocument

Sets the number of tokens to buffer before trying to update the documents element structure.

setToolTip(String) - Method in class java.awt.TrayIcon

Sets the tooltip string for this TrayIcon.

setToolTipText(String) - Method in class javax.swing.JComponent

Registers the text to display in a tool tip.

setToolTipTextAt(int, String) - Method in class javax.swing.JTabbedPane

Sets the tooltip text at index to toolTipText which can be null.

setToPage(int) - Method in class java.awt.JobAttributes

Specifies, for jobs using these attributes, the last page (inclusive) to be printed, if a range of pages is to be printed.

setTopComponent(Component) - Method in class javax.swing.JSplitPane

Sets the component above, or to the left of the divider.

setTopDown(boolean) - Method in class javax.imageio.plugins.bmp.BMPImageWriteParam

If set, the data will be written out in a top-down manner, the first scanline being written first.

setTopInset(float) - Method in class javax.swing.text.AsyncBoxView

Set the top part of the margin around the view.

setToQuadrantRotation(int) - Method in class java.awt.geom.AffineTransform

Sets this transform to a rotation transformation that rotates coordinates by the specified number of quadrants.

setToQuadrantRotation(int, double, double) - Method in class java.awt.geom.AffineTransform

Sets this transform to a translated rotation transformation that rotates coordinates by the specified number of quadrants around the specified anchor point.

setToRotation(double) - Method in class java.awt.geom.AffineTransform

Sets this transform to a rotation transformation.

setToRotation(double, double, double) - Method in class java.awt.geom.AffineTransform

Sets this transform to a translated rotation transformation.

setToRotation(double, double) - Method in class java.awt.geom.AffineTransform

Sets this transform to a rotation transformation that rotates coordinates according to a rotation vector.

setToRotation(double, double, double, double) - Method in class java.awt.geom.AffineTransform

Sets this transform to a rotation transformation that rotates coordinates around an anchor point according to a rotation vector.

setToScale(double, double) - Method in class java.awt.geom.AffineTransform

Sets this transform to a scaling transformation.

setToShear(double, double) - Method in class java.awt.geom.AffineTransform

Sets this transform to a shearing transformation.

setToTranslation(double, double) - Method in class java.awt.geom.AffineTransform

Sets this transform to a translation transformation.

setTrackMute(int, boolean) - Method in interface javax.sound.midi.Sequencer

Sets the mute state for a track.

setTrackSolo(int, boolean) - Method in interface javax.sound.midi.Sequencer

Sets the solo state for a track.

setTrafficClass(int) - Method in class java.net.DatagramSocket

Sets traffic class or type-of-service octet in the IP datagram header for datagrams sent from this DatagramSocket.

setTrafficClass(int) - Method in class java.net.Socket

Sets traffic class or type-of-service octet in the IP header for packets sent from this Socket.

setTransactionIsolation(int) - Method in interface java.sql.Connection

Attempts to change the transaction isolation level for this Connection object to the one given.

setTransactionIsolation(int) - Method in class javax.sql.rowset.BaseRowSet

Sets the transaction isolation property for this JDBC RowSet object to the given constant.

setTransactionIsolation(int) - Method in interface javax.sql.RowSet

Sets the transaction isolation level for this RowSet obejct.

setTransactionTimeout(int) - Method in interface javax.transaction.xa.XAResource

Sets the current transaction timeout value for this XAResource instance.

setTransferHandler(TransferHandler) - Method in class javax.swing.JApplet

Sets the transferHandler property, which is a mechanism to support transfer of data into this component.

setTransferHandler(TransferHandler) - Method in class javax.swing.JComponent

Sets the TransferHandler, which provides support for transfer of data into and out of this component via cut/copy/paste and drag and drop.

setTransferHandler(TransferHandler) - Method in class javax.swing.JDialog

Sets the transferHandler property, which is a mechanism to support transfer of data into this component.

setTransferHandler(TransferHandler) - Method in class javax.swing.JFrame

Sets the transferHandler property, which is a mechanism to support transfer of data into this component.

setTransferHandler(TransferHandler) - Method in class javax.swing.JWindow

Sets the transferHandler property, which is a mechanism to support transfer of data into this component.

setTransform(AffineTransform) - Method in class java.awt.geom.AffineTransform

Sets this transform to a copy of the transform in the specified AffineTransform object.

setTransform(double, double, double, double, double, double) - Method in class java.awt.geom.AffineTransform

Sets this transform to the matrix specified by the 6 double precision values.

setTransform(AffineTransform) - Method in class java.awt.Graphics2D

Overwrites the Transform in the Graphics2D context.

setTransform(AffineTransform) - Method in class java.awt.image.renderable.RenderContext

Sets the current user-to-device AffineTransform contained in the RenderContext to a given transform.

setTree(JTree) - Method in class javax.swing.tree.DefaultTreeCellEditor

Sets the tree currently editing for.

setTrustAnchors(Set<TrustAnchor>) - Method in class java.security.cert.PKIXParameters

Sets the Set of most-trusted CAs.

setTTL(byte) - Method in class java.net.DatagramSocketImpl

Deprecated.
use setTimeToLive instead.

setTTL(byte) - Method in class java.net.MulticastSocket

Deprecated.
use the setTimeToLive method instead, which uses int instead of byte as the type for ttl.

setType(Window.Type) - Method in class java.awt.Window

Sets the type of the window.

setType(AclEntryType) - Method in class java.nio.file.attribute.AclEntry.Builder

Sets the type component of this builder.

setType(int) - Method in class javax.sql.rowset.BaseRowSet

Sets the type for this RowSet object to the specified type.

setType(int) - Method in interface javax.sql.RowSet

Sets the type of this RowSet object to the given type.

setType(short) - Method in class javax.swing.text.DefaultStyledDocument.ElementSpec

Sets the element type.

setType(int, String) - Method in class org.xml.sax.helpers.AttributesImpl

Set the type of a specific attribute.

setTypeMap(Map<String, Class<?>>) - Method in interface java.sql.Connection

Installs the given TypeMap object as the type map for this Connection object.

setTypeMap(Map<String, Class<?>>) - Method in class javax.sql.rowset.BaseRowSet

Installs the given java.util.Map object as the type map associated with the Connection object for this RowSet object.

setTypeMap(Map<String, Class<?>>) - Method in interface javax.sql.RowSet

Installs the given java.util.Map object as the default type map for this RowSet object.

setUI(ButtonUI) - Method in class javax.swing.AbstractButton

Sets the L&F object that renders this component.

setUI(ColorChooserUI) - Method in class javax.swing.JColorChooser

Sets the L&F object that renders this component.

setUI(ComboBoxUI) - Method in class javax.swing.JComboBox

Sets the L&F object that renders this component.

setUI(ComponentUI) - Method in class javax.swing.JComponent

Sets the look and feel delegate for this component.

setUI(DesktopPaneUI) - Method in class javax.swing.JDesktopPane

Sets the L&F object that renders this component.

setUI(DesktopIconUI) - Method in class javax.swing.JInternalFrame.JDesktopIcon

Sets the look-and-feel object that renders this component.

setUI(InternalFrameUI) - Method in class javax.swing.JInternalFrame

Sets the UI delegate for this JInternalFrame.

setUI(LabelUI) - Method in class javax.swing.JLabel

Sets the L&F object that renders this component.

setUI(LayerUI<? super V>) - Method in class javax.swing.JLayer

Sets the LayerUI which will perform painting and receive input events for this JLayer.

setUI(ListUI) - Method in class javax.swing.JList

Sets the ListUI, the look and feel object that renders this component.

setUI(MenuBarUI) - Method in class javax.swing.JMenuBar

Sets the L&F object that renders this component.

setUI(MenuItemUI) - Method in class javax.swing.JMenuItem

Sets the look and feel object that renders this component.

setUI(OptionPaneUI) - Method in class javax.swing.JOptionPane

Sets the UI object which implements the L&F for this component.

setUI(PanelUI) - Method in class javax.swing.JPanel

Sets the look and feel (L&F) object that renders this component.

setUI(PopupMenuUI) - Method in class javax.swing.JPopupMenu

Sets the L&F object that renders this component.

setUI(ProgressBarUI) - Method in class javax.swing.JProgressBar

Sets the look-and-feel object that renders this component.

setUI(RootPaneUI) - Method in class javax.swing.JRootPane

Sets the L&F object that renders this component.

setUI(ScrollBarUI) - Method in class javax.swing.JScrollBar

Sets the L&F object that renders this component.

setUI(ScrollPaneUI) - Method in class javax.swing.JScrollPane

Sets the ScrollPaneUI object that provides the look and feel (L&F) for this component.

setUI(SeparatorUI) - Method in class javax.swing.JSeparator

Sets the L&F object that renders this component.

setUI(SliderUI) - Method in class javax.swing.JSlider

Sets the UI object which implements the L&F for this component.

setUI(SpinnerUI) - Method in class javax.swing.JSpinner

Sets the look and feel (L&F) object that renders this component.

setUI(SplitPaneUI) - Method in class javax.swing.JSplitPane

Sets the L&F object that renders this component.

setUI(TabbedPaneUI) - Method in class javax.swing.JTabbedPane

Sets the UI object which implements the L&F for this component.

setUI(TableUI) - Method in class javax.swing.JTable

Sets the L&F object that renders this component and repaints.

setUI(ToolBarUI) - Method in class javax.swing.JToolBar

Sets the L&F object that renders this component.

setUI(TreeUI) - Method in class javax.swing.JTree

Sets the L&F object that renders this component.

setUI(ViewportUI) - Method in class javax.swing.JViewport

Sets the L&F object that renders this component.

setUI(TableHeaderUI) - Method in class javax.swing.table.JTableHeader

Sets the look and feel (L&F) object that renders this component.

setUI(TextUI) - Method in class javax.swing.text.JTextComponent

Sets the user-interface factory for this text-oriented editor.

setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler) - Method in class java.lang.Thread

Set the handler invoked when this thread abruptly terminates due to an uncaught exception.

setUndecorated(boolean) - Method in class java.awt.Dialog

Disables or enables decorations for this dialog.

setUndecorated(boolean) - Method in class java.awt.Frame

Disables or enables decorations for this frame.

setUnderline(boolean) - Method in class javax.swing.text.LabelView

Sets whether or not the view is underlined.

setUnderline(MutableAttributeSet, boolean) - Static method in class javax.swing.text.StyleConstants

Sets the underline attribute.

setUnexecutedModifications(ModificationItem[]) - Method in exception javax.naming.directory.AttributeModificationException

Sets the unexecuted modification list to be e.

setUnicast(boolean) - Method in class java.beans.EventSetDescriptor

Mark an event set as unicast (or not).

setUnicodeLocaleKeyword(String, String) - Method in class java.util.Locale.Builder

Sets the Unicode locale keyword type for the given key.

setUnicodeStream(int, InputStream, int) - Method in interface java.sql.PreparedStatement

Deprecated.

setUnicodeStream(int, InputStream, int) - Method in class javax.sql.rowset.BaseRowSet

Deprecated.
getCharacterStream should be used in its place

setUnitIncrement(int) - Method in interface java.awt.Adjustable

Sets the unit value increment for the adjustable object.

setUnitIncrement(int) - Method in class java.awt.Scrollbar

Sets the unit increment for this scroll bar.

setUnitIncrement(int) - Method in class java.awt.ScrollPaneAdjustable

setUnitIncrement(int) - Method in class javax.swing.JScrollBar

Sets the unitIncrement property.

setUnitIncrement(int) - Method in class javax.swing.JScrollPane.ScrollBar

Messages super to set the value, and resets the unitIncrementSet instance variable to true.

setup(FileSystemView) - Method in class javax.swing.JFileChooser

Performs common constructor initialization and setup.

setUpdatePolicy(int) - Method in class javax.swing.text.DefaultCaret

Sets the caret movement policy on the document updates.

setUpdateRect(Rectangle) - Method in class java.awt.event.PaintEvent

Sets the rectangle representing the area which needs to be repainted in response to this event.

setUpdateSelectionOnSort(boolean) - Method in class javax.swing.JTable

Specifies whether the selection should be updated after sorting.

setUpdateTableInRealTime(boolean) - Method in class javax.swing.table.JTableHeader

Obsolete as of Java 2 platform v1.3.

setupMenuCloseKey() - Method in class javax.swing.plaf.basic.BasicInternalFrameUI

setupMenuOpenKey() - Method in class javax.swing.plaf.basic.BasicInternalFrameUI

setupPostTimer(JMenu) - Method in class javax.swing.plaf.basic.BasicMenuUI

setURI(int, String) - Method in class org.xml.sax.helpers.AttributesImpl

Set the Namespace URI of a specific attribute.

setURIDereferencer(URIDereferencer) - Method in class javax.xml.crypto.dom.DOMCryptoContext

setURIDereferencer(URIDereferencer) - Method in interface javax.xml.crypto.XMLCryptoContext

Sets a URIDereferencer that is used to dereference URIReferences.

setURIResolver(URIResolver) - Method in class javax.xml.transform.Transformer

Set an object that will be used to resolve URIs used in document().

setURIResolver(URIResolver) - Method in class javax.xml.transform.TransformerFactory

Set an object that is used by default during the transformation to resolve URIs used in document(), xsl:import, or xsl:include.

setURL(URL, String, String, int, String, String, String, String, String) - Method in class java.net.URLStreamHandler

Sets the fields of the URL argument to the indicated values.

setURL(URL, String, String, int, String, String) - Method in class java.net.URLStreamHandler

Deprecated.
Use setURL(URL, String, String, int, String, String, String, String);

setURL(String, URL) - Method in interface java.sql.CallableStatement

Sets the designated parameter to the given java.net.URL object.

setURL(int, URL) - Method in interface java.sql.PreparedStatement

Sets the designated parameter to the given java.net.URL value.

setUrl(String) - Method in class javax.sql.rowset.BaseRowSet

Sets the Url property for this RowSet object to the given String object and sets the dataSource name property to null.

setURL(int, URL) - Method in class javax.sql.rowset.BaseRowSet

Sets the designated parameter to the given java.net.URL value.

setUrl(String) - Method in interface javax.sql.RowSet

Sets the URL this RowSet object will use when it uses the DriverManager to create a connection.

setURL(int, URL) - Method in interface javax.sql.RowSet

Sets the designated parameter to the given java.net.URL value.

setURL(URL) - Method in class javax.xml.bind.helpers.ValidationEventLocatorImpl

Set the URL field on this event locator.

setURLStreamHandlerFactory(URLStreamHandlerFactory) - Static method in class java.net.URL

Sets an application's URLStreamHandlerFactory.

setUsageThreshold(long) - Method in interface java.lang.management.MemoryPoolMXBean

Sets the threshold of this memory pool to the given threshold value if this memory pool supports the usage threshold.

setUseCache(boolean) - Static method in class javax.imageio.ImageIO

Sets a flag indicating whether a disk-based cache file should be used when creating ImageInputStreams and ImageOutputStreams.

setUseCaches(boolean) - Method in class java.net.URLConnection

Sets the value of the useCaches field of this URLConnection to the specified value.

setUseClientMode(boolean) - Method in class javax.net.ssl.SSLEngine

Configures the engine to use client (or server) mode when handshaking.

setUseClientMode(boolean) - Method in class javax.net.ssl.SSLServerSocket

Controls whether accepted connections are in the (default) SSL server mode, or the SSL client mode.

setUseClientMode(boolean) - Method in class javax.net.ssl.SSLSocket

Configures the socket to use client (or server) mode when handshaking.

setUseParentHandlers(boolean) - Method in class java.util.logging.Logger

Specify whether or not this logger should send its output to its parent Logger.

setUserData(String, Object, UserDataHandler) - Method in class javax.imageio.metadata.IIOMetadataNode

This DOM Level 3 method is not supported for IIOMetadataNode and will throw a DOMException.

setUserData(Object) - Method in class javax.management.Notification

Set the user data.

setUserData(String, Object, UserDataHandler) - Method in interface org.w3c.dom.Node

Associate an object to a key on this node.

setUsername(String) - Method in class javax.sql.rowset.BaseRowSet

Sets the username property for this RowSet object to the given user name.

setUsername(String) - Method in interface javax.sql.RowSet

Sets the username property for this RowSet object to the given String.

setUserObject(Object) - Method in class javax.imageio.metadata.IIOMetadataNode

Sets the value associated with this node.

setUserObject(Object) - Method in class javax.swing.tree.DefaultMutableTreeNode

Sets the user object for this node to userObject.

setUserObject(Object) - Method in interface javax.swing.tree.MutableTreeNode

Resets the user object of the receiver to object.

setValidating(boolean) - Method in class javax.xml.bind.helpers.AbstractUnmarshallerImpl

Specifies whether or not the Unmarshaller should validate during unmarshal operations.

setValidating(boolean) - Method in interface javax.xml.bind.Unmarshaller

Deprecated.
since JAXB2.0, please see Unmarshaller.setSchema(javax.xml.validation.Schema)

setValidating(boolean) - Method in class javax.xml.parsers.DocumentBuilderFactory

Specifies that the parser produced by this code will validate documents as they are parsed.

setValidating(boolean) - Method in class javax.xml.parsers.SAXParserFactory

Specifies that the parser produced by this code will validate documents as they are parsed.

setValidCharacters(String) - Method in class javax.swing.text.MaskFormatter

Allows for further restricting of the characters that can be input.

setValue(int) - Method in interface java.awt.Adjustable

Sets the current value of the adjustable object.

setValue(int) - Method in class java.awt.Scrollbar

Sets the value of this scroll bar to the specified value.

setValue(int) - Method in class java.awt.ScrollPaneAdjustable

Sets the value of this scrollbar to the specified value.

setValue(Object) - Method in class java.beans.Expression

Sets the value of this expression to value.

setValue(String, Object) - Method in class java.beans.FeatureDescriptor

Associate a named attribute with this feature.

setValue(Object) - Method in interface java.beans.PropertyEditor

Set (or change) the object that is to be edited.

setValue(Object) - Method in class java.beans.PropertyEditorSupport

Set (or change) the object that is to be edited.

setValue(String) - Method in class java.net.HttpCookie

Assigns a new value to a cookie after the cookie is created.

setValue(V) - Method in class java.util.AbstractMap.SimpleEntry

Replaces the value corresponding to this entry with the specified value.

setValue(V) - Method in class java.util.AbstractMap.SimpleImmutableEntry

Replaces the value corresponding to this entry with the specified value (optional operation).

setValue(V) - Method in interface java.util.Map.Entry

Replaces the value corresponding to this entry with the specified value (optional operation).

setValue(boolean) - Method in class javax.sound.sampled.BooleanControl

Sets the current value for the control.

setValue(Object) - Method in class javax.sound.sampled.EnumControl

Sets the current value for the control.

setValue(float) - Method in class javax.sound.sampled.FloatControl

Sets the current value for the control.

setValue(int) - Method in interface javax.swing.BoundedRangeModel

Sets the model's current value to newValue if newValue satisfies the model's constraints.

setValue(int) - Method in class javax.swing.DefaultBoundedRangeModel

Sets the current value of the model.

setValue(Object) - Method in class javax.swing.DefaultCellEditor.EditorDelegate

Sets the value of this cell.

setValue(Object) - Method in class javax.swing.JFormattedTextField

Sets the value that will be formatted by an AbstractFormatter obtained from the current AbstractFormatterFactory.

setValue(Object) - Method in class javax.swing.JOptionPane

Sets the value the user has chosen.

setValue(int) - Method in class javax.swing.JProgressBar

Sets the progress bar's current value to n.

setValue(int) - Method in class javax.swing.JScrollBar

Sets the scrollbar's value.

setValue(int) - Method in class javax.swing.JSlider

Sets the slider's current value to n.

setValue(Object) - Method in class javax.swing.JSpinner

Changes current value of the model, typically this value is displayed by the editor.

setValue(Object, boolean) - Method in interface javax.swing.Renderer

Specifies the value to display and whether or not the value should be portrayed as "currently selected".

setValue(Object) - Method in class javax.swing.SpinnerDateModel

Sets the current Date for this sequence.

setValue(Object) - Method in class javax.swing.SpinnerListModel

Changes the current element of the sequence and notifies ChangeListeners.

setValue(Object) - Method in interface javax.swing.SpinnerModel

Changes current value of the model, typically this value is displayed by the editor part of a JSpinner.

setValue(Object) - Method in class javax.swing.SpinnerNumberModel

Sets the current value for this sequence.

setValue(int) - Method in class javax.swing.Spring

Sets the current value of this Spring to value.

setValue(Object) - Method in class javax.swing.table.DefaultTableCellRenderer

Sets the String object for the cell being rendered to value.

setValue(T) - Method in class javax.xml.bind.JAXBElement

Set the content model and attributes of this xml element.

setValue(String) - Method in interface javax.xml.soap.Node

If this is a Text node then this method will set its value, otherwise it sets the value of the immediate (Text) child of this node.

setValue(String) - Method in interface org.w3c.dom.Attr

On retrieval, the value of the attribute is returned as a string.

setValue(int, String) - Method in class org.xml.sax.helpers.AttributesImpl

Set the value of a specific attribute.

setValueAt(Object, int, int) - Method in class javax.swing.JTable

Sets the value for the cell in the table model at row and column.

setValueAt(Object, int, int) - Method in class javax.swing.table.AbstractTableModel

This empty implementation is provided so users don't have to implement this method if their data model is not editable.

setValueAt(Object, int, int) - Method in class javax.swing.table.DefaultTableModel

Sets the object value for the cell at column and row.

setValueAt(Object, int, int) - Method in interface javax.swing.table.TableModel

Sets the value in the cell at columnIndex and rowIndex to aValue.

setValueClass(Class<?>) - Method in class javax.swing.text.DefaultFormatter

Sets that class that is used to create new Objects.

setValueContainsLiteralCharacters(boolean) - Method in class javax.swing.text.MaskFormatter

If true, the returned value and set value will also contain the literal characters in mask.

setValueIsAdjusting(boolean) - Method in class java.awt.Scrollbar

Sets the valueIsAdjusting property.

setValueIsAdjusting(boolean) - Method in class java.awt.ScrollPaneAdjustable

Sets the valueIsAdjusting property.

setValueIsAdjusting(boolean) - Method in interface javax.swing.BoundedRangeModel

This attribute indicates that any upcoming changes to the value of the model should be considered a single event.

setValueIsAdjusting(boolean) - Method in class javax.swing.DefaultBoundedRangeModel

Sets the valueIsAdjusting property.

setValueIsAdjusting(boolean) - Method in class javax.swing.DefaultListSelectionModel

Sets the valueIsAdjusting property, which indicates whether or not upcoming selection changes should be considered part of a single change.

setValueIsAdjusting(boolean) - Method in class javax.swing.JList

Sets the selection model's valueIsAdjusting property.

setValueIsAdjusting(boolean) - Method in class javax.swing.JScrollBar

Sets the model's valueIsAdjusting property.

setValueIsAdjusting(boolean) - Method in class javax.swing.JSlider

Sets the model's valueIsAdjusting property.

setValueIsAdjusting(boolean) - Method in interface javax.swing.ListSelectionModel

Sets the valueIsAdjusting property, which indicates whether or not upcoming selection changes should be considered part of a single change.

setValues(int, int, int, int) - Method in class java.awt.Scrollbar

Sets the values of four properties for this scroll bar: value, visibleAmount, minimum, and maximum.

setValues(int, int, int, int) - Method in class javax.swing.JScrollBar

Sets the four BoundedRangeModel properties after forcing the arguments to obey the usual constraints:

setVariant(String) - Method in class java.util.Locale.Builder

Sets the variant.

setVerbose(boolean) - Method in interface java.lang.management.ClassLoadingMXBean

Enables or disables the verbose output for the class loading system.

setVerbose(boolean) - Method in interface java.lang.management.MemoryMXBean

Enables or disables verbose output for the memory system.

setVerifyInputWhenFocusTarget(boolean) - Method in class javax.swing.JComponent

Sets the value to indicate whether input verifier for the current focus owner will be called before this component requests focus.

setVersion(int) - Method in class java.net.HttpCookie

Sets the version of the cookie protocol this cookie complies with.

setVerticalAlignment(int) - Method in class javax.swing.AbstractButton

Sets the vertical alignment of the icon and text.

setVerticalAlignment(int) - Method in class javax.swing.JLabel

Sets the alignment of the label's contents along the Y axis.

setVerticalGroup(GroupLayout.Group) - Method in class javax.swing.GroupLayout

Sets the Group that positions and sizes components along the vertical axis.

setVerticalScrollBar(JScrollBar) - Method in class javax.swing.JScrollPane

Adds the scrollbar that controls the viewports vertical view position to the scrollpane.

setVerticalScrollBarPolicy(int) - Method in class javax.swing.JScrollPane

Determines when the vertical scrollbar appears in the scrollpane.

setVerticalScrollBarPolicy(int) - Method in class javax.swing.ScrollPaneLayout

Sets the vertical scrollbar-display policy.

setVerticalTextPosition(int) - Method in class javax.swing.AbstractButton

Sets the vertical position of the text relative to the icon.

setVerticalTextPosition(int) - Method in class javax.swing.JLabel

Sets the vertical position of the label's text, relative to its image.

setVgap(int) - Method in class java.awt.BorderLayout

Sets the vertical gap between components.

setVgap(int) - Method in class java.awt.CardLayout

Sets the vertical gap between components.

setVgap(int) - Method in class java.awt.FlowLayout

Sets the vertical gap between components and between the components and the borders of the Container.

setVgap(int) - Method in class java.awt.GridLayout

Sets the vertical gap between components to the specified value.

setView(V) - Method in class javax.swing.JLayer

Sets the JLayer's view component, which can be null.

setView(Component) - Method in class javax.swing.JViewport

Sets the JViewport's one lightweight child (view), which can be null.

setView(View) - Method in class javax.swing.plaf.basic.BasicTextUI

Sets the current root of the view hierarchy and calls invalidate().

setViewport(JViewport) - Method in class javax.swing.JScrollPane

Removes the old viewport (if there is one); forces the viewPosition of the new viewport to be in the +x,+y quadrant; syncs up the row and column headers (if there are any) with the new viewport; and finally syncs the scrollbars and headers with the new viewport.

setViewportBorder(Border) - Method in class javax.swing.JScrollPane

Adds a border around the viewport.

setViewportView(Component) - Method in class javax.swing.JScrollPane

Creates a viewport if necessary and then sets its view.

setViewPosition(Point) - Method in class javax.swing.JViewport

Sets the view coordinates that appear in the upper left hand corner of the viewport, does nothing if there's no view.

setViewSize(Dimension) - Method in class javax.swing.JViewport

Sets the size of the view.

setVisible(boolean) - Method in class java.awt.Component.AccessibleAWTComponent

Sets the visible state of the object.

setVisible(boolean) - Method in class java.awt.Component

Shows or hides this component depending on the value of parameter b.

setVisible(boolean) - Method in class java.awt.Dialog

Shows or hides this Dialog depending on the value of parameter b.

setVisible(boolean) - Method in class java.awt.List.AccessibleAWTList.AccessibleAWTListChild

Set the visible state of the object.

setVisible(boolean) - Method in class java.awt.MenuComponent.AccessibleAWTMenuComponent

Sets the visible state of the object.

setVisible(boolean) - Method in class java.awt.Window

Shows or hides this Window depending on the value of parameter b.

setVisible(boolean) - Method in interface javax.accessibility.AccessibleComponent

Sets the visible state of the object.

setVisible(boolean) - Method in class javax.swing.JComponent

Makes the component visible or invisible.

setVisible(boolean) - Method in class javax.swing.JList.AccessibleJList.AccessibleJListChild

setVisible(boolean) - Method in class javax.swing.JPopupMenu

Sets the visibility of the popup menu.

setVisible(boolean) - Method in class javax.swing.JTable.AccessibleJTable.AccessibleJTableCell

Sets the visible state of the object.

setVisible(boolean) - Method in class javax.swing.JTree.AccessibleJTree.AccessibleJTreeNode

setVisible(boolean) - Method in class javax.swing.table.JTableHeader.AccessibleJTableHeader.AccessibleJTableHeaderEntry

setVisible(boolean) - Method in interface javax.swing.text.Caret

Sets the visibility of the caret.

setVisible(boolean) - Method in class javax.swing.text.DefaultCaret

Sets the caret visibility, and repaints the caret.

setVisibleAmount(int) - Method in interface java.awt.Adjustable

Sets the length of the proportional indicator of the adjustable object.

setVisibleAmount(int) - Method in class java.awt.Scrollbar

Sets the visible amount of this scroll bar.

setVisibleAmount(int) - Method in class java.awt.ScrollPaneAdjustable

This method should NOT be called by user code.

setVisibleAmount(int) - Method in class javax.swing.JScrollBar

Set the model's extent property.

setVisibleComponent(Component) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI

setVisibleRowCount(int) - Method in class javax.swing.JList

Sets the visibleRowCount property, which has different meanings depending on the layout orientation: For a VERTICAL layout orientation, this sets the preferred number of rows to display without requiring scrolling; for other orientations, it affects the wrapping of cells.

setVisibleRowCount(int) - Method in class javax.swing.JTree

Sets the number of rows that are to be displayed.

setWantClientAuth(boolean) - Method in class javax.net.ssl.SSLEngine

Configures the engine to request client authentication.

setWantClientAuth(boolean) - Method in class javax.net.ssl.SSLParameters

Sets whether client authentication should be requested.

setWantClientAuth(boolean) - Method in class javax.net.ssl.SSLServerSocket

Controls whether accepted server-mode SSLSockets will be initially configured to request client authentication.

setWantClientAuth(boolean) - Method in class javax.net.ssl.SSLSocket

Configures the socket to request client authentication.

setWantsInput(boolean) - Method in class javax.swing.JOptionPane

Sets the wantsInput property.

setWasIcon(JInternalFrame, Boolean) - Method in class javax.swing.DefaultDesktopManager

Sets that the component has been iconized and the bounds of the desktopIcon are valid.

setWeekDate(int, int, int) - Method in class java.util.Calendar

Sets the date of this Calendar with the the given date specifiers - week year, week of year, and day of week.

setWeekDate(int, int, int) - Method in class java.util.GregorianCalendar

Sets this GregorianCalendar to the date given by the date specifiers - weekYear, weekOfYear, and dayOfWeek.

setWeekdays(String[]) - Method in class java.text.DateFormatSymbols

Sets weekday strings.

setWestPane(JComponent) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI

setWheelScrollingEnabled(boolean) - Method in class java.awt.ScrollPane

Enables/disables scrolling in response to movement of the mouse wheel.

setWheelScrollingEnabled(boolean) - Method in class javax.swing.JScrollPane

Enables/disables scrolling in response to movement of the mouse wheel.

setWidth(Spring) - Method in class javax.swing.SpringLayout.Constraints

Sets the width property, which controls the width of a component.

setWidth(int) - Method in class javax.swing.table.TableColumn

This method should not be used to set the widths of columns in the JTable, use setPreferredWidth instead.

setWindingRule(int) - Method in class java.awt.geom.Path2D

Sets the winding rule for this path to the specified value.

setWindowDecorationStyle(int) - Method in class javax.swing.JRootPane

Sets the type of Window decorations (such as borders, widgets for closing a Window, title ...) the JRootPane should provide.

setWrapStyleWord(boolean) - Method in class javax.swing.JTextArea

Sets the style of wrapping used if the text area is wrapping lines.

setWritable(boolean, boolean) - Method in class java.io.File

Sets the owner's or everybody's write permission for this abstract pathname.

setWritable(boolean) - Method in class java.io.File

A convenience method to set the owner's write permission for this abstract pathname.

setWriteMethod(Method) - Method in class java.beans.PropertyDescriptor

Sets the method that should be used to write the property value.

setWriter(Writer) - Method in interface javax.script.ScriptContext

Sets the Writer for scripts to use when displaying output.

setWriter(Writer) - Method in class javax.script.SimpleScriptContext

Sets the Writer for scripts to use when displaying output.

setWriter(Writer) - Method in class javax.xml.transform.stream.StreamResult

Set the writer that is to receive the result.

setX(Spring) - Method in class javax.swing.SpringLayout.Constraints

Sets the x property, which controls the x value of a component's location.

setXIncludeAware(boolean) - Method in class javax.xml.parsers.DocumentBuilderFactory

Set state of XInclude processing.

setXIncludeAware(boolean) - Method in class javax.xml.parsers.SAXParserFactory

Set state of XInclude processing.

setXMLReader(XMLReader) - Method in class javax.xml.transform.sax.SAXSource

Set the XMLReader to be used for the Source.

setXMLReporter(XMLReporter) - Method in class javax.xml.stream.XMLInputFactory

The reporter that will be set on any XMLStreamReader or XMLEventReader created by this factory instance.

setXMLResolver(XMLResolver) - Method in class javax.xml.stream.XMLInputFactory

The resolver that will be set on any XMLStreamReader or XMLEventReader created by this factory instance.

setXmlStandalone(boolean) - Method in interface org.w3c.dom.Document

An attribute specifying, as part of the XML declaration, whether this document is standalone.

setXmlVersion(String) - Method in interface org.w3c.dom.Document

An attribute specifying, as part of the XML declaration, the version number of this document.

setXMLVersion(String) - Method in class org.xml.sax.ext.Locator2Impl

Assigns the current value of the version property.

setXORMode(Color) - Method in class java.awt.Graphics

Sets the paint mode of this graphics context to alternate between this graphics context's current color and the new specified color.

setXORMode(Color) - Method in class javax.swing.DebugGraphics

Overrides Graphics.setXORMode.

setXPathFunctionResolver(XPathFunctionResolver) - Method in interface javax.xml.xpath.XPath

Establish a function resolver.

setXPathFunctionResolver(XPathFunctionResolver) - Method in class javax.xml.xpath.XPathFactory

Establish a default function resolver.

setXPathVariableResolver(XPathVariableResolver) - Method in interface javax.xml.xpath.XPath

Establish a variable resolver.

setXPathVariableResolver(XPathVariableResolver) - Method in class javax.xml.xpath.XPathFactory

Establish a default variable resolver.

setY(Spring) - Method in class javax.swing.SpringLayout.Constraints

Sets the y property, which controls the y value of a component's location.

setYear(int) - Method in class java.sql.Time

Deprecated.

setYear(int) - Method in class java.util.Date

Deprecated.
As of JDK version 1.1, replaced by Calendar.set(Calendar.YEAR, year + 1900).

setYear(BigInteger) - Method in class javax.xml.datatype.XMLGregorianCalendar

Set low and high order component of XSD dateTime year field.

setYear(int) - Method in class javax.xml.datatype.XMLGregorianCalendar

Set year of XSD dateTime year field.

setZeroDigit(char) - Method in class java.text.DecimalFormatSymbols

Sets the character used for zero.

setZoneStrings(String[][]) - Method in class java.text.DateFormatSymbols

Sets time zone strings.

SEVERE - Static variable in class java.util.logging.Level

SEVERE is a message level indicating a serious failure.

severe(String) - Method in class java.util.logging.Logger

Log a SEVERE message.

Severity - Class in javax.print.attribute.standard

Class Severity is a printing attribute class, an enumeration, that denotes the severity of a PrinterStateReason attribute.

Severity(int) - Constructor for class javax.print.attribute.standard.Severity

Construct a new severity enumeration value with the given integer value.

SEVERITY_ERROR - Static variable in interface org.w3c.dom.DOMError

The severity of the error described by the DOMError is error.

SEVERITY_FATAL_ERROR - Static variable in interface org.w3c.dom.DOMError

The severity of the error described by the DOMError is fatal error.

SEVERITY_WARNING - Static variable in interface org.w3c.dom.DOMError

The severity of the error described by the DOMError is warning.

SHA1 - Static variable in class java.security.spec.MGF1ParameterSpec

The MGF1ParameterSpec which uses "SHA-1" message digest.

SHA1 - Static variable in interface javax.xml.crypto.dsig.DigestMethod

The SHA1 digest method algorithm URI.

SHA256 - Static variable in class java.security.spec.MGF1ParameterSpec

The MGF1ParameterSpec which uses "SHA-256" message digest.

SHA256 - Static variable in interface javax.xml.crypto.dsig.DigestMethod

The SHA256 digest method algorithm URI.

SHA384 - Static variable in class java.security.spec.MGF1ParameterSpec

The MGF1ParameterSpec which uses "SHA-384" message digest.

SHA512 - Static variable in class java.security.spec.MGF1ParameterSpec

The MGF1ParameterSpec which uses SHA-512 message digest.

SHA512 - Static variable in interface javax.xml.crypto.dsig.DigestMethod

The SHA512 digest method algorithm URI.

shadow - Variable in class javax.swing.border.EtchedBorder

shadow - Variable in class javax.swing.plaf.basic.BasicBorders.ButtonBorder

shadow - Variable in class javax.swing.plaf.basic.BasicBorders.FieldBorder

shadow - Variable in class javax.swing.plaf.basic.BasicBorders.SplitPaneBorder

shadow - Variable in class javax.swing.plaf.basic.BasicSeparatorUI

shadow - Variable in class javax.swing.plaf.basic.BasicTabbedPaneUI

shadowInner - Variable in class javax.swing.border.BevelBorder

shadowOuter - Variable in class javax.swing.border.BevelBorder

shallowClone() - Method in class java.awt.image.renderable.ParameterBlock

Creates a shallow copy of a ParameterBlock.

shape(char[], int, int) - Method in class java.awt.font.NumericShaper

Converts the digits in the text that occur between start and start + count.

shape(char[], int, int, int) - Method in class java.awt.font.NumericShaper

Converts the digits in the text that occur between start and start + count, using the provided context.

shape(char[], int, int, NumericShaper.Range) - Method in class java.awt.font.NumericShaper

Converts the digits in the text that occur between start and start + count, using the provided context.

Shape - Interface in java.awt

The Shape interface provides definitions for objects that represent some form of geometric shape.

SHAPE - Static variable in class javax.swing.text.html.HTML.Attribute

ShapeGraphicAttribute - Class in java.awt.font

The ShapeGraphicAttribute class is an implementation of GraphicAttribute that draws shapes in a TextLayout.

ShapeGraphicAttribute(Shape, int, boolean) - Constructor for class java.awt.font.ShapeGraphicAttribute

Constructs a ShapeGraphicAttribute for the specified Shape.

SHAPES - Static variable in class javax.swing.text.html.HTML.Attribute

sharedInstance - Static variable in class javax.swing.JTree.EmptySelectionModel

The single instance of EmptySelectionModel.

sharedInstance() - Static method in class javax.swing.JTree.EmptySelectionModel

Returns the single instance of EmptySelectionModel.

sharedInstance() - Static method in class javax.swing.ToolTipManager

Returns a shared ToolTipManager instance.

SHAVIAN - Static variable in class java.lang.Character.UnicodeBlock

Constant for the "Shavian" Unicode character block.

shear(double, double) - Method in class java.awt.geom.AffineTransform

Concatenates this transform with a shearing transformation.

shear(double, double) - Method in class java.awt.Graphics2D

Concatenates the current Graphics2D Transform with a shearing transform.

SheetCollate - Class in javax.print.attribute.standard

Class SheetCollate is a printing attribute class, an enumeration, that specifies whether or not the media sheets of each copy of each printed document in a job are to be in sequence, when multiple copies of the document are specified by the Copies attribute.

SheetCollate(int) - Constructor for class javax.print.attribute.standard.SheetCollate

Construct a new sheet collate enumeration value with the given integer value.

shift(float, float, int) - Method in class javax.sound.sampled.FloatControl

Changes the control value from the initial value to the final value linearly over the specified time period, specified in microseconds.

SHIFT_DOWN_MASK - Static variable in class java.awt.event.InputEvent

The Shift key extended modifier constant.

SHIFT_MASK - Static variable in class java.awt.event.ActionEvent

The shift modifier.

SHIFT_MASK - Static variable in class java.awt.event.InputEvent

The Shift key modifier constant.

SHIFT_MASK - Static variable in class java.awt.Event

This flag indicates that the Shift key was down when the event occurred.

shiftDown() - Method in class java.awt.Event

NOTE: The Event class is obsolete and is available only for backwards compatilibility.

shiftEnd(int) - Method in class javax.swing.text.GapContent

Make the gap bigger, moving any necessary data and updating the appropriate marks

shiftGap(int) - Method in class javax.swing.text.GapContent

Move the start of the gap to a new location, without changing the size of the gap.

shiftGapEndUp(int) - Method in class javax.swing.text.GapContent

Adjust the gap end upward.

shiftGapStartDown(int) - Method in class javax.swing.text.GapContent

Adjust the gap end downward.

shiftLeft(int) - Method in class java.math.BigInteger

Returns a BigInteger whose value is (this << n).

shiftRight(int) - Method in class java.math.BigInteger

Returns a BigInteger whose value is (this >> n).

Short - Class in java.lang

The Short class wraps a value of primitive type short in an object.

Short(short) - Constructor for class java.lang.Short

Constructs a newly allocated Short object that represents the specified short value.

Short(String) - Constructor for class java.lang.Short

Constructs a newly allocated Short object that represents the short value indicated by the String parameter.

SHORT - Static variable in class java.text.DateFormat

Constant for short style pattern.

SHORT - Static variable in class java.util.Calendar

A style specifier for getDisplayName and getDisplayNames indicating a short name, such as "Jan".

SHORT - Static variable in class java.util.TimeZone

A style specifier for getDisplayName() indicating a short name, such as "PST."

SHORT - Static variable in class javax.management.openmbean.SimpleType

The SimpleType instance describing values whose Java class name is java.lang.Short.

SHORT_DESCRIPTION - Static variable in interface javax.swing.Action

The key used for storing a short String description for the action, used for tooltip text.

ShortBuffer - Class in java.nio

A short buffer.

ShortBufferException - Exception in javax.crypto

This exception is thrown when an output buffer provided by the user is too short to hold the operation result.

ShortBufferException() - Constructor for exception javax.crypto.ShortBufferException

Constructs a ShortBufferException with no detail message.

ShortBufferException(String) - Constructor for exception javax.crypto.ShortBufferException

Constructs a ShortBufferException with the specified detail message.

shortcuts() - Method in class java.awt.MenuBar

Gets an enumeration of all menu shortcuts this menu bar is managing.

ShortHolder - Class in org.omg.CORBA

The Holder for Short.

ShortHolder() - Constructor for class org.omg.CORBA.ShortHolder

Constructs a new ShortHolder object with its value field initialized to 0.

ShortHolder(short) - Constructor for class org.omg.CORBA.ShortHolder

Constructs a new ShortHolder object with its value field initialized to the given short.

ShortLookupTable - Class in java.awt.image

This class defines a lookup table object.

ShortLookupTable(int, short[][]) - Constructor for class java.awt.image.ShortLookupTable

Constructs a ShortLookupTable object from an array of short arrays representing a lookup table for each band.

ShortLookupTable(int, short[]) - Constructor for class java.awt.image.ShortLookupTable

Constructs a ShortLookupTable object from an array of shorts representing a lookup table for each band.

ShortMessage - Class in javax.sound.midi

A ShortMessage contains a MIDI message that has at most two data bytes following its status byte.

ShortMessage() - Constructor for class javax.sound.midi.ShortMessage

Constructs a new ShortMessage.

ShortMessage(int) - Constructor for class javax.sound.midi.ShortMessage

Constructs a new ShortMessage which represents a MIDI message that takes no data bytes.

ShortMessage(int, int, int) - Constructor for class javax.sound.midi.ShortMessage

Constructs a new ShortMessage which represents a MIDI message that takes up to two data bytes.

ShortMessage(int, int, int, int) - Constructor for class javax.sound.midi.ShortMessage

Constructs a new ShortMessage which represents a channel MIDI message that takes up to two data bytes.

ShortMessage(byte[]) - Constructor for class javax.sound.midi.ShortMessage

Constructs a new ShortMessage.

ShortSeqHelper - Class in org.omg.CORBA

The Helper for ShortSeqHelper.

ShortSeqHelper() - Constructor for class org.omg.CORBA.ShortSeqHelper

ShortSeqHolder - Class in org.omg.CORBA

The Holder for ShortSeq.

ShortSeqHolder() - Constructor for class org.omg.CORBA.ShortSeqHolder

ShortSeqHolder(short[]) - Constructor for class org.omg.CORBA.ShortSeqHolder

shortValue() - Method in class java.lang.Byte

Returns the value of this Byte as a short.

shortValue() - Method in class java.lang.Double

Returns the value of this Double as a short (by casting to a short).

shortValue() - Method in class java.lang.Float

Returns the value of this Float as a short (by casting to a short).

shortValue() - Method in class java.lang.Integer

Returns the value of this Integer as a short.

shortValue() - Method in class java.lang.Long

Returns the value of this Long as a short.

shortValue() - Method in class java.lang.Number

Returns the value of the specified number as a short.

shortValue() - Method in class java.lang.Short

Returns the value of this Short as a short.

shortValueExact() - Method in class java.math.BigDecimal

Converts this BigDecimal to a short, checking for lost information.

shouldAccept(URI, HttpCookie) - Method in interface java.net.CookiePolicy

Will be called to see whether or not this cookie should be accepted.

shouldFillGap(int, int, int, int) - Method in class javax.swing.plaf.metal.MetalTabbedPaneUI

shouldPadTabRun(int, int) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI

shouldPadTabRun(int, int) - Method in class javax.swing.plaf.metal.MetalTabbedPaneUI

shouldPaintExpandControl(TreePath, int, boolean, boolean, boolean) - Method in class javax.swing.plaf.basic.BasicTreeUI

Returns true if the expand (toggle) control should be drawn for the specified row.

shouldRotateTabRuns(int) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI

shouldRotateTabRuns(int, int) - Method in class javax.swing.plaf.metal.MetalTabbedPaneUI

shouldScroll(int) - Method in class javax.swing.plaf.basic.BasicSliderUI.TrackListener

shouldSelectCell(EventObject) - Method in class javax.swing.AbstractCellEditor

Returns true.

shouldSelectCell(EventObject) - Method in interface javax.swing.CellEditor

Returns true if the editing cell should be selected, false otherwise.

shouldSelectCell(EventObject) - Method in class javax.swing.DefaultCellEditor.EditorDelegate

Returns true to indicate that the editing cell may be selected.

shouldSelectCell(EventObject) - Method in class javax.swing.DefaultCellEditor

Forwards the message from the CellEditor to the delegate.

shouldSelectCell(EventObject) - Method in class javax.swing.tree.DefaultTreeCellEditor

Messages the realEditor for the return value.

shouldStartEditingTimer(EventObject) - Method in class javax.swing.tree.DefaultTreeCellEditor

Returns true if event is a MouseEvent and the click count is 1.

shouldUpdateStyleOnAncestorChanged() - Method in class javax.swing.plaf.nimbus.NimbusLookAndFeel

shouldUpdateStyleOnAncestorChanged() - Method in class javax.swing.plaf.synth.SynthLookAndFeel

Returns whether or not the UIs should update their SynthStyles from the SynthStyleFactory when the ancestor of the JComponent changes.

shouldUpdateStyleOnEvent(PropertyChangeEvent) - Method in class javax.swing.plaf.nimbus.NimbusLookAndFeel

shouldUpdateStyleOnEvent(PropertyChangeEvent) - Method in class javax.swing.plaf.synth.SynthLookAndFeel

Returns whether or not the UIs should update their styles when a particular event occurs.

shouldYieldFocus(JComponent) - Method in class javax.swing.InputVerifier

Calls verify(input) to ensure that the input is valid.

show(Container, String) - Method in class java.awt.CardLayout

Flips to the component that was added to this layout with the specified name, using addLayoutComponent.

show() - Method in class java.awt.Component.BltBufferStrategy

Makes the next available buffer visible.

show() - Method in class java.awt.Component.FlipBufferStrategy

Makes the next available buffer visible by either blitting or flipping.

show() - Method in class java.awt.Component

Deprecated.
As of JDK version 1.1, replaced by setVisible(boolean).

show(boolean) - Method in class java.awt.Component

Deprecated.
As of JDK version 1.1, replaced by setVisible(boolean).

show() - Method in class java.awt.Dialog

Deprecated.
As of JDK version 1.5, replaced by setVisible(boolean).

show() - Method in class java.awt.image.BufferStrategy

Makes the next available buffer visible by either copying the memory (blitting) or changing the display pointer (flipping).

show(Component, int, int) - Method in class java.awt.PopupMenu

Shows the popup menu at the x, y position relative to an origin component.

show() - Method in class java.awt.Window

Deprecated.
As of JDK version 1.5, replaced by Window.setVisible(boolean).

show() - Method in class javax.swing.JInternalFrame

If the internal frame is not visible, brings the internal frame to the front, makes it visible, and attempts to select it.

show(Component, int, int) - Method in class javax.swing.JPopupMenu

Displays the popup menu at the position x,y in the coordinate space of the component invoker.

show() - Method in class javax.swing.plaf.basic.BasicComboPopup

Implementation of ComboPopup.show().

show() - Method in interface javax.swing.plaf.basic.ComboPopup

Shows the popup

show() - Method in class javax.swing.Popup

Makes the Popup visible.

showConfirmDialog(Component, Object) - Static method in class javax.swing.JOptionPane

Brings up a dialog with the options Yes, No and Cancel; with the title, Select an Option.

showConfirmDialog(Component, Object, String, int) - Static method in class javax.swing.JOptionPane

Brings up a dialog where the number of choices is determined by the optionType parameter.

showConfirmDialog(Component, Object, String, int, int) - Static method in class javax.swing.JOptionPane

Brings up a dialog where the number of choices is determined by the optionType parameter, where the messageType parameter determines the icon to display.

showConfirmDialog(Component, Object, String, int, int, Icon) - Static method in class javax.swing.JOptionPane

Brings up a dialog with a specified icon, where the number of choices is determined by the optionType parameter.

showDialog(Component, String, Color) - Static method in class javax.swing.JColorChooser

Shows a modal color-chooser dialog and blocks until the dialog is hidden.

showDialog(Component, String) - Method in class javax.swing.JFileChooser

Pops a custom file chooser dialog with a custom approve button.

showDocument(URL) - Method in interface java.applet.AppletContext

Requests that the browser or applet viewer show the Web page indicated by the url argument.

showDocument(URL, String) - Method in interface java.applet.AppletContext

Requests that the browser or applet viewer show the Web page indicated by the url argument.

showHorizontalLines - Variable in class javax.swing.JTable

The table draws horizontal lines between cells if showHorizontalLines is true.

SHOWING - Static variable in class javax.accessibility.AccessibleState

Indicates this object, the object's parent, the object's parent's parent, and so on, are all visible.

SHOWING_CHANGED - Static variable in class java.awt.event.HierarchyEvent

A change flag indicates that the HIERARCHY_CHANGED event was generated due to the changing of the hierarchy showing state.

showInputDialog(Object) - Static method in class javax.swing.JOptionPane

Shows a question-message dialog requesting input from the user.

showInputDialog(Object, Object) - Static method in class javax.swing.JOptionPane

Shows a question-message dialog requesting input from the user, with the input value initialized to initialSelectionValue.

showInputDialog(Component, Object) - Static method in class javax.swing.JOptionPane

Shows a question-message dialog requesting input from the user parented to parentComponent.

showInputDialog(Component, Object, Object) - Static method in class javax.swing.JOptionPane

Shows a question-message dialog requesting input from the user and parented to parentComponent.

showInputDialog(Component, Object, String, int) - Static method in class javax.swing.JOptionPane

Shows a dialog requesting input from the user parented to parentComponent with the dialog having the title title and message type messageType.

showInputDialog(Component, Object, String, int, Icon, Object[], Object) - Static method in class javax.swing.JOptionPane

Prompts the user for input in a blocking dialog where the initial selection, possible selections, and all other options can be specified.

showInternalConfirmDialog(Component, Object) - Static method in class javax.swing.JOptionPane

Brings up an internal dialog panel with the options Yes, No and Cancel; with the title, Select an Option.

showInternalConfirmDialog(Component, Object, String, int) - Static method in class javax.swing.JOptionPane

Brings up a internal dialog panel where the number of choices is determined by the optionType parameter.

showInternalConfirmDialog(Component, Object, String, int, int) - Static method in class javax.swing.JOptionPane

Brings up an internal dialog panel where the number of choices is determined by the optionType parameter, where the messageType parameter determines the icon to display.

showInternalConfirmDialog(Component, Object, String, int, int, Icon) - Static method in class javax.swing.JOptionPane

Brings up an internal dialog panel with a specified icon, where the number of choices is determined by the optionType parameter.

showInternalInputDialog(Component, Object) - Static method in class javax.swing.JOptionPane

Shows an internal question-message dialog requesting input from the user parented to parentComponent.

showInternalInputDialog(Component, Object, String, int) - Static method in class javax.swing.JOptionPane

Shows an internal dialog requesting input from the user parented to parentComponent with the dialog having the title title and message type messageType.

showInternalInputDialog(Component, Object, String, int, Icon, Object[], Object) - Static method in class javax.swing.JOptionPane

Prompts the user for input in a blocking internal dialog where the initial selection, possible selections, and all other options can be specified.

showInternalMessageDialog(Component, Object) - Static method in class javax.swing.JOptionPane

Brings up an internal confirmation dialog panel.

showInternalMessageDialog(Component, Object, String, int) - Static method in class javax.swing.JOptionPane

Brings up an internal dialog panel that displays a message using a default icon determined by the messageType parameter.

showInternalMessageDialog(Component, Object, String, int, Icon) - Static method in class javax.swing.JOptionPane

Brings up an internal dialog panel displaying a message, specifying all parameters.

showInternalOptionDialog(Component, Object, String, int, int, Icon, Object[], Object) - Static method in class javax.swing.JOptionPane

Brings up an internal dialog panel with a specified icon, where the initial choice is determined by the initialValue parameter and the number of choices is determined by the optionType parameter.

showMessageDialog(Component, Object) - Static method in class javax.swing.JOptionPane

Brings up an information-message dialog titled "Message".

showMessageDialog(Component, Object, String, int) - Static method in class javax.swing.JOptionPane

Brings up a dialog that displays a message using a default icon determined by the messageType parameter.

showMessageDialog(Component, Object, String, int, Icon) - Static method in class javax.swing.JOptionPane

Brings up a dialog displaying a message, specifying all parameters.

showOpenDialog(Component) - Method in class javax.swing.JFileChooser

Pops up an "Open File" file chooser dialog.

showOptionDialog(Component, Object, String, int, int, Icon, Object[], Object) - Static method in class javax.swing.JOptionPane

Brings up a dialog with a specified icon, where the initial choice is determined by the initialValue parameter and the number of choices is determined by the optionType parameter.

showPopup() - Method in class javax.swing.JComboBox

Causes the combo box to display its popup window.

SHOWS_ROOT_HANDLES_PROPERTY - Static variable in class javax.swing.JTree

Bound property name for showsRootHandles.

showSaveDialog(Component) - Method in class javax.swing.JFileChooser

Pops up a "Save File" file chooser dialog.

showsRootHandles - Variable in class javax.swing.JTree

True if handles are displayed at the topmost level of the tree.

showStatus(String) - Method in class java.applet.Applet

Requests that the argument string be displayed in the "status window".

showStatus(String) - Method in interface java.applet.AppletContext

Requests that the argument string be displayed in the "status window".

showSystemMenu() - Method in class javax.swing.plaf.basic.BasicInternalFrameTitlePane

showSystemMenu() - Method in class javax.swing.plaf.metal.MetalInternalFrameTitlePane

Override the parent's method to do nothing.

showVerticalLines - Variable in class javax.swing.JTable

The table draws vertical lines between cells if showVerticalLines is true.

shrinkAbsorb - Variable in class java.awt.font.GlyphJustificationInfo

If true,this glyph absorbs all remaining shrinkage at this and lower priority levels as it shrinks.

shrinkLeftLimit - Variable in class java.awt.font.GlyphJustificationInfo

The maximum amount by which the left side of this glyph can shrink (a positive number).

shrinkPriority - Variable in class java.awt.font.GlyphJustificationInfo

The priority level of this glyph as it is shrinking.

shrinkRightLimit - Variable in class java.awt.font.GlyphJustificationInfo

The maximum amount by which the right side of this glyph can shrink (a positive number).

shuffle(List<?>) - Static method in class java.util.Collections

Randomly permutes the specified list using a default source of randomness.

shuffle(List<?>, Random) - Static method in class java.util.Collections

Randomly permute the specified list using the specified source of randomness.

shutdown() - Method in class java.nio.channels.AsynchronousChannelGroup

Initiates an orderly shutdown of the group.

shutdown() - Method in interface java.rmi.activation.ActivationSystem

Shutdown the activation system.

shutdown() - Method in interface java.util.concurrent.ExecutorService

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

shutdown() - Method in class java.util.concurrent.ForkJoinPool

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

shutdown() - Method in class java.util.concurrent.ScheduledThreadPoolExecutor

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

shutdown() - Method in class java.util.concurrent.ThreadPoolExecutor

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

SHUTDOWN - Static variable in class javax.print.attribute.standard.PrinterStateReason

Someone has removed a printer from service, and the device may be powered down or physically removed.

shutdown(boolean) - Method in class org.omg.CORBA.ORB

Instructs the ORB to shut down, which causes all object adapters to shut down, in preparation for destruction.
If the wait_for_completion parameter is true, this operation blocks until all ORB processing (including processing of currently executing requests, object deactivation, and other object adapter operations) has completed.

ShutdownChannelGroupException - Exception in java.nio.channels

Unchecked exception thrown when an attempt is made to construct a channel in a group that is shutdown or the completion handler for an I/O operation cannot be invoked because the channel group has terminated.

ShutdownChannelGroupException() - Constructor for exception java.nio.channels.ShutdownChannelGroupException

Constructs an instance of this class.

shutdownInput() - Method in class java.net.Socket

Places the input stream for this socket at "end of stream".

shutdownInput() - Method in class java.net.SocketImpl

Places the input stream for this socket at "end of stream".

shutdownInput() - Method in class java.nio.channels.AsynchronousSocketChannel

Shutdown the connection for reading without closing the channel.

shutdownInput() - Method in class java.nio.channels.SocketChannel

Shutdown the connection for reading without closing the channel.

shutdownNow() - Method in class java.nio.channels.AsynchronousChannelGroup

Shuts down the group and closes all open channels in the group.

shutdownNow() - Method in interface java.util.concurrent.ExecutorService

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

shutdownNow() - Method in class java.util.concurrent.ForkJoinPool

Attempts to cancel and/or stop all tasks, and reject all subsequently submitted tasks.

shutdownNow() - Method in class java.util.concurrent.ScheduledThreadPoolExecutor

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

shutdownNow() - Method in class java.util.concurrent.ThreadPoolExecutor

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

shutdownOutput() - Method in class java.net.Socket

Disables the output stream for this socket.

shutdownOutput() - Method in class java.net.SocketImpl

Disables the output stream for this socket.

shutdownOutput() - Method in class java.nio.channels.AsynchronousSocketChannel

Shutdown the connection for writing without closing the channel.

shutdownOutput() - Method in class java.nio.channels.SocketChannel

Shutdown the connection for writing without closing the channel.

SIDE - Static variable in class javax.print.attribute.standard.MediaTray

The side input tray.

Sides - Class in javax.print.attribute.standard

Class Sides is a printing attribute class, an enumeration, that specifies how print-stream pages are to be imposed upon the sides of an instance of a selected medium, i.e., an impression.

Sides(int) - Constructor for class javax.print.attribute.standard.Sides

Construct a new sides enumeration value with the given integer value.

SIGN - Static variable in class java.security.Signature

Possible Signature.state value, signifying that this signature object has been initialized for signing.

sign() - Method in class java.security.Signature

Returns the signature bytes of all the data updated.

sign(byte[], int, int) - Method in class java.security.Signature

Finishes the signature operation and stores the resulting signature bytes in the provided buffer outbuf, starting at offset.

SIGN - Static variable in class java.text.NumberFormat.Field

Constant identifying the sign field.

sign(XMLSignContext) - Method in interface javax.xml.crypto.dsig.XMLSignature

Signs this XMLSignature.

SIGN - Static variable in class javax.xml.crypto.KeySelector.Purpose

A key for signing.

signal() - Method in class java.util.concurrent.locks.AbstractQueuedLongSynchronizer.ConditionObject

Moves the longest-waiting thread, if one exists, from the wait queue for this condition to the wait queue for the owning lock.

signal() - Method in class java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject

Moves the longest-waiting thread, if one exists, from the wait queue for this condition to the wait queue for the owning lock.

signal() - Method in interface java.util.concurrent.locks.Condition

Wakes up one waiting thread.

signalAll() - Method in class java.util.concurrent.locks.AbstractQueuedLongSynchronizer.ConditionObject

Moves all threads from the wait queue for this condition to the wait queue for the owning lock.

signalAll() - Method in class java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject

Moves all threads from the wait queue for this condition to the wait queue for the owning lock.

signalAll() - Method in interface java.util.concurrent.locks.Condition

Wakes up all waiting threads.

Signature - Class in java.security

The Signature class is used to provide applications the functionality of a digital signature algorithm.

Signature(String) - Constructor for class java.security.Signature

Creates a Signature object for the specified algorithm.

SIGNATURE_VERSION - Static variable in class java.util.jar.Attributes.Name

Name object for Signature-Version manifest attribute used when signing JAR files.

SignatureException - Exception in java.security

This is the generic Signature exception.

SignatureException() - Constructor for exception java.security.SignatureException

Constructs a SignatureException with no detail message.

SignatureException(String) - Constructor for exception java.security.SignatureException

Constructs a SignatureException with the specified detail message.

SignatureException(String, Throwable) - Constructor for exception java.security.SignatureException

Creates a SignatureException with the specified detail message and cause.

SignatureException(Throwable) - Constructor for exception java.security.SignatureException

Creates a SignatureException with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).

SignatureMethod - Interface in javax.xml.crypto.dsig

A representation of the XML SignatureMethod element as defined in the W3C Recommendation for XML-Signature Syntax and Processing.

SignatureMethodParameterSpec - Interface in javax.xml.crypto.dsig.spec

A specification of algorithm parameters for an XML SignatureMethod algorithm.

SignatureProperties - Interface in javax.xml.crypto.dsig

A representation of the XML SignatureProperties element as defined in the W3C Recommendation for XML-Signature Syntax and Processing.

SignatureProperty - Interface in javax.xml.crypto.dsig

A representation of the XML SignatureProperty element as defined in the W3C Recommendation for XML-Signature Syntax and Processing.

SignatureSpi - Class in java.security

This class defines the Service Provider Interface (SPI) for the Signature class, which is used to provide the functionality of a digital signature algorithm.

SignatureSpi() - Constructor for class java.security.SignatureSpi

SignedInfo - Interface in javax.xml.crypto.dsig

An representation of the XML SignedInfo element as defined in the W3C Recommendation for XML-Signature Syntax and Processing.

SignedObject - Class in java.security

SignedObject is a class for the purpose of creating authentic runtime objects whose integrity cannot be compromised without being detected.

SignedObject(Serializable, PrivateKey, Signature) - Constructor for class java.security.SignedObject

Constructs a SignedObject from any Serializable object.

Signer - Class in java.security

Deprecated.
This class is no longer used. Its functionality has been replaced by java.security.KeyStore, the java.security.cert package, and java.security.Principal.

Signer() - Constructor for class java.security.Signer

Deprecated.

Creates a signer.

Signer(String) - Constructor for class java.security.Signer

Deprecated.

Creates a signer with the specified identity name.

Signer(String, IdentityScope) - Constructor for class java.security.Signer

Deprecated.

Creates a signer with the specified identity name and scope.

signum(int) - Static method in class java.lang.Integer

Returns the signum function of the specified int value.

signum(long) - Static method in class java.lang.Long

Returns the signum function of the specified long value.

signum(double) - Static method in class java.lang.Math

Returns the signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater than zero, -1.0 if the argument is less than zero.

signum(float) - Static method in class java.lang.Math

Returns the signum function of the argument; zero if the argument is zero, 1.0f if the argument is greater than zero, -1.0f if the argument is less than zero.

signum(double) - Static method in class java.lang.StrictMath

Returns the signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater than zero, -1.0 if the argument is less than zero.

signum(float) - Static method in class java.lang.StrictMath

Returns the signum function of the argument; zero if the argument is zero, 1.0f if the argument is greater than zero, -1.0f if the argument is less than zero.

signum() - Method in class java.math.BigDecimal

Returns the signum function of this BigDecimal.

signum() - Method in class java.math.BigInteger

Returns the signum function of this BigInteger.

SILENT - Static variable in class java.rmi.server.LogStream

Deprecated.

log level constant (no logging).

SIMPLE_SCROLL_MODE - Static variable in class javax.swing.JViewport

This mode uses the very simple method of redrawing the entire contents of the scrollpane each time it is scrolled.

SimpleAnnotationValueVisitor6<R,P> - Class in javax.lang.model.util

A simple visitor for annotation values with default behavior appropriate for the RELEASE_6 source version.

SimpleAnnotationValueVisitor6() - Constructor for class javax.lang.model.util.SimpleAnnotationValueVisitor6

Constructor for concrete subclasses; uses null for the default value.

SimpleAnnotationValueVisitor6(R) - Constructor for class javax.lang.model.util.SimpleAnnotationValueVisitor6

Constructor for concrete subclasses; uses the argument for the default value.

SimpleAnnotationValueVisitor7<R,P> - Class in javax.lang.model.util

A simple visitor for annotation values with default behavior appropriate for the RELEASE_7 source version.

SimpleAnnotationValueVisitor7() - Constructor for class javax.lang.model.util.SimpleAnnotationValueVisitor7

Constructor for concrete subclasses; uses null for the default value.

SimpleAnnotationValueVisitor7(R) - Constructor for class javax.lang.model.util.SimpleAnnotationValueVisitor7

Constructor for concrete subclasses; uses the argument for the default value.

SimpleAttributeSet - Class in javax.swing.text

A straightforward implementation of MutableAttributeSet using a hash table.

SimpleAttributeSet() - Constructor for class javax.swing.text.SimpleAttributeSet

Creates a new attribute set.

SimpleAttributeSet(AttributeSet) - Constructor for class javax.swing.text.SimpleAttributeSet

Creates a new attribute set based on a supplied set of attributes.

SimpleBeanInfo - Class in java.beans

This is a support class to make it easier for people to provide BeanInfo classes.

SimpleBeanInfo() - Constructor for class java.beans.SimpleBeanInfo

SimpleBindings - Class in javax.script

A simple implementation of Bindings backed by a HashMap or some other specified Map.

SimpleBindings(Map<String, Object>) - Constructor for class javax.script.SimpleBindings

Constructor uses an existing Map to store the values.

SimpleBindings() - Constructor for class javax.script.SimpleBindings

Default constructor uses a HashMap.

SimpleDateFormat - Class in java.text

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner.

SimpleDateFormat() - Constructor for class java.text.SimpleDateFormat

Constructs a SimpleDateFormat using the default pattern and date format symbols for the default locale.

SimpleDateFormat(String) - Constructor for class java.text.SimpleDateFormat

Constructs a SimpleDateFormat using the given pattern and the default date format symbols for the default locale.

SimpleDateFormat(String, Locale) - Constructor for class java.text.SimpleDateFormat

Constructs a SimpleDateFormat using the given pattern and the default date format symbols for the given locale.

SimpleDateFormat(String, DateFormatSymbols) - Constructor for class java.text.SimpleDateFormat

Constructs a SimpleDateFormat using the given pattern and date format symbols.

SimpleDoc - Class in javax.print

This class is an implementation of interface Doc that can be used in many common printing requests.

SimpleDoc(Object, DocFlavor, DocAttributeSet) - Constructor for class javax.print.SimpleDoc

Constructs a SimpleDoc with the specified print data, doc flavor and doc attribute set.

SimpleElementVisitor6<R,P> - Class in javax.lang.model.util

A simple visitor of program elements with default behavior appropriate for the RELEASE_6 source version.

SimpleElementVisitor6() - Constructor for class javax.lang.model.util.SimpleElementVisitor6

Constructor for concrete subclasses; uses null for the default value.

SimpleElementVisitor6(R) - Constructor for class javax.lang.model.util.SimpleElementVisitor6

Constructor for concrete subclasses; uses the argument for the default value.

SimpleElementVisitor7<R,P> - Class in javax.lang.model.util

A simple visitor of program elements with default behavior appropriate for the RELEASE_7 source version.

SimpleElementVisitor7() - Constructor for class javax.lang.model.util.SimpleElementVisitor7

Constructor for concrete subclasses; uses null for the default value.

SimpleElementVisitor7(R) - Constructor for class javax.lang.model.util.SimpleElementVisitor7

Constructor for concrete subclasses; uses the argument for the default value.

SimpleFileVisitor<T> - Class in java.nio.file

A simple visitor of files with default behavior to visit all files and to re-throw I/O errors.

SimpleFileVisitor() - Constructor for class java.nio.file.SimpleFileVisitor

Initializes a new instance of this class.

SimpleFormatter - Class in java.util.logging

Print a brief summary of the LogRecord in a human readable format.

SimpleFormatter() - Constructor for class java.util.logging.SimpleFormatter

SimpleJavaFileObject - Class in javax.tools

Provides simple implementations for most methods in JavaFileObject.

SimpleJavaFileObject(URI, JavaFileObject.Kind) - Constructor for class javax.tools.SimpleJavaFileObject

Construct a SimpleJavaFileObject of the given kind and with the given URI.

SimpleScriptContext - Class in javax.script

Simple implementation of ScriptContext.

SimpleScriptContext() - Constructor for class javax.script.SimpleScriptContext

SimpleTimeZone - Class in java.util

SimpleTimeZone is a concrete subclass of TimeZone that represents a time zone for use with a Gregorian calendar.

SimpleTimeZone(int, String) - Constructor for class java.util.SimpleTimeZone

Constructs a SimpleTimeZone with the given base time zone offset from GMT and time zone ID with no daylight saving time schedule.

SimpleTimeZone(int, String, int, int, int, int, int, int, int, int) - Constructor for class java.util.SimpleTimeZone

Constructs a SimpleTimeZone with the given base time zone offset from GMT, time zone ID, and rules for starting and ending the daylight time.

SimpleTimeZone(int, String, int, int, int, int, int, int, int, int, int) - Constructor for class java.util.SimpleTimeZone

Constructs a SimpleTimeZone with the given base time zone offset from GMT, time zone ID, and rules for starting and ending the daylight time.

SimpleTimeZone(int, String, int, int, int, int, int, int, int, int, int, int, int) - Constructor for class java.util.SimpleTimeZone

Constructs a SimpleTimeZone with the given base time zone offset from GMT, time zone ID, and rules for starting and ending the daylight time.

SimpleType<T> - Class in javax.management.openmbean

The SimpleType class is the open type class whose instances describe all open data values which are neither arrays, nor CompositeData values, nor TabularData values.

SimpleTypeVisitor6<R,P> - Class in javax.lang.model.util

A simple visitor of types with default behavior appropriate for the RELEASE_6 source version.

SimpleTypeVisitor6() - Constructor for class javax.lang.model.util.SimpleTypeVisitor6

Constructor for concrete subclasses; uses null for the default value.

SimpleTypeVisitor6(R) - Constructor for class javax.lang.model.util.SimpleTypeVisitor6

Constructor for concrete subclasses; uses the argument for the default value.

SimpleTypeVisitor7<R,P> - Class in javax.lang.model.util

A simple visitor of types with default behavior appropriate for the RELEASE_7 source version.

SimpleTypeVisitor7() - Constructor for class javax.lang.model.util.SimpleTypeVisitor7

Constructor for concrete subclasses; uses null for the default value.

SimpleTypeVisitor7(R) - Constructor for class javax.lang.model.util.SimpleTypeVisitor7

Constructor for concrete subclasses; uses the argument for the default value.

SIMPLIFIED_CHINESE - Static variable in class java.util.Locale

Useful constant for language.

SIMPLIFIED_HANZI - Static variable in class java.awt.im.InputSubset

Constant for all Han characters used in writing Simplified Chinese, including a subset of the CJK unified ideographs as well as Simplified Chinese Han characters that may be defined as surrogate characters.

sin(double) - Static method in class java.lang.Math

Returns the trigonometric sine of an angle.

sin(double) - Static method in class java.lang.StrictMath

Returns the trigonometric sine of an angle.

SINGLE_DOCUMENT - Static variable in class javax.print.attribute.standard.MultipleDocumentHandling

Single document -- see above for further information.

SINGLE_DOCUMENT_NEW_SHEET - Static variable in class javax.print.attribute.standard.MultipleDocumentHandling

Single document new sheet -- see above for further information.

SINGLE_INTERVAL_SELECTION - Static variable in interface javax.swing.ListSelectionModel

A value for the selectionMode property: select one contiguous range of indices at a time.

SINGLE_LINE - Static variable in class javax.accessibility.AccessibleState

Indicates this (text) object can contain only a single line of text

SINGLE_SELECTION - Static variable in interface javax.swing.ListSelectionModel

A value for the selectionMode property: select one list index at a time.

SINGLE_THREAD_MODEL - Static variable in class org.omg.PortableServer.ThreadPolicyValue

SINGLE_TREE_SELECTION - Static variable in interface javax.swing.tree.TreeSelectionModel

Selection can only contain one path at a time.

SINGLEFRAME - Static variable in interface java.awt.image.ImageConsumer

The image contain a single static image.

SINGLEFRAMEDONE - Static variable in interface java.awt.image.ImageConsumer

One frame of the image is complete but there are more frames to be delivered.

SINGLEPASS - Static variable in interface java.awt.image.ImageConsumer

The pixels will be delivered in a single pass.

SinglePixelPackedSampleModel - Class in java.awt.image

This class represents pixel data packed such that the N samples which make up a single pixel are stored in a single data array element, and each data data array element holds samples for only one pixel.

SinglePixelPackedSampleModel(int, int, int, int[]) - Constructor for class java.awt.image.SinglePixelPackedSampleModel

Constructs a SinglePixelPackedSampleModel with bitMasks.length bands.

SinglePixelPackedSampleModel(int, int, int, int, int[]) - Constructor for class java.awt.image.SinglePixelPackedSampleModel

Constructs a SinglePixelPackedSampleModel with bitMasks.length bands and a scanline stride equal to scanlineStride data array elements.

SingleSelectionModel - Interface in javax.swing

A model that supports at most one indexed selection.

singleton(T) - Static method in class java.util.Collections

Returns an immutable set containing only the specified object.

singletonKeySelector(Key) - Static method in class javax.xml.crypto.KeySelector

Returns a KeySelector that always selects the specified key, regardless of the KeyInfo passed to it.

singletonList(T) - Static method in class java.util.Collections

Returns an immutable list containing only the specified object.

singletonMap(K, V) - Static method in class java.util.Collections

Returns an immutable map, mapping only the specified key to the specified value.

sinh(double) - Static method in class java.lang.Math

Returns the hyperbolic sine of a double value.

sinh(double) - Static method in class java.lang.StrictMath

Returns the hyperbolic sine of a double value.

SINHALA - Static variable in class java.lang.Character.UnicodeBlock

Constant for the "Sinhala" Unicode character block.

sink() - Method in class java.nio.channels.Pipe

Returns this pipe's sink channel.

size() - Method in class java.awt.Component

Deprecated.
As of JDK version 1.1, replaced by getSize().

size - Variable in class java.awt.Font

The point size of this Font, rounded to integer.

SIZE - Static variable in class java.awt.font.TextAttribute

Attribute key for the font size.

size - Variable in class java.awt.image.DataBuffer

Usable size of all banks.

size() - Method in class java.awt.RenderingHints

Returns the number of key-value mappings in this RenderingHints.

size() - Method in class java.beans.beancontext.BeanContextMembershipEvent

Gets the number of children affected by the notification.

size() - Method in class java.beans.beancontext.BeanContextSupport

Gets the number of children currently nested in this BeanContext.

size() - Method in class java.io.ByteArrayOutputStream

Returns the current size of the buffer.

size() - Method in class java.io.CharArrayWriter

Returns the current size of the buffer.

size() - Method in class java.io.DataOutputStream

Returns the current value of the counter written, the number of bytes written to this data output stream so far.

SIZE - Static variable in class java.lang.Byte

The number of bits used to represent a byte value in two's complement binary form.

SIZE - Static variable in class java.lang.Character

The number of bits used to represent a char value in unsigned binary form, constant 16.

SIZE - Static variable in class java.lang.Double

The number of bits used to represent a double value.

SIZE - Static variable in class java.lang.Float

The number of bits used to represent a float value.

SIZE - Static variable in class java.lang.Integer

The number of bits used to represent an int value in two's complement binary form.

SIZE - Static variable in class java.lang.Long

The number of bits used to represent a long value in two's complement binary form.

SIZE - Static variable in class java.lang.Short

The number of bits used to represent a short value in two's complement binary form.

size() - Method in class java.nio.channels.AsynchronousFileChannel

Returns the current size of this channel's file.

size() - Method in class java.nio.channels.FileChannel

Returns the current size of this channel's file.

size() - Method in class java.nio.channels.FileLock

Returns the size of the locked region in bytes.

size() - Method in interface java.nio.channels.SeekableByteChannel

Returns the current size of entity to which this channel is connected.

size() - Method in interface java.nio.file.attribute.BasicFileAttributes

Returns the size of the file (in bytes).

size(String) - Method in interface java.nio.file.attribute.UserDefinedFileAttributeView

Returns the size of the value of a user-defined attribute.

size(Path) - Static method in class java.nio.file.Files

Returns the size of a file (in bytes).

size() - Method in class java.security.IdentityScope

Deprecated.

Returns the number of identities within this identity scope.

size() - Method in class java.security.KeyStore

Retrieves the number of entries in this keystore.

size() - Method in class java.util.AbstractCollection

size() - Method in class java.util.AbstractMap

Returns the number of key-value mappings in this map.

size() - Method in class java.util.ArrayDeque

Returns the number of elements in this deque.

size() - Method in class java.util.ArrayList

Returns the number of elements in this list.

size() - Method in class java.util.BitSet

Returns the number of bits of space actually in use by this BitSet to represent bit values.

size() - Method in interface java.util.Collection

Returns the number of elements in this collection.

size() - Method in class java.util.concurrent.ArrayBlockingQueue

Returns the number of elements in this queue.

size() - Method in interface java.util.concurrent.BlockingDeque

Returns the number of elements in this deque.

size() - Method in class java.util.concurrent.ConcurrentHashMap

Returns the number of key-value mappings in this map.

size() - Method in class java.util.concurrent.ConcurrentLinkedDeque

Returns the number of elements in this deque.

size() - Method in class java.util.concurrent.ConcurrentLinkedQueue

Returns the number of elements in this queue.

size() - Method in class java.util.concurrent.ConcurrentSkipListMap

Returns the number of key-value mappings in this map.

size() - Method in class java.util.concurrent.ConcurrentSkipListSet

Returns the number of elements in this set.

size() - Method in class java.util.concurrent.CopyOnWriteArrayList

Returns the number of elements in this list.

size() - Method in class java.util.concurrent.CopyOnWriteArraySet

Returns the number of elements in this set.

size() - Method in class java.util.concurrent.DelayQueue

size() - Method in class java.util.concurrent.LinkedBlockingDeque

Returns the number of elements in this deque.

size() - Method in class java.util.concurrent.LinkedBlockingQueue

Returns the number of elements in this queue.

size() - Method in class java.util.concurrent.LinkedTransferQueue

Returns the number of elements in this queue.

size() - Method in class java.util.concurrent.PriorityBlockingQueue

size() - Method in class java.util.concurrent.SynchronousQueue

Always returns zero.

size() - Method in interface java.util.Deque

Returns the number of elements in this deque.

size() - Method in class java.util.Dictionary

Returns the number of entries (distinct keys) in this dictionary.

size() - Method in class java.util.EnumMap

Returns the number of key-value mappings in this map.

size() - Method in class java.util.HashMap

Returns the number of key-value mappings in this map.

size() - Method in class java.util.HashSet

Returns the number of elements in this set (its cardinality).

size() - Method in class java.util.Hashtable

Returns the number of keys in this hashtable.

size() - Method in class java.util.IdentityHashMap

Returns the number of key-value mappings in this identity hash map.

size() - Method in class java.util.jar.Attributes

Returns the number of attributes in this Map.

size() - Method in class java.util.LinkedList

Returns the number of elements in this list.

size() - Method in interface java.util.List

Returns the number of elements in this list.

size() - Method in interface java.util.Map

Returns the number of key-value mappings in this map.

size() - Method in class java.util.PriorityQueue

size() - Method in interface java.util.Set

Returns the number of elements in this set (its cardinality).

size() - Method in class java.util.TreeMap

Returns the number of key-value mappings in this map.

size() - Method in class java.util.TreeSet

Returns the number of elements in this set (its cardinality).

size() - Method in class java.util.Vector

Returns the number of components in this vector.

size() - Method in class java.util.WeakHashMap

Returns the number of key-value mappings in this map.

size() - Method in class java.util.zip.ZipFile

Returns the number of entries in the ZIP file.

size() - Method in class javax.accessibility.AccessibleRelationSet

Returns the number of relations in the relation set.

size() - Method in class javax.activation.MimeTypeParameterList

Return the number of name-value pairs in this list.

size() - Method in interface javax.management.openmbean.TabularData

Returns the number of CompositeData values (ie the number of rows) contained in this TabularData instance.

size() - Method in class javax.management.openmbean.TabularDataSupport

Returns the number of rows in this TabularDataSupport instance.

size() - Method in class javax.naming.CompositeName

Retrieves the number of components in this composite name.

size() - Method in class javax.naming.CompoundName

Retrieves the number of components in this compound name.

size() - Method in interface javax.naming.directory.Attribute

Retrieves the number of values in this attribute.

size() - Method in interface javax.naming.directory.Attributes

Retrieves the number of attributes in the attribute set.

size() - Method in class javax.naming.directory.BasicAttribute

size() - Method in class javax.naming.directory.BasicAttributes

size() - Method in class javax.naming.ldap.LdapName

Retrieves the number of components in this LDAP name.

size() - Method in class javax.naming.ldap.Rdn

Retrieves the number of attribute type/value pairs in this Rdn.

size() - Method in interface javax.naming.Name

Returns the number of components in this name.

size() - Method in class javax.naming.Reference

Retrieves the number of addresses in this reference.

size() - Method in interface javax.print.attribute.AttributeSet

Returns the number of attributes in this attribute set.

size() - Method in class javax.print.attribute.HashAttributeSet

Returns the number of attributes in this attribute set.

size() - Method in class javax.script.SimpleBindings

Returns the number of key-value mappings in this map.

size() - Method in class javax.sound.midi.Track

Obtains the number of events in this track.

size() - Method in interface javax.sql.rowset.CachedRowSet

Returns the number of rows in this CachedRowSet object.

size() - Method in class javax.swing.ActionMap

Returns the number of bindings in this ActionMap.

size() - Method in class javax.swing.DefaultListModel

Returns the number of components in this list.

size() - Method in class javax.swing.InputMap

Returns the number of KeyStroke bindings.

SIZE - Static variable in class javax.swing.text.html.HTML.Attribute

Size - Static variable in class javax.swing.text.StyleConstants

Name of the font size.

Size2DSyntax - Class in javax.print.attribute

Class Size2DSyntax is an abstract base class providing the common implementation of all attributes denoting a size in two dimensions.

Size2DSyntax(float, float, int) - Constructor for class javax.print.attribute.Size2DSyntax

Construct a new two-dimensional size attribute from the given floating-point values.

Size2DSyntax(int, int, int) - Constructor for class javax.print.attribute.Size2DSyntax

Construct a new two-dimensional size attribute from the given integer values.

SIZE_CMD - Static variable in class javax.swing.plaf.basic.BasicInternalFrameTitlePane

sizeAction - Variable in class javax.swing.plaf.basic.BasicInternalFrameTitlePane

sizeColumnsToFit(boolean) - Method in class javax.swing.JTable

Deprecated.
As of Swing version 1.0.3, replaced by doLayout().

sizeColumnsToFit(int) - Method in class javax.swing.JTable

Obsolete as of Java 2 platform v1.4.

SizeLimitExceededException - Exception in javax.naming

This exception is thrown when a method produces a result that exceeds a size-related limit.

SizeLimitExceededException() - Constructor for exception javax.naming.SizeLimitExceededException

Constructs a new instance of SizeLimitExceededException.

SizeLimitExceededException(String) - Constructor for exception javax.naming.SizeLimitExceededException

Constructs a new instance of SizeLimitExceededException using an explanation.

SizeRequirements - Class in javax.swing

For the convenience of layout managers, calculates information about the size and position of components.

SizeRequirements() - Constructor for class javax.swing.SizeRequirements

Creates a SizeRequirements object with the minimum, preferred, and maximum sizes set to zero and an alignment value of 0.5 (centered).

SizeRequirements(int, int, int, float) - Constructor for class javax.swing.SizeRequirements

Creates a SizeRequirements object with the specified minimum, preferred, and maximum sizes and the specified alignment.

sizes - Variable in class javax.swing.plaf.basic.BasicSplitPaneUI.BasicHorizontalLayoutManager

SizeSequence - Class in javax.swing

A SizeSequence object efficiently maintains an ordered list of sizes and corresponding positions.

SizeSequence() - Constructor for class javax.swing.SizeSequence

Creates a new SizeSequence object that contains no entries.

SizeSequence(int) - Constructor for class javax.swing.SizeSequence

Creates a new SizeSequence object that contains the specified number of entries, all initialized to have size 0.

SizeSequence(int, int) - Constructor for class javax.swing.SizeSequence

Creates a new SizeSequence object that contains the specified number of entries, all initialized to have size value.

SizeSequence(int[]) - Constructor for class javax.swing.SizeSequence

Creates a new SizeSequence object that contains the specified sizes.

sizeWidthToFit() - Method in class javax.swing.table.TableColumn

Resizes the TableColumn to fit the width of its header cell.

Skeleton - Interface in java.rmi.server

Deprecated.
no replacement. Skeletons are no longer required for remote method calls in the Java 2 platform v1.2 and greater.

SkeletonMismatchException - Exception in java.rmi.server

Deprecated.
no replacement. Skeletons are no longer required for remote method calls in the Java 2 platform v1.2 and greater.

SkeletonMismatchException(String) - Constructor for exception java.rmi.server.SkeletonMismatchException

Deprecated.
no replacement

SkeletonNotFoundException - Exception in java.rmi.server

Deprecated.
no replacement. Skeletons are no longer required for remote method calls in the Java 2 platform v1.2 and greater.

SkeletonNotFoundException(String) - Constructor for exception java.rmi.server.SkeletonNotFoundException

Deprecated.

Constructs a SkeletonNotFoundException with the specified detail message.

SkeletonNotFoundException(String, Exception) - Constructor for exception java.rmi.server.SkeletonNotFoundException

Deprecated.

Constructs a SkeletonNotFoundException with the specified detail message and nested exception.

skip(long) - Method in class java.io.BufferedInputStream

See the general contract of the skip method of InputStream.

skip(long) - Method in class java.io.BufferedReader

Skips characters.

skip(long) - Method in class java.io.ByteArrayInputStream

Skips n bytes of input from this input stream.

skip(long) - Method in class java.io.CharArrayReader

Skips characters.

skip(long) - Method in class java.io.FileInputStream

Skips over and discards n bytes of data from the input stream.

skip(long) - Method in class java.io.FilterInputStream

Skips over and discards n bytes of data from the input stream.

skip(long) - Method in class java.io.FilterReader

Skips characters.

skip(long) - Method in class java.io.InputStream

Skips over and discards n bytes of data from this input stream.

skip(long) - Method in class java.io.LineNumberInputStream

Deprecated.

Skips over and discards n bytes of data from this input stream.

skip(long) - Method in class java.io.LineNumberReader

Skip characters.

skip(long) - Method in interface java.io.ObjectInput

Skips n bytes of input.

skip(long) - Method in class java.io.PushbackInputStream

Skips over and discards n bytes of data from this input stream.

skip(long) - Method in class java.io.PushbackReader

Skips characters.

skip(long) - Method in class java.io.Reader

Skips characters.

skip(long) - Method in class java.io.StringBufferInputStream

Deprecated.

Skips n bytes of input from this input stream.

skip(long) - Method in class java.io.StringReader

Skips the specified number of characters in the stream.

skip(Pattern) - Method in class java.util.Scanner

Skips input that matches the specified pattern, ignoring delimiters.

skip(String) - Method in class java.util.Scanner

Skips input that matches a pattern constructed from the specified string.

skip(long) - Method in class java.util.zip.CheckedInputStream

Skips specified number of bytes of input.

skip(long) - Method in class java.util.zip.DeflaterInputStream

Skips over and discards data from the input stream.

skip(long) - Method in class java.util.zip.InflaterInputStream

Skips specified number of bytes of uncompressed data.

skip(long) - Method in class java.util.zip.ZipInputStream

Skips specified number of bytes in the current ZIP entry.

skip(long) - Method in class javax.crypto.CipherInputStream

Skips n bytes of input from the bytes that can be read from this input stream without blocking.

skip(long) - Method in class javax.sound.sampled.AudioInputStream

Skips over and discards a specified number of bytes from this audio input stream.

skip(long) - Method in class javax.swing.ProgressMonitorInputStream

Overrides FilterInputStream.skip to update the progress monitor after the skip.

skipBytes(int) - Method in interface java.io.DataInput

Makes an attempt to skip over n bytes of data from the input stream, discarding the skipped bytes.

skipBytes(int) - Method in class java.io.DataInputStream

See the general contract of the skipBytes method of DataInput.

skipBytes(int) - Method in class java.io.ObjectInputStream

Skips bytes.

skipBytes(int) - Method in class java.io.RandomAccessFile

Attempts to skip over n bytes of input discarding the skipped bytes.

skipBytes(int) - Method in interface javax.imageio.stream.ImageInputStream

Moves the stream position forward by a given number of bytes.

skipBytes(long) - Method in interface javax.imageio.stream.ImageInputStream

Moves the stream position forward by a given number of bytes.

skipBytes(int) - Method in class javax.imageio.stream.ImageInputStreamImpl

Advances the current stream position by calling seek(getStreamPosition() + n).

skipBytes(long) - Method in class javax.imageio.stream.ImageInputStreamImpl

Advances the current stream position by calling seek(getStreamPosition() + n).

skippedEntity(String) - Method in interface org.xml.sax.ContentHandler

Receive notification of a skipped entity.

skippedEntity(String) - Method in class org.xml.sax.helpers.DefaultHandler

Receive notification of a skipped entity.

skippedEntity(String) - Method in class org.xml.sax.helpers.XMLFilterImpl

Filter a skipped entity event.

skippedEntity(String) - Method in class org.xml.sax.helpers.XMLReaderAdapter

Adapt a SAX2 skipped entity event.

skipReferral() - Method in exception javax.naming.ReferralException

Discards the referral about to be processed.

slashSlashComments(boolean) - Method in class java.io.StreamTokenizer

Determines whether or not the tokenizer recognizes C++-style comments.

slashStarComments(boolean) - Method in class java.io.StreamTokenizer

Determines whether or not the tokenizer recognizes C-style comments.

sleep(long) - Static method in class java.lang.Thread

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.

sleep(long, int) - Static method in class java.lang.Thread

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds plus the specified number of nanoseconds, subject to the precision and accuracy of system timers and schedulers.

sleep(long) - Method in enum java.util.concurrent.TimeUnit

Performs a Thread.sleep using this time unit.

slice() - Method in class java.nio.ByteBuffer

Creates a new byte buffer whose content is a shared subsequence of this buffer's content.

slice() - Method in class java.nio.CharBuffer

Creates a new char buffer whose content is a shared subsequence of this buffer's content.

slice() - Method in class java.nio.DoubleBuffer

Creates a new double buffer whose content is a shared subsequence of this buffer's content.

slice() - Method in class java.nio.FloatBuffer

Creates a new float buffer whose content is a shared subsequence of this buffer's content.

slice() - Method in class java.nio.IntBuffer

Creates a new int buffer whose content is a shared subsequence of this buffer's content.

slice() - Method in class java.nio.LongBuffer

Creates a new long buffer whose content is a shared subsequence of this buffer's content.

slice() - Method in class java.nio.ShortBuffer

Creates a new short buffer whose content is a shared subsequence of this buffer's content.

SLIDER - Static variable in class javax.accessibility.AccessibleRole

An object that allows the user to select from a bounded range.

slider - Variable in class javax.swing.plaf.basic.BasicSliderUI

SLIDER - Static variable in class javax.swing.plaf.synth.Region

Slider region.

SLIDER_FILL - Variable in class javax.swing.plaf.metal.MetalSliderUI

SLIDER_THUMB - Static variable in class javax.swing.plaf.synth.Region

Thumb of the Slider.

SLIDER_TRACK - Static variable in class javax.swing.plaf.synth.Region

Track of the Slider.

sliderModel - Variable in class javax.swing.JSlider

The data model that handles the numeric maximum value, minimum value, and current-position value for the slider.

SliderUI - Class in javax.swing.plaf

Pluggable look and feel interface for JSlider.

SliderUI() - Constructor for class javax.swing.plaf.SliderUI

SMALL - Static variable in class javax.swing.text.html.HTML.Tag

SMALL_FORM_VARIANTS - Static variable in class java.lang.Character.UnicodeBlock

Constant for the "Small Form Variants" Unicode character block.

SMALL_ICON - Static variable in interface javax.swing.Action

The key used for storing a small Icon, such as ImageIcon.

SMALL_KEY - Static variable in class javax.swing.plaf.nimbus.NimbusStyle

SMALL_SCALE - Static variable in class javax.swing.plaf.nimbus.NimbusStyle

SMALLINT - Static variable in class java.sql.Types

The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type SMALLINT.

SMPTE_24 - Static variable in class javax.sound.midi.Sequence

The SMPTE-based timing type with 24 frames per second (resolution is expressed in ticks per frame).

SMPTE_25 - Static variable in class javax.sound.midi.Sequence

The SMPTE-based timing type with 25 frames per second (resolution is expressed in ticks per frame).

SMPTE_30 - Static variable in class javax.sound.midi.Sequence

The SMPTE-based timing type with 30 frames per second (resolution is expressed in ticks per frame).

SMPTE_30DROP - Static variable in class javax.sound.midi.Sequence

The SMPTE-based timing type with 29.97 frames per second (resolution is expressed in ticks per frame).

snapToTicks - Variable in class javax.swing.JSlider

If true, the knob (and the data value it represents) resolve to the closest tick mark next to where the user positioned the knob.

SND - Static variable in class javax.sound.sampled.AudioFileFormat.Type

Specifies a SND file.

SO_BINDADDR - Static variable in interface java.net.SocketOptions

Fetch the local address binding of a socket (this option cannot be "set" only "gotten", since sockets are bound at creation time, and so the locally bound address cannot be changed).

SO_BROADCAST - Static variable in interface java.net.SocketOptions

Sets SO_BROADCAST for a socket.

SO_BROADCAST - Static variable in class java.net.StandardSocketOption

Allow transmission of broadcast datagrams.

SO_KEEPALIVE - Static variable in interface java.net.SocketOptions

When the keepalive option is set for a TCP socket and no data has been exchanged across the socket in either direction for 2 hours (NOTE: the actual value is implementation dependent), TCP automatically sends a keepalive probe to the peer.

SO_KEEPALIVE - Static variable in class java.net.StandardSocketOption

Keep connection alive.

SO_LINGER - Static variable in interface java.net.SocketOptions

Specify a linger-on-close timeout.

SO_LINGER - Static variable in class java.net.StandardSocketOption

Linger on close if data is present.

SO_OOBINLINE - Static variable in interface java.net.SocketOptions

When the OOBINLINE option is set, any TCP urgent data received on the socket will be received through the socket input stream.

SO_RCVBUF - Static variable in interface java.net.SocketOptions

Set a hint the size of the underlying buffers used by the platform for incoming network I/O.

SO_RCVBUF - Static variable in class java.net.StandardSocketOption

The size of the socket receive buffer.

SO_REUSEADDR - Static variable in interface java.net.SocketOptions

Sets SO_REUSEADDR for a socket.

SO_REUSEADDR - Static variable in class java.net.StandardSocketOption

Re-use address.

SO_SNDBUF - Static variable in interface java.net.SocketOptions

Set a hint the size of the underlying buffers used by the platform for outgoing network I/O.

SO_SNDBUF - Static variable in class java.net.StandardSocketOption

The size of the socket send buffer.

SO_TIMEOUT - Static variable in interface java.net.SocketOptions

Set a timeout on blocking Socket operations:

SOAP11HTTP_BINDING - Static variable in interface javax.xml.ws.soap.SOAPBinding

A constant representing the identity of the SOAP 1.1 over HTTP binding.

SOAP11HTTP_MTOM_BINDING - Static variable in interface javax.xml.ws.soap.SOAPBinding

A constant representing the identity of the SOAP 1.1 over HTTP binding with MTOM enabled by default.

SOAP12HTTP_BINDING - Static variable in interface javax.xml.ws.soap.SOAPBinding

A constant representing the identity of the SOAP 1.2 over HTTP binding.

SOAP12HTTP_MTOM_BINDING - Static variable in interface javax.xml.ws.soap.SOAPBinding

A constant representing the identity of the SOAP 1.2 over HTTP binding with MTOM enabled by default.

SOAP_1_1_CONTENT_TYPE - Static variable in interface javax.xml.soap.SOAPConstants

The media type of the Content-Type MIME header in SOAP 1.1.

SOAP_1_1_PROTOCOL - Static variable in interface javax.xml.soap.SOAPConstants

Used to create MessageFactory instances that create SOAPMessages whose behavior supports the SOAP 1.1 specification.

SOAP_1_2_CONTENT_TYPE - Static variable in interface javax.xml.soap.SOAPConstants

The media type of the Content-Type MIME header in SOAP 1.2.

SOAP_1_2_PROTOCOL - Static variable in interface javax.xml.soap.SOAPConstants

Used to create MessageFactory instances that create SOAPMessages whose behavior supports the SOAP 1.2 specification

SOAP_DATAENCODINGUNKNOWN_FAULT - Static variable in interface javax.xml.soap.SOAPConstants

SOAP 1.2 DataEncodingUnknown Fault

SOAP_ENV_PREFIX - Static variable in interface javax.xml.soap.SOAPConstants

The default namespace prefix for http://www.w3.org/2003/05/soap-envelope

SOAP_MUSTUNDERSTAND_FAULT - Static variable in interface javax.xml.soap.SOAPConstants

SOAP 1.2 MustUnderstand Fault

SOAP_RECEIVER_FAULT - Static variable in interface javax.xml.soap.SOAPConstants

SOAP 1.2 Receiver Fault

SOAP_SENDER_FAULT - Static variable in interface javax.xml.soap.SOAPConstants

SOAP 1.2 Sender Fault

SOAP_VERSIONMISMATCH_FAULT - Static variable in interface javax.xml.soap.SOAPConstants

SOAP 1.2 VersionMismatch Fault

SOAPACTION_URI_PROPERTY - Static variable in interface javax.xml.ws.BindingProvider

Standard property for SOAPAction.

SOAPACTION_USE_PROPERTY - Static variable in interface javax.xml.ws.BindingProvider

Standard property for SOAPAction.

SOAPBinding - Annotation Type in javax.jws.soap

Specifies the mapping of the Web Service onto the SOAP message protocol.

SOAPBinding - Interface in javax.xml.ws.soap

The SOAPBinding interface is an abstraction for the SOAP binding.

SOAPBinding.ParameterStyle - Enum in javax.jws.soap

The style of mapping parameters onto SOAP messages

SOAPBinding.Style - Enum in javax.jws.soap

The SOAP binding style

SOAPBinding.Use - Enum in javax.jws.soap

The SOAP binding use

SOAPBody - Interface in javax.xml.soap

An object that represents the contents of the SOAP body element in a SOAP message.

SOAPBodyElement - Interface in javax.xml.soap

A SOAPBodyElement object represents the contents in a SOAPBody object.

SOAPConnection - Class in javax.xml.soap

A point-to-point connection that a client can use for sending messages directly to a remote party (represented by a URL, for instance).

SOAPConnection() - Constructor for class javax.xml.soap.SOAPConnection

SOAPConnectionFactory - Class in javax.xml.soap

A factory for creating SOAPConnection objects.

SOAPConnectionFactory() - Constructor for class javax.xml.soap.SOAPConnectionFactory

SOAPConstants - Interface in javax.xml.soap

The definition of constants pertaining to the SOAP protocol.

SOAPElement - Interface in javax.xml.soap

An object representing an element of a SOAP message that is allowed but not specifically prescribed by a SOAP specification.

SOAPElementFactory - Class in javax.xml.soap

Deprecated.
- Use javax.xml.soap.SOAPFactory for creating SOAPElements.

SOAPEnvelope - Interface in javax.xml.soap

The container for the SOAPHeader and SOAPBody portions of a SOAPPart object.

SOAPException - Exception in javax.xml.soap

An exception that signals that a SOAP exception has occurred.

SOAPException() - Constructor for exception javax.xml.soap.SOAPException

Constructs a SOAPException object with no reason or embedded Throwable object.

SOAPException(String) - Constructor for exception javax.xml.soap.SOAPException

Constructs a SOAPException object with the given String as the reason for the exception being thrown.

SOAPException(String, Throwable) - Constructor for exception javax.xml.soap.SOAPException

Constructs a SOAPException object with the given String as the reason for the exception being thrown and the given Throwable object as an embedded exception.

SOAPException(Throwable) - Constructor for exception javax.xml.soap.SOAPException

Constructs a SOAPException object initialized with the given Throwable object.

SOAPFactory - Class in javax.xml.soap

SOAPFactory is a factory for creating various objects that exist in the SOAP XML tree.

SOAPFactory() - Constructor for class javax.xml.soap.SOAPFactory

SOAPFault - Interface in javax.xml.soap

An element in the SOAPBody object that contains error and/or status information.

SOAPFaultElement - Interface in javax.xml.soap

A representation of the contents in a SOAPFault object.

SOAPFaultException - Exception in javax.xml.ws.soap

The SOAPFaultException exception represents a SOAP 1.1 or 1.2 fault.

SOAPFaultException(SOAPFault) - Constructor for exception javax.xml.ws.soap.SOAPFaultException

Constructor for SOAPFaultException

SOAPHandler<T extends SOAPMessageContext> - Interface in javax.xml.ws.handler.soap

The SOAPHandler class extends Handler to provide typesafety for the message context parameter and add a method to obtain access to the headers that may be processed by the handler.

SOAPHeader - Interface in javax.xml.soap

A representation of the SOAP header element.

SOAPHeaderElement - Interface in javax.xml.soap

An object representing the contents in the SOAP header part of the SOAP envelope.

SOAPMessage - Class in javax.xml.soap

The root class for all SOAP messages.

SOAPMessage() - Constructor for class javax.xml.soap.SOAPMessage

SOAPMessageContext - Interface in javax.xml.ws.handler.soap

The interface SOAPMessageContext provides access to the SOAP message for either RPC request or response.

SOAPMessageHandler - Annotation Type in javax.jws.soap

Deprecated.
As of JSR-181 2.0 with no replacement.

SOAPMessageHandlers - Annotation Type in javax.jws.soap

Deprecated.
As of JSR-181 2.0 with no replacement.

SOAPPart - Class in javax.xml.soap

The container for the SOAP-specific portion of a SOAPMessage object.

SOAPPart() - Constructor for class javax.xml.soap.SOAPPart

Socket - Class in java.net

This class implements client sockets (also called just "sockets").

Socket() - Constructor for class java.net.Socket

Creates an unconnected socket, with the system-default type of SocketImpl.

Socket(Proxy) - Constructor for class java.net.Socket

Creates an unconnected socket, specifying the type of proxy, if any, that should be used regardless of any other settings.

Socket(SocketImpl) - Constructor for class java.net.Socket

Creates an unconnected Socket with a user-specified SocketImpl.

Socket(String, int) - Constructor for class java.net.Socket

Creates a stream socket and connects it to the specified port number on the named host.

Socket(InetAddress, int) - Constructor for class java.net.Socket

Creates a stream socket and connects it to the specified port number at the specified IP address.

Socket(String, int, InetAddress, int) - Constructor for class java.net.Socket

Creates a socket and connects it to the specified remote host on the specified remote port.

Socket(InetAddress, int, InetAddress, int) - Constructor for class java.net.Socket

Creates a socket and connects it to the specified remote address on the specified remote port.

Socket(String, int, boolean) - Constructor for class java.net.Socket

Deprecated.
Use DatagramSocket instead for UDP transport.

Socket(InetAddress, int, boolean) - Constructor for class java.net.Socket

Deprecated.
Use DatagramSocket instead for UDP transport.

socket() - Method in class java.nio.channels.DatagramChannel

Retrieves a datagram socket associated with this channel.

socket() - Method in class java.nio.channels.ServerSocketChannel

Retrieves a server socket associated with this channel.

socket() - Method in class java.nio.channels.SocketChannel

Retrieves a socket associated with this channel.

SocketAddress - Class in java.net

This class represents a Socket Address with no protocol attachment.

SocketAddress() - Constructor for class java.net.SocketAddress

SocketChannel - Class in java.nio.channels

A selectable channel for stream-oriented connecting sockets.

SocketChannel(SelectorProvider) - Constructor for class java.nio.channels.SocketChannel

Initializes a new instance of this class.

SocketException - Exception in java.net

Thrown to indicate that there is an error creating or accessing a Socket.

SocketException(String) - Constructor for exception java.net.SocketException

Constructs a new SocketException with the specified detail message.

SocketException() - Constructor for exception java.net.SocketException

Constructs a new SocketException with no detail message.

SocketFactory - Class in javax.net

This class creates sockets.

SocketFactory() - Constructor for class javax.net.SocketFactory

Creates a SocketFactory.

SocketHandler - Class in java.util.logging

Simple network logging Handler.

SocketHandler() - Constructor for class java.util.logging.SocketHandler

Create a SocketHandler, using only LogManager properties (or their defaults).

SocketHandler(String, int) - Constructor for class java.util.logging.SocketHandler

Construct a SocketHandler using a specified host and port.

SocketImpl - Class in java.net

The abstract class SocketImpl is a common superclass of all classes that actually implement sockets.

SocketImpl() - Constructor for class java.net.SocketImpl

SocketImplFactory - Interface in java.net

This interface defines a factory for socket implementations.

SocketOption<T> - Interface in java.net

A socket option associated with a socket.

SocketOptions - Interface in java.net

Interface of methods to get/set socket options.

SocketPermission - Class in java.net

This class represents access to a network via sockets.

SocketPermission(String, String) - Constructor for class java.net.SocketPermission

Creates a new SocketPermission object with the specified actions.

SocketSecurityException - Exception in java.rmi.server

An obsolete subclass of ExportException.

SocketSecurityException(String) - Constructor for exception java.rmi.server.SocketSecurityException

Constructs an SocketSecurityException with the specified detail message.

SocketSecurityException(String, Exception) - Constructor for exception java.rmi.server.SocketSecurityException

Constructs an SocketSecurityException with the specified detail message and nested exception.

SocketTimeoutException - Exception in java.net

Signals that a timeout has occurred on a socket read or accept.

SocketTimeoutException(String) - Constructor for exception java.net.SocketTimeoutException

Constructs a new SocketTimeoutException with a detail message.

SocketTimeoutException() - Constructor for exception java.net.SocketTimeoutException

Construct a new SocketTimeoutException with no detailed message.

SoftBevelBorder - Class in javax.swing.border

A class which implements a raised or lowered bevel with softened corners.

SoftBevelBorder(int) - Constructor for class javax.swing.border.SoftBevelBorder

Creates a bevel border with the specified type and whose colors will be derived from the background color of the component passed into the paintBorder method.

SoftBevelBorder(int, Color, Color) - Constructor for class javax.swing.border.SoftBevelBorder

Creates a bevel border with the specified type, highlight and shadow colors.

SoftBevelBorder(int, Color, Color, Color, Color) - Constructor for class javax.swing.border.SoftBevelBorder

Creates a bevel border with the specified type, highlight shadow colors.

SoftReference<T> - Class in java.lang.ref

Soft reference objects, which are cleared at the discretion of the garbage collector in response to memory demand.

SoftReference(T) - Constructor for class java.lang.ref.SoftReference

Creates a new soft reference that refers to the given object.

SoftReference(T, ReferenceQueue<? super T>) - Constructor for class java.lang.ref.SoftReference

Creates a new soft reference that refers to the given object and is registered with the given queue.

solveCubic(double[]) - Static method in class java.awt.geom.CubicCurve2D

Solves the cubic whose coefficients are in the eqn array and places the non-complex roots back into the same array, returning the number of roots.

solveCubic(double[], double[]) - Static method in class java.awt.geom.CubicCurve2D

Solve the cubic whose coefficients are in the eqn array and place the non-complex roots into the res array, returning the number of roots.

solveQuadratic(double[]) - Static method in class java.awt.geom.QuadCurve2D

Solves the quadratic whose coefficients are in the eqn array and places the non-complex roots back into the same array, returning the number of roots.

solveQuadratic(double[], double[]) - Static method in class java.awt.geom.QuadCurve2D

Solves the quadratic whose coefficients are in the eqn array and places the non-complex roots into the res array, returning the number of roots.

SOMEBITS - Static variable in interface java.awt.image.ImageObserver

This flag in the infoflags argument to imageUpdate indicates that more pixels needed for drawing a scaled variation of the image are available.

SONG_POSITION_POINTER - Static variable in class javax.sound.midi.ShortMessage

Status byte for Song Position Pointer message (0xF2, or 242).

SONG_SELECT - Static variable in class javax.sound.midi.ShortMessage

Status byte for MIDI Song Select message (0xF3, or 243).

sort(int[]) - Static method in class java.util.Arrays

Sorts the specified array into ascending numerical order.

sort(int[], int, int) - Static method in class java.util.Arrays

Sorts the specified range of the array into ascending order.

sort(long[]) - Static method in class java.util.Arrays

Sorts the specified array into ascending numerical order.

sort(long[], int, int) - Static method in class java.util.Arrays

Sorts the specified range of the array into ascending order.

sort(short[]) - Static method in class java.util.Arrays

Sorts the specified array into ascending numerical order.

sort(short[], int, int) - Static method in class java.util.Arrays

Sorts the specified range of the array into ascending order.

sort(char[]) - Static method in class java.util.Arrays

Sorts the specified array into ascending numerical order.

sort(char[], int, int) - Static method in class java.util.Arrays

Sorts the specified range of the array into ascending order.

sort(byte[]) - Static method in class java.util.Arrays

Sorts the specified array into ascending numerical order.

sort(byte[], int, int) - Static method in class java.util.Arrays

Sorts the specified range of the array into ascending order.

sort(float[]) - Static method in class java.util.Arrays

Sorts the specified array into ascending numerical order.

sort(float[], int, int) - Static method in class java.util.Arrays

Sorts the specified range of the array into ascending order.

sort(double[]) - Static method in class java.util.Arrays

Sorts the specified array into ascending numerical order.

sort(double[], int, int) - Static method in class java.util.Arrays

Sorts the specified range of the array into ascending order.

sort(Object[]) - Static method in class java.util.Arrays

Sorts the specified array of objects into ascending order, according to the natural ordering of its elements.

sort(Object[], int, int) - Static method in class java.util.Arrays

Sorts the specified range of the specified array of objects into ascending order, according to the natural ordering of its elements.

sort(T[], Comparator<? super T>) - Static method in class java.util.Arrays

Sorts the specified array of objects according to the order induced by the specified comparator.

sort(T[], int, int, Comparator<? super T>) - Static method in class java.util.Arrays

Sorts the specified range of the specified array of objects according to the order induced by the specified comparator.

sort(List<T>) - Static method in class java.util.Collections

Sorts the specified list into ascending order, according to the natural ordering of its elements.

sort(List<T>, Comparator<? super T>) - Static method in class java.util.Collections

Sorts the specified list according to the order induced by the specified comparator.

sort() - Method in class javax.swing.DefaultRowSorter

Sorts and filters the rows in the view based on the sort keys of the columns currently being sorted and the filter, if any, associated with this sorter.

sort(Vector<? extends File>) - Method in class javax.swing.plaf.basic.BasicDirectoryModel

SortControl - Class in javax.naming.ldap

Requests that the results of a search operation be sorted by the LDAP server before being returned.

SortControl(String, boolean) - Constructor for class javax.naming.ldap.SortControl

Constructs a control to sort on a single attribute in ascending order.

SortControl(String[], boolean) - Constructor for class javax.naming.ldap.SortControl

Constructs a control to sort on a list of attributes in ascending order.

SortControl(SortKey[], boolean) - Constructor for class javax.naming.ldap.SortControl

Constructs a control to sort on a list of sort keys.

SortedMap<K,V> - Interface in java.util

A Map that further provides a total ordering on its keys.

SortedSet<E> - Interface in java.util

A Set that further provides a total ordering on its elements.

sorterChanged(RowSorterEvent) - Method in interface javax.swing.event.RowSorterListener

Notification that the RowSorter has changed.

sorterChanged(RowSorterEvent) - Method in class javax.swing.JTable

RowSorterListener notification that the RowSorter has changed in some way.

SortingFocusTraversalPolicy - Class in javax.swing

A FocusTraversalPolicy that determines traversal order by sorting the Components of a focus traversal cycle based on a given Comparator.

SortingFocusTraversalPolicy() - Constructor for class javax.swing.SortingFocusTraversalPolicy

Constructs a SortingFocusTraversalPolicy without a Comparator.

SortingFocusTraversalPolicy(Comparator<? super Component>) - Constructor for class javax.swing.SortingFocusTraversalPolicy

Constructs a SortingFocusTraversalPolicy with the specified Comparator.

SortKey - Class in javax.naming.ldap

A sort key and its associated sort parameters.

SortKey(String) - Constructor for class javax.naming.ldap.SortKey

Creates the default sort key for an attribute.

SortKey(String, boolean, String) - Constructor for class javax.naming.ldap.SortKey

Creates a sort key for an attribute.

SortOrder - Enum in javax.swing

SortOrder is an enumeration of the possible sort orderings.

SortResponseControl - Class in javax.naming.ldap

Indicates whether the requested sort of search results was successful or not.

SortResponseControl(String, boolean, byte[]) - Constructor for class javax.naming.ldap.SortResponseControl

Constructs a control to indicate the outcome of a sort request.

Soundbank - Interface in javax.sound.midi

A Soundbank contains a set of Instruments that can be loaded into a Synthesizer.

SoundbankReader - Class in javax.sound.midi.spi

A SoundbankReader supplies soundbank file-reading services.

SoundbankReader() - Constructor for class javax.sound.midi.spi.SoundbankReader

SoundbankResource - Class in javax.sound.midi

A SoundbankResource represents any audio resource stored in a Soundbank.

SoundbankResource(Soundbank, String, Class<?>) - Constructor for class javax.sound.midi.SoundbankResource

Constructs a new SoundbankResource from the given sound bank and wavetable index.

source() - Method in class java.nio.channels.Pipe

Returns this pipe's source channel.

source - Variable in class java.util.EventObject

The object on which the Event initially occurred.

source - Variable in class javax.management.Notification

This field hides the EventObject.source field in the parent class to make it non-transient and therefore part of the serialized form.

source - Variable in class javax.swing.plaf.basic.BasicTreeUI.MouseInputHandler

Source that events are coming from.

Source - Interface in javax.xml.transform

An object that implements this interface contains the information needed to act as source input (XML source or transformation instructions).

sourceActions - Variable in class java.awt.dnd.DragGestureRecognizer

An int representing the type(s) of action(s) used in this Drag and Drop operation.

sourceAddress() - Method in class java.nio.channels.MembershipKey

Returns the source address if this membership key is source-specific, or null if this membership is not source-specific.

sourceBands - Variable in class javax.imageio.IIOParam

An array of ints indicating which source bands will be used, or null.

SourceDataLine - Interface in javax.sound.sampled

A source data line is a data line to which data may be written.

SourceLocator - Interface in javax.xml.transform

This interface is primarily for the purposes of reporting where an error occurred in the XML source or transformation instructions.

sourceRegion - Variable in class javax.imageio.IIOParam

The source region, on null if none is set.

sourceRenderSize - Variable in class javax.imageio.ImageReadParam

The desired rendering width and height of the source, if canSetSourceRenderSize is true, or null.

sources - Variable in class java.awt.image.renderable.ParameterBlock

A Vector of sources, stored as arbitrary Objects.

sourceToInputSource(Source) - Static method in class javax.xml.transform.sax.SAXSource

Attempt to obtain a SAX InputSource object from a Source object.

SourceVersion - Enum in javax.lang.model

Source versions of the Java™ programming language.

sourceXSubsampling - Variable in class javax.imageio.IIOParam

The decimation subsampling to be applied in the horizontal direction.

sourceYSubsampling - Variable in class javax.imageio.IIOParam

The decimation subsampling to be applied in the vertical direction.

SOUTH - Static variable in class java.awt.BorderLayout

The south layout constraint (bottom of container).

SOUTH - Static variable in class java.awt.GridBagConstraints

Put the component at the bottom of its display area, centered horizontally.

SOUTH - Static variable in class javax.swing.SpringLayout

Specifies the bottom edge of a component's bounding rectangle.

SOUTH - Static variable in interface javax.swing.SwingConstants

Compass-direction south (down).

SOUTH_EAST - Static variable in interface javax.swing.SwingConstants

Compass-direction south-east (lower right).

SOUTH_WEST - Static variable in interface javax.swing.SwingConstants

Compass-direction south-west (lower left).

SOUTHEAST - Static variable in class java.awt.GridBagConstraints

Put the component at the bottom-right corner of its display area.

southPane - Variable in class javax.swing.plaf.basic.BasicInternalFrameUI

SOUTHWEST - Static variable in class java.awt.GridBagConstraints

Put the component at the bottom-left corner of its display area.

SPACE - Static variable in interface javax.xml.stream.XMLStreamConstants

The characters are white space (see [XML], 2.10 "White Space Handling").

SPACE_SEPARATOR - Static variable in class java.lang.Character

General category "Zs" in the Unicode specification.

SpaceAbove - Static variable in class javax.swing.text.StyleConstants

The amount of space above the paragraph.

SpaceBelow - Static variable in class javax.swing.text.StyleConstants

The amount of space below the paragraph.

SPACING_MODIFIER_LETTERS - Static variable in class java.lang.Character.UnicodeBlock

Constant for the "Spacing Modifier Letters" Unicode character block.

SPAN - Static variable in class javax.swing.text.html.HTML.Tag

SPEAKER - Static variable in class javax.sound.sampled.Port.Info

A type of port that sends audio to a built-in speaker or a speaker jack.

SPECIAL_SYSTEM_EXCLUSIVE - Static variable in class javax.sound.midi.SysexMessage

Status byte for Special System Exclusive message (0xF7, or 247), which is used in MIDI files.

SPECIALS - Static variable in class java.lang.Character.UnicodeBlock

Constant for the "Specials" Unicode character block.

SPECIFICATION_TITLE - Static variable in class java.util.jar.Attributes.Name

Name object for Specification-Title manifest attribute used for package versioning.

SPECIFICATION_VENDOR - Static variable in class java.util.jar.Attributes.Name

Name object for Specification-Vendor manifest attribute used for package versioning.

SPECIFICATION_VERSION - Static variable in class java.util.jar.Attributes.Name

Name object for Specification-Version manifest attribute used for package versioning.

SPIN_BOX - Static variable in class javax.accessibility.AccessibleRole

A SPIN_BOX is a simple spinner component and its main use is for simple numbers.

spinner - Variable in class javax.swing.plaf.basic.BasicSpinnerUI

The spinner that we're a UI delegate for.

SPINNER - Static variable in class javax.swing.plaf.synth.Region

Spinner region.

SpinnerDateModel - Class in javax.swing

A SpinnerModel for sequences of Dates.

SpinnerDateModel(Date, Comparable, Comparable, int) - Constructor for class javax.swing.SpinnerDateModel

Creates a SpinnerDateModel that represents a sequence of dates between start and end.

SpinnerDateModel() - Constructor for class javax.swing.SpinnerDateModel

Constructs a SpinnerDateModel whose initial value is the current date, calendarField is equal to Calendar.DAY_OF_MONTH, and for which there are no start/end limits.

SpinnerListModel - Class in javax.swing

A simple implementation of SpinnerModel whose values are defined by an array or a List.

SpinnerListModel(List<?>) - Constructor for class javax.swing.SpinnerListModel

Constructs a SpinnerModel whose sequence of values is defined by the specified List.

SpinnerListModel(Object[]) - Constructor for class javax.swing.SpinnerListModel

Constructs a SpinnerModel whose sequence of values is defined by the specified array.

SpinnerListModel() - Constructor for class javax.swing.SpinnerListModel

Constructs an effectively empty SpinnerListModel.

SpinnerModel - Interface in javax.swing

A model for a potentially unbounded sequence of object values.

SpinnerNumberModel - Class in javax.swing

A SpinnerModel for sequences of numbers.

SpinnerNumberModel(Number, Comparable, Comparable, Number) - Constructor for class javax.swing.SpinnerNumberModel

Constructs a SpinnerModel that represents a closed sequence of numbers from minimum to maximum.

SpinnerNumberModel(int, int, int, int) - Constructor for class javax.swing.SpinnerNumberModel

Constructs a SpinnerNumberModel with the specified value, minimum/maximum bounds, and stepSize.

SpinnerNumberModel(double, double, double, double) - Constructor for class javax.swing.SpinnerNumberModel

Constructs a SpinnerNumberModel with the specified value, minimum/maximum bounds, and stepSize.

SpinnerNumberModel() - Constructor for class javax.swing.SpinnerNumberModel

Constructs a SpinnerNumberModel with no minimum or maximum value, stepSize equal to one, and an initial value of zero.

SpinnerUI - Class in javax.swing.plaf

Pluggable look and feel interface for JSpinner

SpinnerUI() - Constructor for class javax.swing.plaf.SpinnerUI

SplashScreen - Class in java.awt

The splash screen can be displayed at application startup, before the Java Virtual Machine (JVM) starts.

split(String, int) - Method in class java.lang.String

Splits this string around matches of the given regular expression.

split(String) - Method in class java.lang.String

Splits this string around matches of the given regular expression.

split(CharSequence, int) - Method in class java.util.regex.Pattern

Splits the given input sequence around matches of this pattern.

split(CharSequence) - Method in class java.util.regex.Pattern

Splits the given input sequence around matches of this pattern.

SPLIT_PANE - Static variable in class javax.accessibility.AccessibleRole

A specialized panel that presents two other panels at the same time.

SPLIT_PANE - Static variable in class javax.swing.plaf.synth.Region

SplitPane region.

SPLIT_PANE_DIVIDER - Static variable in class javax.swing.plaf.synth.Region

Divider of the SplitPane.

splitPane - Variable in class javax.swing.plaf.basic.BasicSplitPaneDivider

JSplitPane the receiver is contained in.

splitPane - Variable in class javax.swing.plaf.basic.BasicSplitPaneUI

JSplitPane instance this instance is providing the look and feel for.

splitPaneUI - Variable in class javax.swing.plaf.basic.BasicSplitPaneDivider

UI this instance was created from.

SplitPaneUI - Class in javax.swing.plaf

Pluggable look and feel interface for JSplitPane.

SplitPaneUI() - Constructor for class javax.swing.plaf.SplitPaneUI

splitText(int) - Method in interface org.w3c.dom.Text

Breaks this node into two nodes at the specified offset, keeping both in the tree as siblings.

SPOOL_AREA_FULL - Static variable in class javax.print.attribute.standard.PrinterStateReason

The limit of persistent storage allocated for spooling has been reached.

spPropertyChangeListener - Variable in class javax.swing.plaf.basic.BasicScrollPaneUI

spreadInvoker(MethodType, int) - Static method in class java.lang.invoke.MethodHandles

Produces a method handle which will invoke any method handle of the given type on a standard set of Object type arguments and a single trailing Object[] array.

Spring - Class in javax.swing

An instance of the Spring class holds three properties that characterize its behavior: the minimum, preferred, and maximum values.

Spring() - Constructor for class javax.swing.Spring

Used by factory methods to create a Spring.

SpringLayout - Class in javax.swing

A SpringLayout lays out the children of its associated container according to a set of constraints.

SpringLayout() - Constructor for class javax.swing.SpringLayout

Constructs a new SpringLayout.

SpringLayout.Constraints - Class in javax.swing

A Constraints object holds the constraints that govern the way a component's size and position change in a container controlled by a SpringLayout.

SpringLayout.Constraints() - Constructor for class javax.swing.SpringLayout.Constraints

Creates an empty Constraints object.

SpringLayout.Constraints(Spring, Spring) - Constructor for class javax.swing.SpringLayout.Constraints

Creates a Constraints object with the specified values for its x and y properties.

SpringLayout.Constraints(Spring, Spring, Spring, Spring) - Constructor for class javax.swing.SpringLayout.Constraints

Creates a Constraints object with the specified values for its x, y, width, and height properties.

SpringLayout.Constraints(Component) - Constructor for class javax.swing.SpringLayout.Constraints

Creates a Constraints object with suitable x, y, width and height springs for component, c.

SQLClientInfoException - Exception in java.sql

The subclass of SQLException is thrown when one or more client info properties could not be set on a Connection.

SQLClientInfoException() - Constructor for exception java.sql.SQLClientInfoException

Constructs a SQLClientInfoException Object.

SQLClientInfoException(Map<String, ClientInfoStatus>) - Constructor for exception java.sql.SQLClientInfoException

Constructs a SQLClientInfoException object initialized with a given failedProperties.

SQLClientInfoException(Map<String, ClientInfoStatus>, Throwable) - Constructor for exception java.sql.SQLClientInfoException

Constructs a SQLClientInfoException object initialized with a given cause and failedProperties.

SQLClientInfoException(String, Map<String, ClientInfoStatus>) - Constructor for exception java.sql.SQLClientInfoException

Constructs a SQLClientInfoException object initialized with a given reason and failedProperties.

SQLClientInfoException(String, Map<String, ClientInfoStatus>, Throwable) - Constructor for exception java.sql.SQLClientInfoException

Constructs a SQLClientInfoException object initialized with a given reason, cause and failedProperties.

SQLClientInfoException(String, String, Map<String, ClientInfoStatus>) - Constructor for exception java.sql.SQLClientInfoException

Constructs a SQLClientInfoException object initialized with a given reason, SQLState and failedProperties.

SQLClientInfoException(String, String, Map<String, ClientInfoStatus>, Throwable) - Constructor for exception java.sql.SQLClientInfoException

Constructs a SQLClientInfoException object initialized with a given reason, SQLState, cause and failedProperties.

SQLClientInfoException(String, String, int, Map<String, ClientInfoStatus>) - Constructor for exception java.sql.SQLClientInfoException

Constructs a SQLClientInfoException object initialized with a given reason, SQLState, vendorCode and failedProperties.

SQLClientInfoException(String, String, int, Map<String, ClientInfoStatus>, Throwable) - Constructor for exception java.sql.SQLClientInfoException

Constructs a SQLClientInfoException object initialized with a given reason, SQLState, cause, vendorCode and failedProperties.

SQLData - Interface in java.sql

The interface used for the custom mapping of an SQL user-defined type (UDT) to a class in the Java programming language.

SQLDataException - Exception in java.sql

The subclass of SQLException thrown when the SQLState class value is '22', or under vendor-specified conditions.

SQLDataException() - Constructor for exception java.sql.SQLDataException

Constructs a SQLDataException object.

SQLDataException(String) - Constructor for exception java.sql.SQLDataException

Constructs a SQLDataException object with a given reason.

SQLDataException(String, String) - Constructor for exception java.sql.SQLDataException

Constructs a SQLDataException object with a given reason and SQLState.

SQLDataException(String, String, int) - Constructor for exception java.sql.SQLDataException

Constructs a SQLDataException object with a given reason, SQLState and vendorCode.

SQLDataException(Throwable) - Constructor for exception java.sql.SQLDataException

Constructs a SQLDataException object with a given cause.

SQLDataException(String, Throwable) - Constructor for exception java.sql.SQLDataException

Constructs a SQLDataException object with a given reason and cause.

SQLDataException(String, String, Throwable) - Constructor for exception java.sql.SQLDataException

Constructs a SQLDataException object with a given reason, SQLState and cause.

SQLDataException(String, String, int, Throwable) - Constructor for exception java.sql.SQLDataException

Constructs a SQLDataException object with a given reason, SQLState, vendorCode and cause.

SQLException - Exception in java.sql

An exception that provides information on a database access error or other errors.

SQLException(String, String, int) - Constructor for exception java.sql.SQLException

Constructs a SQLException object with a given reason, SQLState and vendorCode.

SQLException(String, String) - Constructor for exception java.sql.SQLException

Constructs a SQLException object with a given reason and SQLState.

SQLException(String) - Constructor for exception java.sql.SQLException

Constructs a SQLException object with a given reason.

SQLException() - Constructor for exception java.sql.SQLException

Constructs a SQLException object.

SQLException(Throwable) - Constructor for exception java.sql.SQLException

Constructs a SQLException object with a given cause.

SQLException(String, Throwable) - Constructor for exception java.sql.SQLException

Constructs a SQLException object with a given reason and cause.

SQLException(String, String, Throwable) - Constructor for exception java.sql.SQLException

Constructs a SQLException object with a given reason, SQLState and cause.

SQLException(String, String, int, Throwable) - Constructor for exception java.sql.SQLException

Constructs a SQLException object with a given reason, SQLState, vendorCode and cause.

SQLFeatureNotSupportedException - Exception in java.sql

The subclass of SQLException thrown when the SQLState class value is '0A' ( the value is 'zero' A).

SQLFeatureNotSupportedException() - Constructor for exception java.sql.SQLFeatureNotSupportedException

Constructs a SQLFeatureNotSupportedException object.

SQLFeatureNotSupportedException(String) - Constructor for exception java.sql.SQLFeatureNotSupportedException

Constructs a SQLFeatureNotSupportedException object with a given reason.

SQLFeatureNotSupportedException(String, String) - Constructor for exception java.sql.SQLFeatureNotSupportedException

Constructs a SQLFeatureNotSupportedException object with a given reason and SQLState.

SQLFeatureNotSupportedException(String, String, int) - Constructor for exception java.sql.SQLFeatureNotSupportedException

Constructs a SQLFeatureNotSupportedException object with a given reason, SQLState and vendorCode.

SQLFeatureNotSupportedException(Throwable) - Constructor for exception java.sql.SQLFeatureNotSupportedException

Constructs a SQLFeatureNotSupportedException object with a given cause.

SQLFeatureNotSupportedException(String, Throwable) - Constructor for exception java.sql.SQLFeatureNotSupportedException

Constructs a SQLFeatureNotSupportedException object with a given reason and cause.

SQLFeatureNotSupportedException(String, String, Throwable) - Constructor for exception java.sql.SQLFeatureNotSupportedException

Constructs a SQLFeatureNotSupportedException object with a given reason, SQLState and cause.

SQLFeatureNotSupportedException(String, String, int, Throwable) - Constructor for exception java.sql.SQLFeatureNotSupportedException

Constructs a SQLFeatureNotSupportedException object with a given reason, SQLState, vendorCode and cause.

SQLInput - Interface in java.sql

An input stream that contains a stream of values representing an instance of an SQL structured type or an SQL distinct type.

SQLInputImpl - Class in javax.sql.rowset.serial

An input stream used for custom mapping user-defined types (UDTs).

SQLInputImpl(Object[], Map<String, Class<?>>) - Constructor for class javax.sql.rowset.serial.SQLInputImpl

Creates an SQLInputImpl object initialized with the given array of attributes and the given type map.

SQLIntegrityConstraintViolationException - Exception in java.sql

The subclass of SQLException thrown when the SQLState class value is '23', or under vendor-specified conditions.

SQLIntegrityConstraintViolationException() - Constructor for exception java.sql.SQLIntegrityConstraintViolationException

Constructs a SQLIntegrityConstraintViolationException object.

SQLIntegrityConstraintViolationException(String) - Constructor for exception java.sql.SQLIntegrityConstraintViolationException

Constructs a SQLIntegrityConstraintViolationException with a given reason.

SQLIntegrityConstraintViolationException(String, String) - Constructor for exception java.sql.SQLIntegrityConstraintViolationException

Constructs a SQLIntegrityConstraintViolationException object with a given reason and SQLState.

SQLIntegrityConstraintViolationException(String, String, int) - Constructor for exception java.sql.SQLIntegrityConstraintViolationException

Constructs a SQLIntegrityConstraintViolationException object with a given reason, SQLState and vendorCode.

SQLIntegrityConstraintViolationException(Throwable) - Constructor for exception java.sql.SQLIntegrityConstraintViolationException

Constructs an SQLIntegrityConstraintViolationException object with a given cause.

SQLIntegrityConstraintViolationException(String, Throwable) - Constructor for exception java.sql.SQLIntegrityConstraintViolationException

Constructs a SQLIntegrityConstraintViolationException object with a given reason and cause.

SQLIntegrityConstraintViolationException(String, String, Throwable) - Constructor for exception java.sql.SQLIntegrityConstraintViolationException

Constructs a SQLIntegrityConstraintViolationException object with a given reason, SQLState and cause.

SQLIntegrityConstraintViolationException(String, String, int, Throwable) - Constructor for exception java.sql.SQLIntegrityConstraintViolationException

Constructs a SQLIntegrityConstraintViolationException object with a given reason, SQLState, vendorCode and cause.

SQLInvalidAuthorizationSpecException - Exception in java.sql

The subclass of SQLException thrown when the SQLState class value is '28', or under vendor-specified conditions.

SQLInvalidAuthorizationSpecException() - Constructor for exception java.sql.SQLInvalidAuthorizationSpecException

Constructs a SQLInvalidAuthorizationSpecException object.

SQLInvalidAuthorizationSpecException(String) - Constructor for exception java.sql.SQLInvalidAuthorizationSpecException

Constructs a SQLInvalidAuthorizationSpecException object with a given reason.

SQLInvalidAuthorizationSpecException(String, String) - Constructor for exception java.sql.SQLInvalidAuthorizationSpecException

Constructs a SQLInvalidAuthorizationSpecException object with a given reason and SQLState.

SQLInvalidAuthorizationSpecException(String, String, int) - Constructor for exception java.sql.SQLInvalidAuthorizationSpecException

Constructs a SQLInvalidAuthorizationSpecException object with a given reason, SQLState and vendorCode.

SQLInvalidAuthorizationSpecException(Throwable) - Constructor for exception java.sql.SQLInvalidAuthorizationSpecException

Constructs a SQLInvalidAuthorizationSpecException object with a given cause.

SQLInvalidAuthorizationSpecException(String, Throwable) - Constructor for exception java.sql.SQLInvalidAuthorizationSpecException

Constructs a SQLInvalidAuthorizationSpecException object with a given reason and cause.

SQLInvalidAuthorizationSpecException(String, String, Throwable) - Constructor for exception java.sql.SQLInvalidAuthorizationSpecException

Constructs a SQLInvalidAuthorizationSpecException object with a given reason, SQLState and cause.

SQLInvalidAuthorizationSpecException(String, String, int, Throwable) - Constructor for exception java.sql.SQLInvalidAuthorizationSpecException

Constructs a SQLInvalidAuthorizationSpecException object with a given reason, SQLState, vendorCode and cause.

SQLNonTransientConnectionException - Exception in java.sql

The subclass of SQLException thrown for the SQLState class value '08', or under vendor-specified conditions.

SQLNonTransientConnectionException() - Constructor for exception java.sql.SQLNonTransientConnectionException

Constructs a SQLNonTransientConnectionException object.

SQLNonTransientConnectionException(String) - Constructor for exception java.sql.SQLNonTransientConnectionException

Constructs a SQLNonTransientConnectionException object with a given reason.

SQLNonTransientConnectionException(String, String) - Constructor for exception java.sql.SQLNonTransientConnectionException

Constructs a SQLNonTransientConnectionException object with a given reason and SQLState.

SQLNonTransientConnectionException(String, String, int) - Constructor for exception java.sql.SQLNonTransientConnectionException

Constructs a SQLNonTransientConnectionException object with a given reason, SQLState and vendorCode.

SQLNonTransientConnectionException(Throwable) - Constructor for exception java.sql.SQLNonTransientConnectionException

Constructs a SQLNonTransientConnectionException object with a given cause.

SQLNonTransientConnectionException(String, Throwable) - Constructor for exception java.sql.SQLNonTransientConnectionException

Constructs a SQLTransientException object with a given reason and cause.

SQLNonTransientConnectionException(String, String, Throwable) - Constructor for exception java.sql.SQLNonTransientConnectionException

Constructs a SQLNonTransientConnectionException object with a given reason, SQLState and cause.

SQLNonTransientConnectionException(String, String, int, Throwable) - Constructor for exception java.sql.SQLNonTransientConnectionException

Constructs a SQLNonTransientConnectionException object with a given reason, SQLState, vendorCode and cause.

SQLNonTransientException - Exception in java.sql

The subclass of SQLException thrown when an instance where a retry of the same operation would fail unless the cause of the SQLException is corrected.

SQLNonTransientException() - Constructor for exception java.sql.SQLNonTransientException

Constructs a SQLNonTransientException object.

SQLNonTransientException(String) - Constructor for exception java.sql.SQLNonTransientException

Constructs a SQLNonTransientException object with a given reason.

SQLNonTransientException(String, String) - Constructor for exception java.sql.SQLNonTransientException

Constructs a SQLNonTransientException object with a given reason and SQLState.

SQLNonTransientException(String, String, int) - Constructor for exception java.sql.SQLNonTransientException

Constructs a SQLNonTransientException object with a given reason, SQLState and vendorCode.

SQLNonTransientException(Throwable) - Constructor for exception java.sql.SQLNonTransientException

Constructs a SQLNonTransientException object with a given cause.

SQLNonTransientException(String, Throwable) - Constructor for exception java.sql.SQLNonTransientException

Constructs a SQLTransientException object with a given reason and cause.

SQLNonTransientException(String, String, Throwable) - Constructor for exception java.sql.SQLNonTransientException

Constructs a SQLNonTransientException object with a given reason, SQLState and cause.

SQLNonTransientException(String, String, int, Throwable) - Constructor for exception java.sql.SQLNonTransientException

Constructs a SQLNonTransientException object with a given reason, SQLState, vendorCode and cause.

SQLOutput - Interface in java.sql

The output stream for writing the attributes of a user-defined type back to the database.

SQLOutputImpl - Class in javax.sql.rowset.serial

The output stream for writing the attributes of a custom-mapped user-defined type (UDT) back to the database.

SQLOutputImpl(Vector<?>, Map<String, ?>) - Constructor for class javax.sql.rowset.serial.SQLOutputImpl

Creates a new SQLOutputImpl object initialized with the given vector of attributes and type map.

SQLPermission - Class in java.sql

The permission for which the SecurityManager will check when code that is running in an applet, or an application with a SecurityManager enabled, calls the DriverManager.setLogWriter method, DriverManager.setLogStream (deprecated) method, SyncFactory.setJNDIContext method, SyncFactory.setLogger method, Connection.setNetworktimeout method, or the Connection.abort method.

SQLPermission(String) - Constructor for class java.sql.SQLPermission

Creates a new SQLPermission object with the specified name.

SQLPermission(String, String) - Constructor for class java.sql.SQLPermission

Creates a new SQLPermission object with the specified name.

SQLRecoverableException - Exception in java.sql

The subclass of SQLException thrown in situations where a previously failed operation might be able to succeed if the application performs some recovery steps and retries the entire transaction or in the case of a distributed transaction, the transaction branch.

SQLRecoverableException() - Constructor for exception java.sql.SQLRecoverableException

Constructs a SQLRecoverableException object.

SQLRecoverableException(String) - Constructor for exception java.sql.SQLRecoverableException

Constructs a SQLRecoverableException object with a given reason.

SQLRecoverableException(String, String) - Constructor for exception java.sql.SQLRecoverableException

Constructs a SQLRecoverableException object with a given reason and SQLState.

SQLRecoverableException(String, String, int) - Constructor for exception java.sql.SQLRecoverableException

Constructs a SQLRecoverableException object with a given reason, SQLState and vendorCode.

SQLRecoverableException(Throwable) - Constructor for exception java.sql.SQLRecoverableException

Constructs a SQLRecoverableException object with a given cause.

SQLRecoverableException(String, Throwable) - Constructor for exception java.sql.SQLRecoverableException

Constructs a SQLRecoverableException object with a given reason and cause.

SQLRecoverableException(String, String, Throwable) - Constructor for exception java.sql.SQLRecoverableException

Constructs a SQLRecoverableException object with a given reason, SQLState and cause.

SQLRecoverableException(String, String, int, Throwable) - Constructor for exception java.sql.SQLRecoverableException

Constructs a SQLRecoverableException object with a given reason, SQLState, vendorCode and cause.

sqlStateSQL - Static variable in interface java.sql.DatabaseMetaData

A possible return value for the method DatabaseMetaData.getSQLStateType which is used to indicate whether the value returned by the method SQLException.getSQLState is an SQLSTATE value.

sqlStateSQL99 - Static variable in interface java.sql.DatabaseMetaData

A possible return value for the method DatabaseMetaData.getSQLStateType which is used to indicate whether the value returned by the method SQLException.getSQLState is an SQL99 SQLSTATE value.

sqlStateXOpen - Static variable in interface java.sql.DatabaseMetaData

A possible return value for the method DatabaseMetaData.getSQLStateType which is used to indicate whether the value returned by the method SQLException.getSQLState is an X/Open (now know as Open Group) SQL CLI SQLSTATE value.

SQLSyntaxErrorException - Exception in java.sql

The subclass of SQLException thrown when the SQLState class value is '42', or under vendor-specified conditions.

SQLSyntaxErrorException() - Constructor for exception java.sql.SQLSyntaxErrorException

Constructs a SQLSyntaxErrorException object.

SQLSyntaxErrorException(String) - Constructor for exception java.sql.SQLSyntaxErrorException

Constructs a SQLSyntaxErrorException object with a given reason.

SQLSyntaxErrorException(String, String) - Constructor for exception java.sql.SQLSyntaxErrorException

Constructs a SQLSyntaxErrorException object with a given reason and SQLState.

SQLSyntaxErrorException(String, String, int) - Constructor for exception java.sql.SQLSyntaxErrorException

Constructs a SQLSyntaxErrorException object with a given reason, SQLState and vendorCode.

SQLSyntaxErrorException(Throwable) - Constructor for exception java.sql.SQLSyntaxErrorException

Constructs a SQLSyntaxErrorException object with a given cause.

SQLSyntaxErrorException(String, Throwable) - Constructor for exception java.sql.SQLSyntaxErrorException

Constructs a SQLSyntaxErrorException object with a given reason and cause.

SQLSyntaxErrorException(String, String, Throwable) - Constructor for exception java.sql.SQLSyntaxErrorException

Constructs a SQLSyntaxErrorException object with a given reason, SQLState and cause.

SQLSyntaxErrorException(String, String, int, Throwable) - Constructor for exception java.sql.SQLSyntaxErrorException

Constructs a SQLSyntaxErrorException object with a given reason, SQLState, vendorCode and cause.

SQLTimeoutException - Exception in java.sql

The subclass of SQLException thrown when the timeout specified by Statement has expired.

SQLTimeoutException() - Constructor for exception java.sql.SQLTimeoutException

Constructs a SQLTimeoutException object.

SQLTimeoutException(String) - Constructor for exception java.sql.SQLTimeoutException

Constructs a SQLTimeoutException object with a given reason.

SQLTimeoutException(String, String) - Constructor for exception java.sql.SQLTimeoutException

Constructs a SQLTimeoutException object with a given reason and SQLState.

SQLTimeoutException(String, String, int) - Constructor for exception java.sql.SQLTimeoutException

Constructs a SQLTimeoutException object with a given reason, SQLState and vendorCode.

SQLTimeoutException(Throwable) - Constructor for exception java.sql.SQLTimeoutException

Constructs a SQLTimeoutException object with a given cause.

SQLTimeoutException(String, Throwable) - Constructor for exception java.sql.SQLTimeoutException

Constructs a SQLTimeoutException object with a given reason and cause.

SQLTimeoutException(String, String, Throwable) - Constructor for exception java.sql.SQLTimeoutException

Constructs a SQLTimeoutException object with a given reason, SQLState and cause.

SQLTimeoutException(String, String, int, Throwable) - Constructor for exception java.sql.SQLTimeoutException

Constructs a SQLTimeoutException object with a given reason, SQLState, vendorCode and cause.

SQLTransactionRollbackException - Exception in java.sql

The subclass of SQLException thrown when the SQLState class value is '40', or under vendor-specified conditions.

SQLTransactionRollbackException() - Constructor for exception java.sql.SQLTransactionRollbackException

Constructs a SQLTransactionRollbackException object.

SQLTransactionRollbackException(String) - Constructor for exception java.sql.SQLTransactionRollbackException

Constructs a SQLTransactionRollbackException object with a given reason.

SQLTransactionRollbackException(String, String) - Constructor for exception java.sql.SQLTransactionRollbackException

Constructs a SQLTransactionRollbackException object with a given reason and SQLState.

SQLTransactionRollbackException(String, String, int) - Constructor for exception java.sql.SQLTransactionRollbackException

Constructs a SQLTransactionRollbackException object with a given reason, SQLState and vendorCode.

SQLTransactionRollbackException(Throwable) - Constructor for exception java.sql.SQLTransactionRollbackException

Constructs a SQLTransactionRollbackException object with a given cause.

SQLTransactionRollbackException(String, Throwable) - Constructor for exception java.sql.SQLTransactionRollbackException

Constructs a SQLTransactionRollbackException object with a given reason and cause.

SQLTransactionRollbackException(String, String, Throwable) - Constructor for exception java.sql.SQLTransactionRollbackException

Constructs a SQLTransactionRollbackException object with a given reason, SQLState and cause.

SQLTransactionRollbackException(String, String, int, Throwable) - Constructor for exception java.sql.SQLTransactionRollbackException

Constructs a SQLTransactionRollbackException object with a given reason, SQLState, vendorCode and cause.

SQLTransientConnectionException - Exception in java.sql

The subclass of SQLException for the SQLState class value '08', or under vendor-specified conditions.

SQLTransientConnectionException() - Constructor for exception java.sql.SQLTransientConnectionException

Constructs a SQLTransientConnectionException object.

SQLTransientConnectionException(String) - Constructor for exception java.sql.SQLTransientConnectionException

Constructs a SQLTransientConnectionException object with a given reason.

SQLTransientConnectionException(String, String) - Constructor for exception java.sql.SQLTransientConnectionException

Constructs a SQLTransientConnectionException object with a given reason and SQLState.

SQLTransientConnectionException(String, String, int) - Constructor for exception java.sql.SQLTransientConnectionException

Constructs a SQLTransientConnectionException object with a given reason, SQLState and vendorCode.

SQLTransientConnectionException(Throwable) - Constructor for exception java.sql.SQLTransientConnectionException

Constructs a SQLTransientConnectionException object with a given cause.

SQLTransientConnectionException(String, Throwable) - Constructor for exception java.sql.SQLTransientConnectionException

Constructs a SQLTransientConnectionException object with a given reason and cause.

SQLTransientConnectionException(String, String, Throwable) - Constructor for exception java.sql.SQLTransientConnectionException

Constructs a SQLTransientConnectionException object with a given reason, SQLState and cause.

SQLTransientConnectionException(String, String, int, Throwable) - Constructor for exception java.sql.SQLTransientConnectionException

Constructs a SQLTransientConnectionException object with a given reason, SQLState, vendorCode and cause.

SQLTransientException - Exception in java.sql

The subclass of SQLException is thrown in situations where a previoulsy failed operation might be able to succeed when the operation is retried without any intervention by application-level functionality.

SQLTransientException() - Constructor for exception java.sql.SQLTransientException

Constructs a SQLTransientException object.

SQLTransientException(String) - Constructor for exception java.sql.SQLTransientException

Constructs a SQLTransientException object with a given reason.

SQLTransientException(String, String) - Constructor for exception java.sql.SQLTransientException

Constructs a SQLTransientException object with a given reason and SQLState.

SQLTransientException(String, String, int) - Constructor for exception java.sql.SQLTransientException

Constructs a SQLTransientException object with a given reason, SQLState and vendorCode.

SQLTransientException(Throwable) - Constructor for exception java.sql.SQLTransientException

Constructs a SQLTransientException object with a given cause.

SQLTransientException(String, Throwable) - Constructor for exception java.sql.SQLTransientException

Constructs a SQLTransientException object with a given reason and cause.

SQLTransientException(String, String, Throwable) - Constructor for exception java.sql.SQLTransientException

Constructs a SQLTransientException object with a given reason, SQLState and cause.

SQLTransientException(String, String, int, Throwable) - Constructor for exception java.sql.SQLTransientException

Constructs a SQLTransientException object with a given reason, SQLState, vendorCode and cause.

SQLWarning - Exception in java.sql

An exception that provides information on database access warnings.

SQLWarning(String, String, int) - Constructor for exception java.sql.SQLWarning

Constructs a SQLWarning object with a given reason, SQLState and vendorCode.

SQLWarning(String, String) - Constructor for exception java.sql.SQLWarning

Constructs a SQLWarning object with a given reason and SQLState.

SQLWarning(String) - Constructor for exception java.sql.SQLWarning

Constructs a SQLWarning object with a given reason.

SQLWarning() - Constructor for exception java.sql.SQLWarning

Constructs a SQLWarning object.

SQLWarning(Throwable) - Constructor for exception java.sql.SQLWarning

Constructs a SQLWarning object with a given cause.

SQLWarning(String, Throwable) - Constructor for exception java.sql.SQLWarning

Constructs a SQLWarning object with a given reason and cause.

SQLWarning(String, String, Throwable) - Constructor for exception java.sql.SQLWarning

Constructs a SQLWarning object with a given reason, SQLState and cause.

SQLWarning(String, String, int, Throwable) - Constructor for exception java.sql.SQLWarning

Constructs aSQLWarning object with a given reason, SQLState, vendorCode and cause.

SQLXML - Interface in java.sql

The mapping in the JavaTM programming language for the SQL XML type.

SQLXML - Static variable in class java.sql.Types

The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type XML.

sqrt(double) - Static method in class java.lang.Math

Returns the correctly rounded positive square root of a double value.

sqrt(double) - Static method in class java.lang.StrictMath

Returns the correctly rounded positive square root of a double value.

squareButton - Variable in class javax.swing.plaf.basic.BasicComboBoxUI

Indicates whether or not the combo box button should be square.

SRC - Static variable in class java.awt.AlphaComposite

The source is copied to the destination (Porter-Duff Source rule).

Src - Static variable in class java.awt.AlphaComposite

AlphaComposite object that implements the opaque SRC rule with an alpha of 1.0f.

SRC - Static variable in class javax.swing.text.html.HTML.Attribute

SRC_ATOP - Static variable in class java.awt.AlphaComposite

The part of the source lying inside of the destination is composited onto the destination (Porter-Duff Source Atop Destination rule).

SRC_IN - Static variable in class java.awt.AlphaComposite

The part of the source lying inside of the destination replaces the destination (Porter-Duff Source In Destination rule).

SRC_OUT - Static variable in class java.awt.AlphaComposite

The part of the source lying outside of the destination replaces the destination (Porter-Duff Source Held Out By Destination rule).

SRC_OVER - Static variable in class java.awt.AlphaComposite

The source is composited over the destination (Porter-Duff Source Over Destination rule).

SrcAtop - Static variable in class java.awt.AlphaComposite

AlphaComposite object that implements the opaque SRC_ATOP rule with an alpha of 1.0f.

srccols - Variable in class java.awt.image.ReplicateScaleFilter

An int array containing information about a column of pixels.

srcHeight - Variable in class java.awt.image.ReplicateScaleFilter

The height of the source image.

SrcIn - Static variable in class java.awt.AlphaComposite

AlphaComposite object that implements the opaque SRC_IN rule with an alpha of 1.0f.

SrcOut - Static variable in class java.awt.AlphaComposite

AlphaComposite object that implements the opaque SRC_OUT rule with an alpha of 1.0f.

SrcOver - Static variable in class java.awt.AlphaComposite

AlphaComposite object that implements the opaque SRC_OVER rule with an alpha of 1.0f.

srcrows - Variable in class java.awt.image.ReplicateScaleFilter

An int array containing information about a row of pixels.

srcWidth - Variable in class java.awt.image.ReplicateScaleFilter

The width of the source image.

SSLContext - Class in javax.net.ssl

Instances of this class represent a secure socket protocol implementation which acts as a factory for secure socket factories or SSLEngines.

SSLContext(SSLContextSpi, Provider, String) - Constructor for class javax.net.ssl.SSLContext

Creates an SSLContext object.

SSLContextSpi - Class in javax.net.ssl

This class defines the Service Provider Interface (SPI) for the SSLContext class.

SSLContextSpi() - Constructor for class javax.net.ssl.SSLContextSpi

SSLEngine - Class in javax.net.ssl

A class which enables secure communications using protocols such as the Secure Sockets Layer (SSL) or IETF RFC 2246 "Transport Layer Security" (TLS) protocols, but is transport independent.

SSLEngine() - Constructor for class javax.net.ssl.SSLEngine

Constructor for an SSLEngine providing no hints for an internal session reuse strategy.

SSLEngine(String, int) - Constructor for class javax.net.ssl.SSLEngine

Constructor for an SSLEngine.

SSLEngineResult - Class in javax.net.ssl

An encapsulation of the result state produced by SSLEngine I/O calls.

SSLEngineResult(SSLEngineResult.Status, SSLEngineResult.HandshakeStatus, int, int) - Constructor for class javax.net.ssl.SSLEngineResult

Initializes a new instance of this class.

SSLEngineResult.HandshakeStatus - Enum in javax.net.ssl

An SSLEngineResult enum describing the current handshaking state of this SSLEngine.

SSLEngineResult.Status - Enum in javax.net.ssl

An SSLEngineResult enum describing the overall result of the SSLEngine operation.

SSLException - Exception in javax.net.ssl

Indicates some kind of error detected by an SSL subsystem.

SSLException(String) - Constructor for exception javax.net.ssl.SSLException

Constructs an exception reporting an error found by an SSL subsystem.

SSLException(String, Throwable) - Constructor for exception javax.net.ssl.SSLException

Creates a SSLException with the specified detail message and cause.

SSLException(Throwable) - Constructor for exception javax.net.ssl.SSLException

Creates a SSLException with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).

SSLHandshakeException - Exception in javax.net.ssl

Indicates that the client and server could not negotiate the desired level of security.

SSLHandshakeException(String) - Constructor for exception javax.net.ssl.SSLHandshakeException

Constructs an exception reporting an error found by an SSL subsystem during handshaking.

SSLKeyException - Exception in javax.net.ssl

Reports a bad SSL key.

SSLKeyException(String) - Constructor for exception javax.net.ssl.SSLKeyException

Constructs an exception reporting a key management error found by an SSL subsystem.

SSLParameters - Class in javax.net.ssl

Encapsulates parameters for an SSL/TLS connection.

SSLParameters() - Constructor for class javax.net.ssl.SSLParameters

Constructs SSLParameters.

SSLParameters(String[]) - Constructor for class javax.net.ssl.SSLParameters

Constructs SSLParameters from the specified array of ciphersuites.

SSLParameters(String[], String[]) - Constructor for class javax.net.ssl.SSLParameters

Constructs SSLParameters from the specified array of ciphersuites and protocols.

SSLPeerUnverifiedException - Exception in javax.net.ssl

Indicates that the peer's identity has not been verified.

SSLPeerUnverifiedException(String) - Constructor for exception javax.net.ssl.SSLPeerUnverifiedException

Constructs an exception reporting that the SSL peer's identity has not been verifiied.

SSLPermission - Class in javax.net.ssl

This class is for various network permissions.

SSLPermission(String) - Constructor for class javax.net.ssl.SSLPermission

Creates a new SSLPermission with the specified name.

SSLPermission(String, String) - Constructor for class javax.net.ssl.SSLPermission

Creates a new SSLPermission object with the specified name.

SSLProtocolException - Exception in javax.net.ssl

Reports an error in the operation of the SSL protocol.

SSLProtocolException(String) - Constructor for exception javax.net.ssl.SSLProtocolException

Constructs an exception reporting an SSL protocol error detected by an SSL subsystem.

SslRMIClientSocketFactory - Class in javax.rmi.ssl

An SslRMIClientSocketFactory instance is used by the RMI runtime in order to obtain client sockets for RMI calls via SSL.

SslRMIClientSocketFactory() - Constructor for class javax.rmi.ssl.SslRMIClientSocketFactory

Creates a new SslRMIClientSocketFactory.

SslRMIServerSocketFactory - Class in javax.rmi.ssl

An SslRMIServerSocketFactory instance is used by the RMI runtime in order to obtain server sockets for RMI calls via SSL.

SslRMIServerSocketFactory() - Constructor for class javax.rmi.ssl.SslRMIServerSocketFactory

Creates a new SslRMIServerSocketFactory with the default SSL socket configuration.

SslRMIServerSocketFactory(String[], String[], boolean) - Constructor for class javax.rmi.ssl.SslRMIServerSocketFactory

Creates a new SslRMIServerSocketFactory with the specified SSL socket configuration.

SslRMIServerSocketFactory(SSLContext, String[], String[], boolean) - Constructor for class javax.rmi.ssl.SslRMIServerSocketFactory

Creates a new SslRMIServerSocketFactory with the specified SSLContext and SSL socket configuration.

SSLServerSocket - Class in javax.net.ssl

This class extends ServerSockets and provides secure server sockets using protocols such as the Secure Sockets Layer (SSL) or Transport Layer Security (TLS) protocols.

SSLServerSocket() - Constructor for class javax.net.ssl.SSLServerSocket

Used only by subclasses.

SSLServerSocket(int) - Constructor for class javax.net.ssl.SSLServerSocket

Used only by subclasses.

SSLServerSocket(int, int) - Constructor for class javax.net.ssl.SSLServerSocket

Used only by subclasses.

SSLServerSocket(int, int, InetAddress) - Constructor for class javax.net.ssl.SSLServerSocket

Used only by subclasses.

SSLServerSocketFactory - Class in javax.net.ssl

SSLServerSocketFactorys create SSLServerSockets.

SSLServerSocketFactory() - Constructor for class javax.net.ssl.SSLServerSocketFactory

Constructor is used only by subclasses.

SSLSession - Interface in javax.net.ssl

In SSL, sessions are used to describe an ongoing relationship between two entities.

SSLSessionBindingEvent - Class in javax.net.ssl

This event is propagated to a SSLSessionBindingListener.

SSLSessionBindingEvent(SSLSession, String) - Constructor for class javax.net.ssl.SSLSessionBindingEvent

Constructs a new SSLSessionBindingEvent.

SSLSessionBindingListener - Interface in javax.net.ssl

This interface is implemented by objects which want to know when they are being bound or unbound from a SSLSession.

SSLSessionContext - Interface in javax.net.ssl

A SSLSessionContext represents a set of SSLSessions associated with a single entity.

SSLSocket - Class in javax.net.ssl

This class extends Sockets and provides secure socket using protocols such as the "Secure Sockets Layer" (SSL) or IETF "Transport Layer Security" (TLS) protocols.

SSLSocket() - Constructor for class javax.net.ssl.SSLSocket

Used only by subclasses.

SSLSocket(String, int) - Constructor for class javax.net.ssl.SSLSocket

Used only by subclasses.

SSLSocket(InetAddress, int) - Constructor for class javax.net.ssl.SSLSocket

Used only by subclasses.

SSLSocket(String, int, InetAddress, int) - Constructor for class javax.net.ssl.SSLSocket

Used only by subclasses.

SSLSocket(InetAddress, int, InetAddress, int) - Constructor for class javax.net.ssl.SSLSocket

Used only by subclasses.

SSLSocketFactory - Class in javax.net.ssl

SSLSocketFactorys create SSLSockets.

SSLSocketFactory() - Constructor for class javax.net.ssl.SSLSocketFactory

Constructor is used only by subclasses.

Stack<E> - Class in java.util

The Stack class represents a last-in-first-out (LIFO) stack of objects.

Stack() - Constructor for class java.util.Stack

Creates an empty Stack.

StackOverflowError - Error in java.lang

Thrown when a stack overflow occurs because an application recurses too deeply.

StackOverflowError() - Constructor for error java.lang.StackOverflowError

Constructs a StackOverflowError with no detail message.

StackOverflowError(String) - Constructor for error java.lang.StackOverflowError

Constructs a StackOverflowError with the specified detail message.

StackTraceElement - Class in java.lang

An element in a stack trace, as returned by Throwable.getStackTrace().

StackTraceElement(String, String, String, int) - Constructor for class java.lang.StackTraceElement

Creates a stack trace element representing the specified execution point.

STANDALONE - Static variable in class javax.xml.transform.OutputKeys

standalone = "yes" | "no".

standaloneSet() - Method in interface javax.xml.stream.events.StartDocument

Returns true if the standalone attribute was set in the encoding declaration of the document.

standaloneSet() - Method in class javax.xml.stream.util.StreamReaderDelegate

standaloneSet() - Method in interface javax.xml.stream.XMLStreamReader

Checks if standalone was set in the document

STANDARD - Static variable in class java.awt.font.GlyphMetrics

Indicates a glyph that represents a single standard character.

STANDARD - Static variable in class javax.print.attribute.standard.JobSheets

One or more site specific standard job sheets are printed.

STANDARD_INPUT_TYPE - Static variable in class javax.imageio.spi.ImageReaderSpi

Deprecated.
Instead of using this field, directly create the equivalent array { ImageInputStream.class }.

STANDARD_OUTPUT_TYPE - Static variable in class javax.imageio.spi.ImageWriterSpi

Deprecated.
Instead of using this field, directly create the equivalent array { ImageOutputStream.class }.

STANDARD_TIME - Static variable in class java.util.SimpleTimeZone

Constant for a mode of start or end time specified as standard time.

StandardCopyOption - Enum in java.nio.file

Defines the standard copy options.

StandardEmitterMBean - Class in javax.management

An MBean whose management interface is determined by reflection on a Java interface, and that emits notifications.

StandardEmitterMBean(T, Class<T>, NotificationEmitter) - Constructor for class javax.management.StandardEmitterMBean

Make an MBean whose management interface is specified by mbeanInterface, with the given implementation and where notifications are handled by the given NotificationEmitter.

StandardEmitterMBean(T, Class<T>, boolean, NotificationEmitter) - Constructor for class javax.management.StandardEmitterMBean

Make an MBean whose management interface is specified by mbeanInterface, with the given implementation and where notifications are handled by the given NotificationEmitter.

StandardEmitterMBean(Class<?>, NotificationEmitter) - Constructor for class javax.management.StandardEmitterMBean

Make an MBean whose management interface is specified by mbeanInterface, and where notifications are handled by the given NotificationEmitter.

StandardEmitterMBean(Class<?>, boolean, NotificationEmitter) - Constructor for class javax.management.StandardEmitterMBean

Make an MBean whose management interface is specified by mbeanInterface, and where notifications are handled by the given NotificationEmitter.

standardFormatSupported - Variable in class javax.imageio.metadata.IIOMetadata

A boolean indicating whether the concrete subclass supports the standard metadata format, set via the constructor.

StandardJavaFileManager - Interface in javax.tools

File manager based on java.io.File.

StandardLocation - Enum in javax.tools

Standard locations of file objects.

StandardMBean - Class in javax.management

An MBean whose management interface is determined by reflection on a Java interface.

StandardMBean(T, Class<T>) - Constructor for class javax.management.StandardMBean

Make a DynamicMBean out of the object implementation, using the specified mbeanInterface class.

StandardMBean(Class<?>) - Constructor for class javax.management.StandardMBean

Make a DynamicMBean out of this, using the specified mbeanInterface class.

StandardMBean(T, Class<T>, boolean) - Constructor for class javax.management.StandardMBean

Make a DynamicMBean out of the object implementation, using the specified mbeanInterface class, and choosing whether the resultant MBean is an MXBean.

StandardMBean(Class<?>, boolean) - Constructor for class javax.management.StandardMBean

Make a DynamicMBean out of this, using the specified mbeanInterface class, and choosing whether the resulting MBean is an MXBean.

standardMetadataFormatName - Static variable in class javax.imageio.metadata.IIOMetadataFormatImpl

A String constant containing the standard format name, "javax_imageio_1.0".

StandardOpenOption - Enum in java.nio.file

Defines the standard open options.

StandardProtocolFamily - Enum in java.net

Defines the standard families of communication protocols.

StandardSocketOption - Class in java.net

Defines the standard socket options.

StandardWatchEventKind - Class in java.nio.file

Defines the standard event kinds.

STANDBY - Static variable in class javax.swing.text.html.HTML.Attribute

STAPLE - Static variable in class javax.print.attribute.standard.Finishings

Bind the document(s) with one or more staples.

STAPLE_BOTTOM_LEFT - Static variable in class javax.print.attribute.standard.Finishings

Bind the document(s) with one or more staples in the bottom left corner.

STAPLE_BOTTOM_RIGHT - Static variable in class javax.print.attribute.standard.Finishings

Bind the document(s) with one or more staples in the bottom right corner.

STAPLE_DUAL_BOTTOM - Static variable in class javax.print.attribute.standard.Finishings

Bind the document(s) with two staples (wire stitches) along the bottom edge assuming a portrait document (see above).

STAPLE_DUAL_LEFT - Static variable in class javax.print.attribute.standard.Finishings

Bind the document(s) with two staples (wire stitches) along the left edge assuming a portrait document (see above).

STAPLE_DUAL_RIGHT - Static variable in class javax.print.attribute.standard.Finishings

Bind the document(s) with two staples (wire stitches) along the right edge assuming a portrait document (see above).

STAPLE_DUAL_TOP - Static variable in class javax.print.attribute.standard.Finishings

Bind the document(s) with two staples (wire stitches) along the top edge assuming a portrait document (see above).

STAPLE_TOP_LEFT - Static variable in class javax.print.attribute.standard.Finishings

Bind the document(s) with one or more staples in the top left corner.

STAPLE_TOP_RIGHT - Static variable in class javax.print.attribute.standard.Finishings

Bind the document(s) with one or more staples in the top right corner.

start() - Method in class java.applet.Applet

Called by the browser or applet viewer to inform this applet that it should start its execution.

start - Variable in class java.awt.geom.Arc2D.Double

The starting angle of the arc in degrees.

start - Variable in class java.awt.geom.Arc2D.Float

The starting angle of the arc in degrees.

start() - Method in class java.lang.ProcessBuilder

Starts a new process using the attributes of this process builder.

start() - Method in class java.lang.Thread

Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

start() - Method in class java.util.regex.Matcher

Returns the start index of the previous match.

start(int) - Method in class java.util.regex.Matcher

Returns the start index of the subsequence captured by the given group during the previous match operation.

start() - Method in interface java.util.regex.MatchResult

Returns the start index of the match.

start(int) - Method in interface java.util.regex.MatchResult

Returns the start index of the subsequence captured by the given group during this match.

start() - Method in class javax.management.monitor.CounterMonitor

Starts the counter monitor.

start() - Method in class javax.management.monitor.GaugeMonitor

Starts the gauge monitor.

start() - Method in class javax.management.monitor.Monitor

Starts the monitor.

start() - Method in interface javax.management.monitor.MonitorMBean

Starts the monitor.

start() - Method in class javax.management.monitor.StringMonitor

Starts the string monitor.

start() - Method in interface javax.management.remote.JMXConnectorServerMBean

Activates the connector server, that is, starts listening for client connections.

start() - Method in class javax.management.remote.rmi.RMIConnectorServer

Activates the connector server, that is starts listening for client connections.

start() - Method in class javax.management.timer.Timer

Starts the timer.

start() - Method in interface javax.management.timer.TimerMBean

Starts the timer.

start() - Method in interface javax.sound.midi.Sequencer

Starts playback of the MIDI data in the currently loaded sequence.

START - Static variable in class javax.sound.midi.ShortMessage

Status byte for Start message (0xFA, or 250).

start() - Method in interface javax.sound.sampled.DataLine

Allows a line to engage in data I/O.

START - Static variable in class javax.sound.sampled.LineEvent.Type

A type of event that is sent when a line begins to engage in active input or output of audio data in response to a start request.

START - Static variable in class javax.swing.text.html.HTML.Attribute

start(HTML.Tag, MutableAttributeSet) - Method in class javax.swing.text.html.HTMLDocument.HTMLReader.BlockAction

start(HTML.Tag, MutableAttributeSet) - Method in class javax.swing.text.html.HTMLDocument.HTMLReader.CharacterAction

start(HTML.Tag, MutableAttributeSet) - Method in class javax.swing.text.html.HTMLDocument.HTMLReader.FormAction

start(HTML.Tag, MutableAttributeSet) - Method in class javax.swing.text.html.HTMLDocument.HTMLReader.HiddenAction

start(HTML.Tag, MutableAttributeSet) - Method in class javax.swing.text.html.HTMLDocument.HTMLReader.IsindexAction

start(HTML.Tag, MutableAttributeSet) - Method in class javax.swing.text.html.HTMLDocument.HTMLReader.ParagraphAction

start(HTML.Tag, MutableAttributeSet) - Method in class javax.swing.text.html.HTMLDocument.HTMLReader.PreAction

start(HTML.Tag, MutableAttributeSet) - Method in class javax.swing.text.html.HTMLDocument.HTMLReader.SpecialAction

start(HTML.Tag, MutableAttributeSet) - Method in class javax.swing.text.html.HTMLDocument.HTMLReader.TagAction

Called when a start tag is seen for the type of tag this action was registered to.

start() - Method in class javax.swing.Timer

Starts the Timer, causing it to start sending action events to its listeners.

start(Xid, int) - Method in interface javax.transaction.xa.XAResource

Starts work on behalf of a transaction branch specified in xid.

START_DOCUMENT - Static variable in interface javax.xml.stream.XMLStreamConstants

Indicates an event is a start document

START_ELEMENT - Static variable in interface javax.xml.stream.XMLStreamConstants

Indicates an event is a start element

START_PUNCTUATION - Static variable in class java.lang.Character

General category "Ps" in the Unicode specification.

start_value() - Method in interface org.omg.CORBA.portable.ValueInputStream

The start_value method reads a valuetype header for a nested custom valuetype and increments the valuetype nesting depth.

start_value(String) - Method in interface org.omg.CORBA.portable.ValueOutputStream

The start_value method ends any currently open chunk, writes a valuetype header for a nested custom valuetype (with a null codebase and the specified repository ID), and increments the valuetype nesting depth.

startAnimationTimer() - Method in class javax.swing.plaf.basic.BasicProgressBarUI

Starts the animation thread, creating and initializing it if necessary.

startAutoScrolling(int) - Method in class javax.swing.plaf.basic.BasicComboPopup

This protected method is implementation specific and should be private.

startCDATA() - Method in class org.xml.sax.ext.DefaultHandler2

startCDATA() - Method in interface org.xml.sax.ext.LexicalHandler

Report the start of a CDATA section.

startCellEditing(EventObject) - Method in class javax.swing.DefaultCellEditor.EditorDelegate

Returns true to indicate that editing has begun.

StartDocument - Interface in javax.xml.stream.events

An interface for the start document event

startDocument() - Method in interface org.xml.sax.ContentHandler

Receive notification of the beginning of a document.

startDocument() - Method in interface org.xml.sax.DocumentHandler

Deprecated.

Receive notification of the beginning of a document.

startDocument() - Method in class org.xml.sax.HandlerBase

Deprecated.

Receive notification of the beginning of the document.

startDocument() - Method in class org.xml.sax.helpers.DefaultHandler

Receive notification of the beginning of the document.

startDocument() - Method in class org.xml.sax.helpers.ParserAdapter

Adapter implementation method; do not call.

startDocument() - Method in class org.xml.sax.helpers.XMLFilterImpl

Filter a start document event.

startDocument() - Method in class org.xml.sax.helpers.XMLReaderAdapter

Start document event.

startDrag(Cursor, Transferable) - Method in class java.awt.dnd.DragGestureEvent

Starts the drag operation given the Cursor for this drag operation and the Transferable representing the source data for this drag operation.

startDrag(Cursor, Transferable, DragSourceListener) - Method in class java.awt.dnd.DragGestureEvent

Starts the drag given the initial Cursor to display, the Transferable object, and the DragSourceListener to use.

startDrag(Cursor, Image, Point, Transferable, DragSourceListener) - Method in class java.awt.dnd.DragGestureEvent

Start the drag given the initial Cursor to display, a drag Image, the offset of the Image, the Transferable object, and the DragSourceListener to use.

startDrag(DragGestureEvent, Cursor, Image, Point, Transferable, DragSourceListener, FlavorMap) - Method in class java.awt.dnd.DragSource

Start a drag, given the DragGestureEvent that initiated the drag, the initial Cursor to use, the Image to drag, the offset of the Image origin from the hotspot of the Cursor at the instant of the trigger, the Transferable subject data of the drag, the DragSourceListener, and the FlavorMap.

startDrag(DragGestureEvent, Cursor, Transferable, DragSourceListener, FlavorMap) - Method in class java.awt.dnd.DragSource

Start a drag, given the DragGestureEvent that initiated the drag, the initial Cursor to use, the Transferable subject data of the drag, the DragSourceListener, and the FlavorMap.

startDrag(DragGestureEvent, Cursor, Image, Point, Transferable, DragSourceListener) - Method in class java.awt.dnd.DragSource

Start a drag, given the DragGestureEvent that initiated the drag, the initial Cursor to use, the Image to drag, the offset of the Image origin from the hotspot of the Cursor at the instant of the trigger, the subject data of the drag, and the DragSourceListener.

startDrag(DragGestureEvent, Cursor, Transferable, DragSourceListener) - Method in class java.awt.dnd.DragSource

Start a drag, given the DragGestureEvent that initiated the drag, the initial Cursor to use, the Transferable subject data of the drag, and the DragSourceListener.

startDragging() - Method in class javax.swing.plaf.basic.BasicSplitPaneUI

Should be messaged before the dragging session starts, resets lastDragLocation and dividerSize.

startDTD(String, String, String) - Method in class org.xml.sax.ext.DefaultHandler2

startDTD(String, String, String) - Method in interface org.xml.sax.ext.LexicalHandler

Report the start of DTD declarations, if any.

startEditing(TreePath, MouseEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI

Will start editing for node if there is a cellEditor and shouldSelectCell returns true.

startEditingAtPath(TreePath) - Method in class javax.swing.JTree

Selects the node identified by the specified path and initiates editing.

startEditingAtPath(JTree, TreePath) - Method in class javax.swing.plaf.basic.BasicTreeUI

Selects the last item in path and tries to edit it.

startEditingAtPath(JTree, TreePath) - Method in class javax.swing.plaf.multi.MultiTreeUI

Invokes the startEditingAtPath method on each UI handled by this object.

startEditingAtPath(JTree, TreePath) - Method in class javax.swing.plaf.TreeUI

Selects the last item in path and tries to edit it.

startEditingTimer() - Method in class javax.swing.tree.DefaultTreeCellEditor

Starts the editing timer.

StartElement - Interface in javax.xml.stream.events

The StartElement interface provides access to information about start elements.

startElement(Element) - Method in interface org.w3c.dom.ls.LSParserFilter

The parser will call this method after each Element start tag has been scanned, but before the remainder of the Element is processed.

startElement(String, String, String, Attributes) - Method in interface org.xml.sax.ContentHandler

Receive notification of the beginning of an element.

startElement(String, AttributeList) - Method in interface org.xml.sax.DocumentHandler

Deprecated.

Receive notification of the beginning of an element.

startElement(String, AttributeList) - Method in class org.xml.sax.HandlerBase

Deprecated.

Receive notification of the start of an element.

startElement(String, String, String, Attributes) - Method in class org.xml.sax.helpers.DefaultHandler

Receive notification of the start of an element.

startElement(String, AttributeList) - Method in class org.xml.sax.helpers.ParserAdapter

Adapter implementation method; do not call.

startElement(String, String, String, Attributes) - Method in class org.xml.sax.helpers.XMLFilterImpl

Filter a start element event.

startElement(String, String, String, Attributes) - Method in class org.xml.sax.helpers.XMLReaderAdapter

Adapt a SAX2 start element event.

startEntity(String) - Method in class org.xml.sax.ext.DefaultHandler2

startEntity(String) - Method in interface org.xml.sax.ext.LexicalHandler

Report the beginning of some internal and external XML entities.

startFontTag(String) - Method in class javax.swing.text.html.MinimalHTMLWriter

This is no longer used, instead <span> will be written out.

startGrabbing() - Method in class java.awt.image.PixelGrabber

Request the PixelGrabber to start fetching the pixels.

startHandshake() - Method in class javax.net.ssl.SSLSocket

Starts an SSL handshake on this connection.

startIndex - Variable in class javax.accessibility.AccessibleAttributeSequence

The start index of the text sequence

startIndex - Variable in class javax.accessibility.AccessibleTextSequence

startPrefixMapping(String, String) - Method in interface org.xml.sax.ContentHandler

Begin the scope of a prefix-URI Namespace mapping.

startPrefixMapping(String, String) - Method in class org.xml.sax.helpers.DefaultHandler

Receive notification of the start of a Namespace mapping.

startPrefixMapping(String, String) - Method in class org.xml.sax.helpers.XMLFilterImpl

Filter a start Namespace prefix mapping event.

startPrefixMapping(String, String) - Method in class org.xml.sax.helpers.XMLReaderAdapter

Adapt a SAX2 start prefix mapping event.

startProduction(ImageConsumer) - Method in class java.awt.image.FilteredImageSource

Starts production of the filtered image.

startProduction(ImageConsumer) - Method in interface java.awt.image.ImageProducer

Registers the specified ImageConsumer object as a consumer and starts an immediate reconstruction of the image data which will then be delivered to this consumer and any other consumer which might have already been registered with the producer.

startProduction(ImageConsumer) - Method in class java.awt.image.MemoryImageSource

Adds an ImageConsumer to the list of consumers interested in data for this image and immediately starts delivery of the image data through the ImageConsumer interface.

startProduction(ImageConsumer) - Method in class java.awt.image.renderable.RenderableImageProducer

Adds an ImageConsumer to the list of consumers interested in data for this image, and immediately starts delivery of the image data through the ImageConsumer interface.

startRecording() - Method in interface javax.sound.midi.Sequencer

Starts recording and playback of MIDI data.

startsWith(String, int) - Method in class java.lang.String

Tests if the substring of this string beginning at the specified index starts with the specified prefix.

startsWith(String) - Method in class java.lang.String

Tests if this string starts with the specified prefix.

startsWith(Path) - Method in interface java.nio.file.Path

Tests if this path starts with the given path.

startsWith(String) - Method in interface java.nio.file.Path

Tests if this path starts with a Path, constructed by converting the given path string, in exactly the manner specified by the startsWith(Path) method.

startsWith(Name) - Method in class javax.naming.CompositeName

Determines whether a composite name is a prefix of this composite name.

startsWith(Name) - Method in class javax.naming.CompoundName

Determines whether a compound name is a prefix of this compound name.

startsWith(Name) - Method in class javax.naming.ldap.LdapName

Determines whether this LDAP name starts with a specified LDAP name prefix.

startsWith(List<Rdn>) - Method in class javax.naming.ldap.LdapName

Determines whether the specified RDN sequence forms a prefix of this LDAP name.

startsWith(Name) - Method in interface javax.naming.Name

Determines whether this name starts with a specified prefix.

startTag(Element) - Method in class javax.swing.text.html.HTMLWriter

Writes out a start tag for the element.

STARTTAG - Static variable in interface javax.swing.text.html.parser.DTDConstants

startTag(TagElement) - Method in class javax.swing.text.html.parser.Parser

Handle a start tag.

StartTagType - Static variable in class javax.swing.text.DefaultStyledDocument.ElementSpec

A possible value for getType.

startTimer() - Method in class javax.swing.plaf.basic.BasicTreeUI.ComponentHandler

Creates, if necessary, and starts a Timer to check if need to resize the bounds.

StartTlsRequest - Class in javax.naming.ldap

This class implements the LDAPv3 Extended Request for StartTLS as defined in Lightweight Directory Access Protocol (v3): Extension for Transport Layer Security The object identifier for StartTLS is 1.3.6.1.4.1.1466.20037 and no extended request value is defined.

StartTlsRequest() - Constructor for class javax.naming.ldap.StartTlsRequest

Constructs a StartTLS extended request.

StartTlsResponse - Class in javax.naming.ldap

This class implements the LDAPv3 Extended Response for StartTLS as defined in Lightweight Directory Access Protocol (v3): Extension for Transport Layer Security The object identifier for StartTLS is 1.3.6.1.4.1.1466.20037 and no extended response value is defined.

StartTlsResponse() - Constructor for class javax.naming.ldap.StartTlsResponse

Constructs a StartTLS extended response.

state - Variable in class java.security.Signature

Current state of this signature object.

State<T extends JComponent> - Class in javax.swing.plaf.nimbus

Represents a built in, or custom, state in Nimbus.

State(String) - Constructor for class javax.swing.plaf.nimbus.State

Create a new custom State.

state() - Method in interface org.omg.PortableInterceptor.IORInfoOperations

Return the adapter state of the object adapter that was just created and is running IOR interceptors.

State - Class in org.omg.PortableServer.POAManagerPackage

Specifies the states for the POAManager

State(int) - Constructor for class org.omg.PortableServer.POAManagerPackage.State

STATE_FACTORIES - Static variable in interface javax.naming.Context

Constant that holds the name of the environment property for specifying the list of state factories to use.

stateChanged(ChangeEvent) - Method in class javax.swing.AbstractButton.ButtonChangeListener

stateChanged(ChangeEvent) - Method in interface javax.swing.event.ChangeListener

Invoked when the target of the listener has changed its state.

stateChanged(ChangeEvent) - Method in class javax.swing.JMenuItem.AccessibleJMenuItem

Supports the change listener interface and fires property changes.

stateChanged(ChangeEvent) - Method in class javax.swing.JScrollPane.AccessibleJScrollPane

Invoked when the target of the listener has changed its state.

stateChanged(ChangeEvent) - Method in class javax.swing.JSpinner.AccessibleJSpinner

Invoked when the target of the listener has changed its state.

stateChanged(ChangeEvent) - Method in class javax.swing.JSpinner.DefaultEditor

This method is called when the spinner's model's state changes.

stateChanged(ChangeEvent) - Method in class javax.swing.JTabbedPane.AccessibleJTabbedPane

stateChanged(ChangeEvent) - Method in class javax.swing.JTabbedPane.ModelListener

stateChanged(ChangeEvent) - Method in class javax.swing.plaf.basic.BasicButtonListener

stateChanged(ChangeEvent) - Method in class javax.swing.plaf.basic.BasicMenuUI.ChangeHandler

stateChanged(ChangeEvent) - Method in class javax.swing.plaf.basic.BasicProgressBarUI.ChangeHandler

stateChanged(ChangeEvent) - Method in class javax.swing.plaf.basic.BasicScrollBarUI.ModelListener

stateChanged(ChangeEvent) - Method in class javax.swing.plaf.basic.BasicScrollPaneUI.HSBChangeListener

stateChanged(ChangeEvent) - Method in class javax.swing.plaf.basic.BasicScrollPaneUI.ViewportChangeHandler

stateChanged(ChangeEvent) - Method in class javax.swing.plaf.basic.BasicScrollPaneUI.VSBChangeListener

stateChanged(ChangeEvent) - Method in class javax.swing.plaf.basic.BasicSliderUI.ChangeHandler

stateChanged(ChangeEvent) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI.TabSelectionHandler

stateChanged(ChangeEvent) - Method in class javax.swing.ProgressMonitor.AccessibleProgressMonitor

Invoked when the target of the listener has changed its state.

StateEdit - Class in javax.swing.undo

StateEdit is a general edit for objects that change state.

StateEdit(StateEditable) - Constructor for class javax.swing.undo.StateEdit

Create and return a new StateEdit.

StateEdit(StateEditable, String) - Constructor for class javax.swing.undo.StateEdit

Create and return a new StateEdit with a presentation name.

StateEditable - Interface in javax.swing.undo

StateEditable defines the interface for objects that can have their state undone/redone by a StateEdit.

StateFactory - Interface in javax.naming.spi

This interface represents a factory for obtaining the state of an object for binding.

stateMask - Variable in class javax.swing.DefaultButtonModel

The bitmask used to store the state of the button.

STATEMENT - Static variable in class java.awt.PageAttributes.MediaType

An alias for INVOICE.

Statement - Class in java.beans

A Statement object represents a primitive statement in which a single method is applied to a target and a set of arguments - as in "a.setFoo(b)".

Statement(Object, String, Object[]) - Constructor for class java.beans.Statement

Creates a new Statement object for the specified target object to invoke the method specified by the name and by the array of arguments.

Statement - Interface in java.sql

The object used for executing a static SQL statement and returning the results it produces.

statementClosed(StatementEvent) - Method in interface javax.sql.StatementEventListener

The driver calls this method on all StatementEventListeners registered on the connection when it detects that a PreparedStatement is closed.

statementErrorOccurred(StatementEvent) - Method in interface javax.sql.StatementEventListener

The driver calls this method on all StatementEventListeners registered on the connection when it detects that a PreparedStatement is invalid.

StatementEvent - Class in javax.sql

A StatementEvent is sent to all StatementEventListeners which were registered with a PooledConnection.

StatementEvent(PooledConnection, PreparedStatement) - Constructor for class javax.sql.StatementEvent

Constructs a StatementEvent with the specified PooledConnection and PreparedStatement.

StatementEvent(PooledConnection, PreparedStatement, SQLException) - Constructor for class javax.sql.StatementEvent

Constructs a StatementEvent with the specified PooledConnection, PreparedStatement and SQLException

StatementEventListener - Interface in javax.sql

An object that registers to be notified of events that occur on PreparedStatements that are in the Statement pool.

states - Variable in class javax.accessibility.AccessibleStateSet

Each entry in the Vector represents an AccessibleState.

STATIC - Static variable in class java.lang.reflect.修饰符

The int value representing the static modifier.

STATICIMAGEDONE - Static variable in interface java.awt.image.ImageConsumer

The image is complete and there are no more pixels or frames to be delivered.

status() - Method in class java.awt.image.PixelGrabber

Returns the status of the pixels.

STATUS_BAR - Static variable in class javax.accessibility.AccessibleRole

A STATUS_BAR is an simple component that can contain multiple labels of status information to the user.

statusAll(boolean) - Method in class java.awt.MediaTracker

Calculates and returns the bitwise inclusive OR of the status of all media that are tracked by this media tracker.

statusID(int, boolean) - Method in class java.awt.MediaTracker

Calculates and returns the bitwise inclusive OR of the status of all media with the specified identifier that are tracked by this media tracker.

StAXResult - Class in javax.xml.transform.stax

Acts as a holder for an XML Result in the form of a StAX writer,i.e.

StAXResult(XMLEventWriter) - Constructor for class javax.xml.transform.stax.StAXResult

Creates a new instance of a StAXResult by supplying an XMLEventWriter.

StAXResult(XMLStreamWriter) - Constructor for class javax.xml.transform.stax.StAXResult

Creates a new instance of a StAXResult by supplying an XMLStreamWriter.

StAXSource - Class in javax.xml.transform.stax

Acts as a holder for an XML Source in the form of a StAX reader,i.e.

StAXSource(XMLEventReader) - Constructor for class javax.xml.transform.stax.StAXSource

Creates a new instance of a StAXSource by supplying an XMLEventReader.

StAXSource(XMLStreamReader) - Constructor for class javax.xml.transform.stax.StAXSource

Creates a new instance of a StAXSource by supplying an XMLStreamReader.

StdACChrominance - Static variable in class javax.imageio.plugins.jpeg.JPEGHuffmanTable

The standard AC chrominance Huffman table.

StdACLuminance - Static variable in class javax.imageio.plugins.jpeg.JPEGHuffmanTable

The standard AC luminance Huffman table.

StdDCChrominance - Static variable in class javax.imageio.plugins.jpeg.JPEGHuffmanTable

The standard DC chrominance Huffman table.

StdDCLuminance - Static variable in class javax.imageio.plugins.jpeg.JPEGHuffmanTable

The standard DC luminance Huffman table.

stop() - Method in class java.applet.Applet

Called by the browser or applet viewer to inform this applet that it should stop its execution.

stop() - Method in interface java.applet.AudioClip

Stops playing this audio clip.

stop() - Method in class java.awt.dnd.DropTarget.DropTargetAutoScroller

cause autoscrolling to stop

stop() - Method in class java.lang.Thread

Deprecated.
This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior. Many uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. If the target thread waits for long periods (on a condition variable, for example), the interrupt method should be used to interrupt the wait. For more information, see Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?.

stop(Throwable) - Method in class java.lang.Thread

Deprecated.
This method is inherently unsafe. See Thread.stop() for details. An additional danger of this method is that it may be used to generate exceptions that the target thread is unprepared to handle (including checked exceptions that the thread could not possibly throw, were it not for this method). For more information, see Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?.

stop() - Method in class java.lang.ThreadGroup

Deprecated.
This method is inherently unsafe. See Thread.stop() for details.

stop() - Method in class javax.management.monitor.CounterMonitor

Stops the counter monitor.

stop() - Method in class javax.management.monitor.GaugeMonitor

Stops the gauge monitor.

stop() - Method in class javax.management.monitor.Monitor

Stops the monitor.

stop() - Method in interface javax.management.monitor.MonitorMBean

Stops the monitor.

stop() - Method in class javax.management.monitor.StringMonitor

Stops the string monitor.

stop() - Method in interface javax.management.remote.JMXConnectorServerMBean

Deactivates the connector server, that is, stops listening for client connections.

stop() - Method in class javax.management.remote.rmi.RMIConnectorServer

Deactivates the connector server, that is, stops listening for client connections.

stop() - Method in class javax.management.timer.Timer

Stops the timer.

stop() - Method in interface javax.management.timer.TimerMBean

Stops the timer.

stop() - Method in interface javax.sound.midi.Sequencer

Stops recording, if active, and playback of the currently loaded sequence, if any.

STOP - Static variable in class javax.sound.midi.ShortMessage

Status byte for Stop message (0xFC, or 252).

stop() - Method in interface javax.sound.sampled.DataLine

Stops the line.

STOP - Static variable in class javax.sound.sampled.LineEvent.Type

A type of event that is sent when a line ceases active input or output of audio data in response to a stop request, or because the end of media has been reached.

stop() - Method in class javax.swing.Timer

Stops the Timer, causing it to stop sending action events to its listeners.

stop() - Method in class javax.xml.ws.Endpoint

Stops publishing this endpoint.

stopAnimationTimer() - Method in class javax.swing.plaf.basic.BasicProgressBarUI

Stops the animation thread.

stopAutoScrolling() - Method in class javax.swing.plaf.basic.BasicComboPopup

This protected method is implementation specific and should be private.

stopCellEditing() - Method in class javax.swing.AbstractCellEditor

Calls fireEditingStopped and returns true.

stopCellEditing() - Method in interface javax.swing.CellEditor

Tells the editor to stop editing and accept any partially edited value as the value of the editor.

stopCellEditing() - Method in class javax.swing.DefaultCellEditor.EditorDelegate

Stops editing and returns true to indicate that editing has stopped.

stopCellEditing() - Method in class javax.swing.DefaultCellEditor

Forwards the message from the CellEditor to the delegate.

stopCellEditing() - Method in class javax.swing.tree.DefaultTreeCellEditor

If the realEditor will allow editing to stop, the realEditor is removed and true is returned, otherwise false is returned.

stopEditing() - Method in class javax.swing.JTree

Ends the current editing session.

stopEditing(JTree) - Method in class javax.swing.plaf.basic.BasicTreeUI

Stops the current editing session.

stopEditing(JTree) - Method in class javax.swing.plaf.multi.MultiTreeUI

Invokes the stopEditing method on each UI handled by this object.

stopEditing(JTree) - Method in class javax.swing.plaf.TreeUI

Stops the current editing session.

stopEditingInCompleteEditing - Variable in class javax.swing.plaf.basic.BasicTreeUI

Set to false when editing and shouldSelectCell() returns true meaning the node should be selected before editing, used in completeEditing.

STOPPED - Static variable in class javax.print.attribute.standard.PrinterState

Indicates that no jobs can be processed and intervention is required.

STOPPED_PARTLY - Static variable in class javax.print.attribute.standard.PrinterStateReason

When a printer controls more than one output device, this reason indicates that one or more output devices are stopped.

STOPPING - Static variable in class javax.print.attribute.standard.PrinterStateReason

The printer is in the process of stopping the device and will be stopped in a while.

stopPropagation() - Method in interface org.w3c.dom.events.Event

The stopPropagation method is used prevent further propagation of an event during event flow.

stopRecording() - Method in interface javax.sound.midi.Sequencer

Stops recording, if active.

store(OutputStream, char[]) - Method in class java.security.KeyStore

Stores this keystore to the given output stream, and protects its integrity with the given password.

store(KeyStore.LoadStoreParameter) - Method in class java.security.KeyStore

Stores this keystore using the given LoadStoreParameter.

store(Writer, String) - Method in class java.util.Properties

Writes this property list (key and element pairs) in this Properties table to the output character stream in a format suitable for using the load(Reader) method.

store(OutputStream, String) - Method in class java.util.Properties

Writes this property list (key and element pairs) in this Properties table to the output stream in a format suitable for loading into a Properties table using the load(InputStream) method.

store() - Method in class javax.management.modelmbean.RequiredModelMBean

Captures the current state of this MBean instance and writes it out to the persistent store.

store() - Method in interface javax.management.PersistentMBean

Captures the current state of this MBean instance and writes it out to the persistent store.

STORED - Static variable in class java.util.zip.ZipEntry

Compression method for uncompressed entries.

STORED - Static variable in class java.util.zip.ZipOutputStream

Compression method for uncompressed (STORED) entries.

storesLowerCaseIdentifiers() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database treats mixed case unquoted SQL identifiers as case insensitive and stores them in lower case.

storesLowerCaseQuotedIdentifiers() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database treats mixed case quoted SQL identifiers as case insensitive and stores them in lower case.

storesMixedCaseIdentifiers() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database treats mixed case unquoted SQL identifiers as case insensitive and stores them in mixed case.

storesMixedCaseQuotedIdentifiers() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database treats mixed case quoted SQL identifiers as case insensitive and stores them in mixed case.

storeState(Hashtable<Object, Object>) - Method in interface javax.swing.undo.StateEditable

Upon receiving this message the receiver should place any relevant state into state.

storesUpperCaseIdentifiers() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database treats mixed case unquoted SQL identifiers as case insensitive and stores them in upper case.

storesUpperCaseQuotedIdentifiers() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database treats mixed case quoted SQL identifiers as case insensitive and stores them in upper case.

storeToXML(OutputStream, String) - Method in class java.util.Properties

Emits an XML document representing all of the properties contained in this table.

storeToXML(OutputStream, String, String) - Method in class java.util.Properties

Emits an XML document representing all of the properties contained in this table, using the specified encoding.

strategy - Variable in class javax.swing.text.FlowView

The behavior for keeping the flow updated.

STREAM_MAGIC - Static variable in interface java.io.ObjectStreamConstants

Magic number that is written to the stream header.

STREAM_VERSION - Static variable in interface java.io.ObjectStreamConstants

Version number that is written to the stream header.

Streamable - Interface in org.omg.CORBA.portable

The base class for the Holder classess of all complex IDL types.

StreamableValue - Interface in org.omg.CORBA.portable

Defines the base type for all non-boxed IDL valuetypes that are not custom marshaled.

StreamCorruptedException - Exception in java.io

Thrown when control information that was read from an object stream violates internal consistency checks.

StreamCorruptedException(String) - Constructor for exception java.io.StreamCorruptedException

Create a StreamCorruptedException and list a reason why thrown.

StreamCorruptedException() - Constructor for exception java.io.StreamCorruptedException

Create a StreamCorruptedException and list no reason why thrown.

StreamDescriptionProperty - Static variable in interface javax.swing.text.Document

The property name for the description of the stream used to initialize the document.

StreamFilter - Interface in javax.xml.stream

This interface declares a simple filter interface that one can create to filter XMLStreamReaders

StreamHandler - Class in java.util.logging

Stream based logging Handler.

StreamHandler() - Constructor for class java.util.logging.StreamHandler

Create a StreamHandler, with no current output stream.

StreamHandler(OutputStream, Formatter) - Constructor for class java.util.logging.StreamHandler

Create a StreamHandler with a given Formatter and output stream.

streamPos - Variable in class javax.imageio.stream.ImageInputStreamImpl

The current read position within the stream.

StreamPrintService - Class in javax.print

This class extends PrintService and represents a print service that prints data in different formats to a client-provided output stream.

StreamPrintService(OutputStream) - Constructor for class javax.print.StreamPrintService

Constructs a StreamPrintService object.

StreamPrintServiceFactory - Class in javax.print

A StreamPrintServiceFactory is the factory for StreamPrintService instances, which can print to an output stream in a particular document format described as a mime type.

StreamPrintServiceFactory() - Constructor for class javax.print.StreamPrintServiceFactory

StreamReaderDelegate - Class in javax.xml.stream.util

This is the base class for deriving an XMLStreamReader filter This class is designed to sit between an XMLStreamReader and an application's XMLStreamReader.

StreamReaderDelegate() - Constructor for class javax.xml.stream.util.StreamReaderDelegate

Construct an empty filter with no parent.

StreamReaderDelegate(XMLStreamReader) - Constructor for class javax.xml.stream.util.StreamReaderDelegate

Construct an filter with the specified parent.

StreamResult - Class in javax.xml.transform.stream

Acts as an holder for a transformation result, which may be XML, plain Text, HTML, or some other form of markup.

StreamResult() - Constructor for class javax.xml.transform.stream.StreamResult

Zero-argument default constructor.

StreamResult(OutputStream) - Constructor for class javax.xml.transform.stream.StreamResult

Construct a StreamResult from a byte stream.

StreamResult(Writer) - Constructor for class javax.xml.transform.stream.StreamResult

Construct a StreamResult from a character stream.

StreamResult(String) - Constructor for class javax.xml.transform.stream.StreamResult

Construct a StreamResult from a URL.

StreamResult(File) - Constructor for class javax.xml.transform.stream.StreamResult

Construct a StreamResult from a File.

StreamSource - Class in javax.xml.transform.stream

Acts as an holder for a transformation Source in the form of a stream of XML markup.

StreamSource() - Constructor for class javax.xml.transform.stream.StreamSource

Zero-argument default constructor.

StreamSource(InputStream) - Constructor for class javax.xml.transform.stream.StreamSource

Construct a StreamSource from a byte stream.

StreamSource(InputStream, String) - Constructor for class javax.xml.transform.stream.StreamSource

Construct a StreamSource from a byte stream.

StreamSource(Reader) - Constructor for class javax.xml.transform.stream.StreamSource

Construct a StreamSource from a character reader.

StreamSource(Reader, String) - Constructor for class javax.xml.transform.stream.StreamSource

Construct a StreamSource from a character reader.

StreamSource(String) - Constructor for class javax.xml.transform.stream.StreamSource

Construct a StreamSource from a URL.

StreamSource(File) - Constructor for class javax.xml.transform.stream.StreamSource

Construct a StreamSource from a File.

StreamTokenizer - Class in java.io

The StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens to be read one at a time.

StreamTokenizer(InputStream) - Constructor for class java.io.StreamTokenizer

Deprecated.
As of JDK version 1.1, the preferred way to tokenize an input stream is to convert it into a character stream, for example:
   Reader r = new BufferedReader(new InputStreamReader(is));
   StreamTokenizer st = new StreamTokenizer(r);
StreamTokenizer(Reader) - Constructor for class java.io.StreamTokenizer

Create a tokenizer that parses the given character stream.

STRENGTH - Static variable in class javax.security.sasl.Sasl

The name of a property that specifies the cipher strength to use.

STRICT - Static variable in class java.lang.reflect.修饰符

The int value representing the strictfp modifier.

strict - Variable in class javax.swing.text.html.parser.Parser

This flag determines whether or not the Parser will be strict in enforcing SGML compatibility.

StrictMath - Class in java.lang

The class StrictMath contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.

STRIKE - Static variable in class javax.swing.text.html.HTML.Tag

STRIKETHROUGH - Static variable in class java.awt.font.TextAttribute

Attribute key for strikethrough.

StrikeThrough - Static variable in class javax.swing.text.StyleConstants

Name of the Strikethrough attribute.

STRIKETHROUGH_ON - Static variable in class java.awt.font.TextAttribute

A single strikethrough.

String - Class in java.lang

The String class represents character strings.

String() - Constructor for class java.lang.String

Initializes a newly created String object so that it represents an empty character sequence.

String(String) - Constructor for class java.lang.String

Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string.

String(char[]) - Constructor for class java.lang.String

Allocates a new String so that it represents the sequence of characters currently contained in the character array argument.

String(char[], int, int) - Constructor for class java.lang.String

Allocates a new String that contains characters from a subarray of the character array argument.

String(int[], int, int) - Constructor for class java.lang.String

Allocates a new String that contains characters from a subarray of the Unicode code point array argument.

String(byte[], int, int, int) - Constructor for class java.lang.String

Deprecated.
This method does not properly convert bytes into characters. As of JDK 1.1, the preferred way to do this is via the String constructors that take a Charset, charset name, or that use the platform's default charset.

String(byte[], int) - Constructor for class java.lang.String

Deprecated.
This method does not properly convert bytes into characters. As of JDK 1.1, the preferred way to do this is via the String constructors that take a Charset, charset name, or that use the platform's default charset.

String(byte[], int, int, String) - Constructor for class java.lang.String

Constructs a new String by decoding the specified subarray of bytes using the specified charset.

String(byte[], int, int, Charset) - Constructor for class java.lang.String

Constructs a new String by decoding the specified subarray of bytes using the specified charset.

String(byte[], String) - Constructor for class java.lang.String

Constructs a new String by decoding the specified array of bytes using the specified charset.

String(byte[], Charset) - Constructor for class java.lang.String

Constructs a new String by decoding the specified array of bytes using the specified charset.

String(byte[], int, int) - Constructor for class java.lang.String

Constructs a new String by decoding the specified subarray of bytes using the platform's default charset.

String(byte[]) - Constructor for class java.lang.String

Constructs a new String by decoding the specified array of bytes using the platform's default charset.

String(StringBuffer) - Constructor for class java.lang.String

Allocates a new string that contains the sequence of characters currently contained in the string buffer argument.

String(StringBuilder) - Constructor for class java.lang.String

Allocates a new string that contains the sequence of characters currently contained in the string builder argument.

STRING - Static variable in class javax.management.openmbean.SimpleType

The SimpleType instance describing values whose Java class name is java.lang.String.

STRING - Static variable in class javax.xml.xpath.XPathConstants

The XPath 1.0 string data type.

STRING_TO_COMPARE_VALUE_DIFFERED - Static variable in class javax.management.monitor.MonitorNotification

Notification type denoting that the observed attribute has differed from the "string to compare" value.

STRING_TO_COMPARE_VALUE_MATCHED - Static variable in class javax.management.monitor.MonitorNotification

Notification type denoting that the observed attribute has matched the "string to compare" value.

string_to_object(String) - Method in class org.omg.CORBA.ORB

Converts a string produced by the method object_to_string back to a CORBA object reference.

StringBuffer - Class in java.lang

A thread-safe, mutable sequence of characters.

StringBuffer() - Constructor for class java.lang.StringBuffer

Constructs a string buffer with no characters in it and an initial capacity of 16 characters.

StringBuffer(int) - Constructor for class java.lang.StringBuffer

Constructs a string buffer with no characters in it and the specified initial capacity.

StringBuffer(String) - Constructor for class java.lang.StringBuffer

Constructs a string buffer initialized to the contents of the specified string.

StringBuffer(CharSequence) - Constructor for class java.lang.StringBuffer

Constructs a string buffer that contains the same characters as the specified CharSequence.

StringBufferInputStream - Class in java.io

Deprecated.
This class does not properly convert characters into bytes. As of JDK 1.1, the preferred way to create a stream from a string is via the StringReader class.

StringBufferInputStream(String) - Constructor for class java.io.StringBufferInputStream

Deprecated.

Creates a string input stream to read data from the specified string.

StringBuilder - Class in java.lang

A mutable sequence of characters.

StringBuilder() - Constructor for class java.lang.StringBuilder

Constructs a string builder with no characters in it and an initial capacity of 16 characters.

StringBuilder(int) - Constructor for class java.lang.StringBuilder

Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument.

StringBuilder(String) - Constructor for class java.lang.StringBuilder

Constructs a string builder initialized to the contents of the specified string.

StringBuilder(CharSequence) - Constructor for class java.lang.StringBuilder

Constructs a string builder that contains the same characters as the specified CharSequence.

StringCharacterIterator - Class in java.text

StringCharacterIterator implements the CharacterIterator protocol for a String.

StringCharacterIterator(String) - Constructor for class java.text.StringCharacterIterator

Constructs an iterator with an initial index of 0.

StringCharacterIterator(String, int) - Constructor for class java.text.StringCharacterIterator

Constructs an iterator with the specified initial index.

StringCharacterIterator(String, int, int, int) - Constructor for class java.text.StringCharacterIterator

Constructs an iterator over the given range of the given string, with the index set at the specified position.

StringContent - Class in javax.swing.text

An implementation of the AbstractDocument.Content interface that is a brute force implementation that is useful for relatively small documents and/or debugging.

StringContent() - Constructor for class javax.swing.text.StringContent

Creates a new StringContent object.

StringContent(int) - Constructor for class javax.swing.text.StringContent

Creates a new StringContent object, with the initial size specified.

stringFlavor - Static variable in class java.awt.datatransfer.DataFlavor

The DataFlavor representing a Java Unicode String class, where:

StringHolder - Class in org.omg.CORBA

The Holder for String.

StringHolder() - Constructor for class org.omg.CORBA.StringHolder

Constructs a new StringHolder object with its value field initialized to null.

StringHolder(String) - Constructor for class org.omg.CORBA.StringHolder

Constructs a new StringHolder object with its value field initialized to the given String.

StringIndexOutOfBoundsException - Exception in java.lang

Thrown by String methods to indicate that an index is either negative or greater than the size of the string.

StringIndexOutOfBoundsException() - Constructor for exception java.lang.StringIndexOutOfBoundsException

Constructs a StringIndexOutOfBoundsException with no detail message.

StringIndexOutOfBoundsException(String) - Constructor for exception java.lang.StringIndexOutOfBoundsException

Constructs a StringIndexOutOfBoundsException with the specified detail message.

StringIndexOutOfBoundsException(int) - Constructor for exception java.lang.StringIndexOutOfBoundsException

Constructs a new StringIndexOutOfBoundsException class with an argument indicating the illegal index.

StringMonitor - Class in javax.management.monitor

Defines a monitor MBean designed to observe the values of a string attribute.

StringMonitor() - Constructor for class javax.management.monitor.StringMonitor

Default constructor.

StringMonitorMBean - Interface in javax.management.monitor

Exposes the remote management interface of the string monitor MBean.

StringNameHelper - Class in org.omg.CosNaming.NamingContextExtPackage

StringName is the Stringified Name, Array of Name Components represented as a String.

StringNameHelper() - Constructor for class org.omg.CosNaming.NamingContextExtPackage.StringNameHelper

stringPropertyNames() - Method in class java.util.Properties

Returns a set of keys in this property list where the key and its corresponding value are strings, including distinct keys in the default property list if a key of the same name has not already been found from the main properties list.

StringReader - Class in java.io

A character stream whose source is a string.

StringReader(String) - Constructor for class java.io.StringReader

Creates a new string reader.

StringRefAddr - Class in javax.naming

This class represents the string form of the address of a communications end-point.

StringRefAddr(String, String) - Constructor for class javax.naming.StringRefAddr

Constructs a new instance of StringRefAddr using its address type and contents.

StringSelection - Class in java.awt.datatransfer

A Transferable which implements the capability required to transfer a String.

StringSelection(String) - Constructor for class java.awt.datatransfer.StringSelection

Creates a Transferable capable of transferring the specified String.

StringSeqHelper - Class in org.omg.CORBA

An array of Strings

StringSeqHelper() - Constructor for class org.omg.CORBA.StringSeqHelper

StringSeqHolder - Class in org.omg.CORBA

An array of Strings

StringSeqHolder() - Constructor for class org.omg.CORBA.StringSeqHolder

StringSeqHolder(String[]) - Constructor for class org.omg.CORBA.StringSeqHolder

stringToColor(String) - Method in class javax.swing.text.html.StyleSheet

Converts a color string such as "RED" or "#NNNNNN" to a Color.

StringTokenizer - Class in java.util

The string tokenizer class allows an application to break a string into tokens.

StringTokenizer(String, String, boolean) - Constructor for class java.util.StringTokenizer

Constructs a string tokenizer for the specified string.

StringTokenizer(String, String) - Constructor for class java.util.StringTokenizer

Constructs a string tokenizer for the specified string.

StringTokenizer(String) - Constructor for class java.util.StringTokenizer

Constructs a string tokenizer for the specified string.

stringToValue(String) - Method in class javax.swing.JFormattedTextField.AbstractFormatter

Parses text returning an arbitrary Object.

stringToValue(String) - Method in class javax.swing.text.DefaultFormatter

Converts the passed in String into an instance of getValueClass by way of the constructor that takes a String argument.

stringToValue(String) - Method in class javax.swing.text.InternationalFormatter

Returns the Object representation of the String text.

stringToValue(String) - Method in class javax.swing.text.MaskFormatter

Parses the text, returning the appropriate Object representation of the String value.

StringValueExp - Class in javax.management

Represents strings that are arguments to relational constraints.

StringValueExp() - Constructor for class javax.management.StringValueExp

Basic constructor.

StringValueExp(String) - Constructor for class javax.management.StringValueExp

Creates a new StringValueExp representing the given string.

StringValueHelper - Class in org.omg.CORBA

The Helper for StringValue.

StringValueHelper() - Constructor for class org.omg.CORBA.StringValueHelper

stringWidth(String) - Method in class java.awt.FontMetrics

Returns the total advance width for showing the specified String in this Font.

StringWriter - Class in java.io

A character stream that collects its output in a string buffer, which can then be used to construct a string.

StringWriter() - Constructor for class java.io.StringWriter

Create a new string writer using the default initial string-buffer size.

StringWriter(int) - Constructor for class java.io.StringWriter

Create a new string writer using the specified initial string-buffer size.

STRIP - Static variable in interface java.util.jar.Pack200.Packer

The string "strip", a possible value for certain properties.

stripTrailingZeros() - Method in class java.math.BigDecimal

Returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation.

STROKE - Static variable in class java.awt.font.ShapeGraphicAttribute

A key indicating the shape should be stroked with a 1-pixel wide stroke.

Stroke - Interface in java.awt

The Stroke interface allows a Graphics2D object to obtain a Shape that is the decorated outline, or stylistic representation of the outline, of the specified Shape.

StrokeBorder - Class in javax.swing.border

A class which implements a border of an arbitrary stroke.

StrokeBorder(BasicStroke) - Constructor for class javax.swing.border.StrokeBorder

Creates a border of the specified stroke.

StrokeBorder(BasicStroke, Paint) - Constructor for class javax.swing.border.StrokeBorder

Creates a border of the specified stroke and paint.

STRONG - Static variable in class javax.swing.text.html.HTML.Tag

Struct - Interface in java.sql

The standard mapping in the Java programming language for an SQL structured type.

STRUCT - Static variable in class java.sql.Types

The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type STRUCT.

StructMember - Class in org.omg.CORBA

Describes a member of an IDL struct in the Interface Repository, including the name of the struct member, the type of the struct member, and the typedef that represents the IDL type of the struct member described the struct member object.

StructMember() - Constructor for class org.omg.CORBA.StructMember

Constructs a default StructMember object.

StructMember(String, TypeCode, IDLType) - Constructor for class org.omg.CORBA.StructMember

Constructs a StructMember object initialized with the given values.

StructMemberHelper - Class in org.omg.CORBA

The Helper for StructMember.

StructMemberHelper() - Constructor for class org.omg.CORBA.StructMemberHelper

Stub - Class in javax.rmi.CORBA

Base class from which all RMI-IIOP stubs must inherit.

Stub() - Constructor for class javax.rmi.CORBA.Stub

StubDelegate - Interface in javax.rmi.CORBA

Supports delegation for method implementations in Stub.

StubNotFoundException - Exception in java.rmi

A StubNotFoundException is thrown if a valid stub class could not be found for a remote object when it is exported.

StubNotFoundException(String) - Constructor for exception java.rmi.StubNotFoundException

Constructs a StubNotFoundException with the specified detail message.

StubNotFoundException(String, Exception) - Constructor for exception java.rmi.StubNotFoundException

Constructs a StubNotFoundException with the specified detail message and nested exception.

style - Variable in class java.awt.Font

The style of this Font, as passed to the constructor.

STYLE - Static variable in class javax.swing.text.html.HTML.Attribute

STYLE - Static variable in class javax.swing.text.html.HTML.Tag

Style - Interface in javax.swing.text

A collection of attributes to associate with an element in a document.

styleChanged(Style) - Method in class javax.swing.text.DefaultStyledDocument

Called when any of this document's styles have changed.

StyleConstants - Class in javax.swing.text

A collection of well known or common attribute keys and methods to apply to an AttributeSet or MutableAttributeSet to get/set the properties in a typesafe manner.

StyleConstants.CharacterConstants - Class in javax.swing.text

This is a typesafe enumeration of the well-known attributes that contribute to a character style.

StyleConstants.ColorConstants - Class in javax.swing.text

This is a typesafe enumeration of the well-known attributes that contribute to a color.

StyleConstants.FontConstants - Class in javax.swing.text

This is a typesafe enumeration of the well-known attributes that contribute to a font.

StyleConstants.ParagraphConstants - Class in javax.swing.text

This is a typesafe enumeration of the well-known attributes that contribute to a paragraph style.

StyleContext - Class in javax.swing.text

A pool of styles and their associated resources.

StyleContext() - Constructor for class javax.swing.text.StyleContext

Creates a new StyleContext object.

StyleContext.NamedStyle - Class in javax.swing.text

A collection of attributes, typically used to represent character and paragraph styles.

StyleContext.NamedStyle(String, Style) - Constructor for class javax.swing.text.StyleContext.NamedStyle

Creates a new named style.

StyleContext.NamedStyle(Style) - Constructor for class javax.swing.text.StyleContext.NamedStyle

Creates a new named style.

StyleContext.NamedStyle() - Constructor for class javax.swing.text.StyleContext.NamedStyle

Creates a new named style, with a null name and parent.

StyleContext.SmallAttributeSet - Class in javax.swing.text

This class holds a small number of attributes in an array.

StyleContext.SmallAttributeSet(Object[]) - Constructor for class javax.swing.text.StyleContext.SmallAttributeSet

StyleContext.SmallAttributeSet(AttributeSet) - Constructor for class javax.swing.text.StyleContext.SmallAttributeSet

StyledDocument - Interface in javax.swing.text

Interface for a generic styled document.

StyledEditorKit - Class in javax.swing.text

This is the set of things needed by a text component to be a reasonably functioning editor for some type of text document.

StyledEditorKit() - Constructor for class javax.swing.text.StyledEditorKit

Creates a new EditorKit used for styled documents.

StyledEditorKit.AlignmentAction - Class in javax.swing.text

An action to set paragraph alignment.

StyledEditorKit.AlignmentAction(String, int) - Constructor for class javax.swing.text.StyledEditorKit.AlignmentAction

Creates a new AlignmentAction.

StyledEditorKit.BoldAction - Class in javax.swing.text

An action to toggle the bold attribute.

StyledEditorKit.BoldAction() - Constructor for class javax.swing.text.StyledEditorKit.BoldAction

Constructs a new BoldAction.

StyledEditorKit.FontFamilyAction - Class in javax.swing.text

An action to set the font family in the associated JEditorPane.

StyledEditorKit.FontFamilyAction(String, String) - Constructor for class javax.swing.text.StyledEditorKit.FontFamilyAction

Creates a new FontFamilyAction.

StyledEditorKit.FontSizeAction - Class in javax.swing.text

An action to set the font size in the associated JEditorPane.

StyledEditorKit.FontSizeAction(String, int) - Constructor for class javax.swing.text.StyledEditorKit.FontSizeAction

Creates a new FontSizeAction.

StyledEditorKit.ForegroundAction - Class in javax.swing.text

An action to set foreground color.

StyledEditorKit.ForegroundAction(String, Color) - Constructor for class javax.swing.text.StyledEditorKit.ForegroundAction

Creates a new ForegroundAction.

StyledEditorKit.ItalicAction - Class in javax.swing.text

An action to toggle the italic attribute.

StyledEditorKit.ItalicAction() - Constructor for class javax.swing.text.StyledEditorKit.ItalicAction

Constructs a new ItalicAction.

StyledEditorKit.StyledTextAction - Class in javax.swing.text

An action that assumes it's being fired on a JEditorPane with a StyledEditorKit (or subclass) installed.

StyledEditorKit.StyledTextAction(String) - Constructor for class javax.swing.text.StyledEditorKit.StyledTextAction

Creates a new StyledTextAction from a string action name.

StyledEditorKit.UnderlineAction - Class in javax.swing.text

An action to toggle the underline attribute.

StyledEditorKit.UnderlineAction() - Constructor for class javax.swing.text.StyledEditorKit.UnderlineAction

Constructs a new UnderlineAction.

StyleSheet - Class in javax.swing.text.html

Support for defining the visual characteristics of HTML views being rendered.

StyleSheet() - Constructor for class javax.swing.text.html.StyleSheet

Construct a StyleSheet

StyleSheet.BoxPainter - Class in javax.swing.text.html

Class to carry out some of the duties of CSS formatting.

StyleSheet.ListPainter - Class in javax.swing.text.html

Class to carry out some of the duties of CSS list formatting.

SUB - Static variable in class javax.swing.text.html.HTML.Tag

SUBCLASS_IMPLEMENTATION_PERMISSION - Static variable in interface java.io.ObjectStreamConstants

Enable overriding of readObject and writeObject.

subdivide(CubicCurve2D, CubicCurve2D) - Method in class java.awt.geom.CubicCurve2D

Subdivides this cubic curve and stores the resulting two subdivided curves into the left and right curve parameters.

subdivide(CubicCurve2D, CubicCurve2D, CubicCurve2D) - Static method in class java.awt.geom.CubicCurve2D

Subdivides the cubic curve specified by the src parameter and stores the resulting two subdivided curves into the left and right curve parameters.

subdivide(double[], int, double[], int, double[], int) - Static method in class java.awt.geom.CubicCurve2D

Subdivides the cubic curve specified by the coordinates stored in the src array at indices srcoff through (srcoff + 7) and stores the resulting two subdivided curves into the two result arrays at the corresponding indices.

subdivide(QuadCurve2D, QuadCurve2D) - Method in class java.awt.geom.QuadCurve2D

Subdivides this QuadCurve2D and stores the resulting two subdivided curves into the left and right curve parameters.

subdivide(QuadCurve2D, QuadCurve2D, QuadCurve2D) - Static method in class java.awt.geom.QuadCurve2D

Subdivides the quadratic curve specified by the src parameter and stores the resulting two subdivided curves into the left and right curve parameters.

subdivide(double[], int, double[], int, double[], int) - Static method in class java.awt.geom.QuadCurve2D

Subdivides the quadratic curve specified by the coordinates stored in the src array at indices srcoff through srcoff + 5 and stores the resulting two subdivided curves into the two result arrays at the corresponding indices.

Subject - Class in javax.security.auth

A Subject represents a grouping of related information for a single entity, such as a person.

Subject() - Constructor for class javax.security.auth.Subject

Create an instance of a Subject with an empty Set of Principals and empty Sets of public and private credentials.

Subject(boolean, Set<? extends Principal>, Set<?>, Set<?>) - Constructor for class javax.security.auth.Subject

Create an instance of a Subject with Principals and credentials.

SubjectDelegationPermission - Class in javax.management.remote

Permission required by an authentication identity to perform operations on behalf of an authorization identity.

SubjectDelegationPermission(String) - Constructor for class javax.management.remote.SubjectDelegationPermission

Creates a new SubjectDelegationPermission with the specified name.

SubjectDelegationPermission(String, String) - Constructor for class javax.management.remote.SubjectDelegationPermission

Creates a new SubjectDelegationPermission object with the specified name.

SubjectDomainCombiner - Class in javax.security.auth

A SubjectDomainCombiner updates ProtectionDomains with Principals from the Subject associated with this SubjectDomainCombiner.

SubjectDomainCombiner(Subject) - Constructor for class javax.security.auth.SubjectDomainCombiner

Associate the provided Subject with this SubjectDomainCombiner.

subList(int, int) - Method in class java.util.AbstractList

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

subList(int, int) - Method in class java.util.ArrayList

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

subList(int, int) - Method in class java.util.concurrent.CopyOnWriteArrayList

Returns a view of the portion of this list between fromIndex, inclusive, and toIndex, exclusive.

subList(int, int) - Method in interface java.util.List

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

subList(int, int) - Method in class java.util.Vector

Returns a view of the portion of this List between fromIndex, inclusive, and toIndex, exclusive.

subMap(K, boolean, K, boolean) - Method in interface java.util.concurrent.ConcurrentNavigableMap

subMap(K, K) - Method in interface java.util.concurrent.ConcurrentNavigableMap

subMap(K, boolean, K, boolean) - Method in class java.util.concurrent.ConcurrentSkipListMap

subMap(K, K) - Method in class java.util.concurrent.ConcurrentSkipListMap

subMap(K, boolean, K, boolean) - Method in interface java.util.NavigableMap

Returns a view of the portion of this map whose keys range from fromKey to toKey.

subMap(K, K) - Method in interface java.util.NavigableMap

Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive.

subMap(K, K) - Method in interface java.util.SortedMap

Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive.

subMap(K, boolean, K, boolean) - Method in class java.util.TreeMap

subMap(K, K) - Method in class java.util.TreeMap

SUBMISSION_INTERRUPTED - Static variable in class javax.print.attribute.standard.JobStateReason

The job was not completely submitted for some unforeseen reason.

submit(Runnable) - Method in class java.util.concurrent.AbstractExecutorService

submit(Runnable, T) - Method in class java.util.concurrent.AbstractExecutorService

submit(Callable<T>) - Method in class java.util.concurrent.AbstractExecutorService

submit(Callable<V>) - Method in interface java.util.concurrent.CompletionService

Submits a value-returning task for execution and returns a Future representing the pending results of the task.

submit(Runnable, V) - Method in interface java.util.concurrent.CompletionService

Submits a Runnable task for execution and returns a Future representing that task.

submit(Callable<V>) - Method in class java.util.concurrent.ExecutorCompletionService

submit(Runnable, V) - Method in class java.util.concurrent.ExecutorCompletionService

submit(Callable<T>) - Method in interface java.util.concurrent.ExecutorService

Submits a value-returning task for execution and returns a Future representing the pending results of the task.

submit(Runnable, T) - Method in interface java.util.concurrent.ExecutorService

Submits a Runnable task for execution and returns a Future representing that task.

submit(Runnable) - Method in interface java.util.concurrent.ExecutorService

Submits a Runnable task for execution and returns a Future representing that task.

submit(ForkJoinTask<T>) - Method in class java.util.concurrent.ForkJoinPool

Submits a ForkJoinTask for execution.

submit(Callable<T>) - Method in class java.util.concurrent.ForkJoinPool

submit(Runnable, T) - Method in class java.util.concurrent.ForkJoinPool

submit(Runnable) - Method in class java.util.concurrent.ForkJoinPool

submit(Runnable) - Method in class java.util.concurrent.ScheduledThreadPoolExecutor

submit(Runnable, T) - Method in class java.util.concurrent.ScheduledThreadPoolExecutor

submit(Callable<T>) - Method in class java.util.concurrent.ScheduledThreadPoolExecutor

SUBMIT - Static variable in class javax.swing.text.html.FormView

Deprecated.
As of 1.3, value now comes from UIManager property FormView.submitButtonText

submitData(String) - Method in class javax.swing.text.html.FormView

This method is responsible for submitting the form data.

subpath(int, int) - Method in interface java.nio.file.Path

Returns a relative Path that is a subsequence of the name elements of this path.

subsamplingXOffset - Variable in class javax.imageio.IIOParam

A horizontal offset to be applied to the subsampling grid before subsampling.

subsamplingYOffset - Variable in class javax.imageio.IIOParam

A vertical offset to be applied to the subsampling grid before subsampling.

Subscript - Static variable in class javax.swing.text.StyleConstants

Name of the Subscript attribute.

subSequence(int, int) - Method in interface java.lang.CharSequence

Returns a new CharSequence that is a subsequence of this sequence.

subSequence(int, int) - Method in class java.lang.String

Returns a new character sequence that is a subsequence of this sequence.

subSequence(int, int) - Method in class java.lang.StringBuffer

subSequence(int, int) - Method in class java.nio.CharBuffer

Creates a new character buffer that represents the specified subsequence of this buffer, relative to the current position.

subSequence(int, int) - Method in class javax.swing.text.Segment

Returns a new CharSequence that is a subsequence of this sequence.

subSet(E, boolean, E, boolean) - Method in class java.util.concurrent.ConcurrentSkipListSet

subSet(E, E) - Method in class java.util.concurrent.ConcurrentSkipListSet

subSet(E, boolean, E, boolean) - Method in interface java.util.NavigableSet

Returns a view of the portion of this set whose elements range from fromElement to toElement.

subSet(E, E) - Method in interface java.util.NavigableSet

Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive.

subSet(E, E) - Method in interface java.util.SortedSet

Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive.

subSet(E, boolean, E, boolean) - Method in class java.util.TreeSet

subSet(E, E) - Method in class java.util.TreeSet

substituteColorModel(ColorModel, ColorModel) - Method in class java.awt.image.RGBImageFilter

Registers two ColorModel objects for substitution.

SUBSTITUTION_PERMISSION - Static variable in interface java.io.ObjectStreamConstants

Enable substitution of one object for another during serialization/deserialization.

substring(int) - Method in class java.lang.String

Returns a new string that is a substring of this string.

substring(int, int) - Method in class java.lang.String

Returns a new string that is a substring of this string.

substring(int) - Method in class java.lang.StringBuffer

substring(int, int) - Method in class java.lang.StringBuffer

substringData(int, int) - Method in interface org.w3c.dom.CharacterData

Extracts a range of data from the node.

subtract(Area) - Method in class java.awt.geom.Area

Subtracts the shape of the specified Area from the shape of this Area.

subtract(BigDecimal) - Method in class java.math.BigDecimal

Returns a BigDecimal whose value is (this - subtrahend), and whose scale is max(this.scale(), subtrahend.scale()).

subtract(BigDecimal, MathContext) - Method in class java.math.BigDecimal

Returns a BigDecimal whose value is (this - subtrahend), with rounding according to the context settings.

subtract(BigInteger) - Method in class java.math.BigInteger

Returns a BigInteger whose value is (this - val).

SUBTRACT - Static variable in class javax.xml.crypto.dsig.spec.XPathType.Filter

The subtract filter operation.

subtract(Duration) - Method in class javax.xml.datatype.Duration

Computes a new duration whose value is this-rhs.

SUBTREE_SCOPE - Static variable in class javax.naming.directory.SearchControls

Search the entire subtree rooted at the named object.

SUBTREE_SCOPE - Static variable in interface javax.naming.event.EventContext

Constant for expressing interest in events concerning objects in the subtree of the object named by the target, including the object named by the target.

SUBWINDOW_OF - Static variable in class javax.accessibility.AccessibleRelation

Indicates that an object is a subwindow of one or more objects.

SUBWINDOW_OF_PROPERTY - Static variable in class javax.accessibility.AccessibleRelation

Indicates the SUBWINDOW_OF relation between two or more objects has changed.

SUCCESS_NO_INFO - Static variable in interface java.sql.Statement

The constant indicating that a batch statement executed successfully but that no count of the number of rows it affected is available.

SUCCESSFUL - Interface in org.omg.PortableInterceptor

org/omg/PortableInterceptor/SUCCESSFUL.java .

SUFFICIENT - Static variable in class javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag

Sufficient LoginModule.

suffixes - Variable in class javax.imageio.spi.ImageReaderWriterSpi

An array of strings to be returned from getFileSuffixes, initially null.

sum(Spring, Spring) - Static method in class javax.swing.Spring

Returns s1+s2: a spring representing s1 and s2 in series.

SUNDANESE - Static variable in class java.lang.Character.UnicodeBlock

Constant for the "Sundanese" Unicode character block.

SUNDAY - Static variable in class java.util.Calendar

Value of the Calendar.DAY_OF_WEEK field indicating Sunday.

SUP - Static variable in class javax.swing.text.html.HTML.Tag

superLayout(Container) - Method in class javax.swing.plaf.metal.MetalComboBoxUI.MetalComboBoxLayoutManager

SUPERSCRIPT - Static variable in class java.awt.font.TextAttribute

Attribute key for superscripting and subscripting.

Superscript - Static variable in class javax.swing.text.StyleConstants

Name of the Superscript attribute.

SUPERSCRIPT_SUB - Static variable in class java.awt.font.TextAttribute

Standard subscript.

SUPERSCRIPT_SUPER - Static variable in class java.awt.font.TextAttribute

Standard superscript.

SUPERSCRIPTS_AND_SUBSCRIPTS - Static variable in class java.lang.Character.UnicodeBlock

Constant for the "Superscripts and Subscripts" Unicode character block.

SUPPLEMENTAL_ARROWS_A - Static variable in class java.lang.Character.UnicodeBlock

Constant for the "Supplemental Arrows-A" Unicode character block.

SUPPLEMENTAL_ARROWS_B - Static variable in class java.lang.Character.UnicodeBlock

Constant for the "Supplemental Arrows-B" Unicode character block.

SUPPLEMENTAL_MATHEMATICAL_OPERATORS - Static variable in class java.lang.Character.UnicodeBlock

Constant for the "Supplemental Mathematical Operators" Unicode character block.

SUPPLEMENTAL_PUNCTUATION - Static variable in class java.lang.Character.UnicodeBlock

Constant for the "Supplemental Punctuation" Unicode character block.

SUPPLEMENTARY_PRIVATE_USE_AREA_A - Static variable in class java.lang.Character.UnicodeBlock

Constant for the "Supplementary Private Use Area-A" Unicode character block.

SUPPLEMENTARY_PRIVATE_USE_AREA_B - Static variable in class java.lang.Character.UnicodeBlock

Constant for the "Supplementary Private Use Area-B" Unicode character block.

SUPPORT_DTD - Static variable in class javax.xml.stream.XMLInputFactory

The property that requires the parser to support DTDs

SUPPORTED - Static variable in class javax.print.attribute.standard.ColorSupported

The printer is capable of some type of color printing, such as highlight color or full process color.

SupportedAnnotationTypes - Annotation Type in javax.annotation.processing

An annotation used to indicate what annotation types an annotation processor supports.

supportedFileAttributeViews() - Method in class java.nio.file.FileSystem

Returns the set of the names of the file attribute views supported by this FileSystem.

supportedOptions() - Method in interface java.nio.channels.NetworkChannel

Returns a set of the socket options supported by this channel.

SupportedOptions - Annotation Type in javax.annotation.processing

An annotation used to indicate what options an annotation processor supports.

SupportedSourceVersion - Annotation Type in javax.annotation.processing

An annotation used to indicate the latest source version an annotation processor supports.

SupportedValuesAttribute - Interface in javax.print.attribute

Interface SupportedValuesAttribute is a tagging interface which a printing attribute class implements to indicate the attribute describes the supported values for another attribute.

supportsAlterTableWithAddColumn() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports ALTER TABLE with add column.

supportsAlterTableWithDropColumn() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports ALTER TABLE with drop column.

supportsANSI92EntryLevelSQL() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports the ANSI92 entry level SQL grammar.

supportsANSI92FullSQL() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports the ANSI92 full SQL grammar supported.

supportsANSI92IntermediateSQL() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports the ANSI92 intermediate SQL grammar supported.

supportsBatchUpdates() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports batch updates.

supportsCatalogsInDataManipulation() - Method in interface java.sql.DatabaseMetaData

Retrieves whether a catalog name can be used in a data manipulation statement.

supportsCatalogsInIndexDefinitions() - Method in interface java.sql.DatabaseMetaData

Retrieves whether a catalog name can be used in an index definition statement.

supportsCatalogsInPrivilegeDefinitions() - Method in interface java.sql.DatabaseMetaData

Retrieves whether a catalog name can be used in a privilege definition statement.

supportsCatalogsInProcedureCalls() - Method in interface java.sql.DatabaseMetaData

Retrieves whether a catalog name can be used in a procedure call statement.

supportsCatalogsInTableDefinitions() - Method in interface java.sql.DatabaseMetaData

Retrieves whether a catalog name can be used in a table definition statement.

supportsColumnAliasing() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports column aliasing.

supportsConvert() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports the JDBC scalar function CONVERT for the conversion of one JDBC type to another.

supportsConvert(int, int) - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports the JDBC scalar function CONVERT for conversions between the JDBC types fromType and toType.

supportsCoreSQLGrammar() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports the ODBC Core SQL grammar.

supportsCorrelatedSubqueries() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports correlated subqueries.

supportsCrossJoin() - Method in interface javax.sql.rowset.JoinRowSet

Indicates if CROSS_JOIN is supported by a JoinRowSet implementation

supportsCustomEditor() - Method in interface java.beans.PropertyEditor

Determines whether this property editor supports a custom editor.

supportsCustomEditor() - Method in class java.beans.PropertyEditorSupport

Determines whether the propertyEditor can provide a custom editor.

supportsDataDefinitionAndDataManipulationTransactions() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports both data definition and data manipulation statements within a transaction.

supportsDataManipulationTransactionsOnly() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports only data manipulation statements within a transaction.

supportsDifferentTableCorrelationNames() - Method in interface java.sql.DatabaseMetaData

Retrieves whether, when table correlation names are supported, they are restricted to being different from the names of the tables.

supportsExpressionsInOrderBy() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports expressions in ORDER BY lists.

supportsExtendedSQLGrammar() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports the ODBC Extended SQL grammar.

supportsFileAttributeView(Class<? extends FileAttributeView>) - Method in class java.nio.file.FileStore

Tells whether or not this file store supports the file attributes identified by the given file attribute view.

supportsFileAttributeView(String) - Method in class java.nio.file.FileStore

Tells whether or not this file store supports the file attributes identified by the given file attribute view.

supportsFullJoin() - Method in interface javax.sql.rowset.JoinRowSet

Indicates if FULL_JOIN is supported by a JoinRowSet implementation

supportsFullOuterJoins() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports full nested outer joins.

supportsGetGeneratedKeys() - Method in interface java.sql.DatabaseMetaData

Retrieves whether auto-generated keys can be retrieved after a statement has been executed

supportsGroupBy() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports some form of GROUP BY clause.

supportsGroupByBeyondSelect() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports using columns not included in the SELECT statement in a GROUP BY clause provided that all of the columns in the SELECT statement are included in the GROUP BY clause.

supportsGroupByUnrelated() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports using a column that is not in the SELECT statement in a GROUP BY clause.

supportsInnerJoin() - Method in interface javax.sql.rowset.JoinRowSet

Indicates if INNER_JOIN is supported by a JoinRowSet implementation

supportsIntegrityEnhancementFacility() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports the SQL Integrity Enhancement Facility.

supportsLeftOuterJoin() - Method in interface javax.sql.rowset.JoinRowSet

Indicates if LEFT_OUTER_JOIN is supported by a JoinRowSet implementation

supportsLikeEscapeClause() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports specifying a LIKE escape clause.

supportsLimitedOuterJoins() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database provides limited support for outer joins.

supportsMinimumSQLGrammar() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports the ODBC Minimum SQL grammar.

supportsMixedCaseIdentifiers() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database treats mixed case unquoted SQL identifiers as case sensitive and as a result stores them in mixed case.

supportsMixedCaseQuotedIdentifiers() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database treats mixed case quoted SQL identifiers as case sensitive and as a result stores them in mixed case.

supportsMulticast() - Method in class java.net.NetworkInterface

Returns whether a network interface supports multicasting or not.

supportsMultipleOpenResults() - Method in interface java.sql.DatabaseMetaData

Retrieves whether it is possible to have multiple ResultSet objects returned from a CallableStatement object simultaneously.

supportsMultipleResultSets() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports getting multiple ResultSet objects from a single call to the method execute.

supportsMultipleTransactions() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database allows having multiple transactions open at once (on different connections).

supportsNamedParameters() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports named parameters to callable statements.

supportsNonNullableColumns() - Method in interface java.sql.DatabaseMetaData

Retrieves whether columns in this database may be defined as non-nullable.

supportsOpenCursorsAcrossCommit() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports keeping cursors open across commits.

supportsOpenCursorsAcrossRollback() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports keeping cursors open across rollbacks.

supportsOpenStatementsAcrossCommit() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports keeping statements open across commits.

supportsOpenStatementsAcrossRollback() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports keeping statements open across rollbacks.

supportsOrderByUnrelated() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports using a column that is not in the SELECT statement in an ORDER BY clause.

supportsOuterJoins() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports some form of outer join.

supportsParameter(Object) - Method in class java.security.Provider.Service

Test whether this Service can use the specified parameter.

supportsPositionedDelete() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports positioned DELETE statements.

supportsPositionedUpdate() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports positioned UPDATE statements.

supportsResultSetConcurrency(int, int) - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports the given concurrency type in combination with the given result set type.

supportsResultSetHoldability(int) - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports the given result set holdability.

supportsResultSetType(int) - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports the given result set type.

supportsRightOuterJoin() - Method in interface javax.sql.rowset.JoinRowSet

Indicates if RIGHT_OUTER_JOIN is supported by a JoinRowSet implementation

supportsSavepoints() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports savepoints.

supportsSchemasInDataManipulation() - Method in interface java.sql.DatabaseMetaData

Retrieves whether a schema name can be used in a data manipulation statement.

supportsSchemasInIndexDefinitions() - Method in interface java.sql.DatabaseMetaData

Retrieves whether a schema name can be used in an index definition statement.

supportsSchemasInPrivilegeDefinitions() - Method in interface java.sql.DatabaseMetaData

Retrieves whether a schema name can be used in a privilege definition statement.

supportsSchemasInProcedureCalls() - Method in interface java.sql.DatabaseMetaData

Retrieves whether a schema name can be used in a procedure call statement.

supportsSchemasInTableDefinitions() - Method in interface java.sql.DatabaseMetaData

Retrieves whether a schema name can be used in a table definition statement.

supportsSelectForUpdate() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports SELECT FOR UPDATE statements.

supportsStandardImageMetadataFormat - Variable in class javax.imageio.spi.ImageReaderWriterSpi

A boolean indicating whether this plug-in supports the standard metadata format for image metadata, initially false.

supportsStandardStreamMetadataFormat - Variable in class javax.imageio.spi.ImageReaderWriterSpi

A boolean indicating whether this plug-in supports the standard metadata format for stream metadata, initially false.

supportsStatementPooling() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports statement pooling.

supportsStoredFunctionsUsingCallSyntax() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports invoking user-defined or vendor functions using the stored procedure escape syntax.

supportsStoredProcedures() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports stored procedure calls that use the stored procedure escape syntax.

supportsSubqueriesInComparisons() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports subqueries in comparison expressions.

supportsSubqueriesInExists() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports subqueries in EXISTS expressions.

supportsSubqueriesInIns() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports subqueries in IN expressions.

supportsSubqueriesInQuantifieds() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports subqueries in quantified expressions.

supportsTableCorrelationNames() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports table correlation names.

supportsTransactionIsolationLevel(int) - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports the given transaction isolation level.

supportsTransactions() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports transactions.

supportsUnion() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports SQL UNION.

supportsUnionAll() - Method in interface java.sql.DatabaseMetaData

Retrieves whether this database supports SQL UNION ALL.

supportsUpdatableView() - Method in class javax.sql.rowset.spi.SyncProvider

Returns whether this SyncProvider implementation can perform synchronization between a RowSet object and the SQL VIEW in the data source from which the RowSet object got its data.

supportsUrgentData() - Method in class java.net.SocketImpl

Returns whether or not this SocketImpl supports sending urgent data.

SuppressWarnings - Annotation Type in java.lang

Indicates that the named compiler warnings should be suppressed in the annotated element (and in all program elements contained in the annotated element).

SURROGATE - Static variable in class java.lang.Character

General category "Cs" in the Unicode specification.

SURROGATES_AREA - Static variable in class java.lang.Character.UnicodeBlock

Deprecated.
As of J2SE 5, use Character.UnicodeBlock.HIGH_SURROGATES, Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES, and Character.UnicodeBlock.LOW_SURROGATES. These new constants match the block definitions of the Unicode Standard. The Character.UnicodeBlock.of(char) and Character.UnicodeBlock.of(int) methods return the new constants, not SURROGATES_AREA.

suspend() - Method in class java.lang.Thread

Deprecated.
This method has been deprecated, as it is inherently deadlock-prone. If the target thread holds a lock on the monitor protecting a critical system resource when it is suspended, no thread can access this resource until the target thread is resumed. If the thread that would resume the target thread attempts to lock this monitor prior to calling resume, deadlock results. Such deadlocks typically manifest themselves as "frozen" processes. For more information, see Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?.

suspend() - Method in class java.lang.ThreadGroup

Deprecated.
This method is inherently deadlock-prone. See Thread.suspend() for details.

sval - Variable in class java.io.StreamTokenizer

If the current token is a word token, this field contains a string giving the characters of the word token.

SW_RESIZE_CURSOR - Static variable in class java.awt.Cursor

The south-west-resize cursor type.

SW_RESIZE_CURSOR - Static variable in class java.awt.Frame

Deprecated.
replaced by Cursor.SW_RESIZE_CURSOR.

swap(List<?>, int, int) - Static method in class java.util.Collections

Swaps the elements at the specified positions in the specified list.

SWAP_COLORS - Static variable in class java.awt.font.TextAttribute

Attribute key for swapping foreground and background Paints.

SWAP_COLORS_ON - Static variable in class java.awt.font.TextAttribute

Swap foreground and background.

SWING_COMPONENT - Static variable in class javax.accessibility.AccessibleRole

A Swing component, but nothing else is known about it.

SwingConstants - Interface in javax.swing

A collection of constants generally used for positioning and orienting components on the screen.

SwingPropertyChangeSupport - Class in javax.swing.event

This subclass of java.beans.PropertyChangeSupport is almost identical in functionality.

SwingPropertyChangeSupport(Object) - Constructor for class javax.swing.event.SwingPropertyChangeSupport

Constructs a SwingPropertyChangeSupport object.

SwingPropertyChangeSupport(Object, boolean) - Constructor for class javax.swing.event.SwingPropertyChangeSupport

Constructs a SwingPropertyChangeSupport object.

SwingUtilities - Class in javax.swing

A collection of utility methods for Swing.

SwingWorker<T,V> - Class in javax.swing

An abstract class to perform lengthy GUI-interaction tasks in a background thread.

SwingWorker() - Constructor for class javax.swing.SwingWorker

Constructs this SwingWorker.

SwingWorker.StateValue - Enum in javax.swing

Values for the state bound property.

SwitchPoint - Class in java.lang.invoke

A SwitchPoint is an object which can publish state transitions to other threads.

SwitchPoint() - Constructor for class java.lang.invoke.SwitchPoint

Creates a new switch point.

SYLOTI_NAGRI - Static variable in class java.lang.Character.UnicodeBlock

Constant for the "Syloti Nagri" Unicode character block.

sync() - Method in class java.awt.Toolkit

Synchronizes this toolkit's graphics state.

sync() - Method in class java.io.FileDescriptor

Force all system buffers to synchronize with the underlying device.

sync() - Method in class java.util.prefs.AbstractPreferences

Implements the sync method as per the specification in Preferences.sync().

sync() - Method in class java.util.prefs.Preferences

Ensures that future reads from this preference node and its descendants reflect any changes that were committed to the persistent store (from any VM) prior to the sync invocation.

SYNC_FLUSH - Static variable in class java.util.zip.Deflater

Compression flush mode used to flush out all pending output; may degrade compression for some compression algorithms.

sync_scope() - Method in interface org.omg.PortableInterceptor.RequestInfoOperations

Defines how far the request shall progress before control is returned to the client.

SYNC_WITH_TRANSPORT - Interface in org.omg.Messaging

org/omg/Messaging/SYNC_WITH_TRANSPORT.java .

syncAll(MutableCallSite[]) - Static method in class java.lang.invoke.MutableCallSite

Performs a synchronization operation on each call site in the given array, forcing all other threads to throw away any cached values previously loaded from the target of any of the call sites.

syncAllWidths - Variable in class javax.swing.plaf.basic.BasicOptionPaneUI.ButtonAreaLayout

SyncFactory - Class in javax.sql.rowset.spi

The Service Provider Interface (SPI) mechanism that generates SyncProvider instances to be used by disconnected RowSet objects.

SyncFactoryException - Exception in javax.sql.rowset.spi

Indicates an error with SyncFactory mechanism.

SyncFactoryException() - Constructor for exception javax.sql.rowset.spi.SyncFactoryException

Creates new SyncFactoryException without detail message.

SyncFactoryException(String) - Constructor for exception javax.sql.rowset.spi.SyncFactoryException

Constructs an SyncFactoryException with the specified detail message.

SyncFailedException - Exception in java.io

Signals that a sync operation has failed.

SyncFailedException(String) - Constructor for exception java.io.SyncFailedException

Constructs an SyncFailedException with a detail message.

synchronize(Line[], boolean) - Method in interface javax.sound.sampled.Mixer

Synchronizes two or more lines.

SYNCHRONIZED - Static variable in class java.lang.reflect.修饰符

The int value representing the synchronized modifier.

synchronizedCollection(Collection<T>) - Static method in class java.util.Collections

Returns a synchronized (thread-safe) collection backed by the specified collection.

synchronizedList(List<T>) - Static method in class java.util.Collections

Returns a synchronized (thread-safe) list backed by the specified list.

synchronizedMap(Map<K, V>) - Static method in class java.util.Collections

Returns a synchronized (thread-safe) map backed by the specified map.

synchronizedSet(Set<T>) - Static method in class java.util.Collections

Returns a synchronized (thread-safe) set backed by the specified set.

synchronizedSortedMap(SortedMap<K, V>) - Static method in class java.util.Collections

Returns a synchronized (thread-safe) sorted map backed by the specified sorted map.

synchronizedSortedSet(SortedSet<T>) - Static method in class java.util.Collections

Returns a synchronized (thread-safe) sorted set backed by the specified sorted set.

synchronizedView(AttributeSet) - Static method in class javax.print.attribute.AttributeSetUtilities

Creates a synchronized view of the given attribute set.

synchronizedView(DocAttributeSet) - Static method in class javax.print.attribute.AttributeSetUtilities

Creates a synchronized view of the given doc attribute set.

synchronizedView(PrintRequestAttributeSet) - Static method in class javax.print.attribute.AttributeSetUtilities

Creates a synchronized view of the given print request attribute set.

synchronizedView(PrintJobAttributeSet) - Static method in class javax.print.attribute.AttributeSetUtilities

Creates a synchronized view of the given print job attribute set.

synchronizedView(PrintServiceAttributeSet) - Static method in class javax.print.attribute.AttributeSetUtilities

Creates a synchronized view of the given print service attribute set.

SynchronousQueue<E> - Class in java.util.concurrent

A blocking queue in which each insert operation must wait for a corresponding remove operation by another thread, and vice versa.

SynchronousQueue() - Constructor for class java.util.concurrent.SynchronousQueue

Creates a SynchronousQueue with nonfair access policy.

SynchronousQueue(boolean) - Constructor for class java.util.concurrent.SynchronousQueue

Creates a SynchronousQueue with the specified fairness policy.

SyncProvider - Class in javax.sql.rowset.spi

The synchronization mechanism that provides reader/writer capabilities for disconnected RowSet objects.

SyncProvider() - Constructor for class javax.sql.rowset.spi.SyncProvider

Creates a default SyncProvider object.

SyncProviderException - Exception in javax.sql.rowset.spi

Indicates an error with the SyncProvider mechanism.

SyncProviderException() - Constructor for exception javax.sql.rowset.spi.SyncProviderException

Creates a new SyncProviderException object without a detail message.

SyncProviderException(String) - Constructor for exception javax.sql.rowset.spi.SyncProviderException

Constructs a SyncProviderException object with the specified detail message.

SyncProviderException(SyncResolver) - Constructor for exception javax.sql.rowset.spi.SyncProviderException

Constructs a SyncProviderException object with the specified SyncResolver instance.

SyncResolver - Interface in javax.sql.rowset.spi

Defines a framework that allows applications to use a manual decision tree to decide what should be done when a synchronization conflict occurs.

SyncScopeHelper - Class in org.omg.Messaging

Synchronization scope

SyncScopeHelper() - Constructor for class org.omg.Messaging.SyncScopeHelper

syncScrollPaneWithViewport() - Method in class javax.swing.plaf.basic.BasicScrollPaneUI

syncSpi() - Method in class java.util.prefs.AbstractPreferences

This method is invoked with this node locked.

syncWithScrollPane(JScrollPane) - Method in class javax.swing.ScrollPaneLayout

This method is invoked after the ScrollPaneLayout is set as the LayoutManager of a JScrollPane.

SYNTAX_ERR - Static variable in exception org.w3c.dom.DOMException

If an invalid or illegal string is specified.

SynthButtonUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JButton.

SynthButtonUI() - Constructor for class javax.swing.plaf.synth.SynthButtonUI

SynthCheckBoxMenuItemUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JCheckBoxMenuItem.

SynthCheckBoxMenuItemUI() - Constructor for class javax.swing.plaf.synth.SynthCheckBoxMenuItemUI

SynthCheckBoxUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JCheckBox.

SynthCheckBoxUI() - Constructor for class javax.swing.plaf.synth.SynthCheckBoxUI

SynthColorChooserUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JColorChooser.

SynthColorChooserUI() - Constructor for class javax.swing.plaf.synth.SynthColorChooserUI

SynthComboBoxUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JComboBox.

SynthComboBoxUI() - Constructor for class javax.swing.plaf.synth.SynthComboBoxUI

SynthConstants - Interface in javax.swing.plaf.synth

Constants used by Synth.

SynthContext - Class in javax.swing.plaf.synth

An immutable transient object containing contextual information about a Region.

SynthContext(JComponent, Region, SynthStyle, int) - Constructor for class javax.swing.plaf.synth.SynthContext

Creates a SynthContext with the specified values.

SynthDesktopIconUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for a minimized internal frame on a desktop.

SynthDesktopIconUI() - Constructor for class javax.swing.plaf.synth.SynthDesktopIconUI

SynthDesktopPaneUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JDesktopPane.

SynthDesktopPaneUI() - Constructor for class javax.swing.plaf.synth.SynthDesktopPaneUI

SynthEditorPaneUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JEditorPane.

SynthEditorPaneUI() - Constructor for class javax.swing.plaf.synth.SynthEditorPaneUI

synthesizedElement(Element) - Method in class javax.swing.text.html.HTMLWriter

Returns true if the element is a synthesized element.

Synthesizer - Interface in javax.sound.midi

A Synthesizer generates sound.

SynthFormattedTextFieldUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JFormattedTextField.

SynthFormattedTextFieldUI() - Constructor for class javax.swing.plaf.synth.SynthFormattedTextFieldUI

SynthGraphicsUtils - Class in javax.swing.plaf.synth

Wrapper for primitive graphics calls.

SynthGraphicsUtils() - Constructor for class javax.swing.plaf.synth.SynthGraphicsUtils

Creates a SynthGraphicsUtils.

SynthInternalFrameUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JInternalFrame.

SynthInternalFrameUI(JInternalFrame) - Constructor for class javax.swing.plaf.synth.SynthInternalFrameUI

SynthLabelUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JLabel.

SynthLabelUI() - Constructor for class javax.swing.plaf.synth.SynthLabelUI

SynthListUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JList.

SynthListUI() - Constructor for class javax.swing.plaf.synth.SynthListUI

SynthLookAndFeel - Class in javax.swing.plaf.synth

SynthLookAndFeel provides the basis for creating a customized look and feel.

SynthLookAndFeel() - Constructor for class javax.swing.plaf.synth.SynthLookAndFeel

Creates a SynthLookAndFeel.

SynthMenuBarUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JMenuBar.

SynthMenuBarUI() - Constructor for class javax.swing.plaf.synth.SynthMenuBarUI

SynthMenuItemUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JMenuItem.

SynthMenuItemUI() - Constructor for class javax.swing.plaf.synth.SynthMenuItemUI

SynthMenuUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JMenu.

SynthMenuUI() - Constructor for class javax.swing.plaf.synth.SynthMenuUI

SynthOptionPaneUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JOptionPane.

SynthOptionPaneUI() - Constructor for class javax.swing.plaf.synth.SynthOptionPaneUI

SynthPainter - Class in javax.swing.plaf.synth

SynthPainter is used for painting portions of JComponents.

SynthPainter() - Constructor for class javax.swing.plaf.synth.SynthPainter

SynthPanelUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JPanel.

SynthPanelUI() - Constructor for class javax.swing.plaf.synth.SynthPanelUI

SynthPasswordFieldUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JPasswordField.

SynthPasswordFieldUI() - Constructor for class javax.swing.plaf.synth.SynthPasswordFieldUI

SynthPopupMenuUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JPopupMenu.

SynthPopupMenuUI() - Constructor for class javax.swing.plaf.synth.SynthPopupMenuUI

SynthProgressBarUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JProgressBar.

SynthProgressBarUI() - Constructor for class javax.swing.plaf.synth.SynthProgressBarUI

SynthRadioButtonMenuItemUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JRadioButtonMenuItem.

SynthRadioButtonMenuItemUI() - Constructor for class javax.swing.plaf.synth.SynthRadioButtonMenuItemUI

SynthRadioButtonUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JRadioButton.

SynthRadioButtonUI() - Constructor for class javax.swing.plaf.synth.SynthRadioButtonUI

SynthRootPaneUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JRootPane.

SynthRootPaneUI() - Constructor for class javax.swing.plaf.synth.SynthRootPaneUI

SynthScrollBarUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JScrollBar.

SynthScrollBarUI() - Constructor for class javax.swing.plaf.synth.SynthScrollBarUI

SynthScrollPaneUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JScrollPane.

SynthScrollPaneUI() - Constructor for class javax.swing.plaf.synth.SynthScrollPaneUI

SynthSeparatorUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JSeparator.

SynthSeparatorUI() - Constructor for class javax.swing.plaf.synth.SynthSeparatorUI

SynthSliderUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JSlider.

SynthSliderUI(JSlider) - Constructor for class javax.swing.plaf.synth.SynthSliderUI

SynthSpinnerUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JSpinner.

SynthSpinnerUI() - Constructor for class javax.swing.plaf.synth.SynthSpinnerUI

SynthSplitPaneUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JSplitPane.

SynthSplitPaneUI() - Constructor for class javax.swing.plaf.synth.SynthSplitPaneUI

SynthStyle - Class in javax.swing.plaf.synth

SynthStyle is a set of style properties.

SynthStyle() - Constructor for class javax.swing.plaf.synth.SynthStyle

Constructs a SynthStyle.

SynthStyleFactory - Class in javax.swing.plaf.synth

Factory used for obtaining SynthStyles.

SynthStyleFactory() - Constructor for class javax.swing.plaf.synth.SynthStyleFactory

Creates a SynthStyleFactory.

SynthTabbedPaneUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JTabbedPane.

SynthTabbedPaneUI() - Constructor for class javax.swing.plaf.synth.SynthTabbedPaneUI

SynthTableHeaderUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JTableHeader.

SynthTableHeaderUI() - Constructor for class javax.swing.plaf.synth.SynthTableHeaderUI

SynthTableUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JTable.

SynthTableUI() - Constructor for class javax.swing.plaf.synth.SynthTableUI

SynthTextAreaUI - Class in javax.swing.plaf.synth

Provides the look and feel for a plain text editor in the Synth look and feel.

SynthTextAreaUI() - Constructor for class javax.swing.plaf.synth.SynthTextAreaUI

SynthTextFieldUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JTextField.

SynthTextFieldUI() - Constructor for class javax.swing.plaf.synth.SynthTextFieldUI

SynthTextPaneUI - Class in javax.swing.plaf.synth

Provides the look and feel for a styled text editor in the Synth look and feel.

SynthTextPaneUI() - Constructor for class javax.swing.plaf.synth.SynthTextPaneUI

SynthToggleButtonUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JToggleButton.

SynthToggleButtonUI() - Constructor for class javax.swing.plaf.synth.SynthToggleButtonUI

SynthToolBarUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JToolBar.

SynthToolBarUI() - Constructor for class javax.swing.plaf.synth.SynthToolBarUI

SynthToolTipUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JToolTip.

SynthToolTipUI() - Constructor for class javax.swing.plaf.synth.SynthToolTipUI

SynthTreeUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JTree.

SynthTreeUI() - Constructor for class javax.swing.plaf.synth.SynthTreeUI

SynthUI - Interface in javax.swing.plaf.synth

SynthUI is used to fetch the SynthContext for a particular Component.

SynthViewportUI - Class in javax.swing.plaf.synth

Provides the Synth L&F UI delegate for JViewport.

SynthViewportUI() - Constructor for class javax.swing.plaf.synth.SynthViewportUI

SYRIAC - Static variable in class java.lang.Character.UnicodeBlock

Constant for the "Syriac" Unicode character block.

SysexMessage - Class in javax.sound.midi

A SysexMessage object represents a MIDI system exclusive message.

SysexMessage() - Constructor for class javax.sound.midi.SysexMessage

Constructs a new SysexMessage.

SysexMessage(byte[], int) - Constructor for class javax.sound.midi.SysexMessage

Constructs a new SysexMessage and sets the data for the message.

SysexMessage(int, byte[], int) - Constructor for class javax.sound.midi.SysexMessage

Constructs a new SysexMessage and sets the data for the message.

SysexMessage(byte[]) - Constructor for class javax.sound.midi.SysexMessage

Constructs a new SysexMessage.

System - Class in java.lang

The System class contains several useful class fields and methods.

SYSTEM - Static variable in interface javax.swing.text.html.parser.DTDConstants

SYSTEM_EXCEPTION - Interface in org.omg.PortableInterceptor

org/omg/PortableInterceptor/SYSTEM_EXCEPTION.java .

SYSTEM_EXCLUSIVE - Static variable in class javax.sound.midi.SysexMessage

Status byte for System Exclusive message (0xF0, or 240).

SYSTEM_ID - Static variable in class org.omg.PortableServer.IdAssignmentPolicyValue

SYSTEM_PORT - Static variable in interface java.rmi.activation.ActivationSystem

The port to lookup the activation system.

SYSTEM_RESET - Static variable in class javax.sound.midi.ShortMessage

Status byte for System Reset message (0xFF, or 255).

SystemColor - Class in java.awt

A class to encapsulate symbolic colors representing the color of native GUI objects on a system.

SystemException - Exception in org.omg.CORBA

The root class for all CORBA standard exceptions.

SystemException(String, int, CompletionStatus) - Constructor for exception org.omg.CORBA.SystemException

Constructs a SystemException exception with the specified detail message, minor code, and completion status.

SystemFlavorMap - Class in java.awt.datatransfer

The SystemFlavorMap is a configurable map between "natives" (Strings), which correspond to platform-specific data formats, and "flavors" (DataFlavors), which correspond to platform-independent MIME types.

systemNodeForPackage(Class<?>) - Static method in class java.util.prefs.Preferences

Returns the preference node from the system preference tree that is associated (by convention) with the specified class's package.

systemRoot() - Static method in class java.util.prefs.Preferences

Returns the root preference node for the system.

systemRoot() - Method in interface java.util.prefs.PreferencesFactory

Returns the system root preference node.

SystemTray - Class in java.awt

The SystemTray class represents the system tray for a desktop.

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _

概述

软件包

类

使用

树

已过时

Index

帮助

Java™ Platform
Standard Ed. 7
草案 ea-b138

Prev Letter

Next Letter

框架

无框架

所有的类


T-Index

请注意：本 java api 1.7Beta 规范不是最终稳定版，未来随着版本的更迭，本规范可能有更新。
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _

T

TAB - Static variable in class java.awt.Event
The Tab key.
TabableView - Interface in javax.swing.text
Interface for Views that have size dependent upon tabs.
tabAreaBackground - Variable in class javax.swing.plaf.metal.MetalTabbedPaneUI
tabAreaInsets - Variable in class javax.swing.plaf.basic.BasicTabbedPaneUI
TABBED_PANE - Static variable in class javax.swing.plaf.synth.Region
TabbedPane region.
TABBED_PANE_CONTENT - Static variable in class javax.swing.plaf.synth.Region
Region of a TabbedPane containing the content.
TABBED_PANE_TAB - Static variable in class javax.swing.plaf.synth.Region
Region of a TabbedPane for one tab.
TABBED_PANE_TAB_AREA - Static variable in class javax.swing.plaf.synth.Region
Region of a TabbedPane containing the tabs.
TabbedPaneUI - Class in javax.swing.plaf
Pluggable look and feel interface for JTabbedPane.
TabbedPaneUI() - Constructor for class javax.swing.plaf.TabbedPaneUI
tabChangeListener - Variable in class javax.swing.plaf.basic.BasicTabbedPaneUI
TabExpander - Interface in javax.swing.text
Simple interface to allow for different types of implementations of tab expansion.
tabForCoordinate(JTabbedPane, int, int) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI
Returns the tab index which intersects the specified point in the JTabbedPane's coordinate space.
tabForCoordinate(JTabbedPane, int, int) - Method in class javax.swing.plaf.multi.MultiTabbedPaneUI
Invokes the tabForCoordinate method on each UI handled by this object.
tabForCoordinate(JTabbedPane, int, int) - Method in class javax.swing.plaf.TabbedPaneUI
tabInsets - Variable in class javax.swing.plaf.basic.BasicTabbedPaneUI
TABLE - Static variable in class javax.accessibility.AccessibleRole
An object used to present information in terms of rows and columns.
table - Variable in class javax.swing.plaf.basic.BasicTableUI
TABLE - Static variable in class javax.swing.plaf.synth.Region
Table region.
table - Variable in class javax.swing.table.JTableHeader
The table for which this object is the header; the default is null.
TABLE - Static variable in class javax.swing.text.html.HTML.Tag
TABLE_HEADER - Static variable in class javax.swing.plaf.synth.Region
TableHeader region.
TableCellEditor - Interface in javax.swing.table
This interface defines the method any object that would like to be an editor of values for components such as JListBox, JComboBox, JTree, or JTable needs to implement.
TableCellRenderer - Interface in javax.swing.table
This interface defines the method required by any object that would like to be a renderer for cells in a JTable.
tableChanged(TableModelEvent) - Method in interface javax.swing.event.TableModelListener
This fine grain notification tells listeners the exact range of cells, rows, or columns that changed.
tableChanged(TableModelEvent) - Method in class javax.swing.JTable.AccessibleJTable
Track changes to the table contents
tableChanged(TableModelEvent) - Method in class javax.swing.JTable
Invoked when this table's TableModel generates a TableModelEvent.
TableColumn - Class in javax.swing.table
A TableColumn represents all the attributes of a column in a JTable, such as width, resizibility, minimum and maximum width.
TableColumn() - Constructor for class javax.swing.table.TableColumn
Cover method, using a default model index of 0, default width of 75, a null renderer and a null editor.
TableColumn(int) - Constructor for class javax.swing.table.TableColumn
Cover method, using a default width of 75, a null renderer and a null editor.
TableColumn(int, int) - Constructor for class javax.swing.table.TableColumn
Cover method, using a null renderer and a null editor.
TableColumn(int, int, TableCellRenderer, TableCellEditor) - Constructor for class javax.swing.table.TableColumn
Creates and initializes an instance of TableColumn with the specified model index, width, cell renderer, and cell editor; all TableColumn constructors delegate to this one.
TableColumnModel - Interface in javax.swing.table
Defines the requirements for a table column model object suitable for use with JTable.
TableColumnModelEvent - Class in javax.swing.event
TableColumnModelEvent is used to notify listeners that a table column model has changed, such as a column was added, removed, or moved.
TableColumnModelEvent(TableColumnModel, int, int) - Constructor for class javax.swing.event.TableColumnModelEvent
Constructs a TableColumnModelEvent object.
TableColumnModelListener - Interface in javax.swing.event
TableColumnModelListener defines the interface for an object that listens to changes in a TableColumnModel.
tableColumns - Variable in class javax.swing.table.DefaultTableColumnModel
Array of TableColumn objects in this model
tableHeader - Variable in class javax.swing.JTable
The TableHeader working with the table.
TableHeaderUI - Class in javax.swing.plaf
Pluggable look and feel interface for JTableHeader.
TableHeaderUI() - Constructor for class javax.swing.plaf.TableHeaderUI
tableIndexClustered - Static variable in interface java.sql.DatabaseMetaData
Indicates that this table index is a clustered index.
tableIndexHashed - Static variable in interface java.sql.DatabaseMetaData
Indicates that this table index is a hashed index.
tableIndexOther - Static variable in interface java.sql.DatabaseMetaData
Indicates that this table index is not a clustered index, a hashed index, or table statistics; it is something other than these.
tableIndexStatistic - Static variable in interface java.sql.DatabaseMetaData
Indicates that this column contains table statistics that are returned in conjunction with a table's index descriptions.
TableModel - Interface in javax.swing.table
The TableModel interface specifies the methods the JTable will use to interrogate a tabular data model.
TableModelEvent - Class in javax.swing.event
TableModelEvent is used to notify listeners that a table model has changed.
TableModelEvent(TableModel) - Constructor for class javax.swing.event.TableModelEvent
All row data in the table has changed, listeners should discard any state that was based on the rows and requery the TableModel to get the new row count and all the appropriate values.
TableModelEvent(TableModel, int) - Constructor for class javax.swing.event.TableModelEvent
This row of data has been updated.
TableModelEvent(TableModel, int, int) - Constructor for class javax.swing.event.TableModelEvent
The data in rows [firstRow, lastRow] have been updated.
TableModelEvent(TableModel, int, int, int) - Constructor for class javax.swing.event.TableModelEvent
The cells in column column in the range [firstRow, lastRow] have been updated.
TableModelEvent(TableModel, int, int, int, int) - Constructor for class javax.swing.event.TableModelEvent
The cells from (firstRow, column) to (lastRow, column) have been changed.
TableModelListener - Interface in javax.swing.event
TableModelListener defines the interface for an object that listens to changes in a TableModel.
tableRowsDeleted(TableModelEvent) - Method in class javax.swing.JTable.AccessibleJTable
Track changes to the table contents (row deletions)
tableRowsInserted(TableModelEvent) - Method in class javax.swing.JTable.AccessibleJTable
Track changes to the table contents (row insertions)
TableRowSorter<M extends TableModel> - Class in javax.swing.table
An implementation of RowSorter that provides sorting and filtering using a TableModel.
TableRowSorter() - Constructor for class javax.swing.table.TableRowSorter
Creates a TableRowSorter with an empty model.
TableRowSorter(M) - Constructor for class javax.swing.table.TableRowSorter
Creates a TableRowSorter using model as the underlying TableModel.
TableStringConverter - Class in javax.swing.table
TableStringConverter is used to convert objects from the model into strings.
TableStringConverter() - Constructor for class javax.swing.table.TableStringConverter
TableUI - Class in javax.swing.plaf
Pluggable look and feel interface for JTable.
TableUI() - Constructor for class javax.swing.plaf.TableUI
TableView - Class in javax.swing.text
Implements View interface for a table, that is composed of an element structure where the child elements of the element this view is responsible for represent rows and the child elements of the row elements are cells.
TableView(Element) - Constructor for class javax.swing.text.TableView
Constructs a TableView for the given element.
TableView.TableCell - Class in javax.swing.text
Deprecated.
A table cell can now be any View implementation.
TableView.TableCell(Element) - Constructor for class javax.swing.text.TableView.TableCell
Deprecated.
Constructs a TableCell for the given element.
TableView.TableRow - Class in javax.swing.text
View of a row in a row-centric table.
TableView.TableRow(Element) - Constructor for class javax.swing.text.TableView.TableRow
Constructs a TableView for the given element.
TABLOID - Static variable in class java.awt.PageAttributes.MediaType
An alias for LEDGER.
TABLOID - Static variable in class javax.print.attribute.standard.MediaSize.Other
Specifies the tabloid size, 11 inches by 17 inches.
TABLOID - Static variable in class javax.print.attribute.standard.MediaSizeName
tabloid size .
tabPane - Variable in class javax.swing.plaf.basic.BasicTabbedPaneUI
tabPlacement - Variable in class javax.swing.JTabbedPane
Where the tabs are placed.
tabRunOverlay - Variable in class javax.swing.plaf.basic.BasicTabbedPaneUI
tabRuns - Variable in class javax.swing.plaf.basic.BasicTabbedPaneUI
TabSet - Static variable in class javax.swing.text.StyleConstants
TabSet for the paragraph, type is a TabSet containing TabStops.
TabSet - Class in javax.swing.text
A TabSet is comprised of many TabStops.
TabSet(TabStop[]) - Constructor for class javax.swing.text.TabSet
Creates and returns an instance of TabSet.
tabSizeAttribute - Static variable in class javax.swing.text.PlainDocument
Name of the attribute that specifies the tab size for tabs contained in the content.
TabStop - Class in javax.swing.text
This class encapsulates a single tab stop (basically as tab stops are thought of by RTF).
TabStop(float) - Constructor for class javax.swing.text.TabStop
Creates a tab at position pos with a default alignment and default leader.
TabStop(float, int, int) - Constructor for class javax.swing.text.TabStop
Creates a tab with the specified position pos, alignment align and leader leader.
TabularData - Interface in javax.management.openmbean
The TabularData interface specifies the behavior of a specific type of complex open data objects which represent tabular data structures.
TabularDataSupport - Class in javax.management.openmbean
The TabularDataSupport class is the open data class which implements the TabularData and the Map interfaces, and which is internally based on a hash map data structure.
TabularDataSupport(TabularType) - Constructor for class javax.management.openmbean.TabularDataSupport
Creates an empty TabularDataSupport instance whose open-type is tabularType, and whose underlying HashMap has a default initial capacity (101) and default load factor (0.75).
TabularDataSupport(TabularType, int, float) - Constructor for class javax.management.openmbean.TabularDataSupport
Creates an empty TabularDataSupport instance whose open-type is tabularType, and whose underlying HashMap has the specified initial capacity and load factor.
TabularType - Class in javax.management.openmbean
The TabularType class is the open type class whose instances describe the types of TabularData values.
TabularType(String, String, CompositeType, String[]) - Constructor for class javax.management.openmbean.TabularType
Constructs a TabularType instance, checking for the validity of the given parameters.
tag - Variable in class org.omg.IOP.TaggedComponent
The tag, represented as a component id.
tag - Variable in class org.omg.IOP.TaggedProfile
The tag, represented as a profile id.
TAG_ACNT - Static variable in interface java.awt.font.OpenType
Accent attachment.
TAG_ALTERNATE_IIOP_ADDRESS - Interface in org.omg.IOP
org/omg/IOP/TAG_ALTERNATE_IIOP_ADDRESS.java .
TAG_AVAR - Static variable in interface java.awt.font.OpenType
Axis variaiton.
TAG_BASE - Static variable in interface java.awt.font.OpenType
Baseline data.
TAG_BDAT - Static variable in interface java.awt.font.OpenType
Bitmap data.
TAG_BLOC - Static variable in interface java.awt.font.OpenType
Bitmap location.
TAG_BSLN - Static variable in interface java.awt.font.OpenType
Baseline table.
TAG_CFF - Static variable in interface java.awt.font.OpenType
Compact font format (Type1 font).
TAG_CMAP - Static variable in interface java.awt.font.OpenType
Character to glyph mapping.
TAG_CODE_SETS - Interface in org.omg.IOP
org/omg/IOP/TAG_CODE_SETS.java .
TAG_CVAR - Static variable in interface java.awt.font.OpenType
CVT variation.
TAG_CVT - Static variable in interface java.awt.font.OpenType
Control value table.
TAG_DSIG - Static variable in interface java.awt.font.OpenType
Digital signature.
TAG_EBDT - Static variable in interface java.awt.font.OpenType
Embedded bitmap data.
TAG_EBLC - Static variable in interface java.awt.font.OpenType
Embedded bitmap location.
TAG_EBSC - Static variable in interface java.awt.font.OpenType
Embedded bitmap scaling.
TAG_FDSC - Static variable in interface java.awt.font.OpenType
Font descriptors.
TAG_FEAT - Static variable in interface java.awt.font.OpenType
Feature name.
TAG_FMTX - Static variable in interface java.awt.font.OpenType
Font metrics.
TAG_FPGM - Static variable in interface java.awt.font.OpenType
Font program.
TAG_FVAR - Static variable in interface java.awt.font.OpenType
Font variation.
TAG_GASP - Static variable in interface java.awt.font.OpenType
Grid-fitting and scan conversion procedure.
TAG_GDEF - Static variable in interface java.awt.font.OpenType
Glyph definition.
TAG_GLYF - Static variable in interface java.awt.font.OpenType
Glyph data.
TAG_GPOS - Static variable in interface java.awt.font.OpenType
Glyph positioning.
TAG_GSUB - Static variable in interface java.awt.font.OpenType
Glyph substitution.
TAG_GVAR - Static variable in interface java.awt.font.OpenType
Glyph variation.
TAG_HDMX - Static variable in interface java.awt.font.OpenType
Horizontal device metrics.
TAG_HEAD - Static variable in interface java.awt.font.OpenType
Font header.
TAG_HHEA - Static variable in interface java.awt.font.OpenType
Horizontal metrics header.
TAG_HMTX - Static variable in interface java.awt.font.OpenType
Horizontal metrics.
TAG_INTERNET_IOP - Interface in org.omg.IOP
org/omg/IOP/TAG_INTERNET_IOP.java .
TAG_JAVA_CODEBASE - Interface in org.omg.IOP
org/omg/IOP/TAG_JAVA_CODEBASE.java .
TAG_JSTF - Static variable in interface java.awt.font.OpenType
Justification.
TAG_JUST - Static variable in interface java.awt.font.OpenType
Justification.
TAG_KERN - Static variable in interface java.awt.font.OpenType
Kerning.
TAG_LCAR - Static variable in interface java.awt.font.OpenType
Ligature caret.
TAG_LOCA - Static variable in interface java.awt.font.OpenType
Index to location.
TAG_LTSH - Static variable in interface java.awt.font.OpenType
Linear threshold.
TAG_MAXP - Static variable in interface java.awt.font.OpenType
Maximum profile.
TAG_MMFX - Static variable in interface java.awt.font.OpenType
Multiple master font metrics.
TAG_MMSD - Static variable in interface java.awt.font.OpenType
Multiple master supplementary data.
TAG_MORT - Static variable in interface java.awt.font.OpenType
Glyph metamorphosis.
TAG_MULTIPLE_COMPONENTS - Interface in org.omg.IOP
org/omg/IOP/TAG_MULTIPLE_COMPONENTS.java .
TAG_NAME - Static variable in interface java.awt.font.OpenType
Naming table.
TAG_OPBD - Static variable in interface java.awt.font.OpenType
Optical bounds.
TAG_ORB_TYPE - Interface in org.omg.IOP
org/omg/IOP/TAG_ORB_TYPE.java .
TAG_OS2 - Static variable in interface java.awt.font.OpenType
OS/2 and Windows specific metrics.
TAG_PCLT - Static variable in interface java.awt.font.OpenType
PCL 5 data.
TAG_POLICIES - Interface in org.omg.IOP
org/omg/IOP/TAG_POLICIES.java .
TAG_POST - Static variable in interface java.awt.font.OpenType
PostScript Information.
TAG_PREP - Static variable in interface java.awt.font.OpenType
CVT preprogram.
TAG_PROP - Static variable in interface java.awt.font.OpenType
Glyph properties.
TAG_RMI_CUSTOM_MAX_STREAM_FORMAT - Interface in org.omg.IOP
org/omg/IOP/TAG_RMI_CUSTOM_MAX_STREAM_FORMAT.java .
TAG_TRAK - Static variable in interface java.awt.font.OpenType
Tracking.
TAG_TYP1 - Static variable in interface java.awt.font.OpenType
Adobe Type 1 font data.
TAG_VDMX - Static variable in interface java.awt.font.OpenType
Vertical device metrics.
TAG_VHEA - Static variable in interface java.awt.font.OpenType
Vertical metrics header.
TAG_VMTX - Static variable in interface java.awt.font.OpenType
Vertical metrics.
TAGALOG - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Tagalog" Unicode character block.
TAGBANWA - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Tagbanwa" Unicode character block.
TagElement - Class in javax.swing.text.html.parser
A generic HTML TagElement class.
TagElement(Element) - Constructor for class javax.swing.text.html.parser.TagElement
TagElement(Element, boolean) - Constructor for class javax.swing.text.html.parser.TagElement
TaggedComponent - Class in org.omg.IOP
org/omg/IOP/TaggedComponent.java .
TaggedComponent() - Constructor for class org.omg.IOP.TaggedComponent
TaggedComponent(int, byte[]) - Constructor for class org.omg.IOP.TaggedComponent
TaggedComponentHelper - Class in org.omg.IOP
org/omg/IOP/TaggedComponentHelper.java .
TaggedComponentHelper() - Constructor for class org.omg.IOP.TaggedComponentHelper
TaggedComponentHolder - Class in org.omg.IOP
org/omg/IOP/TaggedComponentHolder.java .
TaggedComponentHolder() - Constructor for class org.omg.IOP.TaggedComponentHolder
TaggedComponentHolder(TaggedComponent) - Constructor for class org.omg.IOP.TaggedComponentHolder
TaggedProfile - Class in org.omg.IOP
org/omg/IOP/TaggedProfile.java .
TaggedProfile() - Constructor for class org.omg.IOP.TaggedProfile
TaggedProfile(int, byte[]) - Constructor for class org.omg.IOP.TaggedProfile
TaggedProfileHelper - Class in org.omg.IOP
org/omg/IOP/TaggedProfileHelper.java .
TaggedProfileHelper() - Constructor for class org.omg.IOP.TaggedProfileHelper
TaggedProfileHolder - Class in org.omg.IOP
org/omg/IOP/TaggedProfileHolder.java .
TaggedProfileHolder() - Constructor for class org.omg.IOP.TaggedProfileHolder
TaggedProfileHolder(TaggedProfile) - Constructor for class org.omg.IOP.TaggedProfileHolder
TAGS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Tags" Unicode character block.
TAI_LE - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Tai Le" Unicode character block.
TAI_THAM - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Tai Tham" Unicode character block.
TAI_VIET - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Tai Viet" Unicode character block.
TAI_XUAN_JING_SYMBOLS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Tai Xuan Jing Symbols" Unicode character block.
tailMap(K, boolean) - Method in interface java.util.concurrent.ConcurrentNavigableMap
tailMap(K) - Method in interface java.util.concurrent.ConcurrentNavigableMap
tailMap(K, boolean) - Method in class java.util.concurrent.ConcurrentSkipListMap
tailMap(K) - Method in class java.util.concurrent.ConcurrentSkipListMap
tailMap(K, boolean) - Method in interface java.util.NavigableMap
Returns a view of the portion of this map whose keys are greater than (or equal to, if inclusive is true) fromKey.
tailMap(K) - Method in interface java.util.NavigableMap
Returns a view of the portion of this map whose keys are greater than or equal to fromKey.
tailMap(K) - Method in interface java.util.SortedMap
Returns a view of the portion of this map whose keys are greater than or equal to fromKey.
tailMap(K, boolean) - Method in class java.util.TreeMap
tailMap(K) - Method in class java.util.TreeMap
tailSet(E, boolean) - Method in class java.util.concurrent.ConcurrentSkipListSet
tailSet(E) - Method in class java.util.concurrent.ConcurrentSkipListSet
tailSet(E, boolean) - Method in interface java.util.NavigableSet
Returns a view of the portion of this set whose elements are greater than (or equal to, if inclusive is true) fromElement.
tailSet(E) - Method in interface java.util.NavigableSet
Returns a view of the portion of this set whose elements are greater than or equal to fromElement.
tailSet(E) - Method in interface java.util.SortedSet
Returns a view of the portion of this set whose elements are greater than or equal to fromElement.
tailSet(E, boolean) - Method in class java.util.TreeSet
tailSet(E) - Method in class java.util.TreeSet
TAIWAN - Static variable in class java.util.Locale
Useful constant for country.
take() - Method in interface java.nio.file.WatchService
Retrieves and removes next watch key, waiting if none are yet present.
take() - Method in class java.util.concurrent.ArrayBlockingQueue
take() - Method in interface java.util.concurrent.BlockingDeque
Retrieves and removes the head of the queue represented by this deque (in other words, the first element of this deque), waiting if necessary until an element becomes available.
take() - Method in interface java.util.concurrent.BlockingQueue
Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.
take() - Method in interface java.util.concurrent.CompletionService
Retrieves and removes the Future representing the next completed task, waiting if none are yet present.
take() - Method in class java.util.concurrent.DelayQueue
Retrieves and removes the head of this queue, waiting if necessary until an element with an expired delay is available on this queue.
take() - Method in class java.util.concurrent.ExecutorCompletionService
take() - Method in class java.util.concurrent.LinkedBlockingDeque
take() - Method in class java.util.concurrent.LinkedBlockingQueue
take() - Method in class java.util.concurrent.LinkedTransferQueue
take() - Method in class java.util.concurrent.PriorityBlockingQueue
take() - Method in class java.util.concurrent.SynchronousQueue
Retrieves and removes the head of this queue, waiting if necessary for another thread to insert it.
takeFirst() - Method in interface java.util.concurrent.BlockingDeque
Retrieves and removes the first element of this deque, waiting if necessary until an element becomes available.
takeFirst() - Method in class java.util.concurrent.LinkedBlockingDeque
takeLast() - Method in interface java.util.concurrent.BlockingDeque
Retrieves and removes the last element of this deque, waiting if necessary until an element becomes available.
takeLast() - Method in class java.util.concurrent.LinkedBlockingDeque
TAMIL - Static variable in class java.awt.font.NumericShaper
Identifies the TAMIL range and decimal base.
TAMIL - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Tamil" Unicode character block.
tan(double) - Static method in class java.lang.Math
Returns the trigonometric tangent of an angle.
tan(double) - Static method in class java.lang.StrictMath
Returns the trigonometric tangent of an angle.
tanh(double) - Static method in class java.lang.Math
Returns the hyperbolic tangent of a double value.
tanh(double) - Static method in class java.lang.StrictMath
Returns the hyperbolic tangent of a double value.
target - Variable in class java.awt.Event
The target component.
Target - Annotation Type in java.lang.annotation
Indicates the kinds of program element to which an annotation type is applicable.
TARGET - Static variable in class javax.swing.text.html.HTML.Attribute
target() - Method in class org.omg.CORBA.Request
Retrieves the the target object reference.
target() - Method in interface org.omg.PortableInterceptor.ClientRequestInfoOperations
Returns the object which the client called to perform the operation.
target_is_a(String) - Method in interface org.omg.PortableInterceptor.ServerRequestInfoOperations
Returns true if the servant is the given repository id, false if it is not.
target_most_derived_interface() - Method in interface org.omg.PortableInterceptor.ServerRequestInfoOperations
Returns the repository id for the most derived interface of the servant.
TargetDataLine - Interface in javax.sound.sampled
A target data line is a type of DataLine from which audio data can be read.
TargetedNotification - Class in javax.management.remote
A (Notification, Listener ID) pair.
TargetedNotification(Notification, Integer) - Constructor for class javax.management.remote.TargetedNotification
Constructs a TargetedNotification object.
targetMustExist() - Method in interface javax.naming.event.EventContext
Determines whether a listener can register interest in a target that does not exist.
TC_ARRAY - Static variable in interface java.io.ObjectStreamConstants
new Array.
TC_BASE - Static variable in interface java.io.ObjectStreamConstants
First tag value.
TC_BLOCKDATA - Static variable in interface java.io.ObjectStreamConstants
Block of optional data.
TC_BLOCKDATALONG - Static variable in interface java.io.ObjectStreamConstants
long Block data.
TC_CLASS - Static variable in interface java.io.ObjectStreamConstants
Reference to Class.
TC_CLASSDESC - Static variable in interface java.io.ObjectStreamConstants
new Class Descriptor.
TC_ENDBLOCKDATA - Static variable in interface java.io.ObjectStreamConstants
End of optional block data blocks for an object.
TC_ENUM - Static variable in interface java.io.ObjectStreamConstants
new Enum constant.
TC_EXCEPTION - Static variable in interface java.io.ObjectStreamConstants
Exception during write.
TC_LONGSTRING - Static variable in interface java.io.ObjectStreamConstants
Long string.
TC_MAX - Static variable in interface java.io.ObjectStreamConstants
Last tag value.
TC_NULL - Static variable in interface java.io.ObjectStreamConstants
Null object reference.
TC_OBJECT - Static variable in interface java.io.ObjectStreamConstants
new Object.
TC_PROXYCLASSDESC - Static variable in interface java.io.ObjectStreamConstants
new Proxy Class Descriptor.
TC_REFERENCE - Static variable in interface java.io.ObjectStreamConstants
Reference to an object already written into the stream.
TC_RESET - Static variable in interface java.io.ObjectStreamConstants
Reset stream context.
TC_STRING - Static variable in interface java.io.ObjectStreamConstants
new String.
TCKind - Class in org.omg.CORBA
The Java mapping of the IDL enum TCKind, which specifies the kind of a TypeCode object.
TCKind(int) - Constructor for class org.omg.CORBA.TCKind
Deprecated.
Do not use this constructor as this method should be private according to the OMG specification. Use TCKind.from_int(int) instead.
TCP_NODELAY - Static variable in interface java.net.SocketOptions
Disable Nagle's algorithm for this connection.
TCP_NODELAY - Static variable in class java.net.StandardSocketOption
Disable the Nagle algorithm.
TD - Static variable in class javax.swing.text.html.HTML.Tag
TELUGU - Static variable in class java.awt.font.NumericShaper
Identifies the TELUGU range and decimal base.
TELUGU - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Telugu" Unicode character block.
Templates - Interface in javax.xml.transform
An object that implements this interface is the runtime representation of processed transformation instructions.
TemplatesHandler - Interface in javax.xml.transform.sax
A SAX ContentHandler that may be used to process SAX parse events (parsing transformation instructions) into a Templates object.
TEN - Static variable in class java.math.BigDecimal
The value 10, with a scale of 0.
TEN - Static variable in class java.math.BigInteger
The BigInteger constant ten.
terminated() - Method in class java.util.concurrent.ThreadPoolExecutor
Method invoked when the Executor has terminated.
TERTIARY - Static variable in class java.text.Collator
Collator strength value.
tertiaryOrder(int) - Static method in class java.text.CollationElementIterator
Return the tertiary component of a collation element.
testBit(int) - Method in class java.math.BigInteger
Returns true if and only if the designated bit is set.
TEXT - Static variable in class java.awt.SystemColor
The array index for the SystemColor.text system color.
text - Static variable in class java.awt.SystemColor
The color rendered for the background of text control objects, such as textfields and comboboxes.
TEXT - Static variable in class javax.accessibility.AccessibleRole
An object that presents text to the user.
text - Variable in class javax.accessibility.AccessibleTextSequence
The text
text(Element) - Method in class javax.swing.text.AbstractWriter
Writes out text.
TEXT - Static variable in class javax.swing.text.html.HTML.Attribute
text(Element) - Method in class javax.swing.text.html.HTMLWriter
Writes out text.
text(Element) - Method in class javax.swing.text.html.MinimalHTMLWriter
Writes out text.
Text - Interface in javax.xml.soap
A representation of a node whose value is text.
Text - Interface in org.w3c.dom
The Text interface inherits from CharacterData and represents the textual content (termed character data in XML) of an Element or Attr.
TEXT_ALIGN - Static variable in class javax.swing.text.html.CSS.Attribute
TEXT_AREA - Static variable in class javax.swing.plaf.synth.Region
TextArea region.
TEXT_BACKGROUND - Static variable in class javax.swing.plaf.synth.ColorType
ColorType for the background of a region.
TEXT_CHANGED_PROPERTY - Static variable in class javax.swing.AbstractButton
Identifies a change in the button's text.
TEXT_CURSOR - Static variable in class java.awt.Cursor
The text cursor type.
TEXT_CURSOR - Static variable in class java.awt.Frame
Deprecated.
replaced by Cursor.TEXT_CURSOR.
TEXT_DECORATION - Static variable in class javax.swing.text.html.CSS.Attribute
TEXT_EVENT_MASK - Static variable in class java.awt.AWTEvent
The event mask for selecting text events.
TEXT_FIELD - Static variable in class javax.swing.plaf.synth.Region
TextField region.
TEXT_FIRST - Static variable in class java.awt.event.TextEvent
The first number in the range of ids used for text events.
TEXT_FOREGROUND - Static variable in class javax.swing.plaf.synth.ColorType
ColorType for the foreground of a region.
TEXT_HIGHLIGHT - Static variable in class java.awt.SystemColor
The array index for the SystemColor.textHighlight system color.
TEXT_HIGHLIGHT_TEXT - Static variable in class java.awt.SystemColor
The array index for the SystemColor.textHighlightText system color.
TEXT_HTML - Static variable in class javax.print.DocFlavor.CHAR_ARRAY
Doc flavor with MIME type = "text/html; charset=utf-16", print data representation class name = "[C" (character array).
TEXT_HTML - Static variable in class javax.print.DocFlavor.READER
Doc flavor with MIME type = "text/html; charset=utf-16", print data representation class name = "java.io.Reader" (character stream).
TEXT_HTML - Static variable in class javax.print.DocFlavor.STRING
Doc flavor with MIME type = "text/html; charset=utf-16", print data representation class name = "java.lang.String".
TEXT_HTML_HOST - Static variable in class javax.print.DocFlavor.BYTE_ARRAY
Doc flavor with MIME type = "text/html", encoded in the host platform encoding.
TEXT_HTML_HOST - Static variable in class javax.print.DocFlavor.INPUT_STREAM
Doc flavor with MIME type = "text/html", encoded in the host platform encoding.
TEXT_HTML_HOST - Static variable in class javax.print.DocFlavor.URL
Doc flavor with MIME type = "text/html", encoded in the host platform encoding.
TEXT_HTML_US_ASCII - Static variable in class javax.print.DocFlavor.BYTE_ARRAY
Doc flavor with MIME type = "text/html; charset=us-ascii", print data representation class name = "[B" (byte array).
TEXT_HTML_US_ASCII - Static variable in class javax.print.DocFlavor.INPUT_STREAM
Doc flavor with MIME type = "text/html; charset=us-ascii", print data representation class name = "java.io.InputStream" (byte stream).
TEXT_HTML_US_ASCII - Static variable in class javax.print.DocFlavor.URL
Doc flavor with MIME type = "text/html; charset=us-ascii", print data representation class name = "java.net.URL" (byte stream).
TEXT_HTML_UTF_16 - Static variable in class javax.print.DocFlavor.BYTE_ARRAY
Doc flavor with MIME type = "text/html; charset=utf-16", print data representation class name = "[B" (byte array).
TEXT_HTML_UTF_16 - Static variable in class javax.print.DocFlavor.INPUT_STREAM
Doc flavor with MIME type = "text/html; charset=utf-16", print data representation class name = "java.io.InputStream" (byte stream).
TEXT_HTML_UTF_16 - Static variable in class javax.print.DocFlavor.URL
Doc flavor with MIME type = "text/html; charset=utf-16", print data representation class name = "java.net.URL" (byte stream).
TEXT_HTML_UTF_16BE - Static variable in class javax.print.DocFlavor.BYTE_ARRAY
Doc flavor with MIME type = "text/html; charset=utf-16be" (big-endian byte ordering), print data representation class name = "[B" (byte array).
TEXT_HTML_UTF_16BE - Static variable in class javax.print.DocFlavor.INPUT_STREAM
Doc flavor with MIME type = "text/html; charset=utf-16be" (big-endian byte ordering), print data representation class name = "java.io.InputStream" (byte stream).
TEXT_HTML_UTF_16BE - Static variable in class javax.print.DocFlavor.URL
Doc flavor with MIME type = "text/html; charset=utf-16be" (big-endian byte ordering), print data representation class name = "java.net.URL" (byte stream).
TEXT_HTML_UTF_16LE - Static variable in class javax.print.DocFlavor.BYTE_ARRAY
Doc flavor with MIME type = "text/html; charset=utf-16le" (little-endian byte ordering), print data representation class name = "[B" (byte array).
TEXT_HTML_UTF_16LE - Static variable in class javax.print.DocFlavor.INPUT_STREAM
Doc flavor with MIME type = "text/html; charset=utf-16le" (little-endian byte ordering), print data representation class name = "java.io.InputStream" (byte stream).
TEXT_HTML_UTF_16LE - Static variable in class javax.print.DocFlavor.URL
Doc flavor with MIME type = "text/html; charset=utf-16le" (little-endian byte ordering), print data representation class name = "java.net.URL" (byte stream).
TEXT_HTML_UTF_8 - Static variable in class javax.print.DocFlavor.BYTE_ARRAY
Doc flavor with MIME type = "text/html; charset=utf-8", print data representation class name = "[B" (byte array).
TEXT_HTML_UTF_8 - Static variable in class javax.print.DocFlavor.INPUT_STREAM
Doc flavor with MIME type = "text/html; charset=utf-8", print data representation class name = "java.io.InputStream" (byte stream).
TEXT_HTML_UTF_8 - Static variable in class javax.print.DocFlavor.URL
Doc flavor with MIME type = "text/html; charset=utf-8", print data representation class name = "java.net.URL" (byte stream).
TEXT_INACTIVE_TEXT - Static variable in class java.awt.SystemColor
The array index for the SystemColor.textInactiveText system color.
TEXT_INDENT - Static variable in class javax.swing.text.html.CSS.Attribute
TEXT_INSET_H - Static variable in class javax.swing.border.TitledBorder
TEXT_LAST - Static variable in class java.awt.event.TextEvent
The last number in the range of ids used for text events.
TEXT_NODE - Static variable in interface org.w3c.dom.Node
The node is a Text node.
TEXT_PANE - Static variable in class javax.swing.plaf.synth.Region
TextPane region.
TEXT_PLAIN - Static variable in class javax.print.DocFlavor.CHAR_ARRAY
Doc flavor with MIME type = "text/plain; charset=utf-16", print data representation class name = "[C" (character array).
TEXT_PLAIN - Static variable in class javax.print.DocFlavor.READER
Doc flavor with MIME type = "text/plain; charset=utf-16", print data representation class name = "java.io.Reader" (character stream).
TEXT_PLAIN - Static variable in class javax.print.DocFlavor.STRING
Doc flavor with MIME type = "text/plain; charset=utf-16", print data representation class name = "java.lang.String".
TEXT_PLAIN_HOST - Static variable in class javax.print.DocFlavor.BYTE_ARRAY
Doc flavor with MIME type = "text/plain", encoded in the host platform encoding.
TEXT_PLAIN_HOST - Static variable in class javax.print.DocFlavor.INPUT_STREAM
Doc flavor with MIME type = "text/plain", encoded in the host platform encoding.
TEXT_PLAIN_HOST - Static variable in class javax.print.DocFlavor.URL
Doc flavor with MIME type = "text/plain", encoded in the host platform encoding.
TEXT_PLAIN_US_ASCII - Static variable in class javax.print.DocFlavor.BYTE_ARRAY
Doc flavor with MIME type = "text/plain; charset=us-ascii", print data representation class name = "[B" (byte array).
TEXT_PLAIN_US_ASCII - Static variable in class javax.print.DocFlavor.INPUT_STREAM
Doc flavor with MIME type = "text/plain; charset=us-ascii", print data representation class name = "java.io.InputStream" (byte stream).
TEXT_PLAIN_US_ASCII - Static variable in class javax.print.DocFlavor.URL
Doc flavor with MIME type = "text/plain; charset=us-ascii", print data representation class name = "java.net.URL" (byte stream).
TEXT_PLAIN_UTF_16 - Static variable in class javax.print.DocFlavor.BYTE_ARRAY
Doc flavor with MIME type = "text/plain; charset=utf-16", print data representation class name = "[B" (byte array).
TEXT_PLAIN_UTF_16 - Static variable in class javax.print.DocFlavor.INPUT_STREAM
Doc flavor with MIME type = "text/plain; charset=utf-16", print data representation class name = "java.io.InputStream" (byte stream).
TEXT_PLAIN_UTF_16 - Static variable in class javax.print.DocFlavor.URL
Doc flavor with MIME type = "text/plain; charset=utf-16", print data representation class name = java.net.URL"" (byte stream).
TEXT_PLAIN_UTF_16BE - Static variable in class javax.print.DocFlavor.BYTE_ARRAY
Doc flavor with MIME type = "text/plain; charset=utf-16be" (big-endian byte ordering), print data representation class name = "[B" (byte array).
TEXT_PLAIN_UTF_16BE - Static variable in class javax.print.DocFlavor.INPUT_STREAM
Doc flavor with MIME type = "text/plain; charset=utf-16be" (big-endian byte ordering), print data representation class name = "java.io.InputStream" (byte stream).
TEXT_PLAIN_UTF_16BE - Static variable in class javax.print.DocFlavor.URL
Doc flavor with MIME type = "text/plain; charset=utf-16be" (big-endian byte ordering), print data representation class name = "java.net.URL" (byte stream).
TEXT_PLAIN_UTF_16LE - Static variable in class javax.print.DocFlavor.BYTE_ARRAY
Doc flavor with MIME type = "text/plain; charset=utf-16le" (little-endian byte ordering), print data representation class name = "[B" (byte array).
TEXT_PLAIN_UTF_16LE - Static variable in class javax.print.DocFlavor.INPUT_STREAM
Doc flavor with MIME type = "text/plain; charset=utf-16le" (little-endian byte ordering), print data representation class name = "java.io.InputStream" (byte stream).
TEXT_PLAIN_UTF_16LE - Static variable in class javax.print.DocFlavor.URL
Doc flavor with MIME type = "text/plain; charset=utf-16le" (little-endian byte ordering), print data representation class name = "java.net.URL" (byte stream).
TEXT_PLAIN_UTF_8 - Static variable in class javax.print.DocFlavor.BYTE_ARRAY
Doc flavor with MIME type = "text/plain; charset=utf-8", print data representation class name = "[B" (byte array).
TEXT_PLAIN_UTF_8 - Static variable in class javax.print.DocFlavor.INPUT_STREAM
Doc flavor with MIME type = "text/plain; charset=utf-8", print data representation class name = "java.io.InputStream" (byte stream).
TEXT_PLAIN_UTF_8 - Static variable in class javax.print.DocFlavor.URL
Doc flavor with MIME type = "text/plain; charset=utf-8", print data representation class name = "java.net.URL" (byte stream).
TEXT_SPACING - Static variable in class javax.swing.border.TitledBorder
TEXT_TEXT - Static variable in class java.awt.SystemColor
The array index for the SystemColor.textText system color.
TEXT_TRANSFORM - Static variable in class javax.swing.text.html.CSS.Attribute
TEXT_VALUE_CHANGED - Static variable in class java.awt.event.TextEvent
This event id indicates that object's text changed.
TextAction - Class in javax.swing.text
An Action implementation useful for key bindings that are shared across a number of different text components.
TextAction(String) - Constructor for class javax.swing.text.TextAction
Creates a new JTextAction object.
TextArea - Class in java.awt
A TextArea object is a multi-line region that displays text.
TextArea() - Constructor for class java.awt.TextArea
Constructs a new text area with the empty string as text.
TextArea(String) - Constructor for class java.awt.TextArea
Constructs a new text area with the specified text.
TextArea(int, int) - Constructor for class java.awt.TextArea
Constructs a new text area with the specified number of rows and columns and the empty string as text.
TextArea(String, int, int) - Constructor for class java.awt.TextArea
Constructs a new text area with the specified text, and with the specified number of rows and columns.
TextArea(String, int, int, int) - Constructor for class java.awt.TextArea
Constructs a new text area with the specified text, and with the rows, columns, and scroll bar visibility as specified.
TEXTAREA - Static variable in class javax.swing.text.html.HTML.Tag
TextArea.AccessibleAWTTextArea - Class in java.awt
This class implements accessibility support for the TextArea class.
TextArea.AccessibleAWTTextArea() - Constructor for class java.awt.TextArea.AccessibleAWTTextArea
textAreaContent(char[]) - Method in class javax.swing.text.html.HTMLDocument.HTMLReader
Adds the given content to the textarea document.
textAreaContent(AttributeSet) - Method in class javax.swing.text.html.HTMLWriter
Writes out text that is contained in a TEXTAREA form element.
TextAttribute - Class in java.awt.font
The TextAttribute class defines attribute keys and attribute values used for text rendering.
TextAttribute(String) - Constructor for class java.awt.font.TextAttribute
Constructs a TextAttribute with the specified name.
TextComponent - Class in java.awt
The TextComponent class is the superclass of any component that allows the editing of some text.
TextComponent.AccessibleAWTTextComponent - Class in java.awt
This class implements accessibility support for the TextComponent class.
TextComponent.AccessibleAWTTextComponent() - Constructor for class java.awt.TextComponent.AccessibleAWTTextComponent
Constructs an AccessibleAWTTextComponent.
TextEvent - Class in java.awt.event
A semantic event which indicates that an object's text changed.
TextEvent(Object, int) - Constructor for class java.awt.event.TextEvent
Constructs a TextEvent object.
TextField - Class in java.awt
A TextField object is a text component that allows for the editing of a single line of text.
TextField() - Constructor for class java.awt.TextField
Constructs a new text field.
TextField(String) - Constructor for class java.awt.TextField
Constructs a new text field initialized with the specified text.
TextField(int) - Constructor for class java.awt.TextField
Constructs a new empty text field with the specified number of columns.
TextField(String, int) - Constructor for class java.awt.TextField
Constructs a new text field initialized with the specified text to be displayed, and wide enough to hold the specified number of columns.
TextField.AccessibleAWTTextField - Class in java.awt
This class implements accessibility support for the TextField class.
TextField.AccessibleAWTTextField() - Constructor for class java.awt.TextField.AccessibleAWTTextField
textHighlight - Static variable in class java.awt.SystemColor
The color rendered for the background of selected items, such as in menus, comboboxes, and text.
textHighlightText - Static variable in class java.awt.SystemColor
The color rendered for the text of selected items, such as in menus, comboboxes, and text.
TextHitInfo - Class in java.awt.font
The TextHitInfo class represents a character position in a text model, and a bias, or "side," of the character.
textIconGap - Variable in class javax.swing.plaf.basic.BasicTabbedPaneUI
textInactiveText - Static variable in class java.awt.SystemColor
The color rendered for the text of inactive items, such as in menus.
TextInputCallback - Class in javax.security.auth.callback
Underlying security services instantiate and pass a TextInputCallback to the handle method of a CallbackHandler to retrieve generic text information.
TextInputCallback(String) - Constructor for class javax.security.auth.callback.TextInputCallback
Construct a TextInputCallback with a prompt.
TextInputCallback(String, String) - Constructor for class javax.security.auth.callback.TextInputCallback
Construct a TextInputCallback with a prompt and default input value.
TextLayout - Class in java.awt.font
TextLayout is an immutable graphical representation of styled character data.
TextLayout(String, Font, FontRenderContext) - Constructor for class java.awt.font.TextLayout
Constructs a TextLayout from a String and a Font.
TextLayout(String, Map<? extends AttributedCharacterIterator.Attribute, ?>, FontRenderContext) - Constructor for class java.awt.font.TextLayout
Constructs a TextLayout from a String and an attribute set.
TextLayout(AttributedCharacterIterator, FontRenderContext) - Constructor for class java.awt.font.TextLayout
Constructs a TextLayout from an iterator over styled text.
TextLayout.CaretPolicy - Class in java.awt.font
Defines a policy for determining the strong caret location.
TextLayout.CaretPolicy() - Constructor for class java.awt.font.TextLayout.CaretPolicy
Constructs a CaretPolicy.
TextListener - Interface in java.awt.event
The listener interface for receiving text events.
textListener - Variable in class java.awt.TextComponent
TextMeasurer - Class in java.awt.font
The TextMeasurer class provides the primitive operations needed for line break: measuring up to a given advance, determining the advance of a range of characters, and generating a TextLayout for a range of characters.
TextMeasurer(AttributedCharacterIterator, FontRenderContext) - Constructor for class java.awt.font.TextMeasurer
Constructs a TextMeasurer from the source text.
textNonSelectionColor - Variable in class javax.swing.tree.DefaultTreeCellRenderer
Color to use for the foreground for non-selected nodes.
TextOutputCallback - Class in javax.security.auth.callback
Underlying security services instantiate and pass a TextOutputCallback to the handle method of a CallbackHandler to display information messages, warning messages and error messages.
TextOutputCallback(int, String) - Constructor for class javax.security.auth.callback.TextOutputCallback
Construct a TextOutputCallback with a message type and message to be displayed.
textSelectionColor - Variable in class javax.swing.tree.DefaultTreeCellRenderer
Color to use for the foreground for selected nodes.
TextSyntax - Class in javax.print.attribute
Class TextSyntax is an abstract base class providing the common implementation of all attributes whose value is a string.
TextSyntax(String, Locale) - Constructor for class javax.print.attribute.TextSyntax
Constructs a TextAttribute with the specified string and locale.
textText - Static variable in class java.awt.SystemColor
The color rendered for the text of text control objects, such as textfields and comboboxes.
TextUI - Class in javax.swing.plaf
Text editor user interface
TextUI() - Constructor for class javax.swing.plaf.TextUI
TexturePaint - Class in java.awt
The TexturePaint class provides a way to fill a Shape with a texture that is specified as a BufferedImage.
TexturePaint(BufferedImage, Rectangle2D) - Constructor for class java.awt.TexturePaint
Constructs a TexturePaint object.
textValueChanged(TextEvent) - Method in class java.awt.AWTEventMulticaster
textValueChanged(TextEvent) - Method in interface java.awt.event.TextListener
Invoked when the value of the text has changed.
textValueChanged(TextEvent) - Method in class java.awt.TextComponent.AccessibleAWTTextComponent
TextListener notification of a text value change.
TH - Static variable in class javax.swing.text.html.HTML.Tag
THAANA - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Thaana" Unicode character block.
THAI - Static variable in class java.awt.font.NumericShaper
Identifies the THAI range and decimal base.
THAI - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Thai" Unicode character block.
the_activator() - Method in interface org.omg.PortableServer.POAOperations
This attribute identifies the adapter activator associated with the POA.
the_activator(AdapterActivator) - Method in interface org.omg.PortableServer.POAOperations
This attribute identifies the adapter activator associated with the POA.
the_children() - Method in interface org.omg.PortableServer.POAOperations
This attribute identifies the current set of all child POAs of the POA.
the_name() - Method in interface org.omg.PortableServer.POAOperations
This attribute identifies the POA relative to its parent.
the_parent() - Method in interface org.omg.PortableServer.POAOperations
This attribute identifies the parent of the POA.
the_POAManager() - Method in interface org.omg.PortableServer.POAOperations
This attribute identifies the POA manager associated with the POA.
thickness - Variable in class javax.swing.border.LineBorder
this_object(Servant) - Method in interface org.omg.PortableServer.portable.Delegate
This allows the servant to obtain the object reference for the target CORBA Object it is incarnating for that request.
thisObject() - Method in interface javax.rmi.CORBA.Tie
Returns an object reference for the target object represented by this tie.
Thread - Class in java.lang
A thread is a thread of execution in a program.
Thread() - Constructor for class java.lang.Thread
Allocates a new Thread object.
Thread(Runnable) - Constructor for class java.lang.Thread
Allocates a new Thread object.
Thread(ThreadGroup, Runnable) - Constructor for class java.lang.Thread
Allocates a new Thread object.
Thread(String) - Constructor for class java.lang.Thread
Allocates a new Thread object.
Thread(ThreadGroup, String) - Constructor for class java.lang.Thread
Allocates a new Thread object.
Thread(Runnable, String) - Constructor for class java.lang.Thread
Allocates a new Thread object.
Thread(ThreadGroup, Runnable, String) - Constructor for class java.lang.Thread
Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group.
Thread(ThreadGroup, Runnable, String, long) - Constructor for class java.lang.Thread
Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group, and has the specified stack size.
Thread.State - Enum in java.lang
A thread state.
Thread.UncaughtExceptionHandler - Interface in java.lang
Interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception.
THREAD_MXBEAN_NAME - Static variable in class java.lang.management.ManagementFactory
String representation of the ObjectName for the ThreadMXBean.
THREAD_POLICY_ID - Interface in org.omg.PortableServer
org/omg/PortableServer/THREAD_POLICY_ID.java .
ThreadDeath - Error in java.lang
An instance of ThreadDeath is thrown in the victim thread when the (deprecated) Thread.stop() method is invoked.
ThreadDeath() - Constructor for error java.lang.ThreadDeath
ThreadFactory - Interface in java.util.concurrent
An object that creates new threads on demand.
ThreadGroup - Class in java.lang
A thread group represents a set of threads.
ThreadGroup(String) - Constructor for class java.lang.ThreadGroup
Constructs a new thread group.
ThreadGroup(ThreadGroup, String) - Constructor for class java.lang.ThreadGroup
Creates a new thread group.
ThreadInfo - Class in java.lang.management
Thread information.
ThreadLocal<T> - Class in java.lang
This class provides thread-local variables.
ThreadLocal() - Constructor for class java.lang.ThreadLocal
Creates a thread local variable.
ThreadLocalRandom - Class in java.util.concurrent
A random number generator isolated to the current thread.
ThreadMXBean - Interface in java.lang.management
The management interface for the thread system of the Java virtual machine.
ThreadPolicy - Interface in org.omg.PortableServer
The ThreadPolicy specifies the threading model used with the created POA.
ThreadPolicyOperations - Interface in org.omg.PortableServer
The ThreadPolicy specifies the threading model used with the created POA.
ThreadPolicyValue - Class in org.omg.PortableServer
The ThreadPolicyValue can have the following values.
ThreadPolicyValue(int) - Constructor for class org.omg.PortableServer.ThreadPolicyValue
ThreadPoolExecutor - Class in java.util.concurrent
An ExecutorService that executes each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods.
ThreadPoolExecutor(int, int, long, TimeUnit, BlockingQueue<Runnable>) - Constructor for class java.util.concurrent.ThreadPoolExecutor
Creates a new ThreadPoolExecutor with the given initial parameters and default thread factory and rejected execution handler.
ThreadPoolExecutor(int, int, long, TimeUnit, BlockingQueue<Runnable>, ThreadFactory) - Constructor for class java.util.concurrent.ThreadPoolExecutor
Creates a new ThreadPoolExecutor with the given initial parameters and default rejected execution handler.
ThreadPoolExecutor(int, int, long, TimeUnit, BlockingQueue<Runnable>, RejectedExecutionHandler) - Constructor for class java.util.concurrent.ThreadPoolExecutor
Creates a new ThreadPoolExecutor with the given initial parameters and default thread factory.
ThreadPoolExecutor(int, int, long, TimeUnit, BlockingQueue<Runnable>, ThreadFactory, RejectedExecutionHandler) - Constructor for class java.util.concurrent.ThreadPoolExecutor
Creates a new ThreadPoolExecutor with the given initial parameters.
ThreadPoolExecutor.AbortPolicy - Class in java.util.concurrent
A handler for rejected tasks that throws a RejectedExecutionException.
ThreadPoolExecutor.AbortPolicy() - Constructor for class java.util.concurrent.ThreadPoolExecutor.AbortPolicy
Creates an AbortPolicy.
ThreadPoolExecutor.CallerRunsPolicy - Class in java.util.concurrent
A handler for rejected tasks that runs the rejected task directly in the calling thread of the execute method, unless the executor has been shut down, in which case the task is discarded.
ThreadPoolExecutor.CallerRunsPolicy() - Constructor for class java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy
Creates a CallerRunsPolicy.
ThreadPoolExecutor.DiscardOldestPolicy - Class in java.util.concurrent
A handler for rejected tasks that discards the oldest unhandled request and then retries execute, unless the executor is shut down, in which case the task is discarded.
ThreadPoolExecutor.DiscardOldestPolicy() - Constructor for class java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy
Creates a DiscardOldestPolicy for the given executor.
ThreadPoolExecutor.DiscardPolicy - Class in java.util.concurrent
A handler for rejected tasks that silently discards the rejected task.
ThreadPoolExecutor.DiscardPolicy() - Constructor for class java.util.concurrent.ThreadPoolExecutor.DiscardPolicy
Creates a DiscardPolicy.
threshold - Variable in class javax.xml.ws.soap.MTOMFeature
Property for MTOM threshold value.
THRESHOLD_ERROR - Static variable in class javax.management.monitor.MonitorNotification
Notification type denoting that the type of the thresholds, offset or modulus is not correct.
THRESHOLD_HIGH_VALUE_EXCEEDED - Static variable in class javax.management.monitor.MonitorNotification
Notification type denoting that the observed attribute has exceeded the threshold high value.
THRESHOLD_LOW_VALUE_EXCEEDED - Static variable in class javax.management.monitor.MonitorNotification
Notification type denoting that the observed attribute has exceeded the threshold low value.
THRESHOLD_VALUE_EXCEEDED - Static variable in class javax.management.monitor.MonitorNotification
Notification type denoting that the observed attribute has reached the threshold value.
Throwable - Class in java.lang
The Throwable class is the superclass of all errors and exceptions in the Java language.
Throwable() - Constructor for class java.lang.Throwable
Constructs a new throwable with null as its detail message.
Throwable(String) - Constructor for class java.lang.Throwable
Constructs a new throwable with the specified detail message.
Throwable(String, Throwable) - Constructor for class java.lang.Throwable
Constructs a new throwable with the specified detail message and cause.
Throwable(Throwable) - Constructor for class java.lang.Throwable
Constructs a new throwable with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).
Throwable(String, Throwable, boolean) - Constructor for class java.lang.Throwable
Constructs a new throwable with the specified detail message, cause, and suppression enabled or disabled.
throwException(Class<?>, Class<? extends Throwable>) - Static method in class java.lang.invoke.MethodHandles
Produces a method handle which will throw exceptions of the given exType.
throwException() - Method in class java.nio.charset.CoderResult
Throws an exception appropriate to the result described by this object.
throwing(String, String, Throwable) - Method in class java.util.logging.Logger
Log throwing an exception.
thumbColor - Variable in class javax.swing.plaf.basic.BasicScrollBarUI
thumbColor - Static variable in class javax.swing.plaf.metal.MetalSliderUI
thumbDarkShadowColor - Variable in class javax.swing.plaf.basic.BasicScrollBarUI
thumbHighlightColor - Variable in class javax.swing.plaf.basic.BasicScrollBarUI
thumbLightShadowColor - Variable in class javax.swing.plaf.basic.BasicScrollBarUI
thumbnailComplete(ImageReader) - Method in interface javax.imageio.event.IIOReadProgressListener
Reports that a thumbnail read operation has completed.
thumbnailComplete(ImageWriter) - Method in interface javax.imageio.event.IIOWriteProgressListener
Reports that a thumbnail write operation has completed.
thumbnailPassComplete(ImageReader, BufferedImage) - Method in interface javax.imageio.event.IIOReadUpdateListener
Reports that the current thumbnail read operation has completed a progressive pass.
thumbnailPassStarted(ImageReader, BufferedImage, int, int, int, int, int, int, int, int[]) - Method in interface javax.imageio.event.IIOReadUpdateListener
Reports that the current thumbnail read operation is about to begin a progressive pass.
thumbnailProgress(ImageReader, float) - Method in interface javax.imageio.event.IIOReadProgressListener
Reports the approximate degree of completion of the current getThumbnail call within the associated ImageReader.
thumbnailProgress(ImageWriter, float) - Method in interface javax.imageio.event.IIOWriteProgressListener
Reports the approximate degree of completion of the current thumbnail write within the associated ImageWriter.
thumbnails - Variable in class javax.imageio.IIOImage
A List of BufferedImage thumbnails, or null.
thumbnailStarted(ImageReader, int, int) - Method in interface javax.imageio.event.IIOReadProgressListener
Reports that a thumbnail read operation is beginning.
thumbnailStarted(ImageWriter, int, int) - Method in interface javax.imageio.event.IIOWriteProgressListener
Reports that a thumbnail write operation is beginning.
thumbnailUpdate(ImageReader, BufferedImage, int, int, int, int, int, int, int[]) - Method in interface javax.imageio.event.IIOReadUpdateListener
Reports that a given region of a thumbnail image has been updated.
thumbRect - Variable in class javax.swing.plaf.basic.BasicScrollBarUI
thumbRect - Variable in class javax.swing.plaf.basic.BasicSliderUI
THURSDAY - Static variable in class java.util.Calendar
Value of the Calendar.DAY_OF_WEEK field indicating Thursday.
TIBETAN - Static variable in class java.awt.font.NumericShaper
Identifies the TIBETAN range and decimal base.
TIBETAN - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Tibetan" Unicode character block.
TICK_BUFFER - Variable in class javax.swing.plaf.metal.MetalSliderUI
tickLength - Static variable in class javax.swing.plaf.metal.MetalSliderUI
tickRect - Variable in class javax.swing.plaf.basic.BasicSliderUI
ticks() - Method in class javax.sound.midi.Track
Obtains the length of the track, expressed in MIDI ticks.
Tie - Interface in javax.rmi.CORBA
Defines methods which all RMI-IIOP server side ties must implement.
TIFINAGH - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Tifinagh" Unicode character block.
tileGridXOffset - Variable in class javax.imageio.ImageWriteParam
The amount by which the tile grid origin should be offset horizontally from the image origin if tiling has been set, or 0 otherwise.
tileGridYOffset - Variable in class javax.imageio.ImageWriteParam
The amount by which the tile grid origin should be offset vertically from the image origin if tiling has been set, or 0 otherwise.
tileHeight - Variable in class javax.imageio.ImageWriteParam
The height of each tile if tiling has been set, or 0 otherwise.
tileIcon - Variable in class javax.swing.border.MatteBorder
TileObserver - Interface in java.awt.image
An interface for objects that wish to be informed when tiles of a WritableRenderedImage become modifiable by some writer via a call to getWritableTile, and when they become unmodifiable via the last call to releaseWritableTile.
tileUpdate(WritableRenderedImage, int, int, boolean) - Method in interface java.awt.image.TileObserver
A tile is about to be updated (it is either about to be grabbed for writing, or it is being released from writing).
tileWidth - Variable in class javax.imageio.ImageWriteParam
The width of each tile if tiling has been set, or 0 otherwise.
tilingMode - Variable in class javax.imageio.ImageWriteParam
The mode controlling tiling settings, which Must be set to one of the four MODE_* values.
tilingSet - Variable in class javax.imageio.ImageWriteParam
A boolean that is true if tiling parameters have been specified.
Time - Class in java.sql
A thin wrapper around the java.util.Date class that allows the JDBC API to identify this as an SQL TIME value.
Time(int, int, int) - Constructor for class java.sql.Time
Deprecated.
Use the constructor that takes a milliseconds value in place of this constructor
Time(long) - Constructor for class java.sql.Time
Constructs a Time object using a milliseconds time value.
TIME - Static variable in class java.sql.Types
The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type TIME.
time - Variable in class java.util.Calendar
The currently set time for this calendar, expressed in milliseconds after January 1, 1970, 0:00:00 GMT.
TIME - Static variable in class javax.xml.datatype.DatatypeConstants
Fully qualified name for W3C XML Schema 1.0 datatype time.
TIME_ZONE - Static variable in class java.text.DateFormat.Field
Constant identifying the time zone field.
TIMED_OUT - Static variable in class javax.print.attribute.standard.PrinterStateReason
The server was able to connect to the output device (or is always connected), but was unable to get a response from the output device.
timedJoin(Thread, long) - Method in enum java.util.concurrent.TimeUnit
Performs a timed Thread.join using this time unit.
timedWait(Object, long) - Method in enum java.util.concurrent.TimeUnit
Performs a timed Object.wait using this time unit.
TimeLimitExceededException - Exception in javax.naming
This exception is thrown when a method does not terminate within the specified time limit.
TimeLimitExceededException() - Constructor for exception javax.naming.TimeLimitExceededException
Constructs a new instance of TimeLimitExceededException.
TimeLimitExceededException(String) - Constructor for exception javax.naming.TimeLimitExceededException
Constructs a new instance of TimeLimitExceededException using the argument supplied.
TIMEOUT - Exception in org.omg.CORBA
TIMEOUT is raised when no delivery has been made and the specified time-to-live period has been exceeded.
TIMEOUT() - Constructor for exception org.omg.CORBA.TIMEOUT
Constructs an TIMEOUT exception with minor code set to 0 and CompletionStatus set to COMPLETED_NO.
TIMEOUT(String) - Constructor for exception org.omg.CORBA.TIMEOUT
Constructs an TIMEOUT exception with the specified message.
TIMEOUT(int, CompletionStatus) - Constructor for exception org.omg.CORBA.TIMEOUT
Constructs an TIMEOUT exception with the specified minor code and completion status.
TIMEOUT(String, int, CompletionStatus) - Constructor for exception org.omg.CORBA.TIMEOUT
Constructs an TIMEOUT exception with the specified message, minor code, and completion status.
TimeoutException - Exception in java.util.concurrent
Exception thrown when a blocking operation times out.
TimeoutException() - Constructor for exception java.util.concurrent.TimeoutException
Constructs a TimeoutException with no specified detail message.
TimeoutException(String) - Constructor for exception java.util.concurrent.TimeoutException
Constructs a TimeoutException with the specified detail message.
Timer - Class in java.util
A facility for threads to schedule tasks for future execution in a background thread.
Timer() - Constructor for class java.util.Timer
Creates a new timer.
Timer(boolean) - Constructor for class java.util.Timer
Creates a new timer whose associated thread may be specified to run as a daemon.
Timer(String) - Constructor for class java.util.Timer
Creates a new timer whose associated thread has the specified name.
Timer(String, boolean) - Constructor for class java.util.Timer
Creates a new timer whose associated thread has the specified name, and may be specified to run as a daemon.
Timer - Class in javax.management.timer
Provides the implementation of the timer MBean.
Timer() - Constructor for class javax.management.timer.Timer
Default constructor.
timer - Variable in class javax.swing.plaf.basic.BasicTreeUI.ComponentHandler
Timer used when inside a scrollpane and the scrollbar is adjusting.
Timer - Class in javax.swing
Fires one or more ActionEvents at specified intervals.
Timer(int, ActionListener) - Constructor for class javax.swing.Timer
Creates a Timer and initializes both the initial delay and between-event delay to delay milliseconds.
timer - Variable in class javax.swing.tree.DefaultTreeCellEditor
Used before starting the editing session.
TimerMBean - Interface in javax.management.timer
Exposes the management interface of the timer MBean.
TimerNotification - Class in javax.management.timer
This class provides definitions of the notifications sent by timer MBeans.
TimerNotification(String, Object, long, long, String, Integer) - Constructor for class javax.management.timer.TimerNotification
Creates a timer notification object.
TimerTask - Class in java.util
A task that can be scheduled for one-time or repeated execution by a Timer.
TimerTask() - Constructor for class java.util.TimerTask
Creates a new timer task.
TIMES - Static variable in class javax.management.Query
A code representing the Query.times(javax.management.ValueExp, javax.management.ValueExp) expression.
times(ValueExp, ValueExp) - Static method in class javax.management.Query
Returns a binary expression representing the product of two numeric values.
Timestamp - Class in java.security
This class encapsulates information about a signed timestamp.
Timestamp(Date, CertPath) - Constructor for class java.security.Timestamp
Constructs a Timestamp.
Timestamp - Class in java.sql
A thin wrapper around java.util.Date that allows the JDBC API to identify this as an SQL TIMESTAMP value.
Timestamp(int, int, int, int, int, int, int) - Constructor for class java.sql.Timestamp
Deprecated.
instead use the constructor Timestamp(long millis)
Timestamp(long) - Constructor for class java.sql.Timestamp
Constructs a Timestamp object using a milliseconds time value.
TIMESTAMP - Static variable in class java.sql.Types
The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type TIMESTAMP.
timestamp() - Method in class java.util.UUID
The timestamp value associated with this UUID.
TimeUnit - Enum in java.util.concurrent
A TimeUnit represents time durations at a given unit of granularity and provides utility methods to convert across units, and to perform timing and delay operations in these units.
TimeZone - Class in java.util
TimeZone represents a time zone offset, and also figures out daylight savings.
TimeZone() - Constructor for class java.util.TimeZone
Sole constructor.
TIMEZONE_FIELD - Static variable in class java.text.DateFormat
Useful constant for TIMEZONE field alignment.
TimeZoneNameProvider - Class in java.util.spi
An abstract class for service providers that provide localized time zone names for the TimeZone class.
TimeZoneNameProvider() - Constructor for class java.util.spi.TimeZoneNameProvider
Sole constructor.
TIMING_CLOCK - Static variable in class javax.sound.midi.ShortMessage
Status byte for Timing Clock messagem (0xF8, or 248).
TINYINT - Static variable in class java.sql.Types
The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type TINYINT.
title - Variable in class javax.swing.border.TitledBorder
title - Variable in class javax.swing.JInternalFrame
The title displayed in this internal frame's title bar.
TITLE - Static variable in class javax.swing.text.html.HTML.Attribute
TITLE - Static variable in class javax.swing.text.html.HTML.Tag
title - Variable in class javax.swing.text.html.parser.DTD
TITLE_PROPERTY - Static variable in class javax.swing.JInternalFrame
Bound property name.
TITLECASE_LETTER - Static variable in class java.lang.Character
General category "Lt" in the Unicode specification.
titleColor - Variable in class javax.swing.border.TitledBorder
TitledBorder - Class in javax.swing.border
A class which implements an arbitrary border with the addition of a String title in a specified position and justification.
TitledBorder(String) - Constructor for class javax.swing.border.TitledBorder
Creates a TitledBorder instance.
TitledBorder(Border) - Constructor for class javax.swing.border.TitledBorder
Creates a TitledBorder instance with the specified border and an empty title.
TitledBorder(Border, String) - Constructor for class javax.swing.border.TitledBorder
Creates a TitledBorder instance with the specified border and title.
TitledBorder(Border, String, int, int) - Constructor for class javax.swing.border.TitledBorder
Creates a TitledBorder instance with the specified border, title, title-justification, and title-position.
TitledBorder(Border, String, int, int, Font) - Constructor for class javax.swing.border.TitledBorder
Creates a TitledBorder instance with the specified border, title, title-justification, title-position, and title-font.
TitledBorder(Border, String, int, int, Font, Color) - Constructor for class javax.swing.border.TitledBorder
Creates a TitledBorder instance with the specified border, title, title-justification, title-position, title-font, and title-color.
titleFont - Variable in class javax.swing.border.TitledBorder
titleJustification - Variable in class javax.swing.border.TitledBorder
titlePane - Variable in class javax.swing.plaf.basic.BasicInternalFrameUI
titlePosition - Variable in class javax.swing.border.TitledBorder
TitleProperty - Static variable in interface javax.swing.text.Document
The property name for the title of the document, if there is one.
tk_abstract_interface - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_abstract_interface.
tk_alias - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_alias.
tk_any - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_any.
tk_array - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_array.
tk_boolean - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_boolean.
tk_char - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_char.
tk_double - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_double.
tk_enum - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_enum.
tk_except - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_except.
tk_fixed - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_fixed.
tk_float - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_float.
tk_long - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_long.
tk_longdouble - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_longdouble.
tk_longlong - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_longlong.
tk_native - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_native.
tk_null - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_null.
tk_objref - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_objref.
tk_octet - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_octet.
tk_Principal - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_Principal.
tk_sequence - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_sequence.
tk_short - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_short.
tk_string - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_string.
tk_struct - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_struct.
tk_TypeCode - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_TypeCode.
tk_ulong - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_ulong.
tk_ulonglong - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_ulonglong.
tk_union - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_union.
tk_ushort - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_ushort.
tk_value - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_value.
tk_value_box - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_value_box.
tk_void - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_void.
tk_wchar - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_wchar.
tk_wstring - Static variable in class org.omg.CORBA.TCKind
The TCKind constant whose value field is initialized with TCKind._tk_wstring.
TMENDRSCAN - Static variable in interface javax.transaction.xa.XAResource
Ends a recovery scan.
TMFAIL - Static variable in interface javax.transaction.xa.XAResource
Disassociates the caller and marks the transaction branch rollback-only.
TMJOIN - Static variable in interface javax.transaction.xa.XAResource
Caller is joining existing transaction branch.
TMNOFLAGS - Static variable in interface javax.transaction.xa.XAResource
Use TMNOFLAGS to indicate no flags value is selected.
TMONEPHASE - Static variable in interface javax.transaction.xa.XAResource
Caller is using one-phase optimization.
TMRESUME - Static variable in interface javax.transaction.xa.XAResource
Caller is resuming association with a suspended transaction branch.
TMSTARTRSCAN - Static variable in interface javax.transaction.xa.XAResource
Starts a recovery scan.
TMSUCCESS - Static variable in interface javax.transaction.xa.XAResource
Disassociates caller from a transaction branch.
TMSUSPEND - Static variable in interface javax.transaction.xa.XAResource
Caller is suspending (not ending) its association with a transaction branch.
to(File) - Static method in class java.lang.ProcessBuilder.Redirect
Returns a redirect to write to the specified file.
to(TimeUnit) - Method in class java.nio.file.attribute.FileTime
Returns the value at the given unit of granularity.
to_any() - Method in interface org.omg.CORBA.DynAny
Deprecated.
Convert a DynAny object to an Any object.
to_any() - Method in class org.omg.DynamicAny._DynAnyStub
Creates an any value from a DynAny object.
to_any() - Method in class org.omg.DynamicAny._DynArrayStub
Creates an any value from a DynAny object.
to_any() - Method in class org.omg.DynamicAny._DynEnumStub
Creates an any value from a DynAny object.
to_any() - Method in class org.omg.DynamicAny._DynFixedStub
Creates an any value from a DynAny object.
to_any() - Method in class org.omg.DynamicAny._DynSequenceStub
Creates an any value from a DynAny object.
to_any() - Method in class org.omg.DynamicAny._DynStructStub
Creates an any value from a DynAny object.
to_any() - Method in class org.omg.DynamicAny._DynUnionStub
Creates an any value from a DynAny object.
to_any() - Method in class org.omg.DynamicAny._DynValueStub
Creates an any value from a DynAny object.
to_any() - Method in interface org.omg.DynamicAny.DynAnyOperations
Creates an any value from a DynAny object.
to_name(String) - Method in class org.omg.CosNaming._NamingContextExtStub
This operation converts a Stringified Name into an equivalent array of Name Components.
to_name(String) - Method in interface org.omg.CosNaming.NamingContextExtOperations
This operation converts a Stringified Name into an equivalent array of Name Components.
to_string(NameComponent[]) - Method in class org.omg.CosNaming._NamingContextExtStub
This operation creates a stringified name from the array of Name components.
to_string(NameComponent[]) - Method in interface org.omg.CosNaming.NamingContextExtOperations
This operation creates a stringified name from the array of Name components.
to_url(String, String) - Method in class org.omg.CosNaming._NamingContextExtStub
This operation creates a URL based "iiopname://" format name from the Stringified Name of the object.
to_url(String, String) - Method in interface org.omg.CosNaming.NamingContextExtOperations
This operation creates a URL based "iiopname://" format name from the Stringified Name of the object.
toAbsolutePath() - Method in interface java.nio.file.Path
Returns a Path object representing the absolute path of this path.
toArray() - Method in class java.awt.dnd.DragGestureEvent
Returns an Object array of the events comprising the drag gesture.
toArray(Object[]) - Method in class java.awt.dnd.DragGestureEvent
Returns an array of the events comprising the drag gesture.
toArray() - Method in class java.beans.beancontext.BeanContextMembershipEvent
Gets the array of children affected by this event.
toArray() - Method in class java.beans.beancontext.BeanContextSupport
Gets all JavaBean or BeanContext instances currently nested in this BeanContext.
toArray(Object[]) - Method in class java.beans.beancontext.BeanContextSupport
Gets an array containing all children of this BeanContext that match the types contained in arry.
toArray() - Method in class java.util.AbstractCollection
Returns an array containing all of the elements in this collection.
toArray(T[]) - Method in class java.util.AbstractCollection
Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.
toArray() - Method in class java.util.ArrayDeque
Returns an array containing all of the elements in this deque in proper sequence (from first to last element).
toArray(T[]) - Method in class java.util.ArrayDeque
Returns an array containing all of the elements in this deque in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
toArray() - Method in class java.util.ArrayList
Returns an array containing all of the elements in this list in proper sequence (from first to last element).
toArray(T[]) - Method in class java.util.ArrayList
Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
toArray() - Method in interface java.util.Collection
Returns an array containing all of the elements in this collection.
toArray(T[]) - Method in interface java.util.Collection
Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.
toArray() - Method in class java.util.concurrent.ArrayBlockingQueue
Returns an array containing all of the elements in this queue, in proper sequence.
toArray(T[]) - Method in class java.util.concurrent.ArrayBlockingQueue
Returns an array containing all of the elements in this queue, in proper sequence; the runtime type of the returned array is that of the specified array.
toArray() - Method in class java.util.concurrent.ConcurrentLinkedDeque
Returns an array containing all of the elements in this deque, in proper sequence (from first to last element).
toArray(T[]) - Method in class java.util.concurrent.ConcurrentLinkedDeque
Returns an array containing all of the elements in this deque, in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
toArray() - Method in class java.util.concurrent.ConcurrentLinkedQueue
Returns an array containing all of the elements in this queue, in proper sequence.
toArray(T[]) - Method in class java.util.concurrent.ConcurrentLinkedQueue
Returns an array containing all of the elements in this queue, in proper sequence; the runtime type of the returned array is that of the specified array.
toArray() - Method in class java.util.concurrent.CopyOnWriteArrayList
Returns an array containing all of the elements in this list in proper sequence (from first to last element).
toArray(T[]) - Method in class java.util.concurrent.CopyOnWriteArrayList
Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
toArray() - Method in class java.util.concurrent.CopyOnWriteArraySet
Returns an array containing all of the elements in this set.
toArray(T[]) - Method in class java.util.concurrent.CopyOnWriteArraySet
Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array.
toArray() - Method in class java.util.concurrent.DelayQueue
Returns an array containing all of the elements in this queue.
toArray(T[]) - Method in class java.util.concurrent.DelayQueue
Returns an array containing all of the elements in this queue; the runtime type of the returned array is that of the specified array.
toArray() - Method in class java.util.concurrent.LinkedBlockingDeque
Returns an array containing all of the elements in this deque, in proper sequence (from first to last element).
toArray(T[]) - Method in class java.util.concurrent.LinkedBlockingDeque
Returns an array containing all of the elements in this deque, in proper sequence; the runtime type of the returned array is that of the specified array.
toArray() - Method in class java.util.concurrent.LinkedBlockingQueue
Returns an array containing all of the elements in this queue, in proper sequence.
toArray(T[]) - Method in class java.util.concurrent.LinkedBlockingQueue
Returns an array containing all of the elements in this queue, in proper sequence; the runtime type of the returned array is that of the specified array.
toArray() - Method in class java.util.concurrent.PriorityBlockingQueue
Returns an array containing all of the elements in this queue.
toArray(T[]) - Method in class java.util.concurrent.PriorityBlockingQueue
Returns an array containing all of the elements in this queue; the runtime type of the returned array is that of the specified array.
toArray() - Method in class java.util.concurrent.SynchronousQueue
Returns a zero-length array.
toArray(T[]) - Method in class java.util.concurrent.SynchronousQueue
Sets the zeroeth element of the specified array to null (if the array has non-zero length) and returns it.
toArray() - Method in class java.util.LinkedList
Returns an array containing all of the elements in this list in proper sequence (from first to last element).
toArray(T[]) - Method in class java.util.LinkedList
Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
toArray() - Method in interface java.util.List
Returns an array containing all of the elements in this list in proper sequence (from first to last element).
toArray(T[]) - Method in interface java.util.List
Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
toArray() - Method in class java.util.PriorityQueue
Returns an array containing all of the elements in this queue.
toArray(T[]) - Method in class java.util.PriorityQueue
Returns an array containing all of the elements in this queue; the runtime type of the returned array is that of the specified array.
toArray() - Method in interface java.util.Set
Returns an array containing all of the elements in this set.
toArray(T[]) - Method in interface java.util.Set
Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array.
toArray() - Method in class java.util.Vector
Returns an array containing all of the elements in this Vector in the correct order.
toArray(T[]) - Method in class java.util.Vector
Returns an array containing all of the elements in this Vector in the correct order; the runtime type of the returned array is that of the specified array.
toArray() - Method in class javax.accessibility.AccessibleRelationSet
Returns the current relation set as an array of AccessibleRelation
toArray() - Method in class javax.accessibility.AccessibleStateSet
Returns the current state set as an array of AccessibleState
toArray() - Method in interface javax.print.attribute.AttributeSet
Returns an array of the attributes contained in this set.
toArray() - Method in class javax.print.attribute.HashAttributeSet
toArray() - Method in class javax.swing.DefaultListModel
Returns an array containing all of the elements in this list in the correct order.
toASCII(String, int) - Static method in class java.net.IDN
Translates a string from Unicode to ASCII Compatible Encoding (ACE), as defined by the ToASCII operation of RFC 3490.
toASCII(String) - Static method in class java.net.IDN
Translates a string from Unicode to ASCII Compatible Encoding (ACE), as defined by the ToASCII operation of RFC 3490.
toASCIIString() - Method in class java.net.URI
Returns the content of this URI as a US-ASCII string.
toAttributes() - Method in class javax.naming.ldap.Rdn
Retrieves the Attributes view of the type/value mappings contained in this Rdn.
toBack() - Method in class java.awt.Dialog
If this Window is visible, sends this Window to the back and may cause it to lose focus or activation if it is the focused or active Window.
toBack() - Method in class java.awt.Window
If this Window is visible, sends this Window to the back and may cause it to lose focus or activation if it is the focused or active Window.
toBack() - Method in class javax.swing.JInternalFrame
Sends this internal frame to the back.
toBigInteger() - Method in class java.math.BigDecimal
Converts this BigDecimal to a BigInteger.
toBigIntegerExact() - Method in class java.math.BigDecimal
Converts this BigDecimal to a BigInteger, checking for lost information.
toBinaryString(int) - Static method in class java.lang.Integer
Returns a string representation of the integer argument as an unsigned integer in base 2.
toBinaryString(long) - Static method in class java.lang.Long
Returns a string representation of the long argument as an unsigned integer in base 2.
TOBOTTOM_TOLEFT - Static variable in class javax.print.attribute.standard.PresentationDirection
Pages are laid out in columns starting at the top right, proceeeding towards the bottom & left.
TOBOTTOM_TORIGHT - Static variable in class javax.print.attribute.standard.PresentationDirection
Pages are laid out in columns starting at the top left, proceeeding towards the bottom & right.
toBundleName(String, Locale) - Method in class java.util.ResourceBundle.Control
Converts the given baseName and locale to the bundle name.
toByteArray() - Method in class java.io.ByteArrayOutputStream
Creates a newly allocated byte array.
toByteArray() - Method in class java.math.BigInteger
Returns a byte array containing the two's-complement representation of this BigInteger.
toByteArray() - Method in class java.text.CollationKey
Converts the CollationKey to a sequence of bits.
toByteArray() - Method in class java.util.BitSet
Returns a new byte array containing all the bits in this bit set.
toCachedRowSet() - Method in interface javax.sql.rowset.JoinRowSet
Creates a new CachedRowSet object containing the data in this JoinRowSet object, which can be saved to a data source using the SyncProvider object for the CachedRowSet object.
toCharArray() - Method in class java.io.CharArrayWriter
Returns a copy of the input data.
toCharArray() - Method in class java.lang.String
Converts this string to a new character array.
toChars(int, char[], int) - Static method in class java.lang.Character
Converts the specified character (Unicode code point) to its UTF-16 representation.
toChars(int) - Static method in class java.lang.Character
Converts the specified character (Unicode code point) to its UTF-16 representation stored in a char array.
toCIEXYZ(float[]) - Method in class java.awt.color.ColorSpace
Transforms a color value assumed to be in this ColorSpace into the CS_CIEXYZ conversion color space.
toCIEXYZ(float[]) - Method in class java.awt.color.ICC_ColorSpace
Transforms a color value assumed to be in this ColorSpace into the CS_CIEXYZ conversion color space.
toCodePoint(char, char) - Static method in class java.lang.Character
Converts the specified surrogate pair to its supplementary code point value.
toCollection() - Method in interface javax.sql.rowset.CachedRowSet
Converts this CachedRowSet object to a Collection object that contains all of this CachedRowSet object's data.
toCollection(int) - Method in interface javax.sql.rowset.CachedRowSet
Converts the designated column in this CachedRowSet object to a Collection object.
toCollection(String) - Method in interface javax.sql.rowset.CachedRowSet
Converts the designated column in this CachedRowSet object to a Collection object.
toCompositeData(CompositeType) - Method in interface javax.management.openmbean.CompositeDataView
Return a CompositeData corresponding to the values in this object.
toDays(long) - Method in enum java.util.concurrent.TimeUnit
Equivalent to DAYS.convert(duration, this).
toDegrees(double) - Static method in class java.lang.Math
Converts an angle measured in radians to an approximately equivalent angle measured in degrees.
toDegrees(double) - Static method in class java.lang.StrictMath
Converts an angle measured in radians to an approximately equivalent angle measured in degrees.
toDisplayString(String, Locale) - Method in class javax.accessibility.AccessibleBundle
Obtains the key as a localized string.
toDisplayString(Locale) - Method in class javax.accessibility.AccessibleBundle
Obtains the key as a localized string.
toDisplayString() - Method in class javax.accessibility.AccessibleBundle
Gets localized string describing the key using the default locale.
toEngineeringString() - Method in class java.math.BigDecimal
Returns a string representation of this BigDecimal, using engineering notation if an exponent is needed.
toExternalForm() - Method in class java.net.URL
Constructs a string representation of this URL.
toExternalForm(URL) - Method in class java.net.URLStreamHandler
Converts a URL of a specific protocol to a String.
toFile() - Method in interface java.nio.file.Path
Returns a File object representing this path.
toFront() - Method in class java.awt.Window
If this Window is visible, brings this Window to the front and may make it the focused Window.
toFront() - Method in class javax.swing.JInternalFrame
Brings this internal frame to the front.
toGenericString() - Method in class java.lang.reflect.Constructor
Returns a string describing this Constructor, including type parameters.
toGenericString() - Method in class java.lang.reflect.字段
Returns a string describing this Field, including its generic type.
toGenericString() - Method in class java.lang.reflect.方法
Returns a string describing this Method, including type parameters.
TOGGLE_BUTTON - Static variable in class javax.accessibility.AccessibleRole
A specialized push button that can be checked or unchecked, but does not provide a separate indicator for the current state.
TOGGLE_BUTTON - Static variable in class javax.swing.plaf.synth.Region
ToggleButton region.
TOGGLE_CLICK_COUNT_PROPERTY - Static variable in class javax.swing.JTree
Bound property name for toggleClickCount.
TOGGLE_EXPAND - Static variable in interface javax.accessibility.AccessibleAction
An action which causes a tree node to collapse if expanded and expand if collapsed.
TOGGLE_POPUP - Static variable in interface javax.accessibility.AccessibleAction
An action which causes a popup to become visible if it is hidden and hidden if it is visible.
toggleClickCount - Variable in class javax.swing.JTree
Number of mouse clicks before a node is expanded.
toggleExpandState(TreePath) - Method in class javax.swing.plaf.basic.BasicTreeUI
Expands path if it is not expanded, or collapses row if it is expanded.
toggleOpenClose() - Method in class javax.swing.plaf.basic.BasicComboBoxUI
Hides the popup if it is showing and shows the popup if it is hidden.
togglePopup() - Method in class javax.swing.plaf.basic.BasicComboPopup
Makes the popup visible if it is hidden and makes it hidden if it is visible.
toggleSortOrder(int) - Method in class javax.swing.DefaultRowSorter
Reverses the sort order from ascending to descending (or descending to ascending) if the specified column is already the primary sorted column; otherwise, makes the specified column the primary sorted column, with an ascending sort order.
toggleSortOrder(int) - Method in class javax.swing.RowSorter
Reverses the sort order of the specified column.
toGMTString() - Method in class java.util.Date
Deprecated.
As of JDK version 1.1, replaced by DateFormat.format(Date date), using a GMT TimeZone.
toGregorianCalendar() - Method in class javax.xml.datatype.XMLGregorianCalendar
Convert this XMLGregorianCalendar to a GregorianCalendar.
toGregorianCalendar(TimeZone, Locale, XMLGregorianCalendar) - Method in class javax.xml.datatype.XMLGregorianCalendar
Convert this XMLGregorianCalendar along with provided parameters to a GregorianCalendar instance.
toHexString(double) - Static method in class java.lang.Double
Returns a hexadecimal string representation of the double argument.
toHexString(float) - Static method in class java.lang.Float
Returns a hexadecimal string representation of the float argument.
toHexString(int) - Static method in class java.lang.Integer
Returns a string representation of the integer argument as an unsigned integer in base 16.
toHexString(long) - Static method in class java.lang.Long
Returns a string representation of the long argument as an unsigned integer in base 16.
toHours(long) - Method in enum java.util.concurrent.TimeUnit
Equivalent to HOURS.convert(duration, this).
toIndex - Variable in class javax.swing.event.TableColumnModelEvent
The index of the column to where it was moved or added
toJMXConnector(Map<String, ?>) - Method in class javax.management.remote.JMXConnectorServer
Returns a client stub for this connector server.
toJMXConnector(Map<String, ?>) - Method in interface javax.management.remote.JMXConnectorServerMBean
Returns a client stub for this connector server.
toJMXConnector(Map<String, ?>) - Method in class javax.management.remote.rmi.RMIConnectorServer
Returns a client stub for this connector server.
toLanguageTag() - Method in class java.util.Locale
Returns a well-formed IETF BCP 47 language tag representing this locale.
TOLEFT_TOBOTTOM - Static variable in class javax.print.attribute.standard.PresentationDirection
Pages are laid out in rows starting at the top right, proceeeding towards the left & bottom.
TOLEFT_TOTOP - Static variable in class javax.print.attribute.standard.PresentationDirection
Pages are laid out in rows starting at the bottom right, proceeeding towards the left & top.
toLocaleString() - Method in class java.util.Date
Deprecated.
As of JDK version 1.1, replaced by DateFormat.format(Date date).
toLocalizedPattern() - Method in class java.text.DecimalFormat
Synthesizes a localized pattern string that represents the current state of this Format object.
toLocalizedPattern() - Method in class java.text.SimpleDateFormat
Returns a localized pattern string describing this date format.
toLongArray() - Method in class java.util.BitSet
Returns a new long array containing all the bits in this bit set.
toLowerCase(char) - Static method in class java.lang.Character
Converts the character argument to lowercase using case mapping information from the UnicodeData file.
toLowerCase(int) - Static method in class java.lang.Character
Converts the character (Unicode code point) argument to lowercase using case mapping information from the UnicodeData file.
toLowerCase(Locale) - Method in class java.lang.String
Converts all of the characters in this String to lower case using the rules of the given Locale.
toLowerCase() - Method in class java.lang.String
Converts all of the characters in this String to lower case using the rules of the default locale.
toMatchResult() - Method in class java.util.regex.Matcher
Returns the match state of this matcher as a MatchResult.
toMethodDescriptorString() - Method in class java.lang.invoke.MethodType
Produces a bytecode descriptor representation of the method type.
toMicros(long) - Method in enum java.util.concurrent.TimeUnit
Equivalent to MICROSECONDS.convert(duration, this).
toMillis() - Method in class java.nio.file.attribute.FileTime
Returns the value in milliseconds.
toMillis(long) - Method in enum java.util.concurrent.TimeUnit
Equivalent to MILLISECONDS.convert(duration, this).
toMinutes(long) - Method in enum java.util.concurrent.TimeUnit
Equivalent to MINUTES.convert(duration, this).
toNanos(long) - Method in enum java.util.concurrent.TimeUnit
Equivalent to NANOSECONDS.convert(duration, this).
TONER_EMPTY - Static variable in class javax.print.attribute.standard.PrinterStateReason
The device is out of toner.
TONER_LOW - Static variable in class javax.print.attribute.standard.PrinterStateReason
The device is low on toner.
toOctalString(int) - Static method in class java.lang.Integer
Returns a string representation of the integer argument as an unsigned integer in base 8.
toOctalString(long) - Static method in class java.lang.Long
Returns a string representation of the long argument as an unsigned integer in base 8.
Tool - Interface in javax.tools
Common interface for tools that can be invoked from a program.
TOOL_BAR - Static variable in class javax.accessibility.AccessibleRole
A bar or palette usually composed of push buttons or toggle buttons.
TOOL_BAR - Static variable in class javax.swing.plaf.synth.Region
ToolBar region.
TOOL_BAR_CONTENT - Static variable in class javax.swing.plaf.synth.Region
Region of the ToolBar containing the content.
TOOL_BAR_DRAG_WINDOW - Static variable in class javax.swing.plaf.synth.Region
Region for the Window containing the ToolBar.
TOOL_BAR_SEPARATOR - Static variable in class javax.swing.plaf.synth.Region
ToolBar separator region.
TOOL_TIP - Static variable in class javax.accessibility.AccessibleRole
An object that provides information about another object.
TOOL_TIP - Static variable in class javax.swing.plaf.synth.Region
ToolTip region.
TOOL_TIP_TEXT_KEY - Static variable in class javax.swing.JComponent
The comment to display when the cursor is over the component, also known as a "value tip", "flyover help", or "flyover label".
toolBar - Variable in class javax.swing.plaf.basic.BasicToolBarUI.DockingListener
toolBar - Variable in class javax.swing.plaf.basic.BasicToolBarUI
toolBarContListener - Variable in class javax.swing.plaf.basic.BasicToolBarUI
toolBarFocusListener - Variable in class javax.swing.plaf.basic.BasicToolBarUI
ToolBarUI - Class in javax.swing.plaf
Pluggable look and feel interface for JToolBar.
ToolBarUI() - Constructor for class javax.swing.plaf.ToolBarUI
Toolkit - Class in java.awt
This class is the abstract superclass of all actual implementations of the Abstract Window Toolkit.
Toolkit() - Constructor for class java.awt.Toolkit
ToolProvider - Class in javax.tools
Provides methods for locating tool providers, for example, providers of compilers.
ToolTipManager - Class in javax.swing
Manages all the ToolTips in the system.
ToolTipManager.insideTimerAction - Class in javax.swing
ToolTipManager.insideTimerAction() - Constructor for class javax.swing.ToolTipManager.insideTimerAction
ToolTipManager.outsideTimerAction - Class in javax.swing
ToolTipManager.outsideTimerAction() - Constructor for class javax.swing.ToolTipManager.outsideTimerAction
ToolTipManager.stillInsideTimerAction - Class in javax.swing
ToolTipManager.stillInsideTimerAction() - Constructor for class javax.swing.ToolTipManager.stillInsideTimerAction
ToolTipUI - Class in javax.swing.plaf
Pluggable look and feel interface for JToolTip.
ToolTipUI() - Constructor for class javax.swing.plaf.ToolTipUI
TooManyListenersException - Exception in java.util
The TooManyListenersException Exception is used as part of the Java Event model to annotate and implement a unicast special case of a multicast Event Source.
TooManyListenersException() - Constructor for exception java.util.TooManyListenersException
Constructs a TooManyListenersException with no detail message.
TooManyListenersException(String) - Constructor for exception java.util.TooManyListenersException
Constructs a TooManyListenersException with the specified detail message.
top - Variable in class java.awt.Insets
The inset from the top.
TOP - Static variable in class javax.print.attribute.standard.MediaTray
The top input tray in the printer.
top - Variable in class javax.swing.border.EmptyBorder
TOP - Static variable in class javax.swing.border.TitledBorder
Position the title in the middle of the border's top line.
TOP - Static variable in class javax.swing.JSplitPane
Used to add a Component above the other Component.
TOP - Static variable in interface javax.swing.SwingConstants
Box-orientation constant used to specify the top of a box.
TOP_ALIGNMENT - Static variable in class java.awt.Component
Ease-of-use constant for getAlignmentY().
TOP_ALIGNMENT - Static variable in class java.awt.font.GraphicAttribute
Aligns top of graphic to top of line.
toPath() - Method in class java.io.File
Returns a java.nio.file.Path object constructed from the this abstract path.
toPattern() - Method in class java.text.ChoiceFormat
Gets the pattern.
toPattern() - Method in class java.text.DecimalFormat
Synthesizes a pattern string that represents the current state of this Format object.
toPattern() - Method in class java.text.MessageFormat
Returns a pattern representing the current state of the message format.
toPattern() - Method in class java.text.SimpleDateFormat
Returns a pattern string describing this date format.
TOPDOWNLEFTRIGHT - Static variable in interface java.awt.image.ImageConsumer
The pixels will be delivered in top-down, left-to-right order.
toPlainString() - Method in class java.math.BigDecimal
Returns a string representation of this BigDecimal without an exponent field.
toRadians(double) - Static method in class java.lang.Math
Converts an angle measured in degrees to an approximately equivalent angle measured in radians.
toRadians(double) - Static method in class java.lang.StrictMath
Converts an angle measured in degrees to an approximately equivalent angle measured in radians.
toRealPath(LinkOption...) - Method in interface java.nio.file.Path
Returns the real path of an existing file.
toResourceName(String, String) - Method in class java.util.ResourceBundle.Control
Converts the given bundleName to the form required by the ClassLoader.getResource method by replacing all occurrences of '.' in bundleName with '/' and appending a '.' and the given file suffix.
toRGB(float[]) - Method in class java.awt.color.ColorSpace
Transforms a color value assumed to be in this ColorSpace into a value in the default CS_sRGB color space.
toRGB(float[]) - Method in class java.awt.color.ICC_ColorSpace
Transforms a color value assumed to be in this ColorSpace into a value in the default CS_sRGB color space.
TORIGHT_TOBOTTOM - Static variable in class javax.print.attribute.standard.PresentationDirection
Pages are laid out in rows starting at the top left, proceeeding towards the right & bottom.
TORIGHT_TOTOP - Static variable in class javax.print.attribute.standard.PresentationDirection
Pages are laid out in rows starting at the bottom left, proceeeding towards the right & top.
toSeconds(long) - Method in enum java.util.concurrent.TimeUnit
Equivalent to SECONDS.convert(duration, this).
toString() - Method in class java.awt.AWTEvent
Returns a String representation of this object.
toString() - Method in class java.awt.AWTKeyStroke
Returns a string that displays and identifies this object's properties.
toString() - Method in class java.awt.BorderLayout
Returns a string representation of the state of this border layout.
toString() - Method in class java.awt.CardLayout
Returns a string representation of the state of this card layout.
toString() - Method in class java.awt.CheckboxGroup
Returns a string representation of this check box group, including the value of its current selection.
toString() - Method in class java.awt.Color
Returns a string representation of this Color.
toString() - Method in class java.awt.Component
Returns a string representation of this component and its values.
toString() - Method in class java.awt.Cursor
Returns a string representation of this cursor.
toString() - Method in class java.awt.datatransfer.DataFlavor
String representation of this DataFlavor and its parameters.
toString() - Method in class java.awt.Dimension
Returns a string representation of the values of this Dimension object's height and width fields.
toString() - Method in class java.awt.Event
NOTE: The Event class is obsolete and is available only for backwards compatilibility.
toString() - Method in class java.awt.FlowLayout
Returns a string representation of this FlowLayout object and its values.
toString() - Method in class java.awt.font.NumericShaper
Returns a String that describes this shaper.
toString() - Method in class java.awt.font.TextHitInfo
Returns a String representing the hit for debugging use only.
toString() - Method in class java.awt.font.TextLayout
Returns debugging information for this TextLayout.
toString() - Method in class java.awt.Font
Converts this Font object to a String representation.
toString() - Method in class java.awt.FontMetrics
Returns a representation of this FontMetrics object's values as a String.
toString() - Method in class java.awt.geom.AffineTransform
Returns a String that represents the value of this Object.
toString() - Method in class java.awt.geom.Point2D.Double
Returns a String that represents the value of this Point2D.
toString() - Method in class java.awt.geom.Point2D.Float
Returns a String that represents the value of this Point2D.
toString() - Method in class java.awt.geom.Rectangle2D.Double
Returns the String representation of this Rectangle2D.
toString() - Method in class java.awt.geom.Rectangle2D.Float
Returns the String representation of this Rectangle2D.
toString() - Method in class java.awt.Graphics
Returns a String object representing this Graphics object's value.
toString() - Method in class java.awt.GridBagLayout
Returns a string representation of this grid bag layout's values.
toString() - Method in class java.awt.GridLayout
Returns the string representation of this grid layout's values.
toString() - Method in class java.awt.image.BufferedImage
Returns a String representation of this BufferedImage object and its values.
toString() - Method in class java.awt.image.ColorModel
Returns the String representation of the contents of this ColorModelobject.
toString() - Method in class java.awt.image.DirectColorModel
Returns a String that represents this DirectColorModel.
toString() - Method in class java.awt.image.IndexColorModel
Returns the String representation of the contents of this ColorModelobject.
toString() - Method in class java.awt.Insets
Returns a string representation of this Insets object.
toString() - Method in class java.awt.JobAttributes
Returns a string representation of this JobAttributes.
toString() - Method in class java.awt.MenuComponent
Returns a representation of this menu component as a string.
toString() - Method in class java.awt.MenuShortcut
Returns an internationalized description of the MenuShortcut.
toString() - Method in class java.awt.PageAttributes
Returns a string representation of this PageAttributes.
toString() - Method in class java.awt.Point
Returns a string representation of this point and its location in the (x,y) coordinate space.
toString() - Method in class java.awt.Rectangle
Returns a String representing this Rectangle and its values.
toString() - Method in class java.awt.RenderingHints
Returns a rather long string representation of the hashmap which contains the mappings of keys to values for this RenderingHints object.
toString() - Method in class java.awt.Robot
Returns a string representation of this Robot.
toString() - Method in class java.awt.ScrollPaneAdjustable
Returns a string representation of this scrollbar and its values.
toString() - Method in class java.awt.SystemColor
Returns a string representation of this Color's values.
toString() - Method in class java.beans.Expression
Prints the value of this expression using a Java-style syntax.
toString() - Method in class java.beans.FeatureDescriptor
Returns a string representation of the object.
toString() - Method in class java.beans.PropertyChangeEvent
Returns a string representation of the object.
toString() - Method in class java.beans.Statement
Prints the value of this statement using a Java-style syntax.
toString() - Method in class java.io.ByteArrayOutputStream
Converts the buffer's contents into a string decoding bytes using the platform's default character set.
toString(String) - Method in class java.io.ByteArrayOutputStream
Converts the buffer's contents into a string by decoding the bytes using the specified charsetName.
toString(int) - Method in class java.io.ByteArrayOutputStream
Deprecated.
This method does not properly convert bytes into characters. As of JDK 1.1, the preferred way to do this is via the toString(String enc) method, which takes an encoding-name argument, or the toString() method, which uses the platform's default character encoding.
toString() - Method in class java.io.CharArrayWriter
Converts input data to a string.
toString() - Method in class java.io.File
Returns the pathname string of this abstract pathname.
toString() - Method in class java.io.ObjectStreamClass
Return a string describing this ObjectStreamClass.
toString() - Method in class java.io.ObjectStreamField
Return a string that describes this field.
toString() - Method in class java.io.StreamTokenizer
Returns the string representation of the current stream token and the line number it occurs on.
toString() - Method in class java.io.StringWriter
Return the buffer's current value as a string.
toString() - Method in interface java.lang.annotation.Annotation
Returns a string representation of this annotation.
toString(boolean) - Static method in class java.lang.Boolean
Returns a String object representing the specified boolean.
toString() - Method in class java.lang.Boolean
Returns a String object representing this Boolean's value.
toString(byte) - Static method in class java.lang.Byte
Returns a new String object representing the specified byte.
toString() - Method in class java.lang.Byte
Returns a String object representing this Byte's value.
toString() - Method in class java.lang.Character.Subset
Returns the name of this subset.
toString() - Method in class java.lang.Character
Returns a String object representing this Character's value.
toString(char) - Static method in class java.lang.Character
Returns a String object representing the specified char.
toString() - Method in interface java.lang.CharSequence
Returns a string containing the characters in this sequence in the same order as this sequence.
toString() - Method in class java.lang.类
Converts the object to a string.
toString(double) - Static method in class java.lang.Double
Returns a string representation of the double argument.
toString() - Method in class java.lang.Double
Returns a string representation of this Double object.
toString() - Method in class java.lang.Enum
Returns the name of this enum constant, as contained in the declaration.
toString(float) - Static method in class java.lang.Float
Returns a string representation of the float argument.
toString() - Method in class java.lang.Float
Returns a string representation of this Float object.
toString(int, int) - Static method in class java.lang.Integer
Returns a string representation of the first argument in the radix specified by the second argument.
toString(int) - Static method in class java.lang.Integer
Returns a String object representing the specified integer.
toString() - Method in class java.lang.Integer
Returns a String object representing this Integer's value.
toString() - Method in class java.lang.invoke.MethodHandle
Returns a string representation of the method handle, starting with the string "MethodHandle" and ending with the string representation of the method handle's type.
toString() - Method in class java.lang.invoke.MethodHandles.Lookup
Displays the name of the class from which lookups are to be made.
toString() - Method in class java.lang.invoke.MethodType
Returns a string representation of the method type, of the form "(PT0,PT1...)RT".
toString(long, int) - Static method in class java.lang.Long
Returns a string representation of the first argument in the radix specified by the second argument.
toString(long) - Static method in class java.lang.Long
Returns a String object representing the specified long.
toString() - Method in class java.lang.Long
Returns a String object representing this Long's value.
toString() - Method in class java.lang.management.LockInfo
Returns a string representation of a lock.
toString() - Method in enum java.lang.management.MemoryType
Returns the string representation of this MemoryType.
toString() - Method in class java.lang.management.MemoryUsage
Returns a descriptive representation of this memory usage.
toString() - Method in class java.lang.management.ThreadInfo
Returns a string representation of this thread info.
toString() - Method in class java.lang.Object
Returns a string representation of the object.
toString() - Method in class java.lang.软件包
Returns the string representation of this Package.
toString() - Method in class java.lang.reflect.Constructor
Returns a string describing this Constructor.
toString() - Method in class java.lang.reflect.字段
Returns a string describing this Field.
toString() - Method in class java.lang.reflect.方法
Returns a string describing this Method.
toString(int) - Static method in class java.lang.reflect.修饰符
Return a string describing the access modifier flags in the specified modifier.
toString(short) - Static method in class java.lang.Short
Returns a new String object representing the specified short.
toString() - Method in class java.lang.Short
Returns a String object representing this Short's value.
toString() - Method in class java.lang.StackTraceElement
Returns a string representation of this stack trace element.
toString() - Method in class java.lang.String
This object (which is already a string!) is itself returned.
toString() - Method in class java.lang.StringBuffer
toString() - Method in class java.lang.StringBuilder
toString() - Method in class java.lang.Thread
Returns a string representation of this thread, including the thread's name, priority, and thread group.
toString() - Method in class java.lang.ThreadGroup
Returns a string representation of this Thread group.
toString() - Method in class java.lang.Throwable
Returns a short description of this throwable.
toString() - Method in class java.math.BigDecimal
Returns the string representation of this BigDecimal, using scientific notation if an exponent is needed.
toString(int) - Method in class java.math.BigInteger
Returns the String representation of this BigInteger in the given radix.
toString() - Method in class java.math.BigInteger
Returns the decimal String representation of this BigInteger.
toString() - Method in class java.math.MathContext
Returns the string representation of this MathContext.
toString() - Method in class java.net.HttpCookie
Constructs a cookie header string representation of this cookie, which is in the format defined by corresponding cookie specification, but without the leading "Cookie:" token.
toString() - Method in class java.net.InetAddress
Converts this IP address to a String.
toString() - Method in class java.net.InetSocketAddress
Constructs a string representation of this InetSocketAddress.
toString() - Method in class java.net.InterfaceAddress
Converts this Interface address to a String.
toString() - Method in class java.net.NetworkInterface
toString() - Method in class java.net.Proxy
Constructs a string representation of this Proxy.
toString() - Method in class java.net.ServerSocket
Returns the implementation address and implementation port of this socket as a String.
toString() - Method in class java.net.Socket
Converts this socket to a String.
toString() - Method in class java.net.SocketImpl
Returns the address and port of this socket as a String.
toString() - Method in class java.net.URI
Returns the content of this URI as a string.
toString() - Method in class java.net.URL
Constructs a string representation of this URL.
toString() - Method in class java.net.URLConnection
Returns a String representation of this URL connection.
toString() - Method in class java.nio.ByteBuffer
Returns a string summarizing the state of this buffer.
toString() - Method in class java.nio.ByteOrder
Constructs a string describing this object.
toString() - Method in class java.nio.channels.FileChannel.MapMode
Returns a string describing this file-mapping mode.
toString() - Method in class java.nio.channels.FileLock
Returns a string describing the range, type, and validity of this lock.
toString() - Method in class java.nio.CharBuffer
Returns a string containing the characters in this buffer.
toString() - Method in class java.nio.charset.Charset
Returns a string describing this charset.
toString() - Method in class java.nio.charset.CoderResult
Returns a string describing this coder result.
toString() - Method in class java.nio.charset.CodingErrorAction
Returns a string describing this action.
toString() - Method in class java.nio.DoubleBuffer
Returns a string summarizing the state of this buffer.
toString() - Method in class java.nio.file.attribute.AclEntry
Returns the string representation of this ACL entry.
toString() - Method in class java.nio.file.attribute.FileTime
Returns the string representation of this FileTime.
toString(Set<PosixFilePermission>) - Static method in class java.nio.file.attribute.PosixFilePermissions
Returns the String representation of a set of permissions.
toString() - Method in interface java.nio.file.Path
Returns the string representation of this path.
toString() - Method in class java.nio.FloatBuffer
Returns a string summarizing the state of this buffer.
toString() - Method in class java.nio.IntBuffer
Returns a string summarizing the state of this buffer.
toString() - Method in class java.nio.LongBuffer
Returns a string summarizing the state of this buffer.
toString() - Method in class java.nio.ShortBuffer
Returns a string summarizing the state of this buffer.
toString() - Method in class java.rmi.dgc.VMID
Return string representation of this VMID.
toString() - Method in class java.rmi.server.LogStream
Deprecated.
no replacement
toString() - Method in class java.rmi.server.ObjID
Returns a string representation of this object identifier.
toString() - Method in class java.rmi.server.Operation
Deprecated.
no replacement
toString() - Method in class java.rmi.server.RemoteObject
Returns a String that represents the value of this remote object.
toString() - Method in class java.rmi.server.UID
Returns a string representation of this UID.
toString() - Method in interface java.security.acl.Acl
Returns a string representation of the ACL contents.
toString() - Method in interface java.security.acl.AclEntry
Returns a string representation of the contents of this ACL entry.
toString() - Method in interface java.security.acl.Permission
Prints a string representation of this permission.
toString() - Method in class java.security.AlgorithmParameters
Returns a formatted string describing the parameters.
toString() - Method in class java.security.cert.Certificate
Returns a string representation of this certificate.
toString() - Method in class java.security.cert.CertPath
Returns a string representation of this certification path.
toString() - Method in class java.security.cert.CollectionCertStoreParameters
Returns a formatted string describing the parameters.
toString() - Method in class java.security.cert.CRL
Returns a string representation of this CRL.
toString() - Method in class java.security.cert.LDAPCertStoreParameters
Returns a formatted string describing the parameters.
toString() - Method in class java.security.cert.PKIXBuilderParameters
Returns a formatted string describing the parameters.
toString() - Method in class java.security.cert.PKIXCertPathBuilderResult
Return a printable representation of this PKIXCertPathBuilderResult.
toString() - Method in class java.security.cert.PKIXCertPathValidatorResult
Return a printable representation of this PKIXCertPathValidatorResult.
toString() - Method in class java.security.cert.PKIXParameters
Returns a formatted string describing the parameters.
toString() - Method in class java.security.cert.PolicyQualifierInfo
Return a printable representation of this PolicyQualifierInfo.
toString() - Method in class java.security.cert.TrustAnchor
Returns a formatted string describing the TrustAnchor.
toString() - Method in class java.security.cert.X509CertSelector
Return a printable representation of the CertSelector.
toString() - Method in class java.security.cert.X509CRLEntry
Returns a string representation of this CRL entry.
toString() - Method in class java.security.cert.X509CRLSelector
Returns a printable representation of the X509CRLSelector.
toString(boolean) - Method in interface java.security.Certificate
Deprecated.
Returns a string that represents the contents of the certificate.
toString() - Method in class java.security.CodeSigner
Returns a string describing this code signer.
toString() - Method in class java.security.CodeSource
Returns a string describing this CodeSource, telling its URL and certificates.
toString() - Method in class java.security.DigestInputStream
Prints a string representation of this digest input stream and its associated message digest object.
toString() - Method in class java.security.DigestOutputStream
Prints a string representation of this digest output stream and its associated message digest object.
toString() - Method in class java.security.Identity
Deprecated.
Returns a short string describing this identity, telling its name and its scope (if any).
toString(boolean) - Method in class java.security.Identity
Deprecated.
Returns a string representation of this identity, with optionally more details than that provided by the toString method without any arguments.
toString() - Method in class java.security.IdentityScope
Deprecated.
Returns a string representation of this identity scope, including its name, its scope name, and the number of identities in this identity scope.
toString() - Method in class java.security.KeyStore.PrivateKeyEntry
Returns a string representation of this PrivateKeyEntry.
toString() - Method in class java.security.KeyStore.SecretKeyEntry
Returns a string representation of this SecretKeyEntry.
toString() - Method in class java.security.KeyStore.TrustedCertificateEntry
Returns a string representation of this TrustedCertificateEntry.
toString() - Method in class java.security.MessageDigest
Returns a string representation of this message digest object.
toString() - Method in class java.security.Permission
Returns a string describing this Permission.
toString() - Method in class java.security.PermissionCollection
Returns a string describing this PermissionCollection object, providing information about all the permissions it contains.
toString() - Method in interface java.security.Principal
Returns a string representation of this principal.
toString() - Method in exception java.security.PrivilegedActionException
toString() - Method in class java.security.ProtectionDomain
Convert a ProtectionDomain to a String.
toString() - Method in class java.security.Provider.Service
Return a String representation of this service.
toString() - Method in class java.security.Provider
Returns a string with the name and the version number of this provider.
toString() - Method in class java.security.Signature
Returns a string representation of this signature object, providing information that includes the state of the object and the name of the algorithm used.
toString() - Method in class java.security.Signer
Deprecated.
Returns a string of information about the signer.
toString() - Method in class java.security.Timestamp
Returns a string describing this timestamp.
toString() - Method in class java.security.UnresolvedPermission
Returns a string describing this UnresolvedPermission.
toString() - Method in class java.sql.Date
Formats a date in the date escape format yyyy-mm-dd.
toString() - Method in interface java.sql.RowId
Returns a String representing the value of the SQL ROWID designated by this java.sql.RowId object.
toString() - Method in class java.sql.Time
Formats a time in JDBC time escape format.
toString() - Method in class java.sql.Timestamp
Formats a timestamp in JDBC timestamp escape format.
toString() - Method in class java.text.Annotation
Returns the String representation of this Annotation.
toString() - Method in class java.text.AttributedCharacterIterator.Attribute
Returns a string representation of the object.
toString() - Method in class java.text.Bidi
Display the bidi internal state, used in debugging.
toString() - Method in class java.text.FieldPosition
Return a string representation of this FieldPosition.
toString() - Method in class java.text.ParsePosition
Return a string representation of this ParsePosition.
toString() - Method in class java.util.AbstractCollection
Returns a string representation of this collection.
toString() - Method in class java.util.AbstractMap.SimpleEntry
Returns a String representation of this map entry.
toString() - Method in class java.util.AbstractMap.SimpleImmutableEntry
Returns a String representation of this map entry.
toString() - Method in class java.util.AbstractMap
Returns a string representation of this map.
toString(long[]) - Static method in class java.util.Arrays
Returns a string representation of the contents of the specified array.
toString(int[]) - Static method in class java.util.Arrays
Returns a string representation of the contents of the specified array.
toString(short[]) - Static method in class java.util.Arrays
Returns a string representation of the contents of the specified array.
toString(char[]) - Static method in class java.util.Arrays
Returns a string representation of the contents of the specified array.
toString(byte[]) - Static method in class java.util.Arrays
Returns a string representation of the contents of the specified array.
toString(boolean[]) - Static method in class java.util.Arrays
Returns a string representation of the contents of the specified array.
toString(float[]) - Static method in class java.util.Arrays
Returns a string representation of the contents of the specified array.
toString(double[]) - Static method in class java.util.Arrays
Returns a string representation of the contents of the specified array.
toString(Object[]) - Static method in class java.util.Arrays
Returns a string representation of the contents of the specified array.
toString() - Method in class java.util.BitSet
Returns a string representation of this bit set.
toString() - Method in class java.util.Calendar
Return a string representation of this calendar.
toString() - Method in class java.util.concurrent.ArrayBlockingQueue
toString() - Method in class java.util.concurrent.atomic.AtomicBoolean
Returns the String representation of the current value.
toString() - Method in class java.util.concurrent.atomic.AtomicInteger
Returns the String representation of the current value.
toString() - Method in class java.util.concurrent.atomic.AtomicIntegerArray
Returns the String representation of the current values of array.
toString() - Method in class java.util.concurrent.atomic.AtomicLong
Returns the String representation of the current value.
toString() - Method in class java.util.concurrent.atomic.AtomicLongArray
Returns the String representation of the current values of array.
toString() - Method in class java.util.concurrent.atomic.AtomicReference
Returns the String representation of the current value.
toString() - Method in class java.util.concurrent.atomic.AtomicReferenceArray
Returns the String representation of the current values of array.
toString() - Method in class java.util.concurrent.CopyOnWriteArrayList
Returns a string representation of this list.
toString() - Method in class java.util.concurrent.CountDownLatch
Returns a string identifying this latch, as well as its state.
toString() - Method in class java.util.concurrent.ForkJoinPool
Returns a string identifying this pool, as well as its state, including indications of run state, parallelism level, and worker and task counts.
toString() - Method in class java.util.concurrent.LinkedBlockingDeque
toString() - Method in class java.util.concurrent.LinkedBlockingQueue
toString() - Method in class java.util.concurrent.locks.AbstractQueuedLongSynchronizer
Returns a string identifying this synchronizer, as well as its state.
toString() - Method in class java.util.concurrent.locks.AbstractQueuedSynchronizer
Returns a string identifying this synchronizer, as well as its state.
toString() - Method in class java.util.concurrent.locks.ReentrantLock
Returns a string identifying this lock, as well as its lock state.
toString() - Method in class java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock
Returns a string identifying this lock, as well as its lock state.
toString() - Method in class java.util.concurrent.locks.ReentrantReadWriteLock
Returns a string identifying this lock, as well as its lock state.
toString() - Method in class java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock
Returns a string identifying this lock, as well as its lock state.
toString() - Method in class java.util.concurrent.Phaser
Returns a string identifying this phaser, as well as its state.
toString() - Method in class java.util.concurrent.PriorityBlockingQueue
toString() - Method in class java.util.concurrent.Semaphore
Returns a string identifying this semaphore, as well as its state.
toString() - Method in class java.util.concurrent.ThreadPoolExecutor
Returns a string identifying this pool, as well as its state, including indications of run state and estimated worker and task counts.
toString() - Method in class java.util.Currency
Returns the ISO 4217 currency code of this currency.
toString() - Method in class java.util.Date
Converts this Date object to a String of the form:
toString() - Method in class java.util.EventObject
Returns a String representation of this EventObject.
toString() - Method in class java.util.Formatter
Returns the result of invoking toString() on the destination for the output.
toString() - Method in class java.util.Hashtable
Returns a string representation of this Hashtable object in the form of a set of entries, enclosed in braces and separated by the ASCII characters ", " (comma and space).
toString() - Method in class java.util.jar.Attributes.Name
Returns the attribute name as a String.
toString() - Method in class java.util.Locale
Returns a string representation of this Locale object, consisting of language, country, variant, script, and extensions as below:
toString() - Method in class java.util.logging.Level
Returns a string representation of this Level.
toString(Object) - Static method in class java.util.Objects
Returns the result of calling toString for a non-null argument and "null" for a null argument.
toString(Object, String) - Static method in class java.util.Objects
Returns the result of calling toString on the first argument if the first argument is not null and returns the second argument otherwise.
toString() - Method in class java.util.prefs.AbstractPreferences
Returns the absolute path name of this preferences node.
toString() - Method in class java.util.prefs.Preferences
Returns a string representation of this preferences node, as if computed by the expression:(this.isUserNode() ? "User" : "System") + " Preference Node: " + this.absolutePath().
toString() - Method in class java.util.regex.Matcher
Returns the string representation of this matcher.
toString() - Method in class java.util.regex.Pattern
Returns the string representation of this pattern.
toString() - Method in class java.util.Scanner
Returns the string representation of this Scanner.
toString() - Method in class java.util.ServiceLoader
Returns a string describing this service.
toString() - Method in class java.util.SimpleTimeZone
Returns a string representation of this time zone.
toString() - Method in class java.util.UUID
Returns a String object representing this UUID.
toString() - Method in class java.util.Vector
Returns a string representation of this Vector, containing the String representation of each element.
toString() - Method in class java.util.zip.ZipEntry
Returns a string representation of the ZIP entry.
toString() - Method in class javax.accessibility.AccessibleBundle
Gets localized string describing the key using the default locale.
toString() - Method in class javax.accessibility.AccessibleRelationSet
Creates a localized String representing all the relations in the set using the default locale.
toString() - Method in class javax.accessibility.AccessibleStateSet
Creates a localized String representing all the states in the set using the default locale.
toString() - Method in class javax.activation.MimeType
Return the String representation of this object.
toString() - Method in class javax.activation.MimeTypeParameterList
Return a string representation of this object.
toString() - Method in class javax.imageio.plugins.jpeg.JPEGHuffmanTable
Returns a String representing this Huffman table.
toString() - Method in class javax.imageio.plugins.jpeg.JPEGQTable
Returns a String representing this quantization table.
toString() - Method in interface javax.lang.model.element.AnnotationValue
Returns a string representation of this value.
toString() - Method in enum javax.lang.model.element.修饰符
Returns this modifier's name in lowercase.
toString() - Method in interface javax.lang.model.type.TypeMirror
Returns an informative string representation of this type.
toString() - Method in class javax.management.Attribute
Returns a String object representing this Attribute's value.
toString() - Method in class javax.management.AttributeValueExp
Returns the string representing its value.
toString() - Method in exception javax.management.BadAttributeValueExpException
Returns the string representing the object.
toString() - Method in exception javax.management.BadBinaryOpValueExpException
Returns the string representing the object.
toString() - Method in exception javax.management.BadStringOperationException
Returns the string representing the object.
toString() - Method in class javax.management.ImmutableDescriptor
toString() - Method in class javax.management.MBeanAttributeInfo
toString() - Method in class javax.management.MBeanConstructorInfo
toString() - Method in class javax.management.MBeanInfo
toString() - Method in class javax.management.MBeanNotificationInfo
toString() - Method in class javax.management.MBeanOperationInfo
toString() - Method in class javax.management.MBeanParameterInfo
toString() - Method in class javax.management.MBeanServerNotification
toString() - Method in class javax.management.modelmbean.DescriptorSupport
Returns a human readable string representing the descriptor.
toString() - Method in class javax.management.modelmbean.ModelMBeanAttributeInfo
Returns a human-readable version of the ModelMBeanAttributeInfo instance.
toString() - Method in class javax.management.modelmbean.ModelMBeanConstructorInfo
Returns a string containing the entire contents of the ModelMBeanConstructorInfo in human readable form.
toString() - Method in class javax.management.modelmbean.ModelMBeanNotificationInfo
Returns a human readable string containing ModelMBeanNotificationInfo.
toString() - Method in class javax.management.modelmbean.ModelMBeanOperationInfo
Returns a string containing the entire contents of the ModelMBeanOperationInfo in human readable form.
toString() - Method in class javax.management.Notification
Returns a String representation of this notification.
toString() - Method in class javax.management.ObjectInstance
Returns a string representing this ObjectInstance object.
toString() - Method in class javax.management.ObjectName
Returns a string representation of the object name.
toString() - Method in class javax.management.openmbean.ArrayType
Returns a string representation of this ArrayType instance.
toString() - Method in interface javax.management.openmbean.CompositeData
Returns a string representation of this CompositeData instance.
toString() - Method in class javax.management.openmbean.CompositeDataSupport
Returns a string representation of this CompositeDataSupport instance.
toString() - Method in class javax.management.openmbean.CompositeType
Returns a string representation of this CompositeType instance.
toString() - Method in interface javax.management.openmbean.OpenMBeanAttributeInfo
Returns a string representation of this OpenMBeanAttributeInfo instance.
toString() - Method in class javax.management.openmbean.OpenMBeanAttributeInfoSupport
Returns a string representation of this OpenMBeanAttributeInfoSupport instance.
toString() - Method in interface javax.management.openmbean.OpenMBeanConstructorInfo
Returns a string representation of this OpenMBeanConstructorInfo instance.
toString() - Method in class javax.management.openmbean.OpenMBeanConstructorInfoSupport
Returns a string representation of this OpenMBeanConstructorInfoSupport instance.
toString() - Method in interface javax.management.openmbean.OpenMBeanInfo
Returns a string representation of this OpenMBeanInfo instance.
toString() - Method in class javax.management.openmbean.OpenMBeanInfoSupport
Returns a string representation of this OpenMBeanInfoSupport instance.
toString() - Method in interface javax.management.openmbean.OpenMBeanOperationInfo
Returns a string representation of this OpenMBeanOperationInfo instance.
toString() - Method in class javax.management.openmbean.OpenMBeanOperationInfoSupport
Returns a string representation of this OpenMBeanOperationInfoSupport instance.
toString() - Method in interface javax.management.openmbean.OpenMBeanParameterInfo
Returns a string representation of this OpenMBeanParameterInfo instance.
toString() - Method in class javax.management.openmbean.OpenMBeanParameterInfoSupport
Returns a string representation of this OpenMBeanParameterInfoSupport instance.
toString() - Method in class javax.management.openmbean.OpenType
Returns a string representation of this open type instance.
toString() - Method in class javax.management.openmbean.SimpleType
Returns a string representation of this SimpleType instance.
toString() - Method in interface javax.management.openmbean.TabularData
Returns a string representation of this TabularData instance.
toString() - Method in class javax.management.openmbean.TabularDataSupport
Returns a string representation of this TabularDataSupport instance.
toString() - Method in class javax.management.openmbean.TabularType
Returns a string representation of this TabularType instance.
toString() - Method in class javax.management.relation.Role
Returns a string describing the role.
toString() - Method in class javax.management.relation.RoleInfo
Returns a string describing the role info.
toString() - Method in class javax.management.relation.RoleUnresolved
Return a string describing this object.
toString() - Method in class javax.management.remote.JMXPrincipal
Returns a string representation of this JMXPrincipal.
toString() - Method in class javax.management.remote.JMXServiceURL
The string representation of this Service URL.
toString() - Method in class javax.management.remote.NotificationResult
Returns a string representation of the object.
toString() - Method in class javax.management.remote.rmi.RMIConnectionImpl
Returns a string representation of this object.
toString() - Method in class javax.management.remote.rmi.RMIConnector
Returns a string representation of this object.
toString() - Method in class javax.management.remote.TargetedNotification
Returns a textual representation of this Targeted Notification.
toString() - Method in class javax.management.StringValueExp
Returns the string representing the object.
toString() - Method in class javax.naming.BinaryRefAddr
Generates the string representation of this address.
toString() - Method in class javax.naming.Binding
Generates the string representation of this binding.
toString() - Method in class javax.naming.CompositeName
Generates the string representation of this composite name.
toString() - Method in class javax.naming.CompoundName
Generates the string representation of this compound name, using the syntax rules of the compound name.
toString() - Method in exception javax.naming.directory.AttributeModificationException
The string representation of this exception consists of information about where the error occurred, and the first unexecuted modification.
toString() - Method in class javax.naming.directory.BasicAttribute
Generates the string representation of this attribute.
toString() - Method in class javax.naming.directory.BasicAttributes
Generates the string representation of this attribute set.
toString() - Method in class javax.naming.directory.ModificationItem
Generates the string representation of this modification item, which consists of the modification operation and its related attribute.
toString() - Method in class javax.naming.directory.SearchResult
Generates the string representation of this SearchResult.
toString() - Method in class javax.naming.ldap.LdapName
Returns a string representation of this LDAP name in a format defined by RFC 2253 and described in the class description.
toString() - Method in class javax.naming.ldap.Rdn
Returns this Rdn as a string represented in a format defined by RFC 2253 and described in the class description for LdapName.
toString() - Method in exception javax.naming.LinkException
Generates the string representation of this exception.
toString(boolean) - Method in exception javax.naming.LinkException
Generates the string representation of this exception.
toString() - Method in class javax.naming.NameClassPair
Generates the string representation of this name/class pair.
toString() - Method in exception javax.naming.NamingException
Generates the string representation of this exception.
toString(boolean) - Method in exception javax.naming.NamingException
Generates the string representation in more detail.
toString() - Method in class javax.naming.RefAddr
Generates the string representation of this address.
toString() - Method in class javax.naming.Reference
Generates the string representation of this reference.
toString() - Method in class javax.net.ssl.SSLEngineResult
Returns a String representation of this object.
toString() - Method in class javax.print.attribute.DateTimeSyntax
Returns a string value corresponding to this date-time attribute.
toString() - Method in class javax.print.attribute.EnumSyntax
Returns a string value corresponding to this enumeration value.
toString() - Method in class javax.print.attribute.IntegerSyntax
Returns a string value corresponding to this integer attribute.
toString(int, String) - Method in class javax.print.attribute.ResolutionSyntax
Returns a string version of this resolution attribute in the given units.
toString() - Method in class javax.print.attribute.ResolutionSyntax
Returns a string version of this resolution attribute.
toString() - Method in class javax.print.attribute.SetOfIntegerSyntax
Returns a string value corresponding to this set-of-integer attribute.
toString(int, String) - Method in class javax.print.attribute.Size2DSyntax
Returns a string version of this two-dimensional size attribute in the given units.
toString() - Method in class javax.print.attribute.Size2DSyntax
Returns a string version of this two-dimensional size attribute.
toString(int, String) - Method in class javax.print.attribute.standard.MediaPrintableArea
Returns a string version of this rectangular size attribute in the given units.
toString() - Method in class javax.print.attribute.standard.MediaPrintableArea
Returns a string version of this rectangular size attribute in mm.
toString() - Method in class javax.print.attribute.TextSyntax
Returns a String identifying this text attribute.
toString() - Method in class javax.print.attribute.URISyntax
Returns a String identifying this URI attribute.
toString() - Method in class javax.print.DocFlavor
Converts this DocFlavor to a string.
toString() - Method in class javax.print.event.PrintEvent
toString() - Method in class javax.rmi.CORBA.Stub
Returns a string representation of this stub.
toString(Stub) - Method in interface javax.rmi.CORBA.StubDelegate
Delegation call for Stub.toString().
toString() - Method in class javax.security.auth.kerberos.KerberosKey
toString() - Method in class javax.security.auth.kerberos.KerberosPrincipal
toString() - Method in class javax.security.auth.kerberos.KerberosTicket
toString() - Method in class javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag
Return a String representation of this controlFlag.
toString() - Method in class javax.security.auth.Subject
Return the String representation of this Subject.
toString() - Method in class javax.security.auth.x500.X500Principal
Return a user-friendly string representation of this X500Principal.
toString() - Method in class javax.security.cert.Certificate
Returns a string representation of this certificate.
toString() - Method in exception javax.security.sasl.SaslException
Returns the string representation of this exception.
toString() - Method in class javax.sound.midi.MidiDevice.Info
Provides a string representation of the device information.
toString() - Method in class javax.sound.midi.Sequencer.SyncMode
Provides this synchronization mode's name as the string representation of the mode.
toString() - Method in class javax.sound.sampled.AudioFileFormat
Provides a string representation of the file format.
toString() - Method in class javax.sound.sampled.AudioFileFormat.Type
Provides the file type's name as the String representation of the file type.
toString() - Method in class javax.sound.sampled.AudioFormat.Encoding
Provides the String representation of the encoding.
toString() - Method in class javax.sound.sampled.AudioFormat
Returns a string that describes the format, such as: "PCM SIGNED 22050 Hz 16 bit mono big-endian".
toString() - Method in class javax.sound.sampled.BooleanControl
Provides a string representation of the control
toString() - Method in class javax.sound.sampled.CompoundControl
Provides a string representation of the control
toString() - Method in class javax.sound.sampled.Control
Obtains a String describing the control type and its current state.
toString() - Method in class javax.sound.sampled.Control.Type
Provides the String representation of the control type.
toString() - Method in class javax.sound.sampled.DataLine.Info
Obtains a textual description of the data line info.
toString() - Method in class javax.sound.sampled.EnumControl
Provides a string representation of the control.
toString() - Method in class javax.sound.sampled.FloatControl
Provides a string representation of the control
toString() - Method in class javax.sound.sampled.Line.Info
Obtains a textual description of the line info.
toString() - Method in class javax.sound.sampled.LineEvent
Obtains a string representation of the event.
toString() - Method in class javax.sound.sampled.LineEvent.Type
Returns the type name as the string representation.
toString() - Method in class javax.sound.sampled.Mixer.Info
Provides a string representation of the mixer info.
toString() - Method in class javax.sound.sampled.Port.Info
Provides a String representation of the port.
toString() - Method in class javax.sound.sampled.ReverbType
Provides a String representation of the reverb type, including its name and its parameter settings.
toString() - Method in class javax.swing.DefaultBoundedRangeModel
Returns a string that displays all of the BoundedRangeModel properties.
toString() - Method in class javax.swing.DefaultListModel
Returns a string that displays and identifies this object's properties.
toString() - Method in class javax.swing.DefaultListSelectionModel
Returns a string that displays and identifies this object's properties.
toString() - Method in class javax.swing.event.DocumentEvent.EventType
Converts the type to a string.
toString() - Method in class javax.swing.event.EventListenerList
Returns a string representation of the EventListenerList.
toString() - Method in class javax.swing.event.HyperlinkEvent.EventType
Converts the type to a string.
toString() - Method in class javax.swing.event.ListDataEvent
Returns a string representation of this ListDataEvent.
toString() - Method in class javax.swing.event.ListSelectionEvent
Returns a String that displays and identifies this object's properties.
toString() - Method in class javax.swing.event.TreeModelEvent
Returns a string that displays and identifies this object's properties.
toString() - Method in class javax.swing.filechooser.FileNameExtensionFilter
Returns a string representation of the FileNameExtensionFilter.
toString() - Method in class javax.swing.GroupLayout
Returns a string representation of this GroupLayout.
toString() - Method in class javax.swing.ImageIcon
Returns a string representation of this image.
toString() - Method in class javax.swing.JList.DropLocation
Returns a string representation of this drop location.
toString() - Method in class javax.swing.JTable.DropLocation
Returns a string representation of this drop location.
toString() - Method in class javax.swing.JTree.DropLocation
Returns a string representation of this drop location.
toString() - Method in class javax.swing.LookAndFeel
Returns a string that displays and identifies this object's properties.
toString() - Method in class javax.swing.plaf.nimbus.State
toString() - Method in class javax.swing.plaf.synth.ColorType
Returns the textual description of this ColorType.
toString() - Method in class javax.swing.plaf.synth.Region
Returns the name of the Region.
toString() - Method in class javax.swing.RepaintManager
Returns a string that displays and identifies this object's properties.
toString() - Method in class javax.swing.SizeRequirements
Returns a string describing the minimum, preferred, and maximum size requirements, along with the alignment.
toString(TableModel, int, int) - Method in class javax.swing.table.TableStringConverter
Returns the string representation of the value at the specified location.
toString() - Method in class javax.swing.text.AbstractDocument.BranchElement
Converts the element to a string.
toString() - Method in class javax.swing.text.AbstractDocument.DefaultDocumentEvent
Returns a string description of the change event.
toString() - Method in class javax.swing.text.AbstractDocument.LeafElement
Converts the element to a string.
toString() - Method in class javax.swing.text.DefaultCaret
toString() - Method in class javax.swing.text.DefaultStyledDocument.ElementSpec
Converts the element to a string.
toString() - Method in class javax.swing.text.html.CSS.Attribute
The string representation of the attribute.
toString() - Method in class javax.swing.text.html.HTML.Attribute
Returns the string representation of this attribute.
toString() - Method in class javax.swing.text.html.HTML.Tag
Returns the string representation of the tag.
toString() - Method in class javax.swing.text.html.Option
String representation is the label.
toString() - Method in class javax.swing.text.html.parser.AttributeList
toString() - Method in class javax.swing.text.html.parser.ContentModel
Convert to a string.
toString() - Method in class javax.swing.text.html.parser.DTD
Returns a string representation of this DTD.
toString() - Method in class javax.swing.text.html.parser.Element
Convert to a string.
toString() - Method in class javax.swing.text.JTextComponent.DropLocation
Returns a string representation of this drop location.
toString() - Method in class javax.swing.text.Position.Bias
string representation
toString() - Method in class javax.swing.text.Segment
Converts a segment into a String.
toString() - Method in class javax.swing.text.SimpleAttributeSet
Converts the attribute set to a String.
toString() - Method in class javax.swing.text.StyleConstants
Returns the string representation.
toString() - Method in class javax.swing.text.StyleContext.NamedStyle
Converts the style to a string.
toString() - Method in class javax.swing.text.StyleContext.SmallAttributeSet
Returns a string showing the key/value pairs
toString() - Method in class javax.swing.text.StyleContext
Converts a StyleContext to a String.
toString() - Method in class javax.swing.text.TabSet
Returns the string representation of the set of tabs.
toString() - Method in class javax.swing.text.TabStop
toString() - Method in class javax.swing.TransferHandler.DropLocation
Returns a string representation of this drop location.
toString() - Method in class javax.swing.tree.DefaultMutableTreeNode
Returns the result of sending toString() to this node's user object, or the empty string if the node has no user object.
toString() - Method in class javax.swing.tree.DefaultTreeSelectionModel
Returns a string that displays and identifies this object's properties.
toString() - Method in class javax.swing.tree.TreePath
Returns a string that displays and identifies this object's properties.
toString() - Method in class javax.swing.UIManager.LookAndFeelInfo
Returns a string that displays and identifies this object's properties.
toString() - Method in class javax.swing.undo.AbstractUndoableEdit
Returns a string that displays and identifies this object's properties.
toString() - Method in class javax.swing.undo.CompoundEdit
Returns a string that displays and identifies this object's properties.
toString() - Method in class javax.swing.undo.UndoableEditSupport
Returns a string that displays and identifies this object's properties.
toString() - Method in class javax.swing.undo.UndoManager
Returns a string that displays and identifies this object's properties.
toString() - Method in class javax.tools.SimpleJavaFileObject
toString() - Method in class javax.xml.bind.helpers.ValidationEventImpl
Returns a string representation of this object in a format helpful to debugging.
toString() - Method in class javax.xml.bind.helpers.ValidationEventLocatorImpl
Returns a string representation of this object in a format helpful to debugging.
toString() - Method in exception javax.xml.bind.JAXBException
Returns a short description of this JAXBException.
toString() - Method in exception javax.xml.bind.TypeConstraintException
Returns a short description of this TypeConstraintException.
toString() - Method in class javax.xml.crypto.dsig.spec.XPathType.Filter
Returns the string form of the operation.
toString() - Method in class javax.xml.crypto.KeySelector.Purpose
Returns a string representation of this purpose ("sign", "verify", "encrypt", or "decrypt").
toString() - Method in class javax.xml.datatype.DatatypeConstants.Field
Returns a field name in English.
toString() - Method in class javax.xml.datatype.Duration
Returns a String representation of this Duration Object.
toString() - Method in class javax.xml.datatype.XMLGregorianCalendar
Returns a String representation of this XMLGregorianCalendar Object.
toString() - Method in class javax.xml.namespace.QName
String representation of this QName.
toString() - Method in class javax.xml.ws.EndpointReference
Displays EPR infoset for debugging convenience.
toString() - Method in exception org.ietf.jgss.GSSException
Returns a textual representation of both the major and the minor status codes.
toString() - Method in interface org.ietf.jgss.GSSName
Returns a textual representation of the GSSName object.
toString() - Method in class org.ietf.jgss.Oid
Returns a string representation of the oid's integer components in dot separated notation.
toString(Object) - Method in class org.omg.CORBA.portable.Delegate
Provides the implementation to override the toString() method of the delegating CORBA object.
toString() - Method in class org.omg.CORBA.portable.ObjectImpl
Returns a String object that represents this ObjectImpl object.
toString() - Method in exception org.omg.CORBA.SystemException
Converts this exception to a representative string.
toString() - Method in exception org.xml.sax.SAXException
Override toString to pick up any embedded exception.
toString() - Method in exception org.xml.sax.SAXParseException
Override toString to provide more detailed error message.
toStub(Remote) - Static method in class java.rmi.server.RemoteObject
Returns the stub for the remote object obj passed as a parameter.
toStub() - Method in class javax.management.remote.rmi.RMIIIOPServerImpl
Returns an IIOP stub.
toStub() - Method in class javax.management.remote.rmi.RMIJRMPServerImpl
Returns a serializable stub for this RMIServer object.
toStub() - Method in class javax.management.remote.rmi.RMIServerImpl
Returns a remotable stub for this server object.
toStub(Remote) - Method in interface javax.rmi.CORBA.PortableRemoteObjectDelegate
Delegation call for PortableRemoteObject.toStub(java.rmi.Remote).
toStub(Remote) - Static method in class javax.rmi.PortableRemoteObject
Returns a stub for the given server object.
totalChildIndent - Variable in class javax.swing.plaf.basic.BasicTreeUI
Total distance that will be indented.
totalColumnWidth - Variable in class javax.swing.table.DefaultTableColumnModel
A local cache of the combined width of all columns
totalMemory() - Method in class java.lang.Runtime
Returns the total amount of memory in the Java virtual machine.
toTitleCase(char) - Static method in class java.lang.Character
Converts the character argument to titlecase using case mapping information from the UnicodeData file.
toTitleCase(int) - Static method in class java.lang.Character
Converts the character (Unicode code point) argument to titlecase using case mapping information from the UnicodeData file.
TOTOP_TOLEFT - Static variable in class javax.print.attribute.standard.PresentationDirection
Pages are laid out in columns starting at the bottom right, proceeeding towards the top & left.
TOTOP_TORIGHT - Static variable in class javax.print.attribute.standard.PresentationDirection
Pages are laid out in columns starting at the bottom left, proceeeding towards the top & right.
toUnicode(String, int) - Static method in class java.net.IDN
Translates a string from ASCII Compatible Encoding (ACE) to Unicode, as defined by the ToUnicode operation of RFC 3490.
toUnicode(String) - Static method in class java.net.IDN
Translates a string from ASCII Compatible Encoding (ACE) to Unicode, as defined by the ToUnicode operation of RFC 3490.
toUpperCase(char) - Static method in class java.lang.Character
Converts the character argument to uppercase using case mapping information from the UnicodeData file.
toUpperCase(int) - Static method in class java.lang.Character
Converts the character (Unicode code point) argument to uppercase using case mapping information from the UnicodeData file.
toUpperCase(Locale) - Method in class java.lang.String
Converts all of the characters in this String to upper case using the rules of the given Locale.
toUpperCase() - Method in class java.lang.String
Converts all of the characters in this String to upper case using the rules of the default locale.
toURI() - Method in class java.io.File
Constructs a file: URI that represents this abstract pathname.
toURI() - Method in class java.net.URL
Returns a URI equivalent to this URL.
toUri() - Method in interface java.nio.file.Path
Returns a URI to represent this path.
toUri() - Method in interface javax.tools.FileObject
Returns a URI identifying this file object.
toUri() - Method in class javax.tools.ForwardingFileObject
toUri() - Method in class javax.tools.SimpleJavaFileObject
toURL() - Method in class java.io.File
Deprecated.
This method does not automatically escape characters that are illegal in URLs. It is recommended that new code convert an abstract pathname into a URL by first converting it into a URI, via the toURI method, and then converting the URI into a URL via the URI.toURL method.
toURL() - Method in class java.net.URI
Constructs a URL from this URI.
toViewCoordinates(Dimension) - Method in class javax.swing.JViewport
Converts a size in pixel coordinates to view coordinates.
toViewCoordinates(Point) - Method in class javax.swing.JViewport
Converts a point in pixel coordinates to view coordinates.
toXMLFormat() - Method in class javax.xml.datatype.XMLGregorianCalendar
Return the lexical representation of this instance.
toXMLString() - Method in class javax.management.modelmbean.DescriptorSupport
Returns an XML String representing the descriptor.
TR - Static variable in class javax.swing.text.html.HTML.Tag
traceInstructions(boolean) - Method in class java.lang.Runtime
Enables/Disables tracing of instructions.
traceMethodCalls(boolean) - Method in class java.lang.Runtime
Enables/Disables tracing of method calls.
TRACK - Static variable in class java.awt.event.AdjustmentEvent
The absolute tracking adjustment type.
Track - Class in javax.sound.midi
A MIDI track is an independent stream of MIDI events (time-stamped MIDI data) that can be stored along with other tracks in a standard MIDI file.
trackBuffer - Variable in class javax.swing.plaf.basic.BasicSliderUI
trackColor - Variable in class javax.swing.plaf.basic.BasicScrollBarUI
tracker - Static variable in class javax.swing.ImageIcon
trackHighlight - Variable in class javax.swing.plaf.basic.BasicScrollBarUI
trackHighlightColor - Variable in class javax.swing.plaf.basic.BasicScrollBarUI
TRACKING - Static variable in class java.awt.font.TextAttribute
Attribute key to control tracking.
TRACKING_LOOSE - Static variable in class java.awt.font.TextAttribute
Perform loose tracking.
TRACKING_TIGHT - Static variable in class java.awt.font.TextAttribute
Perform tight tracking.
trackListener - Variable in class javax.swing.plaf.basic.BasicScrollBarUI
trackListener - Variable in class javax.swing.plaf.basic.BasicSliderUI
trackRect - Variable in class javax.swing.plaf.basic.BasicScrollBarUI
trackRect - Variable in class javax.swing.plaf.basic.BasicSliderUI
tracks - Variable in class javax.sound.midi.Sequence
The MIDI tracks in this sequence.
trackWidth - Static variable in class javax.swing.plaf.metal.MetalSliderUI
TRADITIONAL_CHINESE - Static variable in class java.util.Locale
Useful constant for language.
TRADITIONAL_HANZI - Static variable in class java.awt.im.InputSubset
Constant for all Han characters used in writing Traditional Chinese, including a subset of the CJK unified ideographs as well as Traditional Chinese Han characters that may be defined as surrogate characters.
TRAILING - Static variable in class java.awt.FlowLayout
This value indicates that each row of components should be justified to the trailing edge of the container's orientation, for example, to the right in left-to-right orientations.
trailing(int) - Static method in class java.awt.font.TextHitInfo
Creates a hit on the trailing edge of the character at the specified charIndex.
TRAILING - Static variable in class javax.swing.border.TitledBorder
Position title text at the right side of the border line for left to right orientation, at the left side of the border line for right to left orientation.
TRAILING - Static variable in interface javax.swing.SwingConstants
Identifies the trailing edge of text for use with left-to-right and right-to-left languages.
TRANSACTION_MODE - Exception in org.omg.CORBA
The CORBA TRANSACTION_MODE exception is thrown by the client ORB if it detects a mismatch between the InvocationPolicy in the IOR and the chosen invocation path (i.e, direct or routed invocation).
TRANSACTION_MODE() - Constructor for exception org.omg.CORBA.TRANSACTION_MODE
Constructs a TRANSACTION_MODE exception with a default minor code of 0, a completion state of CompletionStatus.COMPLETED_NO, and a null description.
TRANSACTION_MODE(String) - Constructor for exception org.omg.CORBA.TRANSACTION_MODE
Constructs a TRANSACTION_MODE exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.
TRANSACTION_MODE(int, CompletionStatus) - Constructor for exception org.omg.CORBA.TRANSACTION_MODE
Constructs a TRANSACTION_MODE exception with the specified minor code and completion status.
TRANSACTION_MODE(String, int, CompletionStatus) - Constructor for exception org.omg.CORBA.TRANSACTION_MODE
Constructs a TRANSACTION_MODE exception with the specified description message, minor code, and completion status.
TRANSACTION_NONE - Static variable in interface java.sql.Connection
A constant indicating that transactions are not supported.
TRANSACTION_READ_COMMITTED - Static variable in interface java.sql.Connection
A constant indicating that dirty reads are prevented; non-repeatable reads and phantom reads can occur.
TRANSACTION_READ_UNCOMMITTED - Static variable in interface java.sql.Connection
A constant indicating that dirty reads, non-repeatable reads and phantom reads can occur.
TRANSACTION_REPEATABLE_READ - Static variable in interface java.sql.Connection
A constant indicating that dirty reads and non-repeatable reads are prevented; phantom reads can occur.
TRANSACTION_REQUIRED - Exception in org.omg.CORBA
Exception indicates that the request carried a null transaction context, but an active transaction is required.
TRANSACTION_REQUIRED() - Constructor for exception org.omg.CORBA.TRANSACTION_REQUIRED
Constructs a TRANSACTION_REQUIRED exception with a default minor code of 0, a completion state of CompletionStatus.COMPLETED_NO, and a null description.
TRANSACTION_REQUIRED(String) - Constructor for exception org.omg.CORBA.TRANSACTION_REQUIRED
Constructs a TRANSACTION_REQUIRED exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.
TRANSACTION_REQUIRED(int, CompletionStatus) - Constructor for exception org.omg.CORBA.TRANSACTION_REQUIRED
Constructs a TRANSACTION_REQUIRED exception with the specified minor code and completion status.
TRANSACTION_REQUIRED(String, int, CompletionStatus) - Constructor for exception org.omg.CORBA.TRANSACTION_REQUIRED
Constructs a TRANSACTION_REQUIRED exception with the specified description message, minor code, and completion status.
TRANSACTION_ROLLEDBACK - Exception in org.omg.CORBA
Exception thrown when the transaction associated with the request has already been rolled back or marked to roll back.
TRANSACTION_ROLLEDBACK() - Constructor for exception org.omg.CORBA.TRANSACTION_ROLLEDBACK
Constructs a TRANSACTION_ROLLEDBACK exception with a default minor code of 0, a completion state of CompletionStatus.COMPLETED_NO, and a null description.
TRANSACTION_ROLLEDBACK(String) - Constructor for exception org.omg.CORBA.TRANSACTION_ROLLEDBACK
Constructs a TRANSACTION_ROLLEDBACK exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.
TRANSACTION_ROLLEDBACK(int, CompletionStatus) - Constructor for exception org.omg.CORBA.TRANSACTION_ROLLEDBACK
Constructs a TRANSACTION_ROLLEDBACK exception with the specified minor code and completion status.
TRANSACTION_ROLLEDBACK(String, int, CompletionStatus) - Constructor for exception org.omg.CORBA.TRANSACTION_ROLLEDBACK
Constructs a TRANSACTION_ROLLEDBACK exception with the specified description message, minor code, and completion status.
TRANSACTION_SERIALIZABLE - Static variable in interface java.sql.Connection
A constant indicating that dirty reads, non-repeatable reads and phantom reads are prevented.
TRANSACTION_UNAVAILABLE - Exception in org.omg.CORBA
The CORBA TRANSACTION_UNAVAILABLE exception is thrown by the ORB when it cannot process a transaction service context because its connection to the Transaction Service has been abnormally terminated.
TRANSACTION_UNAVAILABLE() - Constructor for exception org.omg.CORBA.TRANSACTION_UNAVAILABLE
Constructs a TRANSACTION_UNAVAILABLE exception with a default minor code of 0, a completion state of CompletionStatus.COMPLETED_NO, and a null description.
TRANSACTION_UNAVAILABLE(String) - Constructor for exception org.omg.CORBA.TRANSACTION_UNAVAILABLE
Constructs a TRANSACTION_UNAVAILABLE exception with the specifieddescription message, a minor code of 0, and a completion state of COMPLETED_NO.
TRANSACTION_UNAVAILABLE(int, CompletionStatus) - Constructor for exception org.omg.CORBA.TRANSACTION_UNAVAILABLE
Constructs a TRANSACTION_UNAVAILABLE exception with the specified minor code and completion status.
TRANSACTION_UNAVAILABLE(String, int, CompletionStatus) - Constructor for exception org.omg.CORBA.TRANSACTION_UNAVAILABLE
Constructs a TRANSACTION_UNAVAILABLE exception with the specified description message, minor code, and completion status.
TransactionalWriter - Interface in javax.sql.rowset.spi
A specialized interface that facilitates an extension of the standard SyncProvider abstract class so that it has finer grained transaction control.
TransactionRequiredException - Exception in javax.transaction
This exception indicates that a request carried a null transaction context, but the target object requires an activate transaction.
TransactionRequiredException() - Constructor for exception javax.transaction.TransactionRequiredException
TransactionRequiredException(String) - Constructor for exception javax.transaction.TransactionRequiredException
TransactionRolledbackException - Exception in javax.transaction
This exception indicates that the transaction associated with processing of the request has been rolled back, or marked to roll back.
TransactionRolledbackException() - Constructor for exception javax.transaction.TransactionRolledbackException
TransactionRolledbackException(String) - Constructor for exception javax.transaction.TransactionRolledbackException
TransactionService - Interface in org.omg.IOP
org/omg/IOP/TransactionService.java .
transfer(E) - Method in class java.util.concurrent.LinkedTransferQueue
Transfers the element to a consumer, waiting if necessary to do so.
transfer(E) - Method in interface java.util.concurrent.TransferQueue
Transfers the element to a consumer, waiting if necessary to do so.
Transferable - Interface in java.awt.datatransfer
Defines the interface for classes that can be used to provide data for a transfer operation.
transferable - Variable in class java.awt.dnd.DropTargetContext.TransferableProxy
The encapsulated Transferable object.
transferablesFlavorsChanged() - Method in class java.awt.dnd.DragSourceContext
Notifies the peer that the Transferable's DataFlavors have changed.
transferFocus() - Method in class java.awt.Component
Transfers the focus to the next component, as though this Component were the focus owner.
transferFocusBackward() - Method in class java.awt.Component
Transfers the focus to the previous component, as though this Component were the focus owner.
transferFocusDownCycle() - Method in class java.awt.Container
Transfers the focus down one focus traversal cycle.
transferFocusUpCycle() - Method in class java.awt.Component
Transfers the focus up one focus traversal cycle.
transferFrom(ReadableByteChannel, long, long) - Method in class java.nio.channels.FileChannel
Transfers bytes into this channel's file from the given readable byte channel.
TransferHandler - Class in javax.swing
This class is used to handle the transfer of a Transferable to and from Swing components.
TransferHandler(String) - Constructor for class javax.swing.TransferHandler
Constructs a transfer handler that can transfer a Java Bean property from one component to another via the clipboard or a drag and drop operation.
TransferHandler() - Constructor for class javax.swing.TransferHandler
Convenience constructor for subclasses.
TransferHandler.DropLocation - Class in javax.swing
Represents a location where dropped data should be inserted.
TransferHandler.DropLocation(Point) - Constructor for class javax.swing.TransferHandler.DropLocation
Constructs a drop location for the given point.
TransferHandler.TransferSupport - Class in javax.swing
This class encapsulates all relevant details of a clipboard or drag and drop transfer, and also allows for customizing aspects of the drag and drop experience.
TransferHandler.TransferSupport(Component, Transferable) - Constructor for class javax.swing.TransferHandler.TransferSupport
Create a TransferSupport with isDrop() false for the given component and Transferable.
TransferQueue<E> - Interface in java.util.concurrent
A BlockingQueue in which producers may wait for consumers to receive elements.
transferTo(long, long, WritableByteChannel) - Method in class java.nio.channels.FileChannel
Transfers bytes from this channel's file to the given writable byte channel.
transferType - Variable in class java.awt.image.ColorModel
Data type of the array used to represent pixel values.
TRANSFORM - Static variable in class java.awt.font.TextAttribute
Attribute key for the transform of a font.
transform(Point2D, Point2D) - Method in class java.awt.geom.AffineTransform
Transforms the specified ptSrc and stores the result in ptDst.
transform(Point2D[], int, Point2D[], int, int) - Method in class java.awt.geom.AffineTransform
Transforms an array of point objects by this transform.
transform(float[], int, float[], int, int) - Method in class java.awt.geom.AffineTransform
Transforms an array of floating point coordinates by this transform.
transform(double[], int, double[], int, int) - Method in class java.awt.geom.AffineTransform
Transforms an array of double precision coordinates by this transform.
transform(float[], int, double[], int, int) - Method in class java.awt.geom.AffineTransform
Transforms an array of floating point coordinates by this transform and stores the results into an array of doubles.
transform(double[], int, float[], int, int) - Method in class java.awt.geom.AffineTransform
Transforms an array of double precision coordinates by this transform and stores the results into an array of floats.
transform(AffineTransform) - Method in class java.awt.geom.Area
Transforms the geometry of this Area using the specified AffineTransform.
transform(AffineTransform) - Method in class java.awt.geom.Path2D.Double
Transforms the geometry of this path using the specified AffineTransform.
transform(AffineTransform) - Method in class java.awt.geom.Path2D.Float
Transforms the geometry of this path using the specified AffineTransform.
transform(AffineTransform) - Method in class java.awt.geom.Path2D
Transforms the geometry of this path using the specified AffineTransform.
transform(AffineTransform) - Method in class java.awt.Graphics2D
Composes an AffineTransform object with the Transform in this Graphics2D according to the rule last-specified-first-applied.
transform(ClassLoader, String, Class<?>, ProtectionDomain, byte[]) - Method in interface java.lang.instrument.ClassFileTransformer
The implementation of this method may transform the supplied class file and return a new replacement class file.
Transform - Interface in javax.xml.crypto.dsig
A representation of the XML Transform element as defined in the W3C Recommendation for XML-Signature Syntax and Processing.
transform(Data, XMLCryptoContext) - Method in interface javax.xml.crypto.dsig.Transform
Transforms the specified data using the underlying transform algorithm.
transform(Data, XMLCryptoContext, OutputStream) - Method in interface javax.xml.crypto.dsig.Transform
Transforms the specified data using the underlying transform algorithm.
transform(Source, Result) - Method in class javax.xml.transform.Transformer
Transform the XML Source to a Result.
TransformAttribute - Class in java.awt.font
The TransformAttribute class provides an immutable wrapper for a transform so that it is safe to use as an attribute.
TransformAttribute(AffineTransform) - Constructor for class java.awt.font.TransformAttribute
Wraps the specified transform.
Transformer - Class in javax.xml.transform
An instance of this abstract class can transform a source tree into a result tree.
Transformer() - Constructor for class javax.xml.transform.Transformer
Default constructor is protected on purpose.
TransformerConfigurationException - Exception in javax.xml.transform
Indicates a serious configuration error.
TransformerConfigurationException() - Constructor for exception javax.xml.transform.TransformerConfigurationException
Create a new TransformerConfigurationException with no detail mesage.
TransformerConfigurationException(String) - Constructor for exception javax.xml.transform.TransformerConfigurationException
Create a new TransformerConfigurationException with the String specified as an error message.
TransformerConfigurationException(Throwable) - Constructor for exception javax.xml.transform.TransformerConfigurationException
Create a new TransformerConfigurationException with a given Exception base cause of the error.
TransformerConfigurationException(String, Throwable) - Constructor for exception javax.xml.transform.TransformerConfigurationException
Create a new TransformerConfigurationException with the given Exception base cause and detail message.
TransformerConfigurationException(String, SourceLocator) - Constructor for exception javax.xml.transform.TransformerConfigurationException
Create a new TransformerConfigurationException from a message and a Locator.
TransformerConfigurationException(String, SourceLocator, Throwable) - Constructor for exception javax.xml.transform.TransformerConfigurationException
Wrap an existing exception in a TransformerConfigurationException.
TransformerException - Exception in javax.xml.transform
This class specifies an exceptional condition that occured during the transformation process.
TransformerException(String) - Constructor for exception javax.xml.transform.TransformerException
Create a new TransformerException.
TransformerException(Throwable) - Constructor for exception javax.xml.transform.TransformerException
Create a new TransformerException wrapping an existing exception.
TransformerException(String, Throwable) - Constructor for exception javax.xml.transform.TransformerException
Wrap an existing exception in a TransformerException.
TransformerException(String, SourceLocator) - Constructor for exception javax.xml.transform.TransformerException
Create a new TransformerException from a message and a Locator.
TransformerException(String, SourceLocator, Throwable) - Constructor for exception javax.xml.transform.TransformerException
Wrap an existing exception in a TransformerException.
TransformerFactory - Class in javax.xml.transform
A TransformerFactory instance can be used to create Transformer and Templates objects.
TransformerFactory() - Constructor for class javax.xml.transform.TransformerFactory
Default constructor is protected on purpose.
TransformerFactoryConfigurationError - Error in javax.xml.transform
Thrown when a problem with configuration with the Transformer Factories exists.
TransformerFactoryConfigurationError() - Constructor for error javax.xml.transform.TransformerFactoryConfigurationError
Create a new TransformerFactoryConfigurationError with no detail mesage.
TransformerFactoryConfigurationError(String) - Constructor for error javax.xml.transform.TransformerFactoryConfigurationError
Create a new TransformerFactoryConfigurationError with the String specified as an error message.
TransformerFactoryConfigurationError(Exception) - Constructor for error javax.xml.transform.TransformerFactoryConfigurationError
Create a new TransformerFactoryConfigurationError with a given Exception base cause of the error.
TransformerFactoryConfigurationError(Exception, String) - Constructor for error javax.xml.transform.TransformerFactoryConfigurationError
Create a new TransformerFactoryConfigurationError with the given Exception base cause and detail message.
TransformerHandler - Interface in javax.xml.transform.sax
A TransformerHandler listens for SAX ContentHandler parse events and transforms them to a Result.
TransformException - Exception in javax.xml.crypto.dsig
Indicates an exceptional condition that occured while executing a transform algorithm.
TransformException() - Constructor for exception javax.xml.crypto.dsig.TransformException
Constructs a new TransformException with null as its detail message.
TransformException(String) - Constructor for exception javax.xml.crypto.dsig.TransformException
Constructs a new TransformException with the specified detail message.
TransformException(String, Throwable) - Constructor for exception javax.xml.crypto.dsig.TransformException
Constructs a new TransformException with the specified detail message and cause.
TransformException(Throwable) - Constructor for exception javax.xml.crypto.dsig.TransformException
Constructs a new TransformException with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).
TransformParameterSpec - Interface in javax.xml.crypto.dsig.spec
A specification of algorithm parameters for a Transform algorithm.
TransformService - Class in javax.xml.crypto.dsig
A Service Provider Interface for transform and canonicalization algorithms.
TransformService() - Constructor for class javax.xml.crypto.dsig.TransformService
Default constructor, for invocation by subclasses.
Transient - Annotation Type in java.beans
Indicates that an attribute called "transient" should be declared with the given value when the Introspector constructs a PropertyDescriptor or EventSetDescriptor classes associated with the annotated code element.
TRANSIENT - Static variable in class java.lang.reflect.修饰符
The int value representing the transient modifier.
TRANSIENT - Static variable in class javax.accessibility.AccessibleState
Indicates this object is transient.
TRANSIENT - Exception in org.omg.CORBA
Exception thrown when the ORB attempted to reach an object and failed.
TRANSIENT() - Constructor for exception org.omg.CORBA.TRANSIENT
Constructs a TRANSIENT exception with a default minor code of 0, a completion state of CompletionStatus.COMPLETED_NO, and a null description.
TRANSIENT(String) - Constructor for exception org.omg.CORBA.TRANSIENT
Constructs a TRANSIENT exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.
TRANSIENT(int, CompletionStatus) - Constructor for exception org.omg.CORBA.TRANSIENT
Constructs a TRANSIENT exception with the specified minor code and completion status.
TRANSIENT(String, int, CompletionStatus) - Constructor for exception org.omg.CORBA.TRANSIENT
Constructs a TRANSIENT exception with the specified description message, minor code, and completion status.
TRANSIENT - Static variable in class org.omg.PortableServer.LifespanPolicyValue
translate(int, int) - Method in class java.awt.Event
NOTE: The Event class is obsolete and is available only for backwards compatilibility.
translate(double, double) - Method in class java.awt.geom.AffineTransform
Concatenates this transform with a translation transformation.
translate(int, int) - Method in class java.awt.Graphics
Translates the origin of the graphics context to the point (x, y) in the current coordinate system.
translate(int, int) - Method in class java.awt.Graphics2D
Translates the origin of the Graphics2D context to the point (x, y) in the current coordinate system.
translate(double, double) - Method in class java.awt.Graphics2D
Concatenates the current Graphics2D Transform with a translation transform.
translate(int, int) - Method in class java.awt.Point
Translates this point, at location (x,y), by dx along the x axis and dy along the y axis so that it now represents the point (x+dx,y+dy).
translate(int, int) - Method in class java.awt.Polygon
Translates the vertices of the Polygon by deltaX along the x axis and by deltaY along the y axis.
translate(int, int) - Method in class java.awt.Rectangle
Translates this Rectangle the indicated distance, to the right along the X coordinate axis, and downward along the Y coordinate axis.
translate(int, int) - Method in class javax.swing.DebugGraphics
Overrides Graphics.translate.
translateHTMLToCSS(AttributeSet) - Method in class javax.swing.text.html.StyleSheet
Converts a set of HTML attributes to an equivalent set of CSS attributes.
translateKey(Key) - Method in class java.security.KeyFactory
Translates a key object, whose provider may be unknown or potentially untrusted, into a corresponding key object of this key factory.
translateKey(SecretKey) - Method in class javax.crypto.SecretKeyFactory
Translates a key object, whose provider may be unknown or potentially untrusted, into a corresponding key object of this secret-key factory.
translatePoint(int, int) - Method in class java.awt.event.MouseEvent
Translates the event's coordinates to a new position by adding specified x (horizontal) and y (vertical) offsets.
TRANSLUCENT - Static variable in interface java.awt.Transparency
Represents image data that contains or might contain arbitrary alpha values between and including 0.0 and 1.0.
Transmitter - Interface in javax.sound.midi
A Transmitter sends MidiEvent objects to one or more Receivers.
transparency - Variable in class java.awt.image.VolatileImage
The transparency value with which this image was created.
Transparency - Interface in java.awt
The Transparency interface defines the common transparency modes for implementing classes.
TRANSPORT_AND_MAP_SYMBOLS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Transport And Map Symbols" Unicode character block.
TRANSPORT_RETRY - Interface in org.omg.PortableInterceptor
org/omg/PortableInterceptor/TRANSPORT_RETRY.java .
TrayIcon - Class in java.awt
A TrayIcon object represents a tray icon that can be added to the system tray.
TrayIcon(Image) - Constructor for class java.awt.TrayIcon
Creates a TrayIcon with the specified image.
TrayIcon(Image, String) - Constructor for class java.awt.TrayIcon
Creates a TrayIcon with the specified image and tooltip text.
TrayIcon(Image, String, PopupMenu) - Constructor for class java.awt.TrayIcon
Creates a TrayIcon with the specified image, tooltip and popup menu.
TrayIcon.MessageType - Enum in java.awt
The message type determines which icon will be displayed in the caption of the message, and a possible system sound a message may generate upon showing.
TREE - Static variable in class javax.accessibility.AccessibleRole
An object used to present hierarchical information to the user.
tree - Variable in class javax.swing.plaf.basic.BasicTreeUI
Component that we're going to be drawing into.
TREE - Static variable in class javax.swing.plaf.synth.Region
Tree region.
tree - Variable in class javax.swing.tree.DefaultTreeCellEditor
JTree instance listening too.
TREE_CELL - Static variable in class javax.swing.plaf.synth.Region
Region of the Tree for one cell.
TREE_MODEL_PROPERTY - Static variable in class javax.swing.JTree
Bound property name for treeModel.
TreeCellEditor - Interface in javax.swing.tree
Adds to CellEditor the extensions necessary to configure an editor in a tree.
TreeCellRenderer - Interface in javax.swing.tree
Defines the requirements for an object that displays a tree node.
treeCollapsed(TreeExpansionEvent) - Method in interface javax.swing.event.TreeExpansionListener
Called whenever an item in the tree has been collapsed.
treeCollapsed(TreeExpansionEvent) - Method in class javax.swing.JTree.AccessibleJTree
Tree Collapsed notification.
treeCollapsed(TreeExpansionEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI.TreeExpansionHandler
Called whenever an item in the tree has been collapsed.
treeDidChange() - Method in class javax.swing.JTree
Sent when the tree has changed enough that we need to resize the bounds, but not enough that we need to remove the expanded node set (e.g nodes were expanded or collapsed, or nodes were inserted into the tree).
treeExpanded(TreeExpansionEvent) - Method in interface javax.swing.event.TreeExpansionListener
Called whenever an item in the tree has been expanded.
treeExpanded(TreeExpansionEvent) - Method in class javax.swing.JTree.AccessibleJTree
Tree Model Expansion notification.
treeExpanded(TreeExpansionEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI.TreeExpansionHandler
Called whenever an item in the tree has been expanded.
TreeExpansionEvent - Class in javax.swing.event
An event used to identify a single path in a tree.
TreeExpansionEvent(Object, TreePath) - Constructor for class javax.swing.event.TreeExpansionEvent
Constructs a TreeExpansionEvent object.
TreeExpansionListener - Interface in javax.swing.event
The listener that's notified when a tree expands or collapses a node.
TreeMap<K,V> - Class in java.util
A Red-Black tree based NavigableMap implementation.
TreeMap() - Constructor for class java.util.TreeMap
Constructs a new, empty tree map, using the natural ordering of its keys.
TreeMap(Comparator<? super K>) - Constructor for class java.util.TreeMap
Constructs a new, empty tree map, ordered according to the given comparator.
TreeMap(Map<? extends K, ? extends V>) - Constructor for class java.util.TreeMap
Constructs a new tree map containing the same mappings as the given map, ordered according to the natural ordering of its keys.
TreeMap(SortedMap<K, ? extends V>) - Constructor for class java.util.TreeMap
Constructs a new tree map containing the same mappings and using the same ordering as the specified sorted map.
treeModel - Variable in class javax.swing.JTree
The model that defines the tree displayed by this object.
treeModel - Variable in class javax.swing.plaf.basic.BasicTreeUI
Used to determine what to display.
treeModel - Variable in class javax.swing.tree.AbstractLayoutCache
Model providing information.
TreeModel - Interface in javax.swing.tree
The model used by JTree.
TreeModelEvent - Class in javax.swing.event
Encapsulates information describing changes to a tree model, and used to notify tree model listeners of the change.
TreeModelEvent(Object, Object[], int[], Object[]) - Constructor for class javax.swing.event.TreeModelEvent
Used to create an event when nodes have been changed, inserted, or removed, identifying the path to the parent of the modified items as an array of Objects.
TreeModelEvent(Object, TreePath, int[], Object[]) - Constructor for class javax.swing.event.TreeModelEvent
Used to create an event when nodes have been changed, inserted, or removed, identifying the path to the parent of the modified items as a TreePath object.
TreeModelEvent(Object, Object[]) - Constructor for class javax.swing.event.TreeModelEvent
Used to create an event when the node structure has changed in some way, identifying the path to the root of a modified subtree as an array of Objects.
TreeModelEvent(Object, TreePath) - Constructor for class javax.swing.event.TreeModelEvent
Used to create an event when the node structure has changed in some way, identifying the path to the root of the modified subtree as a TreePath object.
TreeModelListener - Interface in javax.swing.event
Defines the interface for an object that listens to changes in a TreeModel.
treeModelListener - Variable in class javax.swing.JTree
Updates the expandedState.
TreeNode - Interface in javax.swing.tree
Defines the requirements for an object that can be used as a tree node in a JTree.
treeNodesChanged(TreeModelEvent) - Method in interface javax.swing.event.TreeModelListener
Invoked after a node (or a set of siblings) has changed in some way.
treeNodesChanged(TreeModelEvent) - Method in class javax.swing.JTree.AccessibleJTree
Tree Model Node change notification.
treeNodesChanged(TreeModelEvent) - Method in class javax.swing.JTree.TreeModelHandler
treeNodesChanged(TreeModelEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI.TreeModelHandler
treeNodesChanged(TreeModelEvent) - Method in class javax.swing.tree.AbstractLayoutCache
Invoked after a node (or a set of siblings) has changed in some way.
treeNodesChanged(TreeModelEvent) - Method in class javax.swing.tree.FixedHeightLayoutCache
Invoked after a node (or a set of siblings) has changed in some way.
treeNodesChanged(TreeModelEvent) - Method in class javax.swing.tree.VariableHeightLayoutCache
Invoked after a node (or a set of siblings) has changed in some way.
treeNodesInserted(TreeModelEvent) - Method in interface javax.swing.event.TreeModelListener
Invoked after nodes have been inserted into the tree.
treeNodesInserted(TreeModelEvent) - Method in class javax.swing.JTree.AccessibleJTree
Tree Model Node change notification.
treeNodesInserted(TreeModelEvent) - Method in class javax.swing.JTree.TreeModelHandler
treeNodesInserted(TreeModelEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI.TreeModelHandler
treeNodesInserted(TreeModelEvent) - Method in class javax.swing.tree.AbstractLayoutCache
Invoked after nodes have been inserted into the tree.
treeNodesInserted(TreeModelEvent) - Method in class javax.swing.tree.FixedHeightLayoutCache
Invoked after nodes have been inserted into the tree.
treeNodesInserted(TreeModelEvent) - Method in class javax.swing.tree.VariableHeightLayoutCache
Invoked after nodes have been inserted into the tree.
treeNodesRemoved(TreeModelEvent) - Method in interface javax.swing.event.TreeModelListener
Invoked after nodes have been removed from the tree.
treeNodesRemoved(TreeModelEvent) - Method in class javax.swing.JTree.AccessibleJTree
Tree Model Node change notification.
treeNodesRemoved(TreeModelEvent) - Method in class javax.swing.JTree.TreeModelHandler
treeNodesRemoved(TreeModelEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI.TreeModelHandler
treeNodesRemoved(TreeModelEvent) - Method in class javax.swing.tree.AbstractLayoutCache
Invoked after nodes have been removed from the tree.
treeNodesRemoved(TreeModelEvent) - Method in class javax.swing.tree.FixedHeightLayoutCache
Invoked after nodes have been removed from the tree.
treeNodesRemoved(TreeModelEvent) - Method in class javax.swing.tree.VariableHeightLayoutCache
Invoked after nodes have been removed from the tree.
TreePath - Class in javax.swing.tree
TreePath represents an array of objects that uniquely identify the path to a node in a tree.
TreePath(Object[]) - Constructor for class javax.swing.tree.TreePath
Creates a TreePath from an array.
TreePath(Object) - Constructor for class javax.swing.tree.TreePath
Creates a TreePath containing a single element.
TreePath(TreePath, Object) - Constructor for class javax.swing.tree.TreePath
Creates a TreePath with the specified parent and element.
TreePath(Object[], int) - Constructor for class javax.swing.tree.TreePath
Creates a TreePath from an array.
TreePath() - Constructor for class javax.swing.tree.TreePath
Creates an empty TreePath.
TreeSelectionEvent - Class in javax.swing.event
An event that characterizes a change in the current selection.
TreeSelectionEvent(Object, TreePath[], boolean[], TreePath, TreePath) - Constructor for class javax.swing.event.TreeSelectionEvent
Represents a change in the selection of a TreeSelectionModel.
TreeSelectionEvent(Object, TreePath, boolean, TreePath, TreePath) - Constructor for class javax.swing.event.TreeSelectionEvent
Represents a change in the selection of a TreeSelectionModel.
TreeSelectionListener - Interface in javax.swing.event
The listener that's notified when the selection in a TreeSelectionModel changes.
treeSelectionModel - Variable in class javax.swing.plaf.basic.BasicTreeUI
Model maintaing the selection.
treeSelectionModel - Variable in class javax.swing.tree.AbstractLayoutCache
Selection model.
TreeSelectionModel - Interface in javax.swing.tree
This interface represents the current state of the selection for the tree component.
TreeSet<E> - Class in java.util
A NavigableSet implementation based on a TreeMap.
TreeSet() - Constructor for class java.util.TreeSet
Constructs a new, empty tree set, sorted according to the natural ordering of its elements.
TreeSet(Comparator<? super E>) - Constructor for class java.util.TreeSet
Constructs a new, empty tree set, sorted according to the specified comparator.
TreeSet(Collection<? extends E>) - Constructor for class java.util.TreeSet
Constructs a new tree set containing the elements in the specified collection, sorted according to the natural ordering of its elements.
TreeSet(SortedSet<E>) - Constructor for class java.util.TreeSet
Constructs a new tree set containing the same elements and using the same ordering as the specified sorted set.
treeState - Variable in class javax.swing.plaf.basic.BasicTreeUI
Object responsible for handling sizing and expanded issues.
treeStructureChanged(TreeModelEvent) - Method in interface javax.swing.event.TreeModelListener
Invoked after the tree has drastically changed structure from a given node down.
treeStructureChanged(TreeModelEvent) - Method in class javax.swing.JTree.AccessibleJTree
Tree Model structure change change notification.
treeStructureChanged(TreeModelEvent) - Method in class javax.swing.JTree.TreeModelHandler
treeStructureChanged(TreeModelEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI.TreeModelHandler
treeStructureChanged(TreeModelEvent) - Method in class javax.swing.tree.AbstractLayoutCache
Invoked after the tree has drastically changed structure from a given node down.
treeStructureChanged(TreeModelEvent) - Method in class javax.swing.tree.FixedHeightLayoutCache
Invoked after the tree has drastically changed structure from a given node down.
treeStructureChanged(TreeModelEvent) - Method in class javax.swing.tree.VariableHeightLayoutCache
Invoked after the tree has drastically changed structure from a given node down.
TreeUI - Class in javax.swing.plaf
Pluggable look and feel interface for JTree.
TreeUI() - Constructor for class javax.swing.plaf.TreeUI
treeWillCollapse(TreeExpansionEvent) - Method in interface javax.swing.event.TreeWillExpandListener
Invoked whenever a node in the tree is about to be collapsed.
treeWillExpand(TreeExpansionEvent) - Method in interface javax.swing.event.TreeWillExpandListener
Invoked whenever a node in the tree is about to be expanded.
TreeWillExpandListener - Interface in javax.swing.event
The listener that's notified when a tree expands or collapses a node.
trim() - Method in class java.lang.String
Returns a copy of the string, with leading and trailing whitespace omitted.
trimEdits(int, int) - Method in class javax.swing.undo.UndoManager
Removes edits in the specified range.
trimForLimit() - Method in class javax.swing.undo.UndoManager
Reduces the number of queued edits to a range of size limit, centered on the index of the next edit.
trimToSize() - Method in class java.lang.StringBuffer
trimToSize() - Method in class java.util.ArrayList
Trims the capacity of this ArrayList instance to be the list's current size.
trimToSize() - Method in class java.util.Vector
Trims the capacity of this vector to be the vector's current size.
trimToSize() - Method in class javax.swing.DefaultListModel
Trims the capacity of this list to be the list's current size.
TRUE - Static variable in class java.lang.Boolean
The Boolean object corresponding to the primitive value true.
TRUE - Static variable in interface java.util.jar.Pack200.Packer
The string "true", a possible value for certain properties.
TRUE - Static variable in interface java.util.jar.Pack200.Unpacker
The string "true", a possible value for certain properties.
TRUETYPE_FONT - Static variable in class java.awt.Font
Identify a font resource of type TRUETYPE.
truncate(long) - Method in class java.nio.channels.AsynchronousFileChannel
Truncates this channel's file to the given size.
truncate(long) - Method in class java.nio.channels.FileChannel
Truncates this channel's file to the given size.
truncate(long) - Method in interface java.nio.channels.SeekableByteChannel
Truncates the entity, to which this channel is connected, to the given size.
truncate(long) - Method in interface java.sql.Blob
Truncates the BLOB value that this Blob object represents to be len bytes in length.
truncate(long) - Method in interface java.sql.Clob
Truncates the CLOB value that this Clob designates to have a length of len characters.
truncate(long) - Method in class javax.sql.rowset.serial.SerialBlob
Truncates the BLOB value that this Blob object represents to be len bytes in length.
truncate(long) - Method in class javax.sql.rowset.serial.SerialClob
Truncates the CLOB value that this SerialClob object represents so that it has a length of len characters.
TRUNCATED - Static variable in class javax.accessibility.AccessibleState
A state indicating that text is truncated by a bounding rectangle and that some of the text is not displayed on the screen.
TrustAnchor - Class in java.security.cert
A trust anchor or most-trusted Certification Authority (CA).
TrustAnchor(X509Certificate, byte[]) - Constructor for class java.security.cert.TrustAnchor
Creates an instance of TrustAnchor with the specified X509Certificate and optional name constraints, which are intended to be used as additional constraints when validating an X.509 certification path.
TrustAnchor(X500Principal, PublicKey, byte[]) - Constructor for class java.security.cert.TrustAnchor
Creates an instance of TrustAnchor where the most-trusted CA is specified as an X500Principal and public key.
TrustAnchor(String, PublicKey, byte[]) - Constructor for class java.security.cert.TrustAnchor
Creates an instance of TrustAnchor where the most-trusted CA is specified as a distinguished name and public key.
TrustManager - Interface in javax.net.ssl
This is the base interface for JSSE trust managers.
TrustManagerFactory - Class in javax.net.ssl
This class acts as a factory for trust managers based on a source of trust material.
TrustManagerFactory(TrustManagerFactorySpi, Provider, String) - Constructor for class javax.net.ssl.TrustManagerFactory
Creates a TrustManagerFactory object.
TrustManagerFactorySpi - Class in javax.net.ssl
This class defines the Service Provider Interface (SPI) for the TrustManagerFactory class.
TrustManagerFactorySpi() - Constructor for class javax.net.ssl.TrustManagerFactorySpi
tryAcquire(long) - Method in class java.util.concurrent.locks.AbstractQueuedLongSynchronizer
Attempts to acquire in exclusive mode.
tryAcquire(int) - Method in class java.util.concurrent.locks.AbstractQueuedSynchronizer
Attempts to acquire in exclusive mode.
tryAcquire() - Method in class java.util.concurrent.Semaphore
Acquires a permit from this semaphore, only if one is available at the time of invocation.
tryAcquire(long, TimeUnit) - Method in class java.util.concurrent.Semaphore
Acquires a permit from this semaphore, if one becomes available within the given waiting time and the current thread has not been interrupted.
tryAcquire(int) - Method in class java.util.concurrent.Semaphore
Acquires the given number of permits from this semaphore, only if all are available at the time of invocation.
tryAcquire(int, long, TimeUnit) - Method in class java.util.concurrent.Semaphore
Acquires the given number of permits from this semaphore, if all become available within the given waiting time and the current thread has not been interrupted.
tryAcquireNanos(long, long) - Method in class java.util.concurrent.locks.AbstractQueuedLongSynchronizer
Attempts to acquire in exclusive mode, aborting if interrupted, and failing if the given timeout elapses.
tryAcquireNanos(int, long) - Method in class java.util.concurrent.locks.AbstractQueuedSynchronizer
Attempts to acquire in exclusive mode, aborting if interrupted, and failing if the given timeout elapses.
tryAcquireShared(long) - Method in class java.util.concurrent.locks.AbstractQueuedLongSynchronizer
Attempts to acquire in shared mode.
tryAcquireShared(int) - Method in class java.util.concurrent.locks.AbstractQueuedSynchronizer
Attempts to acquire in shared mode.
tryAcquireSharedNanos(long, long) - Method in class java.util.concurrent.locks.AbstractQueuedLongSynchronizer
Attempts to acquire in shared mode, aborting if interrupted, and failing if the given timeout elapses.
tryAcquireSharedNanos(int, long) - Method in class java.util.concurrent.locks.AbstractQueuedSynchronizer
Attempts to acquire in shared mode, aborting if interrupted, and failing if the given timeout elapses.
tryLock(long, long, boolean) - Method in class java.nio.channels.AsynchronousFileChannel
Attempts to acquire a lock on the given region of this channel's file.
tryLock() - Method in class java.nio.channels.AsynchronousFileChannel
Attempts to acquire an exclusive lock on this channel's file.
tryLock(long, long, boolean) - Method in class java.nio.channels.FileChannel
Attempts to acquire a lock on the given region of this channel's file.
tryLock() - Method in class java.nio.channels.FileChannel
Attempts to acquire an exclusive lock on this channel's file.
tryLock() - Method in interface java.util.concurrent.locks.Lock
Acquires the lock only if it is free at the time of invocation.
tryLock(long, TimeUnit) - Method in interface java.util.concurrent.locks.Lock
Acquires the lock if it is free within the given waiting time and the current thread has not been interrupted.
tryLock() - Method in class java.util.concurrent.locks.ReentrantLock
Acquires the lock only if it is not held by another thread at the time of invocation.
tryLock(long, TimeUnit) - Method in class java.util.concurrent.locks.ReentrantLock
Acquires the lock if it is not held by another thread within the given waiting time and the current thread has not been interrupted.
tryLock() - Method in class java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock
Acquires the read lock only if the write lock is not held by another thread at the time of invocation.
tryLock(long, TimeUnit) - Method in class java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock
Acquires the read lock if the write lock is not held by another thread within the given waiting time and the current thread has not been interrupted.
tryLock() - Method in class java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock
Acquires the write lock only if it is not held by another thread at the time of invocation.
tryLock(long, TimeUnit) - Method in class java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock
Acquires the write lock if it is not held by another thread within the given waiting time and the current thread has not been interrupted.
tryRelease(long) - Method in class java.util.concurrent.locks.AbstractQueuedLongSynchronizer
Attempts to set the state to reflect a release in exclusive mode.
tryRelease(int) - Method in class java.util.concurrent.locks.AbstractQueuedSynchronizer
Attempts to set the state to reflect a release in exclusive mode.
tryReleaseShared(long) - Method in class java.util.concurrent.locks.AbstractQueuedLongSynchronizer
Attempts to set the state to reflect a release in shared mode.
tryReleaseShared(int) - Method in class java.util.concurrent.locks.AbstractQueuedSynchronizer
Attempts to set the state to reflect a release in shared mode.
tryToLoadClass(String, ClassLoader) - Static method in class java.awt.datatransfer.DataFlavor
Tries to load a class from: the bootstrap loader, the system loader, the context loader (if one is present) and finally the loader specified.
tryTransfer(E) - Method in class java.util.concurrent.LinkedTransferQueue
Transfers the element to a waiting consumer immediately, if possible.
tryTransfer(E, long, TimeUnit) - Method in class java.util.concurrent.LinkedTransferQueue
Transfers the element to a consumer if it is possible to do so before the timeout elapses.
tryTransfer(E) - Method in interface java.util.concurrent.TransferQueue
Transfers the element to a waiting consumer immediately, if possible.
tryTransfer(E, long, TimeUnit) - Method in interface java.util.concurrent.TransferQueue
Transfers the element to a consumer if it is possible to do so before the timeout elapses.
tryUnfork() - Method in class java.util.concurrent.ForkJoinTask
Tries to unschedule this task for execution.
TT - Static variable in class javax.swing.text.html.HTML.Tag
TT_EOF - Static variable in class java.io.StreamTokenizer
A constant indicating that the end of the stream has been read.
TT_EOL - Static variable in class java.io.StreamTokenizer
A constant indicating that the end of the line has been read.
TT_NUMBER - Static variable in class java.io.StreamTokenizer
A constant indicating that a number token has been read.
TT_WORD - Static variable in class java.io.StreamTokenizer
A constant indicating that a word token has been read.
TTL_DONT_CACHE - Static variable in class java.util.ResourceBundle.Control
The time-to-live constant for not caching loaded resource bundle instances.
TTL_NO_EXPIRATION_CONTROL - Static variable in class java.util.ResourceBundle.Control
The time-to-live constant for disabling the expiration control for loaded resource bundle instances in the cache.
ttype - Variable in class java.io.StreamTokenizer
After a call to the nextToken method, this field contains the type of the token just read.
TUESDAY - Static variable in class java.util.Calendar
Value of the Calendar.DAY_OF_WEEK field indicating Tuesday.
TUMBLE - Static variable in class javax.print.attribute.standard.Sides
An alias for "two sided short edge" (see TWO_SIDED_SHORT_EDGE).
TUNE_REQUEST - Static variable in class javax.sound.midi.ShortMessage
Status byte for Tune Request message (0xF6, or 246).
TWO_SIDED_LONG_EDGE - Static variable in class java.awt.JobAttributes.SidesType
The SidesType instance to use for specifying that consecutive job pages should be printed upon front and back sides of consecutive media sheets, such that the orientation of each pair of pages on the medium would be correct for the reader as if for binding on the long edge.
TWO_SIDED_LONG_EDGE - Static variable in class javax.print.attribute.standard.Sides
Imposes each consecutive pair of print-stream pages upon front and back sides of consecutive media sheets, such that the orientation of each pair of print-stream pages on the medium would be correct for the reader as if for binding on the long edge.
TWO_SIDED_SHORT_EDGE - Static variable in class java.awt.JobAttributes.SidesType
The SidesType instance to use for specifying that consecutive job pages should be printed upon front and back sides of consecutive media sheets, such that the orientation of each pair of pages on the medium would be correct for the reader as if for binding on the short edge.
TWO_SIDED_SHORT_EDGE - Static variable in class javax.print.attribute.standard.Sides
Imposes each consecutive pair of print-stream pages upon front and back sides of consecutive media sheets, such that the orientation of each pair of print-stream pages on the medium would be correct for the reader as if for binding on the short edge.
TYPE - Static variable in class java.lang.Boolean
The Class object representing the primitive type boolean.
TYPE - Static variable in class java.lang.Byte
The 类 instance representing the primitive type byte.
TYPE - Static variable in class java.lang.Character
The 类 instance representing the primitive type char.
TYPE - Static variable in class java.lang.Double
The 类 instance representing the primitive type double.
TYPE - Static variable in class java.lang.Float
The 类 instance representing the primitive type float.
TYPE - Static variable in class java.lang.Integer
The 类 instance representing the primitive type int.
type() - Method in class java.lang.invoke.CallSite
Returns the type of this call site's target.
type() - Method in class java.lang.invoke.MethodHandle
Reports the type of this method handle.
TYPE - Static variable in class java.lang.Long
The 类 instance representing the primitive type long.
type() - Method in class java.lang.ProcessBuilder.Redirect
Returns the type of this Redirect.
Type - Interface in java.lang.reflect
Type is the common superinterface for all types in the Java programming language.
TYPE - Static variable in class java.lang.Short
The 类 instance representing the primitive type short.
TYPE - Static variable in class java.lang.Void
The 类 object representing the pseudo-type corresponding to the keyword void.
type() - Method in class java.net.Proxy
Returns the proxy type.
type() - Method in interface java.net.SocketOption
Returns the type of the socket option value.
type() - Method in class java.nio.file.attribute.AclEntry
Returns the ACL entry type.
type() - Method in class java.nio.file.FileStore
Returns the type of this file store.
type() - Method in interface java.nio.file.WatchEvent.Kind
Returns the type of the context value.
type - Variable in class javax.naming.event.NamingEvent
Contains the type of this event.
type - Variable in class javax.sound.midi.MidiFileFormat
The type of MIDI file.
type - Variable in class javax.swing.event.TableModelEvent
type - Variable in class javax.swing.JTable.AccessibleJTable.AccessibleJTableModelChange
TYPE - Static variable in class javax.swing.text.html.HTML.Attribute
type - Variable in class javax.swing.text.html.parser.AttributeList
type - Variable in class javax.swing.text.html.parser.ContentModel
Type.
type - Variable in class javax.swing.text.html.parser.Element
type - Variable in class javax.swing.text.html.parser.Entity
TYPE - Static variable in interface javax.xml.crypto.dsig.keyinfo.PGPData
URI identifying the PGPData KeyInfo type: http://www.w3.org/2000/09/xmldsig#PGPData.
TYPE - Static variable in interface javax.xml.crypto.dsig.keyinfo.X509Data
URI identifying the X509Data KeyInfo type: http://www.w3.org/2000/09/xmldsig#X509Data.
TYPE - Static variable in interface javax.xml.crypto.dsig.Manifest
URI that identifies the Manifest element (this can be specified as the value of the type parameter of the Reference class to identify the referent's type).
TYPE - Static variable in interface javax.xml.crypto.dsig.SignatureProperties
URI that identifies the SignatureProperties element (this can be specified as the value of the type parameter of the Reference class to identify the referent's type).
TYPE - Static variable in interface javax.xml.crypto.dsig.XMLObject
URI that identifies the Object element (this can be specified as the value of the type parameter of the Reference class to identify the referent's type).
type() - Method in class org.omg.CORBA._IDLTypeStub
type() - Method in class org.omg.CORBA.Any
Returns type information for the element contained in this Any object.
type(TypeCode) - Method in class org.omg.CORBA.Any
Sets this Any object's type field to the given TypeCode object and clears its value.
type() - Static method in class org.omg.CORBA.AnySeqHelper
type() - Static method in class org.omg.CORBA.BooleanSeqHelper
type() - Static method in class org.omg.CORBA.CharSeqHelper
type() - Static method in class org.omg.CORBA.CompletionStatusHelper
type() - Static method in class org.omg.CORBA.CurrentHelper
type() - Static method in class org.omg.CORBA.DefinitionKindHelper
type() - Static method in class org.omg.CORBA.DoubleSeqHelper
type() - Method in interface org.omg.CORBA.DynAny
Deprecated.
Returns the TypeCode of the object inserted into this DynAny.
type() - Static method in class org.omg.CORBA.FieldNameHelper
type() - Static method in class org.omg.CORBA.FloatSeqHelper
type() - Static method in class org.omg.CORBA.IdentifierHelper
type() - Static method in class org.omg.CORBA.IDLTypeHelper
type() - Method in interface org.omg.CORBA.IDLTypeOperations
The type attribute describes the type defined by an object derived from IDLType.
type() - Static method in class org.omg.CORBA.LongLongSeqHelper
type() - Static method in class org.omg.CORBA.LongSeqHelper
type() - Static method in class org.omg.CORBA.NameValuePairHelper
type() - Static method in class org.omg.CORBA.ObjectHelper
type() - Static method in class org.omg.CORBA.OctetSeqHelper
type() - Static method in class org.omg.CORBA.ParameterModeHelper
type() - Static method in class org.omg.CORBA.PolicyErrorCodeHelper
type() - Static method in class org.omg.CORBA.PolicyErrorHelper
type() - Static method in class org.omg.CORBA.PolicyHelper
type() - Static method in class org.omg.CORBA.PolicyListHelper
type() - Static method in class org.omg.CORBA.PolicyTypeHelper
type() - Static method in class org.omg.CORBA.RepositoryIdHelper
type() - Static method in class org.omg.CORBA.ServiceDetailHelper
type() - Static method in class org.omg.CORBA.ServiceInformationHelper
type() - Static method in class org.omg.CORBA.SetOverrideTypeHelper
type() - Static method in class org.omg.CORBA.ShortSeqHelper
type() - Static method in class org.omg.CORBA.StringSeqHelper
type() - Static method in class org.omg.CORBA.StringValueHelper
type - Variable in class org.omg.CORBA.StructMember
The type of the struct member described by this StructMember object.
type() - Static method in class org.omg.CORBA.StructMemberHelper
type() - Static method in class org.omg.CORBA.ULongLongSeqHelper
type() - Static method in class org.omg.CORBA.ULongSeqHelper
type - Variable in class org.omg.CORBA.UnionMember
The type of the union member described by this UnionMember object.
type() - Static method in class org.omg.CORBA.UnionMemberHelper
type() - Static method in class org.omg.CORBA.UnknownUserExceptionHelper
type() - Static method in class org.omg.CORBA.UShortSeqHelper
type() - Static method in class org.omg.CORBA.ValueBaseHelper
type - Variable in class org.omg.CORBA.ValueMember
The type of of this value member.
type() - Static method in class org.omg.CORBA.ValueMemberHelper
type() - Static method in class org.omg.CORBA.VersionSpecHelper
type() - Static method in class org.omg.CORBA.VisibilityHelper
type() - Static method in class org.omg.CORBA.WCharSeqHelper
type() - Static method in class org.omg.CORBA.WrongTransactionHelper
type() - Static method in class org.omg.CORBA.WStringSeqHelper
type() - Static method in class org.omg.CORBA.WStringValueHelper
type() - Static method in class org.omg.CosNaming.BindingHelper
type() - Static method in class org.omg.CosNaming.BindingIteratorHelper
type() - Static method in class org.omg.CosNaming.BindingListHelper
type() - Static method in class org.omg.CosNaming.BindingTypeHelper
type() - Static method in class org.omg.CosNaming.IstringHelper
type() - Static method in class org.omg.CosNaming.NameComponentHelper
type() - Static method in class org.omg.CosNaming.NameHelper
type() - Static method in class org.omg.CosNaming.NamingContextExtHelper
type() - Static method in class org.omg.CosNaming.NamingContextExtPackage.AddressHelper
type() - Static method in class org.omg.CosNaming.NamingContextExtPackage.InvalidAddressHelper
type() - Static method in class org.omg.CosNaming.NamingContextExtPackage.StringNameHelper
type() - Static method in class org.omg.CosNaming.NamingContextExtPackage.URLStringHelper
type() - Static method in class org.omg.CosNaming.NamingContextHelper
type() - Static method in class org.omg.CosNaming.NamingContextPackage.AlreadyBoundHelper
type() - Static method in class org.omg.CosNaming.NamingContextPackage.CannotProceedHelper
type() - Static method in class org.omg.CosNaming.NamingContextPackage.InvalidNameHelper
type() - Static method in class org.omg.CosNaming.NamingContextPackage.NotEmptyHelper
type() - Static method in class org.omg.CosNaming.NamingContextPackage.NotFoundHelper
type() - Static method in class org.omg.CosNaming.NamingContextPackage.NotFoundReasonHelper
type() - Method in class org.omg.DynamicAny._DynAnyStub
Returns the TypeCode associated with this DynAny object.
type() - Method in class org.omg.DynamicAny._DynArrayStub
Returns the TypeCode associated with this DynAny object.
type() - Method in class org.omg.DynamicAny._DynEnumStub
Returns the TypeCode associated with this DynAny object.
type() - Method in class org.omg.DynamicAny._DynFixedStub
Returns the TypeCode associated with this DynAny object.
type() - Method in class org.omg.DynamicAny._DynSequenceStub
Returns the TypeCode associated with this DynAny object.
type() - Method in class org.omg.DynamicAny._DynStructStub
Returns the TypeCode associated with this DynAny object.
type() - Method in class org.omg.DynamicAny._DynUnionStub
Returns the TypeCode associated with this DynAny object.
type() - Method in class org.omg.DynamicAny._DynValueStub
Returns the TypeCode associated with this DynAny object.
type() - Static method in class org.omg.DynamicAny.AnySeqHelper
type() - Static method in class org.omg.DynamicAny.DynAnyFactoryHelper
type() - Static method in class org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCodeHelper
type() - Static method in class org.omg.DynamicAny.DynAnyHelper
type() - Method in interface org.omg.DynamicAny.DynAnyOperations
Returns the TypeCode associated with this DynAny object.
type() - Static method in class org.omg.DynamicAny.DynAnyPackage.InvalidValueHelper
type() - Static method in class org.omg.DynamicAny.DynAnyPackage.TypeMismatchHelper
type() - Static method in class org.omg.DynamicAny.DynAnySeqHelper
type() - Static method in class org.omg.DynamicAny.DynArrayHelper
type() - Static method in class org.omg.DynamicAny.DynEnumHelper
type() - Static method in class org.omg.DynamicAny.DynFixedHelper
type() - Static method in class org.omg.DynamicAny.DynSequenceHelper
type() - Static method in class org.omg.DynamicAny.DynStructHelper
type() - Static method in class org.omg.DynamicAny.DynUnionHelper
type() - Static method in class org.omg.DynamicAny.DynValueHelper
type() - Static method in class org.omg.DynamicAny.FieldNameHelper
type() - Static method in class org.omg.DynamicAny.NameDynAnyPairHelper
type() - Static method in class org.omg.DynamicAny.NameDynAnyPairSeqHelper
type() - Static method in class org.omg.DynamicAny.NameValuePairHelper
type() - Static method in class org.omg.DynamicAny.NameValuePairSeqHelper
type() - Static method in class org.omg.IOP.CodecFactoryHelper
type() - Static method in class org.omg.IOP.CodecFactoryPackage.UnknownEncodingHelper
type() - Static method in class org.omg.IOP.CodecPackage.FormatMismatchHelper
type() - Static method in class org.omg.IOP.CodecPackage.InvalidTypeForEncodingHelper
type() - Static method in class org.omg.IOP.CodecPackage.TypeMismatchHelper
type() - Static method in class org.omg.IOP.ComponentIdHelper
type() - Static method in class org.omg.IOP.IORHelper
type() - Static method in class org.omg.IOP.MultipleComponentProfileHelper
type() - Static method in class org.omg.IOP.ProfileIdHelper
type() - Static method in class org.omg.IOP.ServiceContextHelper
type() - Static method in class org.omg.IOP.ServiceContextListHelper
type() - Static method in class org.omg.IOP.ServiceIdHelper
type() - Static method in class org.omg.IOP.TaggedComponentHelper
type() - Static method in class org.omg.IOP.TaggedProfileHelper
type() - Static method in class org.omg.Messaging.SyncScopeHelper
type() - Static method in class org.omg.PortableInterceptor.AdapterManagerIdHelper
type() - Static method in class org.omg.PortableInterceptor.AdapterNameHelper
type() - Static method in class org.omg.PortableInterceptor.AdapterStateHelper
type() - Static method in class org.omg.PortableInterceptor.CurrentHelper
type() - Static method in class org.omg.PortableInterceptor.ForwardRequestHelper
type() - Static method in class org.omg.PortableInterceptor.InvalidSlotHelper
type() - Static method in class org.omg.PortableInterceptor.IORInterceptor_3_0Helper
type() - Static method in class org.omg.PortableInterceptor.ObjectIdHelper
type() - Static method in class org.omg.PortableInterceptor.ObjectReferenceFactoryHelper
type() - Static method in class org.omg.PortableInterceptor.ObjectReferenceTemplateHelper
type() - Static method in class org.omg.PortableInterceptor.ObjectReferenceTemplateSeqHelper
type() - Static method in class org.omg.PortableInterceptor.ORBIdHelper
type() - Static method in class org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateNameHelper
type() - Static method in class org.omg.PortableInterceptor.ORBInitInfoPackage.InvalidNameHelper
type() - Static method in class org.omg.PortableInterceptor.ORBInitInfoPackage.ObjectIdHelper
type() - Static method in class org.omg.PortableInterceptor.ServerIdHelper
type() - Static method in class org.omg.PortableServer.CurrentHelper
type() - Static method in class org.omg.PortableServer.CurrentPackage.NoContextHelper
type() - Static method in class org.omg.PortableServer.ForwardRequestHelper
type() - Static method in class org.omg.PortableServer.POAHelper
type() - Static method in class org.omg.PortableServer.POAManagerPackage.AdapterInactiveHelper
type() - Static method in class org.omg.PortableServer.POAPackage.AdapterAlreadyExistsHelper
type() - Static method in class org.omg.PortableServer.POAPackage.AdapterNonExistentHelper
type() - Static method in class org.omg.PortableServer.POAPackage.InvalidPolicyHelper
type() - Static method in class org.omg.PortableServer.POAPackage.NoServantHelper
type() - Static method in class org.omg.PortableServer.POAPackage.ObjectAlreadyActiveHelper
type() - Static method in class org.omg.PortableServer.POAPackage.ObjectNotActiveHelper
type() - Static method in class org.omg.PortableServer.POAPackage.ServantAlreadyActiveHelper
type() - Static method in class org.omg.PortableServer.POAPackage.ServantNotActiveHelper
type() - Static method in class org.omg.PortableServer.POAPackage.WrongAdapterHelper
type() - Static method in class org.omg.PortableServer.POAPackage.WrongPolicyHelper
type() - Static method in class org.omg.PortableServer.ServantActivatorHelper
type() - Static method in class org.omg.PortableServer.ServantLocatorHelper
TYPE1_FONT - Static variable in class java.awt.Font
Identify a font resource of type TYPE1.
type2name(int) - Static method in class javax.swing.text.html.parser.AttributeList
TYPE_2CLR - Static variable in class java.awt.color.ColorSpace
Generic 2 component color spaces.
TYPE_3BYTE_BGR - Static variable in class java.awt.image.BufferedImage
Represents an image with 8-bit RGB color components, corresponding to a Windows-style BGR color model) with the colors Blue, Green, and Red stored in 3 bytes.
TYPE_3CLR - Static variable in class java.awt.color.ColorSpace
Generic 3 component color spaces.
TYPE_4BYTE_ABGR - Static variable in class java.awt.image.BufferedImage
Represents an image with 8-bit RGBA color components with the colors Blue, Green, and Red stored in 3 bytes and 1 byte of alpha.
TYPE_4BYTE_ABGR_PRE - Static variable in class java.awt.image.BufferedImage
Represents an image with 8-bit RGBA color components with the colors Blue, Green, and Red stored in 3 bytes and 1 byte of alpha.
TYPE_4CLR - Static variable in class java.awt.color.ColorSpace
Generic 4 component color spaces.
TYPE_5CLR - Static variable in class java.awt.color.ColorSpace
Generic 5 component color spaces.
TYPE_6CLR - Static variable in class java.awt.color.ColorSpace
Generic 6 component color spaces.
TYPE_7CLR - Static variable in class java.awt.color.ColorSpace
Generic 7 component color spaces.
TYPE_8CLR - Static variable in class java.awt.color.ColorSpace
Generic 8 component color spaces.
TYPE_9CLR - Static variable in class java.awt.color.ColorSpace
Generic 9 component color spaces.
TYPE_ACLR - Static variable in class java.awt.color.ColorSpace
Generic 10 component color spaces.
TYPE_BCLR - Static variable in class java.awt.color.ColorSpace
Generic 11 component color spaces.
TYPE_BICUBIC - Static variable in class java.awt.image.AffineTransformOp
Bicubic interpolation type.
TYPE_BILINEAR - Static variable in class java.awt.image.AffineTransformOp
Bilinear interpolation type.
TYPE_BYTE - Static variable in class java.awt.image.DataBuffer
Tag for unsigned byte data.
TYPE_BYTE_BINARY - Static variable in class java.awt.image.BufferedImage
Represents an opaque byte-packed 1, 2, or 4 bit image.
TYPE_BYTE_GRAY - Static variable in class java.awt.image.BufferedImage
Represents a unsigned byte grayscale image, non-indexed.
TYPE_BYTE_INDEXED - Static variable in class java.awt.image.BufferedImage
Represents an indexed byte image.
TYPE_CCLR - Static variable in class java.awt.color.ColorSpace
Generic 12 component color spaces.
TYPE_CMY - Static variable in class java.awt.color.ColorSpace
Any of the family of CMY color spaces.
TYPE_CMYK - Static variable in class java.awt.color.ColorSpace
Any of the family of CMYK color spaces.
TYPE_CUSTOM - Static variable in class java.awt.image.BufferedImage
Image type is not recognized so it must be a customized image.
TYPE_DCLR - Static variable in class java.awt.color.ColorSpace
Generic 13 component color spaces.
type_def - Variable in class org.omg.CORBA.StructMember
The typedef that represents the IDL type of the struct member described by this StructMember object.
type_def - Variable in class org.omg.CORBA.UnionMember
The typedef that represents the IDL type of the union member described by this UnionMember object.
type_def - Variable in class org.omg.CORBA.ValueMember
The typedef that represents the IDL type of the value member described by this ValueMember object.
TYPE_DOUBLE - Static variable in class java.awt.image.DataBuffer
Tag for double data.
TYPE_ECLR - Static variable in class java.awt.color.ColorSpace
Generic 14 component color spaces.
TYPE_FCLR - Static variable in class java.awt.color.ColorSpace
Generic 15 component color spaces.
TYPE_FLIP - Static variable in class java.awt.geom.AffineTransform
This flag bit indicates that the transform defined by this object performs a mirror image flip about some axis which changes the normally right handed coordinate system into a left handed system in addition to the conversions indicated by other flag bits.
TYPE_FLOAT - Static variable in class java.awt.image.DataBuffer
Tag for float data.
TYPE_FORWARD_ONLY - Static variable in interface java.sql.ResultSet
The constant indicating the type for a ResultSet object whose cursor may move only forward.
TYPE_GENERAL_ROTATION - Static variable in class java.awt.geom.AffineTransform
This flag bit indicates that the transform defined by this object performs a rotation by an arbitrary angle in addition to the conversions indicated by other flag bits.
TYPE_GENERAL_SCALE - Static variable in class java.awt.geom.AffineTransform
This flag bit indicates that the transform defined by this object performs a general scale in addition to the conversions indicated by other flag bits.
TYPE_GENERAL_TRANSFORM - Static variable in class java.awt.geom.AffineTransform
This constant indicates that the transform defined by this object performs an arbitrary conversion of the input coordinates.
TYPE_GRAY - Static variable in class java.awt.color.ColorSpace
Any of the family of GRAY color spaces.
TYPE_HLS - Static variable in class java.awt.color.ColorSpace
Any of the family of HLS color spaces.
TYPE_HSV - Static variable in class java.awt.color.ColorSpace
Any of the family of HSV color spaces.
type_id - Variable in class org.omg.IOP.IOR
The type id, represented as a String.
TYPE_IDENTITY - Static variable in class java.awt.geom.AffineTransform
This constant indicates that the transform defined by this object is an identity transform.
TYPE_IMAGE_BUFFER - Static variable in class java.awt.GraphicsDevice
Device is an image buffer.
TYPE_INT - Static variable in class java.awt.image.DataBuffer
Tag for int data.
TYPE_INT_ARGB - Static variable in class java.awt.image.BufferedImage
Represents an image with 8-bit RGBA color components packed into integer pixels.
TYPE_INT_ARGB_PRE - Static variable in class java.awt.image.BufferedImage
Represents an image with 8-bit RGBA color components packed into integer pixels.
TYPE_INT_BGR - Static variable in class java.awt.image.BufferedImage
Represents an image with 8-bit RGB color components, corresponding to a Windows- or Solaris- style BGR color model, with the colors Blue, Green, and Red packed into integer pixels.
TYPE_INT_RGB - Static variable in class java.awt.image.BufferedImage
Represents an image with 8-bit RGB color components packed into integer pixels.
TYPE_Lab - Static variable in class java.awt.color.ColorSpace
Any of the family of Lab color spaces.
TYPE_Luv - Static variable in class java.awt.color.ColorSpace
Any of the family of Luv color spaces.
TYPE_MASK_ROTATION - Static variable in class java.awt.geom.AffineTransform
This constant is a bit mask for any of the rotation flag bits.
TYPE_MASK_SCALE - Static variable in class java.awt.geom.AffineTransform
This constant is a bit mask for any of the scale flag bits.
TYPE_MISMATCH_ERR - Static variable in exception org.w3c.dom.DOMException
If the type of an object is incompatible with the expected type of the parameter associated to the object.
type_modifier() - Method in class org.omg.CORBA.TypeCode
Returns a constant indicating the modifier of the value type that this TypeCode object describes.
TYPE_NEAREST_NEIGHBOR - Static variable in class java.awt.image.AffineTransformOp
Nearest-neighbor interpolation type.
TYPE_PRINTER - Static variable in class java.awt.GraphicsDevice
Device is a printer.
TYPE_QUADRANT_ROTATION - Static variable in class java.awt.geom.AffineTransform
This flag bit indicates that the transform defined by this object performs a quadrant rotation by some multiple of 90 degrees in addition to the conversions indicated by other flag bits.
TYPE_RASTER_SCREEN - Static variable in class java.awt.GraphicsDevice
Device is a raster screen.
TYPE_RGB - Static variable in class java.awt.color.ColorSpace
Any of the family of RGB color spaces.
TYPE_SCROLL_INSENSITIVE - Static variable in interface java.sql.ResultSet
The constant indicating the type for a ResultSet object that is scrollable but generally not sensitive to changes to the data that underlies the ResultSet.
TYPE_SCROLL_SENSITIVE - Static variable in interface java.sql.ResultSet
The constant indicating the type for a ResultSet object that is scrollable and generally sensitive to changes to the data that underlies the ResultSet.
TYPE_SHORT - Static variable in class java.awt.image.DataBuffer
Tag for signed short data.
TYPE_TRANSLATION - Static variable in class java.awt.geom.AffineTransform
This flag bit indicates that the transform defined by this object performs a translation in addition to the conversions indicated by other flag bits.
TYPE_UNDEFINED - Static variable in class java.awt.image.DataBuffer
Tag for undefined data.
TYPE_UNIFORM_SCALE - Static variable in class java.awt.geom.AffineTransform
This flag bit indicates that the transform defined by this object performs a uniform scale in addition to the conversions indicated by other flag bits.
TYPE_USHORT - Static variable in class java.awt.image.DataBuffer
Tag for unsigned short data.
TYPE_USHORT_555_RGB - Static variable in class java.awt.image.BufferedImage
Represents an image with 5-5-5 RGB color components (5-bits red, 5-bits green, 5-bits blue) with no alpha.
TYPE_USHORT_565_RGB - Static variable in class java.awt.image.BufferedImage
Represents an image with 5-6-5 RGB color components (5-bits red, 6-bits green, 5-bits blue) with no alpha.
TYPE_USHORT_GRAY - Static variable in class java.awt.image.BufferedImage
Represents an unsigned short grayscale image, non-indexed).
TYPE_XYZ - Static variable in class java.awt.color.ColorSpace
Any of the family of XYZ color spaces.
TYPE_YCbCr - Static variable in class java.awt.color.ColorSpace
Any of the family of YCbCr color spaces.
TYPE_Yxy - Static variable in class java.awt.color.ColorSpace
Any of the family of Yxy color spaces.
TypeCode - Class in org.omg.CORBA
A container for information about a specific CORBA data type.
TypeCode() - Constructor for class org.omg.CORBA.TypeCode
TypeCodeHolder - Class in org.omg.CORBA
The Holder for TypeCode.
TypeCodeHolder() - Constructor for class org.omg.CORBA.TypeCodeHolder
Constructs a new TypeCodeHolder object with its value field initialized to null.
TypeCodeHolder(TypeCode) - Constructor for class org.omg.CORBA.TypeCodeHolder
Constructs a new TypeCodeHolder object with its value field initialized to the given TypeCode object.
TypeConstraintException - Exception in javax.xml.bind
This exception indicates that a violation of a dynamically checked type constraint was detected.
TypeConstraintException(String) - Constructor for exception javax.xml.bind.TypeConstraintException
Construct a TypeConstraintException with the specified detail message.
TypeConstraintException(String, String) - Constructor for exception javax.xml.bind.TypeConstraintException
Construct a TypeConstraintException with the specified detail message and vendor specific errorCode.
TypeConstraintException(Throwable) - Constructor for exception javax.xml.bind.TypeConstraintException
Construct a TypeConstraintException with a linkedException.
TypeConstraintException(String, Throwable) - Constructor for exception javax.xml.bind.TypeConstraintException
Construct a TypeConstraintException with the specified detail message and linkedException.
TypeConstraintException(String, String, Throwable) - Constructor for exception javax.xml.bind.TypeConstraintException
Construct a TypeConstraintException with the specified detail message, vendor specific errorCode, and linkedException.
TypeElement - Interface in javax.lang.model.element
Represents a class or interface program element.
TypeInfo - Interface in org.w3c.dom
The TypeInfo interface represents a type referenced from Element or Attr nodes, specified in the schemas associated with the document.
TypeInfoProvider - Class in javax.xml.validation
This class provides access to the type information determined by ValidatorHandler.
TypeInfoProvider() - Constructor for class javax.xml.validation.TypeInfoProvider
Constructor for the derived class.
TypeKind - Enum in javax.lang.model.type
The kind of a type mirror.
TypeKindVisitor6<R,P> - Class in javax.lang.model.util
A visitor of types based on their kind with default behavior appropriate for the RELEASE_6 source version.
TypeKindVisitor6() - Constructor for class javax.lang.model.util.TypeKindVisitor6
Constructor for concrete subclasses to call; uses null for the default value.
TypeKindVisitor6(R) - Constructor for class javax.lang.model.util.TypeKindVisitor6
Constructor for concrete subclasses to call; uses the argument for the default value.
TypeKindVisitor7<R,P> - Class in javax.lang.model.util
A visitor of types based on their kind with default behavior appropriate for the RELEASE_7 source version.
TypeKindVisitor7() - Constructor for class javax.lang.model.util.TypeKindVisitor7
Constructor for concrete subclasses to call; uses null for the default value.
TypeKindVisitor7(R) - Constructor for class javax.lang.model.util.TypeKindVisitor7
Constructor for concrete subclasses to call; uses the argument for the default value.
TypeMirror - Interface in javax.lang.model.type
Represents a type in the Java programming language.
TypeMismatch - Exception in org.omg.CORBA.DynAnyPackage
TypeMismatch is thrown by dynamic any accessor methods when type of the actual contents do not match what is trying to be accessed.
TypeMismatch() - Constructor for exception org.omg.CORBA.DynAnyPackage.TypeMismatch
Constructs a TypeMismatch object.
TypeMismatch(String) - Constructor for exception org.omg.CORBA.DynAnyPackage.TypeMismatch
Constructs a TypeMismatch object.
TypeMismatch - Exception in org.omg.DynamicAny.DynAnyPackage
org/omg/DynamicAny/DynAnyPackage/TypeMismatch.java .
TypeMismatch() - Constructor for exception org.omg.DynamicAny.DynAnyPackage.TypeMismatch
TypeMismatch(String) - Constructor for exception org.omg.DynamicAny.DynAnyPackage.TypeMismatch
TypeMismatch - Exception in org.omg.IOP.CodecPackage
org/omg/IOP/CodecPackage/TypeMismatch.java .
TypeMismatch() - Constructor for exception org.omg.IOP.CodecPackage.TypeMismatch
TypeMismatch(String) - Constructor for exception org.omg.IOP.CodecPackage.TypeMismatch
TypeMismatchHelper - Class in org.omg.DynamicAny.DynAnyPackage
org/omg/DynamicAny/DynAnyPackage/TypeMismatchHelper.java .
TypeMismatchHelper() - Constructor for class org.omg.DynamicAny.DynAnyPackage.TypeMismatchHelper
TypeMismatchHelper - Class in org.omg.IOP.CodecPackage
org/omg/IOP/CodecPackage/TypeMismatchHelper.java .
TypeMismatchHelper() - Constructor for class org.omg.IOP.CodecPackage.TypeMismatchHelper
typeName() - Method in exception java.lang.TypeNotPresentException
Returns the fully qualified name of the unavailable type.
typeNoNulls - Static variable in interface java.sql.DatabaseMetaData
Indicates that a NULL value is NOT allowed for this data type.
TypeNotPresentException - Exception in java.lang
Thrown when an application tries to access a type using a string representing the type's name, but no definition for the type with the specified name can be found.
TypeNotPresentException(String, Throwable) - Constructor for exception java.lang.TypeNotPresentException
Constructs a TypeNotPresentException for the named type with the specified cause.
typeNullable - Static variable in interface java.sql.DatabaseMetaData
Indicates that a NULL value is allowed for this data type.
typeNullableUnknown - Static variable in interface java.sql.DatabaseMetaData
Indicates that it is not known whether a NULL value is allowed for this data type.
TypeParameterElement - Interface in javax.lang.model.element
Represents a formal type parameter of a generic class, interface, method, or constructor element.
typePredBasic - Static variable in interface java.sql.DatabaseMetaData
Indicates that the data type can be only be used in WHERE search clauses that do not use LIKE predicates.
typePredChar - Static variable in interface java.sql.DatabaseMetaData
Indicates that the data type can be only be used in WHERE search clauses that use LIKE predicates.
typePredNone - Static variable in interface java.sql.DatabaseMetaData
Indicates that WHERE search clauses are not supported for this type.
Types - Class in java.sql
The class that defines the constants that are used to identify generic SQL types, called JDBC types.
Types - Interface in javax.lang.model.util
Utility methods for operating on types.
typeSearchable - Static variable in interface java.sql.DatabaseMetaData
Indicates that all WHERE search clauses can be based on this type.
typesIn(Iterable<? extends Element>) - Static method in class javax.lang.model.util.ElementFilter
Returns a list of types in elements.
typesIn(Set<? extends Element>) - Static method in class javax.lang.model.util.ElementFilter
Returns a set of types in elements.
TypeVariable<D extends GenericDeclaration> - Interface in java.lang.reflect
TypeVariable is the common superinterface for type variables of kinds.
TypeVariable - Interface in javax.lang.model.type
Represents a type variable.
TypeVisitor<R,P> - Interface in javax.lang.model.type
A visitor of types, in the style of the visitor design pattern.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类


U-Index

请注意：本 java api 1.7Beta 规范不是最终稳定版，未来随着版本的更迭，本规范可能有更新。
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _

U

U - Static variable in class javax.swing.text.html.HTML.Tag
UGARITIC - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Ugaritic" Unicode character block.
ui - Variable in class javax.swing.JComponent
The look and feel delegate for this component.
ui - Variable in class javax.swing.plaf.basic.BasicMenuUI.ChangeHandler
UID - Class in java.rmi.server
A UID represents an identifier that is unique over time with respect to the host it is generated on, or one of 216 "well-known" identifiers.
UID() - Constructor for class java.rmi.server.UID
Generates a UID that is unique over time with respect to the host that it was generated on.
UID(short) - Constructor for class java.rmi.server.UID
Creates a "well-known" UID.
UIDefaults - Class in javax.swing
A table of defaults for Swing components.
UIDefaults() - Constructor for class javax.swing.UIDefaults
Creates an empty defaults table.
UIDefaults(int, float) - Constructor for class javax.swing.UIDefaults
Creates an empty defaults table with the specified initial capacity and load factor.
UIDefaults(Object[]) - Constructor for class javax.swing.UIDefaults
Creates a defaults table initialized with the specified key/value pairs.
UIDefaults.ActiveValue - Interface in javax.swing
This class enables one to store an entry in the defaults table that's constructed each time it's looked up with one of the getXXX(key) methods.
UIDefaults.LazyInputMap - Class in javax.swing
LazyInputMap will create a InputMap in its createValue method.
UIDefaults.LazyInputMap(Object[]) - Constructor for class javax.swing.UIDefaults.LazyInputMap
UIDefaults.LazyValue - Interface in javax.swing
This class enables one to store an entry in the defaults table that isn't constructed until the first time it's looked up with one of the getXXX(key) methods.
UIDefaults.ProxyLazyValue - Class in javax.swing
This class provides an implementation of LazyValue which can be used to delay loading of the Class for the instance to be created.
UIDefaults.ProxyLazyValue(String) - Constructor for class javax.swing.UIDefaults.ProxyLazyValue
Creates a LazyValue which will construct an instance when asked.
UIDefaults.ProxyLazyValue(String, String) - Constructor for class javax.swing.UIDefaults.ProxyLazyValue
Creates a LazyValue which will construct an instance when asked.
UIDefaults.ProxyLazyValue(String, Object[]) - Constructor for class javax.swing.UIDefaults.ProxyLazyValue
Creates a LazyValue which will construct an instance when asked.
UIDefaults.ProxyLazyValue(String, String, Object[]) - Constructor for class javax.swing.UIDefaults.ProxyLazyValue
Creates a LazyValue which will construct an instance when asked.
UIEvent - Interface in org.w3c.dom.events
The UIEvent interface provides specific contextual information associated with User Interface events.
UIManager - Class in javax.swing
UIManager manages the current look and feel, the set of available look and feels, PropertyChangeListeners that are notified when the look and feel changes, look and feel defaults, and convenience methods for obtaining various default values.
UIManager() - Constructor for class javax.swing.UIManager
UIManager.LookAndFeelInfo - Class in javax.swing
Provides a little information about an installed LookAndFeel for the sake of configuring a menu or for initial application set up.
UIManager.LookAndFeelInfo(String, String) - Constructor for class javax.swing.UIManager.LookAndFeelInfo
Constructs a UIManagers LookAndFeelInfo object.
UIResource - Interface in javax.swing.plaf
This interface is used to mark objects created by ComponentUI delegates.
uis - Variable in class javax.swing.plaf.multi.MultiButtonUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiColorChooserUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiComboBoxUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiDesktopIconUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiDesktopPaneUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiFileChooserUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiInternalFrameUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiLabelUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiListUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiMenuBarUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiMenuItemUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiOptionPaneUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiPanelUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiPopupMenuUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiProgressBarUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiRootPaneUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiScrollBarUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiScrollPaneUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiSeparatorUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiSliderUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiSpinnerUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiSplitPaneUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiTabbedPaneUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiTableHeaderUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiTableUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiTextUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiToolBarUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiToolTipUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiTreeUI
The vector containing the real UIs.
uis - Variable in class javax.swing.plaf.multi.MultiViewportUI
The vector containing the real UIs.
uisToArray(Vector) - Static method in class javax.swing.plaf.multi.MultiLookAndFeel
Creates an array, populates it with UI objects from the passed-in vector, and returns the array.
UK - Static variable in class java.util.Locale
Useful constant for country.
UL - Static variable in class javax.swing.text.html.HTML.Tag
ULAW - Static variable in class javax.sound.sampled.AudioFormat.Encoding
Specifies u-law encoded data.
ULongLongSeqHelper - Class in org.omg.CORBA
The Helper for ULongLongSeq.
ULongLongSeqHelper() - Constructor for class org.omg.CORBA.ULongLongSeqHelper
ULongLongSeqHolder - Class in org.omg.CORBA
The Holder for ULongLongSeq.
ULongLongSeqHolder() - Constructor for class org.omg.CORBA.ULongLongSeqHolder
ULongLongSeqHolder(long[]) - Constructor for class org.omg.CORBA.ULongLongSeqHolder
ULongSeqHelper - Class in org.omg.CORBA
The Helper for ULongSeq.
ULongSeqHelper() - Constructor for class org.omg.CORBA.ULongSeqHelper
ULongSeqHolder - Class in org.omg.CORBA
The Holder for ULongSeq.
ULongSeqHolder() - Constructor for class org.omg.CORBA.ULongSeqHolder
ULongSeqHolder(int[]) - Constructor for class org.omg.CORBA.ULongSeqHolder
ulp(double) - Static method in class java.lang.Math
Returns the size of an ulp of the argument.
ulp(float) - Static method in class java.lang.Math
Returns the size of an ulp of the argument.
ulp(double) - Static method in class java.lang.StrictMath
Returns the size of an ulp of the argument.
ulp(float) - Static method in class java.lang.StrictMath
Returns the size of an ulp of the argument.
ulp() - Method in class java.math.BigDecimal
Returns the size of an ulp, a unit in the last place, of this BigDecimal.
UNASSIGNED - Static variable in class java.lang.Character
General category "Cn" in the Unicode specification.
UNAUTHORIZED - Static variable in exception org.ietf.jgss.GSSException
Operation unauthorized.
UNAVAILABLE - Static variable in exception org.ietf.jgss.GSSException
Operation unavailable.
unbind(String) - Static method in class java.rmi.Naming
Destroys the binding for the specified name that is associated with a remote object.
unbind(String) - Method in interface java.rmi.registry.Registry
Removes the binding for the specified name in this registry.
unbind(Name) - Method in interface javax.naming.Context
Unbinds the named object.
unbind(String) - Method in interface javax.naming.Context
Unbinds the named object.
unbind(String) - Method in class javax.naming.InitialContext
unbind(Name) - Method in class javax.naming.InitialContext
unbind(NameComponent[]) - Method in class org.omg.CosNaming._NamingContextExtStub
The unbind operation removes a name binding from a context.
unbind(NameComponent[]) - Method in class org.omg.CosNaming._NamingContextStub
The unbind operation removes a name binding from a context.
unbind(NameComponent[]) - Method in interface org.omg.CosNaming.NamingContextOperations
The unbind operation removes a name binding from a context.
unblock(InetAddress) - Method in class java.nio.channels.MembershipKey
Unblock multicast datagrams from the given source address that was previously blocked using the block method.
unboxedType(TypeMirror) - Method in interface javax.lang.model.util.Types
Returns the type (a primitive type) of unboxed values of a given type.
uncaughtException(Thread, Throwable) - Method in interface java.lang.Thread.UncaughtExceptionHandler
Method invoked when the given thread terminates due to the given uncaught exception.
uncaughtException(Thread, Throwable) - Method in class java.lang.ThreadGroup
Called by the Java Virtual Machine when a thread in this thread group stops because of an uncaught exception, and the thread does not have a specific Thread.UncaughtExceptionHandler installed.
unchecked_narrow(Object) - Static method in class org.omg.CosNaming.BindingIteratorHelper
unchecked_narrow(Object) - Static method in class org.omg.CosNaming.NamingContextExtHelper
unchecked_narrow(Object) - Static method in class org.omg.CosNaming.NamingContextHelper
unchecked_narrow(Object) - Static method in class org.omg.DynamicAny.DynAnyFactoryHelper
unchecked_narrow(Object) - Static method in class org.omg.DynamicAny.DynAnyHelper
unchecked_narrow(Object) - Static method in class org.omg.DynamicAny.DynArrayHelper
unchecked_narrow(Object) - Static method in class org.omg.DynamicAny.DynEnumHelper
unchecked_narrow(Object) - Static method in class org.omg.DynamicAny.DynFixedHelper
unchecked_narrow(Object) - Static method in class org.omg.DynamicAny.DynSequenceHelper
unchecked_narrow(Object) - Static method in class org.omg.DynamicAny.DynStructHelper
unchecked_narrow(Object) - Static method in class org.omg.DynamicAny.DynUnionHelper
unchecked_narrow(Object) - Static method in class org.omg.DynamicAny.DynValueHelper
unchecked_narrow(Object) - Static method in class org.omg.IOP.CodecFactoryHelper
unchecked_narrow(Object) - Static method in class org.omg.PortableInterceptor.CurrentHelper
unchecked_narrow(Object) - Static method in class org.omg.PortableInterceptor.IORInterceptor_3_0Helper
unchecked_narrow(Object) - Static method in class org.omg.PortableServer.ServantActivatorHelper
unchecked_narrow(Object) - Static method in class org.omg.PortableServer.ServantLocatorHelper
UNCOLLATED - Static variable in class javax.print.attribute.standard.SheetCollate
Sheets within a document appear in uncollated order when multiple copies are printed.
unconfigurableExecutorService(ExecutorService) - Static method in class java.util.concurrent.Executors
Returns an object that delegates all defined ExecutorService methods to the given executor, but not any other methods that might otherwise be accessible using casts.
unconfigurableScheduledExecutorService(ScheduledExecutorService) - Static method in class java.util.concurrent.Executors
Returns an object that delegates all defined ScheduledExecutorService methods to the given executor, but not any other methods that might otherwise be accessible using casts.
unconfigureArrowButton() - Method in class javax.swing.plaf.basic.BasicComboBoxUI
This public method is implementation specific and should be private.
unconfigureEditor() - Method in class javax.swing.plaf.basic.BasicComboBoxUI
This protected method is implementation specific and should be private.
unconfigureEditor() - Method in class javax.swing.plaf.metal.MetalComboBoxUI
unconfigureEnclosingScrollPane() - Method in class javax.swing.JTable
Reverses the effect of configureEnclosingScrollPane by replacing the columnHeaderView of the enclosing scroll pane with null.
UNDECIMBER - Static variable in class java.util.Calendar
Value of the Calendar.MONTH field indicating the thirteenth month of the year.
UndeclaredThrowableException - Exception in java.lang.reflect
Thrown by a method invocation on a proxy instance if its invocation handler's invoke method throws a checked exception (a Throwable that is not assignable to RuntimeException or Error) that is not assignable to any of the exception types declared in the throws clause of the method that was invoked on the proxy instance and dispatched to the invocation handler.
UndeclaredThrowableException(Throwable) - Constructor for exception java.lang.reflect.UndeclaredThrowableException
Constructs an UndeclaredThrowableException with the specified Throwable.
UndeclaredThrowableException(Throwable, String) - Constructor for exception java.lang.reflect.UndeclaredThrowableException
Constructs an UndeclaredThrowableException with the specified Throwable and a detail message.
UNDEFINED - Static variable in class java.awt.BufferCapabilities.FlipContents
When flip contents are UNDEFINED, the contents of the back buffer are undefined after flipping.
UNDEFINED_CONDITION - Static variable in class javax.swing.JComponent
Constant used by some of the APIs to mean that no condition is defined.
UndefinedProperty - Static variable in class java.awt.Image
The UndefinedProperty object should be returned whenever a property which was not defined for a particular image is fetched.
UNDERFLOW - Static variable in class java.nio.charset.CoderResult
Result object indicating underflow, meaning that either the input buffer has been completely consumed or, if the input buffer is not yet empty, that additional input is required.
UNDERLINE - Static variable in class java.awt.font.TextAttribute
Attribute key for underline.
Underline - Static variable in class javax.swing.text.StyleConstants
Name of the underline attribute.
UNDERLINE_LOW_DASHED - Static variable in class java.awt.font.TextAttribute
Single pixel dashed low underline.
UNDERLINE_LOW_DOTTED - Static variable in class java.awt.font.TextAttribute
Single pixel dotted low underline.
UNDERLINE_LOW_GRAY - Static variable in class java.awt.font.TextAttribute
Double pixel gray low underline.
UNDERLINE_LOW_ONE_PIXEL - Static variable in class java.awt.font.TextAttribute
Single pixel solid low underline.
UNDERLINE_LOW_TWO_PIXEL - Static variable in class java.awt.font.TextAttribute
Double pixel solid low underline.
UNDERLINE_ON - Static variable in class java.awt.font.TextAttribute
Standard underline.
undo() - Method in class javax.swing.text.AbstractDocument.DefaultDocumentEvent
Undoes a change.
undo() - Method in class javax.swing.text.AbstractDocument.ElementEdit
Undoes a change.
undo() - Method in class javax.swing.text.DefaultStyledDocument.AttributeUndoableEdit
Undoes a change.
undo() - Method in class javax.swing.undo.AbstractUndoableEdit
Throws CannotUndoException if canUndo returns false.
undo() - Method in class javax.swing.undo.CompoundEdit
Sends undo to all contained UndoableEdits in the reverse of the order in which they were added.
undo() - Method in class javax.swing.undo.StateEdit
Tells the edited object to apply the state prior to the edit
undo() - Method in interface javax.swing.undo.UndoableEdit
Undo the edit.
undo() - Method in class javax.swing.undo.UndoManager
Undoes the appropriate edits.
UndoableEdit - Interface in javax.swing.undo
An UndoableEdit represents an edit.
UndoableEditEvent - Class in javax.swing.event
An event indicating that an operation which can be undone has occurred.
UndoableEditEvent(Object, UndoableEdit) - Constructor for class javax.swing.event.UndoableEditEvent
Constructs an UndoableEditEvent object.
undoableEditHappened(UndoableEditEvent) - Method in interface javax.swing.event.UndoableEditListener
An undoable edit happened
undoableEditHappened(UndoableEditEvent) - Method in class javax.swing.undo.UndoManager
An UndoableEditListener method.
UndoableEditListener - Interface in javax.swing.event
Interface implemented by a class interested in hearing about undoable operations.
UndoableEditSupport - Class in javax.swing.undo
A support class used for managing UndoableEdit listeners.
UndoableEditSupport() - Constructor for class javax.swing.undo.UndoableEditSupport
Constructs an UndoableEditSupport object.
UndoableEditSupport(Object) - Constructor for class javax.swing.undo.UndoableEditSupport
Constructs an UndoableEditSupport object.
undoDelete() - Method in interface javax.sql.rowset.CachedRowSet
Cancels the deletion of the current row and notifies listeners that a row has changed.
undoInsert() - Method in interface javax.sql.rowset.CachedRowSet
Immediately removes the current row from this CachedRowSet object if the row has been inserted, and also notifies listeners that a row has changed.
UndoManager - Class in javax.swing.undo
UndoManager manages a list of UndoableEdits, providing a way to undo or redo the appropriate edits.
UndoManager() - Constructor for class javax.swing.undo.UndoManager
Creates a new UndoManager.
UndoName - Static variable in class javax.swing.undo.AbstractUndoableEdit
String returned by getUndoPresentationName; as of Java 2 platform v1.3.1 this field is no longer used.
undoOrRedo() - Method in class javax.swing.undo.UndoManager
Convenience method that invokes one of undo or redo.
undoRedoName - Variable in class javax.swing.undo.StateEdit
The undo/redo presentation name
undoTo(UndoableEdit) - Method in class javax.swing.undo.UndoManager
Undoes all changes from the index of the next edit to edit, updating the index of the next edit appropriately.
undoUpdate() - Method in interface javax.sql.rowset.CachedRowSet
Immediately reverses the last update operation if the row has been modified.
unescapeValue(String) - Static method in class javax.naming.ldap.Rdn
Given an attribute value string formated according to the rules specified in RFC 2253, returns the unformated value.
UnexpectedException - Exception in java.rmi
An UnexpectedException is thrown if the client of a remote method call receives, as a result of the call, a checked exception that is not among the checked exception types declared in the throws clause of the method in the remote interface.
UnexpectedException(String) - Constructor for exception java.rmi.UnexpectedException
Constructs an UnexpectedException with the specified detail message.
UnexpectedException(String, Exception) - Constructor for exception java.rmi.UnexpectedException
Constructs a UnexpectedException with the specified detail message and nested exception.
unexportObject(Remote, boolean) - Static method in class java.rmi.activation.Activatable
Remove the remote object, obj, from the RMI runtime.
unexportObject(Remote, boolean) - Static method in class java.rmi.server.UnicastRemoteObject
Removes the remote object, obj, from the RMI runtime.
unexportObject(Remote) - Method in interface javax.rmi.CORBA.PortableRemoteObjectDelegate
Delegation call for PortableRemoteObject.unexportObject(java.rmi.Remote).
unexportObject(Remote) - Static method in class javax.rmi.CORBA.Util
Removes the associated tie from an internal table and calls Tie.deactivate() to deactivate the object.
unexportObject(Remote) - Method in interface javax.rmi.CORBA.UtilDelegate
Delegation call for Util.unexportObject(java.rmi.Remote).
unexportObject(Remote) - Static method in class javax.rmi.PortableRemoteObject
Deregisters a server object from the runtime, allowing the object to become available for garbage collection.
UnicastRemoteObject - Class in java.rmi.server
Used for exporting a remote object with JRMP and obtaining a stub that communicates to the remote object.
UnicastRemoteObject() - Constructor for class java.rmi.server.UnicastRemoteObject
Creates and exports a new UnicastRemoteObject object using an anonymous port.
UnicastRemoteObject(int) - Constructor for class java.rmi.server.UnicastRemoteObject
Creates and exports a new UnicastRemoteObject object using the particular supplied port.
UnicastRemoteObject(int, RMIClientSocketFactory, RMIServerSocketFactory) - Constructor for class java.rmi.server.UnicastRemoteObject
Creates and exports a new UnicastRemoteObject object using the particular supplied port and socket factories.
UNICODE_CASE - Static variable in class java.util.regex.Pattern
Enables Unicode-aware case folding.
UNICODE_LOCALE_EXTENSION - Static variable in class java.util.Locale
The key for Unicode locale extension ('u').
UNICODE_STREAM_PARAM - Static variable in class javax.sql.rowset.BaseRowSet
A constant indicating to a RowSetReaderImpl object that a given parameter is a Unicode stream.
unicodeStream - Variable in class javax.sql.rowset.BaseRowSet
The InputStream object that will be returned by the method getUnicodeStream, which is specified in the ResultSet interface.
UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Unified Canadian Aboriginal Syllabics" Unicode character block.
UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS_EXTENDED - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Unified Canadian Aboriginal Syllabics Extended" Unicode character block.
uninitialize() - Method in class javax.swing.LookAndFeel
Uninitializes the look and feel.
uninitialize() - Method in class javax.swing.plaf.basic.BasicLookAndFeel
Uninitializes the look and feel.
uninitialize() - Method in class javax.swing.plaf.nimbus.NimbusLookAndFeel
Called by UIManager when this look and feel is uninstalled.
uninitialize() - Method in class javax.swing.plaf.synth.SynthLookAndFeel
Called by UIManager when this look and feel is uninstalled.
UNINITIALIZED - Static variable in class java.security.Signature
Possible Signature.state value, signifying that this signature object has not yet been initialized.
UNINITIALIZED_VALUE - Static variable in class javax.swing.JOptionPane
Indicates that the user has not yet selected a value.
uninstall() - Method in class javax.swing.JFormattedTextField.AbstractFormatter
Uninstalls any state the AbstractFormatter may have installed on the JFormattedTextField.
uninstallBorder(JComponent) - Static method in class javax.swing.LookAndFeel
Convenience method for uninstalling a border.
uninstallChooserPanel(JColorChooser) - Method in class javax.swing.colorchooser.AbstractColorChooserPanel
Invoked when the panel is removed from the chooser.
uninstallComboBoxModelListeners(ComboBoxModel) - Method in class javax.swing.plaf.basic.BasicComboPopup
Removes the listeners from the combo box model
uninstallComponents() - Method in class javax.swing.plaf.basic.BasicComboBoxUI
The aggregate components which compise the combo box are unregistered and uninitialized.
uninstallComponents() - Method in class javax.swing.plaf.basic.BasicDesktopIconUI
uninstallComponents(JFileChooser) - Method in class javax.swing.plaf.basic.BasicFileChooserUI
uninstallComponents() - Method in class javax.swing.plaf.basic.BasicInternalFrameUI
uninstallComponents(JLabel) - Method in class javax.swing.plaf.basic.BasicLabelUI
uninstallComponents(JMenuItem) - Method in class javax.swing.plaf.basic.BasicMenuItemUI
uninstallComponents() - Method in class javax.swing.plaf.basic.BasicOptionPaneUI
uninstallComponents(JRootPane) - Method in class javax.swing.plaf.basic.BasicRootPaneUI
uninstallComponents() - Method in class javax.swing.plaf.basic.BasicScrollBarUI
uninstallComponents() - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI
Removes any installed subcomponents from the JTabbedPane.
uninstallComponents() - Method in class javax.swing.plaf.basic.BasicToolBarUI
uninstallComponents() - Method in class javax.swing.plaf.basic.BasicTreeUI
Uninstalls the renderer pane.
uninstallComponents() - Method in class javax.swing.plaf.metal.MetalDesktopIconUI
uninstallComponents(JFileChooser) - Method in class javax.swing.plaf.metal.MetalFileChooserUI
uninstallComponents() - Method in class javax.swing.plaf.metal.MetalInternalFrameUI
uninstallComponents() - Method in class javax.swing.plaf.synth.SynthInternalFrameUI
uninstallComponents() - Method in class javax.swing.plaf.synth.SynthToolBarUI
uninstallDefaultChoosers() - Method in class javax.swing.plaf.basic.BasicColorChooserUI
uninstallDefaults(AbstractButton) - Method in class javax.swing.plaf.basic.BasicButtonUI
uninstallDefaults() - Method in class javax.swing.plaf.basic.BasicColorChooserUI
uninstallDefaults() - Method in class javax.swing.plaf.basic.BasicComboBoxUI
Uninstalls the default colors, default font, default renderer, and default editor from the combo box.
uninstallDefaults() - Method in class javax.swing.plaf.basic.BasicDesktopIconUI
uninstallDefaults() - Method in class javax.swing.plaf.basic.BasicDesktopPaneUI
uninstallDefaults(JFileChooser) - Method in class javax.swing.plaf.basic.BasicFileChooserUI
uninstallDefaults() - Method in class javax.swing.plaf.basic.BasicInternalFrameTitlePane
uninstallDefaults() - Method in class javax.swing.plaf.basic.BasicInternalFrameUI
uninstallDefaults(JLabel) - Method in class javax.swing.plaf.basic.BasicLabelUI
uninstallDefaults() - Method in class javax.swing.plaf.basic.BasicListUI
Sets the list properties that have not been explicitly overridden to null.
uninstallDefaults() - Method in class javax.swing.plaf.basic.BasicMenuBarUI
uninstallDefaults() - Method in class javax.swing.plaf.basic.BasicMenuItemUI
uninstallDefaults() - Method in class javax.swing.plaf.basic.BasicMenuUI
uninstallDefaults() - Method in class javax.swing.plaf.basic.BasicOptionPaneUI
uninstallDefaults(JPanel) - Method in class javax.swing.plaf.basic.BasicPanelUI
uninstallDefaults() - Method in class javax.swing.plaf.basic.BasicPopupMenuUI
uninstallDefaults() - Method in class javax.swing.plaf.basic.BasicProgressBarUI
uninstallDefaults(AbstractButton) - Method in class javax.swing.plaf.basic.BasicRadioButtonUI
uninstallDefaults(JRootPane) - Method in class javax.swing.plaf.basic.BasicRootPaneUI
uninstallDefaults() - Method in class javax.swing.plaf.basic.BasicScrollBarUI
uninstallDefaults(JScrollPane) - Method in class javax.swing.plaf.basic.BasicScrollPaneUI
uninstallDefaults(JSeparator) - Method in class javax.swing.plaf.basic.BasicSeparatorUI
uninstallDefaults(JSlider) - Method in class javax.swing.plaf.basic.BasicSliderUI
uninstallDefaults() - Method in class javax.swing.plaf.basic.BasicSpinnerUI
Sets the JSpinner's layout manager to null.
uninstallDefaults() - Method in class javax.swing.plaf.basic.BasicSplitPaneUI
Uninstalls the UI defaults.
uninstallDefaults() - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI
uninstallDefaults() - Method in class javax.swing.plaf.basic.BasicTableHeaderUI
uninstallDefaults() - Method in class javax.swing.plaf.basic.BasicTableUI
uninstallDefaults() - Method in class javax.swing.plaf.basic.BasicTextUI
Sets the component properties that have not been explicitly overridden to null.
uninstallDefaults() - Method in class javax.swing.plaf.basic.BasicToolBarUI
uninstallDefaults(JComponent) - Method in class javax.swing.plaf.basic.BasicToolTipUI
uninstallDefaults() - Method in class javax.swing.plaf.basic.BasicTreeUI
uninstallDefaults(JComponent) - Method in class javax.swing.plaf.basic.BasicViewportUI
uninstallDefaults(AbstractButton) - Method in class javax.swing.plaf.metal.MetalButtonUI
uninstallDefaults(AbstractButton) - Method in class javax.swing.plaf.metal.MetalCheckBoxUI
uninstallDefaults() - Method in class javax.swing.plaf.metal.MetalInternalFrameTitlePane
uninstallDefaults(AbstractButton) - Method in class javax.swing.plaf.metal.MetalRadioButtonUI
uninstallDefaults(AbstractButton) - Method in class javax.swing.plaf.metal.MetalToggleButtonUI
uninstallDefaults(AbstractButton) - Method in class javax.swing.plaf.synth.SynthButtonUI
uninstallDefaults() - Method in class javax.swing.plaf.synth.SynthColorChooserUI
uninstallDefaults() - Method in class javax.swing.plaf.synth.SynthComboBoxUI
uninstallDefaults() - Method in class javax.swing.plaf.synth.SynthDesktopIconUI
uninstallDefaults() - Method in class javax.swing.plaf.synth.SynthDesktopPaneUI
uninstallDefaults() - Method in class javax.swing.plaf.synth.SynthEditorPaneUI
uninstallDefaults() - Method in class javax.swing.plaf.synth.SynthInternalFrameUI
uninstallDefaults(JLabel) - Method in class javax.swing.plaf.synth.SynthLabelUI
uninstallDefaults() - Method in class javax.swing.plaf.synth.SynthListUI
uninstallDefaults() - Method in class javax.swing.plaf.synth.SynthMenuBarUI
uninstallDefaults() - Method in class javax.swing.plaf.synth.SynthMenuItemUI
uninstallDefaults() - Method in class javax.swing.plaf.synth.SynthMenuUI
uninstallDefaults() - Method in class javax.swing.plaf.synth.SynthOptionPaneUI
uninstallDefaults(JPanel) - Method in class javax.swing.plaf.synth.SynthPanelUI
uninstallDefaults() - Method in class javax.swing.plaf.synth.SynthPopupMenuUI
uninstallDefaults() - Method in class javax.swing.plaf.synth.SynthProgressBarUI
uninstallDefaults(JRootPane) - Method in class javax.swing.plaf.synth.SynthRootPaneUI
uninstallDefaults() - Method in class javax.swing.plaf.synth.SynthScrollBarUI
uninstallDefaults(JScrollPane) - Method in class javax.swing.plaf.synth.SynthScrollPaneUI
uninstallDefaults(JSeparator) - Method in class javax.swing.plaf.synth.SynthSeparatorUI
Uninstalls default setting.
uninstallDefaults(JSlider) - Method in class javax.swing.plaf.synth.SynthSliderUI
Uninstalls default setting.
uninstallDefaults() - Method in class javax.swing.plaf.synth.SynthSpinnerUI
Sets the JSpinner's layout manager to null.
uninstallDefaults() - Method in class javax.swing.plaf.synth.SynthSplitPaneUI
Uninstalls the UI defaults.
uninstallDefaults(SynthContext) - Method in class javax.swing.plaf.synth.SynthStyle
Uninstalls any state that this style installed on the JComponent from context.
uninstallDefaults() - Method in class javax.swing.plaf.synth.SynthTabbedPaneUI
uninstallDefaults() - Method in class javax.swing.plaf.synth.SynthTableHeaderUI
uninstallDefaults() - Method in class javax.swing.plaf.synth.SynthTableUI
uninstallDefaults() - Method in class javax.swing.plaf.synth.SynthTextAreaUI
uninstallDefaults() - Method in class javax.swing.plaf.synth.SynthTextFieldUI
uninstallDefaults() - Method in class javax.swing.plaf.synth.SynthToolBarUI
uninstallDefaults(JComponent) - Method in class javax.swing.plaf.synth.SynthToolTipUI
uninstallDefaults() - Method in class javax.swing.plaf.synth.SynthTreeUI
uninstallDefaults(JComponent) - Method in class javax.swing.plaf.synth.SynthViewportUI
Uninstalls defaults from a viewport.
uninstallDesktopManager() - Method in class javax.swing.plaf.basic.BasicDesktopPaneUI
uninstallDesktopManager() - Method in class javax.swing.plaf.synth.SynthDesktopPaneUI
uninstallIcons(JFileChooser) - Method in class javax.swing.plaf.basic.BasicFileChooserUI
uninstallingUI() - Method in class javax.swing.plaf.basic.BasicComboPopup
Called when the UI is uninstalling.
uninstallingUI() - Method in interface javax.swing.plaf.basic.ComboPopup
Called to inform the ComboPopup that the UI is uninstalling.
uninstallKeyboardActions(JComponent) - Method in class javax.swing.plaf.basic.BasicButtonListener
Unregister's default key actions
uninstallKeyboardActions(AbstractButton) - Method in class javax.swing.plaf.basic.BasicButtonUI
uninstallKeyboardActions() - Method in class javax.swing.plaf.basic.BasicComboBoxUI
Removes the focus InputMap and ActionMap.
uninstallKeyboardActions() - Method in class javax.swing.plaf.basic.BasicComboPopup
uninstallKeyboardActions() - Method in class javax.swing.plaf.basic.BasicDesktopPaneUI
uninstallKeyboardActions() - Method in class javax.swing.plaf.basic.BasicInternalFrameUI
uninstallKeyboardActions(JLabel) - Method in class javax.swing.plaf.basic.BasicLabelUI
uninstallKeyboardActions() - Method in class javax.swing.plaf.basic.BasicListUI
Unregisters keyboard actions installed from installKeyboardActions.
uninstallKeyboardActions() - Method in class javax.swing.plaf.basic.BasicMenuBarUI
uninstallKeyboardActions() - Method in class javax.swing.plaf.basic.BasicMenuItemUI
uninstallKeyboardActions() - Method in class javax.swing.plaf.basic.BasicMenuUI
uninstallKeyboardActions() - Method in class javax.swing.plaf.basic.BasicOptionPaneUI
uninstallKeyboardActions() - Method in class javax.swing.plaf.basic.BasicPopupMenuUI
uninstallKeyboardActions(JRootPane) - Method in class javax.swing.plaf.basic.BasicRootPaneUI
uninstallKeyboardActions() - Method in class javax.swing.plaf.basic.BasicScrollBarUI
uninstallKeyboardActions(JScrollPane) - Method in class javax.swing.plaf.basic.BasicScrollPaneUI
uninstallKeyboardActions(JSlider) - Method in class javax.swing.plaf.basic.BasicSliderUI
uninstallKeyboardActions() - Method in class javax.swing.plaf.basic.BasicSplitPaneUI
Uninstalls the keyboard actions for the UI.
uninstallKeyboardActions() - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI
uninstallKeyboardActions() - Method in class javax.swing.plaf.basic.BasicTableHeaderUI
Unregisters default key actions.
uninstallKeyboardActions() - Method in class javax.swing.plaf.basic.BasicTableUI
uninstallKeyboardActions() - Method in class javax.swing.plaf.basic.BasicTextUI
uninstallKeyboardActions() - Method in class javax.swing.plaf.basic.BasicToolBarUI
uninstallKeyboardActions() - Method in class javax.swing.plaf.basic.BasicTreeUI
uninstallKeyboardActions() - Method in class javax.swing.plaf.metal.MetalInternalFrameUI
uninstallListeners(AbstractButton) - Method in class javax.swing.plaf.basic.BasicButtonUI
uninstallListeners() - Method in class javax.swing.plaf.basic.BasicColorChooserUI
uninstallListeners() - Method in class javax.swing.plaf.basic.BasicComboBoxUI
Removes the installed listeners from the combo box and its model.
uninstallListeners() - Method in class javax.swing.plaf.basic.BasicDesktopIconUI
uninstallListeners() - Method in class javax.swing.plaf.basic.BasicDesktopPaneUI
Uninstalls the PropertyChangeListener returned from createPropertyChangeListener from the JDesktopPane.
uninstallListeners(JFileChooser) - Method in class javax.swing.plaf.basic.BasicFileChooserUI
uninstallListeners() - Method in class javax.swing.plaf.basic.BasicInternalFrameTitlePane
uninstallListeners() - Method in class javax.swing.plaf.basic.BasicInternalFrameUI
uninstallListeners(JLabel) - Method in class javax.swing.plaf.basic.BasicLabelUI
uninstallListeners() - Method in class javax.swing.plaf.basic.BasicListUI
Removes the listeners from the JList, its model, and its selectionModel.
uninstallListeners() - Method in class javax.swing.plaf.basic.BasicMenuBarUI
uninstallListeners() - Method in class javax.swing.plaf.basic.BasicMenuItemUI
uninstallListeners() - Method in class javax.swing.plaf.basic.BasicMenuUI
uninstallListeners() - Method in class javax.swing.plaf.basic.BasicOptionPaneUI
uninstallListeners() - Method in class javax.swing.plaf.basic.BasicPopupMenuUI
uninstallListeners() - Method in class javax.swing.plaf.basic.BasicProgressBarUI
Removes all listeners installed by this object.
uninstallListeners(JRootPane) - Method in class javax.swing.plaf.basic.BasicRootPaneUI
uninstallListeners() - Method in class javax.swing.plaf.basic.BasicScrollBarUI
uninstallListeners(JComponent) - Method in class javax.swing.plaf.basic.BasicScrollPaneUI
uninstallListeners(JSeparator) - Method in class javax.swing.plaf.basic.BasicSeparatorUI
uninstallListeners(JSlider) - Method in class javax.swing.plaf.basic.BasicSliderUI
uninstallListeners() - Method in class javax.swing.plaf.basic.BasicSpinnerUI
Removes the PropertyChangeListener added by installListeners.
uninstallListeners() - Method in class javax.swing.plaf.basic.BasicSplitPaneUI
Uninstalls the event listeners for the UI.
uninstallListeners() - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI
uninstallListeners() - Method in class javax.swing.plaf.basic.BasicTableHeaderUI
uninstallListeners() - Method in class javax.swing.plaf.basic.BasicTableUI
uninstallListeners() - Method in class javax.swing.plaf.basic.BasicTextUI
Uninstalls listeners for the UI.
uninstallListeners() - Method in class javax.swing.plaf.basic.BasicToolBarUI
uninstallListeners(JComponent) - Method in class javax.swing.plaf.basic.BasicToolTipUI
uninstallListeners() - Method in class javax.swing.plaf.basic.BasicTreeUI
uninstallListeners() - Method in class javax.swing.plaf.metal.MetalDesktopIconUI
uninstallListeners() - Method in class javax.swing.plaf.metal.MetalInternalFrameUI
uninstallListeners(JComponent) - Method in class javax.swing.plaf.metal.MetalScrollPaneUI
uninstallListeners(JScrollPane) - Method in class javax.swing.plaf.metal.MetalScrollPaneUI
Deprecated.
- Replaced by MetalScrollPaneUI.uninstallListeners(JComponent)
uninstallListeners() - Method in class javax.swing.plaf.metal.MetalToolBarUI
uninstallListeners(AbstractButton) - Method in class javax.swing.plaf.synth.SynthButtonUI
uninstallListeners() - Method in class javax.swing.plaf.synth.SynthColorChooserUI
uninstallListeners() - Method in class javax.swing.plaf.synth.SynthComboBoxUI
uninstallListeners() - Method in class javax.swing.plaf.synth.SynthDesktopIconUI
uninstallListeners() - Method in class javax.swing.plaf.synth.SynthDesktopPaneUI
uninstallListeners() - Method in class javax.swing.plaf.synth.SynthInternalFrameUI
uninstallListeners() - Method in class javax.swing.plaf.synth.SynthListUI
uninstallListeners() - Method in class javax.swing.plaf.synth.SynthMenuBarUI
uninstallListeners() - Method in class javax.swing.plaf.synth.SynthMenuItemUI
uninstallListeners() - Method in class javax.swing.plaf.synth.SynthMenuUI
uninstallListeners() - Method in class javax.swing.plaf.synth.SynthOptionPaneUI
uninstallListeners(JPanel) - Method in class javax.swing.plaf.synth.SynthPanelUI
Uninstalls listeners from the panel.
uninstallListeners() - Method in class javax.swing.plaf.synth.SynthPopupMenuUI
uninstallListeners() - Method in class javax.swing.plaf.synth.SynthProgressBarUI
uninstallListeners() - Method in class javax.swing.plaf.synth.SynthScrollBarUI
uninstallListeners(JComponent) - Method in class javax.swing.plaf.synth.SynthScrollPaneUI
uninstallListeners(JSeparator) - Method in class javax.swing.plaf.synth.SynthSeparatorUI
Uninstalls listeners.
uninstallListeners(JSlider) - Method in class javax.swing.plaf.synth.SynthSliderUI
uninstallListeners() - Method in class javax.swing.plaf.synth.SynthSpinnerUI
uninstallListeners() - Method in class javax.swing.plaf.synth.SynthSplitPaneUI
Uninstalls the event listeners from the UI.
uninstallListeners() - Method in class javax.swing.plaf.synth.SynthTabbedPaneUI
uninstallListeners() - Method in class javax.swing.plaf.synth.SynthTableHeaderUI
uninstallListeners() - Method in class javax.swing.plaf.synth.SynthTableUI
uninstallListeners() - Method in class javax.swing.plaf.synth.SynthToolBarUI
uninstallListeners(JComponent) - Method in class javax.swing.plaf.synth.SynthToolTipUI
uninstallListeners() - Method in class javax.swing.plaf.synth.SynthTreeUI
uninstallListeners(JComponent) - Method in class javax.swing.plaf.synth.SynthViewportUI
Uninstalls listeners from the viewport.
uninstallPreviewPanel() - Method in class javax.swing.plaf.basic.BasicColorChooserUI
Removes installed preview panel from the UI delegate.
uninstallStrings(JFileChooser) - Method in class javax.swing.plaf.basic.BasicFileChooserUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicButtonUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicColorChooserUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicComboBoxUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicDesktopIconUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicDesktopPaneUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicEditorPaneUI
Deinstalls the UI for a component.
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicFileChooserUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicInternalFrameUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicLabelUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicListUI
Uninitializes this.list by calling uninstallListeners(), uninstallKeyboardActions(), and uninstallDefaults() in order.
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicMenuBarUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicMenuItemUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicOptionPaneUI
Removes the receiver from the L&F controller of the passed in split pane.
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicPanelUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicPopupMenuUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicProgressBarUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicRootPaneUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicScrollBarUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicScrollPaneUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicSeparatorUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicSliderUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicSpinnerUI
Calls uninstallDefaults, uninstallListeners, and then removes all of the spinners children.
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicSplitPaneUI
Uninstalls the UI.
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicTabbedPaneUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicTableHeaderUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicTableUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicTextUI
Deinstalls the UI for a component.
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicToolBarUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicToolTipUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicTreeUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.basic.BasicViewportUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.ComponentUI
Reverses configuration which was done on the specified component during installUI.
uninstallUI(JComponent) - Method in class javax.swing.plaf.LayerUI
Reverses the configuration which was previously set in the LayerUI.installUI(JComponent) method.
uninstallUI(JComponent) - Method in class javax.swing.plaf.metal.MetalFileChooserUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.metal.MetalInternalFrameUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.metal.MetalMenuBarUI
Reverses configuration which was done on the specified component during installUI.
uninstallUI(JComponent) - Method in class javax.swing.plaf.metal.MetalRootPaneUI
Invokes supers implementation to uninstall any of its state.
uninstallUI(JComponent) - Method in class javax.swing.plaf.metal.MetalScrollPaneUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.metal.MetalToolBarUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.metal.MetalToolTipUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.metal.MetalTreeUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiButtonUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiColorChooserUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiComboBoxUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiDesktopIconUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiDesktopPaneUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiFileChooserUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiInternalFrameUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiLabelUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiListUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiMenuBarUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiMenuItemUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiOptionPaneUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiPanelUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiPopupMenuUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiProgressBarUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiRootPaneUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiScrollBarUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiScrollPaneUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiSeparatorUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiSliderUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiSpinnerUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiSplitPaneUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiTabbedPaneUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiTableHeaderUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiTableUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiTextUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiToolBarUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiToolTipUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiTreeUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.multi.MultiViewportUI
Invokes the uninstallUI method on each UI handled by this object.
uninstallUI(JComponent) - Method in class javax.swing.plaf.synth.SynthComboBoxUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.synth.SynthMenuItemUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.synth.SynthMenuUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.synth.SynthPanelUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.synth.SynthSeparatorUI
uninstallUI(JComponent) - Method in class javax.swing.plaf.synth.SynthViewportUI
union(Rectangle2D, Rectangle2D, Rectangle2D) - Static method in class java.awt.geom.Rectangle2D
Unions the pair of source Rectangle2D objects and puts the result into the specified destination Rectangle2D object.
union(Rectangle) - Method in class java.awt.Rectangle
Computes the union of this Rectangle with the specified Rectangle.
union(Descriptor...) - Static method in class javax.management.ImmutableDescriptor
Return an ImmutableDescriptor whose contents are the union of the given descriptors.
UNION - Static variable in class javax.xml.crypto.dsig.spec.XPathType.Filter
The union filter operation.
UnionMember - Class in org.omg.CORBA
A description in the Interface Repository of a member of an IDL union.
UnionMember() - Constructor for class org.omg.CORBA.UnionMember
Constructs a new UnionMember object with its fields initialized to null.
UnionMember(String, Any, TypeCode, IDLType) - Constructor for class org.omg.CORBA.UnionMember
Constructs a new UnionMember object with its fields initialized to the given values.
UnionMemberHelper - Class in org.omg.CORBA
The Helper for UnionMember.
UnionMemberHelper() - Constructor for class org.omg.CORBA.UnionMemberHelper
UNIQUE_ID - Static variable in class org.omg.PortableServer.IdUniquenessPolicyValue
UNIT_DECREMENT - Static variable in class java.awt.event.AdjustmentEvent
The unit decrement adjustment type.
UNIT_INCREMENT - Static variable in class java.awt.event.AdjustmentEvent
The unit increment adjustment type.
unitIncrement - Variable in class javax.swing.JScrollBar
UNIX_LINES - Static variable in class java.util.regex.Pattern
Enables Unix lines mode.
UNKNOWN - Static variable in class java.awt.ComponentOrientation
Indicates that a component's orientation has not been set.
UNKNOWN - Static variable in class javax.accessibility.AccessibleRole
The object contains some Accessible information, but its role is not known.
UNKNOWN - Static variable in class javax.management.MBeanOperationInfo
Indicates that the impact of the operation is unknown or cannot be expressed using one of the other values.
UNKNOWN - Static variable in class javax.print.attribute.standard.JobState
The job state is unknown.
UNKNOWN - Static variable in class javax.print.attribute.standard.PrinterState
The printer state is unknown.
UNKNOWN - Exception in org.omg.CORBA
This exception is raised if an operation implementation throws a non-CORBA exception (such as an exception specific to the implementation's programming language), or if an operation raises a user exception that does not appear in the operation's raises expression.
UNKNOWN() - Constructor for exception org.omg.CORBA.UNKNOWN
Constructs an UNKNOWN exception with a default minor code of 0, a completion state of CompletionStatus.COMPLETED_NO, and a null description.
UNKNOWN(String) - Constructor for exception org.omg.CORBA.UNKNOWN
Constructs an UNKNOWN exception with the specified description message, a minor code of 0, and a completion state of COMPLETED_NO.
UNKNOWN(int, CompletionStatus) - Constructor for exception org.omg.CORBA.UNKNOWN
Constructs an UNKNOWN exception with the specified minor code and completion status.
UNKNOWN(String, int, CompletionStatus) - Constructor for exception org.omg.CORBA.UNKNOWN
Constructs an UNKNOWN exception with the specified description message, minor code, and completion status.
UNKNOWN - Interface in org.omg.PortableInterceptor
org/omg/PortableInterceptor/UNKNOWN.java .
unknown_adapter(POA, String) - Method in interface org.omg.PortableServer.AdapterActivatorOperations
This operation is invoked when the ORB receives a request for an object reference that identifies a target POA that does not exist.
UNKNOWN_ATTRIBUTE - Static variable in interface java.util.jar.Pack200.Packer
Indicates the action to take when a class-file containing an unknown attribute is encountered.
UNKNOWN_LENGTH - Static variable in class javax.sound.midi.MidiFileFormat
Represents unknown length.
UNKNOWN_NUMBER_OF_PAGES - Static variable in interface java.awt.print.Pageable
This constant is returned from the getNumberOfPages method if a Pageable implementation does not know the number of pages in its set.
UnknownAnnotationValueException - Exception in javax.lang.model.element
Indicates that an unknown kind of annotation value was encountered.
UnknownAnnotationValueException(AnnotationValue, Object) - Constructor for exception javax.lang.model.element.UnknownAnnotationValueException
Creates a new UnknownAnnotationValueException.
UnknownElementException - Exception in javax.lang.model.element
Indicates that an unknown kind of element was encountered.
UnknownElementException(Element, Object) - Constructor for exception javax.lang.model.element.UnknownElementException
Creates a new UnknownElementException.
UnknownEncoding - Exception in org.omg.IOP.CodecFactoryPackage
org/omg/IOP/CodecFactoryPackage/UnknownEncoding.java .
UnknownEncoding() - Constructor for exception org.omg.IOP.CodecFactoryPackage.UnknownEncoding
UnknownEncoding(String) - Constructor for exception org.omg.IOP.CodecFactoryPackage.UnknownEncoding
UnknownEncodingHelper - Class in org.omg.IOP.CodecFactoryPackage
org/omg/IOP/CodecFactoryPackage/UnknownEncodingHelper.java .
UnknownEncodingHelper() - Constructor for class org.omg.IOP.CodecFactoryPackage.UnknownEncodingHelper
UnknownEntityException - Exception in javax.lang.model
Superclass of exceptions which indicate that an unknown kind of entity was encountered.
UnknownEntityException(String) - Constructor for exception javax.lang.model.UnknownEntityException
Creates a new UnknownEntityException with the specified detail message.
UnknownError - Error in java.lang
Thrown when an unknown but serious exception has occurred in the Java Virtual Machine.
UnknownError() - Constructor for error java.lang.UnknownError
Constructs an UnknownError with no detail message.
UnknownError(String) - Constructor for error java.lang.UnknownError
Constructs an UnknownError with the specified detail message.
UnknownException - Exception in org.omg.CORBA.portable
The org.omg.CORBA.portable.UnknownException is used for reporting unknown exceptions between ties and ORBs and between ORBs and stubs.
UnknownException(Throwable) - Constructor for exception org.omg.CORBA.portable.UnknownException
Constructs an UnknownException object.
UnknownFormatConversionException - Exception in java.util
Unchecked exception thrown when an unknown conversion is given.
UnknownFormatConversionException(String) - Constructor for exception java.util.UnknownFormatConversionException
Constructs an instance of this class with the unknown conversion.
UnknownFormatFlagsException - Exception in java.util
Unchecked exception thrown when an unknown flag is given.
UnknownFormatFlagsException(String) - Constructor for exception java.util.UnknownFormatFlagsException
Constructs an instance of this class with the specified flags.
UnknownGroupException - Exception in java.rmi.activation
An UnknownGroupException is thrown by methods of classes and interfaces in the java.rmi.activation package when the ActivationGroupID parameter to the method is determined to be invalid, i.e., not known by the ActivationSystem.
UnknownGroupException(String) - Constructor for exception java.rmi.activation.UnknownGroupException
Constructs an UnknownGroupException with the specified detail message.
UnknownHostException - Exception in java.net
Thrown to indicate that the IP address of a host could not be determined.
UnknownHostException(String) - Constructor for exception java.net.UnknownHostException
Constructs a new UnknownHostException with the specified detail message.
UnknownHostException() - Constructor for exception java.net.UnknownHostException
Constructs a new UnknownHostException with no detail message.
UnknownHostException - Exception in java.rmi
An UnknownHostException is thrown if a java.net.UnknownHostException occurs while creating a connection to the remote host for a remote method call.
UnknownHostException(String) - Constructor for exception java.rmi.UnknownHostException
Constructs an UnknownHostException with the specified detail message.
UnknownHostException(String, Exception) - Constructor for exception java.rmi.UnknownHostException
Constructs an UnknownHostException with the specified detail message and nested exception.
UnknownObjectException - Exception in java.rmi.activation
An UnknownObjectException is thrown by methods of classes and interfaces in the java.rmi.activation package when the ActivationID parameter to the method is determined to be invalid.
UnknownObjectException(String) - Constructor for exception java.rmi.activation.UnknownObjectException
Constructs an UnknownObjectException with the specified detail message.
UnknownServiceException - Exception in java.net
Thrown to indicate that an unknown service exception has occurred.
UnknownServiceException() - Constructor for exception java.net.UnknownServiceException
Constructs a new UnknownServiceException with no detail message.
UnknownServiceException(String) - Constructor for exception java.net.UnknownServiceException
Constructs a new UnknownServiceException with the specified detail message.
UnknownTypeException - Exception in javax.lang.model.type
Indicates that an unknown kind of type was encountered.
UnknownTypeException(TypeMirror, Object) - Constructor for exception javax.lang.model.type.UnknownTypeException
Creates a new UnknownTypeException.The p parameter may be used to pass in an additional argument with information about the context in which the unknown type was encountered; for example, the visit methods of TypeVisitor may pass in their additional parameter.
UnknownUserException - Exception in org.omg.CORBA
A class that contains user exceptions returned by the server.
UnknownUserException() - Constructor for exception org.omg.CORBA.UnknownUserException
Constructs an UnknownUserException object.
UnknownUserException(Any) - Constructor for exception org.omg.CORBA.UnknownUserException
Constructs an UnknownUserException object that contains the given Any object.
UnknownUserExceptionHelper - Class in org.omg.CORBA
The Helper for UnknownUserException.
UnknownUserExceptionHelper() - Constructor for class org.omg.CORBA.UnknownUserExceptionHelper
UnknownUserExceptionHolder - Class in org.omg.CORBA
The Holder for UnknownUserException.
UnknownUserExceptionHolder() - Constructor for class org.omg.CORBA.UnknownUserExceptionHolder
UnknownUserExceptionHolder(UnknownUserException) - Constructor for class org.omg.CORBA.UnknownUserExceptionHolder
UNLIMITED - Static variable in class java.math.MathContext
A MathContext object whose settings have the values required for unlimited precision arithmetic.
unloadAllInstruments(Soundbank) - Method in interface javax.sound.midi.Synthesizer
Unloads all instruments contained in the specified Soundbank.
unloadInstrument(Instrument) - Method in interface javax.sound.midi.Synthesizer
Unloads a particular instrument.
unloadInstruments(Soundbank, Patch[]) - Method in interface javax.sound.midi.Synthesizer
Unloads the instruments referenced by the specified patches, from the MIDI sound bank specified.
unloadZone(View) - Method in class javax.swing.text.ZoneView
Unload a zone (Convert the zone to its memory saving state).
unlock() - Method in interface java.util.concurrent.locks.Lock
Releases the lock.
unlock() - Method in class java.util.concurrent.locks.ReentrantLock
Attempts to release this lock.
unlock() - Method in class java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock
Attempts to release this lock.
unlock() - Method in class java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock
Attempts to release this lock.
unmappableCharacterAction() - Method in class java.nio.charset.CharsetDecoder
Returns this decoder's current action for unmappable-character errors.
unmappableCharacterAction() - Method in class java.nio.charset.CharsetEncoder
Returns this encoder's current action for unmappable-character errors.
UnmappableCharacterException - Exception in java.nio.charset
Checked exception thrown when an input character (or byte) sequence is valid but cannot be mapped to an output byte (or character) sequence.
UnmappableCharacterException(int) - Constructor for exception java.nio.charset.UnmappableCharacterException
unmappableForLength(int) - Static method in class java.nio.charset.CoderResult
Static factory method that returns the unique result object describing an unmappable-character error of the given length.
unmarshal(String) - Method in class javax.xml.bind.annotation.adapters.CollapsedStringAdapter
Removes leading and trailing whitespaces of the string given as the parameter, then truncate any sequnce of tab, CR, LF, and SP by a single whitespace character ' '.
unmarshal(String) - Method in class javax.xml.bind.annotation.adapters.HexBinaryAdapter
unmarshal(String) - Method in class javax.xml.bind.annotation.adapters.NormalizedStringAdapter
Replace any tab, CR, and LF by a whitespace character ' ', as specified in the whitespace facet 'replace'
unmarshal(ValueType) - Method in class javax.xml.bind.annotation.adapters.XmlAdapter
Convert a value type to a bound type.
unmarshal(XmlNode) - Method in class javax.xml.bind.Binder
Unmarshal XML infoset view to a JAXB object tree.
unmarshal(XmlNode, Class<T>) - Method in class javax.xml.bind.Binder
Unmarshal XML root element by provided declaredType to a JAXB object tree.
unmarshal(Source) - Method in class javax.xml.bind.helpers.AbstractUnmarshallerImpl
unmarshal(XMLReader, InputSource) - Method in class javax.xml.bind.helpers.AbstractUnmarshallerImpl
Unmarshals an object by using the specified XMLReader and the InputSource.
unmarshal(InputSource) - Method in class javax.xml.bind.helpers.AbstractUnmarshallerImpl
unmarshal(URL) - Method in class javax.xml.bind.helpers.AbstractUnmarshallerImpl
unmarshal(File) - Method in class javax.xml.bind.helpers.AbstractUnmarshallerImpl
unmarshal(InputStream) - Method in class javax.xml.bind.helpers.AbstractUnmarshallerImpl
unmarshal(Reader) - Method in class javax.xml.bind.helpers.AbstractUnmarshallerImpl
unmarshal(XMLEventReader) - Method in class javax.xml.bind.helpers.AbstractUnmarshallerImpl
unmarshal(XMLStreamReader) - Method in class javax.xml.bind.helpers.AbstractUnmarshallerImpl
unmarshal(Node, Class<T>) - Method in class javax.xml.bind.helpers.AbstractUnmarshallerImpl
unmarshal(Source, Class<T>) - Method in class javax.xml.bind.helpers.AbstractUnmarshallerImpl
unmarshal(XMLStreamReader, Class<T>) - Method in class javax.xml.bind.helpers.AbstractUnmarshallerImpl
unmarshal(XMLEventReader, Class<T>) - Method in class javax.xml.bind.helpers.AbstractUnmarshallerImpl
unmarshal(File, Class<T>) - Static method in class javax.xml.bind.JAXB
Reads in a Java object tree from the given XML input.
unmarshal(URL, Class<T>) - Static method in class javax.xml.bind.JAXB
Reads in a Java object tree from the given XML input.
unmarshal(URI, Class<T>) - Static method in class javax.xml.bind.JAXB
Reads in a Java object tree from the given XML input.
unmarshal(String, Class<T>) - Static method in class javax.xml.bind.JAXB
Reads in a Java object tree from the given XML input.
unmarshal(InputStream, Class<T>) - Static method in class javax.xml.bind.JAXB
Reads in a Java object tree from the given XML input.
unmarshal(Reader, Class<T>) - Static method in class javax.xml.bind.JAXB
Reads in a Java object tree from the given XML input.
unmarshal(Source, Class<T>) - Static method in class javax.xml.bind.JAXB
Reads in a Java object tree from the given XML input.
unmarshal(File) - Method in interface javax.xml.bind.Unmarshaller
Unmarshal XML data from the specified file and return the resulting content tree.
unmarshal(InputStream) - Method in interface javax.xml.bind.Unmarshaller
Unmarshal XML data from the specified InputStream and return the resulting content tree.
unmarshal(Reader) - Method in interface javax.xml.bind.Unmarshaller
Unmarshal XML data from the specified Reader and return the resulting content tree.
unmarshal(URL) - Method in interface javax.xml.bind.Unmarshaller
Unmarshal XML data from the specified URL and return the resulting content tree.
unmarshal(InputSource) - Method in interface javax.xml.bind.Unmarshaller
Unmarshal XML data from the specified SAX InputSource and return the resulting content tree.
unmarshal(Node) - Method in interface javax.xml.bind.Unmarshaller
Unmarshal global XML data from the specified DOM tree and return the resulting content tree.
unmarshal(Node, Class<T>) - Method in interface javax.xml.bind.Unmarshaller
Unmarshal XML data by JAXB mapped declaredType and return the resulting content tree.
unmarshal(Source) - Method in interface javax.xml.bind.Unmarshaller
Unmarshal XML data from the specified XML Source and return the resulting content tree.
unmarshal(Source, Class<T>) - Method in interface javax.xml.bind.Unmarshaller
Unmarshal XML data from the specified XML Source by declaredType and return the resulting content tree.
unmarshal(XMLStreamReader) - Method in interface javax.xml.bind.Unmarshaller
Unmarshal XML data from the specified pull parser and return the resulting content tree.
unmarshal(XMLStreamReader, Class<T>) - Method in interface javax.xml.bind.Unmarshaller
Unmarshal root element to JAXB mapped declaredType and return the resulting content tree.
unmarshal(XMLEventReader) - Method in interface javax.xml.bind.Unmarshaller
Unmarshal XML data from the specified pull parser and return the resulting content tree.
unmarshal(XMLEventReader, Class<T>) - Method in interface javax.xml.bind.Unmarshaller
Unmarshal root element to JAXB mapped declaredType and return the resulting content tree.
unmarshal(DataInputStream) - Method in interface org.omg.CORBA.CustomMarshal
Unmarshal method has to be implemented by the Customized Marshal class.
UnmarshalException - Exception in java.rmi
An UnmarshalException can be thrown while unmarshalling the parameters or results of a remote method call if any of the following conditions occur: if an exception occurs while unmarshalling the call header if the protocol for the return value is invalid if a java.io.IOException occurs unmarshalling parameters (on the server side) or the return value (on the client side).
UnmarshalException(String) - Constructor for exception java.rmi.UnmarshalException
Constructs an UnmarshalException with the specified detail message.
UnmarshalException(String, Exception) - Constructor for exception java.rmi.UnmarshalException
Constructs an UnmarshalException with the specified detail message and nested exception.
UnmarshalException - Exception in javax.xml.bind
This exception indicates that an error has occurred while performing an unmarshal operation that prevents the JAXB Provider from completing the operation.
UnmarshalException(String) - Constructor for exception javax.xml.bind.UnmarshalException
Construct an UnmarshalException with the specified detail message.
UnmarshalException(String, String) - Constructor for exception javax.xml.bind.UnmarshalException
Construct an UnmarshalException with the specified detail message and vendor specific errorCode.
UnmarshalException(Throwable) - Constructor for exception javax.xml.bind.UnmarshalException
Construct an UnmarshalException with a linkedException.
UnmarshalException(String, Throwable) - Constructor for exception javax.xml.bind.UnmarshalException
Construct an UnmarshalException with the specified detail message and linkedException.
UnmarshalException(String, String, Throwable) - Constructor for exception javax.xml.bind.UnmarshalException
Construct an UnmarshalException with the specified detail message, vendor specific errorCode, and linkedException.
unmarshalKeyInfo(XMLStructure) - Method in class javax.xml.crypto.dsig.keyinfo.KeyInfoFactory
Unmarshals a new KeyInfo instance from a mechanism-specific XMLStructure (ex: DOMStructure) instance.
Unmarshaller - Interface in javax.xml.bind
The Unmarshaller class governs the process of deserializing XML data into newly created Java content trees, optionally validating the XML data as it is unmarshalled.
Unmarshaller.Listener - Class in javax.xml.bind

Register an instance of an implementation of this class with Unmarshaller to externally listen for unmarshal events.

Unmarshaller.Listener() - Constructor for class javax.xml.bind.Unmarshaller.Listener
UnmarshallerHandler - Interface in javax.xml.bind
Unmarshaller implemented as SAX ContentHandler.
unmarshalXMLSignature(XMLValidateContext) - Method in class javax.xml.crypto.dsig.XMLSignatureFactory
Unmarshals a new XMLSignature instance from a mechanism-specific XMLValidateContext instance.
unmarshalXMLSignature(XMLStructure) - Method in class javax.xml.crypto.dsig.XMLSignatureFactory
Unmarshals a new XMLSignature instance from a mechanism-specific XMLStructure instance.
UnmodifiableClassException - Exception in java.lang.instrument
Thrown by an implementation of Instrumentation.redefineClasses when one of the specified classes cannot be modified.
UnmodifiableClassException() - Constructor for exception java.lang.instrument.UnmodifiableClassException
Constructs an UnmodifiableClassException with no detail message.
UnmodifiableClassException(String) - Constructor for exception java.lang.instrument.UnmodifiableClassException
Constructs an UnmodifiableClassException with the specified detail message.
unmodifiableCollection(Collection<? extends T>) - Static method in class java.util.Collections
Returns an unmodifiable view of the specified collection.
unmodifiableList(List<? extends T>) - Static method in class java.util.Collections
Returns an unmodifiable view of the specified list.
unmodifiableMap(Map<? extends K, ? extends V>) - Static method in class java.util.Collections
Returns an unmodifiable view of the specified map.
unmodifiableSet(Set<? extends T>) - Static method in class java.util.Collections
Returns an unmodifiable view of the specified set.
UnmodifiableSetException - Exception in javax.print.attribute
Thrown to indicate that the requested operation cannot be performed because the set is unmodifiable.
UnmodifiableSetException() - Constructor for exception javax.print.attribute.UnmodifiableSetException
Constructs an UnsupportedOperationException with no detail message.
UnmodifiableSetException(String) - Constructor for exception javax.print.attribute.UnmodifiableSetException
Constructs an UnmodifiableSetException with the specified detail message.
unmodifiableSortedMap(SortedMap<K, ? extends V>) - Static method in class java.util.Collections
Returns an unmodifiable view of the specified sorted map.
unmodifiableSortedSet(SortedSet<T>) - Static method in class java.util.Collections
Returns an unmodifiable view of the specified sorted set.
unmodifiableView(AttributeSet) - Static method in class javax.print.attribute.AttributeSetUtilities
Creates an unmodifiable view of the given attribute set.
unmodifiableView(DocAttributeSet) - Static method in class javax.print.attribute.AttributeSetUtilities
Creates an unmodifiable view of the given doc attribute set.
unmodifiableView(PrintRequestAttributeSet) - Static method in class javax.print.attribute.AttributeSetUtilities
Creates an unmodifiable view of the given print request attribute set.
unmodifiableView(PrintJobAttributeSet) - Static method in class javax.print.attribute.AttributeSetUtilities
Creates an unmodifiable view of the given print job attribute set.
unmodifiableView(PrintServiceAttributeSet) - Static method in class javax.print.attribute.AttributeSetUtilities
Creates an unmodifiable view of the given print service attribute set.
UNNECESSARY - Static variable in class java.awt.GraphicsConfigTemplate
Value used for "Enum" (Integer) type.
unpack(InputStream, JarOutputStream) - Method in interface java.util.jar.Pack200.Unpacker
Read a Pack200 archive, and write the encoded JAR to a JarOutputStream.
unpack(File, JarOutputStream) - Method in interface java.util.jar.Pack200.Unpacker
Read a Pack200 archive, and write the encoded JAR to a JarOutputStream.
unpark(Thread) - Static method in class java.util.concurrent.locks.LockSupport
Makes available the permit for the given thread, if it was not already available.
unparsedEntityDecl(String, String, String, String) - Method in interface org.xml.sax.DTDHandler
Receive notification of an unparsed entity declaration event.
unparsedEntityDecl(String, String, String, String) - Method in class org.xml.sax.HandlerBase
Deprecated.
Receive notification of an unparsed entity declaration.
unparsedEntityDecl(String, String, String, String) - Method in class org.xml.sax.helpers.DefaultHandler
Receive notification of an unparsed entity declaration.
unparsedEntityDecl(String, String, String, String) - Method in class org.xml.sax.helpers.XMLFilterImpl
Filter an unparsed entity declaration event.
unquote(String) - Static method in class javax.management.ObjectName
Returns an unquoted form of the given String.
unread(int) - Method in class java.io.PushbackInputStream
Pushes back a byte by copying it to the front of the pushback buffer.
unread(byte[], int, int) - Method in class java.io.PushbackInputStream
Pushes back a portion of an array of bytes by copying it to the front of the pushback buffer.
unread(byte[]) - Method in class java.io.PushbackInputStream
Pushes back an array of bytes by copying it to the front of the pushback buffer.
unread(int) - Method in class java.io.PushbackReader
Pushes back a single character by copying it to the front of the pushback buffer.
unread(char[], int, int) - Method in class java.io.PushbackReader
Pushes back a portion of an array of characters by copying it to the front of the pushback buffer.
unread(char[]) - Method in class java.io.PushbackReader
Pushes back an array of characters by copying it to the front of the pushback buffer.
UnrecoverableEntryException - Exception in java.security
This exception is thrown if an entry in the keystore cannot be recovered.
UnrecoverableEntryException() - Constructor for exception java.security.UnrecoverableEntryException
Constructs an UnrecoverableEntryException with no detail message.
UnrecoverableEntryException(String) - Constructor for exception java.security.UnrecoverableEntryException
Constructs an UnrecoverableEntryException with the specified detail message, which provides more information about why this exception has been thrown.
UnrecoverableKeyException - Exception in java.security
This exception is thrown if a key in the keystore cannot be recovered.
UnrecoverableKeyException() - Constructor for exception java.security.UnrecoverableKeyException
Constructs an UnrecoverableKeyException with no detail message.
UnrecoverableKeyException(String) - Constructor for exception java.security.UnrecoverableKeyException
Constructs an UnrecoverableKeyException with the specified detail message, which provides more information about why this exception has been thrown.
Unreferenced - Interface in java.rmi.server
A remote object implementation should implement the Unreferenced interface to receive notification when there are no more clients that reference that remote object.
unreferenced() - Method in interface java.rmi.server.Unreferenced
Called by the RMI runtime sometime after the runtime determines that the reference list, the list of clients referencing the remote object, becomes empty.
unreferenced() - Method in class javax.management.remote.rmi.RMIConnectionImpl
unreflect(Method) - Method in class java.lang.invoke.MethodHandles.Lookup
Makes a direct method handle to m, if the lookup class has permission.
unreflectConstructor(Constructor) - Method in class java.lang.invoke.MethodHandles.Lookup
Produces a method handle for a reflected constructor.
unreflectGetter(Field) - Method in class java.lang.invoke.MethodHandles.Lookup
Produces a method handle giving read access to a reflected field.
unreflectSetter(Field) - Method in class java.lang.invoke.MethodHandles.Lookup
Produces a method handle giving write access to a reflected field.
unreflectSpecial(Method, Class<?>) - Method in class java.lang.invoke.MethodHandles.Lookup
Produces a method handle for a reflected method.
unregister(ActivationID) - Static method in class java.rmi.activation.Activatable
Revokes previous registration for the activation descriptor associated with id.
unregister_value_factory(String) - Method in class org.omg.CORBA_2_3.ORB
unregisterComponent(JComponent) - Method in class javax.swing.ToolTipManager
Removes a component from tooltip control.
unregisterGroup(ActivationGroupID) - Method in interface java.rmi.activation.ActivationSystem
Remove the activation group.
unregisterKeyboardAction(KeyStroke) - Method in class javax.swing.JComponent
This method is now obsolete.
unregisterKeyboardActions() - Method in class javax.swing.plaf.basic.BasicDesktopPaneUI
unregisterListeners() - Method in class java.awt.dnd.DragGestureRecognizer
unregister this DragGestureRecognizer's Listeners with the Component subclasses must override this method
unregisterListeners() - Method in class java.awt.dnd.MouseDragGestureRecognizer
unregister this DragGestureRecognizer's Listeners with the Component subclasses must override this method
unregisterMBean(ObjectName) - Method in interface javax.management.MBeanServer
Unregisters an MBean from the MBean server.
unregisterMBean(ObjectName) - Method in interface javax.management.MBeanServerConnection
Unregisters an MBean from the MBean server.
unregisterMBean(ObjectName, Subject) - Method in interface javax.management.remote.rmi.RMIConnection
Handles the method MBeanServerConnection.unregisterMBean(ObjectName).
unregisterMBean(ObjectName, Subject) - Method in class javax.management.remote.rmi.RMIConnectionImpl
unregisterMBean(ObjectName, Subject) - Method in class javax.management.remote.rmi.RMIConnectionImpl_Stub
unregisterObject(ActivationID) - Method in interface java.rmi.activation.ActivationSystem
Remove the activation id and associated descriptor previously registered with the ActivationSystem; the object can no longer be activated via the object's activation id.
unregisterProvider(String) - Static method in class javax.sql.rowset.spi.SyncFactory
Removes the designated currently registered synchronization provider from the Factory SPI register.
UNREGISTRATION_NOTIFICATION - Static variable in class javax.management.MBeanServerNotification
Notification type denoting that an MBean has been unregistered.
UnresolvedAddressException - Exception in java.nio.channels
Unchecked exception thrown when an attempt is made to invoke a network operation upon an unresolved socket address.
UnresolvedAddressException() - Constructor for exception java.nio.channels.UnresolvedAddressException
Constructs an instance of this class.
UnresolvedPermission - Class in java.security
The UnresolvedPermission class is used to hold Permissions that were "unresolved" when the Policy was initialized.
UnresolvedPermission(String, String, String, Certificate[]) - Constructor for class java.security.UnresolvedPermission
Creates a new UnresolvedPermission containing the permission information needed later to actually create a Permission of the specified class, when the permission is resolved.
UnsatisfiedLinkError - Error in java.lang
Thrown if the Java Virtual Machine cannot find an appropriate native-language definition of a method declared native.
UnsatisfiedLinkError() - Constructor for error java.lang.UnsatisfiedLinkError
Constructs an UnsatisfiedLinkError with no detail message.
UnsatisfiedLinkError(String) - Constructor for error java.lang.UnsatisfiedLinkError
Constructs an UnsatisfiedLinkError with the specified detail message.
unscaledValue() - Method in class java.math.BigDecimal
Returns a BigInteger whose value is the unscaled value of this BigDecimal.
UNSELECTED_CONVERTED_TEXT_HIGHLIGHT - Static variable in class java.awt.im.InputMethodHighlight
Constant for the default highlight for unselected converted text.
UNSELECTED_RAW_TEXT_HIGHLIGHT - Static variable in class java.awt.im.InputMethodHighlight
Constant for the default highlight for unselected raw text.
UNSEQ_TOKEN - Static variable in exception org.ietf.jgss.GSSException
A later token has already been processed.
UNSET - Static variable in class javax.swing.Spring
An integer value signifying that a property value has not yet been calculated.
unsetCompression() - Method in class javax.imageio.ImageWriteParam
Removes any previous compression type and quality settings.
unsetCompression() - Method in class javax.imageio.plugins.jpeg.JPEGImageWriteParam
Removes any previous compression quality setting.
unsetDecodeTables() - Method in class javax.imageio.plugins.jpeg.JPEGImageReadParam
Removes any quantization and Huffman tables that are currently set.
unsetEncodeTables() - Method in class javax.imageio.plugins.jpeg.JPEGImageWriteParam
Removes any quantization and Huffman tables that are currently set.
unsetMatchColumn(int) - Method in interface javax.sql.rowset.Joinable
Unsets the designated column as the match column for this RowSet object.
unsetMatchColumn(int[]) - Method in interface javax.sql.rowset.Joinable
Unsets the designated columns as the match column for this RowSet object.
unsetMatchColumn(String) - Method in interface javax.sql.rowset.Joinable
Unsets the designated column as the match column for this RowSet object.
unsetMatchColumn(String[]) - Method in interface javax.sql.rowset.Joinable
Unsets the designated columns as the match columns for this RowSet object.
unsetOrdering(Class<T>, T, T) - Method in class javax.imageio.spi.ServiceRegistry
Sets a pairwise ordering between two service provider objects within a given category.
unsetTiling() - Method in class javax.imageio.ImageWriteParam
Removes any previous tile grid parameters specified by calls to setTiling.
UnsolicitedNotification - Interface in javax.naming.ldap
This interface represents an unsolicited notification as defined in RFC 2251.
UnsolicitedNotificationEvent - Class in javax.naming.ldap
This class represents an event fired in response to an unsolicited notification sent by the LDAP server.
UnsolicitedNotificationEvent(Object, UnsolicitedNotification) - Constructor for class javax.naming.ldap.UnsolicitedNotificationEvent
Constructs a new instance of UnsolicitedNotificationEvent.
UnsolicitedNotificationListener - Interface in javax.naming.ldap
This interface is for handling UnsolicitedNotificationEvent.
UNSPECIFIED_EVENT_TYPE_ERR - Static variable in exception org.w3c.dom.events.EventException
If the Event's type was not specified by initializing the event before the method was called.
UNSPECIFIED_OPTION - Static variable in class javax.security.auth.callback.ConfirmationCallback
Unspecified option type.
UNSUPPORTED_COMPRESSION - Static variable in class javax.print.attribute.standard.JobStateReason
The job was aborted by the system because the printer determined while attempting to decompress the document's data that the compression is actually not among those supported by the printer.
UNSUPPORTED_DOCUMENT_FORMAT - Static variable in class javax.print.attribute.standard.JobStateReason
The job was aborted by the system because the document data's document format (doc flavor) is not among those supported by the printer.
UNSUPPORTED_EMPTY_COLLECTION - Static variable in class java.security.Policy
A read-only empty PermissionCollection instance.
UNSUPPORTED_POLICY - Interface in org.omg.CORBA
One of the PolicyErrorCodes which would be filled if the requested Policy is understood to be valid by the ORB, but is not currently supported.
UNSUPPORTED_POLICY_VALUE - Interface in org.omg.CORBA
A PolicyErrorCode which would be filled if the value requested for the Policy is of a valid type and within the valid range for that type, but this valid value is not currently supported.
UnsupportedAddressTypeException - Exception in java.nio.channels
Unchecked exception thrown when an attempt is made to bind or connect to a socket address of a type that is not supported.
UnsupportedAddressTypeException() - Constructor for exception java.nio.channels.UnsupportedAddressTypeException
Constructs an instance of this class.
UnsupportedAudioFileException - Exception in javax.sound.sampled
An UnsupportedAudioFileException is an exception indicating that an operation failed because a file did not contain valid data of a recognized file type and format.
UnsupportedAudioFileException() - Constructor for exception javax.sound.sampled.UnsupportedAudioFileException
Constructs a UnsupportedAudioFileException that has null as its error detail message.
UnsupportedAudioFileException(String) - Constructor for exception javax.sound.sampled.UnsupportedAudioFileException
Constructs a UnsupportedAudioFileException that has the specified detail message.
UnsupportedCallbackException - Exception in javax.security.auth.callback
Signals that a CallbackHandler does not recognize a particular Callback.
UnsupportedCallbackException(Callback) - Constructor for exception javax.security.auth.callback.UnsupportedCallbackException
Constructs a UnsupportedCallbackException with no detail message.
UnsupportedCallbackException(Callback, String) - Constructor for exception javax.security.auth.callback.UnsupportedCallbackException
Constructs a UnsupportedCallbackException with the specified detail message.
UnsupportedCharsetException - Exception in java.nio.charset
Unchecked exception thrown when no support is available for a requested charset.
UnsupportedCharsetException(String) - Constructor for exception java.nio.charset.UnsupportedCharsetException
Constructs an instance of this class.
UnsupportedClassVersionError - Error in java.lang
Thrown when the Java Virtual Machine attempts to read a class file and determines that the major and minor version numbers in the file are not supported.
UnsupportedClassVersionError() - Constructor for error java.lang.UnsupportedClassVersionError
Constructs a UnsupportedClassVersionError with no detail message.
UnsupportedClassVersionError(String) - Constructor for error java.lang.UnsupportedClassVersionError
Constructs a UnsupportedClassVersionError with the specified detail message.
UnsupportedDataTypeException - Exception in javax.activation
Signals that the requested operation does not support the requested data type.
UnsupportedDataTypeException() - Constructor for exception javax.activation.UnsupportedDataTypeException
Constructs an UnsupportedDataTypeException with no detail message.
UnsupportedDataTypeException(String) - Constructor for exception javax.activation.UnsupportedDataTypeException
Constructs an UnsupportedDataTypeException with the specified message.
UnsupportedEncodingException - Exception in java.io
The Character Encoding is not supported.
UnsupportedEncodingException() - Constructor for exception java.io.UnsupportedEncodingException
Constructs an UnsupportedEncodingException without a detail message.
UnsupportedEncodingException(String) - Constructor for exception java.io.UnsupportedEncodingException
Constructs an UnsupportedEncodingException with a detail message.
UnsupportedFlavorException - Exception in java.awt.datatransfer
Signals that the requested data is not supported in this flavor.
UnsupportedFlavorException(DataFlavor) - Constructor for exception java.awt.datatransfer.UnsupportedFlavorException
Constructs an UnsupportedFlavorException.
UnsupportedLookAndFeelException - Exception in javax.swing
An exception that indicates the requested look & feel management classes are not present on the user's system.
UnsupportedLookAndFeelException(String) - Constructor for exception javax.swing.UnsupportedLookAndFeelException
Constructs an UnsupportedLookAndFeelException object.
UnsupportedOperationException - Exception in java.lang
Thrown to indicate that the requested operation is not supported.
UnsupportedOperationException() - Constructor for exception java.lang.UnsupportedOperationException
Constructs an UnsupportedOperationException with no detail message.
UnsupportedOperationException(String) - Constructor for exception java.lang.UnsupportedOperationException
Constructs an UnsupportedOperationException with the specified detail message.
UnsupportedOperationException(String, Throwable) - Constructor for exception java.lang.UnsupportedOperationException
Constructs a new exception with the specified detail message and cause.
UnsupportedOperationException(Throwable) - Constructor for exception java.lang.UnsupportedOperationException
Constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).
unsynchronize(Line[]) - Method in interface javax.sound.sampled.Mixer
Releases synchronization for the specified lines.
unwrap() - Method in class java.lang.invoke.MethodType
Converts all wrapper types to their corresponding primitive types.
unwrap(Class<T>) - Method in interface java.sql.Wrapper
Returns an object that implements the given interface to allow access to non-standard methods, or standard methods not exposed by the proxy.
unwrap(byte[], String, int) - Method in class javax.crypto.Cipher
Unwrap a previously wrapped key.
unwrap(ByteBuffer, ByteBuffer) - Method in class javax.net.ssl.SSLEngine
Attempts to decode SSL/TLS network data into a plaintext application data buffer.
unwrap(ByteBuffer, ByteBuffer[]) - Method in class javax.net.ssl.SSLEngine
Attempts to decode SSL/TLS network data into a sequence of plaintext application data buffers.
unwrap(ByteBuffer, ByteBuffer[], int, int) - Method in class javax.net.ssl.SSLEngine
Attempts to decode SSL/TLS network data into a subsequence of plaintext application data buffers.
unwrap(byte[], int, int) - Method in interface javax.security.sasl.SaslClient
Unwraps a byte array received from the server.
unwrap(byte[], int, int) - Method in interface javax.security.sasl.SaslServer
Unwraps a byte array received from the client.
unwrap(Class<T>) - Method in class javax.sql.rowset.RowSetMetaDataImpl
Returns an object that implements the given interface to allow access to non-standard methods, or standard methods not exposed by the proxy.
unwrap(byte[], int, int, MessageProp) - Method in interface org.ietf.jgss.GSSContext
Used to process tokens generated by the wrap method on the other side of the context.
unwrap(InputStream, OutputStream, MessageProp) - Method in interface org.ietf.jgss.GSSContext
Uses streams to process tokens generated by the wrap method on the other side of the context.
UNWRAP_MODE - Static variable in class javax.crypto.Cipher
Constant used to initialize cipher to key-unwrapping mode.
UP - Static variable in class java.awt.Event
The Up Arrow key, a non-ASCII action key.
UP_CYCLE_TRAVERSAL_KEYS - Static variable in class java.awt.KeyboardFocusManager
The identifier for the Up Cycle focus traversal keys.
upAction - Static variable in class javax.swing.text.DefaultEditorKit
Name of the Action for moving the caret logically upward one position.
UPDATABLE_VIEW_SYNC - Static variable in class javax.sql.rowset.spi.SyncProvider
Indicates that a SyncProvider implementation supports synchronization between a RowSet object and the SQL VIEW used to populate it.
update(Graphics) - Method in class java.awt.Canvas
Updates this canvas.
update(Graphics) - Method in class java.awt.Component
Updates this component.
update(Graphics) - Method in class java.awt.Container
Updates the container.
UPDATE - Static variable in class java.awt.event.PaintEvent
The update event type.
update() - Method in class java.awt.SplashScreen
Updates the splash window with current contents of the overlay image.
update(byte) - Method in class java.security.MessageDigest
Updates the digest using the specified byte.
update(byte[], int, int) - Method in class java.security.MessageDigest
Updates the digest using the specified array of bytes, starting at the specified offset.
update(byte[]) - Method in class java.security.MessageDigest
Updates the digest using the specified array of bytes.
update(ByteBuffer) - Method in class java.security.MessageDigest
Update the digest using the specified ByteBuffer.
update(byte) - Method in class java.security.Signature
Updates the data to be signed or verified by a byte.
update(byte[]) - Method in class java.security.Signature
Updates the data to be signed or verified, using the specified array of bytes.
update(byte[], int, int) - Method in class java.security.Signature
Updates the data to be signed or verified, using the specified array of bytes, starting at the specified offset.
update(ByteBuffer) - Method in class java.security.Signature
Updates the data to be signed or verified using the specified ByteBuffer.
update(Observable, Object) - Method in interface java.util.Observer
This method is called whenever the observed object is changed.
update(int) - Method in class java.util.zip.Adler32
Updates the checksum with the specified byte (the low eight bits of the argument b).
update(byte[], int, int) - Method in class java.util.zip.Adler32
Updates the checksum with the specified array of bytes.
update(byte[]) - Method in class java.util.zip.Adler32
Updates the checksum with the specified array of bytes.
update(int) - Method in interface java.util.zip.Checksum
Updates the current checksum with the specified byte.
update(byte[], int, int) - Method in interface java.util.zip.Checksum
Updates the current checksum with the specified array of bytes.
update(int) - Method in class java.util.zip.CRC32
Updates the CRC-32 checksum with the specified byte (the low eight bits of the argument b).
update(byte[], int, int) - Method in class java.util.zip.CRC32
Updates the CRC-32 checksum with the specified array of bytes.
update(byte[]) - Method in class java.util.zip.CRC32
Updates the CRC-32 checksum with the specified array of bytes.
UPDATE - Static variable in interface javax.accessibility.AccessibleTableModelChange
Identifies a change to existing data.
update(byte[]) - Method in class javax.crypto.Cipher
Continues a multiple-part encryption or decryption operation (depending on how this cipher was initialized), processing another data part.
update(byte[], int, int) - Method in class javax.crypto.Cipher
Continues a multiple-part encryption or decryption operation (depending on how this cipher was initialized), processing another data part.
update(byte[], int, int, byte[]) - Method in class javax.crypto.Cipher
Continues a multiple-part encryption or decryption operation (depending on how this cipher was initialized), processing another data part.
update(byte[], int, int, byte[], int) - Method in class javax.crypto.Cipher
Continues a multiple-part encryption or decryption operation (depending on how this cipher was initialized), processing another data part.
update(ByteBuffer, ByteBuffer) - Method in class javax.crypto.Cipher
Continues a multiple-part encryption or decryption operation (depending on how this cipher was initialized), processing another data part.
update(byte) - Method in class javax.crypto.Mac
Processes the given byte.
update(byte[]) - Method in class javax.crypto.Mac
Processes the given array of bytes.
update(byte[], int, int) - Method in class javax.crypto.Mac
Processes the first len bytes in input, starting at offset inclusive.
update(ByteBuffer) - Method in class javax.crypto.Mac
Processes input.remaining() bytes in the ByteBuffer input, starting at input.position().
update(LineEvent) - Method in interface javax.sound.sampled.LineListener
Informs the listener that a line's state has changed.
update(Graphics) - Method in class javax.swing.CellRendererPane
Shouldn't be called.
UPDATE - Static variable in class javax.swing.event.TableModelEvent
Identifies a change to existing data.
update(Graphics) - Method in class javax.swing.JApplet
Just calls paint(g).
update(Graphics) - Method in class javax.swing.JComponent
Calls paint.
update(Graphics) - Method in class javax.swing.JDialog
Calls paint(g).
update(Graphics) - Method in class javax.swing.JFrame
Just calls paint(g).
update(Graphics) - Method in class javax.swing.JWindow
Calls paint(g).
update(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicMenuItemUI
We draw the background in paintMenuItem() so override update (which fills the background of opaque components by default) to just call paint().
update(Graphics, JComponent) - Method in class javax.swing.plaf.basic.BasicTextUI
Superclass paints background in an uncontrollable way (i.e.
update(Graphics, JComponent) - Method in class javax.swing.plaf.ComponentUI
Notifies this UI delegate that it is time to paint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.metal.MetalButtonUI
If necessary paints the background of the component, then invokes paint.
update(Graphics, JComponent) - Method in class javax.swing.plaf.metal.MetalMenuBarUI
If necessary paints the background of the component, then invokes paint.
update(Graphics, JComponent) - Method in class javax.swing.plaf.metal.MetalTabbedPaneUI
update(Graphics, JComponent) - Method in class javax.swing.plaf.metal.MetalToggleButtonUI
If necessary paints the background of the component, then invokes paint.
update(Graphics, JComponent) - Method in class javax.swing.plaf.metal.MetalToolBarUI
If necessary paints the background of the component, then invokes paint.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiButtonUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiColorChooserUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiComboBoxUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiDesktopIconUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiDesktopPaneUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiFileChooserUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiInternalFrameUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiLabelUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiListUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiMenuBarUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiMenuItemUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiOptionPaneUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiPanelUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiPopupMenuUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiProgressBarUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiRootPaneUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiScrollBarUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiScrollPaneUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiSeparatorUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiSliderUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiSpinnerUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiSplitPaneUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiTabbedPaneUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiTableHeaderUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiTableUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiTextUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiToolBarUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiToolTipUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiTreeUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.multi.MultiViewportUI
Invokes the update method on each UI handled by this object.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthButtonUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthColorChooserUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthComboBoxUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthDesktopIconUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthDesktopPaneUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthEditorPaneUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthInternalFrameUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthLabelUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthListUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthMenuBarUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthMenuItemUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthMenuUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthOptionPaneUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthPanelUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthPopupMenuUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthProgressBarUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthRootPaneUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthScrollBarUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthScrollPaneUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthSeparatorUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthSliderUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthSpinnerUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthSplitPaneUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthTabbedPaneUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthTableHeaderUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthTableUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthTextAreaUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthTextFieldUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthToolBarUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthToolTipUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthTreeUI
Notifies this UI delegate to repaint the specified component.
update(Graphics, JComponent) - Method in class javax.swing.plaf.synth.SynthViewportUI
Notifies this UI delegate to repaint the specified component.
UPDATE_ROW_CONFLICT - Static variable in interface javax.sql.rowset.spi.SyncResolver
Indicates that a conflict occurred while the RowSet object was attempting to update a row in the data source.
UPDATE_WHEN_ON_EDT - Static variable in class javax.swing.text.DefaultCaret
Indicates that the caret position is to be updated only when document changes are performed on the Event Dispatching Thread.
updateArray(int, Array) - Method in interface java.sql.ResultSet
Updates the designated column with a java.sql.Array value.
updateArray(String, Array) - Method in interface java.sql.ResultSet
Updates the designated column with a java.sql.Array value.
updateAsciiStream(int, InputStream, int) - Method in interface java.sql.ResultSet
Updates the designated column with an ascii stream value, which will have the specified number of bytes.
updateAsciiStream(String, InputStream, int) - Method in interface java.sql.ResultSet
Updates the designated column with an ascii stream value, which will have the specified number of bytes.
updateAsciiStream(int, InputStream, long) - Method in interface java.sql.ResultSet
Updates the designated column with an ascii stream value, which will have the specified number of bytes.
updateAsciiStream(String, InputStream, long) - Method in interface java.sql.ResultSet
Updates the designated column with an ascii stream value, which will have the specified number of bytes.
updateAsciiStream(int, InputStream) - Method in interface java.sql.ResultSet
Updates the designated column with an ascii stream value.
updateAsciiStream(String, InputStream) - Method in interface java.sql.ResultSet
Updates the designated column with an ascii stream value.
updateAutoscroll(Point) - Method in class java.awt.dnd.DropTarget
update autoscrolling with current cursor locn
updateBigDecimal(int, BigDecimal) - Method in interface java.sql.ResultSet
Updates the designated column with a java.math.BigDecimal value.
updateBigDecimal(String, BigDecimal) - Method in interface java.sql.ResultSet
Updates the designated column with a java.sql.BigDecimal value.
updateBinaryStream(int, InputStream, int) - Method in interface java.sql.ResultSet
Updates the designated column with a binary stream value, which will have the specified number of bytes.
updateBinaryStream(String, InputStream, int) - Method in interface java.sql.ResultSet
Updates the designated column with a binary stream value, which will have the specified number of bytes.
updateBinaryStream(int, InputStream, long) - Method in interface java.sql.ResultSet
Updates the designated column with a binary stream value, which will have the specified number of bytes.
updateBinaryStream(String, InputStream, long) - Method in interface java.sql.ResultSet
Updates the designated column with a binary stream value, which will have the specified number of bytes.
updateBinaryStream(int, InputStream) - Method in interface java.sql.ResultSet
Updates the designated column with a binary stream value.
updateBinaryStream(String, InputStream) - Method in interface java.sql.ResultSet
Updates the designated column with a binary stream value.
updateBlob(int, Blob) - Method in interface java.sql.ResultSet
Updates the designated column with a java.sql.Blob value.
updateBlob(String, Blob) - Method in interface java.sql.ResultSet
Updates the designated column with a java.sql.Blob value.
updateBlob(int, InputStream, long) - Method in interface java.sql.ResultSet
Updates the designated column using the given input stream, which will have the specified number of bytes.
updateBlob(String, InputStream, long) - Method in interface java.sql.ResultSet
Updates the designated column using the given input stream, which will have the specified number of bytes.
updateBlob(int, InputStream) - Method in interface java.sql.ResultSet
Updates the designated column using the given input stream.
updateBlob(String, InputStream) - Method in interface java.sql.ResultSet
Updates the designated column using the given input stream.
updateBoolean(int, boolean) - Method in interface java.sql.ResultSet
Updates the designated column with a boolean value.
updateBoolean(String, boolean) - Method in interface java.sql.ResultSet
Updates the designated column with a boolean value.
updateButtonMnemonic - Variable in class javax.swing.plaf.basic.BasicFileChooserUI
updateButtonText - Variable in class javax.swing.plaf.basic.BasicFileChooserUI
updateButtonToolTipText - Variable in class javax.swing.plaf.basic.BasicFileChooserUI
updateByte(int, byte) - Method in interface java.sql.ResultSet
Updates the designated column with a byte value.
updateByte(String, byte) - Method in interface java.sql.ResultSet
Updates the designated column with a byte value.
updateBytes(int, byte[]) - Method in interface java.sql.ResultSet
Updates the designated column with a byte array value.
updateBytes(String, byte[]) - Method in interface java.sql.ResultSet
Updates the designated column with a byte array value.
updateCachedPreferredSize() - Method in class javax.swing.plaf.basic.BasicTreeUI
Updates the preferredSize instance variable, which is returned from getPreferredSize().
updateCellEditor() - Method in class javax.swing.plaf.basic.BasicTreeUI
Updates the cellEditor based on the editability of the JTree that we're contained in.
updateCharacterStream(int, Reader, int) - Method in interface java.sql.ResultSet
Updates the designated column with a character stream value, which will have the specified number of bytes.
updateCharacterStream(String, Reader, int) - Method in interface java.sql.ResultSet
Updates the designated column with a character stream value, which will have the specified number of bytes.
updateCharacterStream(int, Reader, long) - Method in interface java.sql.ResultSet
Updates the designated column with a character stream value, which will have the specified number of bytes.
updateCharacterStream(String, Reader, long) - Method in interface java.sql.ResultSet
Updates the designated column with a character stream value, which will have the specified number of bytes.
updateCharacterStream(int, Reader) - Method in interface java.sql.ResultSet
Updates the designated column with a character stream value.
updateCharacterStream(String, Reader) - Method in interface java.sql.ResultSet
Updates the designated column with a character stream value.
updateChildren(DocumentEvent.ElementChange, DocumentEvent, ViewFactory) - Method in class javax.swing.text.View
Updates the child views in response to receiving notification that the model changed, and there is change record for the element this view is responsible for.
updateChildren(DocumentEvent.ElementChange, DocumentEvent, ViewFactory) - Method in class javax.swing.text.ZoneView
The superclass behavior will try to update the child views which is not desired in this case, since the children are zones and not directly effected by the changes to the associated element.
updateChooser() - Method in class javax.swing.colorchooser.AbstractColorChooserPanel
Invoked automatically when the model's state changes.
updateClob(int, Clob) - Method in interface java.sql.ResultSet
Updates the designated column with a java.sql.Clob value.
updateClob(String, Clob) - Method in interface java.sql.ResultSet
Updates the designated column with a java.sql.Clob value.
updateClob(int, Reader, long) - Method in interface java.sql.ResultSet
Updates the designated column using the given Reader object, which is the given number of characters long.
updateClob(String, Reader, long) - Method in interface java.sql.ResultSet
Updates the designated column using the given Reader object, which is the given number of characters long.
updateClob(int, Reader) - Method in interface java.sql.ResultSet
Updates the designated column using the given Reader object.
updateClob(String, Reader) - Method in interface java.sql.ResultSet
Updates the designated column using the given Reader object.
updateColumnHeader(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicScrollPaneUI
updateComponents() - Method in class javax.swing.plaf.basic.BasicSplitPaneUI.BasicHorizontalLayoutManager
Determines the components.
updateComponentTreeUI(Component) - Static method in class javax.swing.SwingUtilities
A simple minded look and feel change: ask each node in the tree to updateUI() -- that is, to initialize its UI property with the current look and feel.
updateCurrentCursor(int, int, int) - Method in class java.awt.dnd.DragSourceContext
If the default drag cursor behavior is active, this method sets the default drag cursor for the specified actions supported by the drag source, the drop target action, and status, otherwise this method does nothing.
updateDamage(DocumentEvent, Shape, ViewFactory) - Method in class javax.swing.text.PlainView
Repaint the region of change covered by the given document event.
updateDate(int, Date) - Method in interface java.sql.ResultSet
Updates the designated column with a java.sql.Date value.
updateDate(String, Date) - Method in interface java.sql.ResultSet
Updates the designated column with a java.sql.Date value.
updateDepthOffset() - Method in class javax.swing.plaf.basic.BasicTreeUI
Updates how much each depth should be offset by.
updateDouble(int, double) - Method in interface java.sql.ResultSet
Updates the designated column with a double value.
updateDouble(String, double) - Method in interface java.sql.ResultSet
Updates the designated column with a double value.
updateExpandedDescendants(TreePath) - Method in class javax.swing.plaf.basic.BasicTreeUI
Updates the expanded state of all the descendants of path by getting the expanded descendants from the tree and forwarding to the tree state.
updateFloat(int, float) - Method in interface java.sql.ResultSet
Updates the designated column with a float value.
updateFloat(String, float) - Method in interface java.sql.ResultSet
Updates the designated column with a float value.
updateInt(int, int) - Method in interface java.sql.ResultSet
Updates the designated column with an int value.
updateInt(String, int) - Method in interface java.sql.ResultSet
Updates the designated column with an int value.
updateJAXB(XmlNode) - Method in class javax.xml.bind.Binder
Takes an XML node and updates its associated JAXB object and its descendants.
updateLabelUIs() - Method in class javax.swing.JSlider
Updates the UIs for the labels in the label table by calling updateUI on each label.
updateLayout(DocumentEvent.ElementChange, DocumentEvent, Shape) - Method in class javax.swing.text.AsyncBoxView
Update the layout in response to receiving notification of change from the model.
updateLayout(DocumentEvent.ElementChange, DocumentEvent, Shape) - Method in class javax.swing.text.View
Updates the layout in response to receiving notification of change from the model.
updateLayoutCacheExpandedNodes() - Method in class javax.swing.plaf.basic.BasicTreeUI
Makes all the nodes that are expanded in JTree expanded in LayoutCache.
updateLayoutState() - Method in class javax.swing.plaf.basic.BasicListUI
Recompute the value of cellHeight or cellHeights based and cellWidth, based on the current font and the current values of fixedCellWidth, fixedCellHeight, and prototypeCellValue.
updateLayoutStateNeeded - Variable in class javax.swing.plaf.basic.BasicListUI
updateLeadIndex() - Method in class javax.swing.tree.DefaultTreeSelectionModel
Updates the leadIndex instance variable.
updateLeadSelectionRow() - Method in class javax.swing.plaf.basic.BasicTreeUI
Updates the lead row of the selection.
updateLevel - Variable in class javax.swing.undo.UndoableEditSupport
updateListBoxSelectionForEvent(MouseEvent, boolean) - Method in class javax.swing.plaf.basic.BasicComboPopup
A utility method used by the event listeners.
updateListeners - Variable in class javax.imageio.ImageReader
A List of currently registered IIOReadUpdateListeners, initialized by default to null, which is synonymous with an empty List.
updateLocation(Point) - Method in class java.awt.dnd.DropTarget.DropTargetAutoScroller
cause autoscroll to occur
updateLong(int, long) - Method in interface java.sql.ResultSet
Updates the designated column with a long value.
updateLong(String, long) - Method in interface java.sql.ResultSet
Updates the designated column with a long value.
updateMetrics() - Method in class javax.swing.text.PlainView
Checks to see if the font metrics and longest line are up-to-date.
updateNCharacterStream(int, Reader, long) - Method in interface java.sql.ResultSet
Updates the designated column with a character stream value, which will have the specified number of bytes.
updateNCharacterStream(String, Reader, long) - Method in interface java.sql.ResultSet
Updates the designated column with a character stream value, which will have the specified number of bytes.
updateNCharacterStream(int, Reader) - Method in interface java.sql.ResultSet
Updates the designated column with a character stream value.
updateNCharacterStream(String, Reader) - Method in interface java.sql.ResultSet
Updates the designated column with a character stream value.
updateNClob(int, NClob) - Method in interface java.sql.ResultSet
Updates the designated column with a java.sql.NClob value.
updateNClob(String, NClob) - Method in interface java.sql.ResultSet
Updates the designated column with a java.sql.NClob value.
updateNClob(int, Reader, long) - Method in interface java.sql.ResultSet
Updates the designated column using the given Reader object, which is the given number of characters long.
updateNClob(String, Reader, long) - Method in interface java.sql.ResultSet
Updates the designated column using the given Reader object, which is the given number of characters long.
updateNClob(int, Reader) - Method in interface java.sql.ResultSet
Updates the designated column using the given Reader The data will be read from the stream as needed until end-of-stream is reached.
updateNClob(String, Reader) - Method in interface java.sql.ResultSet
Updates the designated column using the given Reader object.
updateNString(int, String) - Method in interface java.sql.ResultSet
Updates the designated column with a String value.
updateNString(String, String) - Method in interface java.sql.ResultSet
Updates the designated column with a String value.
updateNull(int) - Method in interface java.sql.ResultSet
Updates the designated column with a null value.
updateNull(String) - Method in interface java.sql.ResultSet
Updates the designated column with a null value.
updateObject(int, Object, int) - Method in interface java.sql.ResultSet
Updates the designated column with an Object value.
updateObject(int, Object) - Method in interface java.sql.ResultSet
Updates the designated column with an Object value.
updateObject(String, Object, int) - Method in interface java.sql.ResultSet
Updates the designated column with an Object value.
updateObject(String, Object) - Method in interface java.sql.ResultSet
Updates the designated column with an Object value.
updateRef(int, Ref) - Method in interface java.sql.ResultSet
Updates the designated column with a java.sql.Ref value.
updateRef(String, Ref) - Method in interface java.sql.ResultSet
Updates the designated column with a java.sql.Ref value.
updateRenderer(JComponent, String) - Static method in class javax.swing.plaf.basic.BasicHTML
Stash the HTML render for the given text into the client properties of the given JComponent.
updateRenderer() - Method in class javax.swing.plaf.basic.BasicTreeUI
Messaged from the tree we're in when the renderer has changed.
updateRoleMap(String, Role, List<ObjectName>) - Method in class javax.management.relation.RelationService
Handles update of the Relation Service role map for the update of given role in given relation.
updateRoleMap(String, Role, List<ObjectName>) - Method in interface javax.management.relation.RelationServiceMBean
Handles update of the Relation Service role map for the update of given role in given relation.
updateRow() - Method in interface java.sql.ResultSet
Updates the underlying database with the new contents of the current row of this ResultSet object.
updateRowHeader(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicScrollPaneUI
updateRowId(int, RowId) - Method in interface java.sql.ResultSet
Updates the designated column with a RowId value.
updateRowId(String, RowId) - Method in interface java.sql.ResultSet
Updates the designated column with a RowId value.
updatesAreDetected(int) - Method in interface java.sql.DatabaseMetaData
Retrieves whether or not a visible row update can be detected by calling the method ResultSet.rowUpdated.
updateScrollBarDisplayPolicy(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicScrollPaneUI
updateShort(int, short) - Method in interface java.sql.ResultSet
Updates the designated column with a short value.
updateShort(String, short) - Method in interface java.sql.ResultSet
Updates the designated column with a short value.
updateSize() - Method in class javax.swing.plaf.basic.BasicTreeUI
Marks the cached size as being invalid, and messages the tree with treeDidChange.
updateSQLXML(int, SQLXML) - Method in interface java.sql.ResultSet
Updates the designated column with a java.sql.SQLXML value.
updateSQLXML(String, SQLXML) - Method in interface java.sql.ResultSet
Updates the designated column with a java.sql.SQLXML value.
updateString(int, String) - Method in interface java.sql.ResultSet
Updates the designated column with a String value.
updateString(String, String) - Method in interface java.sql.ResultSet
Updates the designated column with a String value.
updateStyles(Component) - Static method in class javax.swing.plaf.synth.SynthLookAndFeel
Updates the style associated with c, and all its children.
updateTableInRealTime - Variable in class javax.swing.table.JTableHeader
Obsolete as of Java 2 platform v1.3.
updateTime(int, Time) - Method in interface java.sql.ResultSet
Updates the designated column with a java.sql.Time value.
updateTime(String, Time) - Method in interface java.sql.ResultSet
Updates the designated column with a java.sql.Time value.
updateTimestamp(int, Timestamp) - Method in interface java.sql.ResultSet
Updates the designated column with a java.sql.Timestamp value.
updateTimestamp(String, Timestamp) - Method in interface java.sql.ResultSet
Updates the designated column with a java.sql.Timestamp value.
updateUI() - Method in class javax.swing.AbstractButton
Resets the UI property to a value from the current look and feel.
updateUI() - Method in class javax.swing.JButton
Resets the UI property to a value from the current look and feel.
updateUI() - Method in class javax.swing.JCheckBox
Resets the UI property to a value from the current look and feel.
updateUI() - Method in class javax.swing.JColorChooser
Notification from the UIManager that the L&F has changed.
updateUI() - Method in class javax.swing.JComboBox
Resets the UI property to a value from the current look and feel.
updateUI() - Method in class javax.swing.JComponent
Resets the UI property to a value from the current look and feel.
updateUI() - Method in class javax.swing.JDesktopPane
Notification from the UIManager that the L&F has changed.
updateUI() - Method in class javax.swing.JFileChooser
Resets the UI property to a value from the current look and feel.
updateUI() - Method in class javax.swing.JInternalFrame.JDesktopIcon
Notification from the UIManager that the look and feel has changed.
updateUI() - Method in class javax.swing.JInternalFrame
Notification from the UIManager that the look and feel has changed.
updateUI() - Method in class javax.swing.JLabel
Resets the UI property to a value from the current look and feel.
updateUI() - Method in class javax.swing.JLayer
Delegates its functionality to the LayerUI.updateUI(JLayer) method, if LayerUI is set.
updateUI() - Method in class javax.swing.JList
Resets the ListUI property by setting it to the value provided by the current look and feel.
updateUI() - Method in class javax.swing.JMenu
Resets the UI property with a value from the current look and feel.
updateUI() - Method in class javax.swing.JMenuBar
Resets the UI property with a value from the current look and feel.
updateUI() - Method in class javax.swing.JMenuItem
Resets the UI property with a value from the current look and feel.
updateUI() - Method in class javax.swing.JOptionPane
Notification from the UIManager that the L&F has changed.
updateUI() - Method in class javax.swing.JPanel
Resets the UI property with a value from the current look and feel.
updateUI() - Method in class javax.swing.JPasswordField
Reloads the pluggable UI.
updateUI() - Method in class javax.swing.JPopupMenu
Resets the UI property to a value from the current look and feel.
updateUI() - Method in class javax.swing.JProgressBar
Resets the UI property to a value from the current look and feel.
updateUI() - Method in class javax.swing.JRadioButton
Resets the UI property to a value from the current look and feel.
updateUI() - Method in class javax.swing.JRootPane
Resets the UI property to a value from the current look and feel.
updateUI() - Method in class javax.swing.JScrollBar
Overrides JComponent.updateUI.
updateUI() - Method in class javax.swing.JScrollPane
Replaces the current ScrollPaneUI object with a version from the current default look and feel.
updateUI() - Method in class javax.swing.JSeparator
Resets the UI property to a value from the current look and feel.
updateUI() - Method in class javax.swing.JSlider
Resets the UI property to a value from the current look and feel.
updateUI() - Method in class javax.swing.JSpinner
Resets the UI property with the value from the current look and feel.
updateUI() - Method in class javax.swing.JSplitPane
Notification from the UIManager that the L&F has changed.
updateUI() - Method in class javax.swing.JTabbedPane
Resets the UI property to a value from the current look and feel.
updateUI() - Method in class javax.swing.JTable
Notification from the UIManager that the L&F has changed.
updateUI() - Method in class javax.swing.JToggleButton
Resets the UI property to a value from the current look and feel.
updateUI() - Method in class javax.swing.JToolBar
Notification from the UIFactory that the L&F has changed.
updateUI() - Method in class javax.swing.JToolTip
Resets the UI property to a value from the current look and feel.
updateUI() - Method in class javax.swing.JTree
Notification from the UIManager that the L&F has changed.
updateUI() - Method in class javax.swing.JViewport
Resets the UI property to a value from the current look and feel.
updateUI(JLayer<? extends V>) - Method in class javax.swing.plaf.LayerUI
Invoked when JLayer.updateUI() is called by the JLayer this LayerUI is set to.
updateUI() - Method in class javax.swing.table.DefaultTableCellRenderer
Notification from the UIManager that the look and feel [L&F] has changed.
updateUI() - Method in class javax.swing.table.JTableHeader
Notification from the UIManager that the look and feel (L&F) has changed.
updateUI() - Method in class javax.swing.text.JTextComponent
Reloads the pluggable UI.
updateUI() - Method in class javax.swing.tree.DefaultTreeCellRenderer
Resets the UI property to a value from the current look and feel.
updateUndoPositions(Vector, int, int) - Method in class javax.swing.text.GapContent
Resets the location for all the UndoPosRef instances in positions.
updateUndoPositions(Vector) - Method in class javax.swing.text.StringContent
Resets the location for all the UndoPosRef instances in positions.
updateViewport(PropertyChangeEvent) - Method in class javax.swing.plaf.basic.BasicScrollPaneUI
updateXML(Object) - Method in class javax.xml.bind.Binder
Takes an JAXB object and updates its associated XML node and its descendants.
updateXML(Object, XmlNode) - Method in class javax.xml.bind.Binder
Changes in JAXB object tree are updated in its associated XML parse tree.
upFocusCycle(Component) - Method in class java.awt.DefaultKeyboardFocusManager
Moves the focus up one focus traversal cycle.
upFocusCycle(Component) - Method in class java.awt.KeyboardFocusManager
Moves the focus up one focus traversal cycle.
upFocusCycle() - Method in class java.awt.KeyboardFocusManager
Moves the focus up one focus traversal cycle from the current focus owner.
upFolderIcon - Variable in class javax.swing.plaf.basic.BasicFileChooserUI
upKey - Variable in class javax.swing.plaf.basic.BasicSplitPaneUI
Deprecated.
As of Java 2 platform v1.3.
upKey - Variable in class javax.swing.plaf.basic.BasicTabbedPaneUI
Deprecated.
As of Java 2 platform v1.3.
upKey - Variable in class javax.swing.plaf.basic.BasicToolBarUI
Deprecated.
As of Java 2 platform v1.3.
UPPER_LEADING_CORNER - Static variable in interface javax.swing.ScrollPaneConstants
Identifies the upper leading edge corner of the viewport.
UPPER_LEFT_CORNER - Static variable in interface javax.swing.ScrollPaneConstants
Identifies the upper left corner of the viewport.
UPPER_RIGHT_CORNER - Static variable in interface javax.swing.ScrollPaneConstants
Identifies the upper right corner of the viewport.
UPPER_TRAILING_CORNER - Static variable in interface javax.swing.ScrollPaneConstants
Identifies the upper trailing edge corner of the viewport.
UPPERCASE - Static variable in class java.util.FormattableFlags
Converts the output to upper case according to the rules of the locale given during creation of the formatter argument of the formatTo() method.
UPPERCASE_LETTER - Static variable in class java.lang.Character
General category "Lu" in the Unicode specification.
upperLeft - Variable in class javax.swing.JScrollPane
The component to display in the upper left corner.
upperLeft - Variable in class javax.swing.ScrollPaneLayout
The component to display in the upper left corner.
upperRight - Variable in class javax.swing.JScrollPane
The component to display in the upper right corner.
upperRight - Variable in class javax.swing.ScrollPaneLayout
The component to display in the upper right corner.
URI - Class in java.net
Represents a Uniform Resource Identifier (URI) reference.
URI(String) - Constructor for class java.net.URI
Constructs a URI by parsing the given string.
URI(String, String, String, int, String, String, String) - Constructor for class java.net.URI
Constructs a hierarchical URI from the given components.
URI(String, String, String, String, String) - Constructor for class java.net.URI
Constructs a hierarchical URI from the given components.
URI(String, String, String, String) - Constructor for class java.net.URI
Constructs a hierarchical URI from the given components.
URI(String, String, String) - Constructor for class java.net.URI
Constructs a URI from the given components.
uri - Variable in class javax.tools.SimpleJavaFileObject
A URI for this file object.
URI_NS_SOAP_1_1_ENVELOPE - Static variable in interface javax.xml.soap.SOAPConstants
The namespace identifier for the SOAP 1.1 envelope.
URI_NS_SOAP_1_2_ENCODING - Static variable in interface javax.xml.soap.SOAPConstants
The namespace identifier for the SOAP 1.2 encoding.
URI_NS_SOAP_1_2_ENVELOPE - Static variable in interface javax.xml.soap.SOAPConstants
The namespace identifier for the SOAP 1.2 envelope.
URI_NS_SOAP_ENCODING - Static variable in interface javax.xml.soap.SOAPConstants
The namespace identifier for the SOAP 1.1 encoding.
URI_NS_SOAP_ENVELOPE - Static variable in interface javax.xml.soap.SOAPConstants
The namespace identifier for the SOAP 1.1 envelope, All SOAPElements in this namespace are defined by the SOAP 1.1 specification.
URI_SOAP_1_2_ROLE_NEXT - Static variable in interface javax.xml.soap.SOAPConstants
The URI identifying the next application processing a SOAP request as the intended role for a SOAP 1.2 header entry (see section 2.2 of part 1 of the SOAP 1.2 specification).
URI_SOAP_1_2_ROLE_NONE - Static variable in interface javax.xml.soap.SOAPConstants
The URI specifying the role None in SOAP 1.2.
URI_SOAP_1_2_ROLE_ULTIMATE_RECEIVER - Static variable in interface javax.xml.soap.SOAPConstants
The URI identifying the ultimate receiver of the SOAP 1.2 message.
URI_SOAP_ACTOR_NEXT - Static variable in interface javax.xml.soap.SOAPConstants
The URI identifying the next application processing a SOAP request as the intended actor for a SOAP 1.1 header entry (see section 4.2.2 of the SOAP 1.1 specification).
URIDereferencer - Interface in javax.xml.crypto
A dereferencer of URIReferences.
URIException - Interface in javax.print
Interface URIException is a mixin interface which a subclass of PrintException can implement to report an error condition involving a URI address.
URIInaccessible - Static variable in interface javax.print.URIException
Indicates that the printer cannot access the URI address.
URIOtherProblem - Static variable in interface javax.print.URIException
Indicates any kind of problem not specifically identified by the other reasons.
URIParameter - Class in java.security
A parameter that contains a URI pointing to data intended for a PolicySpi or ConfigurationSpi implementation.
URIParameter(URI) - Constructor for class java.security.URIParameter
Constructs a URIParameter with the URI pointing to data intended for an SPI implementation.
URIReference - Interface in javax.xml.crypto
Identifies a data object via a URI-Reference, as specified by RFC 2396.
URIReferenceException - Exception in javax.xml.crypto
Indicates an exceptional condition thrown while dereferencing a URIReference.
URIReferenceException() - Constructor for exception javax.xml.crypto.URIReferenceException
Constructs a new URIReferenceException with null as its detail message.
URIReferenceException(String) - Constructor for exception javax.xml.crypto.URIReferenceException
Constructs a new URIReferenceException with the specified detail message.
URIReferenceException(String, Throwable) - Constructor for exception javax.xml.crypto.URIReferenceException
Constructs a new URIReferenceException with the specified detail message and cause.
URIReferenceException(String, Throwable, URIReference) - Constructor for exception javax.xml.crypto.URIReferenceException
Constructs a new URIReferenceException with the specified detail message, cause and URIReference.
URIReferenceException(Throwable) - Constructor for exception javax.xml.crypto.URIReferenceException
Constructs a new URIReferenceException with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).
URIResolver - Interface in javax.xml.transform
An object that implements this interface that can be called by the processor to turn a URI used in document(), xsl:import, or xsl:include into a Source object.
URISchemeNotSupported - Static variable in interface javax.print.URIException
Indicates that the printer does not support the URI scheme ("http", "ftp", etc.) in the URI address.
URISyntax - Class in javax.print.attribute
Class URISyntax is an abstract base class providing the common implementation of all attributes whose value is a Uniform Resource Identifier (URI).
URISyntax(URI) - Constructor for class javax.print.attribute.URISyntax
Constructs a URI attribute with the specified URI.
URISyntaxException - Exception in java.net
Checked exception thrown to indicate that a string could not be parsed as a URI reference.
URISyntaxException(String, String, int) - Constructor for exception java.net.URISyntaxException
Constructs an instance from the given input string, reason, and error index.
URISyntaxException(String, String) - Constructor for exception java.net.URISyntaxException
Constructs an instance from the given input string and reason.
URL - Class in java.net
Class URL represents a Uniform Resource Locator, a pointer to a "resource" on the World Wide Web.
URL(String, String, int, String) - Constructor for class java.net.URL
Creates a URL object from the specified protocol, host, port number, and file.
URL(String, String, String) - Constructor for class java.net.URL
Creates a URL from the specified protocol name, host name, and file name.
URL(String, String, int, String, URLStreamHandler) - Constructor for class java.net.URL
Creates a URL object from the specified protocol, host, port number, file, and handler.
URL(String) - Constructor for class java.net.URL
Creates a URL object from the String representation.
URL(URL, String) - Constructor for class java.net.URL
Creates a URL by parsing the given spec within a specified context.
URL(URL, String, URLStreamHandler) - Constructor for class java.net.URL
Creates a URL by parsing the given spec with the specified handler within a specified context.
url - Variable in class java.net.URLConnection
The URL represents the remote object on the World Wide Web to which this connection is opened.
URL_PKG_PREFIXES - Static variable in interface javax.naming.Context
Constant that holds the name of the environment property for specifying the list of package prefixes to use when loading in URL context factories.
URLClassLoader - Class in java.net
This class loader is used to load classes and resources from a search path of URLs referring to both JAR files and directories.
URLClassLoader(URL[], ClassLoader) - Constructor for class java.net.URLClassLoader
Constructs a new URLClassLoader for the given URLs.
URLClassLoader(URL[]) - Constructor for class java.net.URLClassLoader
Constructs a new URLClassLoader for the specified URLs using the default delegation parent ClassLoader.
URLClassLoader(URL[], ClassLoader, URLStreamHandlerFactory) - Constructor for class java.net.URLClassLoader
Constructs a new URLClassLoader for the specified URLs, parent class loader, and URLStreamHandlerFactory.
URLConnection - Class in java.net
The abstract class URLConnection is the superclass of all classes that represent a communications link between the application and a URL.
URLConnection(URL) - Constructor for class java.net.URLConnection
Constructs a URL connection to the specified URL.
URLDataSource - Class in javax.activation
The URLDataSource class provides an object that wraps a URL object in a DataSource interface.
URLDataSource(URL) - Constructor for class javax.activation.URLDataSource
URLDataSource constructor.
URLDecoder - Class in java.net
Utility class for HTML form decoding.
URLDecoder() - Constructor for class java.net.URLDecoder
URLEncoder - Class in java.net
Utility class for HTML form encoding.
URLStreamHandler - Class in java.net
The abstract class URLStreamHandler is the common superclass for all stream protocol handlers.
URLStreamHandler() - Constructor for class java.net.URLStreamHandler
URLStreamHandlerFactory - Interface in java.net
This interface defines a factory for URL stream protocol handlers.
URLStringHelper - Class in org.omg.CosNaming.NamingContextExtPackage
URLString is the URL address (corbaloc: or corbaname:) represented as a String.
URLStringHelper() - Constructor for class org.omg.CosNaming.NamingContextExtPackage.URLStringHelper
US - Static variable in class java.util.Locale
Useful constant for country.
USE_ACTIVE_OBJECT_MAP_ONLY - Static variable in class org.omg.PortableServer.RequestProcessingPolicyValue
USE_ALL_BEANINFO - Static variable in class java.beans.Introspector
USE_DEFAULT_SERVANT - Static variable in class org.omg.PortableServer.RequestProcessingPolicyValue
USE_SERVANT_MANAGER - Static variable in class org.omg.PortableServer.RequestProcessingPolicyValue
USE_STD3_ASCII_RULES - Static variable in class java.net.IDN
Flag to turn on the check against STD-3 ASCII rules
useAnchoringBounds(boolean) - Method in class java.util.regex.Matcher
Sets the anchoring of region bounds for this matcher.
useCaches - Variable in class java.net.URLConnection
If true, the protocol is allowed to use caching whenever it can.
useDaylightTime() - Method in class java.util.SimpleTimeZone
Queries if this time zone uses daylight saving time.
useDaylightTime() - Method in class java.util.TimeZone
Queries if this TimeZone uses Daylight Saving Time.
useDelimiter(Pattern) - Method in class java.util.Scanner
Sets this scanner's delimiting pattern to the specified pattern.
useDelimiter(String) - Method in class java.util.Scanner
Sets this scanner's delimiting pattern to a pattern constructed from the specified String.
useLocale(Locale) - Method in class java.util.Scanner
Sets this scanner's locale to the specified locale.
USEMAP - Static variable in class javax.swing.text.html.HTML.Attribute
usePattern(Pattern) - Method in class java.util.regex.Matcher
Changes the Pattern that this Matcher uses to find matches with.
useProtocolVersion(int) - Method in class java.io.ObjectOutputStream
Specify stream protocol version to use when writing the stream.
USER_EXCEPTION - Interface in org.omg.PortableInterceptor
org/omg/PortableInterceptor/USER_EXCEPTION.java .
USER_ID - Static variable in class org.omg.PortableServer.IdAssignmentPolicyValue
useRadix(int) - Method in class java.util.Scanner
Sets this scanner's default radix to the specified radix.
UserDataHandler - Interface in org.w3c.dom
When associating an object to a key on a node using Node.setUserData() the application can provide a handler that gets called when the node the object is associated to is being cloned, imported, or renamed.
UserDefinedFileAttributeView - Interface in java.nio.file.attribute
A file attribute view that provides a view of a file's user-defined attributes, sometimes known as extended attributes.
UserException - Exception in org.omg.CORBA
The root class for CORBA IDL-defined user exceptions.
UserException() - Constructor for exception org.omg.CORBA.UserException
Constructs a UserException object.
UserException(String) - Constructor for exception org.omg.CORBA.UserException
Constructs a UserException object with a detail message.
USERNAME_PROPERTY - Static variable in interface javax.xml.ws.BindingProvider
Standard property: User name for authentication.
userNodeForPackage(Class<?>) - Static method in class java.util.prefs.Preferences
Returns the preference node from the calling user's preference tree that is associated (by convention) with the specified class's package.
userObject - Variable in class javax.swing.tree.DefaultMutableTreeNode
optional user object
UserPrincipal - Interface in java.nio.file.attribute
A Principal representing an identity used to determine access rights to objects in a file system.
UserPrincipalLookupService - Class in java.nio.file.attribute
An object to lookup user and group principals by name.
UserPrincipalLookupService() - Constructor for class java.nio.file.attribute.UserPrincipalLookupService
Initializes a new instance of this class.
UserPrincipalNotFoundException - Exception in java.nio.file.attribute
Checked exception thrown when a lookup of UserPrincipal fails because the principal does not exist.
UserPrincipalNotFoundException(String) - Constructor for exception java.nio.file.attribute.UserPrincipalNotFoundException
Constructs an instance of this class.
userRoot() - Static method in class java.util.prefs.Preferences
Returns the root preference node for the calling user.
userRoot() - Method in interface java.util.prefs.PreferencesFactory
Returns the user root preference node corresponding to the calling user.
usesFractionalMetrics() - Method in class java.awt.font.FontRenderContext
Returns a boolean which whether text fractional metrics mode is used in this FontRenderContext.
usesLocalFilePerTable() - Method in interface java.sql.DatabaseMetaData
Retrieves whether this database uses a file for each table.
usesLocalFiles() - Method in interface java.sql.DatabaseMetaData
Retrieves whether this database stores tables in a local file.
usesShiftModifier() - Method in class java.awt.MenuShortcut
Returns whether this MenuShortcut must be invoked using the SHIFT key.
useToString(int) - Method in class javax.swing.DefaultRowSorter
Returns whether or not to convert the value to a string before doing comparisons when sorting.
useToString(int) - Method in class javax.swing.table.TableRowSorter
Returns whether or not to convert the value to a string before doing comparisons when sorting.
useTransparentBounds(boolean) - Method in class java.util.regex.Matcher
Sets the transparency of region bounds for this matcher.
UShortSeqHelper - Class in org.omg.CORBA
The Helper for UShortSeq.
UShortSeqHelper() - Constructor for class org.omg.CORBA.UShortSeqHelper
UShortSeqHolder - Class in org.omg.CORBA
The Holder for UShortSeq.
UShortSeqHolder() - Constructor for class org.omg.CORBA.UShortSeqHolder
UShortSeqHolder(short[]) - Constructor for class org.omg.CORBA.UShortSeqHolder
usingProxy() - Method in class java.net.HttpURLConnection
Indicates if the connection is going through a proxy.
UTC(int, int, int, int, int, int) - Static method in class java.util.Date
Deprecated.
As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date, hrs, min, sec) or GregorianCalendar(year + 1900, month, date, hrs, min, sec), using a UTC TimeZone, followed by Calendar.getTime().getTime().
UTC_TIME - Static variable in class java.util.SimpleTimeZone
Constant for a mode of start or end time specified as UTC.
UTFDataFormatException - Exception in java.io
Signals that a malformed string in modified UTF-8 format has been read in a data input stream or by any class that implements the data input interface.
UTFDataFormatException() - Constructor for exception java.io.UTFDataFormatException
Constructs a UTFDataFormatException with null as its error detail message.
UTFDataFormatException(String) - Constructor for exception java.io.UTFDataFormatException
Constructs a UTFDataFormatException with the specified detail message.
Util - Class in javax.rmi.CORBA
Provides utility methods that can be used by stubs and ties to perform common operations.
UtilDelegate - Interface in javax.rmi.CORBA
Supports delegation for method implementations in Util.
Utilities - Class in javax.swing.text
A collection of methods to deal with various text related activities.
Utilities() - Constructor for class javax.swing.text.Utilities
UUID - Class in java.util
A class that represents an immutable universally unique identifier (UUID).
UUID(long, long) - Constructor for class java.util.UUID
Constructs a new UUID using the specified data.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类

提交错误或意见
有关更多的 API 参考资料和开发人员文档，请参阅 Java SE 开发人员文档. 该文档包含更详细的、面向开发人员的描述，以及总体概述、术语定义、使用技巧和工作代码示例。
版权所有 © 1993, 2011, Oracle 及其联盟会员。保留所有权利。
草案 ea-b138

e =h/Dprrrm///


V-Index

请注意：本 java api 1.7Beta 规范不是最终稳定版，未来随着版本的更迭，本规范可能有更新。
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _

V

VAI - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Vai" Unicode character block.
valid() - Method in class java.io.FileDescriptor
Tests if this file descriptor object is valid.
validate() - Method in class java.awt.Component
Validates this component.
validate() - Method in class java.awt.Container
Validates this container and all of its subcomponents.
validate(GraphicsConfiguration) - Method in class java.awt.image.VolatileImage
Attempts to restore the drawing surface of the image if the surface had been lost since the last validate call.
validate(CertPath, CertPathParameters) - Method in class java.security.cert.CertPathValidator
Validates the specified certification path using the specified algorithm parameter set.
validate() - Method in class javax.swing.DefaultListCellRenderer
Overridden for performance reasons.
validate() - Method in class javax.swing.table.DefaultTableCellRenderer
Overridden for performance reasons.
validate() - Method in class javax.swing.tree.DefaultTreeCellRenderer
Overridden for performance reasons.
validate(Object) - Method in interface javax.xml.bind.Validator
Deprecated.
since JAXB2.0
validate(XMLValidateContext) - Method in interface javax.xml.crypto.dsig.Reference
Validates this reference.
validate(XMLValidateContext) - Method in interface javax.xml.crypto.dsig.XMLSignature.SignatureValue
Validates the signature value.
validate(XMLValidateContext) - Method in interface javax.xml.crypto.dsig.XMLSignature
Validates the signature according to the core validation processing rules.
validate(Source) - Method in class javax.xml.validation.Validator
Validates the specified input.
validate(Source, Result) - Method in class javax.xml.validation.Validator
Validates the specified input and send the augmented validation result to the specified output.
validate_connection() - Method in class org.omg.CORBA.LocalObject
Throws an org.omg.CORBA.NO_IMPLEMENT exception with the message "This is a locally constrained object." This method does not apply to local objects and is therefore not implemented.
validatedContents - Variable in class java.awt.Component.BltBufferStrategy
Whether or not the drawing buffer has been recently restored from a lost state.
validatedContents - Variable in class java.awt.Component.FlipBufferStrategy
Whether or not the drawing buffer has been recently restored from a lost state.
validateFileCache() - Method in class javax.swing.plaf.basic.BasicDirectoryModel
validateInvalidComponents() - Method in class javax.swing.RepaintManager
Validate all of the components that have been marked invalid.
validateObject() - Method in interface java.io.ObjectInputValidation
Validates the object.
validatePage(PageFormat) - Method in class java.awt.print.PrinterJob
Returns the clone of page with its settings adjusted to be compatible with the current printer of this PrinterJob.
validatePendingAdd(Object) - Method in class java.beans.beancontext.BeanContextSupport
Subclasses of this class may override, or envelope, this method to add validation behavior for the BeanContext to examine child objects immediately prior to their being added to the BeanContext.
validatePendingRemove(Object) - Method in class java.beans.beancontext.BeanContextSupport
Subclasses of this class may override, or envelope, this method to add validation behavior for the BeanContext to examine child objects immediately prior to their being removed from the BeanContext.
validatePendingSetBeanContext(BeanContext) - Method in class java.beans.beancontext.BeanContextChildSupport
Called from setBeanContext to validate (or otherwise) the pending change in the nesting BeanContext property value.
validateRoot(Object) - Method in interface javax.xml.bind.Validator
Deprecated.
since JAXB2.0
validateTree() - Method in class java.awt.Container
Recursively descends the container tree and recomputes the layout for any subtrees marked as needing it (those marked as invalid).
validating - Variable in class javax.xml.bind.helpers.AbstractUnmarshallerImpl
whether or not the unmarshaller will validate
VALIDATION_ERR - Static variable in exception org.w3c.dom.DOMException
If a call to a method such as insertBefore or removeChild would make the Node invalid with respect to "partial validity", this exception would be raised and the operation would not be done.
ValidationEvent - Interface in javax.xml.bind
This event indicates that a problem was encountered while validating the incoming XML data during an unmarshal operation, while performing on-demand validation of the Java content tree, or while marshalling the Java content tree back to XML data.
ValidationEventCollector - Class in javax.xml.bind.util
ValidationEventHandler implementation that collects all events.
ValidationEventCollector() - Constructor for class javax.xml.bind.util.ValidationEventCollector
ValidationEventHandler - Interface in javax.xml.bind
A basic event handler interface for validation errors.
ValidationEventImpl - Class in javax.xml.bind.helpers
Default implementation of the ValidationEvent interface.
ValidationEventImpl(int, String, ValidationEventLocator) - Constructor for class javax.xml.bind.helpers.ValidationEventImpl
Create a new ValidationEventImpl.
ValidationEventImpl(int, String, ValidationEventLocator, Throwable) - Constructor for class javax.xml.bind.helpers.ValidationEventImpl
Create a new ValidationEventImpl.
ValidationEventLocator - Interface in javax.xml.bind
Encapsulate the location of a ValidationEvent.
ValidationEventLocatorImpl - Class in javax.xml.bind.helpers
Default implementation of the ValidationEventLocator interface.
ValidationEventLocatorImpl() - Constructor for class javax.xml.bind.helpers.ValidationEventLocatorImpl
Creates an object with all fields unavailable.
ValidationEventLocatorImpl(Locator) - Constructor for class javax.xml.bind.helpers.ValidationEventLocatorImpl
Constructs an object from an org.xml.sax.Locator.
ValidationEventLocatorImpl(SAXParseException) - Constructor for class javax.xml.bind.helpers.ValidationEventLocatorImpl
Constructs an object from the location information of a SAXParseException.
ValidationEventLocatorImpl(Node) - Constructor for class javax.xml.bind.helpers.ValidationEventLocatorImpl
Constructs an object that points to a DOM Node.
ValidationEventLocatorImpl(Object) - Constructor for class javax.xml.bind.helpers.ValidationEventLocatorImpl
Constructs an object that points to a JAXB content object.
ValidationException - Exception in javax.xml.bind
This exception indicates that an error has occurred while performing a validate operation.
ValidationException(String) - Constructor for exception javax.xml.bind.ValidationException
Construct an ValidationException with the specified detail message.
ValidationException(String, String) - Constructor for exception javax.xml.bind.ValidationException
Construct an ValidationException with the specified detail message and vendor specific errorCode.
ValidationException(Throwable) - Constructor for exception javax.xml.bind.ValidationException
Construct an ValidationException with a linkedException.
ValidationException(String, Throwable) - Constructor for exception javax.xml.bind.ValidationException
Construct an ValidationException with the specified detail message and linkedException.
ValidationException(String, String, Throwable) - Constructor for exception javax.xml.bind.ValidationException
Construct an ValidationException with the specified detail message, vendor specific errorCode, and linkedException.
Validator - Interface in javax.xml.bind
Deprecated.
since JAXB 2.0
Validator - Class in javax.xml.validation
A processor that checks an XML document against Schema.
Validator() - Constructor for class javax.xml.validation.Validator
Constructor for derived classes.
ValidatorHandler - Class in javax.xml.validation
Streaming validator that works on SAX stream.
ValidatorHandler() - Constructor for class javax.xml.validation.ValidatorHandler
Constructor for derived classes.
validCachedPreferredSize - Variable in class javax.swing.plaf.basic.BasicTreeUI
Is the preferredSize valid?
validOps() - Method in class java.nio.channels.DatagramChannel
Returns an operation set identifying this channel's supported operations.
validOps() - Method in class java.nio.channels.Pipe.SinkChannel
Returns an operation set identifying this channel's supported operations.
validOps() - Method in class java.nio.channels.Pipe.SourceChannel
Returns an operation set identifying this channel's supported operations.
validOps() - Method in class java.nio.channels.SelectableChannel
Returns an operation set identifying this channel's supported operations.
validOps() - Method in class java.nio.channels.ServerSocketChannel
Returns an operation set identifying this channel's supported operations.
validOps() - Method in class java.nio.channels.SocketChannel
Returns an operation set identifying this channel's supported operations.
VALIGN - Static variable in class javax.swing.text.html.HTML.Attribute
value() - Method in interface java.nio.file.attribute.FileAttribute
Returns the attribute value.
value - Variable in class java.sql.DriverPropertyInfo
The value field specifies the current value of the property, based on a combination of the information supplied to the method getPropertyInfo, the Java environment, and the driver-supplied default values.
value(String) - Static method in class javax.management.Query
Returns a new string expression.
value(Number) - Static method in class javax.management.Query
Returns a numeric value expression that can be used in any Query call that expects a ValueExp.
value(int) - Static method in class javax.management.Query
Returns a numeric value expression that can be used in any Query call that expects a ValueExp.
value(long) - Static method in class javax.management.Query
Returns a numeric value expression that can be used in any Query call that expects a ValueExp.
value(float) - Static method in class javax.management.Query
Returns a numeric value expression that can be used in any Query call that expects a ValueExp.
value(double) - Static method in class javax.management.Query
Returns a numeric value expression that can be used in any Query call that expects a ValueExp.
value(boolean) - Static method in class javax.management.Query
Returns a boolean value expression that can be used in any Query call that expects a ValueExp.
value - Variable in class javax.naming.ldap.BasicControl
The control's ASN.1 BER encoded value.
value - Variable in class javax.swing.DefaultCellEditor.EditorDelegate
The value of this cell.
value - Variable in class javax.swing.JOptionPane
Currently selected value, will be a valid option, or UNINITIALIZED_VALUE or null.
VALUE - Static variable in class javax.swing.text.html.HTML.Attribute
value - Variable in class javax.swing.text.html.parser.AttributeList
value - Variable in class javax.xml.bind.JAXBElement
xml element value.
value - Variable in class javax.xml.ws.Holder
The value contained in the holder.
value - Variable in class org.omg.CORBA.AnyHolder
The Any value held by this AnyHolder object.
value - Variable in class org.omg.CORBA.AnySeqHolder
value - Static variable in interface org.omg.CORBA.ARG_IN
The value indicating an input argument.
value - Static variable in interface org.omg.CORBA.ARG_INOUT
The constant value indicating an argument used for both input and output.
value - Static variable in interface org.omg.CORBA.ARG_OUT
The constant value indicating an output argument.
value - Static variable in interface org.omg.CORBA.BAD_POLICY
The Error code in PolicyError exception.
value - Static variable in interface org.omg.CORBA.BAD_POLICY_TYPE
The Error code in PolicyError exception.
value - Static variable in interface org.omg.CORBA.BAD_POLICY_VALUE
The value used to represent a bad policy value error in a PolicyError exception.
value - Variable in class org.omg.CORBA.BooleanHolder
The boolean value held by this BooleanHolder object.
value - Variable in class org.omg.CORBA.BooleanSeqHolder
value - Variable in class org.omg.CORBA.ByteHolder
The byte value held by this ByteHolder object.
value - Variable in class org.omg.CORBA.CharHolder
The char value held by this CharHolder object.
value - Variable in class org.omg.CORBA.CharSeqHolder
value() - Method in class org.omg.CORBA.CompletionStatus
Retrieves the value of this CompletionStatus object.
value - Static variable in interface org.omg.CORBA.CTX_RESTRICT_SCOPE
The field containing the int value of a CTX_RESTRICT_SCOPE flag.
value - Variable in class org.omg.CORBA.CurrentHolder
value() - Method in class org.omg.CORBA.DefinitionKind
Returns the int constant identifying the type of an IR object.
value - Variable in class org.omg.CORBA.DoubleHolder
The double value held by this DoubleHolder object.
value - Variable in class org.omg.CORBA.DoubleSeqHolder
value - Variable in class org.omg.CORBA.FixedHolder
The value held by the FixedHolder
value - Variable in class org.omg.CORBA.FloatHolder
The float value held by this FloatHolder object.
value - Variable in class org.omg.CORBA.FloatSeqHolder
value - Variable in class org.omg.CORBA.IntHolder
The int value held by this IntHolder object in its value field.
value - Variable in class org.omg.CORBA.LongHolder
The long value held by this LongHolder object.
value - Variable in class org.omg.CORBA.LongLongSeqHolder
value - Variable in class org.omg.CORBA.LongSeqHolder
value() - Method in class org.omg.CORBA.NamedValue
Retrieves the value for this NamedValue object.
value - Variable in class org.omg.CORBA.NameValuePair
The value to be associated with a name by this NameValuePair object.
value - Variable in class org.omg.CORBA.ObjectHolder
The Object value held by this ObjectHolder object.
value - Variable in class org.omg.CORBA.OctetSeqHolder
value - Static variable in interface org.omg.CORBA.OMGVMCID
The vendor minor code ID reserved for OMG.
value() - Method in class org.omg.CORBA.ParameterMode
value - Variable in class org.omg.CORBA.ParameterModeHolder
value - Variable in class org.omg.CORBA.PolicyErrorHolder
value - Variable in class org.omg.CORBA.PolicyHolder
value - Variable in class org.omg.CORBA.PolicyListHolder
value - Variable in class org.omg.CORBA.PrincipalHolder
Deprecated.
The Principal value held by this PrincipalHolder object.
value - Static variable in interface org.omg.CORBA.PRIVATE_MEMBER
value - Static variable in interface org.omg.CORBA.PUBLIC_MEMBER
value - Variable in class org.omg.CORBA.ServiceInformationHolder
The ServiceInformation value held by this ServiceInformationHolder object in its value field.
value() - Method in class org.omg.CORBA.SetOverrideType
Retrieves the value of this SetOverrideType instance.
value - Variable in class org.omg.CORBA.ShortHolder
The short value held by this ShortHolder object.
value - Variable in class org.omg.CORBA.ShortSeqHolder
value - Variable in class org.omg.CORBA.StringHolder
The String value held by this StringHolder object.
value - Variable in class org.omg.CORBA.StringSeqHolder
value() - Method in class org.omg.CORBA.TCKind
Retrieves the value of this TCKind instance.
value - Variable in class org.omg.CORBA.TypeCodeHolder
The TypeCode value held by this TypeCodeHolder object.
value - Variable in class org.omg.CORBA.ULongLongSeqHolder
value - Variable in class org.omg.CORBA.ULongSeqHolder
value - Variable in class org.omg.CORBA.UnknownUserExceptionHolder
value - Static variable in interface org.omg.CORBA.UNSUPPORTED_POLICY
The Error code for PolicyError exception.
value - Static variable in interface org.omg.CORBA.UNSUPPORTED_POLICY_VALUE
The Error code for PolicyError exception.
value - Variable in class org.omg.CORBA.UShortSeqHolder
value - Variable in class org.omg.CORBA.ValueBaseHolder
The java.io.Serializable value held by this ValueBaseHolder object.
value - Static variable in interface org.omg.CORBA.VM_ABSTRACT
The value representing an abstract interface value type in a typecode.
value - Static variable in interface org.omg.CORBA.VM_CUSTOM
The value representing a custom marshalled value type in a typecode.
value - Static variable in interface org.omg.CORBA.VM_NONE
The value representing the value type in a typecode as per CORBA 2.3 spec.
value - Static variable in interface org.omg.CORBA.VM_TRUNCATABLE
The value representing a truncatable value type in a typecode.
value - Variable in class org.omg.CORBA.WCharSeqHolder
value - Variable in class org.omg.CORBA.WrongTransactionHolder
value - Variable in class org.omg.CORBA.WStringSeqHolder
value - Variable in class org.omg.CosNaming.BindingHolder
value - Variable in class org.omg.CosNaming.BindingIteratorHolder
value - Variable in class org.omg.CosNaming.BindingListHolder
value() - Method in class org.omg.CosNaming.BindingType
value - Variable in class org.omg.CosNaming.BindingTypeHolder
value - Variable in class org.omg.CosNaming.NameComponentHolder
value - Variable in class org.omg.CosNaming.NameHolder
value - Variable in class org.omg.CosNaming.NamingContextExtHolder
value - Variable in class org.omg.CosNaming.NamingContextExtPackage.InvalidAddressHolder
value - Variable in class org.omg.CosNaming.NamingContextHolder
value - Variable in class org.omg.CosNaming.NamingContextPackage.AlreadyBoundHolder
value - Variable in class org.omg.CosNaming.NamingContextPackage.CannotProceedHolder
value - Variable in class org.omg.CosNaming.NamingContextPackage.InvalidNameHolder
value - Variable in class org.omg.CosNaming.NamingContextPackage.NotEmptyHolder
value - Variable in class org.omg.CosNaming.NamingContextPackage.NotFoundHolder
value() - Method in class org.omg.CosNaming.NamingContextPackage.NotFoundReason
value - Variable in class org.omg.CosNaming.NamingContextPackage.NotFoundReasonHolder
value - Variable in class org.omg.DynamicAny.NameDynAnyPair
The DynAny value associated with the name.
value - Variable in class org.omg.DynamicAny.NameValuePair
The Any value associated with the name.
value - Static variable in interface org.omg.IOP.CodeSets
Identifies a CDR encapsulation of the CONV_FRAME.CodeSetContext defined in Section 13.10.2.5, "GIOP Code Set Service Context," on page 13-43.
value - Static variable in interface org.omg.IOP.ENCODING_CDR_ENCAPS
The CDR Encapsulation encoding.
value - Static variable in interface org.omg.IOP.ExceptionDetailMessage
CORBA formal/02-06-01: 13.7.1: ExceptionDetailMessage identifies a CDR encapsulation of a wstring, encoded using GIOP 1.2 with a TCS-W of UTF-16.
value - Variable in class org.omg.IOP.IORHolder
value - Variable in class org.omg.IOP.MultipleComponentProfileHolder
value - Static variable in interface org.omg.IOP.RMICustomMaxStreamFormat
Identifies a CDR encapsulation of the RMICustomMaxStreamFormat service context which contains a single byte specifying the client's maximum RMI-IIOP stream format version.
value - Variable in class org.omg.IOP.ServiceContextHolder
value - Variable in class org.omg.IOP.ServiceContextListHolder
value - Static variable in interface org.omg.IOP.TAG_ALTERNATE_IIOP_ADDRESS
In cases where the same object key is used for more than one internet location, the following standard IOR Component is defined for support in IIOP version 1.2.
value - Static variable in interface org.omg.IOP.TAG_CODE_SETS
The code set component of the IOR multi-component profile structure contains: server's native char code set and conversion code sets, and server's native wchar code set and conversion code sets. Both char and wchar conversion code sets are listed in order of preference.
value - Static variable in interface org.omg.IOP.TAG_INTERNET_IOP
Identifies profiles that support the Internet Inter-ORB Protocol.
value - Static variable in interface org.omg.IOP.TAG_JAVA_CODEBASE
Class downloading is supported for stubs, ties, values, and value helpers.
value - Static variable in interface org.omg.IOP.TAG_MULTIPLE_COMPONENTS
Indicates that the value encapsulated is of type MultipleComponentProfile.
value - Static variable in interface org.omg.IOP.TAG_ORB_TYPE
It is often useful in the real world to be able to identify the particular kind of ORB an object reference is coming from, to work around problems with that particular ORB, or exploit shared efficiencies.
value - Static variable in interface org.omg.IOP.TAG_POLICIES
A profile component containing the sequence of QoS policies exported with the object reference by an object adapter.
value - Static variable in interface org.omg.IOP.TAG_RMI_CUSTOM_MAX_STREAM_FORMAT
RMI-IIOP has multiple stream format versions.
value - Variable in class org.omg.IOP.TaggedComponentHolder
value - Variable in class org.omg.IOP.TaggedProfileHolder
value - Static variable in interface org.omg.IOP.TransactionService
Identifies a CDR encapsulation of the CosTSInteroperation.PropogationContext defined in CORBAservices: Common Object Services Specifications.
value - Static variable in interface org.omg.Messaging.SYNC_WITH_TRANSPORT
Constant, defined in the Messaging spec, to define how far the request shall progress before control is returned to the client.
value - Static variable in interface org.omg.PortableInterceptor.ACTIVE
Object adapter state that indicates normal request processing.
value - Static variable in interface org.omg.PortableInterceptor.DISCARDING
Object adapter state that causes all requests to be discarded.
value - Static variable in interface org.omg.PortableInterceptor.HOLDING
Object adapter state that holds requests temporarily until the state is changed.
value - Static variable in interface org.omg.PortableInterceptor.INACTIVE
Object adapter state that causes all requests to be discarded.
value - Variable in class org.omg.PortableInterceptor.IORInterceptor_3_0Holder
value - Static variable in interface org.omg.PortableInterceptor.LOCATION_FORWARD
Indicates a LocationForward reply status.
value - Static variable in interface org.omg.PortableInterceptor.NON_EXISTENT
Object adapter state indicating that the adapter has been destroyed.
value - Variable in class org.omg.PortableInterceptor.ObjectReferenceFactoryHolder
value - Variable in class org.omg.PortableInterceptor.ObjectReferenceTemplateHolder
value - Variable in class org.omg.PortableInterceptor.ObjectReferenceTemplateSeqHolder
value - Static variable in interface org.omg.PortableInterceptor.SUCCESSFUL
Indicates a successful Reply Status.
value - Static variable in interface org.omg.PortableInterceptor.SYSTEM_EXCEPTION
Indicates a SystemException reply status.
value - Static variable in interface org.omg.PortableInterceptor.TRANSPORT_RETRY
Indicates a Transport Retry reply status.
value - Static variable in interface org.omg.PortableInterceptor.UNKNOWN
XXX
value - Static variable in interface org.omg.PortableInterceptor.USER_EXCEPTION
Indicates a UserException reply status.
value - Static variable in interface org.omg.PortableServer.ID_ASSIGNMENT_POLICY_ID
The value representing ID_ASSIGNMENT_POLICY_ID.
value - Static variable in interface org.omg.PortableServer.ID_UNIQUENESS_POLICY_ID
The value representing ID_UNIQUENESS_POLICY_ID.
value() - Method in interface org.omg.PortableServer.IdAssignmentPolicyOperations
specifies the policy value
value() - Method in class org.omg.PortableServer.IdAssignmentPolicyValue
value() - Method in interface org.omg.PortableServer.IdUniquenessPolicyOperations
specifies the policy value
value() - Method in class org.omg.PortableServer.IdUniquenessPolicyValue
value - Static variable in interface org.omg.PortableServer.IMPLICIT_ACTIVATION_POLICY_ID
The value representing IMPLICIT_ACTIVATION_POLICY_ID.
value() - Method in interface org.omg.PortableServer.ImplicitActivationPolicyOperations
specifies the policy value
value() - Method in class org.omg.PortableServer.ImplicitActivationPolicyValue
value - Static variable in interface org.omg.PortableServer.LIFESPAN_POLICY_ID
The value representing LIFESPAN_POLICY_ID.
value() - Method in interface org.omg.PortableServer.LifespanPolicyOperations
specifies the policy value
value() - Method in class org.omg.PortableServer.LifespanPolicyValue
value() - Method in class org.omg.PortableServer.POAManagerPackage.State
value - Static variable in interface org.omg.PortableServer.REQUEST_PROCESSING_POLICY_ID
The value representing REQUEST_PROCESSING_POLICY_ID.
value() - Method in interface org.omg.PortableServer.RequestProcessingPolicyOperations
specifies the policy value
value() - Method in class org.omg.PortableServer.RequestProcessingPolicyValue
value - Static variable in interface org.omg.PortableServer.SERVANT_RETENTION_POLICY_ID
The value representing SERVANT_RETENTION_POLICY_ID.
value - Variable in class org.omg.PortableServer.ServantLocatorPackage.CookieHolder
value() - Method in interface org.omg.PortableServer.ServantRetentionPolicyOperations
specifies the policy value
value() - Method in class org.omg.PortableServer.ServantRetentionPolicyValue
value - Static variable in interface org.omg.PortableServer.THREAD_POLICY_ID
The value representing THREAD_POLICY_ID.
value() - Method in interface org.omg.PortableServer.ThreadPolicyOperations
specifies the policy value
value() - Method in class org.omg.PortableServer.ThreadPolicyValue
VALUE_ALPHA_INTERPOLATION_DEFAULT - Static variable in class java.awt.RenderingHints
Alpha interpolation hint value -- alpha blending algorithms are chosen by the implementation for a good tradeoff of performance vs.
VALUE_ALPHA_INTERPOLATION_QUALITY - Static variable in class java.awt.RenderingHints
Alpha interpolation hint value -- alpha blending algorithms are chosen with a preference for precision and visual quality.
VALUE_ALPHA_INTERPOLATION_SPEED - Static variable in class java.awt.RenderingHints
Alpha interpolation hint value -- alpha blending algorithms are chosen with a preference for calculation speed.
VALUE_ANTIALIAS_DEFAULT - Static variable in class java.awt.RenderingHints
Antialiasing hint value -- rendering is done with a default antialiasing mode chosen by the implementation.
VALUE_ANTIALIAS_OFF - Static variable in class java.awt.RenderingHints
Antialiasing hint value -- rendering is done without antialiasing.
VALUE_ANTIALIAS_ON - Static variable in class java.awt.RenderingHints
Antialiasing hint value -- rendering is done with antialiasing.
VALUE_ARBITRARY - Static variable in interface javax.imageio.metadata.IIOMetadataFormat
A constant returned by getAttributeValueType and getObjectValueType to indicate that the attribute or user object may be set a single, arbitrary value.
value_as_string() - Method in interface org.omg.CORBA.DynEnum
Deprecated.
Return the value of the IDL enum stored in this DynEnum as a string.
value_as_string(String) - Method in interface org.omg.CORBA.DynEnum
Deprecated.
Set a particular enum in this DynEnum.
value_as_ulong() - Method in interface org.omg.CORBA.DynEnum
Deprecated.
Return the value of the IDL enum as a Java int.
value_as_ulong(int) - Method in interface org.omg.CORBA.DynEnum
Deprecated.
Set the value of the IDL enum.
VALUE_COLOR_RENDER_DEFAULT - Static variable in class java.awt.RenderingHints
Color rendering hint value -- perform color conversion calculations as chosen by the implementation to represent the best available tradeoff between performance and accuracy.
VALUE_COLOR_RENDER_QUALITY - Static variable in class java.awt.RenderingHints
Color rendering hint value -- perform the color conversion calculations with the highest accuracy and visual quality.
VALUE_COLOR_RENDER_SPEED - Static variable in class java.awt.RenderingHints
Color rendering hint value -- perform the fastest color conversion to the format of the output device.
VALUE_DITHER_DEFAULT - Static variable in class java.awt.RenderingHints
Dithering hint value -- use a default for dithering chosen by the implementation.
VALUE_DITHER_DISABLE - Static variable in class java.awt.RenderingHints
Dithering hint value -- do not dither when rendering geometry.
VALUE_DITHER_ENABLE - Static variable in class java.awt.RenderingHints
Dithering hint value -- dither when rendering geometry, if needed.
VALUE_ENUMERATION - Static variable in interface javax.imageio.metadata.IIOMetadataFormat
A constant returned by getAttributeValueType and getObjectValueType to indicate that the attribute or user object may be set one of a number of enumerated values.
VALUE_FRACTIONALMETRICS_DEFAULT - Static variable in class java.awt.RenderingHints
Font fractional metrics hint value -- character glyphs are positioned with accuracy chosen by the implementation.
VALUE_FRACTIONALMETRICS_OFF - Static variable in class java.awt.RenderingHints
Font fractional metrics hint value -- character glyphs are positioned with advance widths rounded to pixel boundaries.
VALUE_FRACTIONALMETRICS_ON - Static variable in class java.awt.RenderingHints
Font fractional metrics hint value -- character glyphs are positioned with sub-pixel accuracy.
VALUE_INTERPOLATION_BICUBIC - Static variable in class java.awt.RenderingHints
Interpolation hint value -- the color samples of 9 nearby integer coordinate samples in the image are interpolated using a cubic function in both X and Y to produce a color sample.
VALUE_INTERPOLATION_BILINEAR - Static variable in class java.awt.RenderingHints
Interpolation hint value -- the color samples of the 4 nearest neighboring integer coordinate samples in the image are interpolated linearly to produce a color sample.
VALUE_INTERPOLATION_NEAREST_NEIGHBOR - Static variable in class java.awt.RenderingHints
Interpolation hint value -- the color sample of the nearest neighboring integer coordinate sample in the image is used.
VALUE_LIST - Static variable in interface javax.imageio.metadata.IIOMetadataFormat
A constant returned by getAttributeValueType and getObjectValueType to indicate that the attribute or user object may be set to a list or array of values.
VALUE_NONE - Static variable in interface javax.imageio.metadata.IIOMetadataFormat
A constant returned by getObjectValueType to indicate the absence of a user object.
VALUE_PROPERTY - Static variable in class javax.swing.JOptionPane
Bound property name for value.
VALUE_RANGE - Static variable in interface javax.imageio.metadata.IIOMetadataFormat
A constant returned by getAttributeValueType and getObjectValueType to indicate that the attribute or user object may be set a range of values.
VALUE_RANGE_MAX_INCLUSIVE - Static variable in interface javax.imageio.metadata.IIOMetadataFormat
A constant returned by getAttributeValueType and getObjectValueType to indicate that the attribute or user object may be set to a range of values.
VALUE_RANGE_MAX_INCLUSIVE_MASK - Static variable in interface javax.imageio.metadata.IIOMetadataFormat
A value that may be or'ed with VALUE_RANGE to obtain VALUE_RANGE_MAX_INCLUSIVE, and with VALUE_RANGE_MIN_INCLUSIVE to obtain VALUE_RANGE_MIN_MAX_INCLUSIVE.
VALUE_RANGE_MIN_INCLUSIVE - Static variable in interface javax.imageio.metadata.IIOMetadataFormat
A constant returned by getAttributeValueType and getObjectValueType to indicate that the attribute or user object may be set to a range of values.
VALUE_RANGE_MIN_INCLUSIVE_MASK - Static variable in interface javax.imageio.metadata.IIOMetadataFormat
A value that may be or'ed with VALUE_RANGE to obtain VALUE_RANGE_MIN_INCLUSIVE, and with VALUE_RANGE_MAX_INCLUSIVE to obtain VALUE_RANGE_MIN_MAX_INCLUSIVE.
VALUE_RANGE_MIN_MAX_INCLUSIVE - Static variable in interface javax.imageio.metadata.IIOMetadataFormat
A constant returned by getAttributeValueType and getObjectValueType to indicate that the attribute or user object may be set a range of values.
VALUE_RENDER_DEFAULT - Static variable in class java.awt.RenderingHints
Rendering hint value -- rendering algorithms are chosen by the implementation for a good tradeoff of performance vs.
VALUE_RENDER_QUALITY - Static variable in class java.awt.RenderingHints
Rendering hint value -- rendering algorithms are chosen with a preference for output quality.
VALUE_RENDER_SPEED - Static variable in class java.awt.RenderingHints
Rendering hint value -- rendering algorithms are chosen with a preference for output speed.
VALUE_STROKE_DEFAULT - Static variable in class java.awt.RenderingHints
Stroke normalization control hint value -- geometry may be modified or left pure depending on the tradeoffs in a given implementation.
VALUE_STROKE_NORMALIZE - Static variable in class java.awt.RenderingHints
Stroke normalization control hint value -- geometry should be normalized to improve uniformity or spacing of lines and overall aesthetics.
VALUE_STROKE_PURE - Static variable in class java.awt.RenderingHints
Stroke normalization control hint value -- geometry should be left unmodified and rendered with sub-pixel accuracy.
VALUE_TEXT_ANTIALIAS_DEFAULT - Static variable in class java.awt.RenderingHints
Text antialiasing hint value -- text rendering is done according to the RenderingHints.KEY_ANTIALIASING hint or a default chosen by the implementation.
VALUE_TEXT_ANTIALIAS_GASP - Static variable in class java.awt.RenderingHints
Text antialiasing hint value -- text rendering is requested to use information in the font resource which specifies for each point size whether to apply RenderingHints.VALUE_TEXT_ANTIALIAS_ON or RenderingHints.VALUE_TEXT_ANTIALIAS_OFF.
VALUE_TEXT_ANTIALIAS_LCD_HBGR - Static variable in class java.awt.RenderingHints
Text antialiasing hint value -- request that text be displayed optimised for an LCD display with subpixels in order from display left to right of B,G,R such that the horizontal subpixel resolution is three times that of the full pixel horizontal resolution (HBGR).
VALUE_TEXT_ANTIALIAS_LCD_HRGB - Static variable in class java.awt.RenderingHints
Text antialiasing hint value -- request that text be displayed optimised for an LCD display with subpixels in order from display left to right of R,G,B such that the horizontal subpixel resolution is three times that of the full pixel horizontal resolution (HRGB).
VALUE_TEXT_ANTIALIAS_LCD_VBGR - Static variable in class java.awt.RenderingHints
Text antialiasing hint value -- request that text be displayed optimised for an LCD display with subpixel organisation from display top to bottom of B,G,R such that the vertical subpixel resolution is three times that of the full pixel vertical resolution (VBGR).
VALUE_TEXT_ANTIALIAS_LCD_VRGB - Static variable in class java.awt.RenderingHints
Text antialiasing hint value -- request that text be displayed optimised for an LCD display with subpixel organisation from display top to bottom of R,G,B such that the vertical subpixel resolution is three times that of the full pixel vertical resolution (VRGB).
VALUE_TEXT_ANTIALIAS_OFF - Static variable in class java.awt.RenderingHints
Text antialiasing hint value -- text rendering is done without any form of antialiasing.
VALUE_TEXT_ANTIALIAS_ON - Static variable in class java.awt.RenderingHints
Text antialiasing hint value -- text rendering is done with some form of antialiasing.
ValueBase - Interface in org.omg.CORBA.portable
The generated Java classes corresponding to valuetype IDL types implement this interface.
ValueBaseHelper - Class in org.omg.CORBA
ValueBaseHelper() - Constructor for class org.omg.CORBA.ValueBaseHelper
ValueBaseHolder - Class in org.omg.CORBA
The Holder for ValueBase.
ValueBaseHolder() - Constructor for class org.omg.CORBA.ValueBaseHolder
Constructs a new ValueBaseHolder object with its value field initialized to 0.
ValueBaseHolder(Serializable) - Constructor for class org.omg.CORBA.ValueBaseHolder
Constructs a new ValueBaseHolder object with its value field initialized to the given java.io.Serializable.
valueBound(SSLSessionBindingEvent) - Method in interface javax.net.ssl.SSLSessionBindingListener
This is called to notify the listener that it is being bound into an SSLSession.
valueChanged(ListSelectionEvent) - Method in interface javax.swing.event.ListSelectionListener
Called whenever the value of the selection changes.
valueChanged(TreeSelectionEvent) - Method in interface javax.swing.event.TreeSelectionListener
Called whenever the value of the selection changes.
valueChanged(ListSelectionEvent) - Method in class javax.swing.JList.AccessibleJList
List Selection Listener value change method.
valueChanged(ListSelectionEvent) - Method in class javax.swing.JTable.AccessibleJTable
Track changes to table cell selections
valueChanged(ListSelectionEvent) - Method in class javax.swing.JTable
Invoked when the row selection changes -- repaints to show the new selection.
valueChanged(TreeSelectionEvent) - Method in class javax.swing.JTree.AccessibleJTree
Tree Selection Listener value change method.
valueChanged(TreeSelectionEvent) - Method in class javax.swing.JTree.TreeSelectionRedirector
Invoked by the TreeSelectionModel when the selection changes.
valueChanged(ListSelectionEvent) - Method in class javax.swing.plaf.basic.BasicComboPopup.ListSelectionHandler
valueChanged(ListSelectionEvent) - Method in class javax.swing.plaf.basic.BasicFileChooserUI.SelectionListener
valueChanged(ListSelectionEvent) - Method in class javax.swing.plaf.basic.BasicListUI.ListSelectionHandler
valueChanged(TreeSelectionEvent) - Method in class javax.swing.plaf.basic.BasicTreeUI.TreeSelectionHandler
Messaged when the selection changes in the tree we're displaying for.
valueChanged(ListSelectionEvent) - Method in class javax.swing.plaf.metal.MetalFileChooserUI
valueChanged(ListSelectionEvent) - Method in class javax.swing.table.DefaultTableColumnModel
A ListSelectionListener that forwards ListSelectionEvents when there is a column selection change.
valueChanged(TreeSelectionEvent) - Method in class javax.swing.tree.DefaultTreeCellEditor
Resets lastPath.
ValueExp - Interface in javax.management
Represents values that can be passed as arguments to relational expressions.
ValueFactory - Interface in org.omg.CORBA.portable
The ValueFactory interface is the native mapping for the IDL type CORBA::ValueFactory.
valueForPathChanged(TreePath, Object) - Method in class javax.swing.tree.DefaultTreeModel
This sets the user object of the TreeNode identified by path and posts a node changed.
valueForPathChanged(TreePath, Object) - Method in interface javax.swing.tree.TreeModel
Messaged when the user has altered the value for the item identified by path to newValue.
valueForXPosition(int) - Method in class javax.swing.plaf.basic.BasicSliderUI
Returns the value at the x position.
valueForXPosition(int) - Method in class javax.swing.plaf.synth.SynthSliderUI
valueForYPosition(int) - Method in class javax.swing.plaf.basic.BasicSliderUI
Returns the value at the y position.
valueForYPosition(int) - Method in class javax.swing.plaf.synth.SynthSliderUI
ValueHandler - Interface in javax.rmi.CORBA
Defines methods which allow serialization of Java objects to and from GIOP streams.
ValueHandlerMultiFormat - Interface in javax.rmi.CORBA
Java to IDL ptc 02-01-12 1.5.1.5
ValueInputStream - Interface in org.omg.CORBA.portable
Java to IDL ptc 02-01-12 1.5.1.4 ValueInputStream is used for implementing RMI-IIOP stream format version 2.
valueIsAdjusting - Variable in class javax.swing.plaf.basic.BasicComboPopup
As of Java 2 platform v1.4 this previously undocumented field is no longer used.
ValueMember - Class in org.omg.CORBA
A description in the Interface Repository of a member of a value object.
ValueMember() - Constructor for class org.omg.CORBA.ValueMember
Constructs a default ValueMember object.
ValueMember(String, String, String, String, TypeCode, IDLType, short) - Constructor for class org.omg.CORBA.ValueMember
Constructs a ValueMember object initialized with the given values.
ValueMemberHelper - Class in org.omg.CORBA
The Helper for ValueMember.
ValueMemberHelper() - Constructor for class org.omg.CORBA.ValueMemberHelper
valueOf(String) - Static method in enum java.awt.Component.BaselineResizeBehavior
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.awt.Desktop.Action
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.awt.Dialog.ModalExclusionType
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.awt.Dialog.ModalityType
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.awt.font.NumericShaper.Range
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.awt.GraphicsDevice.WindowTranslucency
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.awt.MultipleGradientPaint.ColorSpaceType
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.awt.MultipleGradientPaint.CycleMethod
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.awt.TrayIcon.MessageType
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.awt.Window.Type
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.lang.annotation.ElementType
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.lang.annotation.RetentionPolicy
Returns the enum constant of this type with the specified name.
valueOf(boolean) - Static method in class java.lang.Boolean
Returns a Boolean instance representing the specified boolean value.
valueOf(String) - Static method in class java.lang.Boolean
Returns a Boolean with a value represented by the specified string.
valueOf(byte) - Static method in class java.lang.Byte
Returns a Byte instance representing the specified byte value.
valueOf(String, int) - Static method in class java.lang.Byte
Returns a Byte object holding the value extracted from the specified String when parsed with the radix given by the second argument.
valueOf(String) - Static method in class java.lang.Byte
Returns a Byte object holding the value given by the specified String.
valueOf(String) - Static method in enum java.lang.Character.UnicodeScript
Returns the enum constant of this type with the specified name.
valueOf(char) - Static method in class java.lang.Character
Returns a Character instance representing the specified char value.
valueOf(String) - Static method in class java.lang.Double
Returns a Double object holding the double value represented by the argument string s.
valueOf(double) - Static method in class java.lang.Double
Returns a Double instance representing the specified double value.
valueOf(Class<T>, String) - Static method in class java.lang.Enum
Returns the enum constant of the specified enum type with the specified name.
valueOf(String) - Static method in class java.lang.Float
Returns a Float object holding the float value represented by the argument string s.
valueOf(float) - Static method in class java.lang.Float
Returns a Float instance representing the specified float value.
valueOf(String, int) - Static method in class java.lang.Integer
Returns an Integer object holding the value extracted from the specified String when parsed with the radix given by the second argument.
valueOf(String) - Static method in class java.lang.Integer
Returns an Integer object holding the value of the specified String.
valueOf(int) - Static method in class java.lang.Integer
Returns an Integer instance representing the specified int value.
valueOf(String, int) - Static method in class java.lang.Long
Returns a Long object holding the value extracted from the specified String when parsed with the radix given by the second argument.
valueOf(String) - Static method in class java.lang.Long
Returns a Long object holding the value of the specified String.
valueOf(long) - Static method in class java.lang.Long
Returns a Long instance representing the specified long value.
valueOf(String) - Static method in enum java.lang.management.MemoryType
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.lang.ProcessBuilder.Redirect.Type
Returns the enum constant of this type with the specified name.
valueOf(String, int) - Static method in class java.lang.Short
Returns a Short object holding the value extracted from the specified String when parsed with the radix given by the second argument.
valueOf(String) - Static method in class java.lang.Short
Returns a Short object holding the value given by the specified String.
valueOf(short) - Static method in class java.lang.Short
Returns a Short instance representing the specified short value.
valueOf(Object) - Static method in class java.lang.String
Returns the string representation of the Object argument.
valueOf(char[]) - Static method in class java.lang.String
Returns the string representation of the char array argument.
valueOf(char[], int, int) - Static method in class java.lang.String
Returns the string representation of a specific subarray of the char array argument.
valueOf(boolean) - Static method in class java.lang.String
Returns the string representation of the boolean argument.
valueOf(char) - Static method in class java.lang.String
Returns the string representation of the char argument.
valueOf(int) - Static method in class java.lang.String
Returns the string representation of the int argument.
valueOf(long) - Static method in class java.lang.String
Returns the string representation of the long argument.
valueOf(float) - Static method in class java.lang.String
Returns the string representation of the float argument.
valueOf(double) - Static method in class java.lang.String
Returns the string representation of the double argument.
valueOf(String) - Static method in enum java.lang.Thread.State
Returns the enum constant of this type with the specified name.
valueOf(long, int) - Static method in class java.math.BigDecimal
Translates a long unscaled value and an int scale into a BigDecimal.
valueOf(long) - Static method in class java.math.BigDecimal
Translates a long value into a BigDecimal with a scale of zero.
valueOf(double) - Static method in class java.math.BigDecimal
Translates a double into a BigDecimal, using the double's canonical string representation provided by the Double.toString(double) method.
valueOf(long) - Static method in class java.math.BigInteger
Returns a BigInteger whose value is equal to that of the specified long.
valueOf(String) - Static method in enum java.math.RoundingMode
Returns the enum constant of this type with the specified name.
valueOf(int) - Static method in enum java.math.RoundingMode
Returns the RoundingMode object corresponding to a legacy integer rounding mode constant in BigDecimal.
valueOf(String) - Static method in enum java.net.Authenticator.RequestorType
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.net.Proxy.Type
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.net.StandardProtocolFamily
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.nio.file.AccessMode
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.nio.file.attribute.AclEntryFlag
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.nio.file.attribute.AclEntryPermission
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.nio.file.attribute.AclEntryType
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.nio.file.attribute.PosixFilePermission
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.nio.file.FileVisitOption
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.nio.file.FileVisitResult
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.nio.file.LinkOption
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.nio.file.StandardCopyOption
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.nio.file.StandardOpenOption
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.security.cert.CertPathValidatorException.BasicReason
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.security.cert.CRLReason
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.security.cert.PKIXReason
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.security.CryptoPrimitive
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.security.KeyRep.Type
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.sql.ClientInfoStatus
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in class java.sql.Date
Converts a string in JDBC date escape format to a Date value.
valueOf(String) - Static method in enum java.sql.PseudoColumnUsage
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.sql.RowIdLifetime
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in class java.sql.Time
Converts a string in JDBC time escape format to a Time value.
valueOf(String) - Static method in class java.sql.Timestamp
Converts a String object in JDBC timestamp escape format to a Timestamp value.
valueOf(String) - Static method in enum java.text.Normalizer.Form
Returns the enum constant of this type with the specified name.
valueOf(long[]) - Static method in class java.util.BitSet
Returns a new bit set containing all the bits in the given long array.
valueOf(LongBuffer) - Static method in class java.util.BitSet
Returns a new bit set containing all the bits in the given long buffer between its position and limit.
valueOf(byte[]) - Static method in class java.util.BitSet
Returns a new bit set containing all the bits in the given byte array.
valueOf(ByteBuffer) - Static method in class java.util.BitSet
Returns a new bit set containing all the bits in the given byte buffer between its position and limit.
valueOf(String) - Static method in enum java.util.concurrent.TimeUnit
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.util.Formatter.BigDecimalLayoutForm
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum java.util.Locale.Category
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.annotation.Resource.AuthenticationType
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.jws.soap.SOAPBinding.ParameterStyle
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.jws.soap.SOAPBinding.Style
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.jws.soap.SOAPBinding.Use
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.jws.WebParam.Mode
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.lang.model.element.ElementKind
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.lang.model.element.修饰符
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.lang.model.element.NestingKind
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.lang.model.SourceVersion
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.lang.model.type.TypeKind
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.net.ssl.SSLEngineResult.HandshakeStatus
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.net.ssl.SSLEngineResult.Status
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.swing.DropMode
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.swing.event.RowSorterEvent.Type
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.swing.GroupLayout.Alignment
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.swing.JTable.PrintMode
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.swing.LayoutStyle.ComponentPlacement
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.swing.plaf.nimbus.AbstractRegionPainter.PaintContext.CacheMode
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.swing.RowFilter.ComparisonType
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.swing.SortOrder
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.swing.SwingWorker.StateValue
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.swing.text.html.FormSubmitEvent.MethodType
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.tools.Diagnostic.Kind
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.tools.JavaFileObject.Kind
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.tools.StandardLocation
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.xml.bind.annotation.XmlAccessOrder
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.xml.bind.annotation.XmlAccessType
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.xml.bind.annotation.XmlNsForm
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in class javax.xml.namespace.QName
QName derived from parsing the formatted String.
valueOf(String) - Static method in enum javax.xml.ws.handler.MessageContext.Scope
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.xml.ws.Service.Mode
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum javax.xml.ws.soap.AddressingFeature.Responses
Returns the enum constant of this type with the specified name.
ValueOutputStream - Interface in org.omg.CORBA.portable
Java to IDL ptc 02-01-12 1.5.1.3 ValueOutputStream is used for implementing RMI-IIOP stream format version 2.
values() - Static method in enum java.awt.Component.BaselineResizeBehavior
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.awt.Desktop.Action
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.awt.Dialog.ModalExclusionType
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.awt.Dialog.ModalityType
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.awt.font.NumericShaper.Range
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.awt.GraphicsDevice.WindowTranslucency
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.awt.MultipleGradientPaint.ColorSpaceType
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.awt.MultipleGradientPaint.CycleMethod
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Method in class java.awt.RenderingHints
Returns a Collection view of the values contained in this RenderinHints.
values() - Static method in enum java.awt.TrayIcon.MessageType
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.awt.Window.Type
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.lang.annotation.ElementType
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.lang.annotation.RetentionPolicy
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.lang.Character.UnicodeScript
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.lang.management.MemoryType
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.lang.ProcessBuilder.Redirect.Type
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.lang.Thread.State
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.math.RoundingMode
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.net.Authenticator.RequestorType
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.net.Proxy.Type
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.net.StandardProtocolFamily
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.nio.file.AccessMode
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.nio.file.attribute.AclEntryFlag
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.nio.file.attribute.AclEntryPermission
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.nio.file.attribute.AclEntryType
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.nio.file.attribute.PosixFilePermission
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.nio.file.FileVisitOption
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.nio.file.FileVisitResult
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.nio.file.LinkOption
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.nio.file.StandardCopyOption
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.nio.file.StandardOpenOption
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.security.cert.CertPathValidatorException.BasicReason
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.security.cert.CRLReason
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.security.cert.PKIXReason
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.security.CryptoPrimitive
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.security.KeyRep.Type
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Method in class java.security.Provider
Returns an unmodifiable Collection view of the property values contained in this provider.
values() - Static method in enum java.sql.ClientInfoStatus
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.sql.PseudoColumnUsage
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.sql.RowIdLifetime
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum java.text.Normalizer.Form
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Method in class java.util.AbstractMap
Returns a Collection view of the values contained in this map.
values() - Method in class java.util.concurrent.ConcurrentHashMap
Returns a Collection view of the values contained in this map.
values() - Method in class java.util.concurrent.ConcurrentSkipListMap
Returns a Collection view of the values contained in this map.
values() - Static method in enum java.util.concurrent.TimeUnit
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Method in class java.util.EnumMap
Returns a Collection view of the values contained in this map.
values() - Static method in enum java.util.Formatter.BigDecimalLayoutForm
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Method in class java.util.HashMap
Returns a Collection view of the values contained in this map.
values() - Method in class java.util.Hashtable
Returns a Collection view of the values contained in this map.
values() - Method in class java.util.IdentityHashMap
Returns a Collection view of the values contained in this map.
values() - Method in class java.util.jar.Attributes
Returns a Collection view of the attribute values contained in this Map.
values() - Static method in enum java.util.Locale.Category
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Method in interface java.util.Map
Returns a Collection view of the values contained in this map.
values() - Method in interface java.util.SortedMap
Returns a Collection view of the values contained in this map.
values() - Method in class java.util.TreeMap
Returns a Collection view of the values contained in this map.
values() - Method in class java.util.WeakHashMap
Returns a Collection view of the values contained in this map.
values() - Static method in enum javax.annotation.Resource.AuthenticationType
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.jws.soap.SOAPBinding.ParameterStyle
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.jws.soap.SOAPBinding.Style
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.jws.soap.SOAPBinding.Use
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.jws.WebParam.Mode
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.lang.model.element.ElementKind
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.lang.model.element.修饰符
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.lang.model.element.NestingKind
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.lang.model.SourceVersion
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.lang.model.type.TypeKind
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Method in interface javax.management.openmbean.CompositeData
Returns an unmodifiable Collection view of the item values contained in this CompositeData instance.
values() - Method in class javax.management.openmbean.CompositeDataSupport
Returns an unmodifiable Collection view of the item values contained in this CompositeData instance.
values() - Method in interface javax.management.openmbean.TabularData
Returns a collection view of the CompositeData values (ie the rows) contained in this TabularData instance.
values() - Method in class javax.management.openmbean.TabularDataSupport
Returns a collection view of the rows contained in this TabularDataSupport instance.
values - Variable in class javax.naming.directory.BasicAttribute
Holds the attribute's values.
values() - Static method in enum javax.net.ssl.SSLEngineResult.HandshakeStatus
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.net.ssl.SSLEngineResult.Status
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Method in class javax.script.SimpleBindings
Returns a Collection view of the values contained in this map.
values() - Static method in enum javax.swing.DropMode
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.swing.event.RowSorterEvent.Type
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.swing.GroupLayout.Alignment
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.swing.JTable.PrintMode
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.swing.LayoutStyle.ComponentPlacement
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.swing.plaf.nimbus.AbstractRegionPainter.PaintContext.CacheMode
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.swing.RowFilter.ComparisonType
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.swing.SortOrder
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.swing.SwingWorker.StateValue
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.swing.text.html.FormSubmitEvent.MethodType
Returns an array containing the constants of this enum type, in the order they are declared.
values - Variable in class javax.swing.text.html.parser.AttributeList
values() - Static method in enum javax.tools.Diagnostic.Kind
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.tools.JavaFileObject.Kind
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.tools.StandardLocation
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.xml.bind.annotation.XmlAccessOrder
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.xml.bind.annotation.XmlAccessType
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.xml.bind.annotation.XmlNsForm
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.xml.ws.handler.MessageContext.Scope
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.xml.ws.Service.Mode
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum javax.xml.ws.soap.AddressingFeature.Responses
Returns an array containing the constants of this enum type, in the order they are declared.
valueToString(Object) - Method in class javax.swing.JFormattedTextField.AbstractFormatter
Returns the string value to display for value.
valueToString(Object) - Method in class javax.swing.text.DefaultFormatter
Converts the passed in Object into a String by way of the toString method.
valueToString(Object) - Method in class javax.swing.text.InternationalFormatter
Returns a String representation of the Object value.
valueToString(Object) - Method in class javax.swing.text.MaskFormatter
Returns a String representation of the Object value based on the mask.
VALUETYPE - Static variable in class javax.swing.text.html.HTML.Attribute
valueUnbound(SSLSessionBindingEvent) - Method in interface javax.net.ssl.SSLSessionBindingListener
This is called to notify the listener that it is being unbound from a SSLSession.
VAR - Static variable in class javax.swing.text.html.HTML.Tag
VARBINARY - Static variable in class java.sql.Types
The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type VARBINARY.
VARCHAR - Static variable in class java.sql.Types
The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type VARCHAR.
VariableElement - Interface in javax.lang.model.element
Represents a field, enum constant, method or constructor parameter, local variable, resource variable, or exception parameter.
VariableHeightLayoutCache - Class in javax.swing.tree
NOTE: This will become more open in a future release.
VariableHeightLayoutCache() - Constructor for class javax.swing.tree.VariableHeightLayoutCache
variant() - Method in class java.util.UUID
The variant number associated with this UUID.
VARIATION_SELECTORS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Variation Selectors" Unicode character block.
VARIATION_SELECTORS_SUPPLEMENT - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Variation Selectors Supplement" Unicode character block.
vcSupport - Variable in class java.beans.beancontext.BeanContextChildSupport
The VetoableChangeSupport associated with this BeanContextChildSupport.
Vector<E> - Class in java.util
The Vector class implements a growable array of objects.
Vector(int, int) - Constructor for class java.util.Vector
Constructs an empty vector with the specified initial capacity and capacity increment.
Vector(int) - Constructor for class java.util.Vector
Constructs an empty vector with the specified initial capacity and with its capacity increment equal to zero.
Vector() - Constructor for class java.util.Vector
Constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero.
Vector(Collection<? extends E>) - Constructor for class java.util.Vector
Constructs a vector containing the elements of the specified collection, in the order they are returned by the collection's iterator.
VEDIC_EXTENSIONS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Vedic Extensions" Unicode character block.
vendorName - Variable in class javax.imageio.spi.IIOServiceProvider
A String to be returned from getVendorName, initially null.
VERBOSE - Static variable in class java.rmi.server.LogStream
Deprecated.
log level constant (verbose logging).
verify(PublicKey) - Method in class java.security.cert.Certificate
Verifies that this certificate was signed using the private key that corresponds to the specified public key.
verify(PublicKey, String) - Method in class java.security.cert.Certificate
Verifies that this certificate was signed using the private key that corresponds to the specified public key.
verify(PublicKey) - Method in class java.security.cert.X509CRL
Verifies that this CRL was signed using the private key that corresponds to the given public key.
verify(PublicKey, String) - Method in class java.security.cert.X509CRL
Verifies that this CRL was signed using the private key that corresponds to the given public key.
VERIFY - Static variable in class java.security.Signature
Possible Signature.state value, signifying that this signature object has been initialized for verification.
verify(byte[]) - Method in class java.security.Signature
Verifies the passed-in signature.
verify(byte[], int, int) - Method in class java.security.Signature
Verifies the passed-in signature in the specified array of bytes, starting at the specified offset.
verify(PublicKey, Signature) - Method in class java.security.SignedObject
Verifies that the signature in this SignedObject is the valid signature for the object stored inside, with the given verification key, using the designated verification engine.
verify(String, SSLSession) - Method in interface javax.net.ssl.HostnameVerifier
Verify that the host name is an acceptable match with the server's authentication scheme.
verify(PublicKey) - Method in class javax.security.cert.Certificate
Verifies that this certificate was signed using the private key that corresponds to the specified public key.
verify(PublicKey, String) - Method in class javax.security.cert.Certificate
Verifies that this certificate was signed using the private key that corresponds to the specified public key.
verify(JComponent) - Method in class javax.swing.InputVerifier
Checks whether the JComponent's input is valid.
VERIFY - Static variable in class javax.xml.crypto.KeySelector.Purpose
A key for verifying.
verifyAttributeCategory(Object, Class<?>) - Static method in class javax.print.attribute.AttributeSetUtilities
Verify that the given object is a 类 that implements the given interface, which is assumed to be interface Attribute or a subinterface thereof.
verifyAttributeValue(Object, Class<?>) - Static method in class javax.print.attribute.AttributeSetUtilities
Verify that the given object is an instance of the given interface, which is assumed to be interface Attribute or a subinterface thereof.
verifyCategoryForValue(Class<?>, Attribute) - Static method in class javax.print.attribute.AttributeSetUtilities
Verify that the given attribute category object is equal to the category of the given attribute value object.
VerifyError - Error in java.lang
Thrown when the "verifier" detects that a class file, though well formed, contains some sort of internal inconsistency or security problem.
VerifyError() - Constructor for error java.lang.VerifyError
Constructs an VerifyError with no detail message.
VerifyError(String) - Constructor for error java.lang.VerifyError
Constructs an VerifyError with the specified detail message.
verifyMIC(byte[], int, int, byte[], int, int, MessageProp) - Method in interface org.ietf.jgss.GSSContext
Verifies the cryptographic MIC, contained in the token parameter, over the supplied message.
verifyMIC(InputStream, InputStream, MessageProp) - Method in interface org.ietf.jgss.GSSContext
Uses streams to verify the cryptographic MIC, contained in the token parameter, over the supplied message.
version() - Method in class java.util.UUID
The version number associated with this UUID.
version - Variable in class javax.imageio.spi.IIOServiceProvider
A String to be returned from getVersion, initially null.
VERSION - Static variable in class javax.swing.text.html.HTML.Attribute
VERSION - Static variable in class javax.xml.transform.OutputKeys
version = nmtoken.
version - Variable in class org.omg.CORBA.ValueMember
The version of the value in which this member is defined.
versionColumnNotPseudo - Static variable in interface java.sql.DatabaseMetaData
Indicates that this version column is NOT a pseudo column.
versionColumnPseudo - Static variable in interface java.sql.DatabaseMetaData
Indicates that this version column is a pseudo column.
versionColumnUnknown - Static variable in interface java.sql.DatabaseMetaData
Indicates that this version column may or may not be a pseudo column.
VersionSpecHelper - Class in org.omg.CORBA
The Helper for VersionSpec.
VersionSpecHelper() - Constructor for class org.omg.CORBA.VersionSpecHelper
VERTICAL - Static variable in interface java.awt.Adjustable
Indicates that the Adjustable has vertical orientation.
VERTICAL - Static variable in class java.awt.GridBagConstraints
Resize the component vertically but not horizontally.
VERTICAL - Static variable in class java.awt.Scrollbar
A constant that indicates a vertical scroll bar.
VERTICAL - Static variable in class javax.accessibility.AccessibleState
Indicates the orientation of this object is vertical.
VERTICAL - Static variable in class javax.swing.JList
Indicates a vertical layout of cells, in a single column; the default layout.
VERTICAL - Static variable in interface javax.swing.SwingConstants
Vertical orientation.
VERTICAL_ALIGN - Static variable in class javax.swing.text.html.CSS.Attribute
VERTICAL_ALIGNMENT_CHANGED_PROPERTY - Static variable in class javax.swing.AbstractButton
Identifies a change in the button's vertical alignment.
VERTICAL_CENTER - Static variable in class javax.swing.SpringLayout
Specifies the vertical center of a component's bounding rectangle.
VERTICAL_FORMS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Vertical Forms" Unicode character block.
VERTICAL_SCROLLBAR - Static variable in interface javax.swing.ScrollPaneConstants
Identifies a vertical scrollbar.
VERTICAL_SCROLLBAR_ALWAYS - Static variable in interface javax.swing.ScrollPaneConstants
Used to set the vertical scroll bar policy so that vertical scrollbars are always displayed.
VERTICAL_SCROLLBAR_AS_NEEDED - Static variable in interface javax.swing.ScrollPaneConstants
Used to set the vertical scroll bar policy so that vertical scrollbars are displayed only when needed.
VERTICAL_SCROLLBAR_NEVER - Static variable in interface javax.swing.ScrollPaneConstants
Used to set the vertical scroll bar policy so that vertical scrollbars are never displayed.
VERTICAL_SCROLLBAR_POLICY - Static variable in interface javax.swing.ScrollPaneConstants
Identifies the vertical scroll bar policy property.
VERTICAL_SPLIT - Static variable in class javax.swing.JSplitPane
Vertical split indicates the Components are split along the y axis.
VERTICAL_TEXT_POSITION_CHANGED_PROPERTY - Static variable in class javax.swing.AbstractButton
Identifies a change in the button's vertical text position.
VERTICAL_WRAP - Static variable in class javax.swing.JList
Indicates a "newspaper style" layout with cells flowing vertically then horizontally.
verticalScrollBar - Variable in class javax.swing.JScrollPane
The scrollpane's vertical scrollbar child.
verticalScrollBarPolicy - Variable in class javax.swing.JScrollPane
The display policy for the vertical scrollbar.
vertThumbIcon - Static variable in class javax.swing.plaf.metal.MetalSliderUI
A default vertical thumb Icon.
vetoableChange(PropertyChangeEvent) - Method in class java.beans.beancontext.BeanContextSupport
subclasses may envelope to monitor veto child property changes.
vetoableChange(PropertyChangeEvent) - Method in interface java.beans.VetoableChangeListener
This method gets called when a constrained property is changed.
vetoableChange(PropertyChangeEvent) - Method in class java.beans.VetoableChangeListenerProxy
Forwards the property change event to the listener delegate.
VetoableChangeListener - Interface in java.beans
A VetoableChange event gets fired whenever a bean changes a "constrained" property.
VetoableChangeListenerProxy - Class in java.beans
A class which extends the EventListenerProxy specifically for adding a VetoableChangeListener with a "constrained" property.
VetoableChangeListenerProxy(String, VetoableChangeListener) - Constructor for class java.beans.VetoableChangeListenerProxy
Constructor which binds the VetoableChangeListener to a specific property.
VetoableChangeSupport - Class in java.beans
This is a utility class that can be used by beans that support constrained properties.
VetoableChangeSupport(Object) - Constructor for class java.beans.VetoableChangeSupport
Constructs a VetoableChangeSupport object.
View - Class in javax.swing.text
A very important part of the text package is the View class.
View(Element) - Constructor for class javax.swing.text.View
Creates a new View object.
ViewFactory - Interface in javax.swing.text
A factory to create a view of some portion of document subject.
viewMenuIcon - Variable in class javax.swing.plaf.basic.BasicFileChooserUI
VIEWPORT - Static variable in class javax.accessibility.AccessibleRole
An object usually used in a scroll pane.
viewPort - Variable in class javax.swing.JScrollPane.AccessibleJScrollPane
viewport - Variable in class javax.swing.JScrollPane
The scrollpane's viewport child.
VIEWPORT - Static variable in class javax.swing.plaf.synth.Region
Viewport region.
VIEWPORT - Static variable in interface javax.swing.ScrollPaneConstants
Identifies a "viewport" or display area, within which scrolled contents are visible.
viewport - Variable in class javax.swing.ScrollPaneLayout
The scrollpane's viewport child.
viewportChangeListener - Variable in class javax.swing.plaf.basic.BasicScrollPaneUI
ViewportLayout - Class in javax.swing
The default layout manager for JViewport.
ViewportLayout() - Constructor for class javax.swing.ViewportLayout
ViewportUI - Class in javax.swing.plaf
Pluggable look and feel interface for JViewport.
ViewportUI() - Constructor for class javax.swing.plaf.ViewportUI
viewToModel(JTextComponent, Point) - Method in class javax.swing.plaf.basic.BasicTextUI
Converts the given place in the view coordinate system to the nearest representative location in the model.
viewToModel(JTextComponent, Point, Position.Bias[]) - Method in class javax.swing.plaf.basic.BasicTextUI
Converts the given place in the view coordinate system to the nearest representative location in the model.
viewToModel(JTextComponent, Point) - Method in class javax.swing.plaf.multi.MultiTextUI
Invokes the viewToModel method on each UI handled by this object.
viewToModel(JTextComponent, Point, Position.Bias[]) - Method in class javax.swing.plaf.multi.MultiTextUI
Invokes the viewToModel method on each UI handled by this object.
viewToModel(JTextComponent, Point) - Method in class javax.swing.plaf.TextUI
Converts the given place in the view coordinate system to the nearest representative location in the model.
viewToModel(JTextComponent, Point, Position.Bias[]) - Method in class javax.swing.plaf.TextUI
Provides a mapping from the view coordinate space to the logical coordinate space of the model.
viewToModel(float, float, Shape, Position.Bias[]) - Method in class javax.swing.text.AsyncBoxView
Provides a mapping from the view coordinate space to the logical coordinate space of the model.
viewToModel(float, float, Shape, Position.Bias[]) - Method in class javax.swing.text.BoxView
Provides a mapping from the view coordinate space to the logical coordinate space of the model.
viewToModel(float, float, Shape, Position.Bias[]) - Method in class javax.swing.text.ComponentView
Provides a mapping from the view coordinate space to the logical coordinate space of the model.
viewToModel(float, float, Shape, Position.Bias[]) - Method in class javax.swing.text.CompositeView
Provides a mapping from the view coordinate space to the logical coordinate space of the model.
viewToModel(float, float, Shape, Position.Bias[]) - Method in class javax.swing.text.FieldView
Provides a mapping from the view coordinate space to the logical coordinate space of the model.
viewToModel(GlyphView, float, float, Shape, Position.Bias[]) - Method in class javax.swing.text.GlyphView.GlyphPainter
Provides a mapping from the view coordinate space to the logical coordinate space of the model.
viewToModel(float, float, Shape, Position.Bias[]) - Method in class javax.swing.text.GlyphView
Provides a mapping from the view coordinate space to the logical coordinate space of the model.
viewToModel(float, float, Shape, Position.Bias[]) - Method in class javax.swing.text.html.ImageView
Provides a mapping from the view coordinate space to the logical coordinate space of the model.
viewToModel(float, float, Shape, Position.Bias[]) - Method in class javax.swing.text.IconView
Provides a mapping from the view coordinate space to the logical coordinate space of the model.
viewToModel(Point) - Method in class javax.swing.text.JTextComponent
Converts the given place in the view coordinate system to the nearest representative location in the model.
viewToModel(float, float, Shape, Position.Bias[]) - Method in class javax.swing.text.PasswordView
Provides a mapping from the view coordinate space to the logical coordinate space of the model.
viewToModel(float, float, Shape, Position.Bias[]) - Method in class javax.swing.text.PlainView
Provides a mapping from the view coordinate space to the logical coordinate space of the model.
viewToModel(float, float, Shape, Position.Bias[]) - Method in class javax.swing.text.View
Provides a mapping from the view coordinate space to the logical coordinate space of the model.
viewToModel(float, float, Shape) - Method in class javax.swing.text.View
Deprecated.
VirtualMachineError - Error in java.lang
Thrown to indicate that the Java Virtual Machine is broken or has run out of resources necessary for it to continue operating.
VirtualMachineError() - Constructor for error java.lang.VirtualMachineError
Constructs a VirtualMachineError with no detail message.
VirtualMachineError(String) - Constructor for error java.lang.VirtualMachineError
Constructs a VirtualMachineError with the specified detail message.
Visibility - Interface in java.beans
Under some circumstances a bean may be run on servers where a GUI is not available.
VisibilityHelper - Class in org.omg.CORBA
The Helper for Visibility.
VisibilityHelper() - Constructor for class org.omg.CORBA.VisibilityHelper
VISIBLE - Static variable in class javax.accessibility.AccessibleState
Indicates this object is visible.
VISIBLE_ROW_COUNT_PROPERTY - Static variable in class javax.swing.JTree
Bound property name for visibleRowCount.
visibleRowCount - Variable in class javax.swing.JTree
Number of rows to make visible at one time.
visit(AnnotationValue, P) - Method in interface javax.lang.model.element.AnnotationValueVisitor
Visits an annotation value.
visit(AnnotationValue) - Method in interface javax.lang.model.element.AnnotationValueVisitor
A convenience method equivalent to v.visit(av, null).
visit(Element, P) - Method in interface javax.lang.model.element.ElementVisitor
Visits an element.
visit(Element) - Method in interface javax.lang.model.element.ElementVisitor
A convenience method equivalent to v.visit(e, null).
visit(TypeMirror, P) - Method in interface javax.lang.model.type.TypeVisitor
Visits a type.
visit(TypeMirror) - Method in interface javax.lang.model.type.TypeVisitor
A convenience method equivalent to v.visit(t, null).
visit(AnnotationValue, P) - Method in class javax.lang.model.util.AbstractAnnotationValueVisitor6
Visits an annotation value as if by passing itself to that value's accept.
visit(AnnotationValue) - Method in class javax.lang.model.util.AbstractAnnotationValueVisitor6
Visits an annotation value as if by passing itself to that value's accept method passing null for the additional parameter.
visit(Element, P) - Method in class javax.lang.model.util.AbstractElementVisitor6
Visits any program element as if by passing itself to that element's accept method.
visit(Element) - Method in class javax.lang.model.util.AbstractElementVisitor6
Visits any program element as if by passing itself to that element's accept method and passing null for the additional parameter.
visit(TypeMirror, P) - Method in class javax.lang.model.util.AbstractTypeVisitor6
Visits any type mirror as if by passing itself to that type mirror's accept method.
visit(TypeMirror) - Method in class javax.lang.model.util.AbstractTypeVisitor6
Visits any type mirror as if by passing itself to that type mirror's accept method and passing null for the additional parameter.
visitAnnotation(AnnotationMirror, P) - Method in interface javax.lang.model.element.AnnotationValueVisitor
Visits an annotation value in an annotation.
visitAnnotation(AnnotationMirror, P) - Method in class javax.lang.model.util.SimpleAnnotationValueVisitor6
Visits an annotation value in an annotation.
visitArray(List<? extends AnnotationValue>, P) - Method in interface javax.lang.model.element.AnnotationValueVisitor
Visits an array value in an annotation.
visitArray(ArrayType, P) - Method in interface javax.lang.model.type.TypeVisitor
Visits an array type.
visitArray(List<? extends AnnotationValue>, P) - Method in class javax.lang.model.util.SimpleAnnotationValueVisitor6
Visits an array value in an annotation.
visitArray(ArrayType, P) - Method in class javax.lang.model.util.SimpleTypeVisitor6
Visits an array type.
visitBoolean(boolean, P) - Method in interface javax.lang.model.element.AnnotationValueVisitor
Visits a boolean value in an annotation.
visitBoolean(boolean, P) - Method in class javax.lang.model.util.SimpleAnnotationValueVisitor6
Visits a boolean value in an annotation.
visitByte(byte, P) - Method in interface javax.lang.model.element.AnnotationValueVisitor
Visits a byte value in an annotation.
visitByte(byte, P) - Method in class javax.lang.model.util.SimpleAnnotationValueVisitor6
Visits a byte value in an annotation.
visitChar(char, P) - Method in interface javax.lang.model.element.AnnotationValueVisitor
Visits a char value in an annotation.
visitChar(char, P) - Method in class javax.lang.model.util.SimpleAnnotationValueVisitor6
Visits a char value in an annotation.
visitDeclared(DeclaredType, P) - Method in interface javax.lang.model.type.TypeVisitor
Visits a declared type.
visitDeclared(DeclaredType, P) - Method in class javax.lang.model.util.SimpleTypeVisitor6
Visits a declared type.
visitDisjunctive(DisjunctiveType, P) - Method in interface javax.lang.model.type.TypeVisitor
Visits a disjunctive type.
visitDisjunctive(DisjunctiveType, P) - Method in class javax.lang.model.util.AbstractTypeVisitor6
Visits a DisjunctiveType element by calling visitUnknown.
visitDisjunctive(DisjunctiveType, P) - Method in class javax.lang.model.util.AbstractTypeVisitor7
Visits a DisjunctiveType in a manner defined by a subclass.
visitDisjunctive(DisjunctiveType, P) - Method in class javax.lang.model.util.SimpleTypeVisitor7
This implementation visits a DisjunctiveType by calling defaultAction.
visitDisjunctive(DisjunctiveType, P) - Method in class javax.lang.model.util.TypeKindVisitor7
This implementation visits a DisjunctiveType by calling defaultAction.
visitDouble(double, P) - Method in interface javax.lang.model.element.AnnotationValueVisitor
Visits a double value in an annotation.
visitDouble(double, P) - Method in class javax.lang.model.util.SimpleAnnotationValueVisitor6
Visits a double value in an annotation.
visitEnumConstant(VariableElement, P) - Method in interface javax.lang.model.element.AnnotationValueVisitor
Visits an enum value in an annotation.
visitEnumConstant(VariableElement, P) - Method in class javax.lang.model.util.SimpleAnnotationValueVisitor6
Visits an enum value in an annotation.
visitError(ErrorType, P) - Method in interface javax.lang.model.type.TypeVisitor
Visits an error type.
visitError(ErrorType, P) - Method in class javax.lang.model.util.SimpleTypeVisitor6
Visits an error type.
visitExecutable(ExecutableElement, P) - Method in interface javax.lang.model.element.ElementVisitor
Visits an executable element.
visitExecutable(ExecutableType, P) - Method in interface javax.lang.model.type.TypeVisitor
Visits an executable type.
visitExecutable(ExecutableElement, P) - Method in class javax.lang.model.util.ElementKindVisitor6
Visits an executable element, dispatching to the visit method for the specific kind of executable, CONSTRUCTOR, INSTANCE_INIT, METHOD, or STATIC_INIT.
visitExecutable(ExecutableElement, P) - Method in class javax.lang.model.util.ElementScanner6
Visits an executable element.
visitExecutable(ExecutableElement, P) - Method in class javax.lang.model.util.SimpleElementVisitor6
Visits an executable element.
visitExecutable(ExecutableType, P) - Method in class javax.lang.model.util.SimpleTypeVisitor6
Visits an executable type.
visitExecutableAsConstructor(ExecutableElement, P) - Method in class javax.lang.model.util.ElementKindVisitor6
Visits a CONSTRUCTOR executable element by calling defaultAction.
visitExecutableAsInstanceInit(ExecutableElement, P) - Method in class javax.lang.model.util.ElementKindVisitor6
Visits an INSTANCE_INIT executable element by calling defaultAction.
visitExecutableAsMethod(ExecutableElement, P) - Method in class javax.lang.model.util.ElementKindVisitor6
Visits a METHOD executable element by calling defaultAction.
visitExecutableAsStaticInit(ExecutableElement, P) - Method in class javax.lang.model.util.ElementKindVisitor6
Visits a STATIC_INIT executable element by calling defaultAction.
visitFile(T, BasicFileAttributes) - Method in interface java.nio.file.FileVisitor
Invoked for a file in a directory.
visitFile(T, BasicFileAttributes) - Method in class java.nio.file.SimpleFileVisitor
Invoked for a file in a directory.
visitFileFailed(T, IOException) - Method in interface java.nio.file.FileVisitor
Invoked for a file that could not be visited.
visitFileFailed(T, IOException) - Method in class java.nio.file.SimpleFileVisitor
Invoked for a file that could not be visited.
visitFloat(float, P) - Method in interface javax.lang.model.element.AnnotationValueVisitor
Visits a float value in an annotation.
visitFloat(float, P) - Method in class javax.lang.model.util.SimpleAnnotationValueVisitor6
Visits a float value in an annotation.
visitInt(int, P) - Method in interface javax.lang.model.element.AnnotationValueVisitor
Visits an int value in an annotation.
visitInt(int, P) - Method in class javax.lang.model.util.SimpleAnnotationValueVisitor6
Visits an int value in an annotation.
visitLong(long, P) - Method in interface javax.lang.model.element.AnnotationValueVisitor
Visits a long value in an annotation.
visitLong(long, P) - Method in class javax.lang.model.util.SimpleAnnotationValueVisitor6
Visits a long value in an annotation.
visitNoType(NoType, P) - Method in interface javax.lang.model.type.TypeVisitor
Visits a NoType instance.
visitNoType(NoType, P) - Method in class javax.lang.model.util.SimpleTypeVisitor6
Visits a NoType instance.
visitNoType(NoType, P) - Method in class javax.lang.model.util.TypeKindVisitor6
Visits a NoType instance, dispatching to the visit method for the specific kind of pseudo-type: VOID, 软件包, or NONE.
visitNoTypeAsNone(NoType, P) - Method in class javax.lang.model.util.TypeKindVisitor6
Visits a NONE pseudo-type by calling defaultAction.
visitNoTypeAsPackage(NoType, P) - Method in class javax.lang.model.util.TypeKindVisitor6
Visits a 软件包 pseudo-type by calling defaultAction.
visitNoTypeAsVoid(NoType, P) - Method in class javax.lang.model.util.TypeKindVisitor6
Visits a VOID pseudo-type by calling defaultAction.
visitNull(NullType, P) - Method in interface javax.lang.model.type.TypeVisitor
Visits the null type.
visitNull(NullType, P) - Method in class javax.lang.model.util.SimpleTypeVisitor6
Visits the null type.
visitPackage(PackageElement, P) - Method in interface javax.lang.model.element.ElementVisitor
Visits a package element.
visitPackage(PackageElement, P) - Method in class javax.lang.model.util.ElementKindVisitor6
Visits a package element.
visitPackage(PackageElement, P) - Method in class javax.lang.model.util.ElementScanner6
Visits a package element.
visitPackage(PackageElement, P) - Method in class javax.lang.model.util.SimpleElementVisitor6
Visits a package element.
visitPrimitive(PrimitiveType, P) - Method in interface javax.lang.model.type.TypeVisitor
Visits a primitive type.
visitPrimitive(PrimitiveType, P) - Method in class javax.lang.model.util.SimpleTypeVisitor6
Visits a primitive type.
visitPrimitive(PrimitiveType, P) - Method in class javax.lang.model.util.TypeKindVisitor6
Visits a primitive type, dispatching to the visit method for the specific kind of primitive type: BOOLEAN, BYTE, etc.
visitPrimitiveAsBoolean(PrimitiveType, P) - Method in class javax.lang.model.util.TypeKindVisitor6
Visits a BOOLEAN primitive type by calling defaultAction.
visitPrimitiveAsByte(PrimitiveType, P) - Method in class javax.lang.model.util.TypeKindVisitor6
Visits a BYTE primitive type by calling defaultAction.
visitPrimitiveAsChar(PrimitiveType, P) - Method in class javax.lang.model.util.TypeKindVisitor6
Visits a CHAR primitive type by calling defaultAction.
visitPrimitiveAsDouble(PrimitiveType, P) - Method in class javax.lang.model.util.TypeKindVisitor6
Visits a DOUBLE primitive type by calling defaultAction.
visitPrimitiveAsFloat(PrimitiveType, P) - Method in class javax.lang.model.util.TypeKindVisitor6
Visits a FLOAT primitive type by calling defaultAction.
visitPrimitiveAsInt(PrimitiveType, P) - Method in class javax.lang.model.util.TypeKindVisitor6
Visits an INT primitive type by calling defaultAction.
visitPrimitiveAsLong(PrimitiveType, P) - Method in class javax.lang.model.util.TypeKindVisitor6
Visits a LONG primitive type by calling defaultAction.
visitPrimitiveAsShort(PrimitiveType, P) - Method in class javax.lang.model.util.TypeKindVisitor6
Visits a SHORT primitive type by calling defaultAction.
visitShort(short, P) - Method in interface javax.lang.model.element.AnnotationValueVisitor
Visits a short value in an annotation.
visitShort(short, P) - Method in class javax.lang.model.util.SimpleAnnotationValueVisitor6
Visits a short value in an annotation.
visitString(String, P) - Method in interface javax.lang.model.element.AnnotationValueVisitor
Visits a string value in an annotation.
visitString(String, P) - Method in class javax.lang.model.util.SimpleAnnotationValueVisitor6
Visits a string value in an annotation.
visitType(TypeMirror, P) - Method in interface javax.lang.model.element.AnnotationValueVisitor
Visits a type value in an annotation.
visitType(TypeElement, P) - Method in interface javax.lang.model.element.ElementVisitor
Visits a type element.
visitType(TypeElement, P) - Method in class javax.lang.model.util.ElementKindVisitor6
Visits a type element, dispatching to the visit method for the specific kind of type, ANNOTATION_TYPE, 类, ENUM, or 接口.
visitType(TypeElement, P) - Method in class javax.lang.model.util.ElementScanner6
Visits a type element.
visitType(TypeMirror, P) - Method in class javax.lang.model.util.SimpleAnnotationValueVisitor6
Visits a type value in an annotation.
visitType(TypeElement, P) - Method in class javax.lang.model.util.SimpleElementVisitor6
Visits a type element.
visitTypeAsAnnotationType(TypeElement, P) - Method in class javax.lang.model.util.ElementKindVisitor6
Visits an ANNOTATION_TYPE type element by calling defaultAction.
visitTypeAsClass(TypeElement, P) - Method in class javax.lang.model.util.ElementKindVisitor6
Visits a 类 type element by calling defaultAction.
visitTypeAsEnum(TypeElement, P) - Method in class javax.lang.model.util.ElementKindVisitor6
Visits an ENUM type element by calling defaultAction.
visitTypeAsInterface(TypeElement, P) - Method in class javax.lang.model.util.ElementKindVisitor6
Visits an 接口 type element by calling defaultAction.
visitTypeParameter(TypeParameterElement, P) - Method in interface javax.lang.model.element.ElementVisitor
Visits a type parameter element.
visitTypeParameter(TypeParameterElement, P) - Method in class javax.lang.model.util.ElementKindVisitor6
Visits a type parameter element.
visitTypeParameter(TypeParameterElement, P) - Method in class javax.lang.model.util.ElementScanner6
Visits a type parameter element.
visitTypeParameter(TypeParameterElement, P) - Method in class javax.lang.model.util.SimpleElementVisitor6
Visits a type parameter element.
visitTypeVariable(TypeVariable, P) - Method in interface javax.lang.model.type.TypeVisitor
Visits a type variable.
visitTypeVariable(TypeVariable, P) - Method in class javax.lang.model.util.SimpleTypeVisitor6
Visits a type variable.
visitUnknown(AnnotationValue, P) - Method in interface javax.lang.model.element.AnnotationValueVisitor
Visits an unknown kind of annotation value.
visitUnknown(Element, P) - Method in interface javax.lang.model.element.ElementVisitor
Visits an unknown kind of element.
visitUnknown(TypeMirror, P) - Method in interface javax.lang.model.type.TypeVisitor
Visits an unknown kind of type.
visitUnknown(AnnotationValue, P) - Method in class javax.lang.model.util.AbstractAnnotationValueVisitor6
Visits an unknown kind of annotation value.
visitUnknown(Element, P) - Method in class javax.lang.model.util.AbstractElementVisitor6
Visits an unknown kind of element.
visitUnknown(TypeMirror, P) - Method in class javax.lang.model.util.AbstractTypeVisitor6
Visits an unknown kind of type.
visitVariable(VariableElement, P) - Method in interface javax.lang.model.element.ElementVisitor
Visits a variable element.
visitVariable(VariableElement, P) - Method in class javax.lang.model.util.ElementKindVisitor6
Visits a variable element, dispatching to the visit method for the specific kind of variable, ENUM_CONSTANT, EXCEPTION_PARAMETER, FIELD, LOCAL_VARIABLE, PARAMETER, or RESOURCE_VARIABLE.
visitVariable(VariableElement, P) - Method in class javax.lang.model.util.ElementScanner6
Visits a variable element.
visitVariable(VariableElement, P) - Method in class javax.lang.model.util.ElementScanner7
This implementation scans the enclosed elements.
visitVariable(VariableElement, P) - Method in class javax.lang.model.util.SimpleElementVisitor6
Visits a variable element.
visitVariable(VariableElement, P) - Method in class javax.lang.model.util.SimpleElementVisitor7
This implementation calls defaultAction.
visitVariableAsEnumConstant(VariableElement, P) - Method in class javax.lang.model.util.ElementKindVisitor6
Visits an ENUM_CONSTANT variable element by calling defaultAction.
visitVariableAsExceptionParameter(VariableElement, P) - Method in class javax.lang.model.util.ElementKindVisitor6
Visits an EXCEPTION_PARAMETER variable element by calling defaultAction.
visitVariableAsField(VariableElement, P) - Method in class javax.lang.model.util.ElementKindVisitor6
Visits a FIELD variable element by calling defaultAction.
visitVariableAsLocalVariable(VariableElement, P) - Method in class javax.lang.model.util.ElementKindVisitor6
Visits a LOCAL_VARIABLE variable element by calling defaultAction.
visitVariableAsParameter(VariableElement, P) - Method in class javax.lang.model.util.ElementKindVisitor6
Visits a PARAMETER variable element by calling defaultAction.
visitVariableAsResourceVariable(VariableElement, P) - Method in class javax.lang.model.util.ElementKindVisitor6
Visits a RESOURCE_VARIABLE variable element by calling visitUnknown.
visitVariableAsResourceVariable(VariableElement, P) - Method in class javax.lang.model.util.ElementKindVisitor7
Visits a RESOURCE_VARIABLE variable element by calling defaultAction.
visitWildcard(WildcardType, P) - Method in interface javax.lang.model.type.TypeVisitor
Visits a wildcard type.
visitWildcard(WildcardType, P) - Method in class javax.lang.model.util.SimpleTypeVisitor6
Visits a wildcard type.
VK_0 - Static variable in class java.awt.event.KeyEvent
VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 - 0x39)
VK_1 - Static variable in class java.awt.event.KeyEvent
VK_2 - Static variable in class java.awt.event.KeyEvent
VK_3 - Static variable in class java.awt.event.KeyEvent
VK_4 - Static variable in class java.awt.event.KeyEvent
VK_5 - Static variable in class java.awt.event.KeyEvent
VK_6 - Static variable in class java.awt.event.KeyEvent
VK_7 - Static variable in class java.awt.event.KeyEvent
VK_8 - Static variable in class java.awt.event.KeyEvent
VK_9 - Static variable in class java.awt.event.KeyEvent
VK_A - Static variable in class java.awt.event.KeyEvent
VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A)
VK_ACCEPT - Static variable in class java.awt.event.KeyEvent
Constant for the Accept or Commit function key.
VK_ADD - Static variable in class java.awt.event.KeyEvent
VK_AGAIN - Static variable in class java.awt.event.KeyEvent
VK_ALL_CANDIDATES - Static variable in class java.awt.event.KeyEvent
Constant for the All Candidates function key.
VK_ALPHANUMERIC - Static variable in class java.awt.event.KeyEvent
Constant for the Alphanumeric function key.
VK_ALT - Static variable in class java.awt.event.KeyEvent
VK_ALT_GRAPH - Static variable in class java.awt.event.KeyEvent
Constant for the AltGraph function key.
VK_AMPERSAND - Static variable in class java.awt.event.KeyEvent
VK_ASTERISK - Static variable in class java.awt.event.KeyEvent
VK_AT - Static variable in class java.awt.event.KeyEvent
Constant for the "@" key.
VK_B - Static variable in class java.awt.event.KeyEvent
VK_BACK_QUOTE - Static variable in class java.awt.event.KeyEvent
VK_BACK_SLASH - Static variable in class java.awt.event.KeyEvent
Constant for the back slash key, "\"
VK_BACK_SPACE - Static variable in class java.awt.event.KeyEvent
VK_BEGIN - Static variable in class java.awt.event.KeyEvent
Constant for the Begin key.
VK_BRACELEFT - Static variable in class java.awt.event.KeyEvent
VK_BRACERIGHT - Static variable in class java.awt.event.KeyEvent
VK_C - Static variable in class java.awt.event.KeyEvent
VK_CANCEL - Static variable in class java.awt.event.KeyEvent
VK_CAPS_LOCK - Static variable in class java.awt.event.KeyEvent
VK_CIRCUMFLEX - Static variable in class java.awt.event.KeyEvent
Constant for the "^" key.
VK_CLEAR - Static variable in class java.awt.event.KeyEvent
VK_CLOSE_BRACKET - Static variable in class java.awt.event.KeyEvent
Constant for the close bracket key, "]"
VK_CODE_INPUT - Static variable in class java.awt.event.KeyEvent
Constant for the Code Input function key.
VK_COLON - Static variable in class java.awt.event.KeyEvent
Constant for the ":" key.
VK_COMMA - Static variable in class java.awt.event.KeyEvent
Constant for the comma key, ","
VK_COMPOSE - Static variable in class java.awt.event.KeyEvent
Constant for the Compose function key.
VK_CONTEXT_MENU - Static variable in class java.awt.event.KeyEvent
Constant for the Microsoft Windows Context Menu key.
VK_CONTROL - Static variable in class java.awt.event.KeyEvent
VK_CONVERT - Static variable in class java.awt.event.KeyEvent
Constant for the Convert function key.
VK_COPY - Static variable in class java.awt.event.KeyEvent
VK_CUT - Static variable in class java.awt.event.KeyEvent
VK_D - Static variable in class java.awt.event.KeyEvent
VK_DEAD_ABOVEDOT - Static variable in class java.awt.event.KeyEvent
VK_DEAD_ABOVERING - Static variable in class java.awt.event.KeyEvent
VK_DEAD_ACUTE - Static variable in class java.awt.event.KeyEvent
VK_DEAD_BREVE - Static variable in class java.awt.event.KeyEvent
VK_DEAD_CARON - Static variable in class java.awt.event.KeyEvent
VK_DEAD_CEDILLA - Static variable in class java.awt.event.KeyEvent
VK_DEAD_CIRCUMFLEX - Static variable in class java.awt.event.KeyEvent
VK_DEAD_DIAERESIS - Static variable in class java.awt.event.KeyEvent
VK_DEAD_DOUBLEACUTE - Static variable in class java.awt.event.KeyEvent
VK_DEAD_GRAVE - Static variable in class java.awt.event.KeyEvent
VK_DEAD_IOTA - Static variable in class java.awt.event.KeyEvent
VK_DEAD_MACRON - Static variable in class java.awt.event.KeyEvent
VK_DEAD_OGONEK - Static variable in class java.awt.event.KeyEvent
VK_DEAD_SEMIVOICED_SOUND - Static variable in class java.awt.event.KeyEvent
VK_DEAD_TILDE - Static variable in class java.awt.event.KeyEvent
VK_DEAD_VOICED_SOUND - Static variable in class java.awt.event.KeyEvent
VK_DECIMAL - Static variable in class java.awt.event.KeyEvent
VK_DELETE - Static variable in class java.awt.event.KeyEvent
VK_DIVIDE - Static variable in class java.awt.event.KeyEvent
VK_DOLLAR - Static variable in class java.awt.event.KeyEvent
Constant for the "$" key.
VK_DOWN - Static variable in class java.awt.event.KeyEvent
Constant for the non-numpad down arrow key.
VK_E - Static variable in class java.awt.event.KeyEvent
VK_END - Static variable in class java.awt.event.KeyEvent
VK_ENTER - Static variable in class java.awt.event.KeyEvent
VK_EQUALS - Static variable in class java.awt.event.KeyEvent
Constant for the equals key, "="
VK_ESCAPE - Static variable in class java.awt.event.KeyEvent
VK_EURO_SIGN - Static variable in class java.awt.event.KeyEvent
Constant for the Euro currency sign key.
VK_EXCLAMATION_MARK - Static variable in class java.awt.event.KeyEvent
Constant for the "!" key.
VK_F - Static variable in class java.awt.event.KeyEvent
VK_F1 - Static variable in class java.awt.event.KeyEvent
Constant for the F1 function key.
VK_F10 - Static variable in class java.awt.event.KeyEvent
Constant for the F10 function key.
VK_F11 - Static variable in class java.awt.event.KeyEvent
Constant for the F11 function key.
VK_F12 - Static variable in class java.awt.event.KeyEvent
Constant for the F12 function key.
VK_F13 - Static variable in class java.awt.event.KeyEvent
Constant for the F13 function key.
VK_F14 - Static variable in class java.awt.event.KeyEvent
Constant for the F14 function key.
VK_F15 - Static variable in class java.awt.event.KeyEvent
Constant for the F15 function key.
VK_F16 - Static variable in class java.awt.event.KeyEvent
Constant for the F16 function key.
VK_F17 - Static variable in class java.awt.event.KeyEvent
Constant for the F17 function key.
VK_F18 - Static variable in class java.awt.event.KeyEvent
Constant for the F18 function key.
VK_F19 - Static variable in class java.awt.event.KeyEvent
Constant for the F19 function key.
VK_F2 - Static variable in class java.awt.event.KeyEvent
Constant for the F2 function key.
VK_F20 - Static variable in class java.awt.event.KeyEvent
Constant for the F20 function key.
VK_F21 - Static variable in class java.awt.event.KeyEvent
Constant for the F21 function key.
VK_F22 - Static variable in class java.awt.event.KeyEvent
Constant for the F22 function key.
VK_F23 - Static variable in class java.awt.event.KeyEvent
Constant for the F23 function key.
VK_F24 - Static variable in class java.awt.event.KeyEvent
Constant for the F24 function key.
VK_F3 - Static variable in class java.awt.event.KeyEvent
Constant for the F3 function key.
VK_F4 - Static variable in class java.awt.event.KeyEvent
Constant for the F4 function key.
VK_F5 - Static variable in class java.awt.event.KeyEvent
Constant for the F5 function key.
VK_F6 - Static variable in class java.awt.event.KeyEvent
Constant for the F6 function key.
VK_F7 - Static variable in class java.awt.event.KeyEvent
Constant for the F7 function key.
VK_F8 - Static variable in class java.awt.event.KeyEvent
Constant for the F8 function key.
VK_F9 - Static variable in class java.awt.event.KeyEvent
Constant for the F9 function key.
VK_FINAL - Static variable in class java.awt.event.KeyEvent
VK_FIND - Static variable in class java.awt.event.KeyEvent
VK_FULL_WIDTH - Static variable in class java.awt.event.KeyEvent
Constant for the Full-Width Characters function key.
VK_G - Static variable in class java.awt.event.KeyEvent
VK_GREATER - Static variable in class java.awt.event.KeyEvent
VK_H - Static variable in class java.awt.event.KeyEvent
VK_HALF_WIDTH - Static variable in class java.awt.event.KeyEvent
Constant for the Half-Width Characters function key.
VK_HELP - Static variable in class java.awt.event.KeyEvent
VK_HIRAGANA - Static variable in class java.awt.event.KeyEvent
Constant for the Hiragana function key.
VK_HOME - Static variable in class java.awt.event.KeyEvent
VK_I - Static variable in class java.awt.event.KeyEvent
VK_INPUT_METHOD_ON_OFF - Static variable in class java.awt.event.KeyEvent
Constant for the input method on/off key.
VK_INSERT - Static variable in class java.awt.event.KeyEvent
VK_INVERTED_EXCLAMATION_MARK - Static variable in class java.awt.event.KeyEvent
Constant for the inverted exclamation mark key.
VK_J - Static variable in class java.awt.event.KeyEvent
VK_JAPANESE_HIRAGANA - Static variable in class java.awt.event.KeyEvent
Constant for the Japanese-Hiragana function key.
VK_JAPANESE_KATAKANA - Static variable in class java.awt.event.KeyEvent
Constant for the Japanese-Katakana function key.
VK_JAPANESE_ROMAN - Static variable in class java.awt.event.KeyEvent
Constant for the Japanese-Roman function key.
VK_K - Static variable in class java.awt.event.KeyEvent
VK_KANA - Static variable in class java.awt.event.KeyEvent
VK_KANA_LOCK - Static variable in class java.awt.event.KeyEvent
Constant for the locking Kana function key.
VK_KANJI - Static variable in class java.awt.event.KeyEvent
VK_KATAKANA - Static variable in class java.awt.event.KeyEvent
Constant for the Katakana function key.
VK_KP_DOWN - Static variable in class java.awt.event.KeyEvent
Constant for the numeric keypad down arrow key.
VK_KP_LEFT - Static variable in class java.awt.event.KeyEvent
Constant for the numeric keypad left arrow key.
VK_KP_RIGHT - Static variable in class java.awt.event.KeyEvent
Constant for the numeric keypad right arrow key.
VK_KP_UP - Static variable in class java.awt.event.KeyEvent
Constant for the numeric keypad up arrow key.
VK_L - Static variable in class java.awt.event.KeyEvent
VK_LEFT - Static variable in class java.awt.event.KeyEvent
Constant for the non-numpad left arrow key.
VK_LEFT_PARENTHESIS - Static variable in class java.awt.event.KeyEvent
Constant for the "(" key.
VK_LESS - Static variable in class java.awt.event.KeyEvent
VK_M - Static variable in class java.awt.event.KeyEvent
VK_META - Static variable in class java.awt.event.KeyEvent
VK_MINUS - Static variable in class java.awt.event.KeyEvent
Constant for the minus key, "-"
VK_MODECHANGE - Static variable in class java.awt.event.KeyEvent
VK_MULTIPLY - Static variable in class java.awt.event.KeyEvent
VK_N - Static variable in class java.awt.event.KeyEvent
VK_NONCONVERT - Static variable in class java.awt.event.KeyEvent
Constant for the Don't Convert function key.
VK_NUM_LOCK - Static variable in class java.awt.event.KeyEvent
VK_NUMBER_SIGN - Static variable in class java.awt.event.KeyEvent
Constant for the "#" key.
VK_NUMPAD0 - Static variable in class java.awt.event.KeyEvent
VK_NUMPAD1 - Static variable in class java.awt.event.KeyEvent
VK_NUMPAD2 - Static variable in class java.awt.event.KeyEvent
VK_NUMPAD3 - Static variable in class java.awt.event.KeyEvent
VK_NUMPAD4 - Static variable in class java.awt.event.KeyEvent
VK_NUMPAD5 - Static variable in class java.awt.event.KeyEvent
VK_NUMPAD6 - Static variable in class java.awt.event.KeyEvent
VK_NUMPAD7 - Static variable in class java.awt.event.KeyEvent
VK_NUMPAD8 - Static variable in class java.awt.event.KeyEvent
VK_NUMPAD9 - Static variable in class java.awt.event.KeyEvent
VK_O - Static variable in class java.awt.event.KeyEvent
VK_OPEN_BRACKET - Static variable in class java.awt.event.KeyEvent
Constant for the open bracket key, "["
VK_P - Static variable in class java.awt.event.KeyEvent
VK_PAGE_DOWN - Static variable in class java.awt.event.KeyEvent
VK_PAGE_UP - Static variable in class java.awt.event.KeyEvent
VK_PASTE - Static variable in class java.awt.event.KeyEvent
VK_PAUSE - Static variable in class java.awt.event.KeyEvent
VK_PERIOD - Static variable in class java.awt.event.KeyEvent
Constant for the period key, "."
VK_PLUS - Static variable in class java.awt.event.KeyEvent
Constant for the "+" key.
VK_PREVIOUS_CANDIDATE - Static variable in class java.awt.event.KeyEvent
Constant for the Previous Candidate function key.
VK_PRINTSCREEN - Static variable in class java.awt.event.KeyEvent
VK_PROPS - Static variable in class java.awt.event.KeyEvent
VK_Q - Static variable in class java.awt.event.KeyEvent
VK_QUOTE - Static variable in class java.awt.event.KeyEvent
VK_QUOTEDBL - Static variable in class java.awt.event.KeyEvent
VK_R - Static variable in class java.awt.event.KeyEvent
VK_RIGHT - Static variable in class java.awt.event.KeyEvent
Constant for the non-numpad right arrow key.
VK_RIGHT_PARENTHESIS - Static variable in class java.awt.event.KeyEvent
Constant for the ")" key.
VK_ROMAN_CHARACTERS - Static variable in class java.awt.event.KeyEvent
Constant for the Roman Characters function key.
VK_S - Static variable in class java.awt.event.KeyEvent
VK_SCROLL_LOCK - Static variable in class java.awt.event.KeyEvent
VK_SEMICOLON - Static variable in class java.awt.event.KeyEvent
Constant for the semicolon key, ";"
VK_SEPARATER - Static variable in class java.awt.event.KeyEvent
This constant is obsolete, and is included only for backwards compatibility.
VK_SEPARATOR - Static variable in class java.awt.event.KeyEvent
Constant for the Numpad Separator key.
VK_SHIFT - Static variable in class java.awt.event.KeyEvent
VK_SLASH - Static variable in class java.awt.event.KeyEvent
Constant for the forward slash key, "/"
VK_SPACE - Static variable in class java.awt.event.KeyEvent
VK_STOP - Static variable in class java.awt.event.KeyEvent
VK_SUBTRACT - Static variable in class java.awt.event.KeyEvent
VK_T - Static variable in class java.awt.event.KeyEvent
VK_TAB - Static variable in class java.awt.event.KeyEvent
VK_U - Static variable in class java.awt.event.KeyEvent
VK_UNDEFINED - Static variable in class java.awt.event.KeyEvent
This value is used to indicate that the keyCode is unknown.
VK_UNDERSCORE - Static variable in class java.awt.event.KeyEvent
Constant for the "_" key.
VK_UNDO - Static variable in class java.awt.event.KeyEvent
VK_UP - Static variable in class java.awt.event.KeyEvent
Constant for the non-numpad up arrow key.
VK_V - Static variable in class java.awt.event.KeyEvent
VK_W - Static variable in class java.awt.event.KeyEvent
VK_WINDOWS - Static variable in class java.awt.event.KeyEvent
Constant for the Microsoft Windows "Windows" key.
VK_X - Static variable in class java.awt.event.KeyEvent
VK_Y - Static variable in class java.awt.event.KeyEvent
VK_Z - Static variable in class java.awt.event.KeyEvent
VLINK - Static variable in class javax.swing.text.html.HTML.Attribute
VM_ABSTRACT - Interface in org.omg.CORBA
Defines the code used to represent an Abstract interface in a typecode.
VM_CUSTOM - Interface in org.omg.CORBA
Defines the code used to represent a custom marshalled value type in a typecode.
VM_NONE - Interface in org.omg.CORBA
Defines the code used to represent the one of the values of a value type in a typecode.
VM_TRUNCATABLE - Interface in org.omg.CORBA
Defines the code used to represent a truncatable value type in a typecode.
VMID - Class in java.rmi.dgc
A VMID is a identifier that is unique across all Java virtual machines.
VMID() - Constructor for class java.rmi.dgc.VMID
Create a new VMID.
VoiceStatus - Class in javax.sound.midi
A VoiceStatus object contains information about the current status of one of the voices produced by a Synthesizer.
VoiceStatus() - Constructor for class javax.sound.midi.VoiceStatus
Void - Class in java.lang
The Void class is an uninstantiable placeholder class to hold a reference to the 类 object representing the Java keyword void.
VOID - Static variable in class javax.management.openmbean.SimpleType
The SimpleType instance describing values whose Java class name is java.lang.Void.
VOLATILE - Static variable in class java.lang.reflect.修饰符
The int value representing the volatile modifier.
VolatileCallSite - Class in java.lang.invoke
A VolatileCallSite is a CallSite whose target acts like a volatile variable.
VolatileCallSite(MethodType) - Constructor for class java.lang.invoke.VolatileCallSite
Creates a call site with a volatile binding to its target.
VolatileCallSite(MethodHandle) - Constructor for class java.lang.invoke.VolatileCallSite
Creates a call site with a volatile binding to its target.
VolatileImage - Class in java.awt.image
VolatileImage is an image which can lose its contents at any time due to circumstances beyond the control of the application (e.g., situations caused by the operating system or by other applications).
VolatileImage() - Constructor for class java.awt.image.VolatileImage
volume - Variable in class javax.sound.midi.VoiceStatus
The current MIDI volume level for the voice.
VOLUME - Static variable in class javax.sound.sampled.FloatControl.Type
Represents a control for the volume on a line.
vsb - Variable in class javax.swing.ScrollPaneLayout
The scrollpane's vertical scrollbar child.
vsbChangeListener - Variable in class javax.swing.plaf.basic.BasicScrollPaneUI
vsbPolicy - Variable in class javax.swing.ScrollPaneLayout
The display policy for the vertical scrollbar.
VSPACE - Static variable in class javax.swing.text.html.HTML.Attribute
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类

提交错误或意见
有关更多的 API 参考资料和开发人员文档，请参阅 Java SE 开发人员文档. 该文档包含更详细的、面向开发人员的描述，以及总体概述、术语定义、使用技巧和工作代码示例。
版权所有 © 1993, 2011, Oracle 及其联盟会员。保留所有权利。
草案 ea-b138

td<"a.i c"hhagrSiad


W-Index

请注意：本 java api 1.7Beta 规范不是最终稳定版，未来随着版本的更迭，本规范可能有更新。
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _

W

W3C_LENGTH_UNITS - Static variable in class javax.swing.JEditorPane
Key for a client property used to indicate whether w3c compliant length units are used for html rendering.
W3C_XML_SCHEMA_INSTANCE_NS_URI - Static variable in class javax.xml.XMLConstants
W3C XML Schema Instance Namespace URI.
W3C_XML_SCHEMA_NS_URI - Static variable in class javax.xml.XMLConstants
W3C XML Schema Namespace URI.
W3C_XPATH_DATATYPE_NS_URI - Static variable in class javax.xml.XMLConstants
W3C XPath Datatype Namespace URI.
W3CDomHandler - Class in javax.xml.bind.annotation
DomHandler implementation for W3C DOM (org.w3c.dom package.)
W3CDomHandler() - Constructor for class javax.xml.bind.annotation.W3CDomHandler
Default constructor.
W3CDomHandler(DocumentBuilder) - Constructor for class javax.xml.bind.annotation.W3CDomHandler
Constructor that allows applications to specify which DOM implementation to be used.
W3CEndpointReference - Class in javax.xml.ws.wsaddressing
This class represents a W3C Addressing EndpointReferece which is a remote reference to a web service endpoint that supports the W3C WS-Addressing 1.0 - Core Recommendation.
W3CEndpointReference() - Constructor for class javax.xml.ws.wsaddressing.W3CEndpointReference
W3CEndpointReference(Source) - Constructor for class javax.xml.ws.wsaddressing.W3CEndpointReference
Creates an EPR from infoset representation
W3CEndpointReferenceBuilder - Class in javax.xml.ws.wsaddressing
This class is used to build W3CEndpointReference instances.
W3CEndpointReferenceBuilder() - Constructor for class javax.xml.ws.wsaddressing.W3CEndpointReferenceBuilder
Creates a new W3CEndpointReferenceBuilder instance.
W_RESIZE_CURSOR - Static variable in class java.awt.Cursor
The west-resize cursor type.
W_RESIZE_CURSOR - Static variable in class java.awt.Frame
Deprecated.
replaced by Cursor.W_RESIZE_CURSOR.
WAIS - Static variable in class javax.print.attribute.standard.ReferenceUriSchemesSupported
Wide Area Information Server (WAIS) protocol.
wait(long) - Method in class java.lang.Object
Causes the current thread to wait until either another thread invokes the Object.notify() method or the Object.notifyAll() method for this object, or a specified amount of time has elapsed.
wait(long, int) - Method in class java.lang.Object
Causes the current thread to wait until another thread invokes the Object.notify() method or the Object.notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.
wait() - Method in class java.lang.Object
Causes the current thread to wait until another thread invokes the Object.notify() method or the Object.notifyAll() method for this object.
WAIT_CURSOR - Static variable in class java.awt.Cursor
The wait cursor type.
WAIT_CURSOR - Static variable in class java.awt.Frame
Deprecated.
replaced by Cursor.WAIT_CURSOR.
waitFor() - Method in class java.lang.Process
Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.
waitForAll() - Method in class java.awt.MediaTracker
Starts loading all images tracked by this media tracker.
waitForAll(long) - Method in class java.awt.MediaTracker
Starts loading all images tracked by this media tracker.
waitForID(int) - Method in class java.awt.MediaTracker
Starts loading all images tracked by this media tracker with the specified identifier.
waitForID(int, long) - Method in class java.awt.MediaTracker
Starts loading all images tracked by this media tracker with the specified identifier.
waitForIdle() - Method in class java.awt.Robot
Waits until all events currently on the event queue have been processed.
waitForWork() - Method in class javax.swing.text.LayoutQueue
Used by the worker thread to get a new task to execute
wakeup() - Method in class java.nio.channels.Selector
Causes the first selection operation that has not yet returned to return immediately.
walkFileTree(Path, Set<FileVisitOption>, int, FileVisitor<? super Path>) - Static method in class java.nio.file.Files
Walks a file tree.
walkFileTree(Path, FileVisitor<? super Path>) - Static method in class java.nio.file.Files
Walks a file tree.
WALL_TIME - Static variable in class java.util.SimpleTimeZone
Constant for a mode of start or end time specified as wall clock time.
WANTS_INPUT_PROPERTY - Static variable in class javax.swing.JOptionPane
Bound property name for wantsInput.
wantsInput - Variable in class javax.swing.JOptionPane
If true, a UI widget will be provided to the user to get input.
WARNING - Static variable in class java.util.logging.Level
WARNING is a message level indicating a potential problem.
warning(String) - Method in class java.util.logging.Logger
Log a WARNING message.
WARNING - Static variable in class javax.print.attribute.standard.Severity
Indicates that the PrinterStateReason is a "warning." An implementation may choose to omit some or all warnings.
WARNING - Static variable in class javax.security.auth.callback.ConfirmationCallback
WARNING message type.
WARNING - Static variable in class javax.security.auth.callback.TextOutputCallback
Warning message.
WARNING - Static variable in interface javax.xml.bind.ValidationEvent
Conditions that are not errors or fatal errors as defined by the XML 1.0 recommendation
warning(TransformerException) - Method in interface javax.xml.transform.ErrorListener
Receive notification of a warning.
warning(SAXParseException) - Method in interface org.xml.sax.ErrorHandler
Receive notification of a warning.
warning(SAXParseException) - Method in class org.xml.sax.HandlerBase
Deprecated.
Receive notification of a parser warning.
warning(SAXParseException) - Method in class org.xml.sax.helpers.DefaultHandler
Receive notification of a parser warning.
warning(SAXParseException) - Method in class org.xml.sax.helpers.XMLFilterImpl
Filter a warning event.
WARNING_DIALOG - Static variable in class javax.swing.JRootPane
Constant used for the windowDecorationStyle property.
WARNING_MESSAGE - Static variable in class javax.swing.JOptionPane
Used for warning messages.
warningListeners - Variable in class javax.imageio.ImageReader
A List of currently registered IIOReadWarningListeners, initialized by default to null, which is synonymous with an empty List.
warningListeners - Variable in class javax.imageio.ImageWriter
A List of currently registered IIOWriteWarningListeners, initialized by default to null, which is synonymous with an empty List.
warningLocales - Variable in class javax.imageio.ImageReader
A List of the Locales associated with each currently registered IIOReadWarningListener, initialized by default to null, which is synonymous with an empty List.
warningLocales - Variable in class javax.imageio.ImageWriter
A List of Locales, one for each element of warningListeners, initialized by default null, which is synonymous with an empty List.
warningOccurred(ImageReader, String) - Method in interface javax.imageio.event.IIOReadWarningListener
Reports the occurence of a non-fatal error in decoding.
warningOccurred(ImageWriter, int, String) - Method in interface javax.imageio.event.IIOWriteWarningListener
Reports the occurence of a non-fatal error in encoding.
wasFocused - Variable in class javax.swing.plaf.basic.BasicMenuUI.ChangeHandler
wasIcon(JInternalFrame) - Method in class javax.swing.DefaultDesktopManager
Returns true if the component has been iconized and the bounds of the desktopIcon are valid, otherwise returns false.
wasNull() - Method in interface java.sql.CallableStatement
Retrieves whether the last OUT parameter read had the value of SQL NULL.
wasNull() - Method in interface java.sql.ResultSet
Reports whether the last column read had a value of SQL NULL.
wasNull() - Method in interface java.sql.SQLInput
Retrieves whether the last value read was SQL NULL.
wasNull() - Method in class javax.sql.rowset.serial.SQLInputImpl
Ascertains whether the last value read from this SQLInputImpl object was null.
Watchable - Interface in java.nio.file
An object that may be registered with a watch service so that it can be watched for changes and events.
watchable() - Method in interface java.nio.file.WatchKey
Returns the object for which this watch key was created.
WatchEvent<T> - Interface in java.nio.file
An event or a repeated event for an object that is registered with a WatchService.
WatchEvent.Kind<T> - Interface in java.nio.file
An event kind, for the purposes of identification.
WatchEvent.Modifier - Interface in java.nio.file
An event modifier that qualifies how a Watchable is registered with a WatchService.
WatchKey - Interface in java.nio.file
A token representing the registration of a watchable object with a WatchService.
WatchService - Interface in java.nio.file
A watch service that watches registered objects for changes and events.
WAVE - Static variable in class javax.sound.sampled.AudioFileFormat.Type
Specifies a WAVE file.
WCharSeqHelper - Class in org.omg.CORBA
The Helper for WCharSeq.
WCharSeqHelper() - Constructor for class org.omg.CORBA.WCharSeqHelper
WCharSeqHolder - Class in org.omg.CORBA
The Holder for WCharSeq.
WCharSeqHolder() - Constructor for class org.omg.CORBA.WCharSeqHolder
WCharSeqHolder(char[]) - Constructor for class org.omg.CORBA.WCharSeqHolder
weakCompareAndSet(boolean, boolean) - Method in class java.util.concurrent.atomic.AtomicBoolean
Atomically sets the value to the given updated value if the current value == the expected value.
weakCompareAndSet(int, int) - Method in class java.util.concurrent.atomic.AtomicInteger
Atomically sets the value to the given updated value if the current value == the expected value.
weakCompareAndSet(int, int, int) - Method in class java.util.concurrent.atomic.AtomicIntegerArray
Atomically sets the element at position i to the given updated value if the current value == the expected value.
weakCompareAndSet(T, int, int) - Method in class java.util.concurrent.atomic.AtomicIntegerFieldUpdater
Atomically sets the field of the given object managed by this updater to the given updated value if the current value == the expected value.
weakCompareAndSet(long, long) - Method in class java.util.concurrent.atomic.AtomicLong
Atomically sets the value to the given updated value if the current value == the expected value.
weakCompareAndSet(int, long, long) - Method in class java.util.concurrent.atomic.AtomicLongArray
Atomically sets the element at position i to the given updated value if the current value == the expected value.
weakCompareAndSet(T, long, long) - Method in class java.util.concurrent.atomic.AtomicLongFieldUpdater
Atomically sets the field of the given object managed by this updater to the given updated value if the current value == the expected value.
weakCompareAndSet(V, V, boolean, boolean) - Method in class java.util.concurrent.atomic.AtomicMarkableReference
Atomically sets the value of both the reference and mark to the given update values if the current reference is == to the expected reference and the current mark is equal to the expected mark.
weakCompareAndSet(V, V) - Method in class java.util.concurrent.atomic.AtomicReference
Atomically sets the value to the given updated value if the current value == the expected value.
weakCompareAndSet(int, E, E) - Method in class java.util.concurrent.atomic.AtomicReferenceArray
Atomically sets the element at position i to the given updated value if the current value == the expected value.
weakCompareAndSet(T, V, V) - Method in class java.util.concurrent.atomic.AtomicReferenceFieldUpdater
Atomically sets the field of the given object managed by this updater to the given updated value if the current value == the expected value.
weakCompareAndSet(V, V, int, int) - Method in class java.util.concurrent.atomic.AtomicStampedReference
Atomically sets the value of both the reference and stamp to the given update values if the current reference is == to the expected reference and the current stamp is equal to the expected stamp.
WeakHashMap<K,V> - Class in java.util
Hash table based implementation of the Map interface, with weak keys.
WeakHashMap(int, float) - Constructor for class java.util.WeakHashMap
Constructs a new, empty WeakHashMap with the given initial capacity and the given load factor.
WeakHashMap(int) - Constructor for class java.util.WeakHashMap
Constructs a new, empty WeakHashMap with the given initial capacity and the default load factor (0.75).
WeakHashMap() - Constructor for class java.util.WeakHashMap
Constructs a new, empty WeakHashMap with the default initial capacity (16) and load factor (0.75).
WeakHashMap(Map<? extends K, ? extends V>) - Constructor for class java.util.WeakHashMap
Constructs a new WeakHashMap with the same mappings as the specified map.
WeakReference<T> - Class in java.lang.ref
Weak reference objects, which do not prevent their referents from being made finalizable, finalized, and then reclaimed.
WeakReference(T) - Constructor for class java.lang.ref.WeakReference
Creates a new weak reference that refers to the given object.
WeakReference(T, ReferenceQueue<? super T>) - Constructor for class java.lang.ref.WeakReference
Creates a new weak reference that refers to the given object and is registered with the given queue.
WebEndpoint - Annotation Type in javax.xml.ws
Used to annotate the getPortName() methods of a generated service interface.
WebFault - Annotation Type in javax.xml.ws
Used to annotate service specific exception classes to customize to the local and namespace name of the fault element and the name of the fault bean.
WebMethod - Annotation Type in javax.jws
Customizes a method that is exposed as a Web Service operation.
WebParam - Annotation Type in javax.jws
Customizes the mapping of an individual parameter to a Web Service message part and XML element.
WebParam.Mode - Enum in javax.jws
The direction in which the parameter flows
WebResult - Annotation Type in javax.jws
Customizes the mapping of the return value to a WSDL part and XML element.
WebRowSet - Interface in javax.sql.rowset
The standard interface that all implementations of a WebRowSet must implement.
WebService - Annotation Type in javax.jws
Marks a Java class as implementing a Web Service, or a Java interface as defining a Web Service interface.
WebServiceClient - Annotation Type in javax.xml.ws
Used to annotate a generated service interface.
WebServiceContext - Interface in javax.xml.ws
A WebServiceContext makes it possible for a web service endpoint implementation class to access message context and security information relative to a request being served.
WebServiceException - Exception in javax.xml.ws
The WebServiceException class is the base exception class for all JAX-WS API runtime exceptions.
WebServiceException() - Constructor for exception javax.xml.ws.WebServiceException
Constructs a new exception with null as its detail message.
WebServiceException(String) - Constructor for exception javax.xml.ws.WebServiceException
Constructs a new exception with the specified detail message.
WebServiceException(String, Throwable) - Constructor for exception javax.xml.ws.WebServiceException
Constructs a new exception with the specified detail message and cause.
WebServiceException(Throwable) - Constructor for exception javax.xml.ws.WebServiceException
Constructs a new WebServiceException with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).
WebServiceFeature - Class in javax.xml.ws
A WebServiceFeature is used to represent a feature that can be enabled or disabled for a web service.
WebServiceFeature() - Constructor for class javax.xml.ws.WebServiceFeature
WebServiceFeatureAnnotation - Annotation Type in javax.xml.ws.spi
Annotation used to identify other annotations as a WebServiceFeature.
WebServicePermission - Class in javax.xml.ws
This class defines web service permissions.
WebServicePermission(String) - Constructor for class javax.xml.ws.WebServicePermission
Creates a new permission with the specified name.
WebServicePermission(String, String) - Constructor for class javax.xml.ws.WebServicePermission
Creates a new permission with the specified name and actions.
WebServiceProvider - Annotation Type in javax.xml.ws
Used to annotate a Provider implementation class.
WebServiceRef - Annotation Type in javax.xml.ws
The WebServiceRef annotation is used to define a reference to a web service and (optionally) an injection target for it.
WebServiceRefs - Annotation Type in javax.xml.ws
The WebServiceRefs annotation allows multiple web service references to be declared at the class level.
WEDNESDAY - Static variable in class java.util.Calendar
Value of the Calendar.DAY_OF_WEEK field indicating Wednesday.
WEEK_OF_MONTH - Static variable in class java.text.DateFormat.Field
Constant identifying the week of month field.
WEEK_OF_MONTH - Static variable in class java.util.Calendar
Field number for get and set indicating the week number within the current month.
WEEK_OF_MONTH_FIELD - Static variable in class java.text.DateFormat
Useful constant for WEEK_OF_MONTH field alignment.
WEEK_OF_YEAR - Static variable in class java.text.DateFormat.Field
Constant identifying the week of year field.
WEEK_OF_YEAR - Static variable in class java.util.Calendar
Field number for get and set indicating the week number within the current year.
WEEK_OF_YEAR_FIELD - Static variable in class java.text.DateFormat
Useful constant for WEEK_OF_YEAR field alignment.
weight - Variable in class java.awt.font.GlyphJustificationInfo
The weight of this glyph.
WEIGHT - Static variable in class java.awt.font.TextAttribute
Attribute key for the weight of a font.
WEIGHT_BOLD - Static variable in class java.awt.font.TextAttribute
The standard bold weight.
WEIGHT_DEMIBOLD - Static variable in class java.awt.font.TextAttribute
A moderately lighter weight than WEIGHT_BOLD.
WEIGHT_DEMILIGHT - Static variable in class java.awt.font.TextAttribute
An intermediate weight between WEIGHT_LIGHT and WEIGHT_STANDARD.
WEIGHT_EXTRA_LIGHT - Static variable in class java.awt.font.TextAttribute
The lightest predefined weight.
WEIGHT_EXTRABOLD - Static variable in class java.awt.font.TextAttribute
An extra heavy weight.
WEIGHT_HEAVY - Static variable in class java.awt.font.TextAttribute
A moderately heavier weight than WEIGHT_BOLD.
WEIGHT_LIGHT - Static variable in class java.awt.font.TextAttribute
The standard light weight.
WEIGHT_MEDIUM - Static variable in class java.awt.font.TextAttribute
An intermediate weight between WEIGHT_REGULAR and WEIGHT_BOLD.
WEIGHT_REGULAR - Static variable in class java.awt.font.TextAttribute
The standard weight.
WEIGHT_SEMIBOLD - Static variable in class java.awt.font.TextAttribute
A moderately heavier weight than WEIGHT_REGULAR.
WEIGHT_ULTRABOLD - Static variable in class java.awt.font.TextAttribute
The heaviest predefined weight.
weightx - Variable in class java.awt.GridBagConstraints
Specifies how to distribute extra horizontal space.
weighty - Variable in class java.awt.GridBagConstraints
Specifies how to distribute extra vertical space.
WEST - Static variable in class java.awt.BorderLayout
The west layout constraint (left side of container).
WEST - Static variable in class java.awt.GridBagConstraints
Put the component on the left side of its display area, centered vertically.
WEST - Static variable in class javax.swing.SpringLayout
Specifies the left edge of a component's bounding rectangle.
WEST - Static variable in interface javax.swing.SwingConstants
Compass-direction west (left).
westPane - Variable in class javax.swing.plaf.basic.BasicInternalFrameUI
WHEEL_BLOCK_SCROLL - Static variable in class java.awt.event.MouseWheelEvent
Constant representing scrolling by a "block" (like scrolling with page-up, page-down keys)
WHEEL_UNIT_SCROLL - Static variable in class java.awt.event.MouseWheelEvent
Constant representing scrolling by "units" (like scrolling with the arrow keys)
when - Variable in class java.awt.Event
The time stamp.
WHEN_ANCESTOR_OF_FOCUSED_COMPONENT - Static variable in class javax.swing.JComponent
Constant used for registerKeyboardAction that means that the command should be invoked when the receiving component is an ancestor of the focused component or is itself the focused component.
WHEN_FOCUSED - Static variable in class javax.swing.JComponent
Constant used for registerKeyboardAction that means that the command should be invoked when the component has the focus.
WHEN_IN_FOCUSED_WINDOW - Static variable in class javax.swing.JComponent
Constant used for registerKeyboardAction that means that the command should be invoked when the receiving component is in the window that has the focus or is itself the focused component.
white - Static variable in class java.awt.Color
The color white.
WHITE - Static variable in class java.awt.Color
The color white.
WHITE_SPACE - Static variable in class javax.swing.text.html.CSS.Attribute
WHITESPACE - Static variable in class java.awt.font.GlyphMetrics
Indicates a glyph with no visual representation.
whitespaceChars(int, int) - Method in class java.io.StreamTokenizer
Specifies that all characters c in the range low <= c <= high are white space characters.
why - Variable in exception org.omg.CosNaming.NamingContextPackage.NotFound
width - Variable in class java.awt.Component.BltBufferStrategy
Size of the back buffers
width - Variable in class java.awt.Dimension
The width dimension; negative values can be used.
WIDTH - Static variable in class java.awt.font.TextAttribute
Attribute key for the width of a font.
width - Variable in class java.awt.geom.Arc2D.Double
The overall width of the full ellipse of which this arc is a partial section (not considering the angular extents).
width - Variable in class java.awt.geom.Arc2D.Float
The overall width of the full ellipse of which this arc is a partial section (not considering the angular extents).
width - Variable in class java.awt.geom.Ellipse2D.Double
The overall width of this Ellipse2D.
width - Variable in class java.awt.geom.Ellipse2D.Float
The overall width of this Ellipse2D.
width - Variable in class java.awt.geom.Rectangle2D.Double
The width of this Rectangle2D.
width - Variable in class java.awt.geom.Rectangle2D.Float
The width of this Rectangle2D.
width - Variable in class java.awt.geom.RoundRectangle2D.Double
The width of this RoundRectangle2D.
width - Variable in class java.awt.geom.RoundRectangle2D.Float
The width of this RoundRectangle2D.
WIDTH - Static variable in interface java.awt.image.ImageObserver
This flag in the infoflags argument to imageUpdate indicates that the width of the base image is now available and can be taken from the width argument to the imageUpdate callback method.
width - Variable in class java.awt.image.Raster
The width of this Raster.
width - Variable in class java.awt.image.SampleModel
Width in pixels of the region of image data that this SampleModel describes.
width - Variable in class java.awt.Rectangle
The width of the Rectangle.
width(Component) - Static method in class javax.swing.Spring
Returns a spring whose minimum, preferred, maximum and value properties are defined by the widths of the minimumSize, preferredSize, maximumSize and size properties of the supplied component.
WIDTH - Static variable in class javax.swing.SpringLayout
Specifies the width of a component's bounding rectangle.
width - Variable in class javax.swing.table.TableColumn
The width of the column.
WIDTH - Static variable in class javax.swing.text.html.CSS.Attribute
WIDTH - Static variable in class javax.swing.text.html.HTML.Attribute
WIDTH_CONDENSED - Static variable in class java.awt.font.TextAttribute
The most condensed predefined width.
WIDTH_EXTENDED - Static variable in class java.awt.font.TextAttribute
The most extended predefined width.
WIDTH_REGULAR - Static variable in class java.awt.font.TextAttribute
The standard width.
WIDTH_SEMI_CONDENSED - Static variable in class java.awt.font.TextAttribute
A moderately condensed width.
WIDTH_SEMI_EXTENDED - Static variable in class java.awt.font.TextAttribute
A moderately extended width.
WILDCARD - Static variable in class javax.management.ObjectName
Defines the wildcard "*:*" ObjectName.
WildcardType - Interface in java.lang.reflect
WildcardType represents a wildcard type expression, such as ?, ? extends Number, or ? super Integer.
WildcardType - Interface in javax.lang.model.type
Represents a wildcard type argument.
WIND_EVEN_ODD - Static variable in class java.awt.geom.Path2D
An even-odd winding rule for determining the interior of a path.
WIND_EVEN_ODD - Static variable in interface java.awt.geom.PathIterator
The winding rule constant for specifying an even-odd rule for determining the interior of a path.
WIND_NON_ZERO - Static variable in class java.awt.geom.Path2D
A non-zero winding rule for determining the interior of a path.
WIND_NON_ZERO - Static variable in interface java.awt.geom.PathIterator
The winding rule constant for specifying a non-zero rule for determining the interior of a path.
WINDOW - Static variable in class java.awt.SystemColor
The array index for the SystemColor.window system color.
window - Static variable in class java.awt.SystemColor
The color rendered for the background of interior regions inside windows.
Window - Class in java.awt
A Window object is a top-level window with no borders and no menubar.
Window(Frame) - Constructor for class java.awt.Window
Constructs a new, initially invisible window with the specified Frame as its owner.
Window(Window) - Constructor for class java.awt.Window
Constructs a new, initially invisible window with the specified Window as its owner.
Window(Window, GraphicsConfiguration) - Constructor for class java.awt.Window
Constructs a new, initially invisible window with the specified owner Window and a GraphicsConfiguration of a screen device.
WINDOW - Static variable in class javax.accessibility.AccessibleRole
A top level window with no title or border.
Window.AccessibleAWTWindow - Class in java.awt
This class implements accessibility support for the Window class.
Window.AccessibleAWTWindow() - Constructor for class java.awt.Window.AccessibleAWTWindow
Window.Type - Enum in java.awt
Enumeration of available window types.
WINDOW_ACTIVATED - Static variable in class java.awt.event.WindowEvent
The window-activated event type.
WINDOW_BORDER - Static variable in class java.awt.SystemColor
The array index for the SystemColor.windowBorder system color.
WINDOW_CLOSED - Static variable in class java.awt.event.WindowEvent
The window closed event.
WINDOW_CLOSING - Static variable in class java.awt.event.WindowEvent
The "window is closing" event.
WINDOW_DEACTIVATED - Static variable in class java.awt.event.WindowEvent
The window-deactivated event type.
WINDOW_DEICONIFIED - Static variable in class java.awt.event.WindowEvent
The window deiconified event type.
WINDOW_DEICONIFY - Static variable in class java.awt.Event
The user has asked the window manager to de-iconify the window.
WINDOW_DESTROY - Static variable in class java.awt.Event
The user has asked the window manager to kill the window.
WINDOW_EVENT_MASK - Static variable in class java.awt.AWTEvent
The event mask for selecting window events.
WINDOW_EXPOSE - Static variable in class java.awt.Event
The user has asked the window manager to expose the window.
WINDOW_FIRST - Static variable in class java.awt.event.WindowEvent
The first number in the range of ids used for window events.
WINDOW_FOCUS_EVENT_MASK - Static variable in class java.awt.AWTEvent
The event mask for selecting window focus events.
WINDOW_GAINED_FOCUS - Static variable in class java.awt.event.WindowEvent
The window-gained-focus event type.
WINDOW_ICONIFIED - Static variable in class java.awt.event.WindowEvent
The window iconified event.
WINDOW_ICONIFY - Static variable in class java.awt.Event
The user has asked the window manager to iconify the window.
WINDOW_LAST - Static variable in class java.awt.event.WindowEvent
The last number in the range of ids used for window events.
WINDOW_LOST_FOCUS - Static variable in class java.awt.event.WindowEvent
The window-lost-focus event type.
WINDOW_MOVED - Static variable in class java.awt.Event
The user has asked the window manager to move the window.
WINDOW_OPENED - Static variable in class java.awt.event.WindowEvent
The window opened event.
WINDOW_STATE_CHANGED - Static variable in class java.awt.event.WindowEvent
The window-state-changed event type.
WINDOW_STATE_EVENT_MASK - Static variable in class java.awt.AWTEvent
The event mask for selecting window state events.
WINDOW_TEXT - Static variable in class java.awt.SystemColor
The array index for the SystemColor.windowText system color.
windowActivated(WindowEvent) - Method in class java.awt.AWTEventMulticaster
Handles the windowActivated event by invoking the windowActivated methods on listener-a and listener-b.
windowActivated(WindowEvent) - Method in class java.awt.event.WindowAdapter
Invoked when a window is activated.
windowActivated(WindowEvent) - Method in interface java.awt.event.WindowListener
Invoked when the Window is set to be the active Window.
WindowAdapter - Class in java.awt.event
An abstract adapter class for receiving window events.
WindowAdapter() - Constructor for class java.awt.event.WindowAdapter
windowBorder - Static variable in class java.awt.SystemColor
The color rendered for the border around interior regions inside windows.
windowClosed(WindowEvent) - Method in class java.awt.AWTEventMulticaster
Handles the windowClosed event by invoking the windowClosed methods on listener-a and listener-b.
windowClosed(WindowEvent) - Method in class java.awt.event.WindowAdapter
Invoked when a window has been closed.
windowClosed(WindowEvent) - Method in interface java.awt.event.WindowListener
Invoked when a window has been closed as the result of calling dispose on the window.
windowClosing(WindowEvent) - Method in class java.awt.AWTEventMulticaster
Handles the windowClosing event by invoking the windowClosing methods on listener-a and listener-b.
windowClosing(WindowEvent) - Method in class java.awt.event.WindowAdapter
Invoked when a window is in the process of being closed.
windowClosing(WindowEvent) - Method in interface java.awt.event.WindowListener
Invoked when the user attempts to close the window from the window's system menu.
windowClosing(WindowEvent) - Method in class javax.swing.JMenu.WinListener
Deselect the menu when the popup is closed from outside.
windowClosing(WindowEvent) - Method in class javax.swing.plaf.basic.BasicToolBarUI.FrameListener
WindowConstants - Interface in javax.swing
Constants used to control the window-closing operation.
windowDeactivated(WindowEvent) - Method in class java.awt.AWTEventMulticaster
Handles the windowDeactivated event by invoking the windowDeactivated methods on listener-a and listener-b.
windowDeactivated(WindowEvent) - Method in class java.awt.event.WindowAdapter
Invoked when a window is de-activated.
windowDeactivated(WindowEvent) - Method in interface java.awt.event.WindowListener
Invoked when a Window is no longer the active Window.
windowDeiconified(WindowEvent) - Method in class java.awt.AWTEventMulticaster
Handles the windowDeiconfied event by invoking the windowDeiconified methods on listener-a and listener-b.
windowDeiconified(WindowEvent) - Method in class java.awt.event.WindowAdapter
Invoked when a window is de-iconified.
windowDeiconified(WindowEvent) - Method in interface java.awt.event.WindowListener
Invoked when a window is changed from a minimized to a normal state.
WindowEvent - Class in java.awt.event
A low-level event that indicates that a window has changed its status.
WindowEvent(Window, int, Window, int, int) - Constructor for class java.awt.event.WindowEvent
Constructs a WindowEvent object.
WindowEvent(Window, int, Window) - Constructor for class java.awt.event.WindowEvent
Constructs a WindowEvent object with the specified opposite Window.
WindowEvent(Window, int, int, int) - Constructor for class java.awt.event.WindowEvent
Constructs a WindowEvent object with the specified previous and new window states.
WindowEvent(Window, int) - Constructor for class java.awt.event.WindowEvent
Constructs a WindowEvent object.
WindowFocusListener - Interface in java.awt.event
The listener interface for receiving WindowEvents, including WINDOW_GAINED_FOCUS and WINDOW_LOST_FOCUS events.
windowForComponent(Component) - Static method in class javax.swing.SwingUtilities
Returns the first Window ancestor of c, or null if c is not contained inside a Window.
windowGainedFocus(WindowEvent) - Method in class java.awt.AWTEventMulticaster
Handles the windowGainedFocus event by invoking the windowGainedFocus methods on listener-a and listener-b.
windowGainedFocus(WindowEvent) - Method in class java.awt.event.WindowAdapter
Invoked when the Window is set to be the focused Window, which means that the Window, or one of its subcomponents, will receive keyboard events.
windowGainedFocus(WindowEvent) - Method in interface java.awt.event.WindowFocusListener
Invoked when the Window is set to be the focused Window, which means that the Window, or one of its subcomponents, will receive keyboard events.
windowIconified(WindowEvent) - Method in class java.awt.AWTEventMulticaster
Handles the windowIconified event by invoking the windowIconified methods on listener-a and listener-b.
windowIconified(WindowEvent) - Method in class java.awt.event.WindowAdapter
Invoked when a window is iconified.
windowIconified(WindowEvent) - Method in interface java.awt.event.WindowListener
Invoked when a window is changed from a normal to a minimized state.
windowInit() - Method in class javax.swing.JWindow
Called by the constructors to init the JWindow properly.
WindowListener - Interface in java.awt.event
The listener interface for receiving window events.
windowLostFocus(WindowEvent) - Method in class java.awt.AWTEventMulticaster
Handles the windowLostFocus event by invoking the windowLostFocus methods on listener-a and listener-b.
windowLostFocus(WindowEvent) - Method in class java.awt.event.WindowAdapter
Invoked when the Window is no longer the focused Window, which means that keyboard events will no longer be delivered to the Window or any of its subcomponents.
windowLostFocus(WindowEvent) - Method in interface java.awt.event.WindowFocusListener
Invoked when the Window is no longer the focused Window, which means that keyboard events will no longer be delivered to the Window or any of its subcomponents.
windowMenu - Variable in class javax.swing.plaf.basic.BasicInternalFrameTitlePane
windowOpened(WindowEvent) - Method in class java.awt.AWTEventMulticaster
Handles the windowOpened event by invoking the windowOpened methods on listener-a and listener-b.
windowOpened(WindowEvent) - Method in class java.awt.event.WindowAdapter
Invoked when a window has been opened.
windowOpened(WindowEvent) - Method in interface java.awt.event.WindowListener
Invoked the first time a window is made visible.
windowStateChanged(WindowEvent) - Method in class java.awt.AWTEventMulticaster
Handles the windowStateChanged event by invoking the windowStateChanged methods on listener-a and listener-b.
windowStateChanged(WindowEvent) - Method in class java.awt.event.WindowAdapter
Invoked when a window state is changed.
windowStateChanged(WindowEvent) - Method in interface java.awt.event.WindowStateListener
Invoked when window state is changed.
WindowStateListener - Interface in java.awt.event
The listener interface for receiving window state events.
windowText - Static variable in class java.awt.SystemColor
The color rendered for text of interior regions inside windows.
withCachedThreadPool(ExecutorService, int) - Static method in class java.nio.channels.AsynchronousChannelGroup
Creates an asynchronous channel group with a given thread pool that creates new threads as needed.
withFixedThreadPool(int, ThreadFactory) - Static method in class java.nio.channels.AsynchronousChannelGroup
Creates an asynchronous channel group with a fixed thread pool.
withThreadPool(ExecutorService) - Static method in class java.nio.channels.AsynchronousChannelGroup
Creates an asynchronous channel group with a given thread pool.
WORD - Static variable in interface javax.accessibility.AccessibleText
Constant used to indicate that the part of the text that should be retrieved is a word.
WORD_SPACING - Static variable in class javax.swing.text.html.CSS.Attribute
wordChars(int, int) - Method in class java.io.StreamTokenizer
Specifies that all characters c in the range low <= c <= high are word constituents.
work_pending() - Method in class org.omg.CORBA.ORB
Returns true if the ORB needs the main thread to perform some work, and false if the ORB does not need the main thread.
wrap() - Method in class java.lang.invoke.MethodType
Converts all primitive types to their corresponding wrapper types.
wrap(byte[], int, int) - Static method in class java.nio.ByteBuffer
Wraps a byte array into a buffer.
wrap(byte[]) - Static method in class java.nio.ByteBuffer
Wraps a byte array into a buffer.
wrap(char[], int, int) - Static method in class java.nio.CharBuffer
Wraps a char array into a buffer.
wrap(char[]) - Static method in class java.nio.CharBuffer
Wraps a char array into a buffer.
wrap(CharSequence, int, int) - Static method in class java.nio.CharBuffer
Wraps a character sequence into a buffer.
wrap(CharSequence) - Static method in class java.nio.CharBuffer
Wraps a character sequence into a buffer.
wrap(double[], int, int) - Static method in class java.nio.DoubleBuffer
Wraps a double array into a buffer.
wrap(double[]) - Static method in class java.nio.DoubleBuffer
Wraps a double array into a buffer.
wrap(float[], int, int) - Static method in class java.nio.FloatBuffer
Wraps a float array into a buffer.
wrap(float[]) - Static method in class java.nio.FloatBuffer
Wraps a float array into a buffer.
wrap(int[], int, int) - Static method in class java.nio.IntBuffer
Wraps an int array into a buffer.
wrap(int[]) - Static method in class java.nio.IntBuffer
Wraps an int array into a buffer.
wrap(long[], int, int) - Static method in class java.nio.LongBuffer
Wraps a long array into a buffer.
wrap(long[]) - Static method in class java.nio.LongBuffer
Wraps a long array into a buffer.
wrap(short[], int, int) - Static method in class java.nio.ShortBuffer
Wraps a short array into a buffer.
wrap(short[]) - Static method in class java.nio.ShortBuffer
Wraps a short array into a buffer.
wrap(Key) - Method in class javax.crypto.Cipher
Wrap a key.
wrap(ByteBuffer, ByteBuffer) - Method in class javax.net.ssl.SSLEngine
Attempts to encode a buffer of plaintext application data into SSL/TLS network data.
wrap(ByteBuffer[], ByteBuffer) - Method in class javax.net.ssl.SSLEngine
Attempts to encode plaintext bytes from a sequence of data buffers into SSL/TLS network data.
wrap(ByteBuffer[], int, int, ByteBuffer) - Method in class javax.net.ssl.SSLEngine
Attempts to encode plaintext bytes from a subsequence of data buffers into SSL/TLS network data.
wrap(byte[], int, int) - Method in interface javax.security.sasl.SaslClient
Wraps a byte array to be sent to the server.
wrap(byte[], int, int) - Method in interface javax.security.sasl.SaslServer
Wraps a byte array to be sent to the client.
wrap(byte[], int, int, MessageProp) - Method in interface org.ietf.jgss.GSSContext
Applies per-message security services over the established security context.
wrap(InputStream, OutputStream, MessageProp) - Method in interface org.ietf.jgss.GSSContext
Applies per-message security services over the established security context using streams.
WRAP_MODE - Static variable in class javax.crypto.Cipher
Constant used to initialize cipher to key-wrapping mode.
WRAP_TAB_LAYOUT - Static variable in class javax.swing.JTabbedPane
The tab layout policy for wrapping tabs in multiple runs when all tabs will not fit within a single run.
wrapException(Throwable) - Static method in class javax.rmi.CORBA.Util
Wraps an exception thrown by an implementation method.
wrapException(Throwable) - Method in interface javax.rmi.CORBA.UtilDelegate
Delegation call for Util.wrapException(java.lang.Throwable).
WrappedPlainView - Class in javax.swing.text
View of plain text (text with only one font and color) that does line-wrapping.
WrappedPlainView(Element) - Constructor for class javax.swing.text.WrappedPlainView
Creates a new WrappedPlainView.
WrappedPlainView(Element, boolean) - Constructor for class javax.swing.text.WrappedPlainView
Creates a new WrappedPlainView.
Wrapper - Interface in java.sql
Interface for JDBC classes which provide the ability to retrieve the delegate instance when the instance in question is in fact a proxy class.
wrapperInstanceTarget(Object) - Static method in class java.lang.invoke.MethodHandles
Produces or recovers a target method handle which is behaviorally equivalent to the unique method of this wrapper instance.
wrapperInstanceType(Object) - Static method in class java.lang.invoke.MethodHandles
Recovers the unique single-method interface type for which this wrapper instance was created.
writableAction - Static variable in class javax.swing.text.DefaultEditorKit
Name of the action to set the editor into writeable mode.
WritableByteChannel - Interface in java.nio.channels
A channel that can write bytes.
WritableRaster - Class in java.awt.image
This class extends Raster to provide pixel writing capabilities.
WritableRaster(SampleModel, Point) - Constructor for class java.awt.image.WritableRaster
Constructs a WritableRaster with the given SampleModel.
WritableRaster(SampleModel, DataBuffer, Point) - Constructor for class java.awt.image.WritableRaster
Constructs a WritableRaster with the given SampleModel and DataBuffer.
WritableRaster(SampleModel, DataBuffer, Rectangle, Point, WritableRaster) - Constructor for class java.awt.image.WritableRaster
Constructs a WritableRaster with the given SampleModel, DataBuffer, and parent.
WritableRenderedImage - Interface in java.awt.image
WriteableRenderedImage is a common interface for objects which contain or can produce image data in the form of Rasters and which can be modified and/or written over.
write(String) - Method in class java.awt.color.ICC_Profile
Write this ICC_Profile to a file.
write(OutputStream) - Method in class java.awt.color.ICC_Profile
Write this ICC_Profile to an OutputStream.
write(int) - Method in class java.io.BufferedOutputStream
Writes the specified byte to this buffered output stream.
write(byte[], int, int) - Method in class java.io.BufferedOutputStream
Writes len bytes from the specified byte array starting at offset off to this buffered output stream.
write(int) - Method in class java.io.BufferedWriter
Writes a single character.
write(char[], int, int) - Method in class java.io.BufferedWriter
Writes a portion of an array of characters.
write(String, int, int) - Method in class java.io.BufferedWriter
Writes a portion of a String.
write(int) - Method in class java.io.ByteArrayOutputStream
Writes the specified byte to this byte array output stream.
write(byte[], int, int) - Method in class java.io.ByteArrayOutputStream
Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
write(int) - Method in class java.io.CharArrayWriter
Writes a character to the buffer.
write(char[], int, int) - Method in class java.io.CharArrayWriter
Writes characters to the buffer.
write(String, int, int) - Method in class java.io.CharArrayWriter
Write a portion of a string to the buffer.
write(int) - Method in interface java.io.DataOutput
Writes to the output stream the eight low-order bits of the argument b.
write(byte[]) - Method in interface java.io.DataOutput
Writes to the output stream all the bytes in array b.
write(byte[], int, int) - Method in interface java.io.DataOutput
Writes len bytes from array b, in order, to the output stream.
write(int) - Method in class java.io.DataOutputStream
Writes the specified byte (the low eight bits of the argument b) to the underlying output stream.
write(byte[], int, int) - Method in class java.io.DataOutputStream
Writes len bytes from the specified byte array starting at offset off to the underlying output stream.
write(int) - Method in class java.io.FileOutputStream
Writes the specified byte to this file output stream.
write(byte[]) - Method in class java.io.FileOutputStream
Writes b.length bytes from the specified byte array to this file output stream.
write(byte[], int, int) - Method in class java.io.FileOutputStream
Writes len bytes from the specified byte array starting at offset off to this file output stream.
write(int) - Method in class java.io.FilterOutputStream
Writes the specified byte to this output stream.
write(byte[]) - Method in class java.io.FilterOutputStream
Writes b.length bytes to this output stream.
write(byte[], int, int) - Method in class java.io.FilterOutputStream
Writes len bytes from the specified byte array starting at offset off to this output stream.
write(int) - Method in class java.io.FilterWriter
Writes a single character.
write(char[], int, int) - Method in class java.io.FilterWriter
Writes a portion of an array of characters.
write(String, int, int) - Method in class java.io.FilterWriter
Writes a portion of a string.
write(int) - Method in interface java.io.ObjectOutput
Writes a byte.
write(byte[]) - Method in interface java.io.ObjectOutput
Writes an array of bytes.
write(byte[], int, int) - Method in interface java.io.ObjectOutput
Writes a sub array of bytes.
write(ObjectOutput) - Method in class java.io.ObjectOutputStream.PutField
Deprecated.
This method does not write the values contained by this PutField object in a proper format, and may result in corruption of the serialization stream. The correct way to write PutField data is by calling the ObjectOutputStream.writeFields() method.
write(int) - Method in class java.io.ObjectOutputStream
Writes a byte.
write(byte[]) - Method in class java.io.ObjectOutputStream
Writes an array of bytes.
write(byte[], int, int) - Method in class java.io.ObjectOutputStream
Writes a sub array of bytes.
write(int) - Method in class java.io.OutputStream
Writes the specified byte to this output stream.
write(byte[]) - Method in class java.io.OutputStream
Writes b.length bytes from the specified byte array to this output stream.
write(byte[], int, int) - Method in class java.io.OutputStream
Writes len bytes from the specified byte array starting at offset off to this output stream.
write(int) - Method in class java.io.OutputStreamWriter
Writes a single character.
write(char[], int, int) - Method in class java.io.OutputStreamWriter
Writes a portion of an array of characters.
write(String, int, int) - Method in class java.io.OutputStreamWriter
Writes a portion of a string.
write(int) - Method in class java.io.PipedOutputStream
Writes the specified byte to the piped output stream.
write(byte[], int, int) - Method in class java.io.PipedOutputStream
Writes len bytes from the specified byte array starting at offset off to this piped output stream.
write(int) - Method in class java.io.PipedWriter
Writes the specified char to the piped output stream.
write(char[], int, int) - Method in class java.io.PipedWriter
Writes len characters from the specified character array starting at offset off to this piped output stream.
write(int) - Method in class java.io.PrintStream
Writes the specified byte to this stream.
write(byte[], int, int) - Method in class java.io.PrintStream
Writes len bytes from the specified byte array starting at offset off to this stream.
write(int) - Method in class java.io.PrintWriter
Writes a single character.
write(char[], int, int) - Method in class java.io.PrintWriter
Writes A Portion of an array of characters.
write(char[]) - Method in class java.io.PrintWriter
Writes an array of characters.
write(String, int, int) - Method in class java.io.PrintWriter
Writes a portion of a string.
write(String) - Method in class java.io.PrintWriter
Writes a string.
write(int) - Method in class java.io.RandomAccessFile
Writes the specified byte to this file.
write(byte[]) - Method in class java.io.RandomAccessFile
Writes b.length bytes from the specified byte array to this file, starting at the current file pointer.
write(byte[], int, int) - Method in class java.io.RandomAccessFile
Writes len bytes from the specified byte array starting at offset off to this file.
write(int) - Method in class java.io.StringWriter
Write a single character.
write(char[], int, int) - Method in class java.io.StringWriter
Write a portion of an array of characters.
write(String) - Method in class java.io.StringWriter
Write a string.
write(String, int, int) - Method in class java.io.StringWriter
Write a portion of a string.
write(int) - Method in class java.io.Writer
Writes a single character.
write(char[]) - Method in class java.io.Writer
Writes an array of characters.
write(char[], int, int) - Method in class java.io.Writer
Writes a portion of an array of characters.
write(String) - Method in class java.io.Writer
Writes a string.
write(String, int, int) - Method in class java.io.Writer
Writes a portion of a string.
write(ByteBuffer, A, CompletionHandler<Integer, ? super A>) - Method in interface java.nio.channels.AsynchronousByteChannel
Writes a sequence of bytes to this channel from the given buffer.
write(ByteBuffer) - Method in interface java.nio.channels.AsynchronousByteChannel
Writes a sequence of bytes to this channel from the given buffer.
write(ByteBuffer, long, A, CompletionHandler<Integer, ? super A>) - Method in class java.nio.channels.AsynchronousFileChannel
Writes a sequence of bytes to this channel from the given buffer, starting at the given file position.
write(ByteBuffer, long) - Method in class java.nio.channels.AsynchronousFileChannel
Writes a sequence of bytes to this channel from the given buffer, starting at the given file position.
write(ByteBuffer, long, TimeUnit, A, CompletionHandler<Integer, ? super A>) - Method in class java.nio.channels.AsynchronousSocketChannel
Writes a sequence of bytes to this channel from the given buffer.
write(ByteBuffer, A, CompletionHandler<Integer, ? super A>) - Method in class java.nio.channels.AsynchronousSocketChannel
write(ByteBuffer) - Method in class java.nio.channels.AsynchronousSocketChannel
write(ByteBuffer[], int, int, long, TimeUnit, A, CompletionHandler<Long, ? super A>) - Method in class java.nio.channels.AsynchronousSocketChannel
Writes a sequence of bytes to this channel from a subsequence of the given buffers.
write(ByteBuffer) - Method in class java.nio.channels.DatagramChannel
Writes a datagram to this channel.
write(ByteBuffer[], int, int) - Method in class java.nio.channels.DatagramChannel
Writes a datagram to this channel.
write(ByteBuffer[]) - Method in class java.nio.channels.DatagramChannel
Writes a datagram to this channel.
write(ByteBuffer) - Method in class java.nio.channels.FileChannel
Writes a sequence of bytes to this channel from the given buffer.
write(ByteBuffer[], int, int) - Method in class java.nio.channels.FileChannel
Writes a sequence of bytes to this channel from a subsequence of the given buffers.
write(ByteBuffer[]) - Method in class java.nio.channels.FileChannel
Writes a sequence of bytes to this channel from the given buffers.
write(ByteBuffer, long) - Method in class java.nio.channels.FileChannel
Writes a sequence of bytes to this channel from the given buffer, starting at the given file position.
write(ByteBuffer[], int, int) - Method in interface java.nio.channels.GatheringByteChannel
Writes a sequence of bytes to this channel from a subsequence of the given buffers.
write(ByteBuffer[]) - Method in interface java.nio.channels.GatheringByteChannel
Writes a sequence of bytes to this channel from the given buffers.
write(ByteBuffer) - Method in interface java.nio.channels.SeekableByteChannel
Writes a sequence of bytes to this channel from the given buffer.
write(ByteBuffer) - Method in class java.nio.channels.SocketChannel
write(ByteBuffer[], int, int) - Method in class java.nio.channels.SocketChannel
write(ByteBuffer[]) - Method in class java.nio.channels.SocketChannel
write(ByteBuffer) - Method in interface java.nio.channels.WritableByteChannel
Writes a sequence of bytes to this channel from the given buffer.
write(String, ByteBuffer) - Method in interface java.nio.file.attribute.UserDefinedFileAttributeView
Writes the value of a user-defined attribute from a buffer.
write(Path, byte[], OpenOption...) - Static method in class java.nio.file.Files
Writes bytes to a file.
write(Path, Iterable<? extends CharSequence>, Charset, OpenOption...) - Static method in class java.nio.file.Files
Write lines of text to a file.
write(int) - Method in class java.rmi.server.LogStream
Deprecated.
no replacement
write(byte[], int, int) - Method in class java.rmi.server.LogStream
Deprecated.
no replacement
write(ObjectOutput) - Method in class java.rmi.server.ObjID
Marshals a binary representation of this ObjID to an ObjectOutput instance.
write(DataOutput) - Method in class java.rmi.server.UID
Marshals a binary representation of this UID to a DataOutput instance.
write(int) - Method in class java.security.DigestOutputStream
Updates the message digest (if the digest function is on) using the specified byte, and in any case writes the byte to the output stream.
write(byte[], int, int) - Method in class java.security.DigestOutputStream
Updates the message digest (if the digest function is on) using the specified subarray, and in any case writes the subarray to the output stream.
write(OutputStream) - Method in class java.util.jar.Manifest
Writes the Manifest to the specified OutputStream.
write(int) - Method in class java.util.zip.CheckedOutputStream
Writes a byte.
write(byte[], int, int) - Method in class java.util.zip.CheckedOutputStream
Writes an array of bytes.
write(int) - Method in class java.util.zip.DeflaterOutputStream
Writes a byte to the compressed output stream.
write(byte[], int, int) - Method in class java.util.zip.DeflaterOutputStream
Writes an array of bytes to the compressed output stream.
write(byte[], int, int) - Method in class java.util.zip.GZIPOutputStream
Writes array of bytes to the compressed output stream.
write(int) - Method in class java.util.zip.InflaterOutputStream
Writes a byte to the uncompressed output stream.
write(byte[], int, int) - Method in class java.util.zip.InflaterOutputStream
Writes an array of bytes to the uncompressed output stream.
write(byte[], int, int) - Method in class java.util.zip.ZipOutputStream
Writes an array of bytes to the current ZIP entry data.
write(int) - Method in class javax.crypto.CipherOutputStream
Writes the specified byte to this output stream.
write(byte[]) - Method in class javax.crypto.CipherOutputStream
Writes b.length bytes from the specified byte array to this output stream.
write(byte[], int, int) - Method in class javax.crypto.CipherOutputStream
Writes len bytes from the specified byte array starting at offset off to this output stream.
write(RenderedImage, String, ImageOutputStream) - Static method in class javax.imageio.ImageIO
Writes an image using the an arbitrary ImageWriter that supports the given format to an ImageOutputStream.
write(RenderedImage, String, File) - Static method in class javax.imageio.ImageIO
Writes an image using an arbitrary ImageWriter that supports the given format to a File.
write(RenderedImage, String, OutputStream) - Static method in class javax.imageio.ImageIO
Writes an image using an arbitrary ImageWriter that supports the given format to an OutputStream.
write(IIOMetadata, IIOImage, ImageWriteParam) - Method in class javax.imageio.ImageWriter
Appends a complete image stream containing a single image and associated stream and image metadata and thumbnails to the output.
write(IIOImage) - Method in class javax.imageio.ImageWriter
Appends a complete image stream containing a single image with default metadata and thumbnails to the output.
write(RenderedImage) - Method in class javax.imageio.ImageWriter
Appends a complete image stream consisting of a single image with default metadata and thumbnails to the output.
write(int) - Method in class javax.imageio.stream.FileCacheImageOutputStream
write(byte[], int, int) - Method in class javax.imageio.stream.FileCacheImageOutputStream
write(int) - Method in class javax.imageio.stream.FileImageOutputStream
write(byte[], int, int) - Method in class javax.imageio.stream.FileImageOutputStream
write(int) - Method in interface javax.imageio.stream.ImageOutputStream
Writes a single byte to the stream at the current position.
write(byte[]) - Method in interface javax.imageio.stream.ImageOutputStream
Writes a sequence of bytes to the stream at the current position.
write(byte[], int, int) - Method in interface javax.imageio.stream.ImageOutputStream
Writes a sequence of bytes to the stream at the current position.
write(int) - Method in class javax.imageio.stream.ImageOutputStreamImpl
write(byte[]) - Method in class javax.imageio.stream.ImageOutputStreamImpl
write(byte[], int, int) - Method in class javax.imageio.stream.ImageOutputStreamImpl
write(int) - Method in class javax.imageio.stream.MemoryCacheImageOutputStream
write(byte[], int, int) - Method in class javax.imageio.stream.MemoryCacheImageOutputStream
write(Sequence, int, OutputStream) - Static method in class javax.sound.midi.MidiSystem
Writes a stream of bytes representing a file of the MIDI file type indicated to the output stream provided.
write(Sequence, int, File) - Static method in class javax.sound.midi.MidiSystem
Writes a stream of bytes representing a file of the MIDI file type indicated to the external file provided.
write(Sequence, int, OutputStream) - Method in class javax.sound.midi.spi.MidiFileWriter
Writes a stream of bytes representing a MIDI file of the file type indicated to the output stream provided.
write(Sequence, int, File) - Method in class javax.sound.midi.spi.MidiFileWriter
Writes a stream of bytes representing a MIDI file of the file type indicated to the external file provided.
write(AudioInputStream, AudioFileFormat.Type, OutputStream) - Static method in class javax.sound.sampled.AudioSystem
Writes a stream of bytes representing an audio file of the specified file type to the output stream provided.
write(AudioInputStream, AudioFileFormat.Type, File) - Static method in class javax.sound.sampled.AudioSystem
Writes a stream of bytes representing an audio file of the specified file type to the external file provided.
write(byte[], int, int) - Method in interface javax.sound.sampled.SourceDataLine
Writes audio data to the mixer via this source data line.
write(AudioInputStream, AudioFileFormat.Type, OutputStream) - Method in class javax.sound.sampled.spi.AudioFileWriter
Writes a stream of bytes representing an audio file of the file type indicated to the output stream provided.
write(AudioInputStream, AudioFileFormat.Type, File) - Method in class javax.sound.sampled.spi.AudioFileWriter
Writes a stream of bytes representing an audio file of the file format indicated to the external file provided.
write() - Method in class javax.swing.text.AbstractWriter
This abstract method needs to be implemented by subclasses.
write(char) - Method in class javax.swing.text.AbstractWriter
Writes out a character.
write(String) - Method in class javax.swing.text.AbstractWriter
Writes out a string.
write(char[], int, int) - Method in class javax.swing.text.AbstractWriter
All write methods call into this one.
write(OutputStream, Document, int, int) - Method in class javax.swing.text.DefaultEditorKit
Writes content from a document to the given stream in a format appropriate for this kind of content handler.
write(Writer, Document, int, int) - Method in class javax.swing.text.DefaultEditorKit
Writes content from a document to the given stream as plain text.
write(OutputStream, Document, int, int) - Method in class javax.swing.text.EditorKit
Writes content from a document to the given stream in a format appropriate for this kind of content handler.
write(Writer, Document, int, int) - Method in class javax.swing.text.EditorKit
Writes content from a document to the given stream in a format appropriate for this kind of content handler.
write(Writer, Document, int, int) - Method in class javax.swing.text.html.HTMLEditorKit
Write content from a document to the given stream in a format appropriate for this kind of content handler.
write() - Method in class javax.swing.text.html.HTMLWriter
Iterates over the Element tree and controls the writing out of all the tags and its attributes.
write() - Method in class javax.swing.text.html.MinimalHTMLWriter
Generates HTML output from a StyledDocument.
write(Writer) - Method in class javax.swing.text.JTextComponent
Stores the contents of the model into the given stream.
write(OutputStream, Document, int, int) - Method in class javax.swing.text.rtf.RTFEditorKit
Write content from a document to the given stream in a format appropriate for this kind of content handler.
write(Writer, Document, int, int) - Method in class javax.swing.text.rtf.RTFEditorKit
Write content from a document to the given stream as plain text.
write(OutputStream, Any[]) - Static method in class org.omg.CORBA.AnySeqHelper
write(OutputStream, boolean[]) - Static method in class org.omg.CORBA.BooleanSeqHelper
write(OutputStream, char[]) - Static method in class org.omg.CORBA.CharSeqHelper
write(OutputStream, CompletionStatus) - Static method in class org.omg.CORBA.CompletionStatusHelper
write(OutputStream, Current) - Static method in class org.omg.CORBA.CurrentHelper
write(OutputStream, DefinitionKind) - Static method in class org.omg.CORBA.DefinitionKindHelper
write(OutputStream, double[]) - Static method in class org.omg.CORBA.DoubleSeqHelper
write(OutputStream, String) - Static method in class org.omg.CORBA.FieldNameHelper
write(OutputStream, float[]) - Static method in class org.omg.CORBA.FloatSeqHelper
write(OutputStream, String) - Static method in class org.omg.CORBA.IdentifierHelper
write(OutputStream, IDLType) - Static method in class org.omg.CORBA.IDLTypeHelper
write(OutputStream, long[]) - Static method in class org.omg.CORBA.LongLongSeqHelper
write(OutputStream, int[]) - Static method in class org.omg.CORBA.LongSeqHelper
write(OutputStream, NameValuePair) - Static method in class org.omg.CORBA.NameValuePairHelper
write(OutputStream, Object) - Static method in class org.omg.CORBA.ObjectHelper
write(OutputStream, byte[]) - Static method in class org.omg.CORBA.OctetSeqHelper
write(OutputStream, ParameterMode) - Static method in class org.omg.CORBA.ParameterModeHelper
write(OutputStream, short) - Static method in class org.omg.CORBA.PolicyErrorCodeHelper
write(OutputStream, PolicyError) - Static method in class org.omg.CORBA.PolicyErrorHelper
write(OutputStream, Policy) - Static method in class org.omg.CORBA.PolicyHelper
write(OutputStream, Policy[]) - Static method in class org.omg.CORBA.PolicyListHelper
write(OutputStream, int) - Static method in class org.omg.CORBA.PolicyTypeHelper
write(int) - Method in class org.omg.CORBA.portable.OutputStream
Writes an integer (length of arrays) onto this stream.
write(OutputStream, String) - Static method in class org.omg.CORBA.RepositoryIdHelper
write(OutputStream, ServiceDetail) - Static method in class org.omg.CORBA.ServiceDetailHelper
write(OutputStream, ServiceInformation) - Static method in class org.omg.CORBA.ServiceInformationHelper
write(OutputStream, SetOverrideType) - Static method in class org.omg.CORBA.SetOverrideTypeHelper
write(OutputStream, short[]) - Static method in class org.omg.CORBA.ShortSeqHelper
write(OutputStream, String[]) - Static method in class org.omg.CORBA.StringSeqHelper
write(OutputStream, String) - Static method in class org.omg.CORBA.StringValueHelper
write(OutputStream, StructMember) - Static method in class org.omg.CORBA.StructMemberHelper
write(OutputStream, long[]) - Static method in class org.omg.CORBA.ULongLongSeqHelper
write(OutputStream, int[]) - Static method in class org.omg.CORBA.ULongSeqHelper
write(OutputStream, UnionMember) - Static method in class org.omg.CORBA.UnionMemberHelper
write(OutputStream, UnknownUserException) - Static method in class org.omg.CORBA.UnknownUserExceptionHelper
write(OutputStream, short[]) - Static method in class org.omg.CORBA.UShortSeqHelper
write(OutputStream, Serializable) - Static method in class org.omg.CORBA.ValueBaseHelper
write(OutputStream, ValueMember) - Static method in class org.omg.CORBA.ValueMemberHelper
write(OutputStream, String) - Static method in class org.omg.CORBA.VersionSpecHelper
write(OutputStream, short) - Static method in class org.omg.CORBA.VisibilityHelper
write(OutputStream, char[]) - Static method in class org.omg.CORBA.WCharSeqHelper
write(OutputStream, WrongTransaction) - Static method in class org.omg.CORBA.WrongTransactionHelper
write(OutputStream, String[]) - Static method in class org.omg.CORBA.WStringSeqHelper
write(OutputStream, String) - Static method in class org.omg.CORBA.WStringValueHelper
write(OutputStream, Binding) - Static method in class org.omg.CosNaming.BindingHelper
write(OutputStream, BindingIterator) - Static method in class org.omg.CosNaming.BindingIteratorHelper
write(OutputStream, Binding[]) - Static method in class org.omg.CosNaming.BindingListHelper
write(OutputStream, BindingType) - Static method in class org.omg.CosNaming.BindingTypeHelper
write(OutputStream, String) - Static method in class org.omg.CosNaming.IstringHelper
write(OutputStream, NameComponent) - Static method in class org.omg.CosNaming.NameComponentHelper
write(OutputStream, NameComponent[]) - Static method in class org.omg.CosNaming.NameHelper
write(OutputStream, NamingContextExt) - Static method in class org.omg.CosNaming.NamingContextExtHelper
write(OutputStream, String) - Static method in class org.omg.CosNaming.NamingContextExtPackage.AddressHelper
write(OutputStream, InvalidAddress) - Static method in class org.omg.CosNaming.NamingContextExtPackage.InvalidAddressHelper
write(OutputStream, String) - Static method in class org.omg.CosNaming.NamingContextExtPackage.StringNameHelper
write(OutputStream, String) - Static method in class org.omg.CosNaming.NamingContextExtPackage.URLStringHelper
write(OutputStream, NamingContext) - Static method in class org.omg.CosNaming.NamingContextHelper
write(OutputStream, AlreadyBound) - Static method in class org.omg.CosNaming.NamingContextPackage.AlreadyBoundHelper
write(OutputStream, CannotProceed) - Static method in class org.omg.CosNaming.NamingContextPackage.CannotProceedHelper
write(OutputStream, InvalidName) - Static method in class org.omg.CosNaming.NamingContextPackage.InvalidNameHelper
write(OutputStream, NotEmpty) - Static method in class org.omg.CosNaming.NamingContextPackage.NotEmptyHelper
write(OutputStream, NotFound) - Static method in class org.omg.CosNaming.NamingContextPackage.NotFoundHelper
write(OutputStream, NotFoundReason) - Static method in class org.omg.CosNaming.NamingContextPackage.NotFoundReasonHelper
write(OutputStream, Any[]) - Static method in class org.omg.DynamicAny.AnySeqHelper
write(OutputStream, DynAnyFactory) - Static method in class org.omg.DynamicAny.DynAnyFactoryHelper
write(OutputStream, InconsistentTypeCode) - Static method in class org.omg.DynamicAny.DynAnyFactoryPackage.InconsistentTypeCodeHelper
write(OutputStream, DynAny) - Static method in class org.omg.DynamicAny.DynAnyHelper
write(OutputStream, InvalidValue) - Static method in class org.omg.DynamicAny.DynAnyPackage.InvalidValueHelper
write(OutputStream, TypeMismatch) - Static method in class org.omg.DynamicAny.DynAnyPackage.TypeMismatchHelper
write(OutputStream, DynAny[]) - Static method in class org.omg.DynamicAny.DynAnySeqHelper
write(OutputStream, DynArray) - Static method in class org.omg.DynamicAny.DynArrayHelper
write(OutputStream, DynEnum) - Static method in class org.omg.DynamicAny.DynEnumHelper
write(OutputStream, DynFixed) - Static method in class org.omg.DynamicAny.DynFixedHelper
write(OutputStream, DynSequence) - Static method in class org.omg.DynamicAny.DynSequenceHelper
write(OutputStream, DynStruct) - Static method in class org.omg.DynamicAny.DynStructHelper
write(OutputStream, DynUnion) - Static method in class org.omg.DynamicAny.DynUnionHelper
write(OutputStream, DynValue) - Static method in class org.omg.DynamicAny.DynValueHelper
write(OutputStream, String) - Static method in class org.omg.DynamicAny.FieldNameHelper
write(OutputStream, NameDynAnyPair) - Static method in class org.omg.DynamicAny.NameDynAnyPairHelper
write(OutputStream, NameDynAnyPair[]) - Static method in class org.omg.DynamicAny.NameDynAnyPairSeqHelper
write(OutputStream, NameValuePair) - Static method in class org.omg.DynamicAny.NameValuePairHelper
write(OutputStream, NameValuePair[]) - Static method in class org.omg.DynamicAny.NameValuePairSeqHelper
write(OutputStream, CodecFactory) - Static method in class org.omg.IOP.CodecFactoryHelper
write(OutputStream, UnknownEncoding) - Static method in class org.omg.IOP.CodecFactoryPackage.UnknownEncodingHelper
write(OutputStream, FormatMismatch) - Static method in class org.omg.IOP.CodecPackage.FormatMismatchHelper
write(OutputStream, InvalidTypeForEncoding) - Static method in class org.omg.IOP.CodecPackage.InvalidTypeForEncodingHelper
write(OutputStream, TypeMismatch) - Static method in class org.omg.IOP.CodecPackage.TypeMismatchHelper
write(OutputStream, int) - Static method in class org.omg.IOP.ComponentIdHelper
write(OutputStream, IOR) - Static method in class org.omg.IOP.IORHelper
write(OutputStream, TaggedComponent[]) - Static method in class org.omg.IOP.MultipleComponentProfileHelper
write(OutputStream, int) - Static method in class org.omg.IOP.ProfileIdHelper
write(OutputStream, ServiceContext) - Static method in class org.omg.IOP.ServiceContextHelper
write(OutputStream, ServiceContext[]) - Static method in class org.omg.IOP.ServiceContextListHelper
write(OutputStream, int) - Static method in class org.omg.IOP.ServiceIdHelper
write(OutputStream, TaggedComponent) - Static method in class org.omg.IOP.TaggedComponentHelper
write(OutputStream, TaggedProfile) - Static method in class org.omg.IOP.TaggedProfileHelper
write(OutputStream, short) - Static method in class org.omg.Messaging.SyncScopeHelper
write(OutputStream, int) - Static method in class org.omg.PortableInterceptor.AdapterManagerIdHelper
write(OutputStream, String[]) - Static method in class org.omg.PortableInterceptor.AdapterNameHelper
write(OutputStream, short) - Static method in class org.omg.PortableInterceptor.AdapterStateHelper
write(OutputStream, Current) - Static method in class org.omg.PortableInterceptor.CurrentHelper
write(OutputStream, ForwardRequest) - Static method in class org.omg.PortableInterceptor.ForwardRequestHelper
write(OutputStream, InvalidSlot) - Static method in class org.omg.PortableInterceptor.InvalidSlotHelper
write(OutputStream, IORInterceptor_3_0) - Static method in class org.omg.PortableInterceptor.IORInterceptor_3_0Helper
write(OutputStream, byte[]) - Static method in class org.omg.PortableInterceptor.ObjectIdHelper
write(OutputStream, ObjectReferenceFactory) - Static method in class org.omg.PortableInterceptor.ObjectReferenceFactoryHelper
write(OutputStream, ObjectReferenceTemplate) - Static method in class org.omg.PortableInterceptor.ObjectReferenceTemplateHelper
write(OutputStream, ObjectReferenceTemplate[]) - Static method in class org.omg.PortableInterceptor.ObjectReferenceTemplateSeqHelper
write(OutputStream, String) - Static method in class org.omg.PortableInterceptor.ORBIdHelper
write(OutputStream, DuplicateName) - Static method in class org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateNameHelper
write(OutputStream, InvalidName) - Static method in class org.omg.PortableInterceptor.ORBInitInfoPackage.InvalidNameHelper
write(OutputStream, String) - Static method in class org.omg.PortableInterceptor.ORBInitInfoPackage.ObjectIdHelper
write(OutputStream, String) - Static method in class org.omg.PortableInterceptor.ServerIdHelper
write(OutputStream, Current) - Static method in class org.omg.PortableServer.CurrentHelper
write(OutputStream, NoContext) - Static method in class org.omg.PortableServer.CurrentPackage.NoContextHelper
write(OutputStream, ForwardRequest) - Static method in class org.omg.PortableServer.ForwardRequestHelper
write(OutputStream, POA) - Static method in class org.omg.PortableServer.POAHelper
write(OutputStream, AdapterInactive) - Static method in class org.omg.PortableServer.POAManagerPackage.AdapterInactiveHelper
write(OutputStream, AdapterAlreadyExists) - Static method in class org.omg.PortableServer.POAPackage.AdapterAlreadyExistsHelper
write(OutputStream, AdapterNonExistent) - Static method in class org.omg.PortableServer.POAPackage.AdapterNonExistentHelper
write(OutputStream, InvalidPolicy) - Static method in class org.omg.PortableServer.POAPackage.InvalidPolicyHelper
write(OutputStream, NoServant) - Static method in class org.omg.PortableServer.POAPackage.NoServantHelper
write(OutputStream, ObjectAlreadyActive) - Static method in class org.omg.PortableServer.POAPackage.ObjectAlreadyActiveHelper
write(OutputStream, ObjectNotActive) - Static method in class org.omg.PortableServer.POAPackage.ObjectNotActiveHelper
write(OutputStream, ServantAlreadyActive) - Static method in class org.omg.PortableServer.POAPackage.ServantAlreadyActiveHelper
write(OutputStream, ServantNotActive) - Static method in class org.omg.PortableServer.POAPackage.ServantNotActiveHelper
write(OutputStream, WrongAdapter) - Static method in class org.omg.PortableServer.POAPackage.WrongAdapterHelper
write(OutputStream, WrongPolicy) - Static method in class org.omg.PortableServer.POAPackage.WrongPolicyHelper
write(OutputStream, ServantActivator) - Static method in class org.omg.PortableServer.ServantActivatorHelper
write(OutputStream, ServantLocator) - Static method in class org.omg.PortableServer.ServantLocatorHelper
write(Node, LSOutput) - Method in interface org.w3c.dom.ls.LSSerializer
Serialize the specified node as described above in the general description of the LSSerializer interface.
write_Abstract(Object) - Method in interface org.omg.CORBA.DataOutputStream
Writes the IDL Abstract interface type to the output stream.
write_abstract_interface(Object) - Method in class org.omg.CORBA_2_3.portable.OutputStream
Marshals a value object or a stub object.
write_any(Any) - Method in interface org.omg.CORBA.DataOutputStream
Writes the Any value to the output stream.
write_any(Any) - Method in class org.omg.CORBA.portable.OutputStream
Writes an Any on this output stream.
write_any_array(Any[], int, int) - Method in interface org.omg.CORBA.DataOutputStream
Writes the array of IDL Anys from offset for length elements to the output stream.
write_boolean(boolean) - Method in interface org.omg.CORBA.DataOutputStream
Writes the boolean value to the output stream.
write_boolean(boolean) - Method in class org.omg.CORBA.portable.OutputStream
Writes a boolean value to this stream.
write_boolean_array(boolean[], int, int) - Method in interface org.omg.CORBA.DataOutputStream
Writes the array of IDL booleans from offset for length elements to the output stream.
write_boolean_array(boolean[], int, int) - Method in class org.omg.CORBA.portable.OutputStream
Writes an array of booleans on this output stream.
write_char(char) - Method in interface org.omg.CORBA.DataOutputStream
Writes the IDL character value to the output stream.
write_char(char) - Method in class org.omg.CORBA.portable.OutputStream
Writes a char value to this stream.
write_char_array(char[], int, int) - Method in interface org.omg.CORBA.DataOutputStream
Writes the array of IDL characters from offset for length elements to the output stream.
write_char_array(char[], int, int) - Method in class org.omg.CORBA.portable.OutputStream
Writes an array of chars on this output stream.
write_Context(Context, ContextList) - Method in class org.omg.CORBA.portable.OutputStream
Writes a CORBA context on this stream.
write_double(double) - Method in interface org.omg.CORBA.DataOutputStream
Writes the IDL double value to the output stream.
write_double(double) - Method in class org.omg.CORBA.portable.OutputStream
Writes a double value to this stream.
write_double_array(double[], int, int) - Method in interface org.omg.CORBA.DataOutputStream
Writes the array of IDL doubles from offset for length elements to the output stream.
write_double_array(double[], int, int) - Method in class org.omg.CORBA.portable.OutputStream
Writes an array of doubles on this output stream.
WRITE_FAILURE - Static variable in class java.util.logging.ErrorManager
WRITE_FAILURE is used when a write to an output stream fails.
write_fixed(BigDecimal) - Method in class org.omg.CORBA.portable.OutputStream
Writes a BigDecimal number.
write_float(float) - Method in interface org.omg.CORBA.DataOutputStream
Writes the IDL float value to the output stream.
write_float(float) - Method in class org.omg.CORBA.portable.OutputStream
Writes a float value to this stream.
write_float_array(float[], int, int) - Method in interface org.omg.CORBA.DataOutputStream
Writes the array of IDL floats from offset for length elements to the output stream.
write_float_array(float[], int, int) - Method in class org.omg.CORBA.portable.OutputStream
Writes an array of floats on this output stream.
write_long(int) - Method in interface org.omg.CORBA.DataOutputStream
Writes the IDL long value (represented as a Java int) to the output stream.
write_long(int) - Method in class org.omg.CORBA.portable.OutputStream
Writes a CORBA long (i.e.
write_long_array(int[], int, int) - Method in interface org.omg.CORBA.DataOutputStream
Writes the array of IDL longs from offset for length elements to the output stream.
write_long_array(int[], int, int) - Method in class org.omg.CORBA.portable.OutputStream
Writes an array of CORBA longs (i.e.
write_longlong(long) - Method in interface org.omg.CORBA.DataOutputStream
Writes the IDL long long value (represented as a Java long) to the output stream.
write_longlong(long) - Method in class org.omg.CORBA.portable.OutputStream
Writes a CORBA longlong (i.e.
write_longlong_array(long[], int, int) - Method in interface org.omg.CORBA.DataOutputStream
Writes the array of IDL long longs from offset for length elements to the output stream.
write_longlong_array(long[], int, int) - Method in class org.omg.CORBA.portable.OutputStream
Writes an array of CORBA longlongs (i.e.
write_Object(Object) - Method in interface org.omg.CORBA.DataOutputStream
Writes the IDL CORBA::Object value to the output stream.
write_Object(Object) - Method in class org.omg.CORBA.portable.OutputStream
Writes a CORBA Object on this output stream.
write_octet(byte) - Method in interface org.omg.CORBA.DataOutputStream
Writes the IDL octet value (represented as a Java byte) to the output stream.
write_octet(byte) - Method in class org.omg.CORBA.portable.OutputStream
Writes a CORBA octet (i.e.
write_octet_array(byte[], int, int) - Method in interface org.omg.CORBA.DataOutputStream
Writes the array of IDL octets from offset for length elements to the output stream.
write_octet_array(byte[], int, int) - Method in class org.omg.CORBA.portable.OutputStream
Writes an array of CORBA octets (bytes) on this output stream.
write_Principal(Principal) - Method in class org.omg.CORBA.portable.OutputStream
Deprecated.
Deprecated by CORBA 2.2.
write_short(short) - Method in interface org.omg.CORBA.DataOutputStream
Writes the IDL short value to the output stream.
write_short(short) - Method in class org.omg.CORBA.portable.OutputStream
Writes a short value to this stream.
write_short_array(short[], int, int) - Method in interface org.omg.CORBA.DataOutputStream
Writes the array of IDL shorts from offset for length elements to the output stream.
write_short_array(short[], int, int) - Method in class org.omg.CORBA.portable.OutputStream
Writes an array of shorts on this output stream.
write_string(String) - Method in interface org.omg.CORBA.DataOutputStream
Writes the IDL string value to the output stream.
write_string(String) - Method in class org.omg.CORBA.portable.OutputStream
Writes a string value to this stream.
write_TypeCode(TypeCode) - Method in interface org.omg.CORBA.DataOutputStream
Writes the typecode to the output stream.
write_TypeCode(TypeCode) - Method in class org.omg.CORBA.portable.OutputStream
Writes a TypeCode on this output stream.
write_ulong(int) - Method in interface org.omg.CORBA.DataOutputStream
Writes the IDL unsigned long value (represented as a Java int) to the output stream.
write_ulong(int) - Method in class org.omg.CORBA.portable.OutputStream
Writes an unsigned CORBA long (i.e.
write_ulong_array(int[], int, int) - Method in interface org.omg.CORBA.DataOutputStream
Writes the array of IDL unsigned longs (represented as Java ints) from offset for length elements to the output stream.
write_ulong_array(int[], int, int) - Method in class org.omg.CORBA.portable.OutputStream
Writes an array of unsigned CORBA longs (i.e.
write_ulonglong(long) - Method in interface org.omg.CORBA.DataOutputStream
Writes the IDL unsigned long long value (represented as a Java long) to the output stream.
write_ulonglong(long) - Method in class org.omg.CORBA.portable.OutputStream
Writes an unsigned CORBA longlong (i.e.
write_ulonglong_array(long[], int, int) - Method in interface org.omg.CORBA.DataOutputStream
Writes the array of IDL unsigned long longs (represented as Java longs) from offset for length elements to the output stream.
write_ulonglong_array(long[], int, int) - Method in class org.omg.CORBA.portable.OutputStream
Writes an array of unsigned CORBA longlongs (i.e.
write_ushort(short) - Method in interface org.omg.CORBA.DataOutputStream
Writes the IDL unsigned short value (represented as a Java short value) to the output stream.
write_ushort(short) - Method in class org.omg.CORBA.portable.OutputStream
Writes an unsigned short value to this stream.
write_ushort_array(short[], int, int) - Method in interface org.omg.CORBA.DataOutputStream
Writes the array of IDL unsigned shorts (represented as Java shorts) from offset for length elements to the output stream.
write_ushort_array(short[], int, int) - Method in class org.omg.CORBA.portable.OutputStream
Writes an array of unsigned shorts on this output stream.
write_value(OutputStream) - Method in class org.omg.CORBA.Any
Writes out the value of this Any object to the given output stream.
write_Value(Serializable) - Method in interface org.omg.CORBA.DataOutputStream
Writes the IDL value type value to the output stream.
write_value(OutputStream, Serializable) - Method in interface org.omg.CORBA.portable.BoxedValueHelper
write_value(OutputStream, Serializable) - Method in class org.omg.CORBA.StringValueHelper
write_value(OutputStream, Serializable) - Method in class org.omg.CORBA.WStringValueHelper
write_value(Serializable) - Method in class org.omg.CORBA_2_3.portable.OutputStream
Marshals a value type to the output stream.
write_value(Serializable, Class) - Method in class org.omg.CORBA_2_3.portable.OutputStream
Marshals a value type to the output stream.
write_value(Serializable, String) - Method in class org.omg.CORBA_2_3.portable.OutputStream
Marshals a value type to the output stream.
write_value(Serializable, BoxedValueHelper) - Method in class org.omg.CORBA_2_3.portable.OutputStream
Marshals a value type to the output stream.
write_wchar(char) - Method in interface org.omg.CORBA.DataOutputStream
Writes the IDL wide character value to the output stream.
write_wchar(char) - Method in class org.omg.CORBA.portable.OutputStream
Writes a wide char value to this stream.
write_wchar_array(char[], int, int) - Method in interface org.omg.CORBA.DataOutputStream
Writes the array of IDL wide characters from offset for length elements to the output stream.
write_wchar_array(char[], int, int) - Method in class org.omg.CORBA.portable.OutputStream
Writes an array of wide chars on this output stream.
write_wstring(String) - Method in interface org.omg.CORBA.DataOutputStream
Writes the IDL wide string value (represented as a Java String) to the output stream.
write_wstring(String) - Method in class org.omg.CORBA.portable.OutputStream
Writes a wide string value to this stream.
WRITE_XML_DECLARATION - Static variable in class javax.xml.soap.SOAPMessage
Specifies whether the SOAP Message will contain an XML declaration when it is sent.
writeAborted(ImageWriter) - Method in interface javax.imageio.event.IIOWriteProgressListener
Reports that a write has been aborted via the writer's abort method.
WriteAbortedException - Exception in java.io
Signals that one of the ObjectStreamExceptions was thrown during a write operation.
WriteAbortedException(String, Exception) - Constructor for exception java.io.WriteAbortedException
Constructs a WriteAbortedException with a string describing the exception and the exception causing the abort.
writeAbstractObject(OutputStream, Object) - Static method in class javax.rmi.CORBA.Util
Writes a java.lang.Object as either a value or a CORBA Object.
writeAbstractObject(OutputStream, Object) - Method in interface javax.rmi.CORBA.UtilDelegate
Delegation call for Util.writeAbstractObject(org.omg.CORBA.portable.OutputStream, java.lang.Object).
writeAny(OutputStream, Object) - Static method in class javax.rmi.CORBA.Util
Writes any java.lang.Object as a CORBA any.
writeAny(OutputStream, Object) - Method in interface javax.rmi.CORBA.UtilDelegate
Delegation call for Util.writeAny(org.omg.CORBA.portable.OutputStream, java.lang.Object).
writeArray(Array) - Method in interface java.sql.SQLOutput
Writes an SQL ARRAY value to the stream.
writeArray(Array) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes an Array object in the Java programming language to this SQLOutputImpl object.
writeAsciiStream(InputStream) - Method in interface java.sql.SQLOutput
Writes the next attribute to the stream as a stream of ASCII characters.
writeAsciiStream(InputStream) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes a stream of ASCII characters to this SQLOutputImpl object.
writeAsEncodedUnicode(Writer) - Method in interface javax.xml.stream.events.XMLEvent
This method will write the XMLEvent as per the XML 1.0 specification as Unicode characters.
writeAttribute(String, String) - Method in interface javax.xml.stream.XMLStreamWriter
Writes an attribute to the output stream without a prefix.
writeAttribute(String, String, String, String) - Method in interface javax.xml.stream.XMLStreamWriter
Writes an attribute to the output stream
writeAttribute(String, String, String) - Method in interface javax.xml.stream.XMLStreamWriter
Writes an attribute to the output stream
writeAttributes(AttributeSet) - Method in class javax.swing.text.AbstractWriter
Writes out the set of attributes as " =" pairs.
writeAttributes(AttributeSet) - Method in class javax.swing.text.html.HTMLWriter
Writes out the attribute set.
writeAttributes(AttributeSet) - Method in class javax.swing.text.html.MinimalHTMLWriter
Writes out all the attributes for the following types: StyleConstants.ParagraphConstants, StyleConstants.CharacterConstants, StyleConstants.FontConstants, StyleConstants.ColorConstants.
writeAttributes(ObjectOutputStream, AttributeSet) - Method in class javax.swing.text.StyleContext
Context-specific handling of writing out attributes
writeAttributeSet(ObjectOutputStream, AttributeSet) - Static method in class javax.swing.text.StyleContext
Writes a set of attributes to the given object stream for the purpose of serialization.
writeBigDecimal(BigDecimal) - Method in interface java.sql.SQLOutput
Writes the next attribute to the stream as a java.math.BigDecimal object.
writeBigDecimal(BigDecimal) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes a java.math.BigDecimal object in the Java programming language to this SQLOutputImpl object.
writeBinaryStream(InputStream) - Method in interface java.sql.SQLOutput
Writes the next attribute to the stream as a stream of uninterpreted bytes.
writeBinaryStream(InputStream) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes a stream of uninterpreted bytes to this SQLOutputImpl object.
writeBit(int) - Method in interface javax.imageio.stream.ImageOutputStream
Writes a single bit, given by the least significant bit of the argument, to the stream at the current bit offset within the current byte position.
writeBit(int) - Method in class javax.imageio.stream.ImageOutputStreamImpl
writeBits(long, int) - Method in interface javax.imageio.stream.ImageOutputStream
Writes a sequence of bits, given by the numBits least significant bits of the bits argument in left-to-right order, to the stream at the current bit offset within the current byte position.
writeBits(long, int) - Method in class javax.imageio.stream.ImageOutputStreamImpl
writeBlob(Blob) - Method in interface java.sql.SQLOutput
Writes an SQL BLOB value to the stream.
writeBlob(Blob) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes a Blob object in the Java programming language to this SQLOutputImpl object.
writeBody() - Method in class javax.swing.text.html.MinimalHTMLWriter
Iterates over the elements in the document and processes elements based on whether they are branch elements or leaf elements.
writeBoolean(boolean) - Method in interface java.io.DataOutput
Writes a boolean value to this output stream.
writeBoolean(boolean) - Method in class java.io.DataOutputStream
Writes a boolean to the underlying output stream as a 1-byte value.
writeBoolean(boolean) - Method in class java.io.ObjectOutputStream
Writes a boolean.
writeBoolean(boolean) - Method in class java.io.RandomAccessFile
Writes a boolean to the file as a one-byte value.
writeBoolean(boolean) - Method in interface java.sql.SQLOutput
Writes the next attribute to the stream as a Java boolean.
writeBoolean(boolean) - Method in interface javax.imageio.stream.ImageOutputStream
Writes a boolean value to the stream.
writeBoolean(boolean) - Method in class javax.imageio.stream.ImageOutputStreamImpl
writeBoolean(boolean) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes a boolean in the Java programming language to this SQLOutputImpl object.
writeByte(int) - Method in interface java.io.DataOutput
Writes to the output stream the eight low- order bits of the argument v.
writeByte(int) - Method in class java.io.DataOutputStream
Writes out a byte to the underlying output stream as a 1-byte value.
writeByte(int) - Method in class java.io.ObjectOutputStream
Writes an 8 bit byte.
writeByte(int) - Method in class java.io.RandomAccessFile
Writes a byte to the file as a one-byte value.
writeByte(byte) - Method in interface java.sql.SQLOutput
Writes the next attribute to the stream as a Java byte.
writeByte(int) - Method in interface javax.imageio.stream.ImageOutputStream
Writes the 8 low-order bits of v to the stream.
writeByte(int) - Method in class javax.imageio.stream.ImageOutputStreamImpl
writeByte(byte) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes a byte in the Java programming language to this SQLOutputImpl object.
writeBytes(String) - Method in interface java.io.DataOutput
Writes a string to the output stream.
writeBytes(String) - Method in class java.io.DataOutputStream
Writes out the string to the underlying output stream as a sequence of bytes.
writeBytes(String) - Method in class java.io.ObjectOutputStream
Writes a String as a sequence of bytes.
writeBytes(String) - Method in class java.io.RandomAccessFile
Writes the string to the file as a sequence of bytes.
writeBytes(byte[]) - Method in interface java.sql.SQLOutput
Writes the next attribute to the stream as an array of bytes.
writeBytes(String) - Method in interface javax.imageio.stream.ImageOutputStream
Writes a string to the output stream.
writeBytes(String) - Method in class javax.imageio.stream.ImageOutputStreamImpl
writeBytes(byte[]) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes an array of bytes in the Java programming language to this SQLOutputImpl object.
writeCData(String) - Method in interface javax.xml.stream.XMLStreamWriter
Writes a CData section
writeChar(int) - Method in interface java.io.DataOutput
Writes a char value, which is comprised of two bytes, to the output stream.
writeChar(int) - Method in class java.io.DataOutputStream
Writes a char to the underlying output stream as a 2-byte value, high byte first.
writeChar(int) - Method in class java.io.ObjectOutputStream
Writes a 16 bit char.
writeChar(int) - Method in class java.io.RandomAccessFile
Writes a char to the file as a two-byte value, high byte first.
writeChar(int) - Method in interface javax.imageio.stream.ImageOutputStream
This method is a synonym for writeShort.
writeChar(int) - Method in class javax.imageio.stream.ImageOutputStreamImpl
writeCharacters(String) - Method in interface javax.xml.stream.XMLStreamWriter
Write text to the output
writeCharacters(char[], int, int) - Method in interface javax.xml.stream.XMLStreamWriter
Write text to the output
writeCharacterStream(Reader) - Method in interface java.sql.SQLOutput
Writes the next attribute to the stream as a stream of Unicode characters.
writeCharacterStream(Reader) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes a stream of Unicode characters to this SQLOutputImpl object.
writeChars(String) - Method in interface java.io.DataOutput
Writes every character in the string s, to the output stream, in order, two bytes per character.
writeChars(String) - Method in class java.io.DataOutputStream
Writes a string to the underlying output stream as a sequence of characters.
writeChars(String) - Method in class java.io.ObjectOutputStream
Writes a String as a sequence of chars.
writeChars(String) - Method in class java.io.RandomAccessFile
Writes a string to the file as a sequence of characters.
writeChars(String) - Method in interface javax.imageio.stream.ImageOutputStream
Writes a string to the output stream.
writeChars(char[], int, int) - Method in interface javax.imageio.stream.ImageOutputStream
Writes a sequence of chars to the stream at the current position.
writeChars(String) - Method in class javax.imageio.stream.ImageOutputStreamImpl
writeChars(char[], int, int) - Method in class javax.imageio.stream.ImageOutputStreamImpl
writeChildren(ObjectOutputStream) - Method in class java.beans.beancontext.BeanContextSupport
Used to serialize all children of this BeanContext.
writeClassDescriptor(ObjectStreamClass) - Method in class java.io.ObjectOutputStream
Write the specified class descriptor to the ObjectOutputStream.
writeClob(Clob) - Method in interface java.sql.SQLOutput
Writes an SQL CLOB value to the stream.
writeClob(Clob) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes a Clob object in the Java programming language to this SQLOutputImpl object.
writeComment(String) - Method in interface javax.xml.stream.XMLStreamWriter
Writes an xml comment with the data enclosed
writeComponent(Element) - Method in class javax.swing.text.html.MinimalHTMLWriter
Responsible for handling Component Elements; deliberately unimplemented.
writeContent(Element, boolean) - Method in class javax.swing.text.html.MinimalHTMLWriter
Writes out the attribute set in an HTML-compliant manner.
writeData(RowSetInternal) - Method in interface javax.sql.RowSetWriter
Writes the changes in this RowSetWriter object's rowset back to the data source from which it got its data.
writeDate(Date) - Method in interface java.sql.SQLOutput
Writes the next attribute to the stream as a java.sql.Date object.
writeDate(Date) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes a java.sql.Date object in the Java programming language to this SQLOutputImpl object.
writeDefaultNamespace(String) - Method in interface javax.xml.stream.XMLStreamWriter
Writes the default namespace to the stream
writeDouble(double) - Method in interface java.io.DataOutput
Writes a double value, which is comprised of eight bytes, to the output stream.
writeDouble(double) - Method in class java.io.DataOutputStream
Converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the underlying output stream as an 8-byte quantity, high byte first.
writeDouble(double) - Method in class java.io.ObjectOutputStream
Writes a 64 bit double.
writeDouble(double) - Method in class java.io.RandomAccessFile
Converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the file as an eight-byte quantity, high byte first.
writeDouble(double) - Method in interface java.sql.SQLOutput
Writes the next attribute to the stream as a Java double.
writeDouble(double) - Method in interface javax.imageio.stream.ImageOutputStream
Writes a double value, which is comprised of four bytes, to the output stream.
writeDouble(double) - Method in class javax.imageio.stream.ImageOutputStreamImpl
writeDouble(double) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes a double in the Java programming language to this SQLOutputImpl object.
writeDoubles(double[], int, int) - Method in interface javax.imageio.stream.ImageOutputStream
Writes a sequence of doubles to the stream at the current position.
writeDoubles(double[], int, int) - Method in class javax.imageio.stream.ImageOutputStreamImpl
writeDTD(String) - Method in interface javax.xml.stream.XMLStreamWriter
Write a DTD section.
writeEmbeddedTags(AttributeSet) - Method in class javax.swing.text.html.HTMLWriter
Searches for embedded tags in the AttributeSet and writes them out.
writeEmptyElement(String, String) - Method in interface javax.xml.stream.XMLStreamWriter
Writes an empty element tag to the output
writeEmptyElement(String, String, String) - Method in interface javax.xml.stream.XMLStreamWriter
Writes an empty element tag to the output
writeEmptyElement(String) - Method in interface javax.xml.stream.XMLStreamWriter
Writes an empty element tag to the output
writeEndDocument() - Method in interface javax.xml.stream.XMLStreamWriter
Closes any start tags and writes corresponding end tags.
writeEndElement() - Method in interface javax.xml.stream.XMLStreamWriter
Writes an end tag to the output relying on the internal state of the writer to determine the prefix and local name of the event.
writeEndParagraph() - Method in class javax.swing.text.html.MinimalHTMLWriter
Emits an end tag for a <p> tag.
writeEndTag(String) - Method in class javax.swing.text.html.MinimalHTMLWriter
Writes out an end tag appropriately indented.
writeEntityRef(String) - Method in interface javax.xml.stream.XMLStreamWriter
Writes an entity reference
writeExpression(Expression) - Method in class java.beans.Encoder
The implementation first checks to see if an expression with this value has already been written.
writeExpression(Expression) - Method in class java.beans.XMLEncoder
Records the Expression so that the Encoder will produce the actual output when the stream is flushed.
writeExternal(ObjectOutput) - Method in class java.awt.datatransfer.DataFlavor
Serializes this DataFlavor.
writeExternal(ObjectOutput) - Method in interface java.io.Externalizable
The object implements the writeExternal method to save its contents by calling the methods of DataOutput for its primitive values or calling the writeObject method of ObjectOutput for objects, strings, and arrays.
writeExternal(ObjectOutput) - Method in class javax.activation.MimeType
The object implements the writeExternal method to save its contents by calling the methods of DataOutput for its primitive values or calling the writeObject method of ObjectOutput for objects, strings and arrays.
writeExternal(ObjectOutput) - Method in class javax.management.loading.MLet
Save this MLet's contents to the given ObjectOutput.
writeFields() - Method in class java.io.ObjectOutputStream
Write the buffered fields to the stream.
writeFloat(float) - Method in interface java.io.DataOutput
Writes a float value, which is comprised of four bytes, to the output stream.
writeFloat(float) - Method in class java.io.DataOutputStream
Converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the underlying output stream as a 4-byte quantity, high byte first.
writeFloat(float) - Method in class java.io.ObjectOutputStream
Writes a 32 bit float.
writeFloat(float) - Method in class java.io.RandomAccessFile
Converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the file as a four-byte quantity, high byte first.
writeFloat(float) - Method in interface java.sql.SQLOutput
Writes the next attribute to the stream as a Java float.
writeFloat(float) - Method in interface javax.imageio.stream.ImageOutputStream
Writes a float value, which is comprised of four bytes, to the output stream.
writeFloat(float) - Method in class javax.imageio.stream.ImageOutputStreamImpl
writeFloat(float) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes a float in the Java programming language to this SQLOutputImpl object.
writeFloats(float[], int, int) - Method in interface javax.imageio.stream.ImageOutputStream
Writes a sequence of floats to the stream at the current position.
writeFloats(float[], int, int) - Method in class javax.imageio.stream.ImageOutputStreamImpl
writeHeader() - Method in class javax.swing.text.html.MinimalHTMLWriter
Writes out the <head> and <style> tags, and then invokes writeStyles() to write out all the named styles as the content of the <style> tag.
writeHTMLTags(AttributeSet) - Method in class javax.swing.text.html.MinimalHTMLWriter
Generates bold <b>, italic <i>, and <u> tags for the text based on its attribute settings.
writeImage(Element) - Method in class javax.swing.text.html.MinimalHTMLWriter
Responsible for handling Icon Elements; deliberately unimplemented.
writeInsert(int, IIOImage, ImageWriteParam) - Method in class javax.imageio.ImageWriter
Inserts a new image into an existing image stream.
writeInt(int) - Method in interface java.io.DataOutput
Writes an int value, which is comprised of four bytes, to the output stream.
writeInt(int) - Method in class java.io.DataOutputStream
Writes an int to the underlying output stream as four bytes, high byte first.
writeInt(int) - Method in class java.io.ObjectOutputStream
Writes a 32 bit int.
writeInt(int) - Method in class java.io.RandomAccessFile
Writes an int to the file as four bytes, high byte first.
writeInt(int) - Method in interface java.sql.SQLOutput
Writes the next attribute to the stream as a Java int.
writeInt(int) - Method in interface javax.imageio.stream.ImageOutputStream
Writes the 32 bits of v to the stream.
writeInt(int) - Method in class javax.imageio.stream.ImageOutputStreamImpl
writeInt(int) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes an int in the Java programming language to this SQLOutputImpl object.
writeInts(int[], int, int) - Method in interface javax.imageio.stream.ImageOutputStream
Writes a sequence of ints to the stream at the current position.
writeInts(int[], int, int) - Method in class javax.imageio.stream.ImageOutputStreamImpl
writeLeaf(Element) - Method in class javax.swing.text.html.MinimalHTMLWriter
Responsible for writing out other non-text leaf elements.
writeLineSeparator() - Method in class javax.swing.text.AbstractWriter
Writes the line separator.
writeLineSeparator() - Method in class javax.swing.text.html.HTMLWriter
Writes the line separator.
writeLock() - Method in interface java.util.concurrent.locks.ReadWriteLock
Returns the lock used for writing.
writeLock() - Method in class java.util.concurrent.locks.ReentrantReadWriteLock
writeLock() - Method in class javax.swing.text.AbstractDocument
Acquires a lock to begin mutating the document this lock protects.
writeLong(long) - Method in interface java.io.DataOutput
Writes a long value, which is comprised of eight bytes, to the output stream.
writeLong(long) - Method in class java.io.DataOutputStream
Writes a long to the underlying output stream as eight bytes, high byte first.
writeLong(long) - Method in class java.io.ObjectOutputStream
Writes a 64 bit long.
writeLong(long) - Method in class java.io.RandomAccessFile
Writes a long to the file as eight bytes, high byte first.
writeLong(long) - Method in interface java.sql.SQLOutput
Writes the next attribute to the stream as a Java long.
writeLong(long) - Method in interface javax.imageio.stream.ImageOutputStream
Writes the 64 bits of v to the stream.
writeLong(long) - Method in class javax.imageio.stream.ImageOutputStreamImpl
writeLong(long) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes a long in the Java programming language to this SQLOutputImpl object.
writeLongs(long[], int, int) - Method in interface javax.imageio.stream.ImageOutputStream
Writes a sequence of longs to the stream at the current position.
writeLongs(long[], int, int) - Method in class javax.imageio.stream.ImageOutputStreamImpl
writeNamespace(String, String) - Method in interface javax.xml.stream.XMLStreamWriter
Writes a namespace to the output stream If the prefix argument to this method is the empty string, "xmlns", or null this method will delegate to writeDefaultNamespace
writeNClob(NClob) - Method in interface java.sql.SQLOutput
Writes an SQL NCLOB value to the stream.
writeNClob(NClob) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes an SQL NCLOB value to the stream.
writeNonHTMLAttributes(AttributeSet) - Method in class javax.swing.text.html.MinimalHTMLWriter
Writes out the remaining character-level attributes (attributes other than bold, italic, and underline) in an HTML-compliant way.
writeNString(String) - Method in interface java.sql.SQLOutput
Writes the next attribute to the stream as a String in the Java programming language.
writeNString(String) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes the next attribute to the stream as a String in the Java programming language.
writeObject(Object) - Method in class java.beans.Encoder
Write the specified object to the output stream.
writeObject(Object, Encoder) - Method in class java.beans.PersistenceDelegate
The writeObject is a single entry point to the persistence and is used by a Encoder in the traditional mode of delegation.
writeObject(Object) - Method in class java.beans.XMLEncoder
Write an XML representation of the specified object to the output.
writeObject(Object) - Method in interface java.io.ObjectOutput
Write an object to the underlying storage or stream.
writeObject(Object) - Method in class java.io.ObjectOutputStream
Write the specified object to the ObjectOutputStream.
writeObject(SQLData) - Method in interface java.sql.SQLOutput
Writes to the stream the data contained in the given SQLData object.
writeObject(Stub, ObjectOutputStream) - Method in interface javax.rmi.CORBA.StubDelegate
Delegation call for Stub.writeObject(java.io.ObjectOutputStream).
writeObject(SQLData) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes to the stream the data contained in the given SQLData object.
writeObjectOverride(Object) - Method in class java.io.ObjectOutputStream
Method used by subclasses to override the default writeObject method.
writeOption(Option) - Method in class javax.swing.text.html.HTMLWriter
Writes out the content of the Option form element.
WritePendingException - Exception in java.nio.channels
Unchecked exception thrown when an attempt is made to write to an asynchronous socket channel and a previous write has not completed.
WritePendingException() - Constructor for exception java.nio.channels.WritePendingException
Constructs an instance of this class.
writeProcessingInstruction(String) - Method in interface javax.xml.stream.XMLStreamWriter
Writes a processing instruction
writeProcessingInstruction(String, String) - Method in interface javax.xml.stream.XMLStreamWriter
Writes a processing instruction
writer() - Method in class java.io.Console
Retrieves the unique PrintWriter object associated with this console.
Writer - Class in java.io
Abstract class for writing to character streams.
Writer() - Constructor for class java.io.Writer
Creates a new character-stream writer whose critical sections will synchronize on the writer itself.
Writer(Object) - Constructor for class java.io.Writer
Creates a new character-stream writer whose critical sections will synchronize on the given object.
writer - Variable in class javax.script.SimpleScriptContext
This is the writer to be used to output from scripts.
writeRef(Ref) - Method in interface java.sql.SQLOutput
Writes an SQL REF value to the stream.
writeRef(Ref) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes a Ref object in the Java programming language to this SQLOutputImpl object.
writeRemoteObject(OutputStream, Object) - Static method in class javax.rmi.CORBA.Util
Writes a java.lang.Object as a CORBA Object.
writeRemoteObject(OutputStream, Object) - Method in interface javax.rmi.CORBA.UtilDelegate
Delegation call for Util.writeRemoteObject(org.omg.CORBA.portable.OutputStream, java.lang.Object).
writeReplace() - Method in class java.security.cert.Certificate
Replace the Certificate to be serialized.
writeReplace() - Method in class java.security.cert.CertPath
Replaces the CertPath to be serialized with a CertPathRep object.
writeReplace(Serializable) - Method in interface javax.rmi.CORBA.ValueHandler
If the value contains a writeReplace method then the result is returned.
writeRowId(RowId) - Method in interface java.sql.SQLOutput
Writes an SQL ROWID value to the stream.
writeRowId(RowId) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes an SQL ROWID value to the stream.
writerSpiNames - Variable in class javax.imageio.spi.ImageReaderSpi
An array of strings to be returned from getImageWriterSpiNames, initially null.
writeShort(int) - Method in interface java.io.DataOutput
Writes two bytes to the output stream to represent the value of the argument.
writeShort(int) - Method in class java.io.DataOutputStream
Writes a short to the underlying output stream as two bytes, high byte first.
writeShort(int) - Method in class java.io.ObjectOutputStream
Writes a 16 bit short.
writeShort(int) - Method in class java.io.RandomAccessFile
Writes a short to the file as two bytes, high byte first.
writeShort(short) - Method in interface java.sql.SQLOutput
Writes the next attribute to the stream as a Java short.
writeShort(int) - Method in interface javax.imageio.stream.ImageOutputStream
Writes the 16 low-order bits of v to the stream.
writeShort(int) - Method in class javax.imageio.stream.ImageOutputStreamImpl
writeShort(short) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes a short in the Java programming language to this SQLOutputImpl object.
writeShorts(short[], int, int) - Method in interface javax.imageio.stream.ImageOutputStream
Writes a sequence of shorts to the stream at the current position.
writeShorts(short[], int, int) - Method in class javax.imageio.stream.ImageOutputStreamImpl
writeSQL(SQLOutput) - Method in interface java.sql.SQLData
Writes this object to the given SQL data stream, converting it back to its SQL value in the data source.
writeSQLXML(SQLXML) - Method in interface java.sql.SQLOutput
Writes an SQL XML value to the stream.
writeSQLXML(SQLXML) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes an SQL XML value to the stream.
writeStartDocument() - Method in interface javax.xml.stream.XMLStreamWriter
Write the XML Declaration.
writeStartDocument(String) - Method in interface javax.xml.stream.XMLStreamWriter
Write the XML Declaration.
writeStartDocument(String, String) - Method in interface javax.xml.stream.XMLStreamWriter
Write the XML Declaration.
writeStartElement(String) - Method in interface javax.xml.stream.XMLStreamWriter
Writes a start tag to the output.
writeStartElement(String, String) - Method in interface javax.xml.stream.XMLStreamWriter
Writes a start tag to the output
writeStartElement(String, String, String) - Method in interface javax.xml.stream.XMLStreamWriter
Writes a start tag to the output
writeStartParagraph(Element) - Method in class javax.swing.text.html.MinimalHTMLWriter
Emits the start tag for a paragraph.
writeStartTag(String) - Method in class javax.swing.text.html.MinimalHTMLWriter
Writes out a start tag appropriately indented.
writeStatement(Statement) - Method in class java.beans.Encoder
Writes statement oldStm to the stream.
writeStatement(Statement) - Method in class java.beans.XMLEncoder
Records the Statement so that the Encoder will produce the actual output when the stream is flushed.
writeStreamHeader() - Method in class java.io.ObjectOutputStream
The writeStreamHeader method is provided so subclasses can append or prepend their own header to the stream.
writeString(String) - Method in interface java.sql.SQLOutput
Writes the next attribute to the stream as a String in the Java programming language.
writeString(String) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes a String in the Java programming language to this SQLOutputImpl object.
writeStruct(Struct) - Method in interface java.sql.SQLOutput
Writes an SQL structured type value to the stream.
writeStruct(Struct) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes a Struct object in the Java programming language to this SQLOutputImpl object.
writeStyles() - Method in class javax.swing.text.html.MinimalHTMLWriter
Writes out all the named styles as the content of the <style> tag.
writeTime(Time) - Method in interface java.sql.SQLOutput
Writes the next attribute to the stream as a java.sql.Time object.
writeTime(Time) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes a java.sql.Time object in the Java programming language to this SQLOutputImpl object.
writeTimestamp(Timestamp) - Method in interface java.sql.SQLOutput
Writes the next attribute to the stream as a java.sql.Timestamp object.
writeTimestamp(Timestamp) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes a java.sql.Timestamp object in the Java programming language to this SQLOutputImpl object.
writeTo(OutputStream) - Method in class java.io.ByteArrayOutputStream
Writes the complete contents of this byte array output stream to the specified output stream argument, as if by calling the output stream's write method using out.write(buf, 0, count).
writeTo(Writer) - Method in class java.io.CharArrayWriter
Writes the contents of the buffer to another character stream.
writeTo(Object, String, OutputStream) - Method in interface javax.activation.DataContentHandler
Convert the object to a byte stream of the specified MIME type and write it to the output stream.
writeTo(OutputStream) - Method in class javax.activation.DataHandler
Write the data to an OutputStream.
writeTo(OutputStream) - Method in class javax.xml.soap.SOAPMessage
Writes this SOAPMessage object to the given output stream.
writeTo(Result) - Method in class javax.xml.ws.EndpointReference
write this EndpointReference to the specified infoset format
writeTo(Result) - Method in class javax.xml.ws.wsaddressing.W3CEndpointReference
write this EndpointReference to the specified infoset format
writeToSequence(IIOImage, ImageWriteParam) - Method in class javax.imageio.ImageWriter
Appends a single image and possibly associated metadata and thumbnails, to the output.
writeToString(Node) - Method in interface org.w3c.dom.ls.LSSerializer
Serialize the specified node as described above in the general description of the LSSerializer interface.
writeToURI(Node, String) - Method in interface org.w3c.dom.ls.LSSerializer
A convenience method that acts as if LSSerializer.write was called with a LSOutput with no encoding specified and LSOutput.systemId set to the uri argument.
writeUnlock() - Method in class javax.swing.text.AbstractDocument
Releases a write lock previously obtained via writeLock.
writeUnshared(Object) - Method in class java.io.ObjectOutputStream
Writes an "unshared" object to the ObjectOutputStream.
writeURL(URL) - Method in interface java.sql.SQLOutput
Writes a SQL DATALINK value to the stream.
writeURL(URL) - Method in class javax.sql.rowset.serial.SQLOutputImpl
Writes an java.sql.Type.DATALINK object in the Java programming language to this SQLOutputImpl object.
writeUTF(String) - Method in interface java.io.DataOutput
Writes two bytes of length information to the output stream, followed by the modified UTF-8 representation of every character in the string s.
writeUTF(String) - Method in class java.io.DataOutputStream
Writes a string to the underlying output stream using modified UTF-8 encoding in a machine-independent manner.
writeUTF(String) - Method in class java.io.ObjectOutputStream
Primitive data write of this String in modified UTF-8 format.
writeUTF(String) - Method in class java.io.RandomAccessFile
Writes a string to the file using modified UTF-8 encoding in a machine-independent manner.
writeUTF(String) - Method in interface javax.imageio.stream.ImageOutputStream
Writes two bytes of length information to the output stream in network byte order, followed by the modified UTF-8 representation of every character in the string s.
writeUTF(String) - Method in class javax.imageio.stream.ImageOutputStreamImpl
writeValue(OutputStream, Serializable) - Method in interface javax.rmi.CORBA.ValueHandler
Writes a value to the stream using Java semantics.
writeValue(OutputStream, Serializable, byte) - Method in interface javax.rmi.CORBA.ValueHandlerMultiFormat
Allows the ORB to pass the stream format version for RMI/IDL custom value types.
writeXML(WebRowSet, Writer) - Method in interface javax.sql.rowset.spi.XmlWriter
Writes the given WebRowSet object to the specified java.io.Writer output stream as an XML document.
writeXml(ResultSet, Writer) - Method in interface javax.sql.rowset.WebRowSet
Populates this WebRowSet object with the contents of the given ResultSet object and writes its data, properties, and metadata to the given Writer object in XML format.
writeXml(ResultSet, OutputStream) - Method in interface javax.sql.rowset.WebRowSet
Populates this WebRowSet object with the contents of the given ResultSet object and writes its data, properties, and metadata to the given OutputStream object in XML format.
writeXml(Writer) - Method in interface javax.sql.rowset.WebRowSet
Writes the data, properties, and metadata for this WebRowSet object to the given Writer object in XML format.
writeXml(OutputStream) - Method in interface javax.sql.rowset.WebRowSet
Writes the data, properties, and metadata for this WebRowSet object to the given OutputStream object in XML format.
written - Variable in class java.io.DataOutputStream
The number of bytes written to the data output stream so far.
WRONG_DOCUMENT_ERR - Static variable in exception org.w3c.dom.DOMException
If a Node is used in a different document than the one that created it (that doesn't support it).
WrongAdapter - Exception in org.omg.PortableServer.POAPackage
org/omg/PortableServer/POAPackage/WrongAdapter.java .
WrongAdapter() - Constructor for exception org.omg.PortableServer.POAPackage.WrongAdapter
WrongAdapter(String) - Constructor for exception org.omg.PortableServer.POAPackage.WrongAdapter
WrongAdapterHelper - Class in org.omg.PortableServer.POAPackage
org/omg/PortableServer/POAPackage/WrongAdapterHelper.java .
WrongAdapterHelper() - Constructor for class org.omg.PortableServer.POAPackage.WrongAdapterHelper
WrongMethodTypeException - Exception in java.lang.invoke
Thrown to indicate that code has attempted to call a method handle via the wrong method type.
WrongMethodTypeException() - Constructor for exception java.lang.invoke.WrongMethodTypeException
Constructs a WrongMethodTypeException with no detail message.
WrongMethodTypeException(String) - Constructor for exception java.lang.invoke.WrongMethodTypeException
Constructs a WrongMethodTypeException with the specified detail message.
WrongPolicy - Exception in org.omg.PortableServer.POAPackage
org/omg/PortableServer/POAPackage/WrongPolicy.java .
WrongPolicy() - Constructor for exception org.omg.PortableServer.POAPackage.WrongPolicy
WrongPolicy(String) - Constructor for exception org.omg.PortableServer.POAPackage.WrongPolicy
WrongPolicyHelper - Class in org.omg.PortableServer.POAPackage
org/omg/PortableServer/POAPackage/WrongPolicyHelper.java .
WrongPolicyHelper() - Constructor for class org.omg.PortableServer.POAPackage.WrongPolicyHelper
WrongTransaction - Exception in org.omg.CORBA
The CORBA WrongTransaction user-defined exception.
WrongTransaction() - Constructor for exception org.omg.CORBA.WrongTransaction
Constructs a WrongTransaction object with an empty detail message.
WrongTransaction(String) - Constructor for exception org.omg.CORBA.WrongTransaction
Constructs a WrongTransaction object with the given detail message.
WrongTransactionHelper - Class in org.omg.CORBA
The Helper for WrongTransaction.
WrongTransactionHelper() - Constructor for class org.omg.CORBA.WrongTransactionHelper
WrongTransactionHolder - Class in org.omg.CORBA
The Holder for WrongTransaction.
WrongTransactionHolder() - Constructor for class org.omg.CORBA.WrongTransactionHolder
WrongTransactionHolder(WrongTransaction) - Constructor for class org.omg.CORBA.WrongTransactionHolder
WSDL_DESCRIPTION - Static variable in interface javax.xml.ws.handler.MessageContext
Standard property: input source for WSDL document.
WSDL_INTERFACE - Static variable in interface javax.xml.ws.handler.MessageContext
Standard property: name of wsdl interface (2.0) or port type (1.1).
WSDL_OPERATION - Static variable in interface javax.xml.ws.handler.MessageContext
Standard property: name of WSDL operation.
WSDL_PORT - Static variable in class javax.xml.ws.Endpoint
Standard property: name of WSDL port.
WSDL_PORT - Static variable in interface javax.xml.ws.handler.MessageContext
Standard property: name of WSDL port.
WSDL_SERVICE - Static variable in class javax.xml.ws.Endpoint
Standard property: name of WSDL service.
WSDL_SERVICE - Static variable in interface javax.xml.ws.handler.MessageContext
Standard property: name of WSDL service.
wsdlDocumentLocation(String) - Method in class javax.xml.ws.wsaddressing.W3CEndpointReferenceBuilder
Sets the wsdlDocumentLocation that will be referenced as wsa:Metadata/@wsdli:wsdlLocation.
WStringSeqHelper - Class in org.omg.CORBA
An array of WStrings
WStringSeqHelper() - Constructor for class org.omg.CORBA.WStringSeqHelper
WStringSeqHolder - Class in org.omg.CORBA
An array of WStrings
WStringSeqHolder() - Constructor for class org.omg.CORBA.WStringSeqHolder
WStringSeqHolder(String[]) - Constructor for class org.omg.CORBA.WStringSeqHolder
WStringValueHelper - Class in org.omg.CORBA
org/omg/CORBA/WStringValueHelper.java Generated by the IDL-to-Java compiler (portable), version "3.0" from orb.idl 31 May 1999 22:27:30 o'clock GMT+00:00 The class definition has been modified to conform to the following OMG specifications : ORB core as defined by CORBA 2.3.1 (formal/99-10-07) IDL/Java Language Mapping as defined in ptc/00-01-08
WStringValueHelper() - Constructor for class org.omg.CORBA.WStringValueHelper
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类


X-Index

请注意：本 java api 1.7Beta 规范不是最终稳定版，未来随着版本的更迭，本规范可能有更新。
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _

X

x - Variable in class java.awt.Event
The x coordinate of the event.
x - Variable in class java.awt.geom.Arc2D.Double
The X coordinate of the upper-left corner of the framing rectangle of the arc.
x - Variable in class java.awt.geom.Arc2D.Float
The X coordinate of the upper-left corner of the framing rectangle of the arc.
x - Variable in class java.awt.geom.Ellipse2D.Double
The X coordinate of the upper-left corner of the framing rectangle of this Ellipse2D.
x - Variable in class java.awt.geom.Ellipse2D.Float
The X coordinate of the upper-left corner of the framing rectangle of this Ellipse2D.
x - Variable in class java.awt.geom.Point2D.Double
The X coordinate of this Point2D.
x - Variable in class java.awt.geom.Point2D.Float
The X coordinate of this Point2D.
x - Variable in class java.awt.geom.Rectangle2D.Double
The X coordinate of this Rectangle2D.
x - Variable in class java.awt.geom.Rectangle2D.Float
The X coordinate of this Rectangle2D.
x - Variable in class java.awt.geom.RoundRectangle2D.Double
The X coordinate of this RoundRectangle2D.
x - Variable in class java.awt.geom.RoundRectangle2D.Float
The X coordinate of this RoundRectangle2D.
x - Variable in class java.awt.Point
The X coordinate of this Point.
x - Variable in class java.awt.Rectangle
The X coordinate of the upper-left corner of the Rectangle.
x1 - Variable in class java.awt.geom.CubicCurve2D.Double
The X coordinate of the start point of the cubic curve segment.
x1 - Variable in class java.awt.geom.CubicCurve2D.Float
The X coordinate of the start point of the cubic curve segment.
x1 - Variable in class java.awt.geom.Line2D.Double
The X coordinate of the start point of the line segment.
x1 - Variable in class java.awt.geom.Line2D.Float
The X coordinate of the start point of the line segment.
x1 - Variable in class java.awt.geom.QuadCurve2D.Double
The X coordinate of the start point of the quadratic curve segment.
x1 - Variable in class java.awt.geom.QuadCurve2D.Float
The X coordinate of the start point of the quadratic curve segment.
x2 - Variable in class java.awt.geom.CubicCurve2D.Double
The X coordinate of the end point of the cubic curve segment.
x2 - Variable in class java.awt.geom.CubicCurve2D.Float
The X coordinate of the end point of the cubic curve segment.
x2 - Variable in class java.awt.geom.Line2D.Double
The X coordinate of the end point of the line segment.
x2 - Variable in class java.awt.geom.Line2D.Float
The X coordinate of the end point of the line segment.
x2 - Variable in class java.awt.geom.QuadCurve2D.Double
The X coordinate of the end point of the quadratic curve segment.
x2 - Variable in class java.awt.geom.QuadCurve2D.Float
The X coordinate of the end point of the quadratic curve segment.
X500Principal - Class in javax.security.auth.x500
This class represents an X.500 Principal.
X500Principal(String) - Constructor for class javax.security.auth.x500.X500Principal
Creates an X500Principal from a string representation of an X.500 distinguished name (ex: "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US").
X500Principal(String, Map<String, String>) - Constructor for class javax.security.auth.x500.X500Principal
Creates an X500Principal from a string representation of an X.500 distinguished name (ex: "CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US").
X500Principal(byte[]) - Constructor for class javax.security.auth.x500.X500Principal
Creates an X500Principal from a distinguished name in ASN.1 DER encoded form.
X500Principal(InputStream) - Constructor for class javax.security.auth.x500.X500Principal
Creates an X500Principal from an InputStream containing the distinguished name in ASN.1 DER encoded form.
X500PrivateCredential - Class in javax.security.auth.x500
This class represents an X500PrivateCredential.
X500PrivateCredential(X509Certificate, PrivateKey) - Constructor for class javax.security.auth.x500.X500PrivateCredential
Creates an X500PrivateCredential that associates an X.509 certificate, a private key and the KeyStore alias.
X500PrivateCredential(X509Certificate, PrivateKey, String) - Constructor for class javax.security.auth.x500.X500PrivateCredential
Creates an X500PrivateCredential that associates an X.509 certificate, a private key and the KeyStore alias.
X509Certificate - Class in java.security.cert
Abstract class for X.509 certificates.
X509Certificate() - Constructor for class java.security.cert.X509Certificate
Constructor for X.509 certificates.
X509Certificate - Class in javax.security.cert
Abstract class for X.509 v1 certificates.
X509Certificate() - Constructor for class javax.security.cert.X509Certificate
X509CertSelector - Class in java.security.cert
A CertSelector that selects X509Certificates that match all specified criteria.
X509CertSelector() - Constructor for class java.security.cert.X509CertSelector
Creates an X509CertSelector.
X509CRL - Class in java.security.cert
Abstract class for an X.509 Certificate Revocation List (CRL).
X509CRL() - Constructor for class java.security.cert.X509CRL
Constructor for X.509 CRLs.
X509CRLEntry - Class in java.security.cert
Abstract class for a revoked certificate in a CRL (Certificate Revocation List).
X509CRLEntry() - Constructor for class java.security.cert.X509CRLEntry
X509CRLSelector - Class in java.security.cert
A CRLSelector that selects X509CRLs that match all specified criteria.
X509CRLSelector() - Constructor for class java.security.cert.X509CRLSelector
Creates an X509CRLSelector.
X509Data - Interface in javax.xml.crypto.dsig.keyinfo
A representation of the XML X509Data element as defined in the W3C Recommendation for XML-Signature Syntax and Processing.
X509EncodedKeySpec - Class in java.security.spec
This class represents the ASN.1 encoding of a public key, encoded according to the ASN.1 type SubjectPublicKeyInfo.
X509EncodedKeySpec(byte[]) - Constructor for class java.security.spec.X509EncodedKeySpec
Creates a new X509EncodedKeySpec with the given encoded key.
X509ExtendedKeyManager - Class in javax.net.ssl
Abstract class that provides for extension of the X509KeyManager interface.
X509ExtendedKeyManager() - Constructor for class javax.net.ssl.X509ExtendedKeyManager
Constructor used by subclasses only.
X509ExtendedTrustManager - Class in javax.net.ssl
Extensions to the X509TrustManager interface to support SSL/TLS connection sensitive trust management.
X509ExtendedTrustManager() - Constructor for class javax.net.ssl.X509ExtendedTrustManager
X509Extension - Interface in java.security.cert
Interface for an X.509 extension.
X509IssuerSerial - Interface in javax.xml.crypto.dsig.keyinfo
A representation of the XML X509IssuerSerial element as defined in the W3C Recommendation for XML-Signature Syntax and Processing.
X509KeyManager - Interface in javax.net.ssl
Instances of this interface manage which X509 certificate-based key pairs are used to authenticate the local side of a secure socket.
X509TrustManager - Interface in javax.net.ssl
Instance of this interface manage which X509 certificates may be used to authenticate the remote side of a secure socket.
X_AXIS - Static variable in class javax.swing.BoxLayout
Specifies that components should be laid out left to right.
X_AXIS - Static variable in class javax.swing.text.View
Axis for format/break operations.
XA_HEURCOM - Static variable in exception javax.transaction.xa.XAException
The transaction branch has been heuristically committed.
XA_HEURHAZ - Static variable in exception javax.transaction.xa.XAException
The transaction branch may have been heuristically completed.
XA_HEURMIX - Static variable in exception javax.transaction.xa.XAException
The transaction branch has been heuristically committed and rolled back.
XA_HEURRB - Static variable in exception javax.transaction.xa.XAException
The transaction branch has been heuristically rolled back.
XA_NOMIGRATE - Static variable in exception javax.transaction.xa.XAException
Resumption must occur where the suspension occurred.
XA_OK - Static variable in interface javax.transaction.xa.XAResource
The transaction work has been prepared normally.
XA_RBBASE - Static variable in exception javax.transaction.xa.XAException
The inclusive lower bound of the rollback codes.
XA_RBCOMMFAIL - Static variable in exception javax.transaction.xa.XAException
Indicates that the rollback was caused by a communication failure.
XA_RBDEADLOCK - Static variable in exception javax.transaction.xa.XAException
A deadlock was detected.
XA_RBEND - Static variable in exception javax.transaction.xa.XAException
The inclusive upper bound of the rollback error code.
XA_RBINTEGRITY - Static variable in exception javax.transaction.xa.XAException
A condition that violates the integrity of the resource was detected.
XA_RBOTHER - Static variable in exception javax.transaction.xa.XAException
The resource manager rolled back the transaction branch for a reason not on this list.
XA_RBPROTO - Static variable in exception javax.transaction.xa.XAException
A protocol error occurred in the resource manager.
XA_RBROLLBACK - Static variable in exception javax.transaction.xa.XAException
Indicates that the rollback was caused by an unspecified reason.
XA_RBTIMEOUT - Static variable in exception javax.transaction.xa.XAException
A transaction branch took too long.
XA_RBTRANSIENT - Static variable in exception javax.transaction.xa.XAException
May retry the transaction branch.
XA_RDONLY - Static variable in exception javax.transaction.xa.XAException
The transaction branch was read-only and has been committed.
XA_RDONLY - Static variable in interface javax.transaction.xa.XAResource
The transaction branch has been read-only and has been committed.
XA_RETRY - Static variable in exception javax.transaction.xa.XAException
Routine returned with no effect and may be reissued.
XAConnection - Interface in javax.sql
An object that provides support for distributed transactions.
XADataSource - Interface in javax.sql
A factory for XAConnection objects that is used internally.
XAER_ASYNC - Static variable in exception javax.transaction.xa.XAException
There is an asynchronous operation already outstanding.
XAER_DUPID - Static variable in exception javax.transaction.xa.XAException
The XID already exists.
XAER_INVAL - Static variable in exception javax.transaction.xa.XAException
Invalid arguments were given.
XAER_NOTA - Static variable in exception javax.transaction.xa.XAException
The XID is not valid.
XAER_OUTSIDE - Static variable in exception javax.transaction.xa.XAException
The resource manager is doing work outside a global transaction.
XAER_PROTO - Static variable in exception javax.transaction.xa.XAException
Routine was invoked in an inproper context.
XAER_RMERR - Static variable in exception javax.transaction.xa.XAException
A resource manager error has occurred in the transaction branch.
XAER_RMFAIL - Static variable in exception javax.transaction.xa.XAException
Resource manager is unavailable.
XAException - Exception in javax.transaction.xa
The XAException is thrown by the Resource Manager (RM) to inform the Transaction Manager of an error encountered by the involved transaction.
XAException() - Constructor for exception javax.transaction.xa.XAException
Create an XAException.
XAException(String) - Constructor for exception javax.transaction.xa.XAException
Create an XAException with a given string.
XAException(int) - Constructor for exception javax.transaction.xa.XAException
Create an XAException with a given error code.
XAResource - Interface in javax.transaction.xa
The XAResource interface is a Java mapping of the industry standard XA interface based on the X/Open CAE Specification (Distributed Transaction Processing: The XA Specification).
Xid - Interface in javax.transaction.xa
The Xid interface is a Java mapping of the X/Open transaction identifier XID structure.
XML_DTD_NS_URI - Static variable in class javax.xml.XMLConstants
XML Document Type Declaration Namespace URI as an arbitrary value.
XML_NS_PREFIX - Static variable in class javax.xml.XMLConstants
The official XML Namespace prefix.
XML_NS_URI - Static variable in class javax.xml.XMLConstants
The official XML Namespace name URI.
XmlAccessOrder - Enum in javax.xml.bind.annotation
Used by XmlAccessorOrder to control the ordering of properties and fields in a JAXB bound class.
XmlAccessorOrder - Annotation Type in javax.xml.bind.annotation
Controls the ordering of fields and properties in a class.
XmlAccessorType - Annotation Type in javax.xml.bind.annotation
Controls whether fields or Javabean properties are serialized by default.
XmlAccessType - Enum in javax.xml.bind.annotation
Used by XmlAccessorType to control serialization of fields or properties.
XmlAdapter<ValueType,BoundType> - Class in javax.xml.bind.annotation.adapters
Adapts a Java type for custom marshaling.
XmlAdapter() - Constructor for class javax.xml.bind.annotation.adapters.XmlAdapter
Do-nothing constructor for the derived classes.
XmlAnyAttribute - Annotation Type in javax.xml.bind.annotation
Maps a JavaBean property to a map of wildcard attributes.
XmlAnyElement - Annotation Type in javax.xml.bind.annotation
Maps a JavaBean property to XML infoset representation and/or JAXB element.
XmlAttachmentRef - Annotation Type in javax.xml.bind.annotation
Marks a field/property that its XML form is a uri reference to mime content.
XmlAttribute - Annotation Type in javax.xml.bind.annotation
Maps a JavaBean property to a XML attribute.
XMLConstants - Class in javax.xml
Utility class to contain basic XML values as constants.
XMLCryptoContext - Interface in javax.xml.crypto
Contains common context information for XML cryptographic operations.
XMLDecoder - Class in java.beans
The XMLDecoder class is used to read XML documents created using the XMLEncoder and is used just like the ObjectInputStream.
XMLDecoder(InputStream) - Constructor for class java.beans.XMLDecoder
Creates a new input stream for reading archives created by the XMLEncoder class.
XMLDecoder(InputStream, Object) - Constructor for class java.beans.XMLDecoder
Creates a new input stream for reading archives created by the XMLEncoder class.
XMLDecoder(InputStream, Object, ExceptionListener) - Constructor for class java.beans.XMLDecoder
Creates a new input stream for reading archives created by the XMLEncoder class.
XMLDecoder(InputStream, Object, ExceptionListener, ClassLoader) - Constructor for class java.beans.XMLDecoder
Creates a new input stream for reading archives created by the XMLEncoder class.
XMLDecoder(InputSource) - Constructor for class java.beans.XMLDecoder
Creates a new decoder to parse XML archives created by the XMLEncoder class.
XmlElement - Annotation Type in javax.xml.bind.annotation
Maps a JavaBean property to a XML element derived from property name.
XmlElement.DEFAULT - Class in javax.xml.bind.annotation
Used in XmlElement.type() to signal that the type be inferred from the signature of the property.
XmlElement.DEFAULT() - Constructor for class javax.xml.bind.annotation.XmlElement.DEFAULT
XmlElementDecl - Annotation Type in javax.xml.bind.annotation
Maps a factory method to a XML element.
XmlElementDecl.GLOBAL - Class in javax.xml.bind.annotation
Used in XmlElementDecl.scope() to signal that the declaration is in the global scope.
XmlElementDecl.GLOBAL() - Constructor for class javax.xml.bind.annotation.XmlElementDecl.GLOBAL
XmlElementRef - Annotation Type in javax.xml.bind.annotation
Maps a JavaBean property to a XML element derived from property's type.
XmlElementRef.DEFAULT - Class in javax.xml.bind.annotation
Used in XmlElementRef.type() to signal that the type be inferred from the signature of the property.
XmlElementRef.DEFAULT() - Constructor for class javax.xml.bind.annotation.XmlElementRef.DEFAULT
XmlElementRefs - Annotation Type in javax.xml.bind.annotation
Marks a property that refers to classes with XmlElement or JAXBElement.
XmlElements - Annotation Type in javax.xml.bind.annotation
A container for multiple @XmlElement annotations.
XmlElementWrapper - Annotation Type in javax.xml.bind.annotation
Generates a wrapper element around XML representation.
XMLEncoder - Class in java.beans
The XMLEncoder class is a complementary alternative to the ObjectOutputStream and can used to generate a textual representation of a JavaBean in the same way that the ObjectOutputStream can be used to create binary representation of Serializable objects.
XMLEncoder(OutputStream) - Constructor for class java.beans.XMLEncoder
Creates a new XML encoder to write out JavaBeans to the stream out using an XML encoding.
XMLEncoder(OutputStream, String, boolean, int) - Constructor for class java.beans.XMLEncoder
Creates a new XML encoder to write out JavaBeans to the stream out using the given charset starting from the given indentation.
XmlEnum - Annotation Type in javax.xml.bind.annotation
Maps an enum type Enum to XML representation.
XmlEnumValue - Annotation Type in javax.xml.bind.annotation
Maps an enum constant in Enum type to XML representation.
XMLEvent - Interface in javax.xml.stream.events
This is the base event interface for handling markup events.
XMLEventAllocator - Interface in javax.xml.stream.util
This interface defines a class that allows a user to register a way to allocate events given an XMLStreamReader.
XMLEventConsumer - Interface in javax.xml.stream.util
This interface defines an event consumer interface.
XMLEventFactory - Class in javax.xml.stream
This interface defines a utility class for creating instances of XMLEvents
XMLEventFactory() - Constructor for class javax.xml.stream.XMLEventFactory
XMLEventReader - Interface in javax.xml.stream
This is the top level interface for parsing XML Events.
XMLEventWriter - Interface in javax.xml.stream
This is the top level interface for writing XML documents.
XMLFilter - Interface in org.xml.sax
Interface for an XML filter.
XMLFilterImpl - Class in org.xml.sax.helpers
Base class for deriving an XML filter.
XMLFilterImpl() - Constructor for class org.xml.sax.helpers.XMLFilterImpl
Construct an empty XML filter, with no parent.
XMLFilterImpl(XMLReader) - Constructor for class org.xml.sax.helpers.XMLFilterImpl
Construct an XML filter with the specified parent.
XMLFormatter - Class in java.util.logging
Format a LogRecord into a standard XML format.
XMLFormatter() - Constructor for class java.util.logging.XMLFormatter
XMLGregorianCalendar - Class in javax.xml.datatype
Representation for W3C XML Schema 1.0 date/time datatypes.
XMLGregorianCalendar() - Constructor for class javax.xml.datatype.XMLGregorianCalendar
Default no-arg constructor.
XmlID - Annotation Type in javax.xml.bind.annotation
Maps a JavaBean property to XML ID.
XmlIDREF - Annotation Type in javax.xml.bind.annotation
Maps a JavaBean property to XML IDREF.
XmlInlineBinaryData - Annotation Type in javax.xml.bind.annotation
Disable consideration of XOP encoding for datatypes that are bound to base64-encoded binary data in XML.
XMLInputFactory - Class in javax.xml.stream
Defines an abstract implementation of a factory for getting streams.
XMLInputFactory() - Constructor for class javax.xml.stream.XMLInputFactory
XmlJavaTypeAdapter - Annotation Type in javax.xml.bind.annotation.adapters
Use an adapter that implements XmlAdapter for custom marshaling.
XmlJavaTypeAdapter.DEFAULT - Class in javax.xml.bind.annotation.adapters
Used in XmlJavaTypeAdapter.type() to signal that the type be inferred from the signature of the field, property, parameter or the class.
XmlJavaTypeAdapter.DEFAULT() - Constructor for class javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter.DEFAULT
XmlJavaTypeAdapters - Annotation Type in javax.xml.bind.annotation.adapters
A container for multiple @XmlJavaTypeAdapter annotations.
XmlList - Annotation Type in javax.xml.bind.annotation
Used to map a property to a list simple type.
XmlMimeType - Annotation Type in javax.xml.bind.annotation
Associates the MIME type that controls the XML representation of the property.
XmlMixed - Annotation Type in javax.xml.bind.annotation
Annotate a JavaBean multi-valued property to support mixed content.
XmlNs - Annotation Type in javax.xml.bind.annotation
Associates a namespace prefix with a XML namespace URI.
XMLNS - Static variable in interface javax.xml.crypto.dsig.XMLSignature
The XML Namespace URI of the W3C Recommendation for XML-Signature Syntax and Processing.
XMLNS - Static variable in class org.xml.sax.helpers.NamespaceSupport
The XML Namespace URI as a constant.
XMLNS_ATTRIBUTE - Static variable in class javax.xml.XMLConstants
The official XML attribute used for specifying XML Namespace declarations.
XMLNS_ATTRIBUTE_NS_URI - Static variable in class javax.xml.XMLConstants
The official XML attribute used for specifying XML Namespace declarations, XMLConstants.XMLNS_ATTRIBUTE, Namespace name URI.
XmlNsForm - Enum in javax.xml.bind.annotation
Enumeration of XML Schema namespace qualifications.
XMLObject - Interface in javax.xml.crypto.dsig
A representation of the XML Object element as defined in the W3C Recommendation for XML-Signature Syntax and Processing.
XMLOutputFactory - Class in javax.xml.stream
Defines an abstract implementation of a factory for getting XMLEventWriters and XMLStreamWriters.
XMLOutputFactory() - Constructor for class javax.xml.stream.XMLOutputFactory
XMLParseException - Exception in javax.management.modelmbean
This exception is thrown when an XML formatted string is being parsed into ModelMBean objects or when XML formatted strings are being created from ModelMBean objects.
XMLParseException() - Constructor for exception javax.management.modelmbean.XMLParseException
Default constructor .
XMLParseException(String) - Constructor for exception javax.management.modelmbean.XMLParseException
Constructor taking a string.
XMLParseException(Exception, String) - Constructor for exception javax.management.modelmbean.XMLParseException
Constructor taking a string and an exception.
XmlReader - Interface in javax.sql.rowset.spi
A specialized interface that facilitates an extension of the SyncProvider abstract class for XML orientated synchronization providers.
XMLReader - Interface in org.xml.sax
Interface for reading an XML document using callbacks.
XMLReaderAdapter - Class in org.xml.sax.helpers
Adapt a SAX2 XMLReader as a SAX1 Parser.
XMLReaderAdapter() - Constructor for class org.xml.sax.helpers.XMLReaderAdapter
Create a new adapter.
XMLReaderAdapter(XMLReader) - Constructor for class org.xml.sax.helpers.XMLReaderAdapter
Create a new adapter.
XMLReaderFactory - Class in org.xml.sax.helpers
Factory for creating an XML reader.
XmlRegistry - Annotation Type in javax.xml.bind.annotation
Marks a class that has XmlElementDecls.
XMLReporter - Interface in javax.xml.stream
This interface is used to report non-fatal errors.
XMLResolver - Interface in javax.xml.stream
This interface is used to resolve resources during an XML parse.
XmlRootElement - Annotation Type in javax.xml.bind.annotation
Maps a class or an enum type to an XML element.
XmlSchema - Annotation Type in javax.xml.bind.annotation
Maps a package name to a XML namespace.
XmlSchemaType - Annotation Type in javax.xml.bind.annotation
Maps a Java type to a simple schema built-in type.
XmlSchemaType.DEFAULT - Class in javax.xml.bind.annotation
Used in XmlSchemaType.type() to signal that the type be inferred from the signature of the property.
XmlSchemaType.DEFAULT() - Constructor for class javax.xml.bind.annotation.XmlSchemaType.DEFAULT
XmlSchemaTypes - Annotation Type in javax.xml.bind.annotation
A container for multiple @XmlSchemaType annotations.
XmlSeeAlso - Annotation Type in javax.xml.bind.annotation
Instructs JAXB to also bind other classes when binding this class.
XMLSignature - Interface in javax.xml.crypto.dsig
A representation of the XML Signature element as defined in the W3C Recommendation for XML-Signature Syntax and Processing.
XMLSignature.SignatureValue - Interface in javax.xml.crypto.dsig
A representation of the XML SignatureValue element as defined in the W3C Recommendation for XML-Signature Syntax and Processing.
XMLSignatureException - Exception in javax.xml.crypto.dsig
Indicates an exceptional condition that occured during the XML signature generation or validation process.
XMLSignatureException() - Constructor for exception javax.xml.crypto.dsig.XMLSignatureException
Constructs a new XMLSignatureException with null as its detail message.
XMLSignatureException(String) - Constructor for exception javax.xml.crypto.dsig.XMLSignatureException
Constructs a new XMLSignatureException with the specified detail message.
XMLSignatureException(String, Throwable) - Constructor for exception javax.xml.crypto.dsig.XMLSignatureException
Constructs a new XMLSignatureException with the specified detail message and cause.
XMLSignatureException(Throwable) - Constructor for exception javax.xml.crypto.dsig.XMLSignatureException
Constructs a new XMLSignatureException with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).
XMLSignatureFactory - Class in javax.xml.crypto.dsig
A factory for creating XMLSignature objects from scratch or for unmarshalling an XMLSignature object from a corresponding XML representation.
XMLSignatureFactory() - Constructor for class javax.xml.crypto.dsig.XMLSignatureFactory
Default constructor, for invocation by subclasses.
XMLSignContext - Interface in javax.xml.crypto.dsig
Contains context information for generating XML Signatures.
XMLStreamConstants - Interface in javax.xml.stream
This interface declares the constants used in this API.
XMLStreamException - Exception in javax.xml.stream
The base exception for unexpected processing errors.
XMLStreamException() - Constructor for exception javax.xml.stream.XMLStreamException
Default constructor
XMLStreamException(String) - Constructor for exception javax.xml.stream.XMLStreamException
Construct an exception with the assocated message.
XMLStreamException(Throwable) - Constructor for exception javax.xml.stream.XMLStreamException
Construct an exception with the assocated exception
XMLStreamException(String, Throwable) - Constructor for exception javax.xml.stream.XMLStreamException
Construct an exception with the assocated message and exception
XMLStreamException(String, Location, Throwable) - Constructor for exception javax.xml.stream.XMLStreamException
Construct an exception with the assocated message, exception and location.
XMLStreamException(String, Location) - Constructor for exception javax.xml.stream.XMLStreamException
Construct an exception with the assocated message, exception and location.
XMLStreamReader - Interface in javax.xml.stream
The XMLStreamReader interface allows forward, read-only access to XML.
XMLStreamWriter - Interface in javax.xml.stream
The XMLStreamWriter interface specifies how to write XML.
XMLStructure - Interface in javax.xml.crypto
A representation of an XML structure from any namespace.
XmlTransient - Annotation Type in javax.xml.bind.annotation
Prevents the mapping of a JavaBean property/type to XML representation.
XmlType - Annotation Type in javax.xml.bind.annotation
Maps a class or an enum type to a XML Schema type.
XmlType.DEFAULT - Class in javax.xml.bind.annotation
Used in XmlType.factoryClass() to signal that either factory mehod is not used or that it's in the class with this XmlType itself.
XmlType.DEFAULT() - Constructor for class javax.xml.bind.annotation.XmlType.DEFAULT
XMLValidateContext - Interface in javax.xml.crypto.dsig
Contains context information for validating XML Signatures.
XmlValue - Annotation Type in javax.xml.bind.annotation
Enables mapping a class to a XML Schema complex type with a simpleContent or a XML Schema simple type.
XmlWriter - Interface in javax.sql.rowset.spi
A specialized interface that facilitates an extension of the SyncProvider abstract class for XML orientated synchronization providers.
XOR - Static variable in class java.awt.AlphaComposite
The part of the source that lies outside of the destination is combined with the part of the destination that lies outside of the source (Porter-Duff Source Xor Destination rule).
Xor - Static variable in class java.awt.AlphaComposite
AlphaComposite object that implements the opaque XOR rule with an alpha of 1.0f.
xor(BigInteger) - Method in class java.math.BigInteger
Returns a BigInteger whose value is (this ^ val).
xor(BitSet) - Method in class java.util.BitSet
Performs a logical XOR of this bit set with the bit set argument.
XPATH - Static variable in interface javax.xml.crypto.dsig.Transform
The XPath transform algorithm URI.
XPath - Interface in javax.xml.xpath
XPath provides access to the XPath evaluation environment and expressions.
XPATH2 - Static variable in interface javax.xml.crypto.dsig.Transform
The XPath Filter 2 transform algorithm URI.
XPathConstants - Class in javax.xml.xpath
XPath constants.
XPathException - Exception in javax.xml.xpath
XPathException represents a generic XPath exception.
XPathException(String) - Constructor for exception javax.xml.xpath.XPathException
Constructs a new XPathException with the specified detail message.
XPathException(Throwable) - Constructor for exception javax.xml.xpath.XPathException
Constructs a new XPathException with the specified cause.
XPathExpression - Interface in javax.xml.xpath
XPathExpression provides access to compiled XPath expressions.
XPathExpressionException - Exception in javax.xml.xpath
XPathExpressionException represents an error in an XPath expression.
XPathExpressionException(String) - Constructor for exception javax.xml.xpath.XPathExpressionException
Constructs a new XPathExpressionException with the specified detail message.
XPathExpressionException(Throwable) - Constructor for exception javax.xml.xpath.XPathExpressionException
Constructs a new XPathExpressionException with the specified cause.
XPathFactory - Class in javax.xml.xpath
An XPathFactory instance can be used to create XPath objects.
XPathFactory() - Constructor for class javax.xml.xpath.XPathFactory
Protected constructor as XPathFactory.newInstance() or XPathFactory.newInstance(String uri) or XPathFactory.newInstance(String uri, String factoryClassName, ClassLoader classLoader) should be used to create a new instance of an XPathFactory.
XPathFactoryConfigurationException - Exception in javax.xml.xpath
XPathFactoryConfigurationException represents a configuration error in a XPathFactory environment.
XPathFactoryConfigurationException(String) - Constructor for exception javax.xml.xpath.XPathFactoryConfigurationException
Constructs a new XPathFactoryConfigurationException with the specified detail message.
XPathFactoryConfigurationException(Throwable) - Constructor for exception javax.xml.xpath.XPathFactoryConfigurationException
Constructs a new XPathFactoryConfigurationException with the specified cause.
XPathFilter2ParameterSpec - Class in javax.xml.crypto.dsig.spec
Parameters for the W3C Recommendation XPath Filter 2.0 Transform Algorithm.
XPathFilter2ParameterSpec(List) - Constructor for class javax.xml.crypto.dsig.spec.XPathFilter2ParameterSpec
Creates an XPathFilter2ParameterSpec.
XPathFilterParameterSpec - Class in javax.xml.crypto.dsig.spec
Parameters for the XPath Filtering Transform Algorithm.
XPathFilterParameterSpec(String) - Constructor for class javax.xml.crypto.dsig.spec.XPathFilterParameterSpec
Creates an XPathFilterParameterSpec with the specified XPath expression.
XPathFilterParameterSpec(String, Map) - Constructor for class javax.xml.crypto.dsig.spec.XPathFilterParameterSpec
Creates an XPathFilterParameterSpec with the specified XPath expression and namespace map.
XPathFunction - Interface in javax.xml.xpath
XPathFunction provides access to XPath functions.
XPathFunctionException - Exception in javax.xml.xpath
XPathFunctionException represents an error with an XPath function.
XPathFunctionException(String) - Constructor for exception javax.xml.xpath.XPathFunctionException
Constructs a new XPathFunctionException with the specified detail message.
XPathFunctionException(Throwable) - Constructor for exception javax.xml.xpath.XPathFunctionException
Constructs a new XPathFunctionException with the specified cause.
XPathFunctionResolver - Interface in javax.xml.xpath
XPathFunctionResolver provides access to the set of user defined XPathFunctions.
XPathType - Class in javax.xml.crypto.dsig.spec
The XML Schema Definition of the XPath element as defined in the W3C Recommendation for XML-Signature XPath Filter 2.0:
XPathType(String, XPathType.Filter) - Constructor for class javax.xml.crypto.dsig.spec.XPathType
Creates an XPathType instance with the specified XPath expression and filter.
XPathType(String, XPathType.Filter, Map) - Constructor for class javax.xml.crypto.dsig.spec.XPathType
Creates an XPathType instance with the specified XPath expression, filter, and namespace map.
XPathType.Filter - Class in javax.xml.crypto.dsig.spec
Represents the filter set operation.
XPathVariableResolver - Interface in javax.xml.xpath
XPathVariableResolver provides access to the set of user defined XPath variables.
xpoints - Variable in class java.awt.Polygon
The array of X coordinates.
xPositionForValue(int) - Method in class javax.swing.plaf.basic.BasicSliderUI
xPositionForValue(int) - Method in class javax.swing.plaf.synth.SynthSliderUI
XSLT - Static variable in interface javax.xml.crypto.dsig.Transform
The XSLT transform algorithm URI.
XSLTTransformParameterSpec - Class in javax.xml.crypto.dsig.spec
Parameters for the XSLT Transform Algorithm.
XSLTTransformParameterSpec(XMLStructure) - Constructor for class javax.xml.crypto.dsig.spec.XSLTTransformParameterSpec
Creates an XSLTTransformParameterSpec with the specified stylesheet.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类

提交错误或意见
有关更多的 API 参考资料和开发人员文档，请参阅 Java SE 开发人员文档. 该文档包含更详细的、面向开发人员的描述，以及总体概述、术语定义、使用技巧和工作代码示例。
版权所有 © 1993, 2011, Oracle 及其联盟会员。保留所有权利。
草案 ea-b138

dish i/ooou


Y-Index

请注意：本 java api 1.7Beta 规范不是最终稳定版，未来随着版本的更迭，本规范可能有更新。
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _

Y

y - Variable in class java.awt.Event
The y coordinate of the event.
y - Variable in class java.awt.geom.Arc2D.Double
The Y coordinate of the upper-left corner of the framing rectangle of the arc.
y - Variable in class java.awt.geom.Arc2D.Float
The Y coordinate of the upper-left corner of the framing rectangle of the arc.
y - Variable in class java.awt.geom.Ellipse2D.Double
The Y coordinate of the upper-left corner of the framing rectangle of this Ellipse2D.
y - Variable in class java.awt.geom.Ellipse2D.Float
The Y coordinate of the upper-left corner of the framing rectangle of this Ellipse2D.
y - Variable in class java.awt.geom.Point2D.Double
The Y coordinate of this Point2D.
y - Variable in class java.awt.geom.Point2D.Float
The Y coordinate of this Point2D.
y - Variable in class java.awt.geom.Rectangle2D.Double
The Y coordinate of this Rectangle2D.
y - Variable in class java.awt.geom.Rectangle2D.Float
The Y coordinate of this Rectangle2D.
y - Variable in class java.awt.geom.RoundRectangle2D.Double
The Y coordinate of this RoundRectangle2D.
y - Variable in class java.awt.geom.RoundRectangle2D.Float
The Y coordinate of this RoundRectangle2D.
y - Variable in class java.awt.Point
The Y coordinate of this Point.
y - Variable in class java.awt.Rectangle
The Y coordinate of the upper-left corner of the Rectangle.
y1 - Variable in class java.awt.geom.CubicCurve2D.Double
The Y coordinate of the start point of the cubic curve segment.
y1 - Variable in class java.awt.geom.CubicCurve2D.Float
The Y coordinate of the start point of the cubic curve segment.
y1 - Variable in class java.awt.geom.Line2D.Double
The Y coordinate of the start point of the line segment.
y1 - Variable in class java.awt.geom.Line2D.Float
The Y coordinate of the start point of the line segment.
y1 - Variable in class java.awt.geom.QuadCurve2D.Double
The Y coordinate of the start point of the quadratic curve segment.
y1 - Variable in class java.awt.geom.QuadCurve2D.Float
The Y coordinate of the start point of the quadratic curve segment.
y2 - Variable in class java.awt.geom.CubicCurve2D.Double
The Y coordinate of the end point of the cubic curve segment.
y2 - Variable in class java.awt.geom.CubicCurve2D.Float
The Y coordinate of the end point of the cubic curve segment.
y2 - Variable in class java.awt.geom.Line2D.Double
The Y coordinate of the end point of the line segment.
y2 - Variable in class java.awt.geom.Line2D.Float
The Y coordinate of the end point of the line segment.
y2 - Variable in class java.awt.geom.QuadCurve2D.Double
The Y coordinate of the end point of the quadratic curve segment.
y2 - Variable in class java.awt.geom.QuadCurve2D.Float
The Y coordinate of the end point of the quadratic curve segment.
Y_AXIS - Static variable in class javax.swing.BoxLayout
Specifies that components should be laid out top to bottom.
Y_AXIS - Static variable in class javax.swing.text.View
Axis for format/break operations.
YEAR - Static variable in class java.text.DateFormat.Field
Constant identifying the year field.
YEAR - Static variable in class java.util.Calendar
Field number for get and set indicating the year.
YEAR_FIELD - Static variable in class java.text.DateFormat
Useful constant for YEAR field alignment.
YEARS - Static variable in class javax.xml.datatype.DatatypeConstants
A constant that represents the years field.
yellow - Static variable in class java.awt.Color
The color yellow.
YELLOW - Static variable in class java.awt.Color
The color yellow.
YES - Static variable in class javax.security.auth.callback.ConfirmationCallback
YES option.
YES_NO_CANCEL_OPTION - Static variable in class javax.security.auth.callback.ConfirmationCallback
YES/NO/CANCEL confirmation confirmation option.
YES_NO_CANCEL_OPTION - Static variable in class javax.swing.JOptionPane
Type used for showConfirmDialog.
YES_NO_OPTION - Static variable in class javax.security.auth.callback.ConfirmationCallback
YES/NO confirmation option.
YES_NO_OPTION - Static variable in class javax.swing.JOptionPane
Type used for showConfirmDialog.
YES_OPTION - Static variable in class javax.swing.JOptionPane
Return value from class method if YES is chosen.
YI_RADICALS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Yi Radicals" Unicode character block.
YI_SYLLABLES - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Yi Syllables" Unicode character block.
yield() - Static method in class java.lang.Thread
A hint to the scheduler that the current thread is willing to yield its current use of a processor.
YIJING_HEXAGRAM_SYMBOLS - Static variable in class java.lang.Character.UnicodeBlock
Constant for the "Yijing Hexagram Symbols" Unicode character block.
YOU_1 - Static variable in class javax.print.attribute.standard.MediaSize.JIS
Specifies the JIS You ("Western") #1 envelope size, 120 mm by 176 mm.
YOU_2 - Static variable in class javax.print.attribute.standard.MediaSize.JIS
Specifies the JIS You ("Western") #2 envelope size, 114 mm by 162 mm.
YOU_3 - Static variable in class javax.print.attribute.standard.MediaSize.JIS
Specifies the JIS You ("Western") #3 envelope size, 98 mm by 148 mm.
YOU_4 - Static variable in class javax.print.attribute.standard.MediaSize.JIS
Specifies the JIS You ("Western") #4 envelope size, 105 mm by 235 mm.
YOU_5 - Static variable in class javax.print.attribute.standard.MediaSize.JIS
Specifies the JIS You ("Western") #5 envelope size, 95 mm by 217 mm.
YOU_6 - Static variable in class javax.print.attribute.standard.MediaSize.JIS
Specifies the JIS You ("Western") #6 envelope size, 98 mm by 190 mm.
YOU_7 - Static variable in class javax.print.attribute.standard.MediaSize.JIS
Specifies the JIS You ("Western") #7 envelope size, 92 mm by 165 mm.
ypoints - Variable in class java.awt.Polygon
The array of Y coordinates.
yPositionForValue(int) - Method in class javax.swing.plaf.basic.BasicSliderUI
yPositionForValue(int, int, int) - Method in class javax.swing.plaf.basic.BasicSliderUI
Returns the y location for the specified value.
yPositionForValue(int, int, int) - Method in class javax.swing.plaf.synth.SynthSliderUI
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类

提交错误或意见
有关更多的 API 参考资料和开发人员文档，请参阅 Java SE 开发人员文档. 该文档包含更详细的、面向开发人员的描述，以及总体概述、术语定义、使用技巧和工作代码示例。
版权所有 © 1993, 2011, Oracle 及其联盟会员。保留所有权利。
草案 ea-b138

xraaax.///f"llstaTe


Z-Index

请注意：本 java api 1.7Beta 规范不是最终稳定版，未来随着版本的更迭，本规范可能有更新。
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _

Z

ZERO - Static variable in class java.math.BigDecimal
The value 0, with a scale of 0.
ZERO - Static variable in class java.math.BigInteger
The BigInteger constant zero.
ZipEntry - Class in java.util.zip
This class is used to represent a ZIP file entry.
ZipEntry(String) - Constructor for class java.util.zip.ZipEntry
Creates a new zip entry with the specified name.
ZipEntry(ZipEntry) - Constructor for class java.util.zip.ZipEntry
Creates a new zip entry with fields taken from the specified zip entry.
ZipError - Error in java.util.zip
Signals that an unrecoverable error has occurred.
ZipError(String) - Constructor for error java.util.zip.ZipError
Constructs a ZipError with the given detail message.
ZipException - Exception in java.util.zip
Signals that a Zip exception of some sort has occurred.
ZipException() - Constructor for exception java.util.zip.ZipException
Constructs a ZipException with null as its error detail message.
ZipException(String) - Constructor for exception java.util.zip.ZipException
Constructs a ZipException with the specified detail message.
ZipFile - Class in java.util.zip
This class is used to read entries from a zip file.
ZipFile(String) - Constructor for class java.util.zip.ZipFile
Opens a zip file for reading.
ZipFile(File, int) - Constructor for class java.util.zip.ZipFile
Opens a new ZipFile to read from the specified File object in the specified mode.
ZipFile(File) - Constructor for class java.util.zip.ZipFile
Opens a ZIP file for reading given the specified File object.
ZipFile(File, int, Charset) - Constructor for class java.util.zip.ZipFile
Opens a new ZipFile to read from the specified File object in the specified mode.
ZipFile(String, Charset) - Constructor for class java.util.zip.ZipFile
Opens a zip file for reading.
ZipFile(File, Charset) - Constructor for class java.util.zip.ZipFile
Opens a ZIP file for reading given the specified File object.
ZipInputStream - Class in java.util.zip
This class implements an input stream filter for reading files in the ZIP file format.
ZipInputStream(InputStream) - Constructor for class java.util.zip.ZipInputStream
Creates a new ZIP input stream.
ZipInputStream(InputStream, Charset) - Constructor for class java.util.zip.ZipInputStream
Creates a new ZIP input stream.
ZipOutputStream - Class in java.util.zip
This class implements an output stream filter for writing files in the ZIP file format.
ZipOutputStream(OutputStream) - Constructor for class java.util.zip.ZipOutputStream
Creates a new ZIP output stream.
ZipOutputStream(OutputStream, Charset) - Constructor for class java.util.zip.ZipOutputStream
Creates a new ZIP output stream.
ZONE_OFFSET - Static variable in class java.util.Calendar
Field number for get and set indicating the raw offset from GMT in milliseconds.
ZoneView - Class in javax.swing.text
ZoneView is a View implementation that creates zones for which the child views are not created or stored until they are needed for display or model/view translations.
ZoneView(Element, int) - Constructor for class javax.swing.text.ZoneView
Constructs a ZoneView.
zoneWasLoaded(View) - Method in class javax.swing.text.ZoneView
Called by a zone when it gets loaded.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _
  • 概述
  • 软件包
  • 类
  • 使用
  • 树
  • 已过时
  • Index
  • 帮助
Java™ Platform
Standard Ed. 7
草案 ea-b138
  • Prev Letter
  • Next Letter
  • 框架
  • 无框架
  • 所有的类

提交错误或意见
有关更多的 API 参考资料和开发人员文档，请参阅 Java SE 开发人员文档. 该文档包含更详细的、面向开发人员的描述，以及总体概述、术语定义、使用技巧和工作代码示例。
版权所有 © 1993, 2011, Oracle 及其联盟会员。保留所有权利。
草案 ea-b138

Olpa./rfffa. /wna/


New Features in Java 2D(TM) Technology

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

New Java 2D™ Features in Java™ 2 SDK, v1.4

New Pipeline Architecture | Hardware Acceleration for Offscreen Images
Pluggable Image I/O Framework | New Java Print Service API
Support for additional Image Types | Public Bidi Algorithm
Font Rasterizer support for TrueType hinting | Hinted Lucida Fonts
OpenType Font Table Support | Support for Numeric Shaping
Improved Complex Text Layout Support | Complete Porter-Duff Support
Support for Checking if Font has a Transform | New Equality Methods for FontRenderContext

New Pipeline Architecture

The bugtraq reports that correspond to this change are: 4228939 and 4268962

In the Java 2 SDK, version 1.2 and 1.3, common operations on a Graphics object often invalidated the rendering data cached for this Graphics object. This invalidation interrupted the rendering process by causing continuous re-creation of rendering information for the Graphics object, even for such simple and benign operations as create(), setColor(), and translate(). Because the rendering of Swing hierarchies relies heavily on these common operations, the invalidation and re-creation of rendering data caused poor repaint performance for many Swing applications.

The new pipeline architecture reduces this performance overhead with several implementation changes that:

  • Improve the way that data is shared by the various rendering pipelines.
  • Reduce the amount of code executed and garbage created when responding to changes in the rendering attributes.
  • Improve the way that various graphics routines are chosen such as the routines that copy pixels from one format and location to another.
These changes are especially noticeable when the following calls are used frequently, as they are in Swing applications:
  • getGraphics, Graphics.create() and Graphics.dispose()
  • Graphics.setColor(), Graphics.translate
  • Graphics.copyArea, especially when the source and destination regions overlap.
The runtime footprint should also be improved through better code sharing.

Other changes in the pipeline architecture have greatly improved the performance of:

  • draw(Shape) and fill(Shape), especially when the Shape is a GeneralPath
  • scaled drawImage.
  • Blitting from an offscreen image created with createImage() multiple times without any intervening rendering or modifications to that image
  • Remote X11 display over the network of applications that use createImage() to create an image buffer for double buffering.
  • Rendering non-opaque text.
  • Systems, such as the SGI Visual 320 workstation, which have display cards that use an RGBx format for pixel storage.
  • Rendering coordinates outside of the range -32768 to 32767 with antialiasing turned off.
For more information on this feature, see the whitepaper, High Performance Graphics.

Hardware Acceleration for Offscreen Images

The bugtraq report that corresponds to this change is: 4330166

The SDK 1.4 provides access to hardware acceleration for offscreen images, resulting in better performance of rendering to and copying from these images. One problem with hardware-accelerated images is that, on some platforms such as Microsoft Windows, their contents can be lost at any time due to circumstances beyond the application's control. The new VolatileImage class allows you to create a hardware-accelerated offscreen image and manage the contents of that image.

This new API includes:

  • java.awt.image.VolatileImage:
    This class represents an image whose content can be lost at any time, but provides performance benefits. For example, on Microsoft Windows this image can be stored in VRAM and can benefit from hardware acceleration. The class includes methods that you can call to find out if the contents of the image need to be restored.
  • createVolatileImage(w,h) in Component.
    This method creates a VolatileImage that is compatible with the Component.
  • createCompatibleVolatileImage(int width, int height)
    This method creates a VolatileImage that is compatible with the GraphicsConfiguration.
  • GraphicsDevice.getAvailableAcceleratedMemory
    This method returns the number of bytes of available accelerated memory.

For more information on using the VolatileImage class, see The VolatileImage API User Guide

Pluggable Image I/O Framework

The bugtraq report that corresponds to this change is: 4101949

The JavaTM Image I/O API is an pluggable, extensible framework that supports reading and writing images of various formats and protocols. The API provides this support through plug-ins, most of which will be written by third parties. A conforming implementation will only be required to provide a minimal set of plug-ins, principally for compatibility with previous versions of the Java SDK. An application using this API should be able to read and write images without knowing the image's storage format or the plug-in used to support the format.

Fundamentally, all image I/O operations consist of reading or writing streams that contain one or more images, one or more preview (thumbnail) images associated with each image, and metadata, which is everything other than pixel data.

The Java Image I/O API allows applications to:

  • Auto-detect installed plug-ins
  • Choose plug-ins based on format name, file suffix, file contents, or MIME type
  • Access individual images in multi-image files
  • Monitor reading and writing progress
  • Provide progressive updates of images being loaded
  • Read or write only a region of interest of an image
  • Read only selected bands of an image
  • Choose the output size of resolution-independent imagery
  • Retrieve detailed image and stream metadata
  • Work with unknown formats using generic interfaces
  • Work efficiently with both random-access and streaming data sources
  • Transcode between different formats

See Java Image I/O for more information on the Java Image I/O API.

New JavaTM Print Service

The bugtraq reports that corresponds to this change are:
4285177 and 4360752

This API is the product of JSR006, Unified Printing API, and will allow client applications to provide rich access to the capablities of print services available including:

  • Printer browsing and selection
  • Discovery of the capablities of printers
  • Selection of printers for a printer job
  • Specification of a printer job.
Since all capabilities will be exposed through the API, server applications become first class citizens of this API.

Server applications can be beneficiaries of the capabilities for spooling documents to print services, whereas previously only graphics calls could be used to generate printer jobs from Java applications.

See Java Print Service for more information.

Support for float and double Image Types

The bugtraq report that corresponds to this change is: 4364491

Prior to the SDK 1.4, the Java 2D API did not have DataBuffer subclasses for float or double sample types. The Java Image I/O API needs these classes to read and write float and double image types.

The SDK 1.4 contains two new classes to provide float and double image type support: DataBufferFloat and DataBufferDouble. The DataBufferFloat class wraps float arrays of pixels. The DataBufferDouble class wraps double arrays of pixels.

The existing ComponentColorModel and ComponentSampleModel class implementations have also been updated to support signed short,float, and double data. These classes include definitions of the normalized ranges of component values for the newly-supported data types:

  • For the existing data types, the range remains 0.0 to 1.0.
  • For short data, the values are scaled to between -1.0 and 1.0.
  • For float data, the range is the full range of the float primitive type.
  • For double data, the range is also the range of the float primitive type, since values must be cast to float to interact with the ColorSpace class.
The ComponentColorModel class will not clamp the pixel data. Applications are expected to scale to the appropriate range. Methods are added to the ColorSpace class to determine per component minimum and maximum normalized values. Alpha component values must still range from 0.0 to 1.0 normalized.

The complete additional API is listed below.

java.awt.image.ColorModel includes three new methods to parallel existing methods:

  • getDataElement(float[] normComponents, int normOffset)
  • getDataElements(float[] normComponents, int normOffset, Object obj)
  • getNormalizedComponents(Object pixel, float[] normComponents, int normOffset)
java.awt.image.ComponentColorModel includes a new constructor based on the new datatypes and new methods to override the existing ColorModel methods:
  • ComponentColorModel(ColorSpace colorSpace, boolean hasAlpha, boolean isAlphaPremultiplied, int transparency, int transferType)
  • getRed(Object inData)
  • getGreen(Object inData)
  • getBlue(Object inData)
  • getAlpha(Object inData)
  • getDataElements(int rgb, Object pixel)
  • coerceData(WritableRaster raster, boolean isAlphaPremultiplied)
  • createCompatibleWritableRaster(int w, int h)
  • createCompatibleSampleModel(int w, int h)
java.awt.image.SampleModel includes two new methods to accept the new datatypes:
  • getDataElements(int x, int y, int w, int h, Object obj, DataBuffer data)
  • setDataElements(int x, int y, int w, int h, Object obj, DataBuffer data)
java.awt.image.ComponentSampleModel includes two methods to accept the new datatypes:
  • createDataBuffer()
  • getDataElements(int x, int y, Object obj, DataBuffer data)
java.awt.image.BandedSampleModel has three methods that were edited to accept the new datatypes:
  • createDataBuffer()
  • getDataElements(int x, int y, Object obj, DataBuffer data)
  • setDataElements(int x, int y, Object obj, DataBuffer data)
java.awt.color.ColorSpace includes two new methods determine per component minimum and maximum normalized values:
  • getMinValue(int component)
  • getMaxValue(int component)
java.awt.color.ICC_ColorSpace includes new methods override the two new ColorSpace methods.

Public Bidi Algorithm

The bugtraq report that corresponds to this change is: 4285083

The Unicode Bidirectional Algorithm analyzes text using the Unicode character properties and determines the direction of runs of the text. The algorithm is necessary to properly display bidirectional text, such as Hebrew and Arabic text, in the correct order.

The current implementation is all written in the Java programming language, but the SDK 1.4 will include efficient access from native font code so that Hebrew and Arabic text can be more efficiently rendered. The SDK 1.4 will provide access to the native code through the Java Native Interface.

The new public Bidi class implements the Unicode 3.0 Bidi Algorithm and allows access to information on the bidirectional reordering of text so that the mixed, bidirectional text is properly displayed.

The example BidiSample demonstrates some of the Bidi routines.

Font Rasterizer support for TrueType hinting

Before this release, the T2K font rasterizer used by Java 2D did not support font-hinting for TrueType fonts. As a result, when TrueType fonts did not always display with a consistent, attractive appearance. For this release, the T2K rasterizer has been modified to use the hints stored in the TrueType fonts.

By adding this functionality to the T2K rasterizer, dependency on native rasterizers has been greatly reduced. Reducing this dependency results in:

  • Greater portability because hinting of TrueType fonts is performed by the cross-platform T2K rasterizer, not the native rasterizer.
  • More consistent metrics display of TrueType fonts because the same rasterizer is being used for on-screen and off-screen drawing.

Hinted Lucida Fonts

The bugtraq report that corresponds to this change is: 4285089

For the SDK 1.4, the Lucida fonts that are in the Java 2 SDK will be upgraded to contain hints. This will give the Java 2 SDK higher quality fonts that could be used in place of existing fonts or if no other fonts are available. Adding hints to the Lucida fonts also allows the new cross-platform rasterizer to hint the Lucida fonts contained in the SDK, which causes the Lucida fonts to be displayed in a more consistent and attractive manner.

OpenType Font Table Support

The bugtraq report that corresponds to this change is: 4285161

The SDK 1.4 includes a new architecture for providing general OpenType font support. This new architecture provides international character support for contextual scripts like Thai, Indic, Arabic, and Hebrew. It also provides enhanced typographical support for Roman languages.

Support for Numeric Shaping

The bugtraq report that corresponds to this change is: 4210199

Currently, when Java 2D renders numerals surrounded by Arabic text, the numerals have Arabic (roman) shapes, which are the commonly expected numeral shapes in most western countries. However, people in a Hindi locale expect to see Hindi shapes.

A new attribute, TextAttribute.NUMERIC_SHAPING, and a new class, NumericShaper, enable you to shape ASCII digits to other Unicode decimal ranges.

For example, to cause a TextLayout instance to convert digits from European to Arabic:

  1. Create a NumericShaper that shapes ARABIC digits:
          Numeric Shaper nS
         = NumericShaper.getContextualShaper(NumericShaper.ARABIC)
  2. Add the NumericShaper to an attribute Map along with the key value of TextAttribute.NUMERIC_SHAPING:
          Map map = new HashMap();
      map.put(TextAttribute.NUMERIC_SHAPING, nS);
  3. Create a TextLayout with the attribute Map:
          FontRenderContext frc = ...;
      TextLayout layout = new TextLayout(text, map, frc);
  4. Render the text:
          layout.draw(g2d, x, y);

The NumericShaper class includes 19 constants representing different Unicode decimal ranges, allowing you to convert to 19 different digit shapes, including Devanagari and Thai.

Improved Complex-Layout Support in GlyphVector

Prior to this release, clients could not access glyph-to-character mapping information from GlyphVector. Clients can use this information to find out which glyphs in the GlyphVector correspond to which characters. This release also defines new methods to get the precise bounds of the GlyphVector and of individual glyphs within a GlyphVector.

Note: Although clients can use GlyphVector and the glyph-to-character mapping information to implement selection and hit testing, most clients will find TextLayout and the Swing JTextArea and JTextField classes to be more useful and convenient.

These GlyphVector methods are new in the SDK 1.4:

  • getGlyphCharIndex(int glyphIndex)
    Returns the character index of the specified glyph. The character index is the index of the first logical character represented by the glyph.
  • getGlyphCharIndices(int beginGlyphIndex, int numEntries, int[] codeReturn)
    Returns the character indices of the specified glyphs.
  • getGlyphOutline(int glyphIndex, float x, float y)
    Returns a Shape whose interior corresponds to the visual representation of the specified glyph within this GlyphVector, offset to x, y.
  • getPixelBounds(FontRenderContext renderFRC, float x, float y)
    Returns the pixel bounds of this GlyphVector when rendered in a graphics with the given FontRenderContext at the given location.
  • getGlyphPixelBounds(int index, FontRenderContext renderFRC, float x, float y)
    Returns the pixel bounds of the glyph at index when this GlyphVector is rendered in a Graphics with the given FontRenderContext at the given location.
These new GlyphMetrics methods deal with transformed fonts:
  • getAdvanceX()
    Returns the x-component of the advance of the glyph.
  • getAdvanceY
    Returns the y-component of the advance of the glyph.
Complete Porter-Duff Support

The bugtraq report that corresponds to this change is: 4380232

The AlphaComposite class provides alpha blending capabilities according to modes or rules established by Porter and Duff. Out of the 12 rules that Porter and Duff identified, the AlphaComposite API for the SDK, version 1.3 defines and implements only 8 of them:

  • Clear
  • A (Src)
  • A over B (SrcOver)
  • B over A (DstOver)
  • A in B (SrcIn)
  • B in A (DstIn)
  • A held out by B (SrcOut)
  • B held out by A (DstOut)

For the SDK 1.4, AlphaComposite implements the remaining 4 Porter-Duff rules:

  • B (Dst)
  • A atop B (SrcAtop)
  • B atop A (DstAtop)
  • A xor B (Xor)

Support for Checking if Font has a Transform

The bugtraq report that corresponds to this change is: 4314043

As of the SDK 1.2 the Font object has a transform attribute that can be accessed with the Font.getTransform method. You can perform geometric transformations, such as rotating and shearing, on the Font by setting the transform attribute. However, most applications use the Size attribute rather than the transform to control the size and shape of characters. In this case, the transform is a simple identity transform.

Currently, the only way to determine if the transform is an identity transform is to call getTransform and inspect the returned AffineTransform. Unfortunately, calling getTransform requires the Font object to clone the AffineTransform because the transform is mutable.

Two new methods in the SDK 1.4 allow you to check if a Font object's transform is an identity tranform without creating a new AffineTransform:

  • java.awt.Font.isTransformed:
    Returns true if this Font object has a non-identity AffineTransform attribute.
  • java.awt.font.TransformAttribute.isIdentity:
    Returns true if the wrapped transform is an identity transform.
New Equality Methods for FontRenderContext

The bugtraq report that corresponds to this change is: 4328579

A FontRenderContext object encapsulates state about the graphics context and is used by GlyphVector and TextLayout. Three new methods in FontRenderContext allow you to compare the FontRenderContext in the GlyphVector against the one in the graphics context into which the GlyphVector draws:

  • equals(FontRenderContext)
  • equals(Object)
  • hashCode()
These equals methods also have performance benefits because a client does not have to create an AffineTransform to perform an equality test.

*As used on this web site, the terms "Java Virtual Machine" or "JVM" mean a virtual machine for the Java platform.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.jdi.AbsentInformationException (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.AbsentInformationException

  • Packages that use AbsentInformationException
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of AbsentInformationException in com.sun.jdi

      Methods in com.sun.jdi that throw AbsentInformationException
      Modifier and Type Method and Description
      List<Location> Method.allLineLocations()
      Returns a list containing a Location object for each executable source line in this method.
      List<Location> ReferenceType.allLineLocations()
      Returns a list containing a Location object for each executable source line in this reference type.
      List<Location> Method.allLineLocations(String stratum, String sourceName)
      Returns a list containing a Location object for each executable source line in this method.
      List<Location> ReferenceType.allLineLocations(String stratum, String sourceName)
      Returns a list containing a Location object for each executable source line in this reference type.
      List<LocalVariable> Method.arguments()
      Returns a list containing each LocalVariable that is declared as an argument of this method.
      List<Location> Method.locationsOfLine(int lineNumber)
      Returns a List containing all Location objects that map to the given line number.
      List<Location> ReferenceType.locationsOfLine(int lineNumber)
      Returns a List containing all Location objects that map to the given line number.
      List<Location> Method.locationsOfLine(String stratum, String sourceName, int lineNumber)
      Returns a List containing all Location objects that map to the given line number and source name.
      List<Location> ReferenceType.locationsOfLine(String stratum, String sourceName, int lineNumber)
      Returns a List containing all Location objects that map to the given line number.
      String ReferenceType.sourceDebugExtension()
      Get the source debug extension of this type.
      String Location.sourceName()
      Gets an identifing name for the source corresponding to this location.
      String ReferenceType.sourceName()
      Gets an identifying name for the source corresponding to the declaration of this type.
      String Location.sourceName(String stratum)
      Gets an identifing name for the source corresponding to this location.
      List<String> ReferenceType.sourceNames(String stratum)
      Gets the identifying names for all the source corresponding to the declaration of this type.
      String Location.sourcePath()
      Gets the path to the source corresponding to this location.
      String Location.sourcePath(String stratum)
      Gets the path to the source corresponding to this location.
      List<String> ReferenceType.sourcePaths(String stratum)
      Gets the paths to the source corresponding to the declaration of this type.
      List<LocalVariable> Method.variables()
      Returns a list containing each LocalVariable declared in this method.
      List<LocalVariable> Method.variablesByName(String name)
      Returns a list containing each LocalVariable of a given name in this method.
      LocalVariable StackFrame.visibleVariableByName(String name)
      Finds a LocalVariable that matches the given name and is visible at the current frame location.
      List<LocalVariable> StackFrame.visibleVariables()
      Returns a list containing each LocalVariable that can be accessed from this frame's location.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.views.AbstractView (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.views.AbstractView

  • Packages that use AbstractView
    Package Description
    org.w3c.dom.css
    org.w3c.dom.events
    org.w3c.dom.views

    • Uses of AbstractView in org.w3c.dom.css

      Subinterfaces of AbstractView in org.w3c.dom.css
      Modifier and Type Interface and Description
      interface  ViewCSS
      This interface represents a CSS view.

    • Uses of AbstractView in org.w3c.dom.events

      Methods in org.w3c.dom.events that return AbstractView
      Modifier and Type Method and Description
      AbstractView UIEvent.getView()
      The view attribute identifies the AbstractView from which the event was generated.
      Methods in org.w3c.dom.events with parameters of type AbstractView
      Modifier and Type Method and Description
      void MouseEvent.initMouseEvent(String typeArg, boolean canBubbleArg, boolean cancelableArg, AbstractView viewArg, int detailArg, int screenXArg, int screenYArg, int clientXArg, int clientYArg, boolean ctrlKeyArg, boolean altKeyArg, boolean shiftKeyArg, boolean metaKeyArg, short buttonArg, EventTarget relatedTargetArg)
      The initMouseEvent method is used to initialize the value of a MouseEvent created through the DocumentEvent interface.
      void UIEvent.initUIEvent(String typeArg, boolean canBubbleArg, boolean cancelableArg, AbstractView viewArg, int detailArg)
      The initUIEvent method is used to initialize the value of a UIEvent created through the DocumentEvent interface.

    • Uses of AbstractView in org.w3c.dom.views

      Methods in org.w3c.dom.views that return AbstractView
      Modifier and Type Method and Description
      AbstractView DocumentView.getDefaultView()
      The default AbstractView for this Document, or null if none available.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.Accessible (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.Accessible

  • Packages that use Accessible
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of Accessible in com.sun.jdi

      Subinterfaces of Accessible in com.sun.jdi
      Modifier and Type Interface and Description
      interface  ArrayType
      Provides access to the class of an array and the type of its components in the target VM.
      interface  ClassType
      A mirror of a class in the target VM.
      interface  Field
      A class or instance variable in the target VM.
      interface  InterfaceType
      A mirror of an interface in the target VM.
      interface  Method
      A static or instance method in the target VM.
      interface  ReferenceType
      The type of an object in a target VM.
      interface  TypeComponent
      An entity declared within a user defined type (class or interface).
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.event.AccessWatchpointEvent (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.event.AccessWatchpointEvent

No usage of com.sun.jdi.event.AccessWatchpointEvent
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.request.AccessWatchpointRequest (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.request.AccessWatchpointRequest

  • Packages that use AccessWatchpointRequest
    Package Description
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of AccessWatchpointRequest in com.sun.jdi.request

      Methods in com.sun.jdi.request that return AccessWatchpointRequest
      Modifier and Type Method and Description
      AccessWatchpointRequest EventRequestManager.createAccessWatchpointRequest(Field field)
      Creates a new disabled watchpoint which watches accesses to the specified field.
      Methods in com.sun.jdi.request that return types with arguments of type AccessWatchpointRequest
      Modifier and Type Method and Description
      List<AccessWatchpointRequest> EventRequestManager.accessWatchpointRequests()
      Return an unmodifiable list of the enabled and disabled access watchpoint requests.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Acknowledgments

The Java Native Interface (JNI) specification was formed as a result of a series of discussions among JavaSoft and Java licensees. The goal is to achieve a native interface standard.

Sheng Liang at JavaSoft is responsible for the JNI design and specification. JNI is partly evolved from Netscape’s Java Runtime Interface (JRI), which was designed by Warren Harris. Warren Harris also helped to improve the JNI design. Simon Nash at IBM and Patrick Beard at Apple provided extensive feedbacks that shaped the JNI design in many ways.

In addition, the JNI benefited greatly from JavaSoft internal design reviews. These design reviews were conducted by James Gosling, Peter Kessler, Tim Lindholm, Mark Reinhold, Derek White, and Frank Yellin.

We also want to acknowledge the helpful comments and suggestions we received from numerous people on various drafts of the specification.

Lastly, Beth Stearns improved the presentation of this document.

Contents | Previous | Next
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JAAS Authorization

This tutorial expands the program and policy file developed in the JAAS Authentication tutorial to demonstrate the JAAS authorization component, which ensures the authenticated caller has the access control rights (permissions) required to do subsequent security-sensitive operations. Since the authorization component requires that the user authentication first be completed, please read the JAAS Authentication tutorial first if you have not already done so.

The rest of this tutorial consists of the following sections:

  • What is JAAS Authorization?
  • How is JAAS Authorization Performed?
    • How Do You Make Principal-Based Policy File Statements?
    • How Do You Associate a Subject with an Access Control Context?
  • The Authorization Tutorial Code
  • The Login Configuration File
  • The Policy File
  • Running the Authorization Tutorial Code

If you want to first see the tutorial code in action, you can skip directly to Running the Authorization Tutorial Code and then go back to the other sections to learn more.

What is JAAS Authorization?

JAAS authorization extends the existing Java security architecture that uses a security policy to specify what access rights are granted to executing code. That architecture, introduced in the Java 2 platform, is code-centric. That is, the permissions are granted based on code characteristics: where the code is coming from and whether it is digitally signed and if so by whom. We saw an example of this in the jaasacn.policy file used in the JAAS Authentication tutorial. That file contains the following:

grant codebase "file:./JaasAcn.jar" {
   permission javax.security.auth.AuthPermission
                    "createLoginContext.JaasSample";
};

This grants the code in the JaasAcn.jar file, located in the current directory, the specified permission. (No signer is specified, so it doesn't matter whether the code is signed or not.)

JAAS authorization augments the existing code-centric access controls with new user-centric access controls. Permissions can be granted based not just on what code is running but also on who is running it.

When an application uses JAAS authentication to authenticate the user (or other entity such as a service), a Subject is created as a result. The purpose of the Subject is to represent the authenticated user. A Subject is comprised of a set of Principals, where each Principal represents an identity for that user. For example, a Subject could have a name Principal ("Susan Smith") and a Social Security Number Principal ("987-65-4321"), thereby distinguishing this Subject from other Subjects.

Permissions can be granted in the policy to specific Principals. After the user has been authenticated, the application can associate the Subject with the current access control context. For each subsequent security-checked operation, (a local file access, for example), the Java runtime will automatically determine whether the policy grants the required permission only to a specific Principal and if so, the operation will be allowed only if the Subject associated with the access control context contains the designated Principal.

How is JAAS Authorization Performed?

To make JAAS authorization take place, the following is required:

  • The user must be authenticated, as described in the JAAS Authentication tutorial.
  • Principal-based entries must be configured in the security policy.
  • The Subject that is the result of authentication must be associated with the current access control context.

How Do You Make Principal-Based Policy File Statements?

Policy file grant statements can now optionally include one or more Principal fields. Inclusion of a Principal field indicates that the user or other entity represented by the specified Principal, executing the specified code, has the designated permissions.

Thus, the basic format of a grant statement is now

grant <signer(s) field>, <codeBase URL>
  <Principal field(s)> {
    permission perm_class_name "target_name", "action";
    ....
    permission perm_class_name "target_name", "action";
  };
where each of the signer, codeBase and Principal fields is optional and the order between the fields doesn't matter.

A Principal field looks like the following:

Principal Principal_class "principal_name"

That is, it is the word "Principal" (where case doesn't matter) followed by the (fully qualified) name of a Principal class and a principal name.

A Principal class is a class that implements the java.security.Principal interface. All Principal objects have an associated name that can be obtained by calling their getName method. The format used for the name is dependent on each Principal implementation.

The type of Principal placed in the Subject created by the Kerberos authentication mechanism used by this tutorial is javax.security.auth.kerberos.KerberosPrincipal, so that is what should be used as the Principal_class part of our grant statement's Principal designation. User names for KerberosPrincipals are of the form "name@realm". Thus, if the user name is "mjones" and the realm is "KRBNT-OPS.ABC.COM", the full principal_name designation to use in the grant statement is "mjones@KRBNT-OPS.ABC.COM".

It is possible to include more than one Principal field in a grant statement. If multiple Principal fields are specified, then the permissions in that grant statement are granted only if the Subject associated with the current access control context contains all of those Principals.

To grant the same set of permissions to different Principals, create multiple grant statements where each lists the permissions and contains a single Principal field designating one of the Principals.

The policy file for this tutorial includes one grant statement with a Principal field:

grant codebase "file:./SampleAction.jar",
    Principal javax.security.auth.kerberos.KerberosPrincipal
        "your_user_name@your_realm"  {

   permission java.util.PropertyPermission "java.home", "read";
   permission java.util.PropertyPermission "user.home", "read";
   permission java.io.FilePermission "foo.txt", "read";
};
where you substitute your Kerberos user name (complete with "@" and realm) for "your_user_name@your_realm".

This specifies that the indicated permissions are granted to the specified principal executing the code in SampleAction.jar.

How Do You Associate a Subject with an Access Control Context?

To create and associate a Subject with an access control context, you need the following:

  • The user must first be authenticated, as described in JAAS Authentication.
  • The static doAs method from the Subject class must be called, passing it an authenticated Subject and a java.security.PrivilegedAction or java.security.PrivilegedExceptionAction. (See API for Privileged Blocks for a comparison of PrivilegedAction and PrivilegedExceptionAction.) The doAs method associates the provided Subject with the current access control context and then invokes the run method from the action. The run method implementation contains all the code to be executed as the specified Subject. The action thus executes as the specified Subject.

    The static doAsPrivileged method from the Subject class may be called instead of the doAs method. In addition to the parameters passed to doAs, doAsPrivileged requires a third parameter: an AccessControlContext. Unlike doAs, which associates the provided Subject with the current access control context, doAsPrivileged associates the Subject with the provided access control context. See doAs vs. doAsPrivileged in the JAAS Reference Guide for a comparison of those methods.

The Authorization Tutorial Code

The code for this tutorial consists of two files:

  • JaasAzn.java is exactly the same as the JaasAcn.java from the JAAS Authentication tutorial except for the additional code needed to call Subject.doAsPrivileged.
  • SampleAction.java contains the SampleAction class. This class implements PrivilegedAction and has a run method that contains all the code we want to be executed with Principal-based authorization checks.

JaasAzn.java

JaasAzn.java is exactly the same as the JaasAcn.java code used in the previous tutorial except with three statements added at the end of the main method, after the authentication is done. These statements result in (1) association of a Subject representing the authenticated user with the current access control context and (2) execution of the code in the run method of SampleAction. Associating the Subject with the access control context enables security-sensitive operations in the SampleAction run method (and any code it invokes directly or indirectly) to be executed if a Principal representing the authenticated user is granted the required permissions in the current policy.

Like JaasAcn.java, JaasAzn.java instantiates a LoginContext lc and calls its login method to perform the authentication. If successful, the authenticated Subject (which includes a Principal representing the user) is obtained by calling the LoginContext's getSubject method:

Subject mySubject = lc.getSubject();

The main method then calls Subject.doAsPrivileged, passing it the authenticated Subject mySubject, a PrivilegedAction (SampleAction) and a null AccessControlContext, as described in the following.

The SampleAction class is instantiated via the following:

PrivilegedAction action = new SampleAction();

The call to Subject.doAsPrivileged is performed via:

Subject.doAsPrivileged(mySubject, action, null);

The doAsPrivileged method invokes execution of the run method in the PrivilegedAction action (SampleAction) to initiate execution of the rest of the code, which is considered to be executed on behalf of the Subject mySubject.

Passing null as the AccessControlContext (third) argument to doAsPrivileged indicates that mySubject should be associated with a new empty AccessControlContext. The result is that security checks occurring during execution of SampleAction will only require permissions for the SampleAction code itself (or other code it invokes), running as mySubject. Note that the caller of doAsPrivileged (and the callers on the execution stack at the time doAsPrivileged was called) do not require any permissions while the action executes.

SampleAction.java

SampleAction.java contains the SampleAction class. This class implements java.security.PrivilegedAction and has a run method that contains all the code we want to be executed as the Subject mySubject. For this tutorial, we will perform three operations, each of which cannot be done unless code has been granted required permissions. We will:

  • Read and print the value of the java.home system property,
  • Read and print the value of the user.home system property, and
  • Determine whether or not a file named foo.txt exists in the current directory.

Here is the code:

import java.io.File;
import java.security.PrivilegedAction;

public class SampleAction implements PrivilegedAction {

  public Object run() {

    System.out.println("\nYour java.home property value is: "
                + System.getProperty("java.home"));

    System.out.println("\nYour user.home property value is: "
                + System.getProperty("user.home"));

    File f = new File("foo.txt");
    System.out.print("\nfoo.txt does ");
    if (!f.exists())
        System.out.print("not ");
    System.out.println("exist in the current working directory.");
    return null;
  }
}

The Login Configuration File

The login configuration file used for this tutorial can be exactly the same as that used by the JAAS Authentication tutorial. Thus we can use jaas.conf, which contains just one entry:

JaasSample {
  com.sun.security.auth.module.Krb5LoginModule required;
};

This entry is named "JaasSample" and that is the name that both our tutorial applications JaasAcn and JaasAzn use to refer to it. The entry specifies that the LoginModule to be used to do the user authentication is the Krb5LoginModule in the com.sun.security.auth.module package and that this Krb5LoginModule is required to "succeed" in order for authentication to be considered successful. The Krb5LoginModule succeeds only if the name and password supplied by the user are successfully used to log the user into the Kerberos KDC.

The Policy File

This authorization tutorial contains two classes, JaasAzn and SampleAction. The code in each class contains some security-sensitive operations and thus relevant permissions are required in a policy file in order for the operations to be executed.

Permissions Required by JaasAzn

The main method of the JaasAzn class does two operations for which permissions are required. It

  • creates a LoginContext, and
  • calls the doAsPrivileged static method of the Subject class.

The LoginContext creation is exactly the same as was done in the authentication tutorial, and it thus needs the same javax.security.auth.AuthPermission permission with target "createLoginContext.JaasSample".

In order to call the doAsPrivileged method of the Subject class, you need to have a javax.security.auth.AuthPermission with target "doAsPrivileged".

Assuming the JaasAzn class is placed in a JAR file named JaasAzn.jar, these permissions can be granted to the JaasAzn code via the following grant statement in the policy file:

grant codebase "file:./JaasAzn.jar" {
   permission javax.security.auth.AuthPermission
                    "createLoginContext.JaasSample";
   permission javax.security.auth.AuthPermission "doAsPrivileged";
};

Permissions Required by SampleAction

The SampleAction code does three operations for which permissions are required. It

  • reads the value of the "java.home" system property.
  • reads the value of the "user.home" system property.
  • checks to see whether or not a file named foo.txt exists in the current directory.

The permissions required for these operations are the following:

permission java.util.PropertyPermission "java.home", "read";
permission java.util.PropertyPermission "user.home", "read";
permission java.io.FilePermission "foo.txt", "read";

We need to grant these permissions to the code in SampleAction.class, which we will place in a JAR file named SampleAction.jar. However, for this particular grant statement we want to grant the permissions not just to the code but to a specific user executing the code, to demonstrate how to restrict access to a particular user.

Thus, as explained in How Do You Make Principal-Based Policy File Statements?, our grant statement looks like the following:

grant codebase "file:./SampleAction.jar",
    Principal javax.security.auth.kerberos.KerberosPrincipal
        "your_user_name@your_realm"  {

   permission java.util.PropertyPermission "java.home", "read";
   permission java.util.PropertyPermission "user.home", "read";
   permission java.io.FilePermission "foo.txt", "read";
};
You substitute your Kerberos user name (complete with "@" and realm) for "your_user_name@your_realm". For example, if your user name is "mjones" and your realm is "KRBNT-OPERATIONS.ABC.COM", you would use "mjones@KRBNT-OPERATIONS.ABC.COM" (complete with the quotes).

The Full Policy File

The full policy file is jaasazn.policy.

Running the Authorization Tutorial Code

To execute our JAAS authorization tutorial code, all you have to do is

  1. Place the following files into a directory:
    • The JaasAzn.java source file.
    • The SampleAction.java source file.
    • The jaas.conf login configuration file.
    • The jaasazn.policy policy file.
  2. Replace "your_user_name@your_realm" in jaasazn.policy with your user name and realm.
  3. Compile SampleAction.java and JaasAzn.java:
    javac SampleAction.java JaasAzn.java
  4. Create a JAR file named JaasAzn.jar containing JaasAzn.class:
    jar -cvf JaasAzn.jar JaasAzn.class
  5. Create a JAR file named SampleAction.jar containing SampleAction.class:
    jar -cvf SampleAction.jar SampleAction.class
  6. Execute the JaasAzn application, specifying
    1. by an appropriate -classpath clause that classes should be searched for in the JaasAzn.jar and SampleAction.jar JAR files,
    2. by -Djava.security.manager that a security manager should be installed,
    3. by -Djava.security.krb5.realm=<your_realm> that your Kerberos realm is the one specified.
    4. by -Djava.security.krb5.kdc=<your_kdc> that your Kerberos KDC is the one specified.
    5. by -Djava.security.policy=jaasazn.policy that the policy file to be used is jaasazn.policy, and
    6. by -Djava.security.auth.login.config=jaas.conf that the login configuration file to be used is jaas.conf.

    Below are the full commands to use for both Microsoft Windows and Unix systems. The only difference is that on Windows systems you use semicolons to separate classpath items, while you use colons for that purpose on Unix systems. Be sure to replace <your_realm> with your Kerberos realm, and <your_kdc> with your Kerberos KDC.

    Here is the full command for Windows systems:

    java -classpath JaasAzn.jar;SampleAction.jar
 -Djava.security.manager
 -Djava.security.krb5.realm=<your_realm>
 -Djava.security.krb5.kdc=<your_kdc>
 -Djava.security.policy=jaasazn.policy
 -Djava.security.auth.login.config=jaas.conf JaasAzn

    Here is the full command for UNIX systems:

    java -classpath JaasAzn.jar:SampleAction.jar
 -Djava.security.manager
 -Djava.security.krb5.realm=<your_realm>
 -Djava.security.krb5.kdc=<your_kdc>
 -Djava.security.policy=jaasazn.policy
 -Djava.security.auth.login.config=jaas.conf JaasAzn

    Type the full command on one line. Multiple lines are used here for legibility. If the command is too long for your system, you may need to place it in a .bat file (for Windows) or a .sh file (for UNIX) and then run that file to execute the command.

    You will be prompted for your Kerberos user name and password, and the underlying Kerberos authentication mechanism specified in the login configuration file will log you into Kerberos. If your login is successful, you will see the message "Authentication succeeded!" and if not, you will see "Authentication Failed."

    For login troubleshooting suggestions, see Troubleshooting.

    Once authentication is successfully completed, the rest of the program (in SampleAction) will be executed on behalf of you, the user, requiring you to have been granted appropriate permissions. The jaasazn.policy policy file grants you the required permissions, so you will see a display of the values of your java.home and user.home system properties and a statement as to whether or not you have a file named foo.txt in the current directory.

Tutorials Introduction and TOC
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JAAS Authentication

The Java Authentication and Authorization Service (JAAS) was introduced as an optional package to the Java 2 SDK, Standard Edition (J2SDK), v 1.3. JAAS has now been integrated into the J2SDK 1.4.

JAAS can be used for two purposes:

  • for authentication of users, to reliably and securely determine who is currently executing Java code, regardless of whether the code is running as an application, an applet, a bean, or a servlet; and
  • for authorization of users to ensure they have the access control rights (permissions) required to do the actions performed.

This section provides a basic tutorial for the authentication component. The authorization component will be described in the JAAS Authorization tutorial.

JAAS authentication is performed in a pluggable fashion. This permits Java applications to remain independent from underlying authentication technologies. New or updated technologies can be plugged in without requiring modifications to the application itself. An implementation for a particular authentication technology to be used is determined at runtime. The implementation is specified in a login configuration file. The authentication technology used for this tutorial is Kerberos. (See Kerberos Requirements.)

The rest of this tutorial consists of the following sections:

  1. The Authentication Tutorial Code
  2. The Login Configuration
  3. Running the Code
  4. Running the Code with a Security Manager

If you want to first see the tutorial code in action, you can skip directly to Running the Code and then go back to the other sections to learn about coding and configuration file details.

The Authentication Tutorial Code

Our authentication tutorial code is contained in a single source file, JaasAcn.java. This file's main method performs the authentication and then reports whether or not authentication succeeded.

The code for authenticating the user is very simple, consisting of just two steps:

  1. Instantiate a LoginContext.
  2. Call the LoginContext's login method.

First the basic code is shown, followed by a complete listing of the JaasAcn.java source file, complete with import statements and error handling.

Instantiating a LoginContext

In order to authenticate a user, you first need a javax.security.auth.login.LoginContext. Here is the basic way to instantiate a LoginContext:

import javax.security.auth.login.*;
. . .
LoginContext lc =
    new LoginContext(<config file entry name>,
           <CallbackHandler to be used for user interaction>);
and here is the specific way our tutorial code does the instantiation:
import javax.security.auth.login.*;
import com.sun.security.auth.callback.TextCallbackHandler;
. . .
LoginContext lc =
    new LoginContext("JaasSample",
          new TextCallbackHandler());

The arguments are the following:

  1. The name of an entry in the JAAS login configuration file

    This is the name for the LoginContext to use to look up an entry for this application in the JAAS login configuration file, described here. Such an entry specifies the class(es) that implement the desired underlying authentication technology(ies). The class(es) must implement the LoginModule interface, which is in the javax.security.auth.spi package.

    In our sample code, we use the Krb5LoginModule in the com.sun.security.auth.module package, which performs Kerberos authentication.

    The entry in the login configuration file we use for this tutorial (see jaas.conf) has the name "JaasSample", so that is the name we specify as the first argument to the LoginContext constructor.

  2. A CallbackHandler instance.

    When a LoginModule needs to communicate with the user, for example to ask for a user name and password, it does not do so directly. That is because there are various ways of communicating with a user, and it is desirable for LoginModules to remain independent of the different types of user interaction. Rather, the LoginModule invokes a CallbackHandler to perform the user interaction and obtain the requested information, such as the user name and password. (CallbackHandler is an interface in the javax.security.auth.callback pkg.)

    An instance of the particular CallbackHandler to be used is specified as the second argument to the LoginContext constructor. The LoginContext forwards that instance to the underlying LoginModule (in our case Krb5LoginModule). An application typically provides its own CallbackHandler implementation. Two simple CallbackHandlers, TextCallbackHandler and DialogCallbackHandler, are provided in the com.sun.security.auth.callback package as sample implementations. Our code uses the TextCallbackHandler, which outputs information to and reads input from the command line.

Calling the LoginContext's login Method

Once we have a LoginContext lc, we can call its login method to carry out the authentication process:

lc.login();

The LoginContext instantiates a new empty javax.security.auth.Subject object (which represents the user or service being authenticated). The LoginContext constructs the configured LoginModule (in our case Krb5LoginModule) and initializes it with this new Subject and TextCallbackHandler.

The LoginContext's login method then calls methods in the Krb5LoginModule to perform the login and authentication. The Krb5LoginModule will utilize the TextCallbackHandler to obtain the user name and password. Then the Krb5LoginModule will use this information to get the user credentials from the Kerberos KDC. See the Kerberos reference documentation.

If authentication is successful, the Krb5LoginModule populates the Subject with (1) a Kerberos Principal representing the user and (2) the user's credentials (TGT). See Subjects, Principals, Authentication, and Credentials for information on these terms.

The calling application can subsequently retrieve the authenticated Subject by calling the LoginContext's getSubject method, although doing so is not necessary for this tutorial.

The Complete JaasAcn.java Code

Now that you have seen the basic code required to authenticate the user, we can put it all together into the full class in JaasAcn.java, which includes relevant import statements and error handling:

import javax.security.auth.*;
import javax.security.auth.callback.*;
import javax.security.auth.login.*;
import com.sun.security.auth.callback.TextCallbackHandler;

/**
 * This JaasAcn application attempts to authenticate a user
 * and reports whether or not the authentication was successful.
 */
public class JaasAcn {

  public static void main(String[] args) {

      // Obtain a LoginContext, needed for authentication. Tell
      // it to use the LoginModule implementation specified by
      // the entry named "JaasSample" in the JAAS login
      // configuration file and to also use the specified
      // CallbackHandler.
      LoginContext lc = null;
      try {
          lc = new LoginContext("JaasSample",
                      new TextCallbackHandler());
      } catch (LoginException le) {
          System.err.println("Cannot create LoginContext. "
              + le.getMessage());
          System.exit(-1);
      } catch (SecurityException se) {
          System.err.println("Cannot create LoginContext. "
              + se.getMessage());
          System.exit(-1);
      }

      try {

          // attempt authentication
          lc.login();

      } catch (LoginException le) {

          System.err.println("Authentication failed: "
          System.err.println("  " + le.getMessage());
          System.exit(-1);

      }

      System.out.println("Authentication succeeded!");

    }
}

The Login Configuration

JAAS authentication is performed in a pluggable fashion, so applications can remain independent from underlying authentication technologies. A system administrator determines the authentication technologies, or LoginModules, to be used for each application and configures them in a login Configuration. The source of the configuration information (for example, a file or a database) is up to the current javax.security.auth.login.Configuration implementation. The default Configuration implementation from Sun Microsystems reads configuration information from configuration files, as described in com.sun.security.auth.login.ConfigFile.html.

See JAAS Login Configuration File for information as to what a login configuration file is, what it contains, and how to specify which login configuration file should be used.

The Login Configuration File for This Tutorial

As noted, the login configuration file we use for this tutorial, jaas.conf, contains just one entry, which is

JaasSample {
  com.sun.security.auth.module.Krb5LoginModule required;
};

This entry is named "JaasSample" and that is the name that our tutorial application, JaasAcn, uses to refer to this entry. The entry specifies that the LoginModule to be used to do the user authentication is the Krb5LoginModule in the com.sun.security.auth.module package and that this Krb5LoginModule is required to "succeed" in order for authentication to be considered successful. The Krb5LoginModule succeeds only if the name and password supplied by the user are successfully used to log the user into the Kerberos KDC.

For information about all the possible options that can be passed to Krb5LoginModule, see the Krb5LoginModule documentation.

Running the Code

To execute our JAAS authentication tutorial code, all you have to do is

  1. Place the JaasAcn.java application source file and the jaas.conf login configuration file into a directory.
  2. Compile JaasAcn.java:
    javac JaasAcn.java
  3. Execute the JaasAcn application, specifying
    • by -Djava.security.krb5.realm=<your_realm> that your Kerberos realm is the one specified. For example, if your realm is "KRBNT-OPERATIONS.ABC.COM" you'd put -Djava.security.krb5.realm=KRBNT-OPERATIONS.ABC.COM.
    • by -Djava.security.krb5.kdc=<your_kdc> that your Kerberos KDC is the one specified. For example, if your KDC is "samplekdc.abc.com" you'd put -Djava.security.krb5.kdc=samplekdc.abc.com.
    • by -Djava.security.auth.login.config=jaas.conf that the login configuration file to be used is jaas.conf.

The full command is below. Be sure to replace <your_realm> with your Kerberos realm, and <your_kdc> with your Kerberos KDC.

java -Djava.security.krb5.realm=<your_realm>
 -Djava.security.krb5.kdc=<your_kdc>
 -Djava.security.auth.login.config=jaas.conf JaasAcn

Type all that on one line. Multiple lines are used here for legibility.

You will be prompted for your Kerberos user name and password, and the underlying Kerberos authentication mechanism specified in the login configuration file will log you into Kerberos. If your login is successful, you will see the following message:

Authentication succeeded!
If the login is not successful (for example, if you misspell your password), you will see
Authentication failed:
followed by a reason for the failure. For example, if you mistype your user name, you may see a message like the following (where the formatting is slightly modified here to increase legibility):
Authentication failed:
  Kerberos Authentication Failed:
    javax.security.auth.login.LoginException:
      KrbException: Client not found in Kerberos database

For login troubleshooting suggestions, see Troubleshooting.

After fixing any problems, re-run the program to try again.

Running the Code with a Security Manager

When a Java program is run with a security manager installed, the program is not allowed to access resources or otherwise perform security-sensitive operations unless it is explicitly granted permission to do so by the security policy in effect. In Java platforms that are compatible with J2SE v 1.2 and later, the permission must be granted by an entry in a policy file.

Most browsers install a security manager, so applets typically run under the scrutiny of a security manager. Applications, on the other hand, do not, since a security manager is not automatically installed when an application is running. Thus an application, like our JaasAcn application, by default has full access to resources.

To run an application with a security manager, simply invoke the interpreter with a -Djava.security.manager argument included on the command line.

If you try invoking JaasAcn with a security manager but without specifying any policy file, you will get the following (unless you have a default policy setup elsewhere that grants the required permissions or grants AllPermission):

% java -Djava.security.manager \
 -Djava.security.krb5.realm=<your_realm> \
 -Djava.security.krb5.kdc=<your_kdc> \
 -Djava.security.auth.login.config=jaas.conf JaasAcn
Exception in thread "main" java.security.AccessControlException:
  access denied (
  javax.security.auth.AuthPermission createLoginContext.JaasSample)

As you can see, you get an AccessControlException, because we haven't created and used a policy file granting our code the permission that is required in order to be allowed to create a LoginContext.

Here are the complete steps required in order to be able to run our JaasAcn application with a security manager installed. You can skip the first two steps if you have already done them, as described in Running the Code.

  1. Place the JaasAcn.java application source file and the jaas.conf login configuration file into a directory.
  2. Compile JaasAcn.java:
    javac JaasAcn.java
  3. Create a JAR file containing JaasAcn.class:
    jar -cvf JaasAcn.jar JaasAcn.class

    This command creates a JAR file, JaasAcn.jar, and places the JaasAcn.class file inside it.

  4. Create a policy file granting the code in the JAR file the required permission.

    The permission that is needed by code attempting to instantiate a LoginContext is a javax.security.auth.AuthPermission with target "createLoginContext.<entry name>". Here, <entry name> refers to the name of the login configuration file entry that the application references in its instantiation of LoginContext. The name used by our JaasAcn application's LoginContext instantiation is "JaasSample", as you can see in the code:

    LoginContext lc =
    new LoginContext("JaasSample",
          new TextCallbackHandler());
    Thus, the permission that needs to be granted to JaasAcn.jar is
    permission javax.security.auth.AuthPermission
  "createLoginContext.JaasSample";
    Copy the policy file jaasacn.policy to the same directory as that in which you stored JaasAcn.java, etc. This is a text file containing the following grant statement to grant JaasAcn.jar (in the current directory) the required permission:
    grant codebase "file:./JaasAcn.jar" {
   permission javax.security.auth.AuthPermission
                    "createLoginContext.JaasSample";
};

    Note: Policy files and the structure of entries within them are described in Default Policy Implementation and Policy File Syntax. Permissions are described here.

  5. Execute the JaasAcn application, specifying
    1. by an appropriate -classpath clause that classes should be searched for in the JaasAcn.jar JAR file,
    2. by -Djava.security.manager that a security manager should be installed,
    3. by -Djava.security.krb5.realm=<your_realm> that your Kerberos realm is the one specified. For example, if your realm is "KRBNT-OPERATIONS.ABC.COM" you'd put -Djava.security.krb5.realm=KRBNT-OPERATIONS.ABC.COM.
    4. by -Djava.security.krb5.kdc=<your_kdc> that your Kerberos KDC is the one specified. For example, if your KDC is "samplekdc.abc.com" you'd put -Djava.security.krb5.kdc=samplekdc.abc.com.
    5. by -Djava.security.policy=jaasacn.policy that the policy file to be used is jaasacn.policy, and
    6. by -Djava.security.auth.login.config=jaas.conf that the login configuration file to be used is jaas.conf.

    The full command is below. Be sure to replace <your_realm> with your Kerberos realm, and <your_kdc> with your Kerberos KDC.

    java -classpath JaasAcn.jar -Djava.security.manager
 -Djava.security.krb5.realm=<your_realm>
 -Djava.security.krb5.kdc=<your_kdc>
 -Djava.security.policy=jaasacn.policy
 -Djava.security.auth.login.config=jaas.conf JaasAcn

    Type all that on one line. Multiple lines are used here for legibility. If the command is too long for your system, you may need to place it in a .bat file (for Windows) or a .sh file (for UNIX) and then run that file to execute the command.

    Since the specified policy file contains an entry granting the code the required permission, JaasAcn will be allowed to instantiate a LoginContext and continue execution. You will be prompted for your Kerberos user name and password, and the underlying Kerberos authentication mechanism specified in the login configuration file will log you into Kerberos. If your login is successful, you will see the message "Authentication succeeded!" and if not, you will see "Authentication failed:" followed by a reason for the failure.

    For login troubleshooting suggestions, see Troubleshooting.

Tutorials Introduction and TOC
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL: Using Adapter Activators

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Using Adapter Activators

When creating a new POA, the application developer may declare specific policy choices for the new POA and provide a different adapter activator and servant manager (these are callback objects used by the POA to activate POAs on demand and activate servants). Creating new POAs also allows the application developer to partition the name space of objects, as Object Ids are interpreted relative to a POA. Finally, by creating new POAs, the developer can independently control request processing for multiple sets of objects.

An adapter activator is optional. You would use an adapter activator if POAs need to be created during request processing. If all needed POAs are created when the application is initialized, an adapter activator is not required.

An adapter activator supplies a POA with the ability to create child POAs on demand, as a side-effect of receiving a request that names the child POA (or one of its children), or when the find_POA method is called with an activate parameter value of TRUE. The ORB will invoke an operation on an adapter activator when a request is received for a child POA that does not currently exist. The adapter activator can then create the required POA on demand.

A request must be capable of conveying the Object Id of the target object as well as the identification of the POA that created the target object reference. When a client issues a request, the ORB first locates an appropriate server (perhaps starting one if needed) and then it locates the appropriate POA within that server.

If the POA does not exist in the server process, the application has the opportunity to re-create the required POA by using an adapter activator. An adapter activator is a user-implemented object that can be associated with a POA. It is invoked by the ORB when a request is received for a nonexistent child POA. The adapter activator has the opportunity to create the required POA. If it does not, the client receives the ADAPTER_NONEXISTENT exception.

Once the ORB has located the appropriate POA, it delivers the request to that POA. The further processing of that request depends both upon the policies associated with that POA as well as the object's current state of activation.

An Example Using Adapter Activators

The following example code shows an application that uses Adapter Activators to enable the POA to be created during request processing. This application builds on the "Hello World" example. The following files are included in this example:

  • Client.java
  • Server.java
  • Hello.idl
  • HelloServant.java
  • Makefile
  • run.bat

For instructions on running this example, see Running the Example Adapter Activator Application.

Client.java

The code for the example client initializes the ORB, resolves HelloServant, and invokes the sayHello() method.

//Client.java
import org.omg.CORBA.ORB;
import org.omg.CosNaming.NamingContext;
import org.omg.CosNaming.NamingContextHelper;
import org.omg.CosNaming.NameComponent;

public class Client {

    public void run(String[] args) {
        try {
            //initialize the orb
            ORB orb = ORB.init(args, null);
            System.out.println("ORB initialized");

            NamingContext namingContext = NamingContextHelper.narrow(
                orb.resolve_initial_references("NameService"));
            NameComponent[] nc = { new NameComponent("HelloServer", "") };

            //resolve HelloServant and invoke sayHello()
            Hello helloRef = HelloHelper.narrow(namingContext.resolve(nc));
            System.out.println("Resolved HelloServant");

            System.out.println(helloRef.sayHello());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new Client().run(args);
    }
}

Server.java

The code for the server does the following:

  • Initializes the ORB.
  • Resolve RootPOA.
  • Registers the adapter activator with rootPOA so that child POAs can be created on demand.
  • Runs find_POA with an activate parameter of TRUE to cause the adapter activator associated with rootPOA to be invoked if 'HelloPOA' does not exist.
  • Creates the object reference for HelloServant and registers it with the naming service.
  • Destroys 'HelloPOA'. This POA will be transparently recreated when the ORB receives a request on HelloPOA using the adapter activator we registered with the RootPOA.
  • Activates rootPOA.
  • Waits for incoming requests.
  • Creates MyAdapterActivator to create the POA with appropriate policies, associate the servant with the new POA, and activate the new POA.
//Server.java
import org.omg.CORBA.ORB;
import org.omg.CORBA.LocalObject;
import org.omg.CORBA.Policy;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;
import org.omg.PortableServer.AdapterActivator;
import org.omg.PortableServer.IdAssignmentPolicyValue;
import org.omg.PortableServer.LifespanPolicyValue;
import org.omg.PortableServer.ImplicitActivationPolicyValue;
import org.omg.CosNaming.NamingContext;
import org.omg.CosNaming.NamingContextHelper;
import org.omg.CosNaming.NameComponent;

public class Server {

    public void run(String[] args) {
        try {
            //initialize the orb
            ORB orb = ORB.init(args, null);
            System.out.println("ORB initialized");

            //resolve RootPOA
            POA rootPOA = POAHelper.narrow(
                orb.resolve_initial_references("RootPOA"));

            //register adapter activator with rootPOA so that child POAs can
            //be created on demand
            rootPOA.the_activator(new MyAdapterActivator());

            //find_POA with an activate parameter TRUE would cause the
            //adapter activator associated with rootPOA to be invoked if
            //'HelloPOA' does not exist
            POA childPOA = rootPOA.find_POA("HelloPOA", true);

            //Create the object reference for HelloServant
            //and register with naming service
            org.omg.CORBA.Object obj = childPOA.id_to_reference(
                "abcd".getBytes());
            Hello helloRef = HelloHelper.narrow(obj);

            NamingContext namingContext = NamingContextHelper.narrow(
                orb.resolve_initial_references("NameService"));
            NameComponent[] nc = { new NameComponent("HelloServer", "") };
            namingContext.rebind(nc, helloRef);

            //Destroy 'HelloPOA'. This POA will be transparently recreated when
            //ORB receives a request on HelloPOA using the adapter activator we
            //registered with the RootPOA
            childPOA.destroy(true, true);

            //activate rootPOA
            rootPOA.the_POAManager().activate();

            //wait for incoming requests
            System.out.println("Server ready and running....");
            orb.run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new Server().run(args);
    }
}

class MyAdapterActivator extends LocalObject implements AdapterActivator {

    public boolean unknown_adapter(POA parent, String name) {
        System.out.println("unknown_adapter() invoked for POA - " + name);
        try {
            // create the POA with appropriate policies
            // this sample uses PERSISTENT, NO_IMPLICIT_ACTIVATION
            // and USER_ID policies
            Policy[] policy = new Policy[3];
            policy[0] = parent.create_lifespan_policy(
                LifespanPolicyValue.PERSISTENT);
            policy[1] = parent.create_id_assignment_policy(
                IdAssignmentPolicyValue.USER_ID);
            policy[2] = parent.create_implicit_activation_policy(
                ImplicitActivationPolicyValue.NO_IMPLICIT_ACTIVATION);

            POA child = parent.create_POA(name, null, policy);

            //Associate the servant with the new POA
            HelloServant hello = new HelloServant();
            child.activate_object_with_id("abcd".getBytes(), hello);

            //activate the new POA
            child.the_POAManager().activate();

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}

Hello.idl

This Interface Definition Language (IDL) file is used in all of the "Hello World" example variations on this site. This IDL file describes a CORBA object whose sayHello() operation returns a string.
interface Hello { string sayHello(); };

HelloServant.java

The servant is the implementation of the Hello IDL interface; each Hello instance is implemented by a HelloServant instance. The servant is a subclass of HelloPOA, which is generated by the idlj compiler from the example IDL. The servant contains one method for each IDL operation, in this example, the sayHello() method. Servant methods are just like ordinary Java methods; the extra code to deal with the ORB, with marshaling arguments and results, and so on, is provided by the skeleton.
//HelloServant.java
public class HelloServant extends HelloPOA {

    public String sayHello() {
        return "Hello :)";
    }
}

Makefile

The make program generates a sequence of commands for execution by the Unix shell.

JAVA_HOME=<path_to_your_Java_installation_bin_directory>

#setup tools
JAVA=$(JAVA_HOME)/bin/java
JAVAC=$(JAVA_HOME)/bin/javac
IDLJ=$(JAVA_HOME)/bin/idlj
ORBD=$(JAVA_HOME)/bin/orbd

all     : clean build run

clean   :
        - rm -rf classes orb.db

build   :
        mkdir -p classes
        $(IDLJ) -fall -td classes Hello.idl
        $(JAVAC) -classpath classes -d classes HelloServant.java Server.java Client.java

run     : runorbd register runclient

runorbd :
        $(ORBD) -ORBInitialPort 10001 &
        sleep 20

register:
        #servertool does not support script based register due to a bug
        #using class instead
        #Please note that the name of the servertool
        #class may change in future releases.
        $(JAVA) com.sun.corba.se.internal.Activation.ServerTool \
        -ORBInitialPort 10001 -cmd \
        register -server Server -classpath classes

runclient :
        $(JAVA) -classpath classes Client -ORBInitialPort 10001

run.bat

The bat utility generates a sequence of commands for execution by the Microsoft Windows command shell.

SET JAVA_HOME=<path_to_your_Java_installation_build_directory>

mkdir classes

%JAVA_HOME%\bin\idlj -fall -td classes Hello.idl
%JAVA_HOME%\bin\javac -classpath classes -d classes HelloServant.java Server.java Client.java

REM - Start the ORB daemon

start %JAVA_HOME%\bin\orbd -ORBInitialPort 10001 -ORBDebug orbd
@echo Wait 10-15 seconds for the orbd to start
@pause

REM - Register the persistent server with orbd using servertool
REM - Please note that the name of the servertool
REM - class may change in future releases.
%JAVA_HOME%\bin\java com.sun.corba.se.internal.Activation.ServerTool -ORBInitialPort 10001 -cmd register -server Server -classpath classes

%JAVA_HOME%\bin\java -classpath classes Client -ORBInitialPort 10001

Running the Example Adapter Activator Application

To run this example,

  • Create the files using the code shown above.
  • Run the example using either of these methods:
    • If you have the Make utility, run the application using the Makefile:

      make all

    • If you have the batch utility, run the application using run.bat. From the application directory, enter:

      run

You will see output generated to the terminal window similar to that below when you run the Makefile:

rm -rf classes orb.db mkdir -p classes /j2sdk1.5.0/bin/idlj -fall -td classes Hello.idl /j2sdk1.5.0/bin/javac -classpath classes -d classes HelloServant.java Server.java Client.java /j2sdk1.5.0/bin/orbd -ORBInitialPort 10001 & sleep 20 #servertool does not support script based register due to a bug #using class instead #Please note that the name of the servertool
#class may change in future releases.
/j2sdk1.5.0/bin/java com.sun.corba.se.internal.Activation.ServerTool \
-ORBInitialPort 10001 -cmd \
register -server Server -classpath classes

        server registered (serverid = 257).

/j2sdk1.5.0/bin/java -classpath classes Client -ORBInitialPort 10001
ORB initialized
Resolved HelloServant
Hello :)
Shut down ORBD when you have completed this example.
  • If using the Unix operating system, type pkill orbd in the terminal window.
  • If using Microsoft Windows, enter Ctrl+C in the command prompt window.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Contents | Previous | Next

Chapter 4

Using JMX Agents

A Java Management Extensions (JMX) agent is a management entity that runs in a Java Virtual Machine (Java VM) and acts as the liaison between the MBeans and the management application. The various components of a JMX agent are outlined in the following sections:

  • "MBean Server"
  • "Agent Services"
  • "Protocol Adaptors and Connectors"

MBean Server

The MBean server is the core component of a JMX agent. It is a registry for objects that are exposed to management operations in an agent. Any object registered with the MBean server becomes visible to management applications. However, the MBean server only exposes the management interface of an MBean, never its direct object reference.

Any resource that you want to manage from outside the agent’s Java VM must be registered as an MBean in the server. The MBean server also provides a standardized interface for accessing MBeans within the same Java VM, giving local objects all the benefits of manipulating manageable resources. MBeans can be instantiated and registered by:

  • Another MBean
  • The agent itself
  • A remote management application

When you register an MBean, you must assign it a unique object name. A management application uses the object name to identify the object on which it is to perform a management operation. The operations available on MBeans include:

  • Discovering the management interface of MBeans
  • Reading and writing their attribute values
  • Performing operations defined by the MBeans
  • Getting notifications emitted by MBeans
  • Querying MBeans based on their object name or their attribute values

Agent Services

Agent services are objects that can perform management operations on the MBeans registered in the MBean server. By including management intelligence into the agent, JMX helps you build more powerful management solutions. Agent services are often MBeans as well, allowing them and their functionality to be controlled through the MBean server. The JMX specification defines the following agent services:

  • Dynamic class loading through the management applet (m-let) service retrieves and instantiates new classes and native libraries dynamically downloaded from the network.
  • Monitors observe the numerical or string value of MBean attributes and can notify other objects of several types of changes.
  • Timers provide a scheduling mechanism and can send notifications at predetermined intervals.
  • The relation service defines associations between MBeans and maintains the consistency of the relation.

Protocol Adaptors and Connectors

Protocol adaptors and connectors make the agent accessible from remote management applications. They provide a view through a specific protocol of the MBeans instantiated and registered in the MBean server. They enable a management application outside the Java VM to:

  • Get or set attributes of existing MBeans
  • Perform operations on existing MBeans
  • Instantiate and register new MBeans
  • Register for and receive notifications emitted by MBeans

Consequently, for a JMX agent to be manageable, it must include at least one protocol adaptor or connector. The Java SE platform includes the standard RMI connector. An agent can include any number of protocol adaptors and connectors, allowing it to be managed and monitored remotely through different protocols simultaneously.

Protocol Adaptors

Protocol adaptors provide a management view of the JMX agent through a given protocol. They adapt the operations of MBeans and the MBean server into a representation in the given protocol, and possibly into a different information model, for example SNMP. The Java SE platform does not include any protocol adaptors as standard.

Management applications that connect to a protocol adaptor are usually specific to the given protocol. This is typically the case for legacy management solutions that rely on a specific management protocol. They access the JMX agent not through a remote representation of the MBean server, but through operations that are mapped to those of the MBean server.

Connectors

Connectors are used to connect an agent with a remote management application enabled for JMX technology, namely, a management application developed using the distributed services of the JMX specification. This kind of communication involves a connector server in the agent and a connector client in the manager.

These components convey management operations transparently point-to-point over a specific protocol. The JMX Remote API provides a remote interface to the MBean server through which the management application can perform operations. A connector is specific to a given protocol, but the management application can use any connector indifferently because they have the same remote interface.

See Chapter 5, "Using JMX Connectors to Manage Resources Remotely" for more information on standard JMX connectors.

Contents | Previous | Next

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.tools.attach.AgentInitializationException (Attach API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Attach API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.tools.attach.AgentInitializationException

  • Packages that use AgentInitializationException
    Package Description
    com.sun.tools.attach
    Provides the API to attach to a JavaTM virtual machine.

    • Uses of AgentInitializationException in com.sun.tools.attach

      Methods in com.sun.tools.attach that throw AgentInitializationException
      Modifier and Type Method and Description
      void VirtualMachine.loadAgent(String agent)
      Loads an agent.
      abstract void VirtualMachine.loadAgent(String agent, String options)
      Loads an agent.
      void VirtualMachine.loadAgentLibrary(String agentLibrary)
      Loads an agent library.
      abstract void VirtualMachine.loadAgentLibrary(String agentLibrary, String options)
      Loads an agent library.
      void VirtualMachine.loadAgentPath(String agentPath)
      Load a native agent library by full pathname.
      abstract void VirtualMachine.loadAgentPath(String agentPath, String options)
      Load a native agent library by full pathname.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Attach API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.tools.attach.AgentLoadException (Attach API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Attach API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.tools.attach.AgentLoadException

  • Packages that use AgentLoadException
    Package Description
    com.sun.tools.attach
    Provides the API to attach to a JavaTM virtual machine.

    • Uses of AgentLoadException in com.sun.tools.attach

      Methods in com.sun.tools.attach that throw AgentLoadException
      Modifier and Type Method and Description
      void VirtualMachine.loadAgent(String agent)
      Loads an agent.
      abstract void VirtualMachine.loadAgent(String agent, String options)
      Loads an agent.
      void VirtualMachine.loadAgentLibrary(String agentLibrary)
      Loads an agent library.
      abstract void VirtualMachine.loadAgentLibrary(String agentLibrary, String options)
      Loads an agent library.
      void VirtualMachine.loadAgentPath(String agentPath)
      Load a native agent library by full pathname.
      abstract void VirtualMachine.loadAgentPath(String agentPath, String options)
      Load a native agent library by full pathname.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Attach API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.javadoc.AnnotationDesc (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.javadoc.AnnotationDesc

    • Uses of AnnotationDesc in com.sun.javadoc

      Methods in com.sun.javadoc that return AnnotationDesc
      Modifier and Type Method and Description
      AnnotationDesc[] ProgramElementDoc.annotations()
      Get the annotations of this program element.
      AnnotationDesc[] Parameter.annotations()
      Get the annotations of this parameter.
      AnnotationDesc[] PackageDoc.annotations()
      Get the annotations of this package.
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.javadoc.AnnotationDesc.ElementValuePair (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.javadoc.AnnotationDesc.ElementValuePair

    • Uses of AnnotationDesc.ElementValuePair in com.sun.javadoc

      Methods in com.sun.javadoc that return AnnotationDesc.ElementValuePair
      Modifier and Type Method and Description
      AnnotationDesc.ElementValuePair[] AnnotationDesc.elementValues()
      Returns this annotation's elements and their values.
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.declaration.AnnotationMirror (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.declaration.AnnotationMirror

  • Packages that use AnnotationMirror
    Package Description
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.

    • Uses of AnnotationMirror in com.sun.mirror.declaration

      Methods in com.sun.mirror.declaration that return types with arguments of type AnnotationMirror
      Modifier and Type Method and Description
      Collection<AnnotationMirror> Declaration.getAnnotationMirrors()
      Deprecated.
      Returns the annotations that are directly present on this declaration.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.apt.AnnotationProcessor (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.apt.AnnotationProcessor

  • Packages that use AnnotationProcessor
    Package Description
    com.sun.mirror.apt
    Classes used to communicate information between annotation processors and an annotation processing tool.

    • Uses of AnnotationProcessor in com.sun.mirror.apt

      Fields in com.sun.mirror.apt declared as AnnotationProcessor
      Modifier and Type Field and Description
      static AnnotationProcessor AnnotationProcessors.NO_OP
      Deprecated.
      An annotation processor that does nothing and has no state.
      Methods in com.sun.mirror.apt that return AnnotationProcessor
      Modifier and Type Method and Description
      static AnnotationProcessor AnnotationProcessors.getCompositeAnnotationProcessor(AnnotationProcessor... aps)
      Deprecated.
      Constructs a new composite annotation processor.
      static AnnotationProcessor AnnotationProcessors.getCompositeAnnotationProcessor(Collection<AnnotationProcessor> aps)
      Deprecated.
      Constructs a new composite annotation processor.
      AnnotationProcessor AnnotationProcessorFactory.getProcessorFor(Set<AnnotationTypeDeclaration> atds, AnnotationProcessorEnvironment env)
      Deprecated.
      Returns an annotation processor for a set of annotation types.
      Methods in com.sun.mirror.apt with parameters of type AnnotationProcessor
      Modifier and Type Method and Description
      static AnnotationProcessor AnnotationProcessors.getCompositeAnnotationProcessor(AnnotationProcessor... aps)
      Deprecated.
      Constructs a new composite annotation processor.
      Method parameters in com.sun.mirror.apt with type arguments of type AnnotationProcessor
      Modifier and Type Method and Description
      static AnnotationProcessor AnnotationProcessors.getCompositeAnnotationProcessor(Collection<AnnotationProcessor> aps)
      Deprecated.
      Constructs a new composite annotation processor.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.apt.AnnotationProcessorEnvironment (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.apt.AnnotationProcessorEnvironment

  • Packages that use AnnotationProcessorEnvironment
    Package Description
    com.sun.mirror.apt
    Classes used to communicate information between annotation processors and an annotation processing tool.

    • Uses of AnnotationProcessorEnvironment in com.sun.mirror.apt

      Methods in com.sun.mirror.apt that return AnnotationProcessorEnvironment
      Modifier and Type Method and Description
      AnnotationProcessorEnvironment RoundCompleteEvent.getSource()
      Deprecated.
      Return source.
      Methods in com.sun.mirror.apt with parameters of type AnnotationProcessorEnvironment
      Modifier and Type Method and Description
      AnnotationProcessor AnnotationProcessorFactory.getProcessorFor(Set<AnnotationTypeDeclaration> atds, AnnotationProcessorEnvironment env)
      Deprecated.
      Returns an annotation processor for a set of annotation types.
      Constructors in com.sun.mirror.apt with parameters of type AnnotationProcessorEnvironment
      Constructor and Description
      RoundCompleteEvent(AnnotationProcessorEnvironment source, RoundState rs)
      Deprecated.
      The current AnnotationProcessorEnvironment is regarded as the source of events.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.apt.AnnotationProcessorFactory (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.apt.AnnotationProcessorFactory

No usage of com.sun.mirror.apt.AnnotationProcessorFactory
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.apt.AnnotationProcessorListener (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.apt.AnnotationProcessorListener

  • Packages that use AnnotationProcessorListener
    Package Description
    com.sun.mirror.apt
    Classes used to communicate information between annotation processors and an annotation processing tool.

    • Uses of AnnotationProcessorListener in com.sun.mirror.apt

      Subinterfaces of AnnotationProcessorListener in com.sun.mirror.apt
      Modifier and Type Interface and Description
      interface  RoundCompleteListener
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. This interface has no direct analog in the standardized API because the different round model renders it unnecessary.
      Methods in com.sun.mirror.apt with parameters of type AnnotationProcessorListener
      Modifier and Type Method and Description
      void AnnotationProcessorEnvironment.addListener(AnnotationProcessorListener listener)
      Deprecated.
      Add a listener.
      void AnnotationProcessorEnvironment.removeListener(AnnotationProcessorListener listener)
      Deprecated.
      Remove a listener.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.mirror.apt.AnnotationProcessors (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.mirror.apt.AnnotationProcessors

No usage of com.sun.mirror.apt.AnnotationProcessors
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Annotations

Many APIs require a fair amount of boilerplate code. For example, in order to write a JAX-RPC web service, you must provide a paired interface and implementation. This boilerplate could be generated automatically by a tool if the program were “decorated” with annotations indicating which methods were remotely accessible.

Other APIs require “side files” to be maintained in parallel with programs. For example JavaBeans requires a BeanInfo class to be maintained in parallel with a bean, and Enterprise JavaBeans (EJB) requires a deployment descriptor. It would be more convenient and less error-prone if the information in these side files were maintained as annotations in the program itself.

The Java platform has always had various ad hoc annotation mechanisms. For example the transient modifier is an ad hoc annotation indicating that a field should be ignored by the serialization subsystem, and the @deprecated javadoc tag is an ad hoc annotation indicating that the method should no longer be used. As of release 5.0, the platform has a general purpose annotation (also known as metadata) facility that permits you to define and use your own annotation types. The facility consists of a syntax for declaring annotation types, a syntax for annotating declarations, APIs for reading annotations, a class file representation for annotations, and an annotation processing tool.

Annotations do not directly affect program semantics, but they do affect the way programs are treated by tools and libraries, which can in turn affect the semantics of the running program. Annotations can be read from source files, class files, or reflectively at run time.

Annotations complement javadoc tags. In general, if the markup is intended to affect or produce documentation, it should probably be a javadoc tag; otherwise, it should be an annotation.

Typical application programmers will never have to define an annotation type, but it is not hard to do so. Annotation type declarations are similar to normal interface declarations. An at-sign (@) precedes the interface keyword. Each method declaration defines an element of the annotation type. Method declarations must not have any parameters or a throws clause. Return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types. Methods can have default values. Here is an example annotation type declaration:

/**
 * Describes the Request-For-Enhancement(RFE) that led
 * to the presence of the annotated API element.
 */
public @interface RequestForEnhancement {
    int    id();
    String synopsis();
    String engineer() default "[unassigned]";
    String date()    default "[unimplemented]";
}

Once an annotation type is defined, you can use it to annotate declarations. An annotation is a special kind of modifier, and can be used anywhere that other modifiers (such as public, static, or final) can be used. By convention, annotations precede other modifiers. Annotations consist of an at-sign (@) followed by an annotation type and a parenthesized list of element-value pairs. The values must be compile-time constants. Here is a method declaration with an annotation corresponding to the annotation type declared above:

@RequestForEnhancement(
    id       = 2868724,
    synopsis = "Enable time-travel",
    engineer = "Mr. Peabody",
    date     = "4/1/3007"
)
public static void travelThroughTime(Date destination) { ... }

An annotation type with no elements is termed a marker annotation type, for example:

/**
 * Indicates that the specification of the annotated API element
 * is preliminary and subject to change.
 */
public @interface Preliminary { }

It is permissible to omit the parentheses in marker annotations, as shown below:

@Preliminary public class TimeTravel { ... }

In annotations with a single element, the element should be named value, as shown below:

/**
 * Associates a copyright notice with the annotated API element.
 */
public @interface Copyright {
    String value();
}

It is permissible to omit the element name and equals sign (=) in a single-element annotation whose element name is value, as shown below:

@Copyright("2002 Yoyodyne Propulsion Systems")
public class OscillationOverthruster { ... }

To tie it all together, we'll build a simple annotation-based test framework. First we need a marker annotation type to indicate that a method is a test method, and should be run by the testing tool:

import java.lang.annotation.*;

/**
 * Indicates that the annotated method is a test method.
 * This annotation should be used only on parameterless static methods.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test { }

Note that the annotation type declaration is itself annotated. Such annotations are called meta-annotations. The first (@Retention(RetentionPolicy.RUNTIME)) indicates that annotations with this type are to be retained by the VM so they can be read reflectively at run-time. The second (@Target(ElementType.METHOD)) indicates that this annotation type can be used to annotate only method declarations.

Here is a sample program, some of whose methods are annotated with the above interface:

public class Foo {
    @Test public static void m1() { }
    public static void m2() { }
    @Test public static void m3() {
        throw new RuntimeException("Boom");
    }
    public static void m4() { }
    @Test public static void m5() { }
    public static void m6() { }
    @Test public static void m7() {
        throw new RuntimeException("Crash");
    }
    public static void m8() { }
}

Here is the testing tool:

import java.lang.reflect.*;

public class RunTests {
   public static void main(String[] args) throws Exception {
      int passed = 0, failed = 0;
      for (Method m : Class.forName(args[0]).getMethods()) {
         if (m.isAnnotationPresent(Test.class)) {
            try {
               m.invoke(null);
               passed++;
            } catch (Throwable ex) {
               System.out.printf("Test %s failed: %s %n", m, ex.getCause());
               failed++;
            }
         }
      }
      System.out.printf("Passed: %d, Failed %d%n", passed, failed);
   }
}

The tool takes a class name as a command line argument and iterates over all the methods of the named class attempting to invoke each method that is annotated with the Test annotation type (defined above). The reflective query to find out if a method has a Test annotation is highlighted in green. If a test method invocation throws an exception, the test is deemed to have failed, and a failure report is printed. Finally, a summary is printed showing the number of tests that passed and failed. Here is how it looks when you run the testing tool on the Foo program (above):

$ java RunTests Foo
Test public static void Foo.m3() failed: java.lang.RuntimeException: Boom
Test public static void Foo.m7() failed: java.lang.RuntimeException: Crash
Passed: 2, Failed 2
While this testing tool is clearly a toy, it demonstrates the power of annotations and could easily be extended to overcome its limitations.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.source.tree.AnnotationTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.AnnotationTree

  • Packages that use AnnotationTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of AnnotationTree in com.sun.source.tree

      Methods in com.sun.source.tree that return types with arguments of type AnnotationTree
      Modifier and Type | Method and Description
      List<? extends AnnotationTree> | ModifiersTree.getAnnotations()
      List<? extends AnnotationTree> | CompilationUnitTree.getPackageAnnotations()
      Methods in com.sun.source.tree with parameters of type AnnotationTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitAnnotation(AnnotationTree node, P p)

    • Uses of AnnotationTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type AnnotationTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitAnnotation(AnnotationTree node, P p)
      R | SimpleTreeVisitor.visitAnnotation(AnnotationTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.type.AnnotationType (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.type.AnnotationType

  • Packages that use AnnotationType
    Package Description
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of AnnotationType in com.sun.mirror.declaration

      Methods in com.sun.mirror.declaration that return AnnotationType
      Modifier and Type Method and Description
      AnnotationType AnnotationMirror.getAnnotationType()
      Deprecated.
      Returns the annotation type of this annotation.

    • Uses of AnnotationType in com.sun.mirror.util

      Methods in com.sun.mirror.util with parameters of type AnnotationType
      Modifier and Type Method and Description
      void TypeVisitor.visitAnnotationType(AnnotationType t)
      Deprecated.
      Visits an annotation type.
      void SimpleTypeVisitor.visitAnnotationType(AnnotationType t)
      Deprecated.
      Visits an annotation type.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.declaration.AnnotationTypeDeclaration (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.declaration.AnnotationTypeDeclaration

  • Packages that use AnnotationTypeDeclaration
    Package Description
    com.sun.mirror.apt
    Classes used to communicate information between annotation processors and an annotation processing tool.
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.
    com.sun.mirror.type
    Interfaces used to model types.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of AnnotationTypeDeclaration in com.sun.mirror.apt

      Methods in com.sun.mirror.apt with parameters of type AnnotationTypeDeclaration
      Modifier and Type Method and Description
      Collection<Declaration> AnnotationProcessorEnvironment.getDeclarationsAnnotatedWith(AnnotationTypeDeclaration a)
      Deprecated.
      Returns the declarations annotated with the given annotation type.
      Method parameters in com.sun.mirror.apt with type arguments of type AnnotationTypeDeclaration
      Modifier and Type Method and Description
      AnnotationProcessor AnnotationProcessorFactory.getProcessorFor(Set<AnnotationTypeDeclaration> atds, AnnotationProcessorEnvironment env)
      Deprecated.
      Returns an annotation processor for a set of annotation types.

    • Uses of AnnotationTypeDeclaration in com.sun.mirror.declaration

      Methods in com.sun.mirror.declaration that return AnnotationTypeDeclaration
      Modifier and Type Method and Description
      AnnotationTypeDeclaration AnnotationTypeElementDeclaration.getDeclaringType()
      Deprecated.
      Returns the type declaration within which this member or constructor is declared.
      Methods in com.sun.mirror.declaration that return types with arguments of type AnnotationTypeDeclaration
      Modifier and Type Method and Description
      Collection<AnnotationTypeDeclaration> PackageDeclaration.getAnnotationTypes()
      Deprecated.
      Returns the declarations of the top-level annotation types in this package.

    • Uses of AnnotationTypeDeclaration in com.sun.mirror.type

      Methods in com.sun.mirror.type that return AnnotationTypeDeclaration
      Modifier and Type Method and Description
      AnnotationTypeDeclaration AnnotationType.getDeclaration()
      Deprecated.
      Returns the declaration of this type.

    • Uses of AnnotationTypeDeclaration in com.sun.mirror.util

      Methods in com.sun.mirror.util with parameters of type AnnotationTypeDeclaration
      Modifier and Type Method and Description
      void SimpleDeclarationVisitor.visitAnnotationTypeDeclaration(AnnotationTypeDeclaration d)
      Deprecated.
      Visits an annotation type declaration.
      void DeclarationVisitor.visitAnnotationTypeDeclaration(AnnotationTypeDeclaration d)
      Deprecated.
      Visits an annotation type declaration.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.javadoc.AnnotationTypeDoc (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.javadoc.AnnotationTypeDoc

    • Uses of AnnotationTypeDoc in com.sun.javadoc

      Methods in com.sun.javadoc that return AnnotationTypeDoc
      Modifier and Type Method and Description
      AnnotationTypeDoc AnnotationDesc.annotationType()
      Returns the annotation type of this annotation.
      AnnotationTypeDoc[] PackageDoc.annotationTypes()
      Get included annotation types in this package.
      AnnotationTypeDoc Type.asAnnotationTypeDoc()
      Return this type as an AnnotationTypeDoc if it represents an annotation type.
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.declaration.AnnotationTypeElementDeclaration (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.declaration.AnnotationTypeElementDeclaration

  • Packages that use AnnotationTypeElementDeclaration
    Package Description
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of AnnotationTypeElementDeclaration in com.sun.mirror.declaration

      Methods in com.sun.mirror.declaration that return types with arguments of type AnnotationTypeElementDeclaration
      Modifier and Type Method and Description
      Map<AnnotationTypeElementDeclaration,AnnotationValue> AnnotationMirror.getElementValues()
      Deprecated.
      Returns this annotation's elements and their values.
      Collection<AnnotationTypeElementDeclaration> AnnotationTypeDeclaration.getMethods()
      Deprecated.
      Returns the annotation type elements of this annotation type.

    • Uses of AnnotationTypeElementDeclaration in com.sun.mirror.util

      Methods in com.sun.mirror.util with parameters of type AnnotationTypeElementDeclaration
      Modifier and Type Method and Description
      void SimpleDeclarationVisitor.visitAnnotationTypeElementDeclaration(AnnotationTypeElementDeclaration d)
      Deprecated.
      Visits an annotation type element declaration.
      void DeclarationVisitor.visitAnnotationTypeElementDeclaration(AnnotationTypeElementDeclaration d)
      Deprecated.
      Visits an annotation type element declaration.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.javadoc.AnnotationTypeElementDoc (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.javadoc.AnnotationTypeElementDoc

    • Uses of AnnotationTypeElementDoc in com.sun.javadoc

      Methods in com.sun.javadoc that return AnnotationTypeElementDoc
      Modifier and Type Method and Description
      AnnotationTypeElementDoc AnnotationDesc.ElementValuePair.element()
      Returns the annotation type element.
      AnnotationTypeElementDoc[] AnnotationTypeDoc.elements()
      Returns the elements of this annotation type.
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.declaration.AnnotationValue (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.declaration.AnnotationValue

  • Packages that use AnnotationValue
    Package Description
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.

    • Uses of AnnotationValue in com.sun.mirror.declaration

      Methods in com.sun.mirror.declaration that return AnnotationValue
      Modifier and Type Method and Description
      AnnotationValue AnnotationTypeElementDeclaration.getDefaultValue()
      Deprecated.
      Returns the default value of this element.
      Methods in com.sun.mirror.declaration that return types with arguments of type AnnotationValue
      Modifier and Type Method and Description
      Map<AnnotationTypeElementDeclaration,AnnotationValue> AnnotationMirror.getElementValues()
      Deprecated.
      Returns this annotation's elements and their values.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Input Method Client API Reference

The following classes are part of the input method client API:

  • java.awt.event
    • java.awt.event.InputMethodEvent
    • java.awt.event.InputMethodListener
  • java.awt.im
    • java.awt.im.InputContext
    • java.awt.im.InputMethodHighlight
    • java.awt.im.InputMethodRequests
    • java.awt.im.InputSubset

    In addition, the following classes and members in other frameworks support the input method client API:

  • java.awt
    • java.awt.AWTEvent
      • INPUT_METHOD_EVENT_MASK
    • java.awt.AWTEventMulticaster
      • add(InputMethodListener, InputMethodListener)
      • caretPositionChanged(InputMethodEvent)
      • inputMethodTextChanged(InputMethodEvent)
      • remove(InputMethodListener, InputMethodListener)
    • java.awt.Component
      • addInputMethodListener(InputMethodListener)
      • enableInputMethods(boolean)
      • getInputContext()
      • getInputMethodRequests()
      • processInputMethodEvent(InputMethodEvent)
      • removeInputMethodListener(InputMethodListener)
    • java.awt.Graphics
      • drawString(AttributedCharacterIterator, int, int)
    • java.awt.Toolkit
      • mapInputMethodHighlight
    • java.awt.Window
      • getInputContext()
  • java.awt.font
    • java.awt.font.TextAttribute
      • INPUT_METHOD_UNDERLINE
      • UNDERLINE_LOW_ONE_PIXEL
      • UNDERLINE_LOW_TWO_PIXEL
      • UNDERLINE_LOW_DOTTED
      • UNDERLINE_LOW_GRAY
      • UNDERLINE_LOW_DASHED
  • java.lang
    • java.lang.Character.Subset
  • java.text
    • java.text.Annotation
    • java.text.AttributedCharacterIterator
    • java.text.AttributedCharacterIterator.Attribute
    • java.text.AttributedString

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Input Method Client API Tutorial

Contents

  1. Implementing an Active Client Component
    • Handling Input Method Events
    • Handling Input Method Highlight Attributes
    • Handling Input Method Requests
    • Ending Input Operations
  2. Enhancing an Active Client Component
    • Handling Additional Text Attributes
    • Creating Private Input Contexts
    • Selecting Input Methods
    • Setting an Expected Character Subset
    • Using Engine-Specific Functionality
  3. Implementing a Non-Client
  4. Sample Code

1. Implementing an Active Client Component

The input method client API makes it possible for client components to implement integrated text input user interfaces such as on-the-spot input. The API defines events and methods that facilitate the communication between a client component and an input method. It also lets the client component request an input method for a particular language.

Since the API doesn't make any assumptions about how and where the text is drawn, it can also be used to implement other input styles such as over-the-spot editing. In this style, the composed text is drawn over surrounding text and covers it instead of being integrated and formatted with it.

Any client component class can become an active client of the input method client API and thus support an integrated text input user interface by performing the following steps:

  • Implement the InputMethodListener interface to handle incoming InputMethodEvents generated by the current input method, and register the listener.
  • Implement the InputMethodRequests interface and override getInputMethodRequests to return the request handler.
  • Store InputMethodHighlight attributes along with composed text and pass them on to the drawing routines.
  • End input operations when the user initiates an operation that requires all text to be committed.

Optionally, the client component can also use the following functionality:

  • Store other text attributes that are created by input methods, and return them when text is requested.
  • Create a private input context (instead of sharing one with other components in the same window).
  • Select input methods, for example, based on the language of the text being edited.
  • Set an expected character subset.

Client components don't need to deal with setting up input contexts, activating or deactivating contexts, or dispatching events to input methods, since all this is handled automatically by AWT.

Handling Input Method Events

The input method framework provides an event class, InputMethodEvent, to support the communication between input methods and text components. The class has two separate event kinds: text changed and caret changed. An event listener interface, InputMethodListener, supports these two events. An active client component must implement the InputMethodListener interface, register the listener, and handle both kinds of events.

InputMethodEvent instances are sent to the client component when there is a change to the user's input text, its highlighting, or to the caret location within the composed text. The event sent for caret-only changes is a simplified version of the one for text changes (it just doesn't have text information), so the following discussion assumes the text-changed event.

An event reporting a text change has a reference to an instance of AttributedCharacterIterator that represents either composed text or committed text or both together. The event's committed character count value specifies how many characters in the iterator's range are committed text; all remaining characters are composed text. Committed text always precedes composed text. If the component has no previous composed text, the committed and composed text replace any selected text or are inserted at the current insertion position of the component's text. If there is previous composed text, the entire previous composed text is replaced with the new committed and composed text. The insertion point moves to the end of the committed text. The client component is responsible for redrawing the updated text.

The event also contains information about the current caret location within the composed text (null if no caret is to be displayed), and about the part of the composed text that is most important to keep in view (null if the input method doesn't have a recommendation).

Handling Input Method Highlight Attributes

The text component generally draws the composed text as part of the text being edited, using its regular text layout and drawing functionality. However, it needs to add certain highlight style attributes to the composed text to indicate the current state of the composition. The framework defines these style attributes as abstract styles (for example, "unconverted unselected text" or "converted selected text"), and maps them internally to platform-dependent concrete styles (for example, 2-pixel gray underline).

Highlight attributes are represented by the InputMethodHighlight class. Instances of this class are used as attribute values of the AttributedCharacterIterator instances representing composed text. Text components must store these attributes with the composed text and pass them on to the drawing routines when drawing composed text. They can use either the drawString methods that accept AttributedCharacterIterator, or create a TextLayout from the iterator and use its draw method. These drawing methods interact with the input method framework to map abstract to concrete highlight styles. Text components using these methods therefore generally do not need to be concerned with the internal details of the input method highlights. If a text component uses some other mechanism to render the text, it should check the input method highlight for concrete style information, and, if none is provided, use Toolkit.mapInputMethodHighlight to map to a concrete style.

Some input methods may treat highlights as "annotations". Annotations are attributes that apply to a specified range of text, but not to subranges or the concatenation of ranges. They are represented by wrapping the InputMethodHighlight instance into an Annotation instance. Input methods may use annotation highlights to separate text segments that will be converted as separate units. On some platforms, these highlights are rendered so as to make the segments visible, for example, by using underlines with short breaks between the segments. Text components have to be able to handle input method highlights whether they are wrapped in Annotation instances or not. If a text component implements line wrapping, special care needs to be taken when the range to which a highlight annotation applies crosses a line boundary: The normal behavior (implemented, for example, in AttributedString) would be to discard the attribute because it doesn't apply to subranges. But, since in this case there's only a visual break and not a logical break, the highlight needs to be preserved - it has to be treated as if it applied to the subranges that are rendered on separate lines. One way to do this is by implementing the AttributedCharacterIterator in a way that returns highlight annotations even for subranges of the intended range.

Handling Input Method Requests

An input method needs to access component information to perform input operations. For example, an input method needs to know the location where a list of possible choices can be shown.

An active client component therefore must implement the InputMethodRequests interface, and override getInputMethodRequests to return the request handler. The interface includes methods to:

  • Perform conversions between screen coordinates and offsets within the composed text.
  • Obtain specified text of the component.
  • Cancel the latest committed text.
  • Obtain the insertion position within the component's committed text.

Ending Input Operations

Input methods typically recognize some user actions that end input operations, for example, an operation that commits all uncommitted text. However, there are also user actions that start operations for which input operations should be ended, but that an input method cannot recognize. Saving the document containing the text is one such example. In these cases, the component has to explicitly call the input context's endComposition method.

2. Enhancing an Active Client Component

Handling Additional Text Attributes

In addition to the input method highlight information, input methods may also attach other attributes to the text they send to a text component. These attributes may be useful information for the component. They may also improve the input method's performance if returned by the InputMethodRequest methods. For the latter reason, it is recommended that text components keep this attribute information around while the text is being edited, and return it with any text requested.

The AttributedCharacterIterator.Attribute class defines the following common attributes:

  • LANGUAGE - the language of the text, specified as a Locale object.
  • READING - a phonetic representation (yomi in Japanese), specified as a String object.
  • INPUT_METHOD_SEGMENT - segmentation information used by input methods.

Input methods written in the Java programming language may define additional attributes.

Creating Private Input Contexts

By default, one InputContext instance is created per Window instance, and this input context is shared by all components within the window's containment hierarchy. This reduces the number of instances created overall, and lets input methods combine information about all the text entered in this window (input methods often use information about previously entered text to improve their conversion accuracy). It means, however, that only one input operation is possible at any one time within a window, and that the text needs to be committed when moving the focus from one text component to another. If this is not desired, text components can create their own input context instances and override getInputContext to return them. A component that doesn't have its own input context uses the one used by its parent.

Selecting Input Methods

Text components can use the input context's selectInputMethod operation to select an input method for a given language or locale. This may be helpful, for example, if the user clicks in text that is written in that language, since it's likely that she wants to continue in the same language. Or, the text component may know that the application only allows text in a certain language to be entered.

Setting an Expected Character Subset

Text components can use the input context's setCharacterSubsets operation to tell input methods which characters can be meaningfully entered. For example, a database application may know that certain fields should only receive input in hiragana (one of the syllabic subscripts used in Japanese), another one only Latin characters, a third one any kind of characters. Passing on this information to input methods may allow the input methods to limit the range of characters that can be entered, or to switch to a different input mode that particularly supports the specified character subsets.

Using Engine-Specific Functionality

Some input methods may provide functionality to client components that can not be made available through the input method framework API. This is possible through input method control objects. The input method developer must publish an interface for these objects. Client components that want to take advantage of the additional functionality can then call InputContext.getInputMethodControlObject, check whether the returned object is an instance of a known control object class, and if it is, call its methods.

3. Implementing a Non-Client

By default, all components that process key events are clients of the input method framework, that is, input method support is enabled for them. In some cases, components may not want to have their input processed by input methods. For example, games may want to interpret keyboard events directly. These components should call enableInputMethods(false), so that events do not get forwarded to input methods.

4. Sample Code

This sample code shows how to implement the different kinds of input method clients that are possible with the input method framework: an active client, a passive client, a non-client, and a peered text component.

  • Applet - run this applet in a Java 2 enabled browser, and you can experiment with the different client components.
  • Source Code
    • IMFDemo.java - the applet/application that contains the different client components.
    • LWTextComponent.java - a lightweight text editing component that doesn't know about input methods, but can be extended to an active client.
    • ActiveClient.java - extends LWTextComponent to become an active client component.
    • PeeredTextArea.java - a peered text component.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Code Overview: AudioSystem.java

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

< Contents

Appendix 1: Code Overview: AudioSystem.java

For the benefit of service providers and API implementers, a brief overview of the Java Sound source code is provided.

javax.sound.sampled.AudioSystem is the entry point to JavaSound for obtaining resources; i.e., mixers, lines, etc. And each method of AudioSystem involves getting the providers of some service—MixerProvider[], FormatConversionProvider[], AudioFileReader[], or AudioFileWriter[]. Then the method goes on to obtain some specific information or perform some task. There is much similarity in how these methods work. Let us take a look at how getMixerInfo() works.

The following is a sequence diagram of getMixerInfo() in AudioSystem.java:

Sequence diagram of getMixerInfo() in AudioSystem.java

getMixerInfo() in AudioSystem first calls getMixerProviders(), a private static method of AudioSystem. The first thing that getMixerProviders() does is attempt to load sun.misc.Service. If an exception is thrown, it means that a pre-1.3 JRE is in use and there is no service provider lookup mechanism present. If an exception is thrown, then sun.media.sound.DefaultServices is used to obtain service providers (not depicted in above diagram). If the 1.3 mechanims is present, then getJDK13Serives() is called (shown above) with "javax.sound.sampled.spi.MixerProvider" as the argument.

getJDK13Services() is another private static method of AudioSystem. It attempts to the load the class for "com.sun.media.sound.JDK13Services", and if it succeeds it set Class jdk13Services equal to it. A bit of trickery is then performed by using Class.getMethod() to get the getProviders() method of jdk13Services, which is returned as object Method m. The method is then invoked, which has the effect of invoking getProviders("javax.sound.sampled.spi.MixerProvider") on JDK13Services. This in turn uses the providers() method of sun.misc.Service to return a vector of mixer providers, MixerProvider[]. The getMixerInfo() method of MixerProvider is then called on each element of the vector to return info (Mixer.info) for all mixers of all mixer providers.

Other services are handled in a similar way. For
instance, getTargetEncodings() calls
getFormatConversionProviders(),
getAudioFileFormat() calls
getAudioFileReaders(), etc., which are similarly
structured to getMixerProviders().

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Code Overview: AudioSystem.java

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

< Contents

Appendix 2: sound.properties File

The Java Sound Configuration file, sound.properties, can be used to specify default service providers for javax.sound.sampled.AudioSystem and javax.sound.midi.MidiSystem.

Properties Keys

The following keys are recognized by AudioSystem methods:

javax.sound.sampled.Clip
javax.sound.sampled.Port
javax.sound.sampled.SourceDataLine
javax.sound.sampled.TargetDataLine

The following keys are recognized by MidiSystem methods:

javax.sound.midi.Sequencer
javax.sound.midi.Synthesizer
javax.sound.midi.Transmitter
javax.sound.midi.Receiver

The values should specify the full class name of the service provider and/or the device name.

sound.properties is located at $JAVAHOME/jre/lib in the Sun implementation.

For more details, see the class descriptions for AudioSystem and MidiSystem.

Examples

To use MyDeviceProvider as the default for SourceDataLine lines, set the following key:

javax.sound.sampled.SourceDataLine=com.xyz.MyDeviceProvider

To specify the default Synthesizer by its name InternalSynth, set the following key:

javax.sound.midi.Synthesizer=#InternalSynth

To specify the default Receiver by provider and name, set the following key:

javax.sound.midi.Receiver=com.sun.media.sound.MidiProvider#SunMIDI1

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
bgcolor="#FFFFFF">
CONTENTS | PREV | NEXT

Appendix B:

Examples for LDAP Programmers

This appendix contains sample JNDI programs intended to help a developer familiar with the LDAP C API. Starting with sample programs from the Netscape Directory SDK for accessing and updating the directory using the LDAP C API, we show the equivalent way of doing the same thing for Java applications using JNDI.

B.1 Search the Directory

B.2 Read An Entry

B.3 Get Attributes

B.4 Compare An Attribute

B.5 Modify Attributes

B.6 Rename An Entry

CONTENTS | PREV | NEXT

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


B.1 Search the Directory

B.1.1 Search Using LDAP C API B.1.2 Search Using JNDI

B.1.1 Search Using LDAP C API

/*
* Copyright (c) 1996. Netscape Communications Corporation. All
* rights reserved.
*
* Search the directory for all people whose surname (last name) is
* “Jensen”. Since the “sn” attribute is a caseignorestring (cis), case
* is not significant when searching.
*
*/

#include “examples.h”

int
main( int argc, char **argv )
{
LDAP *ld;
LDAPMessage *result, *e;
BerElement *ber;
char *a, *dn;
char **vals;
int i;

/* get a handle to an LDAP
connection */
if ( (ld = ldap_init( MY_HOST, MY_PORT )) == NULL ) {
perror( “ldap_init” );
return( 1 );
}
/* authenticate to the directory as nobody */
if ( ldap_simple_bind_s( ld, NULL, NULL ) != LDAP_SUCCESS ) {
ldap_perror( ld, “ldap_simple_bind_s” );
return( 1 );
}
/* search for all entries with surname of Jensen */
if ( ldap_search_s( ld, MY_SEARCHBASE, LDAP_SCOPE_SUBTREE,
MY_FILTER, NULL, 0, &result ) != LDAP_SUCCESS ) {
ldap_perror( ld, “ldap_search_s” );
return( 1 );
}
/* for each entry print out name + all attrs and values */
for ( e = ldap_first_entry( ld, result ); e != NULL;
e = ldap_next_entry( ld, e ) ) {
if ( (dn = ldap_get_dn( ld, e )) != NULL ) {
printf( “dn: %s\n”, dn );
ldap_memfree( dn );
}
for ( a = ldap_first_attribute( ld, e, &ber );
a != NULL; a = ldap_next_attribute( ld, e, ber ) ) {
if ((vals = ldap_get_values( ld, e, a)) != NULL ) {
for ( i = 0; vals[i] != NULL; i++ ) {
printf( “%s: %s\n”, a, vals[i] );
}
ldap_value_free( vals );
}
ldap_memfree( a );
}
if ( ber != NULL ) {
ber_free( ber, 0 );
}
printf( “\n” );
}
ldap_msgfree( result );
ldap_unbind( ld );
return( 0 );
}

B.1.2 Search Using JNDI

/*
 * Copyright (c) 1999 Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.util.Hashtable;
import java.util.Enumeration;
import javax.naming.*;
import javax.naming.directory.*;
/*
 * Search the directory for all people whose surname (last name) is
 * "Jensen".  Since the "sn" attribute is a caseignorestring (cis), case
 * is not significant when searching.
 *
 * [equivalent to search.c in Netscape's SDK.]
 *
 */
class Search {
public static void main(String[] args) {
    Hashtable env = new Hashtable(5, 0.75f);
    /*
     * Specify the initial context implementation to use.
     * This could also be set by using the -D option to the java program.
     * For example,
     *   java -Djava.naming.factory.initial=com.sun.jndi.ldap.LdapCtxFactory \
     *     Search
     */
    env.put(Context.INITIAL_CONTEXT_FACTORY, Env.INITCTX);
    /* Specify host and port to use for directory service */
    env.put(Context.PROVIDER_URL, Env.MY_SERVICE);
    try {
        /* get a handle to an Initial DirContext */
        DirContext ctx = new InitialDirContext(env);
        /* specify search constraints to search subtree */
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        /* search for all entries with surname of Jensen */
        NamingEnumeration results
            = ctx.search(Env.MY_SEARCHBASE, Env.MY_FILTER, constraints);
        /* for each entry print out name + all attrs and values */
        while (results != null && results.hasMore()) {
            SearchResult si = (SearchResult)results.next();
            /* print its name */
            System.out.println("name: " + si.getName());
            Attributes attrs = si.getAttributes();
            if (attrs == null) {
                System.out.println("No attributes");
            } else {
                /* print each attribute */
                for (NamingEnumeration ae = attrs.getAll();
                     ae.hasMoreElements();) {
                    Attribute attr = (Attribute)ae.next();
                    String attrId = attr.getID();
                    /* print each value */
                    for (Enumeration vals = attr.getAll();
                         vals.hasMoreElements();
                         System.out.println(attrId + ": " + vals.nextElement()))
                            ;
                }
            }
            System.out.println();
        }
    } catch (NamingException e) {
        System.err.println("Search example failed.");
        e.printStackTrace();
    }
}
}

CONTENTS | PREV | NEXT

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


B.2 Read An Entry

B.2.1 Read Using LDAP C-API B.2.2 Read Using JNDI

B.2.1 Read Using LDAP C-API

/*
 * Copyright (c) 1996.  Netscape Communications Corporation.  All
 * rights reserved.
 *
 * Search the directory for the specific entry
 * "e;cn=Barbara Jensen, ou=Product Development, o=Ace Industry, c=US”.
 * Retrieve all attributes from the entry.
 *
 */
#include "e;examples.h”
int
main( int argc, char **argv )
{
    LDAP        *ld;
    LDAPMessage *result, *e;
    BerElement  *ber;
    char        *a, *dn;
    char        **vals;
    int         i;
    /* get a handle to an LDAP connection */
    if ( (ld = ldap_init( MY_HOST, MY_PORT )) == NULL ) {
        perror( "e;ldap_init” );
        return( 1 );
    }
    /* authenticate to the directory as nobody */
    if ( ldap_simple_bind_s( ld, NULL, NULL ) != LDAP_SUCCESS ) {
        ldap_perror( ld, "e;ldap_simple_bind_s” );
        return( 1 );
    }
    /* search for Babs’ entry */
    if ( ldap_search_s( ld, ENTRYDN, LDAP_SCOPE_SUBTREE,
            "e;(objectclass=*)”, NULL, 0, &result ) != LDAP_SUCCESS ) {
        ldap_perror( ld, "e;ldap_search_s” );
        return( 1 );
    }
    /* for each entry print out name + all attrs and values */
    for ( e = ldap_first_entry( ld, result ); e != NULL;
            e = ldap_next_entry( ld, e ) ) {
        if ( (dn = ldap_get_dn( ld, e )) != NULL ) {
            printf( "e;dn: %s\n”, dn );
            ldap_memfree( dn );
        }
        for ( a = ldap_first_attribute( ld, e, &ber );
                a != NULL; a = ldap_next_attribute( ld, e, ber ) ) {
            if ((vals = ldap_get_values( ld, e, a)) != NULL ) {
                for ( i = 0; vals[i] != NULL; i++ ) {
                    printf( "e;%s: %s\n”, a, vals[i] );
                }
                ldap_value_free( vals );
            }
            ldap_memfree( a );
        }
        if ( ber != NULL ) {
            ber_free( ber, 0 );
        }
        printf( “\n” );
    }
    ldap_msgfree( result );
    ldap_unbind( ld );
    return( 0 );
}

B.2.2 Read Using JNDI

/*
 * @(#)Rdentry.java     1.2 99/07/26
 *
 * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import java.util.Hashtable;

import javax.naming.*;
import javax.naming.directory.*;
/*
 * Search the directory for the specific entry
 * "cn=Barbara Jensen, ou=Product Development, o=Ace Industry, c=US".
 * Retrieve all attributes from the entry.
 *
 * [Equivalent to rdentry.c in Netscape SDK]
 */
class Rdentry {
public static void main(String[] args) {
    Hashtable env = new Hashtable(5, 0.75f);
    /*
     * Specify the initial context implementation to use.
     * This could also be set by using the -D option to the java program.
     * For example,
     *   java -Djava.naming.factory.initial=com.sun.jndi.ldap.LdapCtxFactory \
     *       Rdentry
     */
    env.put(Context.INITIAL_CONTEXT_FACTORY, Env.INITCTX);
    /* Specify host and port to use for directory service */
    env.put(Context.PROVIDER_URL, Env.MY_SERVICE);
    try {
        /* get a handle to an Initial DirContext */
        DirContext ctx = new InitialDirContext(env);
        /* Read Babs' entry */
        Attributes attrs = ctx.getAttributes(Env.ENTRYDN);
        if (attrs == null) {
            System.out.println(Env.ENTRYDN + "has no attributes");
        } else {
            /* print each attribute */
            for (NamingEnumeration ae = attrs.getAll();
                 ae.hasMoreElements();) {
                Attribute attr = (Attribute)ae.next();
                String attrId = attr.getID();
                /* print each value */
                for (NamingEnumeration vals = attr.getAll();
                     vals.hasMoreElements();
                     System.out.println(attrId + ": " + vals.nextElement()))
                    ;
            }
        }
    } catch (NamingException e) {
        System.err.println("Rdentry example failed.");
        e.printStackTrace();
    }
}
}

CONTENTS | PREV | NEXT

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


B.3 Get Attributes

B.3.1 Get Attributes Using LDAP C API B.3.2 Get Attributes Using JNDI

B.3.1 Get Attributes Using LDAP C API

/*
 * Copyright (c) 1996.  Netscape Communications Corporation.  All
 * rights reserved.
 *
 * Retrieve several attributes of a particular entry.
 */
#include "examples.h"

int
main( int argc, char **argv )
{
    LDAP                *ld;
    LDAPMessage         *result, *e;
    char                **vals, *attrs[ 5 ];
    int                 i;
    /* get a handle to an LDAP connection */
    if ( (ld = ldap_init( MY_HOST, MY_PORT )) == NULL ) {
        perror( "ldap_init" );
        return( 1 );
    }
    attrs[ 0 ] = "cn";         /* Get canonical name(s) (full name) */
    attrs[ 1 ] = "sn";         /* Get surname(s) (last name) */
    attrs[ 2 ] = "mail";       /* Get email address(es) */
    attrs[ 3 ] = "telephonenumber";      /* Get telephone number(s) */
    attrs[ 4 ] = NULL;
    if ( ldap_search_s( ld, ENTRYDN, LDAP_SCOPE_BASE,
            "(objectclass=*)", attrs, 0, &result ) != LDAP_SUCCESS ) {
        ldap_perror( ld, "ldap_search_s" );
        return( 1 );
    }
    /* print it out */
    if (( e = ldap_first_entry( ld, result )) != NULL ) {
        if (( vals = ldap_get_values( ld, e, "cn" )) != NULL ) {
            printf( "Full name:\n" );
            for ( i = 0; vals[i] != NULL; i++ ) {
                printf( "\t%s\n", vals[i] );
            }
            ldap_value_free( vals );
        }
        if (( vals = ldap_get_values( ld, e, "sn" )) != NULL ) {
            printf( "Last name (surname):\n" );
            for ( i = 0; vals[i] != NULL; i++ ) {
                printf( "\t%s\n", vals[i] );
            }
            ldap_value_free( vals );
        }
        if (( vals = ldap_get_values( ld, e, "mail" )) != NULL ) {
            printf( "Email address:\n" );
            for ( i = 0; vals[i] != NULL; i++ ) {
                printf( "\t%s\n", vals[i] );
            }
            ldap_value_free( vals );
        }
        if (( vals = ldap_get_values( ld, e, "telephonenumber" )) != NULL ) {
            printf( "Telephone number:\n" );
            for ( i = 0; vals[i] != NULL; i++ ) {
                printf( "\t%s\n", vals[i] );
            }
            ldap_value_free( vals );
        }
    }
    ldap_msgfree( result );
    ldap_unbind( ld );
    return( 0 );
}

B.3.2 Get Attributes Using JNDI

/*
 *
 * @(#)Getattrs.java      1.2 99/07/26
 *
 * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.util.Hashtable;
import java.util.Enumeration;

import javax.naming.*;
import javax.naming.directory.*;
/*
 * Retrieve several attributes of a particular entry.
 *
 * [equivalent to getattrs.c in Netscape SDK]
 */
class Getattrs {
public static void main(String[] args) {
    Hashtable env = new Hashtable(5, 0.75f);
    /*
     * Specify the initial context implementation to use.
     * For example,
     * This could also be set by using the -D option to the java program.
     *   java -Djava.naming.factory.initial=com.sun.jndi.ldap.LdapCtxFactory \
     *       Getattrs
     */
    env.put(Context.INITIAL_CONTEXT_FACTORY, Env.INITCTX);
    /* Specify host and port to use for directory service */
    env.put(Context.PROVIDER_URL, Env.MY_SERVICE);
    try {
        /* get a handle to an Initial DirContext */
        DirContext ctx = new InitialDirContext(env);
        String[] attrs = new String[4];
        attrs[ 0 ] = "cn";              /* Get canonical name(s) (full name) */
        attrs[ 1 ] = "sn";              /* Get surname(s) (last name) */
        attrs[ 2 ] = "mail";            /* Get email address(es) */
        attrs[ 3 ] = "telephonenumber"; /* Get telephone number(s) */
        Attributes result = ctx.getAttributes(Env.ENTRYDN, attrs);
        if (result == null) {
            System.out.println(Env.ENTRYDN +
                               "has none of the specified attributes.");
        } else {
            /* print it out */
            Attribute attr = result.get("cn");
            if (attr != null) {
                System.out.println("Full name:" );
                for (NamingEnumeration vals = attr.getAll();
                     vals.hasMoreElements();
                     System.out.println("\t" + vals.nextElement()))
                    ;
            }
            attr = result.get("sn");
            if (attr != null) {
                System.out.println("Last name (surname):" );
                for (NamingEnumeration vals = attr.getAll();
                     vals.hasMoreElements();
                     System.out.println("\t" + vals.nextElement()))
                    ;
            }
            attr = result.get("mail");
            if (attr != null) {
                System.out.println("Email address:" );
                for (NamingEnumeration vals = attr.getAll();
                     vals.hasMoreElements();
                     System.out.println("\t" + vals.nextElement()))
                    ;
            }
            attr = result.get("telephonenumber");
            if (attr != null) {
                System.out.println("Telephone number:" );
                for (NamingEnumeration vals = attr.getAll();
                     vals.hasMoreElements();
                     System.out.println("\t" + vals.nextElement()))
                    ;
            }
        }
    } catch (NamingException e) {
        System.err.println("Getattrs example failed.");
        e.printStackTrace();
    }
}
}

CONTENTS | PREV | NEXT

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


B.4 Compare An Attribute

B.4.1 Compare Using LDAP C API B.4.2 Compare Using JNDI

B.4.1 Compare Using LDAP C API

/*
 * Copyright (c) 1996.  Netscape Communications Corporation.  All
 * rights reserved.
 *
 * Use ldap_compare() to compare values agains values contained in entry
 * "cn=Barbara Jensen, ou=Product Development, o=Ace Industry, c=US".
 * We test to see if (1) the value "person" is one of the values in the
 * objectclass attribute (it is), and if (2) the value "xyzzy" is in the
 * objectlass attribute (it isn't, or at least, it shouldn't be).
 *
 */
#include "examples.h"
int
main( int main, char **argv )
{
    LDAP        *ld;
    int         rc;
    /* get a handle to an LDAP connection */
    if ( (ld = ldap_init( MY_HOST, MY_PORT )) == NULL ) {
        perror( "ldap_init" );
        return( 1 );
    }
    /* authenticate to the directory as nobody */
    if ( ldap_simple_bind_s( ld, NULL, NULL ) != LDAP_SUCCESS ) {
        ldap_perror( ld, "ldap_simple_bind_s" );
        return( 1 );
    }
    /* compare the value "person" against the objectclass attribute */
    rc = ldap_compare_s( ld, ENTRYDN, "objectclass", "person" );
    switch ( rc ) {
    case LDAP_COMPARE_TRUE:
        printf( "The value \"person\" is contained in the objectclass "
                "attribute.\n" );
        break;
    case LDAP_COMPARE_FALSE:
        printf( "The value \"person\" is not contained in the objectclass "
                "attribute.\n" );
        break;
    default:
        ldap_perror( ld, "ldap_compare_s" );
    }
    /* compare the value "xyzzy" against the objectclass attribute */
    rc = ldap_compare_s( ld, ENTRYDN, "objectclass", "xyzzy" );
    switch ( rc ) {
    case LDAP_COMPARE_TRUE:
        printf( "The value \"xyzzy\" is contained in the objectclass "
                "attribute.\n" );
        break;
    case LDAP_COMPARE_FALSE:
        printf( "The value \"xyzzy\" is not contained in the objectclass "
                "attribute.\n" );
        break;
    default:
        ldap_perror( ld, "ldap_compare_s" );
    }
    ldap_unbind( ld );
    return( 0 );
}

B.4.2 Compare Using JNDI

/*
 * @(#)Compare.java       1.2 99/07/26
 *
 * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

import java.util.Hashtable;

import javax.naming.*;
import javax.naming.directory.*;
/*
 * Use search() to compare values against values contained in entry
 * "cn=Barbara Jensen, ou=Product Development, o=Ace Industry, c=US".
 * We test to see if (1) the value "person" is one of the values in the
 * objectclass attribute (it is), and if (2) the value "xyzzy" is in the
 * objectlass attribute (it isn't, or at least, it shouldn't be).
 *
 * [equivalent to compare.c in Netscape SDK]
 *
 */
class Compare {
public static void main(String[] args) {
    Hashtable env = new Hashtable(5, 0.75f);
    /*
     * Specify the initial context implementation to use.
     * This could also be set by using the -D option to the java program.
     * For example,
     *    java -Djava.naming.factory.initial=com.sun.jndi.ldap.LdapCtxFactory \
     *       Compare
     */
    env.put(Context.INITIAL_CONTEXT_FACTORY, Env.INITCTX);
    /* Specify host and port to use for directory service */
    env.put(Context.PROVIDER_URL, Env.MY_SERVICE);
    DirContext ctx = null;
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.OBJECT_SCOPE);
    ctls.setReturningAttributes(new String[0]);  // do not return any attrs
    try {
        /* get a handle to an Initial DirContext */
        ctx = new InitialDirContext(env);
    } catch (NamingException e) {
        System.err.println("Cannot get initial context.");
        return;
    }
    try {
        NamingEnumeration results =
            ctx.search(Env.ENTRYDN, "objectclass=person", ctls);
        if (results != null && results.hasMoreElements()) {
            System.out.println(
                "The value \"person\" is contained in the objectclass attribute.");
        } else {
            System.out.println(
          "The value \"person\" is not contained in the objectclass attribute." );
        }
    } catch (NamingException e) {
        System.err.println("Comparison of value person failed.");
    }
    try {
        NamingEnumeration results =
            ctx.search(Env.ENTRYDN, "objectclass=xyzzy", ctls);

        if (results != null && results.hasMoreElements()) {
            System.out.println(
                "The value \"xyzzy\" is contained in the objectclass attribute.");
        } else {
            System.out.println(
          "The value \"xyzzy\" is not contained in the objectclass attribute." );
        }
    } catch (NamingException e) {
        System.err.println("Comparison of value xyzzy failed.");
    }
}
}

CONTENTS | PREV | NEXT

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


B.5 Modify Attributes

B.5.1 Modify Attributes Using LDAP C API B.5.2 Modify Attributes Using JNDI

B.5.1 Modify Attributes Using LDAP C API

/*
 * Copyright (c) 1996.  Netscape Communications Corporation.  All
 * rights reserved.
 *
 * Modify an entry:
 *  - replace any existing values in the "mail" attribute with "babs@ace.com"
 *  - add a new value to the "description" attribute
 */
#include "examples.h"
int
main( int argc, char **argv )
{
    LDAP        *ld;
    LDAPMod     mod0;
    LDAPMod     mod1;
    LDAPMod     *mods[ 3 ];
    char        *vals0[ 2 ];
    char        *vals1[ 2 ];
    time_t      now;
    char        buf[ 128 ];
    /* get a handle to an LDAP connection */
    if ( (ld = ldap_init( MY_HOST, MY_PORT )) == NULL ) {
        perror( "ldap_init" );
        return( 1 );
    }
    /* authenticate */
    if ( ldap_simple_bind_s( ld, ENTRYDN, ENTRYPW ) != LDAP_SUCCESS ) {
        ldap_perror( ld, "ldap_simple_bind_s" );
        return( 1 );
    }
    /* construct the list of modifications to make */
    mod0.mod_op = LDAP_MOD_REPLACE;
    mod0.mod_type = "mail";
    vals0[0] = "babs@ace.com";
    vals0[1] = NULL;
    mod0.mod_values = vals0;
    mod1.mod_op = LDAP_MOD_ADD;
    mod1.mod_type = "description";
    time( &now );
    sprintf( buf, "This entry was modified with the modattrs program on %s",
            ctime( &now ));
    /* Get rid of \n which ctime put on the end of the time string */
    if ( buf[ strlen( buf ) - 1 ] == '\n' ) {
        buf[ strlen( buf ) - 1 ] = '\0';
    }
    vals1[ 0 ] = buf;
    vals1[ 1 ] = NULL;
    mod1.mod_values = vals1;
    mods[ 0 ] = &mod0;
    mods[ 1 ] = &mod1;
    mods[ 2 ] = NULL;
    /* make the change */
    if ( ldap_modify_s( ld, ENTRYDN, mods )
            != LDAP_SUCCESS ) {
        ldap_perror( ld, "ldap_modify_s" );
        return( 1 );
    }
    ldap_unbind( ld );
    printf( "modification was successful\n" );
    return( 0 );
}

Modify Attributes Using JNDI

/*
 * @(#)Modattrs.java      1.2 99/07/26
 *
 * Copyright 1997, 1998, 1999 Sun Microsystems, Inc. All Rights
 * Reserved.
 *
 * Sun grants you ("Licensee") a non-exclusive, royalty free,
 * license to use, modify and redistribute this software in source and
 * binary code form, provided that i) this copyright notice and license
 * appear on all copies of the software; and ii) Licensee does not utilize
 * the software in a manner which is disparaging to Sun.
 *
 * This software is provided "AS IS," without a warranty of any
 * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
 * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
 * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE
 * OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
 * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
 * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
 * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
 * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 *
 * This software is not designed or intended for use in on-line
 * control of aircraft, air traffic, aircraft navigation or aircraft
 * communications; or in the design, construction, operation or
 * maintenance of any nuclear facility. Licensee represents and warrants
 * that it will not use or redistribute the Software for such purposes.
 */

import java.util.Hashtable;
import java.util.Date;

import javax.naming.*;
import javax.naming.directory.*;
/*
 * Modify an entry:
 *  - replace any existing values in the "mail" attribute with "babs@ace.com"
 *  - add a new value to the "description" attribute
 *
 * [equivalent to modattrs.c in Netscape SDK]
 */
class Modattrs {
public static void main(String[] args) {
    Hashtable env = new Hashtable(5, 0.75f);
    /*
     * Specify the initial context implementation to use.
     * This could also be set by using the -D option to the java program.
     * For example,
     *   java -Djava.naming.factory.initial=com.sun.jndi.ldap.LdapCtxFactory \
     *       Modattrs
     */
    env.put(Context.INITIAL_CONTEXT_FACTORY, Env.INITCTX);
    /* Specify host and port to use for directory service */
    env.put(Context.PROVIDER_URL, Env.MY_SERVICE);
    /* specify authentication information */
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, Env.MGR_DN);
    env.put(Context.SECURITY_CREDENTIALS, Env.MGR_PW);
    try {
        /* get a handle to an Initial DirContext */
        DirContext ctx = new InitialDirContext(env);
        /* construct the list of modifications to make */
        ModificationItem[] mods = new ModificationItem[2];
        Attribute mod0 = new BasicAttribute("mail", "babs@eng");
        // Update mail attribute
        mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, mod0);
        // Add another value to description attribute
        Attribute mod1 =
            new BasicAttribute("description",
                          "This entry was modified with the Modattrs program on " +
                          (new Date()).toString());
        mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE, mod1);
         /* Delete the description attribute altogether */
        /*
        Attribute mod1 =  new BasicAttribute("description");
        mods[2] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, mod1);
  */
        /* make the change */
        ctx.modifyAttributes(Env.ENTRYDN, mods);
        System.out.println( "modification was successful." );
    } catch (NamingException e) {
        System.err.println("modification failed. " + e);
    }
}
}

CONTENTS | PREV | NEXT

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


B.6 Rename An Entry

B.6.1 Rename Using LDAP C API

 B.6.2 Rename Using JNDI

B.6.1 Rename Using LDAP C API

/*
 * Copyright (c) 1996.  Netscape Communications Corporation.  All
 * rights reserved.
 *
 * Modify the RDN (relative distinguished name) of an entry.  In this
 * example, we change the dn "cn=Jacques Smith, o=Ace Industry, c=US"
 * to "cn=Jacques M Smith, o=Ace Industry, c=US".
 *
 * Since it is an error to either (1) attempt to modrdn an entry which
 * does not exist, or (2) modrdn an entry where the destination name
 * already exists, we take some steps, for this example, to make sure
 * we’ll succeed.  We (1) add "cn=Jacques Smith" (if the entry exists,
 * we just ignore the error, and (2) delete "cn=Jacques M Smith" (if the
 * entry doesn’t exist, we ignore the error).
 *
 * We pass 0 for the "deleteoldrdn" argument to ldap_modrdn2_s().  This
 * means that after we change the RDN, the server will put the value
 * "Jacques Smith" into the cn attribute of the new entry, in addition to
 * "Jacques M Smith".
 */
#include "examples.h"
#define        NMODS        4
unsigned long        global_counter = 0;
static void free_mods( LDAPMod **mods );
int
main( int argc, char **argv )
{
    LDAP                    *ld;
    char                    *dn, *ndn, *nrdn;
    int                     i;
    int                     rc;
    LDAPMod                 **mods;
    /* Values we’ll use in creating the entry */
    char *objectclass_values[] = { "top", "person", "organizationalPerson",
                                   "inetOrgPerson", NULL };
    char *cn_values[] = { "Jacques Smith", NULL };
    char *sn_values[] = { "Smith", NULL };
    char *givenname_values[] = { "Jacques", NULL };
    /* Specify the DN we’re adding */
    dn = "cn=Jacques Smith, o=Ace Industry, c=US";
    /* the destination DN */
    ndn = "cn=Jacques M Smith, o=Ace Industry, c=US";
    /* the new RDN */
    nrdn = "cn=Jacques M Smith";
    /* get a handle to an LDAP connection */
    if ( (ld = ldap_init( MY_HOST, MY_PORT )) == NULL ) {
        perror( "ldap_init" );
        return( 1 );
    }
    /* authenticate to the directory as the Directory Manager */
    if ( ldap_simple_bind_s( ld, MGR_DN, MGR_PW ) != LDAP_SUCCESS ) {
        ldap_perror( ld, "ldap_simple_bind_s" );
        return( 1 );
    }
    if (( mods = ( LDAPMod ** ) malloc(( NMODS + 1 ) * sizeof( LDAPMod *)))
            == NULL ) {
        fprintf( stderr, "Cannot allocate memory for mods array\n" );
        return( 1 );
    }
    /* Construct the array of values to add */
    for ( i = 0; i < NMODS; i++ ) {
        if (( mods[ i ] = ( LDAPMod * ) malloc( sizeof( LDAPMod ))) == NULL ) {
            fprintf( stderr, "Cannot allocate memory for mods element\n" );
            return( 1 );
        }
    }
    mods[ 0 ]->mod_op = 0;
    mods[ 0 ]->mod_type = "objectclass";
    mods[ 0 ]->mod_values = objectclass_values;
    mods[ 1 ]->mod_op = 0;
    mods[ 1 ]->mod_type = "cn";
    mods[ 1 ]->mod_values = cn_values;
    mods[ 2 ]->mod_op = 0;
    mods[ 2 ]->mod_type = "sn";
    mods[ 2 ]->mod_values = sn_values;
    mods[ 3 ]->mod_op = 0;
    mods[ 3 ]->mod_type = "givenname";
    mods[ 3 ]->mod_values = givenname_values;
    mods[ 4 ] = NULL;

    /* Add the entry */
    if (( rc = ldap_add_s( ld, dn, mods )) != LDAP_SUCCESS ) {
        /* If entry exists already, fine.  Ignore this error. */
        if ( rc == LDAP_ALREADY_EXISTS ) {
            printf( "Entry \"%s is already in the directory.\n", dn );
        } else {
            ldap_perror( ld, "ldap_add_s" );
            free_mods( mods );
            return( 1 );
        }
    } else {
        printf( "Added entry \"%s\".\n", dn );
    }
    free_mods( mods );
    /* Delete the destination entry, for this example */
    if (( rc = ldap_delete_s( ld, ndn )) != LDAP_SUCCESS ) {
        /* If entry does not exist, fine.  Ignore this error. */
        if ( rc == LDAP_NO_SUCH_OBJECT ) {
            printf( "Entry \"%s\" is not in the directory.  "
                    "No need to delete.\n", ndn );
        } else {
            ldap_perror( ld, "ldap_delete_s" );
            return( 1 )
        }
    } else {
        printf( "Deleted entry \"%s\".\n", ndn );
    }
    /* Do the modrdn operation */
    if ( ldap_modrdn2_s( ld, dn, nrdn, 0 ) != LDAP_SUCCESS ) {
        ldap_perror( ld, "ldap_modrdn2_s" );
        return( 1 );
    }
    printf( "The modrdn operation was successful.  Entry\n"
            "\"%s\" has been changed to\n"
            "\"%s\".\n", dn, ndn );
    ldap_unbind( ld );
    return 0;
}

/*
 * Free a mods array.
 */
static void
free_mods( LDAPMod **mods )
{
    int i;

    for ( i = 0; i < NMODS; i++ ) {
        free( mods[ i ] );
    }
    free( mods );
}

B.6.2 Rename Using JNDI

/*
 * @(#)Modrdn.java      1.2 99/07/26
 *
 * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

import java.util.Hashtable;
import java.util.Date;

import javax.naming.*;
import javax.naming.directory.*;
/*
 * Modify the RDN (relative distinguished name) of an entry.  In this
 * example, we change the dn "cn=Jacques Smith, o=Ace Industry, c=US"
 * to "cn=Jacques M Smith, o=Ace Industry, c=US".
 *
 * Since it is an error to either (1) attempt to modrdn an entry which
 * does not exist, or (2) modrdn an entry where the destination name
 * already exists, we take some steps, for this example, to make sure
 * we'll succeed.  We (1) add "cn=Jacques Smith" (if the entry exists,
 * we just ignore the error, and (2) delete "cn=Jacques M Smith" (if the
 * entry doesn't exist, we ignore the error).
 *
 * After renaming, we add back the attribute "Jacques Smith" into the cn
 * attribute.
 *
 * [based on modrdn.c of Netscape  SDK]
 */
class Modrdn {
public static void main(String[] args) {
    /* Values we'll use in creating the entry */
    Attribute objClasses = new BasicAttribute("objectclass");
    objClasses.add("top");
    objClasses.add("person");
    objClasses.add("organizationalPerson");
    objClasses.add("inetOrgPerson");
    Attribute cn = new BasicAttribute("cn", "Jacques Smith");
    Attribute sn = new BasicAttribute("sn", "Smith");
    Attribute givenNames = new BasicAttribute("givenname", "Jacques");
    /* Specify the DN we're adding */
    String dn = "cn=Jacques Smith, " + Env.MY_MODBASE;
    /* the destination DN */
    String ndn = "cn=Jacques M Smith, " + Env.MY_MODBASE;
    /* the new RDN */
    String nrdn = "cn=Jacques M Smith";
    Hashtable env = new Hashtable(5, 0.75f);
    /*
     * Specify the initial context implementation to use.
     * This could also be set by using the -D option to the java program.
     * For example,
     *   java -Djava.naming.factory.initial=com.sun.jndi.ldap.LdapCtxFactory \
     *       Modrdn
     */
    env.put(Context.INITIAL_CONTEXT_FACTORY, Env.INITCTX);
    /* Specify host and port to use for directory service */
    env.put(Context.PROVIDER_URL, Env.MY_SERVICE);
    /* specify authentication information */
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, Env.MGR_DN);
    env.put(Context.SECURITY_CREDENTIALS, Env.MGR_PW);
    DirContext ctx = null;
    try {
        /* get a handle to an Initial DirContext */
        ctx = new InitialDirContext(env);
        Attributes orig = new BasicAttributes();
        orig.put(objClasses);
        orig.put(cn);
        orig.put(sn);
        orig.put(givenNames);
        /* Add the entry */
        ctx.createSubcontext(dn, orig);
        System.out.println( "Added entry " + dn + ".");
    } catch (NameAlreadyBoundException e) {
        /* If entry exists already, fine.  Ignore this error. */
        System.out.println("Entry " + dn + " already exists, no need to add");
    } catch (NamingException e) {
        System.err.println("Modrdn: problem adding entry." + e);
        System.exit(1);
    }
    try {
        /* Delete the destination entry, for this example */
        ctx.destroySubcontext(ndn);
        System.out.println( "Deleted entry " + ndn + "." );
    } catch (NameNotFoundException e) {
        /* If entry does not exist, fine.  Ignore this error. */
        System.out.println( "Entry " + ndn + " is not in the directory.  " +
                    "No need to delete.");
    } catch (NamingException e) {
        System.err.println("Modrdn: problem deleting entry." + e);
        System.exit(1);
    }

    /* Do the modrdn operation */
    try {
        ctx.rename(dn, ndn);
        System.out.println("The modrdn operation was successful.  Entry " +
                           dn + " has been changed to " + ndn + ".");
    } catch (NamingException e) {
        System.err.println("Modify operation failed." + e);
    }
}
}

CONTENTS | PREV | NEXT

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: - Example: Print2DGraphics.java

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

APPENDIX D

Example: Print2DGraphics.java

import java.io.*;
import java.awt.*;
import java.net.*;
import java.awt.image.*;
import java.awt.print.*;
import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;

public class Print2DGraphics implements Printable {

        public Print2DGraphics() {

                /* Construct the print request specification.
                * The print data is a Printable object.
                * the request additonally specifies a job name, 2 copies, and
                * landscape orientation of the media.
                */
                DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
                PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
                aset.add(OrientationRequested.LANDSCAPE);
                aset.add(new Copies(2));
                aset.add(new JobName("My job", null));

                /* locate a print service that can handle the request */
                PrintService[] services =
                        PrintServiceLookup.lookupPrintServices(flavor, aset);

                if (services.length > 0) {
                        System.out.println("selected printer " + services[0].getName());

                        /* create a print job for the chosen service */
                        DocPrintJob pj = services[0].createPrintJob();

                        try {
                                /*
                                * Create a Doc object to hold the print data.
                                */
                                Doc doc = new SimpleDoc(this, flavor, null);

                                /* print the doc as specified */
                                pj.print(doc, aset);

                                /*
                                * Do not explicitly call System.exit() when print returns.
                                * Printing can be asynchronous so may be executing in a
                                * separate thread.
                                * If you want to explicitly exit the VM, use a print job
                                * listener to be notified when it is safe to do so.
                                */

                        } catch (PrintException e) {
                                System.err.println(e);
                        }
                }
        }

        public int print(Graphics g,PageFormat pf,int pageIndex) {

                if (pageIndex == 0) {
                        Graphics2D g2d= (Graphics2D)g;
                        g2d.translate(pf.getImageableX(), pf.getImageableY());
                        g2d.setColor(Color.black);
                        g2d.drawString("example string", 250, 250);
                        g2d.fillRect(0, 0, 200, 200);
                        return Printable.PAGE_EXISTS;
                } else {
                        return Printable.NO_SUCH_PAGE;
                }
        }

        public static void main(String arg[]) {
                Print2DGraphics sp = new Print2DGraphics();
        }
}

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: - Example: Print2DPrinterJob.java

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

APPENDIX C

Example: Print2DPrinterJob.java

import java.io.*;
import java.awt.*;
import java.net.*;
import java.awt.image.*;
import java.awt.print.*;
import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;

public class Print2DPrinterJob implements Printable {

        public Print2DPrinterJob() {

                /* Construct the print request specification.
                * The print data is a Printable object.
                * the request additonally specifies a job name, 2 copies, and
                * landscape orientation of the media.
                */
                PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
                aset.add(OrientationRequested.LANDSCAPE);
                aset.add(new Copies(2));
                aset.add(new JobName("My job", null));

                /* Create a print job */
                PrinterJob pj = PrinterJob.getPrinterJob();
                pj.setPrintable(this);
                /* locate a print service that can handle the request */
                PrintService[] services =
                        PrinterJob.lookupPrintServices();

                if (services.length > 0) {
                        System.out.println("selected printer " + services[0].getName());
                        try {
                                pj.setPrintService(services[0]);
                                pj.pageDialog(aset);
                                if(pj.printDialog(aset)) {
                                        pj.print(aset);
                                }
                        } catch (PrinterException pe) {
                                System.err.println(pe);
                        }
                }
        }

        public int print(Graphics g,PageFormat pf,int pageIndex) {

                if (pageIndex == 0) {
                        Graphics2D g2d= (Graphics2D)g;
                        g2d.translate(pf.getImageableX(), pf.getImageableY());
                        g2d.setColor(Color.black);
                        g2d.drawString("example string", 250, 250);
                        g2d.fillRect(0, 0, 200, 200);
                        return Printable.PAGE_EXISTS;
                } else {
                        return Printable.NO_SUCH_PAGE;
                }
        }

        public static void main(String arg[]) {

                Print2DPrinterJob sp = new Print2DPrinterJob();
        }
}

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: - Example: Print2DtoStream.java

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

APPENDIX E

Example: Print2DtoStream.java

/*
 * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
 *
 * This software is the proprietary information of Oracle.
 * Use is subject to license terms.
 *
 */

import java.io.*;
import java.awt.*;
import java.awt.print.*;
import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;

/*
 * Use the Java(TM) Print Service API to locate a service which can export
 * 2D graphics to a stream as Postscript. This may be spooled to a
 * Postscript printer, or used in a postscript viewer.
 */
public class Print2DtoStream implements Printable{

        public Print2DtoStream() {

                /* Use the pre-defined flavor for a Printable from an InputStream */
                DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;

                /* Specify the type of the output stream */
                String psMimeType = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();

                /* Locate factory which can export a GIF image stream as Postscript */
                StreamPrintServiceFactory[] factories =
                StreamPrintServiceFactory.lookupStreamPrintServiceFactories(
                                        flavor, psMimeType);
                if (factories.length == 0) {
                        System.err.println("No suitable factories");
                        System.exit(0);
                }

                try {
                        /* Create a file for the exported postscript */
                        FileOutputStream fos = new FileOutputStream("out.ps");

                        /* Create a Stream printer for Postscript */
                        StreamPrintService sps = factories[0].getPrintService(fos);

                        /* Create and call a Print Job */
                        DocPrintJob pj = sps.createPrintJob();
                        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();

                        Doc doc = new SimpleDoc(this, flavor, null);

                        pj.print(doc, aset);
                        fos.close();

                } catch (PrintException pe) {
                        System.err.println(pe);
                } catch (IOException ie) {
                        System.err.println(ie);
                }
        }

        public int print(Graphics g,PageFormat pf,int pageIndex) {

                if (pageIndex == 0) {
                        Graphics2D g2d= (Graphics2D)g;
                        g2d.translate(pf.getImageableX(), pf.getImageableY());
                        g2d.setColor(Color.black);
                        g2d.drawString("example string", 250, 250);
                        g2d.fillRect(0, 0, 200, 200);
                        return Printable.PAGE_EXISTS;
                } else {
                        return Printable.NO_SUCH_PAGE;
                }
        }

        public static void main(String args[]) {
                Print2DtoStream sp = new Print2DtoStream();
        }
}

CONTENTS| PREV| NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: - Example: PrintGIF.java

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

APPENDIX F

Example: PrintGIF.java

/*
* Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
*
* This software is the proprietary information of Oracle.
* Use is subject to license terms.
*
*/

import java.io.*;
import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;

/*
*  Use the Java(TM) Print Service API to locate a print service which
*  can print a GIF-encoded image. A GIF image is printed according to
*  a job template specified as a set of printing attributes.
*/
public class PrintGIF {

        public static void main(String args[]) {

                /* Use the pre-defined flavor for a GIF from an InputStream */
                DocFlavor flavor = DocFlavor.INPUT_STREAM.GIF;

                /* Create a set which specifies how the job is to be printed */
                PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
                aset.add(MediaSizeName.NA_LETTER);
                aset.add(new Copies(1));

                /* Locate print services which can print a GIF in the manner specified */
                PrintService[] pservices =
                        PrintServiceLookup.lookupPrintServices(flavor, aset);

                if (pservices.length > 0) {
                        /* Create a Print Job */
                        DocPrintJob printJob = pservices[0].createPrintJob();

                        /* Create a Doc implementation to pass the print data */
                        Doc doc = new InputStreamDoc("java2dlogo.gif", flavor);

                        /* Print the doc as specified */
                        try {
                                printJob.print(doc, aset);
                        } catch (PrintException e) {
                                System.err.println(e);
                        }
                } else {
                        System.err.println("No suitable printers");
                }
        }
}

class InputStreamDoc implements Doc {
        private String filename;
        private DocFlavor docFlavor;
        private InputStream stream;

        public InputStreamDoc(String name, DocFlavor flavor) {
                filename = name;
                docFlavor = flavor;
        }

        public DocFlavor getDocFlavor() {
                return docFlavor;
        }

        /* No attributes attached to this Doc - mainly useful for MultiDoc */
        public DocAttributeSet getAttributes() {
                return null;
        }

        /* Since the data is to be supplied as an InputStream delegate to
        * getStreamForBytes().
        */
        public Object getPrintData() throws IOException {
                return getStreamForBytes();
        }

        /* Not possible to return a GIF as text */
        public Reader getReaderForText()
                throws UnsupportedEncodingException, IOException {
        return null;
        }

        /* Return the print data as an InputStream.
        * Always return the same instance.
        */
        public InputStream getStreamForBytes() throws IOException {
                synchronized(this) {
                        if (stream == null) {
                                stream = new FileInputStream(filename);
                        }
                        return stream;
                }
        }
}

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: - Example: PrintGIFtoStream.java

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

APPENDIX B

Example: PrintGIFtoStream.java

/*
* Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
*
* This software is the proprietary information of Oracle.
* Use is subject to license terms.
*
*/

import java.io.*;
import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;

/*
* Use the Java(TM) Print Service API to locate a service which can export
* a GIF-encoded image to a stream as Postscript. This may be spooled to a
* Postscript printer, or used in a postscript viewer.
*/
public class PrintGIFtoStream {

        public static void main(String args[]) {

                /* Use the pre-defined flavor for a GIF from an InputStream */
                DocFlavor flavor = DocFlavor.INPUT_STREAM.GIF;

                /* Specify the type of the output stream */
                String psMimeType = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();

                /* Locate factory which can export a GIF image stream as Postscript */
                StreamPrintServiceFactory[] factories =
                        StreamPrintServiceFactory.lookupStreamPrintServiceFactories(
                                        flavor, psMimeType);
                if (factories.length == 0) {
                        System.err.println("No suitable factories");
                        System.exit(0);
                }

                try {
                        /* Load the file */
                        FileInputStream fis = new FileInputStream("java2dlogo.gif");
                        /* Create a file for the exported postscript */
                        String filename = "newfile.ps";
                        FileOutputStream fos = new FileOutputStream(filename);

                        /* Create a Stream printer for Postscript */
                        StreamPrintService sps = factories[0].getPrintService(fos);

                        /* Create and call a Print Job for the GIF image */
                        DocPrintJob pj = sps.createPrintJob();
                        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
                        aset.add(new Copies(2));
                        aset.add(MediaSizeName.ISO_A4);
                        aset.add(Sides.TWO_SIDED_LONG_EDGE);
                        aset.add(Finishings.STAPLE);

                        Doc doc = new SimpleDoc(fis, flavor, null);

                        pj.print(doc, aset);
                        fos.close();

                } catch (PrintException pe) {
                        System.err.println(pe);
                } catch (IOException ie) {
                        System.err.println(ie);
                }
        }
}

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: - Example: PrintPS.java

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

APPENDIX A

Example: PrintPS.java

import java.io.*;
import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;
import javax.print.event.*;

public class PrintPS {

        public static void main(String args[]) {
                PrintPS ps = new PrintPS();
        }
        public PrintPS() {
                /* Construct the print request specification.
                 * The print data is Postscript which will be
                 * supplied as a stream.  The media size
                 * required is A4, and 2 copies are to be printed
                 */
                DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
                PrintRequestAttributeSet aset =
                        new HashPrintRequestAttributeSet();
                aset.add(MediaSizeName.ISO_A4);
                aset.add(new Copies(2));
                aset.add(Sides.TWO_SIDED_LONG_EDGE);
                aset.add(Finishings.STAPLE);

                /* locate a print service that can handle it */
                PrintService[] pservices =
                        PrintServiceLookup.lookupPrintServices(flavor, aset);
                if (pservices.length > 0) {
                        System.out.println("selected printer " + pservices[0].getName());

                        /* create a print job for the chosen service */
                        DocPrintJob pj = pservices[0].createPrintJob();
                        try {
                                /*
                                * Create a Doc object to hold the print data.
                                * Since the data is postscript located in a disk file,
                                * an input stream needs to be obtained
                                * BasicDoc is a useful implementation that will if requested
                                * close the stream when printing is completed.
                                */
                                FileInputStream fis = new FileInputStream("example.ps");
                                Doc doc = new SimpleDoc(fis, flavor, null);

                                /* print the doc as specified */
                                pj.print(doc, aset);

                                /*
                                * Do not explicitly call System.exit() when print returns.
                                * Printing can be asynchronous so may be executing in a
                                * separate thread.
                                * If you want to explicitly exit the VM, use a print job
                                * listener to be notified when it is safe to do so.
                                */

                        } catch (IOException ie) {
                                System.err.println(ie);
                        } catch (PrintException e) {
                                System.err.println(e);
                        }
                }
        }
}

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Contents | Previous | Next

Appendix A

JMX Technology Versions

The JMX technology included in the Java 2 Platform Standard Edition (J2SE) was developed through the Java Community Process (JCP) as two closely related Java Specification Requests (JSRs). The versions of the JSRs implemented in the J2SE platform, version 5.0, are detailed in the following sections.

Java Management Extensions (JMX) Instrumentation and Agent Specification (JSR 3)

The Java SE 6 platform implements version 1.4 of the JMX Specification (Maintenance Release, October 2006). It incorporates the modifications listed in the errata provided with the download.

JMX Remote API Specification (JSR 160)

The Java SE 6 platform implements version 1.4 of the JMX Remote API Specification (Maintenance Release, October 2006).

In addition to standard RMI and RMI/IIOP connectors, JSR 160 also defines optional JMX Messaging Protocol (JMXMP) connectors based on TCP sockets. The Java SE platform does not include these optional connectors. However, you might want to use JMXMP connectors if, for example, you require a more advanced level of security.

If you want to use a JMXMP connector, download the JSR 160 Reference Implementation from the download page specified at the beginning of this section, and add the jmxremote_optional.jar file to your classpath. You will find examples of use of JMXMP connectors in the JMX Remote API Tutorial included with the JSR 160 Reference Implementation.

Contents | Previous | Next

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


The APPLET Tag

Here is an example of a simple APPLET tag:

  <applet code="MyApplet.class" width=100 height=140></applet>
This tells the viewer or browser to load the applet whose compiled code is in MyApplet.class (in the same directory as the current HTML document), and to set the initial size of the applet to 100 pixels wide and 140 pixels high.

Here's a more complex example of an APPLET tag:

    <applet codebase="http://java.sun.com/applets/NervousText/1.1"
        code="NervousText.class" width=400 height=75>
    <param name="text" value="Welcome to HotJava!">
    <hr>
    If you were using a Java-enabled browser such as HotJava,
    you would see dancing text instead of this paragraph.
    <hr>
    </applet>
This tells the viewer or browser to load the applet whose compiled code is at the URL http://java.sun.com/applets/NervousText/1.1/NervousText.class, to set the initial size of the applet to 400x75 pixels. The viewer/browser must also set the applet's "text" attribute (which customizes the text this applet displays) to be "Welcome to HotJava!" If the page is viewed by a browser that can't execute Java applets, then the browser will ignore the APPLET and PARAM tags, displaying only the HTML between the <param> and </applet> tags (the alternate HTML).

Here's the result of putting the above example in your HTML file. (The first time you load this page, you may have to wait for the applet to be loaded.)

Download and install the Java Runtime Environment (JRE) to view the applet.

If you were using a Java-enabled browser such as HotJava, you would see dancing text instead of this paragraph.

Here is another example of an APPLET tag:

     <applet code=A21 width=256 height=256 archive="toir.jar">
     <param name=img value=test.gif>
     <hr>
     We need to convert some of the standard applets to use
     archive.  Any volunteers?
     <hr>
     </applet>
In this example, the applet class is A21. Its bytecodes (may) reside in the archive "toir.jar". This archive may also contain the image resource (see resources documentation) with name test.gif.

Here's the complete syntax for the APPLET tag. Required elements are in bold. Optional elements are in regular typeface. Elements your specify are in italics.

    <APPLET
        CODEBASE = codebaseURL
        ARCHIVE = archiveList
        CODE = appletFile ...or...  OBJECT = serializedApplet
        ALT = alternateText
        NAME = appletInstanceName
        WIDTH = pixels  HEIGHT = pixels
        ALIGN = alignment
        VSPACE = pixels  HSPACE = pixels
    >
    <PARAM NAME = appletAttribute1 VALUE = value>
    <PARAM NAME = appletAttribute2 VALUE = value>
    . . .
    alternateHTML
    </APPLET>

CODE, CODEBASE, and so on are attributes of the applet tag; they give the browser information about the applet. The only mandatory attributes are CODE, WIDTH, and HEIGHT. Each attribute is described below.

CODEBASE = codebaseURL
This OPTIONAL attribute specifies the base URL of the applet--the directory that contains the applet's code. If this attribute is not specified, then the document's URL is used.
ARCHIVE = archiveList
This OPTIONAL attribute describes one or more archives containing classes and other resources that will be "preloaded". The classes are loaded using an instance of an AppletClassLoader with the given CODEBASE.
The archives in archiveList are separated by ",". NB: in JDK1.1, multiple APPLET tags with the same CODEBASE share the same instance of a ClassLoader. This is used by some client code to implement inter-applet communication. Future JDKs may provide other mechanisms for inter-applet communication. For security reasons, the applet's class loader can read only from the same codebase from which the applet was started. This means that archives in archiveList must be in the same directory as, or in a subdirectory of, the codebase. Entries in archiveList of the form ../a/b.jar will not work unless explicitly allowed for in the security policy file (except in the case of an http codebase, where archives in archiveList must be from the same host as the codebase, but can have ".."'s in their paths.)
CODE = appletFile
This REQUIRED attribute gives the name of the file that contains the applet's compiled Applet subclass. This file is relative to the base URL of the applet. It cannot be absolute. One of CODE or OBJECT must be present. The value appletFile can be of the form classname.class or of the form packagename.classname.class.
OBJECT = serializedApplet
This attribute gives the name of the file that contains a serialized representation of an Applet. The Applet will be deserialized. The init() method will *not* be invoked; but its start() method will. Attributes valid when the original object was serialized are *not* restored. Any attributes passed to this APPLET instance will be available to the Applet; we advocate very strong restraint in using this feature. An applet should be stopped before it is serialized. One of CODE or OBJECT must be present.
ALT = alternateText
This OPTIONAL attribute specifies any text that should be displayed if the browser understands the APPLET tag but can't run Java applets.
NAME = appletInstanceName
This OPTIONAL attribute specifies a name for the applet instance, which makes it possible for applets on the same page to find (and communicate with) each other.
WIDTH = pixels HEIGHT = pixels
These REQUIRED attributes give the initial width and height (in pixels) of the applet display area, not counting any windows or dialogs that the applet brings up.
ALIGN = alignment
This OPTIONAL attribute specifies the alignment of the applet. The possible values of this attribute are the same as those for the IMG tag: left, right, top, texttop, middle, absmiddle, baseline, bottom, absbottom.
VSPACE = pixels HSPACE = pixels
These OPTIONAL attributes specify the number of pixels above and below the applet (VSPACE) and on each side of the applet (HSPACE). They're treated the same way as the IMG tag's VSPACE and HSPACE attributes.
<PARAM NAME = appletAttribute1 VALUE = value>
<PARAM NAME = appletAttribute2 VALUE = value> . . .
This tag is the only way to specify an applet-specific attribute. Applets access their attributes with the getParameter() method.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Applet Caching

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Applet Caching in Java Plug-in

Applet caching ensures that applets are not unnecessarily downloaded by a browser every time a user references them. Java Plug-in has supported caching in previous versions by using the same cache the browser uses for all other web documents.

This works for casual applet usage, but larger applets can often get flushed from the cache to make room for other documents since the browser has no knowledge that an applet file might be needed in the future. The result is that this caching strategy fails where is needed most in large business applets.

This release introduces an alternative form of applet caching which allows an applet deployer to decide her applet should be "sticky", that is, to stay on the disk in a secondary cache which the browser cannot overwrite. The only time "sticky" applets get downloaded after that is when they are updated on their server. Otherwise the applet is always available for quick loading. We recommend that applets which provide core business applications be made sticky to improve their startup performance.

This new feature is activated by including the new PARAM NAME="cache_option" and PARAM NAME="cache_archive" values in the tag that specifies the use of Java Plug-in as below:

<OBJECT ....>
         <PARAM NAME="archive" VALUE="...">
         ....
         <PARAM NAME="cache_option" VALUE="...">
         <PARAM NAME="cache_archive" VALUE="...">
</OBJECT>

The cache_option attribute can take one of three values:

No
Disable applet installation. Always download the file from the web server.
Browser
Run applets from the browser cache (default).
Plugin
Run applets from the new Java Plug-in cache.

The cache_archive attribute contains a list of the files to be cached:

<PARAM NAME="cache_archive" VALUE="a.jar,b.jar,c.jar">

Like the archive attribute in the APPLET tag, the list of jar files in the cache_archive attribute do not contain the full URL, but are always downloaded from the codebase specified in the EMBED/OBJECT tag.

Note that the list of JAR files in the cache_archive attribute and those in the archive attribute may be similar but should not contain the same JAR files. There are two possible cases:

  1. A JAR file is listed in cache_archive but not in archive. In this case, the JAR file is cached according to cache_option.
  2. A JAR file is listed in archive but not in cache_archive. In this case, the JAR file is cached using the native browser cache. This guarantees a minimum of caching.
cache_option and cache_archive can only be specified once per EMBED/OBJECT tag. In addition, both attributes must be specified. If either cache_archive or cache_option are missing, Java Plug-in will treat the applet normally using the archive attribute.

Note: Caching of the JAR files specified in the manifest's CLASSPATH variable using Java Plug-in's cache is currently not supported.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Applet Compatibility -- Microsoft vs Java 2 Virtual Machine

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Applet Compatibility Issues

This document describes all known applet compatibility issues between the Microsoft Virtual Machine (VM) and the Sun Java VM. The term Java SE used here refers to the Java Platform Standard Edition version 1.2 or later.

ClassFormatError

This error is caused by bytecode generated from old JDK 1.0.2 or 1.1 compilers. In the past, a lot of these compilers generated bytecode that does not conform to the Java VM Specification. Since the verifiers in recent J2SE releases are much stricter about bad class format, the ClassFormatError is thrown by the VM when these bad class files are loaded.

Some typical problems in some older class files are the following (note that this list is not exhaustive):

  • There are extra bytes at the end of the class file;
  • The class file contains method or field names that do not begin with a letter;
  • The class attempts to access private members of another class;
  • The class file has other format errors, including illegal constant pool indices and illegal UTF-8 strings;
  • Some early (third-party) bytecode obfuscators produced class files that violated proper class-file format.

You can avoid this type of problem by recompiling your classes with the Javac bytecode compiler from the current JDK. If you choose to use a third-party obfuscator, be sure to use one that produces class files that respect proper class-file format.

To allow some of the applets with bad class files to run in Java SE, Java Plug-in contains a bytecode transformer to transform some of the bad class files to good ones. Currently, only bad class files with the following ClassFormatError may be transformed:

  • Local variable name has bad constant pool index
  • Extra bytes at the end of the class file
  • Code segment has wrong length
  • Illegal Field/Method name
  • Illegal Field/Method modifiers
  • Invalid start_pc/length in local var table

Unfortunately, the following ClassFormatError problems are not fixable by the bytecode transformer:

  • Illegal use of nonvirtual function call
  • Arguments can't fit into locals
  • Unsorted lookup switch
  • Truncated class file

Thus, any class file having any of these problems will not run under Java SE:

Security exception with sun.audio

The sun.audio package was accessible by applets in JDK 1.1. However, in Java SE the applet sandbox was closed up. Thus, applets trying to access any class libraries in the sun.audio package will result in SecurityException.

To provide maximum applet compatibility, the applet sandbox in Java Plug-in has been opened up to allow applets to again access the sun.audio package.

Unable to find resources from AppletContext.getAudioClip() and AppletContext.getImage()

For the Microsoft and Sun implementations, the resource lookup sequence in AppletContext.getImage() and AppletContext.getAudioClip() is different.

In the Microsoft implementation, resources are looked up in the following sequence:

  1. Archives specified through HTML archive or cabbase parameters
  2. codebase URL

In the Sun implementation, resources are looked up simply by codebase URL.

As a result, some applets relying on the resources lookup sequence of the Microsoft VM may not load resources properly in Java SE.

To provide maximum applet compatibility, the resources lookup sequence in Java Plug-in has been changed as follows:

  1. Archives specified through HTML archive parameters
  2. codebase URL

ClassLoader sharing policy

The ClassLoader sharing policy is different in the Microsoft and Sun implementations.

In the Microsoft implementation, a ClassLoader object is shared between applets if and only if:

  • codebase values are the same,
  • archive values are the same, and
  • cabbase values are the same.

In the Sun implementation, a ClassLoader object is shared between applets if and only if codebase values are the same.

Some applets relying on the ClassLoader sharing policy of the Microsoft implementation may not run properly in Java SE because of potential class definition conflicts.

To provide maximum applet compatibility, the ClassLoader sharing policy in Java Plug-in has been changed. A ClassLoader object is now shared between applets if and only if:

  • codebase values are the same,
  • cache_archive values are the same,
  • java_archive values are the same, and
  • archive values are the same.

Security model—Java SE VS Microsoft

Java SE has a new security model which provides much more capability and flexibility than JDK 1.1, while Microsoft's VM security model is based on JDK 1.1 and its own proprietary technologies.

This issue is not fixable. Thus, an applet that relies on the Microsoft's security model will not run properly in Java SE.

Applet packaging

Applet packaging in Java SE and JDK 1.1 is through .jar files, whereas the Microsoft VM supports applet packaging through .jar files and its own proprietary .cab (cabinet) files.

This issue is not fixable. Thus, an applet packaged in Microsoft .cab file format will not be loaded in Java SE.

Java language specification strictness (null vs zero-length string)

In JDK 1.1 the Java language specification was loose in dealing with null and zero-length strings in the class libraries. Some APIs may treat a zero-length string as null, while other APIs may treat null as it is. In Java SE, the Java language specification has been tightened up to specify what the exact behavior should be.

This issue is not fixable. Thus, in Java SE an applet that relies on the APIs to treat null as a zero-length string may result in an exception.

Applet signing—RSA vs Authenticode

In Java SE, applet signing is supported through RSA and the .jar file, whereas Microsoft supports applet signing through its own proprietary Authenticode and .cab file technologies.

This issue is not fixable. Thus an applet that relies on Microsoft's Authenticode and .cab file technologies may not load properly in Java SE.

Implementation changes in AWT class libraries

In the past, some programmers assumed that AWT was thread safe. Therefore some applets were written using AWT libraries that interacted with the GUI in multiple threads, assuming that the class libraries took care of synchronization issues. In fact, neither AWT nor Swing are thread safe. Therefore, all code that updates the GUI or processes events should occur on the event dispatching thread. Failure to do so may result in a deadlock or race condition. For more information, see Concurrenecy in Swing in The Swing Tutorial. Although this tutorial specifically covers Swing, in this instance, the same rules apply to all Components.

Java/JavaScript communication

In the Microsoft implementation, an applet's methods and properties exposed in JavaScript in an HTML page are exactly the same as the methods and properties of the applet object. In Java Plug-in, an applet's methods and properties are exposed in JavaScript in an HTML page through JavaBeans Introspection, which analyzes methods and properties through naming conventions in the applet object. The side effect is that applet's fields are treated differently.

This problem will be fixed in a future release of Java Plug-in. In the meantime, JavaScript access to fields in the applet object may not work properly in Java SE.

Microsoft proprietary Java classes, methods, and variables

Microsoft has provided many proprietary class libraries in its VM implementation, including J/Direct, AFC, WFC, etc. For other classes, methods, and variables, see How to avoid potential pitfalls of Microsoft's non-standard SDK for Java.

This issue is not fixable. Thus, applets that rely on any of the Microsoft proprietary Java class libraries will not work properly in Java SE.

Whitespace characters in strings returned from Applet.getParameter()

In the Microsoft implementation, whitespace characters are stripped off before the string is returned to an applet in Applet.getParameter(). On the other hand, Sun's implementation returns the string as it is specified in the HTML parameters. As a result, some JDK 1.1 applets refuse to run in Java SE because the applet's logic doesn't take the whitespace into account.

To provide maximum applet compatibility, the implementation of Applet.getParameter() in Java Plug-in has been changed to strip off whitespace characters in the return value.

Design changes in java.util.Hashtable.hashCode()

In JDK 1.1, Hashtable.hashCode() was implemented based on the object identity; thus, each Hashtable object returns its unique value when hashCode() is called. In Java SE, the implementation of Hashtable.hashCode() was changed to be value-based as part of the Java Collection Framework. A Hashtable object returns its hashcode value based on the objects it contains.

This change breaks some JDK 1.1 applets if they add a Hashtable object into itself, which breaks the fundamental design of the Collection Framework and causes StackOverflowError. It breaks logic in some applet code that relies on Hashtable.hashCode() to return a constant value from the same Hashtable object.

To provide maximum applet compatibility, the implementation of Hashtable.hashCode() has been changed to check for this special case to avoid stack overflow.

Accessing frame from applet

To track mouse events or for some other reasons, an applet may sometimes try to access its frame . In the Microsoft and Sun implementations, the number of containers between the frame and the applet is different.

An applet that relies on a frame being at a particular level of containment in the Microsoft VM, without navigating the entire AWT hierarchical component tree, is likely to fail in Java SE. The most common symptom is ClassCastException from the AWT Dispatch Event Thread.

This issue is not fixable. Thus, an applet with this issue may not run properly in Java SE.

MAYSCRIPT

In Netscape Navigator and Java Plug-in, an applet accessing JavaScript is required to specify the MAYSCRIPT attribute in the applet element. Microsoft's implementation, however, doesn't honor this special parameter; it allows an applet to access JavaScript under all conditions. Since most of Internet applets target Microsoft's VM instead of Netscape's, MAYSCRIPT is not specified in these applets.

To provide maximum applet compatibility, the MAYSCRIPT check has been removed from Java Plug-in.

HTTP User-Agent

In the Microsoft and Sun implementations, different HTTP User-Agent strings are passed to the server when an HTTP connection is requested. Most web sites target Microsoft's VM instead of Sun's and do not recognize Sun's HTTP User-Agent.This may result in failure.

For that reason, the HTTP User-Agent string used in Java Plug-in has been made similar to the Microsoft one. Thus, most web servers will recognize requests made from applets running in Java Plug-in.

Events during applet startup and shutdown

In the Microsoft and Sun implementations, the events occurring during applet startup and shutdown may not be exactly the same. For example, the logic in the applet may rely on the applet being visible when Applet.start() or Applet.stop() is called, which may be true in the Microsoft implementation but not in Sun implementation.

An applet that relies on specific events during applet startup and shutdown in the Microsoft VM may not function properly in Java SE. The most common symptom is NullPointerException from the AWT Dispatch Event Thread.

This issue is not fixable.

Java class libraries compatibility

There are many changes in the Java class libraries and Java SE. Some APIs are clarified, some are depreciated, and some have altered implementations. The following have caused some applets run in the Microsoft VM to fail in Java SE:

  • java.awt.Graphics.drawString()

    drawString() treats null as an empty string in the Microsoft VM. In Java SE, drawString() treats null as it is and throws NullPointerException.
  • java.awt.Graphics.drawImage()

     drawImage() ignores null image in the Microsoft VM. In Java SE, drawImage() treats null as it is and throws NullPointerException.
  • java.awt.Color constructors

    In the Microsoft VM, passing over-bound/under-bound values in the Color constructor will cause the VM to print out a warning message in the console, but the values will be reset to max/min automatically. In Java SE, Color constructor checks for illegal values and throws IllegalArgumentException.
  • Thread.stop(), Thread.suspend(), Thread.resume()

     In the Microsoft VM, stopping, suspending, or resuming a dead thread will cause the call to be ignored. In Java SE, calling these methods on a dead thread will result in AccessControlException.

Applets affected by these issues will result in exceptions and may not run properly in Java SE.

Java Moniker

This is a proprietary Microsoft technology that is not supported by Java SE.

object attribute with PARAM element

With the conventional applet format, use of an attribute named object with a PARAM element will cause an exception with the Sun VM: 'Either "code" or "object" should be specified, but not both.' With the Microsoft VM, no exception will be thrown. This is a compatibility issue. To avoid the exception with the Sun VM, do not use an attribute named object with a PARAM element in an applet.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Applet Caching and Installation in Java Plug-in

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

< Contents

Applet Caching

This section covers the following topics:

  • Caching Option
    • cache_archive
    • cache_version
    • cache_archive_ex
    • Cache Update Algorithm
  • Security
  • Known Issues

Caching Option

When an applet is cached, it no longer needs to be downloaded when referenced again. This reduces applet startup time. All file types used by Java Plug-in applets are now cached.

An alternative form of applet caching is provided which allows an applet deployer to decide if an applet should be sticky A sticky applet is placed in a disk cache created and controlled by Java Plug-in which the browser cannot overwrite. The only time a sticky applet gets downloaded after caching is when it is updated on the server. Otherwise the applet is always available for fast loading. Applets providing core business applications should be made sticky to improve startup performance.

This feature is activated by including the cache_archive, cache_version , and cache_archive_ex values in the OBJECT/EMBED tag as described below.

Note

.jar files specified with the archive attribute also get cached in this sticky cache.

cache_archive

The cache_archive attribute contains a list of the files to be cached:

<PARAM NAME="cache_archive" VALUE="a.jar,b.jar,c.jar">

Like the archive attribute in the APPLET tag, the list of .jar files in the cache_archive attribute do not contain the full URL, but are always downloaded from the codebase .

cache_version

The cache_version is an optional attribute. If used, it contains a list of file versions to be cached:

<PARAM NAME="cache_version" VALUE="1.2.0.1, 2.1.1.2, 1.1.2.7">

Each version number is in the form xxxx.xxxx.xxxx.xxxx, where x is a hexadecimal number. Each version number corresponds to a respective .jar file in the cache_archive.

cache_archive_ex

In order to allow pre-loading of .jar files, the HTML parameter cache_archive_ex can be used. This parameter allows you to specify whether the .jar file needs to be pre-loaded; optionally the version of the .jar file can also be specified. VALUE for cache_archive_ex has the following format:

VALUE="<jar_file_name>;<preload(optional)>;<jar_file_version(optional)>,<jar_file_name>;
       <preload(optional)>;<jar_file_version(optional)>,..."

The optional tags preload and jar_file_version can appear after the jar_file_name in any order separated by the delimiter ";". "," separates multiple entries.

The following shows how these tags might be used in an HTML page:

<OBJECT ....
<PARAM NAME="archive" VALUE="a.jar">
<PARAM NAME="cache_archive" VALUE="b.jar, c.jar, d.jar">
<PARAM NAME="cache_version" VALUE="0.0.0.1, 0.0.2A.1, 0.3D.22.FFFE">
<PARAM NAME="cache_archive_ex" VALUE="applet.jar;preload, util.jar;preload;0.9.0.AC1, tools.jar;0.9.8.7F">
</OBJECT>

In the above example, a.jar is specified in archive, whereas b.jar, c.jar and d.jar are specified in cache_archive. The versions are also specified for b.jar, c.jar, and d.jar as 0.0.0.1, 0.0.2A.1, and 0.3D.22.FFFE, respectively. In cache_archive_ex, applet.jar is specified to be pre-loaded. util.jar is also specified to be pre-loaded but along with the version. For tools.jar, only version is specified.

Java Plug-In doesn't compare the versions if they are not specified for all the .jar files specified in HTML parameter cache_archive. If cache_archive is used without cache_version, the .jar files specified in cache_archive are treated no differently than the .jar files specified in HTML parameter archive. Similar treatment is given to .jar files specified in cache_archive_ex when preload and version options are not provided.

Class files and resources will be searched in the following order from the .jar files specified by the HTML parameters

  1. cache_archive_ex
  2. cache_archive
  3. archive

Applet Caching Update Algorithm

By default, without the cache_version attribute, applet caching will be updated if:

  • The cache_archive has not been cached before, or
  • The "Last-Modified" value of the cache_archive on the web server is newer than the one stored locally in the applet cache, or
  • The "Content-Length" of the cache_archive on the web server is different from the one stored locally in the applet cache.

However, in some situations, the "Last-Modified" value returned from the web server through HTTP/HTTPS may not reflect the actual version of the applets. For example, if the web server crashes and all the files are restored, the cache_archive may have a different modification date on the server. Even if the cache_archive has not been updated, it will still force all the Java Plug-in clients to download the cache_archive again.

To strongly enforce the version update, it is recommended that the applet deployer use the cache_version attribute.

If cache_version is used, applet caching will be updated if the cache_version for the cache_archive is larger than the one stored locally in the applet cache. Note that the version number is used for triggering an update; there is no actual version number attached to the .jar file on the web server. In fact, unless version is used to trigger an update, it is possible the applet on the web server could be updated without the applet in cache_archive.

Using cache_version eliminates the need to connect to the web server to obtain "Modification-Date" and "Content-Length" of the cache_archive. In most cases this will speed up performance.

Security

Although sticky applets are cached locally, they will still conform to the security policy defined by their original codebase and signer.

Versioning Support

Java Plug-in 6 applets can use the JNLP Version Download protocol for launching JAR resources listed in the HTML file. Versioning also supports JarDiff. To use versioning support use the archive_x tag where x specifies a number. The following is the syntax of the archive_x tag.

  • First value must be the jar filename
  • Each value must be separated by comma
  • Use preload to indicate preloading of the jar file
  • version= is used to specify the version string for the jar file request

The following are the various ways in which the archive_x tag can be used.

<PARAM NAME="archive_1" VALUE="a.jar, preload, version=2.0+">

  • The + sign after the version indicates the Java Plug-in to request for a jar file whose version is equal to or higher than the specified version
<PARAM NAME="archive_1" VALUE="a.jar, preload, version=2.0*">
  • The * sign after the version indicates the Java Plug-in to request for a jar file whose version begins with 2.0, e.g 2.0.1 or 2.0.2
<PARAM NAME="archive_2" VALUE="b.jar, version=0.0.0.3">
  • This allows Java Plug-in to request for a jar file whose version is exactly 0.0.0.3

Note

The archive_x tag is ignored if it found within the cache_archive, cache_version and cache_archive_ex tag.

Applets using JNLP style version support should use the JNLPDownloadServlet to host the applet resources. More information about JNLP Version Download protocol and JNLPDownloadServlet is available in the JNLP Guide.

Known Issues

  • Caching of the .jar files specified in the manifest's Class-Path variable using Java Plug-in's cache is currently not supported.
  • The path specified in the cache_archive must be a relative URL to the applet's codebase. Full URLs are not supported in cache_archive.
  • The "java.io.IOException: Caching not supported for ..." is thrown because Java Plug-in could not get the expiration and last-modification dates for a given JAR file from the web server. If the Java Plug-in cannot get the date information, the JAR file is downloaded every time it is used.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Applet Deployment

Rich Internet Applications Deployment Advice > Applet Deployment

Contents

  • Introduction
  • Reference: New Parameters to APPLET, OBJECT, EMBED elements
    • Deployment using JNLP
      • jnlp_href
    • Loading Screen
      • boxborder
      • centerimage
    • Command-line Arguments
      • java_arguments
      • separate_jvm
    • JRE Version Selection
      • java_version
      • class-id attribute in Internet Explorer
      • version and jpi-version attributes in the Mozilla Browser family
    • Class Loader Caching
      • classloader_cache

Introduction

Applets may be deployed by hand coding the applet, object or embed tags with the required parameters. However, to assure cross browser compatibility, it is recommended that the Deployment Toolkit be used to deploy applets. Applets may be deployed and launched via:

  • Applet, object or embed tags, or,
  • JNLP

Please refer to the Deployment Advice document for information on using the Deployment Toolkit and deploying applets using JNLP.

Reference: New Parameters to APPLET, OBJECT, EMBED elements

Deployment using JNLP

jnlp_href

The file containing information that the plug-in should use to launch the applet.

Loading Screen

The new plug-in offers better customization of the image which is displayed before the applet is loaded. Animated GIFs are now supported as the target of the image parameter, as described in the Special Attributes section of the old Java Plug-In Guide. Additionally, the following new parameters are now supported:

boxborder

A boolean parameter indicating whether a one-pixel border should be drawn around the edge of the applet's area while displaying the image shown before the applet is loaded. Defaults to true. We recommend setting this value to false, in particular when using an animated GIF as the loading image, to avoid the possibility of flicker.

centerimage

A boolean parameter indicating whether the loading image should be centered within the area of the applet instead of originating at the upper left corner. Defaults to false.

Example using the boxborder and centerimage parameters:

   <APPLET archive="large_archive.jar"
                   code="MyApplet"
                   width="300" height="300">
          <!-- Use an animated GIF as an indeterminate progress bar
                   while the applet is loading -->
          <PARAM NAME="image" VALUE="animated_gif.gif">
          <!-- Turn off the box border for better blending with the
                   surrounding web page -->
          <PARAM NAME="boxborder" VALUE="false">
          <!-- Center the image in the applet's area -->
          <PARAM NAME="centerimage" VALUE="true">
        </APPLET>

Command-line Arguments

java_arguments

Specifies JVM command-line arguments to be used when executing this applet instance. Nearly all JVM command-line arguments are supported, though there are certain rules and restrictions.

Examples

  1. Specifying a larger-than-default maximum heap size:
    <APPLET archive="my_applet.jar" code="MyApplet" width="300" height="300">
    <PARAM name="java_arguments" value="-Xmx128m">
</APPLET>
  2. Specifying a non-default heap size and a Java 2D hardware acceleration option typically used for applets using OpenGL via JOGL:
    <APPLET archive="my_applet.jar" code="MyApplet" width="300" height="300">
    <PARAM name="java_arguments" value="-Xmx256m -Dsun.java2d.noddraw=true">
</APPLET>
  3. Enabling verbose output of the garbage collector, and the assertion facility in the Java programming language:
    <APPLET archive="my_applet.jar" code="MyApplet" width="300" height="300">
    <PARAM name="java_arguments" value="-verbose:gc -ea:MyApplet">
</APPLET>

A set of "secure" JVM command-line arguments and system properties is defined in the JNLP File Syntax section of the Java Web Start Developers' Guide. In the new plug-in, as long as all of the JVM command-line arguments specified via the java_arguments parameter are secure, then the applet, or any classes it loads, may be unsigned.

Insecure JVM command-line arguments (in other words, those not on the secure list) may also be specified via the java_arguments parameter. In this case, there is the potential for a security risk, so the Java Plug-In enforces the rule that no unsigned classes may be loaded. In other words, only trusted code, for which the user has accepted the security dialog, may be loaded by such a JVM instance. If an attempt is made to load an unsigned or untrusted class in a JVM instance for which insecure system properties have been specified, a ClassNotFoundException will be thrown indicating that the given class could not be loaded because it was not signed.

There are relatively few restrictions on what command-line arguments may be passed via the java_arguments parameter. In general, the -Xbootclasspath argument is forbidden, as well as any command-line argument used to specify a path, such as -classpath or -jar. All other command-line arguments, present and future, should be supported, with the caveat about secure and insecure command-line arguments described above.

The command-line arguments passed via the java_arguments parameter are added to any specified via the Java Applet Runtime Settings dialog in the Java Control Panel. The command-line arguments from the control panel are used for all JVM instances of the version for which they are specified; the java_arguments parameters do not completely replace them. (The Java Applet Runtime Settings dialog has also been enhanced in 6u10 to better manage multiple JRE versions, and now has the same capabilities as the Java Applet Runtime Settings dialog used for Java Web Start.)

When JVM command-line arguments are specified, it is likely that the new plug-in will need to launch another JVM instance in order to satisfy them. In other words, it is unlikely that a preexisting JVM instance will have been started with the correct set of command-line arguments to satisfy the request. The rules for exactly when a new JVM instance is launched to start a given applet are deliberately left unspecified, as this functionality is brand new in the 6u10 release and may need to change in subsequent releases. Here is a rough set of guidelines for the sharing and creation of new JVM instances:

  • If the command-line arguments used to start a preexisting JVM instance are a superset of the requested arguments, the preexisting JVM instance will be used.
  • If a JVM instance is launched for the "default" set of command-line arguments (i.e., those specified in the Java Control Panel, with no java_arguments specified), then this JVM instance will never be used to launch any applet that has even one command-line argument specified via java_arguments.
  • -Xmx is handled specially: if a preexisting JVM instance was started with for example -Xmx256m via java_arguments, and a new applet requests -Xmx128m, then new applet will very likely be run in the preexisting JVM instance. In other words, -Xmx specifications are matched with a greater-than-or-equal test.

There is no way to "name" a JVM instance used to launch a particular applet and "force" subsequent applets into that JVM instance.

See the section on the separate_jvm parameter to isolate a particular applet in its own JVM instance, separate from all other applets.

separate_jvm

A boolean parameter specifying that a particular applet should run in its own JVM instance. This supports certain powerful desktop applets which can not tolerate any interference from other applets running in the same JVM and potentially consuming heap space or other resources.

<APPLET archive="my_applet.jar" code="MyApplet" width="300" height="300">
    <PARAM name="java_arguments" value="...">
    <PARAM name="separate_jvm" value="true">
</APPLET>

JRE Version Selection

java_version

Specifies a JRE version upon which to launch a particular applet.

Examples

  1. Specifying a particular JRE version for a particular applet:
    <APPLET archive="my_applet.jar" code="MyApplet" width="300" height="300">
    <PARAM name="java_version" value="1.5.0_09">
</APPLET>
  2. Requesting any JRE in a particular family for a particular applet:
    <APPLET archive="my_applet.jar" code="MyApplet" width="300" height="300">
    <PARAM name="java_version" value="1.5*">
</APPLET>
  3. Specifying a JRE from a particular family or any later family:
    <APPLET archive="my_applet.jar" code="MyApplet" width="300" height="300">
    <PARAM name="java_version" value="1.5+">
</APPLET>

classid Attribute in Internet Explorer

The Internet Explorer browser uses the classid attribute of the <object> tag to indicate how the content of that tag should be displayed. The classid attribute can be used in conjunction with the codebase attribute to automatically download and install a particular JRE version if none is currently available on the system (see classid usage). The family CLSID concept was introduced more recently to provide a way to select an arbitrary JRE in a given family.

Not all of the classid options described in earlier documentation work in conjunction with the new Java Plug-In to both select, and potentially automatically download and install, a particular JRE version. This section describes what works in conjunction with the new plug-in, and what backward compatibility mechanisms are in place.

Recommended Usage

The recommended usage of the classid attribute is in conjunction with the java_version parameter described above. The dynamic classid, which always points to the latest installed JRE version, should be specified in the <object> tag in order to indicate that the latest version of the Java Plug-In, with multiple JRE support, should be used. The java_version parameter should then be used to specify the version of the JRE to use to run the applet.

Example of recommended usage:

  <object
    classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
    codebase="http://java.sun.com/out-of-proc-plugin-url-placeholder.exe#1,6,0,10"
    width="200" height="200">
      <param name="code" value="MyApplet">
      <param name="java_version" value="1.5*">
  </object>

Note that, at the current time, Sun Microsystems, Inc. is not providing a new CLSID to describe the new Java Plug-In, but instead overloading the usage of the dynamic classid. This means that if a previous version of the JRE is already installed which does not have multiple JRE version support in the Java Plug-In, the new Java Plug-In will not be automatically downloaded and installed, since a handler for that classid is already available. The result will be that the version selection via the java_version parameter will be ignored. The decision to not provide a new classid may be revisited in the future. For the time being, Sun expects that sophisticated developers requiring multiple JRE version selection and automatic download of the new Java Plug-In will either document that their users must install and configure the new Java Plug-In in order to properly run their content, or will have administrative control over the client machines, as is common in many enterprises.

Backward Compatibility

To ease the transition for developers already using the classid attribute, two backward compatibility mechanisms have been introduced: the ability to use a classid to select either a specific JRE version, or an arbitrary JRE in a given family. In both cases, the expectation is that both the new Java Plug-In, and the target JRE version for the applet, are already installed and configured. In conjunction with these backward compatibility mechanisms, auto-downloading of any JRE, either the one supplying the new Java Plug-In or the one to be used to run the applet, is not supported.

Note that these backward compatibility mechanisms may be removed in a future release. Sun recommends transitioning existing content to the new mechanisms described above.

Selecting a particular JRE version (1.5.0_11) for an individual applet:

  <object
    classid="clsid:CAFEEFAC-0015-0000-0011-ABCDEFFEDCBA"
    width="200" height="200">
      <param name="code" value="MyApplet">
  </object>
Selecting the latest JRE from a particular family (1.5) using the family CLSID:
  <object
    classid="clsid:CAFEEFAC-0015-0000-FFFF-ABCDEFFEDCBA"
    width="200" height="200">
      <param name="code" value="MyApplet">
  </object>

Note that attempts to download older versions of the JRE using the codebase parameter will be ignored, because these classids are registered on the system to point to more recent versions of the DLLs during the installation process of the new Java Plug-In. Note also that the use of the java_version parameter in conjunction with these classids is not supported. Specifying both the java_version parameter as well as either a static or family classid will result in undefined behavior.

version and jpi-version attributes in the Mozilla Browser Family

The Mozilla browser family uses the MIME type in the <embed> tag to indicate how the content of that tag should be displayed. The <embed> tag also supports automatic downloading of a particular version of the JRE.

Previous versions of the Java Plug-In used the version and jpi-version portions of the application/x-java-applet MIME type to perform JRE version selection. Not all of these mechanisms described in earlier documentation work in conjunction with the new Java Plug-In to both select, and potentially automatically download and install, a particular JRE version. This section describes what works in conjunction with the new plug-in, and what backward compatibility mechanisms are in place.

Recommended Usage

The recommended usage of the <embed> tag is to not specify any version or jpi-version in the MIME type of the applet. Instead, use the java_version parameter to choose a particular JRE version upon which to run the applet. If no previous Java version is installed, auto-download of the new Java Plug-In can be enabled using the pluginspage parameter:

  <embed code="MyApplet"
    type="application/x-java-applet"
    pluginspage="http://java.sun.com/out-of-proc-plugin-url-placeholder.xpi"
    width="200" height="200">
    java_version="1.5*"
  </embed>

Note that, at the current time, Sun Microsystems, Inc. is not providing a new MIME type to describe the new Java Plug-In, but instead overloading the usage of the application/x-java-applet MIME type. This means that if a previous version of the JRE is already installed which does not have multiple JRE version support in the Java Plug-In, the new Java Plug-In will not be automatically downloaded and installed, since a plugin supporting that MIME type is already available. The result will be that the version selection via the java_version parameter will be ignored. The decision to not provide a new MIME type may be revisited in the future. For the time being, Sun expects that sophisticated developers requiring multiple JRE version selection and automatic download of the new Java Plug-In will either document that their users must install and configure the new Java Plug-In in order to properly run their content, or will have administrative control over the client machines, as is common in many enterprises.

Backward Compatibility

To ease the transition for developers already using the version and jpi-version portions of the MIME type, a limited degree of backward compatibility is supported in the new Java Plug-In. Specifically, the version attribute is supported to request an arbitrary JRE in a given family or any later family. Using the jpi-version attribute to select a particular JRE version is no longer supported. Its use is strongly discouraged since it may disrupt correct operation of the new Java Plug-In.

Note that this backward compatibility mechanism may be removed in a future release. Sun recommends transitioning existing content to the new mechanisms described above.

To use the version attribute to require the 1.5 JRE or a later one:

  <embed code="MyApplet"
    type="application/x-java-applet;version=1.5"
    width="200" height="200">
  </embed>

Note that the semantics of the version attribute imply that the above tag is equivalent to using the java_version parameter with a value of 1.5+. Since the new Java Plug-In is delivered with Java SE 6 update 10, which is a later version than 5.0, this version request essentially has no effect.

Note also that combining the version attribute with the java_version parameter is not supported. Specifying both the java_version parameter as well as a version attribute will result in undefined behavior.

Class Loader Caching

classloader_cache

The new plug-in provides a way to opt out of the use of the class loader cache on an applet by applet basis.

<APPLET archive="my_applet.jar" code="MyApplet" width="300" height="300">
    <PARAM name="classloader_cache" value="false">
</APPLET>

The default value of the classloader_cache parameter is true; class loader caching is enabled by default.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Applet Developer's Guide

Rich Internet Applications Development and Deployment > Applet Developer's Guide

Java™ Plug-in technology (hereafter the "Java Plug-in"), which is included in the Java Runtime Environment, enables Java applets to run in popular web browsers on the desktop. The next-generation Java Plug-in, new in Java SE 6 update 10 release, provides powerful new capabilities to applets in the web browser, while improving the overall reliability and functionality of applets in a backward-compatible manner.

The next-generation Java Plug-in offers a completely redesigned architecture. Instead of executing applets in the same operating system process as the web browser, the new plug-in runs one or more Java virtual machine instances ("JVMs") which connect back to the browser for full interoperability with the surrounding web page. This architectural change offers many advantages and enables several new features.

  • Improved reliability. The JVM running the applet is isolated from the web browser at the operating system level. If something should go wrong while running the applet, or if an uncooperative applet refuses to shut down, the new Java Plug-in detects and handles the error condition gracefully; the web browser is unaffected.
  • Built-in JNLP support. The new Java Plug-in offers the capability to launch applets directly from JNLP files, unifying deployment of Java content both in the browser and out of the browser (via Java Web Start). Developers can now reuse JNLP extensions for advanced functionality including the 3D graphics via OpenGL and planetary-scale terrain visualization within applets. Applets can now access JNLP APIs for persistent data storage, local file system access, and other useful functionality from sandboxed code.
  • Improved user experience. The new Java Plug-in starts applets in the background, so the web browser always remains responsive. Applets appear on the web page as they become ready to run.
  • Improved Java/JavaScript communication. The bridge between the JavaScript engine in the web browser and the Java programming language has been completely reimplemented. The new implementation is backward-compatible and features improved reliability, performance and cross-browser portability, for both Java calling JavaScript as well as JavaScript calling Java. Formerly Mozilla-specific "LiveConnect" functionality, such as the ability to call static Java methods, instantiate new Java objects and reference third-party packages from JavaScript, is now available in all browsers.
  • Improved applet lifecycle management. Calls to the applet lifecycle methods init, start, stop, and destroy are more deterministic and cross-browser behavior has been improved. The applet class loader cache and the legacy applet lifecycle, required for backward compatibility, are fully supported and the behavior of both has been improved.
  • Better large heap support. Historically, the maximum heap size that could be specified for applets via the Java Control Panel has been limited. This limitation is fixed in the new Java Plug-in; applets can now utilize as much heap space as command-line applications.
  • Better Windows Vista support. Signed applets running in Protected Mode Internet Explorer on Microsoft's Windows Vista now have the same privileges as normal user applications, eliminating a portability barrier to this platform.
  • Per-applet command-line arguments. JVM command-line arguments may be specified in the HTML of the web page on a per-applet basis, providing fine-grained control over options such as the heap size and Java 2D hardware acceleration features.
  • Multiple JRE version support. Each individual applet instance may request a different JRE version on which to run. This feature is designed for enterprise customers which prefer to qualify their applets against either a particular JRE version or a particular JRE family. Both selection of a specific JRE version, or any in a particular family, are supported in the new Java Plug-in.

The following topics provide more information about developing and deploying applets that leverage the next-generation Java Plug-in.

  • Applet Development Tutorial - A comprehensive Java Tutorial that explains various aspects of applet development and deployment.
  • Java Plug-in and Applet Execution Architecture
  • Applet Deployment

The following topics provide information about the next generation Java Plug-in.

  • Plug-in Configuration
  • Browsers Supported
  • Release Notes for the Next-Generation Java Plug-in Technology

The following topics provide information about the old Java Plug-in available before the Java SE 6 update 10 release.

  • Old Java Plug-in Guide
  • Java Deployment Guide

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Plug-In and Applet Architecture

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java™ Plug-in and Applet Architecture

Applet Developer's Guide > Java Plug-in and Applet Architecture

Contents

  • Architecture
    • Java Runtime Environment
    • Java Runtime Environment Version Selection
    • Thread Considerations
    • Classloader Cache and Interaction between Applets
    • Applet Garbage Collection
    • Applet Privileges
    • Proxy Configuration
    • Security
  • Best Practices for Applet Development

This document describes how the next-generation Java Plug-in, introduced in the Java SE 6 update 10 release, controls the execution of applets and interactions between applets and the browser.

Architecture

Java Runtime Environment

With the next-generation Java Plug-in, the JRE no longer runs inside the browser. Instead, the JRE runs in a separate process. By default, all applets run in the same JRE instance. However, applets can now specify the JRE version they require to run on. More than one JRE instance will be launched when different versions of the JRE are needed, or when the applet requires more resources than any currently extant instance can supply.

In the Java SE 7 release, if a JRE instance has less than 32 MB of available heap memory or more than 50 application threads, the JRE instance is considered unavailable. In this case, applets are run in a new JRE instance.

Java Plug-in running applets on different JRE versions

The browser and the applet can still communicate with one another, however. Existing APIs have been re-engineered to use process sockets, so things continue to work as they did before--only better. This architecture provides a number of benefits:

  • Applets that require different versions of the JRE can run simultaneously.
  • Applets can specify JRE start-up parameters such as heap size. (A new applet uses an existing JRE if it's requirements are a subset of an existing JRE, otherwise, a new JRE instance is launched.)
  • The message-passing interfaces are written in Java, so they run on all supported platforms, in the same way, so cross-browser compatibility is enhanced.

With that architecture, a new JRE can be launched whenever it is needed. But an applet will run in an existing JRE as long as:

  1. The JRE version required by the applet matches an existing JRE, and
  2. The JRE's launch parameters satisfy the applet's requirements

Note:

  • If two applets each require a large amount of memory, they might both run in the same JRE, causing one of them to run out of memory. But that's only a concern when you have multiple applets running simultaneously.
  • The Java browser plugin finds available JREs by inspecting the Java Control Panel.

Java Runtime Environment Version Selection

On all platforms, the new Java Plug-in locates JREs to use from the entries listed in the Java Control Panel ("Java" tab, "View" button under "Java Applet Runtime Settings"). The available JREs in this list are encoded in the deployment.properties file whose location is platform-dependent. On the Windows platform, it is generally located in C:\Documents and Settings\[username]\Application Data\Sun\Java\Deployment. On Unix platforms, it is generally located in ~/.java/deployment/deployment.properties.

On Windows platforms, both the Java Control Panel and the new Java Plug-in will automatically detect the installed JREs and add them to the available set. On Unix platforms, auto-detection of installed JREs is not supported. The Java Applet Runtime Settings dialog in the Java Control Panel may be used to manually add JREs to the known list for the new Java Plug-in.

By default the new Java Plug-in will execute all applets in the latest JRE version named in this list. It will only execute an applet on an earlier JRE version if explicitly requested.

When considering a request to launch an applet on a specific JRE version (for example, a particular update release like "1.5.0_11"):

  1. The list of available JREs is consulted. If there is an exact match of the version string, that JRE version is selected. Otherwise, if there are one or more installed JREs in the same family, the latest version is selected. Otherwise, the latest available JRE on the machine is selected.
  2. The selected JRE version is compared against the security baseline for the family. If it is equal to or more recent than that version, no further prompting is done and the applet is launched.
  3. Otherwise, the code for the applet is downloaded in a JVM instance of the selected JRE version. If the applet is signed and the user accepts the security dialog for the applet (or the code source has already been trusted), no further prompting is done and the applet is launched.
  4. Otherwise, we are dealing with an unsigned applet on an "older" JRE version. A dialog box is presented indicating that this applet is requesting to run on top of an older JRE release, and asks the user whether he or she wants to allow it to. If the user clicks "yes", the applet is launched. If the user clicks "no", the applet is re-launched on top of the latest available JRE version.

When considering a request to launch an applet on a particular family, the most recent JRE from that family will be selected and the above steps starting from (2) will be followed.

When considering a request to launch an applet on a particular family or any later family, the latest available JRE will be used to launch the applet.

Thread Considerations

A web browser's JavaScript interpreter engine is single thread. The Java Plug-in is capable of managing multiple threads. The Java Plug-in creates a separate worker thread for every applet. Applets themselves may be multi-threaded. Applets making JavaScript to Java calls and vice versa, should be designed with the thread related issues in mind.

The following picture shows the thread interactions between the JavaScript Interpreter, Java Plug-in and an applet (i.e. Java).

JavaScript Interpreter, Java Plug-in and Applet Thread Interactions

When the JavaScript interpreter is idle, the Java Plug-in executes a JavaScript to Java call on the per applet worker thread (JavaScript Interpreter Not Busy scenario).

When a Java to Javascript call is in progress and a JavaScript to Java call is made, the latter is executed on the same thread that made the Java to JavaScript call (Round Trip scenario).

When a thread is executing a Java to JavaScript call, another thread wanting to do the same will be blocked till the first thread has received its result and is done (JavaScript Interpreter Busy scenario)

In order to avoid thread related issues especially when multiple applets are running simultaneously, keep both Java to JavaScript and JavaScript to Java calls short and avoid round trips, if possible.

Classloader Cache and Interaction between Applets

Normally, if two applets have the same codebase and archive parameters, they will be loaded by the same class loader instance. This behavior is required for backward compatibility, and is relied on by several real-world applications. The result is that multiple applets on the same web page may access each others' static variables at the Java language level, effectively allowing the multiple applets to be written as though they comprised a single application.

While this feature enables certain kinds of applications to be conveniently written, it has certain drawbacks. It interferes with termination of applets, in particular when multiple instances of the same applet are active. It makes the programming model for applets more complex, since it is under specified exactly when the static fields of an applet will be re-initialized, and when they will be maintained from run to run of the same applet. It causes imprecise behavior of certain user interface operations within the Java Plug-in due to the inability to identify exactly which applet initiated a particular request.

For this reason, the new Java Plug-in provides a way to opt out of the use of the classloader cache on an applet by applet basis.

Applet Garbage Collection

Garbage collection occurs on an applet instance immediately after the destroy method finishes. The garbage collection applies to all memory acquired by the applet, except for static variables . Statics are preserved in the classloader cache, along with the classes themselves, for as long as the class loader is present.

So when does the class loader go away? That behavior is not specified. It's up to the implementation of the Java virtual machine and its interactions with the operating system. You can expect it be retained for as long as possible, but to be discarded when the memory is needed for other purposes.

Applet Privileges

An applet runs in a secure sandbox that prevents it from interacting with the users system, unless authorized. To obtain that authorization, the applet can provide a security certificate that the user must accept. A security certificate is needed to:

  • Print
  • Access the file system
  • Access browser cookies
  • Access other system resources

The basic applet security model is an all or nothing proposition. If you get a security certificate, you can give the applet full access to the user's system. Without it, the applet has virtually no access at all.

Deployment of applets using JNLP allows them to avail a more fine-grained security model (similar to Java Web Start applications), that gives them controlled access to a user's system, under control of the user. (For example, the ability to save or open a file selected by the user and the ability to print.)

Proxy Configuration

See Proxy Configuration in Java Deployment Guide for details.

Security

See Security in Java Deployment Guide for details.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


About Applet Tag Support in Java Plug-in

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

About APPLET Tag Support in JavaTM Plug-in

Note

For more information about compatibility issues between the Microsoft VM and Sun's, see Appendix 4: Microsoft VM and Java Applet Compatibility Issues.

Q: Why should I encourage people to use the Java Platform?

A: The Java Platform is richer than its predecessors in functionality, performance, and security options. As a developer, you want the users of your software to have the most feature-complete Java platform possible so that the full range of APIs and libraries are available for your applications. If your customers are using the Java Platform, you can write more powerful, robust, and full-featured applications and applets. And with the Java Platform the performance of your code will be better too.

By using the latest Java Plug-in with APPLET tag support, you can help to ensure that clients running your applets will have the latest Java Platform.

Q: Can I continue to use OBJECT tags to call my applets?

A: Yes. Even though the Java Plug-in has been enhanced to support APPLET tags, it is fully backward compatible with existing web pages that use OBJECT tags to launch applets.

Q: Are there compatibility issues with using the Java Platform?

A: In the large majority of cases, there are no compatibility issues to be concerned about when moving from JDK 1.1 to the Java Platform. The documentation for a given Java Platform release describes all known incompatibilities, most of which are in the category of "corner cases." For example, known compatibility issues in version 1.4 of the Java Platform are described at http://java.sun.com/j2se/1.4/compatibility.html.

Some old class files generated by early bytecode compilers do not strictly conform to the proper class-file format, and the Java Runtime Environment may not load such classes.

In addition to compatibility issues between different releases of the Java platform, there is the question of incompatibilities between Sun's Java runtime environment and other Java runtime environments; e.g., the one included with some Internet Explorer browsers. Sun has made a great effort to minimize such incompatibilities. Among the steps that Sun as taken in this JRE/Java Plug-in are the following:

  • The classloader sharing policy in Java Plug-in has been changed to minimize incompatible behavior in applets that depend explicitly on the classloader sharing policy of the Microsoft VM.
  • The image and sound resource lookup sequence in Java Plug-in has been changed to give resources specified with the HTML archive paramater priority over those on the codebase URL. This change was made to minimize incompatible behavior for applets that rely explicitly on the resource lookup sequence employed by the Microsoft VM.
  • The implementation of AppletgetParameter() has been modified to strip off leading and trailing whitespace from parameters before they are returned to the applet. This is the behavior of the Microsoft VM in some Internet Explorer browsers, and this change was made to eliminate possible incompatibile behavior in applets that rely explicitly on that behavior.

Q: What security model does Java Plug-in use?

A: JRE/Java Plug-in is a product in the Java Platform family, and it uses the new Java Platform's security model. This security model is more flexible and configurable than the security model used by JDK 1.1. For more information, see the Java Platform's security documentation at http://java.sun.com/j2se/1.4/docs/guide/security/index.html.

Note that applets that rely explicitly on proprietary technology in the security model of the Microsoft VM may not work with Java Plug-in.

Q: My applet fails with a ClassFormatError. What's wrong?

A: This problem may be caused by bytecode generated by old compilers. Such bytecode may not conform to the virtual machine specification, which is more strictly enforced by recent releases of the JRE.

Q: Why doesn't Java Plug-in load my applet's cab file?

A: The Java Plug-in supports applet packaging in .jar files. It does not support the Microsoft proprietary .cab file format. Therefore any applets packaged in Microsoft's .cab file format will not load in JRE/Java Plug-in.

Q: Will my Authenticode-signed applet work with Sun's JRE/Java Plug-in?

A: No. The Sun JRE/Java Plug-in does not support Microsoft proprietary technology such as Authenicode signing and .cab file formats. Signed applets that rely on Microsoft's Authenticode technology will not load in JRE/Java Plug-in.

Q: My applet uses J/Direct, AFC, and WFC, etc. Will it work in Sun's JRE/Java Plug-in?

A: No. Libraries for these and other proprietary Microsoft technologies are not included with JRE/Java Plug-in. Applets that rely on these Microsoft proprietary technologies will not work properly when run on JRE/Java Plug-in.

Q: Why does my applet throw a NullPointerException from the AWT Dispatch Event thread?

A: The events that occur during applet startup and shutdown may differ between the Microsoft and Sun implementation of the Java platform. For example, the logic in an applet may rely on the applet being visible when Applet.start()/Applet.stop() is called. That condition may be true when the applet is run on Microsoft's implementation but may not be true on Sun's impelementation.

Applets that rely on specific events that occur during startup and shutdown on Microsoft's implementation of the Java platform may not work properly with JRE/Java Plug-in. The most common symptom of this type of problem is a NullPointerException from the AWT Dispatch Event thread.

Q: Why does my applet throw a ClassCastException from the AWT Dispatch Event thread?

A: The number of containers between the applet and the encompassing frame are different in the Microsoft and Sun implementations. Therefore, an applet that relies on the frame being at some particular level of containment in the Microsoft VM, without navigating the entire AWT hierarchical component tree, is likely to fail when run on Sun's JRE/Java Plug-in. The most common symptom of this problem is a ClassCastException from the AWT Dispatch Event thread.

Q: Does Java Plug-in support Java-JavaScript communication?

A: Yes, Java Plug-in supports basic, bidirectional Java-JavaScript communication. The following, however, is a known incompatibility.

In the Microsoft implementation, applet methods and properties exposed in JavaScript are exactly the same as the methods and fields in the applet object. In Java Plug-in, an applet's methods and properties are exposed in JavaScript through JavaBeansTM introspection, which treats the applet's fields in a different manner than the Microsoft VM. Therefore, JavaScript accessing fields in an applet object may not work the same when run on JRE/Java Plug-in.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


appletviewer - The Java Applet Viewer

The appletviewer command allows you to run applets outside of a web browser.

SYNOPSIS

appletviewer [ options ] urls ...

DESCRIPTION

The appletviewer command connects to the documents or resources designated by urls and displays each applet referenced by the documents in its own window. Note: if the documents referred to by urls do not reference any applets with the OBJECT, EMBED, or APPLET tag, then appletviewer does nothing. For details on the HTML tags that appletviewer supports, see AppletViewer Tags.

The Java 2 JDK contains two implementations of the Java virtual machine:

Note: The appletviewer requires encoded URLs according to the escaping mechanism defined in RFC2396. Only encoded URLs are supported. However, file names must be unencoded, as specified in RFC2396.

  • The Java HotSpot™ Client VM
    The Java HotSpot Client VM is the default virtual machine. Its use of Java HotSpot technology gives it superior performance as compared with the Classic VM. Unless special command-line options are used to invoke the Classic VM instead (see below), appletviewer will always launch an applet to run on the Client VM.
  • The Java 2 Classic VM
    The Java 2 Classic VM is essentially the same virtual machine implementation as in version 1.2 of the Java 2 SDK. It may be invoked by using the -classic command-line option, as in this example:
    appletviewer -classic MyApplet.html

OPTIONS

-debug
Starts the applet viewer in the Java debugger, jdb, thus allowing you to debug the applets in the document.
-encoding encoding name
Specifies the input HTML file encoding name.
-J javaoption
Passes through the string javaoption as a single argument to the Java interpreter which runs the appletviewer. The argument should not contain spaces. Multiple argument words must all begin with the prefix -J, which is stripped. This is useful for adjusting the compiler's execution environment or memory usage.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


AppletViewer Tags

The applet viewer makes it possible to run a Java applet without using a browser. AppletViewer ignores any HTML that is not immediately relevant to launching an applet. However, it recognizes a wide variety of applet-launching syntax. The HTML code that AppletViewer recognizes is shown below. All other HTML code is ignored.

object

The object tag is the HTML 4.0 tag for embedding applets and mult-media objects into an HTML page. It is also an Internet Explorer 4.x extension to HTML 3.2 which allows IE to run a Java applet using the latest Java plugin from Sun.

<object
  width="pixelWidth"
  height="pixelHeight"
>
  <param name="code" value="yourClass.class">
  <param name="object" value="serializedObjectOrJavaBean">
  <param name="codebase" value="classFileDirectory">
   ...
  alternate-text
</object>

Notes:

  • AppletViewer ignores the "classID" attribute, on the assumption that it is pointing to the Java plugin, with the value:

    classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"

  • AppletViewer also ignores the "codebase" attribute that is usually included as part of the object tag, assuming that it points to a Java plugin in a network cab file with a value like:

    codebase="http://java.sun.com/products/plugin/1.1/jinstall-11-win32.cab#Version=1,1,0,0"

  • The optional codebase param tag supplies a relative URL that specifies the location of the applet class.

  • Either code or object is specified, not both.

  • The type param tag is not used by AppletViewer, but should be present so that browsers load the plugin properly.

    For an applet, the value should be something like:

    <param name="type" value="application/x-java-applet;version=1.1">

    or

    <param name="type" value="application/x-java-applet">

    For a serialized object or JavaBean, the type param value should be something like:

       <param name="type" value="application/x-java-bean;version=1.1">

    or

      <param name="type" value="application/x-java-bean">

  • Other param tags are argument values supplied to the applet.

  • The object tag recognized by IE4.x and the embed tag recognized by Netscape 4.x can be combined so that an applet can use the latest Java plugin from Sun, regardless of the browser that downloads the applet.

    For more information, see Java PlugIn HTML Specification

  • AppletViewer does not recognize the java_code, java_codebase, java_object, or java_type param tags. These tags are only needed when the applet defines parameters with the names code, codebase, object, or type, respectively. (In that situation, the plugin recognizes and uses the java_ version in preference to the version that will be used by the applet.) If the applet requires a parameter with one of these 4 names, it may not run in AppletViewer.

embed

The embed tag is the Netscape extension to HTML 3.2 that allows embedding an applet or a multimedia object in an HTML page. It allows a Netscape 4.x browser (which supports HTML 3.2) to run a Java applet using the latest Java plugin from Sun.

<embed
  code="yourClass.class"
  object="serializedObjectOrJavaBean"
  codebase="classFileDirectory"
  width="pixelWidth"
  height="pixelHeight"
>
   ...
</embed>

Notes:

  • The object and embed tags can be combined so that an applet can use the latest Java plugin from Sun, regardless of the browser that downloads the applet.

    For more information, see the Java PlugIn HTML Specification

  • Unlike the object tag, all values specified in an embed tag are attributes (part of the tag) rather than parameters (between the start tag and end tag, specified with a param tag.

  • To supply argument values for applet parameters, you add additional attributes to the <embed> tag.

  • AppletViewer ignores the "src" attribute that is usually part of an <embed> tag.

  • Either code or object is specified, not both.

  • The optional codebase attribute supplies a relative URL that specifies the location of the applet class.

  • The type attribute is not used by AppletViewer, but should be present so that browsers load the plugin properly.

    For an applet, the value should be something like:

    <type="application/x-java-applet;version=1.1">...

    or

    <type="application/x-java-applet">...

    For a serialized object or JavaBean, the type param value should be something like:

    <type="application/x-java-bean;version=1.1">...

    or

    <type="application/x-java-bean">...

  • The "pluginspage" attribute is not used by AppletViewer, but should be present so that browsers load the plugin properly. It should point to a Java plugin in a network cab file with a value like:

    pluginspage="http://java.sun.com/products/plugin/1.1/jinstall-11-win32.cab#Version=1,1,0,0"

applet

The applet tag is the original HTML 3.2 tag for embedding an applet in an HTML page. Applets loaded using the applet tag are run by the browser, which may not be using the latest version of the Java platform. To ensure that the applet runs with the latest version, use the object tag to load the Java plugin into the browser. The plugin will then run the applet.

<applet
  code="yourClass.class"
  object="serializedObjectOrJavaBean"
  codebase="classFileDirectory"
  width="pixelWidth"
  height="pixelHeight"
>
  <param name="..." value="...">
   ...
  alternate-text
</applet>

Notes:

  • Either code or object is specified, not both.

  • The optional codebase attribute supplies a relative URL that specifies the location of the applet class.

  • Param tags supply argument values for applet parameters.

app

The app tag was a short-lived abbreviation for applet that is no longer supported. AppletViewer translates the tag and prints out an equivalent tag that is supported.

<app
  class="classFileName" (without a .class suffix)
  src="classFileDirectory"
  width="pixelWidth"
  height="pixelHeight"
>
<param name="..." value="...">
 ...
</app>

For more information on the tags that AppletViewer supports and how to combine them, see the Java PlugIn HTML Specification.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java VisualVM

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java VisualVM - Working with Local Applications

When you start Java VisualVM, a node for each local Java application is displayed under the Local node in the Applications window. You can expand an application node to see the profiler snapshots, thread dumps and heap dumps of the application. Right-clicking an application node or sub-node invokes a popup menu enabling you to choose various actions.
Note: The list of local applications always includes Java VisualVM.

screenshot of VisualVM Applications window showing popup menu options

A local application node generally has the following items available in the popup menu.

  • Open. Opens the tab for the application in the main window where you can view application data.
  • Thread Dump. Takes a thread dump for the application.
  • Heap Dump. Takes a heap dump for the application.
  • Profile. Opens the Profiler sub-tab for the application where you can choose to profile the application. (Note that even though Java VisualVM appears in the application tree, Java VisualVM cannot profile itself).
  • Profiler Snapshot. Creates a snapshot of the results from the profiling session. The snapshot opens in the main window and a node for the snapshot appears under the application node. This command is only available when Java VisualVM is profiling the application.
  • Application Snapshot. Creates an application snapshot containing all application dumps and snapshots. A node for the application snapshot appears under the Snapshots node.
  • Enable Heap Dump on OOME. Select this if you want Java VisualVM to automatically take a heap dump when the application encounters an OutOfMemoryException.

You can perform the following tasks directly from the popup menu.

View Application Data

Java VisualVM displays data about each running local application in a dedicated tab in the main window. Each application tab has sub-tabs where information about that application is displayed.

To open the application tab, right-click the application node in the Applications window and choose Open. (Alternatively, double-click the application node.) When you click Open, the Overview tab of the application tab opens in the main window.

The application tab for a local application has the following sub-tabs:

  • Overview. For more, see Viewing Application Overview
  • Monitor. For more, see Monitoring an Application
  • Threads. For more, see Monitoring Application Threads
  • Profiler. For more, see Profiling Applications

Additional tabs and sub-tabs may be visible depending on the installed plugins.

Take a Thread Dump

You can use Java VisualVM to take a thread dump to capture information about the active application threads at the time you take the thread dump. When you take a thread dump, the thread dump opens in a sub-tab of the application in the main window. A node for the thread dump appears under the application node in the Applications window.

You can take a thread dump in the following ways:

  • Right-click the application node in the Applications window and choose Thread Dump.
  • Click the Thread Dump button in the Threads tab of the application tab.

When you take a thread dump, the thread dump opens in a sub-tab of the application in the main window. A node for the thread dump appears under the application node.

For more about working with application threads, see the following document:

  • Monitoring Application Threads

Take a Heap Dump

You can take a heap dump of a local application to capture a snapshot of the objects on the heap.

You can take a heap dump in the following ways:

  • Right-click the application node in the Applications window and choose Heap Dump.
  • Click the Heap Dump button in the Monitor tab of the application tab.

When you take a heap dump, the heap dump opens in a sub-tab of the application in the main window. A node for the heap dump appears under the application node.

For more about working with the heap, see the following document:

  • Browsing a Heap Dump

Profile an Application

Java VisualVM includes a profiler that enables you to analyze the performance and memory usage of a local application. You can profile an application without restarting it. To start a profiling session, right-click the application node and choosing Profile from the popup menu to open the profiling tab.
Note: Java VisualVM cannot be used to Profile itself.

For more see the following document:

  • Profiling Applications

Take Snapshots

Java VisualVM enables you to take snapshots that capture application data at the time the snapshot is taken. You can save snapshots to your local system and then examine them later or send them to others.

Java VisualVM enables you to take the following types of snapshots:

  • Profiler snapshots. A profiler snapshot captures the profiling data at the moment the snapshot is takes. The snapshot is either a memory snapshot or a CPU snapshot. You can take a profiler snapshot only when you are profiling an application.
  • Application snapshots. An application snapshot is an archive that contains all the heap dumps, thread dumps and snapshots that are listed below the application node.

For more see the following document:

  • Working with Snapshots
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java VisualVM

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java VisualVM - Working with Remote Applications

Java VisualVM is able to access and display data about applications running on remote hosts. After connecting to a remote host, Java VisualVM can display general data about the application's runtime environment and can monitor memory heap and thread activity.

Note. Java VisualVM can retrieve monitoring information on remote applications but it cannot profile remote applications.

Connecting to a Remote Host

Connected remote hosts are displayed as nodes under the Remote node in the Applications window. When you are connected to a remote host, Java VisualVM displays applications running on the host as sub-nodes, and automatically updates the status of the remote applications, removing the applications when they stop and adding applications when they start.

To add a remote host, right-click the Remote node in the Applications window, choose Add Remote Host and type the host name or IP address in the Add Remote Host dialog box. (You can also specify a display name that will be used to refer to the host when listed under the Remote node.)

Add Remote Host dialog box

Note: To retrieve and display information on applications running on the remote host, the jstatd utility needs to be running on the remote host. To start the jstatd utility, type jstatd on the command line. The jstatd utility is included as part of Java Development Kit (JDK) version 6. For more on jstatd, see the following document:

  • jstatd - Virtual Machine jstat Daemon

When Java VisualVM is connected to a remote host, a node for the remote host appears under the Remote node in the Applications window. You can expand the remote host node to view the applications running on the remote host.

Remote node in Applications window

Viewing Application Data

Java VisualVM displays data about each running remote application in a dedicated tab in the main window. To open the application tab, right-click the application node in the Applications window and choose Open. (Alternatively, you can double-click the application node.) When you click Open, the Overview tab of the application tab opens in the main window.

Overview tab of remote application

You can use the sub-tabs in the application tab to view details about the application.
For more see the following documents:

  • Viewing Application Overview
  • Monitoring an Application
  • Monitoring Application Threads
  • Connecting to JMX Agents Explicitly
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java VisualVM

Using the Applications Window

When you start Java VisualVM, the Applications window is visible in the left side of the Java VisualVM window. The Applications window uses a tree structure to enable you to quickly view the applications that are running on local and connected remote JVM software instances. The Applications window also displays core dumps and application snapshots.

Applications Window Nodes

The Application window has nodes and sub-nodes that you can expand to view running applications and saved files. For most nodes in the Applications window, you can view additional information and perform actions by right-clicking a node and choosing an item from the popup menu. The actions available in the popup menu vary according to the node.

screenshot of VisualVM window

The Applications window has the following primary nodes:

Local Node

The Local node displays the name and process IDs (PID) of Java applications that are running on the same system as Java VisualVM. When you launch Java VisualVM and expand the Local node, Java VisualVM automatically displays the currently running Java applications. Java VisualVM is always listed as one of the local applications. When a new local Java application is launched, a node for that application appears under the Local node. The application node disappears when the application terminates.

If you use Java VisualVM to take thread dumps, heap dumps or profiling snapshots of an application, they are displayed as sub-nodes below the node for that application. You can right-click a dump or snapshot sub-node to save it to your local system. You can collect and archive all the information collected about an application and save it as an application snapshot.

For more information about how to view data about local applications, see the following pages:

  • Working with Local Applications
  • Working with Snapshots
  • Using the Java VisualVM Profiler

Remote Node

When Java VisualVM connects to a remote host, the remote host is listed as a node under the Remote node. When connected to a remote host, you can expand the node for the remote host to see the Java applications that are running on that host. When a Java application is launched on the remote host, a node for that application is displayed under the remote host node.

You need to explicitly add the location of remote hosts if you want Java VisualVM to be able to connect to the host. Once a remote host is added, Java VisualVM persists the address of the remote host and will make a connection to the host each time Java VisualVM is started. If you do not want Java VisualVM to connect to the host on startup, you should right-click the remote host node and choose Remove before quitting Java VisualVM.

Note: To retrieve and display information on applications running on the remote host, the jstatd utility needs to be running on the remote host. To start the utility, type jstatd on the command line. The jstatd utility is included as part of the Java Development Kit (JDK) version 6.

For more information about how to view data about remote applications, see the following pages:

  • Working with Remote Applications.
  • jstatd - Virtual Machine jstat Daemon

VM Coredumps

The VM Coredumps node lists open core dump binary files when you open the files in Java VisualVM. A core dump is a binary file that contains information about the runtime status of the machine at the time the core dump was taken. If you have a core dump you can then extract an overview of the system properties, a heap dump and a thread dump.

Note: The Core Dump node is only visible if Java VisualVM is running on Solaris or Linux.

For more information, see the following document:

  • Working with Core Dumps

Snapshots

The Snapshots node lists any application snapshots that are saved in the Java VisualVM userdir until they are explicitly deleted. An application snapshot captures the collected heap dumps, thread dumps and profiler snapshots of an application at the moment the snapshot is taken. You can expand the application snapshot node to see the data collected in the snapshot.

You can right-click an application snapshot node or any of the items listed under the node to open a popup menu enabling you to open, save, delete and rename the selected item.

For more information about taking and saving snapshots, see the following document:

  • Working with Snapshots
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Image I/O API Guide: 3 - Writing Image I/O Applications

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

CHAPTER 3

Writing Image I/O Applications

3.1 Reading and Writing Images

The javax.imageio.ImageIO class provides a set of static convenience methods that perform most simple Image I/O operations.

Reading an image that is in a standard format (GIF, PNG, or JPEG) is simple:

File f = new File("c:\images\myimage.gif");
BufferedImage bi = ImageIO.read(f);
The format of the image will be auto-detected by the API based on the contents of the file. Most image files contain a "magic number" in their first few bytes that identifies the file format. For formats that do not have a magic number, auto-detection may fail and somewhat more sophisticated application code will be needed.

Additional formats may be handled by installing JAR files containing plug-ins; the details are described in the next chapter. Once a plug-in has been installed, a new format will be understood automatically without any changes to the application code.

The set of formats available for reading can be obtained by calling ImageIO.getReaderFormatNames. This will return an array of Strings containing the names of the available formats, such as "gif" and "png."

Writing an image in a supported format is equally simple:

BufferedImage bi;
File f = new File("c:\images\myimage.png");
ImageIO.write(im, "png", f);
The list of supported formats may be obtained by calling ImageIO.getWriterFormatNames.
CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Image I/O API Guide: 3 - Writing Image I/O Applications

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

3.2 Going Further

The methods described above are sufficient for simple applications. However, the Image I/O API offers much more power for writing sophisticated applications. In order to make use of the advanced features of the API, applications will work directly with the ImageReader and ImageWriter classes that are part of the API.
CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Image I/O API Guide: 3 - Writing Image I/O Applications

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

3.3 ImageReader

Rather than using the ImageIO class to perform the entire decoding operation, an application may use the ImageIO class to obtain an ImageReader object that may be used to perform the read:
Iterator readers = ImageIO.getImageReadersByFormatName("gif");
ImageReader reader = (ImageReader)readers.next();
Readers may also be retrieved based on file contents, file suffix, or MIME type. The mechanism for locating and instantiating the reader makes use of the javax.imageio.spi.ImageReaderSpi class, which allows information about a reader plug-in to be retrieved without actually instantiating the plug-in. The notion of "service provider interfaces" (SPIs) is described in detail in the following chapter.

Once a reader has been obtained, it must be supplied with an input source. Most readers are able to read from an ImageInputStream, which is a special input source that is defined by the Image I/O API. A special input source is used in order to make it simple for reader and writers to work with both file and streaming I/O.

Obtaining an ImageInputStream is straightforward. Given an input source in the form of a File or InputStream, an ImageInputStream is produced by the call:

Object source; // File or InputStream
ImageInputStream iis = ImageIO.createImageInputStream(source);
Once a source has been obtained, it may be attached to the reader by calling
reader.setInput(iis, true);
The second parameter should be set to false if the source file contains multiple images and the application is not guaranteed to read them in order. For file formats that allow only a single image to be stored in a file, it is always legal to pass in a value of true.

Once the reader has its input source set, we can use it to obtain information about the image without necessarily causing image data to be read into memory. For example, calling reader.getImageWidth(0) allows us to obtain the width of the first image stored in the file. A well-written plug-in will attempt to decode only as much of the file as is necessary to determine the image width, without reading any pixels.

To read the image, the application may call reader.read(imageIndex), where imageIndex is the index of the image within the file. This produces the same result as if it had called ImageIO.read, as shown above.

3.3.1 ImageReadParam

More control may be obtained by supplying the read method with an additional parameter of type ImageReadParam. An ImageReadParam allows the application to specify a destination image in which the decoded image data should be stored, allowing better control over memory use. It also allows a region of interest to be specified, as well as subsampling factors that may be used to obtain a scaled-down version of the image.

When a source region is set, the reader plug-in will attempt to decode only the desired region, to the extent that the file format allows partial decoding. In any case, no pixels outside the region will appear in the output. This capability makes it possible to work with extremely large images in a limited amount of memory.

For example, to decode only the upper-left quadrant of the image, the application first obtains an ImageReadParam that is suitable for use with the reader:

ImageReadParam param = reader.getDefaultReadParam();
Next, the source region of interest is set on the ImageReadParam:
import java.awt.Rectangle;
int imageIndex = 0;
int half_width = reader.getImageWidth(imageIndex)/2;
int half_height = reader.getImageHeight(imageIndex)/2;
Rectangle rect = new Rectangle(0, 0, half_width, half_height);
param.setSourceRegion(rect);
Finally, the image is read using the ImageReadParam:
BufferedImage bi = reader.read(imageIndex, param);
The result is a new BufferedImage whose width and height are equal to half those of the original image (rounding down if the image had an odd width or height).

The lower-right quadrant of the image may then be read into the same BufferedImage that was created to hold the upper-left quadrant, overwriting the previous pixel data:

param.setDestination(bi);
rect = new Rectangle(half_width, half_height, half_width, half_height);
param.setSourceRegion(rect);
BufferedImage bi2 = reader.read(0, param);
if (bi == bi2) {
        System.out.println("The same BufferedImage was used!");
} else {
        System.out.println("This can't happen!");
}
In practice, the application could simply call reader.read(0, param) without assigning the result anywhere, knowing that the pixels will be written into the existing BufferedImage bi.

As another example, to read every third pixel of the image, resulting in an image one-ninth the size of the original, subsampling factors may be set in the ImageReadParam:

param = reader.getDefaultImageParam();
param.setSourceSubsampling(3, 3, 0, 0);
BufferedImage bi3 = reader.read(0, param);

3.3.2 IIOParamController

A plug-in may optionally supply an IIOParamController object that may be used to set up an IIOReadParam (or IIOWriteParam) using a graphical user interface (GUI), or any other interface. A reader plug-in may attach an IIOParamController to any ImageReadParam objects that it creates:
ImageReadParam param = reader.getDefaultImageParam();
IIOParamController controller = param.getController();
if (controller != null) {
        controller.activate(param);
}
When the controller's activate method is called, it displays the GUI and handles user events such as slider movements and button presses. Typically the interface will contain an "OK" or "Apply" button, which when pressed will cause the activate method to return. The controller is responsible for calling methods on its associated ImageReadParam to update its state, either in response to each GUI event, or all at once prior to returning from activate.

3.3.3 Reading From Multi-Image Files

All the methods in the ImageReader class that deal with images take an imageIndex parameter. This parameter allows access to any of the images in a multi-image file.

The ImageReader.getNumImages method returns the number of images that are stored in the input file. This method takes a boolean parameter, allowSearch. Some image formats, notably GIF, do not provide any way to determine the number of images without reading the entire file. Since this may be costly, setting allowSearch to false will allow the reader to return a value of -1 instead of the actual number of images. If the parameter is true, the reader will always return the actual number of images.

Even if the number of images is not known by the application, it is still possible to call read(imageIndex); if the index is too large, the method will throw an IndexOutOfBoundsException. Thus, the application can request images with increasing indices until it receives an exception.

3.3.4 Reading "Thumbnail" Images

Some image formats allow a small preview image (or multiple previews) to be stored alongside the main image. These "thumbnail" images are useful for identifying image files quickly, without the need to decode the entire image.

Applications can determine how many thumbnail images associated with a particular image are available by calling:

reader.getNumThumbnails(imageIndex);
If a thumbnail image is present, it can be retrieved by calling:
int thumbailIndex = 0;
BufferedImage bi;
bi = reader.readThumbnail(imageIndex, thumbnailIndex);

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Image I/O API Guide: 3 - Writing Image I/O Applications

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

3.4 The ImageWriter Class

Just as we obtained a list of ImageReaders for a particular format using a method from the ImageIO class, we can obtain a list of ImageWriters:
Iterator writers = ImageIO.getImageWritersByFormatName("png");
ImageWriter writer = (ImageWriter)writers.next();
Once an ImageWriter has been obtained, its destination must be set to an ImageOutputStream:
File f = new File("c:\images\myimage.png");
ImageOutputStream ios = ImageIO.createImageOutputStream(f);
writer.setOutput(ios);
Finally, the image may be written to the output stream:
BufferedImage bi;
writer.write(bi);

3.4.1 Writing Multiple Images

The IIOImage class is use to store references to an image, one or more thumbnail images, and metadata (non-image data) associated with the image. Metadata will be discussed below; for now, we will simply pass null as the value for the metadata-related parameters.

The ImageWriter class contains a write method that creates a new file from an IIOImage, and a writeInsert method that adds an IIOImage to an existing file . By calling the two in sequence a multi-image file may be written:

BufferedImage first_bi, second_bi;
IIOImage first_IIOImage = new IIOImage(first_bi, null, null);
IIOImage second_IIOImage = new IIOImage(second_bi, null, null);
writer.write(null, first_IIOImage, null);
if (writer.canInsertImage(1)) {
        writer.writeInsert(1, second_IIOImage, null);
} else {
        System.err.println("Writer can't append a second image!");
}

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Image I/O API Guide: 3 - Writing Image I/O Applications

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

3.5 Handling Metadata

Data stored in an image file that does not represent actual pixel values is referred to as metadata. The javax.imageio.metadata package contains classes and interfaces for accessing metadata.

Metadata may contain complex, hierarchical structures. The Java XML Document Object Model (DOM) API is used to represent these structures, allowing developers to leverage their knowledge of these interfaces.

The Image I/O API differentiates between stream metadata, which is associated with all images stored in an image file, and image metadata which is associated with a single image. For image formats that contain a single image, only image metadata is used.

Metadata may be obtained by calling the ImageReader.getStreamMetadata and getImageMetadata(int imageIndex) methods. These return an object that implements the IIOMetadata interface. The actual class type of the returned object is up to the ImageReader, and will usually be a unique class used only by that reader. This object should be designed to store as much of the metadata allowed by the format as possible, as losslessly as possible. However, this fidelity to the specifications of the image format comes at a cost, as access to the metadata becomes format-specific.

In order to allow access to the metadata without the need for format-specific application code, IIOMetadata objects expose their internal information in the form of an XML DOM structure, which is essentially a tree of nodes of various types that may contain a set of attributes (String values accessed by name), and which may reference a set of child nodes.

A single plug-in may support multiple document formats, which are distinguished by a format name. Typically, at least two formats will be supported by a given plug-in. The first is a common, plug-in neutral format called com.sun.imageio_1.0, which is defined in the class comment for the IIOMetadata interface. The second will be a highly plug-in specific format that exposes all of the internal structure of the IIOMetadata object in the form of a DOM. The latter format is referred to as the native format of the plug-in; its name may be determined by calling the getNativeMetadataFormatName method of the IIOMetadata object returned by the reader (advanced users may call a method of the same name on the ImageReaderSpi object used to instantiate the reader. The latter approach is useful for selecting a plug-in based on its support for a particular format). The names of all of the supported document formats may be determined similarly by calling getMetadataFormatNames.

The contents of an IIOMetadata object may be accessed in the form of a tree of XML Node objects by calling its getAsTree method. This method takes a String argument which is the name of one of the document formats supported by the plug-in. This document may then be manipulated as a standard XML DOM tree.

As an example, to print the contents of an XML DOM tree, the following code may be used:

public void displayMetadata(Node root) {
        displayMetadata(root, 0);
}

void indent(int level) {
        for (int i = 0; i < level; i++) {
                System.out.print("  ");
        }
}

void displayMetadata(Node node, int level) {
        indent(level); // emit open tag
        System.out.print("<" + node.getNodeName());
        NamedNodeMap map = node.getAttributes();
        if (map != null) { // print attribute values
                int length = map.getLength();
                for (int i = 0; i < length; i++) {
                        Node attr = map.item(i);
                        System.out.print(" " + attr.getNodeName() +
                                         "=\"" + attr.getNodeValue() + "\"");
                }
        }

        Node child = node.getFirstChild();
        if (child != null) {
                System.out.println(">"); // close current tag
                while (child != null) { // emit child tags recursively
                        displayMetadata(child, level + 1);
                        child = child.getNextSibling();
                }
                indent(level); // emit close tag
                System.out.println("</" + node.getNodeName() + ">");
        } else {
                System.out.println("/>");
        }
}
Executing displayMetadata on the metadata from the standard PNG test image http://www.schaik.com/pngsuite/ccwn2c08.png yields the output:
<com.sun.imageio.png_1.0>
  <IHDR width="32" height="32" bitDepth="8" colorType="RGB"
compressionMethod="deflate" filterMethod="adaptive" interlaceMethod="none"/>
  <cHRM whitePointX="31270" whitePointY="32900" redX="64000" redY="33000"
greenX="30000" greenY="60000" blueX="15000" blueY="6000"/>
  <gAMA value="100000"/>
</com.sun.imageio.png_1.0>
We see that the image contains IHDR, cHRM, and gAMA chunks. The interpretation of the attribute values requires an understanding of the PNG format; however, it is still possible for an application that does not understand PNG internals to display the values and allow them to be edited interactively.

3.5.1 The IIOMetadataFormat Interface

An IIOMetadataFormat object is used to describe the legal structure of a metadata document format. It constrains the types of nodes that may appear, the types of nodes that may be children of a node of a given type, the names and data types of the attributes that may appear at a node of a given type, and the audiotape of an Object value that may be stored at a node of a given type. In XML terms, the information provided by the IIOMetadataFormat interface is somewhere in between a DTD (Document Type Definition), which gives information about node types, children, and attributes, and an XML Schema, which provides detailed information about data types.

For simplicity, only a subset of legal DTD structures can be described by IIOMetadataFormat. For example, the children of a node may be defined in an IIOMetadataFormat as a sequence in which each child must appear once (a, b, c), a sequence in which each child is optional (a?, b?, c?), a choice of a single child (a | b | c), or a repetition of a single node type (a)*, whereas a DTD allows many more combinations.

A node may not contain any textual data, but may contain a reference to an arbitrary Object. The IIOMetadataFormat indicates the class type and optionally the legal enumerated values or a range of values for the Object. Arrays are supported as well.

A DTD does not allow any attribute data types other than character strings; an XML Schema allows extremely complex data types to be built up from simpler ones. IIOMetadataFormat occupies a middle ground; it allows attributes to be constrained to belong to one of a predefined set of simple data types, including integers, floating-point decimals, and dates. Lists of these data types are also allowed.

Since an IIOMetadataFormat might be used to automatically construct a user interface for displaying and editing metadata, restricted the set of legal structures greatly simplifies the mapping between formats and user interface designs.

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Image I/O API Guide: 3 - Writing Image I/O Applications

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

3.6 Transcoding

Transcoding refers to reading an image file with a reader plug-in, and writing out the image using a writer plug-in, especially, if the writer plug-in cannot directly understand the native metadata format of the reader. In such a case, there will always be some loss of information, even if both plug-ins deal with the same file format. A transcoder plug-in is responsible for converting the stream and image metadata that have been created by a reader plug-in into a better form for use by a writer plug-in. The API does not mandate the presence of any transcoder plug-ins, but they may be installed and registered just like readers and writers.

A set of reader and writer plug-ins may be designed to interpret each other's metadata without the need for a separate transcoder. The relationships between plug-ins can be determined using the ImageReaderSpi.getImageWriterSpiNames and ImageWriterSpi.getImageReaderSpiNames methods, which indicate which plug-ins are known to work well with a given plug-in of the opposite type. If multiple plug-ins are being written by a single vendor, this mechanism will provide the best quality.

However, when working with plug-ins that have not been designed to interoperate, a transcoder plug-in may be provided by a developer who understands the metadata formats of a given pair of reader and writer plug-ins, even though each was written without knowledge of the other.

Given a particular pair of reader and writer plug-ins, the set of appropriate transcoder plug-ins may be located as follows:

ImageReader reader;
ImageWriter writer;

Iterator transcoders = ImageIO.getImageTranscoders(reader, writer);

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Image I/O API Guide: 3 - Writing Image I/O Applications

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

3.7 Listening for Events

As an image is being read or written, the plug-in may provide updates to the
application. The application may provide one or more classes that implement
interfaces from the javax.image.event package. Instances of these classes are then
added to the ImageReader or ImageWriter being used. For example,

class MyReadProgressListener implements IIOReadProgressListener {

        public MyReadProgressListener() {}

        public void imageStarted(ImageReader source) {
                System.out.println("Started reading!");
        }

        // Other methods from IIOReadProgressListener omitted
}

IIOReadProgressListener listener = new MyReadProgressListener();
reader.addIIOReadProgressListener(listener);
As the ImageReader.read method progresses, methods on listener will be called at various times to indicate how much of the image has been read. Because these methods are being called while ImageReader.read is active, they must not call most methods from the same ImageReader object. They may call ImageReader.abort(), which will cause ImageReader.read to return even if it is only partially complete.

3.7.1 The IIOReadProgressListener Interface

An IIOReadProgressListener may be used to provide simple status information during reading. An estimate of the percentage of completion of a read is provided, which may be used to update a Swing JProgressBar or other progress indicator, or to estimate the time remaining to read a large image.

The imageStarted method will be called at the start of the read. During the read, the imageProgress method will be called multiple times, each time with a different, increasing value for its percentageDone parameter. When the read is about to complete, the imageComplete method will be called.

Similarly, the thumbnailStarted, thumbnailProgress, and thumbnailComplete methods will be called during thumbnail reads.

Other methods exist to indicate the start and end of a sequence of image reads performed by the ImageReader.readAll method. Additionally, it is possible for an ongoing read to be aborted using the ImageReader.abort method; in this case, the listener's readAborted method will be called.

3.7.2 The IIOReadUpdateListener Interface

An IIOReadUpdateListener provides more detailed information on the progress of an image read. Some image formats allow interlaced or progressive encoding, in which a subset of the pixel data is made available quickly, so that a crude version of the image may be displayed while the remainder of the pixel data is still being received and decoded. A typical scheme might begin by sending only every fourth row, and only every fourth pixel in each of those rows, so that the initial image requires only one sixteenth of the total amount of data to be transmitted and decoded. If interlacing were not used, only the top one-sixteenth of the image would be displayed in the same amount of time. Thus, a person viewing an interlaced image will be able to get a sense of its contents much sooner than if a traditional left-to-right, top-to-bottom order were used.

By implementing the methods of the IIOReadUpdateListener interface, an application class can receive notification when groups of possibly non-contiguous pixels are ready to be displayed. These methods also receive a reference to the BufferedImage that is in the process of being filled in, which may be used to refresh the display to include the newly decoded pixels.

When decoding an interlaced or progressive image, the decoding proceeds in multiple passes. At the start of each pass, the listener's passStarted method will be called to indicate the set of pixels that may be overwritten during the following pass. This estimate is conservative; not every pixel in the region will necessarily be updated during the pass. As the pass progresses, the imageUpdate method will be called with arguments describing the region of pixels that have receive new values. This region is described by the coordinates of its upper-left corner, its width and height, and the spacing between the pixels that make up the pass (in the example above, both parameters would be equal to 4 for the initial pass). When a pass has completed, the passComplete method is called. Similar methods allow the progress of thumbnail image reads to be tracked.

3.7.3 The IIOReadWarningListener Interface

By attaching an IIOReadWarningListener to an ImageReader, information on non-fatal errors may be received. For example, a reader might detect a tag or chunk that should not be present. Even though the reader may choose to ignore the error and proceed with decoding, it may wish to inform the application that the input source was malformed, as this could indicate problems in the application that generated the images.

ImageReaders may specify a set of Locales for which they can provide localized warning messages. The set of available locales can be obtained from the reader's getAvailableLocales method. The desired locale should then be set by calling the reader's setLocale method prior to attaching the IIOReadWarningListener. Each listener will receive messages in the Locale that was in effect at the time it was attached to the reader.

3.7.4 The IIOWriteProgressListener and IIOWriteWarningListener Interfaces

The IIOWriteProgressListener and IIOWriteWarningListener interfaces function similarly to their reader counterparts.
CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Image I/O API Guide: 3 - Writing Image I/O Applications

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

3.8 Handling Errors using IIOException

In the examples above, the possibility of fatal errors was not considered. Errors may result from a number of sources, including true I/O errors (e.g., file not found, file unreadable, file on corrupt media), security violations (e.g., no permission to read files from an applet), file format problems (file contents corrupted, file using a variant of the format that is not supported by the plug-in), or even bugs in the API implementation or in the plug-in.

The Image I/O API makes use of its own subclass of the standard IOException class, called IIOException. IIOExceptions are used to signal all errors encountered during the parsing of a source file (e.g., an incorrect checksum or an invalid value for a particular byte within the file), including true I/O errors that result in an IOException being thrown within the reader.

An IIOException contains a (non-localized) message describing the reason for the exception, as well as a reference to another Exception that was the cause of the IIOException, if one exists.

Thus, application code that attempts to provide graceful handling of errors will look something like:

File f = new File("c:\images\myimage.gif");
ImageInputStream iis = null;
try {
        iis = ImageIO.createImageInputStream(f);
} catch (IIOException iioe1) {
        System.out.println("Unable to create an input stream!");
        return;
}

reader.setInput(stream);
try {
        reader.read(0, param);
} catch (IIOException iioe2) {
        System.out.println("An error occurred during reading: " +
                                 iioe2.getMessage());
        Throwable t = iioe2.getCause();
        if ((t != null) && (t instanceof IOException)) {
                System.out.println("Caused by IOException: " +
                                   t.getMessage());
        }
}

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


apt man page

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

NAME

apt - annotation processing tool

SYNOPSIS

apt [-classpath classpath] [-sourcepath sourcepath] [-d directory] [-s directory] [-factorypath path] [-factory class] [-print] [-nocompile] [-Akey[=val] ...] [javac option] sourcefiles [@files]

PARAMETERS

Options may be in any order. For a discussion of parameters which apply to a specific option, see OPTIONS below.

sourcefiles
Zero or more source files to be processed.
@files
One or more files that list source files or other options

DESCRIPTION

Note: The apt tool and its associated API contained in the package com.sun.mirror have been deprecated since JDK 7 and are planned to be removed in the next major JDK release. Use the options available in the javac tool and the APIs contained in the packages javax.annotation.processing and javax.lang.model to process annotations.

The tool apt, annotation processing tool, includes reflective APIs and supporting infrastructure to process program annotations. The apt reflective APIs provide a build-time, source-based, read-only view of program structure. These reflective APIs are designed to cleanly model the Java™ programming language's type system after the addition of generics. First, apt runs annotation processors that can produce new source code and other files. Next, apt can cause compilation of both original and generated source files, easing development. The reflective APIs and other APIs used to interact with the tool are subpackages of com.sun.mirror.

A fuller discussion of how the tool operates as well as instructions for developing with apt are in Getting Started with apt.

OPTIONS

apt specific options

-s dir
Specify the directory root under which processor-generated source files will be placed; files are placed in subdirectories based on package namespace.
-nocompile
Do not compile source files to class files.
-print
Print out textual representation of specified types; perform no annotation processing or compilation.
-A[key[=val]]
Options to pass to annotation processors -- these are not interpreted by apt directly, but are made available for use by individual processors
-factorypath path
Specify where to find annotation processor factories; if this option is used, the classpath is not searched for factories.
-factory classname
Name of annotation processor factory to use; bypasses default discovery process
-version
Print version information.
-X
Display information about non-standard options.

Options shared with javac

-d dir
Specify where to place processor and javac generated class files
-cp path or -classpath path
Specify where to find user class files and annotation processor factories. If -factorypath is given, the classpath is not searched for factories.

Consult the javac(1) man page for information on javac options.

Non-Standard Options

-XListAnnotationTypes
List found annotation types.
-XListDeclarations
List specified and included declarations.
-XPrintAptRounds
Print information about initial and recursive apt rounds.
-XPrintFactoryInfo
Print information about which annotations a factory is asked to process.
-XclassesAsDecls
Treat both class and source files as declarations to process.

Note: Because these options are non-standard, they are subject to change without notice.

NOTES

The apt tool and its associated API contained in the package com.sun.mirror have been deprecated since JDK 7 and are planned to be removed in the next major JDK release. Use the options available in the javac tool and the APIs contained in the packages javax.annotation.processing and javax.lang.model to process annotations.

SEE ALSO

  • javac, java
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Contents | Previous | Next

Chapter 2

JMX Architecture

JMX technology provides a standard API for management and monitoring of resources. The API includes remote access, so a remote management application can manage and monitor applications, systems, and networks. This chapter outlines JMX architecture in the following sections:

  • "Architecture Outline"
  • "Instrumenting Resources Using MBeans"
  • "Creating a JMX Agent"
  • "Managing Resources Remotely"

Architecture Outline

JMX technology is defined by two closely related specifications developed through the Java Community Process (JCP) as Java Specification Request (JSR) 3 and JSR 160:

  • JSR 3, Java Management Extensions Instrumentation and Agent Specification
  • JSR 160, Java Management Extensions Remote API

The following table shows that the management architecture can be broken down into three levels. The first two levels shown in the table, instrumentation and agent,

Java VM are defined by JSR 3. The remote management level is defined by JSR 160.

TABLE 2-1 – JMX Technology Architecture
Level | Description
Instrumentation | Resources, such as applications, devices, or services, are instrumented using Java objects called Managed Beans (MBeans). MBeans expose their management interfaces, composed of attributes and operations, through a JMX agent for remote management and monitoring.
Agent | The main component of a JMX agent is the MBean server. This is a core managed object server in which MBeans are registered. A JMX agent also includes a set of services for handling MBeans. JMX agents directly control resources and make them available to remote management agents.
Remote Management | Protocol adaptors and standard connectors make a JMX agent accessible from remote management applications outside the agent’s Java Virtual Machine (Java VM).

Instrumenting Resources Using MBeans

To manage resources using JMX technology, you must first instrument the resources in the Java programming language. You use Java objects known as MBeans to implement the access to the instrumentation of resources. MBeans must follow the design patterns and interfaces defined in the specification. This ensures that all MBeans provide the instrumentation of managed resources in a standardized way.

Once a resource has been instrumented by MBeans, it can be managed through a JMX agent. MBeans do not require knowledge of the JMX agent with which they will operate.

MBeans are designed to be flexible, simple, and easy to implement. Developers of applications, systems, and networks can make their products manageable in a standard way without having to understand or invest in complex management systems. Existing resources can be made manageable with minimum effort.

In addition, the instrumentation level specifies a notification mechanism. This allows MBeans to generate and propagate notification events to components of the other levels.

Creating a JMX Agent

A JMX agent is a standard management agent that directly controls resources and makes them available to remote management applications. JMX agents are usually located on the same machine as the resources they control, but this is not a requirement.

The core component of a JMX agent is the MBean server, a managed object server in which MBeans are registered. A JMX agent also includes a set of services to manage MBeans, and at least one communications adaptor or connector to allow access by a management application.

When you implement a JMX agent, you do not need to know the semantics or functions of the resources that it will be used to manage. In fact, a JMX agent does not even need to know which resources it will serve, because any resource instrumented in compliance with the JMX specification can use any JMX agent that offers the services it requires. Similarly, the agent does not need to know the functions of the management applications that will access it.

Managing Resources Remotely

JMX API instrumentation can be accessed in many different ways, either through existing management protocols such as the Simple Network Management Protocol (SNMP), or through proprietary protocols. The MBean server relies on protocol adaptors and connectors to make a JMX agent accessible from management applications outside the agent’s Java Virtual Machine (Java VM).

Each adaptor provides a view through a specific protocol of all MBeans registered in the MBean server. For example, an HTML adaptor could display an MBean in a Web browser.

Connectors provide a manager-side interface that handles the communication between manager and JMX agent. Each connector provides the same remote management interface though a different protocol. When a remote management application uses this interface, it can connect to a JMX agent transparently through the network, regardless of the protocol.

JMX technology provides a standard solution for exporting JMX API instrumentation to remote applications, based on Remote Method Invocation (RMI). In addition, the JMX Remote API defines an optional protocol based directly on TCP sockets, called the JMX Messaging Protocol (JMXMP). An implementation of the JMX Remote API does not have to support this optional protocol. The Java SE platform does not include the optional protocol. See Appendix A, "JMX Technology Versions" for further information.

The JMX Remote API specification describes how you can advertise and find JMX agents using existing discovery and lookup infrastructures. Examples of how to do this are provided and are described in the Java Management Extensions (JMX) Technology Tutorial. The specification does not define its own discovery and lookup service. The use of existing discovery and lookup services is optional: alternatively you can encode the addresses of your JMX API agents in the form of URLs, and communicate these URLs to the manager.

Contents | Previous | Next

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.source.tree.ArrayAccessTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.ArrayAccessTree

  • Packages that use ArrayAccessTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of ArrayAccessTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type ArrayAccessTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitArrayAccess(ArrayAccessTree node, P p)

    • Uses of ArrayAccessTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type ArrayAccessTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitArrayAccess(ArrayAccessTree node, P p)
      R | SimpleTreeVisitor.visitArrayAccess(ArrayAccessTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.ArrayReference (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.ArrayReference

  • Packages that use ArrayReference
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of ArrayReference in com.sun.jdi

      Methods in com.sun.jdi that return ArrayReference
      Modifier and Type Method and Description
      ArrayReference ArrayType.newInstance(int length)
      Creates a new instance of this array class in the target VM.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.type.ArrayType (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.type.ArrayType

  • Packages that use ArrayType
    Package Description
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of ArrayType in com.sun.mirror.util

      Methods in com.sun.mirror.util that return ArrayType
      Modifier and Type Method and Description
      ArrayType Types.getArrayType(TypeMirror componentType)
      Deprecated.
      Returns an array type with the specified component type.
      Methods in com.sun.mirror.util with parameters of type ArrayType
      Modifier and Type Method and Description
      void TypeVisitor.visitArrayType(ArrayType t)
      Deprecated.
      Visits an array type.
      void SimpleTypeVisitor.visitArrayType(ArrayType t)
      Deprecated.
      Visits an array type.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.ArrayTypeTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.ArrayTypeTree

  • Packages that use ArrayTypeTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of ArrayTypeTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type ArrayTypeTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitArrayType(ArrayTypeTree node, P p)

    • Uses of ArrayTypeTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type ArrayTypeTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitArrayType(ArrayTypeTree node, P p)
      R | SimpleTreeVisitor.visitArrayType(ArrayTypeTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


java.lang.ClassFormatError ...

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

java.lang.ClassFormatError Thrown by ClassLoader

Symptoms

When running an applet in a browser using the Sun Java™ Runtime Environment (JRE™), a java.lang.ClassFormatError is thrown by the ClassLoader. The same applet runs under the Microsoft Virtual Machine (VM).

Cause

This error is caused by bytecodes generated from old JDK 1.0.2/1.1 compilers, or from a third-party obfuscator. In the past, many of these compilers and obfuscators generated bytecode that does not conform to the Sun JRE Specification. Because the verifiers in recent Java SE releases are much strict about bad class format, the java.lang.ClassFormatError is thrown by the VM when these bad class files are loaded.

Some typical problems in some older class files are the following (note that this list is not exhaustive):

  • There are extra bytes at the end of the class file.
  • The class file contains method or field names that do not begin with a letter.
  • The class attempts to access private members of another class.
  • The class file has other format errors, including illegal constant pool indices and illegal UTF-8 strings.
  • The class file produced by an early (third-party) bytecode obfuscator violates proper class-file format.

Resolution

To allow some of the applets with bad class files to run in the Java platform, Java Plug-in contains a bytecode transformer to transform some of the bad class files to good ones. Currently, only bad class files with the following problems may be transformed:

  • Local variable name with a bad constant pool index
  • Extra bytes at the end of the class file
  • Code segment of the wrong length
  • Illegal field/method name
  • Illegal field/method modifiers
  • Invalid start_pc/length in local var table

Unfortunately, the bytecode transformer cannot transform the following problems, which will still result in a ClassFormatError:

  • Illegal use of nonvirtual function call
  • Arguments can not fit into locals
  • Unsorted lookup switch
  • Truncated class file

You can resolve these problems by simply recompiling your Java classes with the javac compiler from the JDK. If you choose to use a third-party obfuscator, be sure to use one that produces class files that respect proper class-file format.

Related Information

None.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Applet packaged as .cab file ...

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

java.lang.ClassNotFoundException Thrown by ClassLoader

Symptoms

When running an applet in a browser by using the Sun Java™ Runtime Environment (JRE™) implementation, a java.lang.ClassNotFoundException is thrown by the ClassLoader. The same applet runs without any error under the Microsoft Virtual Machine (VM).

Cause

This error is caused by applets being packaged as .cab files. The .cab file is an archive format specific to Microsoft Windows and it is not supported by the Sun JRE.

Resolution

Extract the applet classes and resources from the .cab files and repackage them as .jar files using the Java Archive File Format (JAR™) tool from Java Development Kit (JDK). Type the following command to repackage files as .jar files:

jar cvf <jar_file> <input_files>

Modify the <APPLET> tag in the HTML page to specify the .jar files in the archive attribute. For example, assume you have the following code:

<APPLET code="MyApplet" width=100 height=100>
        <PARAM name="cabbase" value="package1.cab, package2.cab">
    </APPLET>

You can modify the above code as shown in the following example:

<APPLET code="MyApplet"
archive="package1.jar, package2.jar" width=100
height=100>
</APPLET>

Related Information

See the JAR tool documentation for more details.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Applet running in the JRE is no longer signed after repackaging signed .cab files ...

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Applet Running In the Java™ Runtime Environment (JRE™) Is No Longer Signed After Repackaging the Signed .cab Files As .jar Files.

Symptoms

After repackaging signed .cab files as .jar files, an applet running in the Sun JRE is treated as unsigned. But, the same applet which is packaged as .cab files runs as signed in the Microsoft Virtual Machine (VM).

Cause

Microsoft supports signing applets through its own proprietary Authenticode and .cab file technologies. The signing information is lost in the process of repackaging. As a result, the Sun JRE implementation treats the .jar files as unsigned.

Resolution

Sign the .jar files by using the jarsigner tool of the Java Development Kit (JDK) by using the following method:

  1. Obtain the Sun Java Signing certificate from VeriSign or the Java Code Signing certificate from Thawte or similar certificates from other Certificate Authorities (CAs). RSA certificates may be purchased from a Certificate Authority (CA) that supports RSA, such as Verisign and Thawte.
  2. Import the certificate into your keystore by using the keytool command and an alias name. For example, type the following command:
    C:\>C:\jdk1.6.0\bin\keytool -import -alias MyCert -file VSSStanleyNew.cer

  3. Type the jarsigner command to sign the .jar file, by using the RSA credentials in your keystore that were generated in the previous step. Make sure the same alias name is specified. For example, type the following command:
    C:\>C:\jdk1.6.0\bin\jarsigner C:\TestApplet.jar MyCert
    When you type the above command, the following response appears. Type the Passphrase that you provided while generating the credentials for keystore in the above step.
     Enter Passphrase for keystore:
    Type the Passphrase that you provided while generating the credentials for keystore.
  4. Use "jarsigner -verify -verbose -certs" to verify the .jar files.
    C:>C:\jdk1.6.0\bin\jarsigner -verify -verbose
                -certs d:\TestApplet.jar

         245 Wed Mar 10 11:48:52 PST 2000 META-INF/manifest.mf
         187 Wed Mar 10 11:48:52 PST 2000 META-INF/MYCERT.SF
         968 Wed Mar 10 11:48:52 PST 2000 META-INF/MYCERT.RSA
smk      943 Wed Mar 10 11:48:52 PST 2000 TestApplet.class
smk      163 Wed Mar 10 11:48:52 PST 2000 TestHelper.class

      X.509, CN=XXXXXXX YYY, OU=Java Software,
                O=Sun Microsystems, L=Cupertino,
                ST=CA, C=US (mycert)
      X.509, CN=Sun Microsystems, OU=Java Plug-in QA,
                O=Sun Microsystems, L=Cupertino, ST=CA, C=US
      X.509, EmailAddress=server-certs@thawte.com,
                CN=Thawte Server CA, OU=Certification
                Services Division, O=Thawte Consulting cc,
                L=Cape Town, ST=Western Cape, C=ZA

  s = signature was verified
  m = entry is listed in manifest
  k = at least one certificate was found in keystore
  i = at least one certificate was found in identity scope

jar verified.

Related Information

See Code Signing by VerSign and code-signing certificate support by Thawte for information on how to obtain certificates.

See Signing applets using RSA certificates for more information on how to sign applets.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


java.security.AccessControlException thrown ...

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

java.security.AccessControlException Thrown In the Execution of java.beans.Introspector.setBeanInfoSearchPath() Method

Symptoms

When running an applet in a browser by using the Sun Java™ Runtime Environment (JRE™) implementation, a java.security.AccessControlException is thrown in the execution of the java.beans.Introspector.setBeanInfoSearchPath() method as shown below:

java.security.AccessControlException: access denied (java.util.PropertyPermission * read,write)
    at java.security.AccessControlContext.checkPermission(Unknown Source)
    at java.security.AccessController.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkPropertiesAccess(Unknown Source)
    at java.beans.Introspector.setBeanInfoSearchPath(Unknown Source)
    at ....

The same applet runs without any error with the Microsoft Virtual Machine (VM).

Cause

The Introspector.setBeanInfoSearchPath() method call can change the list of package names used for finding BeanInfo classes. If more than one applet is running in the VM, an untrusted applet could call this method to redirect other applets to look up BeanInfo in unexpected packages. This is a flaw in security.

A security check for java.util.PropertyPermission is added to Introspector.setBeanInfoSearchPath() method in the JRE to address the security concern. If the applet is unsigned and it calls this method, a java.security.AccessControlException is thrown.

Resolution

To fix the above causes:

  • Sign the applet by using the Java Development Kit (JDK) jarsigner tool, so that the applet runs as a trusted applet and has permissions to call the Introspector.setBeanInfoSearchPath() method.
  • Rearchitect the applet code to avoid the call to Introspector.setBeanInfoSearchPath(). For example, instead of relying on the BeanInfo class search path, use a fully qualified package name for searching the BeanInfo.

Related Information

See jarsigner, which is the JAR Signing and Verification Tool.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


java.lang.ClassNotFoundException thrown ...

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

java.lang.ClassNotFoundException Thrown by the ClassLoader on the com.ms.security Package

Symptoms

When running an applet in a browser using the Sun Java™ Runtime Environment (JRE™), a java.lang.ClassNotFoundException is thrown by the ClassLoader on the com.ms.security package. The same applet runs without any error under the Microsoft Virtual Machine (VM).

Cause

The Microsoft VM provides the proprietary com.ms.security package for applets and applications to access the security policy at runtime. Because this package is not available in the Sun JRE, a java.lang.ClassNotFoundException is thrown when the applet runs in a browser.

Resolution

Migrate the applet source from the com.ms.security package to the java.security package by using similar classes.

For example, the following applet uses com.ms.security.PolicyEngine to assert the network I/O permission before connecting to a URL:

public class AssertPermissionApplet extends java.applet.Applet
{
    public void init()
    {
        try
        {
            // Assert permission on network I/O
            com.ms.security.PolicyEngine.assertPermission
            (com.ms.security.PermissionID.NETIO);
            java.net.URL url = new java.net.URL("http://randomhost/randomfile");
            .....
        } catch (java.net.MalformedURLException mue) {
        }
        catch (java.io.IOException ioe) {
        }
      } // init
}

In the Java technology, java.security.AccessController provides similar functionality for permission assertion. The following source code displays the functionality after migration:

public class AssertPermissionApplet extends java.applet.Applet
{
    public void init()
    {
        try
        {
            // Assert permission on network I/O
            java.security.AccessController.checkPermission(new java.net.SocketPermission("randomhost:80", "connect,accept"));
            java.net.URL url = new java.net.URL("http://randomhost/randomfile");
            .....
        } catch (java.net.MalformedURLException mue) {
        }
        catch (java.io.IOException ioe) {
        }
      } // init
}

See the Java™ SE technology API documentation for more details about security.

Related Information

See Security.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


java.lang.ClassNotFoundException thrown ...

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

java.lang.ClassNotFoundException thrown on com.ms.* package when applet runs

Symptoms

When running an applet in a browser by using the Sun Java™ Runtime Environment (JRE™), a java.lang.ClassNotFoundException is thrown by ClassLoader on the com.ms.* package. The same applet runs without any error under the Microsoft Virtual Machine (VM).

Cause

The Microsoft VM provides many proprietary class libraries, including J/Direct, Application Foundation Classes (AFC), and Windows Foundation Classes (WFC). These packages are not available in the Sun JRE, so a java.lang.ClassNotFoundException is thrown when an applet runs in the browser.

Resolution

Migrate the applet source code from using the Microsoft proprietary class libraries to similar classes in the Java platform. The following table shows a list of Microsoft VM and Java Platform class libraries:

Microsoft VM | Java Platform
J/Direct | Java Native Interface
Application Foundation Classes | Swing, Java 2D APIs
Windows Foundation Classes | Swing, Java 2D APIs

Related Information

How to avoid potential pitfalls of Microsoft's non-standard SDK for Java
 Trail: Creating a GUI with JFC/Swing
 Download Archive: Java Native Interface
Lesson: Learning Swing with the NetBeans IDE

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


java.lang.ClassCastException thrown ...

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

java.lang.ClassCastException Thrown From the AWT Event Dispatching Thread When Mouse Moves Over an Applet Frame

Symptoms

While running an applet in a browser by using the Sun Java™ Runtime Environment (JRE™) implementation, a java.lang.ClassCastException is thrown from the Abstract Window Toolkit (AWT) event-dispatching thread when the mouse moves over the applet's frame, as shown in the following code:

java.lang.ClassCastException: sun.plugin....
         at MyApplet.mouseExit(Unknown Source)
         at java.awt.Component.handleEvent(Unknown Source)
         at java.awt.Component.postEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)

The applet runs without any error with the Microsoft Virtual Machine (VM).

Cause

This exception has two possible causes:

  • To track mouse events on the applet's frame, the applet tries to register a MouseListener event on the frame. In the Microsoft VM implementation, the applet's direct parent in the AWT hierarchical component tree is the frame. So, some applets rely on the following code:

    public void foo()
    {
            Frame f = (Frame) getParent();
            ....
    }

    But, applet's direct parent is specific to the implementation and might change. Because the Sun JRE has other containers between the applet and the frame, getParent() method does not return a Frame object, and the above code results in java.lang.ClassCastException error.
  • In the Microsoft VM implementation, java.applet.AppletContext interface is implemented by the applet frame. So, some applets rely on the following code:

    public void foo()
{
Frame f = (Frame)
getParent();
....
AppletContext ac =
(AppletContext) f;
....
}

    But applet's direct parent is specific to the implementation and might change. Because the Sun JRE implements AppletContext using a different object, the above code results in a java.lang.ClassCastException.

Resolution

In the first cause, navigate the entire AWT hierarchical component tree from the applet to locate the frame, instead of relying on a frame at a particular level. The following code shows how you can navigate the entire component tree:

public void foo()
{
// Navigate component
tree
Container c =
getParent();
while (c != null && (c
instanceof Frame) == false)
c
= c.getParent();

// Cast Container to
Frame
if (c instanceof Frame)
{
Frame f
= (Frame) c;
...
}
}

In the second cause, access AppletContext using the Applet.getAppletContext() method as shown in the following code:

public void foo()
    {
         ....
         AppletContext ac = (AppletContext) getAppletContext();
         ...
    }

Related Information

None.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


java.lang.NullPointerException thrown from a thread ...

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

java.lang.NullPointerException Thrown From a Thread When Applet.start() or Applet.stop() is Called

Symptoms

When running an applet in a browser using the Sun Java™ Runtime Environment (JRE™), a java.lang.NullPointerException is thrown from a thread when Applet.start() or Applet.stop() is called. The same applet runs under the Microsoft Virtual Machine (VM).

Cause

In the Microsoft VM, an applet may be visible immediately after Applet.init() is called but before Applet.start(). Similarly, an applet may still be visible after Applet.stop() but before Applet.destroy().

The Sun JRE implementation is slightly different in terms of applet visibility related to the lifecycle methods, so any applet that relies on the Microsoft VM event sequences may break.

Resolution

Code defensively to ensure the applet is visible before drawing. One way to do this is to test whether the Graphics object is null. For example, suppose the applet has the following methods:

        private Thread
paintThread = null;

public void
start()
{
if (paintThread == null)
{
paintThread = new Thread(this);
paintThread.start();
}
}

        public void
stop()
{
if (paintThread != null)
{
paintThread.interrupt();    // Assuming
the thread has sufficient
                                      //
time to be interrupted and stop
                                      //
drawing before destroy() is called.
paintThread = null;
}
}

public void
run()
{
while (Thread.currentThread().isInterrupted() ==
false)
{
Graphics g =
getGraphics();
g.drawString("Hello World", 100,
100);   // java.lang.NullPointerException if
                                                     //
applet is not visible -
//
g will be null !
}
}

The code for the
run method should be changed to the following:

        public void
run()
{
while (Thread.currentThread().isInterrupted() ==
false)
{
Graphics g =
getGraphics();

if (g != null)               // Code defensively!
g.drawString("Hello World", 100, 100);
}
}

Related Information

None.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


java.lang.NullPointerException Thrown in java.awt.Graphics.drawString()

Symptoms

When running an applet in a browser using the Sun Java Runtime Environment (JRE), a java.lang.NullPointerException is thrown by the java.awt.Graphics.drawString() method. The same applet runs under the Microsoft Virtual Machine (VM).

Cause

This exception is caused by passing a null string to the Graphics.drawString() method in the Sun JRE.

The Java class libraries in the Sun JRE have changed over time. Some APIs have been clarified, some have been deprecated, and some have had their implementation altered.

The result of passing a null string to the Graphics.drawString() method was not well defined, and the Microsoft VM treats null as an empty string. However, the implementation in the Sun JRE does not accept null as a valid string, thus resulting in a java.lang.NullPointerException.

Resolution

Code defensively to ensure only a non-null string is passed to the drawString() method. For example, the following code

Graphics g = getGraphics();
g.drawString(s, 100, 100);

should be changed to:

Graphics g = getGraphics();
if (s !== null) {
   g.drawString(s, 100, 100);
}

Related Information

None.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


java.lang.NullPointerException Thrown in java.awt.Graphics.drawImage()

Symptoms

When running an applet in a browser using the Sun Java Runtime Environment (JRE), a java.lang.NullPointerException is thrown in the java.awt.Graphics.drawImage() method. The same applet runs without any error under the Microsoft Virtual Machine (VM).

Cause

This exception is caused by passing a null image to the drawImage() method in the Sun JRE.

The Java class libraries in the Sun JRE have changed over time. Some APIs have been clarified, some have been deprecated, and some have their implementation altered.

The result of passing a null image into the Graphics.drawImage() method was not well defined. The Microsoft VM treats null image as a no-op. However, most versions of the Sun JRE do not accept null as a valid image, thus resulting in a java.lang.NullPointerException. As of JRE version 5.0, the specification has been clarified, and a null image argument is treated as a no-op.

Resolution

In JRE versions before 5.0, code defensively to ensure that only non-null images are passed to the drawImage() method. For example, the following code shows:

Graphics g = getGraphics();
    g.drawImage(img, 100, 100, this);

Change the above code to:

Graphics g = getGraphics();
if (img != null)
g.drawImage(img, 100, 100, this);

Related Information

None.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


java.lang.IllegalArgumentException thrown in java.awt.Color constructor ...

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

java.lang.IllegalArgumentException Thrown in java.awt.Color Constructor

Symptoms

When running an applet in a browser using the Sun Java Runtime Environment (JRE) implementation, a java.lang.IllegalArgumentException is thrown in the java.awt.Color constructor. The same applet runs under the Microsoft Virtual Machine (VM).

Cause

This exception is caused by passing over-bound or under-bound values to the Color constructor in the Sun JRE.

The Java class libraries in the Sun JRE have changed over time. Some APIs have been clarified, some have been deprecated, and some have had their implementation altered.

The result of passing values beyond the upper and lower bounds in the Color constructor is not well defined. The Microsoft VM readjusts the values to maximum color values and minimum color values automatically. The Sun JRE uses a java.lang.IllegalArgumentException to indicate that an out-of-bounds value is specified.

Resolution

Code to ensure that only valid color values are passed to the Color constructor. For example, if you have the following structure of code:

  void Color newColor(int r, int g, int b)
        {
            return new Color(r, g, b);
        }

Change the code to ensure that only valid color values are passed to the color constructor as shown below:

        int ensureColorRange(int v)
        {
            if (v < 0)
                return 0;
            else if (v > 255)
                return 255;
            else
                return v;
        }

        void Color newColor(int r, int g, int b)
        {
            r = ensureColorRange(r);
            g = ensureColorRange(g);
            b = ensureColorRange(b);

            return new Color(r, g, b);
        }

Related Information

None.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


java.security.AccessControlException thrown ...

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

java.security.AccessControlException Thrown in stop(), suspend(), or resume() Method of java.lang.Thread

Symptoms

When running an applet in a browser using the Sun Java Runtime Environment (JRE), a java.security.AccessControlException is thrown in the stop, suspend, or resume method of java.lang.Thread class as shown in the following code:

java.security.AccessControlException: access denied (java.lang.RuntimePermission modifyThread)
        at java.security.AccessControlContext.checkPermission(Unknown Source)
        at java.security.AccessController.checkPermission(Unknown Source)
        at java.lang.SecurityManager.checkPermission(Unknown Source)
        at sun.applet.AppletSecurity.checkAccess(Unknown Source)
        at java.lang.Thread.checkAccess(Unknown Source)
        at java.lang.Thread.stop(Unknown Source)
        at ....

The same applet runs without any error with the Microsoft Virtual Machine (VM).

Cause

This exception is caused when a user call these methods on a dead Thread object in the Sun JRE.

The Java class libraries in the Sun JRE have changed over time. Some APIs have been clarified, some have been deprecated, and some have their implementation altered.

The result of calling stop, suspend, and resume on a dead Thread object was not well defined. In the Microsoft VM, they result in a no-op. However, in the Sun JRE, calling these methods on a dead Thread object invalidates the underlying invariant expression of the implementation, thus resulting in an java.security.AccessControlException.

Resolution

The Thread stop, suspend, and resume methods are inherently unsafe and have been deprecated in the Java technology.

Replace calls to stop, suspend, and resume with code that modifies a variable to indicate that the target thread should stop or suspend or resume.

The following examples show how your can replace stop, suspend and resume methods with the alternative code:

For example, assume that your applet contains the following methods:

    private Thread blinker;

    public void start() {
        blinker = new Thread(this);
        blinker.start();
    }

    public void stop() {
        blinker.stop();  // UNSAFE!
    }

    public void destroy() {
        blinker.stop();  // UNSAFE and WILL throw java.security.AccessControlException in the Sun JRE!
    }

    public void run() {
        Thread thisThread = Thread.currentThread();
        while (true) {
            try {
                thisThread.sleep(interval);
            } catch (InterruptedException e){
            }
            repaint();
        }
    }

You can avoid the use of blinker.stop by modifying the applet's stop, destroy, and run methods as shown in the following code:

    private volatile Thread blinker;

    public void stop() {
        blinker = null;
    }

    public void destroy() {
        blinker = null;
    }

    public void run() {
        Thread thisThread = Thread.currentThread();
        while (blinker == thisThread) {
            try {
                thisThread.sleep(interval);
            } catch (InterruptedException e){
            }
            repaint();
        }
    }

For example consider an applet that has the mousePressed event handler which toggles the state of a thread called blinker as shown in the following code:

    private boolean threadSuspended;

    public void mousePressed(MouseEvent e) {
        e.consume();

        if (threadSuspended)
            blinker.resume();
        else
            blinker.suspend();  // DEADLOCK-PRONE!

        threadSuspended = !threadSuspended;
    }

    public void run()
    {
         while (true) {
        try {
            Thread.currentThread().sleep(interval);
        } catch (InterruptedException e){
        }
        repaint();
    }

You can avoid the use of blinker.suspend and blinker.resume by replacing the event handler with the following code:

    private boolean volatile threadSuspended;

    public synchronized void mousePressed(MouseEvent e) {
        e.consume();

        threadSuspended = !threadSuspended;

        if (!threadSuspended)
            notify();
    }

    public void run() {
        while (true) {
            try {
                Thread.currentThread().sleep(interval);

                if (threadSuspended) {
                    synchronized(this) {
                        while (threadSuspended)
                            wait();
                    }
                }
            } catch (InterruptedException e){
            }
            repaint();
        }
    }

Related Information

Why Are Thread.stop, Thread.suspend, Thread.resume, and Runtime.runFinalizersOnExit Deprecated?

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


java.lang.InstantiationException: Either "code" or "object" ...

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

java.lang.InstantiationException: either code or object should be specified, but not both

Symptoms

When running an applet in a browser using the Sun Java Runtime Environment (JRE) implementation, a java.lang.InstantiationException is thrown. The same applet runs without any errors with the Microsoft Virtual Machine (VM).

Cause

There are two possible causes.

  • Both code and object attributes are specified in the <APPLET> tag:

    <APPLET code=MyApplet object=MyApplet.ser width=100 height=100>
    </APPLET>

    The Sun JRE can access the code or the object attribute, and not both.
  • A code attribute is specified in the <APPLET> tag, and an object attribute is specified in a <PARAM> tag as shown in the following code:

    <APPLET code=MyApplet width=100 height=100>
    <PARAM name="object" value="someValue">
    </APPLET>

    public class MyApplet extends java.applet.Applet
    {
    public void init()
    {
    String value = getParameter("object");
    }
    ....
    }

    The Sun JRE does not support object as a parameter name.

Resolution

In the first cause eliminate the code attribute in the <APPLET> tag as shown in the following code:

     <APPLET object=MyApplet.ser width=100 height=100>
     </APPLET>

In the second cause change the parameter name to a different name as shown in the following code:

     <APPLET code=MyApplet width=100 height=100>
     <PARAM name="property1" value="someValue">
     </APPLET>

     public class MyApplet extends java.applet.Applet
     {
     public void init()
     {
      String value = getParameter("property1");
     }
     ....
     }

Related Information

None.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Signed applet upgraded from .cab to .jar files ...

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Signed Applet Upgraded From .cab to .jar File Throws a Security Exception When Run in Microsoft Virtual Machine (VM)

Symptoms

After you upgrade a signed applet from .cab to .jar files, the applet no longer works in the Microsoft VM. The applet runs without any error in the Sun Java Runtime Environment (JRE) implementation.

Cause

Microsoft VM does not support signed .jar files. Microsoft VM supports unsigned .jar files through the archive attribute of the <APPLET> tag. However Microsoft VM treats classes and resources within the signed .jar files as untrusted.

As a result, the applet is treated as untrusted by the Microsoft VM. Any action which the applet performs ,that requires access outside the applet sandbox, results in a security exception.

Resolution

The only applet signing scheme recognized by the Microsoft VM is Authenticode technology which is used with the .cab files.

Specify the upgraded .jar files through the archive attribute for the Sun JRE, and continue to specify the .cab files through cabbase for the Microsoft VM. For example, assume that you have the following code:

<APPLET code="MyApplet" width=100 height=100>
<PARAM name="cabbase" value="package1.cab, package2.cab">
</APPLET>

Change the above code as shown in the following code:

<APPLET code="MyApplet" archive="package1.jar, package2.jar"
width=100 height=100>
<PARAM name="cabbase" value="package1.cab, package2.cab">
</APPLET>

Related Information

None.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Unable To Use Certificates From the Browser For Client Authentication

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Unable To Use Certificates From the Browser For Client Authentication.

Symptoms

When running an applet in a browser using the Sun Java Runtime Environment (JRE) implementation, the applet is unable to use certificates from the browser for https client authentication.

Cause

The Java plug-in uses certificates for client authentication from a certificate store specific to the Sun Java Runtime Environment (JRE). The plug-in does not use the certificates from the browser certificate store.

Resolution

Client authentication in Java plug-in requires the client certificate store on the user disk, keystore type, and the password to access the client. The following three parameters should be provided with system properties:

-Djavax.net.ssl.keyStore=<client_keystore_file_path>
-Djavax.net.ssl.keyStorePassword=<password to access the client keystore file>
-Djavax.net.ssl.keyStoreType=<keystore_type>

These properties should be specified in the Advanced tab of the Java Control Panel.

To export a digital certificate from the browser certificate store into a file, perform the following steps:

  1. Open a browser window and click on Tools. Click the Internet Options submenu item.
  2. Click the Content tab.
  3. In the certificates section in the middle, click the Certificates button. The available certificates are shown in the dialog box.
  4. Select Client Authentication in the Intended Purpose drop down menu.
  5. Select the certificate you want to export.
  6. Click the Export button. The Certificate Manager Export Wizard starts.
  7. On the Welcome window, click Next.
  8. Keep the default to "Yes, export the private key" and click Next.
  9. Keep the default to "Personal Information Exchange - PKCS #12(.PFX)" and click Next.
  10. Type the required information in the Password window.
  11. Type the path and filename of the file to export. The system automatically gives the file a .pfx extension. Click Next.
  12. Review the information that you provided in above steps and click Finish.

Example:

If the user exports the certificate to a file called c:\certs\client.pfx and uses the password test to protect the .pfx file, the required system properties will take the following values:

-Djavax.net.ssl.keyStore=c:\certs\client.pfx
-Djavax.net.ssl.keyStorePassword=test
-Djavax.net.ssl.keyStoreType=pkcs12

Related Information

None.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Redirection Between HTTP URL and HTTPS URL Is Not Followed.

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Redirection Between HTTP URL and HTTPS URL Is Not Followed

Symptoms

When running an applet in a browser using the Sun Java Runtime Environment (JRE), if the applet makes HTTP requests to a server that redirects the request to an HTTPS URL, the redirection fails. The redirection also fails in the case of making HTTPS requests to a server that redirects the request to an HTTP URL. The same applet runs without any error in the Microsoft Virtual Machine (VM).

Cause

The issue is caused by the HTTP or HTTPS redirection policy implemented in Sun JRE. Because of serious security consequences, redirection between HTTP and HTTPS is not automatically followed.

When an applet is run in a browser using the Microsoft VM, a security warning dialog prompts the user for his consent to redirect. Redirection fails if the user does not consent to it.

Resolution

The application which runs the applet in a browser needs to check the response code and recognize it as a redirect. The Location header field value can be checked for the redirect information, and then the application must decide whether or not to follow the redirect using the new protocol. For example, if the following code is available in an application:

public void makeConnection(URL url)
{
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
....
is.close();
}

the above code should be changed to the following code:

private InputStream openConnectionCheckRedirects(URLConnection c) throws IOException
{
   boolean redir;
   int redirects = 0;
   InputStream in = null;
    do
   {
      if (c instanceof HttpURLConnection)
      {
         ((HttpURLConnection) c).setInstanceFollowRedirects(false);
      }
       // We want to open the input stream before getting headers
      // because getHeaderField() et al swallow IOExceptions.
      in = c.getInputStream();
      redir = false;
      if (c instanceof HttpURLConnection)
      {
         HttpURLConnection http = (HttpURLConnection) c;
         int stat = http.getResponseCode();
         if (stat >= 300 && stat <= 307 && stat != 306 &&
            stat != HttpURLConnection.HTTP_NOT_MODIFIED)
         {
            URL base = http.getURL();
            String loc = http.getHeaderField("Location");
            URL target = null;
            if (loc != null)
            {
               target = new URL(base, loc);
            }
            http.disconnect();
            // Redirection should be allowed only for HTTP and HTTPS
            // and should be limited to 5 redirections at most.
            if (target == null || !(target.getProtocol().equals("http")
               || target.getProtocol().equals("https"))
               || redirects >= 5)
            {
               throw new SecurityException("illegal URL redirect");
            }
            redir = true;
            c = target.openConnection();
            redirects++;
         }
      }
   }
   while (redir);
   return in;
}

public void makeConnection(URL url){
try{
   URLConnection conn = url.openConnection();
   InputStream is = openConnectionCheckRedirects(conn);
   ....
   is.close();
}catch (IOException e){ } }

Related Information

None.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Bold CJK (Chinese-Japanese-Korean) Fonts are Difficult to Read.

Symptoms

CJK (Chinese-Japanese-Korean) fonts, when displayed in bold, are difficult to read.

Cause

CJK fonts, when displayed in bold, are sometimes difficult to read at small sizes of about 16 points or less.

Resolution

Specify the font as 'plain'.

Related Information

None.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Programming With Assertions

An assertion is a statement in the JavaTM programming language that enables you to test your assumptions about your program. For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light.

Each assertion contains a boolean expression that you believe will be true when the assertion executes. If it is not true, the system will throw an error. By verifying that the boolean expression is indeed true, the assertion confirms your assumptions about the behavior of your program, increasing your confidence that the program is free of errors.

Experience has shown that writing assertions while programming is one of the quickest and most effective ways to detect and correct bugs. As an added benefit, assertions serve to document the inner workings of your program, enhancing maintainability.

This document shows you how to program with assertions. It covers the topics:

  • Introduction
  • Putting Assertions Into Your Code
  • Compiling Files That Use Assertions
  • Enabling and Disabling Assertions
  • Compatibility With Existing Programs
  • Design FAQ

Introduction

The assertion statement has two forms. The first, simpler form is:

assert Expression1 ;

where Expression1 is a boolean expression. When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no detail message.

The second form of the assertion statement is:

assert Expression1 : Expression2 ;

where:

  • Expression1 is a boolean expression.
  • Expression2 is an expression that has a value. (It cannot be an invocation of a method that is declared void.)

Use this version of the assert statement to provide a detail message for the AssertionError. The system passes the value of Expression2 to the appropriate AssertionError constructor, which uses the string representation of the value as the error's detail message.

The purpose of the detail message is to capture and communicate the details of the assertion failure. The message should allow you to diagnose and ultimately fix the error that led the assertion to fail. Note that the detail message is not a user-level error message, so it is generally unnecessary to make these messages understandable in isolation, or to internationalize them. The detail message is meant to be interpreted in the context of a full stack trace, in conjunction with the source code containing the failed assertion.

Like all uncaught exceptions, assertion failures are generally labeled in the stack trace with the file and line number from which they were thrown. The second form of the assertion statement should be used in preference to the first only when the program has some additional information that might help diagnose the failure. For example, if Expression1 involves the relationship between two variables x and y, the second form should be used. Under these circumstances, a reasonable candidate for Expression2 would be "x: " + x + ", y: " + y.

In some cases Expression1 may be expensive to evaluate. For example, suppose you write a method to find the minimum element in an unsorted list, and you add an assertion to verify that the selected element is indeed the minimum. The work done by the assert will be at least as expensive as the work done by the method itself. To ensure that assertions are not a performance liability in deployed applications, assertions can be enabled or disabled when the program is started, and are disabled by default. Disabling assertions eliminates their performance penalty entirely. Once disabled, they are essentially equivalent to empty statements in semantics and performance. See Enabling and Disabling Assertions for more information.

The addition of the assert keyword to the Java programming language has implications for existing code. See Compatibility With Existing Programs for more information.

Putting Assertions Into Your Code

There are many situations where it is good to use assertions, including:

  • Internal Invariants
  • Control-Flow Invariants
  • Preconditions, Postconditions, and Class Invariants

There are also situations where you should not use them:

  • Do not use assertions for argument checking in public methods.

    Argument checking is typically part of the published specifications (or contract) of a method, and these specifications must be obeyed whether assertions are enabled or disabled. Another problem with using assertions for argument checking is that erroneous arguments should result in an appropriate runtime exception (such as IllegalArgumentException, IndexOutOfBoundsException, or NullPointerException). An assertion failure will not throw an appropriate exception.

  • Do not use assertions to do any work that your application requires for correct operation.

    Because assertions may be disabled, programs must not assume that the boolean expression contained in an assertion will be evaluated. Violating this rule has dire consequences. For example, suppose you wanted to remove all of the null elements from a list names, and knew that the list contained one or more nulls. It would be wrong to do this:

    // Broken! - action is contained in assertion
assert names.remove(null);

    The program would work fine when asserts were enabled, but would fail when they were disabled, as it would no longer remove the null elements from the list. The correct idiom is to perform the action before the assertion and then assert that the action succeeded:

    // Fixed - action precedes assertion
boolean nullsRemoved = names.remove(null);
assert nullsRemoved;  // Runs whether or not asserts are enabled

    As a rule, the expressions contained in assertions should be free of side effects: evaluating the expression should not affect any state that is visible after the evaluation is complete. One exception to this rule is that assertions can modify state that is used only from within other assertions. An idiom that makes use of this exception is presented later in this document.

Internal Invariants

Before assertions were available, many programmers used comments to indicate their assumptions concerning a program's behavior. For example, you might have written something like this to explain your assumption about an else clause in a multiway if-statement:

if (i % 3 == 0) {
    ...
} else if (i % 3 == 1) {
    ...
} else { // We know (i % 3 == 2)
    ...
}

You should now use an assertion whenever you would have written a comment that asserts an invariant. For example, you should rewrite the previous if-statement like this:

if (i % 3 == 0) {
   ...
} else if (i % 3 == 1) {
    ...
} else {
    assert i % 3 == 2 : i;
    ...
}

Note, incidentally, that the assertion in the above example may fail if i is negative, as the % operator is not a true modulus operator, but computes the remainder, which may be negative.

Another good candidate for an assertion is a switch statement with no default case. The absence of a default case typically indicates that a programmer believes that one of the cases will always be executed. The assumption that a particular variable will have one of a small number of values is an invariant that should be checked with an assertion. For example, suppose the following switch statement appears in a program that handles playing cards:

switch(suit) {
  case Suit.CLUBS:
    ...
  break;

  case Suit.DIAMONDS:
    ...
  break;

  case Suit.HEARTS:
    ...
    break;

  case Suit.SPADES:
      ...
}

It probably indicates an assumption that the suit variable will have one of only four values. To test this assumption, you should add the following default case:

default:
    assert false : suit;

If the suit variable takes on another value and assertions are enabled, the assert will fail and an AssertionError will be thrown.

An acceptable alternative is:

default:
    throw new AssertionError(suit);

This alternative offers protection even if assertions are disabled, but the extra protection adds no cost: the throw statement won't execute unless the program has failed. Moreover, the alternative is legal under some circumstances where the assert statement is not. If the enclosing method returns a value, each case in the switch statement contains a return statement, and no return statement follows the switch statement, then it would cause a syntax error to add a default case with an assertion. (The method would return without a value if no case matched and assertions were disabled.)

Control-Flow Invariants

The previous example not only tests an invariant, it also checks an assumption about the application's flow of control. The author of the original switch statement probably assumed not only that the suit variable would always have one of four values, but also that one of the four cases would always be executed. It points out another general area where you should use assertions: place an assertion at any location you assume will not be reached. The assertions statement to use is:

assert false;

For example, suppose you have a method that looks like this:

void foo() {
    for (...) {
      if (...)
        return;
    }
    // Execution should never reach this point!!!
}

Replace the final comment so that the code now reads:

void foo() {
    for (...) {
      if (...)
        return;
    }
    assert false; // Execution should never reach this point!
}

Note: Use this technique with discretion. If a statement is unreachable as defined in the Java Language Specification, you will get a compile time error if you try to assert that it is not reached. Again, an acceptable alternative is simply to throw an AssertionError.

Preconditions, Postconditions, and Class Invariants

While the assert construct is not a full-blown design-by-contract facility, it can help support an informal design-by-contract style of programming. This section shows you how to use asserts for:

  • Preconditions — what must be true when a method is invoked.
    • Lock-Status Preconditions — preconditions concerning whether or not a given lock is held.
  • Postconditions — what must be true after a method completes successfully.
  • Class invariants — what must be true about each instance of a class.

Preconditions

By convention, preconditions on public methods are enforced by explicit checks that throw particular, specified exceptions. For example:

/**
  * Sets the refresh rate.
  *
  * @param  rate refresh rate, in frames per second.
  * @throws IllegalArgumentException if rate <= 0 or
  * rate > MAX_REFRESH_RATE.
*/
public void setRefreshRate(int rate) {
  // Enforce specified precondition in public method
  if (rate <= 0 || rate > MAX_REFRESH_RATE)
    throw new IllegalArgumentException("Illegal rate: " + rate);
    setRefreshInterval(1000/rate);
  }

This convention is unaffected by the addition of the assert construct. Do not use assertions to check the parameters of a public method. An assert is inappropriate because the method guarantees that it will always enforce the argument checks. It must check its arguments whether or not assertions are enabled. Further, the assert construct does not throw an exception of the specified type. It can throw only an AssertionError.

You can, however, use an assertion to test a nonpublic method's precondition that you believe will be true no matter what a client does with the class. For example, an assertion is appropriate in the following "helper method" that is invoked by the previous method:

/**
 * Sets the refresh interval (which must correspond to a legal frame rate).
 *
 * @param  interval refresh interval in milliseconds.
*/
 private void setRefreshInterval(int interval) {
  // Confirm adherence to precondition in nonpublic method
  assert interval > 0 && interval <= 1000/MAX_REFRESH_RATE : interval;

  ... // Set the refresh interval
 }

Note, the above assertion will fail if MAX_REFRESH_RATE is greater than 1000 and the client selects a refresh rate greater than 1000. This would, in fact, indicate a bug in the library!

Lock-Status Preconditions

Classes designed for multithreaded use often have non-public methods with preconditions relating to whether or not some lock is held. For example, it is not uncommon to see something like this:

private Object[] a;
public synchronized int find(Object key) {
  return find(key, a, 0, a.length);
}

// Recursive helper method - always called with a lock on this object
private int find(Object key, Object[] arr, int start, int len) {
 ...
}

A static method called holdsLock has been added to the Thread class to test whether the current thread holds the lock on a specified object. This method can be used in combination with an assert statement to supplement a comment describing a lock-status precondition, as shown in the following example:

// Recursive helper method - always called with a lock on this.
private int find(Object key, Object[] arr, int start, int len) {
  assert Thread.holdsLock(this); // lock-status assertion
  ...
}

Note that it is also possible to write a lock-status assertion asserting that a given lock isn't held.

Postconditions

You can test postcondition with assertions in both public and nonpublic methods. For example, the following public method uses an assert statement to check a post condition:

 /**
  * Returns a BigInteger whose value is (this-1 mod m).
  *
  * @param  m the modulus.
  * @return this-1 mod m.
  * @throws ArithmeticException  m <= 0, or this BigInteger
  *has no multiplicative inverse mod m (that is, this BigInteger
  *is not relatively prime to m).
  */
public BigInteger modInverse(BigInteger m) {
  if (m.signum <= 0)
    throw new ArithmeticException("Modulus not positive: " + m);
  ... // Do the computation
  assert this.multiply(result).mod(m).equals(ONE) : this;
  return result;
}

Occasionally it is necessary to save some data prior to performing a computation in order to check a postcondition. You can do this with two assert statements and a simple inner class that saves the state of one or more variables so they can be checked (or rechecked) after the computation. For example, suppose you have a piece of code that looks like this:

 void foo(int[] array) {
  // Manipulate array
  ...

  // At this point, array will contain exactly the ints that it did
  // prior to manipulation, in the same order.
 }

Here is how you could modify the above method to turn the textual assertion of a postcondition into a functional one:

 void foo(final int[] array) {

  // Inner class that saves state and performs final consistency check
  class DataCopy {
private int[] arrayCopy;

DataCopy() { arrayCopy = (int[]) array.clone(); }

boolean isConsistent() { return Arrays.equals(array, arrayCopy); }
  }

  DataCopy copy = null;

  // Always succeeds; has side effect of saving a copy of array
  assert ((copy = new DataCopy()) != null);

  ... // Manipulate array

  // Ensure array has same ints in same order as before manipulation.
  assert copy.isConsistent();
  }

You can easily generalize this idiom to save more than one data field, and to test arbitrarily complex assertions concerning pre-computation and post-computation values.

You might be tempted to replace the first assert statement (which is executed solely for its side-effect) by the following, more expressive statement:

 copy = new DataCopy();

Don't make this replacement. The statement above would copy the array whether or not asserts were enabled, violating the principle that assertions should have no cost when disabled.

Class Invariants

A class invariant is a type of internal invariant that applies to every instance of a class at all times, except when an instance is in transition from one consistent state to another. A class invariant can specify the relationships among multiple attributes, and should be true before and after any method completes. For example, suppose you implement a balanced tree data structure of some sort. A class invariant might be that the tree is balanced and properly ordered.

The assertion mechanism does not enforce any particular style for checking invariants. It is sometimes convenient, though, to combine the expressions that check required constraints into a single internal method that can be called by assertions. Continuing the balanced tree example, it might be appropriate to implement a private method that checked that the tree was indeed balanced as per the dictates of the data structure:

 // Returns true if this tree is properly balanced
 private boolean balanced() {
  ...
 }

Because this method checks a constraint that should be true before and after any method completes, each public method and constructor should contain the following line immediately prior to its return:

 assert balanced();

It is generally unnecessary to place similar checks at the head of each public method unless the data structure is implemented by native methods. In this case, it is possible that a memory corruption bug could corrupt a "native peer" data structure in between method invocations. A failure of the assertion at the head of such a method would indicate that such memory corruption had occurred. Similarly, it may be advisable to include class invariant checks at the heads of methods in classes whose state is modifiable by other classes. (Better yet, design classes so that their state is not directly visible to other classes!)

Advanced Uses

The following sections discuss topics that apply only to resource-constrained devices and to systems where asserts must not be disabled in the field. If you have no interest in these topics, skip to the next section, "Compiling Files that Use Assertions".

Removing all Trace of Assertions from Class Files

Programmers developing applications for resource-constrained devices may wish to strip assertions out of class files entirely. While this makes it impossible to enable assertions in the field, it also reduces class file size, possibly leading to improved class loading performance. In the absence of a high quality JIT, it could lead to decreased footprint and improved runtime performance.

The assertion facility offers no direct support for stripping assertions out of class files. The assert statement may, however, be used in conjunction with the "conditional compilation" idiom described in the Java Language Specification, enabling the compiler to eliminate all traces of these asserts from the class files that it generates:

 static final boolean asserts = ... ; // false to eliminate asserts

 if (asserts)
  assert <expr> ;

Requiring that Assertions are Enabled

Programmers of certain critical systems might wish to ensure that assertions are not disabled in the field. The following static initialization idiom prevents a class from being initialized if its assertions have been disabled:

 static {
  boolean assertsEnabled = false;
  assert assertsEnabled = true; // Intentional side effect!!!
  if (!assertsEnabled)
throw new RuntimeException("Asserts must be enabled!!!");
 }

Put this static-initializer at the top of your class.

Compiling Files That Use Assertions

In order for the javac compiler to accept code containing assertions, you must use the -source 1.4 command-line option as in this example:

 javac -source 1.4 MyClass.java

This flag is necessary so as not to cause source compatibility problems.

Enabling and Disabling Assertions

By default, assertions are disabled at runtime. Two command-line switches allow you to selectively enable or disable assertions.

To enable assertions at various granularities, use the -enableassertions, or -ea, switch. To disable assertions at various granularities, use the -disableassertions, or -da, switch. You specify the granularity with the arguments that you provide to the switch:

  • no arguments
    Enables or disables assertions in all classes except system classes.
  • packageName...
    Enables or disables assertions in the named package and any subpackages.
  • ...
    Enables or disables assertions in the unnamed package in the current working directory.
  • className
    Enables or disables assertions in the named class

For example, the following command runs a program, BatTutor, with assertions enabled in only package com.wombat.fruitbat and its subpackages:

 java -ea:com.wombat.fruitbat... BatTutor

If a single command line contains multiple instances of these switches, they are processed in order before loading any classes. For example, the following command runs the BatTutor program with assertions enabled in package com.wombat.fruitbat but disabled in class com.wombat.fruitbat.Brickbat:

 java -ea:com.wombat.fruitbat... -da:com.wombat.fruitbat.Brickbat BatTutor

The above switches apply to all class loaders. With one exception, they also apply to system classes (which do not have an explicit class loader). The exception concerns the switches with no arguments, which (as indicated above) do not apply to system classes.This behavior makes it easy to enable asserts in all classes except for system classes, which is commonly desirable.

To enable assertions in all system classes, use a different switch: -enablesystemassertions, or -esa. Similarly, to disable assertions in system classes, use -disablesystemassertions, or -dsa.

For example, the following command runs the BatTutor program with assertions enabled in system classes, as well as in the com.wombat.fruitbat package and its subpackages:

 java -esa -ea:com.wombat.fruitbat...

The assertion status of a class (enabled or disabled) is set at the time it is initialized, and does not change. There is, however, one corner case that demands special treatment. It is possible, though generally not desirable, to execute methods or constructors prior to initialization. This can happen when a class hierarchy contains a circularity in its static initialization.

If an assert statement executes before its class is initialized, the execution must behave as if assertions were enabled in the class. This topic is discussed in detail in the assertions specification in the Java Language Specification.

Compatibility With Existing Programs

The addition of the assert keyword to the Java programming language does not cause any problems with preexisting binaries (.class files). If you try to compile an application that uses assert as an identifier, however, you will receive a warning or error message. In order to ease the transition from a world where assert is a legal identifier to one where it isn't, the compiler supports two modes of operation in this release:

  • source mode 1.3 (default) — the compiler accepts programs that use assert as an identifier, but issues warnings. In this mode, programs are not permitted to use the assert statement.
  • source mode 1.4 — the compiler generates an error message if the program uses assert as an identifier. In this mode, programs are permitted to use the assert statement.

Unless you specifically request source mode 1.4 with the -source 1.4 flag, the compiler operates in source mode 1.3. If you forget to use this flag, programs that use the new assert statement will not compile. Having the compiler use the old semantics as its default behavior (that is, allowing assert to be used as an identifier) was done for maximal source compatibility. Source mode 1.3 is likely to be phased out over time.

Design FAQ

Here is a collection of frequently asked questions concerning the design of the assertion facility.

  • General Questions
  • Compatibility
  • Syntax and Semantics
  • The AssertionError Class
  • Enabling and Disabling Assertions

General Questions

  • Why provide an assertion facility, given that one can program assertions atop the Java programming language with no special support?

    Although ad hoc implementations are possible, they are of necessity either ugly (requiring an if statement for each assertion) or inefficient (evaluating the condition even if assertions are disabled). Further, each ad hoc implementation has its own means of enabling and disabling assertions, which lessens the utility of these implementations, especially for debugging in the field. As a result of these shortcomings, assertions have never become a part of the culture among engineers using the Java programming language. Adding assertion support to the platform stands a good chance of rectifying this situation.

  • Why does this facility justify a language change, as opposed to a library solution?

    We recognize that a language change is a serious effort, not to be undertaken lightly. The library approach was considered. It was, however, deemed essential that the runtime cost of assertions be negligible if they are disabled. In order to achieve this with a library, the programmer is forced to hard-code each assertion as an if statement. Many programmers would not do this. Either they would omit the if statement and performance would suffer, or they would ignore the facility entirely. Note also that assertions were contained in James Gosling's original specification for the Java programming language. Assertions were removed from the Oak specification because time constraints prevented a satisfactory design and implementation.

  • Why not provide a full-fledged design-by-contract facility with preconditions, postconditions and class invariants, like the one in the Eiffel programming language?

    We considered providing such a facility, but were unable to convince ourselves that it is possible to graft it onto the Java programming language without massive changes to the Java platform libraries, and massive inconsistencies between old and new libraries. Further, we were not convinced that such a facility would preserve the simplicity that is the hallmark of the Java programming language. On balance, we came to the conclusion that a simple boolean assertion facility was a fairly straight-forward solution and far less risky. It's worth noting that adding a boolean assertion facility to the language doesn't preclude adding a full-fledged design-by-contract facility at some time in the future.

    The simple assertion facility does enable a limited form of design-by-contract style programming. The assert statement is appropriate for nonpublic precondition, postcondition and class invariant checking. Public precondition checking should still be performed by checks inside methods that result in particular, documented exceptions, such as IllegalArgumentException and IllegalStateException.

  • In addition to boolean assertions, why not provide an assert-like construct to suppress the execution of an entire block of code if assertions are disabled?

    Providing such a construct would encourage programmers to put complex assertions inline, when they are better relegated to separate methods.

Compatibility

  • Won't the new keyword cause compatibility problems with existing programs that use assert as an identifier?

    Yes, for source files. (Binaries for classes that use assert as an identifier will continue to work fine.) To ease the transition, we implemented a strategy whereby developers can continue using assert as an identifier during a transitional period.

  • Doesn't this facility produce class files that cannot be run against older JREs?

    Yes. Class files will contain calls to the new ClassLoader and Class methods, such as desiredAssertionStatus. If a class file containing calls to these methods is run against an older JRE (whose ClassLoader class doesn't define the methods), the program will fail at run time, throwing a NoSuchMethodError. It is generally the case that programs using new facilities are not compatible with older releases.

Syntax and Semantics

  • Why allow primitive types in Expression2?

    There is no compelling reason to restrict the type of this expression. Allowing arbitrary types provides convenience for developers who, for example, want to associate a unique integer code with each assertion. Further, it makes this expression feel like the argument of System.out.println(...), which is seen as desirable.

The AssertionError Class

  • When an AssertionError is generated by an assert statement in which Expression2 is absent, why isn't the program text of the asserted condition used as the detail message (for example, "height < maxHeight")?

    While doing so might improve out-of-the-box usefulness of assertions in some cases, the benefit doesn't justify the cost of adding all those string constants to .class files and runtime images.

  • Why doesn't an AssertionError allow access to the object that generated it? Similarly, why not pass an arbitrary object from the assertion to the AssertionError constructor in place of a detail message?

    Access to these objects would encourage programmers to attempt to recover from assertion failures, which defeats the purpose of the facility.

  • Why not provide context accessors (like getFile, getline, getMethod) on AssertionError?

    This facility is best provided on Throwable, so it may be used for all throwables, not just assertion errors. We enhanced Throwable with the getStackTrace method to provide this functionality.

  • Why is AssertionError a subclass of Error rather than RuntimeException?

    This issue was controversial. The expert group discussed it at length, and came to the conclusion that Error was more appropriate to discourage programmers from attempting to recover from assertion failures. It is, in general, difficult or impossible to localize the source of an assertion failure. Such a failure indicates that the program is operating "outside of known space," and attempts to continue execution are likely to be harmful. Further, convention dictates that methods specify most runtime exceptions they may throw (with @throws doc comments). It makes little sense to include in a method's specification the circumstances under which it may generate an assertion failure. Such information may be regarded as an implementation detail, which can change from implementation to implementation and release to release.

Enabling and Disabling Assertions

  • Why not provide a compiler flag to completely eliminate assertions from object files?

    It is a firm requirement that it be possible to enable assertions in the field, for enhanced serviceability. It would have been possible to also permit developers to eliminate assertions from object files at compile time. Assertions can contain side effects, though they should not, and such a flag could therefore alter the behavior of a program in significant ways. It is viewed as good thing that there is only one semantics associated with each valid Java program. Also, we want to encourage users to leave asserts in object files so they can be enabled in the field. Finally, the spec demands that assertions behave as if enabled when a class runs before it is initialized. It would be impossible to offer these semantics if assertions were stripped from the class file. Note, however, that the standard "conditional compilation idiom" described in the Java Language Specification can be used to achieve this effect for developers who really want it.

  • Why do the commands that enable and disable assertions use package-tree semantics instead of the more traditional package semantics?

    Hierarchical control is useful, as programmers really do use package hierarchies to organize their code. For example, package-tree semantics allow assertions to be enabled or disabled in all of Swing at one time.

  • Why does setClassAssertionStatus return a boolean instead of throwing an exception if it is invoked when it's too late to set the assertion status (that is, if the named class has already been initialized)?

    No action (other than perhaps a warning message) is necessary or desirable if it's too late to set the assertion status. An exception seems unduly heavyweight.

  • Why not overload a single method name to take the place of setDefaultAssertionStatus and setAssertionStatus?

    Clarity in method naming is for the greater good. Overloading tends to cause confusion.

  • Why not tweak the semantics of desiredAssertionStatus to make it more "programmer friendly" by returning the actual assertion status if a class is already initialized?

    It's not clear that there would be any use for the resulting method. The method isn't designed for application programmer use, and it seems inadvisable to make it slower and more complex than necessary.

  • Why is there no RuntimePermission to prevent applets from enabling/disabling assertions?

    While applets have no reason to call any of the ClassLoader methods for modifying assertion status, allowing them to do so seems harmless. At worst, an applet can mount a weak denial-of-service attack by enabling assertions in classes that have yet to be initialized. Moreover, applets can only affect the assert status of classes that are to be loaded by class loaders that the applets can access. There already exists a RuntimePermission to prevent untrusted code from gaining access to class loaders (getClassLoader).

  • Why not provide a construct to query the assert status of the containing class?

    Such a construct would encourage people to inline complex assertion code, which we view as a bad thing. Further, it is straightforward to query the assert status atop the current API, if you feel you must:

    boolean assertsEnabled = false;
assert assertsEnabled = true;  // Intentional side-effect!!!
// Now assertsEnabled is set to the correct value
  • Why does an assert statement that executes before its class is initialized behave as if assertions were enabled in the class?

  • Few programmers are aware of the fact that a class's constructors and methods can run prior to its initialization. When this happens, it is quite likely that the class's invariants have not yet been established, which can cause serious and subtle bugs. Any assertion that executes in this state is likely to fail, alerting the programmer to the problem. Thus, it is generally helpful to the programmer to execute all assertions encountered while in this state.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.source.tree.AssertTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.AssertTree

  • Packages that use AssertTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of AssertTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type AssertTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitAssert(AssertTree node, P p)

    • Uses of AssertTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type AssertTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitAssert(AssertTree node, P p)
      R | SimpleTreeVisitor.visitAssert(AssertTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.AssignmentTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.AssignmentTree

  • Packages that use AssignmentTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of AssignmentTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type AssignmentTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitAssignment(AssignmentTree node, P p)

    • Uses of AssignmentTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type AssignmentTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitAssignment(AssignmentTree node, P p)
      R | SimpleTreeVisitor.visitAssignment(AssignmentTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class javax.smartcardio.ATR (Java Smart Card I/O b138)

  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
javax.smartcardio.ATR

    • Uses of ATR in javax.smartcardio

      Methods in javax.smartcardio that return ATR
      Modifier and Type Method and Description
      abstract ATR Card.getATR()
      Returns the ATR of this card.
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.connect.AttachingConnector (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.connect.AttachingConnector

  • Packages that use AttachingConnector
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of AttachingConnector in com.sun.jdi

      Methods in com.sun.jdi that return types with arguments of type AttachingConnector
      Modifier and Type Method and Description
      List<AttachingConnector> VirtualMachineManager.attachingConnectors()
      Returns the list of known AttachingConnector objects.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.tools.attach.AttachNotSupportedException (Attach API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Attach API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.tools.attach.AttachNotSupportedException

  • Packages that use AttachNotSupportedException
    Package Description
    com.sun.tools.attach
    Provides the API to attach to a JavaTM virtual machine.
    com.sun.tools.attach.spi
    Provider classes for the com.sun.tools.attach package.

    • Uses of AttachNotSupportedException in com.sun.tools.attach

      Methods in com.sun.tools.attach that throw AttachNotSupportedException
      Modifier and Type Method and Description
      static VirtualMachine VirtualMachine.attach(String id)
      Attaches to a Java virtual machine.
      static VirtualMachine VirtualMachine.attach(VirtualMachineDescriptor vmd)
      Attaches to a Java virtual machine.

    • Uses of AttachNotSupportedException in com.sun.tools.attach.spi

      Methods in com.sun.tools.attach.spi that throw AttachNotSupportedException
      Modifier and Type Method and Description
      abstract VirtualMachine AttachProvider.attachVirtualMachine(String id)
      Attaches to a Java virtual machine.
      VirtualMachine AttachProvider.attachVirtualMachine(VirtualMachineDescriptor vmd)
      Attaches to a Java virtual machine.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Attach API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.tools.attach.AttachPermission (Attach API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Attach API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.tools.attach.AttachPermission

No usage of com.sun.tools.attach.AttachPermission
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Attach API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.tools.attach.spi.AttachProvider (Attach API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Attach API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.tools.attach.spi.AttachProvider

  • Packages that use AttachProvider
    Package Description
    com.sun.tools.attach
    Provides the API to attach to a JavaTM virtual machine.
    com.sun.tools.attach.spi
    Provider classes for the com.sun.tools.attach package.

    • Uses of AttachProvider in com.sun.tools.attach

      Methods in com.sun.tools.attach that return AttachProvider
      Modifier and Type Method and Description
      AttachProvider VirtualMachineDescriptor.provider()
      Return the AttachProvider that this descriptor references.
      AttachProvider VirtualMachine.provider()
      Returns the provider that created this virtual machine.
      Constructors in com.sun.tools.attach with parameters of type AttachProvider
      Constructor and Description
      VirtualMachine(AttachProvider provider, String id)
      Initializes a new instance of this class.
      VirtualMachineDescriptor(AttachProvider provider, String id)
      Creates a virtual machine descriptor from the given components.
      VirtualMachineDescriptor(AttachProvider provider, String id, String displayName)
      Creates a virtual machine descriptor from the given components.

    • Uses of AttachProvider in com.sun.tools.attach.spi

      Methods in com.sun.tools.attach.spi that return types with arguments of type AttachProvider
      Modifier and Type Method and Description
      static List<AttachProvider> AttachProvider.providers()
      Returns a list of the installed attach providers.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Attach API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.Attr (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.Attr

  • Packages that use Attr
    Package Description
    org.w3c.dom
    Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.

    • Uses of Attr in org.w3c.dom

      Methods in org.w3c.dom that return Attr
      Modifier and Type Method and Description
      Attr Document.createAttribute(String name)
      Creates an Attr of the given name.
      Attr Document.createAttributeNS(String namespaceURI, String qualifiedName)
      Creates an attribute of the given qualified name and namespace URI.
      Attr Element.getAttributeNode(String name)
      Retrieves an attribute node by name.
      Attr Element.getAttributeNodeNS(String namespaceURI, String localName)
      Retrieves an Attr node by local name and namespace URI.
      Attr Element.removeAttributeNode(Attr oldAttr)
      Removes the specified attribute node.
      Attr Element.setAttributeNode(Attr newAttr)
      Adds a new attribute node.
      Attr Element.setAttributeNodeNS(Attr newAttr)
      Adds a new attribute.
      Methods in org.w3c.dom with parameters of type Attr
      Modifier and Type Method and Description
      Attr Element.removeAttributeNode(Attr oldAttr)
      Removes the specified attribute node.
      Attr Element.setAttributeNode(Attr newAttr)
      Adds a new attribute node.
      Attr Element.setAttributeNodeNS(Attr newAttr)
      Adds a new attribute.
      void Element.setIdAttributeNode(Attr idAttr, boolean isId)
      If the parameter isId is true, this method declares the specified attribute to be a user-determined ID attribute .
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Java Print Service API User Guide: 2 - Attributes

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

CHAPTER 2

Attributes

When sending print data to a printer, a client also provides instructions on how to print the data, such as: what media (paper) to use and how many copies to print. The client specifies these processing instructions using the attribute definitions of the Java™ Print Service API.

The Java Print Service API includes two packages that define attributes: javax.print.attribute and javax.print.attribute.standard. The javax.print.attribute package contains the interfaces and classes that describe the types of attributes and how they are collected into sets. The javax.print.attribute.standard package enumerates all of the standard attributes in the API. Most of the attribute definitions in the JPS API are implementations of the standard and extensible attributes defined by the Internet Printing Protocol (IPP) Specification from the IETF.

This chapter describes the attribute definitions of the JPS API in more detail.The Attribute Categories and Values section explains what an attribute is according to the JPS. The Attribute Roles section describes the type of attributes. The Attribute Sets section describes how the attributes are collected into sets. The Standard Attributes section describes some of the more-commonly used attributes defined in the javax.attribute.standard package.

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 2 - Attributes

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

Attribute Categories and Values

Every printer has a set of capabilities, such as the ability to print on different paper sizes or the ability to print more than one copy. Each of the capabilities has a range of values. For example, a printer's orientation capability might have this range of values: [landscape, portrait]. For each print request, the capability is set to one of these possible values. The Java Print Service API uses the term attribute category to refer to a printer capability, such as orientation, and the term attribute value to refer to the value of the capability, such as landscape.

In the Java Print Service API, an attribute category is represented by a Java class implementing the Attribute interface, and attribute values are instances of such a class or one of its subclasses. For example, to print 5 copies of a job, an application constructs an instance of the Copies class with the value of 5 and uses the Copies instance to specify the print job. The Copies class represents the attribute category, and the Copies instance represents the attribute value. Because the attribute value is encapsulated as a Java object, the attribute value implies its attribute category, and so an attribute value is usually referred to simply as an attribute. The category and value constitute a key-value pair, which you can add to a set along with other attributes. See Attribute Sets for more information

The Attribute interface defines just two methods: getName and getCategory. The getName method returns a String name for the attribute category. The getCategory method returns the class that first implements that category. To ensure that all implementations of a particular category report the same name and class, subclasses should not override the getName or getCategory methods.

To determine what attribute categories and values are supported by a printer, use the query methods defined in the PrintService interface. A print request does not need to specify attribute values for all of the target printer's supported attribute categories: each supported attribute category has a default value. For example, a printer might support printing up to 999 copies of a job, but if a print request does not specify the number of copies, the printer almost always prints a default of just 1 copy.

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 2 - Attributes

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

Attribute Roles

When submitting a print job to a printer, the client provides the attributes describing the characteristics of the print data, such as the document name, and how the print data should be printed, such as double-sided, five copies. If a print job consists of multiple pieces of print data, different pieces might have different processing instructions, such as 8 x 11 inch media for the first document, and 11 x 17 inch media for another document.

Once the printer starts processing the print job, additional information about the job becomes available, which might include: the job state (such as completed or queued) and the number of pages printed so far. These pieces of information are also attributes. Attributes can also describe the printer itself, such as: the printer name, the printer location, and the number of jobs queued.

The Java Print Service API defines these different kinds of attribute roles with five subinterfaces of Attribute:

  • PrintRequestAttribute is used by an application to represents a setting applied to an entire print job and to specify how the entire print job should be printed.
  • DocAttribute is used by an application to specify a characteristic of a single document and the print job settings to be applied to the document.
  • PrintJobAttribute is used by a print service to report how a job is being printed. These values will usually be identical the requested attribute values. However, if the printer does not support the value of a print request attribute then the corresponding print job attribute contains a different value that is supported by the printer
  • PrintServiceAttribute is used by a print service to report the status of the print service.
  • SupportedValuesAttribute is used by a print service o indicate the range of values supported for a request attribute. For example, a printer might support only a certain range of copies. When a print service is queried for the supported range of copies, it returns this information in a CopiesSupported object, which implements SupportedValuesAttribute.
Many attributes can be members of more than one role. For example, the Media attribute belongs to the doc, print job, and print request roles because the Media attribute can describe the paper size, the paper tray, or paper type. In fact, most doc attributes are also request attributes, and all request attributes are also job attributes.

The next section describes how to collect attributes together into attribute sets, which also have roles.

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 2 - Attributes

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

Attribute Sets

A client usually needs to provide more than one processing instruction when submitting a print job. For example, the client might need to specify an A4 media and a landscape orientation. To send more than one processing instruction to the printer, the client collects the attributes representing the instructions into an attribute set, which the Java Print Service API represents with the AttributeSet interface.

The AttributeSet interface is similar to the java.util.Map interface: it provides a map of keys to values, in which each key is unique and can contain no more than one value. However, the AttributeSet interface is designed to specifically support the needs of the Java Print Service API. An AttributeSet requires that:

  • Each key in an AttributeSet corresponds to a category, and the value of the key can only be one of the attribute values that belong to the category represented by the key. Thus, unlike a Map, an AttributeSet restricts the possible values of a key: an attribute category cannot be set to an attribute value that does not belong to that category.
  • Only attributes implementing the Attribute interface can be added to the attribute set.
  • Only one attribute from a particular category can exist in an AttributeSet. For example, if an attribute set already contains a Media attribute, adding another Media attribute overwrites the first one.
Like a single attribute, an attribute set has a role. The roles are defined by the AttributeSet subinterfaces, which parallel the Attribute subinterfaces mentioned in the Attribute Roles section. The AttributeSet subinterfaces are: PrintRequestAttributeSet, PrintJobAttributeSet, DocAttributeSet, and PrintServiceAttributeSet. The role of the attribute set determines what kind of attributes it contains: a print request attribute set can contain only print request attributes.

The Java Print Service API includes HashAttributeSet as a concrete implementation of the AttributeSet interface, but developers can provide their own implementation. Rather than using HashAttributeSet directly, applications will more often use one of the subclasses of HashAttributeSet, which are: HashPrintRequestAttributeSet, HashPrintJobAttributeSet, HashDocumentAttributeSet, and HashPrintServiceAttributeSet. These subclasses implement the corresponding AttributeSet subinterfaces. For example PrintRequestAttributeSet extends AttributeSet, and HashPrintRequestAttributeSet is the concrete implementation of PrintRequestAttributeSet. An attribute set created with HashPrintRequestAttributeSet or any implementation of PrintRequestAttributeSet can contain only request attributes.

Unlike its subclasses, a HashAttributeSet can contain any kind of attribute. An application uses a HashAttributeSet directly when it needs a set to contain more than one kind of attribute. One example is the set returned by the getUnsupportedAttributes method of PrintService. The unsupported attributes returned might belong to more than one attribute role.

As with single attributes, applications will more often create request attribute sets because specifying print requests is the printing application's primary function. To create a request attribute set, use one of the constructors from the HashPrintRequestAttributeSet class:

PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
The next section describes some of the more commonly-used attributes that you can add to a set.
CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 2 - Attributes

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

How to Specify Attributes

Whether you are printing or streaming data, you specify attributes in the same way. You will usually use PrintRequestAttribute more often than the other kinds of attributes because print request attributes specify the settings for an entire print job. Bec ause you will most likely want to specify more than one attribute for a particular job, you need to create an attribute set. This sample demonstrates creating a PrintRequestAttributeSet that instructs the service to use A4 media to print five copies of th e job using both sides of the paper:

PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new Copies(5));
aset.add(MediaSize.ISO_A4);
aset.add(Sides.DUPLEX);
After creating an attribute set, you will pass it to the print job's print method, along with the DocFlavor. The Specifying Document Types discusses using DocFlavor. The Printing and Streaming Documents chapter discusses how to print. The next section explains some of the more commonly-used attributes in more detail.
CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 2 - Attributes

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

Standard Attributes

The javax.print.attribute.standard package enumerates all of the standard attributes in the Java Print Service API. Most of these standard attributes are taken from the attributes defined in the IETF Internet Printing Protocol (IPP) 1.1 specification. This means that each IPP-compliant attribute class(category) defined in package javax.print.attribute.standard corresponds to an IPP attribute category, and the name (as returned by getName) is the actual IPP name for the category. The class names also usually reflect the IPP name as closely as the coding conventions of the Java programming language permit. Furthermore the values defined for a category are the same as the IPP values. IPP compatibility of each attribute category is documented in the API specification.

This section describes the attributes that developers will probably use most frequently. The more commonly-used attributes, including the ones listed here, implement PrintRequestAttribute because printing applications will usually specify how an entire print job should be printed, which is the role of a PrintRequestAttribute.

OrientationRequested

The OrientationRequested attribute category allows you to specify the orientation of the imaging on the paper. The possible attribute values are: PORTRAIT, LANDSCAPE, REVERSE_PORTRAIT, and REVERSE_LANDSCAPE. OrientationRequested.PORTRAIT is usually the default value. This code snippet demonstrates adding an OrientationRequested attribute to a set:

aset.add(OrientationRequested.REVERSE_PORTRAIT);
The OrientationRequested object is a type-safe enumeration encapsulating String values, which correspond to the possible orientations. These values are the actual IPP keywords.

Some pre-formatted document types, such as "Postscript", might not be able to support this attribute category because pre-formatted document types embed printer language commands that are interpreted by the printer, and these commands take precedence over a client request.

Clients can discover the supported orientation values for a particular print service by calling:

PrintService.getSupportedAttributeValues(OrientationRequested.class, ...).
This method returns an array of type OrientationRequested enumerating the supported values.

Copies

The Copies attribute category allows you to specify the number of copies to print. The Copies class encapsulates an integer representing the number of copies requested. This code snippet demonstrates adding a Copies attribute, set to five copies, to an attribute set:

aset.add(Copies(5));
Clients can discover the range of copies that a print service supports by calling :

PrintService.getSupportedAttributeValues(Copies.class, ...)
This method returns a CopiesSupported object, which encapsulates a range of integer values representing the range of copies that the service can handle. Calling getSupportedAttributeValues with CopiesSupported instead of Copies always returns null because the CopiesSupported object does not implement the PrintRequestAttribute interface, and so a client cannot specify a CopiesSupported attribute in a print request.

This code sample demonstrates discovering if a print service supports printing 5 copies and adding a Copies attribute with a value of 5 copies to an attribute set:

CopiesSupported copSupp =
        (CopiesSupported) service.getSupportedAttributeValues(Copies.class, null,
                                                                                null);
if (copSupp != null && copSupp.contains(5)) {
        requestAttrSet.add(new Copies(5));
} else { ...
}

Media

Media is the IPP attribute that identifies the medium on which to print. The Media attribute is an important attribute to understand, butis relatively complex.

The Java Print Service API defines three subclasses of the abstract class Media to reflect the overloaded Media attribute in the IPP specification: MediaSizeName, MediaName and MediaTray. All the Media subclasses have the Media category, for which each subclass defines different standard attribute values. For example, a MediaTray object can specify a value of MANUAL for the Media attribute to indicate that the document must be printed on paper from the printer's manual tray. This code snippet demonstrates adding a Media attribute to a set:

aset.add(MediaTray.MANUAL);

The value of the Media attribute is always a String, but because the attribute is overloaded, its value determines the type of media to which the attribute refers. For example, the IPP pre-defined set of attribute values include the values "a4" and "top-tray". If Media is set to the value "a4" then the Media attribute refers to the size of paper, but if Media is set to "top-tray" then the Media attribute refers to the paper source. Because the String attribute value can refer to such diverse types of media, an application can extend the attribute set to include values such as "company-letterhead" or "yellow letter paper". Of course, to extend the Media attribute in this way, an application must discover a print service that is configured to print with this media.

In most cases, applications will use either MediaSizeName or MediaTray. The MediaSizeName class enumerates the media by size. The MediaTray class enumerates the paper trays on a printer, which usually include a main tray and a manual feed tray. The IPP 1.1 specification does not provide for specifying both the media size and the media tray at the same time, which means, for example, that an application cannot request size A4 paper from the manual tray. A future revision of the IPP specification might provide for a way to request more than one type of media at a time, in which case the JPS API will most likely be enhanced to implement this change.

The JPS API also includes two additional media-related Attribute classes that are not IPP attributes: MediaSize and MediaPrintableArea.

MediaSize

MediaSize is not a request attribute; it is an enumeration of paper dimensions and a mapping to MediaSizeName instances. Each MediaSizeName instance usually has a MediaSize object associated with it so that clients can obtain the dimensions of the paper that the MediaSizeName instance defines. To determine the dimensions of the MediaSizeName instance, call:

MediaSize size = MediaSizeName.getMediaSizeForName(paper);

MediaPrintableArea

MediaPrintableArea is used in a print request in conjunction with a compatible Media to specify the area of the paper on which to print. Printer hardware usually defines the printable area of a page, which is rarely the entire page. For this reason, an application needs to determine what printable area a printer defines for a particular size media to ensure that the print data can fit within this area.

For example, to determine the supported printable area for 5" x 7" paper, the application needs to choose a media size attribute value that corresponds to this size paper and then query the print service with the media size:

PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(MediaSizeName.NA_5X7);
MediaPrintableArea printableArea =
(MediaPrintableArea)service.
        getSupportedAttributeValues(MediaPrintableArea.class, null, aset);
The returned value indicates the largest printable area that can be supported by that printer for that paper size.

Destination

The Destination attribute allows you to redirect your print data to a file rather than sending it to a printer device. The "print-to-file" option is very common in user dialogs, but the spooled data is not always usable because it might be a device-specific raster that can only be interpreted by the device from which it was redirected. For this reason, the Java Print Service API requires that the client query the print service to determine if it can redirect the output to a file. The service might not support the category at all, or it might support only particular values. For example, since the JPS API can be used in an network environment, in which the formatting of print data does not occur on the host computer, specifying a local file for output might not be possible because the service formatting the data might not have access to the local filesystems of the client. The Destination attribute takes a URL as the value of the destination, which allows a network printer to use a protocol such as ftp to upload formatted print data. However, most printers that support this attribute will run as part of a local environment and can accept the "file:" protocol URL. This code snippet redirects the output to a file called out.prn on the c: drive:

aset.add(new Destination("file:c:\out.prn"));

SheetCollate

The SheetCollate attribute allows you to specify whether or not your print job is collated when you are printing more than one copy of a multi-page document. For example, the pages of a 3-page, 2-copy collated job will print as (1,2,3,1,2,3), but the pages of the same document submitted in a 2-copy uncollated job will be printed as (1,1,2,2,3,3). This attribute is not in version 1.1 of the IPP specification, but it is very useful and most printers support it. This code snippet demonstrates specifying a collated job:

aset.add(SheetCollate.COLLATED);

Sides

Some printers, particularly high-end printers, can print on both sides of the paper. The Sides attribute allows applications to specify two-sided printing instead of the usual default of single-sided printing. Two-sided printing is sometimes referred to as "duplex" or "tumble" printing. These two values are differentiated by the orientation of the output. The Java Print Service API refers to duplex as "two sided long edge" and tumble as "two sided short edge". Read the API specification for Sides for further explanation. This code snippet specifiesthat a job print the documents two-sided:

aset.add(Sides.DUPLEX);

Fidelity

The Fidelity attribute is an IPP boolean attribute that represents whether or not a print job should be rejected if the print service does not support any attribute specified in the print request. Fidelity is not an attribute many developers will need to consider, but it is an important attribute in the context of the JPS API. The default value is FIDELITY_FALSE, which indicates that a print job should not be rejected if the print service does not support an attribute specified in the print request. For example, if an application specifies an orientation of reverse landscape, but the printer does not support reverse landscape, the job is rejected if fidelity is true, but if fidelity is false then the printer might substitute a reasonable alternative, such as the landscape orientation. The Fidelity attribute allows applications to decide whether to only print the document exactly as specified or to print it even though the printer might not support all attributes. This code snippet specifies that a job should be rejected if the printer does not support the requested attributes:

aset.add(Fidelity.FIDELITY_TRUE);
For the cases in which fidelity is important, the Java Print Service API provides many tools for applications to query exactly what can be supported for a particular print request. See the various query methods on the PrintService interface.
CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 2 - Attributes

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

Uses of JPS Attributes

Unlike attributes of previous Java printing APIs, the Java Print Service attributes can be used in both the program and from the user dialog. Applications can specify as little as needed about how a job should be printed and can inspect the selections made by end users in user dialogs.

The JPS attributes are designed to be extensible. An AttributeSet can contain anything that properly implements the Attribute interfaces, which means that the set of standard attributes can evolve and still be compatible with future JDK versions, and implementors of services can extend attributes in two ways:

  • Using their own subclasses of a standard attribute category to support additional values of that category.
  • Creating new attribute categories.
Demonstrating attribute usage from the user dialog requires providing a user interface, which is beyond the scope of this user guide. Likewise, extending JPS attributes is a task for service providers, and is not included as an example in this version of the user guide. However, the Printing a Document chapter explains a simple printing application, which covers the basics of using the JPS attributes as described in this chapter.
CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.net.httpserver.Authenticator (Java HTTP Server b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.net.httpserver.Authenticator

  • Packages that use Authenticator
    Package Description
    com.sun.net.httpserver
    Provides a simple high-level Http server API, which can be used to build embedded HTTP servers.

    • Uses of Authenticator in com.sun.net.httpserver

      Subclasses of Authenticator in com.sun.net.httpserver
      Modifier and Type Class and Description
      class  BasicAuthenticator
      BasicAuthenticator provides an implementation of HTTP Basic authentication.
      Methods in com.sun.net.httpserver that return Authenticator
      Modifier and Type Method and Description
      abstract Authenticator HttpContext.getAuthenticator()
      Returns the currently set Authenticator for this context if one exists.
      abstract Authenticator HttpContext.setAuthenticator(Authenticator auth)
      Sets the Authenticator for this HttpContext.
      Methods in com.sun.net.httpserver with parameters of type Authenticator
      Modifier and Type Method and Description
      abstract Authenticator HttpContext.setAuthenticator(Authenticator auth)
      Sets the Authenticator for this HttpContext.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.net.httpserver.Authenticator.Failure (Java HTTP Server b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.net.httpserver.Authenticator.Failure

No usage of com.sun.net.httpserver.Authenticator.Failure
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.net.httpserver.Authenticator.Result (Java HTTP Server b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.net.httpserver.Authenticator.Result

  • Packages that use Authenticator.Result
    Package Description
    com.sun.net.httpserver
    Provides a simple high-level Http server API, which can be used to build embedded HTTP servers.

    • Uses of Authenticator.Result in com.sun.net.httpserver

      Subclasses of Authenticator.Result in com.sun.net.httpserver
      Modifier and Type Class and Description
      static class  Authenticator.Failure
      Indicates an authentication failure.
      static class  Authenticator.Retry
      Indicates an authentication must be retried.
      static class  Authenticator.Success
      Indicates an authentication has succeeded and the authenticated user principal can be acquired by calling getPrincipal().
      Methods in com.sun.net.httpserver that return Authenticator.Result
      Modifier and Type | Method and Description
      Authenticator.Result | BasicAuthenticator.authenticate(HttpExchange t)
      abstract Authenticator.Result Authenticator.authenticate(HttpExchange exch)
      called to authenticate each incoming request.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.net.httpserver.Authenticator.Retry (Java HTTP Server b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.net.httpserver.Authenticator.Retry

No usage of com.sun.net.httpserver.Authenticator.Retry
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.net.httpserver.Authenticator.Success (Java HTTP Server b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.net.httpserver.Authenticator.Success

No usage of com.sun.net.httpserver.Authenticator.Success
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.jgss.AuthorizationDataEntry (Java GSS-API Utilities b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java GSS-API Utilities
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.jgss.AuthorizationDataEntry

No usage of com.sun.security.jgss.AuthorizationDataEntry
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java GSS-API Utilities
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2000, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Autoboxing

As any Java programmer knows, you can't put an int (or other primitive value) into a collection. Collections can only hold object references, so you have to box primitive values into the appropriate wrapper class (which is Integer in the case of int). When you take the object out of the collection, you get the Integer that you put in; if you need an int, you must unbox the Integer using the intValue method. All of this boxing and unboxing is a pain, and clutters up your code. The autoboxing and unboxing feature automates the process, eliminating the pain and the clutter.

The following example illustrates autoboxing and unboxing, along with generics and the for-each loop. In a mere ten lines of code, it computes and prints an alphabetized frequency table of the words appearing on the command line.

import java.util.*;

// Prints a frequency table of the words on the command line
public class Frequency {
   public static void main(String[] args) {
      Map<String, Integer> m = new TreeMap<String, Integer>();
      for (String word : args) {
          Integer freq = m.get(word);
          m.put(word, (freq == null ? 1 : freq + 1));
      }
      System.out.println(m);
   }
}

java Frequency if it is to be it is up to me to do the watusi
{be=1, do=1, if=1, is=2, it=2, me=1, the=1, to=3, up=1, watusi=1}

The program first declares a map from String to Integer, associating the number of times a word occurs on the command line with the word. Then it iterates over each word on the command line. For each word, it looks up the word in the map. Then it puts a revised entry for the word into the map. The line that does this (highlighted in green) contains both autoboxing and unboxing. To compute the new value to associate with the word, first it looks at the current value (freq). If it is null, this is the first occurrence of the word, so it puts 1 into the map. Otherwise, it adds 1 to the number of prior occurrences and puts that value into the map. But of course you cannot put an int into a map, nor can you add one to an Integer. What is really happening is this: In order to add 1 to freq, it is automatically unboxed, resulting in an expression of type int. Since both of the alternative expressions in the conditional expression are of type int, so too is the conditional expression itself. In order to put this int value into the map, it is automatically boxed into an Integer.

The result of all this magic is that you can largely ignore the distinction between int and Integer, with a few caveats. An Integer expression can have a null value. If your program tries to autounbox null, it will throw a NullPointerException. The == operator performs reference identity comparisons on Integer expressions and value equality comparisons on int expressions. Finally, there are performance costs associated with boxing and unboxing, even if it is done automatically.

Here is another sample program featuring autoboxing and unboxing. It is a static factory that takes an int array and returns a List of Integer backed by the array. In a mere ten lines of code this method provides the full richness of the List interface atop an int array. All changes to the list write through to the array and vice-versa. The lines that use autoboxing or unboxing are highlighted in green:

// List adapter for primitive int array
public static List<Integer> asList(final int[] a) {
    return new AbstractList<Integer>() {
        public Integer get(int i) { return a[i]; }
        // Throws NullPointerException if val == null
        public Integer set(int i, Integer val) {
            Integer oldVal = a[i];
            a[i] = val;
            return oldVal;
        }
        public int size() { return a.length; }
    };
}

The performance of the resulting list is likely to be poor, as it boxes or unboxes on every get or set operation. It is plenty fast enough for occasional use, but it would be folly to use it in a performance critical inner loop.

So when should you use autoboxing and unboxing? Use them only when there is an "impedance mismatch" between reference types and primitives, for example, when you have to put numerical values into a collection. It is not appropriate to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code. An Integer is not a substitute for an int; autoboxing and unboxing blur the distinction between primitive types and reference types, but they do not eliminate it.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Autodownload Files

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Auto Download of the Java Platform

The Windows releases of Java Plug-in and Java Web Start make use of the codebase attribute of the OBJECT element to autodownload and install a particular version of the JRE. See:

  • Auto download with Java Plug-in
  • Auto download with Java Web Start

By specifying a particular .cab file in the codebase, a particular version of the JRE can be automatically downloaded and installed as required by an applet or application. For a list of the available .cab files, see Autodownload Files. Note that not every release of the JRE has an associated .cab file for autodownload.

For additional information read the technical article on Auto Install.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


AWT Native Interface

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

The AWT Native Interface

The Key to Rendering to an AWT Canvas from Native Code

The new Java™ SE AWT Native Interface enables rendering libraries compiled to native code to draw directly to a Java Canvas drawing surface. This means that such libraries can be used without being converted to Java first and without significant impact on performance. An example illustrating how easy it is to use the AWT Native Interface is presented and discussed in this technical note.

Introduction

The definition of Java Standard Edition includes JNI, the Java Native Interface. Most Java developers will never need to use it, but the interface is invaluable in certain situations because it provides the only way for Java byte code to interact directly with application code that has been compiled to the native machine instructions for the host microprocessor. JNI is most often used as an ``escape valve'' to enable access to platform functionality not yet supported by the Java programming language. For example, you could use JNI to integrate with native code that communicates with a peripheral device, such as a scanner, connected to a system via a USB port.

Of course, JNI is general enough to be used to access almost any sort of native library, regardless of whether the task to be accomplished could also be done using pure Java. The major penalty for using it is that code portability suffers, but this may be acceptable or even necessary for business or technical reasons.

Business reasons? Consider the situation where the legacy software you are trying to port to Java uses a third-party library for a critical set of operations. If you do not have source rights to this library and you cannot convince the owner to provide a Java version, you may not be able to use it. Even if you do have the source, the effort needed to port a standard library to Java and test it may be too expensive to consider.

Another important reason for leaving the native code alone is related to performance. If you are dealing with a finely crafted piece of code, carefully tuned for performance over the course of years, you probably do not want to convert it to Java and risk a performance penalty. It is usually best to keep it intact until you are satisfied that the benefits of Java portability and code maintainability outweigh the expected performance difference.

A rendering library is a good example of a piece of native code that most developers would just as soon leave alone for performance reasons. Unfortunately, this is the very type of library that has been most difficult to integrate with Java code through JNI. The fundamental problem has been that the rendering code cannot identify where to draw. It needs access to information about a Java drawing surface (such as a handle to the underlying peer of a Canvas), but cannot get it.

Until now, the Java platform has kept access to this information private — "private" in the sense of undocumented, unsupported, and deprecated. The good news is that this situation will be remedied with the introduction of the "AWT Native Interface" in the Java upgrade release ("Kestrel"). For the first time there will be an official way to obtain all the information you need to know about the peer of a Java Canvas so that you can draw directly to the Canvas from a native code library using the drawing routines provided by the operating system.

How It Works

In this section we'll describe the most common usage of the AWT Native Interface — overriding the paint method to direct drawing operations to a native rendering library which then queries the Java VM to determine the information it needs in order to render. Note, however, that any native code may use the AWT Native Interface to learn about a target drawing surface, not just code in a paint method.

The first step in hooking up a native rendering library to a Java Canvas is to define a new class that extends Canvas and overrides the paint method. The Java system routes all drawing operations for a Canvas object through the paint method, as it does for all other GUI objects.

The new paint method, to be implemented in the native rendering library, must be declared as public native void , and the native library itself is loaded at runtime by including a call to System.loadLibrary( "myRenderingLib")in the static block of the class. The myRenderingLib name is used for the native shared library; for the Solaris operating environment, the actual name for the library file on disk is libmyRenderingLib.so .

Here is a simple example of such a class:

import java.awt.*;
import java.awt.event.*;

public class MyCanvas extends Canvas {
    static {
        System.loadLibrary("myRenderingLib");
    }
    public native void paint(Graphics g);

    public static void main(String[] args) {
        Frame f = new Frame();
        f.setBounds(0, 0, 500, 110);
        f.add( new MyCanvas() );
        f.addWindowListener( new WindowAdapter() {
            public void windowClosing(WindowEvent ev) {
                System.exit(0);
            }
        } );
        f.show();
    }
}

Note that this class has a main method that can be used torun this code as an application for testing purposes.

The next step is to run the javah tool on the MyCanvas class file above to generate a C/C++ header file that describes the interface to the native paint method that Java expects to be used. javah is a standard tool included with the Java SDK.

The final step the most interesting one is to write the native rendering method, with an interface that conforms to the header file that javah generated, and build it as a standard shared library (called myRenderingLib in the above example) by linking it, for the Solaris operating environment, against the jre/lib/sparc/libjawt.so library. (For Microsoft Windows, link against the jre/bin/jawt.dll library.) This code will call back to the Java virtual machine to get the drawing surface information it needs to access the MyCanvas peer. Once this information is available, the code can draw directly to MyCanvas using standard drawing routines supplied by the underlying operating system.

Here is sample source code for a native paint method designed for use in a Solaris X11-based drawing environment and a Java VM where the AWT Native Interface is present:

/*
 * Copyright (c) 1999 Oracle and/or its affiliates.  All rights reserved.
 *
 */

#include "MyCanvas.h"
#include "jawt_md.h"

/*
 * Class:     MyCanvas
 * Method:    paint
 * Signature: (Ljava/awt/Graphics;)V
 */
JNIEXPORT void JNICALL Java_MyCanvas_paint
(JNIEnv* env, jobject canvas, jobject graphics)
{
    JAWT awt;
    JAWT_DrawingSurface* ds;
    JAWT_DrawingSurfaceInfo* dsi;
    JAWT_X11DrawingSurfaceInfo* dsi_x11;
    jboolean result;
    jint lock;
    GC gc;

    short       i;
    char        *testString = "^^^ rendered from native code ^^^";

    /* Get the AWT */
    awt.version = JAWT_VERSION_1_3;
    if (JAWT_GetAWT(env, &awt) == JNI_FALSE) {
        printf("AWT Not found\n");
        return;
    }

    /* Get the drawing surface */
    ds = awt.GetDrawingSurface(env, canvas);
    if (ds == NULL) {
        printf("NULL drawing surface\n");
        return;
    }

    /* Lock the drawing surface */
    lock = ds->Lock(ds);
    if((lock & JAWT_LOCK_ERROR) != 0) {
        printf("Error locking surface\n");
        awt.FreeDrawingSurface(ds);
        return;
    }

    /* Get the drawing surface info */
    dsi = ds->GetDrawingSurfaceInfo(ds);
    if (dsi == NULL) {
        printf("Error getting surface info\n");
        ds->Unlock(ds);
        awt.FreeDrawingSurface(ds);
        return;
    }

    /* Get the platform-specific drawing info */
    dsi_x11 = (JAWT_X11DrawingSurfaceInfo*)dsi->platformInfo;

    /* Now paint */
    gc = XCreateGC(dsi_x11->display, dsi_x11->drawable, 0, 0);
    XSetBackground(dsi_x11->display, gc, 0);
    for (i=0; i<36;i++)
    {
        XSetForeground(dsi_x11->display, gc, 10*i);
        XFillRectangle(dsi_x11->display, dsi_x11->drawable, gc,
                        10*i, 5, 90, 90);
    }
    XSetForeground(dsi_x11->display, gc, 155);
    XDrawImageString(dsi_x11->display, dsi_x11->drawable, gc,
                        100, 110, testString, strlen(testString));
    XFreeGC(dsi_x11->display, gc);

    /* Free the drawing surface info */
    ds->FreeDrawingSurfaceInfo(dsi);

    /* Unlock the drawing surface */
    ds->Unlock(ds);

    /* Free the drawing surface */
    awt.FreeDrawingSurface(ds);
}

The key data structure here is JAWT , which is defined in jawt.h (included by jawt_md.h) ; it provides access to all the information the native code needs to get the job done. The first part of the native method is boilerplate: it populates the JAWT structure, gets a JAWT_DrawingSurface structure, locks the surface (only one drawing engine at a time, please!), then gets a JAWT_DrawingSurfaceInfo structure that contains a pointer (in the platformInfo field) to the necessary platform-specific drawing information. It also includes the bounding rectangle of the drawing surface and the current clipping region.

The structure of the information pointed to by platformInfo is defined in a machine-dependent header file called jawt_md.h. For Solaris/X11 drawing, it includes information about the X11 display and X11 drawable associated with MyCanvas. After the drawing operations are completed, there is more boilerplate code as JAWT_DrawingSurfaceInfo is freed and JAWT_DrawingSurface is unlocked and freed.

The corresponding code for the Microsoft Windows platform would be structured similarly, but would include the version of jawt_md.h for Microsoft Windows and the structure located in the platformInfo field of drawing surface info would be cast as a JAWT_Win32DrawingSurfaceInfo* . And, of course, the actual drawing operations would need to be changed to those appropriate for the Microsoft Windows platform.

Summary

The ability to draw directly into a Java Canvas from a native code library is extremely useful for developers planning to migrate a legacy software system to Java, especially one that includes a high-performance rendering engine. It makes it much easier to migrate in stages, leaving performance-sensitive rendering code alone, while other less-sensitive portions of code are converted to Java. The result can be a modern Java-centric application, providing the benefit of portability and development efficiency, but one that does not sacrifice an investment in performance of a key piece of native code.

References

The definitive reference to the Java Native Interface is The Java Native Interface: Programmer's Guide and Specification by Sheng Liang of Sun Microsystems. This book was published in June 1999 by Addison-Wesley. The ISBN is 0-201-32577-2.

Appendix

Header Files for jawt.h and jawt_md.h

jawt.h

/*
 * @(#)jawt.h   1.2 99/05/27
 *
 * Copyright (c) 1999 Oracle and/or its affiliates.  All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Sun Microsystems, Inc. ("Confidential Information").  You
 * shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement
 * you entered into with Sun.
 */

#ifndef _JAVASOFT_JAWT_H_
#define _JAVASOFT_JAWT_H_

#include "jni.h"

#ifdef __cplusplus
extern "C" {
#endif

/*
 * AWT native interface (new in JDK 1.3)
 *
 * The AWT native interface allows a native C or C++ application a means
 * by which to access native structures in AWT.  This is to facilitate moving
 * legacy C and C++ applications to Java and to target the needs of the
 * community who, at present, wish to do their own native rendering to canvases
 * for performance reasons.  Standard extensions such as Java3D also require a
 * means to access the underlying native data structures of AWT.
 *
 * There may be future extensions to this API depending on demand.
 *
 * A VM does not have to implement this API in order to pass the JCK.
 * It is recommended, however, that this API is implemented on VMs that support
 * standard extensions, such as Java3D.
 *
 * Since this is a native API, any program which uses it cannot be considered
 * 100% pure java.
 */

/*
 * AWT Native Drawing Surface (JAWT_DrawingSurface).
 *
 * For each platform, there is a native drawing surface structure.  This
 * platform-specific structure can be found in jawt_md.h.  It is recommended
 * that additional platforms follow the same model.  It is also recommended
 * that VMs on Microsoft Windows platforms and Solaris operating environment
 * support the existing structures in jawt_md.h.
 *
 *******************
 * EXAMPLE OF USAGE:
 *******************
 *
 * In Miscrosoft Windows, a programmer wishes to access the HWND of a canvas
 * to perform native rendering into it.  The programmer has declared the
 * paint() method for their canvas subclass to be native:
 *
 *
 * MyCanvas.java:
 *
 * import java.awt.*;
 *
 * public class MyCanvas extends Canvas {
 *
 *     static {
 *         System.loadLibrary("mylib");
 *     }
 *
 *     public native void paint(Graphics g);
 * }
 *
 *
 * myfile.c:
 *
 * #include "jawt_md.h"
 * #include <assert.h>
 *
 * JNIEXPORT void JNICALL
 * Java_MyCanvas_paint(JNIEnv* env, jobject canvas, jobject graphics)
 * {
 *     JAWT awt;
 *     JAWT_DrawingSurface* ds;
 *     JAWT_DrawingSurfaceInfo* dsi;
 *     JAWT_Win32DrawingSurfaceInfo* dsi_win;
 *     jboolean result;
 *     jint lock;
 *
 *     // Get the AWT
 *     awt.version = JAWT_VERSION_1_3;
 *     result = JAWT_GetAWT(env, &awt);
 *     assert(result != JNI_FALSE);
 *
 *     // Get the drawing surface
 *     ds = awt.GetDrawingSurface(env, canvas);
 *     assert(ds != NULL);
 *
 *     // Lock the drawing surface
 *     lock = ds->Lock(ds);
 *     assert((lock & JAWT_LOCK_ERROR) == 0);
 *
 *     // Get the drawing surface info
 *     dsi = ds->GetDrawingSurfaceInfo(ds);
 *
 *     // Get the platform-specific drawing info
 *     dsi_win = (JAWT_Win32DrawingSurfaceInfo*)dsi->platformInfo;
 *
 *     //////////////////////////////
 *     // !!! DO PAINTING HERE !!! //
 *     //////////////////////////////
 *
 *     // Free the drawing surface info
 *     ds->FreeDrawingSurfaceInfo(dsi);
 *
 *     // Unlock the drawing surface
 *     ds->Unlock(ds);
 *
 *     // Free the drawing surface
 *     awt.FreeDrawingSurface(ds);
 * }
 *
 */

/*
 * JAWT_Rectangle
 * Structure for a native rectangle.
 */
typedef struct jawt_Rectangle {
    jint x;
    jint y;
    jint width;
    jint height;
} JAWT_Rectangle;

struct jawt_DrawingSurface;

/*
 * JAWT_DrawingSurfaceInfo
 * Structure for containing the underlying drawing information of a component.
 */
typedef struct jawt_DrawingSurfaceInfo {
    /*
     * Pointer to the platform-specific information.  This can be safely
     * cast to a JAWT_Win32DrawingSurfaceInfo on Microsoft Windows or a
     * JAWT_X11DrawingSurfaceInfo on Solaris operating environment.
     * See jawt_md.h for details.
     */
    void* platformInfo;
    /* Cached pointer to the underlying drawing surface */
    struct jawt_DrawingSurface* ds;
    /* Bounding rectangle of the drawing surface */
    JAWT_Rectangle bounds;
    /* Number of rectangles in the clip */
    jint clipSize;
    /* Clip rectangle array */
    JAWT_Rectangle* clip;
} JAWT_DrawingSurfaceInfo;

#define JAWT_LOCK_ERROR                 0x00000001
#define JAWT_LOCK_CLIP_CHANGED          0x00000002
#define JAWT_LOCK_BOUNDS_CHANGED        0x00000004
#define JAWT_LOCK_SURFACE_CHANGED       0x00000008

/*
 * JAWT_DrawingSurface
 * Structure for containing the underlying drawing information of a component.
 * All operations on a JAWT_DrawingSurface MUST be performed from the same
 * thread as the call to GetDrawingSurface.
 */
typedef struct jawt_DrawingSurface {
    /* Cached reference to the Java environment of the calling thread */
    JNIEnv* env;
    /* Cached reference to the target object */
    jobject target;
    /*
     * Lock the surface of the target component for native rendering.
     * When finished drawing, the surface must be unlocked with
     * Unlock().  This function returns a bitmask with one or more of the
     * following values:
     *
     * JAWT_LOCK_ERROR - When an error has occurred and the surface could not
     * be locked.
     *
     * JAWT_LOCK_CLIP_CHANGED - When the clip region has changed.
     *
     * JAWT_LOCK_BOUNDS_CHANGED - When the bounds of the surface have changed.
     *
     * JAWT_LOCK_SURFACE_CHANGED - When the surface itself has changed
     */
    jint (JNICALL *Lock)
        (struct jawt_DrawingSurface* ds);
    /*
     * Get the drawing surface info.
     * The value returned may be cached, but the values may change if
     * additional calls to Lock() or Unlock() are made.
     * Lock() must be called before this can return a valid value.
     * Returns NULL if an error has occurred.
     * When finished with the returned value, FreeDrawingSurfaceInfo must be
     * called.
     */
    JAWT_DrawingSurfaceInfo* (JNICALL *GetDrawingSurfaceInfo)
        (struct jawt_DrawingSurface* ds);
    /*
     * Free the drawing surface info.
     */
    void (JNICALL *FreeDrawingSurfaceInfo)
        (JAWT_DrawingSurfaceInfo* dsi);
    /*
     * Unlock the drawing surface of the target component for native rendering.
     */
    void (JNICALL *Unlock)
        (struct jawt_DrawingSurface* ds);
} JAWT_DrawingSurface;

/*
 * JAWT
 * Structure for containing native AWT functions.
 */
typedef struct jawt {
    /*
     * Version of this structure.  This must always be set before
     * calling JAWT_GetAWT()
     */
    jint version;
    /*
     * Return a drawing surface from a target jobject.  This value
     * may be cached.
     * Returns NULL if an error has occurred.
     * Target must be a java.awt.Canvas.
     * FreeDrawingSurface() must be called when finished with the
     * returned JAWT_DrawingSurface.
     */
    JAWT_DrawingSurface* (JNICALL *GetDrawingSurface)
        (JNIEnv* env, jobject target);
    /*
     * Free the drawing surface allocated in GetDrawingSurface.
     */
    void (JNICALL *FreeDrawingSurface)
        (JAWT_DrawingSurface* ds);
} JAWT;

/*
 * Get the AWT native structure.  This function returns JNI_FALSE if
 * an error occurs.
 */
_JNI_IMPORT_OR_EXPORT_
jboolean JNICALL JAWT_GetAWT(JNIEnv* env, JAWT* awt);

#define JAWT_VERSION_1_3 0x00010003

#ifdef __cplusplus
} /* extern "C" */
#endif

#endif /* !_JAVASOFT_JAWT_H_ */

jawt_md.h (Solaris/X11 operating environment version)

/*
 * @(#)jawt_md.h        1.2 99/05/27
 *
 * Copyright (c) 1999 Oracle and/or its affiliates.  All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Sun Microsystems, Inc. ("Confidential Information").  You
 * shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement
 * you entered into with Sun.
 */

#ifndef _JAVASOFT_JAWT_MD_H_
#define _JAVASOFT_JAWT_MD_H_

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Intrinsic.h>
#include "jawt.h"

#ifdef __cplusplus
extern "C" {
#endif

/*
 * X11-specific declarations for AWT native interface.
 * See notes in jawt.h for an example of use.
 */
typedef struct jawt_X11DrawingSurfaceInfo {
    Drawable drawable;
    Display* display;
    VisualID visualID;
    Colormap colormapID;
    int depth;
} JAWT_X11DrawingSurfaceInfo;

#ifdef __cplusplus
}
#endif

#endif /* !_JAVASOFT_JAWT_MD_H_ */

jawt_md.h (Microsoft Windows version)

/*
 * @(#)jawt_md.h        1.2 99/05/27
 *
 * Copyright (c) 1999 Oracle and/or its affiliates.  All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Sun Microsystems, Inc. ("Confidential Information").  You
 * shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement
 * you entered into with Sun.
 */

#ifndef _JAVASOFT_JAWT_MD_H_
#define _JAVASOFT_JAWT_MD_H_

#include <windows.h>
#include "jawt.h"

#ifdef __cplusplus
extern "C" {
#endif

/*
 * Microsoft Windows specific declarations for AWT native interface.
 * See notes in jawt.h for an example of use.
 */
typedef struct jawt_Win32DrawingSurfaceInfo {
    /* Native window, DDB, or DIB handle */
    union {
        HWND hwnd;
        HBITMAP hbitmap;
        void* pbits;
    };
    /*
     * This HDC should always be used instead of the HDC returned from
     * BeginPaint() or any calls to GetDC().
     */
    HDC hdc;
    HPALETTE hpalette;
} JAWT_Win32DrawingSurfaceInfo;

#ifdef __cplusplus
}
#endif

#endif /* !_JAVASOFT_JAWT_MD_H_ */
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


AWT Enhancements

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

AWT Enhancements in the Java™ 2 SDK, v1.4

1.4.2 Bug Fixes
1.4.1 Bug Fixes
New Focus Subsystem
Deprecated Focus Methods
ActionEvents (and Other Events) Need Timestamps
Headless Support
Window Centering API Required for Multiscreen Support
The New Fullscreen Exclusive Mode API
Sync Out of Range Error From Video Driver Under Windows NT Undecorated Frames
Mouse Wheel Support
Programmatic Zooming of Frames
Dynamic Layout During Resize
Access to Component Listener Lists
Changes to Drag and Drop
64-Bit Compliance on Solaris
Inconsistent DLLs Warning
Removal of the DrawingSurface API
New InputEvent Key Modifiers
Change in Drop Down Behavior for Choice Menus
Choice Component Now Obeys Layout Manager Constraints

1.4.2 Bug Fixes

4648702: On Microsoft Windows 2000 and Windows XP, a TextArea will sometimes display only a vertical scrollbar, even though the SCROLLBARS_BOTH field is set to true.

4636311: Modal dialogs may hang when run from a Runnable on release 1.3.1 and 1.4.

4385243: Unable to input text in Microsoft Windows locales that don't have an ANSI code page (such as Hindi).

1.4.1 Bug Fixes

4690831: Game applets fail to repaint properly with Internet Explorer.

4627627: Focus traversal keys moved from awt.properties to Preferences API.

4636548/ 4639735: Crash of release 1.4 when screensaver on Microsoft Windows 2000 is activated.

4379138: Problems on Linux with key events for some dead keys.

4627542: Swing applications don't support international keyboards under Linux.

4395157: Under Linux on 1.3, can't type "%" in applets.

4669873: A drag and drop bug, reported on hopper-beta under Microsoft Windows, caused an application to briefly freeze during DnD and is fixed in the final release of 1.4.1.

New Focus Subsystem

The bugtraq report that corresponds to this change is: 4290675.

A new focus subsystem replaces the previous focus architecture and addresses many focus-related bugs caused by platform inconsistencies, and incompatibilities between AWT and Swing components. See the new Focus Model Specification for further details.

See the javadoc here.

Headless Support

The bugtraq report that corresponds to this change is: 4281163.

Many environments, such as mainframe machines and dedicated servers, do not support a display, keyboard, or mouse. Headless support is enabled by the new GraphicsEnvironment methods isHeadless and isHeadlessInstance. These methods indicate whether a display, keyboard, and mouse can be supported in a graphics environment.

The API changes for headless include:

  • A new public exception class, java.awt.HeadlessException, is introduced. It is derived from UnsupportedOperationException, which derives from RuntimeException, so that existing implementations of methods that throw the new exception will not require signature changes.
  • Two new methods, are added to java.awt.GraphicsEnvironment.
        public static boolean isHeadless()

    public boolean isHeadlessInstance()
  • The constructors of Applet and all heavyweight components (*) are changed to throw HeadlessException if a display, keyboard, and mouse are not supported by the toolkit implementation. All javadoc tags on all constructors are changed to reflect this RuntimeException.
  • The Robot constructor throws an AWTException if a display, keyboard, and mouse are not supported by the toolkit implementation.
  • Many of the methods in Toolkit and GraphicsEnvironment, with the exception of fonts, imaging, and printing, are changed to throw HeadlessException if a display, keyboard, and mouse are not supported. All the javadoc tags on these methods are changed to reflect this RuntimeException.
  • Other methods that may be affected by lack of display, keyboard, or mouse support, are changed to throw HeadlessException.
  • It should be worth noting that the HeadlessException is thrown if and only if isHeadless returns true, and that all javadoc comments should specify this.

(*)Applet, Button, Checkbox, Choice, FileDialog, Label, List, Menu, MenuBar, MenuComponent, MenuItem, PopupMenu, Scrollbar, ScrollPane, TextArea, TextComponent, Frame, Window, Dialog, JApplet, JFrame, JWindow, JDialog, and TextField. Canvas and Panel do not need to throw this exception since these can be given empty peers and treated as lightweights.

To run our environment with a headless implementation, the follow property may be specified at the java command line:

  -Djava.awt.headless=true
If this property is not specified and a display, keyboard, and mouse are not supported, then headless implementation is used by default.

Source code should check for headless, so that the exception may be caught gracefully. For example, see the following pre-headless implementation of the class Foo:

class Foo {
  static Choice c = new Choice();  // could throw HeadlessException
}
The new and improved implementation of Foo should be placed in a static block:
class Foo {
  static Choice c;
  static {
    try {
      c = new Choice();
    catch (HeadlessException e) {
        ...
    }
  }
}

The New Fullscreen Exclusive Mode API

The bugtraq report that corresponds to this change is: 4189326.

The new full-screen exclusive mode API supports high performance graphics by suspending the windowing system so that drawing can be done directly to the screen. Full screen mode, which is entirely different from simply taking an AWT Frame, Window, or Dialog and expanding it to fit the screen, is a graphics mode whereby the application takes entire control over the contents of video memory. The application tells the graphics card what to draw, how to draw it, and when to draw it. This mode is not always available. On some operating systems, it may not be implemented at all. On other operating systems, it may only be available if the capability is supported by the graphics card. Nevertheless, this mode is critical for performance and is necessary for enabling hardware page-flipping on Windows.

For a tutorial explaining how to use the full screen exclusive API mode with several code examples, see here.

API Changes:

  • A new public final class, java.awt.DisplayMode, is introduced.
  • Changes to java.awt.GraphicsDevice:
        public void setFullScreenWindow(Window w)

    public Window getFullScreenWindow()

    public boolean isDisplayChangeSupported()

    public void setDisplayMode(DisplayMode dm)

    public DisplayMode getDisplayMode()

    public DisplayMode[] getDisplayModes()
  • The algorithm which handles direct video buffer control has been localized to a new class, java.awt.image.BufferStrategy.
  • A new class java.awt.BufferCapabilities can be used when creating a buffer strategy. Likewise, a new class java.awt.ImageCapabilities is available to define the image capabilities of a specific configuration.
  • An application programmer can create and use a buffer strategy from a Canvas or a Window. There are two buffer strategies that are supported as protected inner classes: java.awt.Component.FlipBufferStrategy and java.awt.Component.BltBufferStrategy. One of these two inner classes is used on the Canvas or Window when the createBufferStrategy method is called, depending on the BufferCapabilities object supplied when creating the strategy (if any). To get the buffer strategy used by a particular component, the getBufferStrategy method is used.
Sync Out of Range Error From Video Driver Under Windows NT

The bugtraq report that corresponds to this change is: 4452207.

If you have a Dell Optiplex GX110 using an Intel 810 Graphics Controller, under Windows NT, you may get a "sync out of range" message from the video driver if you change the display mode more than once and use a high display resolution. There is evidently a bug in the (DirectX) video driver that is causing this. There are several workarounds to this problem:

  • Disable DirectDraw by using -Dsun.java2d.noddraw=true at the command line.
  • Do not change the display resolution more than once during the lifetime of a program that is intended to run on this hardware.
  • Disallow the following display modes on this hardware:
        1152 X 864     8       85
    1152 X 864     16      85
    1152 X 864     24      85

    1280 X 1024    8       70,72,75,85
    1280 X 1024    16      70,72,75,85
    1280 X 1024    24      70,75,85

    Bad Color (Unsatisfactory appearance in terms of color)

    1024 X 768     8       60,70,72,75,85

Undecorated Frames

The bugtraq report that corresponds to this change is: 4038769.

For certain applications having no native frame decorations makes sense. For example, applications that will run across many platforms and that require that the look and feel is the same, or when the programmer does not want the end-user coming in contact with the native operating system.

This release allows a Java application to turn off the creation of frame decorations; no native titlebar, system menu, border, or other native operating system dependent screen components appear when this mode is enabled. AWT and Swing components work transparently.

Changes to java.awt.Frame:

    public void setUndecorated(boolean undecorated)

    public boolean isUndecorated()

Changes to java.awt.Dialog:

    public void setUndecorated(boolean undecorated)

    public boolean isUndecorated()

Mouse Wheel Support

The bugtraq report that corresponds to this change is: 4289845.

The mouse wheel, with a scroll wheel in place of the middle mouse button, is enabled with new built-in Java support for scrolling via the mouse wheel. The java.awt.event.MouseWheelEvent class enables seamless support for mouse wheel scrolling in Java applications with no recompiling required. Also, a new java.awt.event.MouseWheelListener interface allows customization of mouse wheel behavior.

Note, for those using the mouse wheel on Linux, see here.

  • Scrolling Behavior:
    • A scrollbar is considered "scrollable" if it is both showing and there is more content in the scrolling Component than can be displayed at once, such that the scroll thumb does not occupy the entire scroll track.
    • It is possible for a scrollbar to be showing, but not be scrollable. Usually this occurs when a scrollbar is set to always be displayed.
    • The scrollbar to be scrolled by the mouse wheel is determined as follows:
      • If only one scrollbar is scrollable, it will be scrolled.
      • If both a horizontal and a vertical scrollbar are scrollable, the vertical scrollbar will be scrolled.
    • Wheel scrolling may be disabled altogether using setWheelScrollEnabled(false).
    • Up/away-from-user rotations cause vertical scroll bars to scroll upwards, and horizontal scrollbars to scroll to the left. Just the opposite is true for down/towards rotations.
    • No scrolling takes place if a scroll thumb is at the end of the scroll track.
  • Heavyweight support:
    • Some native peers with integrated scroll bars can handle mouse wheel scrolling by themselves. Examples on Windows includes TextArea, Choice, FileDialog, and List. Such components will let their native peers handle wheel scrolling.
    • Components which do not inherit any native mouse wheel behavior will propagate mouse wheel events up the Container hierarchy until a Container with MouseWheelEvents enabled is found. This is typically a ScrollPane. Mouse wheel events are delivered to the Component with MouseWheelEvents enabled.
    • Alternatively, client programmers may add MouseWheelListeners to customize what happens when the mouse wheel is moved while the mouse is over a Component. In the case of Components that already have native handling of mouse wheel events, clients may consume the mouse wheel event to avoid native handling.
    • java.awt.ScrollPane is modified to have MouseWheelEvents enabled by default. When a ScrollPane receives a MouseWheelEvent, it will properly scroll its contained Component. This functionality may be disabled with the new setWheelScrollingEnabled method.

  • Lightweight Support:

    • Lightweight components will deliver mouse wheel events to their first ancestor with a MouseWheelListener.
    • MouseWheelListeners may be added to any JComponent for custom event handling.
    • javax.swing.JScrollPane is modified to properly scroll its viewed component. Like java.awt.ScrollPane, this may be disabled using setWheelScrollingEnabled.
  • New API:

    In addition to the new class and new interface previously mentioned, there are some other changes to the API to support the mouse wheel.

    • Change to java.awt.AWTEvent:
          public final static long MOUSE_WHEEL_EVENT_MASK;
    • Changes to java.awt.AWTEventMulticaster:
          public void mouseWheelMoved(MouseWheelEvent e)

    public static MouseWheelListener add(MouseWheelListener a, MouseWheelListener b)

    public static MouseWheelListener remove(MouseWheelListener l, MouseWheelListener oldl)
    • Changes to java.awt.Component:
          public synchronized void addMouseWheelListener(MouseWheelListener l)

    public synchronized void removeMouseWheelListener(MouseWheelListener l)
    • Changes to java.awt.ScrollPane:
          public void setWheelScrollingEnabled(boolean handleWheel)

    public boolean isWheelScrollingEnabled()
    • Change to java.awt.Robot:
          public synchronized void mouseWheel(int wheelAmt)
  • Linux Mouse Wheel Support:

    For Linux to recognize your mouse wheel, two modifications to the /etc/X11/XF86Config file are required. Under the "Pointer" section:

    • Add the line:

          ZAxisMapping 4 5

    • Change the protocol to: "imps/2" (this will vary depending on your particular wheel mouse).

Programmatic Zooming of Frames

The bugtraq report that corresponds to this change is: 4071554.

Previously there was no way to zoom (or maximize) a Frame programmatically. This feature has been added to this release.

The new interface java.awt.event.WindowStateListener is introduced.

Changes to java.awt.Frame:

    public static final int MAXIMIZED_HORIZ;

    public static final int MAXIMIZED_VERT;

    public static final int MAXIMIZED_BOTH;

    public synchronized void setMaximizedBounds(Rectangle bounds)

    public Rectangle getMaximizedBounds()

    public synchronized void setExtendedState(int state)

    public synchronized int getExtendedState()

Changes to java.awt.event.WindowEvent:

    public static final int WINDOW_STATE_CHANGED;

    public WindowEvent(Window source, int id, Window opposite, int oldState, int newState)

    public WindowEvent(Window source, int id, int oldState, int newState)

    public int getOldState()

    public int getNewState()

Changes to java.awt.AWTEvent:

    public final static long WINDOW_STATE_EVENT_MASK;

Changes to java.awt.Toolkit:

    public boolean isFrameStateSupported(int state) throws HeadlessException

Changes to java.awt.Window:

    public synchronized void addWindowStateListener(WindowStateListener l)

    public synchronized void removeWindowStateListener(WindowStateListener l)

    public synchronized WindowStateListener[] getWindowStateListeners()

    protected void processWindowStateEvent(WindowEvent e)

Change to java.awt.event.WindowAdapter:

    public void windowStateChanged(WindowEvent e)

Changes to java.awt.AWTEventMulticaster:

    public static WindowStateListener add(WindowStateListener a, WindowStateListener b)

    public static WindowStateListener remove(WindowStateListener l, WindowStateListener oldl)

Dynamic Layout During Resize

The bugtraq report that corresponds to this change is: 4077991.

Previously, dynamic window resizing wasn't supported on all platforms. For example, on Windows NT, with solid resize on, resizing a window recalculated the layout only when the drag was finished. This has been fixed in this release with the addition of the new desktop property awt.dynamicLayoutSupported. When dynamic layout is enabled, a Container continually lays out its components as it resizes. If disabled, the layout will be validated after resizing has finished.

API changes to java.awt.Toolkit.

    public void setDynamicLayout(boolean dynamic)

    protected boolean isDynamicLayoutSet()

    public boolean isDynamicLayoutActive()

Access to Component Listener Lists

The bugtraq report that corresponds to this change is: 4290704.

Previously all of the state in an AWT component that could be written could also be read. For example, there are no write-only properties in the component API. Event listeners were a notable exception. AWT event listeners are managed according to the JavaBeansTM conventions with a pair of methods: addXXXListener and removeXXXListener for a listener that implements the XXXEventListener interface.

No access was provided to the listener lists themselves. The fields that contain the listener lists are package private and no method was provided that returns the contents of a listener list. This has caused some problems for Swing and other AWT clients.

To mitigate the problem in the Java 2 SDK, v1.3 release, we added a getListeners method to Component and to the Swing classes that defined listener lists. The getListeners method uses a class to specify a particular listener list. For example to get all of the listeners added with addFocusListener, one would write: getListeners(FocusListener.class).

This particular approach to exposing listener lists was taken to minimize the overall change to the AWT/Swing public API. It was not intended to be a convention for all JavaBeans and it did not handle PropertyChangeListeners - which can be added to a single property, as in addPropertyChangeListener("myProperty", myListener). For this release, we have designed a more complete solution to accessing event listeners. The two conceptual changes are:

  • The addition of a getFooListeners method to the add/remove convention in AWT and Swing classes.
  • Support for PropertyChangeListeners and VetoableChangeListeners, including those which listen to a single property, using the new java.util.EventListenerProxy class.

There is a new java.awt.event.AWTEventListenerProxy class.

API Changes to java.awt.Toolkit:

    public PropertyChangeListener[] getPropertyChangeListeners()

    public synchronized PropertyChangeListener[] getPropertyChangeListeners(String propertyName)

    public AWTEventListener[] getAWTEventListeners()

    public AWTEventListener[] getAWTEventListeners(long eventMask)

Changes to Drag and Drop

The bugtraq reports that corresponds to this change are: 4407057 and 4426750.

In the Solaris and Linux releases of Java 2 Standard Edition, SDK 1.3, several of the AWT heavyweight Components exhibited default drag behavior via the middle mouse button, even if the application did not identify these Components as DragSources via the java.awt.dnd API. These Components were implemented using Motif peers, and Motif provides middle button drag behavior for these peers by default.

Because of the design of the AWT, and because of bugs in the Motif library, this default behavior has been the source of numerous stability problems. Rather than continue to risk the stability of AWT and Drag & Drop for a niche feature, we have chosen to disable this feature explicitly in our implementations.

Developers can still identify these Components as DragSources in their applications using the java.awt.dnd API. This is both functional and supported. This approach is superior to relying upon default Motif behavior in any case, because it enables drag support for these Components on all platforms, not just Solaris and Linux.

64-Bit Compliance on Solaris Machines

The bugtraq report that corresponds to this change is: 4295833.

64-bit Solaris applications use 64 bits to address memory instead of 32. This allows larger applications by providing a much larger virtual memory space. For this release, AWT has been brought up to 64-bit compliance. For more information, see here.

Inconsistent DLLs Warning

The bugtraq report that corresponds to this change is: 4414004.

If you have installed English VC++ 6.0 onto a machine that also has Asian Windows NT installed, you may encounter strange artifacts when rendering Asian text in the TextArea component. You may also see this problem if you have installed Microsoft Exchange or Microsoft Office 97 onto a machine running Asian Windows NT 4.0. Although this problem was reported on the Japanese version of Windows NT, it will probably occur on other non-Latin versions of NT as well, such as Chinese or Korean.

The problem was caused when the installation of those programs replaced the Asian Riched32.dll with the English version. The problem can be corrected by replacing Riched32.dll with the Asian version.

Removal of the Drawing Surface API

The bugtraq report that corresponds to this change is: 4293646.

The sun.awt.DrawingSurface API has been removed. It was never made public, but some developers have been using it. The functionality has been replaced by the JAWT. For more information, see the AWT Native Interface description.

Window Centering API Required for Multiscreen Support

The bugtraq report that corresponds to this change is: 4463949.

Xinerama-aware applications running on multi-headed systems have caused problems which have resulted in a variety of bug reports. Some multi-headed environments use monitors with little or no borders, which can be butted up against one another such that the resulting effect is one mammoth display. In this case, a "properly" centered window may span multiple screens. Other multi-headed environments use regular CRT monitors, with several inches of packaging between the actual display areas. In this case, a window spanning multiple screens produces a disconcerting effect, especially if the window cannot be dragged onto one monitor or the other (the Solaris login screen, for example). In short there was no way to tell where to center a window in a Xinerama environment.

To address this problem, the X group has added API which allows Xinerama users to specify where they want "centered" windows to be centered, and allows developers of Xinerama-aware applications to code accordingly.

Prior to this release, the way to center a window has been to center it within the bounds of the default GraphicsDevice, like this:

    bounds = getDefaultScreenDevice().getDefaultConfiguration().getBounds();
    frame.setLocation(bounds / 2 - size of window / 2);
This code would center the windows "correctly" on Xinerama systems where windows should be centered to the entire Xinerama coordinate space.

As of this release, post 4356756-fix JDKs will center windows "correctly" on Xinerama systems where windows should be centered within the first display.

To accomplish this, the getCenterPoint method has been added to GraphicsEnvironment .

This method works as follows on various platforms:

  • Microsoft Windows/Macintosh:
    These platforms include all monitors in a single virtual coordinate space. However, there is one "primary" display (on Microsoft Windows the primary display contains the task bar, on the Mac, the menubar). Here, getCenterPoint returns the coordinates of the center of the primary display.
  • X-Window, non-Xinerama
    Each display has its own coordinate system; the upper-left corner of every display is 0.0. Again, there is a "first" display. Here, getCenterPoint returns the center point of the primary display.
  • X-Window, Xinerama
    All monitors share a single virtual coordinate space, as on Microsoft Windows. However, it is possible for the user to specify through X resources where windows should be centered. If these resources are set, getCenterPoint reflects their value. Otherwise, it returns the point at the center of the virtual coordinate space. (In practice, this will almost always be set - CDE sets it by default.)

As of JDK 1.4, the correct code for centering is:

    frame.setLocation(getCenterPoint() - size of window / 2);

The other method added to GraphicsEnvironment is getMaximumWindowBounds. Both getCenterPoint and getMaximumWindowBounds throw a HeadlessException when in Headless mode.

New InputEvent Key Modifiers

The bugtraq reports that corresponds to this change are: 4387938 and 4421515.

Previously, the InputEvent modifiers had the same values for keyboard and mouse buttons. In certain situations there was no way to distinguish which one was pressed or when more than one was held simultaneously. These situations included cases when more than one mouse button was down at the same time, or when a modifier key was used to modify a mouse event.

To address this deficiency, the following constants were added to InputEvent:

  • SHIFT_DOWN_MASK
  • CTRL_DOWN_MASK
  • META_DOWN_MASK
  • ALT_DOWN_MASK
  • ALT_GRAPH_DOWN_MASK
  • BUTTON1_DOWN_MASK
  • BUTTON2_DOWN_MASK
  • BUTTON3_DOWN_MASK

The following methods were added to InputEvent:

  • getModifiersEx
  • getModifiersExText

The class spec for MouseEvent was updated. The following constants were also added to MouseEvent:

  • NOBUTTON
  • BUTTON1
  • BUTTON2
  • BUTTON3

These methods in MouseEvent were added:

  • MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int clickCount, boolean popupTrigger, int button)
  • getButton
  • getMouseModifiersText

DragSourceDragEvent has the new method getGestureModifiersEx.

Change in Drop Down Behavior for Choice Menus

The bugtraq report that corresponds to this change is: 4462677.

The Choice drop down menu behavior has changed from JDK 1.3.1 to 1.4. In 1.3.1, you could click anywhere on the choice bar and the menu would drop down. In 1.4, you must click on the arrow selector on the right hand side of the Choice bar. Clicking anywhere else on the Choice bar has no effect. Also, the symbol on the Choice bar has changed from a bar to an arrow/bar combination. Finally, if the drop down menu extends outside of the parent, when clicking on that area, the application underneath is brought to the foreground. This happens on Solaris, not Windows.

Choice Component Now Obeys Layout Manager Constraints

The bugtraq report that corresponds to this change is: 4288285.

In releases prior to 1.4, the AWT Choice widget sometimes ignored the size that the layout manager told it to be. As of this release, it now obeys the layout manager constraints.

Deprecated Focus Methods

The bugtraq report that corresponds to this change is: 4476300.

The new focus subsystem, introduced in this release, introduced a new architecture and a new terminology for handling keyboard focus in sophisticated AWT and Swing applications. Prior to this project, many of the focus-related APIs were inconsistent in usage and termonology, were improperly documented, and led to poorly designed UIs. Now that the new architecture is in place, the most egregious of these APIs has been deprecated.

The following constants and methods have been deprecated:

  • javax.swing.FocusManager.FOCUS_MANAGER_CLASS_PROPERTY
  • javax.swing.FocusManager.disableSwingFocusManager()
  • javax.swing.FocusManager.isFocusManagerEnabled()
  • javax.swing.JComponent.requestDefaultFocus()
  • javax.swing.JComponent.isManagingFocus()
  • javax.swing.JComponent.setNextFocusableComponent(Component)
  • javax.swing.JComponent.getNextFocusableComponent()
  • java.awt.Component.isFocusTraversable()
  • java.awt.Component.hasFocus()
  • javax.swing.SwingUtilities.findFocusOwner(Component)
ActionEvents (and Other Events) Need Timestamps

The bugtraq report that corresponds to this change is: 4434193.

The new focus architecture includes a type-ahead mechanism that ensures that subsequent KeyEvents that follow a KeyEvent that initiates a focus transfer are not delivered until the transfer is completed. The design for this feature is based on the UTC timestamps of the various events. Events with timestamps later than that of the initiating event are enqueued pending resolution of the transfer; events with earlier timestamps are not.

To implement this feature, the focus code keeps track of the timestamp of the event currently being handled. If a focus change is initiated during this handling, the timestamp is available for use. However, if the current event does not have a timestamp, then the current system time is used. This time is usually too far ahead of the time that the event actually occurred to be of any real use. As a result, the type-ahead mechanism fails, and KeyEvents are delivered before the focus transfer is completed.

The most common case where we encountered this problem was with ActionEvents. ActionEvents are high-level, semantic events generated in response to underlying InputEvents. While the InputEvents had timestamps associated with them, the ActionEvents did not. The ActionEvent API has therefore been expanded to accomodate a timestamp and the implementation has been updated so that an ActionEvent's timestamp is equal to that of its underlying InputEvent.

The following methods have been added to ActionEvent:

  • ActionEvent(Object source, int id, String command, long when, int modifiers)
  • getWhen

The following ActionEvent methods were modified:

  • ActionEvent(Object source, int id, String command)
  • ActionEvent(Object source, int id, String command, int modifiers)

The getWhen method was added to InvocationEvent.

The InvocationEvent constructors InvocationEvent(Object, Runnable) and InvocationEvent(Object, Runnable, Object, boolean) were modified.

A new constructor InputMethodEvent(Component, int, long, AttributedCharacterIterator, int, TextHitInfo, TextHitInfo) was added to InputMethodEvent, as well as the getWhen method.

The following InputMethodEvent constructors have been modified:

  • InputMethodEvent(Component, int, AttributedCharacterIterator, int, TextHitInfo, TextHitInfo)
  • InputMethodEvent(Component, int, TextHitInfo, TextHitInfo).

Finally, the following methods were added to EventQueue:

  • getMostRecentEventTime
  • getCurrentEvent
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.net.httpserver.BasicAuthenticator (Java HTTP Server b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.net.httpserver.BasicAuthenticator

No usage of com.sun.net.httpserver.BasicAuthenticator
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Use of Java GSS-API for Secure Message Exchanges Without JAAS Programming

This tutorial presents two sample applications demonstrating the use of the Java GSS-API for secure exchanges of messages between communicating applications, in this case a client application and a server application.

Java GSS-API uses what is called a "security mechanism" to provide these services. The GSS-API implementation available with the Java 2 Standard Edition platform contains support for the Kerberos V5 mechanism in addition to any other vendor-specific choices. We use the Kerberos V5 mechanism for this tutorial.

In order to perform authentication between the client and server and to establish cryptographic keys for secure communication, a GSS-API mechanism needs access to certain credentials for the local entity on each side of the connection. In our case, the credential used on the client side consists of a Kerberos ticket, and on the server side, it consists of a long-term Kerberos secret key. Kerberos tickets can optionally include the host address and IPv4 and IPv6 host addresses are both supported. Java GSS-API requires that the mechanism obtain these credentials from the Subject associated with the thread's access control context.

To populate a Subject with such credentials, client and server applications typically will first perform JAAS authentication using a Kerberos module. The JAAS Authentication tutorial demonstrates how to do this. The JAAS Authorization tutorial then demonstrates how to associate the authenticated Subject with the thread's access control context. A utility has also been written as a convenience to automatically perform those operations on your behalf. The Use of JAAS Login Utility tutorial demonstrates how to use the Login utility.

For this tutorial, we will not have the client and server perform JAAS authentication, nor will we have them use the Login utility. Instead, we will rely on setting the system property javax.security.auth.useSubjectCredsOnly to false, which allows us to relax the restriction of requiring a GSS mechanism to obtain necessary credentials from an existing Subject, set up by JAAS. See The useSubjectCredsOnly System Property.

Note: This is a simplified introductory tutorial. For example, we do not include any policy files or run the sample code using a security manager. In real life, code using Java GSS-API should be run with a security manager, so that security-sensitive operations would not be allowed unless the required permissions were explicitly granted.

There is another tutorial, Use of JAAS Login Utility and Java GSS-API for Secure Message Exchanges, that is just like the tutorial you are reading except that it utilizes the Login utility, policy files, and a more complex login configuration file (A login configuration file, required whenever JAAS authentication is done, specifies the desired authentication module).

As with all tutorials in this series, the underlying technology used to support authentication and secure communication for the applications in this tutorial is Kerberos V5. See Kerberos Requirements.

  • Overview of the Client And Server Applications
  • The SampleClient and SampleServer Code
  • Kerberos User and Service Principal Names
  • The Login Configuration File
  • The useSubjectCredsOnly System Property
  • Running the SampleClient and SampleServer Programs

If you want to first see the tutorial code in action, you can skip directly to Running the SampleClient and SampleServer Programs and then go back to the other sections to learn more.

Overview of the Client And Server Applications

The applications for this tutorial are named SampleClient and SampleServer.

Here is a summary of execution of the SampleClient and SampleServer applications:

  1. Run the SampleServer application. SampleServer
    1. Reads its argument, the port number that it should listen on for client connections.
    2. Creates a ServerSocket for listening for client connections on that port.
    3. Listens for a connection.
  2. Run the SampleClient application (possibly on a different machine). SampleClient
    1. Reads its arguments: (1) The name of the Kerberos principal that represents SampleServer. (See Kerberos User and Service Principal Names.), (2) the name of the host (machine) on which SampleServer is running, and (3) the port number on which SampleServer listens for client connections.
    2. Attempts a socket connection with the SampleServer, using the host and port it was passed as arguments.
  3. The socket connection is accepted by SampleServer and both applications initialize a DataInputStream and a DataOutputStream from the socket input and output streams, to be used for future data exchanges.
  4. SampleClient and SampleServer each instantiate a GSSContext and follow a protocol for establishing a shared context that will enable subsequent secure data exchanges.
  5. SampleClient and SampleServer can now securely exchange messages.
  6. When SampleClient and SampleServer are done exchanging messages, they perform clean-up operations.

The actual code and further details are presented in the following sections.

The SampleClient and SampleServer Code

The entire code for both the SampleClient and SampleServer programs resides in their main methods and can be broken down into the following subparts:

  1. Obtain the Command-Line Arguments
  2. Establish a Socket Connection for Transfers Between SampleClient and SampleServer
  3. Establish a Security Context
  4. Securely Exchange Messages
  5. Clean Up

Note: The Java GSS-API classes utilized by these programs (GSSManager, GSSContext, GSSName, GSSCredential, MessageProp, and Oid) are found in the org.ietf.jgss package.

Obtaining the Command-Line Arguments

The first thing both our client and server main methods do is read the command-line arguments.

Arguments Read By SampleClient

SampleClient expects three arguments:

  1. A service principal name -- The name of the Kerberos principal that represents SampleServer. (See Kerberos User and Service Principal Names.)
  2. A host name -- The machine on which SampleServer is running.
  3. A port number -- The port number of the port on which SampleServer listens for connections.

Here is the code for reading the command-line arguments:

if (args.length < 3) {
    System.out.println("Usage: java <options> Login SampleClient "
       + " <servicePrincipal> <hostName> <port>");
    System.exit(-1);
}

String server = args[0];
String hostName = args[1];
int port = Integer.parseInt(args[2]);

Argument Read By SampleServer

SampleServer expects just one argument:

  • A local port number -- The port number used by SampleServer for listening for connections with clients. This number should be the same as the port number specified when running the SampleClient program.

Here is the code for reading the command-line argument:

if (args.length != 1) {
    System.out.println(
        "Usage: java <options> Login SampleServer <localPort>");
    System.exit(-1);
}

int localPort = Integer.parseInt(args[0]);

Establishing a Socket Connection for Message Exchanges

Java GSS-API provides methods for creating and interpreting tokens (opaque byte data). The tokens contain messages to be securely exchanged between two peers, but the method of actual token transfer is up to the peers. For our SampleClient and SampleServer applications, we establish a socket connection between the client and server and exchange data using the socket input and output streams.

SampleClient Code For Socket Connection

SampleClient was passed as arguments the name of the host machine SampleServer is running on, as well as the port number on which SampleServer will be listening for connections, so SampleClient has all it needs to establish a socket connection with SampleServer. It uses the following code to set up the connection and initialize a DataInputStream and a DataOutputStream for future data exchanges:

Socket socket = new Socket(hostName, port);

DataInputStream inStream =
  new DataInputStream(socket.getInputStream());
DataOutputStream outStream =
  new DataOutputStream(socket.getOutputStream());

System.out.println("Connected to server "
   + socket.getInetAddress());

SampleServer Code For Socket Connection

The SampleServer application was passed as an argument the port number to be used for listening for connections from clients. It creates a ServerSocket for listening on that port:

ServerSocket ss = new ServerSocket(localPort);

The ServerSocket can then wait for and accept a connection from a client, and then initialize a DataInputStream and a DataOutputStream for future data exchanges with the client :

Socket socket = ss.accept();

DataInputStream inStream =
    new DataInputStream(socket.getInputStream());
DataOutputStream outStream =
    new DataOutputStream(socket.getOutputStream());

System.out.println("Got connection from client "
    + socket.getInetAddress());

The accept method waits until a client (in our case, SampleClient) requests a connection on the host and port of the SampleServer, which SampleClient does via

Socket socket = new Socket(hostName, port);

When the connection is requested and established, the accept method returns a new Socket object bound to a new port. The server can communicate with the client over this new socket and continue to listen for other client connection requests on the ServerSocket bound to the original port. Thus, a server program typically has a loop which can handle multiple connection requests.

The basic loop structure for our SampleServer is the following:

while (true) {

    Socket socket = ss.accept();

    <Establish input and output streams for the connection>
    <Establish a context with the client>
    <Exchange messages with the client>;
    <Clean up>;
}

Client connections are queued at the original port, so with this program structure used by SampleServer, the interaction with the first client making a connection has to complete before the next connection can be accepted. The server could actually service multiple clients simultaneously through the use of threads - one thread per client connection, as in

while (true) {
    <accept a connection>;
    <create a thread to handle the client>;
}

Establishing a Security Context

Before two applications can use Java GSS-API to securely exchange messages between them, they must establish a joint security context using their credentials. (Note: In the case of SampleClient, the credentials were established when the Login utility authenticated the user on whose behalf the SampleClient was run, and similarly for SampleServer.) The security context encapsulates shared state information that might include, for example, cryptographic keys. One use of such keys might be to encrypt messages to be exchanged, if encryption is requested.

As part of the security context establishment, the context initiator (in our case, SampleClient) is authenticated to the acceptor (SampleServer), and may require that the acceptor also be authenticated back to the initiator, in which case we say that "mutual authentication" took place.

Both applications create and use a GSSContext object to establish and maintain the shared information that makes up the security context.

The instantiation of the context object is done differently by the context initiator and the context acceptor. After the initiator instantiates a GSSContext, it may choose to set various context options that will determine the characteristics of the desired security context, for example, specifying whether or not mutual authentication should take place. After all the desired characteristics have been set, the initiator calls the initSecContext method, which produces a token required by the acceptor's acceptSecContext method.

While Java GSS-API methods exist for preparing tokens to be exchanged between applications, it is the responsibility of the applications to actually transfer the tokens between them. So after the initiator has received a token from its call to initSecContext, it sends that token to the acceptor. The acceptor calls acceptSecContext, passing it the token. The acceptSecContext method may in turn return a token. If it does, the acceptor should send that token to the initiator, which should then call initSecContext again and pass it this token. Each time initSecContext or acceptSecContext returns a token, the application that called the method should send the token to its peer and that peer should pass the token to its appropriate method (acceptSecContext or initSecContext). This continues until the context is fully established (which is the case when the context's isEstablished method returns true).

The context establishment code for our sample applications is described in the following:

  • Context Establishment by SampleClient
  • Context Establishment by SampleServer

Context Establishment by SampleClient

In our client/server scenario, SampleClient is the context initiator. Here are the basic steps it takes to establish a security context. It

  1. Instantiates a GSSContext.
  2. Sets the desired optional features on the context.
  3. Loops while the context is not yet established, each time calling initSecContext, sending any returned token to SampleServer, and receiving a token (if any) from SampleServer.

SampleClient GSSContext Instantiation

A GSSContext is created by instantiating a GSSManager and then calling one of its createContext methods. The GSSManager class serves as a factory for other important GSS API classes. It can create instances of classes implementing the GSSContext, GSSCredential, and GSSName interfaces.

SampleClient obtains an instance of the default GSSManager subclass by calling the GSSManager static method getInstance:

GSSManager manager = GSSManager.getInstance();

The default GSSManager subclass is one whose create* methods (createContext, etc.) return classes whose implementations support Kerberos as the underlying technology.

The GSSManager factory method for creating a context on the initiator's side has the following signature:

GSSContext createContext(GSSName peer, Oid mech,
            GSSCredential myCred, int lifetime);

The arguments are described below, followed by the complete call to createContext.

The GSSName peer Argument

The peer in our client/server paradigm is the server. For the peer argument, we need a GSSName for the service principal representing the server. (See Kerberos User and Service Principal Names.) A String for the service principal name is passed as the first argument to SampleClient, which places the argument into its local String variable named server. The GSSManager manager is used to instantiate a GSSName by calling one of its createName methods. SampleClient calls the createName method with the following signature:

GSSName createName(String nameStr, Oid nameType);

SampleClient passes the server String for the nameStr argument.

The second argument is an Oid. An Oid represents a Universal Object Identifier. Oids are hierarchically globally-interpretable identifiers used within the GSS-API framework to identify mechanisms and name types. The structure and encoding of Oids is defined in the ISOIEC-8824 and ISOIEC-8825 standards. The Oid passed to the createName method is specifically a name type Oid (not a mechanism Oid).

In GSS-API, string names are often mapped from a mechanism-independent format into a mechanism-specific format. Usually, an Oid specifies what name format the string is in so that the mechanism knows how to do this mapping. Passing in a null Oid indicates that the name is already in a native format that the mechanism uses. This is the case for the server String; it is in the appropriate format for a Kerberos Version 5 name. Thus, SampleClient passes a null for the Oid. Here is the call:

GSSName serverName = manager.createName(server, null);

The Oid mech Argument

The second argument to the GSSManager createContext method is an Oid representing the mechanism to be used for the authentication between the client and the server during context establishment and for subsequent secure communication between them.

Our tutorial will use Kerberos V5 as the security mechanism. The Oid for the Kerberos V5 mechanism is defined in RFC 1964 as "1.2.840.113554.1.2.2" so we create such an Oid:

Oid krb5Oid = new Oid("1.2.840.113554.1.2.2");

SampleClient passes krb5Oid as the second argument to createContext.

The GSSCredential myCred Argument

The third argument to the GSSManager createContext method is a GSSCredential representing the caller's credentials. If you pass null for this argument, as SampleClient does, the default credentials are used.

The int lifetime Argument

The final argument to the GSSManager createContext method is an int specifying the desired lifetime, in seconds, for the context that is created. SampleClient passes GSSContext.DEFAULT_LIFETIME to request a default lifetime.

The Complete createContext Call

Now that we have all the required arguments, here is the call SampleClient makes to create a GSSContext:

GSSContext context =
    manager.createContext(serverName,
                          krb5Oid,
                          null,
                          GSSContext.DEFAULT_LIFETIME);

SampleClient Setting of Desired Options

After instantiating a context, and prior to actually establishing the context with the context acceptor, the context initiator may choose to set various options that determine the desired security context characteristics. Each such option is set by calling a request method on the instantiated context. Most request methods take a boolean argument for indicating whether or not the feature is requested. It is not always possible for a request to be satisfied, so whether or not it was can be determined after context establishment by calling one of the get methods.

SampleClient requests the following:

  1. Mutual authentication. The context initiator is always authenticated to the acceptor. If the initiator requests mutual authentication, then the acceptor is also authenticated to the initiator.
  2. Confidentiality. Requesting confidentiality means that you request the enabling of encryption for the context method named wrap. Encryption is actually used only if the MessageProp object passed to the wrap method requests privacy.
  3. Integrity. This requests integrity for the wrap and getMIC methods. When integrity is requested, a cryptographic tag known as a Message Integrity Code (MIC) will be generated when calling those methods. When getMIC is called, the generated MIC appears in the returned token. When wrap is called, the MIC is packaged together with the message (the original message or the result of encrypting the message, depending on whether confidentiality was applied) all as part of one token. You can subsequently verify the MIC against the message to ensure that the message has not been modified in transit.

The SampleClient code for making these requests on the GSSException context is the following:

context.requestMutualAuth(true);  // Mutual authentication
context.requestConf(true);  // Will use encryption later
context.requestInteg(true); // Will use integrity later

Note: When using the default GSSManager implementation and the Kerberos mechanism, these requests will always be granted.

SampleClient Context Establishment Loop

After SampleClient has instantiated a GSSContext and specified the desired context options, it can actually establish the security context with SampleServer. To do so, SampleClient has a loop. Each loop iteration

  1. Calls the context's initSecContext method. If this is the first call, the method is passed a null token. Otherwise, it is passed the token most recently sent to SampleClient by SampleServer (a token generated by a SampleServer call to acceptSecContext).
  2. Sends the token returned by initSecContext (if any) to SampleServer. The first call to initSecContext always produces a token. The last call might not return a token.
  3. Checks to see if the context is established. If not, SampleClient receives another token from SampleServer and then starts the next loop iteration.

The tokens returned by initSecContext or received from SampleServer are placed in a byte array. Tokens should be treated by SampleClient and SampleServer as opaque data to be passed between them and interpreted by Java GSS-API methods.

The initSecContext arguments are a byte array containing a token, the starting offset into that array of where the token begins, and the token length. For the first call, SampleClient passes a null token, since no token has yet been received from SampleServer.

To exchange tokens with SampleServer, SampleClient uses the DataInputStream inStream and DataOutputStream outStream it previously set up using the input and output streams for the socket connection made with SampleServer. Note that whenever a token is written, the number of bytes in the token is written first, followed by the token itself. The reasons are discussed in the introduction to the The SampleClient and SampleServer Message Exchanges section.

Here is the SampleClient context establishment loop, followed by code displaying information about who the client and server are and whether or not mutual authentication actually took place:

byte[] token = new byte[0];

while (!context.isEstablished()) {

    // token is ignored on the first call
    token = context.initSecContext(token, 0, token.length);

    // Send a token to the server if one was generated by
    // initSecContext
    if (token != null) {
        System.out.println("Will send token of size "
                   + token.length + " from initSecContext.");
        outStream.writeInt(token.length);
        outStream.write(token);
        outStream.flush();
    }

    // If the client is done with context establishment
    // then there will be no more tokens to read in this loop
    if (!context.isEstablished()) {
        token = new byte[inStream.readInt()];
        System.out.println("Will read input token of size "
                   + token.length
                   + " for processing by initSecContext");
        inStream.readFully(token);
    }
}

System.out.println("Context Established! ");
System.out.println("Client is " + context.getSrcName());
System.out.println("Server is " + context.getTargName());
if (context.getMutualAuthState())
    System.out.println("Mutual authentication took place!");

Context Establishment by SampleServer

In our client/server scenario, SampleServer is the context acceptor. Here are the basic steps it takes to establish a security context. It

  1. Instantiates a GSSContext.
  2. Loops while the context is not yet established, each time receiving a token from SampleClient, calling acceptSecContext and passing it the token, and sending any returned token to SampleClient.

SampleServer GSSContext Instantiation

As described in SampleClient GSSContext Instantiation, a GSSContext is created by instantiating a GSSManager and then calling one of its createContext methods.

Like SampleClient, SampleServer obtains an instance of the default GSSManager subclass by calling the GSSManager static method getInstance:

GSSManager manager = GSSManager.getInstance();

The GSSManager factory method for creating a context on the acceptor's side has the following signature:

GSSContext createContext(GSSCredential myCred);

If you pass null for the GSSCredential argument, as SampleServer does, the default credentials are used. The context is instantiated via the following:

  GSSContext context = manager.createContext((GSSCredential)null);

SampleServer Context Establishment Loop

After SampleServer has instantiated a GSSContext, it can establish the security context with SampleClient. To do so, SampleServer has a loop that continues until the context is established. Each loop iteration does the following:

  1. Receives a token from SampleClient. This token is the result of a SampleClient initSecContext call.
  2. Calls the context's acceptSecContext method, passing it the token just received.
  3. If acceptSecContext returns a token, then SampleServer sends this token to SampleClient and then starts the next loop iteration if the context is not yet established.

The tokens returned by acceptSecContext or received from SampleClient are placed in a byte array.

The acceptSecContext arguments are a byte array containing a token, the starting offset into that array of where the token begins, and the token length.

To exchange tokens with SampleClient, SampleServer uses the DataInputStream inStream and DataOutputStream outStream it previously set up using the input and output streams for the socket connection made with SampleClient.

Here is the SampleServer context establishment loop:

byte[] token = null;

while (!context.isEstablished()) {

    token = new byte[inStream.readInt()];
    System.out.println("Will read input token of size "
       + token.length
       + " for processing by acceptSecContext");
    inStream.readFully(token);

    token = context.acceptSecContext(token, 0, token.length);

    // Send a token to the peer if one was generated by
    // acceptSecContext
    if (token != null) {
        System.out.println("Will send token of size "
           + token.length
           + " from acceptSecContext.");
        outStream.writeInt(token.length);
        outStream.write(token);
        outStream.flush();
    }
}

System.out.print("Context Established! ");
System.out.println("Client is " + context.getSrcName());
System.out.println("Server is " + context.getTargName());
if (context.getMutualAuthState())
    System.out.println("Mutual authentication took place!");

Exchanging Messages Securely

Once a security context has been established between SampleClient and SampleServer, they can use the context to securely exchange messages.

  • GSSContext Methods for Message Exchange
  • The SampleClient and SampleServer Message Exchanges

GSSContext Methods for Message Exchange

Two types of methods exist for preparing messages for secure exchange: wrap and getMIC. There are actually two wrap methods (and two getMIC methods), where the differences between the two are the indication of where the input message is (a byte array or an input stream) and where the output should go (to a byte array return value or to an output stream).

These methods for preparing messages for exchange, and the corresponding methods for interpretation by the peer of the resulting tokens, are described below.

wrap

The wrap method is the primary method for message exchanges.

The signature for the wrap method called by SampleClient is the following:

byte[] wrap (byte[] inBuf, int offset, interface len,
                MessageProp msgProp)

You pass wrap a message (in inBuf), the offset into inBuf where the message begins (offset), and the length of the message (len). You also pass a MessageProp, which is used to indicate the desired QOP (Quality-of-Protection) and to specify whether or not privacy (encryption) is desired. A QOP value selects the cryptographic integrity and encryption (if requested) algorithm(s) to be used. The algorithms corresponding to various QOP values are specified by the provider of the underlying mechanism. For example, the values for Kerberos V5 are defined in RFC 1964 in section 4.2. It is common to specify 0 as the QOP value to request the default QOP.

The wrap method returns a token containing the message and a cryptographic Message Integrity Code (MIC) over it. The message placed in the token will be encrypted if the MessageProp indicates privacy is desired. You do not need to know the format of the returned token; it should be treated as opaque data. You send the returned token to your peer application, which calls the unwrap method to "unwrap" the token to get the original message and to verify its integrity.

getMIC

If you simply want to get a token containing a cryptographic Message Integrity Code (MIC) for a supplied message, you call getMIC. A sample reason you might want to do this is to confirm with your peer that you both have the same data, by just transporting a MIC for that data without incurring the cost of transporting the data itself to each other.

The signature for the getMIC method called by SampleServer is the following:

byte[] getMIC (byte[] inMsg, int offset, int len,
            MessageProp msgProp)

You pass getMIC a message (in inMsg), the offset into inMsg where the message begins (offset), and the length of the message (len). You also pass a MessageProp, which is used to indicate the desired QOP (Quality-of-Protection). It is common to specify 0 as the QOP value to request the default QOP.

If you have a token created by getMIC and the message used to calculate the MIC (or a message purported to be the message on which the MIC was calculated), you can call the verifyMIC method to verify the MIC for the message. If the verification is successful (that is, if a GSSException is not thrown), it proves that the message is exactly the same as it was when the MIC was calculated. A peer receiving a message from an application typically expects a MIC as well, so that they can verify the MIC and be assured the message has not been modified or corrupted in transit. Note: If you know ahead of time that you will want the MIC as well as the message then it is more convenient to use the wrap and unwrap methods. But there could be situations where the message and the MIC are received separately.

The signature for the verifyMIC corresponding to the getMIC shown above is

void verifyMIC (byte[] inToken, int tokOffset, int tokLen,
        byte[] inMsg, int msgOffset, int msgLen,
        MessageProp msgProp);

This verifies the MIC contained in the inToken (of length tokLen, starting at offset tokOffset) over the message contained in inMsg (of length msgLen, starting at offset msgOffset). The MessageProp is used by the underlying mechanism to return information to the caller, such as the QOP indicating the strength of protection that was applied to the message.

The SampleClient and SampleServer Message Exchanges

The message exchanges between SampleClient and SampleServer are summarized below, followed by the coding details.

These steps are the "standard" steps used for verifying a GSS-API client and server. A group at MIT has written a GSS-API client and a GSS-API server that have become fairly popular test programs for checking interoperability between different implementations of the GSS-API library. (These GSS-API sample applications can be downloaded as a part of the Kerberos distribution available from MIT at http://web.mit.edu/kerberos.) This client and server from MIT follow the protocol that once the context is established, the client sends a message across and it expects back the MIC on that message. If you implement a GSS-API library, it is common practice to test it by running either the client or server using your library implementation against a corresponding peer server or client that uses another GSS-API library implementation. If both library implementations conform to the standards, then the two peers will be able to communicate successfully.

One implication of testing your client or server against ones written in C (like the MIT ones) is the way tokens must be exchanged. C implementations of GSS-API do not include stream-based methods. In the absence of stream-based methods on your peer, when you write a token you must first write the number of bytes and then write the token. Similarly, when you are reading a token, you first read the number of bytes and then read the token. This is what SampleClient and SampleServer do.

Here is the summary of the SampleClient and SampleServer message exchanges:

  1. SampleClient calls wrap to encrypt and calculate a MIC for a message.
  2. SampleClient sends the token returned from wrap to SampleServer.
  3. SampleServer calls unwrap to obtain the original message and verify its integrity.
  4. SampleServer calls getMIC to calculate a MIC on the decrypted message.
  5. SampleServer sends the token returned by getMIC (which contains the MIC) to SampleClient.
  6. SampleClient calls verifyMIC to verify that the MIC sent by SampleServer is a valid MIC for the original message.

SampleClient Code to Encrypt the Message and Send It

The SampleClient code for encrypting a message, calculating a MIC for it, and sending the result to SampleServer is the following:

byte[] messageBytes = "Hello There!\0".getBytes();

/*
 * The first MessageProp argument is 0 to request
 * the default Quality-of-Protection.
 * The second argument is true to request
 * privacy (encryption of the message).
 */
MessageProp prop =  new MessageProp(0, true);

/*
 * Encrypt the data and send it across. Integrity protection
 * is always applied, irrespective of encryption.
 */
token = context.wrap(messageBytes, 0, messageBytes.length,
    prop);
System.out.println("Will send wrap token of size "
    + token.length);
outStream.writeInt(token.length);
outStream.write(token);
outStream.flush();

SampleServer Code to Unwrap Token, Calculate MIC, and Send It

The following SampleServer code reads the wrapped token sent by SampleClient and "unwraps" it to obtain the original message and have its integrity verified. The unwrapping in this case includes decryption since the message was encrypted.

Note: Here the integrity check is expected to succeed. But note that in general if an integrity check fails it signifies that the message was changed in transit. If the unwrap method encounters an integrity check failure, it throws a GSSException with major error code GSSException.BAD_MIC.

/*
 * Create a MessageProp which unwrap will use to return
 * information such as the Quality-of-Protection that was
 * applied to the wrapped token, whether or not it was
 * encrypted, etc. Since the initial MessageProp values
 * are ignored, it doesn't matter what they are set to.
 */
MessageProp prop = new MessageProp(0, false);

/*
 * Read the token. This uses the same token byte array
 * as that used during context establishment.
 */
token = new byte[inStream.readInt()];
System.out.println("Will read token of size "
    + token.length);
inStream.readFully(token);

byte[] bytes = context.unwrap(token, 0, token.length, prop);
String str = new String(bytes);
System.out.println("Received data \""
    + str + "\" of length " + str.length());
System.out.println("Encryption applied: "
    + prop.getPrivacy());

Next, SampleServer generates a MIC for the decrypted message and sends it to SampleClient. This is not really necessary but simply illustrates generating a MIC on the decrypted message, which should be exactly the same as the original message SampleClient wrapped and sent to SampleServer. When SampleServer generates this and sends it to SampleClient, and SampleClient verifies it, this proves to SampleClient that the decrypted message SampleServer has is in fact exactly the same as the original message from SampleClient.

/*
 * First reset the QOP of the MessageProp to 0
 * to ensure the default Quality-of-Protection
 * is applied.
 */
prop.setQOP(0);

token = context.getMIC(bytes, 0, bytes.length, prop);

System.out.println("Will send MIC token of size "
                   + token.length);
outStream.writeInt(token.length);
outStream.write(token);
outStream.flush();

SampleClient Code to Verify the MIC

The following SampleClient code reads the MIC calculated by SampleServer on the decrypted message and then verifies that the MIC is a MIC for the original message, proving that the decrypted message SampleServer has is the same as the original message:

token = new byte[inStream.readInt()];
System.out.println("Will read token of size " + token.length);
inStream.readFully(token);

/*
 * Recall messageBytes is the byte array containing
 * the original message and prop is the MessageProp
 * already instantiated by SampleClient.
 */
context.verifyMIC(token, 0, token.length,
          messageBytes, 0, messageBytes.length,
          prop);

System.out.println("Verified received MIC for message.");

Clean Up

When SampleClient and SampleServer have finished exchanging messages, they need to perform cleanup operations. Both contain the following code to
  • close the socket connection and
  • release system resources and cryptographic information stored in the context object and then invalidate the context.
socket.close();
context.dispose();

Kerberos User and Service Principal Names

Since the underlying authentication and secure communication technology used by this tutorial is Kerberos V5, we use Kerberos-style principal names wherever a user or service is called for.

For example, when you run SampleClient you are asked to provide your user name. Your Kerberos-style user name is simply the user name you were assigned for Kerberos authentication. It consists of a base user name (like "mjones") followed by an "@" and your realm (like "mjones@KRBNT-OPERATIONS.ABC.COM").

A server program like SampleServer is typically considered to offer a "service" and to be run on behalf of a particular "service principal." A service principal name for SampleServer is needed in several places:

  • When you run SampleServer, and SampleClient attempts a connection to it, the underlying Kerberos mechanism will attempt to authenticate to the Kerberos KDC. It prompts you to log in. You should log in as the appropriate service principal.
  • When you run SampleClient, one of the arguments is the service principal name. This is needed so SampleClient can initiate establishment of a security context with the appropriate service.
  • If the SampleClient and SampleServer programs were run with a security manager (they're not for this tutorial), the client and server policy files would each require a ServicePermission with name equal to the service principal name and action equal to "initiate" or "accept" (for initiating or accepting establishment of a security context).

Throughout this document, and in the accompanying login configuration file,

service_principal@your_realm
is used as a placeholder to be replaced by the actual name to be used in your environment. Any Kerberos principal can actually be used for the service principal name. So for the purposes of trying out this tutorial, you could use your user name as both the client user name and the service principal name.

In a production environment, system administrators typically like servers to be run as specific principals only and may assign a particular name to be used. Often the Kerberos-style service principal name assigned is of the form

service_name/machine_name@realm;

For example, an nfs service run on a machine named "raven" in the realm named "KRBNT-OPERATIONS.ABC.COM" could have the service principal name

nfs/raven@KRBNT-OPERATIONS.ABC.COM

Such multi-component names are not required, however. Single-component names, just like those of user principals, can be used. For example, an installation might use the same ftp service principal ftp@realm for all ftp servers in that realm, while another installation might have different ftp principals for different ftp servers, such as ftp/host1@realm and ftp/host2@realm on machines host1 and host2, respectively.

When the Realm is Required in Principal Names

If the realm of a user or service principal name is the default realm (see Kerberos Requirements), you can leave off the realm when you are logging into Kerberos (that is, when you are prompted for your username). Thus, for example, if your user name is "mjones@KRBNT-OPERATIONS.ABC.COM", and you run SampleClient, when it requests your user name you could just specify "mjones", leaving off the realm. The name is interpreted in the context of being a Kerberos principal name and the default realm is appended, as needed.

You can also leave off the realm if a principal name will be converted to a GSSName by a GSSManager createName method. For example, when you run SampleClient, one of the arguments is the server service principal name. You can specify the name without including the realm, because SampleClient passes the name to such a createName method, which appends the default realm as needed.

It is recommended that you always include realms when principal names are used in login configuration files and policy files, because the behavior of the parsers for such files may be implementation-dependent; they may or may not append the default realm before such names are utilized and subsequent actions may fail if there is no realm in the name.

The Login Configuration File

For this tutorial, we are letting the underlying Kerberos mechanism obtain credentials of the users running SampleClient and SampleServer, rather than invoking JAAS methods directly (as in the JAAS Authentication and JAAS Authorization tutorials) or indirectly (for example, via the Login utility described in the Use of JAAS Login Utility tutorial and in the Use of JAAS Login Utility and Java GSS-API for Secure Message Exchanges tutorial).

The default Kerberos mechanism implementation supplied by Sun Microsystems actually prompts for a Kerberos name and password and authenticates the specified user (or service) to the Kerberos KDC. The mechanism relies on JAAS to perform this authentication.

JAAS supports a pluggable authentication framework, meaning that any type of authentication module can be plugged under a calling application. A login configuration specifies the login module to be used for a particular application. The default JAAS implementation from Sun Microsystems requires that the login configuration information be specified in a file. (Note: Some other vendors might not have file-based implementations.) See JAAS Login Configuration File for information as to what a login configuration file is, what it contains, and how to specify which login configuration file should be used.

For this tutorial, the Kerberos login module com.sun.security.auth.module.Krb5LoginModule is specified in the configuration file. This login module prompts for a Kerberos name and password and attempts to authenticate to the Kerberos KDC.

Both SampleClient and SampleServer can use the same login configuration file, if that file contains two entries, one entry for the client side and one for the server side.

The bcsLogin.conf login configuration file used for this tutorial is the following:

com.sun.security.jgss.initiate  {
  com.sun.security.auth.module.Krb5LoginModule required;
};

com.sun.security.jgss.accept  {
  com.sun.security.auth.module.Krb5LoginModule required storeKey=true
};

Entries with these two names (com.sun.security.jgss.initiate and com.sun.security.jgss.accept) are used by Sun implementations of GSS-API mechanisms when they need new credentials. Since the mechanism used in this tutorial is the Kerberos V5 mechanism, a Kerberos login module will need to be invoked in order to obtain these credentials. Thus we list Krb5LoginModule as a required module in these entries. The com.sun.security.jgss.initiate entry specifies the configuration for the client side and the com.sun.security.jgss.accept entry for the server side.

The Krb5LoginModule succeeds only if the attempt to log in to the Kerberos KDC as a specified entity is successful. When running SampleClient or SampleServer, the user will be prompted for a name and password.

The SampleServer entry storeKey=true indicates that a secret key should be calculated from the password provided during login and it should be stored in the private credentials of the Subject created as a result of login. This key is subsequently utilized during mutual authentication when establishing a security context between SampleClient and SampleServer.

For information about all the possible options that can be passed to Krb5LoginModule, see the Krb5LoginModule documentation.

The useSubjectCredsOnly System Property

For this tutorial, we set the system property javax.security.auth.useSubjectCredsOnly to false, which allows us to relax the usual restriction of requiring a GSS mechanism to obtain necessary credentials from an existing Subject, set up by JAAS. When this restriction is relaxed, it allows the mechanism to obtain credentials from some vendor-specific location. For example, some vendors might choose to use the operating system's cache if one exists, while others might choose to read from a protected file on disk.

When this restriction is relaxed, Sun Microsystem's Kerberos mechanism still looks for the credentials in the Subject associated with the thread's access control context, but if it doesn't find any there, it performs JAAS authentication using a Kerberos module to obtain new ones. The Kerberos module prompts you for a Kerberos principal name and password. Note that Kerberos mechanism implementations from other vendors may behave differently when this property is set to false. Consult their documentation to determine their implementation's behavior.

Running the SampleClient and SampleServer Programs

To execute the SampleClient and SampleServer programs, do the following:

  • Prepare SampleServer for Execution
  • Prepare SampleClient for Execution
  • Execute SampleServer
  • Execute SampleClient

Prepare SampleServer for Execution

To prepare SampleServer for execution, do the following:

  1. Copy the following files into a directory accessible by the machine on which you will run SampleServer:
    • The SampleServer.java source file.
    • The bcsLogin.conf login configuration file.
  2. Compile SampleServer.java:
    javac SampleServer.java

Prepare SampleClient for Execution

To prepare SampleClient for execution, do the following:

  1. Copy the following files into a directory accessible by the machine on which you will run SampleClient:
    • The SampleClient.java source file.
    • The bcsLogin.conf login configuration file.
  2. Compile SampleClient.java:
    javac SampleClient.java

Execute SampleServer

It is important to execute SampleServer before SampleClient because SampleClient will try to make a socket connection to SampleServer and that will fail if SampleServer is not yet running and accepting socket connections.

To execute SampleServer, be sure to run it on the machine it is expected to be run on. This machine name (host name) is specified as an argument to SampleClient. The service principal name appears in several places, including the login configuration file and the policy files.

Go to the directory in which you have prepared SampleServer for execution. Execute SampleServer, specifying

  • by -Djava.security.krb5.realm=<your_realm> that your Kerberos realm is the one specified. For example, if your realm is "KRBNT-OPERATIONS.ABC.COM" you'd put -Djava.security.krb5.realm=KRBNT-OPERATIONS.ABC.COM.
  • by -Djava.security.krb5.kdc=<your_kdc> that your Kerberos KDC is the one specified. For example, if your KDC is "samplekdc.abc.com" you'd put -Djava.security.krb5.kdc=samplekdc.abc.com.
  • by -Djavax.security.auth.useSubjectCredsOnly=false that the underlying mechanism can decide how to get credentials. See The useSubjectCredsOnly System Property.
  • by -Djava.security.auth.login.config=bcsLogin.conf that the login configuration file to be used is bcsLogin.conf.

The only argument required by SampleServer is one specifying the port number to be used for listening for client connections. Choose a high port number unlikely to be used for anything else. An example would be something like 4444.

Below is the full command to use for both Microsoft Windows and Unix systems.

Important: In this command, you must replace <port_number> with an appropriate port number, <your_realm> with your Kerberos realm, and <your_kdc> with your Kerberos KDC.

Here is the command:

java -Djava.security.krb5.realm=<your_realm>
 -Djava.security.krb5.kdc=<your_kdc>
 -Djavax.security.auth.useSubjectCredsOnly=false
 -Djava.security.auth.login.config=bcsLogin.conf
 SampleServer <port_number>

The full command should appear on one line (or, on UNIX systems, on multiple lines where each line but the last is terminated with " \" indicating that there is more to come). Multiple lines are used here just for legibility. Since this command is very long, you may need to place it in a .bat file (for Windows) or a .sh file (for UNIX) and then run that file to execute the command.

The SampleServer code will listen for socket connections on the specified port. When prompted, type the Kerberos name and password for the service principal. The underlying Kerberos authentication mechanism specified in the login configuration file will log the service principal into Kerberos.

For login troubleshooting suggestions, see Troubleshooting.

Execute SampleClient

To execute SampleClient, first go to the directory in which you have prepared SampleClient for execution. Execute SampleClient, specifying

  • by -Djava.security.krb5.realm=<your_realm> that your Kerberos realm is the one specified.
  • by -Djava.security.krb5.kdc=<your_kdc> that your Kerberos KDC is the one specified.
  • by -Djavax.security.auth.useSubjectCredsOnly=false that the underlying mechanism can decide how to get credentials.
  • by -Djava.security.auth.login.config=bcsLogin.conf that the login configuration file to be used is bcsLogin.conf.

The SampleClient arguments are (1) the Kerberos name of the service principal that represents SampleServer, (2) the name of the host (machine) on which SampleServer is running, and (3) the port number on which SampleServer is listening for client connections.

Below is the full command to use for both Windows and Unix systems.

Important: In this command, you must replace <service_principal>, <host>, <port_number>, <your_realm>, and <your_kdc> with appropriate values (and note that the port number must be the same as the port number passed as an argument to SampleServer). These values need not be placed in quotes.

Here is the command:

java -Djava.security.krb5.realm=<your_realm>
 -Djava.security.krb5.kdc=<your_kdc>
 -Djavax.security.auth.useSubjectCredsOnly=false
 -Djava.security.auth.login.config=bcsLogin.conf
 SampleClient <service_principal> <host> <port_number>

Type the full command on one line. Multiple lines are used here for legibility. As with the command for executing SampleServer, if the command is too long to type directly into your command window, place it in a .bat file (Windows) or a .sh file (UNIX) and then execute that file.

When prompted, type your Kerberos user name and password. The underlying Kerberos authentication mechanism specified in the login configuration file will log you into Kerberos. The SampleClient code requests a socket connection with SampleServer. Once SampleServer accepts the connection, SampleClient and SampleServer establish a shared context and then exchange messages as described in this tutorial.

For login troubleshooting suggestions, see Troubleshooting.

Tutorials Introduction and TOC
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Basics

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Basic Information

This section covers the following topics:

  • Basic Information
  • Supported Features
  • Version Information

Basic Information

Q: What is Java Plug-in Software?

A: Java Plug-in Software is a software product from Sun Microsystems, Inc., that allows enterprise web managers to direct Java applets and JavaBeansTM components on their intranet web pages to run using Sun's Java Runtime Environment (JRE). With the 1.4 release of Java Plug-in, it is also allows the conventional APPLET tag to direct Java applets to use Sun's JRE. This is especially useful in browser, such Internet Explorer 6, that do not support Java.

Q: For whom is Java Plug-in Software intended?

A: Java Plug-in Software is designed for enterprise customers who want to deploy Java SDK, Standard Edition based applets on their intranet web pages, and support Microsoft Windows-, Solaris-, and Linux-based browsers in their enterprise. With the 1.4 release, it is also designed for the consumer who wants to run Java applets on a web page.

Q: Is there documentation available for Java Plug-in Software?

A: To assist in your deployment of Java Plug-in Software, Sun has made available a variety of technical documentation. Documentation regarding the HTML specifications, using Java Plug-in Software in intranet environments, how proxy configuration works, how to script applets, and much more are available from the Java Plug-in Software documentation page. For the consumer-oriented product that uses conventional APPLET tag support, you may also want to visit the Get Java Technology page and see the documentation available there.

Q: What features does Java Plug-in Software offer?

A: Java Plug-in Software delivers several key capabilities to for users of Internet Explorer or Netscape's Navigator:

  • Full Java SDK, Standard Edition
  • Full Java CompatibleTM support
  • Future-ready architecture
  • Free public download and easy install
  • Free Java Plug-in Software

Q: What is the advantage of downloading and using Java Plug-in Software rather than the browser's default JavaTM virtual machine?

A: Using Java Plug-in Software allows enterprises and consumers to:

  1. Take full advantage of Java SDK, Standard Edition functionality such as JavaBeans, JNITM, and RMI today.
  2. Develop and deploy 100% Pure JavaSM applets on Internet Explorer and Netscape Navigator browsers, and be assured that they will run reliably and consistently in both browsers.
  3. Be assured that they will receive support for the latest releases of Sun's Java platform --including the high-performance Java HotSpotTM virtual machine--in Internet Explorer and Navigator as soon as Sun releases them.
  4. Run applets in web browsers that no longer support Java.

Q: Is Java Plug-in Software included in the Java Software Development Kit (SDK), Standard Edition?

A: Yes.

Q: Does Java Plug-in Software work on platforms other than Microsoft Windows or Solaris (for example, Mac OS, AIX, Linux, HP-UX, etc.) versions of IE or Navigator?

A: Sun has made Java Plug-in Software available for porting to all operating system providers. For information about support for Java Plug-in Software on other operating systems, contact the operating system provider.

Q: What information should I provide when reporting a bug to http://bugreport.sun.com/bugreport/

A: When reporting bugs against Java Plug-in Software, always include the following information:

  1. Operating system, including version number
  2. Web browser, including version number
  3. Complete output of the JavaTM Console window
  4. Network configuration information—proxy, special intranet environment, etc.
  5. Complete description of the failure/problem encountered. Include the steps required to reproduce the problem.

Supported Features

Q: Does Java Plug-in Software offer support for all the features in Java SDK, Standard Edition?

A: Yes. Java Plug-in Software uses the same JRE that users can download from Sun's web site today (see http://java.sun.com/j2se/).

Q: Is Java Plug-in Software fully compliant with the JCK (Java Compatibility Kit) test suite for Java SDK, Standard Edition?

A: Java Plug-in Software is fully compliant with the JCK test suite for Java SDK, Standard Edition.

Q: What browsers and operating systems does Java Plug-in support?

A: See Supported Operating Systems and Browsers.

Q: Does Java Plug-in Software support scripting?

A: Java Plug-in Software supports scripting of applets in Internet Explorer and Netscape 6. However, scripting is not available when using Java Plug-in Software in Navigator 4.

Q: Does Java Plug-in Software support signed applets?

A: Yes, Java Plug-in Software supports standard Java SDK, Standard Edition signed JARs and applets signed using Netscape signing tools. See the How to Sign Applets Using RSA-Signed Certificates for more details.

Q: Does Java Plug-in Software automatically recognize and use the proxy server configuration that the browser was using?

A: It can. There are in fact three options beginning with the 1.4 release. See Proxy Configuration for details.

Q: What protocol does Java Plug-in Software support over the proxy?

A: HTTP, HTTPS, FTP, Gopher, and SOCKS are supported.

Q: Does Java Plug-in Software support SSL?

A: Yes, SSL is supported through Java Secure Socket Extension (JSSE).

Q: Is there a way to pre-load Java Plug-in Software during the browser startup?

A: Internet Explorer and Netscape Navigator do not have mechanisms to support pre-loading Java Plug-in Software during startup. You can work around this limitation by providing your own startup page that launches a dummy applet using Java Plug-in Software.

Q: Can I set up Java Plug-in Software to download from an intranet web server (behind a firewall) rather than from Sun's web site?

A: Yes. For more information, see Intranet With OBJECT/EMBED Tag under Part II: Deployment Schemes.

Q: How can I open the Java Plug-in Control Panel on Microsoft Windows?

A: On the Start menu, choose Start>Settings>Control Panel, then double-click on the steaming Java cup icon labeled Java Plug-in.

Version Information

Q: How can I tell what version of Java Plug-in Software has been installed?

A: There are a couple of ways:

  • Check the version number in C:\Windows\Downloaded Program Files\Java Runtime Environment or C:\WINNT\Downloaded Program Files\
  • Open Netscape Navigator. Go to the Help>About Plugins. Check the MIME types listed under Java Plug-in. If the following exist:

    application/x-java-applet;version=1.4, you are using Java Plug-in Software 1.4

    application/x-java-applet;version=1.3, you are using Java Plug-in Software 1.3

    application/x-java-applet;version=1.2, you are using Java Plug-in Software 1.2

    application/x-java-applet;version=1.1.2, you are using Java Plug-in Software 1.1.2

    application/x-java-applet;version=1.1.1, you are using Java Plug-in Software 1.1.1

    application/x-java-applet;version=1.1, you are using Java Plug-in Software 1.1

    Note: You may see more than one if you have multiple versions of Java Plug-in installed.

Q: Can different versions of Java Plug-in Software co-exist on the same system?

A: Yes, it can be done through multi-version support. See Supporting Multiple Versions of JRE/Java Plug-in.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


BasicService (JNLP API Reference 1.7.0)

  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method
javax.jnlp

Interface BasicService

  • public interface BasicService
    The BasicService interface provides access to the codebase of the application, if an application is run in offline mode, and simple interaction with the native browser on the given platform.

    This interface mimics loosely the AppletContext functionality.

    Since:
    1.0

    • Method Summary

      Methods
      Modifier and Type Method and Description
      java.net.URL getCodeBase()
      Returns the codebase for the application.
      boolean isOffline()
      Determines if the system is offline.
      boolean isWebBrowserSupported()
      Checks if a Web browser is supported on the current platform and by the given JNLP Client.
      boolean showDocument(java.net.URL url)
      Directs a browser on the client to show the given URL.

    • Method Detail

      • getCodeBase

        java.net.URL getCodeBase()
        Returns the codebase for the application. The codebase is either specified directly in the JNLP file, or it is the location of the JAR file containing the main class of the application.
        Returns:
        a URL with the codebase of the application

      • isOffline

        boolean isOffline()
        Determines if the system is offline. The return value represents the JNLP client's "best guess" at the online / offline state of the client system. The return value is does not have to be guaranteed to be reliable, as it is sometimes difficult to ascertain the true online / offline state of a client system.
        Returns:
        true if the system is offline, otherwise false

      • showDocument

        boolean showDocument(java.net.URL url)
        Directs a browser on the client to show the given URL. This will typically replace the page currently being viewed in a browser with the given URL, or cause a browser to be launched that will show the given URL.
        Parameters:
        url - an URL giving the location of the document. A relative URL will be relative to the codebase.
        Returns:
        true if the request succeded, otherwise false

      • isWebBrowserSupported

        boolean isWebBrowserSupported()
        Checks if a Web browser is supported on the current platform and by the given JNLP Client. If this is not the case, then showDocument(java.net.URL) will always return false.
        Returns:
        true if a Web browser is supported, otherwise false
  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.


Extensible Runtime Containment and Services Protocol for JavaBeans Version 1.0

1.0 Introduction.

Currently the JavaBeans specification (Version 1.0) contains neither conventions describing a hierarchy or logical structure of JavaBeans, nor conventions for those JavaBeans to rendezvous with, or obtain arbitrary services or facilities from, the execution environment within which the JavaBean was instantiated.

It is desirable to both provide a logical, traversable, hierarchy of JavaBeans, and further to provide a general mechanism whereby an object instantiating an arbitrary JavaBean can offer that JavaBean a variety of services, or interpose itself between the underlying system service and the JavaBean, in a conventional fashion.

In other component models there exists the concept of a relationship between a Component and its environment, or Container, wherein a newly instantiated Component is provided with a reference to its Container or Embedding Context.

The Container, or Embedding Context not only establishes the hierarchy or logical structure, but its also acts as a service provider that Components may interrogate in order to determine, and subsequently employ, the services provided by their Context.

This proposal defines such a protocol that supports extensible mechanisms that:

  • Introduce an abstraction for the environment, or context, in which a JavaBean logically functions during its lifecycle, that is a hierarchy or structure of JavaBeans.
  • Enable the dynamic addition of arbitrary services to a JavaBean’s environment.
  • Provide a single service discovery mechanism through which JavaBeans may interrogate their environment in order both to ascertain the availability of particular services and to subsequently employ those services.
  • Provide a simple mechanism to propagate an Environment to a JavaBean.
  • Provide better support for JavaBeans that are also Applets.
graphic representation of previous list points

2.0 API Specification

2.1 interface java.beans.beancontext.BeanContext

The hierarchal structure and general facilities of a BeanContext are provided for as follows:

public interface                java.beans.beancontext.BeanContext
           extends              java.beans.beancontext.BeanContextChild,
                      java.util.Collection,
                         java.beans.DesignMode,
                         java.beans.Visibility {

        Object instantiateChild(String beanName)
                  throws IOException, ClassNotFoundException;

        public InputStream
                getResourceAsStream(String           name,
                                    BeanContextChild requestor
                );

        public java.net.URL
                getResource(String           name,
                            BeanContextChild requestor
                );

        void addBeanContextMembershipListener(
                   BeanContextMembershipListener bcml
          );

        void removeBeanContextMembershipListener{
                    BeanContextMembershipListener bcml
        );

        public static final Object globalHierarchyLock;
}

Notifications of changes in the membership of a BeanContext are modeled as follows:

public interface BeanContextMembershipListener
          extends   java.util.Listener {
        void childrenAdded(BeanContextMembershipEvent   bcme);
        void childrenRemoved(BeanContextMembershipEvent bcme);
}

The base class of all BeanContext related Events is defined by:

public abstract class BeanContextEvent
          extends  java.util.EventObject {
        public BeanContext getBeanContext();

        public synchronized void
                setPropagatedFrom(BeanContext bc);

        public synchronized BeanContext getPropagatedFrom();

        public synchronized boolean isPropagated()
}

The BeanContextMembershipEvent is defined as:

public class BeanContextMembershipEvent
          extends BeanContextEvent {

        public BeanContextMembershipEvent(BeanContext bc,
                                          Object[]    deltas);

        public BeanContextMembershipEvent(BeanContext bc,
                                          Collection     deltas);

        public int size();

        public boolean contains(Object child);

        public Object[] toArray();

        public Iterator iterator();
}

2.1.1 The BeanContext as a participant in nested structure

One of the roles of the BeanContext is to introduce the notion of a hierarchical nesting or structure of BeanContext and JavaBean instances. In order to model this structure the BeanContext must expose API that defines the relationships in the structure or hierarchy.

The BeanContext exposes its superstructure through implementation of the java.beans.beancontext.BeanContextChild interface (as described later). This interface allows the discovery and manipulation of a BeanContext’s nesting BeanContext, and thus introduces a facility to create a hierarchy of BeanContexts.

The BeanContext exposes its substructure through a number of interface methods modeled by the java.util.Collection interface semantics

BeanContexts are required to implement all the mandatory Collection API’s, with the following particular semantics for add() and remove():.

The add() method may be invoked in order to nest a new Object, BeanContextChild, or BeanContext within the target BeanContext. A conformant add() implementation is required to adhere to the following semantics:

  • Synchronize on the BeanContext.globalHierarchyLock.
  • Each child object shall appear only once in the set of children for a given BeanContext. If the instance is already a member of the BeanContext then the method shall return False.
  • Each valid child shall be added to the set of children of a given source BeanContext, and thus shall appear in the set of children, obtained through either the toArray(), or iterator() methods, until such time as that child is deleted from the nesting BeanContext via an invocation of remove(), removeAll(), retainAll(), or clear()
  • As the child is added to the set of nested children, and where that child implements the java.beans.beancontext.BeanContextChild interface (or BeanContextProxy, see later for details), the BeanContext shall invoke the setBeanContext() method upon that child, with a reference to itself. Upon invocation, a child may, if it is for some reason unable or unprepared to function in that BeanContext, throw a PropertyVetoException to notify the nesting BeanContext. If the child throws such an exception the BeanContext shall revoke the addition of the child (and any other partial changes made to the state of the BeanContext as a side effect of this addition operation) to the set of nested children and throw an IllegalStateException.
  • JavaBeans that implement the java.beans.Visibility interface shall be notified via the appropriate method, either dontUseGui() or okToUseGui(), of their current ability to render GUI as defined the policy of the BeanContext.
  • If the newly added child implements BeanContextChild, the BeanContext shall register itself with the child on both its VetoableChangeListener and PropertyChangeListener interfaces to monitor, at least, that BeanContextChild’s “beanContext” property.

By doing so the BeanContext can monitor its child and can detect when such children are removed by a 3rd party (usually another BeanContext) invoking setBeanContext(). A BeanContext may veto such a change by a 3rd party if it determines that the child is not in a state to depart membership at that time.

  • If the JavaBean(s) added implement Listener interfaces that the BeanContext is a source for, then the BeanContext may register the newly added objects via the appropriate Listener registration methods as a permissible side effect of nesting.
  • If the JavaBean(s) added are Event Sources for Event that a particular BeanContext has interest in the BeanContext may, as a side effect of adding the child, register Listeners on that child. The BeanContext should avoid using Serializable Listeners thus avoiding accidental serialization of unwanted structure when a child serializes itself.
  • Once the targetChild has been successfully processed, the BeanContext shall fire a java.beans.beancontext.BeanContextMembershipEvent, containing a reference to the newly added targetChild, to the childrenAdded() method of all the BeanContextMemebrshipListeners currently registered.
  • The method shall return true if successful.

The remove() method may be invoked in order to remove an existing child JavaBean or BeanContext from within the target BeanContext. A conformant remove() implementation is required to adhere to the following semantics:

  • Synchronize with the BeanContext.globalHierarchyLock.
  • If a particular child is not present in the set of children for the source BeanContext, the method shall return False.
  • Remove the valid targetChild from the set of children for the source BeanContext, also removing that child from any other Listener interfaces that it was implicitly registered on, for that BeanContext as a side-effect of nesting.

Subsequently, if the targetChild implements the java.beans.beancontext.BeanContextChild interface (or BeanContextProxy, see later for deatils), the BeanContext shall invoke the setBeanContext() with a null1 BeanContext value, in order to notify that child that it is no longer nested within the BeanContext.

If a particular BeanContextChild is in a state where it is not able to be un-nested from its nesting BeanContext it may throw a PropertyVetoException, upon receipt of this the BeanContext shall revoke the remove operation for this instance and throw IllegalStateException. To avoid infinite recursion, children are not permitted to repeatedly veto subsequent remove notifications. In practice, a child should attempt to resolve the condition (if temporary) that precludes it’s removal from it’s current nesting BeanContext.

  • If the targetChild implements java.beans.beancontext.BeanContextChild then the BeanContext shall de-register itself from that child’s PropertyChangeListener and VetoableChangeListener sources.
  • If the BeanContext had previously registered the object(s) removed as Listeners on events sources implemented by the BeanContext as a side effect of nesting those objects, then the BeanContext shall de-register the newly removed object from the applicable source(s) via the appropriate Listener de-registration method(s)
  • If the BeanContext had previously registered Listener(s) on the object(s) removed then the BeanContext shall remove those Listener(s) from those object(s).
  • Once the targetChild has been removed from the set of children, the BeanContext shall fire a java.beans.beancontext.BeanContextMembershipEvent, containing a reference to the targetChild just removed, to the childrenRemoved() method of all the BeanContextMembershipListeners currently registered.
  • Finally the method shall return the value true if successful.

Note that the lifetime of any child of a nesting BeanContext, is at least for the duration of that child’s containment within a given BeanContext. For simple JavaBeans that are not aware of their containment within a BeanContext, this usually implies that the JavaBean shall exist for at least the lifetime of the nesting BeanContext.

BeanContext’s are not required to implement either addAll(), removeAll(), retainAll() or clear() optional methods defined by java.util.Collection API, however if they do they must implement the semantics defined, per object, for both add() and remove() above. In the failure cases these methods shall revoke any partially applied changes to return the BeanContext to the state it was in prior to the failing composite operation being invoked, no BeanContextEvents shall be fired in the failure case as is consistent with the definition of add() and remove() above.

BeanContextMembershipListeners may be added and removed via invocations of addBeanContextMembershipListener() and removeBeanContextMembershipListener().

The toArray(), method shall return a copy of the current set of JavaBean or BeanContext instances nested within the target BeanContext, and the iterator() method shall supply a java.util.Iterator object over the same set of children.

The contains() method shall return true if the object specified is currently a child of the BeanContext.

The size() method returns the current number of children nested.

The isEmpty() method returns true if the BeanContext has no children.

Note that all the Collection methods all require proper synchronization between each other by a given implementation in order to function correctly in a multi-threaded environment, that is, to ensure that any changes to the membership of the set of JavaBeans nested within a given BeanContext are applied atomically. All implementations are required to synchronized their implementations of these methods with the BeanContext.globalHierarchyLock.

In some situations, add() and remove() (or a variant thereof) operations may occur nested, that is multiple occurrences may appear on the stack of the calling Thread simultaneously, e.g: when BeanContextChild, A, is added (or removed), it’s setBeanContext() method also adds (or removes) another BeanContextChild, B. A particular BeanContext implementation may choose to fire either two BeanContextMembershipListener notifications, one for each add()/remove() operation of B then A (in this order since B is successfully added before A), or coalesce these into a single notification containing both A, and B. Note that should A be unable to be added or removed for any reason it shall not perform, or undo, any add or remove operations upon B as a side-effect, prior to throwing a PropertyVetoException to indicate this condition, that is, it must avoid or undo any side-effect membership changes prior to rejecting any changes to its own membership status.

The instantiateChild() method is a convenience method that may be invoked to instantiate a new JavaBean instance as a child of the target BeanContext. The implementation of the JavaBean is derived from the value of the beanName actual parameter, and is defined by the java.beans.Beans.instantiate() method.

Typically, this shall be implemented by calling the appropriate java.beans.Beans.instantiate() method, using the ClassLoader of the target BeanContext. However a particular BeanContext implementation may interpose side-effects on the instantiate operation in their implementation of this method.

The BeanContextEvent is the abstract root EventObject class for all Events pertaining to changes in state of a BeanContext’s defined semantics. This abstract root class defines the BeanContext that is the source of the notification, and also introduces a mechanism to allow the propagation of BeanContextEvent subclasses through a hierarchy of BeanContexts. The setPropagatedFrom() and getPropagatedFrom() methods allows a BeanContext to identify itself as the source of a propagated Event to the BeanContext to which it subsequently propagates the Event to. This is a general propagation mechanism and should be used with care as it has significant performance implications when propagated through large hierarchies.

The BeanContextMembershipEvent describes changes that occur in the membership of a particular BeanContext instance. This event encapsulates the list of children either added to, or removed from, the membership of a particular BeanContext instance, i.e the delta in the membership set.

Whenever a successful add(), remove(), addAll(), retainAll(), removeAll(), or clear() is invoked upon a particular BeanContext instance, a BeanContextMembershipEvent is fired describing the children effected by the operation.

2.1.2 Resources.

The BeanContext defines two methods; getResourceAsStream() and getResource() which are analogous to those methods found on java.lang.ClassLoader. BeanContextChild instances nested within a BeanContext shall invoke the methods on their nesting BeanContext in preference for those on ClassLoader, to allow a BeanContext implementation to augment the semantics by interposing behavior between the child and the underlying ClassLoader semantics.

2.1.3 The BeanContext as a Service Provider

The service facilities of a BeanContext are provided as follows:

public interface BeanContextServices
          extends   BeanContext,BeanContextServicesListener {

        boolean addService(Class           serviceClass,
                           BeanContextServiceProvider service);

        boolean revokeService(Class           serviceClass,
                              BeanContextServiceProvider bcsp,
                              boolean         revokeNow
        );

        boolean hasService(Class serviceClass);

        Object getService(BeanContextChild      bcc,
                          Object                requestor.
                          Class                 serviceClass,
                          Object                serviceSelector,
                          BeanContextServicesRevokedListener sl
        ) throws TooManyListenersException;

        void releaseService(BeanContextChild bcc,
                            Object           requestor,
                            Object           service);

        Iterator getCurrentServiceClasses();

        public Iterator getCurrentServiceSelectors(Class sc);

        addBeanContextServicesListener(
                BeanContextServicesListener bcsl
        );

        removeBeanContextServicesListener(
                BeanContextServicesListener bcsl
     );
}

The BeanContextServiceProvider interface is defined as follows:

public interface BeanContextServiceProvider {
        Object getService(BeanContext bc,
                          Object      requestor,
                          Class       serviceCls,
                          Object      serviceSelector);

        void releaseService(BeanContext bc,
                            Object      requestor,
                            Object      service);

        Iterator getCurrentServiceSelectors(BeanContext bc,
                                            Class serviceCls);
}

The BeanContextServiceRevokedListener is defined as follows:

public interface BeanContextServiceRevokedListener
          extends java.util.EventListener {
        void serviceRevoked(
                BeanContextServiceRevokedEvent bcsre
        );
}

The BeanContextServicesListener is defined as follows:

public interface BeanContextServicesListener
          extends BeanContextServiceRevokedListener {
        void serviceAvailable(
                BeanContextServiceAvailableEvent bcsae
        );
}

The BeanContextServiceAvailableEvent is defined as follows:

public class BeanContextServiceAvailableEvent
          extends BeanContextEvent {

        public BeanContextServiceAvailableEvent(
                        BeanContextServices        bcs,
                        Class                      sc
     );

        BeanContextServices getSourceAsBeanContextServices();

        public Class getServiceClass();

        public boolean isServiceClass(Class serviceClass);

        public Iterator getCurrentServiceSelectors();
}

The BeanContextServiceRevokedEvent is defined as follows:

public class BeanContextServiceRevokedEvent
          extends BeanContextEvent {
        public BeanContextServiceRevokedEvent(
                                BeanContextServices        bcs,
                                Class                      sc,
                             boolean                    invalidNow
        );
        public BeanContextServices
                        getSourceAsBeanContextServices();

        public Class getServiceClass();

        public boolean isServiceClass(Class service);

        public boolean isCurrentServiceInvalidNow();
}

The BeanContextServiceProviderBeanInfo is defined as follows:

public interface BeanContextServicesProviderBeanInfo
       extends   java.beans.BeanInfo {
    java.beans.BeanInfo[] getServicesBeanInfo();
}

Apart from providing a structured hierarchy, the other major role of a BeanContext is to provide a standard mechanism for a JavaBean component to obtain context-specific facilities or services from its environment.

A service, represented by a Class object, is typically a reference to either an interface, or to an implementation that is not publicly instantiable. This Class defines an interface protocol or contract between a BeanContextServiceProvider, the factory of the service, and an arbitrary object associated with a BeanContextChild that is currently nested within the BeanContext the service is registered with. Typically such protocols encapsulate some context specific or sensitive behavior that isolates a BeanContextChild’s implementation from such dependencies thus resulting in simpler implementations, greater interoperability and portability.

A BeanContextServiceProvider, is a “factory” for one or more services. It registers itself with a particular BeanContextServices via it’s adService() method, if the service is not already registered with the BeanContextServices, the BeanContextServices associates the service specified with the BeanContextServiceProvider, and fires a BeanContextServiceAvailableEvent via the serviceAvailable() method to those BeanContextServicesListeners currently registered, then returns true, otherwise false indicating that the service is already registered for that BeanContextServices.

Once registered, and until revoked, the service is available via the BeanContextServices getService() method.

The hasService() method may be used to test the presence of a particular service, and the getCurrentServices() method returns an iterator over the currently available services for that BeanContextServices.

A BeanContextChild or any arbitrary object associated with a BeanContextChild, may obtain a reference to a currently registered service from its nesting BeanContextServices via an invocation of the getService() method. The getService() method specifies; the BeanContextChild, the associated requestor, the Class of the service requested, a service dependent parameter (known as a Service Selector), and a BeanContextServicesRevokedListener used to subsequently notify the requestor that the service class has been revoked by the BeanContextServiceProvider. The Listener is registered automatically with a unicast event source per requestor and service class and is automatically unregistered when a requestor relinquishes all references of a given service class, or as a side effect of the service being “forcibly revoked” by the providing BeanContextServiceProvider.

The BeanContextServices passes this getService() invocation onto the associated BeanContextServiceProvider (if any) to be satisfied via an invocation of its getService() method. The BeanContextServiceProvider is passed the BeanContext, the Class of the service provided, the service dependent service parameter (the Service Selector) and a reference to the object requesting the service.

The reference to the BeanContext is intended to enable the BeanContextServiceProvider to distinguish service requests from multiple sources. A BeanContextServiceProvider is only permitted to retain a weak reference to any BeanContext so obtained.

The Service Selector parameter is a service dependent value used by a service requestor for a particular service in order to parameterize the service to be provided to it by the BeanContextServiceProvider. Some examples of its usage are; a parameter to a constructor for the service implementation class; a value for a particular service’s property, or as a key into a map of existing implementations.

The reference to the requestor is intended to permit the BeanContextServiceProvider to interrogate the state of the requestor in order to perform any customization or parameterization of the service, therefore this reference shall be treated as immutable by the BeanContextServicesProvider. Additionally the BeanContextServiceProvider is permitted to retain only weak and immutable reference to both the requestor and the BeanContextChild after returning from the getService() invocation.

The BeanContextServiceProvider may satisfy the request, returning a reference to an instance of the Class of the requested service (such that the reference returned shall result in the expression: <serviceRefence> instanceof <serviceClass> being true), return null, or throw an unchecked exception.

In the case when a nested BeanContextServices is requested for a particular service that it has no BeanContextServiceProvider for, then the BeanContextServices may delegate the service requested to its own nesting BeanContextServices in order to be satisfied. Thus delegation requests can propagate from the leaf BeanContextServices to the root BeanContextServices.

A BeanContextChild may query a particular BeanContextServices for a list of currently available Service Classes (via the getCurrentServiceClasses() method)and any associated Service Selectors, if a particular service Class implements a finite list of apriori values for a Service Class, via its nesting BeanContextServices.getCurrentServiceSelectors() method, which in turn obtains the currently available Service Selectors (if any) via the BeanContextServiceProvider.getCurrentServiceSelectors() method.

If the service in question does not implement a finite set of apriori values for the set of valid Service Selectors it shall return null.

A reference obtained by a BeanContextChild via getService() is valid until the reference is released by the BeanContextChild via an invocation of its nesting BeanContextServices releaseService() method, except in the case where the BeanContextServices fires a BeanContextServiceRevokedEvent and that Event’s isCurrentServiceInvalidNow() method returns true, in this case the BeanContextServices and/or the BeanContextServiceProvider that provided the service has determined that current service references are immediately invalidated, or “forcibly revoked” (this typically occurs in the following situation).

When BeanContextChild instances are removed from a particular BeanContextServices instance, they shall discard all references to any services they obtained from that BeanContextServices by appropriate invocations of releaseService(). If the un-nesting BeanContextChild is also a BeanContextServices instance, and if any of these service references have been exposed to the un-nesting BeanContextServices’s own members as a result of a delegated getService() request as defined above, the BeanContextServiecs shall fire a BeanContextServiceRevokedEvent to notify its nested children that the service(s) are “forcibly revoked”. This immediate invalidation of current references to delegated services at un-nesting is to ensure that services that are dependent upon the structure of the hierarchy are not used by requestors after their location in the structure has changed.

BeanContextChild instances receiving a “forcable revocation” of a Service Class shall not invoke releaseService() for any references it may hold of that type, since in this case, the BeanContextServiceProvider or the BeanContextServices that provided the service reference to that BeanContextChild has already invalidated all references to that service on their behalf.

A BeanContextServiceProvider may revoke a Service Class at any time after it has registered it with a BeanContextServices by invoking its revokeService() method. Once the BeanContextServices has fired a BeanContextServiceRevokedEvent notifying the currently registered BeanContextServiceRevokedListeners and the BeanContextServicesListeners that the service is now unavailable it shall no longer satisfy any new service requests for the revoked service until (if at all) that Service Class is re-registered. References obtained by BeanContextChild requestors to a service prior to its being revoked remain valid, and therefore the service shall remain valid to satisfy those extant references, until all references to that service are released, unless in exceptional circumstances the BeanContextServiceProvider, or BeanContextServices, when revoking the service, wants to immediately terminate service to all the current references. This immediate revocation is achieved by invoking the BeanContextServices .revokeService() method with an actual parameter value of revokeNow == true. Subsequent to immediate invalidation of current service references the service implementation may throw a service specific unchecked exception in response to any attempts to continue to use the revoked service by service requestors that have erroneously retained references to the service, ignoring the earlier immediate revocation notification.

Note that in order to function correctly (when delegating service requests) in a multi-threaded environment, implementations of BeanContextServices are required to synchronize their implementations of; addService(), hasService(), getCurrentServiceClasses(), getCurrentServiceSelectors(), getService(), releaseService() and revokeService() with the BeanContext.globalHierarhyLock.

A BeanContextServicesProvider may expose the BeanInfo for the Service Classes it provides implementations for by providing a BeanInfo class that implements BeanContextServicesProviderBeanInfo. Thus exposing an array of BeanInfo’s, one for each Service Class supported. Builder tools can, for example, use this infomation to provide application developers with a palette of Servlice Classes for inclusion in an application.

2.1.4 The role of a BeanContext in Persistence

Since one of the primary roles of a BeanContext is to represent a logical nested structure of JavaBean component and BeanContext instance hierarchies, it is natural to expect that in many scenarios that hierarchy should be persistent, i.e that the BeanContext should participate in persistence mechanisms, in particular, either java.io.Serializable or java.io.Externalizable (If the latter the BeanContext is responsible for acting as the persistence container for the sub-graph of children, encoding and decoding the class information, and maintaining sub-graph equivalence after deserialization, basically the function(s) provide for serialization by ObjectOutputStream and ObjectInputStream).

In particular BeanContexts shall persist and restore their current children that implement the appropriate persistence interfaces when they themselves are made persistent or subsequently restored.

As a result of the above requirement, persistent BeanContextChild implementations are required to not persist any references to either their nesting BeanContext, or to any Delegates obtained via its nesting BeanContextServices.

BeanContexts shall, when restoring an instance of BeanContextChild from its persistence state, be required to perform the equivalent of invoking add()on the newly instantiated BeanContextChild,, in order to notify the newly restored instance of its nesting BeanContext, thus allowing that BeanContextChild to fully reestablish its dependencies on its environment.

Also note that since BeanContext implements java.beans.beancontext.BeanContextChild it shall obey the persistence requirements defined below for implementors of that interface.

2.1.5 BeanContext with associated presentation hierarchies

Although not required, many BeanContexts may be associated within a presentation hierarchy of java.awt.Containers and java.awt.Components. A Container cannot implement BeanContext directly2 but may be associated with one by implementing the BeanContextProxy interface described herein.

public interface BeanContextProxy {
    BeanContext getBeanContext();
}

For instances of classes that do not (or cannot in the case of Component or subclasses thereof) directly implement the BeanContext interface, but are associated with an instance of such an implementation, (via delegation) such instances may expose this association by implementing the BeanContextProxy interface. By doing so, this enables arbitrary 3rd parties, such as builder tools, to interrogate and discover the BeanContext associated with such objects for the purposes of either nesting objects within that associated BeanContext, observing changes in the membership, or obtaining services thereof.

This also permits multiple distinct objects (e.g: Containers) to share a single BeanContext. [Note though that in this case a shared BeanContext shall not implement BeanContextContainerProxy since that is a peer-to-peer relationship between a single BeanContext and the Container implementing that interface]

The value returned from getBeanContext() is constant for the lifetime of the implementing instance, that is the relationship between a BeanContextProxy and it’s associated BeanContext is static and thus may not change for the lifetime of either participant.

No class may implement both the BeanContext (or BeanContextChild) and the BeanContextProxy interfaces, they are mutually exclusive.

Some BeanContextProxy implementors may also implement java.util.Collection, or some other collection-like API (e.g java.awt.Container), in addition to, and possibly distinct from, maintaining a BeanContext based Collection.

In such cases it is possible to add, or remove, elements from either the BeanContext, via it’s Collection API’s, or the BeanContextProxy implementor using it’s own collection-like API’s (e.g: public boolean java.awt.Container.add(Component)). It is implementation dependent whether or not objects added or removed from either the BeanContext’s Collection, or the BeanContextProxy implementor’s collection are also added or removed from the corresponding object’s collection (i.e: should a Container.add() also infer a BeanContext.add() and vica-versa?). In such situations both participants (the implementor of BeanContextProxy and the BeanContext itself) are required to; 1) implement the same add/remove semantics as the other (i.e: if x.add(o) has a side effect of x.getBeanContext().add(o) then x.getBeanContext().add(o) should also a have side effect of x.add(o)), and 2) before adding/removing an object to/from the other participants collection, it should test (synchronized) if that object is/is not a member of the other participants collection before proceeding with the operation in question (this is to avoid infinite recursion between collection operations on both participants) (i.e: x.add(o) should not invoke x.getBeanContext().add(o) if x.getBeanContext().contains(o) is true and vica-versa).

It is important to note that if an object that implements BeanContextProxy is added to , or removed from, a BeanContext, that in addition to the operation performed on that object, the same operation should be performed on the BeanContext returned from BeanContextProxy.getBeanContext(). That is an implementor of BeanContextProxy shall be treated as though it directly implemented BeanContext by any nesting BeanContext. (and vica-versa if the operation is applied to the BeanContext its shall also be applied to the corresponding BeanContextProxy)

The following interface is defined to allow a BeanContext to expose a reference to an associated Container to enable it’s BeanContextChild members to add, or remove, their associated Component objects to/from that Container or to inspect some state on the Container.

public interface BeanContextContainerProxy {
        Container getContainer()
}

When a BeanContextChild with an associated Component is added to a BeanContext with an associated Container there are three models of interaction that can occur in relation to the nesting of the Component in the Container as a result:

  • If the associated Component was added to the associated Container via a Container API, then the nesting of the BeanContextChild in the BeanContext is a side effect of that and no further action is required.
  • If the Component and Container are not nested then the nesting BeanContext may as a side effect cause the Component associated with the BeanContextChild to be added to it’s associated Container.

OR

  • If the Component and Container are not nested then the BeanContextChild being nested may as a side effect may cause it’s Component to be associated with the Container associated with the nesting BeanContext.

Thus, for greatest interoperability a BeanContextChild shall always check if its Compoent’s parent is the BeanContext Container, and if it is not, then it may add itself if appropriate. Thus a BeanContextChild may function correctly under all scenarios.

The BeanContextChild is responsible for initially causing itself to eligible to be displayed via an invocation of show() [note that the BeanContextChild may also subsequently repeatedly hide() and show() itself].

The nesting BeanContext, or its associated Container, may subsequently hide() or show() the BeanContextChild’s Component arbitrarily, but it is strongly recommended that it treat that Component as immutable in all other respects with the exception of registering Listeners to obtain event notifications, or where other Component/Container specific protocols permit or require the Container to alter the state of its Component containees. An example of such a permitted interaction would be where a property such as background or foreground color were propagated from Container to Component.

Once a BeanContextChild has been un-nested from it’s BeanContext, it’s associated Component (if any) shall be removed from that BeanContext’s Container as a side effect of the removal operation, this is the responsibility of the BeanContext (typically if the BeanContextChild has been moved to another BeanContext with an associated Container via an invocation of it’s setBeanContext() method, the Component will already have been re-parented as a side effect of that operation by the time the original BeanContext is notified of the change via a PropertyChangeEvent from the child, however the check should be made and the Component removed if it has not already occurred).

To avoid infinite recursion, both a BeanContext and a BeanContextChild that also are associated with a Container and Component nesting relationship should avoid undoing any changes applied to the Component by the other party in the relationship. In general the BeanContext is responsible for the appearance, visibility and relative layout of the BeanContextChild’s Component, and the BeanContextChild is responsible for the Component’s state and content pertaining to the application functionality it is implementing.

The value returned from the getContainer() method is constant for the lifetime of the implementing BeanContext, that is the relationship between a BeanContext and a Container is static for the lifetime of both participants.

In addition the following interface is also defined:

public interface BeanContextChildComponentProxy {
    Component getComponent();
}

A BeanContext or a BeanContextChild may implement this interface to expose the GUI Component that it is associated with to it’s nesting BeanContext. A BeanContext may use this method to establish the relationship between references to instances of Component and BeanContextChild that are known to it, where a BeanContextChild and Component are not implemented by the same object instance (that is the BeanContextChild delegates its Component implementation to a distinct object rather than inheriting from Component]. A BeanContext may interrogate the Component reference it obtains from a nested BeanContextChild in order to determine its state, and it may also register Listeners for particular events, however it is strongly recommended that the BeanContext treat the reference as generally immutable to avoid changing the Component state.

The value returned from the getComponent() method is a constant for the lifetime of that BeanContextChild.

In the situation where a BeanContext has an associated Container, but does not wish to expose that Container by implementing the BeanContextContainerProxy interface, but wishes to handle the nesting of an arbitrary BeanContextChild’s associated Component (exposed by the BeanContextChild either implementing the BeanContextChildComponentProxy interface or as direct subclass of Component) the BeanContext is permitted to add/remove that Component to/from its associated Container.In such cases the BeanContextChild and it’s associated Component implementation shall not interfere with this action.

If a class implements both BeanContextChildComponentProxy and BeanContextContainerProxy then the object returned by both getComponent() and getContainer() shall be the same object.

2.2 interface java.beans.beancontext.BeanContextChild3

Simple JavaBeans that do not require any support or knowledge of their environment shall continue to function as they do today. However both JavaBeans that wish to utilize their containing BeanContext, and BeanContexts that may be nested, require to implement a mechanism that enables the propagation of the reference to the enclosing BeanContext through to cognizant JavaBeans and nested BeanContexts, the interface proposed is:

public interface java.beans.beancontext.BeanContextChild {
        void        setBeanContext(BeanContext bc)
                                throws PropertyVetoException;

        BeanContext getBeanContext();

        void addPropertyChangeListener
                (String name, PropertyChangeListener pcl);

     void removePropertyChangeListener
                (String name, PropertyChangeListener pcl);

        void addVetoableChangeListener
                (String name, VetoableChangeListener pcl);

     void removeVetoableChangeListener
                (String name, VetoableChangeListener pcl);

}

The expected usage is that some 3rd party shall invoke one of the appropriate methods defined on BeanContext (by virtue of its inheritance from Collection) in order to add a BeanContextChild to the membership of the target BeanContext. As a consequence the BeanContext shall attempt to set the BeanContextChild’s “beanContext” property by invoking its setter method, setBeanContext(). Only a BeanContext may call a BeanContextChild’s setBeanContext() method, since this is the mechanism that a BeanContext uses to notify a child that it is now has a new BeanContext value. Since this property is not directly settable or customizable by a user in the context of an application construction tool the BeanInfo for a BeanContextChild should set the hidden state for this property in order for builder tools to avoid presenting the property to the user for customization.

A BeanContextChild object may throw a PropertyVetoException, to notify the nesting BeanContext that it is unable to function/be nested within that particular BeanContext. Such a veto shall be interpreted by a BeanContext as an indication that the BeanContextChild has determined that it is unable to function in that particular BeanContext and is final.

During the un-nesting of a BeanContextChild from its BeanContext, it is possible for the child, or a 3rd party listening to the child’s “beanContext” property for PropertyVetoEvents, to throw a PropertyVetoException to notify the caller that it is not in a state to be un-nested. In order to bound this interaction a BeanContextChild, or 3rd party, may veto the initial un-nesting notification, but may not veto any subsequent notifications, and must, upon receipt of such notifications, amend its state accordingly to prepare itself to be subsequently un-nested.

Note that classes that implement this interface, also act as an Event Source for (sub)interface(s) of java.beans.PropertyChangeListener, and are required to update their state accordingly and subsequently fire the appropriate java.beans.PropertyChangeEvent with propertyName = “beanContext”, oldValue = the reference to the previous nesting BeanContext, and newValue = the reference to the new nesting BeanContext, to notify any Listeners that its nesting BeanContext has changed value.

BeanContextChild instances, or nested BeanContexts in the process of terminating themselves, shall invoke the remove() method on their nesting BeanContext in order to withdraw themselves from the hierarchy prior to termination.

2.2.1 Important Persistence considerations

Instances of BeanContextChild nested within an BeanContext, will typically define fields or instance variables that will contain references to their nesting BeanContext instance, and possibly services obtained from that BeanContextServices instance via its getService() method.

In order to ensure that the act of making such an instance persistent does not erroneously persist objects from the instances nesting environment, such instances shall be required to define such fields, or instance variables as either transient, or to implement custom persistence methods that avoid persisting such state.

This requirement is crucial since operations such as cutting and pasting object instances through a clipboard via object serialization will not function correctly if the act of serializing the target object also serializes much of the entire source environment it is nested within.

3.0 Overloading java.beans.instantiate() static method

Since java.beans.instantiate() is the current mechanism for (re)instantiating JavaBeans we need to extend or overload the syntax and semantics of this method in order to accommodate the introduction of the BeanContext abstraction. The extension proposed is:

public static Object instantiate(ClassLoader cl,
                                                String        beanName,
                                                BeanContext beanContext);

This method behaves has it is currently defined in the JavaBeans specification, but in addition to these existing semantics, when a non-null BeanContext is specified then the method invokes the add() method on the beanContext actual parameter with the value of the targetChild actual parameter = a reference to the newly instantiated JavaBean component.4

4.0 Providing better support for Beans that are also Applets

The current implementation of java.beans.instantiate() contains minimal support for instantiating JavaBeans that are also Applets. In particular, this method will currently construct an AppletContext and AppletStub for the newly instantiated JavaBean, set the stub on the newly instantiated Applet, and init() the Applet if it has not already been invoked.

Unfortunately this does not provide sufficient support in order to allow most Applets to be fully functional, since the AppletContext and AppletStub created by java.beans.instantiate(), are no-ops. This is a direct consequence of the lack of sufficient specification of how to construct AppletContext and AppletStub implementations in the existing Applet API’s. Furthermore, even if such specifications existed we would require an API that propagated a number of Applet attributes such as its Codebase, Parameters, AppletContext, and Documentbase into java.beans.instantiate() in order for it to subsequently instantiate the appropriately initialized objects.

Since key to supporting fully functional Applets is to provide them with fully functional AppletContext and AppletStub instances, the design goal is to provide a mechanism to provide this state to instantiate() so that it may carry out the appropriate initialization and binding5, therefore the proposed interface is:

public static Object
                        instantiate(ClassLoader                                 cl,
                                          String                beanName,
                                          BeanContext           bCtxt,
                                          AppletInitializer                                                                                                                     ai
                        );

public interface AppletInitializer {
        void initialize(Applet newApplet, BeanContext bCtxt);
        void activate(Applet newApplet);
}

If the newly instantiated JavaBean component is an instance of java.applet.Applet then the new constructed Applet, (Bean) will be passed to the AppletInitializer via a call to initialize().

Compliant implementations of AppletInitializer.initialize() shall:

  • Associate the newly instantiated Applet with the appropriate AppletContext.
  • Instantiate an AppletStub() and associate that AppletStub with the Applet via
  • an invocation of setStub().
  • If BeanContext parameter is null, then it shall associate the Applet with its appropriate Container by adding that Applet to its Container via an invocation of add(). If the BeanContext parameter is non-null, then it is the responsibility of the BeanContext to associate the Applet with its Container during the subsequent invocation of its addChildren() method.

Compliant implementations of AppletInitializer.activate() shall mark the Applet as active, and may optionally also invoke the Applet’s start() method.

Note that if the newly instantiated JavaBean is not an instance of Applet, then the AppletInitializer interface is ignored.

5.0 Standard/Suggested Conventions for BeanContext Services

5.1 BeanContexts that support InfoBus.

The InfoBus technology is a standard extension package that is intended to facilitate the rendezvous and exchange of dynamic self describing data, based upon a publish and subscribe abstraction, between JavaBean Components within a single Java Virtual Machine.

A BeanContext that exposes an InfoBus to its nested BeanContextChild shall do so by exposing a service via the hasService() and getService() methods of type javax.infobus.InfoBus.

Thus BeanContextChild implementations may locate a common InfoBus implementation for their current BeanContext by using this mechanism to rendezvous with that InfoBus instance.

The Infobus 1.2 specification shall define a convenience mechanism provided by the InfoBus class to simplify the discovery mechanism for BeanContextChild instances nested within a particular instance of BeanContextServices.

5.2 BeanContexts that support printing

A BeanContext that wishes to expose printing facilities to its descendants may delegate a reference of (sub)type java.awt.PrintJob.

As the Java Network Printing Interface evolves additional specifications will be provided to expose it’s facilities via the services mechanism.

5.3 BeanContext Design/Runtime mode support.

JavaBeans support the concepts of “design”-mode, when JavaBeans are being manipulated and composed by a developer in an Application Builder or IDE, and “Run”-mode, when the resulting JavaBeans are instantiated at runtime as part of an Applet, Application or some other executable abstraction.

In the first version of the specification, the “mode” or state, that is “design”-time or “run”-time was a JVM global attribute. This is insufficient since, for example, in an Application Builder environment, there may be JavaBeans that function, in “run”-mode, as part of the Application Builder environment itself, as well as the JavaBeans that function, in “design”-mode, under construction by the developer using the Application Builder to compose an application.

Therefore we require the ability to scope this “mode” at a granularity below that of JVM global.

The BeanContext abstraction, as a “Container” or “Context” for one or more JavaBeans provides appropriate mechanism to better scope this “mode”.

Thus BeanContext’s that wish to expose and propagate this “mode” to its descendants may delegate a reference of type java.beans.DesignMode:

public interface java.beans.DesignMode {
        void    setDesignTime(boolean isDesignTime);
        boolean isDesignTime();
}

Additionally, BeanContexts delegating such a reference shall be required to fire the appropriate java.beans.propertyChangeEvent, with propertyName = “designTime”, with the appropriate values for oldValue and newValue, when the “mode” changes value.

Note that it is illegal for instances of BeanContextChild to call setDesignTime() on instances of BeanContext that they are nested within.

5.4 BeanContext Visibility support.

JavaBeans with associated presentation, or GUI, may be instantiated in environments where the ability to present that GUI is either not physically possible (when the hardware is not present), or is not appropriate under the current conditions (running in a server context instead of a client).

The first version of the JavaBeans Specification introduced the java.beans.Visibility interface in order to provide a mechanism for JavaBeans to have their “visible” state, or ability to render a GUI, controlled from their environment.

BeanContexts that wish to enforce a particular policy regarding the ability of their children to present GUI, shall use the java.beans.Visibility interface to control their children.

5.5 Determining Locale from a BeanContext

BeanContexts may have a locale associated with them, in order to associate and propagate this important attribute across the JavaBeans nested therein.

Therefore, BeanContexts, shall be required to fire the appropriate java.beans.PropertyChangeEvent, with propertyName = “locale”, oldValue = the reference to the previous value of the Locale delegate, and newValue = the reference to the new value of the Locale delegate, in order to notify its Listeners of any change in Locale.

Setting and getting the value of the Locale on the BeanContext is implementation dependent.

6.0 Support classes

In order to ease the implementation of this relatively complex protocol a “helper” classes are provided; java.beans.beancontext.BeanContextChildSupport, java.beans.beancontext.BeanContextSupport, and java.beans.beancontext.BeanContextServicesSupport. These classes are designed to either be subclassed, or delegated implicitly by another object, and provides fully compliant (extensible) implementations of the protocols embodied herein.

1Note, if the remove() was invoked as a result of the BeanContext receiving an unexpected PropertyChan- geEvent notification as a result of a 3rd party invoking setBeanContext() then the remove implementation shall not invoke setBeanContext(null) on that child as part of the remove() semantics, since to do so would overwrite the value previously set by the 3rd party.
2Unfortunately because of method name collisions between Component and Collection a Component can- not implement BeanContext or Collection directly and must model the capability with a “HasA” rather than an “IsA” relationship.
3I don’t like this name much but I am struggling for a better alternative! (we are stuck with it)
4Note: Since simple JavaBeans have no knowledge of a BeanContext, it is not advisable to introduce such instances into the hierarchy since there is no mechanism for these simple JavaBeans to remove them- selves from the hierarchy and thus subsequently be garbage collected.
5AppletContext objects expose a list of Applet objects they “contain”, unfortunately the current Applet or AppletStub API’s as defined, provide no mechanism for the AppletContext to discover its Applets from its AppletStubs, or for an AppletStub to inform its AppletContext of its Applet. Therefore we will have to assume that this binding/discovery can occur in order for this mechanism to be worthwhile in java.beans.instantiate().

Contents
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Extensible Runtime Containment and Server Protocol for JavaBeans Version 1.0

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Extensible Runtime Containment and Server Protocol for JavaBeans

Version 1.0

Laurence Cable

Contents | Previous | Next

Extensible Runtime Containment and Server Protocol for JavaBeans Version 1.0

2.0 API Specification

3.0 Overloading java.beans.instantiate() static method

4.0 Providing better support for Beans that are also Applets

5.0 Standard/Suggested Conventions for BeanContext Services

6.0 Support classes

Contents | Previous | Next
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Best Practices For Applet Development

Applet Developer's Guide > Java Plug-in and Applet Architecture > Best Practices For Applet Development

Contents

  • Introduction
  • Avoid Static State
  • Return from Start Method Quickly
  • Provide an ID for Applet
  • Disable Classloader Cache
  • Set up a Proxy to Manipulate the Applet GUI from JavaScript
  • Keep Inter-process Calls Short
  • Avoid Roundtrip Inter-process Calls
  • Take Advantage of Java's Multi-Threading

Introduction

Applets have a complex runtime environment and several issues need to be considered to ensure that applets run predictably on various browsers and versions of Java Plug-ins. This document describes the best practices for applet development and deployment .

Avoid Static State

Values stored in the applet could persist between invocations, if the memory acquired by the class loader cache isn't needed for other purposes. But you can't depend on that behavior. In general, applets should be stateless. If persistent storage is needed, use browser cookies.

Return from the start method as quickly as possible

If start doesn't terminate, stop can't be called. That's important, because garbage collection occurs after the destroy method terminates. If the applet lingers in the start method, then the applet may not be torn down properly. (It will be torn down, and garbage collection will occur, but resources acquired during applet initialization may not be properly released.)

For a computationally-intensive app like the Clock demo, the trick is to implement the Runnable interface, do the heavy lifting in the run method it requires, and launch a separate thread to do the actual work, as shown in this abstract from the source code:

public class Clock extends Applet implements Runnable {
  private volatile Thread timer;    // The thread that displays the clock
  ...
  public void start() {
    timer = new Thread(this);       // Create the thread and start it
    timer.start();
  }

  public void stop() {
    timer = null;                   // Release the thread resource
  }

  public void run() {
    Thread me = Thread.currentThread();
    while (timer == me) {
      try {
        Thread.currentThread().sleep(100);
      }
      catch (InterruptedException e) {
      }
      repaint();
    }
  }
  ...

Here, the action is to pause the Clock instance that's running in the new thread (hence the need to store a pointer to it.) Applets that don't need to do all that can simply put their processing code into the run method.

For an interactive app like the spreadsheet demo, that goal is easily achieved, since the majority of time is spent in the event-processing thread, as shown in this abstract from the source code:

public class SpreadSheet extends Applet
  implements MouseListener, KeyListener  // Event processing
{
  public void init() {
    ...
    addMouseListener(this);
    addKeyListener(this);
  }
  ...
  public void start() {
        isStopped = false;
  }

  public void stop() {
         isStopped = true;
  }

  public void keyTyped(KeyEvent e) {    // Invoked when an event occurs
    ...
  }
  public void mousePressed(MouseEvent e) {
    ...
  }

  ...
class CellUpdater extends Thread {
  ...
  public void run() {
    ...
      if (!target.app.isStopped && !target.paused) {
                        target.app.repaint();
      }

In this particular implementation, each cell has it's own update thread. Updating is paused when a cell is selected, and only stops completely when the applet terminates. The important point is that the applet's start and stop methods only keep track of applet state. Most of the time is spent in the underlying event-processing thread, waiting for the user's keystroke or mouseclick. The applet's real work then occurs in response to one of those events.

Provide an ID for the Applet

An ID defines the namespace, and ensures proper naming at all levels of the data hierarchy:

<applet
  id="myApplet"
  name="myApplet"
  ...

Disable the Classloader Cache

Truly stateless applets don't depend on values previously stored in static variables. Since you can't depend on those values to be retained, it's a good idea to create stateless applets. But the user can still store state. It's just that store the data where it belongs--with the user, rather than in the applet code.

To implement a stateless app, access browser cookies or launch with JNLP to use Java Web Start muffins, so the applet gets it's initial settings from persistent storage, rather than using values stored in the program.

To ensure that your applet is stateless, use the classloader_cache attribute to disable the cache. For example:

<applet
  ...
  classloader_cache="false"

That setting ensures that the applet is stateless, and that it is truly decoupled from the remainder of the system and from other instances of the applet. It also ensures that the applet runs the exact same way every time, since it won't be affected by state that has been inadvertently retained.

Note:
In the rare case that you expect your users to re-run the same applet repeatedly, you might consider leaving the cache enabled for production for the sake of performance, but disable it during development to ensure quality.

Set up a Proxy to Manipulate the Applet GUI from JavaScript

To prevent thread contention, don't update the Swing or AWT GUI from javascript directly. Instead, set up a proxy that forwards the request to the appropriate dispatch thread:

  • Swing: javax.swing.SwingUtilities.invokeLater(Runnable)
  • AWT: java.awt.EventQueue.invokeLater(Runnable)

Keep Inter-process Calls Short

Minimize the time taken to call from Java into javascript, and from javascript into Java. Don't do long-running work in such calls, or you risk a deadlock. To keep the calls short:

  1. In Java method that is invoked from javascript, launch a separate thread to do the work.
  2. If a javascript function has a lot to do, move the code to the Java process and do the work in a separate thread to offload work from the browser.

Avoid Roundtrip Inter-process Calls

When calling into Java, don't make calls back into javascript if you can possibly help it, and vice versa. In that original plugin, doing so used to lock up the browser. That shouldn't happen anymore, but round-trip calls do introduce significant delays in processing time.

When a javascript function needs the applet to do something, the best practice is to return a value that tells the applet to do it, and then call back with the results, or else use invokeLater to minimize traffic tie ups.

Take Advantage of Java's Multi-Threading

The Java platform has powerful multi-threading capabilities that you can take advantage of with classes like Thread, Swing invokeLater, and AWT invokeLater, as well as the new ThreadPoolExecutor class that maintains a background thread pool.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Binary Literals

In Java SE 7, the integral types (byte, short, int, and long) can also be expressed using the binary number system. To specify a binary literal, add the prefix 0b or 0B to the number. The following examples show binary literals:

// An 8-bit 'byte' literal.
byte aByte = (byte)0b00100001;

// A 16-bit 'short' literal.
short aShort = (short)0b1010000101000101;

// Some 32-bit 'int' literals.
int anInt1 = 0b10100001010001011010000101000101;
int anInt2 = 0b101;
int anInt3 = 0B101; // The B can be upper or lower case.

// A 64-bit 'long' literal. Note the "L" suffix.
long aLong = 0b1010000101000101101000010100010110100001010001011010000101000101L;

Binary literals can make relationships among data more apparent than they would be in hexadecimal or octal. For example, each successive number in the following array is rotated by one bit:

public static final int[] phases = {
  0b00110001,
  0b01100010,
  0b11000100,
  0b10001001,
  0b00010011,
  0b00100110,
  0b01001100,
  0b10011000
}

In hexadecimal, the relationship among the numbers is not readily apparent:

public static final int[] phases = {
    0x31, 0x62, 0xC4, 0x89, 0x13, 0x26, 0x4C, 0x98
}

You can use binary integral constants in code that you can verify against a specifications document, such as a simulator for a hypothetical 8-bit microprocessor:

public State decodeInstruction(int instruction, State state) {
  if ((instruction & 0b11100000) == 0b00000000) {
    final int register = instruction & 0b00001111;
    switch (instruction & 0b11110000) {
      case 0b00000000: return state.nop();
      case 0b00010000: return state.copyAccumTo(register);
      case 0b00100000: return state.addToAccum(register);
      case 0b00110000: return state.subFromAccum(register);
      case 0b01000000: return state.multiplyAccumBy(register);
      case 0b01010000: return state.divideAccumBy(register);
      case 0b01100000: return state.setAccumFrom(register);
      case 0b01110000: return state.returnFromCall();
      default: throw new IllegalArgumentException();
    }
  } else {
    final int address = instruction & 0b00011111;
    switch (instruction & 0b11100000) {
      case 0b00100000: return state.jumpTo(address);
      case 0b01000000: return state.jumpIfAccumZeroTo(address);
      case 0b01000000: return state.jumpIfAccumNonzeroTo(address);
      case 0b01100000: return state.setAccumFromMemory(address);
      case 0b10100000: return state.writeAccumToMemory(address);
      case 0b11000000: return state.callTo(address);
      default: throw new IllegalArgumentException();
    }
  }
}

You can use binary literals to make a bitmap more readable:

public static final short[] HAPPY_FACE = {
   (short)0b0000011111100000;
   (short)0b0000100000010000;
   (short)0b0001000000001000;
   (short)0b0010000000000100;
   (short)0b0100000000000010;
   (short)0b1000011001100001;
   (short)0b1000011001100001;
   (short)0b1000000000000001;
   (short)0b1000000000000001;
   (short)0b1001000000001001;
   (short)0b1000100000010001;
   (short)0b0100011111100010;
   (short)0b0010000000000100;
   (short)0b0001000000001000;
   (short)0b0000100000010000;
   (short)0b0000011111100000;
}
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.source.tree.BinaryTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.BinaryTree

  • Packages that use BinaryTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of BinaryTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type BinaryTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitBinary(BinaryTree node, P p)

    • Uses of BinaryTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type BinaryTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitBinary(BinaryTree node, P p)
      R | SimpleTreeVisitor.visitBinary(BinaryTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.BlockTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.BlockTree

  • Packages that use BlockTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of BlockTree in com.sun.source.tree

      Methods in com.sun.source.tree that return BlockTree
      Modifier and Type | Method and Description
      BlockTree | TryTree.getBlock()
      BlockTree | SynchronizedTree.getBlock()
      BlockTree | CatchTree.getBlock()
      BlockTree | MethodTree.getBody()
      BlockTree | TryTree.getFinallyBlock()
      Methods in com.sun.source.tree with parameters of type BlockTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitBlock(BlockTree node, P p)

    • Uses of BlockTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type BlockTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitBlock(BlockTree node, P p)
      R | SimpleTreeVisitor.visitBlock(BlockTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.BooleanType (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.BooleanType

No usage of com.sun.jdi.BooleanType
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.BooleanValue (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.BooleanValue

  • Packages that use BooleanValue
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of BooleanValue in com.sun.jdi

      Methods in com.sun.jdi that return BooleanValue
      Modifier and Type Method and Description
      BooleanValue VirtualMachine.mirrorOf(boolean value)
      Creates a BooleanValue for the given value.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.jdi.Bootstrap (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.Bootstrap

No usage of com.sun.jdi.Bootstrap
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.event.BreakpointEvent (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.event.BreakpointEvent

No usage of com.sun.jdi.event.BreakpointEvent
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.request.BreakpointRequest (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.request.BreakpointRequest

  • Packages that use BreakpointRequest
    Package Description
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of BreakpointRequest in com.sun.jdi.request

      Methods in com.sun.jdi.request that return BreakpointRequest
      Modifier and Type Method and Description
      BreakpointRequest EventRequestManager.createBreakpointRequest(Location location)
      Creates a new disabled BreakpointRequest.
      Methods in com.sun.jdi.request that return types with arguments of type BreakpointRequest
      Modifier and Type Method and Description
      List<BreakpointRequest> EventRequestManager.breakpointRequests()
      Return an unmodifiable list of the enabled and disabled breakpoint requests.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.BreakTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.BreakTree

  • Packages that use BreakTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of BreakTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type BreakTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitBreak(BreakTree node, P p)

    • Uses of BreakTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type BreakTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitBreak(BreakTree node, P p)
      R | SimpleTreeVisitor.visitBreak(BreakTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Browser Support in New Java(TM) Plug-In

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Browser Support in New JavaTM Plug-in

Applet Developer's Guide > Browser Support in New Java Plug-in

The new Java Plug-in introduced in Java SE 6 update 10 release is designed to work in the following browsers:

  • Internet Explorer 6 and 7 on Windows XP and Vista
  • Firefox 3 on Windows XP, Windows Vista, Solaris and Linux

Note that the new Java Plug-in does not work in Firefox 2. On the Windows platform, when the new Java Plug-in is enabled via the Java Control Panel, launching Firefox 2 will use the classic Java Plug-in and launching Firefox 3 will use the new Java Plug-in. Sun Microsystems and the Mozilla Foundation have been working closely in order to support the new Java Plug-In in Firefox 3. Both organizations have mutually decided not to back-port the required changes — which are significant — to Firefox 2, as it is expected that most Firefox users will upgrade to Firefox 3 a short time after its final version has been released.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.ByteType (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.ByteType

No usage of com.sun.jdi.ByteType
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.ByteValue (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.ByteValue

  • Packages that use ByteValue
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of ByteValue in com.sun.jdi

      Methods in com.sun.jdi that return ByteValue
      Modifier and Type Method and Description
      ByteValue VirtualMachine.mirrorOf(byte value)
      Creates a ByteValue for the given value.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Supported Calendars

This page documents calendar systems supported in Sun's Java SE Development Kit 6 (JDK) and Java SE Runtime Environment 6 (JRE). Other implementations of the Java SE Platform may support different calendar systems.

1. Introduction

Calendar is an abstract base class for converting between a Date object and a set of integer fields such as YEAR, MONTH, DAY, HOUR, and so on. Subclasses of Calendar interpret a Date according to the rules of a specific calendar system. The platform provides one public concrete subclass of Calendar: GregorianCalendar. The factory method, Calendar.getInstance, returns the concrete calendar system implementation for the given Locale. The following are supported calendar systems:

Locale | Calendar System | Since (JRE version)
th_TH (with any variant) | Thai Buddhist calendar | 1.4
ja_JP_JP | Japanese imperial calendar | 1.6
Any except above Locales | Gregorian calendar (GregorianCalendar) | 1.1

2. Thai Buddhist Calendar

In Thailand, the Gregorian calendar system is used with the Buddhist Era-based year numbering. In Buddhist Era (พุทธศักราช) or B.E. (พ.ศ.) for short, year 1 corresponds to BCE (BC) 543 (Julian). Therefore, Gregorian year + 543 is the B.E. year value.

The Calendar.getInstance method returns a Thai Buddhist calendar instance if a Thai locale is specified, which is determined by its language and country values. This Thai Buddhist calendar implementation supports dates accurately from B.E. 2484 (1941 Gregorian). The historical calendar system transitions are not supported by the implementation. The Calendar.ERA value for Buddhist Era is 1.

3. Japanese Imperial Calendar

In Japan, the Gregorian calendar system is used with the imperial era-based year numbering. An imperial era starts from an emperor's ascension and its year number is reset to 1 with a new era name. The first year of an imperial era is not in sync with the Gregorian year boundaries, and any day could be the first day of an imperial era. For example, the current era started from January 8, 1989 (Gregorian). However, the month and the day of month numberings are in sync with the Gregorian calendar system.

The Calendar.getInstance method returns a Japanese imperial calendar instance if ja_JP_JP locale is specified. This implementation supports the eras since Meiji with the following transition dates.

Era Name
(in Japanese)
 Era
Abbr.
 ERA
 field value
 Transition date and time
(Gregorian)
- (西暦)
 -
 0
 -
Meiji (明治)
 M
 1
 1868-01-01 00:00:00 local time
Taisho (大正)
 T
 2
 1912-07-30 00:00:00 local time
Showa (昭和)
 S
 3
 1926-12-25 00:00:00 local time
Heisei (平成)
 H
 4
 1989-01-08 00:00:00 local time

Before Meiji, the Gregorian year numbering is supported. Unlike GregorianCalendar, the Japanese imperial calendar implementation doesn't support any Julian to Gregorian transition, and the year numbering before Gregorian 1 is 0, -1, -2, ..., not 1, 2, 3, ... Strictly speaking, the Gregorian calendar is in use from 1873 (Meiji 5) and other calendar systems were used before that year. However, the implementation defines the first day of Meiji as January 1, 1868, which is not historically accurate. The Japanese decrees related to calendar systems don't specify how to deal with time zones outside of Japan. The implementation assumes that era transitions occur at midnight in local time in any time zone.

In the Calendar API, some fields are in sync with the year value for the era transitions and therefore handle irregular rules in the first year of an imperial era. The following table shows those fields.

Calendar field
 Description
WEEK_OF_YEAR
         To determine the first WEEK_OF_YEAR of year 1 in each era, the same rules as determining the first week by the first day of week and minimal days in the first week values are applied. For example, if the first day of week is SUNDAY and the minimal days in the first week is 1, the WEEK_OF_YEAR value of 1926-12-18 is 51 of Taisho 15 and the value of 1926-12-25 is 1 of Showa 1.
DAY_OF_YEAR
         The DAY_OF_YEAR value of the first day of each era is 1. For example, looking at the transition between the Showa and Heisei eras, the last day of the Showa era (Showa 64.01.07, gregorian value 1989-01-07) is 7 and the next day, which is the first day of the Heisei era (Heisei 1.01.08), is 1. The getLeastMaximum method returns the minimum value of all year 1 lengths in days.

4. Formatting and Parsing Non-GregorianCalendar Dates

A DateFormat instance has a Calendar instance for internal date-time conversions based on the given Locale or the default one. The same rule is applied for creating a Calendar instance. For example, if ja_JP_JP locale is specified, the DateFormat.getDateInstance method returns a DateFormat instance that handles Japanese imperial calendar dates. The following code:
DateFormat df = DateFormat.getDateInstance(DateFormat.FULL,
                                           new Locale("ja", "JP", "JP"));
System.out.println(df.format(new Date()));
will produce the output, like:
平成17年10月25日
Also, the DateFormat.parse method parses a date string with an imperial era. The following code:
System.out.println(df.parse("平成元年10月25日"));
will produce the output in the Asia/Tokyo time zone:
Wed Oct 25 00:00:00 JST 1989
Note that a Date object returned by the DateFormat.parse method represents a corresponding Gregorian date. To convert a Date to a Japanese imperial date, the Calendar.setTime method must be used with the given Date.

In SimpleDateFormat, the following rules are applied for the Thai Buddhist and Japanese imperial calendar systems.

Calendar system
         Pattern Letter
         Description
Thai Buddhist G
         The number of pattern letters doesn't affect displayed era names.
Thai Buddhist y
         The same rule of the number of pattern letters as GregorianCalendar is applied.
Japanese imperial G
         For formatting, if the number of pattern letters is 4 or more, the long era names (e.g., "平成") are used. Otherwise, the abbreviations (e.g., "H") are used. For parsing, both the long era names and abbreviations are accepted.
Japanese imperial y
         For formatting, if the number of pattern letters is 4 or more, the first year of an era is formatted as the locale specific representation, such as "元" in Japanese locale. Other year values are displayed as numbers. The 2- and 4-digit rules of GregorianCalendar date formatting are not applied. For parsing, both the locale specific representation and the number representation are accepted.

If the variant element is "TH" in Thai locale, the Thai digits are used for the date-time formatting. For example, the following code:
DateFormat df = DateFormat.getDateInstance(DateFormat.FULL,
                                           new Locale("th", "TH", "TH"));
System.out.println(df.format(new Date()));
will produce the output, like:
วันอังคารที่ ๒๕ ตุลาคม พ.ศ. ๒๕๔๘

5. Serialization Considerations

When a Calendar object returned by the Calendar.getInstance factory method is serialized and sent to another JVM, deserialization of the object fails if the destination JVM does not support the same Calendar subclass that has been used to create the serialized Calendar object. Please make sure that the same Calendar subclasses are supported in JVMs where you would like to exchange serialized Calendar objects.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class javax.smartcardio.Card (Java Smart Card I/O b138)

  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
javax.smartcardio.Card

    • Uses of Card in javax.smartcardio

      Methods in javax.smartcardio that return Card
      Modifier and Type Method and Description
      abstract Card CardTerminal.connect(String protocol)
      Establishes a connection to the card.
      abstract Card CardChannel.getCard()
      Returns the Card this channel is associated with.
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class javax.smartcardio.CardChannel (Java Smart Card I/O b138)

  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
javax.smartcardio.CardChannel

    • Uses of CardChannel in javax.smartcardio

      Methods in javax.smartcardio that return CardChannel
      Modifier and Type Method and Description
      abstract CardChannel Card.getBasicChannel()
      Returns the CardChannel for the basic logical channel.
      abstract CardChannel Card.openLogicalChannel()
      Opens a new logical channel to the card and returns it.
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class javax.smartcardio.CardException (Java Smart Card I/O b138)

  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
javax.smartcardio.CardException

    • Uses of CardException in javax.smartcardio

      Subclasses of CardException in javax.smartcardio
      Modifier and Type Class and Description
      class  CardNotPresentException
      Exception thrown when an application tries to establish a connection with a terminal that has no card present.
      Methods in javax.smartcardio that throw CardException
      Modifier and Type Method and Description
      abstract void Card.beginExclusive()
      Requests exclusive access to this card.
      abstract void CardChannel.close()
      Closes this CardChannel.
      abstract Card CardTerminal.connect(String protocol)
      Establishes a connection to the card.
      abstract void Card.disconnect(boolean reset)
      Disconnects the connection with this card.
      abstract void Card.endExclusive()
      Releases the exclusive access previously established using beginExclusive.
      abstract boolean CardTerminal.isCardPresent()
      Returns whether a card is present in this terminal.
      List<CardTerminal> CardTerminals.list()
      Returns an unmodifiable list of all available terminals.
      abstract List<CardTerminal> CardTerminals.list(CardTerminals.State state)
      Returns an unmodifiable list of all terminals matching the specified state.
      abstract CardChannel Card.openLogicalChannel()
      Opens a new logical channel to the card and returns it.
      abstract int CardChannel.transmit(ByteBuffer command, ByteBuffer response)
      Transmits the command APDU stored in the command ByteBuffer and receives the reponse APDU in the response ByteBuffer.
      abstract ResponseAPDU CardChannel.transmit(CommandAPDU command)
      Transmits the specified command APDU to the Smart Card and returns the response APDU.
      abstract byte[] Card.transmitControlCommand(int controlCode, byte[] command)
      Transmits a control command to the terminal device.
      abstract boolean CardTerminal.waitForCardAbsent(long timeout)
      Waits until a card is absent in this terminal or the timeout expires.
      abstract boolean CardTerminal.waitForCardPresent(long timeout)
      Waits until a card is present in this terminal or the timeout expires.
      void CardTerminals.waitForChange()
      Waits for card insertion or removal in any of the terminals of this object.
      abstract boolean CardTerminals.waitForChange(long timeout)
      Waits for card insertion or removal in any of the terminals of this object or until the timeout expires.
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class javax.smartcardio.CardNotPresentException (Java Smart Card I/O b138)

  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
javax.smartcardio.CardNotPresentException

No usage of javax.smartcardio.CardNotPresentException
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class javax.smartcardio.CardPermission (Java Smart Card I/O b138)

  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
javax.smartcardio.CardPermission

No usage of javax.smartcardio.CardPermission
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class javax.smartcardio.CardTerminal (Java Smart Card I/O b138)

  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
javax.smartcardio.CardTerminal

    • Uses of CardTerminal in javax.smartcardio

      Methods in javax.smartcardio that return CardTerminal
      Modifier and Type Method and Description
      CardTerminal CardTerminals.getTerminal(String name)
      Returns the terminal with the specified name or null if no such terminal exists.
      Methods in javax.smartcardio that return types with arguments of type CardTerminal
      Modifier and Type Method and Description
      List<CardTerminal> CardTerminals.list()
      Returns an unmodifiable list of all available terminals.
      abstract List<CardTerminal> CardTerminals.list(CardTerminals.State state)
      Returns an unmodifiable list of all terminals matching the specified state.
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class javax.smartcardio.CardTerminals (Java Smart Card I/O b138)

  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
javax.smartcardio.CardTerminals

    • Uses of CardTerminals in javax.smartcardio

      Methods in javax.smartcardio that return CardTerminals
      Modifier and Type Method and Description
      protected abstract CardTerminals TerminalFactorySpi.engineTerminals()
      Returns the CardTerminals created by this factory.
      CardTerminals TerminalFactory.terminals()
      Returns a new CardTerminals object encapsulating the terminals supported by this factory.
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class javax.smartcardio.CardTerminals.State (Java Smart Card I/O b138)

  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
javax.smartcardio.CardTerminals.State

    • Uses of CardTerminals.State in javax.smartcardio

      Methods in javax.smartcardio that return CardTerminals.State
      Modifier and Type Method and Description
      static CardTerminals.State CardTerminals.State.valueOf(String name)
      Returns the enum constant of this type with the specified name.
      static CardTerminals.State[] CardTerminals.State.values()
      Returns an array containing the constants of this enum type, in the order they are declared.
      Methods in javax.smartcardio with parameters of type CardTerminals.State
      Modifier and Type Method and Description
      abstract List<CardTerminal> CardTerminals.list(CardTerminals.State state)
      Returns an unmodifiable list of all terminals matching the specified state.
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.CaseTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.CaseTree

  • Packages that use CaseTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of CaseTree in com.sun.source.tree

      Methods in com.sun.source.tree that return types with arguments of type CaseTree
      Modifier and Type | Method and Description
      List<? extends CaseTree> | SwitchTree.getCases()
      Methods in com.sun.source.tree with parameters of type CaseTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitCase(CaseTree node, P p)

    • Uses of CaseTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type CaseTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitCase(CaseTree node, P p)
      R | SimpleTreeVisitor.visitCase(CaseTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking

This page covers the following topics:

  • Handling More Than One Type of Exception
  • Rethrowing Exceptions with More Inclusive Type Checking

Handling More Than One Type of Exception

In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.

Consider the following example, which contains duplicate code in each of the catch blocks:

catch (IOException ex) {
     logger.log(ex);
     throw ex;
catch (SQLException ex) {
     logger.log(ex);
     throw ex;
}

In releases prior to Java SE 7, it is difficult to create a common method to eliminate the duplicated code because the variable ex has different types.

The following example, which is valid in Java SE 7 and later, eliminates the duplicated code:

catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}

The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|).

Note: If a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block.

Bytecode generated by compiling a catch block that handles multiple exception types will be smaller (and thus superior) than compiling many catch blocks that handle only one exception type each. A catch block that handles multiple exception types creates no duplication in the bytecode generated by the compiler; the bytecode has no replication of exception handlers.

Rethrowing Exceptions with More Inclusive Type Checking

The Java SE 7 compiler performs more precise analysis of rethrown exceptions than earlier releases of Java SE. This enables you to specify more specific exception types in the throws clause of a method declaration.

Consider the following example:

  static class FirstException extends Exception { }
  static class SecondException extends Exception { }

  public void rethrowException(String exceptionName) throws Exception {
    try {
      if (exceptionName.equals("First")) {
        throw new FirstException();
      } else {
        throw new SecondException();
      }
    } catch (Exception e) {
      throw e;
    }
  }

This examples's try block could throw either FirstException or SecondException. Suppose you want to specify these exception types in the throws clause of the rethrowException method declaration. In releases prior to Java SE 7, you cannot do so. Because the exception parameter of the catch clause, e, is type Exception, and the catch block rethrows the exception parameter e, you can only specify the exception type Exception in the throws clause of the rethrowException method declaration.

However, in Java SE 7, you can specify the exception types FirstException and SecondException in the throws clause in the rethrowException method declaration. The Java SE 7 compiler can determine that the exception thrown by the statement throw e must have come from the try block, and the only exceptions thrown by the try block can be FirstException and SecondException. Even though the exception parameter of the catch clause, e, is type Exception, the compiler can determine that it is an instance of either FirstException or SecondException:

  public void rethrowException(String exceptionName)
  throws FirstException, SecondException {
    try {
      // ...
    }
    catch (Exception e) {
      throw e;
    }
  }

This analysis is disabled if the catch parameter is assigned to another value in the catch block. However, if the catch parameter is assigned to another value, you must specify the exception type Exception in the throws clause of the method declaration.

In detail, in Java SE 7 and later, when you declare one or more exception types in a catch clause, and rethrow the exception handled by this catch block, the compiler verifies that the type of the rethrown exception meets the following conditions:

  • The try block is able to throw it.
  • There are no other preceding catch blocks that can handle it.
  • It is a subtype or supertype of one of the catch clause's exception parameters.

The Java SE 7 compiler allows you to specify the exception types FirstException and SecondException in the throws clause in the rethrowException method declaration because you can rethrow an exception that is a supertype of any of the types declared in the throws.

In releases prior to Java SE 7, you cannot throw an exception that is a supertype of one of the catch clause's exception parameters. A compiler from a release prior to Java SE 7 generates the error, "unreported exception Exception; must be caught or declared to be thrown" at the statement throw e. The compiler checks if the type of the exception thrown is assignable to any of the types declared in the throws clause of the rethrowException method declaration. However, the type of the catch parameter e is Exception, which is a supertype, not a subtype, of FirstException andSecondException.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.source.tree.CatchTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.CatchTree

  • Packages that use CatchTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of CatchTree in com.sun.source.tree

      Methods in com.sun.source.tree that return types with arguments of type CatchTree
      Modifier and Type | Method and Description
      List<? extends CatchTree> | TryTree.getCatches()
      Methods in com.sun.source.tree with parameters of type CatchTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitCatch(CatchTree node, P p)

    • Uses of CatchTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type CatchTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitCatch(CatchTree node, P p)
      R | SimpleTreeVisitor.visitCatch(CatchTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.CDATASection (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.CDATASection

  • Packages that use CDATASection
    Package Description
    org.w3c.dom
    Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.

    • Uses of CDATASection in org.w3c.dom

      Methods in org.w3c.dom that return CDATASection
      Modifier and Type Method and Description
      CDATASection Document.createCDATASection(String data)
      Creates a CDATASection node whose value is the specified string.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


X.509 certificates

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

X.509 Certificates and Certificate Revocation Lists (CRLs)

In One Sentence: What is a Certificate?
What Applications use Certificates?
How do I get a Certificate?
What is Inside an X.509 Certificate?
What Java API Can Be Used to Access and Manage Certificates?
What Java Tool Can Generate, Display, Import, and Export X.509 Certificates?

In One Sentence: What is a Certificate?

A public-key certificate is a digitally signed statement from one entity, saying that the public key (and some other information) of another entity has some specific value.

Let us expand on some of the key terms used in this sentence:

Public Keys
These are numbers associated with a particular entity, and are intended to be known to everyone who needs to have trusted interactions with that entity. Public keys are used to verify signatures.
Digitally Signed
If some data is digitally signed it has been stored with the "identity" of an entity, and a signature that proves that entity knows about the data. The data is rendered unforgeable by signing with the entitys' private key.
Identity
A known way of addressing an entity. In some systems the identity is the public key, in others it can be anything from a Unix UID to an Email address to an X.509 Distinguished Name.
Signature
A signature is computed over some data using the private key of an entity (the signer).
Private Keys
These are numbers, each of which is supposed to be known only to the particular entity whose private key it is (that is, it's supposed to be kept secret). Private and public keys exist in pairs in all public key cryptography systems (also referred to as "public key crypto systems"). In a typical public key crypto system, such as DSA, a private key corresponds to exactly one public key. Private keys are used to compute signatures.
Entity
An entity is a person, organization, program, computer, business, bank, or something else you are trusting to some degree.

Basically, public key cryptography requires access to users' public keys. In a large-scale networked environment it is impossible to guarantee that prior relationships between communicating entities have been established or that a trusted repository exists with all used public keys. Certificates were invented as a solution to this public key distribution problem. Now a Certification Authority (CA) can act as a Trusted Third Party. CAs are entities (e.g., businesses) that are trusted to sign (issue) certificates for other entities. It is assumed that CAs will only create valid and reliable certificates as they are bound by legal agreements. There are many public Certification Authorities, such as VeriSign, Thawte, Entrust, and so on. You can also run your own Certification Authority using products such as the Netscape/Microsoft Certificate Servers or the Entrust CA product for your organization.

What Applications use Certificates?

Probably the most widely visible application of X.509 certificates today is in web browsers (such as Mozilla Firefox and Microsoft Internet Explorer) that support the TLS protocol. TLS (Transport Layer Security) is a security protocol that provides privacy and authentication for your network traffic. These browsers can only use this protocol with web servers that support TLS.

Other technologies that rely on X.509 certificates include:

  • Various code-signing schemes, such as signed Java ARchives, and Microsoft Authenticode.
  • Various secure E-Mail standards, such as PEM and S/MIME.
  • E-Commerce protocols, such as SET.

How do I Get a Certificate?

There are two basic techniques used to get certificates:

  1. you can create one yourself (using the right tools, such as keytool), or
  2. you can ask a Certification Authority to issue you one (either directly or using a tool such as keytool to generate the request).
The main inputs to the certificate creation process are:
  • Matched public and private keys, generated using some special tools (such as keytool), or a browser. Only the public key is ever shown to anyone else. The private key is used to sign data; if someone knows your private key, they can masquerade as you ... perhaps forging legal documents attributed to you!
  • You need to provide information about the entity being certified (e.g., you). This normally includes information such as your name and organizational address. If you ask a CA to issue a certificate for you, you will normally need to provide proof to show correctness of the information.

If you are asking a CA to issue you a certificate, you provide your public key and some information about you. You'll use a tool (such as keytool or a browser that supports Certificate Signing Request generation). to digitally sign this information, and send it to the CA. The CA will then generate the certificate and return it.

If you're generating the certificate yourself, you'll take that same information, add a little more (dates during which the certificate is valid, a serial number), and just create the certificate using some tool (such as keytool). Not everyone will accept self-signed certificates; one part of the value provided by a CA is to serve as a neutral and trusted introduction service, based in part on their verification requirements, which are openly published in their Certification Service Practices (CSP).

What's Inside an X.509 Certificate?

The X.509 standard defines what information can go into a certificate, and describes how to write it down (the data format). All X.509 certificates have the following data, in addition to the signature:

Version
This identifies which version of the X.509 standard applies to this certificate, which affects what information can be specified in it. Thus far, three versions are defined.
Serial Number
The entity that created the certificate is responsible for assigning it a serial number to distinguish it from other certificates it issues. This information is used in numerous ways, for example when a certificate is revoked its serial number is placed in a Certificate Revocation List (CRL).
Signature Algorithm Identifier
This identifies the algorithm used by the CA to sign the certificate.
Issuer Name
The X.500 name of the entity that signed the certificate. This is normally a CA. Using this certificate implies trusting the entity that signed this certificate. (Note that in some cases, such as root or top-level CA certificates, the issuer signs its own certificate.)
Validity Period
Each certificate is valid only for a limited amount of time. This period is described by a start date and time and an end date and time, and can be as short as a few seconds or almost as long as a century. The validity period chosen depends on a number of factors, such as the strength of the private key used to sign the certificate or the amount one is willing to pay for a certificate. This is the expected period that entities can rely on the public value, if the associated private key has not been compromised.
Subject Name
The name of the entity whose public key the certificate identifies. This name uses the X.500 standard, so it is intended to be unique across the Internet. This is the Distinguished Name (DN) of the entity, for example,
    CN=Java Duke, OU=Java Software Division, O=Sun Microsystems Inc, C=US
(These refer to the subject's Common Name, Organizational Unit, Organization, and Country.)
Subject Public Key Information
This is the public key of the entity being named, together with an algorithm identifier which specifies which public key crypto system this key belongs to and any associated key parameters.

X.509 Version 1 has been available since 1988, is widely deployed, and is the most generic.

X.509 Version 2 introduced the concept of subject and issuer unique identifiers to handle the possibility of reuse of subject and/or issuer names over time. Most certificate profile documents strongly recommend that names not be reused, and that certificates should not make use of unique identifiers. Version 2 certificates are not widely used.

X.509 Version 3 is the most recent (1996) and supports the notion of extensions, whereby anyone can define an extension and include it in the certificate. Some common extensions in use today are: KeyUsage (limits the use of the keys to particular purposes such as "signing-only") and AlternativeNames (allows other identities to also be associated with this public key, e.g. DNS names, Email addresses, IP addresses). Extensions can be marked critical to indicate that the extension should be checked and enforced/used. For example, if a certificate has the KeyUsage extension marked critical and set to "keyCertSign" then if this certificate is presented during SSL communication, it should be rejected, as the certificate extension indicates that the associated private key should only be used for signing certificates and not for SSL use.

All the data in a certificate is encoded using two related standards called ASN.1/DER. Abstract Syntax Notation 1 describes data. The Definite Encoding Rules describe a single way to store and transfer that data. People have been known to describe this combination simultaneously as "powerful and flexible" and as "cryptic and awkward".

The IETF PKIX working group is in the process of defining standards for the Internet Public Key Infrastructure. We are closely following their work, and support the X.509 Certificate and CRL Profile, which is specified in RFC 3280.

What Java API Can Be Used to Access and Manage Certificates?

The Certificate API, found in the java.security.cert package, includes the following:
  • the CertificateFactory class defines the functionality of a certificate factory, which is used to generate certificate, certificate revocation list (CRL), and certification path objects from their encoding.
  • the Certificate class is an abstract class for managing a variety of certificates. It is an abstraction for certificates that have different formats but important common uses. For example, different types of certificates, such as X.509 and PGP, share general certificate functionality (like encoding and verifying) and some types of information like public key.
  • the CRL class is an abstract class for managing a variety of Certificate Revocation Lists (CRLs).
  • the X509Certificate class is an abstract class for X.509 Certificates. It provides a standard way to access all the attributes of an X.509 certificate.
  • the X509Extension interface is an interface for an X.509 extension. The extensions defined for X.509 v3 certificates and v2 CRLs (Certificate Revocation Lists) provide mechanisms for associating additional attributes with users or public keys, such as for managing the certification hierarchy, and for managing CRL distribution.
  • the X509CRL class is an abstract class for an X.509 Certificate Revocation List (CRL). A CRL is a time-stamped list identifying revoked certificates. It is signed by a Certification Authority (CA) and made freely available in a public repository.
  • the X509CRLEntry class is an abstract class for a CRL entry.
In JDK 1.4, new classes were added to support building and validating chains of certificates, or certification paths. These classes are described in further detail in the PKI Programmer's Guide.

What Java Tool Can Generate, Display, Import, and Export X.509 Certificates?

There is a tool named keytool ( for Solaris ) ( for Windows ) that can be used to create public/private key pairs and self-signed X.509 v3 certificates, and to manage keystores. Keys and certificates are used to digitally sign your Java applications and applets (see the jarsigner ( for Solaris ) ( for Windows ) tool).

A keystore is a protected database that holds keys and certificates. Access to a keystore is guarded by a password (defined at the time the keystore is created, by the person who creates the keystore, and changeable only when providing the current password). In addition, each private key in a keystore can be guarded by its own password.

Using keytool, it is possible to display, import, and export X.509 v1, v2, and v3 certificates stored as files, and to generate new self-signed v3 certificates. For examples, see the "EXAMPLES" section of the keytool documentation ( for Solaris ) ( for Windows ).

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Certification Form for CSPs

Sun's JCE implements encryption using Cryptographic Service
Providers (CSPs). Only CSPs signed by a trusted entity can be
plugged into the JCE framework. You have indicated that you
will be providing a CSP for JCE. Please read, sign, and return
this form to:

    Sun Microsystems, Inc.
    International Trade Services/Export Compliance
    Attn: Encryption Export
    10 Network Circle MS: UMPK10-144
    Menlo Park, CA 94025

You can also fax paperwork to the follwing number, with the following headings:

    Fax #: 408-668-0918

    Subject Line: CSR #___
    Attention: Encryption Export
    Sun Microsystems, Inc.
    International Trade Services/Export Compliance

Before you return this form, you must send, via email, a
Certificate Signing Request (CSR) and contact information
to javasoft-cert-request@sun.com, as noted in
java.sun.com/j2se/1.4.2/docs/guide/security/jce/HowToImplAJCEProvider.html

In response, you will receive a request number, also via email.
You may then mail this form. Include the request number here:

    Request Number: ______________________________

Including the request number ensures this form can be matched
to your email message.

                        Overview

Export controls on commercial encryption products are
administered by the Bureau of Industry and Security (BIS) in the
U.S. Department of Commerce. Rules governing exports of
encryption are found in the Export Administration Regulations
(EAR), 15 CFR Parts 730-774  which implements the Export
Administration Act ("EAA" 50 U.S.C. App. 2401 et seq.).

BIS requires that each entity exporting products be familiar
with and comply with their affirmative obligations set forth in
the Export Administration Regulations.  Please note that the
regulations are subject to change.  We recommend that you obtain
your own legal advice when attempting to export.  In addition
some countries may restrict certain levels of encryption
imported into their country. We recommend consulting legal
counsel in the appropriate country or the applicable
governmental agencies in the particular country.

If you developed your CSP inside the United States, and you
want to export your CSP, it must be reviewed and approved
for export by the Bureau of Industry and Security.

If you developed your CSP outside the United States, then you may not
have to submit your product for a technical review, but it may be
subject to the requirements of the Export Administration
Regulations.

                      Certification

I certify that I have read the above "Overview" and will comply
with the Export Administration Regulations.  I understand that
any CSP developed in the United States may not be exported from
the United States without prior approval by the US Government
and that such approval is my responsibility.  I further understand that
any CSP developed outside the United States nevertheless may be
subject to the Export Administration Regulations.

Company: _______________________________________________

Address: _______________________________________________

Signature: ____________________________  	Date:  _______

Printed Name: ____________________________________

Title:  ____________________________________________


Java(TM) PKI API Programmer's Guide

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java™ PKI Programmer's Guide

  • Overview
    • Acknowledgments
    • Who Should Read This Document
    • Related Documentation
    • Introduction
  • Core Classes and Interfaces
    • Basic Classes
      • The CertPath Class
      • The CertificateFactory Class
      • The CertPathParameters Interface
    • Certification Path Validation Classes
      • The CertPathValidator Class
      • The CertPathValidatorResult Interface
    • Certification Path Building Classes
      • The CertPathBuilder Class
      • The CertPathBuilderResult Interface
    • Certificate/CRL Storage Classes
      • The CertStore Class
      • The CertStoreParameters Interface
        • The LDAPCertStoreParameters Class
        • The CollectionCertStoreParameters Class
      • The CertSelector and CRLSelector Interfaces
        • The X509CertSelector Class
        • The X509CRLSelector Class
    • PKIX Classes
      • The TrustAnchor Class
      • The PKIXParameters Class
      • The PKIXCertPathValidatorResult Class
      • The PolicyNode Interface and PolicyQualifierInfo Class
      • The PKIXBuilderParameters Class
      • The PKIXCertPathBuilderResult Class
      • The PKIXCertPathChecker Class
      • Using PKIXCertPathChecker in Certificate Path Validation
  • Implementing a Service Provider
  • Appendix A: Standard Names
  • Appendix B: The "SUN" Provider
  • Appendix C: On-Line Certificate Status Protocol (OCSP) Support
  • Appendix D: Disabling Cryptographic Algorithms

Overview

The JavaTM Certification Path API consists of classes and interfaces for handling certification paths (also known as "certificate chains"). A certification path is an ordered list of certificates. If a certification path meets certain validation rules, it may be used to securely establish the mapping of a public key to a subject.

This API defines interfaces and abstract classes for creating, building, and validating certification paths. Implementations may be plugged in using a provider-based interface. The API is based on the Cryptographic Service Provider architecture, described in the Java Cryptography Architecture Reference Guide.

The API also includes algorithm-specific classes for building and validating X.509 certification paths according to the PKIX standards. The PKIX standards are developed by the IETF PKIX working group.

This API was originally specified using the Java Community ProcessSM program as JavaTM Specification Request (JSR) 000055. The API was included in the JavaTM SDK, starting with Java 2 Standard Edition (JDK), v 1.4. Please refer to the JSR 055 Home Page for more information on the JSR.

Acknowledgments

The author would like to thank the individuals who contributed to the Certification Path API and provided useful comments and technical advice. Special thanks to the members of the Sun Microsystems Laboratories team who designed and developed the Certification Path API which provided the basis of the work for the Java Community Process. This team includes Anne Anderson, Yassir Elley, Geoff Goodell, Steve Hanna, Sean Mullan, Radia Perlman, and Seth Proctor.

The expert group helped improve and refine the API using the Java Community Process and includes the following members:

  • Peter Hesse, CygnaCom Solutions, An Entrust Technologies Company
  • Sean Mullan, Sun Microsystems (Specification Lead)
  • Anthony Nadalin, IBM
  • Bob Naugle, Bluestone Software
  • Hemma Prafullchandra, VeriSign
  • Ming Yung, DSTC
Maxine Erlund, Steve Hanna, Phil Rosenzweig and Bob Sproull of Sun Microsystems provided leadership and vision. The members of the Java Security, Networking and Naming Group of Sun Microsystems contributed invaluable comments and support, especially Sharon Liu, Jeff Nisewanger, Gary Ellison, and Andreas Sterbenz. Helpful comments and advice were received from many in the technical community, especially Mary Dageforde, Edward Dobner, Tom Gindin, Jan Luehe, David Kuehr-McLaren, Parag Salvi, Alexei Semidetnov, and Yanni Zhang.

Who Should Read This Document

This document is intended for two classes of experienced developers:

  1. those who want to design secure applications that build or validate certification paths.

  2. those who want to write a service provider implementation for building or validating certification paths.

Related Documentation

This document assumes you have already read the following documents:

  • X.509 Certificates and Certificate Revocation Lists (CRLs)

  • Java Cryptography Architecture Reference Guide

  • How to Implement a Provider for the Java Cryptography Architecture

Introduction

Users of public key applications and systems must be confident that a subject's public key is genuine, i.e., that the associated private key is owned by the subject. Public key certificates are used to establish this trust. A public key (or identity) certificate is a binding of a public key to an identity, which is digitally signed by the private key of another entity, often called a Certification Authority (CA). We shall use the term CA to refer to an entity that signs a certificate for the remainder of this section.

If the user does not have a trusted copy of the public key of the CA that signed the subject's public key certificate, then another public key certificate vouching for the signing CA is required. This logic can be applied recursively, until a chain of certificates (or a certification path) is discovered from a trust anchor or a most-trusted CA to the target subject (commonly referred to as the end-entity). The most-trusted CA is usually specified by a certificate issued to a CA that the user directly trusts. In general, a certification path is an ordered list of certificates, usually comprised of the end-entity's public key certificate and zero or more additional certificates. A certification path typically has one or more encodings, allowing it to be safely transmitted across networks and to different operating system architectures.

Figure 1 illustrates a certification path from a most-trusted CA's public key (CA 1) to the target subject (Alice). The certification path establishes trust in Alice's public key through an intermediate CA named CA2.

The previous context describes this image
Figure 1: Certification Path

A certification path must be validated before it can be relied on to establish trust in a subject's public key. Validation can consist of various checks on the certificates contained in the certification path, such as verifying the signatures and checking that each certificate has not been revoked. The PKIX standards define an algorithm for validating certification paths consisting of X.509 certificates.

Often a user may not have a certification path from a most-trusted CA to the subject. Providing services to build or discover certification paths is an important feature of public key enabled systems. RFC 2587 defines an LDAP (Lightweight Directory Access Protocol) schema definition which facilitates the discovery of X.509 certification paths using the LDAP directory service protocol.

Building and validating certification paths is an important part of many standard security protocols such as SSL/TLS, S/MIME, and IPSEC. The JavaTM Certification Path API provides a set of classes and interfaces for developers who need to integrate this functionality into their applications. This API benefits two types of developers: those who need to write service provider implementations for a specific certification path building or validation algorithm; and those who need to access standard algorithms for creating, building, and validating certification paths in an implementation-independent manner.

Core Classes and Interfaces

The core classes of the Java Certification Path API consist of interfaces and classes that support certification path functionality in an algorithm- and implementation -independent manner. The API also includes a set of algorithm-specific classes for the PKIX standards that are discussed in the section titled PKIX Classes. The API builds on and extends the existing JavaTM Standard Edition (JDK) java.security.cert package for handling certificates. The core classes can be broken up into 4 class categories: Basic, Validation, Building, and Storage:

  • Basic Certification Path Classes

    • CertPath, CertificateFactory, CertPathParameters

  • Certification Path Validation Classes

    • CertPathValidator, CertPathValidatorResult

  • Certification Path Building Classes

    • CertPathBuilder, CertPathBuilderResult

  • Certificate/CRL Storage Classes

    • CertStore, CertStoreParameters, CertSelector, CRLSelector

The following sections describe the most commonly used methods of each class and interface. Usage examples for some of the classes are interspersed throughout the guide. The complete reference documentation for the relevant Certification Path API classes can be found in:

  • java.security.cert package summary

Most of the classes and interfaces in the CertPath API are not thread-safe. However, there are some exceptions which will be noted in this guide and the API specification. Multiple threads that need to access a single non-thread-safe object concurrently should synchronize amongst themselves and provide the necessary locking. Multiple threads each manipulating separate objects need not synchronize.

Basic Certification Path Classes

The basic certification path classes provide fundamental functionality for encoding and representing certification paths. The key basic class in the Java Certification Path API is CertPath, which encapsulates the universal aspects shared by all types of certification paths. An application uses an instance of the CertificateFactory class to create a CertPath object.

The CertPath Class

The CertPath class is an abstract class for certification paths. It defines the functionality shared by all certification path objects. Various certification path types can be implemented by subclassing the CertPath class, even though they may have different contents and ordering schemes. All CertPath objects are serializable, immutable and thread-safe and share the following characteristics:

  • A type

    This corresponds to the type of the certificates in the certification path, for example: X.509. The type of a CertPath is obtained using the method:

        public String getType()

    See Appendix A in the Java Cryptography Architecture Reference Guide for information about standard certificate types.

  • A list of certificates

    The getCertificates method returns the list of certificates in the certification path:

        public abstract List<? extends Certificate> getCertificates()
    This method returns a List of zero or more java.security.cert.Certificate objects. The returned List and the Certificates contained within it are immutable, in order to protect the contents of the CertPath object. The ordering of the certificates returned depends on the type. By convention, the certificates in a CertPath object of type X.509 are ordered starting with the target certificate and ending with a certificate issued by the trust anchor. That is, the issuer of one certificate is the subject of the following one. The certificate representing the TrustAnchor should not be included in the certification path. Unvalidated X.509 CertPaths may not follow this convention. PKIX CertPathValidators will detect any departure from these conventions that cause the certification path to be invalid and throw a CertPathValidatorException.

  • One or more encodings

    Each CertPath object supports one or more encodings. These are external encoded forms for the certification path, used when a standard representation of the path is needed outside the Java Virtual Machine (as when transmitting the path over a network to some other party). Each path can be encoded in a default format, the bytes of which are returned using the method:

        public abstract byte[] getEncoded()
    Alternatively, the getEncoded(String) method returns a specific supported encoding by specifying the encoding format as a String (ex: "PKCS7"). A list of standard encoding formats are defined in Appendix A.

        public abstract byte[] getEncoded(String encoding)
    Also, the getEncodings method returns an iterator over the supported encoding format Strings (the default encoding format is returned first):

        public abstract Iterator<String> getEncodings()

All CertPath objects are also Serializable. CertPath objects are resolved into an alternate CertPathRep object during serialization. This allows a CertPath object to be serialized into an equivalent representation regardless of its underlying implementation.

CertPath objects are generated from an encoded byte array or list of Certificates using a CertificateFactory. Alternatively, a CertPathBuilder may be used to try to find a CertPath from a most-trusted CA to a particular subject. Once a CertPath object has been created, it may be validated by passing it to the validate method of CertPathValidator. Each of these concepts are explained in more detail in subsequent sections.

The CertificateFactory Class

The CertificateFactory class is an engine class that defines the functionality of a certificate factory. In releases prior to JDK, v 1.4 it was used to generate Certificate and CRL objects. It was enhanced in JDK, v 1.4 to also be used to generate certification path (CertPath) objects. A CertificateFactory should not be confused with a CertPathBuilder. A CertPathBuilder (discussed later) is used to discover or find a certification path when one does not exist. In contrast, a CertificateFactory is used when a certification path has already been discovered and the caller needs to instantiate a CertPath object from its contents which exist in a different form such as an encoded byte array or an array of Certificates.

Creating a CertificateFactory Object

See the CertificateFactory section in the Java Cryptography Architecture Reference Guide for details on creating a CertificateFactory object.

Generating CertPath Objects

A CertificateFactory instance generates CertPath objects from a List of Certificate objects or from an InputStream that contains the encoded form of a CertPath. Just like a CertPath, each CertificateFactory supports a default encoding format for certification paths (ex: PKCS#7). To generate a CertPath object and initialize it with the data read from an input stream (in the default encoding format), use the generateCertPath method:

    public final CertPath generateCertPath(InputStream inStream)

or from a particular encoding format:

    public final CertPath generateCertPath(InputStream inStream,
                                           String encoding)

To find out what encoding formats are supported, use the getCertPathEncodings method (the default encoding is returned first):

    public final Iterator<String> getCertPathEncodings()

To generate a certification path object from a List of Certificate objects, use the following method:

    public final CertPath generateCertPath(List<? extends Certificate> certificates)

A CertificateFactory always returns CertPath objects that consist of Certificates that are of the same type as the factory. For example, a CertificateFactory of type X.509 returns CertPath objects consisting of certificates that are an instance of java.security.cert.X509Certificate.

The following code sample illustrates generating a certification path from a PKCS#7 encoded certificate reply stored in a file:

    // open an input stream to the file
    FileInputStream fis = new FileInputStream(filename);
    // instantiate a CertificateFactory for X.509
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    // extract the certification path from
    // the PKCS7 SignedData structure
    CertPath cp = cf.generateCertPath(fis, "PKCS7");
    // print each certificate in the path
    List<Certificate> certs = cp.getCertificates();
    for (Certificate cert : certs) {
        System.out.println(cert);
    }
Here's another code sample that fetches a certificate chain from a KeyStore and converts it to a CertPath using a CertificateFactory:
    // instantiate a KeyStore with type JKS
    KeyStore ks = KeyStore.getInstance("JKS");
    // load the contents of the KeyStore
    ks.load(new FileInputStream("./keystore"),
        "password".toCharArray());
    // fetch certificate chain stored with alias "sean"
    Certificate[] certArray = ks.getCertificateChain("sean");
    // convert chain to a List
    List certList = Arrays.asList(certArray);
    // instantiate a CertificateFactory for X.509
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    // extract the certification path from
    // the List of Certificates
    CertPath cp = cf.generateCertPath(certList);

Note that there is an existing method in CertificateFactory named generateCertificates that parses a sequence of Certificates. For encodings consisting of multiple certificates, use generateCertificates when you want to parse a collection of possibly unrelated certificates. Otherwise, use generateCertPath when you want to generate a CertPath and subsequently validate it with a CertPathValidator (discussed later).

The CertPathParameters Interface

The CertPathParameters interface is a transparent representation of the set of parameters used with a particular certification path builder or validation algorithm. Its main purpose is to group (and provide type safety for) all certification path parameter specifications. The CertPathParameters interface extends the Cloneable interface and defines a clone() method that does not throw an exception. All concrete implementations of this interface should implement and override the Object.clone() method, if necessary. This allows applications to clone any CertPathParameters object.

Objects implementing the CertPathParameters interface are passed as arguments to methods of the CertPathValidator and CertPathBuilder classes. Typically, a concrete implementation of the CertPathParameters interface will hold a set of input parameters specific to a particular certification path build or validation algorithm. For example, the PKIXParameters class is an implementation of the CertPathParameters interface that holds a set of input parameters for the PKIX certification path validation algorithm. One such parameter is the set of most-trusted CAs that the caller trusts for anchoring the validation process. This parameter among others is discussed in more detail in the section discussing the PKIXParameters class.

Certification Path Validation Classes

The Java Certification Path API includes classes and interfaces for validating certification paths. An application uses an instance of the CertPathValidator class to validate a CertPath object. If successful, the result of the validation algorithm is returned in an object implementing the CertPathValidatorResult interface.

The CertPathValidator Class

The CertPathValidator class is an engine class used to validate a certification path.

Creating a CertPathValidator Object

As with all engine classes, the way to get a CertPathValidator object for a particular validation algorithm is to call one of the getInstance static factory methods on the CertPathValidator class:

        public static CertPathValidator getInstance(String algorithm)
        public static CertPathValidator getInstance(String algorithm,
                                                    String provider)
        public static CertPathValidator getInstance(String algorithm,
                                                    Provider provider)
The algorithm parameter is the name of a certification path validation algorithm (for example, "PKIX"). Standard CertPathValidator algorithm names are listed in Appendix A.
Validating a Certification Path

Once a CertPathValidator object is created, paths can be validated by calling the validate method, passing it the certification path to be validated and a set of algorithm-specific parameters:

        public final CertPathValidatorResult
                validate(CertPath certPath, CertPathParameters params)
                throws CertPathValidatorException,
                       InvalidAlgorithmParameterException

If the validation algorithm is successful, the result is returned in an object implementing the CertPathValidatorResult interface. Otherwise, a CertPathValidatorException is thrown. The CertPathValidatorException contains methods that return the CertPath, and if relevant, the index of the certificate that caused the algorithm to fail and the root exception or cause of the failure.

Note that the CertPath and CertPathParameters passed to the validate method must be of a type that is supported by the validation algorithm. Otherwise, an InvalidAlgorithmParameterException is thrown. For example, a CertPathValidator instance that implements the PKIX algorithm validates CertPath objects of type X.509 and CertPathParameters that are an instance of PKIXParameters.

The CertPathValidatorResult Interface

The CertPathValidatorResult interface is a transparent representation of the successful result or output of a certification path validation algorithm. Its main purpose is to group (and provide type safety for) all validation results. Like the CertPathParameters interface, CertPathValidatorResult extends Cloneable and defines a clone() method that does not throw an exception. This allows applications to clone any CertPathValidatorResult object.

Objects implementing the CertPathValidatorResult interface are returned by the validate method of CertPathValidator (only when successful; otherwise a CertPathValidatorException is thrown with a description of the failure). Typically, a concrete implementation of the CertPathValidatorResult interface will hold a set of output parameters specific to a particular certification path validation algorithm. For example, the PKIXCertPathValidatorResult class is an implementation of the CertPathValidatorResult interface which contains methods to get the output parameters of the PKIX certification path validation algorithm. One such parameter is the valid policy tree. This parameter among others is discussed in more detail in the section discussing the PKIXCertPathValidatorResult class.

Here's a simplified code sample that illustrates how to create a CertPathValidator and use it to validate a certification path. The sample assumes that the CertPath and CertPathParameters objects which are passed to the validate method have been previously created; a more complete example will be illustrated in the section describing the PKIX classes.

    // create CertPathValidator that implements the "PKIX" algorithm
    CertPathValidator cpv = null;
    try {
        cpv = CertPathValidator.getInstance("PKIX");
    } catch (NoSuchAlgorithmException nsae) {
        System.err.println(nsae);
        System.exit(1);
    }
    // validate certification path ("cp") with specified parameters ("params")
    try {
        CertPathValidatorResult cpvResult = cpv.validate(cp, params);
    } catch (InvalidAlgorithmParameterException iape) {
        System.err.println("validation failed: " + iape);
        System.exit(1);
    } catch (CertPathValidatorException cpve) {
        System.err.println("validation failed: " + cpve);
        System.err.println("index of certificate that caused exception: "
                + cpve.getIndex());
        System.exit(1);
    }

Certification Path Building Classes

The Java Certification Path API includes classes for building (or discovering) certification paths. An application uses an instance of the CertPathBuilder class to build a CertPath object. If successful, the result of the build is returned in an object implementing the CertPathBuilderResult interface.

The CertPathBuilder Class

The CertPathBuilder class is an engine class used to build a certification path.

Creating a CertPathBuilder Object

As with all engine classes, the way to get a CertPathBuilder object for a particular build algorithm is to call one of the getInstance static factory method on the CertPathBuilder class:

        public static CertPathBuilder getInstance(String algorithm)
        public static CertPathBuilder getInstance(String algorithm,
                                                  String provider)
        public static CertPathBuilder getInstance(String algorithm,
                                                  Provider provider)
The algorithm parameter is the name of a certification path builder algorithm (for example, "PKIX"). Standard CertPathBuilder algorithm names are listed in Appendix A.
Building a Certification Path

Once a CertPathBuilder object is created, paths can be constructed by calling the build method, passing it an algorithm-specific parameter specification:

        public final CertPathBuilderResult build(CertPathParameters params)
                throws CertPathBuilderException,
                       InvalidAlgorithmParameterException

If the build algorithm is successful, the result is returned in an object implementing the CertPathBuilderResult interface. Otherwise, a CertPathBuilderException is thrown containing information about the failure; for example, the underlying exception (if any) and an error message.

Note that the CertPathParameters passed to the build method must be of a type that is supported by the build algorithm. Otherwise, an InvalidAlgorithmParameterException is thrown.

The CertPathBuilderResult Interface

The CertPathBuilderResult interface is a transparent representation of the result or output of a certification path builder algorithm. This interface contains a method to return the certification path that has been successfully built:

        public CertPath getCertPath()

The purpose of the CertPathBuilderResult interface is to group (and provide type safety for) all build results. Like the CertPathValidatorResult interface, CertPathBuilderResult extends Cloneable and defines a clone() method that does not throw an exception. This allows applications to clone any CertPathBuilderResult object.

Objects implementing the CertPathBuilderResult interface are returned by the build method of CertPathBuilder.

Here's a simplified code sample that illustrates how to create a CertPathBuilder and use it to build a certification path. The sample assumes that the CertPathParameters object which is passed to the build method has been previously created; a more complete example will be illustrated in the section describing the PKIX classes.

    // create CertPathBuilder that implements the "PKIX" algorithm
    CertPathBuilder cpb = null;
    try {
        cpb = CertPathBuilder.getInstance("PKIX");
    } catch (NoSuchAlgorithmException nsae) {
        System.err.println(nsae);
        System.exit(1);
    }
    // build certification path using specified parameters ("params")
    try {
        CertPathBuilderResult cpbResult = cpb.build(params);
        CertPath cp = cpbResult.getCertPath();
        System.out.println("build passed, path contents: " + cp);
    } catch (InvalidAlgorithmParameterException iape) {
        System.err.println("build failed: " + iape);
        System.exit(1);
    } catch (CertPathBuilderException cpbe) {
        System.err.println("build failed: " + cpbe);
        System.exit(1);
    }

Certificate/CRL Storage Classes

The Java Certification Path API also includes the CertStore class for retrieving certificates and CRLs from a repository. This is useful because it allows a caller to specify the repository a CertPathValidator or CertPathBuilder implementation should use to find certificates and CRLs (see the addCertStores method of PKIXParameters for an example).

A CertPathValidator implementation may use the CertStore object that the caller specifies as a callback mechanism to fetch CRLs for performing revocation checks. Similarly, a CertPathBuilder may use the CertStore as a callback mechanism to fetch certitificates and, if performing revocation checks, CRLs.

The CertStore Class

The CertStore class is an engine class used to provide the functionality of a certificate and certificate revocation list (CRL) repository. It can be used by CertPathBuilder and CertPathValidator implementations to find certificates and CRLs or as a general purpose certificate and CRL retrieval mechanism.

Unlike the java.security.KeyStore class, which provides access to a cache of private keys and trusted certificates, a CertStore is designed to provide access to a potentially vast repository of untrusted certificates and CRLs. For example, an LDAP implementation of CertStore provides access to certificates and CRLs stored in one or more directories using the LDAP protocol.

All public methods of CertStore objects are thread-safe. That is, multiple threads may concurrently invoke these methods on a single CertStore object (or more than one) with no ill effects. This allows a CertPathBuilder to search for a CRL while simultaneously searching for further certificates, for instance.

Creating a CertStore Object

As with all engine classes, the way to get a CertStore object for a particular repository type is to call one of the getInstance static factory methods on the CertStore class:

        public static CertStore getInstance(String type,
                CertStoreParameters params)
        public static CertStore getInstance(String type,
                CertStoreParameters params, String provider)
        public static CertStore getInstance(String type,
                CertStoreParameters params, Provider provider)
The type parameter is the name of a certificate repository type (for example, "LDAP"). Standard CertStore types are listed in Appendix A.

The initialization parameters (params) are specific to the repository type. For example, the initialization parameters for a server-based repository may include the hostname and the port of the server. An InvalidAlgorithmParameterException is thrown if the parameters are invalid for this CertStore type. The getCertStoreParameters method returns the CertStoreParameters that were used to initialize a CertStore:

        public final CertStoreParameters getCertStoreParameters()
Retrieving Certificates

Once you have created a CertStore object, you can retrieve certificates from the repository using the getCertificates method. This method takes a CertSelector (discussed in more detail later) object as an argument, which specifies a set of selection criteria for determining which certificates should be returned:

        public final Collection<? extends Certificate> getCertificates(CertSelector selector)
                throws CertStoreException

This method returns a Collection of java.security.cert.Certificate objects that satisfy the selection criteria. An empty Collection is returned if there are no matches. A CertStoreException is usually thrown if an unexpected error condition is encountered, such as a communications failure with a remote repository.

For some CertStore implementations, it may not be feasible to search the entire repository for certificates or CRLs that match the specified selection criteria. In these instances, the CertStore implementation may use information that is specified in the selectors to locate certificates and CRLs. For instance, an LDAP CertStore may not search all entries in the directory. Instead, it may just search entries that are likely to contain the certificates it is looking for. If the CertSelector provided does not provide enough information for the LDAP CertStore to determine which entries it should look in, the LDAP CertStore may throw a CertStoreException.

Retrieving CRLs

You can also retrieve CRLs from the repository using the getCRLs method. This method takes a CRLSelector (discussed in more detail later) object as an argument, which specifies a set of selection criteria for determining which CRLs should be returned:

        public final Collection<? extends CRL> getCRLs(CRLSelector selector)
                throws CertStoreException

This method returns a Collection of java.security.cert.CRL objects that satisfy the selection criteria. An empty Collection is returned if there are no matches.

The CertStoreParameters Interface

The CertStoreParameters interface is a transparent representation of the set of parameters used with a particular CertStore. Its main purpose is to group (and provide type safety for) all certificate storage parameter specifications. The CertStoreParameters interface extends the Cloneable interface and defines a clone method that does not throw an exception. Implementations of this interface should implement and override the Object.clone() method, if necessary. This allows applications to clone any CertStoreParameters object.

Objects implementing the CertStoreParameters interface are passed as arguments to the getInstance method of the CertStore class. Two classes implementing the CertStoreParameters interface are defined in this API: the LDAPCertStoreParameters and the CollectionCertStoreParameters classes.

The LDAPCertStoreParameters Class

The LDAPCertStoreParameters class is an implementation of the CertStoreParameters interface and holds a set of minimal initialization parameters (host and port number of the directory server) for retrieving certificates and CRLs from a CertStore of type LDAP.

Please refer to the LDAPCertStoreParameters API documentation for more detailed information on this class.

The CollectionCertStoreParameters Class

The CollectionCertStoreParameters class is an implementation of the CertStoreParameters interface and holds a set of initialization parameters for retrieving certificates and CRLs from a CertStore of type Collection.

Please refer to the CollectionCertStoreParameters API documentation for more detailed information on this class.

The CertSelector and CRLSelector Interfaces

The CertSelector and CRLSelector interfaces are a specification of the set of criteria for selecting certificates and CRLs from a collection or large group of certificates and CRLs. The interfaces group and provide type safety for all selector specifications. Each selector interface extends Cloneable and defines a clone() method that does not throw an exception. This allows applications to clone any CertSelector or CRLSelector object.

The CertSelector and CRLSelector interfaces each define a method named match. The match method takes a Certificate or CRL object as an argument and returns true if the object satisfies the selection criteria. Otherwise, it returns false. The match method for the CertSelector interface is defined as follows:

        public boolean match(Certificate cert)

and for the CRLSelector interface:

        public boolean match(CRL crl)

Typically, objects implementing these interfaces are passed as parameters to the getCertificates and getCRLs methods of the CertStore class. These methods return a Collection of Certificates or CRLs from the CertStore repository that match the specified selection criteria. CertSelectors may also be used to specify the validation constraints on a target or end-entity certificate in a certification path (see for example, the PKIXParameters.setTargetCertConstraints method.

The X509CertSelector Class

The X509CertSelector class is an implementation of the CertSelector interface that defines a set of criteria for selecting X.509 certificates. An X509Certificate object must match all of the specified criteria to be selected by the match method. The selection criteria are designed to be used by a CertPathBuilder implementation to discover potential certificates as it builds an X.509 certification path.

For example, the setSubject method of X509CertSelector allows a PKIX CertPathBuilder to filter out X509Certificates that do not match the issuer name of the preceding X509Certificate in a partially completed chain. By setting this and other criteria in an X509CertSelector object, a CertPathBuilder is able to discard irrelevant certificates and more easily find an X.509 certification path that meets the requirements specified in the CertPathParameters object.

Please refer to http://www.ietf.org/rfc/rfc3280.txt for definitions of the X.509 certificate extensions mentioned in this section.

Creating an X509CertSelector Object

An X509CertSelector object is created by calling the default constructor:

        public X509CertSelector()

No criteria are initially set (any X509Certificate will match).

Setting Selection Criteria

The selection criteria allow a caller to match on different components of an X.509 certificate. A few of the methods for setting selection criteria are described here. Please refer to the X509CertSelector API documentation for details on the other methods.

The setIssuer methods set the issuer criterion:

        public void setIssuer(X500Principal issuer)
        public void setIssuer(String issuerDN)
        public void setIssuer(byte[] issuerDN)

The specified distinguished name (in X500Principal, RFC 2253 String or ASN.1 DER encoded form) must match the issuer distinguished name in the certificate. If null, any issuer distinguished name will do. Note that use of an X500Principal to represent a distinguished name is preferred because it is more efficient and suitably typed.

Similarly, the setSubject methods set the subject criterion:

        public void setSubject(X500Principal subject)
        public void setSubject(String subjectDN)
        public void setSubject(byte[] subjectDN)

The specified distinguished name (in X500Principal, RFC 2253 String or ASN.1 DER encoded form) must match the subject distinguished name in the certificate. If null, any subject distinguished name will do.

The setSerialNumber method sets the serialNumber criterion:

        public void setSerialNumber(BigInteger serial)

The specified serial number must match the certificate serial number in the certificate. If null, any certificate serial number will do.

The setAuthorityKeyIdentifier method sets the authorityKeyIdentifier criterion:

        public void setAuthorityKeyIdentifier(byte[] authorityKeyID)

The certificate must contain an Authority Key Identifier extension matching the specified value. If null, no check will be done on the authorityKeyIdentifier criterion.

The setCertificateValid method sets the certificateValid criterion:

        public void setCertificateValid(Date certValid)

The specified date must fall within the certificate validity period for the certificate. If null, any date is valid.

The setKeyUsage method sets the keyUsage criterion:

        public void setKeyUsage(boolean[] keyUsage)

The certificate's Key Usage Extension must allow the specified key usage values (those which are set to true). If null, no keyUsage check will be done.

Getting Selection Criteria

The current values for each of the selection criteria can be retrieved using an appropriate get method. Please refer to the X509CertSelector API documentation for further details on these methods.

Example

Here is an example of retrieving X.509 certificates from an LDAP CertStore with the X509CertSelector class.

First, we create the LDAPCertStoreParameters object that we will use to initialize the CertStore object with the hostname and port of the LDAP server:

        LDAPCertStoreParameters lcsp = new
                LDAPCertStoreParameters("ldap.sun.com", 389);

Next, create the CertStore object, and pass it the LDAPCertStoreParameters object, as in the following statement:

        CertStore cs = CertStore.getInstance("LDAP", lcsp);

This call creates a CertStore object that retrieves certificates and CRLs from an LDAP repository using the schema defined in RFC 2587.

The following block of code establishes an X509CertSelector to retrieve all unexpired (as of the current date and time) end-entity certificates issued to a particular subject with 1) a key usage that allows digital signatures, and 2) a subject alternative name with a specific email address:

        X509CertSelector xcs = new X509CertSelector();
        // select only unexpired certificates
        xcs.setCertificateValid(new Date());
        // select only certificates issued to
        // 'CN=alice, O=xyz, C=us'
        xcs.setSubject(new X500Principal("CN=alice, O=xyz, C=us"));
        // select only end-entity certificates
        xcs.setBasicConstraints(-2);
        // select only certificates with a digitalSignature
        // keyUsage bit set (set the first entry in the
        // boolean array to true)
        boolean[] keyUsage = {true};
        xcs.setKeyUsage(keyUsage);
        // select only certificates with a subjectAltName of
        // 'alice@xyz.com' (1 is the integer value of
        // an RFC822Name)
        xcs.addSubjectAlternativeName(1, "alice@xyz.com");

Then we pass the selector to the getCertificates method of our CertStore object that we previously created:

        Collection<Certificate> certs = cs.getCertificates(xcs);

A PKIX CertPathBuilder may use similar code to help discover and sort through potential certificates by discarding those that do not meet validation constraints or other criteria.

The X509CRLSelector Class

The X509CRLSelector class is an implementation of the CRLSelector interface that defines a set of criteria for selecting X.509 CRLs. An X509CRL object must match all of the specified criteria to be selected by the match method. The selection criteria are designed to be useful to a CertPathValidator or CertPathBuilder implementation that must retrieve CRLs from a repository to check the revocation status of certificates in an X.509 certification path.

For example, the setDateAndTime method of X509CRLSelector allows a PKIX CertPathValidator to filter out X509CRLs that have been issued after or expire before the time indicated. By setting this and other criteria in an X509CRLSelector object, it allows the CertPathValidator to discard irrelevant CRLs and more easily check if a certificate has been revoked.

Please refer to http://www.ietf.org/rfc/rfc3280.txt for definitions of the X.509 CRL fields and extensions mentioned in this section.

Creating an X509CRLSelector Object

An X509CRLSelector object is created by calling the default constructor:

        public X509CRLSelector()

No criteria are initially set (any X509CRL will match).

Setting Selection Criteria

The selection criteria allow a caller to match on different components of an X.509 CRL. Most of the methods for setting selection criteria are described here. Please refer to the X509CRLSelector API documentation for details on the remaining methods.

The setIssuers and setIssuerNames methods set the issuerNames criterion:

        public void setIssuers(Collection<X500Principal> issuers)
        public void setIssuerNames(Collection<?> names)

The issuer distinguished name in the CRL must match at least one of the specified distinguished names. The setIssuers method is preferred as the use of X500Principals to represent distinguished names is more efficient and suitably typed. For the setIssuerNames method, each entry of the names argument is either a String or a byte array (representing the name, in RFC 2253 or ASN.1 DER encoded form, respectively). If null, any issuer distinguished name will do.

The setMinCRLNumber and setMaxCRLNumber methods set the minCRLNumber and maxCRLNumber criterion:

        public void setMinCRLNumber(BigInteger minCRL)
        public void setMaxCRLNumber(BigInteger maxCRL)

The CRL must have a CRL Number extension whose value is greater than or equal to the specified value if the setMinCRLNumber method is called, and less than or equal to the specified value if the setMaxCRLNumber method is called. If the value passed to one of these methods is null, the corresponding check is not done.

The setDateAndTime method sets the dateAndTime criterion:

        public void setDateAndTime(Date dateAndTime)

The specified date must be equal to or later than the value of the thisUpdate component of the CRL and earlier than the value of the nextUpdate component. If null, no dateAndTime check will be done.

The setCertificateChecking method sets the certificate whose revocation status is being checked:

        public void setCertificateChecking(X509Certificate cert)

This is not a criterion. Rather, it is optional information that may help a CertStore find CRLs that would be relevant when checking revocation for the specified certificate. If null is specified, then no such optional information is provided. An application should always call this method when checking revocation for a particular certificate, as it may provide the CertStore with more information for finding the correct CRLs and filtering out irrelevant ones.

Getting Selection Criteria

The current values for each of the selection criteria can be retrieved using an appropriate get method. Please refer to the X509CRLSelectorAPI documentation for further details on these methods.

Example

Creating an X509CRLSelector to retrieve CRLs from an LDAP repository is similar to the X509CertSelector example. Suppose we want to retrieve all current (as of the current date and time) CRLs issued by a specific CA and with a minimum CRL number. First, we create an X509CRLSelector object and call the appropriate methods to set the selection criteria:

        X509CRLSelector xcrls = new X509CRLSelector();
        // select CRLs satisfying current date and time
        xcrls.setDateAndTime(new Date());
        // select CRLs issued by 'O=xyz, C=us'
        xcrls.addIssuerName("O=xyz, C=us");
        // select only CRLs with a CRL number at least '2'
        xcrls.setMinCRLNumber(new BigInteger("2"));

Then we pass the selector to the getCRLs method of our CertStore object (created in the X509CertSelector example):

        Collection<CRL> crls = cs.getCRLs(xcrls);

PKIX Classes

The Java Certification Path API also includes a set of algorithm-specific classes modelled for use with the PKIX certification path validation algorithm defined in RFC 3280: Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile.

The TrustAnchor Class

This class represents a "most-trusted CA", which is used as a trust anchor for validating X.509 certification paths. A most-trusted CA includes the public key of the CA, the CA's name, and any constraints upon the set of paths which may be validated using this key. These parameters can be specified in the form of a trusted X509Certificate or as individual parameters.

All TrustAnchor objects are immutable and thread-safe. That is, multiple threads may concurrently invoke the methods defined in this class on a single TrustAnchor object (or more than one) with no ill effects. Requiring TrustAnchor objects to be immutable and thread-safe allows them to be passed around to various pieces of code without worrying about coordinating access.

Note that although this class is described as a PKIX class it may be used with other X.509 certification path validation algorithms.

Creating a TrustAnchor Object

To instantiate a TrustAnchor object, a caller must specify "the most-trusted CA" as a trusted X509Certificate or public key and distinguished name pair. The caller may also optionally specify name constraints that are applied to the trust anchor by the validation algorithm during initialization. Note that support for name constraints on trust anchors is not required by the PKIX algorithm, therefore a PKIX CertPathValidator or CertPathBuilder may choose not to support this parameter and instead throw an exception. Use one of the following constructors to create a TrustAnchor object:

        public TrustAnchor(X509Certificate trustedCert,
                byte[] nameConstraints)
        public TrustAnchor(X500Principal caPrincipal, PublicKey pubKey,
                byte[] nameConstraints)
        public TrustAnchor(String caName, PublicKey pubKey,
                byte[] nameConstraints)

The nameConstraints parameter is specifed as a byte array containing the ASN.1 DER encoding of a NameConstraints extension. An IllegalArgumentException is thrown if the name constraints cannot be decoded (are not formatted correctly).

Getting Parameter Values

Each of the parameters can be retrieved using a corresponding get method:

        public final X509Certificate getTrustedCert()
        public final X500Principal getCA()
        public final String getCAName()
        public final PublicKey getCAPublicKey()
        public final byte[] getNameConstraints()
Note that the getTrustedCert method returns null if the trust anchor was specified as a public key and name pair. Likewise, the getCA, getCAName and getCAPublicKey methods return null if the trust anchor was specified as an X509Certificate.

The PKIXParameters Class

This class (which implements the CertPathParameters interface) specifies the set of input parameters defined by the PKIX certification path validation algorithm. It also includes a few additional useful parameters.

An X.509 CertPath object and a PKIXParameters object are passed as arguments to the validate method of a CertPathValidator instance implementing the PKIX algorithm. The CertPathValidator uses the parameters to initialize the PKIX certification path validation algorithm.

Creating a PKIXParameters Object

To instantiate a PKIXParameters object, a caller must specify "the most-trusted CA(s)" as defined by the PKIX validation algorithm. The most-trusted CAs can be specified using one of two constructors:

        public PKIXParameters(Set<TrustAnchor> trustAnchors)
            throws InvalidAlgorithmParameterException
        public PKIXParameters(KeyStore keystore)
            throws KeyStoreException, InvalidAlgorithmParameterException

The first constructor allows the caller to specify the most-trusted CAs as a Set of TrustAnchor objects. Alternatively, a caller can use the second constructor and specify a KeyStore instance containing trusted certificate entries, each of which will be considered as a most-trusted CA.

Setting Parameter Values

Once a PKIXParameters object has been created, a caller can set (or replace the current value of) various parameters. A few of the methods for setting parameters are described here. Please refer to the PKIXParameters API documentation for details on the other methods.

The setInitialPolicies method sets the initial policy identifiers, as specified by the PKIX validation algorithm. The elements of the Set are object identifiers (OIDs) represented as a String. If the initialPolicies parameter is null or not set, any policy is acceptable:

        public void setInitialPolicies(Set<String> initialPolicies)

The setDate method sets the time for which the validity of the path should be determined. If the date parameter is not set or is null, the current date is used:

        public void setDate(Date date)

The setPolicyMappingInhibited method sets the value of the policy mapping inhibited flag. The default value for the flag, if not specified, is false:

        public void setPolicyMappingInhibited(boolean val)

The setExplicitPolicyRequired method sets the value of the explicit policy required flag. The default value for the flag, if not specified, is false:

        public void setExplicitPolicyRequired(boolean val)

The setAnyPolicyInhibited method sets the value of the any policy inhibited flag. The default value for the flag, if not specified, is false:

        public void setAnyPolicyInhibited(boolean val)

The setTargetCertConstraints method allows the caller to set constraints on the target or end-entity certificate. For example, the caller can specify that the target certificate must contain a specific subject name. The constraints are specified as a CertSelector object. If the selector parameter is null or not set, no constraints are defined on the target certificate:

        public void setTargetCertConstraints(CertSelector selector)

The setCertStores method allows a caller to specify a List of CertStore objects that will be used by a PKIX implementation of CertPathValidator to find CRLs for path validation. This provides an extensible mechanism for specifying where to locate CRLs. The setCertStores method takes a List of CertStore objects as a parameter. The first CertStores in the list may be preferred to those that appear later.

        public void setCertStores(List<CertStore> stores)

The setCertPathCheckers method allows a caller to extend the PKIX validation algorithm by creating implementation-specific certification path checkers. For example, this mechanism can be used to process private certificate extensions. The setCertPathCheckers method takes a list of PKIXCertPathChecker (discussed later) objects as a parameter:

        public void setCertPathCheckers(List<PKIXCertPathChecker> checkers)

The setRevocationEnabled method allows a caller to disable revocation checking. Revocation checking is enabled by default, since it is a required check of the PKIX validation algorithm. However, PKIX does not define how revocation should be checked. An implementation may use CRLs or OCSP, for example. This method allows the caller to disable the implementation's default revocation checking mechanism if it is not appropriate. A different revocation checking mechanism can then be specified by calling the setCertPathCheckers method, and passing it a PKIXCertPathChecker that implements the alternate mechanism.

        public void setRevocationEnabled(boolean val)

The setPolicyQualifiersRejected method allows a caller to enable or disable policy qualifier processing. When a PKIXParameters object is created, this flag is set to true. This setting reflects the most common (and simplest) strategy for processing policy qualifiers. Applications that want to use a more sophisticated policy must set this flag to false.

        public void setPolicyQualifiersRejected(boolean qualifiersRejected)
Getting Parameter Values

The current values for each of the parameters can be retrieved using an appropriate get method. Please refer to the PKIXParameters API documentation for further details on these methods.

The PKIXCertPathValidatorResult Class

This class (which implements the CertPathValidatorResult interface) represents the result of the PKIX certification path validation algorithm. It holds the valid policy tree and subject public key resulting from the validation algorithm, and includes methods (getPolicyTree() and getPublicKey()) for returning them. Instances of PKIXCertPathValidatorResult are returned by the validate method of CertPathValidator objects implementing the PKIX algorithm.

Please refer to the PKIXCertPathValidatorResult API documentation for more detailed information on this class.

The PolicyNode Interface and PolicyQualifierInfo Class

The PKIX validation algorithm defines several outputs related to certificate policy processing. Most applications will not need to use these outputs, but all providers that implement the PKIX validation or building algorithm must support them.

The PolicyNode interface represents a node of a valid policy tree resulting from a successful execution of the PKIX certification path validation. An application can obtain the root of a valid policy tree using the getPolicyTree method of PKIXCertPathValidatorResult. Policy Trees are discussed in more detail in the PKIX Certificate and CRL Profile.

The getPolicyQualifiers method of PolicyNode returns a Set of PolicyQualifierInfo objects, each of which represents a policy qualifier contained in the Certificate Policies extension of the relevant certificate that this policy applies to.

Most applications will not need to examine the valid policy tree and policy qualifiers. They can achieve their policy processing goals by setting the policy-related parameters in PKIXParameters. However, the valid policy tree is available for more sophisticated applications, especially those that process policy qualifiers.

Please refer to the PolicyNode and PolicyQualifierInfo API documentation for more detailed information on these classes.

Example of Validating a Certification Path using the PKIX algorithm

This is an example of validating a certification path with the PKIX validation algorithm. The example ignores most of the exception handling and assumes that the certification path and public key of the trust anchor have already been created.

First, create the CertPathValidator, as in the following line:

    CertPathValidator cpv = CertPathValidator.getInstance("PKIX");

The next step is to create a TrustAnchor object. This will be used as an anchor for validating the certification path. In this example, the most-trusted CA is specified as a public key and name (name constraints are not applied and are specified as null):

    TrustAnchor anchor = new TrustAnchor("O=xyz,C=us", pubkey, null);

The next step is to create a PKIXParameters object. This will be used to populate the parameters used by the PKIX algorithm. In this example, we pass to the constructor a Set containing a single element - the TrustAnchor we created in the previous step:

    PKIXParameters params = new PKIXParameters(Collections.singleton(anchor));

Next, we populate the parameters object with constraints or other parameters used by the validation algorithm. In this example, we enable the explicitPolicyRequired flag and specify a set of initial policy OIDs (the contents of the set are not shown):

    // set other PKIX parameters here
    params.setExplicitPolicyRequired(true);
    params.setInitialPolicies(policyIds);

The final step is to validate the certification path using the input parameter set we have created:

    try {
        PKIXCertPathValidatorResult result =
            (PKIXCertPathValidatorResult) cpv.validate(certPath, params);
        PolicyNode policyTree = result.getPolicyTree();
        PublicKey subjectPublicKey = result.getPublicKey();
    } catch (CertPathValidatorException cpve) {
        System.out.println("Validation failure, cert["
            + cpve.getIndex() + "] :" + cpve.getMessage());
    }

If the validation algorithm is successful, the policy tree and subject public key resulting from the validation algorithm are obtained using the getPolicyTree and getPublicKey methods of PKIXCertPathValidatorResult.

Otherwise, a CertPathValidatorException is thrown and the caller can catch the exception and print some details about the failure, such as the error message and the index of the certificate that caused the failure.

The PKIXBuilderParameters Class

This class (which extends the PKIXParameters class) specifies the set of parameters to be used with CertPathBuilders that build certification paths validated against the PKIX certification path validation algorithm.

A PKIXBuilderParameters object is passed as an argument to the build method of a CertPathBuilder instance implementing the PKIX algorithm. All PKIX CertPathBuilders must return certification paths which have been validated according to the PKIX certification path validation algorithm.

Please note that the mechanism that a PKIX CertPathBuilder uses to validate a constructed path is an implementation detail. For example, an implementation might attempt to first build a path with minimal validation and then fully validate it using an instance of a PKIX CertPathValidator, whereas a more efficient implementation may validate more of the path as it is building it, and backtrack to previous stages if it encounters validation failures or dead-ends.

Creating a PKIXBuilderParameters Object

Creating a PKIXBuilderParameters object is similar to creating a PKIXParameters object. However, a caller must specify constraints on the target or end-entity certificate when creating a PKIXBuilderParameters object. These constraints should provide the CertPathBuilder with enough information to find the target certificate. The constraints are specified as a CertSelector object. Use one of the following constructors to create a PKIXBuilderParameters object:

        public PKIXBuilderParameters(Set<TrustAnchor> trustAnchors,
                CertSelector targetConstraints)
                throws InvalidAlgorithmParameterException
        public PKIXBuilderParameters(KeyStore keystore,
                CertSelector targetConstraints)
                throws KeyStoreException, InvalidAlgorithmParameterException
Getting/Setting Parameter Values

The PKIXBuilderParameters class inherits all of the parameters that can be set in the PKIXParameters class. In addition, the setMaxPathLength method can be called to place a limit on the maximum number of certificates in a certification path:

        public void setMaxPathLength(int maxPathLength)

The maxPathLength parameter specifies the maximum number of non-self-issued intermediate certificates that may exist in a certification path. A CertPathBuilder instance implementing the PKIX algorithm must not build paths longer than the length specified. If the value is 0, the path can only contain a single certificate. If the value is -1, the path length is unconstrained (i.e., there is no maximum). The default maximum path length, if not specified, is 5. This method is useful to prevent the CertPathBuilder from spending resources and time constructing long paths that may or may not meet the caller's requirements.

If any of the CA certificates in the path contain a Basic Constraints extension, the value of the pathLenConstraint component of the extension overrides the value of the maxPathLength parameter whenever the result is a certification path of smaller length. There is also a corresponding getMaxPathLength method for retrieving this parameter:

        public int getMaxPathLength()

Also, the setCertStores method (inherited from the PKIXParameters class) is typically used by a PKIX implementation of CertPathBuilder to find Certificates for path construction as well as finding CRLs for path validation. This provides an extensible mechanism for specifying where to locate Certificates and CRLs.

The PKIXCertPathBuilderResult Class

This class (which extends the PKIXCertPathValidatorResult class and implements the CertPathBuilderResult interface) represents the successful result of the PKIX certification path construction algorithm. Instances of PKIXCertPathBuilderResult are returned by the build method of CertPathBuilder objects implementing the PKIX algorithm.

The getCertPath method of a PKIXCertPathBuilderResult instance always returns a CertPath object validated using the PKIX certification path validation algorithm. The returned CertPath object does not include the most-trusted CA certificate that may have been used to anchor the path. Instead, use the getTrustAnchor method to get the Certificate of the most-trusted CA.

Please refer to the PKIXCertPathBuilderResult API documentation for more detailed information on this class.

Example of Building a Certification Path using the PKIX algorithm

This is an example of building a certification path validated against the PKIX algorithm. Some details have been left out, such as exception handling, and the creation of the trust anchors and certificates for populating the CertStore.

First, create the CertPathBuilder, as in the following example:

    CertPathBuilder cpb = CertPathBuilder.getInstance("PKIX");

This call creates a CertPathBuilder object that returns paths validated against the PKIX algorithm.

The next step is to create a PKIXBuilderParameters object. This will be used to populate the PKIX parameters used by the CertPathBuilder:

    // Create parameters object, passing it a Set of
    // trust anchors for anchoring the path
    // and a target subject DN.
    X509CertSelector targetConstraints = new X509CertSelector();
    targetConstraints.setSubject("CN=alice,O=xyz,C=us");
    PKIXBuilderParameters params =
        new PKIXBuilderParameters(trustAnchors, targetConstraints);

The next step is to specify the CertStore that the CertPathBuilder will use to look for certificates and CRLs. For this example, we will populate a Collection CertStore with the certificates and CRLs:

    CollectionCertStoreParameters ccsp =
        new CollectionCertStoreParameters(certsAndCrls);
    CertStore store = CertStore.getInstance("Collection", ccsp);
    params.addCertStore(store);

The next step is to build the certification path using the input parameter set we have created:

    try {
        PKIXCertPathBuilderResult result =
            (PKIXCertPathBuilderResult) cpb.build(params);
        CertPath cp = result.getCertPath();
    } catch (CertPathBuilderException cpbe) {
        System.out.println("build failed: " + cpbe.getMessage());
    }

If the CertPathBuilder cannot build a path that meets the supplied parameters it will throw a CertPathBuilderException. Otherwise, the validated certification path can be obtained from the PKIXCertPathBuilderResult using the getCertPath method.

The PKIXCertPathChecker Class

This section describes a powerful class that allows a user to extend a PKIX CertPathValidator or CertPathBuilder implementation. This is an advanced feature that most users will not need to understand. However, anyone implementing a PKIX service provider should read this section.

The PKIXCertPathChecker class is an abstract class that executes one or more checks on an X.509 certificate. Developers should create concrete implementations of the PKIXCertPathChecker class when it is necessary to dynamically extend a PKIX CertPathValidator or CertPathBuilder implementation at runtime. The following are a few examples of when a PKIXCertPathChecker implementation is useful:

  • If the revocation mechanism supplied by a PKIX CertPathValidator or CertPathBuilder implementation is not adequate. For example, a developer might implement a PKIXCertPathChecker that uses OCSP ( RFC 2560) to check that certificates have not been revoked.

  • If the user wants to recognize certificates containing a critical private extension. Since the extension is private, it will not be recognized by the PKIX CertPathValidator or CertPathBuilder implementation and a CertPathValidatorException will be thrown. In this case, a developer can implement a PKIXCertPathChecker that recognizes and processes the critical private extension.

  • If the developer wants to record information about each certificate processed for debugging or display purposes.

  • If the user wants to reject certificates with certain policy qualifiers.

The setCertPathCheckers method of the PKIXParameters class allows a user to pass a List of PKIXCertPathChecker objects to a PKIX CertPathValidator or CertPathBuilder implementation. Each of the PKIXCertPathChecker objects will be called in turn, for each certificate processed by the PKIX CertPathValidator or CertPathBuilder implementation.

Creating and using a PKIXCertPathChecker Object

The PKIXCertPathChecker class does not have a public constructor. This is intentional, since creating an instance of PKIXCertPathChecker is an implementation-specific issue. For example, the constructor for a PKIXCertPathChecker implementation that uses OCSP to check a certificate's revocation status may require the hostname and port of the OCSP server:

        PKIXCertPathChecker checker = new OCSPChecker("ocsp.sun.com", 1321);

Once the checker has been instantiated, it can be added as a parameter using the addCertPathChecker method of the PKIXParameters class:

        params.addCertPathChecker(checker);

Alternatively, a List of checkers can be added using the setCertPathCheckers method of the PKIXParameters class.

Implementing a PKIXCertPathChecker Object

The PKIXCertPathChecker class is abstract. It has four methods (check, getSupportedExtensions, init, and isForwardCheckingSupported) that all concrete subclasses must implement.

Implementing a PKIXCertPathChecker may be trivial or complex. A PKIXCertPathChecker implementation can be stateless or stateful. A stateless implementation does not maintain state between successive calls of the check method. For example, a PKIXCertPathChecker that checks that each certificate contains a particular policy qualifier is stateless. In contrast, a stateful implementation does maintain state between successive calls of the check method. The check method of a stateful implementation usually depends on the contents of prior certificates in the certification path. For example, a PKIXCertPathChecker that processes the NameConstraints extension is stateful.

Also, the order in which the certificates processed by a service provider implementation are presented (passed) to a PKIXCertPathChecker is very important, especially if the implementation is stateful. Depending on the algorithm used by the service provider, the certificates may be presented in reverse or forward order. A reverse ordering means that the certificates are ordered from the most trusted CA (if present) to the target subject, whereas a forward ordering means that the certificates are ordered from the target subject to the most trusted CA. The order must be made known to the PKIXCertPathChecker implementation, so that it knows how to process consecutive certificates.

Initializing a PKIXCertPathChecker Object

The init method initializes the internal state of the checker:

        public abstract void init(boolean forward)

All stateful implementations should clear or initialize any internal state in the checker. This prevents a service provider implementation from calling a checker that is in an uninitialized state. It also allows stateful checkers to be reused in subsequent operations without reinstantiating them. The forward parameter indicates the order of the certificates presented to the PKIXCertPathChecker. If forward is true, the certificates are presented from target to trust anchor; if false, from trust anchor to target.

Forward Checking

The isForwardCheckingSupported method returns a boolean that indicates if the PKIXCertPathChecker supports forward checking:

        public abstract boolean isForwardCheckingSupported()

All PKIXCertPathChecker implementations must support reverse checking. A PKIXCertPathChecker implementation may support forward checking.

Supporting forward checking improves the efficiency of CertPathBuilders that build forward, since it allows paths to be checked as they are built. However, some stateful PKIXCertPathCheckers may find it difficult or impossible to support forward checking.

Supported Extensions

The getSupportedExtensions method returns an immutable Set of OID Strings for the X.509 extensions that the PKIXCertPathChecker implementation supports (i.e., recognizes, is able to process):

        public abstract Set<String> getSupportedExtensions()

The method should return null if no extensions are processed. All implementations should return the Set of OID Strings that the check method may process.

A CertPathBuilder can use this information to identify certificates with unrecognized critical extensions, even when performing a forward build with a PKIXCertPathChecker that does not support forward checking.

Executing the Check

The following method executes a check on the certificate:

        public abstract void
                check(Certificate cert, Collection<String> unresolvedCritExts)
                throws CertPathValidatorException

The unresolvedCritExts parameter contains a collection of OIDs as Strings. These OIDs represent the set of critical extensions in the certificate that have not yet been resolved by the certification path validation algorithm. Concrete implementations of the check method should remove any critical extensions that it processes from the unresolvedCritExts parameter.

If the certificate does not pass the check(s), a CertPathValidatorException should be thrown.

Cloning a PKIXCertPathChecker

The PKIXCertPathChecker class implements the Cloneable interface. All stateful PKIXCertPathChecker implementations must override the clone method if necessary. The default implementation of the clone method calls the Object.clone method, which performs a simple clone by copying all fields of the original object to the new object. A stateless implementation should not override the clone method. However, all stateful implementations must ensure that the default clone method is correct, and override it if necessary. For example, a PKIXCertPathChecker that stores state in an array must override the clone method to make a copy of the array, rather than just a reference to the array.

The reason that PKIXCertPathChecker objects are Cloneable is to allow a PKIX CertPathBuilder implementation to efficiently backtrack and try another path when a potential certification path reaches a dead end or point of failure. In this case, the implementation is able to restore prior path validation states by restoring the cloned objects.

Example

This is an example of a stateless PKIXCertPathChecker implementation. It checks if a private extension exists in a certificate and processes it according to some rules.

        import java.security.cert.Certificate;
        import java.security.cert.X509Certificate;
        import java.util.Collection;
        import java.util.Collections;
        import java.util.Set;
        import java.security.cert.PKIXCertPathChecker;
        import java.security.cert.CertPathValidatorException;

        public class MyChecker extends PKIXCertPathChecker {
            private static Set supportedExtensions =
                Collections.singleton("2.16.840.1.113730.1.1");

            /*
             * Initialize checker
             */
            public void init(boolean forward)
                throws CertPathValidatorException {
                // nothing to initialize
            }

            public Set getSupportedExtensions() {
                return supportedExtensions;
            }

            public boolean isForwardCheckingSupported() {
                return true;
            }

            /*
             * Check certificate for presence of Netscape's
             * private extension
             * with OID "2.16.840.1.113730.1.1"
             */
            public void check(Certificate cert,
                              Collection unresolvedCritExts)
                throws CertPathValidatorException
            {
                X509Certificate xcert = (X509Certificate) cert;
                byte[] ext =
                    xcert.getExtensionValue("2.16.840.1.113730.1.1");
                if (ext == null)
                    return;

                //
              // process private extension according to some
                // rules - if check fails, throw a
                // CertPathValidatorException ...
                // {insert code here}

                // remove extension from collection of unresolved
                // extensions (if it exists)
                if (unresolvedCritExts != null)
                    unresolvedCritExts.remove("2.16.840.1.113730.1.1");
            }
        }
How a PKIX Service Provider implementation should use a PKIXCertPathChecker

Each PKIXCertPathChecker object must be initialized by a service provider implementation before commencing the build or validation algorithm, for example:

        List<PKIXCertPathChecker> checkers = params.getCertPathCheckers();
        for (PKIXCertPathChecker checker : checkers) {
            checker.init(false);
        }

For each certificate that it validates, the service provider implementation must call the check method of each PKIXCertPathChecker object in turn, passing it the certificate and any remaining unresolved critical extensions:

        for (PKIXCertPathChecker checker : checkers) {
            checker.check(cert, unresolvedCritExts);
        }

If any of the checks throw a CertPathValidatorException, a CertPathValidator implementation should terminate the validation procedure. However, a CertPathBuilder implementation may simply log the failure and continue to search for other potential paths. If all of the checks are successful, the service provider implementation should check that all critical extensions have been resolved and if not, consider the validation to have failed. For example:

        if (unresolvedCritExts != null &&
            !unresolvedCritExts.isEmpty())
        {
            // note that a CertPathBuilder may have an enclosing
            // try block to catch the exception below and continue on error
            throw new CertPathValidatorException
                ("Unrecognized Critical Extension");
        }

As discussed in the previous section, a CertPathBuilder implementation may need to backtrack when a potential certification path reaches a dead end or point of failure. Backtracking in this context implies returning to the previous certificate in the path and checking for other potential paths. If the CertPathBuilder implementation is validating the path as it is building it, it will need to restore the previous state of each PKIXCertPathChecker. It can do this by making clones of the PKIXCertPathChecker objects before each certificate is processed, for example:

        /* clone checkers */
        List newList = new ArrayList(checkers);
        ListIterator li = newList.listIterator();
        while (li.hasNext()) {
            PKIXCertPathChecker checker = (PKIXCertPathChecker) li.next();
            li.set(checker.clone());
        }

Using PKIXCertPathChecker in Certificate Path Validation

Using a PKIXCertPathChecker to customize certificate path validation is relatively straightfoward.

Basic Certification Path Validation

First, consider code that validates a certificate path:

Set<TrustAnchor> trustAnchors = getTrustAnchors();
CertPath cp = getCertPath();

PKIXParameters pkixp = new PKIXParameters(trustAnchors);
pkixp.setRevocationEnabled(false);

CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
PKIXCertPathValidatorResult pcpvr =
    (PKIXCertPathValidatorResult)cpv.validate(cp, pkixp);

If the validation fails, the validate() method throws an exception.

The fundamental steps are as follows:

  1. Obtain the CA root certiifcates and the certification path to be validated.
  2. Create a PKIXParameters with the trust anchors.
  3. Use a CertPathValidator to validate the certificate path.

In this example, getTrustAnchors() and getCertPath() are the methods that obtain CA root certificates and the certification path.

The getTrustAnchors() method in the example must return a Set of TrustAnchors that represent the CA root certificates you wish to use for validation. Here is one simple implementation that loads a single CA root certificate from a file:

public Set<TrustAnchor> getTrustAnchors()
    throws IOException, CertificateException {
  InputStream in = new FileInputStream("x509_ca-certificate.cer");
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  X509Certificate c = (X509Certificate)cf.generateCertificate(in);
  in.close();

  TrustAnchor anchor = new TrustAnchor(c, null);
  return Collections.singleton(anchor);
}

Similarly, here is a simple implementation of getCertPath() that loads a certificate path from a file:

public CertPath getCertPath() throws IOException, CertificateException {
  CertificateFactory cf = CertificateFactory.getInstance("X.509");

  InputStream in = new FileInputStream("certpath.pkcs7");
  CertPath cp = cf.generateCertPath(in, "PKCS7");
  in.close();

  return cp;
}

Note that PKCS#7 does not require a specific order for the certificates in the file, so this code only works for certification path validation when the certificates are ordered starting from the entity to be validated and progressing back toward the CA root. If the certificates are not in the right order, you need to do some additional processing. CertificateFactory has a generateCertPath() method that accepts a Collection, which is useful for this type of processing.

Adding in a PKIXCertPathChecker

To customize certification path validation, add a PKIXCertPathChecker as follows. In this example, SimpleChecker is a PKIXCertPathChecker subclass. The new lines are shown in bold.

Set<TrustAnchor> trustAnchors = getTrustAnchors();
CertPath cp = getCertPath();

PKIXParameters pkixp = new PKIXParameters(trustAnchors);
pkixp.setRevocationEnabled(false);

SimpleChecker sc = new SimpleChecker();
pkixp.addCertPathChecker(sc);

CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
PKIXCertPathValidatorResult pcpvr =
    (PKIXCertPathValidatorResult)cpv.validate(cp, pkixp);

SimpleChecker is a rudimentary subclass of PKIXCertPathChecker. Its check() method is called for every certificate in the certification path that is being validated. SimpleChecker uses an AlgorithmConstraints implementation to examine the signature algorithm and public key of each certificate.

import java.security.AlgorithmConstraints;
import java.security.CryptoPrimitive;
import java.security.Key;
import java.security.cert.*;
import java.util.*;

public class SimpleChecker extends PKIXCertPathChecker {
  private final static Set<CryptoPrimitive> SIGNATURE_PRIMITIVE_SET =
      EnumSet.of(CryptoPrimitive.SIGNATURE);

  public void init(boolean forward) throws CertPathValidatorException {}

  public boolean isForwardCheckingSupported() { return true; }

  public Set<String> getSupportedExtensions() { return null; }

  public void check(Certificate cert,
      Collection<String> unresolvedCritExts)
      throws CertPathValidatorException {
    X509Certificate c = (X509Certificate)cert;
    String sa = c.getSigAlgName();
    Key key = c.getPublicKey();

    AlgorithmConstraints constraints = new SimpleConstraints();

    if (constraints.permits(SIGNATURE_PRIMITIVE_SET, sa, null) == false)
      throw new CertPathValidatorException("Forbidden algorithm: " + sa);

    if (constraints.permits(SIGNATURE_PRIMITIVE_SET, key) == false)
      throw new CertPathValidatorException("Forbidden key: " + key);
  }
}

Finally, SimpleConstraints is a rather severe AlgorithmConstraints implementation that allows only RSA algorithms and requires keys to be 2048 bits or larger.

import java.security.AlgorithmConstraints;
import java.security.AlgorithmParameters;
import java.security.CryptoPrimitive;
import java.security.Key;
import java.security.interfaces.RSAKey;
import java.util.Set;

public class SimpleConstraints implements AlgorithmConstraints {
  public boolean permits(Set<CryptoPrimitive> primitives,
      String algorithm, AlgorithmParameters parameters) {
    return permits(primitives, algorithm, null, parameters);
  }

  public boolean permits(Set<CryptoPrimitive> primitives, Key key) {
    return permits(primitives, null, key, null);
  }

  public boolean permits(Set<CryptoPrimitive> primitives,
      String algorithm, Key key, AlgorithmParameters parameters) {
    if (algorithm == null) algorithm = key.getAlgorithm();

    if (algorithm.indexOf("RSA") == -1) return false;

    if (key != null) {
      RSAKey rsaKey = (RSAKey)key;
      int size = rsaKey.getModulus().bitLength();
      if (size < 2048) return false;
    }

    return true;
  }
}

Implementing a Service Provider

This section is intended for experienced programmers wishing to create their own provider packages supplying certification path service implementations. This section assumes you have read the document: How to Implement a Provider for the Java Cryptography Architecture.

The following engine classes are defined in the Java Certification Path API:

  • CertPathValidator - used to validate certification paths

  • CertPathBuilder - used to build certification paths

  • CertStore - used to retrieve certificates and CRLs from a repository

In addition, the pre-existing CertificateFactory engine class was enhanced in the JDK, v 1.4 to support generation of certification paths.

The application interfaces supplied by an engine class are implemented in terms of a "Service Provider Interface" (SPI). The name of each SPI class is the same as that of the corresponding engine class, followed by "Spi". For example, the SPI class corresponding to the CertPathValidator engine class is the CertPathValidatorSpi class. Each SPI class is abstract. To supply the implementation of a particular type of service, for a specific algorithm or type, a provider must subclass the corresponding SPI class and provide implementations for all the abstract methods. For example, the CertStore class provides access to the functionality of retrieving certificates and CRLs from a repository. The actual implementation supplied in a CertStoreSpi subclass would be that for a specific type of certificate repository, such as LDAP.

Steps to Implement and Integrate a Provider

Developers should follow the required steps listed in the How To Implement A Provider for the Java Cryptography Architecture document. Here are some additional rules to follow for certain steps:

Step 3: Write your "Master Class", a subclass of Provider

These are the properties that must be defined for the certification path services, where the algorithm name is substituted for algName, and certstore type for storeType:

  • CertPathValidator.algName

  • CertPathBuilder.algName

  • CertStore.storeType

See Appendix A for the standard names that are defined for algName and storeType. The value of each property must be the fully qualified name of the class implementing the specified algorithm, or certstore type. That is, it must be the package name followed by the class name, where the two are separated by a period. For example, a provider sets the CertPathValidator.PKIX property to have the value "sun.security.provider.certpath.PKIXCertPathValidator" as follows:

put("CertPathValidator.PKIX", "sun.security.provider.certpath.PKIXCertPathValidator")

In addition, service attributes can be defined for the certification path services. These attributes can be used as filters for selecting service providers. See Appendix A for the definition of some standard service attributes. For example, a provider may set the ValidationAlgorithm service attribute to the name of an RFC or specification that defines the PKIX validation algorithm:

put("CertPathValidator.PKIX ValidationAlgorithm", "RFC3280");

Step 8: Document your Provider and its Supported Services

Certification path service providers should document the following information for each SPI:

Certificate Factories

A provider should document what types of certification paths (and the version numbers of the certificates in the path, if relevant) can be created by the factory. A provider should describe the ordering of the certificates in the certification path, as well as the contents.

A provider should document the list of encoding formats supported. This is not technically necessary, since the client can request them by calling the getCertPathEncodings method. However, the documentation should describe each encoding format in more detail and reference any standards when applicable.

Certification Path Validators

A provider should document any relevant information regarding the CertPathValidator implementation, including the types of certification paths that it validates. In particular, a PKIX CertPathValidator implementation should document the following information:

  • The RFC or specification it is compliant with.
  • The mechanism it uses to check that certificates have not been revoked.
  • Any optional certificate or CRL extensions that it recognizes and how it processes them.

Certification Path Builders

A provider should document any relevant information regarding the CertPathBuilder implementation, including the types of certification paths that it creates and whether or not they are validated. In particular a PKIX CertPathBuilder implementation should document the following information:

  • The RFC or specification it is compliant with.
  • The mechanism it uses to check that certificates have not been revoked.
  • Any optional certificate or CRL extensions that it recognizes and how it processes them.
  • Details on the algorithm it uses for finding certification paths. Ex: depth-first, breadth-first, forward (i.e., from target to trust anchor(s)), reverse (i.e., from trust anchor(s) to target).
  • The algorithm it uses to select and sort potential certificates. For example, given two certificates that are potential candidates for the next certificate in the path, what criteria are used to select one before the other? What criteria are used to reject a certificate?
  • If applicable, the algorithm it uses for backtracking or constructing another path (i.e., when potential paths do not meet constraints).
  • The types of CertStore implementations that have been tested. The implementation should be designed to work with any CertStore type, but this information may still be useful.

All CertPathBuilder implementations should provide additional debugging support, in order to analyze and correct potential path building problems. Details on how to access this debugging information should be documented.

Certificate/CRL Stores

A provider should document what types of certificates and CRLs (and the version numbers, if relevant) are retrieved by the CertStore.

A provider should also document any relevant information regarding the CertStore implementation (such as protocols used or formats supported). For example, an LDAP CertStore implementation should describe which versions of LDAP are supported and which standard attributes are used for finding certificates and CRLs. It should also document if the implementation caches results, and for how long (i.e., under what conditions are they refreshed).

If the implementation returns the certificates and CRLs in a particular order, it should describe the sorting algorithm. An implementation should also document any additional or default initialization parameters.

Finally, an implementation should document if and how it uses information in the CertSelector or CRLSelector objects to find certificates and CRLs.

Service Interdependencies

Here are some common types of algorithm interdependencies in certification path service implementations:

Certification Path Validation and Signature Algorithms

A CertPathValidator implementation often requires use of a signature algorithm to verify each certificate's digital signature. The setSigProvider method of the PKIXParameters class allows a user to specify a specific Signature provider.

Certification Path Builders and Certificate Factories

A CertPathBuilder implementation will often utilize a CertificateFactory to generate a certification path from a list of certificates.

CertStores and Certificate Factories

A CertStore implementation will often utilize a CertificateFactory to generate certificates and CRLs from their encodings. For example, an LDAP CertStore implementation may use an X.509 CertificateFactory to generate X.509 certificates and CRLs from their ASN.1 encoded form.

Certification Path Parameter Specification Interfaces

The Certification Path API contains two interfaces representing transparent specifications of parameters, the CertPathParameters and CertStoreParameters interfaces.

Two implementations of the CertPathParameters interface are included, the PKIXParameters and PKIXBuilderParameters classes. If you are working with PKIX certification path validation and algorithm parameters, you can utilize these classes. If you need parameters for a different algorithm, you will need to supply your own CertPathParameters implementation for that algorithm.

Two implementations of the CertStoreParameters interface are included, the LDAPCertStoreParameters and the CollectionCertStoreParameters classes. These classes are to be used with LDAP and Collection CertStore implementations, respectively. If you need parameters for a different repository type, you will need to supply your own CertStoreParameters implementation for that type.

The CertPathParameters and CertStoreParameters interfaces each define a clone method that implementations should override. A typical implementation will perform a "deep" copy of the object, such that subsequent changes to the copy will not affect the original (and vice versa). However, this is not an absolute requirement for implementations of CertStoreParameters. A shallow copy implementation of clone is more appropriate for applications that need to hold a reference to a parameter contained in the CertStoreParameters. For example, since CertStore.getInstance makes a clone of the specified CertStoreParamters, a shallow copy clone allows an application to hold a reference to and later release the resources of a particular CertStore initialization parameter, rather than waiting for the garbage collection mechanism. This should be done with the utmost care, since the CertStore may still be in use by other threads.

Certification Path Result Specification Interfaces

The Certification Path API contains two interfaces representing transparent specifications of results, the CertPathValidatorResult and CertPathBuilderResult interfaces.

One implementation for each of the interfaces is included: the PKIXCertPathValidatorResult and PKIXCertPathBuilderResult classes. If you are implementing PKIX certification path service providers, you can utilize these classes. If you need certification path results for a different algorithm, you will need to supply your own CertPathValidatorResult or CertPathBuilderResult implementation for that algorithm.

A PKIX implementation of a CertPathValidator or a CertPathBuilder may find it useful to store additional information in the PKIXCertPathValidatorResult or PKIXCertPathBuilderResult, such as debugging traces. In these cases, the implementation should implement a subclass of the appropriate result class with methods to retrieve the relevant information. These classes must be shipped with the provider classes, for example, as part of the provider JAR file.

Certification Path Exception Classes

The Certification Path API contains a set of exception classes for handling errors. CertPathValidatorException, CertPathBuilderException, and CertStoreException are subclasses of GeneralSecurityException.

You may need to extend these classes in your service provider implementation. For example, a CertPathBuilder implementation may provide additional information such as debugging traces when a CertPathBuilderException is thrown. The implementation may throw a subclass of CertPathBuilderException that holds this information. Likewise, a CertStore implementation can provide additional information when a failure occurs by throwing a subclass of CertStoreException. Also, you may want to implement a subclass of CertPathValidatorException to describe a particular failure mode of your CertPathValidator implementation.

In each case, the new exception classes must be shipped with the provider classes, for example, as part of the provider JAR file. Each provider should document the exception subclasses.

TrustAnchor Class

As previously mentioned, a PKIX CertPathValidator or CertPathBuilder is not required to support the nameConstraints parameter of the TrustAnchor class. Implementations should throw an InvalidAlgorithmParameterException if this parameter is not supported.

Appendix A: Standard Names

The Java Certification Path API requires and utilizes a set of standard names for certification path validation algorithms, encodings and certificate storage types. The standard names previously found here in Appendix A and in the other security specifications (JCA/JSSE/etc.) have been combined in the Standard Names document. Specific provider information can be found in the Sun Provider Documentation.

Please note that a service provider may choose to define a new name for a proprietary or non-standard algorithm that is not mentioned in the Standard Names document. However, to prevent name collisions, it is recommended that the name be prefixed with the reverse Internet domain name of the provider's organization (for example: com.sun.MyCertPathValidator).

Appendix B: The "SUN" Provider

The CertPath implementation in the SUN provider as of Java SE 5 passed the Public Key Interoperability Test Suite (PKITS).

The "SUN" provider supports the following standard algorithms, types and encodings:

  • CertificateFactory: X.509 CertPath type with PKCS7 and PkiPath encodings
  • CertPathValidator: PKIX algorithm
  • CertPathBuilder: PKIX algorithm
  • CertStore: LDAP and Collection CertStore types
Each of these service provider interface implementations is discussed in more detail below.

CertificateFactory

The "SUN" provider for the CertificateFactory engine class has been enhanced to support generation of X.509 CertPath objects. The PKCS7 and PkiPath encodings are supported. The PKCS#7 implementation supports a subset of RFC 2315 (only the SignedData ContentInfo type is supported). The certificates in the CertPath are ordered in the forward direction (from target to trust anchor). Each certificate in the CertPath is of type java.security.cert.X509Certificate, and versions 1, 2 and 3 are supported.

CertPathValidator

The "SUN" provider supplies a PKIX implementation of the CertPathValidator engine class. The implementation validates CertPaths of type X.509 and implements the certification path validation algorithm defined in RFC 3280: PKIX Certificate and CRL Profile. This implementation sets the ValidationAlgorithm service attribute to "RFC3280".

In the Java SE 7 release, weak cryptographic algorithms can be disabled in the "SUN" provider using a security property. The jdk.certpath.disabledAlgorithms property is a list of disabled algorithms that applies to certificate path verification. The default value of jdk.certpath.disabledAlgorithms is MD2. This means that no signature algorithm involving MD2 will be used to verify a certificate. Appendix D has examples of values for jdk.certpath.disabledAlgorithms.

The PKIX Certificate and CRL Profile has many optional features. The "SUN" provider implements support for the policy mapping, authority information access and CRL distribution point certificate extensions, the issuing distribution point CRL extension, and the reason code and certificate issuer CRL entry extensions. It does not implement support for the freshest CRL or subject information access certificate extensions. It also does not include support for the freshest CRL and delta CRL Indicator CRL extensions and the invalidity date and hold instruction code CRL entry extensions.

The implementation supports a CRL revocation checking mechanism that conforms to section 6.3 of the PKIX Certificate and CRL Profile. OCSP (RFC 2560) is also currently supported as a built in revocation checking mechanism. See Appendix C for more details on the implementation and configuration and how it works in conjunction with CRLs.

The implementation does not support the nameConstraints parameter of the TrustAnchor class and the validate method throws an InvalidAlgorithmParameterException if it is specified.

CertPathBuilder

The "SUN" provider supplies a PKIX implementation of the CertPathBuilder engine class. The implementation builds CertPaths of type X.509. Each CertPath is validated according to the PKIX algorithm defined in RFC 3280: PKIX Certificate and CRL Profile. This implementation sets the ValidationAlgorithm service attribute to "RFC3280".

The implementation requires that the targetConstraints parameter of a PKIXBuilderParameters object is an instance of X509CertSelector and the subject criterion is set to a non-null value. Otherwise the build method throws an InvalidAlgorithmParameterException.

The implementation builds CertPath objects in a forward direction using a depth-first algorithm. It backtracks to previous states and tries alternate paths when a potential path is determined to be invalid or exceeds the PKIXBuilderParameters maxPathLength parameter.

Validation of the path is performed in the same manner as the CertPathValidator implementation. The implementation validates most of the path as it is being built, in order to eliminate invalid paths earlier in the process. Validation checks that cannot be executed on certificates ordered in a forward direction are delayed and executed on the path after it has been constructed (but before it is returned to the application).

As with CertPathValidator, the jdk.certpath.disabledAlgorithms security property can be used to exclude cryptographic algorithms that are not considered safe.

When two or more potential certificates are discovered that may lead to finding a path that meets the specified constraints, the implementation uses the following criteria to prioritize the certificates (in the examples below, assume a TrustAnchor distinguished name of "ou=D,ou=C,o=B,c=A" is specified):

  1. The issuer DN of the certificate matches the DN of one of the specified TrustAnchors (ex: issuerDN = "ou=D,ou=C,o=B,c=A").
  2. The issuer DN of the certificate is a descendant of the DN of one of the TrustAnchors, ordered by proximity to the anchor (ex: issuerDN = "ou=E,ou=D,ou=C,o=B,c=A").
  3. The issuer DN of the certificate is an ancestor of the DN of one of the TrustAnchors, ordered by proximity to the anchor (ex: issuerDN = "ou=C,o=B,c=A".
  4. The issuer DN of the certificate is in the same namespace of one of the TrustAnchors, ordered by proximity to the anchor (ex: issuerDN = "ou=G,ou=C,o=B,c=A").
  5. The issuer DN of the certificate is an ancestor of the subject DN of the certificate, ordered by proximity to the subject.
These are followed by certificates which don't meet any of the above criteria.

This implementation has been tested with the LDAP and Collection CertStore implementations included in this release of the "SUN" provider.

Debugging support can be enabled by setting the java.security.debug property to certpath. For example:

        java -Djava.security.debug=certpath BuildCertPath
This will print additional debugging information to standard error.

CertStore

The "SUN" provider supports two implementations of the CertStore engine class: Collection and LDAP.

Collection CertStore

The Collection CertStore implementation can hold any objects that are an instance of java.security.cert.Certificate or java.security.cert.CRL.

The certificates and CRLs are not returned in any particular order and will not contain duplicates.

LDAP CertStore

The LDAP CertStore implementation retrieves certificates and CRLs from an LDAP directory using the LDAP schema defined in RFC 2587. The LDAPSchema service attribute is set to "RFC2587".

The implementation fetches certificates from different locations, depending on the values of the subject, issuer, and basicConstraints selection criteria specified in the X509CertSelector. It performs as many of the following operations as possible:

  1. Subject non-null, basicConstraints <= -1

    Looks for certificates in the subject DN's "userCertificate" attribute.

  2. Subject non-null, basicConstraints >= -1

    Looks for certificates in the forward element of the subject DN's "crossCertificatePair" attribute AND in the subject's "caCertificate" attribute.

  3. Issuer non-null, basicConstraints >= -1

    Looks for certificates in the reverse element of the issuer DN's "crossCertificatePair" attribute AND in the issuer DN's "caCertificate" attribute.

In each case, certificates are checked using X509CertSelector.match() before adding them to the resulting collection.

If none of the conditions specified above applies, then an exception is thrown to indicate that it was impossible to fetch certificates using the criteria supplied. Note that even if one or more of the conditions apply, the Collection returned may still be empty if there are no certificates in the directory.

The implementation fetches CRLs from the issuer DNs specified in the setCertificateChecking, addIssuerName or setIssuerNames methods of the X509CRLSelector class. If no issuer DNs have been specified using one of these methods, the implementation throws an exception indicating it was impossible to fetch CRLs using the criteria supplied. Otherwise, the CRLs are searched as follows:

The implementation first creates a list of issuer names. If a certificate was specified in the setCertificateChecking method, it uses the issuer of that certificate. Otherwise, it uses the issuer names specified using the addIssuerName or setIssuerNames methods.

Next, the implementation iterates through the list of issuer names. For each issuer name, it searches first in the issuer's "authorityRevocationList" attribute and then, if no matching CRL was found there, in the issuer's "certificateRevocationList" attribute. One exception to the above is that if the issuer name was obtained from the certificate specified in the setCertificateChecking method, it only checks the issuer's "authorityRevocationList" attribute if the specified certificate is a CA certificate.

All CRLs are checked using X509CRLSelector.match() before adding them to the resulting collection.

If no CRLs satisfying the selection criteria can be found, an empty Collection is returned.

Caching

By default each LDAP CertStore instance caches lookups for a maximum of 30 seconds. The cache lifetime can be changed by setting the system property sun.security.certpath.ldap.cache.lifetime to a value in seconds. A value of 0 disables the cache completely. A value of -1 means unlimited lifetime.

Support for the CRL Distribution Points Extension

Support for the CRL Distribution Points extension is available. It is disabled by default for compatibility and can be enabled by setting the system property com.sun.security.enableCRLDP to the value true.

If set to true, Sun's PKIX implementation uses the information in a certificate's CRL Distribution Points extension (in addition to CertStores that are specified) to find the CRL, provided the distribution point is an X.500 distinguished name or a URI of type ldap, http, or ftp.

Note: Depending on your network and firewall setup, it may be necessary to also configure your networking proxy servers as described in the networking documentation.

Support for the Authority Information Access (AIA) Extension

Support for the caIssuers access method of the Authority Information Access extension is available. It is disabled by default for compatibility and can be enabled by setting the system property com.sun.security.enableAIAcaIssuers to the value true.

If set to true, Sun's PKIX implementation of CertPathBuilder uses the information in a certificate's AIA extension (in addition to CertStores that are specified) to find the issuing CA certificate, provided it is a URI of type ldap, http, or ftp.

Note: Depending on your network and firewall setup, it may be necessary to also configure your networking proxy servers as described in the networking documentation.

Appendix C: On-Line Certificate Status Protocol (OCSP) Support

Client-side support for the On-Line Certificate Status Protocol (OCSP) as defined in RFC 2560 is supported as of JDK 5.0. OCSP checking is controlled by the following five security properties:

Property Name | Description
ocsp.enable | This property's value is either true or false. If true, OCSP checking is enabled when doing certificate revocation checking; if false or not set, OCSP checking is disabled.
ocsp.responderURL This property's value is a URL that identifies the location of the OCSP responder. Here is an example.
ocsp.responderURL=http://ocsp.example.net:80

By default, the location of the OCSP responder is determined implicitly from the certificate being validated. The property is used when the Authority Information Access extension (defined in RFC 3280) is absent from the certificate or when it requires overriding.
ocsp.responderCertSubjectName This property's value is the subject name of the OCSP responder's certificate. Here is an example.
ocsp.responderCertSubjectName="CN=OCSP Responder, O=XYZ Corp"

By default, the certificate of the OCSP responder is that of the issuer of the certificate being validated. This property identifies the certificate of the OCSP responder when the default does not apply. Its value is a string distinguished name (defined in RFC 2253) which identifies a certificate in the set of certificates supplied during cert path validation. In cases where the subject name alone is not sufficient to uniquely identify the certificate, then both the ocsp.responderCertIssuerName and ocsp.responderCertSerialNumber properties must be used instead. When th is property is set, then those two properties are ignored.
ocsp.responderCertIssuerName This property's value is the issuer name of the OCSP responder's certificate . Here is an example.
ocsp.responderCertIssuerName="CN=Enterprise CA, O=XYZ Corp"

By default, the certificate of the OCSP responder is that of the issuer of the certificate being validated. This property identifies the certificate of the OCSP responder when the default does not apply. Its value is a string distinguished name (defined in RFC 2253) which identifies a certificate in the set of certificates supplied during cert path validation. When this property is set then the ocsp.responderCertSerialNumber property must also be set. Note that this property is ignored when the ocsp.responderCertSubjectName property has been set.
ocsp.responderCertSerialNumber This property's value is the serial number of the OCSP responder's certificate Here is an example.
ocsp.responderCertSerialNumber=2A:FF:00

By default, the certificate of the OCSP responder is that of the issuer of the certificate being validated. This property identifies the certificate of the OCSP responder when the default does not apply. Its value is a string of hexadecimal digits (colon or space separators may be present) which identifies a certificate in the set of certificates supplied during cert path validation. When this property is set then the ocsp.responderCertIssuerName property must also be set. Note that this property is ignored when the ocsp.responderCertSubjectName property has been set.

These properties may be set either staticly in the Java runtime's $JAVA_HOME/jre/lib/security/java.security file, or dynamically using the java.security.Security.setProperty() method.

By default, OCSP checking is not enabled. It is enabled by setting the ocsp.enable property to "true". Use of the remaining properties is optional. Note that enabling OCSP checking only has an effect if revocation checking has also been enabled. Revocation checking is enabled via the PKIXParameters.setRevocationEnabled() method.

OCSP checking works in conjunction with Certificate Revocation Lists (CRLs) during revocation checking. Below is a summary of the interaction of OCSP and CRLs. Failover to CRLs occurs only if an OCSP problem is encountered. Failover does not occur if the OCSP responder confirms either that the certificate has been revoked or that it has not been revoked.

PKIXParameters RevocationEnabled (default=true) | ocsp.enable (default=false) | Behavior
true | true | Revocation checking using OCSP, failover to using CRLs
true | false | Revocation checking using CRLs only
false | true | No revocation checking
false | false | No revocation checking

Appendix D: Disabling Cryptographic Algorithms

The jdk.certpath.disabledAlgorithms security property contains a list of cryptographic algorithms that will not be used during certification path processing. The exact syntax of the property is described in the jre/lib/security/java.security file, but is briefly summarized here.

The security property contains a list of cryptographic algorithms that must not be used. The algorithm names are separated by commas. Furthermore, you can also specify restrictions on key sizes.

For example, the following line in java.security specifies that the MD2 and DSA algorithms must not be used for certification path processing. Furthermore, RSA is disabled for key sizes less than 2048 bits.

jdk.certpath.disabledAlgorithms=MD2, DSA, RSA keySize < 2048
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Chained Exception Facility

It is common for Java code to catch one exception and throw another:

try {
    ...
} catch(YourException e) {
    throw new MyException();
}

Unfortunately, the information contained in the "causative exception" (YourException in the example above) is generally lost, which greatly complicates debugging. Recognizing this problem, developers sometimes build ad hoc mechanisms to allow certain "wrapped exceptions" to contain a second exception. An accessor is generally provided to extract the contained exception. Such mechanisms are sometimes known as "exception chaining facilities", as they allow arbitrary chains of exceptions to be constructed when contained exceptions are, themselves, wrapped exceptions.

There are many advantages to unifying all of these facilities. Chief among them are: (1) We guarantee that anyone who wants to record the fact that one exception caused another can do so, regardless of what the exceptions are. (2) By providing a common API to record the fact that one exception caused another, we ease this task, making it more likely that programmers will take the trouble to do it. (3) By providing a common API to access causative exceptions, we greatly increase the likelihood that this information will be made available to those who need it. In fact, the proposed mechanism prints entire "causal chain" as part of the standard stack backtrace, ensuring that preexisting programs will provide this information with no additional effort on the part of their authors.

To address these issues, we have added two new methods to Throwable, getCause() and initCause(Throwable), and two new constructors, Throwable(Throwable) and Throwable(String, Throwable). Other "general purpose" exception classes (like Exception, RunTimeException and Error) have been similarly outfitted with (Throwable) and (String, Throwable) constructors. However, even exceptions without such constructors will be usable as "wrapped exceptions" via the initCause method.

The implementation of Throwable.printStackTrace has been modified to display backtraces for the entire causal chain of exceptions. New method getStackTrace provides programmatic access to the stack trace information provided by printStackTrace.

All of the platform's wrapped exceptions will be retrofitted to support the new facility (in addition to their legacy APIs).

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Object Serialization Specification: -

CONTENTS | PREV | NEXT Java Object Serialization Specification
version 6.0

Change History

May 12, 2005 Updates for JavaTM SE Development Kit, v6 Beta 1

  • Added statement about how an array object returned by a readResolve invocation for an unshared read is handled.
  • Clarified the behavior in the event of an invalid serialPersistentFields value.
  • Clarified that serialVersionUID matching is waived for array classes.
  • Clarified when IllegalArgumentException is thrown by ObjectOutputStream.PutFields methods.

July 24, 2003 Updates for JavaTM 2 SDK, Standard Edition, v1.5 Beta 1

  • Added support for serializing enum constants.
  • Added specification of class modifier flags used in the computation of default serialVersionUID values to Section 4.6, "Stream Unique Identifiers".

Aug. 16, 2001 Updates for JavaTM 2 SDK, Standard Edition, v1.4 Beta 2

  • Added support for class-defined readObjectNoData methods, to be used for initializing serializable class fields in cases not covered by class-defined readObject methods. See Section 3.5, "The readObjectNoData Method", as well as Appendix A, "Security in Object Serialization".
  • New methods ObjectOutputStream.writeUnshared and ObjectInputStream.readUnshared provide a mechanism for ensuring unique references to deserialized objects. See Section 2.1, "The ObjectOutputStream Class", Section 3.1, "The ObjectInputStream Class", as well as Appendix A, "Security in Object Serialization".
  • Documented new security checks in the one-argument constructors for ObjectOutputStream and ObjectInputStream. See Section 2.1, "The ObjectOutputStream Class" and Section 3.1, "The ObjectInputStream Class".
  • Added caution against using inner classes for serialization in Section 1.10, "The Serializable Interface".
  • Clarified requirement that class-defined writeObject methods invoke ObjectOutputStream.defaultWriteObject or writeFields once before writing optional data, and that class-defined readObject methods invoke ObjectInputStream.defaultReadObject or readFields once before reading optional data. See Section 2.3, "The writeObject Method" and Section 3.4, "The readObject Method".
  • Clarified the behavior of ObjectInputStream when class-defined readObject or readExternal methods attempt read operations which exceed the bounds of available data; see Section 3.4, "The readObject Method" and Section 3.6, "The readExternal Method".
  • Clarified the description of non-proxy class descriptor field type strings to require that they be written in "field descriptor" format; see Section 6.2, "Stream Elements".

July 30, 1999 Updates for JavaTM 2 SDK, Standard Edition, v1.3 Beta

  • Added the ability to write String objects for which the UTF encoding is longer than 65535 bytes in length. See Section 6.2, "Stream Elements".
  • New methods ObjectOutputStream.writeClassDescriptor and ObjectInputStream.readClassDescriptor provide a means of customizing the serialized representation of ObjectStreamClass class descriptors. See Section 2.1, "The ObjectOutputStream Class" and Section 3.1, "The ObjectInputStream Class".
  • Expanded Appendix A, "Security in Object Serialization".

Sept. 30, 1998 Updates for JDKTM 1.2 Beta4 RC1

  • Documentation corrections only.

June 22, 1998 Updates for JDKTM 1.2 Beta4

  • Eliminated JDKTM 1.2 java.io interfaces, Replaceable and Resolvable.References to either of these classes as an interface should be replaced with java.io.Serializable. Serialization will use reflection to invoke the methods, writeReplace and readResolve, if the Serializable class defines these methods. See Section 2.5, "The writeReplace Method" and Section 3.7, "The readResolve Method."
  • New javadoc tags @serial, @serialField, and @serialData provide a way to document the Serialized Form of a Serializable class. Javadoc generates a serialization specification based on the contents of these tags. See Section 1.6, "Documenting Serializable Fields and Data for a Class."
  • Special Serializable class member, serialPersistentFields, must be declared private. See Section 1.5, "Defining Serializable Fields for a Class."
  • Clarified the steps involved in computing the serialVersionUID in Section 4.6, "Stream Unique Identifiers."

Feb. 6, 1998 Updates for JDKTM 1.2 Beta 3

  • Introduced the concept of STREAM_PROTOCOL versions. Added the STREAM_PROTOCOL_2 version to indicate a new format for Externalizable objects that enable skipping by an Externalizable object within the stream, even when the object's class is not available in the local Virtual Machine. Compatibility issues are discussed in Section 6.3, "Stream Protocol Versions."
  • The ObjectInputStream.resolveClass method can return a local class in a different package than the name of the class within the stream. This capability enables renaming of packages between releases. The serialVersionUID and the base class name must be the same in the stream and in the local version of the class. See Section 3.1, "The ObjectInputStream Class."
  • Allow substitution of String or array objects when writing them to or reading them from the stream. See Section 2.1, "The ObjectOutputStream Class" and Section 3.1, "The ObjectInputStream Class."

Sept. 4, 1997 Updates for JDKTM 1.2 Beta1

  • Separated the Replaceable interface into two interfaces: Replaceable and Resolvable. The Replaceable interface allows a class to nominate its own replacement just before serializing the object to the stream. The Resolvable interface allows a class to nominate its own replacement when reading an object from the stream.
  • Modified serialization to use the JDKTM 1.2 security model. There is a check for SerializablePermission "enableSubstitution" within the ObjectInputStream.enableReplace and ObjectOutputStream.enableResolve methods. See Section 2.1, "The ObjectOutputStream Class" and Section 3.1, "The ObjectInputStream Class."
  • Updated writeObject's exception handler to write handled IOExceptions into the stream. See Section 2.1, "The ObjectOutputStream Class."

July 3, 1997 Updates for JDKTM 1.2 Alpha

  • Documented the requirements for specifying the serialized state of classes. See Section 1.5, "Defining Serializable Fields for a Class."
  • Added the Serializable Fields API to allow classes more flexibility in accessing the serialized fields of a class. The stream protocol is unchanged. See Section 1.7, "Accessing Serializable Fields of a Class," Section 2.2, "The ObjectOutputStream.PutField Class," and Section 3.2, "The ObjectInputStream.GetField Class."
  • Clarified that field descriptors and data are written to and read from the stream in canonical order. See Section 4.1, "The ObjectStreamClass Class."

CONTENTS | PREV | NEXT
Copyright © 2005, 2010, Oracle and/or its affiliates. All rights reserved.


Appendix C: JNDI Change History

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

Appendix 4:

JNDI Change History

JNDI 1.2: Changes Since JNDI 1.1

  • Added javax.naming.event package.
  • Added javax.naming.ldap package.
  • Added support for configuration using resource files. See Chapter 6 of the JNDI API document.

API-related Changes

  • Added NamingEnumeration.close() for cancelling or terminating enumerations.
  • Added ReferralException.getReferralContext(Hashtable env) and ReferralException.retryReferral() to allow creation and retry of referral context with different environment properties.
  • Clarified how context methods that accept Name argument should deal with CompositeName and non CompositeName arguments. Specifically, instances of CompositeName are treated as composite name, while all others are treated as compound name.
  • Added Context.getNameInNamespace() for retrieving the full name of a context within its own namespace.
  • Clarified definition of the class factory location of a Reference object. Specifically, the location is a codebase, which consists of a list space-separated URLs.
  • Added support for ordered multivalued attributes to Attribute and BasicAttribute .
  • Added BasicAttributes.equals() and BasicAttributes.hashCode() .
  • Redefined semantics of DirContext.getSchemaClassDefinition() so that it returns a context that contains the DirContext objects of class definitions, rather than returning one (arbitrary) class definition.
  • Added protected InitialContext / InitialDirContext constructors to allow lazy initialization. Useful for subclass implementations.

SPI-related Changes

  • Added StateFactory / NamingManager.getStateToBind() , analogous to ObjectFactory / NamingManager.getObjectInstance() , for transforming an object's state before the object is bound in the naming/directory service.
  • Added interfaces DirObjectFactory and DirStateFactory to better support service providers that implement the DirContext interface. Added DirectoryManager.getObjectInstance() and DirectoryManager.getStateToStore() to use these interfaces.
  • Refined definition of NamingManager.getObjectInstance() to not treat URL strings specially. Instead, the URL should be wrapped inside a Reference whose RefAddr type is "URL".
  • Made ResolveResult implement Serializable .
  • Defined a special form of Reference called a next naming system (nns) reference for supporting "dynamic federation". This reference has a RefAddr type of "nns" and a content consisting of the resolved object.
  • Added the string constant NamingManager.CPE which names a property set by NamingManager.getContinuationContext() / DirectoryManager.getContinuationContext() . The value of this property is an instance of CannotProceedException . This is useful to service providers that implement federation by chaining the CPEs.
  • Defined a convention for service providers to use when naming environment properties. See Section 6.1.

CONTENTS | PREV | NEXT

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Collections Framework Change Summary for J2SDK 1.4

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Collections Framework Enhancements

This page summarizes the enhancements made to the collections framework in version 1.4 of the JavaTM 2 SDK.

  • The Collections utility class has several new methods:
    • rotate(List list, int distance) - Rotates all of the elements in the list by the specified distance. This operation is common in GUI computations: moving one or more columns in a table can be accomplished efficiently by applying this operation to a sublist. This operation is also common in mathematical and scientific calculations.
    • replaceAll(List list, Object oldVal, Object newVal) - Replaces all occurrences of one specified value with another. This is essentially a convenience method. Though not difficult to program, it's very commonly needed.
    • indexOfSubList(List source, List target) - Returns the index of the first sublist of source that is equal to target. Commonly used in many domains including text processing.
    • lastIndexOfSubList(List source, List target) - Returns the index of the last sublist of source that is equal to target. Commonly used in many domains including text processing.
    • swap(List list, int i, int j) - Swaps the elements at the specified positions in the specified list. Essentially a convenience method, though this implementation is faster than the naive implementation.
    • list(Enumeration e) - Returns an ArrayList containing the elements returned by the specified enumeration. This convenience method provides interoperability between legacy APIs that return enumerations and new APIs that require collections.
  • New interface RandomAccess is a marker interface that allows List implementations to indicate that they support fast (generally constant time) random access. This allows generic algorithms to alter their behavior to provide good performance when applied to either random or sequential access lists.
  • New class LinkedHashMap provides an insertion-ordered Map implementation that runs nearly as fast as HashMap. Internally, it uses a hash table with a doubly linked list running through it in insertion order. Also available is a corresponding Set implementation, called LinkedHashSet.
  • New class IdentityHashMap is an identity-based Map implementation based on a hash table. This class is useful for topology-preserving object graph transformations (such as serialization or deep-copying). To perform such transformations, you need to maintain an identity-based "node table" that keeps track of which objects have already been seen. Identity-based maps are also used to maintain object-to-meta-information mappings in dynamic debuggers and similar systems. Finally, identity-based maps are useful in thwarting "spoof attacks" resulting from intentionally perverse equals methods. (IdentityHashMap never invokes the equals method on its keys.) An added benefit of this implementation is that it is fast.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Collections Framework Change Summary for JDK 5

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Collections Framework Enhancements

This page summarizes enhancements to the collections framework in version 5 of the JDK.

Three new language features significantly enhance the collections framework:

  • Generics - adds compile-time type safety to the collections framework and eliminates the need to cast when reading elements from collections.
  • Enhanced for loop - eliminates the need for explicit iterators when interating over collections.
  • Autoboxing/unboxing - automatically converts primitives (such as int) to wrapper classes (such as Integer) when inserting them into collections, and converts wrapper class instances to primitives when reading from collections.

Three new collection interfaces are provided:

  • Queue - represents a collection designed for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations.
  • BlockingQueue - extends Queue with operations that wait for the queue to become non-empty when retrieving an element, and that wait for space to become available in the queue when storing an element. (This interface is part of the new package java.util.concurrent.)
  • ConcurrentMap - extends Map with atomic putIfAbsent, remove, and replace methods. (This interface is part of java.util.concurrent.)

Two new concrete Queue implementations are provided, one existing List implementation has been retrofitted to implement Queue, and one abstract Queue implementation is provided:

  • PriorityQueue - an unbounded priority queue backed by a heap.
  • ConcurrentLinkedQueue - an unbounded thread-safe FIFO (first-in first-out) queue backed by linked nodes. (This class is part of java.util.concurrent.)
  • LinkedList - retrofitted to implement the Queue interface. When accessed via the Queue interface, LinkedList behaves as a FIFO queue.
  • AbstractQueue - a skeletal Queue implementation.

Five new BlockingQueue implementations are provided, all of which are part of java.util.concurrent:

  • LinkedBlockingQueue - an optionally bounded FIFO blocking queue backed by linked nodes.
  • ArrayBlockingQueue - a bounded FIFO blocking queue backed by an array.
  • PriorityBlockingQueue - an unbounded blocking priority queue backed by a heap.
  • DelayQueue - a time-based scheduling queue backed by a heap.
  • SynchronousQueue - a simple rendezvous mechanism utilizing the BlockingQueue interface.

One ConcurrentMap implementation is provided:

  • ConcurrentHashMap - a highly concurrent, high-performance ConcurrentMap implementation backed by a hash table. This implementation never blocks when performing retrievals and allows the client to select the concurrency level for updates. It is intended as a drop-in replacement for Hashtable: in addition to implementing ConcurrentMap, it supports all of the "legacy" methods peculiar to Hashtable.

Special-purpose List and Set implementations are provided for use in situations where read operations vastly outnumber write operations and iteration cannot or should not be synchronized:

  • CopyOnWriteArrayList - a List implementation backed by an array. All mutative operations (such as add, set, and remove) are implemented by making a new copy of the array. No synchronization is necessary, even during iteration, and iterators are guaranteed never to throw ConcurrentModificationException. This implementation is well-suited to maintaining event-handler lists (where change is infrequent, and traversal is frequent and potentially time-consuming).
  • CopyOnWriteArraySet - a Set implementation backed by a copy-on-write array. This implementation is similar in nature to CopyOnWriteArrayList. Unlike most Set implementations, the add, remove, and contains methods require time proportional to the size of the set. This implementation is well-suited to maintaining event-handler lists that must prevent duplicates.

Special-purpose Set and Map implementations are provided for use with enums:

  • EnumSet - a high-performance Set implementation backed by a bit-vector. All elements of each EnumSet instance must be elements of a single enum type.
  • EnumMap - a high-performance Map implementation backed by an array. All keys in each EnumMap instance must be elements of a single enum type.

A new family of wrapper implementations is provided, primarily for use with generic collections:

  • Collections.checkedInterface - returns a dynamically typesafe view of the specified collection, which throws a ClassCastException if a client attempts to add an element of the wrong type. The generics mechanism in the language provides compile-time (static) type checking, but it is possible to defeat this mechanism. Dynamically typesafe views eliminate this possibility entirely.

Three new generic algorithms and one comparator converter were added to the Collections utility class:

  • frequency(Collection<?> c, Object o) - counts the number of times the specified element occurs in the specified collection.
  • disjoint(Collection<?> c1, Collection<?> c2) - determines whether two collecitons are disjoint, in other words, whether they contain no elements in common.
  • addAll(Collection<? super T> c, T... a) - convenience method to add all of the elements in the specified array to the specified collection.
  • Comparator<T> reverseOrder(Comparator<T> cmp) - returns a comparator that represents the reverse ordering of the specified comparator.

The Arrays utility class has been outfitted with content-based hashCode and toString methods for arrays of all types. These methods complement the existing equals methods. Versions of all three methods are provided to operate on nested (or "multidimensional") arrays: deepEquals, deepHashCode, and deepToString. It is now trivial to print the contents of any array. The idiom for printing a "flat" array is:

    System.out.println(Arrays.toString(a));

The idiom for printing a nested (multidimensional) array is:

    System.out.println(Arrays.deepToString(a));

Finally, Boolean was retrofitted to implement Comparable.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Enhancements in java.lang.instrument

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Enhancements in Java SE 6

for the java.lang.instrument Package

The following functionality has been added to the java.lang.instrument package between its initial release in JDK 5.0 and Java™ SE 6.

  • Support for retransformation of class files - To facilitate dynamic transformation of classes that have already been loaded, the following methods have been added.
    • Instrumentation.retransformClasses(Class...)
    • Instrumentation.addTransformer(ClassFileTransformer, boolean)
    • Instrumentation.isModifiableClass(Class)
    • Instrumentation.isRetransformClassesSupported()
    They are suited to operations such as adding instrumentation to methods whose classes have already been loaded. Support for retransformation means that access to the original class file is no longer required in order to instrument loaded classes. They enable the easy removal of applied transformations and are designed to work in multi-agent environments.
  • Support for instrumenting native methods - The following methods allow native methods to be instrumented by providing a JVM-aware mechanism for wrapping the native method.
    • Instrumentation.setNativeMethodPrefix(ClassFileTransformer, String)
    • Instrumentation.isNativeMethodPrefixSupported()
  • Support for appending to class loader search - The following methods allow instrumentation support classes to be defined in the appropriate class loader.
  • Instrumentation.appendToBootstrapClassLoaderSearch(JarFile)
  • Instrumentation.appendToSystemClassLoaderSearch(JarFile)
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Concurrency Utilities Change Summary for Java SE 7

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Concurrency Utilities Enhancements

This page summarizes enhancements to the concurrency utilities in Java SE 7.

  • The Fork/Join framework is an easy-to-use way to take advantage of multiple processors.
  • The ThreadLocalRandom class eliminates contention among threads using psuedorandom numbers.
  • The Phaser class is a new synchronization barrier, similar to CyclicBarrier.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


V1.4 JavaBeans API Enhancements

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

API Enhancements to the JavaBeansTM Component API in v1.4

This document describes changes to the java.beans package that were introduced in version 1.4 of the Java 2 Platform, Standard Edition:

  • New API for Long-Term Persistence
  • Other API Additions
  • Changes to the Introspector
  • Garbage Collection and Custom Attributes

New API for Long-Term Persistence

To support long-term persistence, the following classes were added:

Class | Description
Statement | An object that represents a method call, possibly with arguments, upon an object. For example: a.setFoo(b).
Expression | A statement that returns a result. For example: a.getFoo().
XMLDecoder | Reads XML documents that were created using XMLEncoder.
Encoder | Uses persistence delegates to break an object graph down into a series of Statements and Expressions that can be used to recreate it.
XMLEncoder | An Encoder that produces statements and expressions in an XML encoding.
PersistenceDelegate | An abstract class that defines objects that can express the state of another object using the public methods of that object's class.
DefaultPersistenceDelegate | The persistence delegate used, by default, for beans.

See JavaBeans Component API for links to where you can find more information about long-term persistence.

Other API Additions

The following classes were also added in v1.4:

Class | Description
EventHandler | Provides support for dynamically generating event listeners that have a small footprint and can be saved automatically by the persistence scheme.
ExceptionListener | Defines a listener to be notified when a exception was thrown but then recovered from. You can register an exception listener on an XMLEncoder or XMLDecoder object to be notified when the object encounters a recoverable problem while writing or reading a bean.
PropertyChangeListenerProxy | A proxy that implements PropertyChangeListener and serves to group another PropertyChangeListener (the real event handler) with a specific property; the proxy forwards property change events to the real event handler.
VetoableChangeListenerProxy | A proxy that implements VetoableChangeListener and serves to group another VetoableChangeListener (the real event handler) with a specific constrained property; the proxy forwards vetoable property change events to the real event handler.

The following classes have additional methods:

  • The PropertyChangeSupport class now contains a no-argument method to get all the registered property change listeners: getPropertyChangeListeners.
  • Similarly, the VetoableChangeSupport class now contains a no-argument method to get all the registered vetoable change listeners: getVetoableChangeListeners.

Changes to the Introspector

The Introspector class has been reimplemented, and its performance has improved. The new implementation has caused the following changes in the behavior of the introspector:
  • FeatureDescriptors are now shared on a per-BeanInfo basis, rather than copied when the BeanInfo is returned. This change improves the performance of the getBeanInfo method. It also means that when an attribute/value in a FeatureDescriptor changes, that change is persistent among getBeanInfo invocations as long as the BeanInfo is not garbage collected. (Garbage collection of BeanInfos is described in Garbage Collection and Custom Attributes.)
  • The getBeanInfo methods no longer create a copy of the requested BeanInfo. Instead, they cache the BeanInfo and return it. If necessary, you can get the old behavior by storing a reference to the returned BeanInfo and using the flushFromCaches method to flush the bean's class from the introspector's cache.
  • If the instantiate method can't instantiate a particular class using the sibling or bootstrap class loader, it now tries to load the class using the current thread's class loader.

Garbage Collection and Custom Attributes

As of v 1.4, a BeanInfo can be garbage collected when no direct references to it exist and the system is low on memory. This is implemented in the Introspector by wrapping BeanInfos in SoftReferences.

The possibility of garbage collection affects how you store custom attributes inside BeanInfos. If a particular BeanInfo is garbage collected, then the next time you invoke Introspector.getBeanInfo to get the BeanInfo, the returned object won't contain any custom attributes.

To avoid this problem, if you store custom attributes inside a BeanInfo you must ensure that the BeanInfo is correctly initialized with those attributes every time you retrieve the BeanInfo. The following is an example of initializing a BeanInfo class with a custom property in the bean descriptor. The code would be similar for a custom attribute in a property descriptor, method descriptor, or event set descriptor.

BeanInfo beanInfo = getBeanInfo(SomeBean.class);
BeanDescriptor beanDescriptor = beanInfo.getBeanDescriptor();

/*
 * Before using the BeanInfo, check to see if our custom
 * property has been initialized.  (Even if we initialized
 * it before, if the BeanInfo has been garbage collected,
 * then we need to initialize it again.)  Since our custom
 * property's value could be null, we define another property
 * to tell us if the custom property is initialized.
 */
if (beanDescriptor.getValue("myProperty_init") == null) {
    beanDescriptor.setValue("myProperty", someValue);
    beanDescriptor.setValue("myProperty_init", Boolean.TRUE);
}
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JavaBeans API Enhancements in J2SE 5.0

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

API Enhancements to the JavaBeansTM Component API in J2SE 5.0

This document describes changes to the java.beans package that were introduced in version 5.0 of the JavaTM 2 Platform Standard Edition:
  • Support for IndexedPropertyChangeEvent
  • New Method for Creating a PropertyEditor
  • Public Constructors for PropertyEditorSupport

Support for IndexedPropertyChangeEvent

The bugtraq report that corresponds to this change is: 4353056

A new subclass of PropertyChangeEvent named IndexedPropertyChangeEvent has been added to support bound properties that use an index to identify the part of the bean that changed. Also, three methods — all named fireIndexedPropertyChange — have been added to the PropertyChangeSupport utility class to support firing indexed property change events. You can find an example of using indexed property change events in IndexedTest.java.

New Method for Creating a PropertyEditor

The bugtraq report that corresponds to this change is: 4274639

A new method called createPropertyEditor has been added to the PropertyDescriptor class.

Public Constructors for PropertyEditorSupport

The bugtraq report that corresponds to this change is: 4305280

The two PropertyEditorSupport constructors are now public instead of protected, so that PropertyEditorSupport objects can be more easily created and used as delegates. Also, the source object is now exposed by means of new setSource and getSource methods.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Enhancements to the JavaBeans API in Java SE 6.0

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Enhancements to the JavaBeansTM Component API in Java SE 6.0

java.beans

Major Features
Fixed Bugs

Major Features

The @ConstructorProperties annotation

The @ConstructorProperties annotation was introduced in Java SE 6.0 to show how the parameters of annotated constructor correspond to an object's properties. Previously, the constructor DefaultPersistenceDelegate(String[] constructorPropertyNames) was used for the same goal, but was not an appropriate approach for library classes.

Technically, an annotation is used for copying beans with read-only properties. In the following code example the Food properties are read-only.

public class Food {
     private final int varieties;
     private final String country;

     @ConstructorProperties({"varieties", "country"})
     public Point(int varieties, String country) {
         this.varieties = varieties;
         this.country = country;
     }
     public int getVarieties() {
         return this.varieties;
     }
     public String getCountry() {
         return this.country;
     }
}

To create a vegetable object with the same properties that the fruit object has, use the following code:

Food fruit = new Food (5, "Argentina");
Food vegetable = new Food (fruit.getVarieties(), fruit.getCountry());
Defining the annotation accomplishes two goals:
  • Eliminates the need for the developer to explicitly use the DefaultPersistenceDelegate class.
  • Describes the relationship between a constructor parameter and a property, but not an operational logic, therefore the annotation can be applied to both bean related areas, such as Long Term Persistence, and to non-beans related areas, such JMX.

Fixed Bugs

The EventHandler class

6179222: Possible a NullPointerException error with the EventHandler class

The NPR exception was thrown by the EventHandler class. The create method of the EventHandler class checks the null value, and javadoc is corrected accordingly.

6204552: The EventHandler documentation and exception handling problems

Documentation on the EventHandler class of the eventPropertyName argument did not clearly explain waht the argument supports. Information about what the eventProperName property is capable of is included in the documentation for the create method.

6210265: The EventHandler class should not cache the Method object

The method search is improved, and the method is prevented from being cached in the EventHandler class field.

6271692: The target property of the EventHandler class did support same syntax as the event property

The target property syntax is fixed and now supports an arbitrary number of methods or properties. This was accomplished by separating each property or method with a ".".

The XMLEncoder class

The following fixes were performed to improve the long-term persistence process.

6245149: The java.beans.XMLEncoder class does not encode java.net.URI objects

The Statement class could not access a member of the java.net.URI class with modifiers private. In JDK 6.0 an appropriate PersistenceDelegate is provided to solve this problem.

4921212: The XMLEncoder class does not encode null entries in HashMap objects

A null Key entry of the HashMap object was not included into the XML output. The fix includes a null Key entry to the XML file.

6256805: The XMLEncoder class emits invalid XML

The XMLEncoder class produces an XML output only for valid XML characters. A new code attribute was introduced for a character element. The code contains a hexadecimal value if it starts with "#". Otherwise it contains a decimal value.

5015403: The XMLEncoder class does not encode enumerations correctly

The XMLEncoder class was not serializing an enumeration correctly. The EnumPersistenceDelegate class, a new persistence delegate, was introduced to support the serialization of enum classes.

4741757: The XMLEncoder class ignores persistence delegates when used with Java Web Start

A DefaultPersistenceDelegate class for some classes was created improperly. As a result the hack that adds field access for properties and breaking JavaBeans specification was detected. The performed fix removes the hack that was intended for the following classes: java.awt.Dimension, java.awt.Point, and java.awt.Rectangle.

6338070: The XMLDecoder class ignores statements made to owner unless the read() method is called

Initially the XMLDecoder class was created with lazy initialization. The fix enables parsing in the close() method if a file is not parsed by the readObject() method.

6341798: The XMLDecoder class fails when using Turkish Locale

The XMLDecoder class did not function correctly when reading an English XML file on a machine with the locale set to Turkish. To fix this bug the toLowerCase and toUpperCase methods are invoked in the English locale.

6437265: Some Component object is missing during xml serializing

Container objects were not serialized. The fix adds special behavior to the persistence delegate for containers with BorderLayout.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
[Top] [Prev] [Next] [Bottom]

Appendix C: JNDI Change History

JNDI 1.2: JNDI Changes Since JNDI 1.1

  • Added javax.naming.event package.
  • Added javax.naming.ldap package.
  • Added support for configuration using resource files. See Chapter 6 of the JNDI API document.

API-related Changes

  • Added NamingEnumeration.close() for cancelling or terminating enumerations.
  • Added ReferralException.getReferralContext(Hashtable env) and ReferralException.retryReferral() to allow creation and retry of referral context with different environment properties.
  • Clarified how context methods that accept Name argument should deal with CompositeName and nonCompositeName arguments. Specifically, instances of CompositeName are treated as composite name, while al l others are treated as compound name.
  • Added Context.getNameInNamespace() for retrieving the full name of a context within its own namespace.
  • Clarified definition of the class factory location of a Reference object. Specifically, the location is a codebase, which consists of a list space-separated URLs.
  • Added support for ordered multivalued attributes to Attribute and BasicAttribute.
  • Added BasicAttributes.equals() and BasicAttributes.hashCode().
  • Redefined semantics of DirContext.getSchemaClassDefinition() so that it returns a context that contains the DirContext objects of class definitions, rather than returning one (arbitrary) class definition.
  • Added protected InitialContext/InitialDirContext constructors to allow lazy initialization. Useful for subclass implementations.

SPI-related Changes

  • Added StateFactory/NamingManager.getStateToBind(), analogous to ObjectFactory/NamingManager.getObjectInstance(), for transforming an object's state before the object is bound in the naming/directory service.
  • Added interfaces DirObjectFactory and DirStateFactory to better support service providers that implement the DirContext interface. Added DirectoryManager.getObjectInstance() and DirectoryManager.getStateToStore() to use these interfaces.
  • Refined definition of NamingManager.getObjectInstance() to not treat URL strings specially. Instead, the URL should be wrapped inside a Reference whose RefAddr type is "URL".
  • Made ResolveResult implement Serializable.
  • Defined a special form of Reference called a next naming system (nns) reference for supporting "dynamic federation". This reference has a RefAddr type of "nns" and a content consisting of the resolved object.
  • Added the string constant NamingManager.CPE which names a property set by NamingManager.getContinuationContext()/DirectoryManager.getContinuationContext(). The value of this property is an instance of CannotProceedException. This is useful to service providers that implement federation by chaining the CPEs.
  • Defined a convention for service providers to use when naming environment properties. See Section 6.1.

[Top] [Prev] [Next] [Bottom]
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Chapter 1: Introduction to the Java Sound API

Design Goals

The Java Sound API is a low-level API for effecting and controlling the input and output of sound media, including both audio and Musical Instrument Digital Interface (MIDI) data. The Java Sound API provides explicit control over the capabilities normally required for sound input and output, in a framework that promotes extensibility and flexibility.

Who is the Java Sound API For?

Because sound is so fundamental, the Java Sound API fulfills the needs of a wide range of application developers. Potential application areas include:

  • Communication frameworks, such as conferencing and telephony
  • End-user content delivery systems, such as media players and music using streamed content
  • Interactive application programs, such as games and Web sites that use dynamic content
  • Content creation and editing
  • Tools, toolkits, and utilities

How Does the Java Sound API Relate to Other Interfaces?

The Java Sound API provides the lowest level of sound support on the Java platform. It provides application programs with a great amount of control over sound operations, and it is extensible. For example, the Java Sound API supplies mechanisms for installing, accessing, and manipulating system resources such as audio mixers, MIDI synthesizers, other audio or MIDI devices, file readers and writers, and sound format converters. The Java Sound API does not include sophisticated sound editors or graphical tools, but it provides capabilities upon which such programs can be built. It emphasizes low-level control beyond that commonly expected by the end user.

There are other Java platform APIs that have sound-related elements. The Java Media Framework (JMF) is a higher-level API that is currently available as a Standard Extension to the Java platform. JMF specifies a unified architecture, messaging protocol, and programming interface for capturing and playing back time-based media. JMF provides a simpler solution for basic media-player application programs, and it enables synchronization between different media types, such as audio and video. On the other hand, programs that focus on sound can benefit from the Java Sound API, especially if they require more advanced features, such as the ability to carefully control buffered audio playback or directly manipulate a MIDI synthesizer. Other Java APIs with sound aspects include Java 3D and APIs for telephony and speech. An implementation of any of these APIs might use an implementation of the Java Sound API internally, but is not required to do so.

Packages

The Java Sound API includes support for both digital audio and MIDI data. These two major modules of functionality are provided in separate packages:

  • javax.sound.sampled This package specifies interfaces for capture, mixing, and playback of digital (sampled) audio.
  • javax.sound.midi This package provides interfaces for MIDI synthesis, sequencing, and event transport.

Two other packages permit service providers (as opposed to application developers) to create custom software components that extend the capabilities of an implementation of the Java Sound API:
  • javax.sound.sampled.spi
  • javax.sound.midi.spi

The rest of this chapter briefly discusses the sampled-audio system, the MIDI system, and the SPI packages. Each of these is then discussed in detail in a subsequent part of the guide.

Sampled Audio

What Is Sampled Audio?

The javax.sound.sampled package handles digital audio data, which the Java Sound API refers to as sampled audio. Samples are successive snapshots of a signal. In the case of audio, the signal is a sound wave. A microphone converts the acoustic signal into a corresponding analog electrical signal, and an analog-to-digital converter transforms that analog signal into a sampled digital form. The following figure shows a brief moment in a sound recording.

A sampled sound wave A Sampled Sound Wave

This graph plots sound pressure (amplitude) on the vertical axis, and time on the horizontal axis. The amplitude of the analog sound wave is measured periodically at a certain rate, resulting in the discrete samples (the red data points in the figure) that comprise the digital audio signal. The center horizontal line indicates zero amplitude; points above the line are positive-valued samples, and points below are negative. The accuracy of the digital approximation of the analog signal depends on its resolution in time (the sampling rate) and its quantization, or resolution in amplitude (the number of bits used to represent each sample). As a point of reference, the audio recorded for storage on compact discs is sampled 44,100 times per second and represented with 16 bits per sample.

The term "sampled audio" is used here slightly loosely. A sound wave could be sampled at discrete intervals while being left in an analog form. For purposes of the Java Sound API, however, "sampled audio" is equivalent to "digital audio."

Typically, sampled audio on a computer comes from a sound recording, but the sound could instead be synthetically generated (for example, to create the sounds of a touch-tone telephone). The term "sampled audio" refers to the type of data, not its origin.

Further information about the structure of digital audio data is given under "What Is Formatted Audio Data?" in Chapter 2, "Overview of the Sampled Package."

Audio Configurations

The Java Sound API does not assume a specific audio hardware configuration; it is designed to allow different sorts of audio components to be installed on a system and accessed by the API. The Java Sound API supports common functionality such as input and output from a sound card (for example, for recording and playback of sound files) as well as mixing of multiple streams of audio. Here is one example of a typical audio architecture:

The following context describes this graphic

A Typical Audio Architecture

In this example, a device such as a sound card has various input and output ports, and mixing is provided in the software. The mixer might receive data that has been read from a file, streamed from a network, generated on the fly by an application program, or produced by a MIDI synthesizer. (The javax.sound.midi package, discussed next, supplies a Java language interface for synthesizers.) The mixer combines all its audio inputs into a single stream, which can be sent to an output device for rendering.

MIDI

The javax.sound.midi package contains APIs for transporting and sequencing MIDI events, and for synthesizing sound from those events.

What Is MIDI?

Whereas sampled audio is a direct representation of a sound itself, MIDI data can be thought of as a recipe for creating a sound, especially a musical sound. MIDI data, unlike audio data, does not describe sound directly. Instead, it describes events that affect the sound a synthesizer is making. MIDI data is analogous to a graphical user interface's keyboard and mouse events. In the case of MIDI, the events can be thought of as actions upon a musical keyboard, along with actions on various pedals, sliders, switches, and knobs on that musical instrument. These events need not actually originate with a hardware musical instrument; they can be simulated in software, and they can be stored in MIDI files. A program that can create, edit, and perform these files is called a sequencer. Many computer sound cards include MIDI-controllable music synthesizer chips to which sequencers can send their MIDI events. Synthesizers can also be implemented entirely in software. The synthesizers interpret the MIDI events that they receive and produce audio output. Usually the sound synthesized from MIDI data is musical sound (as opposed to speech, for example). MIDI synthesizers are also capable of generating various kinds of sound effects.

Some sound cards include MIDI input and output ports to which external MIDI hardware devices (such as keyboard synthesizers or other instruments) can be connected. From a MIDI input port, an application program can receive events generated by an external MIDI-equipped musical instrument. The program might play the musical performance using the computer's internal synthesizer, save it to disk as a MIDI file, or render it into musical notation. A program might use a MIDI output port to play an external instrument, or to control other external devices such as recording equipment.

More information about MIDI data is given in Chapter 8, "Overview of the MIDI Package," particularly in the section "A MIDI Refresher: Wires and Files."

MIDI Configurations

The diagram below illustrates the functional relationships between the major components in a possible MIDI configuration based on the Java Sound API. (As with audio, the Java Sound API permits a variety of MIDI software devices to be installed and interconnected. The system shown here is one potential scenario.) The flow of data between components is indicated by arrows. The data can be in a standard file format, or (as indicated by the key in the lower right corner of the diagram), it can be audio, raw MIDI bytes, or time-tagged MIDI messages.

The following context describes this graphic

A Possible MIDI Configuration

In this example, the application program prepares a musical performance by loading a musical score that's stored as a standard MIDI file on a disk (left side of the diagram). Standard MIDI files contain tracks, each of which is a list of time-tagged MIDI events. Most of the events represent musical notes (pitches and rhythms). This MIDI file is read and then "performed" by a software sequencer. A sequencer performs its music by sending MIDI messages to some other device, such as an internal or external synthesizer. The synthesizer itself may read a soundbank file containing instructions for emulating the sounds of certain musical instruments. If not, the synthesizer will play the notes stored in the MIDI file using whatever instrument sounds are already loaded into the synthesizer.

As illustrated, the MIDI events must be translated into raw (non-time-tagged) MIDI before being sent through a MIDI output port to an external synthesizer. Similarly, raw MIDI data coming into the computer from an external MIDI source (a keyboard instrument, in the diagram) is translated into time-tagged MIDI messages that can control a synthesizer, or that a sequencer can store for later use. All these aspects of MIDI data flow are explained in detail in the subsequent chapters on MIDI (see Part II of this guide).

Service Provider Interfaces

The javax.sound.sampled.spi and javax.sound.midi.spi packages contain APIs that let software developers create new audio or MIDI resources that can be provided separately to the user and "plugged in" to an existing implementation of the Java Sound API. Here are some examples of services (resources) that can be added in this way:

  • An audio mixer
  • A MIDI synthesizer
  • A file parser that can read or write a new type of audio or MIDI file
  • A converter that translates between different sound data formats

In some cases, services are software interfaces to the capabilities of hardware devices, such as sound cards, and the service provider might be the same as the vendor of the hardware. In other cases, the services exist purely in software. For example, a synthesizer or a mixer could be an interface to a chip on a sound card, or it could be implemented without any hardware support at all.

An implementation of the Java Sound API contains a basic set of services, but the service provider interface (SPI) packages allow third parties to create new services. These third-party services are integrated into the system in the same way as the built-in services. The AudioSystem class in the sampled package and the MidiSystem class in the midi package act as coordinators that let application programs access the services explicitly or implicitly. Often the existence of a service is completely transparent to an application program that uses it. The service-provider mechanism benefits users of application programs based on the Java Sound API, because new sound features can be added to a program without requiring a new release of the Java SDK or runtime environment, and, in many cases, without even requiring a new release of the application program itself.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Chapter 2: Overview of the Sampled Package

Notes

  1. With J2SE 5.0 and the new Direct Audio mixers, the Sun reference implementation allows use of all available soundcards and all supported sample rates and bits per sample.
  2. Direct Audio mixers are always the default on Windows. They are the default on Solaris if the Solaris audio mixer is enabled (see Solaris man page for mixer). On Linux, they are the default only if there is a device that supports mixing.
  3. Because they are "direct," Direct Audio mixers do not support SAMPLE_RATE control.
  4. The default mixer can be selected via the sound.properties file.

This chapter provides an introduction to the Java Sound API's digital audio architecture, which is accessed through the javax.sound.sampled package. First, an explanation is given of the package's focus: playback and capture of formatted audio data. Then this chapter describes the three fundamental components required for playback or capture: an audio data format, a line, and a mixer. The Line interface and its subinterfaces are introduced briefly.

Design Goals

Before examining the elements of the Java Sound API, it helps to understand the orientation of the javax.sound.sampled package.

A Focus on Data Transport

The javax.sound.sampled package is fundamentally concerned with audio transport—in other words, the Java Sound API focuses on playback and capture. The central task that the Java Sound API addresses is how to move bytes of formatted audio data into and out of the system. This task involves opening audio input and output devices and managing buffers that get filled with real-time sound data. It can also involve mixing multiple streams of audio into one stream (whether for input or output). The transport of sound into or out of the system has to be correctly handled when the user requests that the flow of sound be started, paused, resumed, or stopped.

To support this focus on basic audio input and output, the Java Sound API provides methods for converting between various audio data formats, and for reading and writing common types of sound files. However, it does not attempt to be a comprehensive sound-file toolkit. A particular implementation of the Java Sound API need not support an extensive set of file types or data format conversions. Third-party service providers can supply modules that "plug in" to an existing implementation to support additional file types and conversions.

Buffered and Unbuffered Handling of Audio

The Java Sound API can handle audio transport in both a streaming, buffered fashion and an in-memory, unbuffered fashion. "Streaming" is used here in a general sense to refer to real-time handling of audio bytes; it does not refer to the specific, well-known case of sending audio over the Internet in a certain format. In other words, a stream of audio is simply a continuous set of audio bytes that arrive more or less at the same rate that they are to be handled (played, recorded, etc.). Operations on the bytes commence before all the data has arrived. In the streaming model, particularly in the case of audio input rather than audio output, you do not necessarily know in advance how long the sound is and when it will finish arriving. You simply handle one buffer of audio data at a time, until the operation is halted. In the case of audio output (playback), you also need to buffer data if the sound you want to play is too large to fit in memory all at once. In other words, you deliver your audio bytes to the sound engine in chunks, and it takes care of playing each sample at the right time. Mechanisms are provided that make it easy to know how much data to deliver in each chunk.

The Java Sound API also permits unbuffered transport in the case of playback only, assuming you already have all the audio data at hand and it is not too large to fit in memory. In this situation, there is no need for the application program to buffer the audio, although the buffered, real-time approach is still available if desired. Instead, the entire sound can be preloaded at once into memory for subsequent playback. Because all the sound data is loaded in advance, playback can start immediately, for example, as soon as the user clicks a Start button. This can be an advantage compared to the buffered model, where the playback has to wait for the first buffer to fill. In addition, the in-memory, unbuffered model allows sounds to be easily looped (cycled) or set to arbitrary positions in the data.

These two models for playback are discussed further in Chapter 4, "Playing Back Audio." Buffered recording is discussed in Chapter 5, "Capturing Audio."

The Essentials: Format, Mixer, and Line

To play or capture sound using the Java Sound API, you need at least three things: formatted audio data, a mixer, and a line. Each of these is explained below.

What Is Formatted Audio Data?

Formatted audio data refers to sound in any of a number of standard formats. The Java Sound API distinguishes between data formats and file formats.

Data Formats

A data format tells you how to interpret a series of bytes of "raw" sampled audio data, such as samples that have already been read from a sound file, or samples that have been captured from the microphone input. You might need to know, for example, how many bits constitute one sample (the representation of the shortest instant of sound), and similarly you might need to know the sound's sample rate (how fast the samples are supposed to follow one another). When setting up for playback or capture, you specify the data format of the sound you are capturing or playing.

In the Java Sound API, a data format is represented by an AudioFormat object, which includes the following attributes:

  • Encoding technique, usually pulse code modulation (PCM)
  • Number of channels (1 for mono, 2 for stereo, etc.)
  • Sample rate (number of samples per second, per channel)
  • Number of bits per sample (per channel)
  • Frame rate
  • Frame size in bytes
  • Byte order (big-endian or little-endian)

PCM is one kind of encoding of the sound waveform. The Java Sound API includes two PCM encodings that use linear quantization of amplitude, and signed or unsigned integer values. Linear quantization means that the number stored in each sample is directly proportional (except for any distortion) to the original sound pressure at that instant and similarly proportional to the displacement of a loudspeaker or eardrum that is vibrating with the sound at that instant. Compact discs, for example, use linear PCM-encoded sound. Mu-law encoding and a-law encoding are common nonlinear encodings that provide a more compressed version of the audio data; these encodings are typically used for telephony or recordings of speech. A nonlinear encoding maps the original sound's amplitude to the stored value using a nonlinear function, which can be designed to give more amplitude resolution to quiet sounds than to loud sounds.

A frame contains the data for all channels at a particular time. For PCM-encoded data, the frame is simply the set of simultaneous samples in all channels, for a given instant in time, without any additional information. In this case, the frame rate is equal to the sample rate, and the frame size in bytes is the number of channels multiplied by the sample size in bits, divided by the number of bits in a byte.

For other kinds of encodings, a frame might contain additional information besides the samples, and the frame rate might be completely different from the sample rate. For example, consider the MP3 (MPEG-1 Audio Layer 3) encoding, which is not explicitly mentioned in the current version of the Java Sound API, but which could be supported by an implementation of the Java Sound API or by a third-party service provider. In MP3, each frame contains a bundle of compressed data for a series of samples, not just one sample per channel. Because each frame encapsulates a whole series of samples, the frame rate is slower than the sample rate. The frame also contains a header. Despite the header, the frame size in bytes is less than the size in bytes of the equivalent number of PCM frames. (After all, the purpose of MP3 is to be more compact than PCM data.) For such an encoding, the sample rate and sample size refer to the PCM data that the encoded sound will eventually be converted into before being delivered to a digital-to-analog converter (DAC).

File Formats

A file format specifies the structure of a sound file, including not only the format of the raw audio data in the file, but also other information that can be stored in the file. Sound files come in various standard varieties, such as WAVE (also known as WAV, and often associated with PCs), AIFF (often associated with Macintoshes), and AU (often associated with UNIX systems). The different types of sound file have different structures. For example, they might have a different arrangement of data in the file's "header." A header contains descriptive information that typically precedes the file's actual audio samples, although some file formats allow successive "chunks" of descriptive and audio data. The header includes a specification of the data format that was used for storing the audio in the sound file. Any of these types of sound file can contain various data formats (although usually there is only one data format within a given file), and the same data format can be used in files that have different file formats.

In the Java Sound API, a file format is represented by an AudioFileFormat object, which contains:

  • The file type (WAVE, AIFF, etc.)
  • The file's length in bytes
  • The length, in frames, of the audio data contained in the file
  • An AudioFormat object that specifies the data format of the audio data contained in the file

The AudioSystem class (described in Chapter 3, "Accessing Audio System Resources") provides methods for reading and writing sounds in different file formats, and for converting between different data formats. Some of the methods let you access a file's contents through a kind of stream called an AudioInputStream. An AudioInputStream is a subclass of the generic Java InputStream class, which encapsulates a series of bytes that can be read sequentially. To its superclass, the AudioInputStream class adds knowledge of the bytes' audio data format (represented by an AudioFormat object). By reading a sound file as an AudioInputStream, you get immediate access to the samples, without having to worry about the sound file's structure (its header, chunks, etc.). A single method invocation gives you all the information you need about the data format and the file type.

What Is a Mixer?

Many application programming interfaces (APIs) for sound make use of the notion of an audio device. A device is often a software interface to a physical input/output device. For example, a sound-input device might represent the input capabilities of a sound card, including a microphone input, a line-level analog input, and perhaps a digital audio input.

In the Java Sound API, devices are represented by Mixer objects. The purpose of a mixer is to handle one or more streams of audio input and one or more streams of audio output. In the typical case, it actually mixes together multiple incoming streams into one outgoing stream. A Mixer object can represent the sound-mixing capabilities of a physical device such as a sound card, which might need to mix the sound coming in to the computer from various inputs, or the sound coming from application programs and going to outputs.

Alternatively, a Mixer object can represent sound-mixing capabilities that are implemented entirely in software, without any inherent interface to physical devices.

In the Java Sound API, a component such as the microphone input on a sound card is not itself considered a device—that is, a mixer—but rather a port into or out of the mixer. A port typically provides a single stream of audio into or out of the mixer (although the stream can be multichannel, such as stereo). The mixer might have several such ports. For example, a mixer representing a sound card's output capabilities might mix several streams of audio together, and then send the mixed signal to any or all of various output ports connected to the mixer. These output ports could be (for example) a headphone jack, a built-in speaker, or a line-level output.

To understand the notion of a mixer in the Java Sound API, it helps to visualize a physical mixing console, such as those used in live concerts and recording studios. (See illustration that follows.)

Physical mixing console

A Physical Mixing Console

A physical mixer has "strips" (also called "slices"), each representing a path through which a single audio signal goes into the mixer for processing. The strip has knobs and other controls by which you can control the volume and pan (placement in the stereo image) for the signal in that strip. Also, the mixer might have a separate bus for effects such as reverb, and this bus can be connected to an internal or external reverberation unit. Each strip has a potentiometer that controls how much of that strip's signal goes into the reverberated mix. The reverberated ("wet") mix is then mixed with the "dry" signals from the strips. A physical mixer sends this final mixture to an output bus, which typically goes to a tape recorder (or disk-based recording system) and/or speakers.

Imagine a live concert that is being recorded in stereo. Cables (or wireless connections) coming from the many microphones and electric instruments on stage are plugged into the inputs of the mixing console. Each input goes to a separate strip of the mixer, as illustrated. The sound engineer decides on the settings of the gain, pan, and reverb controls. The output of all the strips and the reverb unit are mixed together into two channels. These two channels go to two outputs on the mixer, into which cables are plugged that connect to the stereo tape recorder's inputs. The two channels are perhaps also sent via an amplifier to speakers in the hall, depending on the type of music and the size of the hall.

Now imagine a recording studio, in which each instrument or singer is recorded to a separate track of a multitrack tape recorder. After the instruments and singers have all been recorded, the recording engineer performs a "mixdown" to combine all the taped tracks into a two-channel (stereo) recording that can be distributed on compact discs. In this case, the input to each of the mixer's strips is not a microphone, but one track of the multitrack recording. Once again, the engineer can use controls on the strips to decide each track's volume, pan, and reverb amount. The mixer's outputs go once again to a stereo recorder and to stereo speakers, as in the example of the live concert.

These two examples illustrate two different uses of a mixer: to capture multiple input channels, combine them into fewer tracks, and save the mixture, or to play back multiple tracks while mixing them down to fewer tracks.

In the Java Sound API, a mixer can similarly be used for input (capturing audio) or output (playing back audio). In the case of input, the source from which the mixer gets audio for mixing is one or more input ports. The mixer sends the captured and mixed audio streams to its target, which is an object with a buffer from which an application program can retrieve this mixed audio data. In the case of audio output, the situation is reversed. The mixer's source for audio is one or more objects containing buffers into which one or more application programs write their sound data; and the mixer's target is one or more output ports.

What Is a Line?

The metaphor of a physical mixing console is also useful for understanding the Java Sound API's concept of a line.

A line is an element of the digital audio "pipeline"—that is, a path for moving audio into or out of the system. Usually the line is a path into or out of a mixer (although technically the mixer itself is also a kind of line).

Audio input and output ports are lines. These are analogous to the microphones and speakers connected to a physical mixing console. Another kind of line is a data path through which an application program can get input audio from, or send output audio to, a mixer. These data paths are analogous to the tracks of the multitrack recorder connected to the physical mixing console.

One difference between lines in the Java Sound API and those of a physical mixer is that the audio data flowing through a line in the Java Sound API can be mono or multichannel (for example, stereo). By contrast, each of a physical mixer's inputs and outputs is typically a single channel of sound. To get two or more channels of output from the physical mixer, two or more physical outputs are normally used (at least in the case of analog sound; a digital output jack is often multichannel). In the Java Sound API, the number of channels in a line is specified by the AudioFormat of the data that is currently flowing through the line.

Lines in an Audio-output Configuration

Let's now examine some specific kinds of lines and mixers. The following diagram shows different types of lines in a simple audio-output system that could be part of an implementation of the Java Sound API:

Possible configuration of lines for audio output

A Possible Configuration of Lines for Audio Output

In this example, an application program has gotten access to some available inputs of an audio-input mixer: one or more clips and source data lines. A clip is a mixer input (a kind of line) into which you can load audio data prior to playback; a source data line is a mixer input that accepts a real-time stream of audio data. The application program preloads audio data from a sound file into the clips. It then pushes other audio data into the source data lines, a buffer at a time. The mixer reads data from all these lines, each of which may have its own reverberation, gain, and pan controls, and mixes the dry audio signals with the wet (reverberated) mix. The mixer delivers its final output to one or more output ports, such as a speaker, a headphone jack, and a line-out jack.

Although the various lines are depicted as separate rectangles in the diagram, they are all "owned" by the mixer, and can be considered integral parts of the mixer. The reverb, gain, and pan rectangles represent processing controls (rather than lines) that can be applied by the mixer to data flowing through the lines.

Note that this is just one example of a possible mixer that is supported by the API. Not all audio configurations will have all the features illustrated. An individual source data line might not support panning, a mixer might not implement reverb, and so on.

Lines in an Audio-input Configuration

A simple audio-input system might be similar:

Possible configuration of lines for audio input

A Possible Configuration of Lines for Audio Input

Here, data flows into the mixer from one or more input ports, commonly the microphone or the line-in jack. Gain and pan are applied, and the mixer delivers the captured data to an application program via the mixer's target data line. A target data line is a mixer output, containing the mixture of the streamed input sounds. The simplest mixer has just one target data line, but some mixers can deliver captured data to multiple target data lines simultaneously.

The Line Interface Hierarchy

Now that we've seen some functional pictures of what lines and mixers are, let's discuss them from a slightly more programmatic perspective. Several types of line are defined by subinterfaces of the basic Line interface. The interface hierarchy is shown below.

Line interface hierarchy

The Line Interface Hierarchy

The base interface, Line, describes the minimal functionality common to all lines:

  • Controls Data lines and ports often have a set of controls that affect the audio signal passing through the line. The Java Sound API specifies control classes that can be used to manipulate aspects of sound such as: gain (which affects the signal's volume in decibels), pan (which affects the sound's right-left positioning, reverb (which adds reverberation to the sound to emulate different kinds of room acoustics), and sample rate (which affects the rate of playback as well as the sound's pitch).
  • Open or closed status Successful opening of a line guarantees that resources have been allocated to the line. A mixer has a finite number of lines, so at some point multiple application programs (or the same one) might vie for usage of the mixer's lines. Closing a line indicates that any resources used by the line may now be released.
  • Events A line generates events when it opens or closes. Subinterfaces of Line can introduce other types of events. When a line generates an event, the event is sent to all objects that have registered to "listen" for events on that line. An application program can create these objects, register them to listen for line events, and react to the events as desired.

We'll now examine the subinterfaces of the Line interface.

Ports are simple lines for input or output of audio to or from audio devices. As mentioned earlier, some common types of ports are the microphone, line input, CD-ROM drive, speaker, headphone, and line output.

The Mixer interface represents a mixer, of course, which as we have seen represents either a hardware or a software device. The Mixer interface provides methods for obtaining a mixer's lines. These include source lines, which feed audio to the mixer, and target lines, to which the mixer delivers its mixed audio. For an audio-input mixer, the source lines are input ports such as the microphone input, and the target lines are TargetDataLines (described below), which deliver audio to the application program. For an audio-output mixer, on the other hand, the source lines are Clips or SourceDataLines (described below), to which the application program feeds audio data, and the target lines are output ports such as the speaker.

A Mixer is defined as having one or more source lines and one or more target lines. Note that this definition means that a mixer need not actually mix data; it might have only a single source line. The Mixer API is intended to encompass a variety of devices, but the typical case supports mixing.

The Mixer interface supports synchronization; that is, you can specify that two or more of a mixer's lines be treated as a synchronized group. Then you can start, stop, or close all those data lines by sending a single message to any line in the group, instead of having to control each line individually. With a mixer that supports this feature, you can obtain sample-accurate synchronization between lines.

The generic Line interface does not provide a means to start and stop playback or recording. For that you need a data line. The DataLine interface supplies the following additional media-related features beyond those of a Line:

  • Audio format Each data line has an audio format associated with its data stream.
  • Media position A data line can report its current position in the media, expressed in sample frames. This represents the number of sample frames captured by or rendered from the data line since it was opened.
  • Buffer size This is the size of the data line's internal buffer in bytes. For a source data line, the internal buffer is one to which data can be written, and for a target data line it's one from which data can be read.
  • Level (the current amplitude of the audio signal)

  • Start and stop playback or capture

  • Pause and resume playback or capture

  • Flush (discard unprocessed data from the queue)

  • Drain (block until all unprocessed data has been drained from the queue, and the data line's buffer has become empty)

  • Active status A data line is considered active if it is engaged in active presentation or capture of audio data to or from a mixer.
  • Events START and STOP events are produced when active presentation or capture of data from or to the data line starts or stops.

A TargetDataLine receives audio data from a mixer. Commonly, the mixer has captured audio data from a port such as a microphone; it might process or mix this captured audio before placing the data in the target data line's buffer. The TargetDataLine interface provides methods for reading the data from the target data line's buffer and for determining how much data is currently available for reading.

A SourceDataLine receives audio data for playback. It provides methods for writing data to the source data line's buffer for playback, and for determining how much data the line is prepared to receive without blocking.

A Clip is a data line into which audio data can be loaded prior to playback. Because the data is pre-loaded rather than streamed, the clip's duration is known before playback, and you can choose any starting position in the media. Clips can be looped, meaning that upon playback, all the data between two specified loop points will repeat a specified number of times, or indefinitely.

This chapter has introduced most of the important interfaces and classes of the sampled-audio API. Subsequent chapters show how you can access and use these objects in your application program.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Chapter 3: Accessing Audio System Resources

Notes

  1. The Port class was not available on all platforms before JDK 5.0.
  2. With version 5.0, the sound.properties file can be used to set default devices for Clip, Port, SourceDataLine, and TargetDataLine. For details, see the AudioSystem class in the API; for examples, see Appendix 2: sound.properties File in this guide.
  3. While the method for obtaining lines, as outlined below in Getting a Line of a Desired Type, is still valid, for 5.0 there are convenience methods for Clip, SourceDataLine, and TargetDataLine: AudioSystem.getClip(), AudioSystem.getSourceDataLine(), and AudioSystem.getTargetDataLine(). See the AudioSystem for details.

The Java Sound API takes a flexible approach to system configuration. Different sorts of audio devices (mixers) can be installed on a computer. The API makes few assumptions about what devices have been installed and what their capabilities are. Instead, it provides ways for the system to report about the available audio components, and ways for your program to access them.

This section shows how your program can learn what sampled-audio resources have been installed on the computer, and how it can gain access to the available resources. Among other things, the resources include mixers and the various types of lines owned by the mixers.

The AudioSystem Class

The AudioSystem class acts as a clearinghouse for audio components, including built-in services and separately installed services from third-party providers. AudioSystem serves as an application program's entry point for accessing these installed sampled-audio resources. You can query the AudioSystem to learn what sorts of resources have been installed, and then you can obtain access to them. For example, an application program might start out by asking the AudioSystem class whether there is a mixer that has a certain configuration, such as one of the input or output configurations illustrated earlier in the discussion of lines. From the mixer, the program would then obtain data lines, and so on.

Here are some of the resources an application program can obtain from the AudioSystem:

  • Mixers A system typically has multiple mixers installed. There is usually at least one for audio input and one for audio output. There might also be mixers that don't have I/O ports but instead accept audio from an application program and deliver the mixed audio back to the program. The AudioSystem class provides a list of all of the installed mixers.
  • Lines Even though every line is associated with a mixer, an application program can get a line directly from the AudioSystem, without dealing explicitly with mixers.
  • Format conversions An application program can use format conversions to translate audio data from one format to another. Conversions are described in Chapter 7, "Using Files and Format Converters."
  • Files and streams The AudioSystem class provides methods for translating between audio files and audio streams. It can also report the file format of a sound file and can write files in different formats. These facilities are discussed in Chapter 7, "Using Files and Format Converters."

Information Objects

Several classes in the Java Sound API provide useful information about associated interfaces. For example, Mixer.Info provides details about an installed mixer, such as the mixer's vendor, name, description, and version. Line.Info obtains the class of a specific line. Subclasses of Line.Info include Port.Info and DataLine.Info, which obtain details relevant to a specific port and data line, respectively. Each of these classes is described further in the appropriate section below. It's important not to confuse the Info object with the mixer or line object that it describes.

Getting a Mixer

Usually, one of the first things a program that uses the Java Sound API needs to do is to obtain a mixer, or at least one line of a mixer, so that you can get sound into or out of the computer. Your program might need a specific kind of mixer, or you might want to display a list of all the available mixers so that the user can select one. In either case, you need to learn what kinds of mixers are installed. AudioSystem provides the following method:

    static Mixer.Info[] getMixerInfo()
Each Mixer.Info object returned by this method identifies one type of mixer that is installed. (Usually a system has at most one mixer of a given type. If there happens to be more than one of a given type, the returned array still only has one Mixer.Info for that type.) An application program can iterate over the Mixer.Info objects to find an appropriate one, according to its needs. The Mixer.Info includes the following strings to identify the kind of mixer:
  • Name
  • Version
  • Vendor
  • Description

These are arbitrary strings, so an application program that needs a specific mixer must know what to expect and what to compare the strings to. The company that provides the mixer should include this information in its documentation. Alternatively, and perhaps more typically, the application program will display all the Mixer.Info objects' strings to the user and let the user choose the corresponding mixer.

Once an appropriate mixer is found, the application program invokes the following AudioSystem method to obtain the desired mixer:

    static Mixer getMixer(Mixer.Info info)
What if your program needs a mixer that has certain capabilities, but it doesn't need a specific mixer made by a specific vendor? And what if you can't depend on the user's knowing which mixer should be chosen? In that case, the information in the Mixer.Info objects won't be of much use. Instead, you can iterate over all the Mixer.Info objects returned by getMixerInfo, get a mixer for each by invoking getMixer, and query each mixer for its capabilities. For example, you might need a mixer that can write its mixed audio data to a certain number of target data lines simultaneously. In that case, you would query each mixer using this Mixer method: int getMaxLines(Line.Info info)

Here, the Line.Info would specify a TargetDataLine. The Line.Info class is discussed in the next section.

Getting a Line of a Desired Type

There are two ways to get a line:

  • Directly from the AudioSystem object
  • From a mixer that you have already obtained from the AudioSystem object (see "Getting a Mixer," in this chapter)

Getting a Line Directly from the AudioSystem

Let's assume you haven't obtained a mixer, and your program is a simple one that really only needs a certain kind of line; the details of the mixer don't matter to you. You can use the AudioSystem method:

    static Line getLine(Line.Info info)
which is analogous to the getMixer method discussed above. Unlike Mixer.Info, the Line.Info used as an argument doesn't store textual information to specify the desired line. Instead, it stores information about the class of line desired.

Line.Info is an abstract class, so you use one of its subclasses (Port.Info or DataLine.Info) to obtain a line. The following code excerpt uses the DataLine.Info subclass to obtain and open a target data line:

TargetDataLine line;
DataLine.Info info = new DataLine.Info(TargetDataLine.class,
    format); // format is an AudioFormat object
if (!AudioSystem.isLineSupported(info)) {
    // Handle the error.
    }
    // Obtain and open the line.
try {
    line = (TargetDataLine) AudioSystem.getLine(info);
    line.open(format);
} catch (LineUnavailableException ex) {
        // Handle the error.
    //...
}
This code obtains a TargetDataLine object without specifying any attributes other than its class and its audio format. You can use analogous code to obtain other kinds of lines. For a SourceDataLine or a Clip, just substitute that class for TargetDataLine as the class of the line variable, and also in the first argument to the DataLine.Info constructor.

For a Port, you can use static instances of Port.Info, in code like the following:

if (AudioSystem.isLineSupported(Port.Info.MICROPHONE)) {
    try {
        line = (Port) AudioSystem.getLine(
            Port.Info.MICROPHONE);
    }
}
Note the use of the method isLineSupported to see whether the mixer even has a line of the desired type.

Recall that a source line is an input to a mixer—namely, a Port object if the mixer represents an audio-input device, and a SourceDataLine or Clip object if the mixer represents an audio-output device. Similarly, a target line is an output of the mixer: a Port object for an audio-output mixer, and a TargetDataLine object for an audio-input mixer. What if a mixer doesn't connect to any external hardware device at all? For example, consider an internal or software-only mixer that gets audio from an application program and delivers its mixed audio back to the program. This kind of mixer has SourceDataLine or Clip objects for its input lines and TargetDataLine objects for its output lines.

You can also use the following AudioSystem methods to learn more about source and target lines of a specified type that are supported by any installed mixer:

    static Line.Info[] getSourceLineInfo(Line.Info info)
    static Line.Info[] getTargetLineInfo(Line.Info info)
Note that the array returned by each of these methods indicates unique types of lines, not necessarily all the lines. For example, if two of a mixer's lines, or two lines of different mixers, have identical Line.Info objects, the two lines will represented by only one Line.Info in the returned array.

Getting a Line from a Mixer

The Mixer interface includes variations on the AudioSystem access methods for source and target lines, described above. These Mixer methods include ones that take Line.Info arguments, just as AudioSystem's methods do. However, Mixer also includes these variants, which take no arguments:

    Line.Info[] getSourceLineInfo()
    Line.Info[] getTargetLineInfo()
These methods return arrays of all the Line.Info objects for the particular mixer. Once you've obtained the arrays, you can iterate over them, calling Mixer's getLine method to obtain each line, followed by Line's open method to reserve use of each line for your program.

Selecting Input and Output Ports

The previous section, regarding how to obtain a line of a desired type, applies to ports as well as other types of lines. You can obtain all of the source (i.e., input) and target (i.e, output) ports by passing a Port.Info object to the AudioSystem (or Mixer) methods getSourceLineInfo and getTargetLineInfo that take a Line.Info argument. You then iterate over the returned array of objects and invoke Mixer's getLine method to get each port.

You can then open each Port by invoking Line's open method. Opening a port means you turn it on—that is, you allow sound to come in or out the port. Similarly, you can close ports that you don't want sound to travel through, because some ports might already be open before you even obtain them. Some platforms leave all ports on by default; or a user or system administrator might have selected certain ports to be on or off, using another application program or operating-system software.

Warning: If you want to select a certain port and make sure that the sound is actually going in or out the port, you can open the port as described. However, this can be considered user-hostile behavior! For example, a user might have the speaker port turned off so as not to disturb her co-workers. She would be rather upset if your program suddenly overrode her wishes and started blaring music. As another example, a user might want to be assured that his computer's microphone is never turned on without his knowledge, to avoid eavesdropping. In general, it is recommended not to open or close ports unless your program is responding to the user's intentions, as expressed through the user interface. Instead, respect the settings that the user or the operating system has already selected.

It isn't necessary to open or close a port before the mixer it's attached to will function correctly. For example, you can start playing back sound into an audio-output mixer, even though all its output ports are closed. The data still flows into the mixer; the playback isn't blocked. The user just won't hear anything. As soon as the user opens an output port, the sound will be audible through that port, starting at whatever point in the media the playback has already reached.

Also, you don't need to access the ports to learn whether the mixer has certain ports. To learn whether a mixer is actually an audio-output mixer, for example, you can invoke getTargetLineInfo to see whether it has output ports. There's no reason to access the ports themselves unless you want to change their settings (such as their open-or-closed state, or the settings of any controls they might have).

Permission to Use Audio Resources

The Java Sound API includes an AudioPermission class that indicates what kinds of access an applet (or an application running with a security manager) can have to the sampled-audio system. Permission to record sound is controlled separately. This permission should be granted with care, to help prevent security risks such as unauthorized eavesdropping. By default, applets and applications are granted permissions as follows:

  • An applet running with the applet security manager can play, but not record, audio.
  • An application running with no security manager can both play and record audio.
  • An application running with the default security manager can play, but not record, audio.

In general, applets are run under the scrutiny of a security manager and aren't permitted to record sound. Applications, on the other hand, don't automatically install a security manager, and are able to record sound. (However, if the default security manager is invoked explicitly for an application, the application isn't permitted to record sound.)

Both applets and applications can record sound even when running with a security manager if they have been granted explicit permission to do so.

If your program doesn't have permission to record (or play) sound, an exception will be thrown when it attempts to open a line. There is nothing you can do about this in your program, other than to catch the exception and report the problem to the user, because permissions can't be changed through the API. (If they could, they would be pointless, because nothing would be secure!) Generally, permissions are set in one or more policy configuration files, which a user or system administrator can edit using a text editor or the Policy Tool program.

For more information on security and permissions, see "Security Architecture" and "Policy Permissions" in the Security guide and the specialized trail on security in the Java Tutorial.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Chapter 4: Playing Back Audio

Playback is sometimes referred to as presentation or rendering. These are general terms that are applicable to other kinds of media besides sound. The essential feature is that a sequence of data is delivered somewhere for eventual perception by a user. If the data is time-based, as sound is, it must be delivered at the correct rate. With sound even more than video, it's important that the rate of data flow be maintained, because interruptions to sound playback often produce loud clicks or irritating distortion. The Java Sound API is designed to help application programs play sounds smoothly and continuously, even very long sounds.

The previous chapter discussed how to obtain a line from the audio system or from a mixer. This chapter shows how to play sound through a line.

There are two kinds of line that you can use for playing sound: a Clip and a SourceDataLine. These two interfaces were introduced briefly under "The Line Interface Hierarchy" in Chapter 2, "Overview of the Sampled Package." The chief difference between the two is that with a Clip you specify all the sound data at one time, before playback, whereas with a SourceDataLine you keep writing new buffers of data continuously during playback. Although there are many situations in which you could use either a Clip or a SourceDataLine, the following criteria help identify which kind of line is better suited for a particular situation:

  • Use a Clip when you have non-real-time sound data that can be preloaded into memory.

    For example, you might read a short sound file into a clip. If you want the sound to play back more than once, a Clip is more convenient than a SourceDataLine, especially if you want the playback to loop (cycle repeatedly through all or part of the sound). If you need to start the playback at an arbitrary position in the sound, the Clip interface provides a method to do that easily. Finally, playback from a Clip generally has less latency than buffered playback from a SourceDataLine. In other words, because the sound is preloaded into a clip, playback can start immediately instead of having to wait for the buffer to be filled.

  • Use a SourceDataLine for streaming data, such as a long sound file that won't all fit in memory at once, or a sound whose data can't be known in advance of playback.

    As an example of the latter case, suppose you're monitoring sound input—that is, playing sound back as it's being captured. If you don't have a mixer that can send input audio right back out an output port, your application program will have to take the captured data and send it to an audio-output mixer. In this case, a SourceDataLine is more appropriate than a Clip. Another example of sound that can't be known in advance occurs when you synthesize or manipulate the sound data interactively in response to the user's input. For example, imagine a game that gives aural feedback by "morphing" from one sound to another as the user moves the mouse. The dynamic nature of the sound transformation requires the application program to update the sound data continuously during playback, instead of supplying it all before playback starts.

Using a Clip

You obtain a Clip as described earlier under "Getting a Line of a Desired Type" in Chapter 3, "Accessing Audio System Resources": Construct a DataLine.Info object with Clip.class for the first argument, and pass this DataLine.Info as an argument to the getLine method of AudioSystem or Mixer.

Setting Up the Clip for Playback

Obtaining a line just means you've gotten a way to refer to it; getLine doesn't actually reserve the line for you. Because a mixer might have a limited number of lines of the desired type available, it can happen that after you invoke getLine to obtain the clip, another application program jumps in and grabs the clip before you're ready to start playback. To actually use the clip, you need to reserve it for your program's exclusive use by invoking one of the following Clip methods:

   void open(AudioInputStream stream)
   void open(AudioFormat format, byte[] data, int offset,
   int bufferSize)
Despite the bufferSize argument in the second open method above, Clip (unlike SourceDataLine) includes no methods for writing new data to the buffer. The bufferSize argument here just specifies how much of the byte array to load into the clip. It's not a buffer into which you can subsequently load more data, as you can with a SourceDataLine's buffer.

After opening the clip, you can specify at what point in the data it should start playback, using Clip's setFramePosition or setMicroSecondPosition methods. Otherwise, it will start at the beginning. You can also configure the playback to cycle repeatedly, using the setLoopPoints method.

Starting and Stopping Playback

When you're ready to start playback, simply invoke the start method. To stop or pause the clip, invoke the stop method, and to resume playback, invoke start again. The clip remembers the media position where it stopped playback, so there's no need for explicit pause and resume methods. If you don't want it to resume where it left off, you can "rewind" the clip to the beginning (or to any other position, for that matter) using the frame- or microsecond-positioning methods mentioned above.

A Clip's volume level and activity status (active versus inactive) can be monitored by invoking the DataLine methods getLevel and isActive, respectively. An active Clip is one that is currently playing sound.

Using a SourceDataLine

Obtaining a SourceDataLine is similar to obtaining a Clip. See "Getting a Line of a Desired Type" in Chapter 3, "Accessing Audio System Resources."

Setting Up the SourceDataLine for Playback

Opening the SourceDataLine is also similar to opening a Clip, in that the purpose is once again to reserve the line. However, you use a different method, inherited from DataLine:

    void open(AudioFormat format)
Notice that when you open a SourceDataLine, you don't associate any sound data with the line yet, unlike opening a Clip. Instead, you just specify the format of the audio data you want to play. The system chooses a default buffer length.

You can also stipulate a certain buffer length in bytes, using this variant:

    void open(AudioFormat format, int bufferSize)
For consistency with similar methods, the buffersize argument is expressed in bytes, but it must correspond to an integral number of frames.

How would you select a buffer size? It depends on your program's needs.

To start with, shorter buffer sizes mean less latency. When you send new data, you hear it sooner. For some application programs, particularly highly interactive ones, this kind of responsiveness is important. For example, in a game, the onset of playback might need to be tightly synchronized with a visual event. Such programs might need a latency of less than 0.1 second. As another example, a conferencing application needs to avoid delays in both playback and capture. However, many application programs can afford a greater delay, up to a second or more, because it doesn't matter exactly when the sound starts playing, as long as the delay doesn't confuse or annoy the user. This might be the case for an application program that streams a large audio file using one-second buffers. The user probably won't care if playback takes a second to start, because the sound itself lasts so long and the experience isn't highly interactive.

On the other hand, shorter buffer sizes also mean a greater risk that you'll fail to write data fast enough into the buffer. If that happens, the audio data will contain discontinuities, which will probably be audible as clicks or breakups in the sound. Shorter buffer sizes also mean that your program has to work harder to keep the buffers filled, resulting in more intensive CPU usage. This can slow down the execution of other threads in your program, not to mention other programs.

So an optimal value for the buffer size is one that minimizes latency just to the degree that's acceptable for your application program, while keeping it large enough to reduce the risk of buffer underflow and to avoid unnecessary consumption of CPU resources. For a program like a conferencing application, delays are more annoying than low-fidelity sound, so a small buffer size is preferable. For streaming music, an initial delay is acceptable, but breakups in the sound are not. Thus for streaming music a larger buffer size—say, a second—is preferable. (Note that high sample rates make the buffers larger in terms of the number of bytes, which are the units for measuring buffer size in the DataLine API.)

Instead of using the open method described above, it's also possible to open a SourceDataLine using Line's open() method, without arguments. In this case, the line is opened with its default audio format and buffer size. However, you can't change these later. If you want to know the line's default audio format and buffer size, you can invoke DataLine's getFormat and getBufferSize methods, even before the line has ever been opened.

Starting and Stopping Playback

Once the SourceDataLine is open, you can start playing sound. You do this by invoking DataLine's start method, and then writing data repeatedly to the line's playback buffer.

The start method permits the line to begin playing sound as soon as there's any data in its buffer. You place data in the buffer by the following method:

    int write(byte[] b, int offset, int length)
The offset into the array is expressed in bytes, as is the array's length.

The line begins sending data as soon as possible to its mixer. When the mixer itself delivers the data to its target, the SourceDataLine generates a START event. (In a typical implementation of the Java Sound API, the delay between the moment that the source line delivers data to the mixer and the moment that the mixer delivers the data to its target is negligible—that is, much less than the time of one sample.) This START event gets sent to the line's listeners, as explained below under "Monitoring a Line's Status." The line is now considered active, so the isActive method of DataLine will return true. Notice that all this happens only once the buffer contains data to play, not necessarily right when the start method is invoked. If you invoked start on a new SourceDataLine but never wrote data to the buffer, the line would never be active and a START event would never be sent. (However, in this case, the isRunning method of DataLine would return true.)

So how do you know how much data to write to the buffer, and when to send the second batch of data? Fortunately, you don't need to time the second invocation of write to synchronize with the end of the first buffer! Instead, you can take advantage of the write method's blocking behavior:

  • The method returns as soon as the data has been written to the buffer. It doesn't wait until all the data in the buffer has finished playing. (If it did, you might not have time to write the next buffer without creating a discontinuity in the audio.)
  • It's all right to try to write more data than the buffer will hold. In this case, the method blocks (doesn't return) until all the data you requested has actually been placed in the buffer. In other words, one buffer's worth of your data at a time will be written to the buffer and played, until the remaining data all fits in the buffer, at which point the method returns. Whether or not the method blocks, it returns as soon as the last buffer's worth of data from this invocation can be written. Again, this means that your code will in all likelihood regain control before playback of the last buffer's worth of data has finished.
  • While in many contexts it is fine to write more data than the buffer will hold, if you want to be certain that the next write issued does not block, you can limit the number of bytes you write to the number that DataLine's available method returns.

Here's an example of iterating through chunks of data that are read from a stream, writing one chunk at a time to the SourceDataLine for playback:
// read chunks from a stream and write them to a source data
line
line.start();
while (total < totalToRead && !stopped)}
    numBytesRead = stream.read(myData, 0, numBytesToRead);
    if (numBytesRead == -1) break;
    total += numBytesRead;
    line.write(myData, 0, numBytesRead);

}
If you don't want the write method to block, you can first invoke the available method (inside the loop) to find out how many bytes can be written without blocking, and then limit the numBytesToRead variable to this number, before reading from the stream. In the example given, though, blocking won't matter much, since the write method is invoked inside a loop that won't complete until the last buffer is written in the final loop iteration. Whether or not you use the blocking technique, you'll probably want to invoke this playback loop in a separate thread from the rest of the application program, so that your program doesn't appear to freeze when playing a long sound. On each iteration of the loop, you can test whether the user has requested playback to stop. Such a request needs to set the stopped boolean, used in the code above, to true.

Since write returns before all the data has finished playing, how do you learn when the playback has actually completed? One way is to invoke the drain method of DataLine after writing the last buffer's worth of data. This method blocks until all the data has been played. When control returns to your program, you can free up the line, if desired, without fear of prematurely cutting off the playback of any audio samples:

line.write(b, offset, numBytesToWrite);
//this is the final invocation of write
line.drain();
line.stop();
line.close();
line = null;
You can intentionally stop playback prematurely, of course. For example, the application program might provide the user with a Stop button. Invoke DataLine's stop method to stop playback immediately, even in the middle of a buffer. This leaves any unplayed data in the buffer, so that if you subsequently invoke start, the playback resumes where it left off. If that's not what you want to happen, you can discard the data left in the buffer by invoking flush.

A SourceDataLine generates a STOP event whenever the flow of data has been stopped, whether this stoppage was initiated by the drain method, the stop method, or the flush method, or because the end of a playback buffer was reached before the application program invoked write again to provide new data. A STOP event doesn't necessarily mean that the stop method was invoked, and it doesn't necessarily mean that a subsequent invocation of isRunning will return false. It does, however, mean that isActive will return false. (When the start method has been invoked, the isRunning method will return true, even if a STOP event is generated, and it will begin to return false only once the stop method is invoked.) It's important to realize that START and STOP events correspond to isActive, not to isRunning.

Monitoring a Line's Status

Once you have started a sound playing, how do you find when it's finished? We saw one solution above—invoking the drain method after writing the last buffer of data—but that approach is applicable only to a SourceDataLine. Another approach, which works for both SourceDataLines and Clips, is to register to receive notifications from the line whenever the line changes its state. These notifications are generated in the form of LineEvent objects, of which there are four types: OPEN, CLOSE, START, and STOP.

Any object in your program that implements the LineListener interface can register to receive such notifications. To implement the LineListener interface, the object simply needs an update method that takes a LineEvent argument. To register this object as one of the line's listeners, you invoke the following Line method:

public void addLineListener(LineListener listener)

Whenever the line opens, closes, starts, or stops, it sends an update message to all its listeners. Your object can query the LineEvent that it receives. First you might invoke LineEvent.getLine to make sure the line that stopped is the one you care about. In the case we're discussing here, you want to know if the sound is finished, so you see whether the LineEvent is of type STOP. If it is, you might check the sound's current position, which is also stored in the LineEvent object, and compare it to the sound's length (if known) to see whether it reached the end and wasn't stopped by some other means (such as the user's clicking a Stop button, although you'd probably be able to determine that cause elsewhere in your code).

Along the same lines, if you need to know when the line is opened, closed, or started, you use the same mechanism. LineEvents are generated by different kinds of lines, not just Clips and SourceDataLines. However, in the case of a Port you can't count on getting an event to learn about a line's open or closed state. For example, a Port might be initially open when it's created, so you don't invoke the open method and the Port doesn't ever generate an OPEN event. (See "Selecting Input and Output Ports" in Chapter 3, "Accessing Audio System Resources.")

Synchronizing Playback on Multiple Lines

If you're playing back multiple tracks of audio simultaneously, you probably want to have them all start and stop at exactly the same time. Some mixers facilitate this behavior with their synchronize method, which lets you apply operations such as open, close, start, and stop to a group of data lines using a single command, instead of having to control each line individually. Furthermore, the degree of accuracy with which operations are applied to the lines is controllable.

To find out whether a particular mixer offers this feature for a specified group of data lines, invoke the Mixer interface's isSynchronizationSupported method:

boolean isSynchronizationSupported(Line[] lines,
  boolean  maintainSync)
The first parameter specifies a group of specific data lines, and the second parameter indicates the accuracy with which synchronization must be maintained. If the second parameter is true, the query is asking whether the mixer is capable of maintaining sample-accurate precision in controlling the specified lines at all times; otherwise, precise synchronization is required only during start and stop operations, not throughout playback.

Processing the Outgoing Audio

Some source data lines have signal-processing controls, such as gain, pan, reverb, and sample-rate controls. Similar controls, especially gain controls, might be present on the output ports as well. For more information on how to determine whether a line has such controls, and how to use them if it does, see Chapter 6, "Processing Audio with Controls."

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Chapter 5: Capturing Audio

Capturing refers to the process of obtaining a signal from outside the computer. A common application of audio capture is recording, such as recording the microphone input to a sound file. However, capturing isn't synonymous with recording, because recording implies that the application always saves the sound data that's coming in. An application that captures audio doesn't necessarily store the audio. Instead it might do something with the data as it's coming in—such as transcribe speech into text—but then discard each buffer of audio as soon as it's finished with that buffer.

As discussed in Chapter 2, "Overview of the Sampled Package," a typical audio-input system in an implementation of the Java Sound API consists of:

  1. An input port, such as a microphone port or a line-in port, which feeds its incoming audio data into:
  2. A mixer, which places the input data in:
  3. One or more target data lines, from which an application can retrieve the data.

    Commonly, only one input port can be open at a time, but an audio-input mixer that mixes audio from multiple ports is also possible. Another scenario consists of a mixer that has no ports but instead gets its audio input over a network.

    The TargetDataLine interface was introduced briefly under "The Line Interface Hierarchy" in Chapter 2, "Overview of the Sampled Package." TargetDataLine is directly analogous to the SourceDataLine interface, which was discussed extensively in Chapter 4, "Playing Back Audio." Recall that the SourceDataLine interface consists of:

  • A write method to send audio to the mixer
  • An available method to determine how much data can be written to the buffer without blocking

Similarly, TargetDataLine consists of:
  • A read method to get audio from the mixer
  • An available method to determine how much data can be read from the buffer without blocking

Setting Up a TargetDataLine

The process of obtaining a target data line was described in Chapter 3, "Accessing Audio System Resources," but we repeat it here for convenience:

TargetDataLine line;
DataLine.Info info = new DataLine.Info(TargetDataLine.class,
    format); // format is an AudioFormat object
if (!AudioSystem.isLineSupported(info)) {
    // Handle the error ...
}
// Obtain and open the line.
try {
    line = (TargetDataLine) AudioSystem.getLine(info);
    line.open(format);
} catch (LineUnavailableException ex) {
    // Handle the error ...
}
You could instead invoke Mixer's getLine method, rather than AudioSystem's.

As shown in this example, once you've obtained a target data line, you reserve it for your application's use by invoking the DataLine method open, exactly as was described in the case of a source data line in Chapter 4, "Playing Back Audio." The single-parameter version of the open method causes the line's buffer to have the default size. You can instead set the buffer size according to your application's needs by invoking the two-parameter version:

    void open(AudioFormat format, int bufferSize)
When choosing a buffer size, keep in mind the tradeoff between the delays incurred by long buffers, on the one hand, and the risk of discontinuities in the audio if the buffers are so short that you can't retrieve the data fast enough, on the other hand. When capturing audio, you risk data overflow if you don't pull data from the filled buffers fast enough. If overflow occurs, some of the captured data will be discarded, which will probably cause audible clicks and skips in the sound. This is the opposite situation from playback, where you risk data underflow, which can result in gaps in the sound. (See Chapter 4, "Playing Back Audio," for more on choosing buffer sizes.)

Reading the Data from the TargetDataLine

Once the line is open, it is ready to start capturing data, but it isn't active yet. To actually commence the audio capture, use the DataLine method start. This begins delivering input audio data to the line's buffer for your application to read. Your application should invoke start only when it's ready to begin reading from the line; otherwise a lot of processing is wasted on filling the capture buffer, only to have it overflow (that is, discard data).

To start retrieving data from the buffer, invoke TargetDataLine's read method:

int read(byte[] b, int offset, int length)
This method attempts to read length bytes of data into the array b, starting at the byte position offset in the array. The method returns the number of bytes actually read.

As with SourceDataLine's write method, you can request more data than actually fits in the buffer, because the method blocks until the requested amount of data has been delivered, even if you request many buffers' worth of data.

To avoid having your application hang during recording, you can invoke the read method within a loop, until you've retrieved all the audio input, as in this example:

// Assume that the TargetDataLine, line, has already
// been obtained and opened.
ByteArrayOutputStream out  = new ByteArrayOutputStream();
int numBytesRead;
byte[] data = new byte[line.getBufferSize() / 5];

// Begin audio capture.
line.start();

// Here, stopped is a global boolean set by another thread.
while (!stopped) {
   // Read the next chunk of data from the TargetDataLine.
   numBytesRead =  line.read(data, 0, data.length);
   // Save this chunk of data.
   out.write(data, 0, numBytesRead);
}
Notice that in this example, the size of the byte array into which the data is read is set to be one-fifth the size of the line's buffer. If you instead make it as big as the line's buffer and try to read the entire buffer, you need to be very exact in your timing, because data will be dumped if the mixer needs to deliver data to the line while you are reading from it. By using some fraction of the line's buffer size, as shown here, your application will be more successful in sharing access to the line's buffer with the mixer.

The read method of TargetDataLine takes three arguments: a byte array, an offset into the array, and the number of bytes of input data that you would like to read. In this example, the third argument is simply the length of your byte array. The read method returns the number of bytes that were actually read into your array.

Typically, you read data from the line in a loop, as in this example. Within the while loop, each chunk of retrieved data is processed in whatever way is appropriate for the application—here, it's written to a ByteArrayOutputStream. Not shown here is the use of a separate thread to set the boolean stopped, which terminates the loop. This boolean's value might be set to true when the user clicks a Stop button, and also when a listener receives a CLOSE or STOP event from the line. The listener is necessary for CLOSE events and recommended for STOP events. Otherwise, if the line gets stopped somehow without stopped being set to true, the while loop will capture zero bytes on each iteration, running fast and wasting CPU cycles. A more thorough code example would show the loop being re-entered if capture becomes active again.

As with a source data line, it's possible to drain or flush a target data line. For example, if you're recording the input to a file, you'll probably want to invoke the drain method when the user clicks a Stop button. The drain method will cause the mixer's remaining data to get delivered to the target data line's buffer. If you don't drain the data, the captured sound might seem to be truncated prematurely at the end.

There might be some cases where you instead want to flush the data. In any case, if you neither flush nor drain the data, it will be left in the mixer. This means that when capture recommences, there will be some leftover sound at the beginning of the new recording, which might be undesirable. It can be useful, then, to flush the target data line before restarting the capture.

Monitoring the Line's Status

Because the TargetDataLine interface extends DataLine, target data lines generate events in the same way source data lines do. You can register an object to receive events whenever the target data line opens, closes, starts, or stops. For more information, see "Monitoring the Line's Status" in Chapter 4, "Playing Back Audio."

Processing the Incoming Audio

Like some source data lines, some mixers' target data lines have signal-processing controls, such as gain, pan, reverb, or sample-rate controls. The input ports might have similar controls, especially gain controls. For more information on how to determine whether a line has such controls, and how to use them if it does, see Chapter 6, "Processing Audio with Controls."

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Chapter 6: Processing Audio with Controls

Previous chapters have discussed how to play or capture audio samples. The implicit goal has been to deliver samples as faithfully as possible, without modification (other than possibly mixing the samples with those from other audio lines). Sometimes, however, you want to be able to modify the signal. The user might want it to sound louder, quieter, fuller, more reverberant, higher or lower in pitch, and so on. This chapter discusses the Java Sound API features that provide these kinds of signal processing.

There are two ways to apply signal processing:

  • You can use any processing supported by the mixer or its component lines, by querying for Control objects and then setting the controls as the user desires. Typical controls supported by mixers and lines include gain, pan, and reverberation controls.
  • If the kind of processing you need isn't provided by the mixer or its lines, your program can operate directly on the audio bytes, manipulating them as desired.

This chapter discusses the first technique in greater detail, because there is no special API for the second technique.

Introduction to Controls

A mixer can have various sorts of signal-processing controls on some or all of its lines. For example, a mixer used for audio capture might have an input port with a gain control, and target data lines with gain and pan controls. A mixer used for audio playback might have sample-rate controls on its source data lines. In each case, the controls are all accessed through methods of the Line interface.

Because the Mixer interface extends Line, the mixer itself can have its own set of controls. These might serve as master controls affecting all the mixer's source or target lines. For example, the mixer might have a master gain control whose value in decibels is added to the values of individual gain controls on its target lines.

Others of the mixer's own controls might affect a special line, neither a source nor a target, that the mixer uses internally for its processing. For example, a global reverb control might choose the sort of reverberation to apply to a mixture of the input signals, and this "wet" (reverberated) signal would get mixed back into the "dry" signal before delivery to the mixer's target lines.

If the mixer or any of its lines have controls, you might wish to expose the controls via graphical objects in your program's user interface, so that the user can adjust the audio characteristics as desired. The controls are not themselves graphical; they just allow you to retrieve and change their settings. It's up to you to decide what sort of graphical representations (sliders, buttons, etc.), if any, to use in your program.

All controls are implemented as concrete subclasses of the abstract class Control. Many typical audio-processing controls can be described by abstract subclasses of Control based on a data type (such as boolean, enumerated, or float). Boolean controls, for example, represent binary-state controls, such as on/off controls for mute or reverb. Float controls, on the other hand, are well suited to represent continuously variable controls, such as pan, balance, or volume.

The Java Sound API specifies the following abstract subclasses of Control:

  • BooleanControl—represents a binary-state (true or false) control. For example, mute, solo, and on/off switches would be good candidates for BooleanControls.
  • FloatControl—data model providing control over a range of floating-point values. For example, volume and pan are FloatControls that could be manipulated via a dial or slider.
  • EnumControl—offers a choice from a set of objects. For example, you might associate a set of buttons in the user interface with an EnumControl to select one of several preset reverberation settings.
  • CompoundControl—provides access to a collection of related items, each of which is itself an instance of a Control subclass. CompoundControls represent multi-control modules such as graphic equalizers. (A graphic equalizer would typically be depicted by a set of sliders, each affecting a FloatControl.)

Each subclass of Control above has methods appropriate for its underlying data type. Most of the classes include methods that set and get the control's current value(s), get the control's label(s), and so on.

Of course, each class has methods that are particular to it and the data model represented by the class. For example, EnumControl has a method that lets you get the set of its possible values, and FloatControl permits you to get its minimum and maximum values, as well as the precision (increment or step size) of the control.

Each subclass of Control has a corresponding Control.Type subclass, which includes static instances that identify specific controls.

The following table shows each Control subclass, its corresponding Control.Type subclass, and the static instances that indicate specific kinds of controls:

Control | Control.Type | Control.Type instances
BooleanControl | BooleanControl.Type | MUTE Mute status of line APPLY_REVERB Reverberation on/off
CompoundControl | CompoundControl.Type | (none)
EnumControl | EnumControl.Type | REVERB Access to reverb settings (each is an instance of ReverbType)
FloatControl | FloatControl.Type | AUX_RETURN Auxiliary return gain on a line AUX_SEND Auxiliary send gain on a line BALANCE Left-right volume balance MASTER_GAIN Overall gain on a line PAN Left-right position REVERB_RETURN Post-reverb gain on a line REVERB_SEND Pre-reverb gain on a line SAMPLE_RATE Playback sample rate VOLUME Volume on a line

An implementation of the Java Sound API can provide any or all of these control types on its mixers and lines. It can also supply additional control types not defined in the Java Sound API. Such control types could be implemented via concrete subclasses of any of these four abstract subclasses, or via additional Control subclasses that don't inherit from any of these four abstract subclasses. An application program can query each line to find what controls it supports.

Getting a Line that Has the Desired Controls

In many cases, an application program will simply display whatever controls happen to be supported by the line in question. If the line doesn't have any controls, so be it. But what if it's important to find a line that has certain controls? In that case, you can use a Line.Info to obtain a line that has the right characteristics, as described under "Getting a Line of a Desired Type" in Chapter 3, "Accessing Audio System Resources."

For example, suppose you prefer an input port that lets the user set the volume of the sound input. The following code excerpt shows how one might query the default mixer to determine whether it has the desired port and control:

Port lineIn;
FloatControl volCtrl;
try {
  mixer = AudioSystem.getMixer(null);
  lineIn = (Port)mixer.getLine(Port.Info.LINE_IN);
  lineIn.open();
  volCtrl = (FloatControl) lineIn.getControl(
      FloatControl.Type.VOLUME);
  // Assuming getControl call succeeds,
  // we now have our LINE_IN VOLUME control.
} catch (Exception e) {
  System.out.println("Failed trying to find LINE_IN"
    + " VOLUME control: exception = " + e);
}
if (volCtrl != null)
  // ...

Getting the Controls from the Line

An application program that needs to expose controls in its user interface might simply query the available lines and controls, and then display an appropriate user-interface element for every control on every line of interest. In such a case, the program's only mission is to provide the user with "handles" on the control; not to know what those controls do to the audio signal. As long as the program knows how to map a line's controls into user-interface elements, the Java Sound API architecture of Mixer, Line, and Control will generally take care of the rest.

For example, suppose your program plays back sound. You're using a SourceDataLine, which you've obtained as described under "Getting a Line of a Desired Type" in Chapter 3, "Accessing Audio System Resources." You can access the line's controls by invoking the Line method:

Control[] getControls()
Then, for each of the controls in this returned array, you then use the following Control method to get the control's type:
Control.Type getType()
Knowing the specific Control.Type instance, your program can display a corresponding user-interface element. Of course, choosing "a corresponding user-interface element" for a specific Control.Type depends on the approach taken by your program. On the one hand, you might use the same kind of element to represent all Control.Type instances of the same class. This would require you to query the class of the Control.Type instance using, for example, the Object.getClass method. Let's say the result matched BooleanControl.Type. In this case, your program might display a generic checkbox or toggle button, but if its class matched FloatControl.Type, then you might display a graphic slider.

On the other hand, your program might distinguish between different types of controls—even those of the same class—and use a different user-interface element for each one. This would require you to test the instance returned by Control's getType method. Then if, for example, the type matched BooleanControl.Type.APPLY_REVERB, your program might display a checkbox; while if the type matched BooleanControl.Type.MUTE, you might instead display a toggle button.

Using a Control to Change the Audio Signal

Note

The current implementation requires that to change the value of a Control its corresponding Line must be open.

Now that you know how to access a control and determine its type, this section will describe how to use Controls to change aspects of the audio signal. This section doesn't cover every available control; rather, it provides a few examples in this area to show you how to get started. These example include:

  • Controlling a line's mute state
  • Changing a line's volume
  • Selecting among various reverberation presets

Suppose that your program has accessed all of its mixers, their lines and the controls on those lines, and that it has a data structure to manage the logical associations between the controls and their corresponding user-interface elements. Then, translating the user's manipulations of those controls into the corresponding Control methods becomes a fairly straightforward matter.

The following subsections describe some of the methods that must be invoked to affect the changes to specific controls.

Controlling a Line's Mute State

Controlling the mute state of any line is simply a matter of calling the following BooleanControl method:

void setValue(boolean value)
(Presumably, the program knows, by referring to its control-management data structures, that the mute is an instance of a BooleanControl.) To mute the signal that's passing through the line, the program invokes the method above, specifying true as the value. To turn muting off, permitting the signal to flow through the line, the program invokes the method with the parameter set to false.

Changing a Line's Volume

Let's assume your program associates a particular graphic slider with a particular line's volume control. The value of a volume control (i.e., FloatControl.Type.VOLUME) is set using the following FloatControl method:

void setValue(float newValue)
Detecting that the user moved the slider, the program gets the slider's current value and passes it, as the parameter newValue, to the method above. This changes the volume of the signal flowing though the line that "owns" the control.

Selecting among Various Reverberation Presets

Let's suppose that our program has a mixer with a line that has a control of type EnumControl.Type.REVERB. Calling the EnumControl method:

java.lang.Objects[] getValues()
on that control produces an array of ReverbType objects. If desired, the particular parameter settings of each of these objects can be accessed using the following ReverbType methods:
int getDecayTime()
int getEarlyReflectionDelay()
float getEarlyReflectionIntensity()
int getLateReflectionDelay()
float getLateReflectionIntensity()
For example, if a program only wants a single reverb setting that sounds like a cavern, it can iterate over the ReverbType objects until it finds one for which getDecayTime returns a value greater than 2000. For a thorough explanation of these methods, including a table of representative return values, see the API reference documentation for javax.sound.sampled.ReverbType.

Typically, though, a program will create a user-interface element, for example, a radio button, for each of the ReverbType objects within the array returned by the getValues method. When the user clicks on one of these radio buttons, the program invokes the EnumControl method

void setValue(java.lang.Object value)
where value is set to the ReverbType that corresponds to the newly engaged button. The audio signal sent through the line that "owns" this EnumControl will then be reverberated according to the parameter settings that constitute the control's current ReverbType (i.e., the particular ReverbType specified in the value argument of the setValue method).

So, from our application program's perspective, enabling a user to move from one reverberation preset (i.e., ReverbType) to another is simply a matter of connecting each element of the array returned by getValues to a distinct radio button.

Manipulating the Audio Data Directly

The Control API allows an implementation of the Java Sound API, or a third-party provider of a mixer, to supply arbitrary sorts of signal processing through controls. But what if no mixer offers the kind of signal processing you need? It will take more work, but you might be able to implement the signal processing in your program. Because the Java Sound API gives you access to the audio data as an array of bytes, you can alter these bytes in any way you choose.

If you're processing incoming sound, you can read the bytes from a TargetDataLine and then manipulate them. An algorithmically trivial example that can yield sonically intriguing results is to play a sound backwards by arranging its frames in reverse order. This trivial example may not be of much use for your program, but there are numerous sophisticated digital signal processing (DSP) techniques that might be more appropriate. Some examples are equalization, dynamic-range compression, peak limiting, and time stretching or compression, as well as special effects such as delay, chorus, flanging, distortion, and so on.

To play back processed sound, you can place your manipulated array of bytes into a SourceDataLine or Clip. Of course, the array of bytes need not be derived from an existing sound. You can synthesize sounds from scratch, although this requires some knowledge of acoustics or else access to sound-synthesis functions. For either processing or synthesis, you may want to consult an audio DSP textbook for the algorithms in which you're interested, or else import a third-party library of signal-processing functions into your program. For playback of synthesized sound, consider whether the Synthesizer API in the javax.sound.midi package meets your needs instead. (See Chapter 12, "Synthesizing Sound.")

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Chapter 7: Using Files and Format Converters

Most application programs that deal with sound need to read sound files or audio streams. This is common functionality, regardless of what the program may subsequently do with the data it reads (such as play, mix, or process it). Similarly, many programs need to write sound files (or streams). In some cases, the data that has been read (or that will be written) needs to be converted to a different format.

As was briefly mentioned in Chapter 3, "Accessing Audio System Resources," the Java Sound API provides application developers with various facilities for file input/output and format translations. Application programs can read, write, and translate between a variety of sound file formats and audio data formats.

Chapter 2, "Overview of the Sampled Package," introduced the main classes related to sound files and audio data formats. As a review:

  • A stream of audio data, as might be read from or written to a file, is represented by an AudioInputStream object. (AudioInputStream inherits from java.io.InputStream.)
  • The format of this audio data is represented by an AudioFormat object.

    This format specifies how the audio samples themselves are arranged, but not the structure of a file that they might be stored in. In other words, an AudioFormat describes "raw" audio data, such as the system might hand your program after capturing it from a microphone input or after parsing it from a sound file. An AudioFormat includes such information as the encoding, the byte order, the number of channels, the sampling rate, and the number of bits per sample.

  • There are several well-known, standard formats for sound files, such as WAV, AIFF, or AU. The different types of sound file have different structures for storing audio data as well as for storing descriptive information about the audio data. A sound file format is represented in the Java Sound API by an AudioFileFormat object. The AudioFileFormat includes an AudioFormat object to describe the format of the audio data stored in the file, and also includes information about the file type and the length of the data in the file.
  • The AudioSystem class provides methods for (1) storing a stream of audio data from an AudioInputStream into an audio file of a particular type (in other words, writing a file), (2) extracting a stream of audio bytes (an AudioInputStream) from an audio file (in other words, reading a file), and (3) converting audio data from one data format to another. The present chapter, which is divided into three sections, explains these three kinds of activity.

Note that an implementation of the Java Sound API does not necessarily provide comprehensive facilities for reading, writing, and converting audio in different data and file formats. It might support only the most common data and file formats. However, service providers can develop and distribute conversion services that extend this set, as outlined in Chapter 14, "Providing Sampled-Audio Services." The AudioSystem class supplies methods that allow application programs to learn what conversions are available, as described later in this chapter under "Converting File and Data Formats."

Reading Sound Files

The AudioSystem class provides two types of file-reading services:

  • Information about the format of the audio data stored in the sound file
  • A stream of formatted audio data that can be read from the sound file

The first of these is given by three variants of the getAudioFileFormat method:

static AudioFileFormat getAudioFileFormat (java.io.File file)
static AudioFileFormat getAudioFileFormat(java.io.InputStream stream)
static AudioFileFormat getAudioFileFormat (java.net.URL url)

As mentioned above, the returned AudioFileFormat object tells you the file type, the length of the data in the file, encoding, the byte order, the number of channels, the sampling rate, and the number of bits per sample.

The second type of file-reading functionality is given by these AudioSystem methods

static AudioInputStream getAudioInputStream (java.io.File file)
static AudioInputStream getAudioInputStream (java.net.URL url)
static AudioInputStream getAudioInputStream (java.io.InputStream stream)

These methods give you an object (an AudioInputStream) that lets you read the file's audio data, using one of the read methods of AudioInputStream. We'll see an example momentarily.

Suppose you're writing a sound-editing application that allows the user to load sound data from a file, display a corresponding waveform or spectrogram, edit the sound, play back the edited data, and save the result in a new file. Or perhaps your program will read the data stored in a file, apply some kind of signal processing (such as an algorithm that slows the sound down without changing its pitch), and then play the processed audio. In either case, you need to get access to the data contained in the audio file. Assuming that your program provides some means for the user to select or specify an input sound file, reading that file's audio data involves three steps:

  2. Get an AudioInputStream object from the file.
  3. Create a byte array in which you'll store successive chunks of data from the file.
  4. Repeatedly read bytes from the audio input stream into the array. On each iteration, do something useful with the bytes in the array (for example, you might play them, filter them, analyze them, display them, or write them to another file).

The following code example outlines these steps.
int totalFramesRead = 0;
File fileIn = new File(somePathName);
// somePathName is a pre-existing string whose value was
// based on a user selection.
try {
  AudioInputStream audioInputStream =
    AudioSystem.getAudioInputStream(fileIn);
  int bytesPerFrame =
    audioInputStream.getFormat().getFrameSize();
  // Set an arbitrary buffer size of 1024 frames.
  int numBytes = 1024 * bytesPerFrame;
  byte[] audioBytes = new byte[numBytes];
  try {
    int numBytesRead = 0;
    int numFramesRead = 0;
    // Try to read numBytes bytes from the file.
    while ((numBytesRead =
      audioInputStream.read(audioBytes)) != -1) {
      // Calculate the number of frames actually read.
      numFramesRead = numBytesRead / bytesPerFrame;
      totalFramesRead += numFramesRead;
      // Here, do something useful with the audio data that's
      // now in the audioBytes array...
    }
  } catch (Exception ex) {
    // Handle the error...
  }
} catch (Exception e) {
  // Handle the error...
}
Let's take a look at what's happening in the above code sample. First, the outer try clause instantiates an AudioInputStream object through the call to the AudioSystem.getAudioInputStream(File) method. This method transparently performs all of the testing required to determine whether the specified file is actually a sound file of a type that is supported by the Java Sound API. If the file being inspected (fileIn in this example) is not a sound file, or is a sound file of some unsupported type, an UnsupportedAudioFileException exception is thrown. This behavior is convenient, in that the application programmer need not be bothered with testing file attributes, nor with adhering to any file-naming conventions. Instead, the getAudioInputStream method takes care of all the low-level parsing and verification that is required to validate the input file.

The outer try clause then creates a byte array, audioBytes, of an arbitrary fixed length. We make sure that its length in bytes equals an integral number of frames, so that we won't end up reading only part of a frame or, even worse, only part of a sample. This byte array will serve as a buffer to temporarily hold a chunk of audio data as it's read from the stream. If we knew we would be reading nothing but very short sound files, we could make this array the same length as the data in the file, by deriving the length in bytes from the length in frames, as returned by AudioInputStream's getFrameLength method. (Actually, we'd probably just use a Clip object instead.) But to avoid running out of memory in the general case, we instead read the file in chunks, one buffer at a time.

The inner try clause contains a while loop, which is where we read the audio data from the AudioInputStream into the byte array. You should add code in this loop to handle the audio data in this array in whatever way is appropriate for your program's needs. If you're applying some kind of signal processing to the data, you'll probably need to query the AudioInputStream's AudioFormat further, to learn the number of bits per sample and so on.

Note that the method AudioInputStream.read(byte[]) returns the number of bytes read—not the number of samples or frames. This method returns -1 when there's no more data to read. Upon detecting this condition, we break from the while loop.

Writing Sound Files

The previous section described the basics of reading a sound file, using specific methods of the AudioSystem and AudioInputStream classes. This section describes how to write audio data out to a new file.

The following AudioSystem method creates a disk file of a specified file type. The file will contain the audio data that's in the specified AudioInputStream:

static int write(AudioInputStream in,
  AudioFileFormat.Type fileType, File out)
Note that the second argument must be one of the file types supported by the system (for example, AU, AIFF, or WAV), otherwise the write method will throw an IllegalArgumentException. To avoid this, you can test whether or not a particular AudioInputStream may be written to a particular type of file, by invoking this AudioSystem method:
static boolean isFileTypeSupported
  (AudioFileFormat.Type fileType, AudioInputStream stream)
which will return true only if the particular combination is supported.

More generally, you can learn what types of file the system can write by invoking one of these AudioSystem methods:

static AudioFileFormat.Type[] getAudioFileTypes()
static AudioFileFormat.Type[]
  getAudioFileTypes(AudioInputStream stream)
The first of these returns all the types of file that the system can write, and the second returns only those that the system can write from the given audio input stream.

The following excerpt demonstrates one technique for creating an output file from an AudioInputStream using the write method mentioned above.

File fileOut = new File(someNewPathName);
AudioFileFormat.Type fileType = fileFormat.getType();
if (AudioSystem.isFileTypeSupported(fileType,
    audioInputStream)) {
  AudioSystem.write(audioInputStream, fileType, fileOut);
}
The first statement above, creates a new File object, fileOut, with a user- or program-specified pathname. The second statement gets a file type from a pre-existing AudioFileFormat object called fileFormat, which might have been obtained from another sound file, such as the one that was read in the "Reading Sound Files" section of this chapter. (You could instead supply whatever supported file type you want, instead of getting the file type from elsewhere. For example, you might delete the second statement and replace the other two occurrences of fileType in the code above with AudioFileFormat.Type.WAVE.)

The third statement tests whether a file of the designated type can be written from a desired AudioInputStream. Like the file format, this stream might have been derived from the sound file previously read. (If so, presumably you've processed or altered its data in some way, because otherwise there are easier ways to simply copy a file.) Or perhaps the stream contains bytes that have been freshly captured from the microphone input.

Finally, the stream, file type, and output file are passed to the AudioSystem.write method, to accomplish the goal of writing the file.

Converting File and Data Formats

Recall from the section "What Is Formatted Audio Data?" in Chapter 2, "Overview of the Sampled Package," that the Java Sound API distinguishes between audio file formats and audio data formats. The two are more or less independent. Roughly speaking, the data format refers to the way in which the computer represents each raw data point (sample), while the file format refers to the organization of a sound file as stored on a disk. Each sound file format has a particular structure that defines, for example, the information stored in the file's header. In some cases, the file format also includes structures that contain some form of meta-data, in addition to the actual "raw" audio samples. The remainder of this chapter examines methods of the Java Sound API that enable a variety of file-format and data-format conversions.

Converting from One File Format to Another

This section covers the fundamentals of converting audio file types in the Java Sound API. Once again we pose a hypothetical program whose purpose, this time, is to read audio data from an arbitrary input file and write it into a file whose type is AIFF. Of course, the input file must be of a type that the system is capable of reading, and the output file must be of a type that the system is capable of writing. (In this example, we assume that the system is capable of writing AIFF files.) The example program doesn't do any data format conversion. If the input file's data format can't be represented as an AIFF file, the program simply notifies the user of that problem. On the other hand, if the input sound file is an already an AIFF file, the program notifies the user that there is no need to convert it.

The following function implements the logic just described:

public void ConvertFileToAIFF(String inputPath,
  String outputPath) {
  AudioFileFormat inFileFormat;
  File inFile;
  File outFile;
  try {
    inFile = new File(inputPath);
    outFile = new File(outputPath);
  } catch (NullPointerException ex) {
    System.out.println("Error: one of the
      ConvertFileToAIFF" +" parameters is null!");
    return;
  }
  try {
    // query file type
    inFileFormat = AudioSystem.getAudioFileFormat(inFile);
    if (inFileFormat.getType() != AudioFileFormat.Type.AIFF)
    {
      // inFile is not AIFF, so let's try to convert it.
      AudioInputStream inFileAIS =
        AudioSystem.getAudioInputStream(inFile);
      inFileAIS.reset(); // rewind
      if (AudioSystem.isFileTypeSupported(
             AudioFileFormat.Type.AIFF, inFileAIS)) {
         // inFileAIS can be converted to AIFF.
         // so write the AudioInputStream to the
         // output file.
         AudioSystem.write(inFileAIS,
           AudioFileFormat.Type.AIFF, outFile);
         System.out.println("Successfully made AIFF file, "
           + outFile.getPath() + ", from "
           + inFileFormat.getType() + " file, " +
           inFile.getPath() + ".");
         inFileAIS.close();
         return; // All done now
       } else
         System.out.println("Warning: AIFF conversion of "
           + inFile.getPath()
           + " is not currently supported by AudioSystem.");
    } else
      System.out.println("Input file " + inFile.getPath() +
          " is AIFF." + " Conversion is unnecessary.");
  } catch (UnsupportedAudioFileException e) {
    System.out.println("Error: " + inFile.getPath()
        + " is not a supported audio file type!");
    return;
  } catch (IOException e) {
    System.out.println("Error: failure attempting to read "
      + inFile.getPath() + "!");
    return;
  }
}

As mentioned, the purpose of this example function, ConvertFileToAIFF, is to query an input file to determine whether it's an AIFF sound file, and if it isn't, to try to convert it to one, producing a new copy whose pathname is specified by the second argument. (As an exercise, you might try making this function more general, so that instead of always converting to AIFF, the function converts to the file type specified by a new function argument.) Note that the audio data format of the copy—that is, the new file-mimics the audio data format of original input file.

Most of this function is self-explanatory and is not specific to the Java Sound API. There are, however, a few Java Sound API methods used by the routine that are crucial for sound file-type conversions. These method invocations are all found in the second try clause, above, and include the following:

  • AudioSystem.getAudioFileFormat: used here to determine whether the input file is already an AIFF type. If so, the function quickly returns; otherwise the conversion attempt proceeds.
  • AudioSystem.isFileTypeSupported: Indicates whether the system can write a file of the specified type that contains audio data from the specified AudioInputStream. In our example, this method returns true if the specified audio input file can be converted to AIFF audio file format. If AudioFileFormat.Type.AIFF isn't supported, ConvertFileToAIFF issues a warning that the input file can't be converted, then returns.
  • AudioSystem.write: used here to write the audio data from the AudioInputStream inFileAIS to the output file outFile.

The second of these methods, isFileTypeSupported, helps to determine, in advance of the write, whether a particular input sound file can be converted to a particular output sound file type. In the next section we will see how, with a few modifications to this ConvertFileToAIFF sample routine, we can convert the audio data format, as well as the sound file type.

Converting Audio between Different Data Formats

The previous section showed how to use the Java Sound API to convert a file from one file format (that is, one type of sound file) to another. This section explores some of the methods that enable audio data format conversions.

In the previous section, we read data from a file of an arbitrary type, and saved it in an AIFF file. Note that although we changed the type of file used to store the data, we didn't change the format of the audio data itself. (Most common audio file types, including AIFF, can contain audio data of various formats.) So if the original file contained CD-quality audio data (16-bit sample size, 44.1-kHz sample rate, and two channels), so would our output AIFF file.

Now suppose that we want to specify the data format of the output file, as well as the file type. For example, perhaps we are saving many long files for use on the Internet, and are concerned about the amount of disk space and download time required by our files. We might choose to create smaller AIFF files that contain lower-resolution data-for example, data that has an 8-bit sample size, an 8-kHz sample rate, and a single channel.

Without going into as much coding detail as before, let's explore some of the methods used for data format conversion, and consider the modifications that we would need to make to the ConvertFileToAIFF function to accomplish the new goal.

The principal method for audio data conversion is, once again, found in the AudioSystem class. This method is a variant of getAudioInputStream:

AudioInputStream getAudioInputStream(AudioFormat
    format, AudioInputStream stream)
This function returns an AudioInputStream that is the result of converting the AudioInputStream, stream, using the indicated AudioFormat, format. If the conversion isn't supported by AudioSystem, this function throws an IllegalArgumentException.

To avoid that, we can first check whether the system can perform the required conversion by invoking this AudioSystem method:

boolean isConversionSupported(AudioFormat targetFormat,
    AudioFormat sourceFormat)
In this case, we'd pass stream.getFormat() as the second argument.

To create a specific AudioFormat object, we use one of the two AudioFormat constructors shown below, either

 AudioFormat(float sampleRate, int sampleSizeInBits,
    int channels, boolean signed, boolean bigEndian)
which constructs an AudioFormat with a linear PCM encoding and the given parameters, or
AudioFormat(AudioFormat.Encoding encoding,
    float sampleRate, int sampleSizeInBits, int channels,
    int frameSize, float frameRate, boolean bigEndian)
which also constructs an AudioFormat, but lets you specify the encoding, frame size, and frame rate, in addition to the other parameters.

Now, armed with the methods above, let's see how we might extend our ConvertFileToAIFF function to perform the desired "low-res" audio data format conversion. First, we would construct an AudioFormat object describing the desired output audio data format. The following statement would suffice and could be inserted near the top of the function:

AudioFormat outDataFormat = new AudioFormat((float) 8000.0,
(int) 8, (int) 1, true, false);
Since the AudioFormat constructor above is describing a format with 8-bit samples, the last parameter to the constructor, which specifies whether the samples are big or little endian, is irrelevant. (Big versus little endian is only an issue if the sample size is greater than a single byte.)

The following example shows how we would use this new AudioFormat to convert the AudioInputStream, inFileAIS, that we created from the input file:

AudioInputStream lowResAIS;
  if (AudioSystem.isConversionSupported(outDataFormat,
    inFileAIS.getFormat())) {
    lowResAIS = AudioSystem.getAudioInputStream
      (outDataFormat, inFileAIS);
  }
It wouldn't matter too much where we inserted this code, as long as it was after the construction of inFileAIS. Without the isConversionSupported test, the call would fail and throw an IllegalArgumentException if the particular conversion being requested was unsupported. (In this case, control would transfer to the appropriate catch clause in our function.)

So by this point in the process, we would have produced a new AudioInputStream, resulting from the conversion of the original input file (in its AudioInputStream form) to the desired low-resolution audio data format as defined by outDataFormat.

The final step to produce the desired low-resolution, AIFF sound file would be to replace the AudioInputStream parameter in the call to AudioSystem.write (that is, the first parameter) with our converted stream, lowResAIS, as follows:

AudioSystem.write(lowResAIS, AudioFileFormat.Type.AIFF,
  outFile);
These few modifications to our earlier function produce something that converts both the audio data and the file format of any specified input file, assuming of course that the system supports the conversion.

Learning What Conversions Are Available

Several AudioSystem methods test their parameters to determine whether the system supports a particular data format conversion or file-writing operation. (Typically, each method is paired with another that performs the data conversion or writes the file.) One of these query methods, AudioSystem.isFileTypeSupported, was used in our example function, ConvertFileToAIFF, to determine whether the system was capable of writing the audio data to an AIFF file. A related AudioSystem method, getAudioFileTypes(AudioInputStream), returns the complete list of supported file types for the given stream, as an array of AudioFileFormat.Type instances. The method:

boolean isConversionSupported(AudioFormat.Encoding encoding,
                              AudioFormat format)
is used to determine whether an audio input stream of the specified encoding can be obtained from an audio input stream that has the specified audio format. Similarly, the method:
boolean isConversionSupported(AudioFormat newFormat,
                              AudioFormat oldFormat)

tells us whether an AudioInputStream with the specified audio format, newFormat, can be obtained through the conversion of an AudioInputStream that has the audio format oldFormat. (This method was invoked in the previous section's code excerpt that created a low-resolution audio input stream, lowResAIS.)

These format-related queries help prevent errors when attempting to perform format conversions with the Java Sound API.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Chapter 8: Overview of the MIDI Package

Chapter 1,"Introduction to Java Sound," gave a glimpse into the MIDI capabilities of the Java Sound API. The present chapter assumes you've read Chapter 1. The discussion here provides a more detailed introduction to the Java Sound API's MIDI architecture, which is accessed through the javax.sound.midi package. Some basic features of MIDI itself are explained, as a refresher or introduction, to place the Java Sound API's MIDI features in context. The chapter then goes on to discuss the Java Sound API's approach to MIDI, as a preparation for the programming tasks that are explained in subsequent chapters. This chapter's discussion of the MIDI API is divided into two main areas: data and devices.

A MIDI Refresher: Wires and Files

The Musical Instrument Digital Interface (MIDI) standard defines a communication protocol for electronic music devices, such as electronic keyboard instruments and personal computers. MIDI data can be transmitted over special cables during a live performance, and can also be stored in a standard type of file for later playback or editing.

This section reviews some MIDI basics, without reference to the Java Sound API. The discussion is intended as a refresher for readers acquainted with MIDI, and as a brief introduction for those who are not, to provide background for the subsequent discussion of the Java Sound API's MIDI package. If you have a thorough understanding of MIDI, you can safely skip this section. Before writing substantial MIDI applications, programmers who are unfamiliar with MIDI will probably need a fuller description of MIDI than can be included in this programmer's guide. See the Complete MIDI 1.0 Detailed Specification, which is available only in hard copy from http://www.midi.org (although you might find paraphrased or summarized versions on the Web).

MIDI is both a hardware specification and a software specification. To understand MIDI's design, it helps to understand its history. MIDI was originally designed for passing musical events, such as key depressions, between electronic keyboard instruments such as synthesizers. (As mentioned in Chapter 1, MIDI data consists primarily of control events that communicate a musician's gestures. MIDI data doesn't contain the audio that results from these events.) Hardware devices known as sequencers stored sequences of notes that could control a synthesizer, allowing musical performances to be recorded and subsequently played back. Later, hardware interfaces were developed that connected MIDI instruments to a computer's serial port, allowing sequencers to be implemented in software. More recently, computer sound cards have incorporated hardware for MIDI I/O and for synthesizing musical sound. Today, many users of MIDI deal only with sound cards, never connecting to external MIDI devices. CPUs have become fast enough that synthesizers, too, can be implemented in software. A sound card is needed only for audio I/O and, in some applications, for communicating with external MIDI devices.

The brief hardware portion of the MIDI specification prescribes the pinouts for MIDI cables and the jacks into which these cables are plugged. This portion need not concern us. Because devices that originally required hardware, such as sequencers and synthesizers, are now implementable in software, perhaps the only reason for most programmers to know anything about MIDI hardware devices is simply to understand the metaphors in MIDI. However, external MIDI hardware devices are still essential for some important music applications, and so the Java Sound API supports input and output of MIDI data.

The software portion of the MIDI specification is extensive. This portion concerns the structure of MIDI data and how devices such as synthesizers should respond to that data. It is important to understand that MIDI data can be streamed or sequenced. This duality reflects two different parts of the Complete MIDI 1.0 Detailed Specification:

  • MIDI 1.0
  • Standard MIDI Files

We'll explain what's meant by streaming and sequencing by examining the purpose of each of these two parts of the MIDI specification.

Streaming Data in the MIDI Wire Protocol

The first of these two parts of the MIDI specification describes what is known informally as "MIDI wire protocol." MIDI wire protocol, which is the original MIDI protocol, is based on the assumption that the MIDI data is being sent over a MIDI cable (the "wire"). The cable transmits digital data from one MIDI device to another. Each of the MIDI devices might be a musical instrument or a similar device, or it might be a general-purpose computer equipped with a MIDI-capable sound card or a MIDI-to-serial-port interface.

MIDI data, as defined by MIDI wire protocol, is organized into messages. The different kinds of message are distinguished by the first byte in the message, known as the status byte. (Status bytes are the only bytes that have the highest-order bit set to 1.) The bytes that follow the status byte in a message are known as data bytes. Certain MIDI messages, known as channel messages, have a status byte that contains four bits to specify the kind of channel message and another four bits to specify the channel number. There are therefore 16 MIDI channels; devices that receive MIDI messages can be set to respond to channel messages on all or only one of these virtual channels. Often each MIDI channel (which shouldn't be confused with a channel of audio) is used to send the notes for a different instrument. As an example, two common channel messages are Note On and Note Off, which start a note sounding and then stop it, respectively. These two messages each take two data bytes: the first specifies the note's pitch and the second its "velocity" (how fast the key is depressed or released, assuming a keyboard instrument is playing the note).

MIDI wire protocol defines a streaming model for MIDI data. A central feature of this protocol is that the bytes of MIDI data are delivered in real time—in other words, they are streamed. The data itself contains no timing information; each event is processed as it's received, and it's assumed that it arrives at the correct time. That model is fine if the notes are being generated by a live musician, but it's insufficient if you want to store the notes for later playback, or if you want to compose them out of real time. This limitation is understandable when you realize that MIDI was originally designed for musical performance, as a way for a keyboard musician to control more than one synthesizer, back in the days before many musicians used computers. (The first version of the specification was released in 1984.)

Sequenced Data in Standard MIDI Files

The Standard MIDI Files part of the MIDI specification addresses the timing limitation in MIDI wire protocol. A standard MIDI file is a digital file that contains MIDI events. An event is simply a MIDI message, as defined in the MIDI wire protocol, but with an additional piece of information that specifies the event's timing. (There are also some events that don't correspond to MIDI wire protocol messages, as we'll see in the next section.) The additional timing information is a series of bytes that indicates when to perform the operation described by the message. In other words, a standard MIDI file specifies not just which notes to play, but exactly when to play each of them. It's a bit like a musical score.

The information in a standard MIDI file is referred to as a sequence. A standard MIDI file contains one or more tracks. Each track typically contains the notes that a single instrument would play if the music were performed by live musicians. A sequencer is a software or hardware device that can read a sequence and deliver the MIDI messages contained in it at the right time. A sequencer is a bit like an orchestra conductor: it has the information for all the notes, including their timings, and it tells some other entity when to perform the notes.

The Java Sound API's Representation of MIDI Data

Now that we've sketched the MIDI specification's approach to streamed and sequenced musical data, let's examine how the Java Sound API represents that data.

MIDI Messages

MidiMessage is an abstract class that represents a "raw" MIDI message. A "raw" MIDI message is usually a message defined by the MIDI wire protocol. It can also be one of the events defined by the Standard MIDI Files specification, but without the event's timing information. There are three categories of raw MIDI message, represented in the Java Sound API by these three respective MidiMessage subclasses:

  • ShortMessages are the most common messages and have at most two data bytes following the status byte. The channel messages, such as Note On and Note Off, are all short messages, as are some other messages.
  • SysexMessages contain system-exclusive MIDI messages. They may have many bytes, and generally contain manufacturer-specific instructions.
  • MetaMessages occur in MIDI files, but not in MIDI wire protocol. Meta messages contain data, such as lyrics or tempo settings, that might be useful to sequencers but that are usually meaningless for synthesizers.

MIDI Events

As we've seen, standard MIDI files contain events that are wrappers for "raw" MIDI messages along with timing information. An instance of the Java Sound API's MidiEvent class represents an event such as might be stored in a standard MIDI file.

The API for MidiEvent includes methods to set and get the event's timing value. There's also a method to retrieve its embedded raw MIDI message, which is an instance of a subclass of MidiMessage, discussed next. (The embedded raw MIDI message can be set only when constructing the MidiEvent.)

Sequences and Tracks

As mentioned earlier, a standard MIDI file stores events that are arranged into tracks. Usually the file represents one musical composition, and usually each track represents a part such as might have been played by a single instrumentalist. Each note that the instrumentalist plays is represented by at least two events: a Note On that starts the note, and a Note Off that ends it. The track may also contain events that don't correspond to notes, such as meta-events (which were mentioned above).

The Java Sound API organizes MIDI data in a three-part hierarchy:

  • Sequence
  • Track
  • MidiEvent

A Track is a collection of MidiEvents, and a Sequence is a collection of Tracks. This hierarchy reflects the files, tracks, and events of the Standard MIDI Files specification. (Note: this is a hierarchy in terms of containment and ownership; it's not a class hierarchy in terms of inheritance. Each of these three classes inherits directly from java.lang.Object.)

Sequences can be read from MIDI files, or created from scratch and edited by adding Tracks to the Sequence (or removing them). Similarly, MidiEvents can be added to or removed from the tracks in the sequence.

The Java Sound API's Representation of MIDI Devices

The previous section explained how MIDI messages are represented in the Java Sound API. However, MIDI messages don't exist in a vacuum. They're typically sent from one device to another. A program that uses the Java Sound API can generate MIDI messages from scratch, but more often the messages are instead created by a software device, such as a sequencer, or received from outside the computer through a MIDI input port. Such a device usually sends these messages to another device, such as a synthesizer or a MIDI output port.

The MidiDevice Interface

In the world of external MIDI hardware devices, many devices can transmit MIDI messages to other devices and also receive messages from other devices. Similarly, in the Java Sound API, software objects that implement the MidiDevice interface can transmit and receive messages. Such an object can be implemented purely in software, or it can serve as an interface to hardware such as a sound card's MIDI capabilities. The base MidiDevice interface provides all the functionality generally required by a MIDI input or output port. Synthesizers and sequencers, however, further implement one of the subinterfaces of MidiDevice: Synthesizer or Sequencer, respectively.

The MidiDevice interface includes API for opening and closing a device. It also includes an inner class called MidiDevice.Info that provides textual descriptions of the device, including its name, vendor, and version. If you've read the sampled-audio portion of this programmer's guide, this API will probably sound familiar, because its design is similar to that of the javax.sampled.Mixer interface, which represents an audio device and which has an analogous inner class, Mixer.Info.

Transmitters and Receivers

Most MIDI devices are capable of sending MidiMessages, receiving them, or both. The way a device sends data is via one or more transmitter objects that it "owns." Similarly, the way a device receives data is via one or more of its receiver objects. The transmitter objects implement the Transmitter interface, and the receivers implement the Receiver interface.

Each transmitter can be connected to only one receiver at a time, and vice versa. A device that sends its MIDI messages to multiple other devices simultaneously does so by having multiple transmitters, each connected to a receiver of a different device. Similarly, a device that can receive MIDI messages from more than one source at a time must do so via multiple receivers.

Sequencers

A sequencer is a device for capturing and playing back sequences of MIDI events. It has transmitters, because it typically sends the MIDI messages stored in the sequence to another device, such as a synthesizer or MIDI output port. It also has receivers, because it can capture MIDI messages and store them in a sequence. To its superinterface, MidiDevice, Sequencer adds methods for basic MIDI sequencing operations. A sequencer can load a sequence from a MIDI file, query and set the sequence's tempo, and synchronize other devices to it. An application program can register an object to be notified when the sequencer processes certain kinds of events.

Synthesizers

A Synthesizer is a device for generating sound. It's the only object in the javax.sound.midi package that produces audio data. A synthesizer device controls a set of MIDI channel objects—typically 16 of them, since the MIDI specification calls for 16 MIDI channels. These MIDI channel objects are instances of a class that implements the MidiChannel interface, whose methods represent the MIDI specification's "channel voice messages" and "channel mode messages."

An application program can generate sound by directly invoking methods of a synthesizer's MIDI channel objects. More commonly, though, a synthesizer generates sound in response to messages sent to one or more of its receivers. These messages might be sent by a sequencer or MIDI input port, for example. The synthesizer parses each message that its receivers get, and usually dispatches a corresponding command (such as noteOn or controlChange) to one of its MidiChannel objects, according to the MIDI channel number specified in the event.

The MidiChannel uses the note information in these messages to synthesize music. For example, a noteOn message specifies the note's pitch and "velocity" (volume). However, the note information is insufficient; the synthesizer also requires precise instructions on how to create the audio signal for each note. These instructions are represented by an Instrument. Each Instrument typically emulates a different real-world musical instrument or sound effect. The Instruments might come as presets with the synthesizer, or they might be loaded from soundbank files. In the synthesizer, the Instruments are arranged by bank number (these can be thought of as rows) and program number (columns).

This chapter has provided a background for understanding MIDI data, and it has introduced some of the important interfaces and classes related to MIDI in the Java Sound API. Subsequent chapters show how you can access and use these objects in your application program.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Chapter 9: Accessing MIDI System Resources

Note

With version 5.0, the sound.properties file can be used to set default devices for Sequencer, Synthesizer, Transmitter, and Receiver. For details, see the MidiSystem class in the API; for examples, see Appendix 2: sound.properties File in this guide.

The Java Sound API offers a flexible model for MIDI system configuration, just as it does for configuration of the sampled-audio system. An implementation of the Java Sound API can itself provide different sorts of MIDI devices, and additional ones can be supplied by service providers and installed by users. You can write your program in such a way that it makes few assumptions about which specific MIDI devices are installed on the computer. Instead, the program can take advantage of the MIDI system's defaults, or it can allow the user to select from whatever devices happen to be available.

This section shows how your program can learn what MIDI resources have been installed, and how to get access to the desired ones. After you've accessed and opened the devices, you can connect them to each other, as discussed in the next chapter, "Transmitting and Receiving MIDI Messages."

The MidiSystem Class

The role of the MidiSystem class in the Java Sound API's MIDI package is directly analogous to the role of AudioSystem in the sampled-audio package. MidiSystem acts as a clearinghouse for accessing the installed MIDI resources.

You can query the MidiSystem to learn what sorts of devices are installed, and then you can iterate over the available devices and obtain access to the desired ones. For example, an application program might start out by asking the MidiSystem what synthesizers are available, and then display a list of them, from which the user can select one. A simpler application program might just use the system's default synthesizer.

The MidiSystem class also provides methods for translating between MIDI files and Sequences. It can report the file format of a MIDI file and can write files of different types.

An application program can obtain the following resources from the MidiSystem:

  • Sequencers
  • Synthesizers
  • Transmitters (such as those associated with MIDI input ports)
  • Receivers (such as those associated with MIDI output ports)
  • Data from standard MIDI files
  • Data from soundbank files

This chapter focuses on the first four of these types of resource. The MidiSystem class's file-handling facilities are discussed in Chapter 11, "Playing, Recording, and Editing MIDI Sequences," and Chapter 12, "Synthesizing Sound." To understand how the MIDI system itself gets access to all these resources, see Part III of this guide, "Service Provider Interfaces."

Obtaining Default Devices

A typical MIDI application program that uses the Java Sound API begins by obtaining the devices it needs, which can consist of one or more sequencers, synthesizers, input ports, or output ports.

There is a default synthesizer device, a default sequencer device, a default transmitting device, and a default receiving device. The latter two devices normally represent the MIDI input and output ports, respectively, if there are any available on the system. (It's easy to get confused about the directionality here. Think of the ports' transmission or reception in relation to the software, not in relation to any external physical devices connected to the physical ports. A MIDI input port transmits data from an external device to a Java Sound API Receiver, and likewise a MIDI output port receives data from a software object and relays the data to an external device.)

A simple application program might just use the default instead of exploring all the installed devices. The MidiSystem class includes the following methods for retrieving default resources:

    static Sequencer getSequencer()
    static Synthesizer getSynthesizer()
    static Receiver getReceiver()
    static Transmitter getTransmitter()

The first two of these methods obtain the system's default sequencing and synthesis resources, which either represent physical devices or are implemented wholly in software. The getReceiver method obtains a Receiver object that takes MIDI messages sent to it and relays them to the default receiving device. Similarly, the getTransmitter method obtains a Transmitter object that can send MIDI messages to some receiver on behalf of the default transmitting device.

Learning What Devices Are Installed

Instead of using the default devices, a more thorough approach is to select the desired devices from the full set of devices that are installed on the system. An application program can select the desired devices programmatically, or it can display a list of available devices and let the user select which ones to use. The MidiSystem class provides a method for learning which devices are installed, and a corresponding method to obtain a device of a given type.

Here is the method for learning about the installed devices:

    static MidiDevice.Info[] getMidiDeviceInfo()

As you can see, it returns an array of information objects. Each of these returned MidiDevice.Info objects identifies one type of sequencer, synthesizer, port, or other device that is installed. (Usually a system has at most one instance of a given type. For example, a given model of synthesizer from a certain vendor will be installed only once. ) The MidiDevice.Info includes the following strings to describe the device:

  • Name
  • Version number
  • Vendor (the company that created the device)
  • A description of the device

You can display these strings in your user interface to let the user select from the list of devices.

However, to use the strings programmatically to select a device (as opposed to displaying the strings to the user), you need to know in advance what they might be. The company that provides each device should include this information in its documentation. An application program that requires or prefers a particular device can use this information to locate that device. This approach has the drawback of limiting the program to device implementations that it knows about in advance.

Another, more general, approach is to go ahead and iterate over the MidiDevice.Info objects, obtaining each corresponding device, and determining programmatically whether it's suitable to use (or at least suitable to include in a list from which the user can choose). The next section describes how to do this.

Obtaining a Desired Device

Once an appropriate device's info object is found, the application program invokes the following MidiSystem method to obtain the corresponding device itself:

    static MidiDevice getMidiDevice(MidiDevice.Info info)

You can use this method if you've already found the info object describing the device you need. However, if you can't interpret the info objects returned by getMidiDeviceInfo to determine which device you need, and if you don't want to display information about all the devices to the user, you might be able to do the following instead: Iterate over all the MidiDevice.Info objects returned by getMidiDeviceInfo, get the corresponding devices using the method above, and test each device to see whether it's suitable. In other words, you can query each device for its class and its capabilities before including it in the list that you display to the user, or as a way to decide upon a device programmatically without involving the user. For example, if your program needs a synthesizer, you can obtain each of the installed devices, see which are instances of classes that implement the Synthesizer interface, and then display them in a list from which the user can choose one, as follows:

// Obtain information about all the installed synthesizers.
Vector synthInfos;
MidiDevice device;
MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo();
for (int i = 0; i < infos.length; i++) {
    try {
        device = MidiSystem.getMidiDevice(infos[i]);
    } catch (MidiUnavailableException e) {
          // Handle or throw exception...
    }
    if (device instanceof Synthesizer) {
        synthInfos.add(infos[i]);
    }
}
// Now, display strings from synthInfos list in GUI.

As another example, you might choose a device programmatically, without involving the user. Let's suppose you want to obtain the synthesizer that can play the most notes simultaneously. You iterate over all the MidiDevice.Info objects, as above, but after determining that a device is a synthesizer, you query its capabilities by invoking the getMaxPolyphony method of Synthesizer. You reserve the synthesizer that has the greatest polyphony, as described in the next section. Even though you're not asking the user to choose a synthesizer, you might still display strings from the chosen MidiDevice.Info object, just for the user's information.

Opening Devices

The previous section showed how to get an installed device. However, a device might be installed but unavailable. For example, another application program might have exclusive use of it. To actually reserve a device for your program, you need to use the MidiDevice method open:

if (!(device.isOpen())) {
    try {
      device.open();
  } catch (MidiUnavailableException e) {
          // Handle or throw exception...
  }
}

Once you've accessed a device and reserved it by opening it, you'll probably want to connect it to one or more other devices to let MIDI data flow between them. This procedure is described in Chapter 10, "Transmitting and Receiving MIDI Messages."

When done with a device, you release it for other programs' use by invoking the close method of MidiDevice.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Chapter 10: Transmitting and Receiving MIDI Messages

Understanding Devices, Transmitters, and Receivers

The Java Sound API specifies a message-routing architecture for MIDI data that's flexible and easy to use, once you understand how it works. The system is based on a module-connection design: distinct modules, each of which performs a specific task, can be interconnected (networked), enabling data to flow from one module to another.

The base module in the Java Sound API's messaging system is MidiDevice (a Java language interface). MidiDevices include sequencers (which record, play, load, and edit sequences of time-stamped MIDI messages), synthesizers (which generate sounds when triggered by MIDI messages), and MIDI input and output ports, through which data comes from and goes to external MIDI devices. The functionality typically required of MIDI ports is described by the base MidiDevice interface. The Sequencer and Synthesizer interfaces extend the MidiDevice interface to describe the additional functionality characteristic of MIDI sequencers and synthesizers, respectively. Concrete classes that function as sequencers or synthesizers should implement these interfaces.

A MidiDevice typically owns one or more ancillary objects that implement the Receiver or Transmitter interfaces. These interfaces represent the "plugs" or "portals" that connect devices together, permitting data to flow into and out of them. By connecting a Transmitter of one MidiDevice to a Receiver of another, you can create a network of modules in which data flows from one to another.

The MidiDevice interface includes methods for determining how many transmitter and receiver objects the device can support concurrently, and other methods for accessing those objects. A MIDI output port normally has at least one Receiver through which the outgoing messages may be received; similarly, a synthesizer normally responds to messages sent to its Receiver or Receivers. A MIDI input port normally has at least one Transmitter, which propagates the incoming messages. A full-featured sequencer supports both Receivers, which receive messages during recording, and Transmitters, which send messages during playback.

The Transmitter interface includes methods for setting and querying the receivers to which the transmitter sends its MidiMessages. Setting the receiver establishes the connection between the two. The Receiver interface contains a method that sends a MidiMessage to the receiver. Typically, this method is invoked by a Transmitter. Both the Transmitter and Receiver interfaces include a close method that frees up a previously connected transmitter or receiver, making it available for a different connection.

We'll now examine how to use transmitters and receivers. Before getting to the typical case of connecting two devices (such as hooking a sequencer to a synthesizer), we'll examine the simpler case where you send a MIDI message directly from your application program to a device. Studying this simple scenario should make it easier to understand how the Java Sound API arranges for sending MIDI messages between two devices.

Sending a Message to a Receiver without Using a Transmitter

Let's say you want to create a MIDI message from scratch and then send it to some receiver. You can create a new, blank ShortMessage and then fill it with MIDI data using the following ShortMessage method:

void setMessage(int command, int channel, int data1,
         int data2)

Once you have a message ready to send, you can send it to a Receiver object, using this Receiver method:

void send(MidiMessage message, long timeStamp)

The time-stamp argument will be explained momentarily. For now, we'll just mention that its value can be set to -1 if you don't care about specifying a precise time. In this case, the device receiving the message will try to respond to the message as soon as possible.

An application program can obtain a receiver for a MidiDevice by invoking the device's getReceiver method. If the device can't provide a receiver to the program (typically because all the device's receivers are already in use), a MidiUnavailableException is thrown. Otherwise, the receiver returned from this method is available for immediate use by the program. When the program has finished using the receiver, it should call the receiver's close method. If the program attempts to invoke methods on a receiver after calling close, an IllegalStateException may be thrown.

As a concrete simple example of sending a message without using a transmitter, let's send a Note On message to the default receiver, which is typically associated with a device such as the MIDI output port or a synthesizer. We do this by creating a suitable ShortMessage and passing it as an argument to Receiver's send method:

  ShortMessage myMsg = new ShortMessage();
  // Start playing the note Middle C (60),
  // moderately loud (velocity = 93).
  myMsg.setMessage(ShortMessage.NOTE_ON, 0, 60, 93);
  long timeStamp = -1;
  Receiver       rcvr = MidiSystem.getReceiver();
  rcvr.send(myMsg, timeStamp);

This code uses a static integer field of ShortMessage, namely, NOTE_ON, for use as the MIDI message's status byte. The other parts of the MIDI message are given explicit numeric values as arguments to the setMessage method. The zero indicates that the note is to be played using MIDI channel number 1; the 60 indicates the note Middle C; and the 93 is an arbitrary key-down velocity value, which typically indicates that the synthesizer that eventually plays the note should play it somewhat loudly. (The MIDI specification leaves the exact interpretation of velocity up to the synthesizer's implementation of its current instrument.) This MIDI message is then sent to the receiver with a time stamp of -1. We now need to examine exactly what the time stamp parameter means, which is the subject of the next section.

Understanding Time Stamps

Chapter 8, "Overview of the MIDI Package," explained that the MIDI specification has different parts. One part describes MIDI "wire" protocol (messages sent between devices in real time), and another part describes Standard MIDI Files (messages stored as events in "sequences"). In the latter part of the specification, each event stored in a standard MIDI file is tagged with a timing value that indicates when that event should be played. By contrast, messages in MIDI wire protocol are always supposed to be processed immediately, as soon as they're received by a device, so they have no accompanying timing values.

The Java Sound API adds an additional twist. It comes as no surprise that timing values are present in the MidiEvent objects that are stored in sequences (as might be read from a MIDI file), just as in the Standard MIDI Files specification. But in the Java Sound API, even the messages sent between devices—in other words, the messages that correspond to MIDI wire protocol—can be given timing values, known as time stamps. It is these time stamps that concern us here. (The timing values in MidiEvent objects are discussed in detail in Chapter 11, "Playing, Recording, and Editing MIDI Sequences.")

Time Stamps on Messages Sent to Devices

The time stamp that can optionally accompany messages sent between devices in the Java Sound API is quite different from the timing values in a standard MIDI file. The timing values in a MIDI file are often based on musical concepts such as beats and tempo, and each event's timing measures the time elapsed since the previous event. In contrast, the time stamp on a message sent to a device's Receiver object always measures absolute time in microseconds. Specifically, it measures the number of microseconds elapsed since the device that owns the receiver was opened.

This kind of time stamp is designed to help compensate for latencies introduced by the operating system or by the application program. It's important to realize that these time stamps are used for minor adjustments to timing, not to implement complex queues that can schedule events at completely arbitrary times (as MidiEvent timing values do).

The time stamp on a message sent to a device (through a Receiver) can provide precise timing information to the device. The device might use this information when it processes the message. For example, it might adjust the event's timing by a few milliseconds to match the information in the time stamp. On the other hand, not all devices support time stamps, so the device might completely ignore the message's time stamp.

Even if a device supports time stamps, it might not schedule the event for exactly the time that you requested. You can't expect to send a message whose time stamp is very far in the future and have the device handle it as you intended, and you certainly can't expect a device to correctly schedule a message whose time stamp is in the past! It's up to the device to decide how to handle time stamps that are too far off in the future or are in the past. The sender doesn't know what the device considers to be too far off, or whether the device had any problem with the time stamp. This ignorance mimics the behavior of external MIDI hardware devices, which send messages without ever knowing whether they were received correctly. (MIDI wire protocol is unidirectional.)

Some devices send time-stamped messages (via a Transmitter). For example, the messages sent by a MIDI input port might be stamped with the time the incoming message arrived at the port. On some systems, the event-handling mechanisms cause a certain amount of timing precision to be lost during subsequent processing of the message. The message's time stamp allows the original timing information to be preserved.

To learn whether a device supports time stamps, invoke the following method of MidiDevice:

    long getMicrosecondPosition()

This method returns -1 if the device ignores time stamps. Otherwise, it returns the device's current notion of time, which you as the sender can use as an offset when determining the time stamps for messages you subsequently send. For example, if you want to send a message with a time stamp for five milliseconds in the future, you can get the device's current position in microseconds, add 5000 microseconds, and use that as the time stamp. Keep in mind that the MidiDevice's notion of time always places time zero at the time the device was opened.

Now, with all that explanation of time stamps as a background, let's return to the send method of Receiver:

void send(MidiMessage message, long timeStamp)

The timeStamp argument is expressed in microseconds, according to the receiving device's notion of time. If the device doesn't support time stamps, it simply ignores the timeStamp argument. You aren't required to time-stamp the messages you send to a receiver. You can use -1 for the timeStamp argument to indicate that you don't care about adjusting the exact timing; you're just leaving it up to the receiving device to process the message as soon as it can. However, it's not advisable to send -1 with some messages and explicit time stamps with other messages sent to the same receiver. Doing so is likely to cause irregularities in the resultant timing.

Connecting Transmitters to Receivers

We've seen how you can send a MIDI message directly to a receiver, without using a transmitter. Now let's look at the more common case, where you aren't creating MIDI messages from scratch, but are simply connecting devices together so that one of them can send MIDI messages to the other.

Connecting to a Single Device

The specific case we'll take as our first example is connecting a sequencer to a synthesizer. After this connection is made, starting the sequencer running will cause the synthesizer to generate audio from the events in the sequencer's current sequence. For now, we'll ignore the process of loading a sequence from a MIDI file into the sequencer. Also, we won't go into the mechanism of playing the sequence. Loading and playing sequences is discussed in detail in Chapter 11, "Playing, Recording, and Editing MIDI Sequences." Loading instruments into the synthesizer is discussed in Chapter 12, "Synthesizing Sound." For now, all we're interested in is how to make the connection between the sequencer and the synthesizer. This will serve as an illustration of the more general process of connecting one device's transmitter to another device's receiver.

For simplicity, we'll use the default sequencer and the default synthesizer. (See Chapter 9, "Accessing MIDI System Resources," for more about default devices and how to access non-default devices.)

    Sequencer          seq;
    Transmitter         seqTrans;
    Synthesizer         synth;
    Receiver         synthRcvr;
    try {
          seq     = MidiSystem.getSequencer();
          seqTrans = seq.getTransmitter();
          synth   = MidiSystem.getSynthesizer();
          synthRcvr = synth.getReceiver();
          seqTrans.setReceiver(synthRcvr);
    } catch (MidiUnavailableException e) {
          // handle or throw exception
    }

An implementation might actually have a single object that serves as both the default sequencer and the default synthesizer. In other words, the implementation might use a class that implements both the Sequencer interface and the Synthesizer interface. In that case, it probably wouldn't be necessary to make the explicit connection that we did in the code above. For portability, though, it's safer not to assume such a configuration. If desired, you can test for this condition, of course:

if (seq instanceof Synthesizer)

although the explicit connection above should work in any case.

Connecting to More than One Device

The previous code example illustrated a one-to-one connection between a transmitter and a receiver. But, what if you need to send the same MIDI message to multiple receivers? For example, suppose you want to capture MIDI data from an external device to drive the internal synthesizer while simultaneously recording the data to a sequence. This form of connection, sometimes referred to as "fan out" or as a "splitter," is straightforward. The following statements show how to create a fan-out connection, through which the MIDI messages arriving at the MIDI input port are sent to both a Synthesizer object and a Sequencer object. We assume you've already obtained and opened the three devices: the input port, sequencer, and synthesizer. (To obtain the input port, you'll need to iterate over all the items returned by MidiSystem.getMidiDeviceInfo.)

    Synthesizer  synth;
    Sequencer    seq;
    MidiDevice   inputPort;
    // [obtain and open the three devices...]
    Transmitter   inPortTrans1, inPortTrans2;
    Receiver            synthRcvr;
    Receiver            seqRcvr;
    try {
          inPortTrans1 = inputPort.getTransmitter();
          synthRcvr = synth.getReceiver();
          inPortTrans1.setReceiver(synthRcvr);
          inPortTrans2 = inputPort.getTransmitter();
          seqRcvr = seq.getReceiver();
          inPortTrans2.setReceiver(seqRcvr);
    } catch (MidiUnavailableException e) {
          // handle or throw exception
    }

This code introduces a dual invocation of the MidiDevice.getTransmitter method, assigning the results to inPortTrans1 and inPortTrans2. As mentioned earlier, a device can own multiple transmitters and receivers. Each time MidiDevice.getTransmitter() is invoked for a given device, another transmitter is returned, until no more are available, at which time an exception will be thrown.

To learn how many transmitters and receivers a device supports, you can use the following MidiDevice method:

    int getMaxTransmitters()
    int getMaxReceivers()

These methods return the total number owned by the device, not the number currently available.

A transmitter can transmit MIDI messages to only one receiver at a time. (Every time you call Transmitter's setReceiver method, the existing Receiver, if any, is replaced by the newly specified one. You can tell whether the transmitter currently has a receiver by invoking Transmitter.getReceiver.) However, if a device has multiple transmitters, it can send data to more than one device at a time, by connecting each transmitter to a different receiver, as we saw in the case of the input port above.

Similarly, a device can use its multiple receivers to receive from more than one device at a time. The multiple-receiver code that's required is straightforward, being directly analogous to the multiple-transmitter code above. It's also possible for a single receiver to receive messages from more than one transmitter at a time.

Closing Connections

Once you're done with a connection, you can free up its resources by invoking the close method for each transmitter and receiver that you've obtained. The Transmitter and Receiver interfaces each have a close method. Note that invoking Transmitter.setReceiver doesn't close the transmitter's current receiver. The receiver is left open, and it can still receive messages from any other transmitter that's connected to it.

If you're also done with the devices, you can similarly make them available to other application programs by invoking MidiDevice.close(). Closing a device automatically closes all its transmitters and receivers.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Chapter 11: Playing, Recording and Editing MIDI Sequences

Note

With the 5.0 release, there is a new real-time Sequencer (implementation) that works with all Midi devices and, via its getTransmitter() method, an unlimited number of transmitters may be obtained. Prior to this release, it was not possible to get a Transmitter from a Sequencer.

In the world of MIDI, a sequencer is any hardware or software device that can precisely play or record a sequence of time-stamped MIDI messages. Similarly, in the Java Sound API, the Sequencer abstract interface defines the properties of an object that can play and record Sequences of MidiEvent objects. A Sequencer typically loads these MidiEvent sequences from a standard MIDI file or saves them to such a file. Sequences can also be edited. This chapter explains how to use Sequencer objects, along with related classes and interfaces, to accomplish such tasks.

Introduction to Sequencers

To develop an intuitive understanding of what a Sequencer is, think of it by analogy with a tape recorder, which a sequencer resembles in many respects. Whereas a tape recorder plays audio, a sequencer plays MIDI data. A sequence is a multi-track, linear, time-ordered recording of MIDI musical data, which a sequencer can play at various speeds, rewind, shuttle to particular points, record into, or copy to a file for storage.

Chapter 10, "Transmitting and Receiving MIDI Messages," explained that devices typically have Receiver objects, Transmitter objects, or both. To play music, a device generally receives MidiMessages through a Receiver, which in turn has usually received them from a Transmitter that belongs to a Sequencer. The device that owns this Receiver might be a Synthesizer, which will generate audio directly, or it might be a MIDI output port, which transmits MIDI data through a physical cable to some external piece of equipment. Similarly, to record music, a series of time-stamped MidiMessages are generally sent to a Receiver owned by a Sequencer, which places them in a Sequence object. Typically the object sending the messages is a Transmitter associated with a hardware input port, and the port relays MIDI data that it gets from an external instrument. However, the device responsible for sending the messages might instead be some other Sequencer, or any other device that has a Transmitter. Furthermore, as mentioned in Chapter 10, a program can send messages without using any Transmitter at all.

A Sequencer itself has both Receivers and Transmitters. When it's recording, it actually obtains MidiMessages via its Receivers. During playback, it uses its Transmitters to send MidiMessages that are stored in the Sequence that it has recorded (or loaded from a file).

One way to think of the role of a Sequencer in the Java Sound API is as an aggregator and "de-aggregator" of MidiMessages. A series of separate MidiMessages, each of which is independent, is sent to the Sequencer along with its own time stamp that marks the timing of a musical event. These MidiMessages are encapsulated in MidiEvent objects and collected in Sequence objects through the action of the Sequencer.record method. A Sequence is a data structure containing aggregates of MidiEvents, and it usually represents a series of musical notes, often an entire song or composition. On playback, the Sequencer again extracts the MidiMessages from the MidiEvent objects in the Sequence and then transmits them to one or more devices that will either render them into sound, save them, modify them, or pass them on to some other device.

Some sequencers might have neither transmitters nor receivers. For example, they might create MidiEvents from scratch as a result of keyboard or mouse events, instead of receiving MidiMessages through Receivers. Similarly, they might play music by communicating directly with an internal synthesizer (which could actually be the same object as the sequencer) instead of sending MidiMessages to a Receiver associated with a separate object. However, the rest of this chapter assumes the normal case of a sequencer that uses Receivers and Transmitters.

When to Use a Sequencer

It's possible for an application program to send MIDI messages directly to a device, without using a sequencer, as was described in Chapter 10, "Transmitting and Receiving MIDI Messages." The program simply invokes the Receiver.send method each time it wants to send a message. This is a straightforward approach that's useful when the program itself creates the messages in real time. For example, consider a program that lets the user play notes by clicking on an onscreen piano keyboard. When the program gets a mouse-down event, it immediately sends the appropriate Note On message to the synthesizer.

As mentioned in Chapter 10, the program can include a time stamp with each MIDI message it sends to the device's receiver. However, such time stamps are used only for fine-tuning the timing, to correct for processing latency. The caller can't generally set arbitrary time stamps; the time value passed to Receiver.send must be close to the present time, or the receiving device might not be able to schedule the message correctly. This means that if an application program wanted to create a queue of MIDI messages for an entire piece of music ahead of time (instead of creating each message in response to a real-time event), it would have to be very careful to schedule each invocation of Receiver.send for nearly the right time.

Fortunately, most application programs don't have to be concerned with such scheduling. Instead of invoking Receiver.send itself, a program can use a Sequencer object to manage the queue of MIDI messages for it. The sequencer takes care of scheduling and sending the messages—in other words, playing the music with the correct timing. Generally, it's advantageous to use a sequencer whenever you need to convert a non-real-time series of MIDI messages to a real-time series (as in playback), or vice versa (as in recording). Sequencers are most commonly used for playing data from MIDI files and for recording data from a MIDI input port.

Understanding Sequence Data

Before examining the Sequencer API, it helps to understand the kind of data that's stored in a sequence.

Sequences and Tracks

In the Java Sound API, sequencers closely follow the Standard MIDI Files specification in the way that they organize recorded MIDI data. As mentioned above, a Sequence is an aggregation of MidiEvents, organized in time. But there is more structure to a Sequence than just a linear series of MidiEvents: a Sequence actually contains global timing information plus a collection of Tracks, and it is the Tracks themselves that hold the MidiEvent data. So the data played by a sequencer consists of a three-level hierarchy of objects: Sequencer, Track, and MidiEvent.

In the conventional use of these objects, the Sequence represents a complete musical composition or section of a composition, with each Track corresponding to a voice or player in the ensemble. In this model, all the data on a particular Track would also therefore be encoded into a particular MIDI channel reserved for that voice or player.

This way of organizing data is convenient for purposes of editing sequences, but note that this is just a conventional way to use Tracks. There is nothing in the definition of the Track class per se that keeps it from containing a mix of MidiEvents on different MIDI channels. For example, an entire multi-channel MIDI composition can be mixed and recorded onto one Track. Also, standard MIDI files of Type 0 (as opposed to Type 1 and Type 2) contain by definition only one track; so a Sequence that's read from such a file will necessarily have a single Track object.

MidiEvents and Ticks

As discussed in Chapter 8, "Overview of the MIDI Package," the Java Sound API includes MidiMessage objects that correspond to the raw two- or three-byte sequences that make up most standard MIDI messages. A MidiEvent is simply a packaging of a MidiMessage along with an accompanying timing value that specifies when the event occurs. (We might then say that a sequence really consists of a four- or five-level hierarchy of data, rather than three-level, because the ostensible lowest level, MidiEvent, actually contains a lower-level MidiMessage, and likewise the MidiMessage object contains an array of bytes that comprises a standard MIDI message.)

In the Java Sound API, there are two different ways in which MidiMessages can be associated with timing values. One is the way mentioned above under "When to Use a Sequencer." This technique is described in detail under "Sending a Message to a Receiver without Using a Transmitter" and "Understanding Time Stamps" in Chapter 10, "Transmitting and Receiving MIDI Messages." There, we saw that the send method of Receiver takes a MidiMessage argument and a time-stamp argument. That kind of time stamp can only be expressed in microseconds.

The other way in which a MidiMessage can have its timing specified is by being encapsulated in a MidiEvent. In this case, the timing is expressed in slightly more abstract units called ticks.

What is the duration of a tick? It can vary between sequences (but not within a sequence), and its value is stored in the header of a standard MIDI file. The size of a tick is given in one of two types of units:

  • Pulses (ticks) per quarter note, abbreviated as PPQ
  • Ticks per frame, also known as SMPTE time code (a standard adopted by the Society of Motion Picture and Television Engineers)

If the unit is PPQ, the size of a tick is expressed as a fraction of a quarter note, which is a relative, not absolute, time value. A quarter note is a musical duration value that often corresponds to one beat of the music (a quarter of a measure in 4/4 time). The duration of a quarter note is dependent on the tempo, which can vary during the course of the music if the sequence contains tempo-change events. So if the sequence's timing increments (ticks) occur, say 96 times per quarter note, each event's timing value measures that event's position in musical terms, not as an absolute time value.

On the other hand, in the case of SMPTE, the units measure absolute time, and the notion of tempo is inapplicable. There are actually four different SMPTE conventions available, which refer to the number of motion-picture frames per second. The number of frames per second can be 24, 25, 29.97, or 30. With SMPTE time code, the size of a tick is expressed as a fraction of a frame.

In the Java Sound API, you can invoke Sequence.getDivisionType to learn which type of unit—namely, PPQ or one of the SMPTE units—is used in a particular sequence. You can then calculate the size of a tick after invoking Sequence.getResolution. The latter method returns the number of ticks per quarter note if the division type is PPQ, or per SMPTE frame if the division type is one of the SMPTE conventions. You can get the size of a tick using this formula in the case of PPQ:

ticksPerSecond =
    resolution * (currentTempoInBeatsPerMinute / 60.0);
tickSize = 1.0 / ticksPerSecond;

and this formula in the case of SMPTE:

framesPerSecond =
  (divisionType == Sequence.SMPTE_24 ? 24
    : (divisionType == Sequence.SMPTE_25 ? 25
      : (divisionType == Sequence.SMPTE_30 ? 30
        : (divisionType == Sequence.SMPTE_30DROP ?
            29.97))));
ticksPerSecond = resolution * framesPerSecond;
tickSize = 1.0 / ticksPerSecond;

The Java Sound API's definition of timing in a sequence mirrors that of the Standard MIDI Files specification. However, there's one important difference. The tick values contained in MidiEvents measure cumulative time, rather than delta time. In a standard MIDI file, each event's timing information measures the amount of time elapsed since the onset of the previous event in the sequence. This is called delta time. But in the Java Sound API, the ticks aren't delta values; they're the previous event's time value plus the delta value. In other words, in the Java Sound API the timing value for each event is always greater than that of the previous event in the sequence (or equal, if the events are supposed to be simultaneous). Each event's timing value measures the time elapsed since the beginning of the sequence.

To summarize, the Java Sound API expresses timing information in either MIDI ticks or microseconds. MidiEvents store timing information in terms of MIDI ticks. The duration of a tick can be calculated from the Sequence's global timing information and, if the sequence uses tempo-based timing, the current musical tempo. The time stamp associated with a MidiMessage sent to a Receiver, on the other hand, is always expressed in microseconds.

One goal of this design is to avoid conflicting notions of time. It's the job of a Sequencer to interpret the time units in its MidiEvents, which might have PPQ units, and translate these into absolute time in microseconds, taking the current tempo into account. The sequencer must also express the microseconds relative to the time when the device receiving the message was opened. Note that a sequencer can have multiple transmitters, each delivering messages to a different receiver that might be associated with a completely different device. You can see, then, that the sequencer has to be able to perform multiple translations at the same time, making sure that each device receives time stamps appropriate for its notion of time.

To make matters more complicated, different devices might update their notions of time based on different sources (such as the operating system's clock, or a clock maintained by a sound card). This means that their timings can drift relative to the sequencer's. To keep in synchronization with the sequencer, some devices permit themselves to be "slaves" to the sequencer's notion of time. Setting masters and slaves is discussed later under "Using Advanced Sequencer Features."

Overview of Sequencer Methods

The Sequencer interface provides methods in several categories:

  • Methods to load sequence data from a MIDI file or a Sequence object, and to save the currently loaded sequence data to a MIDI file.
  • Methods analogous to the transport functions of a tape recorder, for stopping and starting playback and recording, enabling and disabling recording on specific tracks, and shuttling the current playback or recording position in a Sequence.
  • Advanced methods for querying and setting the synchronization and timing parameters of the object. A Sequencer may play at different tempos, with some Tracks muted, and in various synchronization states with other objects.
  • Advanced methods for registering "listener" objects that are notified when the Sequencer processes certain kinds of MIDI events.

Regardless of which Sequencer methods you'll invoke, the first step is to obtain a Sequencer device from the system and reserve it for your program's use.

Obtaining a Sequencer

An application program doesn't instantiate a Sequencer; after all, Sequencer is just an interface. Instead, like all devices in the Java Sound API's MIDI package, a Sequencer is accessed through the static MidiSystem object. As mentioned in Chapter 9, "Accessing MIDI System Resources," the following MidiSystem method can be used to obtain the default Sequencer:

    static Sequencer getSequencer()

The following code fragment obtains the default Sequencer, acquires any system resources it needs, and makes it operational:

    Sequencer sequencer;
    // Get default sequencer.
    sequencer = MidiSystem.getSequencer();
    if (sequencer == null) {
        // Error -- sequencer device is not supported.
        // Inform user and return...
    } else {
         // Acquire resources and make operational.
        sequencer.open();
    }

The invocation of open reserves the sequencer device for your program's use. It doesn't make much sense to imagine sharing a sequencer, because it can play only one sequence at a time. When you're done using the sequencer, you can make it available to other programs by invoking close.

Non-default sequencers can be obtained as described in Chapter 9, "Accessing MIDI System Resources."

Loading a Sequence

Having obtained a sequencer from the system and reserved it, you then need load the data that the sequencer should play. There are three typical ways of accomplishing this:

  • Reading the sequence data from a MIDI file
  • Recording it in real time by receiving MIDI messages from another device, such as a MIDI input port
  • Building it programmatically "from scratch" by adding tracks to an empty sequence and adding MidiEvent objects to those tracks

We'll now look at the first of these ways of getting sequence data. (The other two ways are described later under "Recording and Saving Sequences" and "Editing a Sequence," respectively.) This first way actually encompasses two slightly different approaches. One approach is to feed MIDI file data to an InputStream that you then read directly to the sequencer by means of Sequencer.setSequence(InputStream). With this approach, you don't explicitly create a Sequence object. In fact, the Sequencer implementation might not even create a Sequence behind the scenes, because some sequencers have a built-in mechanism for handling data directly from a file.

The other approach is to create a Sequence explicitly. You'll need to use this approach if you're going to edit the sequence data before playing it. With this approach, you invoke MidiSystem's overloaded method getSequence. The method is able to get the sequence from an InputStream, a File, or a URL. The method returns a Sequence object that can then be loaded into a Sequencer for playback. Expanding on the previous code excerpt, here's an example of obtaining a Sequence object from a File and loading it into our sequencer:

    try {
        File myMidiFile = new File("seq1.mid");
        // Construct a Sequence object, and
        // load it into my sequencer.
         Sequence mySeq = MidiSystem.getSequence(myMidiFile);
        sequencer.setSequence(mySeq);
    } catch (Exception e) {
        // Handle error and/or return
    }

Like MidiSystem's getSequence method, setSequence may throw an InvalidMidiDataException—and, in the case of the InputStream variant, an IOException—if it runs into any trouble.

Playing a Sequence

Starting and stopping a Sequencer is accomplished using the following methods:

    void start()

and

    void stop()

The Sequencer.start method begins playback of the sequence. Note that playback starts at the current position in a sequence. Loading an existing sequence using the setSequence method, described above, initializes the sequencer's current position to the very beginning of the sequence. The stop method stops the sequencer, but it does not automatically rewind the current Sequence. Starting a stopped Sequence without resetting the position simply resumes playback of the sequence from the current position. In this case, the stop method has served as a pause operation. However, there are various Sequencer methods for setting the current sequence position to an arbitrary value before playback is started. (We'll discuss these methods below.)

As mentioned earlier, a Sequencer typically has one or more Transmitter objects, through which it sends MidiMessages to a Receiver. It is through these Transmitters that a Sequencer plays the Sequence, by emitting appropriately timed MidiMessages that correspond to the MidiEvents contained in the current Sequence. Therefore, part of the setup procedure for playing back a Sequence is to invoke the setReceiver method on the Sequencer's Transmitter object, in effect wiring its output to the device that will make use of the played-back data. For more details on Transmitters and Receivers, see Chapter 10, "Transmitting and Receiving MIDI Messages."

Recording and Saving Sequences

To capture MIDI data to a Sequence, and subsequently to a file, you need to perform some additional steps beyond those described above. The following outline shows the steps necessary to set up for recording to a Track in a Sequence:

  2. Use MidiSystem.getSequencer to get a new sequencer to use for recording, as above.
  3. Set up the "wiring" of the MIDI connections. The object that is transmitting the MIDI data to be recorded should be configured, through its setReceiver method, to send data to a Receiver associated with the recording Sequencer.
  4. Create a new Sequence object, which will store the recorded data. When you create the Sequence object, you must specify the global timing information for the sequence. For example:
          Sequence mySeq;
      try{
          mySeq = new Sequence(Sequence.PPQ, 10);
      } catch (Exception ex) {
          ex.printStackTrace();
      }
    The constructor for Sequence takes as arguments a divisionType and a timing resolution. The divisionType argument specifies the units of the resolution argument. In this case, we've specified that the timing resolution of the Sequence we're creating will be 10 pulses per quarter note. An additional optional argument to the Sequence constructor is a number of tracks argument, which would cause the initial sequence to begin with the specified number of (initially empty) Tracks. Otherwise the Sequence will be created with no initial Tracks; they can be added later as needed.
  5. Create an empty Track in the Sequence, with Sequence.createTrack. This step is unnecessary if the Sequence was created with initial Tracks.
  6. Using Sequencer.setSequence, select our new Sequence to receive the recording. The setSequence method ties together an existing Sequence with the Sequencer, which is somewhat analogous to loading a tape onto a tape recorder.
  7. Invoke Sequencer.recordEnable for each Track to be recorded. If necessary, get a reference to the available Tracks in the Sequence by invoking Sequence.getTracks.
  8. Invoke startRecording on the Sequencer.
  9. When done recording, invoke Sequencer.stop or Sequencer.stopRecording.
  10. Save the recorded Sequence to a MIDI file with MidiSystem.write. The write method of MidiSystem takes a Sequence as one of its arguments, and will write that Sequence to a stream or file.

Editing a Sequence

Many application programs allow a sequence to be created by loading it from a file, and quite a few also allow a sequence to be created by capturing it from live MIDI input (that is, recording). Some programs, however, will need to create MIDI sequences from scratch, whether programmatically or in response to user input. Full-featured sequencer programs permit the user to manually construct new sequences, as well as to edit existing ones.

These data-editing operations are achieved in the Java Sound API not by Sequencer methods, but by methods of the data objects themselves: Sequence, Track, and MidiEvent. You can create an empty sequence using one of the Sequence constructors, and then add tracks to it by invoking the following Sequence method:

    Track createTrack()
If your program allows the user to edit sequences, you'll need this Sequence method to remove tracks:
    boolean deleteTrack(Track track)

Once the sequence contains tracks, you can modify the contents of the tracks by invoking methods of the Track class. The MidiEvents contained in the Track are stored as a java.util.Vector in the Track object, and Track provides a set of methods for accessing, adding, and removing the events in the list. The methods add and remove are fairly self-explanatory, adding or removing a specified MidiEvent from a Track. A get method is provided, which takes an index into the Track's event list and returns the MidiEvent stored there. In addition, there are size and tick methods, which respectively return the number of MidiEvents in the track, and the track's duration, expressed as a total number of Ticks.

To create a new event before adding it to the track, you'll of course use the MidiEvent constructor. To specify or modify the MIDI message embedded in the event, you can invoke the setMessage method of the appropriate MidiMessage subclass (ShortMessage, SysexMessage, or MetaMessage). To modify the time that the event should occur, invoke MidiEvent.setTick.

In combination, these low-level methods provide the basis for the editing functionality needed by a full-featured sequencer program.

Using Advanced Sequencer Features

So far, this chapter has focused on simple playback and recording of MIDI data. This section will briefly describe some of the more advanced features available through methods of the Sequencer interface and the Sequence class.

Moving to an Arbitrary Position in the Sequence

There are two Sequencer methods that obtain the sequencer's current position in the sequence. The first of these:

    long getTickPosition()

returns the position measured in MIDI ticks from the beginning of the sequence. The second method:

long getMicrosecondPosition()

returns the current position in microseconds. This method assumes that the sequence is being played at the default rate as stored in the MIDI file or in the Sequence. It does not return a different value if you've changed the playback speed as described below.

You can similarly set the sequencer's current position according to one unit or the other:

void setTickPosition(long tick)

or

void setMicrosecondPosition(long microsecond)

Changing the Playback Speed

As indicated earlier, a sequence's speed is indicated by its tempo, which can vary over the course of the sequence. A sequence can contain events that encapsulate standard MIDI tempo-change messages. When the sequencer processes such an event, it changes the speed of playback to reflect the indicated tempo. In addition, you can programmatically change the tempo by invoking any of these Sequencer methods:

    public void setTempoInBPM(float bpm)
    public void setTempoInMPQ(float mpq)
    public void setTempoFactor(float factor)
The first two of these methods set the tempo in beats per minute or microseconds per quarter note, respectively. The tempo will stay at the specified value until one of these methods is invoked again, or until a tempo-change event is encountered in the sequence, at which point the current tempo is overridden by the newly specified one.

The third method, setTempoFactor, is different in nature. It scales whatever tempo is set for the sequencer (whether by tempo-change events or by one of the first two methods above). The default scalar is 1.0 (no change). Although this method causes the playback or recording to be faster or slower than the nominal tempo (unless the factor is 1.0), it doesn't alter the nominal tempo. In other words, the tempo values returned by getTempoInBPM and getTempoInMPQ are unaffected by the tempo factor, even though the tempo factor does affect the actual rate of playback or recording. Also, if the tempo is changed by a tempo-change event or by one of the first two methods, it still gets scaled by whatever tempo factor was last set. If you load a new sequence, however, the tempo factor is reset to 1.0.

Note that all these tempo-change directives are ineffectual when the sequence's division type is one of the SMPTE types, instead of PPQ.

Muting or Soloing Individual Tracks in the Sequence

It's often convenient for users of sequencers to be able to turn off certain tracks, to hear more clearly exactly what is happening in the music. A full-featured sequencer program lets the user choose which tracks should sound during playback. (Speaking more precisely, since sequencers don't actually create sound themselves, the user chooses which tracks will contribute to the stream of MIDI messages that the sequencer produces.) Typically, there are two types of graphical controls on each track: a mute button and a solo button. If the mute button is activated, that track will not sound under any circumstances, until the mute button is deactivated. Soloing is a less well-known feature. It's roughly the opposite of muting. If the solo button on any track is activated, only tracks whose solo buttons are activated will sound. This feature lets the user quickly audition a small number of tracks without having to mute all the other tracks. The mute button typically takes priority over the solo button: if both are activated, the track doesn't sound.

Using Sequencer methods, muting or soloing tracks (as well as querying a track's current mute or solo state) is easily accomplished. Let's assume we have obtained the default Sequencer and that we've loaded sequence data into it. Muting the fifth track in the sequence would be accomplished as follows:

    sequencer.setTrackMute(4, true);
    boolean muted = sequencer.getTrackMute(4);
    if (!muted) {
        return;         // muting failed
    }
There are a couple of things to note about the above code snippet. First, tracks of a sequence are numbered starting with 0 and ending with the total number of tracks minus 1. Also, the second argument to setTrackMute is a boolean. If it's true, the request is to mute the track; otherwise the request is to unmute the specified track. Lastly, in order to test that the muting took effect, we invoke the Sequencer getTrackMute method, passing it the track number we're querying. If it returns true, as we'd expect in this case, then the mute request worked. If it returns false, then it failed.

Mute requests may fail for various reasons. For example, the track number specified in the setTrackMute call might exceed the total number of tracks, or the sequencer might not support muting. By calling getTrackMute, we can determine if our request succeeded or failed.

As an aside, the boolean that's returned by getTrackMute can, indeed, tell us if a failure occurred, but it can't tell us why it occurred. We could test to see if a failure was caused by passing an invalid track number to the setTrackMute method. To do this, we would call the getTracks method of Sequence, which returns an array containing all of the tracks in the sequence. If the track number specified in the setTrackMute call exceeds the length of this array, then we know we specified an invalid track number.

If the mute request succeeded, then in our example, the fifth track will not sound when the sequence is playing, nor will any other tracks that are currently muted.

The method and techniques for soloing a track are very similar to those for muting. To solo a track, invoke the setTrackSolo method of Sequence:

void setTrackSolo(int track, boolean bSolo)
As in setTrackMute, the first argument specifies the zero-based track number, and the second argument, if true, specifies that the track should be in solo mode; otherwise the track should not be soloed.

By default, a track is neither muted nor soloed.

Synchronizing with Other MIDI Devices

Sequencer has an inner class called Sequencer.SyncMode. A SyncMode object represents one of the ways in which a MIDI sequencer's notion of time can be synchronized with a master or slave device. If the sequencer is being synchronized to a master, the sequencer revises its current time in response to certain MIDI messages from the master. If the sequencer has a slave, the sequencer similarly sends MIDI messages to control the slave's timing.

There are three predefined modes that specify possible masters for a sequencer: INTERNAL_CLOCK, MIDI_SYNC, and MIDI_TIME_CODE. The latter two work if the sequencer receives MIDI messages from another device. In these two modes, the sequencer's time gets reset based on system real-time timing clock messages or MIDI time code (MTC) messages, respectively. (See the MIDI specification for more information about these types of message.) These two modes can also be used as slave modes, in which case the sequencer sends the corresponding types of MIDI messages to its receiver. A fourth mode, NO_SYNC, is used to indicate that the sequencer should not send timing information to its receivers.

By calling the setMasterSyncMode method with a supported SyncMode object as the argument, you can specify how the sequencer's timing is controlled. Likewise, the setSlaveSyncMode method determines what timing information the sequencer will send to its receivers. This information controls the timing of devices that use the sequencer as a master timing source.

Specifying Special Event Listeners

Each track of a sequence can contain many different kinds of MidiEvents. Such events include Note On and Note Off messages, program changes, control changes, and meta events. The Java Sound API specifies "listener" interfaces for the last two of these event types (control change events and meta events). You can use these interfaces to receive notifications when such events occur during playback of a sequence.

Objects that support the ControllerEventListener interface can receive notification when a Sequencer processes particular control-change messages. A control-change message is a standard type of MIDI message that represents a change in the value of a MIDI controller, such as a pitch-bend wheel or a data slider. (See the MIDI specification for the complete list of control-change messages.) When such a message is processed during playback of a sequence, the message instructs any device (probably a synthesizer) that's receiving the data from the sequencer to update the value of some parameter. The parameter usually controls some aspect of sound synthesis, such as the pitch of the currently sounding notes if the controller was the pitch-bend wheel. When a sequence is being recorded, the control-change message means that a controller on the external physical device that created the message has been moved, or that such a move has been simulated in software.

Here's how the ControllerEventListener interface is used. Let's assume that you've developed a class that implements the ControllerEventListener interface, meaning that your class contains the following method:

    void controlChange(ShortMessage msg)
Let's also assume that you've created an instance of your class and assigned it to a variable called myListener. If you include the following statements somewhere within your program:
    int[] controllersOfInterest = { 1, 2, 4 };
    sequencer.addControllerEventListener(myListener,
        controllersOfInterest);
then your class's controlChange method will be invoked every time the sequencer processes a control-change message for MIDI controller numbers 1, 2, or 4. In other words, when the Sequencer processes a request to set the value of any of the registered controllers, the Sequencer will invoke your class's controlChange method. (Note that the assignments of MIDI controller numbers to specific control devices is detailed in the MIDI 1.0 Specification.)

The controlChange method is passed a ShortMessage containing the controller number affected, and the new value to which the controller was set. You can obtain the controller number using the ShortMessage.getData1 method, and the new setting of the controller's value using the ShortMessage.getData2 method.

The other kind of special event listener is defined by the MetaEventListener interface. Meta messages, according to the Standard MIDI Files 1.0 specification, are messages that are not present in MIDI wire protocol but that can be embedded in a MIDI file. They are not meaningful to a synthesizer, but can be interpreted by a sequencer. Meta messages include instructions (such as tempo change commands), lyrics or other text, and other indicators (such as end-of-track).

The MetaEventListener mechanism is analogous to ControllerEventListener. Implement the MetaEventListener interface in any class whose instances need to be notified when a MetaMessage is processed by the sequencer. This involves adding the following method to the class:

void meta(MetaMessage msg)

You register an instance of this class by passing it as the argument to the Sequencer addMetaEventListener method:

boolean b = sequencer.addMetaEventListener
        (myMetaListener);
This is slightly different from the approach taken by the ControllerEventListener interface, because you have to register to receive all MetaMessages, not just selected ones of interest. If the sequencer encounters a MetaMessage in its sequence, it will invoke myMetaListener.meta, passing it the MetaMessage encountered. The meta method can invoke getType on its MetaMessage argument to obtain an integer from 0 to 127 that indicates the message type, as defined by the Standard MIDI Files 1.0 specification.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Chapter 12: Synthesizing Sound

Most programs that avail themselves of the Java Sound API's MIDI package do so to synthesize sound. The entire apparatus of MIDI files, events, sequences, and sequencers, which was discussed in other chapters, nearly always has the goal of eventually sending musical data to a synthesizer to convert into audio. (Possible exceptions include programs that convert MIDI into musical notation that can be read by a musician, and programs that send messages to external MIDI-controlled devices such as mixing consoles.)

The Synthesizer interface is therefore fundamental to the MIDI package. This chapter shows how to manipulate a synthesizer to play sound. Many programs will simply use a sequencer to send MIDI file data to the synthesizer, and won't need to invoke many Synthesizer methods directly. However, it's possible to control a synthesizer directly, without using sequencers or even MidiMessage objects, as explained near the end of this chapter.

The synthesis architecture might seem complex for readers who are unfamiliar with MIDI. Its API includes three interfaces:

  • Synthesizer
  • MidiChannel
  • Soundbank

and four classes:
  • Instrument
  • Patch
  • SoundbankResource
  • VoiceStatus

As orientation for all this API, the next section explains some of the basics of MIDI synthesis and how they're reflected in the Java Sound API. (Also see the brief section "Synthesizers" under "The Java Sound API's Representation of MIDI Devices" in Chapter 8, "Overview of the MIDI Package.") Subsequent sections give a more detailed look at the API.

Understanding MIDI Synthesis

How does a synthesizer generate sound? Depending on its implementation, it may use one or more sound-synthesis techniques. For example, many synthesizers use wavetable synthesis. A wavetable synthesizer reads stored snippets of audio from memory, playing them at different sample rates and looping them to create notes of different pitches and durations. For example, to synthesize the sound of a saxophone playing the note C#4 (MIDI note number 61), the synthesizer might access a very short snippet from a recording of a saxophone playing the note Middle C (MIDI note number 60), and then cycle repeatedly through this snippet at a slightly faster sample rate than it was recorded at, which creates a long note of a slightly higher pitch. Other synthesizers use techniques such as frequency modulation (FM), additive synthesis, or physical modeling, which don't make use of stored audio but instead generate audio from scratch using different algorithms.

Instruments

What all synthesis techniques have in common is the ability to create many sorts of sounds. Different algorithms, or different settings of parameters within the same algorithm, create different-sounding results. An instrument is a specification for synthesizing a certain type of sound. That sound may emulate a traditional musical instrument, such as a piano or violin; it may emulate some other kind of sound source, for instance, a telephone or helicopter; or it may emulate no "real-world" sound at all. A specification called General MIDI defines a standard list of 128 instruments, but most synthesizers allow other instruments as well. Many synthesizers provide a collection of built-in instruments that are always available for use; some synthesizers also support mechanisms for loading additional instruments.

An instrument may be vendor-specific—in other words, applicable to only one synthesizer or several models from the same vendor. This incompatibility results when two different synthesizers use different sound-synthesis techniques, or different internal algorithms and parameters even if the fundamental technique is the same. Because the details of the synthesis technique are often proprietary, incompatibility is common. The Java Sound API includes ways to detect whether a given synthesizer supports a given instrument.

An instrument can usually be considered a preset; you don't have to know anything about the details of the synthesis technique that produces its sound. However, you can still vary aspects of its sound. Each Note On message specifies the pitch and volume of an individual note. You can also alter the sound through other MIDI commands such as controller messages or system-exclusive messages.

Channels

Many synthesizers are multimbral (sometimes called polytimbral), meaning that they can play the notes of different instruments simultaneously. (Timbre is the characteristic sound quality that enables a listener to distinguish one kind of musical instrument from other kinds.) Multimbral synthesizers can emulate an entire ensemble of real-world instruments, instead of only one instrument at a time. MIDI synthesizers normally implement this feature by taking advantage of the different MIDI channels on which the MIDI specification allows data to be transmitted. In this case, the synthesizer is actually a collection of sound-generating units, each emulating a different instrument and responding independently to messages that are received on a different MIDI channel. Since the MIDI specification provides only 16 channels, a typical MIDI synthesizer can play up to 16 different instruments at once. The synthesizer receives a stream of MIDI commands, many of which are channel commands. (Channel commands are targeted to a particular MIDI channel; for more information, see the MIDI specification.) If the synthesizer is multitimbral, it routes each channel command to the correct sound-generating unit, according to the channel number indicated in the command.

In the Java Sound API, these sound-generating units are instances of classes that implement the MidiChannel interface. A synthesizer object has at least one MidiChannel object. If the synthesizer is multimbral, it has more than one, normally 16. Each MidiChannel represents an independent sound-generating unit.

Because a synthesizer's MidiChannel objects are more or less independent, the assignment of instruments to channels doesn't have to be unique. For example, all 16 channels could be playing a piano timbre, as though there were an ensemble of 16 pianos. Any grouping is possible—for instance, channels 1, 5, and 8 could be playing guitar sounds, while channels 2 and 3 play percussion and channel 12 has a bass timbre. The instrument being played on a given MIDI channel can be changed dynamically; this is known as a program change.

Even though most synthesizers allow only 16 or fewer instruments to be active at a given time, these instruments can generally be chosen from a much larger selection and assigned to particular channels as required.

Soundbanks and Patches

Instruments are organized hierarchically in a synthesizer. As was mentioned in Chapter 8, "Overview of the MIDI Package," the instruments are arranged by bank number and program number. Banks and programs can be thought of as rows and columns in a two-dimensional table of instruments. A bank is a collection of programs. The MIDI specification allows up to 128 programs in a bank, and up to 128 banks. However, a particular synthesizer might support only one bank, or a few banks, and might support fewer than 128 programs per bank.

In the Java Sound API, there's a higher level to the hierarchy: a soundbank. Soundbanks can contain up to 128 banks, each containing up to 128 instruments. Some synthesizers can load an entire soundbank into memory.

To select an instrument from the current soundbank, you specify a bank number and a program number. The MIDI specification accomplishes this with two MIDI commands: bank select and program change. In the Java Sound API, the combination of a bank number and program number is encapsulated in a Patch object. You change a MIDI channel's current instrument by specifying a new patch. The patch can be considered the two-dimensional index of the instruments in the current soundbank.

You might be wondering if soundbanks, too, are indexed numerically. The answer is no; the MIDI specification does not provide for this. In the Java Sound API, a Soundbank object can be obtained by reading a soundbank file. If the soundbank is supported by the synthesizer, its instruments can be loaded into the synthesizer individually as desired, or all at once. Many synthesizers have a built-in or default soundbank; the instruments contained in this soundbank are always available to the synthesizer.

Voices

It's important to distinguish between the number of timbres a synthesizer can play simultaneously and the number of notes it can play simultaneously. The former was described above under "Channels." The ability to play multiple notes at once is referred to as polyphony. Even a synthesizer that isn't multitimbral can generally play more than one note at a time (all having the same timbre, but different pitches). For example, playing any chord, such as a G major triad or a B minor seventh chord, requires polyphony. Any synthesizer that generates sound in real time has a limitation on the number of notes it can synthesize at once. In the Java Sound API, the synthesizer reports this limitation through the getMaxPolyphony method.

A voice is a succession of single notes, such as a melody that a person can sing. Polyphony consists of multiple voices, such as the parts sung by a choir. A 32-voice synthesizer, for example, can play 32 notes simultaneously. (However, some MIDI literature uses the word "voice" in a different sense, similar to the meaning of "instrument" or "timbre.")

The process of assigning incoming MIDI notes to specific voices is known as voice allocation. A synthesizer maintains a list of voices, keeping track of which ones are active (meaning that they currently have notes sounding). When a note stops sounding, the voice becomes inactive, meaning that it's now free to accept the next note-on request that the synthesizer receives. An incoming stream of MIDI commands can easily request more simultaneous notes than the synthesizer is capable of generating. When all the synthesizer's voices are active, how should the next Note On request be handled? Synthesizers can implement different strategies: the most recently requested note can be ignored; or it can be played by discontinuing another note, such as the least recently started one.

Although the MIDI specification does not require it, a synthesizer can make public the contents of each of its voices. The Java Sound API includes a VoiceStatus class for this purpose.

A VoiceStatus reports on the voice's current active or inactive status, MIDI channel, bank and program number, MIDI note number, and MIDI volume.

With this background, let's examine the specifics of the Java Sound API for synthesis.

Managing Instruments and Soundbanks

In many cases, a program can make use of a Synthesizer object without explicitly invoking almost any of the synthesis API. For example, suppose you're playing a standard MIDI file. You load it into a Sequence object, which you play by having a sequencer send the data to the default synthesizer. The data in the sequence controls the synthesizer as intended, playing all the right notes at the right times.

However, there are cases when this simple scenario is inadequate. The sequence contains the right music, but the instruments sound all wrong! This unfortunate situation probably arose because the creator of the MIDI file had different instruments in mind than the ones that are currently loaded into the synthesizer.

The MIDI 1.0 Specification provides for bank-select and program-change commands, which affect which instrument is currently playing on each MIDI channel. However, the specification does not define what instrument should reside in each patch location (bank and program number). The more recent General MIDI specification addresses this problem by defining a bank containing 128 programs that correspond to specific instrument sounds. A General MIDI synthesizer uses 128 instruments that match this specified set. Different General MIDI synthesizers can sound quite different, even when playing what's supposed to be the same instrument. However, a MIDI file should for the most part sound similar (even if not identical), no matter which General MIDI synthesizer is playing it.

Nonetheless, not all creators of MIDI files want to be limited to the set of 128 timbres defined by General MIDI. This section shows how to change the instruments from the default set that the synthesizer comes with. (If there is no default, meaning that no instruments are loaded when you access the synthesizer, you'll have to use this API to start with in any case.)

Learning What Instruments Are Loaded

To learn whether the instruments currently loaded into the synthesizer are the ones you want, you can invoke this Synthesizer method:

Instrument[] getLoadedInstruments()
and iterate over the returned array to see exactly which instruments are currently loaded. Most likely, you would display the instruments' names in the user interface (using the getName method of Instrument), and let the user decide whether to use those instruments or load others. The Instrument API includes a method that reports which soundbank the instrument belongs to. The soundbank's name might help your program or the user ascertain exactly what the instrument is.

This Synthesizer method:

Soundbank getDefaultSoundbank()
gives you the default soundbank. The Soundbank API includes methods to retrieve the soundbank's name, vendor, and version number, by which the program or the user can verify the bank's identity. However, you can't assume when you first get a synthesizer that the instruments from the default soundbank have been loaded into the synthesizer. For example, a synthesizer might have a large assortment of built-in instruments available for use, but because of its limited memory it might not load them automatically.

Loading Different Instruments

The user might decide to load instruments that are different from the current ones (or you might make that decision programmatically). The following method tells you which instruments come with the synthesizer (versus having to be loaded from soundbank files):

Instrument[] getAvailableInstruments()
You can load any of these instruments by invoking:
boolean loadInstrument(Instrument instrument)
The instrument gets loaded into the synthesizer in the location specified by the instrument's Patch object (which can be retrieved using the getPatch method of Instrument).

To load instruments from other soundbanks, first invoke Synthesizer's isSupportedSoundbank method to make sure that the soundbank is compatible with this synthesizer (if it isn't, you can iterate over the system's synthesizers to try to find one that supports the soundbank). You can then invoke one of these methods to load instruments from the soundbank:

boolean loadAllInstruments(Soundbank soundbank)
boolean loadInstruments(Soundbank soundbank,
  Patch[] patchList)
As the names suggest, the first of these loads the entire set of instruments from a given soundbank, and the second loads selected instruments from the soundbank. You could also use Soundbank's getInstruments method to access all the instruments, then iterate over them and load selected instruments one at a time using loadInstrument.

It's not necessary for all the instruments you load to be from the same soundbank. You could use loadInstrument or loadInstruments to load certain instruments from one soundbank, another set from a different soundbank, and so on.

Each instrument has its own Patch object that specifies the location on the synthesizer where the instrument should be loaded. The location is defined by a bank number and a program number. There's no API to change the location by changing the patch's bank or program number.

However, it is possible to load an instrument into a location other than the one specified by its patch, using the following method of Synthesizer:

boolean remapInstrument(Instrument from, Instrument to)
This method unloads its first argument from the synthesizer, and places its second argument in whatever synthesizer patch location had been occupied by the first argument.

Unloading Instruments

Loading an instrument into a program location automatically unloads whatever instrument was already at that location, if any. You can also explicitly unload instruments without necessarily replacing them with new ones. Synthesizer includes three unloading methods that correspond to the three loading methods. If the synthesizer receives a program-change message that selects a program location where no instrument is currently loaded, there won't be any sound from the MIDI channel on which the program-change message was sent.

Accessing Soundbank Resources

Some synthesizers store other information besides instruments in their soundbanks. For example, a wavetable synthesizer stores audio samples that one or more instruments can access. Because the samples might be shared by multiple instruments, they're stored in the soundbank independently of any instrument. Both the Soundbank interface and the Instrument class provide a method call getSoundbankResources, which returns a list of SoundbankResource objects. The details of these objects are specific to the synthesizer for which the soundbank is designed. In the case of wavetable synthesis, a resource might be an object that encapsulates a series of audio samples, taken from one snippet of a sound recording. Synthesizers that use other synthesis techniques might store other kinds of objects in the synthesizer's SoundbankResources array.

Querying the Synthesizer's Capabilities and Current State

The Synthesizer interface includes methods that return information about the synthesizer's capabilities:

    public long getLatency()
    public int getMaxPolyphony()
The latency measures the worst-case delay between the time a MIDI message is delivered to the synthesizer and the time that the synthesizer actually produces the corresponding result. For example, it might take a synthesizer a few milliseconds to begin generating audio after receiving a note-on event.

The getMaxPolyphony method indicates how many notes the synthesizer can sound simultaneously, as discussed under "Voices" in the section "Understanding MIDI Synthesis" earlier in this chapter. As mentioned in the same discussion, a synthesizer can provide information about its voices. This is accomplished through the following method:

public VoiceStatus[] getVoiceStatus()
Each VoiceStatus in the returned array reports the voice's current active or inactive status, MIDI channel, bank and program number, MIDI note number, and MIDI volume. The array's length should normally be the same number returned by getMaxPolyphony. If the synthesizer isn't playing, all its VoiceStatus objects have their active field set to false.

You can learn additional information about the current status of a synthesizer by retrieving its MidiChannel objects and querying their state. This is discussed more in the next section.

Using Channels

Sometimes it's useful or necessary to access a synthesizer's MidiChannel objects directly. This section discusses such situations.

Controlling the Synthesizer without Using a Sequencer

When using a sequence, such as one read from a MIDI file, you don't need to send MIDI commands to the synthesizer yourself. Instead, you just load the sequence into a sequencer, connect the sequencer to the synthesizer, and let it run. The sequencer takes care of scheduling the events, and the result is a predictable musical performance. This scenario works fine when the desired music is known in advance, which is true when it's read from a file.

In some situations, however, the music is generated on the fly as it's playing. For example, the user interface might display a musical keyboard or a guitar fretboard and let the user play notes at will by clicking with the mouse. As another example, an application might use a synthesizer not to play music per se, but to generate sound effects in response to the user's actions. This scenario is typical of games. As a final example, the application might indeed be playing music that's read from a file, but the user interface allows the user to interact with the music, altering it dynamically. In all these cases, the application sends commands directly to the synthesizer, since the MIDI messages need to be delivered immediately, instead of being scheduled for some determinate point in the future.

There are at least two ways of sending a MIDI message to the synthesizer without using a sequencer. The first is to construct a MidiMessage and pass it to the synthesizer using the send method of Receiver. For example, to produce a Middle C (MIDI note number 60) on MIDI channel 5 (one-based) immediately, you could do the following:

    ShortMessage myMsg = new ShortMessage();
    // Play the note Middle C (60) moderately loud
    // (velocity = 93)on channel 4 (zero-based).
    myMsg.setMessage(ShortMessage.NOTE_ON, 4, 60, 93);
    Synthesizer synth = MidiSystem.getSynthesizer();
    Receiver synthRcvr = synth.getReceiver();
    synthRcvr.send(myMsg, -1); // -1 means no time stamp
The second way is to bypass the message-passing layer (that is, the MidiMessage and Receiver API) altogether, and interact with the synthesizer's MidiChannel objects directly. You first need to retrieve the synthesizer's MidiChannel objects, using the following Synthesizer method:
public MidiChannel[] getChannels()
after which you can invoke the desired MidiChannel methods directly. This is a more immediate route than sending the corresponding MidiMessages to the synthesizer's Receiver and letting the synthesizer handle the communication with its own MidiChannels. For example, the code corresponding to the preceding example would be:
    Synthesizer synth = MidiSystem.getSynthesizer();
    MidiChannel chan[] = synth.getChannels();
    // Check for null; maybe not all 16 channels exist.
    if (chan[4] != null) {
         chan[4].noteOn(60, 93);
    }

Getting a Channel's Current State

The MidiChannel interface provides methods that correspond one-to-one to each of the "channel voice" or "channel mode" messages defined by the MIDI specification. We saw one case with the use of the noteOn method in the previous example. However, in addition to these canonical methods, the Java Sound API's MidiChannel interface adds some "get" methods to retrieve the value most recently set by corresponding voice or mode "set" methods:

    int       getChannelPressure()
    int       getController(int controller)
    boolean   getMono()
    boolean   getOmni()
    int       getPitchBend()
    int       getPolyPressure(int noteNumber)
    int       getProgram()
These methods might be useful for displaying channel state to the user, or for deciding what values to send subsequently to the channel.

Muting and Soloing a Channel

The Java Sound API adds the notions of per-channel solo and mute, which are not required by the MIDI specification. These are similar to the solo and mute on the tracks of a MIDI sequence. (See "Muting or Soloing Individual Tracks in the Sequence" in Chapter 11, "Playing, Recording, and Editing MIDI Sequences.)"

If mute is on, this channel will not sound, but other channels are unaffected. If solo is on, this channel, and any other soloed channel, will sound (if it isn't muted), but no other channels will sound. A channel that is both soloed and muted will not sound. The MidiChannel API includes four methods:

    boolean      getMute()
    boolean      getSolo()
    void         setMute(boolean muteState)
    void         setSolo(boolean soloState)

Permission to Play Synthesized Sound

The audio produced by any installed MIDI synthesizer is typically routed through the sampled-audio system. If your program doesn't have permission to play audio, the synthesizer's sound won't be heard, and a security exception will be thrown. For more information on audio permissions, see "Permission to Use Audio Resources" in Chapter 3, "Accessing Audio System Resources."

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Chapter 13: Introduction to the Service Provider Interfaces

Note

For version 5.0, new constructors for AudioFormat, AudioFileFormat, and MidiFileFormat allow the description of more advanced formats.

What Are Services?

Services are units of sound-handling functionality that are automatically available when an application program makes use of an implementation of the Java Sound API. They consist of objects that do the work of reading, writing, mixing, processing, and converting audio and MIDI data. An implementation of the Java Sound API generally supplies a basic set of services, but mechanisms are also included in the API to support the development of new sound services by third-party developers (or by the vendor of the implementation itself). These new services can be "plugged into" an existing installed implementation to expand its functionality without requiring a new release. In the Java Sound API architecture, third-party services are integrated into the system in such a way that an application program's interface to them is the same as the interface to the "built-in" services. In some cases, application developers who use the javax.sound.sampled and javax.sound.midi packages might not even be aware that they are employing third-party services.

Examples of potential third-party, sampled-audio services include:

  • Sound file readers and writers
  • Converters that translate between different audio data formats
  • New audio mixers and input/output devices, whether implemented purely in software, or in hardware with a software interface
Third-party MIDI services might consist of:
  • MIDI file readers and writers
  • Readers for various types of soundbank files (which are often specific to particular synthesizers)
  • MIDI-controlled sound synthesizers, sequencers, and I/O ports, whether implemented purely in software, or in hardware with a software interface

How Services Work

The javax.sound.sampled and javax.sound.midi packages provide functionality to application developers who wish to include sound services in their application programs. These packages are for consumers of sound services, providing interfaces to get information about, control, and access audio and MIDI services. In addition, the Java Sound API also supplies two packages that define abstract classes to be used by providers of sound services: the javax.sound.sampled.spi and javax.sound.midi.spi packages.

Developers of new sound services implement concrete subclasses of the appropriate classes in the SPI packages. These subclasses, along with any additional classes required to support the new service, are placed in a JavaTM Archive (JAR) archive file with a description of the included service or services. When this JAR file is installed in the user's CLASSPATH, the runtime system automatically makes the new service available, extending the functionality of the JavaTM platform's runtime system.

Once the new service is installed, it can be accessed just like any previously installed service. Consumers of services can get information about the new service, or obtain instances of the new service class itself, by invoking methods of the AudioSystem and MidiSystem classes (in the javax.sound.sampled and javax.sound.midi packages, respectively) to return information about the new services, or to return instances of new or existing service classes themselves. Application programs need not—and should not—reference the classes in the SPI packages (and their subclasses) directly to make use of the installed services.

For example, suppose a hypothetical service provider called Acme Software, Inc. is interested in supplying a package that allows application programs to read a new format of sound file (but one whose audio data is in a standard data format). The SPI class AudioFileReader can be subclassed into a class called, say, AcmeAudioFileReader. In the new subclass, Acme would supply implementations of all the methods defined in AudioFileReader; in this case there are only two methods (with argument variants), getAudioFileFormat and getAudioInputStream. Then when an application program attempted to read a sound file that happened to be in Acme's file format, it would invoke methods of the AudioSystem class in javax.sound.sampled to access the file and information about it. The methods AudioSystem.getAudioInputStream and AudioSystem.getAudioFileFormat provide a standard API to read audio streams; with the AcmeAudioFileReader class installed, this interface is extended to support the new file type transparently. Application developers don't need direct access to the newly registered SPI classes: the AudioSystem object methods pass the query on to the installed AcmeAudioFileReader class.

What's the point of having these "factory" classes? Why not permit the application developer to get access directly to newly provided services? That is a possible approach, but having all management and instantiation of services pass through gatekeeper system objects shields the application developer from having to know anything about the identity of installed services. Application developers just use services of value to them, perhaps without even realizing it. At the same time this architecture permits service providers to effectively manage the available resources in their packages.

Often the use of new sound services is transparent to the application program. For example, imagine a situation where an application developer wants to read in a stream of audio from a file. Assuming that thePathName identifies an audio input file, the program does this:

    File theInFile = new File(thePathName);
    AudioInputStream theInStream = AudioSystem.getAudioInputStream(theInFile);
Behind the scenes, the AudioSystem determines what installed service can read the file and asks it to supply the audio data as an AudioInputStream object. The developer might not know or even care that the input audio file is in some new file format (such as Acme's), supported by installed third-party services. The program's first contact with the stream is through the AudioSystem object, and all its subsequent access to the stream and its properties are through the methods of AudioInputStream. Both of these are standard objects in the javax.sound.sampled API; the special handling that the new file format may require is completely hidden.

How Providers Prepare New Services

Service providers supply their new services in specially formatted JAR files, which are to be installed in a directory on the user's system where the Java runtime will find them. JAR files are archive files, each containing sets of files that might be organized in hierarchical directory structures within the archive. Details about the preparation of the class files that go into these archives are discussed in Chapters 14 and 15, which describe the specifics of the audio and MIDI SPI packages; here we'll just give an overview of the process of JAR file creation.

The JAR file for a new service or services should contain a class file for each service supported in the JAR file. Following the Java platform's convention, each class file has the name of the newly defined class, which is a concrete subclass of one of the abstract service provider classes. The JAR file also must include any supporting classes required by the new service implementation. So that the new service or services can be located by the runtime system's service provider mechanism, the JAR file must also contain special files (described below) that map the SPI class names to the new subclasses being defined.

To continue from our example above, say Acme Software, Inc. is distributing a package of new sampled-audio services. Let's suppose this package consists of two new services:

  • The AcmeAudioFileReader class, which was mentioned above, and which is a subclass of AudioFileReader
  • A subclass of AudioFileWriter called AcmeAudioFileWriter, which will write sound files in Acme's new format
Starting from an arbitrary directory—let's call it /devel—where we want to do the build, we create subdirectories and put the new class files in them, organized in such a manner as to give the desired pathname by which the new classes will be referenced:
    com/acme/AcmeAudioFileReader.class
    com/acme/AcmeAudioFileWriter.class
In addition, for each new SPI class being subclassed, we create a mapping file in a specially named directory META-INF/services. The name of the file is the name of the SPI class being subclassed, and the file contains the names of the new subclasses of that SPI abstract class.

We create the file

META-INF/services/javax.sound.sampled.spi.AudioFileReader, which consists of

    # Providers of sound file-reading services
    # (a comment line begins with a pound sign)
    com.acme.AcmeAudioFileReader

and also the file

META-INF/services/javax.sound.sampled.spi.AudioFileWriter, which consists of

   # Providers of sound file-writing services
    com.acme.AcmeAudioFileWriter

Now we run jar from any directory with the command line:

jar cvf acme.jar -C /devel .
The -C option causes jar to switch to the /devel directory, instead of using the directory in which the command is executed. The final period argument instructs jar to archive all the contents of that directory (namely, /devel), but not the directory itself.

This run will create the file acme.jar with the contents:

com/acme/AcmeAudioFileReader.class
com/acme/AcmeAudioFileWriter.class
META-INF/services/javax.sound.sampled.spi.AudioFileReader
META-INF/services/javax.sound.sampled.spi.AudioFileWriter
META-INF/Manifest.mf
The file Manifest.mf, which is generated by the jar utility itself, is a list of all the files contained in the archive.

How Users Install New Services

For end users (or system administrators) who wish to get access to a new service through their application programs, installation is simple. They place the provided JAR file in a directory in their CLASSPATH. Upon execution, the Java runtime will find the referenced classes when needed.

It's not an error to install more than one provider for the same service. For example, two different service providers might supply support for reading the same type of sound file. In such a case, the system arbitrarily chooses one of the providers. Users who care which provider is chosen should install only the desired one.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Chapter 14: Providing Sampled-Audio Services

As discussed in Chapter 13, "Introduction to the Service Provider Interfaces," the Java Sound API includes two packages, javax.sound.sampled.spi and javax.sound.midi.spi, that define abstract classes to be used by developers of sound services. By implementing and installing a subclass of one of these abstract classes, a service provider registers the new service, extending the functionality of the runtime system. The present chapter tells you how to go about using the javax.sound.sampled.spi package to provide new services for handling sampled audio.

This chapter can be safely skipped by application programmers who merely wish to use existing audio services in their programs. For the use of the installed audio services in an application program, see Part I, "Sampled Audio," of this Programmer's Guide. This chapter assumes that the reader is familiar with the JavaTM Sound API methods that application programs invoke to access installed audio services.

Introduction

There are four abstract classes in the javax.sound.sampled.spi package, representing four different types of services that you can provide for the sampled-audio system:

  • AudioFileWriter provides sound file-writing services. These services make it possible for an application program to write a stream of audio data to a file of a particular type.
  • AudioFileReader provides file-reading services. These services enable an application program to ascertain a sound file's characteristics, and to obtain a stream from which the file's audio data can be read.
  • FormatConversionProvider provides services for converting audio data formats. These services allow an application program to translate audio streams from one data format to another.
  • MixerProvider provides management of a particular kind of mixer. This mechanism allows an application program to obtain information about, and access instances of, a given kind of mixer.

To recapitulate the discussion in Chapter 13, service providers can extend the functionality of the runtime system. A typical SPI class has two types of methods: ones that respond to queries about the types of services available from a particular provider, and ones that either perform the new service directly, or return instances of objects that actually provide the service. The runtime environment's service-provider mechanism provides registration of installed services with the audio system, and management of the new service provider classes.

In essence there is a double isolation of the service instances from the application developer. An application program never directly creates instances of the service objects, such as mixers or format converters, that it needs for its audio processing tasks. Nor does the program even directly request these objects from the SPI classes that administer them. The application program makes requests to the AudioSystem object in the javax.sound.sampled package, and AudioSystem in turn uses the SPI objects to process these queries and service requests.

The existence of new audio services might be completely transparent to both the user and the application programmer. All application references are through standard objects of the javax.sound.sampled package, primarily AudioSystem, and the special handling that new services might be providing is often completely hidden.

In this chapter, we'll continue the previous chapter's convention of referring to new SPI subclasses by names like AcmeMixer and AcmeMixerProvider.

Providing Audio File-Writing Services

Let's start with AudioFileWriter, one of the simpler SPI classes.

A subclass that implements the methods of AudioFileWriter must provide implementations of a set of methods to handle queries about the file formats and file types supported by the class, as well as provide methods that actually write out a supplied audio data stream to a File or OutputStream.

AudioFileWriter includes two methods that have concrete implementations in the base class:

boolean isFileTypeSupported(AudioFileFormat.Type fileType)
boolean isFileTypeSupported(AudioFileFormat.Type fileType,
    AudioInputStream stream)
The first of these methods informs the caller whether this file writer can write sound files of the specified type. This method is a general inquiry, it will return true if the file writer can write that kind of file, assuming the file writer is handed appropriate audio data. However, the ability to write a file can depend on the format of the specific audio data that's handed to the file writer. A file writer might not support every audio data format, or the constraint might be imposed by the file format itself. (Not all kinds of audio data can be written to all kinds of sound files.) The second method is more specific, then, asking whether a particular AudioInputStream can be written to a particular type of file.

Generally, you won't need to override these two concrete methods. Each is simply a wrapper that invokes one of two other query methods and iterates over the results returned. These other two query methods are abstract and therefore need to be implemented in the subclass:

abstract AudioFileFormat.Type[] getAudioFileTypes()
abstract AudioFileFormat.Type[]
    getAudioFileTypes(AudioInputStream stream)
These methods correspond directly to the previous two. Each returns an array of all the supported file types-all that are supported in general, in the case of the first method, and all that are supported for a specific audio stream, in the case of the second method. A typical implementation of the first method might simply return an array that the file writer's constructor initializes. An implementation of the second method might test the stream's AudioFormat object to see whether it's a data format that the requested type of file supports.

The final two methods of AudioFileWriter do the actual file-writing work:

abstract  int write(AudioInputStream stream,
    AudioFileFormat.Type fileType, java.io.File out)
 abstract  int write(AudioInputStream stream,
    AudioFileFormat.Type fileType, java.io.OutputStream out)
These methods write a stream of bytes representing the audio data to the stream or file specified by the third argument. The details of how this is done depend on the structure of the specified type of file. The write method must write the file's header and the audio data in the manner prescribed for sound files of this format (whether it's a standard type of sound file or a new, possibly proprietary one).

Providing Audio File-Reading Services

The AudioFileReader class consists of six abstract methods that your subclass needs to implement-actually, two different overloaded methods, each of which can take a File, URL, or InputStream argument. The first of these overloaded methods accepts queries about the file format of a specified file:

abstract AudioFileFormat getAudioFileFormat(
    java.io.File file)
abstract AudioFileFormat getAudioFileFormat(
    java.io.InputStream stream)
abstract AudioFileFormat getAudioFileFormat(
    java.net.URL url)
A typical implementation of getAudioFileFormat method reads and parses the sound file's header to ascertain its file format. See the description of the AudioFileFormat class to see what fields need to be read from the header, and refer to the specification for the particular file type to figure out how to parse the header.

Because the caller providing a stream as an argument to this method expects the stream to be unaltered by the method, the file reader should generally start by marking the stream. After reading to the end of the header, it should reset the stream to its original position.

The other overloaded AudioFileReader method provides file-reading services, by returning an AudioInputStream from which the file's audio data can be read:

abstract AudioInputStream getAudioInputStream(
    java.io.File file)
abstract AudioInputStream getAudioInputStream(
     java.io.InputStream stream)
abstract AudioInputStream getAudioInputStream(
     java.net.URL url)
Typically, an implementation of getAudioInputStream returns an AudioInputStream wound to the beginning of the file's data chunk (after the header), ready for reading. It would be conceivable, though, for a file reader to return an AudioInputStream whose audio format represents a stream of data that is in some way decoded from what is contained in the file. The important thing is that the method return a formatted stream from which the audio data contained in the file can be read. The AudioFormat encapsulated in the returned AudioInputStream object will inform the caller about the stream's data format, which is usually, but not necessarily, the same as the data format in the file itself.

Generally, the returned stream is an instance of AudioInputStream; it's unlikely you would ever need to subclass AudioInputStream.

Providing Format-Conversion Services

A FormatConversionProvider subclass transforms an AudioInputStream that has one audio data format into one that has another format. The former (input) stream is referred to as the source stream, and the latter (output) stream is referred to as the target stream. Recall from Chapter 2, "Overview of the Sampled Package," that an AudioInputStream contains an AudioFormat, and the AudioFormat in turn contains a particular type of data encoding, represented by an AudioFormat.Encoding object. The format and encoding in the source stream are called the source format and source encoding, and those in the target stream are likewise called the target format and target encoding.

The work of conversion is performed in the overloaded abstract method of FormatConversionProvider called getAudioInputStream. The class also has abstract query methods for learning about all the supported target and source formats and encodings. There are concrete wrapper methods for querying about a specific conversion.

The two variants of getAudioInputStream are:

abstract AudioInputStream getAudioInputStream(
    AudioFormat.Encoding targetEncoding,
    AudioInputStream sourceStream)
and
abstract AudioInputStream getAudioInputStream(
    AudioFormat targetFormat,
    AudioInputStream sourceStream)
These differ in the first argument, according to whether the caller is specifying a complete target format or just the format's encoding.

A typical implementation of getAudioInputStream works by returning a new subclass of AudioInputStream that wraps around the original (source) AudioInputStream and applies a data format conversion to its data whenever a read method is invoked. For example, consider the case of a new FormatConversionProvider subclass called AcmeCodec, which works with a new AudioInputStream subclass called AcmeCodecStream.

The implementation of AcmeCodec's second getAudioInputStream method might be:

public AudioInputStream getAudioInputStream
      (AudioFormat outputFormat, AudioInputStream stream) {
        AudioInputStream cs = null;
        AudioFormat inputFormat = stream.getFormat();
        if (inputFormat.matches(outputFormat) ) {
            cs = stream;
        } else {
            cs = (AudioInputStream)
                (new AcmeCodecStream(stream, outputFormat));
            tempBuffer = new byte[tempBufferSize];
        }
        return cs;
    }
The actual format conversion takes place in new read methods of the returned AcmeCodecStream, a subclass of AudioInputStream. Again, application programs that access this returned AcmeCodecStream simply operate on it as an AudioInputStream, and don't need to know the details of its implementation.

The other methods of a FormatConversionProvider all permit queries about the input and output encodings and formats that the object supports. The following four methods, being abstract, need to be implemented:

abstract AudioFormat.Encoding[] getSourceEncodings()
abstract AudioFormat.Encoding[] getTargetEncodings()
abstract AudioFormat.Encoding[] getTargetEncodings(
    AudioFormat sourceFormat)
abstract  AudioFormat[] getTargetFormats(
    AudioFormat.Encoding targetEncoding,
    AudioFormat sourceFormat)

As in the query methods of the AudioFileReader class discussed above, these queries are typically handled by checking private data of the object and, for the latter two methods, comparing them against the argument(s).

The remaining four FormatConversionProvider methods are concrete and generally don't need to be overridden:

boolean isConversionSupported(
    AudioFormat.Encoding targetEncoding,
    AudioFormat sourceFormat)
boolean isConversionSupported(AudioFormat targetFormat,
    AudioFormat sourceFormat)
boolean isSourceEncodingSupported(
    AudioFormat.Encoding sourceEncoding)
boolean isTargetEncodingSupported(
    AudioFormat.Encoding targetEncoding)
As with AudioFileWriter.isFileTypeSupported(), the default implementation of each of these methods is essentially a wrapper that invokes one of the other query methods and iterates over the results returned.

Providing New Types of Mixers

As its name implies, a MixerProvider supplies instances of mixers. Each concrete MixerProvider subclass acts as a factory for the Mixer objects used by an application program. Of course, defining a new MixerProvider only makes sense if one or more new implementations of the Mixer interface are also defined. As in the FormatConversionProvider example above, where our getAudioInputStream method returned a subclass of AudioInputStream that performed the conversion, our new class AcmeMixerProvider has a method getMixer that returns an instance of another new class that implements the Mixer interface. We'll call the latter class AcmeMixer. Particularly if the mixer is implemented in hardware, the provider might support only one static instance of the requested device. If so, it should return this static instance in response to each invocation of getMixer.

Since AcmeMixer supports the Mixer interface, application programs don't require any additional information to access its basic functionality. However, if AcmeMixer supports functionality not defined in the Mixer interface, and the vendor wants to make this extended functionality accessible to application programs, the mixer should of course be defined as a public class with additional, well-documented public methods, so that a program that wishes to make use of this extended functionality can import AcmeMixer and cast the object returned by getMixer to this type.

The other two methods of MixerProvider are:

abstract Mixer.Info[] getMixerInfo()
and
boolean isMixerSupported(Mixer.Info info)
These methods allow the audio system to determine whether this particular provider class can produce a device that an application program needs. In other words, the AudioSystem object can iterate over all the installed MixerProviders to see which ones, if any, can supply the device that the application program has requested of the AudioSystem. (See the discussion under "Getting a Mixer" in Chapter 3, "Accessing Audio System Resources.") The getMixerInfo method returns an array of objects containing information about the kinds of mixer available from this provider object. The system can pass these information objects, along with those from other providers, to an application program.

A single MixerProvider can provide more than one kind of mixer. When the system invokes the MixerProvider's getMixerInfo method, it gets a list of information objects identifying the different kinds of mixer that this provider supports. The system can then invoke MixerProvider.getMixer(Mixer.Info) to obtain each mixer of interest.

Your subclass needs to implement getMixerInfo, as it's abstract. The isMixerSupported method is concrete and doesn't generally need to be overridden. The default implementation simply compares the provided Mixer.Info to each one in the array returned by getMixerInfo.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Chapter 15: Providing MIDI Services

Chapter 13, "Introduction to the Service Provider Interfaces," explained that the javax.sound.sampled.spi and javax.sound.midi.spi packages define abstract classes to be used by developers of sound services. By implementing a subclass of one of these abstract classes, a service provider can create a new service that extends the functionality of the runtime system. Chapter 14 covered the use of the javax.sound.sampled.spi package. The present chapter discusses how to use the javax.sound.midi.spi package to provide new services for handling MIDI devices and files.

Applications programmers who only use existing MIDI services in their programs can safely skip this chapter. For an overview of MIDI and the use of the installed MIDI services in an application program, see Part II, "MIDI," of this Programmer's Guide. This chapter assumes that the reader is familiar with the Java Sound API methods that application programs invoke to access installed MIDI services.

Introduction

There are four abstract classes in the javax.sound.midi.spi package, which represent four different types of services that you can provide for the MIDI system:

  • MidiFileWriter provides MIDI file-writing services. These services make it possible for an application program to save, to a MIDI file, a MIDI Sequence that it has generated or processed.
  • MidiFileReader provides file-reading services that return a MIDI Sequence from a MIDI file for use in an application program.
  • MidiDeviceProvider supplies instances of one or more specific types of MIDI device, possibly including hardware devices.
  • SoundbankReader supplies soundbank file-reading services. Concrete subclasses of SoundbankReader parse a given soundbank file, producing a Soundbank object that can be loaded into a Synthesizer.

An application program will not directly create an instance of a service object—whether a provider object, such as a MidiDeviceProvider, or an object, such as a Synthesizer, that is supplied by the provider object. Nor will the program directly refer to the SPI classes. Instead, the application program makes requests to the MidiSystem object in the javax.sound.midi package, and MidiSystem in turn uses concrete subclasses of the javax.sound.midi.spi classes to process these requests.

Providing MIDI File-Writing Services

There are three standard MIDI file formats, all of which an implementation of the Java Sound API can support: Type 0, Type 1, and Type 2. These file formats differ in their internal representation of the MIDI sequence data in the file, and are appropriate for different kinds of sequences. If an implementation doesn't itself support all three types, a service provider can supply the support for the unimplemented ones. There are also variants of the standard MIDI file formats, some of them proprietary, which similarly could be supported by a third-party vendor.

The ability to write MIDI files is provided by concrete subclasses of MidiFileWriter. This abstract class is directly analogous to javax.sampled.spi.AudioFileWriter. Again, the methods are grouped into query methods for learning what types of files can be written, and methods for actually writing a file. As with AudioFileWriter, two of the query methods are concrete:

boolean isFileTypeSupported(int fileType)
boolean isFileTypeSupported(int fileType, Sequence sequence)
The first of these provides general information about whether the file writer can ever write the specified type of MIDI file type. The second method is more specific: it asks whether a particular Sequence can be written to the specified type of MIDI file. Generally, you don't need to override either of these two concrete methods. In the default implementation, each invokes one of two other corresponding query methods and iterates over the results returned. Being abstract, these other two query methods need to be implemented in the subclass:
abstract int[] getMidiFileTypes()
abstract int[] getMidiFileTypes(Sequence sequence)
The first of these returns an array of all the file types that are supported in general. A typical implementation might initialize the array in the file writer's constructor and return the array from this method. From that set of file types, the second method finds the subset to which the file writer can write the given Sequence. In accordance with the MIDI specification, not all types of sequences can be written to all types of MIDI files.

The write methods of a MidiFileWriter subclass perform the encoding of the data in a given Sequence into the correct data format for the requested type of MIDI file, writing the coded stream to either a file or an output stream:

abstract int write(Sequence in, int fileType,
                   java.io.File out)
abstract int write(Sequence in, int fileType,
                   java.io.OutputStream out)
To do this, the write method must parse the Sequence by iterating over its tracks, construct an appropriate file header, and write the header and tracks to the output. The MIDI file's header format is, of course, defined by the MIDI specification. It includes such information as a "magic number" identifying this as a MIDI file, the header's length, the number of tracks, and the sequence's timing information (division type and resolution). The rest of the MIDI file consists of the track data, in the format defined by the MIDI specification.

Let's briefly look at how the application program, MIDI system, and service provider cooperate in writing a MIDI file. In a typical situation, an application program has a particular MIDI Sequence to save to a file. The program queries the MidiSystem object to see what MIDI file formats, if any, are supported for the particular Sequence at hand, before attempting to write the file. The MidiSystem.getMidiFileTypes(Sequence) method returns an array of all the MIDI file types to which the system can write a particular sequence. It does this by invoking the corresponding getMidiFileTypes method for each of the installed MidiFileWriter services, and collecting and returning the results in an array of integers that can be thought of as a master list of all file types compatible with the given Sequence. When it comes to writing the Sequence to a file, the call to MidiSystem.write is passed an integer representing a file type, along with the Sequence to be written and the output file; MidiSystem uses the supplied type to decide which installed MidiFileWriter should handle the write request, and dispatches a corresponding write to the appropriate MidiFileWriter.

Providing MIDI File-Reading Services

The MidiFileReader abstract class is directly analogous to javax.sampled.spi.AudioFileReader class. Both consist of two overloaded methods, each of which can take a File, URL, or InputStream argument. The first of the overloaded methods returns the file format of a specified file. In the case of MidiFileReader, the API is:

abstract MidiFileFormat getMidiFileFormat(java.io.File file)
abstract MidiFileFormat getMidiFileFormat(
    java.io.InputStream stream)
abstract MidiFileFormat getMidiFileFormat(java.net.URL url)
Concrete subclasses must implement these methods to return a filled-out MidiFileFormat object describing the format of the specified MIDI file (or stream or URL), assuming that the file is of a type supported by the file reader and that it contains valid header information. Otherwise, an InvalidMidiDataException should be thrown.

The other overloaded method returns a MIDI Sequence from a given file, stream, or URL :

abstract Sequence getSequence(java.io.File file)
abstract Sequence getSequence(java.io.InputStream stream)
abstract Sequence getSequence(java.net.URL url)
The getSequence method performs the actual work of parsing the bytes in the MIDI input file and constructing a corresponding Sequence object. This is essentially the inverse of the process used by MidiFileWriter.write. Because there is a one-to-one correspondence between the contents of a MIDI file as defined by the MIDI specification and a Sequence object as defined by the Java Sound API, the details of the parsing are straightforward. If the file passed to getSequence contains data that the file reader can't parse (for example, because the file has been corrupted or doesn't conform to the MIDI specification), an InvalidMidiDataException should be thrown.

Providing Particular MIDI Devices

A MidiDeviceProvider can be considered a factory that supplies one or more particular types of MIDI device. The class consists of a method that returns an instance of a MIDI device, as well as query methods to learn what kinds of devices this provider can supply.

As with the other javax.sound.midi.spi services, application developers get indirect access to a MidiDeviceProvider service through a call to MidiSystem methods, in this case MidiSystem.getMidiDevice and MidiSystem.getMidiDeviceInfo. The purpose of subclassing MidiDeviceProvider is to supply a new kind of device, so the service developer must also create an accompanying class for the device being returned—just as we saw with MixerProvider in the javax.sound.sampled.spi package. There, the returned device's class implemented the javax.sound.sampled.Mixer interface; here it implements the javax.sound.midi.MidiDevice interface. It might also implement a subinterface of MidiDevice, such as Synthesizer or Sequencer.

Because a single subclass of MidiDeviceProvider can provide more than one type of MidiDevice, the getDeviceInfo method of the class returns an array of MidiDevice.Info objects enumerating the different MidiDevices available:

abstract MidiDevice.Info[] getDeviceInfo()

The returned array can contain a single element, of course. A typical implementation of the provider might initialize an array in its constructor and return it here. This allows MidiSystem to iterate over all installed MidiDeviceProviders to construct a list of all installed devices. MidiSystem can then return this list (MidiDevice.Info[] array) to an application program.

MidiDeviceProvider also includes a concrete query method:

boolean isDeviceSupported(MidiDevice.Info info)
This method permits the system to query the provider about a specific kind of device. Generally, you don't need to override this convenience method. The default implementation iterates over the array returned by getDeviceInfo and compares the argument to each element.

The third and final MidiDeviceProvider method returns the requested device:

abstract MidiDevice getDevice(MidiDevice.Info info)
This method should first test the argument to make sure it describes a device that this provider can supply. If it doesn't, it should throw an IllegalArgumentException. Otherwise, it returns the device.

Providing Soundbank File-Reading Services

A SoundBank is a set of Instruments that can be loaded into a Synthesizer. An Instrument is an implementation of a sound-synthesis algorithm that produces a particular sort of sound, and includes accompanying name and information strings. A SoundBank roughly corresponds to a bank in the MIDI specification, but it's a more extensive and addressable collection; it can perhaps better be thought of as a collection of MIDI banks. (For more background information on SoundBanks and Synthesizers, see Chapter 12, "Synthesizing Sound.")

SoundbankReader consists of a single overloaded method, which the system invokes to read a Soundbank object from a soundbank file:

abstract Soundbank getSoundbank(java.io.File file)
abstract Soundbank getSoundbank(java.io.InputStream stream)
abstract Soundbank getSoundbank(java.net.URL url)

Concrete subclasses of SoundbankReader will work in tandem with particular provider-defined implementations of SoundBank, Instrument, and Synthesizer to allow the system to load a SoundBank from a file into an instance of a particular Synthesizer class. Synthesis techniques may differ wildly from one Synthesizer to another, and, as a consequence, the data stored in an Instrument or SoundBank providing control or specification data for the synthesis process of a Synthesizer can take a variety of forms. One synthesis technique may require only a few bytes of parameter data; another may be based on extensive sound samples. The resources present in a SoundBank will depend upon the nature of the Synthesizer into which they get loaded, and therefore the implementation of the getSoundbank method of a SoundbankReader subclass has access to knowledge of a particular kind of SoundBank. In addition, a particular subclass of SoundbankReader understands a particular file format for storing the SoundBank data. That file format may be vendor-specific and proprietary.

SoundBank is just an interface, with only weak constraints on the contents of a SoundBank object. The methods an object must support to implement this interface (getResources, getInstruments, getVendor, getName, etc.) impose loose requirements on the data that the object contains. For example, getResources and getInstruments can return empty arrays. The actual contents of a subclassed SoundBank object, in particular its instruments and its non-instrument resources, are defined by the service provider. Thus, the mechanism of parsing a soundbank file depends entirely on the specification of that particular kind of soundbank file.

Soundbank files are created outside the Java Sound API, typically by the vendor of the synthesizer that can load that kind of soundbank. Some vendors might supply end-user tools for creating such files.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface org.w3c.dom.CharacterData (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.CharacterData

  • Packages that use CharacterData
    Package Description
    org.w3c.dom
    Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.

    • Uses of CharacterData in org.w3c.dom

      Subinterfaces of CharacterData in org.w3c.dom
      Modifier and Type Interface and Description
      interface  CDATASection
      CDATA sections are used to escape blocks of text containing characters that would otherwise be regarded as markup.
      interface  Comment
      This interface inherits from CharacterData and represents the content of a comment, i.e., all the characters between the starting ' <!--' and ending '-->'.
      interface  Text
      The Text interface inherits from CharacterData and represents the textual content (termed character data in XML) of an Element or Attr.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.CharType (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.CharType

No usage of com.sun.jdi.CharType
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.CharValue (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.CharValue

  • Packages that use CharValue
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of CharValue in com.sun.jdi

      Methods in com.sun.jdi that return CharValue
      Modifier and Type Method and Description
      CharValue VirtualMachine.mirrorOf(char value)
      Creates a CharValue for the given value.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


City Input Method

Contents

  1. About City Input Method
  2. Installing and Selecting the Input Method
  3. Using the Input Method for the First Time
  4. Using the Input Method
  5. Controlling the Status Window
  6. Supported Cities and Locales

1. About City Input Method

City Input Method is a simple input method that lets users enter city names by just typing a three-character airport code and converting it to a corresponding city name. If the user enters more than one airport code (up to three at a time are possible), the input method creates a short phrase such as "From San Francisco to Beijing via Tokyo". For each city, the input method knows the city names and phrases in a number of different languages (or, more precisely, locales). City names and phrases in all supported languages can be freely mixed in any input operation. The input method can be used to enter text into any text component that supports input methods, such as a Swing text component.

2. Installing and Selecting the Input Method

To make the input method available to applications, its jar file must be installed into the extensions directory of a Java 2 runtime environment. After launching a Java application with a text component that supports input methods, the input method can be selected using the input method selection user interface provided by the runtime environment. First, make sure that a text component has the focus - typically, the text component indicates this by showing an insertion point. Then, for Sun's Java 2 Runtime Environment, choose the "Select Input Method" menu from the menu that can be pulled down from the top left corner of the window (the System menu on Windows, Window menu on Solaris), then choose "City Input Method" and the desired locale from the popup menu. Note that correct text display in some languages depends on the font configuration, so you may want to pick the locale of the host operating system or a language that is supported by most fonts, such as English or German.

3. Using the Input Method for the First Time

After selecting the input method, type "SFO", the code for San Francisco International Airport. You will see that the text is input into the text component, but highlighted to indicate that it is still being composed (for Sun's Java 2 Runtime Environment, the text is inverted on Solaris, underlined on Windows). Then type a Space character to start conversion. You will see that the airport code is replaced with the name of San Francisco in the language that you selected. The text is still highlighted, although the highlight may now look somewhat different. Type Space again. A lookup window opens, which shows the city name in all available languages, with the originally displayed name selected. Continue typing Space. You will see that the selection cycles through all the names, and that the selected name is also shown in the text component. Type Return. The lookup window disappears, and the most recently selected name is now shown in the text component without any highlight - it is committed.

4. Using the Input Method

Entering Raw Text

Raw text is any text that is entered through the input method, but hasn't been converted yet. From the moment you type the first character of an airport until you start conversion the input method is in raw text mode. In this mode, letters from "a" to "z" or their uppercase variants (the input method is case insensitive) are added to the raw text input. You can use backspace to delete a character, and you can click into the text using the mouse to move the insertion point.

Converting to City Names

You can start the conversion process from airport codes to city names when the raw text includes one, two, or three airport codes - that is, three, six, or nine characters. To start conversion, type Space. A single airport code is converted to just a city name. Two or three airport codes are converted to phrases such as "From San Francisco to Frankfurt" for two codes or "From San Francisco to Frankfurt via Chicago" for three codes. Each city name is considered a separate segment. One of the segments is selected, that is, it can be further converted using the lookup window. If there are multiple segments, the segment selection can be changed by clicking into a segment or by using the Arrow Right and Arrow Left keys.

Continuing Conversion Using the Lookup Window

The lookup window is a temporary window that shows the city names in all available languages for the airport code of the selected segment, and lets the user choose a different name. To show the window, select a segment, then type Space. The window opens just below or, if there's not enough space, in another location near the segment's text. The currently selected city name is outlined. To change the name selection, type Space, Arrow Down, or Arrow Up to cycle through all available names. To confirm a selected name, you usually commit as described in the next section. To select a name and close the lookup window without committing, type the number in front of the desired name.

Committing the Input

Committing the input text means to end input method processing of it, and make it a normal part of the text component's text body. All input method highlighting is removed from committed text. You can commit the entire input text at any time by typing Return. If you entered more than one airport code and have started conversion, you can also perform a partial commit: typing Control-Arrow Down commits the text up to the currently selected segment, but leaves following segments available for further conversion.

Conversion is requested using the Space character. During conversion, the input method first offers the city name in the selected language (if that name is available). If the user does not accept this selection, a second step brings up a choice window that offers all available names for the city, with the corresponding locale name.

5. Controlling the Status Window

The input method provides a little status window that shows the currently selected locale. Initially this window is positioned near the lower right corner of the screen, but it can be moved to a different location. To request that the status window automatically positions itself below the window containing the currently focussed text component, double-click into the status window's content area.

6. Supported Cities and Locales

The input method's knowledge of the world is limited - airport codes it knows include: SFO, NYC, JFK, LGA, ORD, FRA, MUC, TYO, NRT, HND, KIX, ITM, PEK, BJS, SHA, HKG, TPE. It currently supports the following languages: English, German, Japanese (normal and yomi), Simplified Chinese, Traditional Chinese.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Multithreaded Custom Class Loaders in Java SE 7

The Java SE 7 release contains an important enhancement for multithreaded custom class loaders. In previous releases, certain types of custom class loaders were prone to deadlock. The Java SE 7 release modifies the locking mechanism to avoid deadlock.

Background

The function of a java.lang.ClassLoader is to locate the bytecode for a particular class, then transform that bytecode into a usable class in the runtime system. The runtime system provides class loaders that can locate bootstrap classes, extension classes, and user classes. The CLASSPATH environment variable is one way to indicate to the runtime system where the bytecode is located.

Knowing about the CLASSPATH environment variable is all you may need to know about class loading. In some specific situations, however, customizing the behavior of a class loader by creating your own subclass may be necessary.

Custom class loaders will not run into deadlocks if they adhere to an acyclic class loader delegation model. Acyclic delegation is what the architects of ClassLoader envisioned. In this model, every class loader has a parent (delegate). When a class is requested, the class loader first checks if the class was loaded previously. If the class is not found, the class loader asks its parent to locate the class. If the parent cannot find the class, the class loader attempts to locate the class itself.

Deadlock Scenario

In earlier releases of the Java platform, multithreaded custom class loaders could deadlock when they did not have an acyclic delegation model. Here is one example:

Class Hierarchy:
  class A extends B
  class C extends D

ClassLoader Delegation Hierarchy:

Custom Classloader CL1:
  directly loads class A
  delegates to custom ClassLoader CL2 for class B

Custom Classloader CL2:
  directly loads class C
  delegates to custom ClassLoader CL1 for class D

Thread 1:
  Use CL1 to load class A (locks CL1)
    defineClass A triggers
      loadClass B (try to lock CL2)

Thread 2:
  Use CL2 to load class C (locks CL2)
    defineClass C triggers
      loadClass D (try to lock CL1)

Synchronization in the ClassLoader class was previously heavy-handed, or in technical terms, not sufficiently granular. A request to load a class synchronized on the entire ClassLoader object, which made it prone to deadlock.

Class Loader Synchronization in the Java SE 7 Release

The Java SE 7 release includes the concept of a parallel capable class loader. Loading a class by a parallel capable class loader now synchronizes on the pair consisting of the class loader and the class name.

In the previous scenario, using the Java SE 7 release, the threads are no longer deadlocked, and all classes are loaded successfully:

Thread 1:
  Use CL1 to load class A (locks CL1+A)
    defineClass A triggers
      loadClass B (locks CL2+B)

Thread 2:
  Use CL2 to load class C (locks CL2+C)
    defineClass C triggers
      loadClass D (locks CL1+D)

Recommendations for Multithreaded Custom Class Loaders

Custom class loaders that do not have a history of deadlocks do not require any changes. In particular, you do not need to change custom class loaders that follow the recommended acyclic hierarchical delegation model, that is, delegating first to their parent class. For backward compatibility, the Java SE 7 release continues to lock a class loader object unless it registers as parallel capable.

To create new custom class loaders, the process is similar in the Java SE 7 release as in previous releases. Create a subclass of ClassLoader, then override the findClass() method and possibly loadClass(). Overriding loadClass() makes your life more difficult, but it is the only way to use a different delegation model.

If you have a custom class loader with a risk of deadlocking, with the Java SE 7 release, you can avoid deadlocks by following these rules:

  1. Ensure that your custom class loader is multithread safe for concurrent class loading.
    1. Decide upon an internal locking scheme. For example, java.lang.ClassLoader uses a locking scheme based on the requested class name.
    2. Remove all synchronization on the class loader object lock alone.
    3. Ensure that critical sections are safe for multiple threads loading different classes.
  2. In your custom class loader's static initializer, invoke java.lang.ClassLoader's static method registerAsParallelCapable(). This registration indicates that all instances of your custom class loader are multithread safe.
  3. Check that all class loader classes that this custom class loader extends also invoke the registerAsParallelCapable() method in their class initializers. Ensure that they are multithread safe for concurrent class loading.

If your custom class loader overrides only findClass(String), you do not need further changes. This is the recommended mechanism to create a custom class loader.

If your custom class loader overrides either the protected loadClass(String, boolean) method or the public loadClass(String) method, you must also ensure that the protected defineClass() method is called only once for each class loader and class name pair.

Troubleshooting

If your product ships and appears to have problems due to incomplete handling of critical sections, you can use a new VM flag -XX:+AlwaysLockClassLoader. This flag reverts to locking the class loader lock before invoking your custom class loader's findClass() or loadClass() method, even for class loaders that register as parallel capable.

References

Class Loader API Modifications for Deadlock Fix at OpenJDK

Bug Database Bug 4670071 Detail

Internals of Java Class Loading, Binildas Christudas, O'Reilly Media onJava.com

Demystifying class loading problems, Part 4: Deadlocks and constraints, Simon Burns and Lakshmi Shankar, IBM developerWorks

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Object Serialization Specification: 4 - Class Descriptors

CONTENTS | PREV | NEXT Java Object Serialization Specification
version 6.0

Class Descriptors

CHAPTER 4

Topics:
  • The ObjectStreamClass Class
  • Dynamic Proxy Class Descriptors
  • Serialized Form
  • The ObjectStreamField Class
  • Inspecting Serializable Classes
  • Stream Unique Identifiers

4.1 The ObjectStreamClass Class

The ObjectStreamClass provides information about classes that are saved in a Serialization stream. The descriptor provides the fully-qualified name of the class and its serialization version UID. A SerialVersionUID identifies the unique original class version for which this class is capable of writing streams and from which it can read.

package java.io;

public class ObjectStreamClass
{
    public static ObjectStreamClass lookup(Class cl);

        public static ObjectStreamClass lookupAny(Class cl);

    public String getName();

    public Class forClass();

    public ObjectStreamField[] getFields();

    public long getSerialVersionUID();

    public String toString();
}
The lookup method returns the ObjectStreamClass descriptor for the specified class in the virtual machine. If the class has defined serialVersionUID it is retrieved from the class. If the serialVersionUID is not defined by the class, it is computed from the definition of the class in the virtual machine. If the specified class is not serializable or externalizable, null is returned.

The lookupAny method behaves like the lookup method, except that it returns the descriptor for any class, regardless of whether it implements Serializable. The serialVersionUID of a class that does not implement Serializable is 0L.

The getName method returns the name of the class, in the same format that is used by the Class.getName method.

The forClass method returns the Class in the local virtual machine if one was found by ObjectInputStream.resolveClass method. Otherwise, it returns null.

The getFields method returns an array of ObjectStreamField objects that represent the serializable fields of this class.

The getSerialVersionUID method returns the serialVersionUID of this class. Refer to Section 4.6, "Stream Unique Identifiers." If not specified by the class, the value returned is a hash computed from the class's name, interfaces, methods, and fields using the Secure Hash Algorithm (SHA) as defined by the National Institute of Standards.

The toString method returns a printable representation of the class descriptor including the name of the class and the serialVersionUID.

4.2 Dynamic Proxy Class Descriptors

ObjectStreamClass descriptors are also used to provide information about dynamic proxy classes (e.g., classes obtained via calls to the getProxyClass method of java.lang.reflect.Proxy) saved in a serialization stream. A dynamic proxy class itself has no serializable fields and a serialVersionUID of 0L. In other words, when the Class object for a dynamic proxy class is passed to the static lookup method of ObjectStreamClass, the returned ObjectStreamClass instance will have the following properties:

  • Invoking its getSerialVersionUID method will return 0L.
  • Invoking its getFields method will return an array of length zero.
  • Invoking its getField method with any String argument will return null.

4.3 Serialized Form

The serialized form of an ObjectStreamClass instance depends on whether or not the Class object it represents is serializable, externalizable, or a dynamic proxy class.

When an ObjectStreamClass instance that does not represent a dynamic proxy class is written to the stream, it writes the class name and serialVersionUID, flags, and the number of fields. Depending on the class, additional information may be written:

  • For non-serializable classes, the number of fields is always zero. Neither the SC_SERIALIZABLE nor the SC_EXTERNALIZABLE flag bits are set.
  • For serializable classes, the SC_SERIALIZABLE flag is set, the number of fields counts the number of serializable fields and is followed by a descriptor for each serializable field. The descriptors are written in canonical order. The descriptors for primitive typed fields are written first sorted by field name followed by descriptors for the object typed fields sorted by field name. The names are sorted using String.compareTo. For details of the format, refer to Section 6.4, "Grammar for the Stream Format".
  • For externalizable classes, flags includes the SC_EXTERNALIZABLE flag, and the number of fields is always zero.
  • For enum types, flags includes the SC_ENUM flag, and the number of fields is always zero.
When an ObjectOutputStream serializes the ObjectStreamClass descriptor for a dynamic proxy class, as determined by passing its Class object to the isProxyClass method of java.lang.reflect.Proxy, it writes the number of interfaces that the dynamic proxy class implements, followed by the interface names. Interfaces are listed in the order that they are returned by invoking the getInterfaces method on the Class object of the dynamic proxy class.

The serialized representations of ObjectStreamClass descriptors for dynamic proxy classes and non-dynamic proxy classes are differentiated through the use of different typecodes (TC_PROXYCLASSDESC and TC_CLASSDESC, respectively); for a more detailed specification of the grammar, see Section 6.4, "Grammar for the Stream Format".

4.4 The ObjectStreamField Class

An ObjectStreamField represents a serializable field of a serializable class. The serializable fields of a class can be retrieved from the ObjectStreamClass.

The special static serializable field, serialPersistentFields, is an array of ObjectStreamField components that is used to override the default serializable fields.

package java.io;

public class ObjectStreamField implements Comparable {

    public ObjectStreamField(String fieldName,
                             Class fieldType);

    public ObjectStreamField(String fieldName,
                             Class fieldType,
                             boolean unshared);

    public String getName();

    public Class getType();

    public String getTypeString();

    public char getTypeCode();

    public boolean isPrimitive();

    public boolean isUnshared();

    public int getOffset();

    protected void setOffset(int offset);

    public int compareTo(Object obj);

    public String toString();
}
ObjectStreamField objects are used to specify the serializable fields of a class or to describe the fields present in a stream. Its constructors accept arguments describing the field to represent: a string specifying the name of the field, a Class object specifying the type of the field, and a boolean flag (implicitly false for the two-argument constructor) indicating whether or not values of the represented field should be read and written as "unshared" objects if default serialization/deserialization is in use (see the descriptions of the ObjectInputStream.readUnshared and ObjectOutputStream.writeUnshared methods in sections 3.1 and 2.1, respectively).

The getName method returns the name of the serializable field.

The getType method returns the type of the field.

The getTypeString method returns the type signature of the field.

The getTypeCode method returns a character encoding of the field type (`B' for byte, `C' for char, `D' for double, `F' for float, `I' for int, `J' for long, `L' for non-array object types, `S' for short, `Z' for boolean, and `[` for arrays).

The isPrimitive method returns true if the field is of primitive type, or false otherwise.

The isUnshared method returns true if values of the field should be written as "unshared" objects, or false otherwise.

The getOffset method returns the offset of the field's value within instance data of the class defining the field.

The setOffset method allows ObjectStreamField subclasses to modify the offset value returned by the getOffset method.

The compareTo method compares ObjectStreamFields for use in sorting. Primitive fields are ranked as "smaller" than non-primitive fields; fields otherwise equal are ranked alphabetically.

The toString method returns a printable representation with name and type.

4.5 Inspecting Serializable Classes

The program serialver can be used to find out if a class is serializable and to get its serialVersionUID. When invoked with the-show option, it puts up a simple user interface. To find out if a class is serializable and to find out its serialVersionUID, enter its full class name, then press either the Enter or the Show button. The string printed can be copied and pasted into the evolved class.

serialver, Serial Version Inspector program

When invoked on the command line with one or more class names, serialver prints the serialVersionUID for each class in a form suitable for copying into an evolving class. When invoked with no arguments, it prints a usage line.

4.6 Stream Unique Identifiers

Each versioned class must identify the original class version for which it is capable of writing streams and from which it can read. For example, a versioned class must declare:

    private static final long serialVersionUID = 3487495895819393L;

The stream-unique identifier is a 64-bit hash of the class name, interface class names, methods, and fields. The value must be declared in all versions of a class except the first. It may be declared in the original class but is not required. The value is fixed for all compatible classes. If the SUID is not declared for a class, the value defaults to the hash for that class. The serialVersionUID for dynamic proxy classes and enum types always have the value 0L. Array classes cannot declare an explicit serialVersionUID, so they always have the default computed value, but the requirement for matching serialVersionUID values is waived for array classes.

Note - It is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected serialVersionUID conflicts during deserialization, causing deserialization to fail.
The initial version of an Externalizable class must output a stream data format that is extensible in the future. The initial version of the method readExternal has to be able to read the output format of all future versions of the method writeExternal.

The serialVersionUID is computed using the signature of a stream of bytes that reflect the class definition. The National Institute of Standards and Technology (NIST) Secure Hash Algorithm (SHA-1) is used to compute a signature for the stream. The first two 32-bit quantities are used to form a 64-bit hash. A java.lang.DataOutputStream is used to convert primitive data types to a sequence of bytes. The values input to the stream are defined by the Java Virtual Machine (VM) specification for classes. Class modifiers may include the ACC_PUBLIC, ACC_FINAL, ACC_INTERFACE, and ACC_ABSTRACT flags; other flags are ignored and do not affect serialVersionUID computation. Similarly, for field modifiers, only the ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL, ACC_VOLATILE, and ACC_TRANSIENT flags are used when computing serialVersionUID values. For constructor and method modifiers, only the ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL, ACC_SYNCHRONIZED, ACC_NATIVE, ACC_ABSTRACT and ACC_STRICT flags are used. Names and descriptors are written in the format used by the java.io.DataOutputStream.writeUTF method.

The sequence of items in the stream is as follows:

  1. The class name.
  2. The class modifiers written as a 32-bit integer.
  3. The name of each interface sorted by name.
  4. For each field of the class sorted by field name (except private static and private transient fields:
    1. The name of the field.
    2. The modifiers of the field written as a 32-bit integer.
    3. The descriptor of the field.
  5. If a class initializer exists, write out the following:
    1. The name of the method, <clinit>.
    2. The modifier of the method, java.lang.reflect.Modifier.STATIC, written as a 32-bit integer.
    3. The descriptor of the method, ()V.
  6. For each non-private constructor sorted by method name and signature:
    1. The name of the method, <init>.
    2. The modifiers of the method written as a 32-bit integer.
    3. The descriptor of the method.
  7. For each non-private method sorted by method name and signature:
    1. The name of the method.
    2. The modifiers of the method written as a 32-bit integer.
    3. The descriptor of the method.
  8. The SHA-1 algorithm is executed on the stream of bytes produced by DataOutputStream and produces five 32-bit values sha[0..4].
  9. The hash value is assembled from the first and second 32-bit values of the SHA-1 message digest. If the result of the message digest, the five 32-bit words H0 H1 H2 H3 H4, is in an array of five int values named sha, the hash value would be computed as follows:
      long hash = ((sha[0] >>> 24) & 0xFF) |
              ((sha[0] >>> 16) & 0xFF) << 8 |
              ((sha[0] >>> 8) & 0xFF) << 16 |
              ((sha[0] >>> 0) & 0xFF) << 24 |
              ((sha[1] >>> 24) & 0xFF) << 32 |
              ((sha[1] >>> 16) & 0xFF) << 40 |
              ((sha[1] >>> 8) & 0xFF) << 48 |
              ((sha[1] >>> 0) & 0xFF) << 56;

CONTENTS | PREV | NEXT
Copyright © 2005, 2010, Oracle and/or its affiliates. All rights reserved.


Class Data Sharing

Overview

Class data sharing (CDS) is a new feature in J2SE 5.0 intended to reduce the startup time for Java programming language applications, in particular smaller applications, as well as reduce footprint. When the JRE is installed on 32-bit platforms using the Sun provided installer, the installer loads a set of classes from the system jar file into a private internal representation, and dumps that representation to a file, called a "shared archive". Class data sharing is not supported in Microsoft Windows 95/98/ME. If the Sun JRE installer is not being used, this can be done manually, as explained below. During subsequent JVM invocations, the shared archive is memory-mapped in, saving the cost of loading those classes and allowing much of the JVM's metadata for these classes to be shared among multiple JVM processes.

In J2SE 5.0, class data sharing is supported only with the Java HotSpot Client VM, and only with the serial garbage collector.

The primary motivation for including CDS in the 5.0 release is the decrease in startup time it provides. CDS produces better results for smaller applications because it eliminates a fixed cost: that of loading certain core classes. The smaller the application relative to the number of core classes it uses, the larger the saved fraction of startup time.

The footprint cost of new JVM instances has been reduced in two ways. First, a portion of the shared archive, currently between five and six megabytes, is mapped read-only and therefore shared among multiple JVM processes. Previously this data was replicated in each JVM instance. Second, since the shared archive contains class data in the form in which the Java Hotspot VM uses it, the memory which would otherwise be required to access the original class information in rt.jar is not needed. These savings allow more applications to be run concurrently on the same machine. On Microsoft Windows, the footprint of a process, as measured by various tools, may appear to increase, because a larger number of pages are being mapped in to the process' address space. This is offset by the reduction in the amount of memory (inside Microsoft Windows) which is needed to hold portions on rt.jar. Reducing footprint remains a high priority.

Regenerating the Shared Archive

Under some circumstances the system administrator may need to manually regenerate the shared archive. This is typically only necessary on Solaris if the Java SE packages were installed over the network to a machine of a different architecture than that performing the installation. Regardless, these regeneration instructions apply to all supported platforms.

The shared archive file is colocated with the shared library for the JVM. On Unix platforms, it is stored in jre/lib/[arch]/client/classes.jsa and on Microsoft Windows platforms in jre/bin/client/classes.jsa. If this file exists, it must be manually removed before regeneration.

To regenerate the archive, log in as the administrator; in networked situations, log on to a machine of the same architecture as the J2SE installation and ensure that you have permission to write to the installation directory. Then execute the command

java -Xshare:dump Diagnostic information will be printed as the archive is generated.

Manually Controlling Class Data Sharing

The class data sharing feature is automatically enabled when conditions allow it to be used. The following command line options are present primarily for diagnostic and debugging purposes and may change or be removed in future releases.

-Xshare:off
Disable class data sharing.
-Xshare:on
Require class data sharing to be enabled. If it could not be enabled for various reasons, print an error message and exit.
-Xshare:auto
The default; enable class data sharing whenever possible.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.mirror.declaration.ClassDeclaration (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.declaration.ClassDeclaration

  • Packages that use ClassDeclaration
    Package Description
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.
    com.sun.mirror.type
    Interfaces used to model types.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of ClassDeclaration in com.sun.mirror.declaration

      Subinterfaces of ClassDeclaration in com.sun.mirror.declaration
      Modifier and Type Interface and Description
      interface  EnumDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in TypeElement.
      Methods in com.sun.mirror.declaration that return types with arguments of type ClassDeclaration
      Modifier and Type Method and Description
      Collection<ClassDeclaration> PackageDeclaration.getClasses()
      Deprecated.
      Returns the declarations of the top-level classes in this package.

    • Uses of ClassDeclaration in com.sun.mirror.type

      Methods in com.sun.mirror.type that return ClassDeclaration
      Modifier and Type Method and Description
      ClassDeclaration ClassType.getDeclaration()
      Deprecated.
      Returns the declaration of this type.

    • Uses of ClassDeclaration in com.sun.mirror.util

      Methods in com.sun.mirror.util with parameters of type ClassDeclaration
      Modifier and Type Method and Description
      void SimpleDeclarationVisitor.visitClassDeclaration(ClassDeclaration d)
      Deprecated.
      Visits a class declaration.
      void DeclarationVisitor.visitClassDeclaration(ClassDeclaration d)
      Deprecated.
      Visits a class declaration.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.javadoc.ClassDoc (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.javadoc.ClassDoc

    • Uses of ClassDoc in com.sun.javadoc

      Subinterfaces of ClassDoc in com.sun.javadoc
      Modifier and Type Interface and Description
      interface  AnnotationTypeDoc
      Represents an annotation type.
      Methods in com.sun.javadoc that return ClassDoc
      Modifier and Type Method and Description
      ClassDoc[] PackageDoc.allClasses()
      Get all included classes and interfaces in the package.
      ClassDoc[] PackageDoc.allClasses(boolean filter)
      Get all classes and interfaces in the package, filtered to the specified access modifier option.
      ClassDoc Type.asClassDoc()
      Return this type as a ClassDoc if it represents a class or interface.
      ClassDoc ParameterizedType.asClassDoc()
      Return the generic class or interface that declared this type.
      ClassDoc[] RootDoc.classes()
      Return the included classes and interfaces in all packages.
      ClassDoc RootDoc.classNamed(String qualifiedName)
      Return a ClassDoc for the specified class or interface name.
      ClassDoc ProgramElementDoc.containingClass()
      Get the containing class or interface of this program element.
      ClassDoc[] PackageDoc.enums()
      Get included enum types in this package.
      ClassDoc[] PackageDoc.errors()
      Get included Error classes in this package.
      ClassDoc ThrowsTag.exception()
      Return a ClassDoc that represents the exception.
      ClassDoc[] PackageDoc.exceptions()
      Get included Exception classes in this package.
      ClassDoc SerialFieldTag.fieldTypeDoc()
      Return the ClassDoc for field type.
      ClassDoc PackageDoc.findClass(String className)
      Lookup a class or interface within this package.
      ClassDoc ClassDoc.findClass(String className)
      Find the specified class or interface within the context of this class doc.
      ClassDoc[] ClassDoc.importedClasses()
      Deprecated.
      Import declarations are implementation details that should not be exposed here. In addition, not all imported classes are imported through single-type-import declarations.
      ClassDoc[] ClassDoc.innerClasses()
      Return included nested classes and interfaces within this class or interface.
      ClassDoc[] ClassDoc.innerClasses(boolean filter)
      Return nested classes and interfaces within this class or interface filtered to the specified access modifier option.
      ClassDoc[] PackageDoc.interfaces()
      Get included interfaces in this package, omitting annotation types.
      ClassDoc[] ClassDoc.interfaces()
      Return interfaces implemented by this class or interfaces extended by this interface.
      ClassDoc[] PackageDoc.ordinaryClasses()
      Get included ordinary classes (that is, exclude exceptions, errors, enums, interfaces, and annotation types) in this package.
      ClassDoc MethodDoc.overriddenClass()
      Return the class containing the method that this method overrides.
      ClassDoc SeeTag.referencedClass()
      Get the class doc referenced by the class name part of @see.
      ClassDoc[] RootDoc.specifiedClasses()
      Return the classes and interfaces specified as source file names on the command line.
      ClassDoc ClassDoc.superclass()
      Return the superclass of this class.
      ClassDoc[] ExecutableMemberDoc.thrownExceptions()
      Return exceptions this method or constructor throws.
      Methods in com.sun.javadoc with parameters of type ClassDoc
      Modifier and Type Method and Description
      boolean ClassDoc.subclassOf(ClassDoc cd)
      Test whether this class is a subclass of the specified class.
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Closing a URLClassLoader

How to Close a URLClassLoader?

The URLClassLoader close() method effectively eliminates the problem of how to support updated implementations of the classes and resources loaded from a particular codebase, and in particular from JAR files. In principle, once the application clears all references to a loader object, the garbage collector and finalization mechanisms will eventually ensure that all resources (such as the JarFile objects) are released and closed.

The application can then replace the JAR file, and create a new URLClassLoader instance to load from the same location, but this time using the new implementation of the classes/resources. However, since it can't be predicted exactly when finalization and garbage collection will occur, problems are caused for applications which need to be able to do this in a predictable and timely fashion. It is a problem on Windows, because open files cannot be deleted or replaced.

In Java SE 7, the URLClassLoader close() method effectively invalidates the loader, so that no new classes can be loaded from it. It also closes any JAR files that were opened by the loader. This allows the application to delete or replace these files and, if necessary, create new loaders using new implementations.

The close() method follows the familiar "Closeable" pattern, and URLClassLoader now implements the Closeable interface, which defines URLClassLoader.close(). The following sample code shows how one might use the method.

       //
       // create a class loader loading from "foo.jar"
       //
       URL url = new URL("file:foo.jar");
       URLClassLoader loader = new URLClassLoader (new URL[] {url});
       Class cl = Class.forName ("Foo", true, loader);
       Runnable foo = (Runnable) cl.newInstance();
       foo.run();
       loader.close ();

       // foo.jar gets updated somehow

       loader = new URLClassLoader (new URL[] {url});
       cl = Class.forName ("Foo", true, loader);
       foo = (Runnable) cl.newInstance();
       // run the new implementation of Foo
       foo.run();
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.ClassLoaderReference (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.ClassLoaderReference

  • Packages that use ClassLoaderReference
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of ClassLoaderReference in com.sun.jdi

      Methods in com.sun.jdi that return ClassLoaderReference
      Modifier and Type Method and Description
      ClassLoaderReference ReferenceType.classLoader()
      Gets the classloader object which loaded the class corresponding to this type.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.jdi.ClassNotLoadedException (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.ClassNotLoadedException

  • Packages that use ClassNotLoadedException
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of ClassNotLoadedException in com.sun.jdi

      Methods in com.sun.jdi that throw ClassNotLoadedException
      Modifier and Type Method and Description
      List<Type> Method.argumentTypes()
      Returns a list containing the type of each formal parameter of this method.
      Type ArrayType.componentType()
      Returns the component type of this array, as specified in the array declaration.
      void ThreadReference.forceEarlyReturn(Value value)
      Force a method to return before it reaches a return statement.
      Value ClassType.invokeMethod(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Invokes the specified static Method in the target VM.
      Value ObjectReference.invokeMethod(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Invokes the specified Method on this object in the target VM.
      ObjectReference ClassType.newInstance(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Constructs a new instance of this type, using the given constructor Method in the target VM.
      Type Method.returnType()
      Returns the return type, as specified in the declaration of this method.
      void ClassType.setValue(Field field, Value value)
      Assigns a value to a static field.
      void ObjectReference.setValue(Field field, Value value)
      Sets the value of a given instance or static field in this object.
      void ArrayReference.setValue(int index, Value value)
      Replaces an array component with another value.
      void StackFrame.setValue(LocalVariable variable, Value value)
      Sets the Value of a LocalVariable in this frame.
      void ArrayReference.setValues(int index, List<? extends Value> values, int srcIndex, int length)
      Replaces a range of array components with other values.
      void ArrayReference.setValues(List<? extends Value> values)
      Replaces all array components with other values.
      Type LocalVariable.type()
      Returns the type of this variable.
      Type Field.type()
      Returns the type of this field.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.jdi.ClassNotPreparedException (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.ClassNotPreparedException

No usage of com.sun.jdi.ClassNotPreparedException
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.ClassObjectReference (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.ClassObjectReference

  • Packages that use ClassObjectReference
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of ClassObjectReference in com.sun.jdi

      Methods in com.sun.jdi that return ClassObjectReference
      Modifier and Type Method and Description
      ClassObjectReference ReferenceType.classObject()
      Returns the class object that corresponds to this type in the target VM.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Setting the class path

Synopsis

The class path is the path that the Java runtime environment searches for classes and other resource files. The class search path (more commonly known by the shorter name, "class path") can be set using either the -classpath option when calling a JDK tool (the preferred method) or by setting the CLASSPATH environment variable. The -classpath option is preferred because you can set it individually for each application without affecting other applications and without other applications modifying its value.

C:> sdkTool -classpath classpath1;classpath2...

-or-

C:> set CLASSPATH=classpath1;classpath2...

where:

sdkTool
A command-line tool, such as java, javac, javadoc, or apt. For a listing, see JDK Tools.
classpath1;classpath2
Class paths to the .jar, .zip or .class files. Each classpath should end with a filename or directory depending on what you are setting the class path to:
  • For a .jar or .zip file that contains .class files, the class path ends with the name of the .zip or .jar file.
  • For .class files in an unnamed package, the class path ends with the directory that contains the .class files.
  • For .class files in a named package, the class path ends with the directory that contains the "root" package (the first package in the full package name).

Multiple path entries are separated by semi-colons. With the set command, it's important to omit spaces from around the equals sign (=).

The default class path is the current directory. Setting the CLASSPATH variable or using the -classpath command-line option overrides that default, so if you want to include the current directory in the search path, you must include "." in the new settings.

Classpath entries that are neither directories nor archives (.zip or .jar files) nor * are ignored.

Description

The class path tells JDK tools and applications where to find third-party and user-defined classes -- that is, classes that are not Java extensions or part of the Java platform. The class path needs to find any classes you've compiled with the javac compiler -- its default is the current directory to conveniently enable those classes to be found.

The JDK, the JVM and other JDK tools find classes by searching the Java platform (bootstrap) classes, any extension classes, and the class path, in that order. (For details on the search strategy, see How Classes Are Found.) Class libraries for most applications will want to take advantage of the extensions mechanism. You only need to set the class path when you want to load a class that's (a) not in the current directory or in any of its subdirectories, and (b) not in a location specified by the extensions mechanism.

If you are upgrading from an older version of the JDK, your startup settings may include CLASSPATH settings that are no longer needed. You should remove any settings that are not application-specific, such as classes.zip. Some third-party applications that use the Java Virtual Machine may modify your CLASSPATH environment variable to include the libaries they use. Such settings can remain.

You can change the class path by using the JDK tools' -classpath option when you invoke the JVM or other JDK tools or by using the CLASSPATH environment variable. Using the -classpath option is preferred over setting CLASSPATH environment variable because you can set it individually for each application without affecting other applications and without other applications modifying its value.

Classes can be stored either in directories (folders) or in archive files. The Java platform classes are stored in rt.jar. For more details on archives and information on how the class path works, see Understanding the class path and package names near the end of this document.

Important Note: Some older versions of the JDK sofware included a <jdk-dir>/classes entry in the default class path. That directory exists for use by the JDK software, and should not be used for application classes. Application classes should be placed in a directory outside of the JDK directory hierarcy. That way, installing a new JDK does not force you to reinstall application classes. For compatibility with older versions, applications that use the <jdk-dir>/classes directory as a class library will run in the current version, but there is no guarantee that they will run in future versions.

Using the JDK tools' -classpath option

The JDK tools java, jdb, javac, and javah have a -classpath option which replaces the path or paths specified by the CLASSPATH environment variable while the tool runs. This is the recommended option for changing class path settings, because each application can have the class path it needs without interfering with any other application.

The runtime tool java has a -cp option, as well. This option is an abbreviation for -classpath.

For very special cases, both java and javac have options that let you change the path they use to find their own class libraries. The vast majority of users will never to need to use those options, however.

Using the CLASSPATH environment variable

In general, you will want to use the -classpath command-line option, as explained in the previous section. This section shows you how to set the CLASSPATH environment variable if you want to do that, or clear settings left over from a previous installation.

Setting CLASSPATH

The CLASSPATH environment variable is modified with the set command. The format is:

set CLASSPATH=path1;path2
...

The paths should begin with the letter specifying the drive, for example, C:\. That way, the classes will still be found if you happen to switch to a different drive. (If the path entries start with backslash (\) and you are on drive D:, for example, then the classes will be expected on D:, rather thanC:.)

Clearing CLASSPATH

If your CLASSPATH environment variable has been set to a value that is not correct, or if your startup file or script is setting an incorrect path, you can unset CLASSPATH by using:

      C:> set CLASSPATH=

This command unsets CLASSPATH for the current command prompt window only. You should also delete or modify your startup settings to ensure that you have the right CLASSPATH settings in future sessions.

Changing Startup Settings

If the CLASSPATH variable is set at system startup, the place to look for it depends on your operating system:
Operating System | Method
Windows 95 and 98 | Examine autoexec.bat for the set command.
Other (Windows NT, Windows 2000, ...) | The CLASSPATH environment variable can be set using the System utility in the Control Panel.

Understanding class path wildcards

Class path entries can contain the basename wildcard character *, which is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR. For example, the class path entry foo/* specifies all JAR files in the directory named foo. A classpath entry consisting simply of * expands to a list of all the jar files in the current directory.

A class path entry that contains * will not match class files. To match both classes and JAR files in a single directory foo, use either foo;foo/* or foo/*;foo. The order chosen determines whether the classes and resources in foo are loaded before JAR files in foo, or vice versa.

Subdirectories are not searched recursively. For example, foo/* looks for JAR files only in foo, not in foo/bar, foo/baz, etc.

The order in which the JAR files in a directory are enumerated in the expanded class path is not specified and may vary from platform to platform and even from moment to moment on the same machine. A well-constructed application should not depend upon any particular order. If a specific order is required then the JAR files can be enumerated explicitly in the class path.

Expansion of wildcards is done early, prior to the invocation of a program's main method, rather than late, during the class-loading process itself. Each element of the input class path containing a wildcard is replaced by the (possibly empty) sequence of elements generated by enumerating the JAR files in the named directory. For example, if the directory foo contains a.jar, b.jar, and c.jar, then the class path foo/* is expanded into foo/a.jar;foo/b.jar;foo/c.jar, and that string would be the value of the system property java.class.path.

The CLASSPATH environment variable is not treated any differently from the -classpath (or -cp) command-line option. That is, wildcards are honored in all these cases. However, class path wildcards are not honored in the Class-Path jar-manifest header.

Understanding the class path and package names

Java classes are organized into packages which are mapped to directories in the file system. But, unlike the file system, whenever you specify a package name, you specify the whole package name -- never part of it. For example, the package name for java.awt.Button is always specified as java.awt.

For example, suppose you want the Java runtime to find a class named Cool.class in the package utility.myapp. If the path to that directory is C:\java\MyClasses\utility\myapp, you would set the class path so that it contains C:\java\MyClasses.

To run that app, you could use the following JVM command:

C:> java -classpath C:\java\MyClasses utility.myapp.Cool

When the app runs, the JVM uses the class path settings to find any other classes defined in the utility.myapp package that are used by the Cool class.

Note that the entire package name is specified in the command. It is not possible, for example, to set the class path so it contains C:\java\MyClasses\utility and use the command java myapp.Cool. The class would not be found.

(You may be wondering what defines the package name for a class. The answer is that the package name is part of the class and cannot be modified, except by recompiling the class.)

Note: An interesting consequence of the package specification mechanism is that files which are part of the same package may actually exist in different directories. The package name will be the same for each class, but the path to each file may start from a different directory in the class path.

Folders and archive files

When classes are stored in a directory (folder), like c:\java\MyClasses\utility\myapp, then the class path entry points to the directory that contains the first element of the package name. (in this case, C:\java\MyClasses, since the package name is utility.myapp.)

But when classes are stored in an archive file (a .zip or .jar file) the class path entry is the path to and including the .zip or .jar file. For example, to use a class library that is in a .jar file, the command would look something like this:

C:> java -classpath C:\java\MyClasses\myclasses.jar utility.myapp.Cool

Multiple specifications

To find class files in the directory C:\java\MyClasses as well as classes in C:\java\OtherClasses, you would set the class path to:

C:> java -classpath C:\java\MyClasses;C:\java\OtherClasses ...

Note that the two paths are separated by a semicolon.

Specification order

The order in which you specify multiple class path entries is important. The Java interpreter will look for classes in the directories in the order they appear in the class path variable. In the example above, the Java interpreter will first look for a needed class in the directory C:\java\MyClasses. Only if it doesn't find a class with the proper name in that directory will the interpreter look in the C:\java\OtherClasses directory.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.event.ClassPrepareEvent (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.event.ClassPrepareEvent

No usage of com.sun.jdi.event.ClassPrepareEvent
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.request.ClassPrepareRequest (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.request.ClassPrepareRequest

  • Packages that use ClassPrepareRequest
    Package Description
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of ClassPrepareRequest in com.sun.jdi.request

      Methods in com.sun.jdi.request that return ClassPrepareRequest
      Modifier and Type Method and Description
      ClassPrepareRequest EventRequestManager.createClassPrepareRequest()
      Creates a new disabled ClassPrepareRequest.
      Methods in com.sun.jdi.request that return types with arguments of type ClassPrepareRequest
      Modifier and Type Method and Description
      List<ClassPrepareRequest> EventRequestManager.classPrepareRequests()
      Return an unmodifiable list of the enabled and disabled class prepare requests.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.ClassTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.ClassTree

  • Packages that use ClassTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of ClassTree in com.sun.source.tree

      Methods in com.sun.source.tree that return ClassTree
      Modifier and Type | Method and Description
      ClassTree | NewClassTree.getClassBody()
      Methods in com.sun.source.tree with parameters of type ClassTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitClass(ClassTree node, P p)

    • Uses of ClassTree in com.sun.source.util

      Methods in com.sun.source.util that return ClassTree
      Modifier and Type Method and Description
      abstract ClassTree Trees.getTree(TypeElement element)
      Gets the ClassTree node for a given TypeElement.
      Methods in com.sun.source.util with parameters of type ClassTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitClass(ClassTree node, P p)
      R | SimpleTreeVisitor.visitClass(ClassTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.type.ClassType (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.type.ClassType

  • Packages that use ClassType
    Package Description
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.
    com.sun.mirror.type
    Interfaces used to model types.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of ClassType in com.sun.mirror.declaration

      Methods in com.sun.mirror.declaration that return ClassType
      Modifier and Type Method and Description
      ClassType ClassDeclaration.getSuperclass()
      Deprecated.
      Returns the class type directly extended by this class.

    • Uses of ClassType in com.sun.mirror.type

      Subinterfaces of ClassType in com.sun.mirror.type
      Modifier and Type Interface and Description
      interface  EnumType
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in DeclaredType.
      Methods in com.sun.mirror.type that return ClassType
      Modifier and Type Method and Description
      ClassType ClassType.getSuperclass()
      Deprecated.
      Returns the class type that is a direct supertype of this one.

    • Uses of ClassType in com.sun.mirror.util

      Methods in com.sun.mirror.util with parameters of type ClassType
      Modifier and Type Method and Description
      void TypeVisitor.visitClassType(ClassType t)
      Deprecated.
      Visits a class type.
      void SimpleTypeVisitor.visitClassType(ClassType t)
      Deprecated.
      Visits a class type.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.event.ClassUnloadEvent (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.event.ClassUnloadEvent

No usage of com.sun.jdi.event.ClassUnloadEvent
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.request.ClassUnloadRequest (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.request.ClassUnloadRequest

  • Packages that use ClassUnloadRequest
    Package Description
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of ClassUnloadRequest in com.sun.jdi.request

      Methods in com.sun.jdi.request that return ClassUnloadRequest
      Modifier and Type Method and Description
      ClassUnloadRequest EventRequestManager.createClassUnloadRequest()
      Creates a new disabled ClassUnloadRequest.
      Methods in com.sun.jdi.request that return types with arguments of type ClassUnloadRequest
      Modifier and Type Method and Description
      List<ClassUnloadRequest> EventRequestManager.classUnloadRequests()
      Return an unmodifiable list of the enabled and disabled class unload requests.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Client JRE Capabilities - Quick Reference

Java rich Internet application (RIA) technology is getting increasingly sophisticated. New features are being added in every release of the Java Runtime Environment (JRE) software. This quick reference helps you keep up with the vibrant technology and implement RIA solutions that work elegantly on all versions of the client JRE software. The quick reference provides information about significant capabilities added in each version of the JRE software starting with the Java SE 6 update 10 release.

Applets

Java SE 7

  • Dragged Applet Window Decoration: The window of a dragged applet can be decorated with a default or custom title by specifying the decorated and java_dragged_applet_title parameters.

Java SE 6 update 21

  • Customized loading progress indicator: Customized loading progress indicator can access applet context and invoke JavaScript code in parent web page.

Java SE 6 update 18

  • Customized loading progress indicator: Customized loading progress indicator can be displayed in a top level window or applet container.

Java SE 6 update 10

  • Java Network Launch Protocol (JNLP) Support: The next generation Java Plug-in enables applets that can be deployed by using JNLP and can access JNLP API.
  • Draggable applet: Applets can be dragged out of the browser if specified as "draggable".
  • Splash screen: Custom splash screen displayed if specified.

Java Web Start Applications

JNLP support has been the foundation of Java Web Start applications since the inception of this technology.

Java SE 7

  • Operating systems: The os attribute in the information and resources elements can now contain specific versions of Windows, such as Windows Vista or Windows 7.
  • Installed applications: The JNLP specification now supports a install attribute in the shortcut element so applications can indicate their desire to be installed. Installed applications are not removed when the Java Web Start cache is cleared, but can be explicitly removed using the Java Control Panel.
  • Java Web Start applications can be deployed without specifying the codebase attribute in the JNLP file.

Java SE 6 update 18

  • Customized loading progress indicator: Customized loading progress indicator can be displayed in a top level window. Default splash screen is never displayed. Custom splash screen displayed when loaded from cache.

Resources

  • Java Rich Internet Applications Development and Deployment in Java SE developer guide
  • Deployment trail in the Java Tutorials
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Use of JAAS Login Utility and Java GSS-API for Secure Message Exchanges

This tutorial presents two sample applications to demonstrate the use of the Java GSS-API. This API permits secure exchanges of messages between communicating applications. Here are the sample client and server applications you'll need for this tutorial:

  • SampleClient
  • SampleServer
Note: This tutorial uses the same client and server applications as the Use of Java GSS-API for Secure Message Exchanges Without JAAS Programming tutorial. In that tutorial, JAAS (Java Authentication and Authorization Service) programming is not required. Instead, you let the underlying mechanism decide how to get credentials.
This tutorial uses policy files and a more complex login configuration file. The programs are run with a security manager; as a result, security-sensitive operations are not allowed unless the required permissions were explicitly granted. This tutorial also demonstrates how JAAS authorization adds user-centric access control that applies control based on who is running the code--not just on what code is running.

Contents:

  • Before You Start: Recommended Reading
  • Overview of the Client And Server Applications
  • Kerberos User and Service Principal Names
  • The Login Configuration File
  • The Policy Files
  • Running the SampleClient and SampleServer Programs

Before You Start: Recommended Reading

In this Java GSS-API tutorial, the first step is JAAS authentication. Previous tutorials demonstrated the use of JAAS for user authentication and authorization, and presented examples of policy files and of login configuration files (specifying the underlying authentication technology to be used) that JAAS requires. Applications in the JAAS introductory tutorials, JAAS Authentication and JAAS Authorization, made direct calls to JAAS methods. The Use of JAAS Login Utility tutorial showed the use of a utility program that frees the application from having to do this. The client and server applications in the current tutorial also use the same utility program, so we recommend you read the login utility tutorial first.

As with all tutorials in this series, the underlying technology used to support authentication and secure communication for the applications in this tutorial is Kerberos. See Kerberos Requirements.

Overview of the Client and Server Applications

The applications for this tutorial are named SampleClient and SampleServer.

Each is invoked by executing the Login utility supplied with this tutorial and passing it as arguments the name of the application (SampleClient or SampleServer), followed by the arguments needed by the application. The Login utility uses a JAAS LoginContext to authenticate the user using Kerberos. Finally, the Login utility invokes the main method of the application class, in our case either SampleClient or SampleServer, and passes the application its arguments.

Here is a summary of execution of the SampleClient and SampleServer applications:

  1. Run the SampleServer application by running the Login utility and passing it as arguments the name "SampleServer" followed by the arguments for the SampleServer program. The Login utility prompts you for the password for the principal that SampleServer should run as. (See Kerberos User and Service Principal Names.) After authentication is complete, SampleServer is run it:
    1. Reads its argument, the port number that it should listen on for client connections.
    2. Creates a ServerSocket for listening for client connections on that port.
    3. Listens for a connection.
  2. Run the SampleClient application (possibly on a different machine), by running the Login utility and passing it as arguments the name "SampleClient" followed by the arguments for the SampleClient program. The Login utility prompts you for your Kerberos name and password. After authentication is complete, SampleClient is run. It
    1. Reads its arguments: (1) The name of the Kerberos principal that represents SampleServer. (See Kerberos User and Service Principal Names.), (2) the name of the host (machine) on which SampleServer is running, and (3) the port number on which SampleServer listens for client connections.
    2. Attempts a socket connection with the SampleServer, using the host and port it was passed as arguments.
  3. The socket connection is accepted by SampleServer and both applications initialize a DataInputStream and a DataOutputStream from the socket input and output streams, to be used for future data exchanges.
  4. SampleClient and SampleServer each instantiate a GSSContext and establish a shared context that will enable subsequent secure data exchanges.
  5. SampleClient and SampleServer can now securely exchange messages.
  6. When SampleClient and SampleServer are done exchanging messages, they perform clean-up operations.
Note: Refer to "The SampleClient and SampleServer Code" section of the Use of Java GSS-API for Secure Message Exchanges Without JAAS Programming tutorial for a full discussion of the code used in this tutorial.

Kerberos User and Service Principal Names

Since the underlying authentication and secure communication technology used by this tutorial is Kerberos V5, we use Kerberos-style principal names wherever a user or service is called for.

For example, when you run SampleClient you are asked to provide your user name. Your Kerberos-style user name is simply the user name you were assigned for Kerberos authentication. It consists of a base user name (like "mjones") followed by an "@" and your realm (like "mjones@KRBNT-OPERATIONS.ABC.COM").

A server program like SampleServer is typically considered to offer a "service" and to be run on behalf of a particular "service principal." A service principal name for SampleServer is needed in several places:

  • When you run SampleServer you must log in as the appropriate service principal. The login configuration file for this tutorial actually specifies the service principal name (as an option to the Krb5LoginModule), so the JAAS authentication (done by the Login utility) just asks you to specify the password for that service principal. If you specify the correct password, the authentication is successful, a Subject is created containing a Principal with the service principal name, and that Subject is associated with a new access control context. The subsequently-executed code (the SampleServer code) is considered to be executed on behalf of the specified principal.
  • When you run SampleClient, one of the arguments is the service principal name. This is needed so SampleClient can initiate establishment of a security context with the appropriate service.
  • The client and server policy files each require a ServicePermission with name equal to the service principal name and action equal to "initiate" or "accept" (for initiating or accepting establishment of a security context).

Throughout this document, and in the accompanying login configuration file and policy files,

service_principal@your_realm
is used as a placeholder to be replaced by the actual name to be used in your environment. Any Kerberos principal can actually be used for the service principal name. So for the purposes of trying out this tutorial, you could use your user name as both the client user name and the service principal name.

In a production environment, system administrators typically like servers to be run as specific principals only and may assign a particular name to be used. Often the Kerberos-style service principal name assigned is of the form

service_name/machine_name@realm;

For example, an nfs service run on a machine named "raven" in the realm named "KRBNT-OPERATIONS.ABC.COM" could have the service principal name

nfs/raven@KRBNT-OPERATIONS.ABC.COM

Such multi-component names are not required, however. Single-component names, just like those of user principals, can be used. For example, an installation might use the same ftp service principal ftp@realm for all ftp servers in that realm, while another installation might have different ftp principals for different ftp servers, such as ftp/host1@realm and ftp/host2@realm on machines host1 and host2, respectively.

When the Realm is Required in Principal Names

If the realm of a user or service principal name is the default realm (see Kerberos Requirements), you can leave off the realm when you are logging into Kerberos (that is, when you are prompted for your username). Thus, for example, if your user name is "mjones@KRBNT-OPERATIONS.ABC.COM", and you run SampleClient, when it requests your user name you could just specify "mjones", leaving off the realm. The name is interpreted in the context of being a Kerberos principal name and the default realm is appended, as needed.

You can also leave off the realm if a principal name will be converted to a GSSName by a GSSManager createName method. For example, when you run SampleClient, one of the arguments is the server service principal name. You can specify the name without including the realm, because SampleClient passes the name to such a createName method, which appends the default realm as needed.

It is recommended that you always include realms when principal names are used in login configuration files and policy files, because the behavior of the parsers for such files may be implementation-dependent; they may or may not append the default realm before such names are utilized and subsequent actions may fail if there is no realm in the name.

The Login Configuration File

Whenever JAAS is used, a login configuration is required to specify the desired authentication technology. (See JAAS Login Configuration File for more information about what a login configuration file is.) Both SampleClient and SampleServer can use the same login configuration file, if that file contains two entries, one entry for the client side and one for the server side.

The csLogin.conf login configuration file used for this tutorial is the following:

SampleClient {
  com.sun.security.auth.module.Krb5LoginModule required;
};

SampleServer {
  com.sun.security.auth.module.Krb5LoginModule required storeKey=true
    principal="service_principal@your_realm";
};

Note that the name for each entry matches the respective class names for our two top-level applications, SampleClient and SampleServer. Recall that this is also the name that is passed to the Login utility that performs JAAS operations for the application. That utility expects the name of the entry to be looked up in your login configuration file to be the same as the name it is passed.

Both entries specify that Sun's Kerberos V5 LoginModule must be used to successfully authenticate the user. The Krb5LoginModule succeeds only if the attempt to log in to the Kerberos KDC as a specified entity is successful. In the case of SampleClient, the user will be prompted for their name and password. In the case of SampleServer, a name is already supplied in this login configuration file (the specified principal, as described below) and the user running SampleServer is just asked for the password for the entity specified by that name. They must specify the correct password in order for authentication to succeed.

The SampleServer entry storeKey=true indicates that a secret key should be calculated from the password provided during login and it should be stored in the private credentials of the Subject created as a result of login. This key is subsequently utilized during mutual authentication when establishing a security context between SampleClient and SampleServer.

The Krb5LoginModule has a principal option that can be used to specify that only the specified principal (entity/user) should be logged in for the given program. Here, the SampleClient entry does not specify a principal (although it could, if desired), so the user is prompted for a user name and password and anyone with a valid user name and password can run SampleClient. SampleServer, on the other hand, indicates a particular principal because system administrators usually like servers to be run as specific principals only. In this case, the user running SampleServer is prompted for that principal's password and must supply the correct one in order for authentication to succeed.

Note that you must replace "service_principal@your_realm" with the name of the service principal that represents SampleServer. (See Kerberos User and Service Principal Names.)

For information about all the possible options that can be passed to Krb5LoginModule, see the Krb5LoginModule documentation.

The Policy Files

The policy file used when running SampleClient is client.policy, and the policy file used when running SampleServer is server.policy. Their contents are described below.

The Client Policy File

Permissions Required by the Login utility Classes

A number of permissions are required by the classes in Login.java (Login and MyAction). As recommended in the previous tutorial on the use of Login, we create a Login.jar JAR file containing the Login.class and MyAction.class files and in the client.policy policy file we grant Login.jar AllPermission:

grant codebase "file:./Login.jar" {
   permission java.security.AllPermission;
};

Permissions Required by SampleClient

The SampleClient code does two types of operations for which permissions are required. It

  • opens a socket connection with the host machine running the SampleServer application.
  • initiates establishment of a security context with SampleServer.

The permission required to open a socket connection is

permission java.net.SocketPermission "*", "connect";

You may replace the "*" with the hostname or IP address of the machine that SampleServer will be running on.

The permission(s) required to initiate establishment of a security context will depend on the underlying mechanism. This tutorial uses Kerberos as the underlying mechanism, and for that two javax.security.auth.kerberos.ServicePermissions are required. A ServicePermission contains a service principal name and an action (or list of actions). To initiate establishment of a security context, you need two ServicePermissions with action "initiate", whose names specify:

  • the service principal name for the ticket granting service for your realm. Granting this permission essentially allows the use of Kerberos as a client.
  • the service principal name representing SampleServer. (See Kerberos User and Service Principal Names.) Granting this permission allows you to interact with the service, SampleServer, using Kerberos.

We want to grant the permissions to a specific authenticated user executing SampleClient, so we specify both the SampleClient code location (in SampleClient.jar) and a Principal designation indicating the user name and realm for the user (you, the person who will run SampleClient). (See How Do You Make Principal-Based Policy File Statements? in the second tutorial of this series for information on policy file grant statements that include Principal designations.)

Here is the basic form for the grant statement:

  grant CodeBase "file:./SampleClient.jar",
    Principal javax.security.auth.kerberos.KerberosPrincipal
        "your_user_name@your_realm" {

    permission java.net.SocketPermission "*", "connect";

    permission javax.security.auth.kerberos.ServicePermission
        "krbtgt/your_realm@your_realm",
        "initiate";

    permission javax.security.auth.kerberos.ServicePermission
        "service_principal@your_realm",
        "initiate";
};

You must substitute your Kerberos user name (complete with "@" and realm) for "your_user_name@your_realm". For example, if your user name is "mjones" and your realm is "KRBNT-OPERATIONS.ABC.COM", you would use "mjones@KRBNT-OPERATIONS.ABC.COM" (complete with the quotes).

You must also substitute your realm in "krbtgt/your_realm@your_realm" and the service principal name for the service principal representing the server for "service_principal@your_realm". Suppose the former is "krbtgt/KRBNT-OPERATIONS.ABC.COM@KRBNT-OPERATIONS.ABC.COM" and the latter is "sample/raven.abc.com@KRBNT-OPERATIONS.ABC.COM", and your user name is as specified in the previous paragraph. Then the grant statement would be

grant CodeBase "file:./SampleClient.jar",
    Principal javax.security.auth.kerberos.KerberosPrincipal
        "mjones@KRBNT-OPERATIONS.ABC.COM" {

    permission java.net.SocketPermission "*", "connect";

    permission javax.security.auth.kerberos.ServicePermission
        "krbtgt/KRBNT-OPERATIONS.ABC.COM@KRBNT-OPERATIONS.ABC.COM",
        "initiate";

    permission javax.security.auth.kerberos.ServicePermission
        "sample/raven.abc.com@KRBNT-OPERATIONS.ABC.COM",
        "initiate";
};

The Server Policy File

Permissions Required by the Login Utility Classes

The grant statement in the server policy file for the Login classes is exactly the same as the one in the client policy file, as described in Permissions Required by the Login Utility Classes:

grant codebase "file:./Login.jar" {
   permission java.security.AllPermission;
};

Permissions Required by SampleServer

The SampleServer code does two types of operations for which permissions are required. It

  • accepts socket connections.
  • accepts establishment of a security context, that is, it is the "acceptor" for security context establishment.

The permission required to accept socket connections is

permission java.net.SocketPermission "*", "accept";

You may replace the "*" with the hostname or IP address of the machine that SampleClient will be running on.

The permission required to accept establishment of a security context is

permission javax.security.auth.kerberos.ServicePermission
    "service_principal@your_realm",
    "accept";
where "service_principal@your_realm" is the Kerberos name of the service principal that represents SampleServer.

We want to grant the permissions to a specific authenticated user executing SampleServer (the service principal considered to represent SampleServer), so we specify both the SampleServer code location (in SampleServer.jar) and a Principal designation indicating the service principal. Suppose this name is "sample/raven.abc.com@KRBNT-OPERATIONS.ABC.COM". Then the grant statement would be

  grant CodeBase "file:./SampleServer.jar"
    Principal javax.security.auth.kerberos.KerberosPrincipal
        "sample/raven.abc.com@KRBNT-OPERATIONS.ABC.COM" {

    permission java.net.SocketPermission "*", "accept";

    permission javax.security.auth.kerberos.ServicePermission
        "sample/raven.abc.com@KRBNT-OPERATIONS.ABC.COM", "accept";
};

Running the SampleClient and SampleServer Programs

To execute the SampleClient and SampleServer programs, do the following:

  • Prepare SampleServer for Execution
  • Prepare SampleClient for Execution
  • Execute SampleServer
  • Execute SampleClient

Prepare SampleServer for Execution

To prepare SampleServer for execution, do the following:

  1. Copy the following files into a directory accessible by the machine on which you will run SampleServer:
    • The Login.java source file.
    • The SampleServer.java source file.
    • The csLogin.conf login configuration file.
    • The server.policy policy file.
  2. Replace "service_principal@your_realm" in csLogin.conf with the name of the service principal representing SampleServer.
  3. In both places it appears, replace "service_principal@your_realm" in server.policy with the Kerberos name of the service principal that represents SampleServer. (The same name as that used in the login configuration file.)
  4. Compile Login.java and SampleServer.java:
    javac Login.java SampleServer.java

    Note that Login.java contains two classes and thus compiling Login.java creates Login.class and MyAction.class.

  5. Create a JAR file named Login.jar containing Login.class and MyAction.class:
    jar -cvf Login.jar Login.class MyAction.class
  6. Create a JAR file named SampleServer.jar containing SampleServer.class:
    jar -cvf SampleServer.jar SampleServer.class

Prepare SampleClient for Execution

To prepare SampleClient for execution, do the following:

  1. Copy the following files into a directory accessible by the machine on which you will run SampleClient:
    • The Login.java source file.
    • The SampleClient.java source file.
    • The csLogin.conf login configuration file.
    • The client.policy policy file.
  2. Replace parts of client.policy:
    • replace "your_user_name@your_realm" with your user name and realm.
    • replace your_realm in "krbtgt/your_realm@your_realm" with your realm.
    • replace "service_principal@your_realm" with the Kerberos name of the service principal that represents SampleServer.
  3. Compile Login.java and SampleClient.java:
    javac Login.java SampleClient.java
  4. Create a JAR file named Login.jar containing Login.class and MyAction.class:
    jar -cvf Login.jar Login.class MyAction.class
  5. Create a JAR file named SampleClient.jar containing SampleClient.class:
    jar -cvf SampleClient.jar SampleClient.class

Execute SampleServer

It is important to execute SampleServer before SampleClient because SampleClient will try to make a socket connection to SampleServer and that will fail if SampleServer is not yet running and accepting socket connections.

To execute SampleServer, be sure to run it on the machine it is expected to be run on. This machine name (host name) is specified as an argument to SampleClient. The service principal name appears in several places, including the login configuration file and the policy files.

Go to the directory in which you have prepared SampleServer for execution. Execute the Login class, specifying

  • by an appropriate -classpath clause that classes should be searched for in the Login.jar and SampleServer.jar JAR files,
  • by -Djava.security.manager that a security manager should be installed,
  • by -Djava.security.krb5.realm=<your_realm> that your Kerberos realm is the one specified. For example, if your realm is "KRBNT-OPERATIONS.ABC.COM" you'd put -Djava.security.krb5.realm=KRBNT-OPERATIONS.ABC.COM.
  • by -Djava.security.krb5.kdc=<your_kdc> that your Kerberos KDC is the one specified. For example, if your KDC is "samplekdc.abc.com" you'd put -Djava.security.krb5.kdc=samplekdc.abc.com.
  • by -Djava.security.policy=server.policy that the policy file to be used is server.policy, and
  • by -Djava.security.auth.login.config=csLogin.conf that the login configuration file to be used is csLogin.conf.

You pass the name of your application (in this case, "SampleServer") as an argument to Login. You then add as arguments any arguments required by your application, which in the case of SampleServer is a single argument specifying the port number to be used for listening for client connections. Choose a high port number unlikely to be used for anything else. An example would be something like 4444.

Below are the full commands to use for both Microsoft Windows and Unix systems. The only difference is that on Microsoft Windows systems you use semicolons to separate classpath items, while you use colons for that purpose on Unix systems.

Important: In these commands, you must replace <port_number> with an appropriate port number, <your_realm> with your Kerberos realm, and <your_kdc> with your Kerberos KDC.

Here is the command for Microsoft Windows systems:

java -classpath Login.jar;SampleServer.jar
 -Djava.security.manager
 -Djava.security.krb5.realm=<your_realm>
 -Djava.security.krb5.kdc=<your_kdc>
 -Djava.security.policy=server.policy
 -Djava.security.auth.login.config=csLogin.conf
 Login SampleServer <port_number>

Here is the command for UNIX systems:

java -classpath Login.jar:SampleServer.jar
 -Djava.security.manager
 -Djava.security.krb5.realm=<your_realm>
 -Djava.security.krb5.kdc=<your_kdc>
 -Djava.security.policy=server.policy
 -Djava.security.auth.login.config=csLogin.conf
 Login SampleServer <port_number>

Type the full command on one line. Multiple lines are used here for legibility. If the command is too long for your system, you may need to place it in a .bat file (for Microsoft Windows) or a .sh file (for UNIX) and then run that file to execute the command.

You will be prompted for the Kerberos password for the service principal. The underlying Kerberos authentication mechanism specified in the login configuration file will log the service principal into Kerberos. Once authentication is successfully completed, the SampleServer code will be executed on behalf of the service principal. It will listen for socket connections on the specified port.

For login troubleshooting suggestions, see Troubleshooting.

Execute SampleClient

To execute SampleClient, go to the directory in which you have prepared SampleClient for execution. Then execute the Login class, specifying

  • by an appropriate -classpath clause that classes should be searched for in the Login.jar and SampleClient.jar JAR files,
  • by -Djava.security.manager that a security manager should be installed,
  • by -Djava.security.krb5.realm=<your_realm> that your Kerberos realm is the one specified.
  • by -Djava.security.krb5.kdc=<your_kdc> that your Kerberos KDC is the one specified.
  • by -Djava.security.policy=client.policy that the policy file to be used is client.policy, and
  • by -Djava.security.auth.login.config=csLogin.conf that the login configuration file to be used is csLogin.conf.

Pass to Login the name of your application ("SampleClient") followed by the arguments required by SampleClient. The SampleClient arguments are (1) the Kerberos name of the service principal that represents SampleServer, (2) the name of the host (machine) on which SampleServer is running, and (3) the port number on which SampleServer is listening for client connections.

Below are the full commands to use for both Microsoft Windows and Unix systems.

Important: In these commands, you must replace <service_principal>, <host>, <port_number>, <your_realm>, and <your_kdc> with appropriate values (and note that the port number must be the same as the port number passed as an argument to SampleServer). These values need not be placed in quotes.

Here is the command for Microsoft Windows systems:

java -classpath Login.jar;SampleClient.jar
 -Djava.security.manager
 -Djava.security.krb5.realm=<your_realm>
 -Djava.security.krb5.kdc=<your_kdc>
 -Djava.security.policy=client.policy
 -Djava.security.auth.login.config=csLogin.conf
 Login SampleClient <service_principal> <host> <port_number>

Here is the command for UNIX systems:

java -classpath Login.jar:SampleClient.jar
 -Djava.security.manager
 -Djava.security.krb5.realm=<your_realm>
 -Djava.security.krb5.kdc=<your_kdc>
 -Djava.security.policy=client.policy
 -Djava.security.auth.login.config=csLogin.conf
 Login SampleClient <service_principal> <host> <port_number>

Type the full command on one line. Multiple lines are used here for legibility. As with the command for executing SampleServer, if the command is too long to type directly into your command window, place it in a .bat file (Microsoft Windows) or a .sh file (UNIX) and then execute that file.

When prompted, type your Kerberos user name and password. The underlying Kerberos authentication mechanism specified in the login configuration file will log you into Kerberos. Once authentication is successfully completed, the SampleClient code will be executed on behalf of you. It will request a socket connection with SampleServer. Once SampleServer accepts the connection, SampleClient and SampleServer establish a shared context and then exchange messages as described in this tutorial.

For login troubleshooting suggestions, see Troubleshooting.

Tutorials Introduction and TOC
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


ClipboardService (JNLP API Reference 1.7.0)

  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method
javax.jnlp

Interface ClipboardService

  • public interface ClipboardService
    ClipboardService provides methods for accessing the shared system-wide clipboard, even for applications that are running in the untrusted execution environment. Implementors should warn the user of the potential security risk of letting an untrusted application have access to potentially confidential information stored in the clipboard, or overwriting the contents of the clipboard.
    Since:
    1.0

    • Method Summary

      Methods
      Modifier and Type Method and Description
      java.awt.datatransfer.Transferable getContents()
      Returns a Transferable object representing the current contents of the clipboard.
      void setContents(java.awt.datatransfer.Transferable contents)
      Sets the current contents of the clipboard to the specified Transferable object.

    • Method Detail

      • getContents

        java.awt.datatransfer.Transferable getContents()
        Returns a Transferable object representing the current contents of the clipboard. If the clipboard currently has no contents, it returns null.
        Returns:
        The current Transferable object on the clipboard.

      • setContents

        void setContents(java.awt.datatransfer.Transferable contents)
        Sets the current contents of the clipboard to the specified Transferable object.
        Parameters:
        contents - The Transferable object representing clipboard content.
  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.


Uses of Class com.sun.jdi.connect.spi.ClosedConnectionException (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.connect.spi.ClosedConnectionException

No usage of com.sun.jdi.connect.spi.ClosedConnectionException
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Concurrent Mark Sweep Collector Enhancements

  • Description
  • System.gc() Performed Concurrently
  • Larger Default Young Generation Size
  • Parallel Marking
  • More Information

Description

The concurrent mark sweep collector, also known as the concurrent collector or CMS, is targeted at applications that are sensitive to garbage collection pauses. It performs most garbage collection activity concurrently, i.e., while the application threads are running, to keep garbage collection-induced pauses short. The key performance enhancements made to the CMS collector in JDK 6 are outlined below. See the documents referenced below for more detailed information on these changes, the CMS collector, and garbage collection in HotSpot.

Note that these features only apply when the CMS collector is in use; the option -XX:+UseConcMarkSweepGC selects the CMS collector.

System.gc() Performed Concurrently

The System.gc() and Runtime.getRuntime().gc() methods instruct the JVM to run the garbage collector to recycle unused objects. The HotSpot implementation of these methods currently stops all application threads to collect the entire heap, which can result in a lengthy pause particularly when the heap is large. This works against the goal of the CMS collector to keep pauses short.

In JDK 6, the CMS collector can optionally perform these collections concurrently, to avoid a lengthy pause in response to a System.gc() or Runtime.getRuntime().gc() call. To enable this feature, add the option

-XX:+ExplicitGCInvokesConcurrent

to the java command line.

Larger Default Young Generation Size

Several changes were made that increase the default size of the young generation when the CMS collector is used:

  • the minimum young generation size was increased from 4MB to 16MB.
  • the proportion of the overall heap used for the young generation was increased from 1/15 to 1/7.
  • the survivor spaces are now used by default, and their default size was increased. (In prior releases the survivor spaces were disabled by default with the CMS collector.)

The primary effect of these changes is to improve application performance by reducing garbage collection overhead. However, because the default young generation size is larger, applications may also see larger young generation pause times and a larger memory footprint. If necessary, please see the documents referenced below for more details on generations, survivor spaces and the options available for adjusting their sizes.

Parallel Marking

The CMS collector now uses multiple threads to perform the concurrent marking task in parallel on platforms with multiple processors. This reduces the duration of the concurrent marking cycle, allowing the collector to support applications with larger numbers of threads and higher object allocation rates, particularly on large multiprocessor machines. Prior releases used only a single thread for concurrent marking, limiting the collector's ability to keep up with applications with very high object allocation rates.

More Information

The HotSpot memory management whitepaper provides more detail about the CMS collector and the other collectors available in HotSpot, as well as descriptions of the generations, survivor spaces and other memory management concepts.

The HotSpot documentation page contains links to Garbage Collection Tuning Guides, specific to each release, which include guidelines for choosing the garbage collector that best suits your application and techniques that can help reduce garbage collection overhead.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Dynamic code downloading using Java RMI

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Dynamic code downloading using Java™ RMI
(Using the java.rmi.server.codebase Property)

This tutorial is organized as follows:

  1. Starting out
  2. What is a codebase?
  3. How does it work?
  4. Using codebase in Java RMI for more than just stub downloading
  5. Command-line examples
  6. Troubleshooting tips

1.0 Starting out

One of the most significant capabilities of the Java™ platform is the ability to dynamically download Java software from any Uniform Resource Locator (URL) to a virtual machine (VM) running in a separate process, usually on a different physical system. The result is that a remote system can run a program, for example an applet, which has never been installed on its disk. For the first few sections of this document, codebase with regard to applets will be discussed in order to help describe codebase with regard to Java Remote Method Invocation (Java RMI).

For example, a VM running from within a web browser can download the bytecodes for subclasses of java.applet.Applet and any other classes needed by that applet. The system on which the browser is running has most likely never run this applet before, nor installed it on its disk. Once all the necessary classes have been downloaded from the server, the browser can start the execution of the applet program using the local resources of the system on which the client browser is running.

Java RMI takes advantage of this capability to download and execute classes and on systems where those classes have never been installed on disk. Using the Java RMI API any VM, not only those in browsers, can download any Java class file including specialized Java RMI stub classes, which enable the execution of method calls on a remote server using the server system's resources.

The notion of a codebase originates from the use of ClassLoaders in the Java programming language. When a Java program uses a ClassLoader, that class loader needs to know the location(s) from which it should be allowed to load classes. Usually, a class loader is used in conjunction with an HTTP server that is serving up compiled classes for the Java platform. Most likely, the first ClassLoader/codebase pairing that you came into contact with was the AppletClassLoader, and the "codebase" part of the <applet> HTML tag, so this tutorial will assume that you have some experience with Java RMI programming, as well as writing HTML files that contain applet tags. For example, the HTML source will contain something like:

<applet height=100 width=100 codebase="myclasses/" code="My.class">
        <param name="ticker">
</applet>

2.0 What is a codebase?

A codebase can be defined as a source, or a place, from which to load classes into a virtual machine. For example, if you invited a new friend over for dinner, you would need to give that friend directions to the place where you lived, so that he or she could locate your house. Similarly, you can think of a codebase as the directions that you give to a VM, so it can find your [potentially remote] classes.

You can think of your CLASSPATH as a "local codebase", because it is the list of places on disk from which you load local classes. When loading classes from a local disk-based source, your CLASSPATH variable is consulted. Your CLASSPATH can be set to take either relative or absolute path names to directories and/or archives of class files. So just as CLASSPATH is a kind of "local codebase", the codebase used by applets and remote objects can be thought of as a "remote codebase".

3.0 How does it work?

3.1 How codebase is used in applets

To interact with an applet, that applet and any classes that it needs to run must be accessible by remote clients. While applets can be accessed from "ftp://" or local "file:///" URLs, they are usually accessed from a remote HTTP server.

  1. The client browser requests an applet class that is not found in the client's CLASSPATH
  2. The class definition of the applet (and any other class(es) that it needs) is downloaded from the server to the client using HTTP
  3. The applet executes on the client
illustrates three steps above

Figure 1: Downloading applets

The applet's codebase is always relative to the URL of the HTML page in which the <applet> tag is contained.

3.2 How codebase is used in Java RMI

Using Java RMI, applications can create remote objects that accept method calls from clients in other VMs. In order for a client to call methods on a remote object, the client must have a way to communicate with the remote object. Rather than having to program the client to speak the remote object's protocol, Java RMI uses special classes called stubs that can be downloaded to the client that are used to communicate with (make method calls on) the remote object. The java.rmi.server.codebase property value represents one or more URL locations from which these stubs (and any classes needed by the stubs) can be downloaded.

Like applets, the classes needed to execute remote method calls can be downloaded from "file:///" URLs, but like applets, a "file:///" URL generally requires that the client and the server reside on the same physical host, unless the file system referred to by the URL is made available using some other protocol, such as NFS.

Generally, the classes needed to execute remote method calls should be made accessible from a network resource, such as an HTTP or FTP server.

illustrates the first 5 steps of the stub downloadling process, as listed below

Figure 2: Downloading Java RMI stubs

  1. The remote object's codebase is specified by the remote object's server by setting the java.rmi.server.codebase property. The Java RMI server registers a remote object, bound to a name, with the Java RMI registry. The codebase set on the server VM is annotated to the remote object reference in the Java RMI registry.
  2. The Java RMI client requests a reference to a named remote object. The reference (the remote object's stub instance) is what the client will use to make remote method calls to the remote object.
  3. The Java RMI registry returns a reference (the stub instance) to the requested class. If the class definition for the stub instance can be found locally in the client's CLASSPATH , which is always searched before the codebase, the client will load the class locally. However, if the definition for the stub is not found in the client's CLASSPATH, the client will attempt to retrieve the class definition from the remote object's codebase.
  4. The client requests the class definition from the codebase. The codebase the client uses is the URL that was annotated to the stub instance when the stub class was loaded by the registry. Back in step 1, the annotated stub for the exported object was then registered with the Java RMI registry bound to a name.
  5. The class definition for the stub (and any other class(es) that it needs) is downloaded to the client.
    Note: Steps 4 and 5 are the sames steps that the registry took to load the remote object class, when the remote object was bound to a name in (registered with) the Java RMI registry. When the registry attempted to load the remote object's stub class, it requested the class definition from the codebase associated with that remote object.
  6. Now the client has all the information that it needs to invoke remote methods on the remote object. The stub instance acts as a proxy to the remote object that exists on the server; so unlike the applet which uses a codebase to execute code in its local VM, the Java RMI client uses the remote object's codebase to execute code in another, potentially remote VM, as illustrated in Figure 3:
illustrates the final step of the above procedure

Figure 3: Java RMI client making a remote method call

4.0 Using codebase in Java RMI for more than just stub downloading

In addition to downloading stubs and their associated classes to clients, the java.rmi.server.codebase property can be used to specify a location from which any class, not only stubs, can be downloaded.

When a client makes a method call to a remote object, the method that it calls could be written to accept no arguments or a number of arguments. There are three distinct cases that may occur, based on the data type(s) of the method argument(s).

In the first case, all of the method parameters (and return value) are primitive data types, so the remote object knows how to interpret them as method parameters, and there is no need to check its CLASSPATH or any codebase.

In the second case, at least one remote method parameter or the return value is an object, for which the remote object can find the class definition locally in its CLASSPATH.

In the third case (shown as Step 6, in Figure 4), the remote method receives an object instance, for which the remote object cannot find the class definition locally in its CLASSPATH. This type of remote method call is illustrated in Figure 4. The class of the object sent by the client will be a subtype of the declared parameter type. A subtype is either:

  • An implementation of the interface that is declared as the method parameter (or return) type
  • A subclass of the class that is declared as the method parameter (or return) type
Illustrates passing an unknown subtype as a method parameter, as described above and below.

Figure 4: Java RMI client making a remote method call, passing an unknown subtype as a method parameter

7. Like the applet's codebase, the client-specified codebase is used to download Remote classes, non-remote classes, and interfaces to other VMs. If the codebase property is set on the client application, then that codebase is annotated to the subtype instance when the subtype class is loaded by the client. If the codebase is not set on the client, the remote object will mistakenly use its own codebase.

5.0 Command-line examples

In the case of an applet, the applet codebase value is embedded in an HTML page, as we saw in the HTML example in the first section of this tutorial.

In the case of Java RMI codebase, rather than having a reference to the class embedded in an HTML page, the client first contacts the Java RMI registry for a reference to the remote object. Because the remote object's codebase can refer to any URL, not just one that is relative to a known URL, the value of the Java RMI codebase must be an absolute URL to the location of the stub class and any other classes needed by the stub class. This value of the codebase property can refer to:

  • The URL of a directory in which the classes are organized in package-named sub-directories
  • The URL of a JAR file in which the classes are organized in package-named directories
  • A space-delimited string containing multiple instances of JAR files and/or directories that meet the criteria above

Note: When the codebase property value is set to the URL of a directory, the value must be terminated by a "/".

Examples

If the location of your downloadable classes is on an HTTP server named "webvector", in the directory "export" (under the web root), your codebase property setting might look like this:

        -Djava.rmi.server.codebase=http://webvector/export/

If the location of your downloadable classes is on an HTTP server named "webline", in a JAR file named "mystuff.jar", in the directory "public" (under the web root), your codebase property setting might look like this:

        -Djava.rmi.server.codebase=http://webline/public/mystuff.jar

Now let's suppose that the location of your downloadable classes has been split between two JAR files, "myStuff.jar" and "myOtherStuff.jar". If these JAR files are located on different servers (named "webfront" and "webwave"), your codebase property setting might look like this:

        -Djava.rmi.server.codebase="http://webfront/myStuff.jar http://webwave/myOtherStuff.jar"

6.0 Troubleshooting tips

Any serializable class, including Java RMI stubs, can be downloaded if your Java RMI programs are configured properly. Here are the conditions under which dynamic stub downloading will work:

  1. The stub class and any of the classes that the stub relies on are served up from a URL reachable from the client.
  2. The java.rmi.server.codebase property has been set on the server program (or in the case of activation, the "setup" program) that makes the call to bind or rebind, such that:
    • The value of the codebase property is the URL in step A

      and

    • If the URL specified as the value of the codebase property is a directory, it must end in a trailing "/"

  3. The rmiregistry cannot find the stub class or any of the classes that the stub relies on in its CLASSPATH. This is so the codebase gets annotated to the stub when the registry does its class load of the stub, as a result of calls to bind or rebind in the server or setup code.
  4. The client has installed a SecurityManager that allows the stub to be downloaded. In the Java 2 SDK, Standard Edition, v1.2 and later, this means that the client must also have a properly configured security policy file.

There are two common problems associated with the java.rmi.server.codebase property, which are discussed next.

6.1 If you encounter a problem running your Java RMI server

The first problem you might encounter is the receipt of a ClassNotFoundException when attempting to bind or rebind a remote object to a name in the registry. This exception is usually due to a malformed codebase property, resulting in the registry not being able to locate the remote object's stubs or other classes needed by the stub.

It is important to note that the remote object's stub implements all the same interfaces as the remote object itself, so those interfaces, as well as any other custom classes declared as method parameters or return values, must also be available for download from the specified codebase.

Most frequently, this exception is thrown as a result of omitting the trailing slash from the URL value of the property. Other reasons would include: the value of the property is not a URL; the path to the classes specified in the URL is incorrect or misspelled; the stub class or any other necessary classes are not all available from the specified URL.

The exception that you may encounter in such a case would look like this:

java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
        java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
        java.lang.ClassNotFoundException: examples.callback.MessageReceiverImpl_Stub
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
        java.lang.ClassNotFoundException: examples.callback.MessageReceiverImpl_Stub
java.lang.ClassNotFoundException: examples.callback.MessageReceiverImpl_Stub
        at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Compiled Code)
        at sun.rmi.transport.StreamRemoteCall.executeCall(Compiled Code)
        at sun.rmi.server.UnicastRef.invoke(Compiled Code)
        at sun.rmi.registry.RegistryImpl_Stub.rebind(Compiled Code)
        at java.rmi.Naming.rebind(Compiled Code)
        at examples.callback.MessageReceiverImpl.main(Compiled Code)
RemoteException occurred in server thread; nested exception is:
        java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
        java.lang.ClassNotFoundException: examples.callback.MessageReceiverImpl_Stub

6.2 If you encounter a problem running your Java RMI client

The second problem you could encounter is the receipt of a ClassNotFoundException when attempting to lookup a remote object in the registry. If you receive this exception in a stacktrace resulting from an attempt to run your Java RMI client code, then your problem is the CLASSPATH with which your Java RMI registry was started. See requirement C in section 6.0. Here is what the exception will look like:

java.rmi.UnmarshalException: Return value class not found; nested exception is:
        java.lang.ClassNotFoundException: MyImpl_Stub
        at sun.rmi.registry.RegistryImpl_Stub.lookup(RegistryImpl_Stub.java:109
        at java.rmi.Naming.lookup(Naming.java:60)
        at RmiClient.main(MyClient.java:28)

Other resources

If you your codebase questions are still unanswered, please take a look through the archives of the rmi-users email list first.

You may wish to subscribe to the rmi-users email list.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Codebase Determination

Rich Internet Applications Deployment Advice > Codebase Determination

Contents
  • Codebase Computation Rules
    • Examples
  • Best Practices

Codebase Computation Rules

In a JNLP file, the codebase is an optional parameter to the <jnlp> tag. It is used both to locate resources described in that JNLP file, as well as to find the JNLP file itself. For technical reasons, Java Web Start is not able to refresh the contents of the JNLP file from the server unless an absolute codebase is specified.

In the new Java Plug-in introduced in the Java SE 6 update 10 release, a codebase is always provided by the browser, either because it was explicitly specified, or implicitly obtained from the location of the HTML document. This allows relative URLs to be used in JNLP files, which is very useful for moving an entire tree of content from one server to another.

JNLP files reference other JNLP files in a tree structure. The root JNLP file for a JNLP applet is referenced by an <applet> tag. The applet tag's codebase helps define the location of the root JNLP file.

The rules for codebase computation are as follows:

  • If an absolute codebase is specified in the JNLP file, it is used. This is required for backward compatibility reasons.
  • If the JNLP codebase is not specified, the directory containing the JNLP file is used.
  • Otherwise, merge the JNLP's codebase into the directory containing the JNLP file.

In simple Java terms, this can be expressed as

   URL new_codebase = new URL(current_jnlp_dir, current_jnlp_codebase);

This codebase computation is not an extension of JSR-56. JSR-56 does not restrict the codebase to be absolute, and therefore it may be relative.

Examples

Example 1:

   this JNLP's location:   http://www.sun.com/this.jnlp
   this JNLP's codebase:   http://www.foo.com/test/
   resulting codebase for
     parsing this JNLP:    http://www.foo.com/test/

Example 2:

   this JNLP's location:   http://www.sun.com/test2/this.jnlp
   this JNLP's codebase:   <none>
   resulting codebase for
     parsing this JNLP:    http://www.sun.com/test2/

Example 3:

   this JNLP's location:   http://www.sun.com/this.jnlp
   this JNLP's codebase:   codebasedir
   resulting codebase for
     parsing this JNLP:    http://www.sun.com/codebasedir

Example 4:

Relative paths are used to refer to each nested JNLP, just as in a tree of HTML files.

   www.sun.com/html/my_applet.html
     refers to: my_applet.jnlp
     codebase:  www.sun.com/html

     my_applet.jnlp:
       codebase not specified
       inherits "www.sun.com/html"
       references JNLP extension "jogl/jogl.jnlp"

     jogl/
       jogl.jnlp
       codebase not specified
       inherits "www.sun.com/html/jogl"
         (the directory containing jogl.jnlp)
       references gluegen-rt/gluegen-rt.jnlp

       gluegen-rt/
         gluegen-rt.jnlp
         codebase not specified
         inherits "www.sun.com/html/jogl/gluegen-rt"
           (the directory containing gluegen-rt.jnlp)

Best Practices

We recommend either:

  • Leaving the codebase empty for both the main or extension JNLP file, allowing the referencing JNLP file or <applet> tag to implicitly specify the codebase.
  • Specifying an absolute URL for the codebase of any main or extension JNLP file.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class javax.smartcardio.CommandAPDU (Java Smart Card I/O b138)

  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
javax.smartcardio.CommandAPDU

    • Uses of CommandAPDU in javax.smartcardio

      Methods in javax.smartcardio with parameters of type CommandAPDU
      Modifier and Type Method and Description
      abstract ResponseAPDU CardChannel.transmit(CommandAPDU command)
      Transmits the specified command APDU to the Smart Card and returns the response APDU.
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.Comment (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.Comment

  • Packages that use Comment
    Package Description
    org.w3c.dom
    Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.

    • Uses of Comment in org.w3c.dom

      Methods in org.w3c.dom that return Comment
      Modifier and Type Method and Description
      Comment Document.createComment(String data)
      Creates a Comment node given the specified string.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Appendix 4: Microsoft VM and Java Applet Compatibility Issues

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

< Contents

Appendix 2: Microsoft VM and Java Applet Compatibility Issues

See Java Upgrade Guide in the Java Deployment Guide.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


CORBA Compatibility Information

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

CORBA Compatibility Information - J2SE 5.0

  • CORBA API Changes Between J2SE 1.4.x and J2SE 5.0.x
  • Official Specifications for CORBA support in J2SE 5.0.x
  • Other Compatibility Information

CORBA API Changes Between J2SE 1.3 and J2SE 5.0

This document contains information regarding all of the API changes related to CORBA functionality between JDK 1.3 and 5.0. The changes have been made to make the APIs for the CORBA technology shipped in the JDK 5.0 compliant to the CORBA 2.3 mapping as specified by the following OMG documents:

  • CORBA 2.3.1 (formal/99-10-07)
  • IDL to Java language mapping (ptc/00-01-08)
  • Java to IDL language mapping (ptc/00-01-06)
  • Interoperable Naming Service (/ptc/00-08-07)
  • Portable Interceptors (ptc/2001-03-04)

API changes to org.omg.COSNaming classes

To comply with the IDL to Java mapping specified by the CORBA Version 2.3 specification, the following org.omg.COSNaming classes have been regenerated from the idlj compiler shipped with the JDK. This change (CCC 4284015) consists of the following API changes. Compatibility impact: None.

  1. To conform with CORBA V (2.3) All Helpers Section 1.5.2 Spec ptc/00-01-08.pdf, all Helpers are now abstract public classes. Below is the list of all Helper classes under org.omg.CosNaming that have been changed to abstract public classes.

    • BindingHelper.java
    • BindingIteratorHelper.java
    • BindingListHelper.java
    • BindingTypeHelper.java
    • IStringHelper.java
    • NameComponentHelper.java
    • NameHelper.java
    • NamingContextHelper.java
    • AlreadyBoundHelper.java
    • CannotProceedHelper.java
    • InvalidNameHelper.java
    • NotEmptyHelper.java
    • NotFoundHelper.java
    • NotFoundReasonHelper.java

    To conform with Section 1.7 OMG Spec ptc/00-01-08.pdf, Mapping for Enum, the mapping for the following Enum constructors is changed to protected.

    CLASS | BEFORE | NOW
    BindingType.java | private BindingType( int ) | protected BindingType( int )
    NotFoundReason.java | private NotFoundReason( int ) | protected NotFoundReason( int )

  2. To conform with CORBA 2.3 spec (ptc/00-01-08.pdf), Deletion of constructors in Stub classes, the following constructors have been deleted.

    CLASS | BEFORE | NOW
    _BindingIteratorStub.java | public _BindingIteratorStub(org.omg.CORBA.portable.Delegate d) | The constructor is deleted.
    _NamingContextStub.java | public _NamingContextStub(org.omg.CORBA.portable.Delegate d) | The constructor is deleted.

  3. To conform with CORBA 2.3 spec (ptc/00-01-08.pdf), the following exceptions have been changed.

    CLASS | BEFORE | NOW
    AlreadyBound.java | public final class AlreadyBound extends org.omg.CORBA.UserException implements org.omg.CORBA.portable.IDLEntity | public final class AlreadyBound extends org.omg.CORBA.UserException
    AlreadyBound.java | Only default constructor | Add new constructor public AlreadyBound (String reason)
    CannotProceed.java | public final class CannotProceed extends org.omg.CORBA.UserException implements org.omg.CORBA.portable.IDLEntity | public final class CannotProceed extends org.omg.CORBA.UserException
    CannotProceed.java | Only default constructor | Add new constructor public CannotProceed (String reason)
    InvalidName.java | public final class InvalidName extends org.omg.CORBA.UserException implements org.omg.CORBA.portable.IDLEntity | public final class InvalidName extends org.omg.CORBA.UserException
    InvalidName.java | Only default constructor | Add new constructor public InvalidName (String reason)
    NotEmpty.java | public final class NotEmpty extends org.omg.CORBA.UserException implements org.omg.CORBA.portable.IDLEntity | public final class NotEmpty extends org.omg.CORBA.UserException
    NotEmpty.java | Only default constructor | Add new constructor public NotEmpty (String reason)
    NotFound.java | public final class NotFound extends org.omg.CORBA.UserException implements org.omg.CORBA.portable.IDLEntity | public final class NotFound extends org.omg.CORBA.UserException
    NotFound.java | Only default constructor | Add new constructor public NotFound (String, org.omg.CosNaming.NamingContextPackage.NotFoundReason, org.omg.CosNaming.NameComponent[])

  4. To conform with the CORBA 2.3 specification, the following classes have been added.

    • NamingContextPOA.java
    • BindingIteratorPOA.java

  5. To conform with the CORBA 2.3 specification, the following classes are deprecated.

    • _NamingContextImplBase.java
    • _BindingIteratorImplBase.java

API changes to org.omg.CORBA

  • To conform to OMG spec 99-07-57, IDL to Java mapping, the following methods have been changed.
    • The signature of method org.omg.CORBA.Any.insert_fixed(java.math.BigDecimal, org.omg.CORBA.TypeCode) is changed to throw an org.omg.CORBA.Bad_INV_ORDER exception. System exception does not need to be declared in user's code. (CCC 4340915)
    • The method TypeCode.equivalent is defined as abstract. BEFORE: threw a NO_IMPLEMENT exception. Compatibility impact: Minimal impact for licensees, not for end user. Licensees need to provide a dummy implementation of this method. (CCC 4340932)
    • The method TypeCode.get_compact_typecode is defined as abstract. BEFORE: threw a NO_IMPLEMENT exception. Compatibility impact: Minimal impact for licensees, not for end user. Licensees need to provide a dummy implementation of this method. (CCC 4340932)
    • The mapping for the get_interface_def(org.omg.CORBA.Object) method in org.omg.CORBA.portable.Delegate.java is defined as abstract. Compatibility impact: Yes, a non-abstract method is converted to abstract. (CCC 4366071)
    • The mapping for the write_Principal() method in org.omg.CORBA.portable.OutputStream.java is no longer abstract. Compatibility impact: No, an abstract method is converted to non-abstract. (CCC 4366072)
    • The mapping for the read_Principal() method in org.omg.CORBA.portable.InputStream.java is no longer abstract. Compatibility impact: None, changing a method that is declared abstract to no longer be abstract does not break compatibility with pre-existing binaries. (CCC 4366074)
  • To conform to the CORBA 2.3 specification, the org.omg.DomainManagerOperations interface no longer extends org.omg.CORBA.Object. Compatibility impact: None, no CORBA program will use the DomainManagerOperations interface directly. The DomainManagerOperations interface can only be used by the programs via the DomainManager interface, which already extends org.omg.CORBA.Object. (CCC 4340907)
  • The following classes are declared as abstract and no longer have a private constructor. (CCC 4372196)
    • org.omg.CORBA.ServiceDetailHelper
    • org.omg.CORBA.ServiceInformationHelper
  • To conform with the IDL to Java spec in section 1.15.2, the default constructor javadoc comments in the following org.omg.CORBA files have been changed from COMPLETED_MAYBE to COMPLETED_NO. Compatibility impact: None. (CCC 4363355)
    • INTERNAL.java
    • INVALID_TRANSACTION.java
    • INV_OBJREF.java
  • The following Helper classes in org.omg.CORBA have been changed from public final to public abstract, and the default constructor for the Helper classes has been deleted. This change has been made to comply with the ORB core specification as defined by CORBA 2.3.1 and with the IDL/Java Language mapping as defined in ptc/00-01-08. Compatibility impact: Minimal since the Helper classes have been made 'abstract' as defined by the OMG IDL/Java Language mapping specification, applications which had previously instantiated a Helper class instance would fail. But the Helper class has only static methods in it, and there is no good reason for an application to create an instance of the Helper class. (CCC 4364208)
    • AnySeqHelper.java
    • BooleanSeqHelper.java
    • CharSeqHelper.java
    • DoubleSeqHelper.java
    • FloatSeqHelper.java
    • LongLongSeqHelper.java
    • LongSeqHelper.java
    • OctetSeqHelper.java
    • ShortSeqHelper.java
    • StringValueHelper.java
    • ULongLongSeqHelper.java
    • ULongSeqHelper.java
    • UShortSeqHelper.java
    • WCharSeqHelper.java
    • WStringValueHelper.java
  • To conform with the recently passed OMG issue 3015, which adds a new class, AbstractInterfaceDef to Interface Repository classes, we have added the following new constants to org.omg.CORBA.DefinitionKind. Compatibility impact: None. (CCC 4367601)
    • _dk_AbstractInterface=24. This is a constant that indicates that an Interface Repository object is representing an abstract object.
    • public static final DefinitionKind dk_AbstractInterface = new DefinitionKind(_dk_AbstractInterface). This is the static instance of DefinitionKind, indicating that an Interface Repository object represents an abstract interface.
  • The following org.omg.CORBA APIs for typecodes were changed to conform to the OMG specification. All of the classes in the following list are in the org.omg.CORBA package. Compatibility impact: Yes. See each change below for details. (CCC 4368800)
    • The Typecode methods fixed_digits, fixed_scale, member_visibility, type_modified, and concrete_base_type are changed from concrete to abstract. Typecode is always implemented by an ORB implementor and never subclassed by an ORB user, so this should not impact customers.
    • TCKind.from_int no longer throws the unchecked exception BAD_PARAM. Since BAD_PARAM is an unchecked exception, removing the exception should not affect customer code at compile time.
    • Principal is changed to a concrete class with methods that throw NO_IMPLEMENT from an abstract class with abstract methods. Principal is deprecated and rarely used. In any case, it would not generally be subclassed by a user and would always be fully implemented by an ORB implementor.
    • An extract_Streamable method is added to Any. Adding a method does not affect compatibility.
    • Any.insert_object( object, Typecode ) is changed to throw BAD_PARAM. Since BAD_PARAM is an unchecked exception, adding the exception should not affect customer code at compile time.
    • The Any methods insert_Streamable, extract_Principal, and insert_Principal are no longer abstract. Any is fully implemented by ORB implementors and never subclassed by ORB users, so this should not impact customers.
    • The Any methods extract_value and insert_value are changed to abstract. Any is fully implemented by ORB implementors and never subclassed by ORB users, so this should not impact customers.
  • The Identifier field is added to org.omg.CORBA.Initializer. Compatibility impact: None. (CCC 4372194)
  • To comply with ptc/00-01-08.pdf, the following classes are changed:
    • org.omg.CORBA.ORBPackage.InvalidName.java is declared as final. Compatibility impact: Yes. The InvalidName is being declared as final, which would impact source code that was subclassing this. Since it is an exception type, we do not anticipate this kind of behavior. (CCC 4366734)
    • org.omg.stub.java.rmi._Remote_Stub.java returns a clone of _type_ids. This will prevent mangling of the original type_ids_ array by external users. (CCC 4366734)
    • The from_int(Int i) method in org.omg.CORBA.SetOverrideType no longer throws a BAD_PARAM exception. Compatibility impact: No. Should not cause a compatibility problem since we are removing a throws declaration of an unchecked exception. (CCC 4369490)
    • The from_int(Int i) method in org.omg.CORBA.DefinitionKind no longer throws a BAD_PARAM exception. Compatibility impact: No. (CCC 4370659)
    • org.omg.CORBA.DynamicImplementation has been deprecated by the OMG in favor of the Portable Object Adapter (POA). A default invoke body is supplied. Compatibility impact: No. Should not impact anyone implementing this class. (CCC 4369490)
  • The following classes are changed to correct errors. Compatibility impact: No (CCC 4362556)
    • Helper and Holder classes are added to UnknownUserException.java. No compatibility impact.
    • Helper and Holder classes are added to WrongTransaction.java, and the class is declared final. No compatibility impact.
    • CompletionStatus.java is declared final, no longer implements IDLEntity, is changed to a private constructor. A BAD_PARAM RuntimeException will no longer explicitly be thrown by from_int. Compatibility impact: Yes. New code written using the new CompletionStatus.java class will not have to explicitly catch the BAD_PARAM runtime exception. If it's recompiled with an older JDK, it would get a compile-time error. -- These changes were undone due to JCK regression (4375061). An OMG issue has been filed instead (http://www.omg.org/issues/java-rtf.html#Issue3946).
    • INV_POLICY.java is declared as final. No compatibility impact.
  • The addition of portable interceptors requires a new method on existing CORBA APIs and four new classes generated from IDL typedefs. Compatibility impact: none, these changes are all additions. (CCC 4379826)
    • register_initial_reference is added in public class org.omg.CORBA.ORB.
    • New class org.omg.CORBA.StringSeqHelper is added for 2 IDL typedefs.
    • New class org.omg.CORBA.StringSeqHolder is added for 2 IDL typedefs.
    • New class org.omg.CORBA.WStringSeqHelper is added for 2 IDL typedefs.
    • New class org.omg.CORBA.WStringSeqHolder is added for 2 IDL typedefs.

API changes to javax.rmi.CORBA

To comply with OMG API specifications, the following changes have been made to javax.rmi.CORBA:
  • The protected constructor in javax.rmi.CORBA.Stub is removed. Compatibility impact: None. (CCC 4366722)
  • To comply with OMG specification 00-01-06.pdf, the jaxax.rmi.CORBA.ClassDesc constructor is removed. (CCC 4366734)

Non-API changes

The following non-API changes were also implemented in JDK 5.0.
  • Correct repository id computations. Compatibility impact: Yes. Added ORB versioning support to allow interoperability with the JDK 1.3 ORB, maintain backwards compatibility, and enable interoperability with other vendor ORBs. (CCC 4365188)
  • To conform with the recently passed OMG issue 3015, we have taken all Interface Repository-related version pragmas out of org.omg.CORBA.ir.idl. This also changes the Repository ID values of a few IR interfaces that we ship in org.omg.CORBA, for example, IDLTypeHelper, from

    private static String _id = "IDL:omg.org/CORBA/IDLType:2.3";
    to
    private static String _id = "IDL:omg.org/CORBA/IDLType:1.0";

    Compatibility impact: Yes. This change might affect interoperability with existing implementations. Restart the application and the IR if you get a COMM_FAILURE exception (or something similar). (CCC 4372718)

  • Added @serial exclude tags to all org.omg.* package files so that JAVADOC will ignore the whole package for the Serialization spec. There is no requirement from Object Management Group (OMG) to have Serialization compatibility between different versions. Practically speaking there are no use cases where the org.omg classes will be serialized in one version and de-serialized in the next version. Compatibility impact: None. (CCC 4394004)
  • Changed idlj compiler arguments in support of POA, which is a new CORBA feature in Merlin. Changes to the idlj tool arguments include:
    • removed undocumented -poa flag
    • enabled generation of standard POA-based skeletons by default
    • added a new flag, -oldImplBase, to allow generation of backward compatible skeletons (compatible with JDK 1.2 and 1.3)

    Compatibility impact: Yes, existing programs that use the compiler may need to add the -oldImplBase flag to their idlj invocation to maintain compatibility. (CCC 4407835)

New API

The following new API were added to JDK 5.0.
  • The PortableInterceptor API is added. An incorrect specification, ptc/2000-04-05, was being referenced in the test plan. Another incorrect specification, orbos/99-12-02 was being referenced in the feature list (ptc/2000-04-05 is the same as orbos/99-12-02 except the format has changed). The correct specification reference for this new API is http://www.omg.org/cgi-gin/doc?ptc/2001-03-04. CCC 4307834 includes the list of changes/additions from ptc/2000-04-05. Compatibility impact: none, this is a new feature so no existing code uses it.
  • The addition of portable interceptors requires a new method, id, in public interface org.omg.PortableServer.POA.

Official Specifications for CORBA support in J2SE 5.0

Specification References

The specifications with which the Java 2 Platform Standard Edition (J2SE) 5.0 ORB complies are as follows. If these links do not take you to the referenced specification, the OMG may have changed the URL, and you can link to www.omg.org to search for the correct specification.
  • CORBA 2.3.1 (formal/99-10-07)
  • IDL to Java language mapping (ptc/00-01-08)
  • Revised IDL to Java language mapping (ptc/00-11-03)
  • Java to IDL language mapping (ptc/00-01-06)
  • Interoperable Naming Service (ptc/00-08-07)
  • Portable Interceptors (ptc/2001-08-31)
These are the only specifications referenced by this document.

Supported Specification Details

Not all of the above specifications are currently implemented in the ORB in J2SE 5.0. The precise list of supported sections is as follows:
  • CORBA 2.3.1 chapters 1-3 and 6-9
  • Revised IDL to Java language mapping, section 1.21.8.2, the orb.properties file.
  • CORBA 2.3.1 chapter 4 with the following replacements from the Portable Interceptors specification:
    • section 4.2.3.5 destroy
    • section 4.5.2 CodeFactory and PICurrent are required
    • Section 4.5.3.4 as updated for register_initial_reference
  • CORBA 2.3.1 chapter 5 with the following update from the Portable Interceptors specification:
    • 5.5.2 StringSeq and WStringSeq are required. This adds the following classes to org.omg.CORBA:
      • StringSeqHolder
      • StringSeqHelper
      • WStringSeqHolder
      • WStringSeqHelper
  • CORBA 2.3.1 sections 10.6.1 and 10.6.2 are supported for repository IDs.
  • CORBA 2.3.1 section 10.7 for TypeCode APIs.
  • CORBA 2.3.1 chapter 11, Portable Object Adapter (POA), with the following updates from the Portable Interceptors specification:
    • Section 11.3.7 POAs must preserve all policies
    • Section 11.3.8.2 again states that POAs must preserve all policies
    • Section 11.3.8.26 POA::id is required.
  • CORBA 2.3.1 chapters 13 and 15 define GIOP 1.0, 1.1, and 1.2. The J2SE 5.0 ORB fully supports all versions of GIOP, with the exception that the bi-directional GIOP feature defined in sections 15.8 and 15.9 is not supported.
  • All of the Interoperable Naming Service is supported.
  • Portable Interceptors section 13.8 (the new Coder/Decoder interfaces) and all of chapter 21 (the interceptor specification).
  • Section 1.21.8 of the Revised IDL to Java Language Mapping Specification (ptc/00-11-03) has been changed from the version in the IDL to Java Language Mapping Specification (ptc/00-01-08).

Tools

  • The IDL to Java compiler (idlj) complies with:
    • CORBA 2.3.1 chapter 3 (IDL definition)
    • CORBA 2.3.1 chapters 5 and 6 (semantics of Value types)
    • CORBA 2.3.1 section 10.6.5 (pragmas)
    • The IDL to Java mapping specification
    • The Revised IDL to Java language mapping specification section 1.12.1 "local interfaces"
  • The Java to IDL compiler (the IIOP backend for rmic) complies with:
    • CORBA 2.3.1 chapters 5 and 6 (value types)
    • The Java to IDL language mapping. Note that this implicitly references section 1.21 of the IDL to Java language mapping
    • IDL generated by the -idl flag complies with CORBA 2.3.1 chapter 3.

Other Compatibility Information

  • The class java.util.Calendar is not interoperable between J2SE 1.3.x and J2SE 5.0 when using RMI-IIOP. OMG issue 3151 may resolve this, but it will probably have to be implemented in a later release of the Java platform.

    The J2SE 5.0 version of Calendar writes a ZoneInfo object in its writeObject method. Similarly, it calls readObject to read this. Based on Java Object Serialization, it expects that if it's talking to an older version, the object won't be there, so the stream will throw an EOFException and keep the stream position intact.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.source.tree.CompilationUnitTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.CompilationUnitTree

  • Packages that use CompilationUnitTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of CompilationUnitTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type CompilationUnitTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitCompilationUnit(CompilationUnitTree node, P p)

    • Uses of CompilationUnitTree in com.sun.source.util

      Methods in com.sun.source.util that return CompilationUnitTree
      Modifier and Type | Method and Description
      CompilationUnitTree TreePath.getCompilationUnit()
      Get the compilation unit associated with this path.
      CompilationUnitTree | TaskEvent.getCompilationUnit()
      Methods in com.sun.source.util that return types with arguments of type CompilationUnitTree
      Modifier and Type Method and Description
      abstract Iterable<? extends CompilationUnitTree> JavacTask.parse()
      Parse the specified files returning a list of abstract syntax trees.
      Methods in com.sun.source.util with parameters of type CompilationUnitTree
      Modifier and Type | Method and Description
      long SourcePositions.getEndPosition(CompilationUnitTree file, Tree tree)
      Gets the ending position of tree within file.
      abstract TreePath Trees.getPath(CompilationUnitTree unit, Tree node)
      Gets the path to tree node within the specified compilation unit.
      static TreePath TreePath.getPath(CompilationUnitTree unit, Tree target)
      Gets a tree path for a tree node within a compilation unit.
      long SourcePositions.getStartPosition(CompilationUnitTree file, Tree tree)
      Gets the starting position of tree within file.
      abstract void Trees.printMessage(Diagnostic.Kind kind, CharSequence msg, Tree t, CompilationUnitTree root)
      Prints a message of the specified kind at the location of the tree within the provided compilation unit
      R | TreeScanner.visitCompilationUnit(CompilationUnitTree node, P p)
      R | SimpleTreeVisitor.visitCompilationUnit(CompilationUnitTree node, P p)
      Constructors in com.sun.source.util with parameters of type CompilationUnitTree
      Constructor and Description
      TaskEvent(TaskEvent.Kind kind, CompilationUnitTree unit)
      TaskEvent(TaskEvent.Kind kind, CompilationUnitTree unit, TypeElement clazz)
      TreePath(CompilationUnitTree t)
      Creates a TreePath for a root node.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Official Specifications for CORBA support in J2SE 5.0

Specification References

The specifications with which the Java 2 Platform Standard Edition (J2SE) 5.0 ORB complies are as follows. If these links do not take you to the referenced specification, the OMG may have changed the URL, and you can link to www.omg.org to search for the correct specification.
  • CORBA 2.3.1 (formal/99-10-07)
  • IDL to Java language mapping (ptc/00-01-08)
  • Revised IDL to Java language mapping (ptc/00-11-03)
  • Java to IDL language mapping (ptc/00-01-06)
  • Interoperable Naming Service (ptc/00-08-07)
  • Portable Interceptors (ptc/2001-08-31)
These are the only specifications referenced by this document.

Supported Specification Details

Not all of the above specifications are currently implemented in the ORB in J2SE 5.0. The precise list of supported sections is as follows:
  • CORBA 2.3.1 chapters 1-3 and 6-9
  • Revised IDL to Java language mapping, section 1.21.8.2, the orb.properties file.
  • CORBA 2.3.1 chapter 4 with the following replacements from the Portable Interceptors specification:
    • section 4.2.3.5 destroy
    • section 4.5.2 CodeFactory and PICurrent are required
    • Section 4.5.3.4 as updated for register_initial_reference
  • CORBA 2.3.1 chapter 5 with the following update from the Portable Interceptors specification:
    • 5.5.2 StringSeq and WStringSeq are required. This adds the following classes to org.omg.CORBA:
      • StringSeqHolder
      • StringSeqHelper
      • WStringSeqHolder
      • WStringSeqHelper
  • CORBA 2.3.1 sections 10.6.1 and 10.6.2 are supported for repository IDs.
  • CORBA 2.3.1 section 10.7 for TypeCode APIs.
  • CORBA 2.3.1 chapter 11, Portable Object Adapter (POA), with the following updates from the Portable Interceptors specification:
    • Section 11.3.7 POAs must preserve all policies
    • Section 11.3.8.2 again states that POAs must preserve all policies
    • Section 11.3.8.26 POA::id is required.
  • CORBA 2.3.1 chapters 13 and 15 define GIOP 1.0, 1.1, and 1.2. The J2SE 5.0 ORB fully supports all versions of GIOP, with the exception that the bi-directional GIOP feature defined in sections 15.8 and 15.9 is not supported.
  • All of the Interoperable Naming Service is supported.
  • Portable Interceptors section 13.8 (the new Coder/Decoder interfaces) and all of chapter 21 (the interceptor specification).
  • Section 1.21.8 of the Revised IDL to Java Language Mapping Specification (ptc/00-11-03) has been changed from the version in the IDL to Java Language Mapping Specification (ptc/00-01-08).

Tools

  • The IDL to Java compiler (idlj) complies with:
    • CORBA 2.3.1 chapter 3 (IDL definition)
    • CORBA 2.3.1 chapters 5 and 6 (semantics of Value types)
    • CORBA 2.3.1 section 10.6.5 (pragmas)
    • The IDL to Java mapping specification
    • The Revised IDL to Java language mapping specification section 1.12.1 "local interfaces"
  • The Java to IDL compiler (the IIOP backend for rmic) complies with:
    • CORBA 2.3.1 chapters 5 and 6 (value types)
    • The Java to IDL language mapping. Note that this implicitly references section 1.21 of the IDL to Java language mapping
    • IDL generated by the -idl flag complies with CORBA 2.3.1 chapter 3.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.source.tree.CompoundAssignmentTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.CompoundAssignmentTree

  • Packages that use CompoundAssignmentTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of CompoundAssignmentTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type CompoundAssignmentTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitCompoundAssignment(CompoundAssignmentTree node, P p)

    • Uses of CompoundAssignmentTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type CompoundAssignmentTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitCompoundAssignment(CompoundAssignmentTree node, P p)
      R | SimpleTreeVisitor.visitCompoundAssignment(CompoundAssignmentTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.ConditionalExpressionTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.ConditionalExpressionTree

  • Packages that use ConditionalExpressionTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of ConditionalExpressionTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type ConditionalExpressionTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitConditionalExpression(ConditionalExpressionTree node, P p)

    • Uses of ConditionalExpressionTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type ConditionalExpressionTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitConditionalExpression(ConditionalExpressionTree node, P p)
      R | SimpleTreeVisitor.visitConditionalExpression(ConditionalExpressionTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.auth.login.ConfigFile (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.login.ConfigFile

No usage of com.sun.security.auth.login.ConfigFile
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.jdi.connect.spi.Connection (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.connect.spi.Connection

  • Packages that use Connection
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.
    com.sun.jdi.connect.spi
    This package comprises the interfaces and classes used to develop new TransportService implementations.

    • Uses of Connection in com.sun.jdi

      Methods in com.sun.jdi with parameters of type Connection
      Modifier and Type Method and Description
      VirtualMachine VirtualMachineManager.createVirtualMachine(Connection connection)
      Creates a new virtual machine.
      VirtualMachine VirtualMachineManager.createVirtualMachine(Connection connection, Process process)
      Create a virtual machine mirror for a target VM.

    • Uses of Connection in com.sun.jdi.connect.spi

      Methods in com.sun.jdi.connect.spi that return Connection
      Modifier and Type Method and Description
      abstract Connection TransportService.accept(TransportService.ListenKey listenKey, long acceptTimeout, long handshakeTimeout)
      Accept a connection from a target VM.
      abstract Connection TransportService.attach(String address, long attachTimeout, long handshakeTimeout)
      Attaches to the specified address.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Orderly (and Abortive) Connection Release in Java

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Orderly Versus Abortive Connection Release in Java

This article covers the following topics:

  • Overview
  • Description of the Problem
  • How to Avoid the Problem

Overview

To ensure orderly or graceful release of TCP connections is a challenge with TCP networking applications. Abortive or ungraceful release may result if special care is not taken. In Java, an unexpected abortive release can manifest itself by the application receiving a java.net.SocketException when reading or writing to the socket. read() and write() normally return a numeric value indicating, respectively, the number of bytes received or sent. If an exception is received instead, this indicates the connection has been aborted and also that data may have been lost or discarded. This article explains what causes socket connections to be aborted and provides tips for avoiding the situation, except for the case where an application intends to abort the connection.

Description of the Problem

First, we need to distinguish the differences between an abortive and an orderly connection release. To understand this distinction we need to look at what happens at the TCP protocol level. It is helpful to imagine an established TCP connection as actually two separate, semi-independent streams of data. If the two peers are A and B, then one stream delivers data from A to B, and the other stream from B to A. An orderly release occurs in two stages. First one side (say A) decides to stop sending data and sends a FIN message across to B. When the TCP stack at B's side receives the FIN it knows that no more data is coming from A, and whenever B reads all preceding data off the socket, further reads will return the value -1 to indicate end-of-file. This procedure is known as the TCP half-close, because only one half of the connection is closed. Not surprisingly, the procedure for the other half is exactly the same. B sends a FIN message to A, who eventually receives a -1 after reading all preceding data sent by A off the socket.

By contrast, an abortive close uses the RST (Reset) message. If either side issues an RST, this means the entire connection is aborted and the TCP stack can throw away any queued data which has not been sent or received by either application.

So, how do Java applications perform orderly and abortive releases? Let's consider abortive releases first. A convention that has existed since the days of the original BSD sockets is that the "linger" socket option can be used to force an abortive connection release. Either application can call Socket.setLinger (true, 0) to tell the TCP stack that when this socket is closed, the abortive (RST) procedure is to be used. Setting the linger option has no immediate effect, except that when Socket.close() is called subsequently, the connection is aborted with an RST message. As we will see shortly, there are other ways that may cause a connection to be aborted, but this is the simplest way to make it happen.

The close() method is also used to perform orderly release, as well as abortive. So, at its simplest, the difference between an orderly release and an abortive release could be as little as not setting the linger(0) option, described above, prior to calling Socket.close(). Take the example of two connected peers A and B: If A calls Socket.close(), a FIN message is sent from A to B; and when B calls Socket.close(), a FIN is sent from B to A. In fact, the default setting for the linger option is to not use abortive close; so if two applications terminate their connection just by using Socket.close(), then the outcome should be an orderly release. So what, then, is the problem?

The problem is a slight mismatch between the semantics of Socket.close() and the TCP FIN message. Sending a TCP FIN message means "I am finished sending", whereas Socket.close() means "I am finished sending and receiving." When you call Socket.close(), clearly it is no longer possible to send data; nor, however, is it possible to receive data. So what happens, for example, when A attempts an orderly release by closing the socket, but B continues to send data? This is perfectly allowable in the TCP specification, because as far as TCP is concerned only one half of the connection has been closed. But since A's socket is closed there is nobody to read data if B should continue sending. In this situation A's TCP stack must send an RST to forcibly terminate the connection.

Another common scenario, which may result in an unintended SocketException, is the following: Say A has sent data to B, but B closes the socket without reading all the data. In this situation, B's TCP stack knows that some data is effectively lost and it will forcibly terminate with RST rather than use the orderly FIN procedure. A will get a SocketException if it then tries to send or receive data from the socket.

How to avoid the problem

There are a number of simple ways to avoid being surprised by this problem.

  1. Structure data with a higher-level protocol. Protocols such as HTTP, which are built on top of TCP, deal with the issue by making it clear to both sides when it is safe to close the socket.
  2. Always consume data from a socket before closing it. This will help avoid the second scenario described above.
  3. Use shutdownOutput(). This method has the same effect as close() in that a FIN is sent to indicate that this peer has finished sending, but it is still possible to read from the socket until such time as the remote peer sends a FIN and end-of-file is read from the stream. Then the socket can be closed with Socket.close().
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.connect.Connector (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.connect.Connector

  • Packages that use Connector
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.
    com.sun.jdi.connect
    This package defines connections between the virtual machine using the JDI and the target virtual machine.

    • Uses of Connector in com.sun.jdi

      Methods in com.sun.jdi that return types with arguments of type Connector
      Modifier and Type Method and Description
      List<Connector> VirtualMachineManager.allConnectors()
      Returns the list of all known Connector objects.

    • Uses of Connector in com.sun.jdi.connect

      Subinterfaces of Connector in com.sun.jdi.connect
      Modifier and Type Interface and Description
      interface  AttachingConnector
      A connector which attaches to a previously running target VM.
      interface  LaunchingConnector
      A connector which can launch a target VM before connecting to it.
      interface  ListeningConnector
      A connector which listens for a connection initiated by a target VM.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.connect.Connector.Argument (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.connect.Connector.Argument

  • Packages that use Connector.Argument
    Package Description
    com.sun.jdi.connect
    This package defines connections between the virtual machine using the JDI and the target virtual machine.

    • Uses of Connector.Argument in com.sun.jdi.connect

      Subinterfaces of Connector.Argument in com.sun.jdi.connect
      Modifier and Type Interface and Description
      static interface  Connector.BooleanArgument
      Specification for and value of a Connector argument, whose value is Boolean.
      static interface  Connector.IntegerArgument
      Specification for and value of a Connector argument, whose value is an integer.
      static interface  Connector.SelectedArgument
      Specification for and value of a Connector argument, whose value is a String selected from a list of choices.
      static interface  Connector.StringArgument
      Specification for and value of a Connector argument, whose value is a String.
      Methods in com.sun.jdi.connect that return types with arguments of type Connector.Argument
      Modifier and Type Method and Description
      Map<String,Connector.Argument> Connector.defaultArguments()
      Returns the arguments accepted by this Connector and their default values.
      Method parameters in com.sun.jdi.connect with type arguments of type Connector.Argument
      Modifier and Type Method and Description
      VirtualMachine ListeningConnector.accept(Map<String,? extends Connector.Argument> arguments)
      Waits for a target VM to attach to this connector.
      VirtualMachine AttachingConnector.attach(Map<String,? extends Connector.Argument> arguments)
      Attaches to a running application and and returns a mirror of its VM.
      VirtualMachine LaunchingConnector.launch(Map<String,? extends Connector.Argument> arguments)
      Launches an application and connects to its VM.
      String ListeningConnector.startListening(Map<String,? extends Connector.Argument> arguments)
      Listens for one or more connections initiated by target VMs.
      void ListeningConnector.stopListening(Map<String,? extends Connector.Argument> arguments)
      Cancels listening for connections.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.connect.Connector.BooleanArgument (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.connect.Connector.BooleanArgument

No usage of com.sun.jdi.connect.Connector.BooleanArgument
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.connect.Connector.IntegerArgument (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.connect.Connector.IntegerArgument

No usage of com.sun.jdi.connect.Connector.IntegerArgument
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.connect.Connector.SelectedArgument (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.connect.Connector.SelectedArgument

No usage of com.sun.jdi.connect.Connector.SelectedArgument
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.connect.Connector.StringArgument (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.connect.Connector.StringArgument

No usage of com.sun.jdi.connect.Connector.StringArgument
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Contents | Previous | Next Java Management Extensions (JMX) Technology Tutorial

Chapter 3

JMX Connectors

This chapter introduces the concepts of standard and dynamic management beans (MBeans) and also shows how to use Java Management Extensions (JMX) technology to perform operations on MBeans, both locally and remotely.

Accessing Standard and Dynamic MBeans via the RMI Connector

This example demonstrates standard and dynamic MBeans only.

As seen in Chapter 2, "Essentials of the JMX API", a standard MBean is one that statically defines its management interface through the names of the methods it contains. A dynamic MBean implements a specific Java interface and reveals its attributes and operations at run time.

The JMX technology defines a connector based on RMI. The RMI connector supports the standard RMI transports, Java Remote Method Protocol (JRMP) and the Internet Inter-Object Request Broker (ORB) Protocol (IIOP). This connector allows you to connect to an MBean in an MBean server from a remote location, and perform operations on it, exactly as if the operations were being performed locally.

The purpose of this example is to demonstrate the implementation of a standard MBean and a dynamic MBean. It also shows how to perform operations on them, both locally, and remotely through an RMI connection between a server and a remote client.

When you run this example:

  • The server:
  • Creates an MBean server
  • Registers a SimpleStandard and a SimpleDynamic MBean in the local MBean server
  • Performs local operations on the MBeans
  • Creates an RMI connector server
  • The client:
  • Creates an RMI connector
  • Registers a SimpleStandard and a SimpleDynamic MBean on the remote MBean server
  • Performs remote operations on both MBeans

The RMI connector example is contained in the directory work_dir/jmx_examples/Basic.

  2. Open the work_dir/jmx_examples/Basic directory.

    Inside this directory, you will find the following files:

    • Server.java
    • SimpleStandardMBean.java
    • SimpleStandard.java
    • SimpleDynamic.java
    • ClientListener.java
    • Client.java
    • README
  3. Open each of the *.java files in a text editor.

Analyzing the Example Classes

The following sections analyze each of the classes used in the basic MBean example, and explain how they perform the operations described in the preceding section.

Server.java

Due to its size, the Server.java class is shown in several code excerpts.

CODE EXAMPLE 3-1 MBean Example Class Server.java (Excerpt 1)

public class Server {

 public static void main(String[] args) {
     try {

         MBeanServer mbs = MBeanServerFactory.createMBeanServer();
         waitForEnterPressed();

         String domain = mbs.getDefaultDomain();
         waitForEnterPressed();

         String mbeanClassName = "SimpleStandard";
         String mbeanObjectNameStr =
             domain + ":type=" + mbeanClassName + ",name=1";
         ObjectName mbeanObjectName =
             createSimpleMBean(mbs, mbeanClassName, mbeanObjectNameStr);
         waitForEnterPressed();

         printMBeanInfo(mbs, mbeanObjectName, mbeanClassName);
         waitForEnterPressed();

         manageSimpleMBean(mbs, mbeanObjectName, mbeanClassName);
         waitForEnterPressed();

         mbeanClassName = "SimpleDynamic";
         mbeanObjectNameStr =
             domain + ":type=" + mbeanClassName + ",name=1";
         mbeanObjectName =
             createSimpleMBean(mbs, mbeanClassName, mbeanObjectNameStr);
         waitForEnterPressed();

         printMBeanInfo(mbs, mbeanObjectName, mbeanClassName);
         waitForEnterPressed();

         manageSimpleMBean(mbs, mbeanObjectName, mbeanClassName);
         waitForEnterPressed();

         [...]

Examining this class, you can see that the following occurs:

Firstly, the Server.java class creates a new MBean server called mbs by calling the createMBeanServer() method of the MBeanServerFactory class.

Then, the default domain in which the MBean server is registered is obtained with a call to the getDefaultDomain() method of the MBeanServer interface. The domain is identified by the string domain.

The MBean class named SimpleStandard is also identified by a variable, in this case the string mbeanClassName. SimpleStandard is the name of the Java class for the Java object of which this MBean is an instance. The SimpleStandard.java object is examined in Section "SimpleStandard.java".

Another variable, the string mbeanObjectNameStr, is defined as the combination of the domain, plus the following key=value pairs:

  • The type, which in this case is the mbeanClassName.
  • A name, to differentiate this MBean from other MBeans of the same type that might be created subsequently. In this case the name number is 1.

The purpose of mbeanObjectNameStr is to give the MBean a human-readable identifier.

A call to createSimpleMBean() creates and registers the SimpleStandard MBean in the local MBean server, with the given object name.

The operations printMBeanInfo(), and manageSimpleMBean() are then performed on the SimpleStandard MBean. Like createSimpleMBean(), these methods are defined later in the Server.java code, and are shown in CODE EXAMPLE 3-4 and CODE EXAMPLE 3-5.

In code that is not shown here, a second MBean of the type SimpleDynamic is created and registered in the MBean server in exactly the same way as the SimpleStandard MBean. As the name suggests, this MBean is an instance of the SimpleDynamic Java object, which is examined in Section "SimpleDynamic.java".

CODE EXAMPLE 3-2 MBean Example Class Server.java (Excerpt 2)

[...]

JMXServiceURL url =
  new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/server");
JMXConnectorServer cs =
  JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
cs.start();
waitForEnterPressed();
cs.stop();

[...]

In CODE EXAMPLE 3-2, an RMI connector server is created so that operations can be performed on the MBeans remotely. A call to the class JMXServiceURL creates a new service URL called url, which serves as an address for the connector server. In this example, the service URL is given in JNDI form, rather than in encoded form (see the API documentation for the javax.management.remote.rmi package for an explanation of JNDI form). This service URL defines the following:

  • The connector will use the default RMI transport, denoted by rmi.
  • The RMI registry in which the RMI connector stub will be stored will be running on port 9999 on the local host, and the server address will be registered under the name server. The port 9999 specified in the example is arbitrary; you can use any available port.

An RMI connector server named cs is created by calling the constructor JMXConnectorServerFactory, with the service URL url, a null environment map, and the MBean server mbs as parameters. The connector server cs is launched by calling the start() method of JMXConnectorServer, whereupon RMIConnectorServer exports the RMI object server to the RMI registry. The connection will remain open until the Enter key is pressed, as instructed by the simple method waitForEnterPressed, that is defined later in the Server code.

CODE EXAMPLE 3-3 MBean Example Class Server.java (Excerpt 3)

[...]

private static ObjectName createSimpleMBean(MBeanServer mbs,
                                              String mbeanClassName,
                                              String mbeanObjectNameStr) {
     echo("\n>>> Create the " + mbeanClassName +
          " MBean within the MBeanServer");
     echo("ObjectName = " + mbeanObjectNameStr);
     try {
          ObjectName mbeanObjectName =
             ObjectName.getInstance(mbeanObjectNameStr);
          mbs.createMBean(mbeanClassName, mbeanObjectName);
             return mbeanObjectName;
          } catch (Exception e) {
            echo(       "!!! Could not create the " +
                  mbeanClassName + " MBean !!!");
            e.printStackTrace();
            echo("\nEXITING...\n");
            System.exit(1);
        }
        return null;
     }

[...]

CODE EXAMPLE 3-3 shows the definition of the createSimpleMBean() method. In this method, the MBean instance with the object name mbeanObjectNameStr is passed to the getInstance() method of the ObjectName interface to create a new object name for registering the MBean inside the MBean server. The resulting object name instance is named mbeanObjectName. A call to the MBeanServer method createMBean() then instantiates an MBean defined by the combination of the Java object identified by mbeanClassName and the MBean instance mbeanObjectName and registers this MBean in the MBean server mbs.

CODE EXAMPLE 3-4 MBean Example Class Server.java (Excerpt 4)
[...]

private static void printMBeanInfo(MBeanServer mbs,
                                     ObjectName mbeanObjectName,
                                     String mbeanClassName) {
     MBeanInfo info = null;
     try {
         info = mbs.getMBeanInfo(mbeanObjectName);
     } catch (Exception e) {
         echo(  "!!! Could not get MBeanInfo object for " +
         mbeanClassName +" !!!");
         e.printStackTrace();
         return;
     }

     MBeanAttributeInfo[] attrInfo = info.getAttributes();
     if (attrInfo.length > 0) {
         for (int i = 0; i < attrInfo.length; i++) {
        echo(" ** NAME:    " + attrInfo[i].getName());
        echo("    DESCR:   " + attrInfo[i].getDescription());
        echo("    TYPE:    " + attrInfo[i].getType() +
                "READ: "+ attrInfo[i].isReadable() +
                "WRITE: "+ attrInfo[i].isWritable());
        }
     } else echo(" ** No attributes **");

[...]

In CODE EXAMPLE 3-4 we see the definition of the method printMBeanInfo(). The printMBeanInfo() method calls the MBeanServer method getMBeanInfo() to obtain details of the attributes and operations that are exposed by the MBean mbeanObjectName. MBeanAttributeInfo defines the following methods, each of which is called in turn to obtain information about the mbeanObjectName MBean’s attributes:

  • getName, to obtain the attribute’s name.
  • getDescription, to obtain the human readable description of the attribute.
  • getType, to obtain the class name of the attribute.
  • isReadable, to determine whether or not the attribute is readable.
  • isWritable, to determine whether or not the attribute is writable.

In code that is not shown here, calls are made to obtain information about the mbeanObjectName MBean’s constructors, operations and notifications:

  • MBeanConstructorInfo, to obtain information about the MBean’s Java class.
  • MBeanOperationInfo, to learn what operations the MBean performs, and what parameters it takes.
  • MBeanNotificationInfo, to find out what notifications the MBean sends when its operations are performed.
CODE EXAMPLE 3-5 MBean Example Class Server.java (Excerpt 5)
[...]

private static void manageSimpleMBean(MBeanServer mbs,
                                        ObjectName mbeanObjectName,
                                        String mbeanClassName) {
        try {
            printSimpleAttributes(mbs, mbeanObjectName);

            Attribute stateAttribute = new Attribute("State",
                                                     "new state");
            mbs.setAttribute(mbeanObjectName, stateAttribute);

            printSimpleAttributes(mbs, mbeanObjectName);

            echo("\n    Invoking reset operation...");
            mbs.invoke(mbeanObjectName, "reset", null, null);

            printSimpleAttributes(mbs, mbeanObjectName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void printSimpleAttributes(
                                        MBeanServer mbs,
                                        ObjectName mbeanObjectName) {
        try {
            String State =
               (String) mbs.getAttribute(mbeanObjectName, "State");
            Integer NbChanges =
               (Integer) mbs.getAttribute(mbeanObjectName,
                                          "NbChanges");
        } catch (Exception e) {
            echo(       "!!! Could not read attributes !!!");
            e.printStackTrace();
        }
   }

[...]

CODE EXAMPLE 3-5 shows a method for managing a simple MBean.

The manageSimpleMBean() method first of all calls the printSimpleAttributes() method that is also defined by Server. The printSimpleAttributes() method obtains an MBean attribute called state from the MBean mbeanObjectName, as well as another MBean attribute called NbChanges. Both of these attributes are defined in the SimpleStandard class, shown in Section "SimpleStandard.java".

The manageSimpleMBean() method then defines an attribute called stateAttribute, which is an instance of the Attribute class. The stateAttribute attribute associates a value of new state with the existing attribute state, defined by SimpleStandard. A call to the MBeanServer method setAttribute() then sets the mbeanObjectName MBean’s state to the new state defined by stateAttribute.

Finally, a call to the MBeanServer method invoke() invokes the mbeanObjectName MBean’s reset operation. The reset operation is defined in the SimpleStandard class.

SimpleStandardMBean.java

The SimpleStandardMBean.java class is shown in CODE EXAMPLE 3-1.

CODE EXAMPLE 3-1 MBean Example Class SimpleStandardMBean.java

public interface SimpleStandardMBean {

       public String getState();
       public void setState(String s);
       public int getNbChanges();
       public void reset();

}

The SimpleStandardMBean.java class is a straightforward JMX specification management interface for the MBean SimpleStandard. This interface exposes the four operations defined by SimpleStandard for management through a JMX agent.

SimpleStandard.java

The SimpleStandard.java class is shown in CODE EXAMPLE 3-1.

CODE EXAMPLE 3-1 MBean Example Class SimpleStandard.java

public class SimpleStandard
    extends NotificationBroadcasterSupport
    implements SimpleStandardMBean {
    public String getState() {
       return state;
    }
    public void setState(String s) {
       state = s;
       nbChanges++;
    }

    public int getNbChanges() {
        return nbChanges;
    }

    public void reset() {
       AttributeChangeNotification acn =
           new AttributeChangeNotification(this,
                                          0,
                                          0,
                                          "NbChanges reset",
                                          "NbChanges",
                                          "Integer",
                                          new Integer(nbChanges),
                                          new Integer(0));
       state = "initial state";
       nbChanges = 0;
       nbResets++;
       sendNotification(acn);
    }

    public int getNbResets() {
       return nbResets;
    }

    public MBeanNotificationInfo[] getNotificationInfo() {
        return new MBeanNotificationInfo[] {
          new MBeanNotificationInfo(
          new String[] {
            AttributeChangeNotification.ATTRIBUTE_CHANGE },
            AttributeChangeNotification.class.getName(),
            "This notification is emitted when the reset()
             method is called.")
        };
    }

    private String state = "initial state";
    private int nbChanges = 0;
    private int nbResets = 0;

}

The SimpleStandard class defines a straightforward JMX specification standard MBean.

The SimpleStandard MBean exposes operations and attributes for management by implementing the corresponding SimpleStandardMBean interface, shown in Section "SimpleStandardMBean.java".

The simple operations exposed by this MBean are as follows:

  • To define a state.
  • To update this state.
  • To count the number of times the state is updated
  • To reset the values of the state and the number of changes to their original value of zero
  • To send a notification whenever the reset operation is invoked

The notification emitted by the reset operation is an instance of the class AttributeChangeNotification, which collects information about the number of changes carried out on the State attribute before calling reset. The content of the notification sent is defined by the MBeanNotificationInfo instance.

SimpleDynamic.java

The SimpleDynamic class is shown in CODE EXAMPLE 3-1.

CODE EXAMPLE 3-1 MBean Example Class SimpleDynamic.java

public class SimpleDynamic
    extends NotificationBroadcasterSupport
    implements DynamicMBean {

    public SimpleDynamic() {
        buildDynamicMBeanInfo();
    }

[...]

The SimpleDynamic dynamic MBean shows how to expose attributes and operations for management at runtime, by implementing the DynamicMBean interface. It starts by defining a method, buildDynamicMBeanInfo(), for obtaining information for the MBean dynamically. The buildDynamicMBeanInfo() method builds the MBeanInfo for the dynamic MBean.

The rest of the code of SimpleDynamic corresponds to the implementation of the DynamicMBean interface. The attributes, operations and notifications exposed are identical to those exposed by the SimpleStandard MBean.

ClientListener.java

The ClientListener.java class is shown in CODE EXAMPLE 3-1.

CODE EXAMPLE 3-1 MBean Example Class ClientListener.java

public class ClientListener implements NotificationListener {
 public void handleNotification(Notification notification, Object handback)
     {
         System.out.println("\nReceived notification: " + notification);
     }
}

The ClientListener class implements a straightforward JMX specification notification listener.

The handleNotification() method of the NotificationListener interface is called upon reception of a notification, and prints out a message to confirm that a notification has been received.

Client.java

The Client.java class is shown in CODE EXAMPLE 3-1.

CODE EXAMPLE 3-1 MBean Example Class Client.java

public class Client {

  public static void main(String[] args) {
    try {
      // Create an RMI connector client
      //
      JMXServiceURL url = new JMXServiceURL(
         "service:jmx:rmi:///jndi/rmi://localhost:9999/server");
      JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
      ClientListener listener = new ClientListener();
      MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
      waitForEnterPressed();

      // Get domains from MBeanServer
      //
      String domains[] = mbsc.getDomains();
      for (int i = 0; i < domains.length; i++) {
          System.out.println("Domain[" + i + "] = " + domains[i]);
      }
      waitForEnterPressed();

      String domain = mbsc.getDefaultDomain();

      // Create SimpleStandard MBean
      ObjectName mbeanName =
             new ObjectName(domain +":type=SimpleStandard,name=2");
      mbsc.createMBean("SimpleStandard", stdMBeanName, null, null);
      waitForEnterPressed();

      // Create SimpleDynamic MBean
      ObjectName dynMBeanName =
          new ObjectName(domain +":type=SimpleDynamic,name=2");
      echo("\nCreate SimpleDynamic MBean...");
      mbsc.createMBean("SimpleDynamic", dynMBeanName, null, null);
      waitForEnterPressed();

      // Get MBean count
      echo("\nMBean count = " + mbsc.getMBeanCount());

      // Query MBean names
      echo("\nQuery MBeanServer MBeans:");
      Set names = mbsc.queryNames(null, null);
      for (Iterator i = names.iterator(); i.hasNext(); ) {
      echo(     "ObjectName = " + (ObjectName) i.next());
      }
      waitForEnterPressed();

      mbsc.setAttribute(stdMBeanName,
                        new Attribute("State", "changed state"));

      SimpleStandardMBean proxy = JMX.newMBeanProxy(
          mbsc, stdMBeanName, SimpleStandardMBean.class, true);
      echo("\nState = " + proxy.getState());

      ClientListener listener = new ClientListener();
      mbsc.addNotificationListener(stdMBeanName, listener, null, null);

      mbsc.invoke(stdMBeanName, "reset", null, null);

      mbsc.removeNotificationListener(stdMBeanName, listener);
      mbsc.unregisterMBean(stdMBeanName);

      [...]

      jmxc.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
[...]

The Client.java class creates an RMI connector client that is configured to connect to the RMI connector server created by Server.java.

As you can see, Client.java defines the same service URL url as that defined by Server.java. This allows the connector client to retrieve the RMI connector server stub named server from the RMI registry running on port 9999 of the local host, and to connect to the RMI connector server.

With the RMI registry thus identified, the connector client can be created. The connector client, jmxc, is an instance of the interface JMXConnector, created by the connect() method of JMXConnectorFactory. The connect() method is passed the parameters url and a null environment map when it is called.

The Client also creates an instance of ClientListener, to listen for notifications, as shown in Section "ClientListener.java".

An instance of a JMX specification MBeanServerConnection, named mbsc, is then created by calling the getMBeanServerConnection() method of the JMXConnector instance jmxc.

The connector client is now connected to the MBean server created by Server.java, and can register MBeans and perform operations on them with the connection remaining completely transparent to both ends.

The client creates and registers the SimpleStandard MBean and the SimpleDynamic MBean in the MBean server with a call to the createMBean() method of MBeanServerConnection, and performs the operations defined by SimpleStandard and SimpleDynamic as if they were local JMX specification MBean operations.

MBean proxies allow you to access an MBean through a Java interface, allowing you to make calls on the proxy rather than having to write lengthy code to access a remote MBean. An MBean proxy for SimpleStandardMBean is created here by calling the method newMBeanProxy() in the javax.management.JMX class, passing it the MBean’s MBeanServerConnection, object name, the class name of the MBean interface and true, to signify that the proxy must behave as a NotificationBroadcaster. You can make proxies for MXBeans in exactly the same way as for standard MBeans, by simply calling newMXBeanProxy() instead of newMBeanProxy().

The code for the different operations performed on SimpleDynamic is not shown here, because the operations are the same as those performed on SimpleStandard.

Finally, the client unregisters the SimpleStandard MBean and closes the connection. The final removeNotificationListener is optional, as listeners registered by a remote client are removed when that client is closed.

Running the MBean Example

Having examined the example classes, you can now run the example. To run the example, follow the steps below, or see the README file:

  2. Compile the Java classes.

    $ javac *.java

  3. Start an RMI registry on port 9999 of the local host.

    The RMI registry will be used by the Server to register the RMI connector stub.

    $ rmiregistry 9999 &

  4. Start the Server class.

    $ java -classpath . Server

    You will see confirmation of the creation of the MBean server and the creation of the SimpleStandard MBean in the MBean server. You will then be prompted to press the Enter key to obtain information about, and then to perform operations on, the SimpleStandard MBean.

    Once the operations on the SimpleStandard have completed, the process will be repeated for the SimpleDynamic MBean.

    Once both the MBeans have been created and their operations performed, you see the creation of an RMI connector server, to allow operations to be performed on the MBeans from the remote Client.

  5. Start the Client class in another terminal window.

    $ java -classpath . Client

    You will see confirmation of the creation of the RMI connector client and of the connection with the connector server. You will also be informed of the domain name, and the creation and registration of SimpleStandard and SimpleDynamic MBeans. The client will then perform operations on SimpleStandard and SimpleDynamic MBeans, before unregistering them.

Contents | Previous | Next

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JPDA Connection and Invocation

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Connection and Invocation Details

Contents

Transports
Connectors
Sun VM Invocation Options
Debugging Plug-in Applets
Connecting with JDB
Service Provider Interfaces

Transports

A JPDA Transport is a method of communication between a debugger and the virtual machine that is being debugged (hereafter the target VM). The communication is connection oriented - one side acts as a server, listening for a connection. The other side acts as a client and connects to the server. JPDA allows either the debugger application or the target VM to act as the server. Transport implementations can allow communications between processes running on a single machine, on different machines, or either. When establishing a connection a transport addresses is used to identify the end-point of the connection. The format of a transport address depends on the type of transport.

Within JPDA the debugger application uses the Java Debug Interface (JDI) interface and the Connector abstraction to establish a connection to the target VM. The Connector used by the debugger application encapsulates the transport. On the target VM an agent supporting the JavaTM Debug Wire Protocol is used to communicate with the debugger. This agent (which may be built into the target VM or loaded from a runtime library) encapsulates the transport to communicate with the debugger.

Sun ships two transport implementations with the reference implementation: A socket transport based on TCP/IP, and a shared memory transport. The specifications do not require any specific transport implementation to exist. In addition to transports provided with the implementation the architecture includes service provider interfaces to allow additional transports be developed and deployed.

Socket Transport

The JPDA reference implementation provides a socket transport for the Solaris, Linux, and Microsoft Windows platforms. With the socket transport, the debugger application and the target VM can reside either on the same machine or on different machines. The socket transport uses a single stream TCP/IP connection between the debugger application and the target VM. Both IPv4 and IPv6 are supported on the JDI side of the socket transport. The current implementation on the target VM side only supports IPv4, but this could change in a future release so that both IPv4 and IPv6 are supported.

Command and reply packets are written to the stream in accordance with the JDWP specification using the JDWP Transport Interface. Since many small packets can be sent over JDWP, the TCP_NO_DELAY socket option can improve performance in some socket implementations by avoiding delays that could occur if the socket implementation buffers small packets before sending them. Sockets are closed gracefully so that unsent data is sent if possible.

The socket transport is identified through a unique string, dt_socket. This name can be used to select the socket transport when invoking the target VM. Within the debugger application a corresponding Connector is used which encapsulates the socket transport.

In contexts where a client is attaching to a server, socket transport addresses have the format "<name>:<port>" where <name> is the host name and <port> is the socket port number at which it attaches or listens. In contexts where a server is waiting for a client to attach, the address consists of the port number alone (the host name is implicit).

Shared Memory Transport

In addition to the socket transport, the JPDA reference implementation provides a shared memory transport on the Microsoft Windows platform. The shared memory transport uses a shared memory region to exchange JDWP packets between the debugger application and the target VM. With the shared memory transport, the debugger application and target VM must reside on the same machine.

The shared memory transport is identified through a unique string, dt_shmem. This name can be used to select the socket transport when invoking the target VM. Within the debugger application a corresponding Connector is used which encapsulates the shared memory transport.

Shared memory transport addresses are simply names that can be used as Microsoft Windows file-mapping object names. The name string can consist of any combination of characters, excluding the backslash.

Connectors

A connector is a JDI abstraction that is used in establishing a connection between a debugger application (written to the JDI) and a target VM. Different JDI implementations are free to provide different connector implementations to match the transports and VMs they support. The connector interfaces are very general, to allow JDI to be used with varying connector implementations. Connectors are configured through a set of name/value pairs. Specific connectors accept different name/value pairs.

A good JDI client application will allow users to choose and configure any connector that may be present, but it can be beneficial to incorporate knowledge of specific connectors into the debugger to make their configuration a more pleasant user experience. The example JDB implementation provided with the JPDA illustrates this approach.

The JDI reference implementations provides several connectors which map to the available transport types and the modes of connection (launching, listening, and attaching). These connectors are described in the following sections. A List containing these connectors is returned by JDI method VirtualMachineManager.allConnectors(). In addition, each attaching, listening, and launching connector is contained in the lists returned by the corresponding VirtualMachineManager methods attachingConnectors(), listeningConnectors(), and launchingConnectors().

Sun Command Line Launching Connector

This connector can be used by a debugger application to launch a Sun VM or any other VM which supports the same invocation options with respect to debugging. The details of launching the VM and specifying the necessary debug options are handled by the connector. The underlying transport used by this connector depends on the platform. On Microsoft Windows, the shared memory transport is used. On Solaris and Linux the socket transport is used.

This connector is uniquely identified by the name "com.sun.jdi.CommandLineLaunch".

Sun Command Line Launching Connector Arguments
name | required? | default value | description
home | no | current java.home property value | Location of the Java 2 Runtime Environment used to invoke the Target VM.
options | no | "" | Options, in addition to the standard debugging options, with which to invoke the VM.
main | yes | "" | The debugged application's main class and command line arguments.
suspend | no | true | True if the target VM is to be suspended immediately before the main class is loaded; false otherwise.
quote | yes | "\"" | The character used to combine space-delimited text on the command line.
vmexec | yes | "java" | The VM launcher executable. This can be changed to javaw or to java_g for debugging, if that launcher is available.

Raw Command Line Launching Connector

This connector can be used by a debugger application to launch any VM. The entire command line must be specified and it is not edited in any way. The details of launching the VM with the given command line are handled by the connector. The underlying transport used by this connector depends on the platform. On Microsoft Windows, the shared memory transport is used. On the Solaris operating environment, the socket transport is used.

This connector is uniquely identified by the name "com.sun.jdi.RawCommandLineLaunch".

Raw Command Line Launching Connector Arguments
name | required? | default value | description
command | yes | "" | Full command line to invoke the target VM with the application to be debugged..
address | yes | "" | Transport address at which to listen for the newly launched target VM to connect. This value is typically part of the raw command argument as well, but this is not required if the target VM has some other means of determining the transport address to which it should connect.
quote | yes | "\"" | The character used to combine space-delimited text on the command line.

Socket Attaching Connector

This connector can be used by a debugger application to attach to a currently running target VM through the socket transport.. The target VM must have been invoked with options consistent with this connector's arguments described in the table below. For Sun VMs, the necessary options are described below.

This connector is uniquely identified by the name "com.sun.jdi.SocketAttach".

Socket Attaching Connector Arguments
name | required? | default value | description
hostname | no | local host name | Name of host machine to connect to.
port | yes | "" | Port number on the host machine to connect to.
timeout | no | "" | The timeout, in milliseconds, to use when attaching to the target VM.

Shared Memory Attaching Connector

This connector can be used by a debugger application to attach to a currently running target VM through the shared memory transport. It is available only on the Microsoft Windows platform. The target VM must have been invoked with options consistent with this connectors arguments described in the table below. For Sun VMs, the necessary options are described below.

This connector is uniquely identified by the name "com.sun.jdi.SharedMemoryAttach".

Shared Memory Attaching Connector Arguments
name | required? | default value | description
name | yes | "" | The shared memory transport address at which the target VM is listening..
timeout | no | "" | The timeout, in milliseconds, to use when attaching to the target VM

Socket Listening Connector

This connector can be used by a debugger application to accept a connection from a separately invoked target VM through the socket transport.. The target VM must be invoked with options consistent with this connector's arguments described in the table below. For Sun VMs, the necessary options are described below.

This connector can accept connections from multiple target VMs.

This connector is uniquely identified by the name "com.sun.jdi.SocketListen".

Socket Listening Connector Arguments
name | required? | default value | description
port | no | Ephemeral port number (port assigned by the TCP/IP stack) | Port number at which to listen for a connection..
localAddress | no | All addresses assigned to the host | An IP address assigned to the host
timeout | no | "" | The timeout, in milliseconds, to use while waiting for the target VM to connect

Shared Memory Listening Connector

This connector can be used by a debugger application to accept a connection from a separately invoked target VM through the shared memory transport. It is available only on the Microsoft Windows platform. The target VM must be invoked with options consistent with this connector's arguments described in the table below. For Sun VMs, the necessary options are described below.

This connector can accept connections from multiple target VMs.

This connector is uniquely identified by the name "com.sun.jdi.SharedMemoryListen".

Shared Memory Listening Connector Arguments
name | required? | default value | description
name | yes | "" | A shared memory transport address at which to listen for the target VM connection.
timeout | no | "" | The timeout, in milliseconds, to use while waiting for the target VM to connect

Process Attaching Connector

This connector can be used by a debugger application to attach to a currently running target VM that was started with the "server=y" debugging sub-option described below. The target VM must be Java SE 6 or newer.

The Process Attaching Connector does not have an associated transport. Instead, the transport is determined dynamically when an attach actually occurs. Because of this, the transport().name() method for this connector returns "local".

This connector is uniquely identified by the name "com.sun.jdi.ProcessAttach".

Process Attaching Connector Arguments
name | required? | default value | description
pid | yes | "" | The Process ID of a process to be debugged.
timeout | no | "" | The timeout, in milliseconds, to use when attaching to the target VM.

SA Core Attaching Connector

This connector can be used by a debugger application to debug a core file. It is possible that the core file is corrupted to the extent that not all available debugging operations can be performed on it.

The VirtualMachine object returned by this connector's attach() method is 'read-only'. This means that the method:
vm.canBeModified()
will return false, and that the JDI client should not call any JDI methods that are defined to throw a VMCannotBeModifiedException in this case. The word size (i.e. 32 bit/64 bit) and version (e.g. 5.0, 5.1) of the debugger's Virtual Machine must be the same as that of the Virtual Machine of the process from which the core file was produced.
This connector allows multiple debugging sessions on the same core file.

This connector is uniquely identified by the name "sun.jvm.hotspot.jdi.SACoreAttachingConnector".

SA Core Attaching Connector Arguments
name | required? | default value | description
core | no | core | Pathname of the core file to debug
javaExecutable | yes | "" | Pathname of the Java executable that produced the core file.

SA PID Attaching Connector

This connector can be used by a debugger application to debug a process. It is not available on the Microsoft Windows platforms nor on the Linux Itanium platform. It is possible that the process is corrupted to the extent that not all available debugging operations can be performed on it.

The VirtualMachine object returned by this connector's attach() method is 'read-only'. This means that the method:
vm.canBeModified()
will return false, and that the JDI client should not call any JDI methods that are defined to throw a VMCannotBeModifiedException in this case.

The process to be debugged need not have been started in debug mode(ie, with -agentlib:jdwp or -Xrunjdwp). It is permissable for the process to be hung. The word size (i.e. 32 bit/64 bit) and version (e.g. 5.0, 5.1) of the debugger and debuggee must be the same. The process is suspended when this connector attaches and resumed when this connector detaches. More than one SAPIDAttachingConnector can not attach to a single process simultaneously.

This connector is uniquely identified by the name "sun.jvm.hotspot.jdi.SAPIDAttachingConnector".

SA PID Attaching Connector Arguments
name | required? | default value | description
pid | yes | "" | The Process ID of a process to be debugged.

SA Debug Server Attaching Connector

This connector can be used by a debugger application to debug a process or core file on a machine other than the machine upon which the debugger is running. It is not available on the Microsoft Windows platforms nor on the Linux Itanium platform. It is possible that the remote process/core file is corrupted to the extent that not all available debugging operations can be performed on it.

The VirtualMachine object returned by this connector's attach() method is 'read-only'. This means that the method:
vm.canBeModified()
will return false, and that the JDI client should not call any JDI methods that are defined to throw a VMCannotBeModifiedException in this case.

This connector uses RMI to communicate with a 'debug server' running on the remote machine.
Before the attach() method on this connector is called, the debug server must be started on the remote machine
and told what process or corefile is to be debugged. The following must be done on the remote machine:
  • start the RMI registry with sa-jdi.jar in the classpath:

${JAVA_HOME}/bin/rmiregistry -J-Xbootclasspath/p:${JAVA_HOME}/lib/sa-jdi.jar
  • start the 'debug-server' on the remote machine, specifying the process or corefile to be debugged:
${JAVA_HOME}/bin/java \
    -classpath ${JAVA_HOME}/lib/sa-jdi.jar \
    sun.jvm.hotspot.jdi.SADebugServer \
    <pid> \
    [uniqueID]

or

${JAVA_HOME}/bin/java \
    -classpath ${JAVA_HOME}/lib/sa-jdi.jar \
    sun.jvm.hotspot.jdi.SADebugServer \
    <pathname to the java executable that produced the core file>\
    <pathname of the corefile to debug> \
     [uniqueID]

An alternative to the above two steps is to use the jsadebugd command to start the RMI registry and debug-server on the remote machine.

'uniqueID' is an optional string. If more than one debug server is to run at the same time on the same machine, then each must have a different 'uniqueID' string.

In the above, JAVA_HOME must contain the pathname of a Java installation that is the same bit size (i.e. 32 bit/64 bit) and the same version (e.g. 5.0, 5.1) as the version used by the debuggee. However the debugger does not have to be the same bit size and version.

A process to be debugged need not have been started in debug mode(ie, with -agentlib:jdwp or -Xrunjdwp). It is permissable for the process to be hung. The process is suspended when the debug server attaches to it. When a debug server attached to a process is killed (by ^C or other means), the debuggee process will be resumed. Attaching more than one debug server to a corefile is permitted, but only one debug server can be attached to a process.

This connector allows multiple debugging sessions connected to the same debug server.

This connector is uniquely identified by the name "sun.jvm.hotspot.jdi.SADebugServerAttachingConnector".

SA DebugServer Attaching Connector Arguments
name | required? | default value | description
debugServerName | yes | "" | The IP address or name of the machine upon which the debug server is running. If the machine contains multiple debug servers, this name must be of the form uniqueID@IPAddress or uniqueID@hostname where 'uniqueID' is the string used to start the corresponding debug server.

Sun VM Invocation Options

This section describes the options necessary to invoke Sun VMs for debugging.

Sun's VM implementations require command line options to load the JDWP agent for debugging. From 5.0 onwards the -agentlib:jdwp option is used to load and specify options to the JDWP agent. For releases prior to 5.0, the -Xdebug and -Xrunjdwp options are used (the 5.0 implementation also supports the -Xdebug and -Xrunjdwp options but the newer -agentlib:jdwp option is preferable as the JDWP agent in 5.0 uses the JVM TI interface to the VM rather than the older JVMDI interface).

If your debugger application uses the JDI Sun Command Line Launching Connector, the connector will use the -Xdebug and -Xrunjdwp options as the Connector may be used to connect to a pre-5.0 target VM.

If the target VM is 5.0 or newer the -agentlib:jdwp option is specified as follows:

-agentlib:jdwp=<sub-options>
Loads the JPDA reference implementation of JDWP. This library resides in the target VM and uses JVM TI and JNI to interact with it. It uses a transport and the JDWP protocol to communicate with a separate debugger application. Specific sub-options are described below.

For releases prior to 5.0 the -Xdebug and -Xrunjdwp options are used:

-Xdebug
Enables debugging
-Xrunjdwp:<sub-options>
Loads the JPDA reference implementation of JDWP. This library resides in the target VM and uses JVMDI and JNI to interact with it. It uses a transport and the JDWP protocol to communicate with a separate debugger application. Specific sub-options are described below.

-agentlib:jdwp and -Xrunjdwp sub-options

The -agentlib:jdwp and -Xrunjdwp option can be further qualified with sub-options. The sub-options are specified as follows:

    -agentlib:jdwp=<name1>[=<value1>],<name2>[=<value2>]...

or

    -Xrunjdwp:<name1>[=<value1>],<name2>[=<value2>]...

The table below describes the options that can be used:

-Xrunjdwp Sub-options
name | required? | default value | description
help | no | N/A | Prints a brief help message and exits the VM.
transport | yes | none | Name of the transport to use in connecting to debugger application.
server no "n" If "y", listen for a debugger application to attach; otherwise, attach to the debugger application at the specified address.

If "y" and no address is specified, choose a transport address at which to listen for a debugger application, and print the address to the standard output stream.
address yes, if server=n
no, otherwise 		"" Transport address for the connection. If server=n, attempt to attach to debugger application at this address. If server=y, listen for a connection at this address.
timeout no "" If server=y specifies the timeout, in milliseconds, to wait for the debugger to attach. If server=n specifies the timeout, in milliseconds, to use when attaching to the debugger. Note that the timeout option may be ignored by some transport implementations.
launch no none At completion of JDWP initialization, launch the process given in this string. This option is used in combination with onthrow and/or onuncaught to provide "Just-In-Time debugging" in which a debugger process is launched when a particular event occurs in this VM.

Note that the launched process is not started in its own window. In most cases the launched process should be a small application which in turns launches the debugger application in its own window.

The following strings are appended to the string given in this argument (space-delimited). They can aid the launched debugger in establishing a connection with this VM. The resulting string is executed.

  • The value of the transport sub-option.
  • The value of the address sub-option (or the generated address if one is not given)
onthrow | no | none | Delay initialization of the JDWP library until an exception of the given class is thrown in this VM. The exception class name must be package-qualified.Connection establishment is included in JDWP initialization, so it will not begin until the exception is thrown.
onuncaught | no | "n" | If "y", delay initialization of the JDWP library until an uncaught exception is thrown in this VM. Connection establishment is included in JDWP initialization, so it will not begin until the exception is thrown. See the JDI specification for com.sun.jdi.ExceptionEvent for a definition of uncaught exceptions.
suspend | no | "y" | If "y", VMStartEvent has a suspendPolicy of SUSPEND_ALL. If "n", VMStartEvent has a suspendPolicy of SUSPEND_NONE.

Examples

-agentlib:jdwp=transport=dt_socket,server=y,address=8000
Listen for a socket connection on port 8000. Suspend this VM before main class loads (suspend=y by default). Once the debugger application connects, it can send a JDWP command to resume the VM.

-agentlib:jdwp=transport=dt_socket,server=y,address=localhost:8000,timeout=5000
Listen for a socket connection on port 8000 on the loopback address only. Terminate if the debugger does not attach within 5 seconds. Suspend this VM before main class loads (suspend=y by default). Once the debugger application connects, it can send a JDWP command to resume the VM.

-agentlib:jdwp=transport=dt_shmem,server=y,suspend=n
Choose an available shared memory transport address and print it to stdout. Listen for a shared memory connection at that address. Allow the VM to begin executing before the debugger application attaches.

-agentlib:jdwp=transport=dt_socket,address=myhost:8000
Attach to a running debugger application via socket on host myhost at port 8000. Suspend this VM before the main class loads.

-agentlib:jdwp=transport=dt_shmem,address=mysharedmemory
Attach to a running debugger application via shared memory at transport address "mysharedmemory". Suspend this VM before the main class loads.

-agentlib:jdwp=transport=dt_socket,server=y,address=8000,onthrow=java.io.IOException,launch=/usr/local/bin/debugstub
Wait for an instance of java.io.IOException to be thrown in this VM. Suspend the VM (suspend=y by default). Listen for a socket connection on port 8000. Execute the following: "/usr/local/bin/debugstub dt_socket myhost:8000".This program can launch a debugger process in a separate window which will attach to this VM and begin debugging it.

-agentlib:jdwp=transport=dt_shmem,server=y,onuncaught=y,launch=d:\bin\debugstub.exe
Wait for an uncaught exception to be thrown in this VM. Suspend the VM. Select a shared memory transport address and listen for a connection at that address. Execute the following: "d:\bin\debugstub.exe dt_shmem <address>", where <address> is the selected shared memory address. This program can launch a debugger process in a separate window which will attach to this VM and begin debugging it.

Debugging Plug-in Applets

Beginning with version 1.2.2 of the Java Plug-in, applets running under the Plug-in can be debugged. The required VM options described above can be specified in the Plug-In control panel, under the "Basic" tab, in the "Java Run-Time Parameters". The debug options under the "Advanced" tab should not be used as they will enable the old sun.tools.debug debug support. In future versions of the Plug-in, these debug options will be changed to use JPDA.

JDI launching connectors cannot be used to debug Plug-in applets.

Connecting with JDB

The example implementation of JDB provided with the JPDA, provides an illustration of the usage of JDI connectors. There are "shortcut" options to JDB which assume the use of connectors known to it (that is, connectors present in the reference implementation). It also provides a way to establish a general connection using any connector. While JDB is hardly an example of a good debugger interface, it does provide a simple example of connectors in use.

In JDB, the -attach option provides access to one of the attaching connectors in the reference implementation (shared memory on Microsoft Windows, sockets on the Solaris and Linux platforms). The -listen option provides access to one of the listening connectors in the reference implementation (shared memory on Microsoft Windows, sockets on the Solaris and Linux platforms). A class name and arguments specified directly on the command line provide access to the Sun command line launching connector.

For example:

jdb -attach myhost:8000

is an easy way to attach to a target VM with the Socket Attaching Connector (on the Solaris operating environment), and

jdb Hello 1 2 3

is an easy way to launch a target VM with the Sun Command Line Launching Connector.

However, the -connect option is also provided by JDB to handle any connector by taking an connector name and a set of arbitrary name/value argument pairs. For example the command lines above have the following equivalents.

jdb -connect com.sun.jdi.SocketAttach:hostname=myhost,port=8000
jdb -connect "com.sun.jdi.CommandLineLaunch:main=Hello 1 2 3"

These command lines are more cumbersome than the ones above, but the -connect option can be used with any connector. This kind of operation is a primitive example of how a JDI debugger can deal with any kind of connector while providing a simplified interface for dealing with common, well-known connectors.

Service Provider Interfaces

JPDA includes service provider interfaces to allow the development and deployment of connector and transport implementations. These service provider interfaces allow debugger and other tool vendors develop new connector implementations and provide addition transport mechanisms over and beyond the socket and shared memory transport provided by Sun. The service provider interfaces in JDI are specified in the com.sun.jdi.connect.spi package.

In addition to the service provider interfaces in JDI the Sun implementation also includes a transport library interface called the Java TMDebug Wire Protocol Transport Interface. A transport library is loaded by the JDWP agent in the target VM and is used to establish a connection to the debugger and to transport JDWP packets between the debugger and the VM.

Further information on the service provider interfaces can be in the document JavaTM Platform Debugger Architecture - Service Provider Interfaces.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Console

See Java Console in the Java Deployment Guide.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.mirror.declaration.ConstructorDeclaration (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.declaration.ConstructorDeclaration

  • Packages that use ConstructorDeclaration
    Package Description
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of ConstructorDeclaration in com.sun.mirror.declaration

      Methods in com.sun.mirror.declaration that return types with arguments of type ConstructorDeclaration
      Modifier and Type Method and Description
      Collection<ConstructorDeclaration> ClassDeclaration.getConstructors()
      Deprecated.
      Returns the constructors of this class.

    • Uses of ConstructorDeclaration in com.sun.mirror.util

      Methods in com.sun.mirror.util with parameters of type ConstructorDeclaration
      Modifier and Type Method and Description
      void SimpleDeclarationVisitor.visitConstructorDeclaration(ConstructorDeclaration d)
      Deprecated.
      Visits a constructor declaration.
      void DeclarationVisitor.visitConstructorDeclaration(ConstructorDeclaration d)
      Deprecated.
      Visits a constructor declaration.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.javadoc.ConstructorDoc (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.javadoc.ConstructorDoc

    • Uses of ConstructorDoc in com.sun.javadoc

      Methods in com.sun.javadoc that return ConstructorDoc
      Modifier and Type Method and Description
      ConstructorDoc[] ClassDoc.constructors()
      Return included constructors in this class.
      ConstructorDoc[] ClassDoc.constructors(boolean filter)
      Return constructors in this class, filtered to the specified access modifier option.
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Java Sound Programmer Guide

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

JavaTM Sound Programmer Guide

Introductory Material

Preface

For Whom This Guide Is Intended
What this Guide Describes
For More Information

Chapter: 1 Introduction to the Java Sound API

Design Goals
Who is the Java Sound API For?
How Does the Java Sound API Relate to Other Interfaces?
Packages
Sampled Audio
What Is Sampled Audio?
Audio Configurations
MIDI
What Is MIDI?
MIDI Configurations
Service Provider Interfaces

Part I: Sampled Audio

Chapter 2: Overview of the Sampled Package

Design Goals
A Focus on Data Transport
Buffered and Unbuffered Handling of Audio
The Essentials: Format, Mixer, and Line
What Is Formatted Audio Data?
What Is a Mixer?
What Is a Line?
Lines in an Audio-output Configuration
Lines in an Audio-input Configuration
The Line Interface Hierarchy

Chapter 3: Accessing Audio System Resources

The AudioSystem Class
Information Objects
Getting a Mixer
Getting a Line of a Desired Type
Getting a Line Directly from the AudioSystem
Getting a Line from a Mixer
Selecting Input and Output Ports
Permission to Use Audio Resources

Chapter 4: Playing Back Audio

Using a Clip
Setting Up the Clip for Playback
Starting and Stopping Playback
Using a SourceDataLine
Setting Up the SourceDataLine for Playback
Starting and Stopping Playback
Monitoring a Line's Status
Synchronizing Playback on Multiple Lines
Processing the Outgoing Audio

Chapter 5: Capturing Audio

Setting Up a TargetDataLine
Reading the Data from the TargetDataLine
Monitoring the Line's Status
Processing the Incoming Audio

Chapter 6: Processing Audio with Controls

Introduction to Controls
Getting a Line that Has the Desired Controls
Getting the Controls from the Line
Using a Control to Change the Audio Signal
Controlling a Line's Mute State
Changing a Line's Volume
Selecting among Various Reverberation Presets
Manipulating the Audio Data Directly

Chapter 7: Using Files and Format Converters

Reading Sound Files
Writing Sound Files
Converting File and Data Formats
Converting from One File Format to Another
Converting Audio between Different Data Formats
Learning What Conversions Are Available

Part II: MIDI

Chapter 8: Overview of the MIDI Package

A MIDI Refresher: Wires and Files
Streaming Data in the MIDI Wire Protocol
Sequenced Data in Standard MIDI Files
The Java Sound API's Representation of MIDI Data
MIDI Messages
MIDI Events
Sequences and Tracks
The Java Sound API's Representation of MIDI Devices
The MidiDevice Interface
Transmitters and Receivers
Sequencers
Synthesizers

Chapter 9: Accessing MIDI System Resources

The MidiSystem Class
Obtaining Default Devices
Learning What Devices Are Installed
Obtaining a Desired Device
Opening Devices

Chapter 10: Transmitting and Receiving MIDI Messages

Understanding Devices, Transmitters, and Receivers
Sending a Message to a Receiver without Using a Transmitter
Understanding Time Stamps
Time Stamps on Messages Sent to Devices
Connecting Transmitters to Receivers
Connecting to a Single Device
Connecting to More than One Device
Closing Connections

Chapter 11: Playing, Recording, and Editing MIDI Sequences

Introduction to Sequencers
When to Use a Sequencer
Understanding Sequence Data
Sequences and Tracks
MidiEvents and Ticks
Overview of Sequencer Methods
Obtaining a Sequencer
Loading a Sequence
Playing a Sequence
Recording and Saving Sequences
Editing a Sequence
Using Advanced Sequencer Features
Moving to an Arbitrary Position in the Sequence
Changing the Playback Speed
Muting or Soloing Individual
Tracks in the Sequence
Synchronizing with Other MIDI Devices
Specifying Special Event Listeners

Chapter 12: Synthesizing Sound

Understanding MIDI Synthesis
Instruments
Channels
Soundbanks and Patches
Voices
Managing Instruments and Soundbanks
Learning What Instruments Are Loaded
Loading Different Instruments
Unloading Instruments
Accessing Soundbank Resources
Querying the Synthesizer's Capabilities and Current State
Using Channels
Controlling the Synthesizer without
Using a Sequencer
Getting a Channel's Current State
Muting and Soloing a Channel
Permission to Play Synthesized Sound

Part III: Service Provider Interfaces

Chapter 13: Introduction to the Service Provider Interfaces

What Are Services?
How Services Work
How Providers Prepare New Services
How Users Install New Services

Chapter 14: Providing Sampled-Audio Services

Introduction
Providing Audio File-Writing Services
Providing Audio File-Reading Services
Providing Format-Conversion Services
Providing New Types of Mixers

Chapter 15: Providing MIDI Services

Introduction
Providing MIDI File-Writing Services
Providing MIDI File-Reading Services
Providing Particular MIDI Devices
Providing Soundbank File-Reading Services

Appendices

Appendix 1: Code Overview: AudioSystem.java

Appendix 2: sound.properties File

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.source.tree.ContinueTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.ContinueTree

  • Packages that use ContinueTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of ContinueTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type ContinueTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitContinue(ContinueTree node, P p)

    • Uses of ContinueTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type ContinueTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitContinue(ContinueTree node, P p)
      R | SimpleTreeVisitor.visitContinue(ContinueTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Java Control Panel

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

< Contents

Using the Java Control Panel to Set Plug-in Options

See Java Control Panel in the Java Deployment Guide.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Cookie Support

Cookie Support includes the following topics:

  • Introduction
  • Cookie Support in Java Plug-in and Java Web Start
  • Programmatic Access to Cookies
  • More Information

Introduction

Cookies are a way of storing data on the client side. They have been used extensively for personalization of portal sites, user preference tracking, and logging into web sites. For enterprise customers using cookies in their web sites, cookie support in Java Plug-in and Java Web Start facilitates deployment of client-side Java.

Cookie support allows a Java application to pass a cookie back to a web server if that cookie originated from the web server. This provides the server with information about the state of the client.

Cookie Support in Java Plug-in and Java Web Start

There are two main types of cookies: Session Cookies and Permanent Cookies.

Session Cookies

Session cookies are stored in memory during the applet or application session. Session cookies expire when the applet or application exits and are automatically deleted. These cookies usually store a session ID that is not personally identifiable to users, allowing the user to move from page to page without having to log-in repeatedly. They are widely used by commercial web sites (for example, to keep track of items that a consumer has added to a shopping cart.)

Permanent Cookies

Permanent cookies are stored in persistent storage and are not deleted when the application exits. They are deleted when they expire. They can retain user preferences for a particular web site, allowing those preferences to be used in future sessions. Permanent cookies can be used to identify individual users, so they may be used by web sites to analyze users' surfing behavior within the web site. These cookies can also be used to provide information about the numbers of visitors, the average time spent on a particular page, and the general performance of the web site. They are usually configured to keep track of users for a prolonged period of time, in some cases many years into the future.

Support

Java Plug-in and Java Web Start support handling of both types of cookie on all platforms.

Java Plug-in provides permanent cookie support using the underlying browser cookie store. When it runs in Internet Explorer, the cookie store in IE is used; when it runs in Mozilla, the cookie store in Mozilla is used. Because each browser has a different cookie policy, the cookie-handling behavior depends on the cookie control in the browser. For example, if the browser is configured to reject third-party cookies, the policy will apply to Java Plug-in when it runs in this browser.

Java Web Start provides permanent cookie support on Windows using the cookie store in Internet Explorer, and the cookie-handling behavior is determined by the cookie control in IE. On Linux/Solaris, Java Web Start provides permanent cookie support using its own cookie store implementation.

Programmatic Access to Cookies

There are several ways for an application to override the default cookie handling. Four are outlined below.

void URLConnection.setRequestProperty(String key, String value)

This approach allows the application to set a custom cookie header in URLConnection before making a connection.

URL url = new URL( "http://java.sun.com/" );
URLConnection conn = url.openConnection();
conn.setRequestProperty("Cookie", "foo=bar");
InputStream is = conn.getInputStream();
.....

When the connection is made, the custom cookie would be sent to the server in the HTTP/HTTPS request headers.

Map<String, List<String>> URLConnection.getHeaderFields()

After a connection is made, the server may return a cookie in the HTTP/HTTPS response headers. The approach outlined below allows the application to retrieve the cookie value through URLConnection.

URL url = new URL( "http://java.sun.com/" );
URLConnection conn = url.openConnection();
conn.connect();
.....
Map<String, List<String>> headers = conn.getHeaderFields();
List<String> values = headers.get("Set-Cookie");

String cookieValue = null;
for (Iterator iter = values.iterator(); iter.hasNext(); ) {
     String v = values.next();
     if (cookieValue == null)
         cookieValue = v;
     else
         cookieValue = cookieValue + ";" + v;
}

After the connection is made, the server may return the cookie in the HTTP/HTTPS response headers.

Map<String,List<String>> CookieHandler.get(URI uri, Map<String,List<String>> requestHeaders)

This approach allows the application to retrieve session/permanent cookies for a given URL:

String retrieveCookie(URL url)
{
     String cookieValue = null;

     CookieHandler handler = CookieHandler.getDefault();
     if (handler != null)    {
          Map<String, List<String>> headers = handler.get(url.toURI(), new Map<String,                                                           List<String>>());
          List<String> values = headers.get("Cookie");
          for (Iterator<String> iter=values.iterator(); iter.hasNext();) {
               String v = iter.next();

               if (cookieValue == null)
                    cookieValue = v;
               else
                    cookieValue = cookieValue + ";" + v;
          }
     }
     return cookieValue;
}

CookieHandler is an abstraction of the browser/system cookie storage, so additional security permission is required for execution; the above code will be executed successfully only if the application is trusted.

void CookieHandler.put(URI uri, Map<String,List<String>> responseHeaders)

This approach allows the application to set a session/permanent cookie for a given URL:

void setCookie(URL url, String value)
{
     CookieHandler handler = CookieHandler.getDefault();
     if (handler != null)    {
          Map<String, List<String>> headers= new Map<String, List<String>>();
          List<String> values = new List<String>();
          values.add(value);
          headers.put("Cookie", values);

          handler.put(url.toURI(), headers);
     }
}

CookieHandler is an abstraction of the browser/system cookie storage, so additional security permission is required for execution; the above code will be executed successfully only if the application is trusted.

More information

  • Persistent Client State - HTTP Cookies: http://wp.netscape.com/newsref/std/cookie_spec.html
  • Unofficial Cookie FAQ: http://www.cookiecentral.com/faq/

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


CORBA and Java technologies

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

CORBA Technology and the Java™ Platform Standard Edition

The Java Platform Standard Edition, v1.4, provides an Object Request Broker (ORB) and two CORBA programming models that can utilize the Java CORBA ORB and Internet InterORB Protocol (IIOP). This topic discusses these options for creating and distributing CORBA technology.

CORBA technology is an integral part of the Java platform. It consists of an Object Request Broker (ORB), APIs for the RMI programming model, and APIs for the IDL programming model.

For more information on which specifications are implemented in this release of the Java platform, see the compliance document.

How does Java SE leverage CORBA

Common Object Request Broker Architecture (CORBA) technology is the open standard for heterogeneous computing. CORBA complements the Java™ platform by providing a distributed object framework, services to support that framework, and interoperability with other languages. The Java platform complements CORBA by providing a portable, highly productive implementation environment, and a very robust platform. By combining the Java platform with CORBA and other key enterprise technologies, the Java Platform is the ultimate platform for distributed technology solutions.

CORBA standards provide the proven, interoperable infrastructure to the Java platform. IIOP (Internet Inter-ORB Protocol) manages the communication between the object components that power the system. The Java platform provides a portable object infrastructure that works on every major operating system. CORBA provides the network transparency, Java provides the implementation transparency.

The Object Request Broker

An Object Request Broker (ORB) is part of the Java Platform Standard Edition, since version 1.3. The ORB is a runtime component that can be used for distributed computing using IIOP communication.

NOTE: Although it is true that ORBs written in different languages should be able to talk to each other, we haven't tested the interoperability of the Java ORB with other vendor's ORBs.

The Object Management Group (OMG) is an industry consortium that creates and publishes specifications for CORBA. Vendors implement the specifications to produce products known as Object Request Brokers (ORB). The good news for developers is that the Java™ Platform Standard Edition, v1.2 and higher includes an ORB that is available in every deployment of the Java Platform Standard Edition. For more information, see the ORB class.

The Java CORBA ORB supports both the RMI and IDL programming models, both of which can use the underlying IIOP wire-level protocol for communication.

Introducing the CORBA Programming Models

History of the CORBA Programming Models

In 1997, Remote Method Invocation, or RMI, was introduced in JDK 1.1. Initially, RMI was positioned as a natural outgrowth of Remote Procedure Calls (RPC), strictly for enabling calls to be made between Java objects in different virtual machines, and even on different physical machines.

In 1998, came JDK 1.2, which introduced Java IDL, a Java API for interoperability and integration with CORBA. Java IDL included both a Java-based ORB, which supported IIOP, and the IDL-to-Java compiler, idltojava, for generating client-side stubs and server-side code skeletons. The ORB supports both the RMI over IIOP and Java IDL programming models.

In 1999, the RMI over IIOP standard extension to the Java platform was introduced for JDK 1.1.6 and 1.2. Now that RMI over IIOP is integrated into J2SE version 1.3 and higher, the optional download has been end-of-lifed, but is still available from the archives.

The OMG finalized modifications of its IIOP specification so that it would support most of the JDK 1.1 functionality of RMI. RMI over IIOP was introduced as a standard extension to JDK 1.2. This enabled remote objects written in the Java programming language to be accessible from any language via IIOP.

J2SE, v.1.3 introduced a new, 100% Pure Java™, IDL-to-Java compiler, idlj, along with support for IDL abstract interfaces and value types. Also in v.1.3, RMI over IIOP is included in the JDK.

J2SE v.1.4, the current version, was introduced in 2001, and includes support for the Portable Object Adapter, Portable Interceptors, Interoperable Naming Service, GIOP 1.2, and Dynamic Anys. J2SE v.1.4 also includes an Object Request Broker Daemon (ORBD), which is used to enable clients to transparently locate and invoke persistent objects on servers in the CORBA environment, and servertool, which provides a command-line interface for application programmers to register, unregister, startup, and shutdown a persistent server. For more information on new features in J2SE v.1.4, see Changes in CORBA Features Between J2SE 1.3 and 1.4.

Comparing the CORBA Programming Models

Cross-language, cross-vendor interoperability is achieved via the Internet InterORB Protocol, or IIOP. IIOP is a transport protocol for distributed applications written in either IDL or Java RMI.

When using the IDL programming model, the interface is everything! It defines the points of entry that can be called from a remote process, such as the types of arguments the called procedure will accept, or the value/output parameter of information returned. Using IDL, the programmer can make the entry points and data types that pass between communicating processes act like a standard language.

CORBA is a language-neutral system in which the argument values or return values are limited to what can be represented in the involved implementation languages. In CORBA, object orientation is limited only to objects that can be passed by reference (the object code itself cannot be passed from machine-to-machine) or are predefined in the overall framework. Passed and returned types must be those declared in the interface.

With RMI, the interface and the implementation language are described in the same language, so you don't have to worry about mapping from one to the other. Language-level objects (the code itself) can be passed from one process to the next. Values can be returned by their actual type, not the declared type. Or, you can compile the interfaces to generate IIOP stubs and skeletons which allow your objects to be accessible from other CORBA-compliant languages.

The RMI Programming Model

What is the RMI Programming Model

The RMI Programming model is a general object model for distributed computing via the rmi API. You can choose to work completely within the Java programming language, using the Java Remote Method Protocol (JRMP) or work with other CORBA-compliant programming languages using the Internet InterORB Protocol (IIOP).

The RMI programming model is part of the Java™ Platform Standard Edition, and consists of both an Object Request Broker (ORB) and the rmic compiler. The rmic compiler is used to generate stubs, skeletons, and ties for remote objects using either the JRMP or IIOP protocols. The rmic compiler can also generates OMG IDL. For more information on using rmic, link to rmic - The Java RMI Stub Compiler.

The RMI over IIOP Programmer's Guide discusses the differences between using RMI with JRMP or IIOP.

When should I use the RMI programming model instead of the IDL programming model?

The RMI programming model speeds distributed application development by allowing developers to work completely in the Java programming language. When using the RMI programming model to produce Java technology-based distributed applications, there is no separate Interface Definition Language (IDL) or mapping to learn. The RMI programming model provides flexibility by allowing developers to pass any serializable Java object (Objects By Value) between application components. Like the IDL programming model, the RMI programming model is based on open standards defined with the participation of hundreds of vendors and users in the Java Community Process (JCP). Like the IDL programming model, the RMI programming model can use the Internet Inter-ORB Protocol (IIOP) as its communication protocol. IIOP eases legacy application and platform integration by allowing application components written in C++, Smalltalk, and other CORBA supported languages to communicate with components running on the Java platform.

With the RMI programming model, developers can write remote interfaces in the Java programming language and implement them simply using Java technology and the Java RMI APIs. These interfaces can be implemented in any other language that is supported by an OMG mapping and a vendor supplied ORB for that language. Similarly, clients can be written in other languages using IDL derived from the remote Java technology-based interfaces.

Where can I found out more about the RMI programming model

  • For more information on RMI over IIOP, see RMI over IIOP Documentation.
  • For more information on RMI over JRMP, see RMI Documentation.
  • For an introductory tutorial using RMI over IIOP, see Tutorial: Getting Started with RMI over IIOP.
  • For more information on mapping Java interfaces to OMG IDL, see Catalog of OMG IDL / Language Mappings Specificatons.

The IDL Programming Model

What is the IDL Programming Model

The IDL programming model, known as Java™ IDL, consists of both the Java CORBA ORB and the idlj compiler that maps the OMG IDL to Java bindings that use the Java CORBA ORB, as well as a set of APIs, which can be explored by selecting the org.omg prefix from the Package section of the API index.

Java IDL adds CORBA (Common Object Request Broker Architecture) capability to the Java platform, providing standards-based interoperability and connectivity. Java IDL enables distributed Web-enabled Java applications to transparently invoke operations on remote network services using the industry standard IDL (Object Management Group Interface Definition Language) and IIOP (Internet Inter-ORB Protocol) defined by the Object Management Group. Runtime components include a Java ORB for distributed computing using IIOP communication.

To use the IDL programming model, you define remote interfaces using the Object Management Group's (OMG) Interface Definition Language (IDL), then compile the interfaces using the idlj compiler. When you run the idlj compiler over your interface definition file, it generates the Java version of the interface, as well as the class code files for the stubs and skeletons that enable your applications to hook into the ORB.

Java™ IDL is part of the Java Platform Standard Edition, v1.2 and above. To develop applications with Java IDL, use Java™ IDL Compiler, idlj, which is included in every installation of J2SE v1.3 and higher.

When should I use the IDL programming model instead of the RMI programming model?

The OMG IDL (Interface Definition Language) is a purely declarative language designed for specifying programming-language-independent operational interfaces for distributed applications. OMG specifies a mapping from IDL to several different programming languages, including Java, C, C++, Lisp, Python, Smalltalk, COBOL, and Ada. When mapped, each statement in OMG IDL is translated to a corresponding statement in the programming language of choice. Java IDL is an implementation of the CORBA specification. For example, you could use the Java IDL Compiler, idlj, to map an IDL interface to Java and implement the client class in Java. If you map the same IDL to C++, using an IDL-to-C++ compiler and a C++ ORB, and implement the server in that language, the Java client and C++ server interoperate through the ORB.

NOTE: Although it is true that ORBs written in different languages should be able to talk to each other, we haven't tested the interoperability of the Java ORB with other vendor's ORBs.

Where can I find out more about the IDL programming model

  • For more information on the IDL programming model, see Java IDL Documentation.
  • For an introductory tutorial to the IDL programming model, see the Getting Started with Java IDL tutorial.
  • For more information on how IDL maps to the Java language, see see the Catalog of OMG IDL / Language Mappings Specificatons.

Comparison of IDL and RMI programming models

There are several scenarios that will define how you will want to create distributed CORBA applications. Here are some of them:

  • If you have been developing CORBA applications using IDL for some time, you will probably want to stay in this environment. Create the interfaces using IDL, and define the client and server applications using the Java programming language to take advantage of its portabile, highly productive implementation environment, and its very robust platform.
  • If all of your applications are written in the Java programming language, you will probably want to use Java RMI to enable communication between Java objects on different virtual machines and different physical machines. Using Java RMI without its IIOP option leverages its strengths of code portability, security, and garbage collection.
  • If you are writing most of your new applications using the Java programming language, but need to maintain legacy applications written in other programming languages as well, you will probably want to use Java RMI with its IIOP compiler option.

What about CORBA and J2EE?

In addition to Java IDL and RMI over IIOP, J2EE includes Enterprise JavaBeans™ technology (EJB™).

Enterprise JavaBeans is part of the Java Platform, Enterprise Edition. The EJB server-side component model simplifies development of middleware components that are transactional, scalable, and portable. EJB servers reduce the complexity of developing middleware by providing automatic support for middleware services such as transactions, security, database connectivity, and more.

EJBs use RMI over IIOP for their distributed object model, and use the Java Transaction Service (JTS) for their distributed transaction model. When Enterprise JavaBeans are implemented using the RMI over IIOP protocol for EJB interoperability in heterogeneous server environments, the standard mapping of the EJB architecture to CORBA enables the following interoperability:

  • A Java client using an ORB from one vendor can access enterprise beans residing on an EJB server provided by another vendor.
  • Enterprise beans in one EJB server can access enterprise beans in another EJB server.
  • A non-Java platform CORBA client can access any enterprise bean object.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java VisualVM

Working with Core Dumps

When you start Java VisualVM, the Applications window is visible in the left of the Java VisualVM window. The Applications window enables you to quickly view running local and remote applications. The Applications also displays core dumps and profiling snapshots saved to your local system.

The Core Dump node is visible in the Applications window if Java VisualVM is running on Solaris or Linux. Generally, Java VisualVM can only open a core dump if the core dump was taken on the same machine. A core dump contains informaton on the Java Development Kit (JDK) and kernel of the machine where the core dump was taken. To open the core dump in Java VisualVM, this information must match the JDK software and kernel of the local system.

A core dump is a binary file capturing the entire heap contents at the moment the dump is captured. When you load a core dump in Java VisualVM, a node for the core dump appears below the Core Dump node.

screenshot of Applications window showing Core Dump node

To view an overview of the core dump, right-click the core dump node and choose Open. (Alternatively, double-click the node.)

screenshot of Overview tab of core dump

You can right-click the core dump node and choose Heap Dump or Thread Dump to view the heap dump and thread dump from the core dump.

screenshot of Overview tab of core dump

You can then save the thread dump and heap dump to your local system.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface org.w3c.dom.css.Counter (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.css.Counter

  • Packages that use Counter
    Package Description
    org.w3c.dom.css

    • Uses of Counter in org.w3c.dom.css

      Methods in org.w3c.dom.css that return Counter
      Modifier and Type Method and Description
      Counter CSSPrimitiveValue.getCounterValue()
      This method is used to get the Counter value.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Legal Notices

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.

This software and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intellectual property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is prohibited.

The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us in writing.

If this is software or related software documentation that is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, the following notice is applicable:

U.S. GOVERNMENT RIGHTS Programs, software, databases, and related documentation and technical data delivered to U.S. Government customers are "commercial computer software" or "commercial technical data" pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, the use, duplication, disclosure, modification, and adaptation shall be subject to the restrictions and license terms set forth in the applicable Government contract, and, to the extent applicable by the terms of the Government contract, the additional rights set forth in FAR 52.227-19, Commercial Computer Software License (December 2007). Oracle USA, Inc., 500 Oracle Parkway, Redwood City, CA 94065.

This software or hardware is developed for general use in a variety of information management applications. It is not developed or intended for use in any inherently dangerous applications, including applications which may create a risk of personal injury. If you use this software or hardware in dangerous applications, then you shall be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure the safe use. Oracle Corporation and its affiliates disclaim any liability for any damages caused by use of this software or hardware in dangerous applications.

Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.

AMD, Opteron, the AMD logo, and the AMD Opteron logo are trademarks or registered trademarks of Advanced Micro Devices. Intel and Intel Xeon are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. UNIX is a registered trademark licensed through X/Open Company, Ltd.

This software or hardware and documentation may provide access to or information on content, products, and services from third parties. Oracle Corporation and its affiliates are not responsible for and expressly disclaim all warranties of any kind with respect to third-party content, products, and services. Oracle Corporation and its affiliates will not be responsible for any loss, costs, or damages incurred due to your access to or use of third-party content, products, or services.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Cryptography Architecture (JCA)

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java™ Cryptography Architecture
(JCA) Reference Guide

for Java™ Platform Standard Edition 6
  • Introduction
    • Design Principles
    • Architecture
    • JCA Concepts
  • Core Classes and Interfaces
    • The Provider Class
      • How Provider Implementations are Requested and Supplied
      • Installing Providers
    • The Security Class
    • The SecureRandom Class
    • The MessageDigest Class
    • The Signature Class
    • The Cipher Class
    • Other Cipher-based Classes
      • The Cipher Stream Classes
        • The CipherInputStream Class
        • The CipherOutputStream Class
      • The SealedObject Class
    • The Mac Class
    • Key Interfaces
    • The KeyPair Class
    • Key Specification Interfaces and Classes
      • The KeySpec Interface
      • The KeySpec Subinterfaces
      • The EncodedKeySpec Class
        • The PKCS8EncodedKeySpec Class
        • The X509EncodedKeySpec Class
    • Of Factories and Generators
    • The KeyFactory Class
    • The SecretKeyFactory Class
    • The KeyPairGenerator Class
    • The KeyGenerator Class
    • The KeyAgreement Class
    • Key Management
      • Keystore Location
      • Keystore Implementation
      • The KeyStore Class
    • Algorithm Parameters Classes
      • The AlgorithmParameterSpec Interface
      • The AlgorithmParameters Class
      • The AlgorithmParameterGenerator Class
    • The CertificateFactory Class
  • How the JCA Might Be Used in a SSL/TLS Implementation
  • How to Make Applications "Exempt" from Cryptographic Restrictions
  • Code Examples
    • Computing a MessageDigest Object
    • Generating a Pair of Keys
    • Generating and Verifying a Signature Using Generated Keys
    • Generating/Verifying Signatures Using Key Specifications and KeyFactory
    • Determining If Two Keys Are Equal
    • Reading Base64-Encoded Certificates
    • Parsing a Certificate Reply
    • Using Encryption
    • Using Password-Based Encryption
    • Using Key Agreement
  • Appendix A: Standard Names
  • Appendix B: Jurisdiction Policy File Format
  • Appendix C: Maximum Key Sizes Allowed by "Strong" Jurisdiction Policy Files
  • Appendix D: Sample Programs
    • Diffie-Hellman Key Exchange between 2 Parties
    • Diffie-Hellman Key Exchange between 3 Parties
    • Blowfish Cipher Example
    • HMAC-MD5 Example
    • Reading ASCII Passwords From an InputStream Example

Introduction

The Java platform strongly emphasizes security, including language safety, cryptography, public key infrastructure, authentication, secure communication, and access control.

The JCA is a major piece of the platform, and contains a "provider" architecture and a set of APIs for digital signatures, message digests (hashs), certificates and certificate validation, encryption (symmetric/asymmetric block/stream ciphers), key generation and management, and secure random number generation, to name a few. These APIs allow developers to easily integrate security into their application code. The architecture was designed around the following principles:

  1. Implementation independence
    Applications do not need to implement security algorithms. Rather, they can request security services from the Java platform. Security services are implemented in providers (see below), which are plugged into the Java platform via a standard interface. An application may rely on multiple independent providers for security functionality.
  2. Implementation interoperability
    Providers are interoperable across applications. Specifically, an application is not bound to a specific provider, and a provider is not bound to a specific application.
  3. Algorithm extensibility
    The Java platform includes a number of built-in providers that implement a basic set of security services that are widely used today. However, some applications may rely on emerging standards not yet implemented, or on proprietary services. The Java platform supports the installation of custom providers that implement such services.

Other cryptographic communication libraries available in the JDK use the JCA provider architecture, but are described elsewhere. The Java™ Secure Socket Extension (JSSE) provides access to Secure Socket Layer (SSL) and Transport Layer Security (TLS) implementations. The Java Generic Security Services (JGSS) (via Kerberos) APIs, and the Simple Authentication and Security Layer (SASL) can also be used for securely exchanging messages between communicating applications.

Notes on Terminology

  • Prior to JDK 1.4, the JCE was an unbundled product, and as such, the JCA and JCE were regularly referred to as separate, distinct components. As JCE is now bundled in the JDK, the distinction is becoming less apparent. Since the JCE uses the same architecture as the JCA, the JCE should be more properly thought of as a part of the JCA.
  • The JCA within the JDK includes two software components:
    1. the framework that defines and supports cryptographic services for which providers supply implementations. This framework includes packages such as java.security, javax.crypto, javax.crypto.spec, and javax.crypto.interfaces.
    2. the actual providers such as Sun, SunRsaSign, SunJCE, which contain the actual cryptographic implementations.

    Whenever a specific JCA provider is mentioned, it will be referred to explicitly by the provider's name.

WARNING: The JCA makes it easy to incorporate security features into your application. However, this document does not cover the theory of security/cryptography beyond an elementary introduction to concepts necessary to discuss the APIs. This document also does not cover the strengths/weaknesses of specific algorithms, not does it cover protocol design. Cryptography is an advanced topic and one should consult a solid, preferably recent, reference in order to make best use of these tools.

You should always understand what you are doing and why: DO NOT simply copy random code and expect it to fully solve your usage scenario. Many applications have been deployed that contain significant security or performance problems because the wrong tool or algorithm was selected.

Design Principles

The JCA was designed around these principles:

  • implementation independence and interoperability
  • algorithm independence and extensibility

Implementation independence and algorithm independence are complementary; you can use cryptographic services, such as digital signatures and message digests, without worrying about the implementation details or even the algorithms that form the basis for these concepts. While complete algorithm-independence is not possible, the JCA provides standardized, algorithm-specific APIs. When implementation-independence is not desirable, the JCA lets developers indicate a specific implementation.

Algorithm independence is achieved by defining types of cryptographic "engines" (services), and defining classes that provide the functionality of these cryptographic engines. These classes are called engine classes, and examples are the MessageDigest, Signature, KeyFactory, KeyPairGenerator, and Cipher classes.

Implementation independence is achieved using a "provider"-based architecture. The term Cryptographic Service Provider (CSP) (used interchangeably with "provider" in this document) refers to a package or set of packages that implement one or more cryptographic services, such as digital signature algorithms, message digest algorithms, and key conversion services. A program may simply request a particular type of object (such as a Signature object) implementing a particular service (such as the DSA signature algorithm) and get an implementation from one of the installed providers. If desired, a program may instead request an implementation from a specific provider. Providers may be updated transparently to the application, for example when faster or more secure versions are available.

Implementation interoperability means that various implementations can work with each other, use each other's keys, or verify each other's signatures. This would mean, for example, that for the same algorithms, a key generated by one provider would be usable by another, and a signature generated by one provider would be verifiable by another.

Algorithm extensibility means that new algorithms that fit in one of the supported engine classes can be added easily.

Architecture

Cryptographic Service Providers

java.security.Provider is the base class for all security providers. Each CSP contains an instance of this class which contains the provider's name and lists all of the security services/algorithms it implements. When an instance of a particular algorithm is needed, the JCA framework consults the provider's database, and if a suitable match is found, the instance is created.

Providers contain a package (or a set of packages) that supply concrete implementations for the advertised cryptographic algorithms. Each JDK installation has one or more providers installed and configured by default. Additional providers may be added statically or dynamically (see the Provider and Security classes). Clients may configure their runtime environment to specify the provider preference order. The preference order is the order in which providers are searched for requested services when no specific provider is requested.

To use the JCA, an application simply requests a particular type of object (such as a MessageDigest) and a particular algorithm or service (such as the "MD5" algorithm), and gets an implementation from one of the installed providers. Alternatively, the program can request the objects from a specific provider. Each provider has a name used to refer to it.

    md = MessageDigest.getInstance("MD5");
    md = MessageDigest.getInstance("MD5", "ProviderC");

The following figure illustrates requesting an "MD5" message digest implementation. The figure show three different providers that implement various message digest algorithms ("SHA-1", "MD5", "SHA-256", and "SHA-512"). The providers are ordered by preference from left to right (1-3). In the first illustration, an application requests an MD5 algorithm implementation without specifying a provider name. The providers are searched in preference order and the implementation from the first provider supplying that particular algorithm, ProviderB, is returned. In the second figure, the application requests the MD5 algorithm implementation from a specific provider, ProviderC. This time the implementation from ProviderC is returned, even though a provider with a higher preference order, ProviderB, also supplies an MD5 implementation.

<Image of the General JCA Architecture>

Cryptographic implementations in the Sun JDK are distributed via several different providers (Sun, SunJSSE, SunJCE, SunRsaSign) primarily for historical reasons, but to a lesser extent by the type of functionality and algorithms they provide. Other Java runtime environments may not necessarily contain these Sun providers, so applications should not request an provider-specific implementation unless it is known that a particular provider will be available.

The JCA offers a set of APIs that allow users to query which providers are installed and what services they support.

This architecture also makes it easy for end-users to add additional providers. Many third party provider implementations are already available. See The Provider Class for more information on how providers are written, installed, and registered.

How Providers Are Actually Implemented

As mentioned earlier, algorithm independence is achieved by defining a generic high-level Application Programming Interface (API) that all applications use to access a service type. Implementation independence is achieved by having all provider implementations conform to well-defined interfaces. Instances of engine classes are thus "backed" by implementation classes which have the same method signatures. Application calls are routed through the engine class and are delivered to the underlying backing implementation. The implementation handles the request and return the proper results.

The application API methods in each engine class are routed to the provider's implementations through classes that implement the corresponding Service Provider Interface (SPI). That is, for each engine class, there is a corresponding abstract SPI class which defines the methods that each cryptographic service provider's algorithm must implement. The name of each SPI class is the same as that of the corresponding engine class, followed by Spi. For example, the Signature engine class provides access to the functionality of a digital signature algorithm. The actual provider implementation is supplied in a subclass of SignatureSpi. Applications call the engine class' API methods, which in turn call the SPI methods in the actual implementation.

Each SPI class is abstract. To supply the implementation of a particular type of service for a specific algorithm, a provider must subclass the corresponding SPI class and provide implementations for all the abstract methods.

For each engine class in the API, implementation instances are requested and instantiated by calling the getInstance() factory method in the engine class. A factory method is a static method that returns an instance of a class. The engine classes use the framework provider selection mechanism described above to obtain the actual backing implementation (SPI), and then creates the actual engine object. Each instance of the engine class encapsulates (as a private field) the instance of the corresponding SPI class, known as the SPI object. All API methods of an API object are declared final and their implementations invoke the corresponding SPI methods of the encapsulated SPI object.

To make this clearer, review the following code and illustration:

    import javax.crypto.*;

    Cipher c = Cipher.getInstance("AES");
    c.init(ENCRYPT_MODE, key);
<Image of the Provider Architecture Overview>

Here an application wants an "AES" javax.crypto.Cipher instance, and doesn't care which provider is used. The application calls the getInstance() factory methods of the Cipher engine class, which in turn asks the JCA framework to find the first provider instance that supports "AES". The framework consults each installed provider, and obtains the provider's instance of the Provider class. (Recall that the Provider class is a database of available algorithms.) The framework searches each provider, finally finding a suitable entry in CSP3. This database entry points to the implementation class com.foo.AESCipher which extends CipherSpi, and is thus suitable for use by the Cipher engine class. An instance of com.foo.AESCipher is created, and is encapsulated in a newly-created instance of javax.crypto.Cipher, which is returned to the application. When the application now does the init() operation on the Cipher instance, the Cipher engine class routes the request into the corresponding engineInit() backing method in the com.foo.AESCipher class.

Appendix A lists the Standard Names defined for the Java environment. Other third-party providers may define their own implementations of these services, or even additional services.

Key Management

A database called a "keystore" can be used to manage a repository of keys and certificates. Keystores are available to applications that need data for authentication, encryption, or signing purposes.

Applications can access a keystore via an implementation of the KeyStore class, which is in the java.security package. A default KeyStore implementation is provided by Sun Microsystems. It implements the keystore as a file, using a proprietary keystore type (format) named "jks". Other keystore formats are available, such as "jceks" which is an alternate proprietary keystore format with much stronger encryption than "jks", and "pkcs12", which is based on the RSA PKCS12 Personal Information Exchange Syntax Standard.

Applications can choose different keystore implementations from different providers, using the same provider mechanism described above.

See the Key Management section for more information.

JCA Concepts

This section introduces the major JCA APIs.

Engine Classes and Algorithms

An engine class provides the interface to a specific type of cryptographic service, independent of a particular cryptographic algorithm or provider. The engines either provide:

  • cryptographic operations (encryption, digital signatures, message digests, etc.),
  • generators or converters of cryptographic material (keys and algorithm parameters), or
  • objects (keystores or certificates) that encapsulate the cryptographic data and can be used at higher layers of abstraction.

The following engine classes are available:

  • SecureRandom: used to generate random or pseudo-random numbers.
  • MessageDigest: used to calculate the message digest (hash) of specified data.
  • Signature: initilialized with keys, these are used to sign data and verify digital signatures.
  • Cipher: initialized with keys, these used for encrypting/decrypting data. There are various types of algorithms: symmetric bulk encryption (e.g. AES, DES, DESede, Blowfish, IDEA), stream encryption (e.g. RC4), asymmetric encryption (e.g. RSA), and password-based encryption (PBE).
  • Message Authentication Codes (MAC): like MessageDigests, these also generate hash values, but are first initialized with keys to protect the integrity of messages.

  • KeyFactory: used to convert existing opaque cryptographic keys of type Key into key specifications (transparent representations of the underlying key material), and vice versa.
  • SecretKeyFactory: used to convert existing opaque cryptographic keys of type SecretKey into key specifications (transparent representations of the underlying key material), and vice versa. SecretKeyFactorys are specialized KeyFactorys that create secret (symmetric) keys only.
  • KeyPairGenerator: used to generate a new pair of public and private keys suitable for use with a specified algorithm.
  • KeyGenerator: used to generate new secret keys for use with a specified algorithm.
  • KeyAgreement: used by two or more parties to agree upon and establish a specific key to use for a particular cryptographic operation.

  • AlgorithmParameters: used to store the parameters for a particular algorithm, including parameter encoding and decoding.
  • AlgorithmParameterGenerator : used to generate a set of AlgorithmParameters suitable for a specified algorithm.

  • KeyStore: used to create and manage a keystore. A keystore is a database of keys. Private keys in a keystore have a certificate chain associated with them, which authenticates the corresponding public key. A keystore also contains certificates from trusted entities.

  • CertificateFactory: used to create public key certificates and Certificate Revocation Lists (CRLs).
  • CertPathBuilder: used to build certificate chains (also known as certification paths).
  • CertPathValidator: used to validate certificate chains.
  • CertStore: used to retrieve Certificates and CRLs from a repository.
NOTE: A generator creates objects with brand-new contents, whereas a factory creates objects from existing material (for example, an encoding).

Core Classes and Interfaces

This section discusses the core classes and interfaces provided in the JCA:

  • the Provider and Security classes,
  • the SecureRandom, MessageDigest, Signature, Cipher, Mac, KeyFactory, SecretKeyFactory, KeyPairGenerator, KeyGenerator, KeyAgreement, AlgorithmParameters, AlgorithmParameterGenerator , KeyStore, and CertificateFactory, engine classes,
  • the Key interfaces and classes,
  • the Algorithm Parameter Specification Interfaces and Classes and the Key Specification Interfaces and Classes, and
  • miscellaneous support and convenience interfaces and classes.
  • NOTE: For more information on the CertPathBuilder, CertPathValidator, and CertStore engine classes, please see the Java(TM) PKI Programmer's Guide.
The guide will cover the most useful high-level classes first (Provider, Security, SecureRandom, MessageDigest, Signature, Cipher, and Mac), then delve into the various support classes. For now, it is sufficient to simply say that Keys (public, private, and secret) are generated and represented by the various JCA classes, and are used by the high-level classes as part of their operation.

This section shows the signatures of the main methods in each class and interface. Examples for some of these classes (MessageDigest, Signature, KeyPairGenerator, SecureRandom, KeyFactory, and key specification classes) are supplied in the corresponding Examples sections.

The complete reference documentation for the relevant Security API packages can be found in the package summaries:

  • java.security
  • javax.crypto
  • java.security.cert
  • java.security.spec
  • javax.crypto.spec
  • java.security.interfaces
  • javax.crypto.interfaces

The Provider Class

The term "Cryptographic Service Provider" (used interchangeably with "provider" in this document) refers to a package or set of packages that supply a concrete implementation of a subset of the JDK Security API cryptography features. The Provider class is the interface to such a package or set of packages. It has methods for accessing the provider name, version number, and other information. Please note that in addition to registering implementations of cryptographic services, the Provider class can also be used to register implementations of other security services that might get defined as part of the JDK Security API or one of its extensions.

To supply implementations of cryptographic services, an entity (e.g., a development group) writes the implementation code and creates a subclass of the Provider class. The constructor of the Provider subclass sets the values of various properties; the JDK Security API uses these values to look up the services that the provider implements. In other words, the subclass specifies the names of the classes implementing the services.

<Image of Provider operation>

There are several types of services that can be implemented by provider packages; for more information, see Engine Classes and Algorithms.

The different implementations may have different characteristics. Some may be software-based, while others may be hardware-based. Some may be platform-independent, while others may be platform-specific. Some provider source code may be available for review and evaluation, while some may not. The JCA lets both end-users and developers decide what their needs are.

In this section we explain how end-users install the cryptography implementations that fit their needs, and how developers request the implementations that fit theirs.

NOTE: For information about implementing a provider, see the guide How To Implement a Provider for the Java Cryptography Architecture.

How Provider Implementations Are Requested and Supplied

For each engine class in the API, a implementation instance is requested and instantiated by calling one of the getInstance methods on the engine class, specifying the name of the desired algorithm and, optionally, the name of the provider (or the Provider class) whose implementation is desired.
static EngineClassName getInstance(String algorithm)
    throws NoSuchAlgorithmException

static EngineClassName getInstance(String algorithm, String provider)
    throws NoSuchAlgorithmException, NoSuchProviderException

static EngineClassName getInstance(String algorithm, Provider provider)
    throws NoSuchAlgorithmException
where EngineClassName is the desired engine type (MessageDigest/Cipher/etc). For example:
    MessageDigest md = MessageDigest.getInstance("MD5");
    KeyAgreement ka = KeyAgreement.getInstance("DH", "SunJCE");
return an instance of the "MD5" MessageDigest and "DH" KeyAgreement objects, respectively.

Appendix A contains the list of names that have been standardized for use with the Java environment. Some providers may choose to also include alias names that also refer to the same algorithm. For example, the "SHA-1" algorithm might be referred to as "SHA1". Applications should use standard names instead of an alias, as not all providers may alias algorithm names in the same way.

NOTE: The algorithm name is not case-sensitive. For example, all the following calls are equivalent:
MessageDigest.getInstance("SHA-1")
MessageDigest.getInstance("sha-1")
MessageDigest.getInstance("sHa-1")

If no provider is specified, getInstance searches the registered providers for an implementation of the requested cryptographic service associated with the named algorithm. In any given Java Virtual Machine (JVM), providers are installed in a given preference order, the order in which the provider list is searched if a specific provider is not requested. For example, suppose there are two providers installed in a JVM, PROVIDER_1 and PROVIDER_2. Assume that:

  • PROVIDER_1 implements SHA1withDSA, SHA-1, MD5, DES, and DES3.
    PROVIDER_1 has preference order 1 (the highest priority).
  • PROVIDER_2 implements SHA1withDSA, MD5withRSA, MD2withRSA, MD2, MD5, RC4, RC5, DES, and RSA.
    PROVIDER_2 has preference order 2.
Now let's look at three scenarios:
  1. If we are looking for an MD5 implementation. Both providers supply such an implementation. The PROVIDER_1 implementation is returned since PROVIDER_1 has the highest priority and is searched first.
  2. If we are looking for an MD5withRSA signature algorithm, PROVIDER_1 is first searched for it. No implementation is found, so PROVIDER_2 is searched. Since an implementation is found, it is returned.
  3. Suppose we are looking for a SHA1withRSA signature algorithm. Since no installed provider implements it, a NoSuchAlgorithmException is thrown.

The getInstance methods that include a provider argument are for developers who want to specify which provider they want an algorithm from. A federal agency, for example, will want to use a provider implementation that has received federal certification. Let's assume that the SHA1withDSA implementation from PROVIDER_1 has not received such certification, while the DSA implementation of PROVIDER_2 has received it.

A federal agency program would then have the following call, specifying PROVIDER_2 since it has the certified implementation:

Signature dsa = Signature.getInstance("SHA1withDSA", "PROVIDER_2");

In this case, if PROVIDER_2 was not installed, a NoSuchProviderException would be thrown, even if another installed provider implements the algorithm requested.

A program also has the option of getting a list of all the installed providers (using the getProviders method in the Security class) and choosing one from the list.

NOTE: General purpose applications SHOULD NOT request cryptographic services from specific providers. Otherwise, applications are tied to specific providers which may not be available on other Java implementations. They also might not be able to take advantage of available optimized providers (for example hardware accelerators via PKCS11 or native OS implementations such as Microsoft's MSCAPI) that have a higher preference order than the specific requested provider.

Installing Providers

In order to be used, a cryptographic provider must first be installed, then registered either statically or dynamically. There are a variety of Sun providers shipped with this release (SUN, SunJCE, SunJSSE, SunRsaSign, etc.) that are already installed and registered. The following sections describe how to install and register additional providers.

Installing the Provider Classes

There are two possible ways to install the provider classes:

  1. On the normal Java classpath

    Place a zip or JAR file containing the classes anywhere in your classpath. Some algorithms types (Ciphers) require the provider be a signed Jar file.

  2. As an Installed/Bundled Extension

    The provider will be considered an installed extension if it is placed in the standard extension directory. In Sun's JDK, that would be located in:

        <java-home>/lib/ext                   [Unix]
    <java-home>\lib\ext                   [Windows]
    Here <java-home> refers to the directory where the runtime software is installed, which is the top-level directory of the Java™ Runtime Environment (JRE) or the jre directory in the Java™ JDK software. For example, if you have JDK 6 installed on Solaris in a directory named /home/user1/JDK1.6.0, or on Microsoft Windows in a directory named C:\Java\JDK1.6.0, then you need to install the JAR file in the following directory:
        /home/user1/JDK1.6.0/jre/lib/ext      [Unix]
    C:\JDK1.6.0\jre\lib\ext               [Windows]

    Similarly, if you have the JRE 6 installed on Solaris in a directory named /home/user1/jre1.6.0, or on Microsoft Windows in a directory named C:\jre1.6.0, you need to install the JAR file in the following directory:

          /home/user1/jre1.6.0/lib/ext          [Unix]
      C:\jre1.6.0\lib\ext                   [Windows]
    For more information on how to deploy an extension, see How is an extension deployed?

Registering the Provider

The next step is to add the provider to your list of registered providers. Providers can be registered statically by editing a security properties configuration file before running a Java application, or dynamically by calling a method at runtime. To prevent the installation of rogue providers being added to the runtime environment, applications attempting to dynamically register a provider must possess the appropriate runtime privilege.

Static Registration
The configuration file is located in the following location:
    <java-home>/lib/security/java.security     [Unix]
    <java-home>\lib\security\java.security     [Windows]
For each registered provider, this file should have a statement of the following form:
    security.provider.n=masterClassName

This declares a provider, and specifies its preference order n. The preference order is the order in which providers are searched for requested algorithms (when no specific provider is requested). The order is 1-based: 1 is the most preferred, followed by 2, and so on.

masterClassName must specify the fully qualified name of provider's master class. The provider's documentation will specify its master class. This class is always a subclass of the Provider class. The subclass constructor sets the values of various properties that are required for the Java Cryptography API to look up the algorithms or other facilities the provider implements.

The JDK comes standard with automatically installed and configured providers such as "SUN" and "SunJCE". The "SUN" provider's master class is the SUN class in the sun.security.provider package, and the corresponding java.security file entry is as follows:

    security.provider.5=sun.security.provider.Sun

To utilize another JCA provider, add a line referencing the alternate provider, specify the preference order ( making corresponding adjustments to the other providers' orders, if needed).

Suppose that the master class of CompanyX's provider is com.companyx.provider.ProviderX, and that you would like to configure this provider as the eighth most-preferred. To do so, you would add the following line to the java.security file:

    security.provider.8=com.companyx.provider.ProviderX
Dynamic Registration
To register providers dynamically, applications call either the addProvider or insertProviderAt method in the Security class. This type of registration is not persistent across VM instances, and can only be done by "trusted" programs with the appropriate privilege. See Security.

Setting Provider Permissions

Whenever encryption providers are used (that is, those that supply implementations of Cipher, KeyAgreement, KeyGenerator, Mac, or SecretKeyFactory), and the provider is not an installed extension Permissions may need to be granted for when applets or applications using JCA are run while a security manager is installed. There is typically a security manager installed whenever an applet is running, and a security manager may be installed for an application either via code in the application itself or via a command-line argument. Permissions do not need to be granted to installed extensions, since the default system policy configuration file grants all permissions to installed extensions (that is, installed in the extensions directory).

The documentation from the vendor of each provider you will be using should include information as to which permissions it requires, and how to grant such permissions. For example, the following permissions may be needed by a provider if it is not an installed extension and a security manager is installed:

  • java.lang.RuntimePermission "getProtectionDomain" to get class protection domains. The provider may need to get its own protection domain in the process of doing self-integrity checking.
  • java.security.SecurityPermission "putProviderProperty.{name}" to set provider properties, where {name} is replaced by the actual provider name.

For example, a sample statement granting permissions to a provider whose name is "MyJCE" and whose code is in myjce_provider.jar appears below. Such a statement could appear in a policy file. In this example, the myjce_provider.jar file is assumed to be in the /localWork directory.

    grant codeBase "file:/localWork/myjce_provider.jar" {
        permission java.lang.RuntimePermission "getProtectionDomain";
        permission java.security.SecurityPermission
            "putProviderProperty.MyJCE";
     };

Provider Class Methods

Each Provider class instance has a (currently case-sensitive) name, a version number, and a string description of the provider and its services. You can query the Provider instance for this information by calling the following methods:

public String getName()
public double getVersion()
public String getInfo()

The Security Class

The Security class manages installed providers and security-wide properties. It only contains static methods and is never instantiated. The methods for adding or removing providers, and for setting Security properties, can only be executed by a trusted program. Currently, a "trusted program" is either

  • a local application not running under a security manager, or
  • an applet or application with permission to execute the specified method (see below).
The determination that code is considered trusted to perform an attempted action (such as adding a provider) requires that the applet is granted the proper permission(s) for that particular action. The policy configuration file(s) for a JDK installation specify what permissions (which types of system resource accesses) are allowed by code from specified code sources. (See below and the "Default Policy Implementation and Policy File Syntax" and "Java Security Architecture Specification" files for more information.)

Code being executed is always considered to come from a particular "code source". The code source includes not only the location (URL) where the code originated from, but also a reference to any public key(s) corresponding to the private key(s) that may have been used to sign the code. Public keys in a code source are referenced by (symbolic) alias names from the user's keystore.

In a policy configuration file, a code source is represented by two components: a code base (URL), and an alias name (preceded by signedBy), where the alias name identifies the keystore entry containing the public key that must be used to verify the code's signature.

Each "grant" statement in such a file grants a specified code source a set of permissions, specifying which actions are allowed.

Here is a sample policy configuration file:

grant codeBase "file:/home/sysadmin/", signedBy "sysadmin" {
    permission java.security.SecurityPermission "insertProvider.*";
    permission java.security.SecurityPermission "removeProvider.*";
    permission java.security.SecurityPermission "putProviderProperty.*";
};
This configuration file specifies that code loaded from a signed JAR file from beneath the /home/sysadmin/ directory on the local file system can add or remove providers or set provider properties. (Note that the signature of the JAR file can be verified using the public key referenced by the alias name sysadmin in the user's keystore.)

Either component of the code source (or both) may be missing. Here's an example of a configuration file where the codeBase is omitted:

grant signedBy "sysadmin" {
    permission java.security.SecurityPermission "insertProvider.*";
    permission java.security.SecurityPermission "removeProvider.*";
};
If this policy is in effect, code that comes in a JAR File signed by sysadmin can add/remove providers--regardless of where the JAR File originated.

Here's an example without a signer:

grant codeBase "file:/home/sysadmin/" {
    permission java.security.SecurityPermission "insertProvider.*";
    permission java.security.SecurityPermission "removeProvider.*";
};
In this case, code that comes from anywhere within the /home/sysadmin/ directory on the local filesystem can add/remove providers. The code does not need to be signed.

An example where neither codeBase nor signedBy is included is:

grant {
    permission java.security.SecurityPermission "insertProvider.*";
    permission java.security.SecurityPermission "removeProvider.*";
};
Here, with both code source components missing, any code (regardless of where it originates, or whether or not it is signed, or who signed it) can add/remove providers. Obviously, this is definitely NOT recommended, as this grant could open a security hole. Untrusted code could install a Provider, thus affecting later code that is depending on a properly functioning implementation. (For example, a rogue Cipher object might capture and store the sensitive information it receives.)

Managing Providers

The following tables summarize the methods in the Security class you can use to query which Providers are installed, as well as to install or remove providers at runtime.

Querying Providers
Method | Description
static Provider[] getProviders() | Returns an array containing all the installed providers (technically, the Provider subclass for each package provider). The order of the Providers in the array is their preference order.
static Provider getProvider
(String providerName) 		Returns the Provider named providerName. It returns null if the Provider is not found.
Adding Providers
Method | Description
static int addProvider(Provider provider) | Adds a Provider to the end of the list of installed Providers. It returns the preference position in which the Provider was added, or -1 if the Provider was not added because it was already installed.
static int insertProviderAt (Provider provider, int position) | Adds a new Provider at a specified position. If the given provider is installed at the requested position, the provider formerly at that position and all providers with a position greater than position are shifted up one position (towards the end of the list). This method returns the preference position in which the Provider was added, or -1 if the Provider was not added because it was already installed.
Removing Providers
Method | Description
static void removeProvider(String name) | Removes the Provider with the specified name. It returns silently if the provider is not installed. When the specified provider is removed, all providers located at a position greater than where the specified provider was are shifted down one position (towards the head of the list of installed providers).

NOTE: If you want to change the preference position of a provider, you must first remove it, and then insert it back in at the new preference position.

Security Properties

The Security class maintains a list of system-wide security properties. These properties are similar to the System properties, but are security-related. These properties can be set statically or dynamically. We have already seen an example of static security properties (that is, registering a provider statically via the "security.provider.i" security property). If you want to set properties dynamically, trusted programs can use the following methods:

static String getProperty(String key)
static void setProperty(String key, String datum)
Note: the list of security providers is established during VM startup, therefore the methods described above must be used to alter the provider list.

As a reminder, the configuration file is located in the following location:

<java-home>/lib/security/java.security     [Unix]
<java-home>\lib\security\java.security     [Windows]

The SecureRandom Class

The SecureRandom class is an engine class that provides the functionality of a Random Number Generator (RNG). It differs from the Random class in that it produces cryptographically strong random numbers. If there is insufficient randomness in a generator, it makes it much easier to compromise your protection mechanisms. Random numbers are used throughout cryptography, such as generating cryptographic keys or algorithmic parameters.

<Image of SecureRandom operation>

Creating a SecureRandom Object

As with all engine classes, the way to get a SecureRandom object is to call one of the getInstance() static factory methods in the SecureRandom class.

Seeding or Re-Seeding the SecureRandom Object

The SecureRandom implementation attempts to completely randomize the internal state of the generator itself unless the caller follows the call to a getInstance method with a call to one of the setSeed methods:

synchronized public void setSeed(byte[] seed)
public void setSeed(long seed)
Once the SecureRandom object has been seeded, it will produce bits as random as the original seeds.

At any time a SecureRandom object may be re-seeded using one of the setSeed methods. The given seed supplements, rather than replaces, the existing seed; therefore, repeated calls are guaranteed never to reduce randomness.

Using a SecureRandom Object

To get random bytes, a caller simply passes an array of any length, which is then filled with random bytes:

synchronized public void nextBytes(byte[] bytes)

Generating Seed Bytes

If desired, it is possible to invoke the generateSeed method to generate a given number of seed bytes (to seed other random number generators, for example):
byte[] generateSeed(int numBytes)

The MessageDigest Class

The MessageDigest class is an engine class designed to provide the functionality of cryptographically secure message digests such as SHA-1 or MD5. A cryptographically secure message digest takes arbitrary-sized input (a byte array), and generates a fixed-size output, called a digest or hash.

<Image of MessageDigest operation>

For example, the MD5 algorithm produces a 16 byte digest, and SHA1's is 20 bytes.

A digest has two properties:

  • It should be computationally infeasible to find two messages that hash to the same value.
  • The digest should not reveal anything about the input that was used to generate it.

Message digests are used to produce unique and reliable identifiers of data. They are sometimes called "checksums" or the "digital fingerprints" of the data. Changes to just one bit of the message should produce a different digest value.

Message digests have many uses and can determine when data has been modified, intentionally or not. Recently, there has been considerable effort to determine if there are any weaknesses in popular algorithms, with mixed results. When selecting a digest algorithm, one should always consult a recent reference to determine its status and appropriateness for the task at hand.

Creating a MessageDigest Object

The first step for computing a digest is to create a message digest instance. MessageDigest objects are obtained by using one of the getInstance() static factory methods in the MessageDigest class. The factory method returns an initialized message digest object. It thus does not need further initialization.

Updating a Message Digest Object

The next step for calculating the digest of some data is to supply the data to the initialized message digest object. It can be provided all at once, or in chunks. Pieces can be fed to the message digest by calling one of the update methods:

void update(byte input)
void update(byte[] input)
void update(byte[] input, int offset, int len)

Computing the Digest

After the data chunks have been supplied by calls to update, the digest is computed using a call to one of the digest methods:

byte[] digest()
byte[] digest(byte[] input)
int digest(byte[] buf, int offset, int len)

The first method return the computed digest. The second method does a final update(input) with the input byte array before calling digest(), which returns the digest byte array. The last method stores the computed digest in the provided buffer buf, starting at offset. len is the number of bytes in buf allotted for the digest, the method returns the number of bytes actually stored in buf. If there is not enough room in the buffer, the method will throw an exception.

Please see the Computing a MessageDigest example in the Code Examples section for more details.

The Signature Class

The Signature class is an engine class designed to provide the functionality of a cryptographic digital signature algorithm such as DSA or RSAwithMD5. A cryptographically secure signature algorithm takes arbitrary-sized input and a private key and generates a relatively short (often fixed-size) string of bytes, called the signature, with the following properties:
  • Only the owner of a private/public key pair is able to create a signature. It should be computationally infeasible for anyone having a public key to recover the private key.
  • Given the public key corresponding to the private key used to generate the signature, it should be possible to verify the authenticity and integrity of the input.
  • The signature and the public key do not reveal anything about the private key.
It can also be used to verify whether or not an alleged signature is in fact the authentic signature of the data associated with it. <Image of Signature Operation>

A Signature object is initialized for signing with a Private Key and is given the data to be signed. The resulting signature bytes are typically kept with the signed data. When verification is needed, another Signature object is created and initialized for verification and given the corresponding Public Key. The data and the signature bytes are fed to the signature object, and if the data and signature match, the Signature object reports success.

Even though a signature seems similar to a message digest, they have very different purposes in the type of protection they provide. In fact, algorithms such as "SHA1WithRSA" use the message digest "SHA1" to initially "compress" the large data sets into a more manageable form, then sign the resulting 20 byte message digest with the "RSA" algorithm.

Please see the Examples section for an example of signing and verifying data.

Signature Object States

Signature objects are modal objects. This means that a Signature object is always in a given state, where it may only do one type of operation. States are represented as final integer constants defined in their respective classes.

The three states a Signature object may have are:

  • UNINITIALIZED
  • SIGN
  • VERIFY
When it is first created, a Signature object is in the UNINITIALIZED state. The Signature class defines two initialization methods, initSign and initVerify, which change the state to SIGN and VERIFY, respectively.

Creating a Signature Object

The first step for signing or verifying a signature is to create a Signature instance. Signature objects are obtained by using one of the Signature getInstance() static factory methods.

Initializing a Signature Object

A Signature object must be initialized before it is used. The initialization method depends on whether the object is going to be used for signing or for verification.

If it is going to be used for signing, the object must first be initialized with the private key of the entity whose signature is going to be generated. This initialization is done by calling the method:

final void initSign(PrivateKey privateKey)
This method puts the Signature object in the SIGN state.

If instead the Signature object is going to be used for verification, it must first be initialized with the public key of the entity whose signature is going to be verified. This initialization is done by calling either of these methods:

    final void initVerify(PublicKey publicKey)

    final void initVerify(Certificate certificate)

This method puts the Signature object in the VERIFY state.

Signing

If the Signature object has been initialized for signing (if it is in the SIGN state), the data to be signed can then be supplied to the object. This is done by making one or more calls to one of the update methods:

final void update(byte b)
final void update(byte[] data)
final void update(byte[] data, int off, int len)

Calls to the update method(s) should be made until all the data to be signed has been supplied to the Signature object.

To generate the signature, simply call one of the sign methods:

final byte[] sign()
final int sign(byte[] outbuf, int offset, int len)

The first method returns the signature result in a byte array. The second stores the signature result in the provided buffer outbuf, starting at offset. len is the number of bytes in outbuf allotted for the signature. The method returns the number of bytes actually stored.

Signature encoding is algorithm specific. See the Standard Names document for more information about the use of ASN.1 encoding in the Java Cryptography Architecture.

A call to a sign method resets the signature object to the state it was in when previously initialized for signing via a call to initSign. That is, the object is reset and available to generate another signature with the same private key, if desired, via new calls to update and sign.

Alternatively, a new call can be made to initSign specifying a different private key, or to initVerify (to initialize the Signature object to verify a signature).

Verifying

If the Signature object has been initialized for verification (if it is in the VERIFY state), it can then verify if an alleged signature is in fact the authentic signature of the data associated with it. To start the process, the data to be verified (as opposed to the signature itself) is supplied to the object. The data is passed to the object by calling one of the update methods:

final void update(byte b)
final void update(byte[] data)
final void update(byte[] data, int off, int len)

Calls to the update method(s) should be made until all the data to be verified has been supplied to the Signature object. The signature can now be verified by calling one of the verify methods:

final boolean verify(byte[] signature)

final boolean verify(byte[] signature, int offset, int length)

The argument must be a byte array containing the signature. The argument must be a byte array containing the signature. This byte array would hold the signature bytes which were returned by a previous call to one of the sign methods.

The verify method returns a boolean indicating whether or not the encoded signature is the authentic signature of the data supplied to the update method(s).

A call to the verify method resets the signature object to its state when it was initialized for verification via a call to initVerify. That is, the object is reset and available to verify another signature from the identity whose public key was specified in the call to initVerify.

Alternatively, a new call can be made to initVerify specifying a different public key (to initialize the Signature object for verifying a signature from a different entity), or to initSign (to initialize the Signature object for generating a signature).

The Cipher Class

The Cipher class provides the functionality of a cryptographic cipher used for encryption and decryption. Encryption is the process of taking data (called cleartext) and a key, and producing data (ciphertext) meaningless to a third-party who does not know the key. Decryption is the inverse process: that of taking ciphertext and a key and producing cleartext.

<Image of Cipher operation>

Symmetric vs. Asymmetric Cryptography

There are two major types of encryption: symmetric (also known as secret key), and asymmetric (or public key cryptography). In symmetric cryptography, the same secret key to both encrypt and decrypt the data. Keeping the key private is critical to keeping the data confidential. On the other hand, asymmetric cryptography uses a public/private key pair to encrypt data. Data encrypted with one key is decrypted with the other. A user first generates a public/private key pair, and then publishes the public key in a trusted database that anyone can access. A user who wishes to communicate securely with that user encrypts the data using the retrieved public key. Only the holder of the private key will be able to decrypt. Keeping the private key confidential is critical to this scheme.

Asymmetric algorithms (such as RSA) are generally much slower than symmetric ones. These algorithms are not designed for efficiently protecting large amounts of data. In practice, asymmetric algorithms are used to exchange smaller secret keys which are used to initialize symmetric algorithms.

Stream vs. Block Ciphers

There are two major types of ciphers: block and stream. Block ciphers process entire blocks at a time, usually many bytes in length. If there is not enough data to make a complete input block, the data must be padded: that is, before encryption, dummy bytes must be added to make a multiple of the cipher's block size. These bytes are then stripped off during the decryption phase. The padding can either be done by the application, or by initializing a cipher to use a padding type such as "PKCS5PADDING". In contrast, stream ciphers process incoming data one small unit (typically a byte or even a bit) at a time. This allows for ciphers to process an arbitrary amount of data without padding.

Modes Of Operation

When encrypting using a simple block cipher, two identical blocks of plaintext will always produce an identical block of cipher text. Cryptanalysts trying to break the ciphertext will have an easier job if they note blocks of repeating text. In order to add more complexity to the text, feedback modes use the previous block of output to alter the input blocks before applying the encryption algorithm. The first block will need an initial value, and this value is called the initialization vector (IV). Since the IV simply alters the data before any encryption, the IV should be random but does not necessarily need to be kept secret. There are a variety of modes, such as CBC (Cipher Block Chaining), CFB (Cipher Feedback Mode), and OFB (Output Feedback Mode). ECB (Electronic Cookbook Mode) is a mode with no feedback.

Some algorithms such as AES and RSA allow for keys of different lengths, but others are fixed, such as DES and 3DES. Encryption using a longer key generally implies a stronger resistance to message recovery. As usual, there is a trade off between security and time, so choose the key length appropriately.

Most algorithms use binary keys. Most humans do not have the ability to remember long sequences of binary numbers, even when represented in hexadecimal. Character passwords are much easier to recall. Because character passwords are generally chosen from a small number of characters (for example, [a-zA-Z0-9]), protocols such as "Password-Based Encryption" (PBE) have been defined which take character passwords and generate strong binary keys. In order to make the task of getting from password to key very time-consuming for an attacker (via so-called "dictionary attacks" where common dictionary word->value mappings are precomputed), most PBE implementations will mix in a random number, known as a salt, to increase the key randomness.

Creating a Cipher Object

Cipher objects are obtained by using one of the Cipher getInstance() static factory methods. Here, the algorithm name is slightly different than with other engine classes, in that it specifies not just an algorithm name, but a "transformation". A transformation is a string that describes the operation (or set of operations) to be performed on the given input to produce some output. A transformation always includes the name of a cryptographic algorithm (e.g., DES), and may be followed by a mode and padding scheme.

A transformation is of the form:

  • "algorithm/mode/padding" or
  • "algorithm"

For example, the following are valid transformations:

    "DES/CBC/PKCS5Padding"

    "DES"

If just a transformation name is specified, the system will determine if there is an implementation of the requested transformation available in the environment, and if there is more than one, returns there is a preferred one.

If both a transformation name and a package provider are specified, the system will determine if there is an implementation of the requested transformation in the package requested, and throw an exception if there is not.

If no mode or padding is specified, provider-specific default values for the mode and padding scheme are used. For example, the SunJCE provider uses ECB as the default mode, and PKCS5Padding as the default padding scheme for DES, DES-EDE and Blowfish ciphers. This means that in the case of the SunJCE provider:

    Cipher c1 = Cipher.getInstance("DES/ECB/PKCS5Padding");
and
    Cipher c1 = Cipher.getInstance("DES");
are equivalent statements.

Using modes such as CFB and OFB, block ciphers can encrypt data in units smaller than the cipher's actual block size. When requesting such a mode, you may optionally specify the number of bits to be processed at a time by appending this number to the mode name as shown in the "DES/CFB8/NoPadding" and "DES/OFB32/PKCS5Padding" transformations. If no such number is specified, a provider-specific default is used. (For example, the SunJCE provider uses a default of 64 bits for DES.) Thus, block ciphers can be turned into byte-oriented stream ciphers by using an 8 bit mode such as CFB8 or OFB8.

Appendix A of this document contains a list of standard names that can be used to specify the algorithm name, mode, and padding scheme components of a transformation.

The objects returned by factory methods are uninitialized, and must be initialized before they become usable.

Initializing a Cipher Object

A Cipher object obtained via getInstance must be initialized for one of four modes, which are defined as final integer constants in the Cipher class. The modes can be referenced by their symbolic names, which are shown below along with a description of the purpose of each mode:

ENCRYPT_MODE
Encryption of data.
DECRYPT_MODE
Decryption of data.
WRAP_MODE
Wrapping a java.security.Key into bytes so that the key can be securely transported.
UNWRAP_MODE
Unwrapping of a previously wrapped key into a java.security.Key object.

Each of the Cipher initialization methods takes an operational mode parameter (opmode), and initializes the Cipher object for that mode. Other parameters include the key (key) or certificate containing the key (certificate), algorithm parameters (params), and a source of randomness (random).

To initialize a Cipher object, call one of the following init methods:

    public void init(int opmode, Key key);

    public void init(int opmode, Certificate certificate);

    public void init(int opmode, Key key, SecureRandom random);

    public void init(int opmode, Certificate certificate,
                     SecureRandom random);

    public void init(int opmode, Key key,
                     AlgorithmParameterSpec params);

    public void init(int opmode, Key key,
                     AlgorithmParameterSpec params, SecureRandom random);

    public void init(int opmode, Key key,
                     AlgorithmParameters params);

    public void init(int opmode, Key key,
                     AlgorithmParameters params, SecureRandom random);

If a Cipher object that requires parameters (e.g., an initialization vector) is initialized for encryption, and no parameters are supplied to the init method, the underlying cipher implementation is supposed to supply the required parameters itself, either by generating random parameters or by using a default, provider-specific set of parameters.

However, if a Cipher object that requires parameters is initialized for decryption, and no parameters are supplied to the init method, an InvalidKeyException or InvalidAlgorithmParameterException exception will be raised, depending on the init method that has been used.

See the section about Managing Algorithm Parameters for more details.

The same parameters that were used for encryption must be used for decryption.

Note that when a Cipher object is initialized, it loses all previously-acquired state. In other words, initializing a Cipher is equivalent to creating a new instance of that Cipher, and initializing it. For example, if a Cipher is first initialized for decryption with a given key, and then initialized for encryption, it will lose any state acquired while in decryption mode.

Encrypting and Decrypting Data

Data can be encrypted or decrypted in one step (single-part operation) or in multiple steps (multiple-part operation). A multiple-part operation is useful if you do not know in advance how long the data is going to be, or if the data is too long to be stored in memory all at once.

To encrypt or decrypt data in a single step, call one of the doFinal methods:

    public byte[] doFinal(byte[] input);

    public byte[] doFinal(byte[] input, int inputOffset, int inputLen);

    public int doFinal(byte[] input, int inputOffset,
                       int inputLen, byte[] output);

    public int doFinal(byte[] input, int inputOffset,
                       int inputLen, byte[] output, int outputOffset)

To encrypt or decrypt data in multiple steps, call one of the update methods:

    public byte[] update(byte[] input);

    public byte[] update(byte[] input, int inputOffset, int inputLen);

    public int update(byte[] input, int inputOffset, int inputLen,
                      byte[] output);

    public int update(byte[] input, int inputOffset, int inputLen,
                      byte[] output, int outputOffset)

A multiple-part operation must be terminated by one of the above doFinal methods (if there is still some input data left for the last step), or by one of the following doFinal methods (if there is no input data left for the last step):

    public byte[] doFinal();

    public int doFinal(byte[] output, int outputOffset);

All the doFinal methods take care of any necessary padding (or unpadding), if padding (or unpadding) has been requested as part of the specified transformation.

A call to doFinal resets the Cipher object to the state it was in when initialized via a call to init. That is, the Cipher object is reset and available to encrypt or decrypt (depending on the operation mode that was specified in the call to init) more data.

Wrapping and Unwrapping Keys

Wrapping a key enables secure transfer of the key from one place to another.

The wrap/unwrap API makes it more convenient to write code since it works with key objects directly. These methods also enable the possibility of secure transfer of hardware-based keys.

To wrap a Key, first initialize the Cipher object for WRAP_MODE, and then call the following:

    public final byte[] wrap(Key key);

If you are supplying the wrapped key bytes (the result of calling wrap) to someone else who will unwrap them, be sure to also send additional information the recipient will need in order to do the unwrap:

  1. the name of the key algorithm, and
  2. the type of the wrapped key (one of Cipher.SECRET_KEY, Cipher.PRIVATE_KEY, or Cipher.PUBLIC_KEY).

The key algorithm name can be determined by calling the getAlgorithm method from the Key interface:

    public String getAlgorithm();

To unwrap the bytes returned by a previous call to wrap, first initialize a Cipher object for UNWRAP_MODE, then call the following:

    public final Key unwrap(byte[] wrappedKey,
                            String wrappedKeyAlgorithm,
                            int wrappedKeyType));

Here, wrappedKey is the bytes returned from the previous call to wrap, wrappedKeyAlgorithm is the algorithm associated with the wrapped key, and wrappedKeyType is the type of the wrapped key. This must be one of Cipher.SECRET_KEY, Cipher.PRIVATE_KEY, or Cipher.PUBLIC_KEY.

Managing Algorithm Parameters

The parameters being used by the underlying Cipher implementation, which were either explicitly passed to the init method by the application or generated by the underlying implementation itself, can be retrieved from the Cipher object by calling its getParameters method, which returns the parameters as a java.security.AlgorithmParameters object (or null if no parameters are being used). If the parameter is an initialization vector (IV), it can also be retrieved by calling the getIV method.

In the following example, a Cipher object implementing password-based encryption (PBE) is initialized with just a key and no parameters. However, the selected algorithm for password-based encryption requires two parameters - a salt and an iteration count. Those will be generated by the underlying algorithm implementation itself. The application can retrieve the generated parameters from the Cipher object as follows:

    import javax.crypto.*;
    import java.security.AlgorithmParameters;

    // get cipher object for password-based encryption
    Cipher c = Cipher.getInstance("PBEWithMD5AndDES");

    // initialize cipher for encryption, without supplying
    // any parameters. Here, "myKey" is assumed to refer
    // to an already-generated key.
    c.init(Cipher.ENCRYPT_MODE, myKey);

    // encrypt some data and store away ciphertext
    // for later decryption
    byte[] cipherText = c.doFinal("This is just an example".getBytes());

    // retrieve parameters generated by underlying cipher
    // implementation
    AlgorithmParameters algParams = c.getParameters();

    // get parameter encoding and store it away
    byte[] encodedAlgParams = algParams.getEncoded();

The same parameters that were used for encryption must be used for decryption. They can be instantiated from their encoding and used to initialize the corresponding Cipher object for decryption, as follows:

    import javax.crypto.*;
    import java.security.AlgorithmParameters;

    // get parameter object for password-based encryption
    AlgorithmParameters algParams;
    algParams = AlgorithmParameters.getInstance("PBEWithMD5AndDES");

    // initialize with parameter encoding from above
    algParams.init(encodedAlgParams);

    // get cipher object for password-based encryption
    Cipher c = Cipher.getInstance("PBEWithMD5AndDES");

    // initialize cipher for decryption, using one of the
    // init() methods that takes an AlgorithmParameters
    // object, and pass it the algParams object from above
    c.init(Cipher.DECRYPT_MODE, myKey, algParams);

If you did not specify any parameters when you initialized a Cipher object, and you are not sure whether or not the underlying implementation uses any parameters, you can find out by simply calling the getParameters method of your Cipher object and checking the value returned. A return value of null indicates that no parameters were used.

The following cipher algorithms implemented by the SunJCE provider use parameters:

  • DES, DES-EDE, and Blowfish, when used in feedback (i.e., CBC, CFB, OFB, or PCBC) mode, use an initialization vector (IV). The javax.crypto.spec.IvParameterSpec class can be used to initialize a Cipher object with a given IV.
  • PBEWithMD5AndDES uses a set of parameters, comprising a salt and an iteration count. The javax.crypto.spec.PBEParameterSpec class can be used to initialize a Cipher object implementing PBEWithMD5AndDES with a given salt and iteration count.

Note that you do not have to worry about storing or transferring any algorithm parameters for use by the decryption operation if you use the SealedObject class. This class attaches the parameters used for sealing (encryption) to the encrypted object contents, and uses the same parameters for unsealing (decryption).

Cipher Output Considerations

Some of the update and doFinal methods of Cipher allow the caller to specify the output buffer into which to encrypt or decrypt the data. In these cases, it is important to pass a buffer that is large enough to hold the result of the encryption or decryption operation.

The following method in Cipher can be used to determine how big the output buffer should be:

    public int getOutputSize(int inputLen)

Other Cipher-based Classes

There are some helper classes which interally use Ciphers to provide easy access to common cipher uses.

The Cipher Stream Classes

The CipherInputStream Class

This class is a FilterInputStream that encrypts or decrypts the data passing through it. It is composed of an InputStream, or one of its subclasses, and a Cipher. CipherInputStream represents a secure input stream into which a Cipher object has been interposed. The read methods of CipherInputStream return data that are read from the underlying InputStream but have additionally been processed by the embedded Cipher object. The Cipher object must be fully initialized before being used by a CipherInputStream.

For example, if the embedded Cipher has been initialized for decryption, the CipherInputStream will attempt to decrypt the data it reads from the underlying InputStream before returning them to the application.

This class adheres strictly to the semantics, especially the failure semantics, of its ancestor classes java.io.FilterInputStream and java.io.InputStream. This class has exactly those methods specified in its ancestor classes, and overrides them all, so that the data are additionally processed by the embedded cipher. Moreover, this class catches all exceptions that are not thrown by its ancestor classes. In particular, the skip(long) method skips only data that has been processed by the Cipher.

It is crucial for a programmer using this class not to use methods that are not defined or overridden in this class (such as a new method or constructor that is later added to one of the super classes), because the design and implementation of those methods are unlikely to have considered security impact with regard to CipherInputStream.

As an example of its usage, suppose cipher1 has been initialized for encryption. The code below demonstrates how to use a CipherInputStream containing that cipher and a FileInputStream in order to encrypt input stream data:

    FileInputStream fis;
    FileOutputStream fos;
    CipherInputStream cis;

    fis = new FileInputStream("/tmp/a.txt");
    cis = new CipherInputStream(fis, cipher1);
    fos = new FileOutputStream("/tmp/b.txt");
    byte[] b = new byte[8];
    int i = cis.read(b);
    while (i != -1) {
        fos.write(b, 0, i);
        i = cis.read(b);
    }
    fos.close();

The above program reads and encrypts the content from the file /tmp/a.txt and then stores the result (the encrypted bytes) in /tmp/b.txt.

The following example demonstrates how to easily connect several instances of CipherInputStream and FileInputStream. In this example, assume that cipher1 and cipher2 have been initialized for encryption and decryption (with corresponding keys), respectively.

    FileInputStream fis;
    FileOutputStream fos;
    CipherInputStream cis1, cis2;

    fis = new FileInputStream("/tmp/a.txt");
    cis1 = new CipherInputStream(fis, cipher1);
    cis2 = new CipherInputStream(cis1, cipher2);
    fos = new FileOutputStream("/tmp/b.txt");
    byte[] b = new byte[8];
    int i = cis2.read(b);
    while (i != -1) {
        fos.write(b, 0, i);
        i = cis2.read(b);
    }
    fos.close();

The above program copies the content from file /tmp/a.txt to /tmp/b.txt, except that the content is first encrypted and then decrypted back when it is read from /tmp/a.txt. Of course since this program simply encrypts text and decrypts it back right away, it's actually not very useful except as a simple way of illustrating chaining of CipherInputStreams.

Note that the read methods of the CipherInputStream will block until data is returned from the underlying cipher. If a block cipher is used, a full block of cipher text will have to be obtained from the underlying InputStream.

The CipherOutputStream Class

This class is a FilterOutputStream that encrypts or decrypts the data passing through it. It is composed of an OutputStream, or one of its subclasses, and a Cipher. CipherOutputStream represents a secure output stream into which a Cipher object has been interposed. The write methods of CipherOutputStream first process the data with the embedded Cipher object before writing them out to the underlying OutputStream. The Cipher object must be fully initialized before being used by a CipherOutputStream.

For example, if the embedded Cipher has been initialized for encryption, the CipherOutputStream will encrypt its data, before writing them out to the underlying output stream.

This class adheres strictly to the semantics, especially the failure semantics, of its ancestor classes java.io.OutputStream and java.io.FilterOutputStream. This class has exactly those methods specified in its ancestor classes, and overrides them all, so that all data are additionally processed by the embedded cipher. Moreover, this class catches all exceptions that are not thrown by its ancestor classes.

It is crucial for a programmer using this class not to use methods that are not defined or overridden in this class (such as a new method or constructor that is later added to one of the super classes), because the design and implementation of those methods are unlikely to have considered security impact with regard to CipherOutputStream.

As an example of its usage, suppose cipher1 has been initialized for encryption. The code below demonstrates how to use a CipherOutputStream containing that cipher and a FileOutputStream in order to encrypt data to be written to an output stream:

    FileInputStream fis;
    FileOutputStream fos;
    CipherOutputStream cos;

    fis = new FileInputStream("/tmp/a.txt");
    fos = new FileOutputStream("/tmp/b.txt");
    cos = new CipherOutputStream(fos, cipher1);
    byte[] b = new byte[8];
    int i = fis.read(b);
    while (i != -1) {
        cos.write(b, 0, i);
        i = fis.read(b);
    }
    cos.flush();

The above program reads the content from the file /tmp/a.txt, then encrypts and stores the result (the encrypted bytes) in /tmp/b.txt.

The following example demonstrates how to easily connect several instances of CipherOutputStream and FileOutputStream. In this example, assume that cipher1 and cipher2 have been initialized for decryption and encryption (with corresponding keys), respectively:

    FileInputStream fis;
    FileOutputStream fos;
    CipherOutputStream cos1, cos2;

    fis = new FileInputStream("/tmp/a.txt");
    fos = new FileOutputStream("/tmp/b.txt");
    cos1 = new CipherOutputStream(fos, cipher1);
    cos2 = new CipherOutputStream(cos1, cipher2);
    byte[] b = new byte[8];
    int i = fis.read(b);
    while (i != -1) {
        cos2.write(b, 0, i);
        i = fis.read(b);
    }
    cos2.flush();

The above program copies the content from file /tmp/a.txt to /tmp/b.txt, except that the content is first encrypted and then decrypted back before it is written to /tmp/b.txt.

One thing to keep in mind when using block cipher algorithms is that a full block of plaintext data must be given to the CipherOutputStream before the data will be encrypted and sent to the underlying output stream.

There is one other important difference between the flush and close methods of this class, which becomes even more relevant if the encapsulated Cipher object implements a block cipher algorithm with padding turned on:

  • flush flushes the underlying OutputStream by forcing any buffered output bytes that have already been processed by the encapsulated Cipher object to be written out. Any bytes buffered by the encapsulated Cipher object and waiting to be processed by it will not be written out.
  • close closes the underlying OutputStream and releases any system resources associated with it. It invokes the doFinal method of the encapsulated Cipher object, causing any bytes buffered by it to be processed and written out to the underlying stream by calling its flush method.

The SealedObject Class

This class enables a programmer to create an object and protect its confidentiality with a cryptographic algorithm.

Given any object that implements the java.io.Serializable interface, one can create a SealedObject that encapsulates the original object, in serialized format (i.e., a "deep copy"), and seals (encrypts) its serialized contents, using a cryptographic algorithm such as DES, to protect its confidentiality. The encrypted content can later be decrypted (with the corresponding algorithm using the correct decryption key) and de-serialized, yielding the original object.

A typical usage is illustrated in the following code segment: In order to seal an object, you create a SealedObject from the object to be sealed and a fully initialized Cipher object that will encrypt the serialized object contents. In this example, the String "This is a secret" is sealed using the DES algorithm. Note that any algorithm parameters that may be used in the sealing operation are stored inside of SealedObject:

    // create Cipher object
    // NOTE: sKey is assumed to refer to an already-generated
    // secret DES key.
    Cipher c = Cipher.getInstance("DES");
    c.init(Cipher.ENCRYPT_MODE, sKey);

    // do the sealing
    SealedObject so = new SealedObject("This is a secret", c);

The original object that was sealed can be recovered in two different ways:

  • by using a Cipher object that has been initialized with the exact same algorithm, key, padding scheme, etc., that were used to seal the object:
        c.init(Cipher.DECRYPT_MODE, sKey);
    try {
        String s = (String)so.getObject(c);
    } catch (Exception e) {
        // do something
    };

    This approach has the advantage that the party who unseals the sealed object does not require knowledge of the decryption key. For example, after one party has initialized the cipher object with the required decryption key, it could hand over the cipher object to another party who then unseals the sealed object.

  • by using the appropriate decryption key (since DES is a symmetric encryption algorithm, we use the same key for sealing and unsealing):
        try {
        String s = (String)so.getObject(sKey);
    } catch (Exception e) {
        // do something
    };

    In this approach, the getObject method creates a cipher object for the appropriate decryption algorithm and initializes it with the given decryption key and the algorithm parameters (if any) that were stored in the sealed object. This approach has the advantage that the party who unseals the object does not need to keep track of the parameters (e.g., the IV) that were used to seal the object.

The Mac Class

Similar to a MessageDigest, a Message Authentication Code (MAC) provides a way to check the integrity of information transmitted over or stored in an unreliable medium, but includes a secret key in the calculation. Only someone with the proper key will be able to verify the received message. Typically, message authentication codes are used between two parties that share a secret key in order to validate information transmitted between these parties.

<Image of Mac operation>

A MAC mechanism that is based on cryptographic hash functions is referred to as HMAC. HMAC can be used with any cryptographic hash function, e.g., MD5 or SHA-1, in combination with a secret shared key.

The Mac class provides the functionality of a Message Authentication Code (MAC). Please refer to the code example.

Creating a Mac Object

Mac objects are obtained by using one of the Mac getInstance() static factory methods.

Initializing a Mac Object

A Mac object is always initialized with a (secret) key and may optionally be initialized with a set of parameters, depending on the underlying MAC algorithm.

To initialize a Mac object, call one of its init methods:

    public void init(Key key);

    public void init(Key key, AlgorithmParameterSpec params);

You can initialize your Mac object with any (secret-)key object that implements the javax.crypto.SecretKey interface. This could be an object returned by javax.crypto.KeyGenerator.generateKey(), or one that is the result of a key agreement protocol, as returned by javax.crypto.KeyAgreement.generateSecret(), or an instance of javax.crypto.spec.SecretKeySpec.

With some MAC algorithms, the (secret-)key algorithm associated with the (secret-)key object used to initialize the Mac object does not matter (this is the case with the HMAC-MD5 and HMAC-SHA1 implementations of the SunJCE provider). With others, however, the (secret-)key algorithm does matter, and an InvalidKeyException is thrown if a (secret-)key object with an inappropriate (secret-)key algorithm is used.

Computing a MAC

A MAC can be computed in one step (single-part operation) or in multiple steps (multiple-part operation). A multiple-part operation is useful if you do not know in advance how long the data is going to be, or if the data is too long to be stored in memory all at once.

To compute the MAC of some data in a single step, call the following doFinal method:

    public byte[] doFinal(byte[] input);

To compute the MAC of some data in multiple steps, call one of the update methods:

    public void update(byte input);

    public void update(byte[] input);

    public void update(byte[] input, int inputOffset, int inputLen);

A multiple-part operation must be terminated by the above doFinal method (if there is still some input data left for the last step), or by one of the following doFinal methods (if there is no input data left for the last step):

    public byte[] doFinal();

    public void doFinal(byte[] output, int outOffset);

Key Interfaces

To this point, we have focused the high-level uses of the JCA without getting lost in the details of what keys are and how they are generated/represented. It is now time to turn our attention to keys.

The java.security.Key interface is the top-level interface for all opaque keys. It defines the functionality shared by all opaque key objects.

An opaque key representation is one in which you have no direct access to the key material that constitutes a key. In other words: "opaque" gives you limited access to the key--just the three methods defined by the Key interface (see below): getAlgorithm, getFormat, and getEncoded.

This is in contrast to a transparent representation, in which you can access each key material value individually, through one of the get methods defined in the corresponding specification class.

All opaque keys have three characteristics:

An Algorithm
The key algorithm for that key. The key algorithm is usually an encryption or asymmetric operation algorithm (such as AES, DSA or RSA), which will work with those algorithms and with related algorithms (such as MD5withRSA, SHA1withRSA, etc.) The name of the algorithm of a key is obtained using this method:
String getAlgorithm()
An Encoded Form
The external encoded form for the key used when a standard representation of the key is needed outside the Java Virtual Machine, as when transmitting the key to some other party. The key is encoded according to a standard format (such as X.509 or PKCS8), and is returned using the method:
byte[] getEncoded()
A Format
The name of the format of the encoded key. It is returned by the method:
String getFormat()
Keys are generally obtained through key generators such as KeyGenerator and KeyPairGenerator, certificates, key specifications (using a KeyFactory), or a KeyStore implementation accessing a keystore database used to manage keys. It is possible to parse encoded keys, in an algorithm-dependent manner, using a KeyFactory.

It is also possible to parse certificates, using a CertificateFactory.

Here is a list of interfaces which extend the Key interface in the java.security.interfaces and javax.crypto.interfaces packages:

  • SecretKey
  • PBEKey
  • PrivateKey
  • DHPrivateKey
  • DSAPrivateKey
  • ECPrivateKey
  • RSAMultiPrimePrivateCrtKey
  • RSAPrivateCrtKey
  • RSAPrivateKey
  • PublicKey
  • DHPublicKey
  • DSAPublicKey
  • ECPublicKey
  • RSAPublicKey

The PublicKey and PrivateKey Interfaces

The PublicKey and PrivateKey interfaces (which both extend the Key interface) are methodless interfaces, used for type-safety and type-identification.

The KeyPair Class

The KeyPair class is a simple holder for a key pair (a public key and a private key). It has two public methods, one for returning the private key, and the other for returning the public key:

PrivateKey getPrivate()
PublicKey getPublic()

Key Specification Interfaces and Classes

Key objects and key specifications (KeySpecs) are two different representations of key data. Ciphers use Key objects to initialize their encryption algorithms, but keys may need to be converted into a more portable format for transmission or storage.

A transparent representation of keys means that you can access each key material value individually, through one of the get methods defined in the corresponding specification class. For example, DSAPrivateKeySpec defines getX, getP, getQ, and getG methods, to access the private key x, and the DSA algorithm parameters used to calculate the key: the prime p, the sub-prime q, and the base g. If the key is stored on a hardware device, its specification may contain information that helps identify the key on the device.

This representation is contrasted with an opaque representation, as defined by the Key interface, in which you have no direct access to the key material fields. In other words, an "opaque" representation gives you limited access to the key--just the three methods defined by the Key interface: getAlgorithm, getFormat, and getEncoded.

A key may be specified in an algorithm-specific way, or in an algorithm-independent encoding format (such as ASN.1). For example, a DSA private key may be specified by its components x, p, q, and g (see DSAPrivateKeySpec), or it may be specified using its DER encoding (see PKCS8EncodedKeySpec).

The KeyFactory and SecretKeyFactory classes can be used to convert between opaque and transparent key representations (that is, between Keys and KeySpecs, assuming that the operation is possible. (For example, private keys on smart cards might not be able leave the card. Such Keys are not convertible.)

In the following sections, we discuss the key specification interfaces and classes in the java.security.spec package.

The KeySpec Interface

This interface contains no methods or constants. Its only purpose is to group and provide type safety for all key specifications. All key specifications must implement this interface.

The KeySpec Subinterfaces

Like the Key interface, there are a similar set of KeySpec interfaces.
  • SecretKeySpec
  • EncodedKeySpec
  • PKCS8EncodedKeySpec
  • X509EncodedKeySpec

  • DESKeySpec
  • DESedeKeySpec
  • PBEKeySpec
  • DHPrivateKeySpec
  • DSAPrivateKeySpec
  • ECPrivateKeySpec
  • RSAMultiPrimePrivateCrtKeySpec
  • RSAPrivateCrtKeySpec
  • RSAPrivateKeySpec
  • DHPublicKeySpec
  • DSAPublicKeySpec
  • ECPublicKeySpec
  • RSAPublicKeySpec

The EncodedKeySpec Class

This abstract class (which implements the KeySpec interface) represents a public or private key in encoded format. Its getEncoded method returns the encoded key:
abstract byte[] getEncoded();
and its getFormat method returns the name of the encoding format:
abstract String getFormat();

See the next sections for the concrete implementations PKCS8EncodedKeySpec and X509EncodedKeySpec.

The PKCS8EncodedKeySpec Class

This class, which is a subclass of EncodedKeySpec, represents the DER encoding of a private key, according to the format specified in the PKCS8 standard. Its getEncoded method returns the key bytes, encoded according to the PKCS8 standard. Its getFormat method returns the string "PKCS#8".

The X509EncodedKeySpec Class

This class, which is a subclass of EncodedKeySpec, represents the DER encoding of a public key, according to the format specified in the X.509 standard. Its getEncoded method returns the key bytes, encoded according to the X.509 standard. Its getFormat method returns the string "X.509".

Of Generators and Factories

Newcomers to Java and the JCA APIs in particular sometimes do not grasp the distinction between generators and factories. <Image of the Comparison Between Generators and Factories>

Generators are used to generate brand new objects. Generators can be initialized in either an algorithm-dependent or algorithm-independent way. For example, to create a Diffie-Hellman (DH) keypair, an application could specify the necessary P and G values, or the generator could simply be initialized with the appropriate key length, and the generator will select appropriate P and G values. In both cases, the generator will produce brand new keys based on the parameters.

On the other hand, factories are used to convert data from one existing object type to another. For example, an application might have available the components of a DH private key and can package them as a KeySpec, but needs to convert them into a PrivateKey object that can be used by a KeyAgreement object, or vice-versa. Or they might have the byte array of a certificate, but need to use a CertificateFactory to convert it into a X509Certificate object. Applications use factory objects to do the conversion.

The KeyFactory Class

The KeyFactory class is an engine class designed to perform conversions between opaque cryptographic Keys and key specifications (transparent representations of the underlying key material). <Image of KeyFactory operation>

Key factories are bi-directional. They allow you to build an opaque key object from a given key specification (key material), or to retrieve the underlying key material of a key object in a suitable format.

Multiple compatible key specifications can exist for the same key. For example, a DSA public key may be specified by its components y, p, q, and g (see java.security.spec.DSAPublicKeySpec), or it may be specified using its DER encoding according to the X.509 standard (see X509EncodedKeySpec).

A key factory can be used to translate between compatible key specifications. Key parsing can be achieved through translation between compatible key specifications, e.g., when you translate from X509EncodedKeySpec to DSAPublicKeySpec, you basically parse the encoded key into its components. For an example, see the end of the Generating/Verifying Signatures Using Key Specifications and KeyFactory section.

Creating a KeyFactory Object

KeyFactory objects are obtained by using one of the KeyFactory getInstance() static factory methods.

Converting Between a Key Specification and a Key Object

If you have a key specification for a public key, you can obtain an opaque PublicKey object from the specification by using the generatePublic method:

PublicKey generatePublic(KeySpec keySpec)

Similarly, if you have a key specification for a private key, you can obtain an opaque PrivateKey object from the specification by using the generatePrivate method:

PrivateKey generatePrivate(KeySpec keySpec)

Converting Between a Key Object and a Key Specification

If you have a Key object, you can get a corresponding key specification object by calling the getKeySpec method:

KeySpec getKeySpec(Key key, Class keySpec)
keySpec identifies the specification class in which the key material should be returned. It could, for example, be DSAPublicKeySpec.class, to indicate that the key material should be returned in an instance of the DSAPublicKeySpec class.

Please see the Examples section for more details.

The SecretKeyFactory Class

This class represents a factory for secret keys. Unlike KeyFactory, a javax.crypto.SecretKeyFactory object operates only on secret (symmetric) keys, whereas a java.security.KeyFactory object processes the public and private key components of a key pair.

<Image of SecretKeyFactory operation>

Key factories are used to convert Keys (opaque cryptographic keys of type java.security.Key) into key specifications (transparent representations of the underlying key material in a suitable format), and vice versa.

Objects of type java.security.Key, of which java.security.PublicKey, java.security.PrivateKey, and javax.crypto.SecretKey are subclasses, are opaque key objects, because you cannot tell how they are implemented. The underlying implementation is provider-dependent, and may be software or hardware based. Key factories allow providers to supply their own implementations of cryptographic keys.

For example, if you have a key specification for a Diffie Hellman public key, consisting of the public value y, the prime modulus p, and the base g, and you feed the same specification to Diffie-Hellman key factories from different providers, the resulting PublicKey objects will most likely have different underlying implementations.

A provider should document the key specifications supported by its secret key factory. For example, the SecretKeyFactory for DES keys supplied by the SunJCE provider supports DESKeySpec as a transparent representation of DES keys, the SecretKeyFactory for DES-EDE keys supports DESedeKeySpec as a transparent representation of DES-EDE keys, and the SecretKeyFactory for PBE supports PBEKeySpec as a transparent representation of the underlying password.

The following is an example of how to use a SecretKeyFactory to convert secret key data into a SecretKey object, which can be used for a subsequent Cipher operation:

    // Note the following bytes are not realistic secret key data
    // bytes but are simply supplied as an illustration of using data
    // bytes (key material) you already have to build a DESKeySpec.
    byte[] desKeyData = { (byte)0x01, (byte)0x02, (byte)0x03,
    (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08 };
    DESKeySpec desKeySpec = new DESKeySpec(desKeyData);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

In this case, the underlying implementation of SecretKey is based on the provider of KeyFactory.

An alternative, provider-independent way of creating a functionally equivalent SecretKey object from the same key material is to use the javax.crypto.spec.SecretKeySpec class, which implements the javax.crypto.SecretKey interface:

    byte[] desKeyData = { (byte)0x01, (byte)0x02, ...};
    SecretKeySpec secretKey = new SecretKeySpec(desKeyData, "DES");

Creating a SecretKeyFactory Object

SecretKeyFactory objects are obtained by using one of the SecretKeyFactory getInstance() static factory methods.

Converting Between a Key Specification and a Secret Key Object

If you have a key specification for a secret key, you can obtain an opaque SecretKey object from the specification by using the generateSecret method:

SecretKey generateSecret(KeySpec keySpec)

Converting Between a Secret Key Object and a Key Specification

If you have a Secret Key object, you can get a corresponding key specification object by calling the getKeySpec method:

KeySpec getKeySpec(Key key, Class keySpec)
keySpec identifies the specification class in which the key material should be returned. It could, for example, be DESKeySpec.class, to indicate that the key material should be returned in an instance of the DESKeySpec class.

The KeyPairGenerator Class

The KeyPairGenerator class is an engine class used to generate pairs of public and private keys.

<Image of KeyPairGenerator operation>

There are two ways to generate a key pair: in an algorithm-independent manner, and in an algorithm-specific manner. The only difference between the two is the initialization of the object.

Please see the Examples section for examples of calls to the methods documented below.

Creating a KeyPairGenerator

All key pair generation starts with a KeyPairGenerator. KeyPairGenerator objects are obtained by using one of the KeyPairGenerator getInstance() static factory methods.

Initializing a KeyPairGenerator

A key pair generator for a particular algorithm creates a public/private key pair that can be used with this algorithm. It also associates algorithm-specific parameters with each of the generated keys.

A key pair generator needs to be initialized before it can generate keys. In most cases, algorithm-independent initialization is sufficient. But in other cases, algorithm-specific initialization can be used.

Algorithm-Independent Initialization

All key pair generators share the concepts of a keysize and a source of randomness. The keysize is interpreted differently for different algorithms. For example, in the case of the DSA algorithm, the keysize corresponds to the length of the modulus. (See the Standard Names document for information about the keysizes for specific algorithms.)

An initialize method takes two universally shared types of arguments:

void initialize(int keysize, SecureRandom random)
Another initialize method takes only a keysize argument; it uses a system-provided source of randomness:
void initialize(int keysize)

Since no other parameters are specified when you call the above algorithm-independent initialize methods, it is up to the provider what to do about the algorithm-specific parameters (if any) to be associated with each of the keys.

If the algorithm is a "DSA" algorithm, and the modulus size (keysize) is 512, 768, or 1024, then the SUN provider uses a set of precomputed values for the p, q, and g parameters. If the modulus size is not one of the above values, the SUN provider creates a new set of parameters. Other providers might have precomputed parameter sets for more than just the three modulus sizes mentioned above. Still others might not have a list of precomputed parameters at all and instead always create new parameter sets.

Algorithm-Specific Initialization

For situations where a set of algorithm-specific parameters already exists (such as "community parameters" in DSA), there are two initialize methods that have an AlgorithmParameterSpec argument. One also has a SecureRandom argument, while the source of randomness is system-provided for the other:

void initialize(AlgorithmParameterSpec params,
                SecureRandom random)

void initialize(AlgorithmParameterSpec params)
See the Examples section for more details.

Generating a Key Pair

The procedure for generating a key pair is always the same, regardless of initialization (and of the algorithm). You always call the following method from KeyPairGenerator:

KeyPair generateKeyPair()
Multiple calls to generateKeyPair will yield different key pairs.

The KeyGenerator Class

A key generator is used to generate secret keys for symmetric algorithms.

<Image of KeyGenerator operation>

Creating a KeyGenerator

KeyGenerator objects are obtained by using one of the KeyGenerator getInstance() static factory methods.

Initializing a KeyGenerator Object

A key generator for a particular symmetric-key algorithm creates a symmetric key that can be used with that algorithm. It also associates algorithm-specific parameters (if any) with the generated key.

There are two ways to generate a key: in an algorithm-independent manner, and in an algorithm-specific manner. The only difference between the two is the initialization of the object:

  • Algorithm-Independent Initialization

    All key generators share the concepts of a keysize and a source of randomness. There is an init method that takes these two universally shared types of arguments. There is also one that takes just a keysize argument, and uses a system-provided source of randomness, and one that takes just a source of randomness:

    public void init(SecureRandom random);

    public void init(int keysize);

    public void init(int keysize, SecureRandom random);

    Since no other parameters are specified when you call the above algorithm-independent init methods, it is up to the provider what to do about the algorithm-specific parameters (if any) to be associated with the generated key.

  • Algorithm-Specific Initialization

    For situations where a set of algorithm-specific parameters already exists, there are two init methods that have an AlgorithmParameterSpec argument. One also has a SecureRandom argument, while the source of randomness is system-provided for the other:

        public void init(AlgorithmParameterSpec params);

    public void init(AlgorithmParameterSpec params, SecureRandom random);

In case the client does not explicitly initialize the KeyGenerator (via a call to an init method), each provider must supply (and document) a default initialization.

Creating a Key

The following method generates a secret key:
    public SecretKey generateKey();

The KeyAgreement Class

Key agreement is a protocol by which 2 or more parties can establish the same cryptographic keys, without having to exchange any secret information. <Image of KeyAgreement operation>

Each party initializes their key agreement object with their private key, and then enters the public keys for each party that will participate in the communication. In most cases, there are just two parties, but algorithms such as Diffie-Hellman allow for multiple parties (3 or more) to participate. When all the public keys have been entered, each KeyAgreement object will generate (agree upon) the same key.

The KeyAgreement class provides the functionality of a key agreement protocol. The keys involved in establishing a shared secret are created by one of the key generators (KeyPairGenerator or KeyGenerator), a KeyFactory, or as a result from an intermediate phase of the key agreement protocol.

Creating a KeyAgreement Object

Each party involved in the key agreement has to create a KeyAgreement object. KeyAgreement objects are obtained by using one of the KeyAgreement getInstance() static factory methods.

Initializing a KeyAgreement Object

You initialize a KeyAgreement object with your private information. In the case of Diffie-Hellman, you initialize it with your Diffie-Hellman private key. Additional initialization information may contain a source of randomness and/or a set of algorithm parameters. Note that if the requested key agreement algorithm requires the specification of algorithm parameters, and only a key, but no parameters are provided to initialize the KeyAgreement object, the key must contain the required algorithm parameters. (For example, the Diffie-Hellman algorithm uses a prime modulus p and a base generator g as its parameters.)

To initialize a KeyAgreement object, call one of its init methods:

    public void init(Key key);

    public void init(Key key, SecureRandom random);

    public void init(Key key, AlgorithmParameterSpec params);

    public void init(Key key, AlgorithmParameterSpec params,
                     SecureRandom random);

Executing a KeyAgreement Phase

Every key agreement protocol consists of a number of phases that need to be executed by each party involved in the key agreement.

To execute the next phase in the key agreement, call the doPhase method:

    public Key doPhase(Key key, boolean lastPhase);

The key parameter contains the key to be processed by that phase. In most cases, this is the public key of one of the other parties involved in the key agreement, or an intermediate key that was generated by a previous phase. doPhase may return an intermediate key that you may have to send to the other parties of this key agreement, so they can process it in a subsequent phase.

The lastPhase parameter specifies whether or not the phase to be executed is the last one in the key agreement: A value of FALSE indicates that this is not the last phase of the key agreement (there are more phases to follow), and a value of TRUE indicates that this is the last phase of the key agreement and the key agreement is completed, i.e., generateSecret can be called next.

In the example of Diffie-Hellman between two parties , you call doPhase once, with lastPhase set to TRUE. In the example of Diffie-Hellman between three parties, you call doPhase twice: the first time with lastPhase set to FALSE, the 2nd time with lastPhase set to TRUE.

Generating the Shared Secret

After each party has executed all the required key agreement phases, it can compute the shared secret by calling one of the generateSecret methods:

    public byte[] generateSecret();

    public int generateSecret(byte[] sharedSecret, int offset);

    public SecretKey generateSecret(String algorithm);

Key Management

A database called a "keystore" can be used to manage a repository of keys and certificates. (A certificate is a digitally signed statement from one entity, saying that the public key of some other entity has a particular value.)

Keystore Location

The user keystore is by default stored in a file named .keystore in the user's home directory, as determined by the "user.home" system property. On Solaris systems "user.home" defaults to the user's home directory. On Win32 systems, given user name uName, "user.home" defaults to:

  • C:\Winnt\Profiles\uName on multi-user Windows NT systems
  • C:\Windows\Profiles\uName on multi-user Windows 95/98/2000 systems
  • C:\Windows on single-user Windows 95/98/2000 systems
Of course, keystore files can be located as desired. In some environments, it may make sense for multiple keystores to exist. For example, in JSSE (SSL/TLS), one keystore might hold a user's private keys, and another might hold certificates used to establish trust relationships.

In addition to the user's keystore, the Sun JDK also maintains a system-wide keystore which is used to store trusted certificates from a variety of Certificate Authorities (CA's). These CA certificates can be used to help make trust decisions. For example, in SSL/TLS when the SunJSSE provider is presented with certificates from a remote peer, the default trustmanager will consult the:

    <java-home>/lib/ext/cacerts           [Unix], or
    <java-home>\lib\ext\cacerts           [Windows]
file to determine if the connection is to be trusted. Instead of using the system-wide cacerts keystore, applications can set up and use their own keystores, or even use the user keystore described above.

Keystore Implementation

The KeyStore class supplies well-defined interfaces to access and modify the information in a keystore. It is possible for there to be multiple different concrete implementations, where each implementation is that for a particular type of keystore.

Currently, there are two command-line tools that make use of KeyStore: keytool and jarsigner, and also a GUI-based tool named policytool. It is also used by the Policy reference implementation when it processes policy files specifying the permissions (allowed accesses to system resources) to be granted to code from various sources. Since KeyStore is publicly available, JDK users can write additional security applications that use it.

Applications can choose different types of keystore implementations from different providers, using the getInstance factory method in the KeyStore class. A keystore type defines the storage and data format of the keystore information, and the algorithms used to protect private keys in the keystore and the integrity of the keystore itself. Keystore implementations of different types are not compatible.

There is a built-in default keystore implementation type known as "jks" that is provided by Sun Microsystems. It implements the keystore as a file, utilizing a proprietary keystore type (format). It protects each private key with its own individual password, and also protects the integrity of the entire keystore with a (possibly different) password. The default is specified by the following line in the security properties file:

    keystore.type=jks

To have tools and other applications use a different default keystore implementation, you can change that line to specify a default type. If you have a provider package that supplies a keystore implementation for a keystore type called "jceks", change the line to:

    keystore.type=jceks
Some applications, such as keytool, also let you override the default keystore type (via the -storetype command-line parameter).
NOTE: Keystore type designations are not case-sensitive. For example, "jks" would be considered the same as "jks".
There are two other types of keystores that come with the Sun JDK implementation.
  1. "jceks" is an alternate proprietary keystore format to "jks" that uses much stronger encryption in the form of Password-Based Encryption with Triple-DES.

    The Sun "jceks" implementation can parse and convert a "jks" keystore file to the "jceks" format. You may upgrade your keystore of type "jks" to a keystore of type "jceks" by changing the password of a private-key entry in your keystore and specifying "-storetype jceks" as the keystore type. To apply the cryptographically strong(er) key protection supplied to a private key named "signkey" in your default keystore, use the following command, which will prompt you for the old and new key passwords:

        keytool -keypasswd -alias signkey -storetype jceks
    See Security Tools for more information about keytool and about keystores and how they are managed.
  2. "pkcs12" is another option. This is a cross platform keystore based on the RSA PKCS12 Personal Information Exchange Syntax Standard. This standard is primarily meant for storing or transporting a user's private keys, certificates, and miscellaneous secrets. As of JDK 6, standards for storing Trusted Certificates in "pkcs12" have not been established yet, and thus "jks" or "jceks" should be used for trusted certificates.

Keystore implementations are provider-based. Developers interested in writing their own KeyStore implementations should consult How to Implement a Provider for the Java Cryptography Architecture for more information on this topic.

The KeyStore Class

The KeyStore class is an engine class that supplies well-defined interfaces to access and modify the information in a keystore. <Image of KeyStore operation>

This class represents an in-memory collection of keys and certificates. KeyStore manages two types of entries:

Key Entry

This type of keystore entry holds very sensitive cryptographic key information, which is stored in a protected format to prevent unauthorized access. Typically, a key stored in this type of entry is a secret key, or a private key accompanied by the certificate chain authenticating the corresponding public key.

Private keys and certificate chains are used by a given entity for self-authentication using digital signatures. For example, software distribution organizations digitally sign JAR files as part of releasing and/or licensing software.

Trusted Certificate Entry

This type of entry contains a single public key certificate belonging to another party. It is called a trusted certificate because the keystore owner trusts that the public key in the certificate indeed belongs to the identity identified by the subject (owner) of the certificate.

This type of entry can be used to authenticate other parties.

Each entry in a keystore is identified by an "alias" string. In the case of private keys and their associated certificate chains, these strings distinguish among the different ways in which the entity may authenticate itself. For example, the entity may authenticate itself using different certificate authorities, or using different public key algorithms.

Whether keystores are persistent, and the mechanisms used by the keystore if it is persistent, are not specified here. This convention allows use of a variety of techniques for protecting sensitive (e.g., private or secret) keys. Smart cards or other integrated cryptographic engines (SafeKeyper) are one option, and simpler mechanisms such as files may also be used (in a variety of formats).

The main KeyStore methods are described below.

Creating a KeyStore Object

KeyStore objects are obtained by using one of the KeyStore getInstance() static factory methods.

Loading a Particular Keystore into Memory

Before a KeyStore object can be used, the actual keystore data must be loaded into memory via the load method:
final void load(InputStream stream, char[] password)
The optional password is used to check the integrity of the keystore data. If no password is supplied, no integrity check is performed.

To create an empty keystore, you pass null as the InputStream argument to the load method.

Getting a List of the Keystore Aliases

All keystore entries are accessed via unique aliases. The aliases method returns an enumeration of the alias names in the keystore:

final Enumeration aliases()

Determining Keystore Entry Types

As stated in The KeyStore Class, there are two different types of entries in a keystore.

The following methods determine whether the entry specified by the given alias is a key/certificate or a trusted certificate entry, respectively:

final boolean isKeyEntry(String alias)
final boolean isCertificateEntry(String alias)

Adding/Setting/Deleting Keystore Entries

The setCertificateEntry method assigns a certificate to a specified alias:
final void setCertificateEntry(String alias, Certificate cert)
If alias doesn't exist, a trusted certificate entry with that alias is created. If alias exists and identifies a trusted certificate entry, the certificate associated with it is replaced by cert.

The setKeyEntry methods add (if alias doesn't yet exist) or set key entries:

final void setKeyEntry(String alias,
                       Key key,
                       char[] password,
                       Certificate[] chain)

final void setKeyEntry(String alias,
                       byte[] key,
                       Certificate[] chain)
In the method with key as a byte array, it is the bytes for a key in protected format. For example, in the keystore implementation supplied by the SUN provider, the key byte array is expected to contain a protected private key, encoded as an EncryptedPrivateKeyInfo as defined in the PKCS8 standard. In the other method, the password is the password used to protect the key.

The deleteEntry method deletes an entry:

final void deleteEntry(String alias)

Getting Information from the Keystore

The getKey method returns the key associated with the given alias. The key is recovered using the given password:
final Key getKey(String alias, char[] password)
The following methods return the certificate, or certificate chain, respectively, associated with the given alias:
final Certificate getCertificate(String alias)
final Certificate[] getCertificateChain(String alias)
You can determine the name (alias) of the first entry whose certificate matches a given certificate via the following:
final String getCertificateAlias(Certificate cert)

Saving the KeyStore

The in-memory keystore can be saved via the store method:
final void store(OutputStream stream, char[] password)
The password is used to calculate an integrity checksum of the keystore data, which is appended to the keystore data.

Algorithm Parameters Classes

Like Keys and Keyspecs, an algorithm's initialization parameters are represented by either AlgorithmParameters or AlgorithmParameterSpecs. Depending on the use situation, algorithms can use the parameters directly, or the parameters might need to be converted into a more portable format for transmission or storage.

A transparent representation of a set of parameters (via AlgorithmParameterSpec) means that you can access each parameter value in the set individually. You can access these values through one of the get methods defined in the corresponding specification class (e.g., DSAParameterSpec defines getP, getQ, and getG methods, to access p, q, and g, respectively).

In contrast, the AlgorithmParameters class supplies an opaque representation, in which you have no direct access to the parameter fields. You can only get the name of the algorithm associated with the parameter set (via getAlgorithm) and some kind of encoding for the parameter set (via getEncoded).

The AlgorithmParameterSpec Interface

AlgorithmParameterSpec is an interface to a transparent specification of cryptographic parameters. This interface contains no methods or constants. Its only purpose is to group (and provide type safety for) all parameter specifications. All parameter specifications must implement this interface.

The algorithm parameter specification interfaces and classes in the java.security.spec and javax.crypto.spec packages are described in the JDK javadocs:

  • DHParameterSpec
  • DHGenParameterSpec
  • DSAParameterSpec
  • ECGenParameterSpec
  • ECParameterSpec
  • IvParameterSpec
  • MGF1ParameterSpec
  • OAEPParameterSpec
  • PBEParameterSpec
  • PSSParameterSpec
  • RC2ParameterSpec
  • RC5ParameterSpec
  • RSAKeyGenParameterSpec

The following algorithm parameter specs are used specifically for digital signatures, as part of JSR 105.

  • C14NMethodParameterSpec
  • DigestMethodParameterSpec
  • SignatureMethodParameterSpec
  • TransformParameterSpec
  • ExcC14NParameterSpec
  • HMACParameterSpec
  • XPathFilter2ParameterSpec
  • XPathFilterParameterSpec
  • XSLTTransformParameterSpec

The AlgorithmParameters Class

The AlgorithmParameters class is an engine class that provides an opaque representation of cryptographic parameters. You can initialize the AlgorithmParameters class using a specific AlgorithmParameterSpec object, or by encoding the parameters in a recognized format. You can retrieve the resulting specification with the getParameterSpec method (see the following section).

Creating an AlgorithmParameters Object

AlgorithmParameters objects are obtained by using one of the AlgorithmParameters getInstance() static factory methods.

Initializing an AlgorithmParameters Object

Once an AlgorithmParameters object is instantiated, it must be initialized via a call to init, using an appropriate parameter specification or parameter encoding:

void init(AlgorithmParameterSpec paramSpec)
void init(byte[] params)
void init(byte[] params, String format)
In these init methods, params is an array containing the encoded parameters, and format is the name of the decoding format. In the init method with a params argument but no format argument, the primary decoding format for parameters is used. The primary decoding format is ASN.1, if an ASN.1 specification for the parameters exists.
NOTE: AlgorithmParameters objects can be initialized only once. They are not reusable.

Obtaining the Encoded Parameters

A byte encoding of the parameters represented in an AlgorithmParameters object may be obtained via a call to getEncoded:

byte[] getEncoded()
This method returns the parameters in their primary encoding format. The primary encoding format for parameters is ASN.1, if an ASN.1 specification for this type of parameters exists.

If you want the parameters returned in a specified encoding format, use

byte[] getEncoded(String format)
If format is null, the primary encoding format for parameters is used, as in the other getEncoded method.
NOTE: In the default AlgorithmParameters implementation, supplied by the SUN provider, the format argument is currently ignored.

Converting an AlgorithmParameters Object to a Transparent Specification

A transparent parameter specification for the algorithm parameters may be obtained from an AlgorithmParameters object via a call to getParameterSpec:

AlgorithmParameterSpec getParameterSpec(Class paramSpec)
paramSpec identifies the specification class in which the parameters should be returned. The specification class could be, for example, DSAParameterSpec.class to indicate that the parameters should be returned in an instance of the DSAParameterSpec class. (This class is in the java.security.spec package.)

The AlgorithmParameterGenerator Class

The AlgorithmParameterGenerator class is an engine class used to generate a set of brand-new parameters suitable for a certain algorithm (the algorithm is specified when an AlgorithmParameterGenerator instance is created). This object is used when you do not have an existing set of algorithm parameters, and want to generate one from scratch.

Creating an AlgorithmParameterGenerator Object

AlgorithmParameterGenerator objects are obtained by using one of the AlgorithmParameterGenerator getInstance() static factory methods.

Initializing an AlgorithmParameterGenerator Object

The AlgorithmParameterGenerator object can be initialized in two different ways: an algorithm-independent manner or an algorithm-specific manner.

The algorithm-independent approach uses the fact that all parameter generators share the concept of a "size" and a source of randomness. The measure of size is universally shared by all algorithm parameters, though it is interpreted differently for different algorithms. For example, in the case of parameters for the DSA algorithm, "size" corresponds to the size of the prime modulus, in bits. (See the Standard Names document for information about the sizes for specific algorithms.) When using this approach, algorithm-specific parameter generation values--if any--default to some standard values. One init method that takes these two universally shared types of arguments:

void init(int size, SecureRandom random);
Another init method takes only a size argument and uses a system-provided source of randomness:
void init(int size)

A third approach initializes a parameter generator object using algorithm-specific semantics, which are represented by a set of algorithm-specific parameter generation values supplied in an AlgorithmParameterSpec object:

void init(AlgorithmParameterSpec genParamSpec,
                          SecureRandom random)

void init(AlgorithmParameterSpec genParamSpec)
To generate Diffie-Hellman system parameters, for example, the parameter generation values usually consist of the size of the prime modulus and the size of the random exponent, both specified in number of bits.

Generating Algorithm Parameters

Once you have created and initialized an AlgorithmParameterGenerator object, you can use the generateParameters method to generate the algorithm parameters:
AlgorithmParameters generateParameters()

The CertificateFactory Class

The CertificateFactory class is an engine class that defines the functionality of a certificate factory, which is used to generate certificate and certificate revocation list (CRL) objects from their encodings.

A certificate factory for X.509 must return certificates that are an instance of java.security.cert.X509Certificate, and CRLs that are an instance of java.security.cert.X509CRL.

Creating a CertificateFactory Object

CertificateFactory objects are obtained by using one of the getInstance() static factory methods.

Generating Certificate Objects

To generate a certificate object and initialize it with the data read from an input stream, use the generateCertificate method:
final Certificate generateCertificate(InputStream inStream)
To return a (possibly empty) collection view of the certificates read from a given input stream, use the generateCertificates method:
final Collection generateCertificates(InputStream inStream)

Generating CRL Objects

To generate a certificate revocation list (CRL) object and initialize it with the data read from an input stream, use the generateCRL method:
final CRL generateCRL(InputStream inStream)
To return a (possibly empty) collection view of the CRLs read from a given input stream, use the generateCRLs method:
final Collection generateCRLs(InputStream inStream)

Generating CertPath Objects

The certificate path builder and validator for PKIX is defined by the Internet X.509 Public Key Infrastructure Certificate and CRL Profile, RFC 3280.

A certificate store implementation for retrieving certificates and CRLs from Collection and LDAP directories, using the PKIX LDAP V2 Schema is also available from the IETF as RFC 2587.

To generate a CertPath object and initialize it with data read from an input stream, use one of the following generateCertPath methods (with or without specifying the encoding to be used for the data):

final CertPath generateCertPath(InputStream inStream)

final CertPath generateCertPath(InputStream inStream,
                                String encoding)
To generate a CertPath object and initialize it with a list of certificates, use the following method:
final CertPath generateCertPath(List certificates)
To retrieve a list of the CertPath encodings supported by this certificate factory, you can call the getCertPathEncodings method:
final Iterator getCertPathEncodings()
The default encoding will be listed first.

How the JCA Might Be Used in a SSL/TLS Implementation

With an understanding of the JCA classes, consider how these classes might be combined to implement an advanced network protocol like SSL/TLS. The SSL/TLS Overview section in the JSSE Reference Guide describes at a high level how the protocols work. As asymmetric (public key) cipher operations are much slower than symmetric operations (secret key), public key cryptography is used to establish secret keys which are then used to protect the actual application data. Vastly simplified, the SSL/TLS handshake involves exchanging initialization data, performing some public key operations to arrive at a secret key, and then using that key to encrypt further traffic.
NOTE: The details presented here simply show how some of the above classes might be employed. This section will not present sufficient information for building a SSL/TLS implementation. For more details, please see the JSSE Reference Guide and RFC 2246: The TLS Protocol.

Assume that this SSL/TLS implementation will be made available as a JSSE provider. A concrete implementation of the Provider class is first written that will eventually be registered in the Security class' list of providers. This provider mainly provides a mapping from algorithm names to actual implementation classes. (that is: "SSLContext.TLS"->"com.foo.TLSImpl") When an application requests an "TLS" instance (via SSLContext.getInstance("TLS"), the provider's list is consulted for the requested algorithm, and an appropriate instance is created.

Before discussing details of the actual handshake, a quick review of some of the JSSE's architecture is needed. The heart of the JSSE architecture is the SSLContext. The context eventually creates end objects (SSLSocket and SSLEngine) which actually implement the SSL/TLS protocol. SSLContexts are initialized with two callback classes, KeyManager and TrustManager, which allow applications to first select authentication material to send and second to verify credentials sent by a peer.

A JSSE KeyManager is responsible for choosing which credentials to present to a peer. Many algorithms are possible, but a common strategy is to maintain a RSA or DSA public/private key pair along with a X509Certificate in a KeyStore backed by a disk file. When a KeyStore object is initialized and loaded from the file, the file's raw bytes are converted into PublicKey and PrivateKey objects using a KeyFactory, and a certificate chain's bytes are converted using a CertificateFactory. When a credential is needed, the KeyManager simply consults this KeyStore object and determines which credentials to present.

A KeyStore's contents might have originally been created using a utility such as keytool. keytool creates a RSA or DSA KeyPairGenerator and initializes it with an appropriate keysize. This generator is then used to create a KeyPair which keytool would store along with the newly-created certificate in the KeyStore, which is eventually written to disk.

A JSSE TrustManager is responsible for verifying the credentials received from a peer. There are many ways to verify credentials: one of them is to create a CertPath object, and let the JDK's built-in Public Key Infrastructure (PKI) framework handle the validation. Internally, the CertPath implementation might create a Signature object, and use that to verify that the each of the signatures in the certificate chain.

With this basic understanding of the architecture, we can look at some of the steps in the SSL/TLS handshake. The client begins by sending a ClientHello message to the server. The server selects a ciphersuite to use, and sends that back in a ServerHello message, and begins creating JCA objects based on the suite selection. We'll use server-only authentication in the following examples.

<Image of SSL/TSL messages>

In the first example, the server tries to use a RSA-based ciphersuite such as TLS_RSA_WITH_AES_128_CBC_SHA. The server's KeyManager is queried, and returns an appropriate RSA entry. The server's credentials (that is: certificate/public key) are sent in the server's Certificate message. The client's TrustManager verifies the server's certificate, and if accepted, the client generates some random bytes using a SecureRandom object. This is then encrypted using an encrypting asymmetric RSA Cipher object that has been initialized with the PublicKey found in the server's certificate. This encrypted data is sent in a Client Key Exchange message. The server would use its corresponding PrivateKey to recover the bytes using a similar Cipher in decrypt mode. These bytes are then used to establish the actual encryption keys.

In a different example, an ephemeral Diffie-Hellman key agreement algorithm along with the DSA signature algorithm is chosen, such as TLS_DHE_DSS_WITH_AES_128_CBC_SHA. The two sides must each establish a new temporary DH public/private keypair using a KeyPairGenerator. Each generator creates DH keys which can then be further converted into pieces using the KeyFactory and DHPublicKeySpec classes. Each side then creates a KeyAgreement object and initializes it with their respective DH PrivateKeys. The server sends its public key pieces in a ServerKeyExchange message (protected by the DSA signature algorithm, and the client sends its public key in a ClientKeyExchange message. When the public keys are reassembled using another KeyFactory, they are fed into the agreement objects. The KeyAgreement objects then generate agreed-upon bytes that are then used to establish the actual encryption keys.

Once the actual encryption keys have been established, the secret key is used to initialize a symmetric Cipher object, and this cipher is used to protect all data in transit. To help determine if the data has been modified, a MessageDigest is created and receives a copy of the data destined for the network. When the packet is complete, the digest (hash) is appended to data, and the entire packet is encrypted by the Cipher. If a block cipher such as AES is used, the data must be padded to make a complete block. On the remote side, the steps are simply reversed.

Header Data Digest Padding (if any)

Again, this is vastly simplied, but gives one an idea of how these classes might be combined to create a higher level protocol.

How to Make Applications "Exempt" from Cryptographic Restrictions

Note 1: This section should be ignored by most application developers. It is only for people whose applications may be exported to those few countries whose governments mandate cryptographic restrictions, if it is desired that such applications have fewer cryptographic restrictions than those mandated. Note 2: Throughout this section, the term "application" is meant to encompass both applications and applets.]

The JCA framework includes an ability to enforce restrictions regarding the cryptographic algorithms and maximum cryptographic strengths available to applets/applications in different jurisdiction contexts (locations). Any such restrictions are specified in "jurisdiction policy files".

Due to import control restrictions by the governments of a few countries, the jurisdiction policy files shipped with the Java SE Development Kit 6 from Sun Microsystems specify that "strong" but limited cryptography may be used. An "unlimited strength" version of these files indicating no restrictions on cryptographic strengths is available for those living in eligible countries (which is most countries). But only the "strong" version can be imported into those countries whose governments mandate restrictions. The JCA framework will enforce the restrictions specified in the installed jurisdiction policy files.

It is possible that the governments of some or all such countries may allow certain applications to become exempt from some or all cryptographic restrictions. For example, they may consider certain types of applications as "special" and thus exempt. Or they may exempt any application that utilizes an "exemption mechanism," such as key recovery. Applications deemed to be exempt could get access to stronger cryptography than that allowed for non-exempt applications in such countries.

In order for an application to be recognized as "exempt" at runtime, it must meet the following conditions:

  • It must have a permission policy file bundled with it in a JAR file. The permission policy file specifies what cryptography-related permissions the application has, and under what conditions (if any).
  • The JAR file containing the application and the permission policy file must have been signed using a code-signing certificate issued after the application was accepted as exempt.

Below are sample steps required in order to make an application exempt from some or all cryptographic restrictions. This is a basic outline that includes information about what is required by JCA in order to recognize and treat applications as being exempt. You will need to know the exemption requirements of the particular country or countries in which you would like your application to be able to be run but whose governments require cryptographic restrictions. You will also need to know the requirements of a JCA framework vendor that has a process in place for handling exempt applications. Consult such a vendor for further information. (NOTE: The SunJCE provider does not supply an implementation of the ExemptionMechanismSpi class.)

  • Step 1: Write and Compile Your Application Code
  • Step 2: Create a Permission Policy File Granting Appropriate Cryptographic Permissions
  • Step 3: Prepare for Testing
    • Step 3a: Apply for Government Approval From the Government Mandating Restrictions.
    • Step 3b: Get a Code-Signing Certificate
    • Step 3c: Bundle the Application and Permission Policy File into a JAR file
    • Step 3d: Sign the JAR file
    • Step 3e: Set Up Your Environment Like That of a User in a Restricted Country
    • Step 3f: (only for apps using exemption mechanisms) Install a Provider Implementing the Exemption Mechanism Specified by the entry in the Permission Policy File
  • Step 4: Test Your Application
  • Step 5: Apply for U.S. Government Export Approval If Required
  • Step 6: Deploy Your Application

Special Code Requirements for Applications that Use Exemption Mechanisms

When an application has a permission policy file associated with it (in the same JAR file) and that permission policy file specifies an exemption mechanism, then when the Cipher getInstance method is called to instantiate a Cipher, the JCA code searches the installed providers for one that implements the specified exemption mechanism. If it finds such a provider, JCA instantiates an ExemptionMechanism API object associated with the provider's implementation, and then associates the ExemptionMechanism object with the Cipher returned by getInstance.

After instantiating a Cipher, and prior to initializing it (via a call to the Cipher init method), your code must call the following Cipher method:

    public ExemptionMechanism getExemptionMechanism()

This call returns the ExemptionMechanism object associated with the Cipher. You must then initialize the exemption mechanism implementation by calling the following method on the returned ExemptionMechanism:

    public final void init(Key key)

The argument you supply should be the same as the argument of the same types that you will subsequently supply to a Cipher init method.

Once you have initialized the ExemptionMechanism, you can proceed as usual to initialize and use the Cipher.

Permission Policy Files

In order for an application to be recognized at runtime as being "exempt" from some or all cryptographic restrictions, it must have a permission policy file bundled with it in a JAR file. The permission policy file specifies what cryptography-related permissions the application has, and under what conditions (if any).

NOTE: The permission policy file bundled with an application must be named cryptoPerms.

The format of a permission entry in a permission policy file that accompanies an exempt application is the same as the format for a jurisdiction policy file downloaded with the JDK, which is:

    permission <crypto permission class name>[ <alg_name>
        [[, <exemption mechanism name>][, <maxKeySize>
        [, <AlgorithmParameterSpec class name>,
        <parameters for constructing an AlgorithmParameterSpec object>
        ]]]];

See Appendix B for more information about the jurisdiction policy file format.

Permission Policy Files for Exempt Applications

Some applications may be allowed to be completely unrestricted. Thus, the permission policy file that accompanies such an application usually just needs to contain the following:

    grant {
        // There are no restrictions to any algorithms.
        permission javax.crypto.CryptoAllPermission;
    };

If an application just uses a single algorithm (or several specific algorithms), then the permission policy file could simply mention that algorithm (or algorithms) explicitly, rather than granting CryptoAllPermission. For example, if an application just uses the Blowfish algorithm, the permission policy file doesn't have to grant CryptoAllPermission to all algorithms. It could just specify that there is no cryptographic restriction if the Blowfish algorithm is used. In order to do this, the permission policy file would look like the following:

    grant {
        permission javax.crypto.CryptoPermission "Blowfish";
    };

Permission Policy Files for Applications Exempt Due to Exemption Mechanisms

If an application is considered "exempt" if an exemption mechanism is enforced, then the permission policy file that accompanies the application must specify one or more exemption mechanisms. At runtime, the application will be considered exempt if any of those exemption mechanisms is enforced. Each exemption mechanism must be specified in a permission entry that looks like the following:

    // No algorithm restrictions if specified
    // exemption mechanism is enforced.
    permission javax.crypto.CryptoPermission *,
        "<ExemptionMechanismName>";

where <ExemptionMechanismName> specifies the name of an exemption mechanism. The list of possible exemption mechanism names includes:

  • KeyRecovery
  • KeyEscrow
  • KeyWeakening
As an example, suppose your application is exempt if either key recovery or key escrow is enforced. Then your permission policy file should contain the following:
    grant {
        // No algorithm restrictions if KeyRecovery is enforced.
        permission javax.crypto.CryptoPermission *,
            "KeyRecovery";
        // No algorithm restrictions if KeyEscrow is enforced.
        permission javax.crypto.CryptoPermission *,
            "KeyEscrow";
    };

NOTE: Permission entries that specify exemption mechanisms should not also specify maximum key sizes. The allowed key sizes are actually determined from the installed exempt jurisdiction policy files, as described in the next section.

How Bundled Permission Policy Files Affect Cryptographic Permissions

At runtime, when an application instantiates a Cipher (via a call to its getInstance method) and that application has an associated permission policy file, JCA checks to see whether the permission policy file has an entry that applies to the algorithm specified in the getInstance call. If it does, and the entry grants CryptoAllPermission or does not specify that an exemption mechanism must be enforced, it means there is no cryptographic restriction for this particular algorithm.

If the permission policy file has an entry that applies to the algorithm specified in the getInstance call and the entry does specify that an exemption mechanism must be enforced, then the exempt jurisdiction policy file(s) are examined. If the exempt permissions include an entry for the relevant algorithm and exemption mechanism, and that entry is implied by the permissions in the permission policy file bundled with the application, and if there is an implementation of the specified exemption mechanism available from one of the registered providers, then the maximum key size and algorithm parameter values for the Cipher are determined from the exempt permission entry.

If there is no exempt permission entry implied by the relevant entry in the permission policy file bundled with the application, or if there is no implementation of the specified exemption mechanism available from any of the registered providers, then the application is only allowed the standard default cryptographic permissions.

Code Examples

Here are some short examples which illustrate use of several of the JCA mechanisms. In addition, complete working examples can be found in Appendix D.

Computing a MessageDigest Object

First create the message digest object, as in the following example:

MessageDigest sha = MessageDigest.getInstance("SHA-1");
This call assigns a properly initialized message digest object to the sha variable. The implementation implements the Secure Hash Algorithm (SHA-1), as defined in the National Institute for Standards and Technology's (NIST) FIPS 180-2 document. See Appendix A for a complete discussion of standard names and algorithms.

Next, suppose we have three byte arrays, i1, i2 and i3, which form the total input whose message digest we want to compute. This digest (or "hash") could be calculated via the following calls:

sha.update(i1);
sha.update(i2);
sha.update(i3);
byte[] hash = sha.digest();

An equivalent alternative series of calls would be:

sha.update(i1);
sha.update(i2);
byte[] hash = sha.digest(i3);
After the message digest has been calculated, the message digest object is automatically reset and ready to receive new data and calculate its digest. All former state (i.e., the data supplied to update calls) is lost.

Some hash implementations may support intermediate hashes through cloning. Suppose we want to calculate separate hashes for:

  • i1
  • i1 and i2
  • i1, i2, and i3

A way to do it is:

/* compute the hash for i1 */
sha.update(i1);
byte[] i1Hash = sha.clone().digest();

/* compute the hash for i1 and i2 */
sha.update(i2);
byte[] i12Hash = sha.clone().digest();

/* compute the hash for i1, i2 and i3 */
sha.update(i3);
byte[] i123hash = sha.digest();
This code works only if the SHA-1 implementation is cloneable. While some implementations of message digests are cloneable, others are not. To determine whether or not cloning is possible, attempt to clone the MessageDigest object and catch the potential exception as follows:
try {
    // try and clone it
    /* compute the hash for i1 */
    sha.update(i1);
    byte[] i1Hash = sha.clone().digest();
    . . .
    byte[] i123hash = sha.digest();
} catch (CloneNotSupportedException cnse) {
    // do something else, such as the code shown below
}
If a message digest is not cloneable, the other, less elegant way to compute intermediate digests is to create several digests. In this case, the number of intermediate digests to be computed must be known in advance:
MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
MessageDigest sha12 = MessageDigest.getInstance("SHA-1");
MessageDigest sha123 = MessageDigest.getInstance("SHA-1");

byte[] i1Hash = sha1.digest(i1);

sha12.update(i1);
byte[] i12Hash = sha12.digest(i2);

sha123.update(i1);
sha123.update(i2);
byte[] i123Hash = sha123.digest(i3);

Generating a Pair of Keys

In this example we will generate a public-private key pair for the algorithm named "DSA" (Digital Signature Algorithm), and use this keypair in future examples. We will generate keys with a 1024-bit modulus. We don't care which provider supplies the algorithm implementation.

Creating the Key Pair Generator

The first step is to get a key pair generator object for generating keys for the DSA algorithm:

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");

Initializing the Key Pair Generator

The next step is to initialize the key pair generator. In most cases, algorithm-independent initialization is sufficient, but in some cases, algorithm-specific initialization is used.

Algorithm-Independent Initialization

All key pair generators share the concepts of a keysize and a source of randomness. The KeyPairGenerator class initialization methods at a minimum needs a keysize. If the source of randomness is not explicitly provided, a SecureRandom implementation of the highest-priority installed provider will be used. Thus to generate keys with a keysize of 1024, simply call:

SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keyGen.initialize(1024, random);
The following code illustrates how to use a specific, additionally seeded SecureRandom object:
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
random.setSeed(userSeed);
keyGen.initialize(1024, random);
Since no other parameters are specified when you call the above algorithm-independent initialize method, it is up to the provider what to do about the algorithm-specific parameters (if any) to be associated with each of the keys. The provider may use precomputed parameter values or may generate new values.

Algorithm-Specific Initialization

For situations where a set of algorithm-specific parameters already exists (such as "community parameters" in DSA), there are two initialize methods that have an AlgorithmParameterSpec argument. Suppose your key pair generator is for the "DSA" algorithm, and you have a set of DSA-specific parameters, p, q, and g, that you would like to use to generate your key pair. You could execute the following code to initialize your key pair generator (recall that DSAParameterSpec is an AlgorithmParameterSpec):

DSAParameterSpec dsaSpec = new DSAParameterSpec(p, q, g);
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
random.setSeed(userSeed);
keyGen.initialize(dsaSpec, random);
NOTE: The parameter named p is a prime number whose length is the modulus length ("size"). Therefore, you don't need to call any other method to specify the modulus length.

Generating the Pair of Keys

The final step is actually generating the key pair. No matter which type of initialization was used (algorithm-independent or algorithm-specific), the same code is used to generate the key pair:
KeyPair pair = keyGen.generateKeyPair();

Generating and Verifying a Signature Using Generated Keys

The following signature generation and verification examples use the KeyPair generated in the key pair example above.

Generating a Signature

We first create a signature object:

Signature dsa = Signature.getInstance("SHA1withDSA");
Next, using the key pair generated in the key pair example, we initialize the object with the private key, then sign a byte array called data.
/* Initializing the object with a private key */
PrivateKey priv = pair.getPrivate();
dsa.initSign(priv);

/* Update and sign the data */
dsa.update(data);
byte[] sig = dsa.sign();

Verifying a Signature

Verifying the signature is straightforward. (Note that here we also use the key pair generated in the key pair example.)
/* Initializing the object with the public key */
PublicKey pub = pair.getPublic();
dsa.initVerify(pub);

/* Update and verify the data */
dsa.update(data);
boolean verifies = dsa.verify(sig);
System.out.println("signature verifies: " + verifies);

Generating/Verifying Signatures Using Key Specifications and KeyFactory

Suppose that, rather than having a public/private key pair (as, for example, was generated in the key pair example above), you simply have the components of your DSA private key: x (the private key), p (the prime), q (the sub-prime), and g (the base).

Further suppose you want to use your private key to digitally sign some data, which is in a byte array named someData. You would do the following steps, which also illustrate creating a key specification and using a key factory to obtain a PrivateKey from the key specification (initSign requires a PrivateKey):

DSAPrivateKeySpec dsaPrivKeySpec = new DSAPrivateKeySpec(x, p, q, g);

KeyFactory keyFactory = KeyFactory.getInstance("DSA");
PrivateKey privKey = keyFactory.generatePrivate(dsaPrivKeySpec);

Signature sig = Signature.getInstance("SHA1withDSA");
sig.initSign(privKey);
sig.update(someData);
byte[] signature = sig.sign();
Suppose Alice wants to use the data you signed. In order for her to do so, and to verify your signature, you need to send her three things:
  1. the data,
  2. the signature, and
  3. the public key corresponding to the private key you used to sign the data.
You can store the someData bytes in one file, and the signature bytes in another, and send those to Alice.

For the public key, assume, as in the signing example above, you have the components of the DSA public key corresponding to the DSA private key used to sign the data. Then you can create a DSAPublicKeySpec from those components:

DSAPublicKeySpec dsaPubKeySpec = new DSAPublicKeySpec(y, p, q, g);
You still need to extract the key bytes so that you can put them in a file. To do so, you can first call the generatePublic method on the DSA key factory already created in the example above:
PublicKey pubKey = keyFactory.generatePublic(dsaPubKeySpec);
Then you can extract the (encoded) key bytes via the following:
byte[] encKey = pubKey.getEncoded();
You can now store these bytes in a file, and send it to Alice along with the files containing the data and the signature.

Now, assume Alice has received these files, and she copied the data bytes from the data file to a byte array named data, the signature bytes from the signature file to a byte array named signature, and the encoded public key bytes from the public key file to a byte array named encodedPubKey.

Alice can now execute the following code to verify the signature. The code also illustrates how to use a key factory in order to instantiate a DSA public key from its encoding (initVerify requires a PublicKey).

    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encodedPubKey);

    KeyFactory keyFactory = KeyFactory.getInstance("DSA");
    PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

    Signature sig = Signature.getInstance("SHA1withDSA");
    sig.initVerify(pubKey);
    sig.update(data);
    sig.verify(signature);
NOTE: In the above, Alice needed to generate a PublicKey from the encoded key bits, since initVerify requires a PublicKey. Once she has a PublicKey, she could also use the KeyFactory getKeySpec method to convert it to a DSAPublicKeySpec so that she can access the components, if desired, as in:
    DSAPublicKeySpec dsaPubKeySpec =
        (DSAPublicKeySpec)keyFactory.getKeySpec(pubKey,
            DSAPublicKeySpec.class)
Now she can access the DSA public key components y, p, q, and g through the corresponding "get" methods on the DSAPublicKeySpec class (getY, getP, getQ, and getG).

Determining If Two Keys Are Equal

In many cases you would like to know if two keys are equal; however, the default method java.lang.Object.equals may not give the desired result. The most provider-independent approach is to compare the encoded keys. If this comparison isn't appropriate (for example, when comparing an RSAPrivateKey and an RSAPrivateCrtKey), you should compare each component. The following code demonstrates this idea:

static boolean keysEqual(Key key1, Key key2) {
    if (key1.equals(key2)) {
        return true;
    }

    if (Arrays.equals(key1.getEncoded(), key2.getEncoded())) {
        return true;
    }

    // More code for different types of keys here.
    // For example, the following code can check if
    // an RSAPrivateKey and an RSAPrivateCrtKey are equal:
    // if ((key1 instanceof RSAPrivateKey) &&
    //     (key2 instanceof RSAPrivateKey)) {
    //     if ((key1.getModulus().equals(key2.getModulus())) &&
    //         (key1.getPrivateExponent().equals(
    //                                      key2.getPrivateExponent()))) {
    //         return true;
    //     }
    // }

    return false;
}

Reading Base64-Encoded Certificates

The following example reads a file with Base64-encoded certificates, which are each bounded at the beginning by

-----BEGIN CERTIFICATE-----
and at the end by
-----END CERTIFICATE-----
We convert the FileInputStream (which does not support mark and reset) to a ByteArrayInputStream (which supports those methods), so that each call to generateCertificate consumes only one certificate, and the read position of the input stream is positioned to the next certificate in the file:
FileInputStream fis = new FileInputStream(filename);
BufferedInputStream bis = new BufferedInputStream(fis);

CertificateFactory cf = CertificateFactory.getInstance("X.509");

while (bis.available() > 0) {
    Certificate cert = cf.generateCertificate(bis);
    System.out.println(cert.toString());
}

Parsing a Certificate Reply

The following example parses a PKCS7-formatted certificate reply stored in a file and extracts all the certificates from it:

FileInputStream fis = new FileInputStream(filename);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Collection c = cf.generateCertificates(fis);
Iterator i = c.iterator();
while (i.hasNext()) {
   Certificate cert = (Certificate)i.next();
   System.out.println(cert);
}

Using Encryption

This section takes the user through the process of generating a key, creating and initializing a cipher object, encrypting a file, and then decrypting it. Throughout this example, we use the Advanced Encryption Standard (AES).

Generating a Key

To create an AES key, we have to instantiate a KeyGenerator for AES. We do not specify a provider, because we do not care about a particular AES key generation implementation. Since we do not initialize the KeyGenerator, a system-provided source of randomness and a default keysize will be used to create the AES key:

    KeyGenerator keygen = KeyGenerator.getInstance("AES");
    SecretKey aesKey = keygen.generateKey();

After the key has been generated, the same KeyGenerator object can be re-used to create further keys.

Creating a Cipher

The next step is to create a Cipher instance. To do this, we use one of the getInstance factory methods of the Cipher class. We must specify the name of the requested transformation, which includes the following components, separated by slashes (/):

  • the algorithm name
  • the mode (optional)
  • the padding scheme (optional)

In this example, we create an AES cipher in Electronic Codebook mode, with PKCS5-style padding. We do not specify a provider, because we do not care about a particular implementation of the requested transformation.

The standard algorithm name for AES is "AES", the standard name for the Electronic Codebook mode is "ECB", and the standard name for PKCS5-style padding is "PKCS5Padding":

    Cipher aesCipher;

    // Create the cipher
    aesCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

We use the generated aesKey from above to initialize the Cipher object for encryption:

    // Initialize the cipher for encryption
    aesCipher.init(Cipher.ENCRYPT_MODE, aesKey);

    // Our cleartext
    byte[] cleartext = "This is just an example".getBytes();

    // Encrypt the cleartext
    byte[] ciphertext = aesCipher.doFinal(cleartext);

    // Initialize the same cipher for decryption
    aesCipher.init(Cipher.DECRYPT_MODE, aesKey);

    // Decrypt the ciphertext
    byte[] cleartext1 = aesCipher.doFinal(ciphertext);

cleartext and cleartext1 are identical.

Using Password-Based Encryption

In this example, we prompt the user for a password from which we derive an encryption key.

It would seem logical to collect and store the password in an object of type java.lang.String. However, here's the caveat: Objects of type String are immutable, i.e., there are no methods defined that allow you to change (overwrite) or zero out the contents of a String after usage. This feature makes String objects unsuitable for storing security sensitive information such as user passwords. You should always collect and store security sensitive information in a char array instead.

For that reason, the javax.crypto.spec.PBEKeySpec class takes (and returns) a password as a char array. See the ReadPassword class in the sample code in Appendix D for one possible way of reading character array passwords from an input stream.

In order to use Password-Based Encryption (PBE) as defined in PKCS5, we have to specify a salt and an iteration count. The same salt and iteration count that are used for encryption must be used for decryption:

            PBEKeySpec pbeKeySpec;
            PBEParameterSpec pbeParamSpec;
            SecretKeyFactory keyFac;

            // Salt
            byte[] salt = {
                (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
                (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
            };

            // Iteration count
            int count = 20;

            // Create PBE parameter set
            pbeParamSpec = new PBEParameterSpec(salt, count);

            // Prompt user for encryption password.
            // Collect user password as char array (using the
            // "readPassword" method from above), and convert
            // it into a SecretKey object, using a PBE key
            // factory.
            System.out.print("Enter encryption password:  ");
            System.out.flush();
            pbeKeySpec = new PBEKeySpec(readPassword(System.in));
            keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
            SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

            // Create PBE Cipher
            Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

            // Initialize PBE Cipher with key and parameters
            pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);

            // Our cleartext
            byte[] cleartext = "This is another example".getBytes();

            // Encrypt the cleartext
            byte[] ciphertext = pbeCipher.doFinal(cleartext);

Using Key Agreement

Please refer to Appendix D for sample programs exercising the Diffie-Hellman key exchange between 2 and 3 parties.

Appendix A: Standard Names

The JDK Security API requires and uses a set of standard names for algorithms, certificate and keystore types. The specification names previously found here in Appendix A and in the other security specifications (JSSE/CertPath/etc.) have been combined in the Standard Names document. This document also contains more information about the algorithm specifications. Specific provider information can be found in the Sun Provider Documentation.

Cryptographic implementations in the Sun JDK are distributed through several different providers primarily for historical reasons (Sun, SunJSSE, SunJCE, SunRsaSign). Note these providers may not be available on all JDK implementations, and therefore, truly portable applications should call getInstance() without specifying specific providers. Applications specifying a particular provider may not be able to take advantage of native providers tuned for an underlying operating environment (such as PKCS or Microsoft's CAPI).

The SunPKCS11 provider itself does not contain any cryptographic algorithms, but instead, directs requests into an underlying PKCS11 implementation. The PKCS11 Reference Guide and the underlying PKCS11 implementation should be consulted to determine if a desired algorithm will be available through the PKCS11 provider. Likewise, on Windows systems, the SunMSCAPI provider does not provide any cryptographic functionality, but instead routes requests to the underlying Operating System for handling.

Appendix B: Jurisdiction Policy File Format

JCA represents its jurisdiction policy files as Java style policy files with corresponding permission statements. As described in Default Policy Implementation and Policy File Syntax, a Java policy file specifies what permissions are allowed for code from specified code sources. A permission represents access to a system resource. In the case of JCA, the "resources" are cryptography algorithms, and code sources do not need to be specified, because the cryptographic restrictions apply to all code.

A jurisdiction policy file consists of a very basic "grant entry" containing one or more "permission entries."

grant {
    <permission entries>;
};

The format of a permission entry in a jurisdiction policy file is:

permission <crypto permission class name>[ <alg_name>
    [[, <exemption mechanism name>][, <maxKeySize>
    [, <AlgorithmParameterSpec class name>,
    <parameters for constructing an
        AlgorithmParameterSpec object>]]]];

A sample jurisdiction policy file that includes restricting the "Blowfish" algorithm to maximum key sizes of 64 bits is:

    grant {
        permission javax.crypto.CryptoPermission "Blowfish", 64;
        . . .;
    };

A permission entry must begin with the word permission. The <crypto permission class name> in the template above would actually be a specific permission class name, such as javax.crypto.CryptoPermission. A crypto permission class reflects the ability of an application/applet to use certain algorithms with certain key sizes in certain environments. There are two crypto permission classes: CryptoPermission and CryptoAllPermission. The special CryptoAllPermission class implies all cryptography-related permissions, that is, it specifies that there are no cryptography-related restrictions.

The <alg_name>, when utilized, is a quoted string specifying the standard name (see Appendix A) of a cryptography algorithm, such as "DES" or "RSA".

The <exemption mechanism name>, when specified, is a quoted string indicating an exemption mechanism which, if enforced, enables a reduction in cryptographic restrictions. Exemption mechanism names that can be used include "KeyRecovery" "KeyEscrow", and "KeyWeakening".

<maxKeySize> is an integer specifying the maximum key size (in bits) allowed for the specified algorithm.

For some algorithms it may not be sufficient to specify the algorithm strength in terms of just a key size. For example, in the case of the "RC5" algorithm, the number of rounds must also be considered. For algorithms whose strength needs to be expressed as more than a key size, the permission entry should also specify an AlgorithmParameterSpec class name (such as javax.crypto.spec.RC5ParameterSpec) and a list of parameters for constructing the specified AlgorithmParameterSpec object.

Items that appear in a permission entry must appear in the specified order. An entry is terminated with a semicolon.

Case is unimportant for the identifiers (grant, permission) but is significant for the <crypto permission class name> or for any string that is passed in as a value.

NOTE: An "*" can be used as a wildcard for any permission entry option. For example, an "*" (without the quotes) for an <alg_name> option means "all algorithms."

Appendix C: Maximum Key Sizes Allowed by "Strong" Jurisdiction Policy Files

Due to import control restrictions, the jurisdiction policy files shipped with the Java SE Development Kit allow "strong" but limited cryptography to be used. For more info, please see Import Limits on Cryptographic Algorithms.

Appendix D: Sample Programs

Diffie-Hellman Key Exchange between 2 Parties

/*
 * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.io.*;
import java.math.BigInteger;
import java.security.*;
import java.security.spec.*;
import java.security.interfaces.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;
import com.sun.crypto.provider.SunJCE;

/**
 * This program executes the Diffie-Hellman key agreement protocol
 * between 2 parties: Alice and Bob.
 *
 * By default, preconfigured parameters (1024-bit prime modulus and base
 * generator used by SKIP) are used.
 * If this program is called with the "-gen" option, a new set of
 * parameters is created.
 */

public class DHKeyAgreement2 {

    private DHKeyAgreement2() {}

    public static void main(String argv[]) {
        try {
            String mode = "USE_SKIP_DH_PARAMS";

            DHKeyAgreement2 keyAgree = new DHKeyAgreement2();

            if (argv.length > 1) {
                keyAgree.usage();
                throw new Exception("Wrong number of command options");
            } else if (argv.length == 1) {
                if (!(argv[0].equals("-gen"))) {
                    keyAgree.usage();
                    throw new Exception("Unrecognized flag: " + argv[0]);
                }
                mode = "GENERATE_DH_PARAMS";
            }

            keyAgree.run(mode);
        } catch (Exception e) {
            System.err.println("Error: " + e);
            System.exit(1);
        }
    }

    private void run(String mode) throws Exception {

        DHParameterSpec dhSkipParamSpec;

        if (mode.equals("GENERATE_DH_PARAMS")) {
            // Some central authority creates new DH parameters
            System.out.println
                ("Creating Diffie-Hellman parameters (takes VERY long) ...");
            AlgorithmParameterGenerator paramGen
                = AlgorithmParameterGenerator.getInstance("DH");
            paramGen.init(512);
            AlgorithmParameters params = paramGen.generateParameters();
            dhSkipParamSpec = (DHParameterSpec)params.getParameterSpec
                (DHParameterSpec.class);
        } else {
            // use some pre-generated, default DH parameters
            System.out.println("Using SKIP Diffie-Hellman parameters");
            dhSkipParamSpec = new DHParameterSpec(skip1024Modulus,
                                                  skip1024Base);
        }

        /*
         * Alice creates her own DH key pair, using the DH parameters from
         * above
         */
        System.out.println("ALICE: Generate DH keypair ...");
        KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH");
        aliceKpairGen.initialize(dhSkipParamSpec);
        KeyPair aliceKpair = aliceKpairGen.generateKeyPair();

        // Alice creates and initializes her DH KeyAgreement object
        System.out.println("ALICE: Initialization ...");
        KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH");
        aliceKeyAgree.init(aliceKpair.getPrivate());

        // Alice encodes her public key, and sends it over to Bob.
        byte[] alicePubKeyEnc = aliceKpair.getPublic().getEncoded();

        /*
         * Let's turn over to Bob. Bob has received Alice's public key
         * in encoded format.
         * He instantiates a DH public key from the encoded key material.
         */
        KeyFactory bobKeyFac = KeyFactory.getInstance("DH");
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec
            (alicePubKeyEnc);
        PublicKey alicePubKey = bobKeyFac.generatePublic(x509KeySpec);

        /*
         * Bob gets the DH parameters associated with Alice's public key.
         * He must use the same parameters when he generates his own key
         * pair.
         */
        DHParameterSpec dhParamSpec = ((DHPublicKey)alicePubKey).getParams();

        // Bob creates his own DH key pair
        System.out.println("BOB: Generate DH keypair ...");
        KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH");
        bobKpairGen.initialize(dhParamSpec);
        KeyPair bobKpair = bobKpairGen.generateKeyPair();

        // Bob creates and initializes his DH KeyAgreement object
        System.out.println("BOB: Initialization ...");
        KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH");
        bobKeyAgree.init(bobKpair.getPrivate());

        // Bob encodes his public key, and sends it over to Alice.
        byte[] bobPubKeyEnc = bobKpair.getPublic().getEncoded();

        /*
         * Alice uses Bob's public key for the first (and only) phase
         * of her version of the DH
         * protocol.
         * Before she can do so, she has to instantiate a DH public key
         * from Bob's encoded key material.
         */
        KeyFactory aliceKeyFac = KeyFactory.getInstance("DH");
        x509KeySpec = new X509EncodedKeySpec(bobPubKeyEnc);
        PublicKey bobPubKey = aliceKeyFac.generatePublic(x509KeySpec);
        System.out.println("ALICE: Execute PHASE1 ...");
        aliceKeyAgree.doPhase(bobPubKey, true);

        /*
         * Bob uses Alice's public key for the first (and only) phase
         * of his version of the DH
         * protocol.
         */
        System.out.println("BOB: Execute PHASE1 ...");
        bobKeyAgree.doPhase(alicePubKey, true);

        /*
         * At this stage, both Alice and Bob have completed the DH key
         * agreement protocol.
         * Both generate the (same) shared secret.
         */
        byte[] aliceSharedSecret = aliceKeyAgree.generateSecret();
        int aliceLen = aliceSharedSecret.length;

        byte[] bobSharedSecret = new byte[aliceLen];
        int bobLen;
        try {
            // show example of what happens if you
            // provide an output buffer that is too short
            bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 1);
        } catch (ShortBufferException e) {
            System.out.println(e.getMessage());
        }
        // provide output buffer of required size
        bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 0);

        System.out.println("Alice secret: " +
          toHexString(aliceSharedSecret));
        System.out.println("Bob secret: " +
          toHexString(bobSharedSecret));

        if (!java.util.Arrays.equals(aliceSharedSecret, bobSharedSecret))
            throw new Exception("Shared secrets differ");
        System.out.println("Shared secrets are the same");

        /*
         * Now let's return the shared secret as a SecretKey object
         * and use it for encryption. First, we generate SecretKeys for the
         * "DES" algorithm (based on the raw shared secret data) and
         * then we use DES in ECB mode
         * as the encryption algorithm. DES in ECB mode does not require any
         * parameters.
         *
         * Then we use DES in CBC mode, which requires an initialization
         * vector (IV) parameter. In CBC mode, you need to initialize the
         * Cipher object with an IV, which can be supplied using the
         * javax.crypto.spec.IvParameterSpec class. Note that you have to use
         * the same IV for encryption and decryption: If you use a different
         * IV for decryption than you used for encryption, decryption will
         * fail.
         *
         * NOTE: If you do not specify an IV when you initialize the
         * Cipher object for encryption, the underlying implementation
         * will generate a random one, which you have to retrieve using the
         * javax.crypto.Cipher.getParameters() method, which returns an
         * instance of java.security.AlgorithmParameters. You need to transfer
         * the contents of that object (e.g., in encoded format, obtained via
         * the AlgorithmParameters.getEncoded() method) to the party who will
         * do the decryption. When initializing the Cipher for decryption,
         * the (reinstantiated) AlgorithmParameters object must be passed to
         * the Cipher.init() method.
         */
        System.out.println("Return shared secret as SecretKey object ...");
        // Bob
        // NOTE: The call to bobKeyAgree.generateSecret above reset the key
        // agreement object, so we call doPhase again prior to another
        // generateSecret call
        bobKeyAgree.doPhase(alicePubKey, true);
        SecretKey bobDesKey = bobKeyAgree.generateSecret("DES");

        // Alice
        // NOTE: The call to aliceKeyAgree.generateSecret above reset the key
        // agreement object, so we call doPhase again prior to another
        // generateSecret call
        aliceKeyAgree.doPhase(bobPubKey, true);
        SecretKey aliceDesKey = aliceKeyAgree.generateSecret("DES");

        /*
         * Bob encrypts, using DES in ECB mode
         */
        Cipher bobCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        bobCipher.init(Cipher.ENCRYPT_MODE, bobDesKey);

        byte[] cleartext = "This is just an example".getBytes();
        byte[] ciphertext = bobCipher.doFinal(cleartext);

        /*
         * Alice decrypts, using DES in ECB mode
         */
        Cipher aliceCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        aliceCipher.init(Cipher.DECRYPT_MODE, aliceDesKey);
        byte[] recovered = aliceCipher.doFinal(ciphertext);

        if (!java.util.Arrays.equals(cleartext, recovered))
            throw new Exception("DES in CBC mode recovered text is " +
              "different from cleartext");
        System.out.println("DES in ECB mode recovered text is " +
            "same as cleartext");

        /*
         * Bob encrypts, using DES in CBC mode
         */
        bobCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        bobCipher.init(Cipher.ENCRYPT_MODE, bobDesKey);

        cleartext = "This is just an example".getBytes();
        ciphertext = bobCipher.doFinal(cleartext);
        // Retrieve the parameter that was used, and transfer it to Alice in
        // encoded format
        byte[] encodedParams = bobCipher.getParameters().getEncoded();

        /*
         * Alice decrypts, using DES in CBC mode
         */
        // Instantiate AlgorithmParameters object from parameter encoding
        // obtained from Bob
        AlgorithmParameters params = AlgorithmParameters.getInstance("DES");
        params.init(encodedParams);
        aliceCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        aliceCipher.init(Cipher.DECRYPT_MODE, aliceDesKey, params);
        recovered = aliceCipher.doFinal(ciphertext);

        if (!java.util.Arrays.equals(cleartext, recovered))
            throw new Exception("DES in CBC mode recovered text is " +
              "different from cleartext");
        System.out.println("DES in CBC mode recovered text is " +
            "same as cleartext");
    }

    /*
     * Converts a byte to hex digit and writes to the supplied buffer
     */
    private void byte2hex(byte b, StringBuffer buf) {
        char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
                            '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        int high = ((b & 0xf0) >> 4);
        int low = (b & 0x0f);
        buf.append(hexChars[high]);
        buf.append(hexChars[low]);
    }

    /*
     * Converts a byte array to hex string
     */
    private String toHexString(byte[] block) {
        StringBuffer buf = new StringBuffer();

        int len = block.length;

        for (int i = 0; i < len; i++) {
             byte2hex(block[i], buf);
             if (i < len-1) {
                 buf.append(":");
             }
        }
        return buf.toString();
    }

    /*
     * Prints the usage of this test.
     */
    private void usage() {
        System.err.print("DHKeyAgreement usage: ");
        System.err.println("[-gen]");
    }

    // The 1024 bit Diffie-Hellman modulus values used by SKIP
    private static final byte skip1024ModulusBytes[] = {
        (byte)0xF4, (byte)0x88, (byte)0xFD, (byte)0x58,
        (byte)0x4E, (byte)0x49, (byte)0xDB, (byte)0xCD,
        (byte)0x20, (byte)0xB4, (byte)0x9D, (byte)0xE4,
        (byte)0x91, (byte)0x07, (byte)0x36, (byte)0x6B,
        (byte)0x33, (byte)0x6C, (byte)0x38, (byte)0x0D,
        (byte)0x45, (byte)0x1D, (byte)0x0F, (byte)0x7C,
        (byte)0x88, (byte)0xB3, (byte)0x1C, (byte)0x7C,
        (byte)0x5B, (byte)0x2D, (byte)0x8E, (byte)0xF6,
        (byte)0xF3, (byte)0xC9, (byte)0x23, (byte)0xC0,
        (byte)0x43, (byte)0xF0, (byte)0xA5, (byte)0x5B,
        (byte)0x18, (byte)0x8D, (byte)0x8E, (byte)0xBB,
        (byte)0x55, (byte)0x8C, (byte)0xB8, (byte)0x5D,
        (byte)0x38, (byte)0xD3, (byte)0x34, (byte)0xFD,
        (byte)0x7C, (byte)0x17, (byte)0x57, (byte)0x43,
        (byte)0xA3, (byte)0x1D, (byte)0x18, (byte)0x6C,
        (byte)0xDE, (byte)0x33, (byte)0x21, (byte)0x2C,
        (byte)0xB5, (byte)0x2A, (byte)0xFF, (byte)0x3C,
        (byte)0xE1, (byte)0xB1, (byte)0x29, (byte)0x40,
        (byte)0x18, (byte)0x11, (byte)0x8D, (byte)0x7C,
        (byte)0x84, (byte)0xA7, (byte)0x0A, (byte)0x72,
        (byte)0xD6, (byte)0x86, (byte)0xC4, (byte)0x03,
        (byte)0x19, (byte)0xC8, (byte)0x07, (byte)0x29,
        (byte)0x7A, (byte)0xCA, (byte)0x95, (byte)0x0C,
        (byte)0xD9, (byte)0x96, (byte)0x9F, (byte)0xAB,
        (byte)0xD0, (byte)0x0A, (byte)0x50, (byte)0x9B,
        (byte)0x02, (byte)0x46, (byte)0xD3, (byte)0x08,
        (byte)0x3D, (byte)0x66, (byte)0xA4, (byte)0x5D,
        (byte)0x41, (byte)0x9F, (byte)0x9C, (byte)0x7C,
        (byte)0xBD, (byte)0x89, (byte)0x4B, (byte)0x22,
        (byte)0x19, (byte)0x26, (byte)0xBA, (byte)0xAB,
        (byte)0xA2, (byte)0x5E, (byte)0xC3, (byte)0x55,
        (byte)0xE9, (byte)0x2F, (byte)0x78, (byte)0xC7
    };

    // The SKIP 1024 bit modulus
    private static final BigInteger skip1024Modulus
    = new BigInteger(1, skip1024ModulusBytes);

    // The base used with the SKIP 1024 bit modulus
    private static final BigInteger skip1024Base = BigInteger.valueOf(2);
}

Diffie-Hellman Key Exchange between 3 Parties

/*
 * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.io.*;
import java.math.BigInteger;
import java.security.*;
import java.security.spec.*;
import java.security.interfaces.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;
import com.sun.crypto.provider.SunJCE;

/**
 * This program executes the Diffie-Hellman key agreement protocol
 * between 3 parties: Alice, Bob, and Carol.
 *
 * We use the same 1024-bit prime modulus and base generator that are
 * used by SKIP.
 */

public class DHKeyAgreement3 {

    private DHKeyAgreement3() {}

    public static void main(String argv[]) {
        try {
            DHKeyAgreement3 keyAgree = new DHKeyAgreement3();
            keyAgree.run();
        } catch (Exception e) {
            System.err.println("Error: " + e);
            System.exit(1);
        }
    }

    private void run() throws Exception {

        DHParameterSpec dhSkipParamSpec;

        System.out.println("Using SKIP Diffie-Hellman parameters");
        dhSkipParamSpec = new DHParameterSpec(skip1024Modulus, skip1024Base);

        // Alice creates her own DH key pair
        System.out.println("ALICE: Generate DH keypair ...");
        KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH");
        aliceKpairGen.initialize(dhSkipParamSpec);
        KeyPair aliceKpair = aliceKpairGen.generateKeyPair();

        // Bob creates his own DH key pair
        System.out.println("BOB: Generate DH keypair ...");
        KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH");
        bobKpairGen.initialize(dhSkipParamSpec);
        KeyPair bobKpair = bobKpairGen.generateKeyPair();

        // Carol creates her own DH key pair
        System.out.println("CAROL: Generate DH keypair ...");
        KeyPairGenerator carolKpairGen = KeyPairGenerator.getInstance("DH");
        carolKpairGen.initialize(dhSkipParamSpec);
        KeyPair carolKpair = carolKpairGen.generateKeyPair();

        // Alice initialize
        System.out.println("ALICE: Initialize ...");
        KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH");
        aliceKeyAgree.init(aliceKpair.getPrivate());

        // Bob initialize
        System.out.println("BOB: Initialize ...");
        KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH");
        bobKeyAgree.init(bobKpair.getPrivate());

        // Carol initialize
        System.out.println("CAROL: Initialize ...");
        KeyAgreement carolKeyAgree = KeyAgreement.getInstance("DH");
        carolKeyAgree.init(carolKpair.getPrivate());

        // Alice uses Carol's public key
        Key ac = aliceKeyAgree.doPhase(carolKpair.getPublic(), false);

        // Bob uses Alice's public key
        Key ba = bobKeyAgree.doPhase(aliceKpair.getPublic(), false);

        // Carol uses Bob's public key
        Key cb = carolKeyAgree.doPhase(bobKpair.getPublic(), false);

        // Alice uses Carol's result from above
        aliceKeyAgree.doPhase(cb, true);

        // Bob uses Alice's result from above
        bobKeyAgree.doPhase(ac, true);

        // Carol uses Bob's result from above
        carolKeyAgree.doPhase(ba, true);

        // Alice, Bob and Carol compute their secrets
        byte[] aliceSharedSecret = aliceKeyAgree.generateSecret();
        System.out.println("Alice secret: " + toHexString(aliceSharedSecret));

        byte[] bobSharedSecret = bobKeyAgree.generateSecret();
        System.out.println("Bob secret: " + toHexString(bobSharedSecret));

        byte[] carolSharedSecret = carolKeyAgree.generateSecret();
        System.out.println("Carol secret: " + toHexString(carolSharedSecret));

        // Compare Alice and Bob
        if (!java.util.Arrays.equals(aliceSharedSecret, bobSharedSecret))
            throw new Exception("Alice and Bob differ");
        System.out.println("Alice and Bob are the same");

        // Compare Bob and Carol
        if (!java.util.Arrays.equals(bobSharedSecret, carolSharedSecret))
            throw new Exception("Bob and Carol differ");
        System.out.println("Bob and Carol are the same");
    }

    /*
     * Converts a byte to hex digit and writes to the supplied buffer
     */
    private void byte2hex(byte b, StringBuffer buf) {
        char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
                            '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        int high = ((b & 0xf0) >> 4);
        int low = (b & 0x0f);
        buf.append(hexChars[high]);
        buf.append(hexChars[low]);
    }

    /*
     * Converts a byte array to hex string
     */
    private String toHexString(byte[] block) {
        StringBuffer buf = new StringBuffer();

        int len = block.length;

        for (int i = 0; i < len; i++) {
             byte2hex(block[i], buf);
             if (i < len-1) {
                 buf.append(":");
             }
        }
        return buf.toString();
    }

    /*
     * Prints the usage of this test.
     */
    private void usage() {
        System.err.print("DHKeyAgreement usage: ");
        System.err.println("[-gen]");
    }

    // The 1024 bit Diffie-Hellman modulus values used by SKIP
    private static final byte skip1024ModulusBytes[] = {
        (byte)0xF4, (byte)0x88, (byte)0xFD, (byte)0x58,
        (byte)0x4E, (byte)0x49, (byte)0xDB, (byte)0xCD,
        (byte)0x20, (byte)0xB4, (byte)0x9D, (byte)0xE4,
        (byte)0x91, (byte)0x07, (byte)0x36, (byte)0x6B,
        (byte)0x33, (byte)0x6C, (byte)0x38, (byte)0x0D,
        (byte)0x45, (byte)0x1D, (byte)0x0F, (byte)0x7C,
        (byte)0x88, (byte)0xB3, (byte)0x1C, (byte)0x7C,
        (byte)0x5B, (byte)0x2D, (byte)0x8E, (byte)0xF6,
        (byte)0xF3, (byte)0xC9, (byte)0x23, (byte)0xC0,
        (byte)0x43, (byte)0xF0, (byte)0xA5, (byte)0x5B,
        (byte)0x18, (byte)0x8D, (byte)0x8E, (byte)0xBB,
        (byte)0x55, (byte)0x8C, (byte)0xB8, (byte)0x5D,
        (byte)0x38, (byte)0xD3, (byte)0x34, (byte)0xFD,
        (byte)0x7C, (byte)0x17, (byte)0x57, (byte)0x43,
        (byte)0xA3, (byte)0x1D, (byte)0x18, (byte)0x6C,
        (byte)0xDE, (byte)0x33, (byte)0x21, (byte)0x2C,
        (byte)0xB5, (byte)0x2A, (byte)0xFF, (byte)0x3C,
        (byte)0xE1, (byte)0xB1, (byte)0x29, (byte)0x40,
        (byte)0x18, (byte)0x11, (byte)0x8D, (byte)0x7C,
        (byte)0x84, (byte)0xA7, (byte)0x0A, (byte)0x72,
        (byte)0xD6, (byte)0x86, (byte)0xC4, (byte)0x03,
        (byte)0x19, (byte)0xC8, (byte)0x07, (byte)0x29,
        (byte)0x7A, (byte)0xCA, (byte)0x95, (byte)0x0C,
        (byte)0xD9, (byte)0x96, (byte)0x9F, (byte)0xAB,
        (byte)0xD0, (byte)0x0A, (byte)0x50, (byte)0x9B,
        (byte)0x02, (byte)0x46, (byte)0xD3, (byte)0x08,
        (byte)0x3D, (byte)0x66, (byte)0xA4, (byte)0x5D,
        (byte)0x41, (byte)0x9F, (byte)0x9C, (byte)0x7C,
        (byte)0xBD, (byte)0x89, (byte)0x4B, (byte)0x22,
        (byte)0x19, (byte)0x26, (byte)0xBA, (byte)0xAB,
        (byte)0xA2, (byte)0x5E, (byte)0xC3, (byte)0x55,
        (byte)0xE9, (byte)0x2F, (byte)0x78, (byte)0xC7
    };

    // The SKIP 1024 bit modulus
    private static final BigInteger skip1024Modulus
    = new BigInteger(1, skip1024ModulusBytes);

    // The base used with the SKIP 1024 bit modulus
    private static final BigInteger skip1024Base = BigInteger.valueOf(2);
}

Blowfish Cipher Example

/*
 * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;

/**
 * This program generates a Blowfish key, retrieves its raw bytes, and
 * then reinstantiates a Blowfish key from the key bytes.
 * The reinstantiated key is used to initialize a Blowfish cipher for
 * encryption.
 */

public class BlowfishKey {

    public static void main(String[] args) throws Exception {

        KeyGenerator kgen = KeyGenerator.getInstance("Blowfish");
        SecretKey skey = kgen.generateKey();
        byte[] raw = skey.getEncoded();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish");

        Cipher cipher = Cipher.getInstance("Blowfish");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted =
            cipher.doFinal("This is just an example".getBytes());
    }
}

HMAC-MD5 Example

/*
 * Copyright (c) 1997, 2001, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.security.*;
import javax.crypto.*;

/**
 * This program demonstrates how to generate a secret-key object for
 * HMAC-MD5, and initialize an HMAC-MD5 object with it.
 */

public class initMac {

    public static void main(String[] args) throws Exception {

        // Generate secret key for HMAC-MD5
        KeyGenerator kg = KeyGenerator.getInstance("HmacMD5");
        SecretKey sk = kg.generateKey();

        // Get instance of Mac object implementing HMAC-MD5, and
        // initialize it with the above secret key
        Mac mac = Mac.getInstance("HmacMD5");
        mac.init(sk);
        byte[] result = mac.doFinal("Hi There".getBytes());
    }
}

Reading ASCII Passwords From an InputStream Example

/*
 * @(#)ReadPassword.java  1.1 06/06/07
 *
 * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

import java.util.*;
import java.io.*;
import java.security.*;

public class ReadPassword {
    /**
     * Read a password from the InputStream "in".
     * <p>
     * As Strings are immutable, passwords should be stored as an array
     * of characters, which can be blanked out when no longer needed.
     * <p>
     * If the provided InputStream is the System's Console, this method
     * uses the non-echoing readPassword() method of java.io.Console
     * (new to JDK 6).  If not, a fallback implementation is used.
     * <p>
     * NOTE:  For expository purposes, and because some applications do
     * not understand multi-byte characters, only 8-bit ASCII passwords
     * are handled here.
     * <p>
     * NOTE:  If a SecurityManager is used, the default standard
     * java.policy file found in Sun's JDK (i.e.
     * <java-home>/lib/security/java.policy) allows reading the
     * line.separator property.  If your environment is different, this
     * code will need to be granted the appropriate privilege.
     *
     * @param   in
     *          the InputStream used to obtain the password.
     *
     * @return  A character array containing the password or passphrase,
     *          not including the line-termination characters,
     *          or null if an end of stream has been reached.
     *
     * @throws  IOException
     *          if an I/O problem occurs
     */
    public static final char[] readPassword(InputStream in)
            throws IOException {

        /*
         * If available, directly use the java.io.Console class to
         * avoid character echoing.
         */
        if (in == System.in && System.console() != null) {
            // readPassword returns "" if you just print ENTER,
            return System.console().readPassword();
        }

        /*
         * If a console is not available, read the InputStream
         * directly.  This approach may cause password echoing.
         *
         * Since different operating systems have different End-Of-Line
         * (EOL) sequences, this algorithm should allow for
         * platform-independent implementations.  Typical EOL sequences
         * are a single line feed ('\n'), or a carriage return/linefeed
         * combination ('\r\n').  However, some OS's use a single
         * a carriage return ('\r'), which complicates portability.
         *
         * Since we may not have the ability to push bytes back into the
         * InputStream, another approach is used here.  The javadoc for
         * <code>java.lang.System.getProperties()</code> specifies that
         * the set of system properties will contain a system-specific
         * value for the "line.separator".  Scan for this character
         * sequence instead of hard-coding a particular sequence.
         */

        /*
         * Enclose the getProperty in a doPrivileged block to minimize
         * the call stack permission required.
         */
        char [] EOL = AccessController.doPrivileged(
            new PrivilegedAction<char[]>() {
                public char[] run() {
                    String s = System.getProperty("line.separator");
                    // Shouldn't happen.
                    if (s == null) {
                        throw new RuntimeException(
                            "line.separator not defined");
                    }
                    return s.toCharArray();
                }
            });

        char [] buffer = new char[128];
        try {
            int len = 0;                // len of data in buffer.
            boolean done = false;       // found the EOL sequence
            int b;                      // byte read

            while (!done) {
                /*
                 * realloc if necessary
                 */
                if (len >= buffer.length) {
                    char [] newbuffer = new char[len + 128];
                    System.arraycopy(buffer, 0, newbuffer, 0, len);
                    Arrays.fill(buffer, ' ');
                    buffer = newbuffer;
                }

                /*
                 * End-of-Stream?
                 */
                if ((b = in.read()) == -1) {
                    // Return as much as we have, null otherwise.
                    if (len == 0) {
                        return null;
                    }
                    break;
                } else {
                    /*
                     * NOTE:  In the simple PBE example here,
                     * only 8 bit ASCII characters are handled.
                     */
                    buffer[len++] = (char) b;
                }

                /*
                 * check for the EOL sequence.  Do we have enough bytes?
                 */
                if (len >= EOL.length) {
                    int i = 0;
                    for (i = 0; i < EOL.length; i++) {
                        if (buffer[len - EOL.length + i] != EOL[i]) {
                            break;
                        }
                    }
                    done = (i == EOL.length);
                }
            }

            /*
             * If we found the EOL, strip the EOL chars.
             */
            char [] result = new char[done ? len - EOL.length : len];
            System.arraycopy(buffer, 0, result, 0, result.length);

            return result;
        } finally {
            /*
             * Zero out the buffer.
             */
            if (buffer != null) {
                Arrays.fill(buffer, ' ');
            }
        }
    }
}
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface org.w3c.dom.css.CSS2Properties (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.css.CSS2Properties

No usage of org.w3c.dom.css.CSS2Properties
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.css.CSSCharsetRule (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.css.CSSCharsetRule

No usage of org.w3c.dom.css.CSSCharsetRule
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.css.CSSFontFaceRule (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.css.CSSFontFaceRule

No usage of org.w3c.dom.css.CSSFontFaceRule
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.css.CSSImportRule (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.css.CSSImportRule

No usage of org.w3c.dom.css.CSSImportRule
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.css.CSSMediaRule (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.css.CSSMediaRule

No usage of org.w3c.dom.css.CSSMediaRule
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.css.CSSPageRule (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.css.CSSPageRule

No usage of org.w3c.dom.css.CSSPageRule
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.css.CSSPrimitiveValue (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.css.CSSPrimitiveValue

  • Packages that use CSSPrimitiveValue
    Package Description
    org.w3c.dom.css

    • Uses of CSSPrimitiveValue in org.w3c.dom.css

      Methods in org.w3c.dom.css that return CSSPrimitiveValue
      Modifier and Type Method and Description
      CSSPrimitiveValue RGBColor.getBlue()
      This attribute is used for the blue value of the RGB color.
      CSSPrimitiveValue Rect.getBottom()
      This attribute is used for the bottom of the rect.
      CSSPrimitiveValue RGBColor.getGreen()
      This attribute is used for the green value of the RGB color.
      CSSPrimitiveValue Rect.getLeft()
      This attribute is used for the left of the rect.
      CSSPrimitiveValue RGBColor.getRed()
      This attribute is used for the red value of the RGB color.
      CSSPrimitiveValue Rect.getRight()
      This attribute is used for the right of the rect.
      CSSPrimitiveValue Rect.getTop()
      This attribute is used for the top of the rect.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.css.CSSRule (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.css.CSSRule

  • Packages that use CSSRule
    Package Description
    org.w3c.dom.css

    • Uses of CSSRule in org.w3c.dom.css

      Subinterfaces of CSSRule in org.w3c.dom.css
      Modifier and Type Interface and Description
      interface  CSSCharsetRule
      The CSSCharsetRule interface represents a @charset rule in a CSS style sheet.
      interface  CSSFontFaceRule
      The CSSFontFaceRule interface represents a @font-face rule in a CSS style sheet.
      interface  CSSImportRule
      The CSSImportRule interface represents a @import rule within a CSS style sheet.
      interface  CSSMediaRule
      The CSSMediaRule interface represents a @media rule in a CSS style sheet.
      interface  CSSPageRule
      The CSSPageRule interface represents a @page rule within a CSS style sheet.
      interface  CSSStyleRule
      The CSSStyleRule interface represents a single rule set in a CSS style sheet.
      interface  CSSUnknownRule
      The CSSUnknownRule interface represents an at-rule not supported by this user agent.
      Methods in org.w3c.dom.css that return CSSRule
      Modifier and Type Method and Description
      CSSRule CSSStyleSheet.getOwnerRule()
      If this style sheet comes from an @import rule, the ownerRule attribute will contain the CSSImportRule.
      CSSRule CSSStyleDeclaration.getParentRule()
      The CSS rule that contains this declaration block or null if this CSSStyleDeclaration is not attached to a CSSRule.
      CSSRule CSSRule.getParentRule()
      If this rule is contained inside another rule (e.g.
      CSSRule CSSRuleList.item(int index)
      Used to retrieve a CSS rule by ordinal index.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.css.CSSRuleList (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.css.CSSRuleList

  • Packages that use CSSRuleList
    Package Description
    org.w3c.dom.css

    • Uses of CSSRuleList in org.w3c.dom.css

      Methods in org.w3c.dom.css that return CSSRuleList
      Modifier and Type Method and Description
      CSSRuleList CSSStyleSheet.getCssRules()
      The list of all CSS rules contained within the style sheet.
      CSSRuleList CSSMediaRule.getCssRules()
      A list of all CSS rules contained within the media block.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.css.CSSStyleDeclaration (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.css.CSSStyleDeclaration

  • Packages that use CSSStyleDeclaration
    Package Description
    org.w3c.dom.css

    • Uses of CSSStyleDeclaration in org.w3c.dom.css

      Methods in org.w3c.dom.css that return CSSStyleDeclaration
      Modifier and Type Method and Description
      CSSStyleDeclaration ViewCSS.getComputedStyle(Element elt, String pseudoElt)
      This method is used to get the computed style as it is defined in [CSS2].
      CSSStyleDeclaration DocumentCSS.getOverrideStyle(Element elt, String pseudoElt)
      This method is used to retrieve the override style declaration for a specified element and a specified pseudo-element.
      CSSStyleDeclaration ElementCSSInlineStyle.getStyle()
      The style attribute.
      CSSStyleDeclaration CSSStyleRule.getStyle()
      The declaration-block of this rule set.
      CSSStyleDeclaration CSSPageRule.getStyle()
      The declaration-block of this rule.
      CSSStyleDeclaration CSSFontFaceRule.getStyle()
      The declaration-block of this rule.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.css.CSSStyleRule (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.css.CSSStyleRule

No usage of org.w3c.dom.css.CSSStyleRule
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.css.CSSStyleSheet (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.css.CSSStyleSheet

  • Packages that use CSSStyleSheet
    Package Description
    org.w3c.dom.css

    • Uses of CSSStyleSheet in org.w3c.dom.css

      Methods in org.w3c.dom.css that return CSSStyleSheet
      Modifier and Type Method and Description
      CSSStyleSheet DOMImplementationCSS.createCSSStyleSheet(String title, String media)
      Creates a new CSSStyleSheet.
      CSSStyleSheet CSSRule.getParentStyleSheet()
      The style sheet that contains this rule.
      CSSStyleSheet CSSImportRule.getStyleSheet()
      The style sheet referred to by this rule, if it has been loaded.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.css.CSSUnknownRule (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.css.CSSUnknownRule

No usage of org.w3c.dom.css.CSSUnknownRule
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.css.CSSValue (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.css.CSSValue

  • Packages that use CSSValue
    Package Description
    org.w3c.dom.css

    • Uses of CSSValue in org.w3c.dom.css

      Subinterfaces of CSSValue in org.w3c.dom.css
      Modifier and Type Interface and Description
      interface  CSSPrimitiveValue
      The CSSPrimitiveValue interface represents a single CSS value .
      interface  CSSValueList
      The CSSValueList interface provides the abstraction of an ordered collection of CSS values.
      Methods in org.w3c.dom.css that return CSSValue
      Modifier and Type Method and Description
      CSSValue CSSStyleDeclaration.getPropertyCSSValue(String propertyName)
      Used to retrieve the object representation of the value of a CSS property if it has been explicitly set within this declaration block.
      CSSValue CSSValueList.item(int index)
      Used to retrieve a CSSValue by ordinal index.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.css.CSSValueList (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.css.CSSValueList

No usage of org.w3c.dom.css.CSSValueList
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Customizing the RIA Loading Experience

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Customizing the Rich Internet Application Loading Experience

  • The RIA Loading Experience
  • The RIA Loading Process
  • Issues to Consider
  • Customization Options
    • Adding a Splash Screen for an Applet
    • Implementing a Customized Loading Progress Indicator
      • The javax.jnlp.DownloadServiceListener Interface
      • Constructors of the Loading Progress Indicator Class
      • Methods of the javax.jnlp.DownloadServiceListener Interface
      • Specifying the Custom Progress Indicator in the JNLP File
      • How the RIA Software Communicates Progress
  • Best Practices and Tips
  • Resources

The RIA Loading Experience

Java Rich Internet applications (RIAs) are downloaded over the internet and displayed to the end user. The speed of the download may vary depending on various criteria such as the size of the RIA JAR file, any external dependencies, and the speed of the internet connection.

When the RIA is being downloaded, by default, the RIA software (Java Plug-in and Java Web Start software) will display the standard progress indicators, such as the spinning Java logo and progress bars. End users may get impatient when confronted with large downloads. With improvements in RIA software technology in the Java SE 6 update 18 and Java SE 6 update 21 releases, you can keep the end user engaged by providing a creative, captivating, and meaningful RIA loading experience. You can customize the RIA loading experience in several ways as described next.

  • By providing a splash screen
  • By creating a customized loading progress indicator
  • By leveraging one progress indicator to reflect progress of RIA download and the loading of RIA-specific data

You can also use a combination of the above options to accomodate older versions of the Java Runtime Environment (JRE) software on the client machine.

Note: Certain customization options are specific to applets or to Java Web Start applications. Such cases will be identified in this topic.

The RIA Loading Process

This section describes the process by which RIAs are loaded.

RIA software initiates a series of steps to download, validate, and execute a RIA. The RIA loading process can be broadly broken down into the following stages. RIA software provides varying levels of progress-related feedback during these stages.

  • Initialization – During this stage, RIA software performs an assessment of the resources required to launch the RIA. The amount of work required to download, validate, and execute the RIA is indeterminate at this time.
  • Loading and validation – RIA software downloads the required resources (JAR files) over the Internet, if necessary. If the RIA has been previously cached, RIA software loads the resources from the local cache. RIA software validates the resources. Deterministic feedback is communicated by the RIA software during the resource loading and validation process. Deterministic feedback implies that percent completion rates are calculated and communicated by the RIA software.
  • RIA Execution – During this stage, RIA software executes the RIA. The RIA is now fully functional. The RIA can load application-specific data at this time.

Customization Options

Adding a Splash Screen

The simplest way to customize a RIA's loading experience is to provide a splash screen. Specify the image that should be displayed in the splash screen. No changes are required in the RIA itself. RIA software displays the splash screen when the RIA is being loaded and hides it when the RIA's resources have been downloaded and validated. See the following topics for more information:

  • Creating a Splash Screen for an Applet topic in the Java Tutorials to view an example
  • Java Web Start FAQ and JNLP FIle Syntax for information about adding a splash screen for a Java Web Start application

Implementing a Customized Loading Progress Indicator

You can replace the default loading progress indicator with a custom implementation that provides regular feedback about how the RIA is loading. Don't feel constrained by rectangular boxes or the use of the Swing JProgressBar component. You can develop a customized loading progress indicator that is meaningful to your RIA or web site. The loading progress indicator can use visual or non-visual means to keep the end user interested and engaged while the RIA is loading in the background.

See Customizing the Loading Experience topic in the Java Tutorials for step-by-step instructions and detailed examples. A few screenshots of loading progress indicators are shown next.

Default loading progress indicator for Java Web Start application

Default Progress Indicator for Java Web Start applications

Customized loading progress indicator for Java Web Start application

Customized Progress Indicator for Java Web Start applications

Customized loading progress indicator for the Reversi JavaFX applet (black balls turn white as loading progresses)

Customized Progress Indicator for Reversi application

The following features enable varied customizations of the loading progress indicator for a RIA that is deployed by using JNLP technology:

  • The customized loading progress indicator can provide deterministic or non-deterministic feedback.
  • The customized loading progress indicator can provide visual or non-visual cues to communicate progress.
  • A single loading progress indicator can be developed to support applets and Java Web Start applications.
  • Multiple loading progress indicators can be defined as Java Network Launch Protocol (JNLP) extensions. The loading progress indicator specified in the RIA's main JNLP file takes precedence (if one is specified). You should specify which extension should be displayed to avoid undeterministic behavior.
  • The customized loading progress indicator can be leveraged to also display progress when loading application-specific data. For example, if a RIA invokes web services to load initial application data, you can use the progress range of 0 - 75% to indicate status of RIA download, and use the range of 76% - 100% to indicate progress of a web service invocation that fetches application data.
  • Loading progress indicators for applets can perform the following operations:
    • They can receive a reference to an instance of the java.applet.AppletStub class. This allows the loading progress indicator code to access the java.applet.AppletContext object to retrieve the applet's parameters.
    • They can invoke JavaScript code in the applet's parent web page. A reference to the window can be retrieved as shown next.
      JSObject window = JSObject.getWindow(null);
window.call("someJavaScriptFunction", args);

The next few paragraphs describe technical details about implementing a loading progress indicator.

The javax.jnlp.DownloadServiceListener Interface

A loading progress indicator class should implement the javax.jnlp.DownloadServiceListener interface.

Constructors of the Loading Progress Indicator Class

Specify the following constructors in the loading progress indicator class. The RIA software will invoke the appropriate constructor depending on the capabilities of the JRE software on the client machine. In some cases, RIA software may not instantiate the loading progress indicator class if all resources are up-to-date.

  • Constructor without any parameters – This constructor should be specified in the loading progress indicator class for a Java Web Start application. This constructor can also be specified in the loading progress indicator class for an applet. If the RIA software invokes this constructor, the loading progress indicator UI will be displayed in a top level window such as a javax.swing.JFrame object.
  • Constructor with one parameter – This constructor has one parameter of type java.lang.Object. The Object argument can be typecast to an instance of the java.awt.Container class. This constructor is relevant to loading progress indicators for applets. If the RIA software (in this case, Java Plug-in software) invokes this constructor, the loading progress indicator UI will be displayed in the applet's container.
  • Constructor with two parameters – This constructor has two parameters of type java.lang.Object. The first Object argument can be typecast to an instance of the java.awt.Container class. The second Object argument can be typecast to an instance of the java.applet.AppletStub class. If the RIA software (in this case, Java Plug-in software) invokes this constructor, the loading progress indicator UI will be displayed in the applet's container. The loading progress indicator can access the java.applet.AppletContext object to customize the loading progress indicator further. This constructor is relevant to loading progress indicators for applets.

    When specifying the constructor with two parameters, it is better to also specify the single-parameter constructor to accomodate older versions of the client JRE software. The constructor with two parameters is invoked only when the client JRE software version is at least Java SE 6 update 21.

Methods of the javax.jnlp.DownloadServiceListener Interface

The loading progress indicator class should implement the following methods of the interface to receive and convey the latest progress information.

  • progress(URL url, String version, long readSoFar, long total, int overallPercent)
  • upgradingArchive(java.net.URL url, java.lang.String version, int patchPercent, int overallPercent)
  • validating(java.net.URL url, java.lang.String version, long entry, long total, int overallPercent) – When the loading progress indicator class is instantiated, this method is always invoked with an overallPercent value of 100.

Update progress information in the loading progress indicator based on the overallPercent values received in these methods.

Specifying the Custom Progress Indicator in the JNLP File

Include the following information in the RIA's Java Network Launch Protocol (JNLP) file to specify a loading progress indicator:

  • download="progress" attribute to indicate which JAR file contains the loading progress indicator class
  • progress-class attribute containing fully qualified name of the loading progress indicator class. This attribute can be defined as a part of the <applet-desc>, <application-desc>, or <component-desc> depending on how the RIA and the loading progress indicator are deployed.

A sample JNLP file for an applet is shown next.

<jnlp spec="1.0+" codebase="" href="">
...
  <resources>
    ...
    <jar href="MyApplet.jar" main="true" />
    <jar href="CustomProgressIndicator.jar" download="progress" />
  </resources>

  <applet-desc
     name="MyFavoriteApplet"
     main-class="myAppletPackage.MyFavoriteApplet"
     progress-class="myCustomProgressPackage.MyCustomProgressIndicator"
     width="600"
     height="200">
  </applet-desc>
...
</jnlp>

How the RIA Software Communicates Progress

RIA software communicates progress information as follows:

  • RIA software instantiates loading progress indicator, if necessary. In some cases, when all resources are cached and up-to-date, the loading progress indicator may not be instantiated at all.
  • RIA software invokes the progress, upgradingArchive, validating methods several times with increasing values of overallPercent.
  • In some cases, when the resources are already cached and validated, RIA software may just invoke the constructor followed by a 100% completion message.
  • RIA software will always send a 100% completion message to the loading progress indicator.

Best Practices and Tips

  • When deciding on an approach to customize the RIA loading experience, consider the capabilities of older versions of client JRE software. You can provide a range of increasingly sophisticated implementations depending on the capabilities of the client JRE software and other criteria as described next.
    • Specify a splash screen that can be displayed for applets when the client JRE software version is at least Java SE 6 update 10.
    • Specify a customized loading progress indicator that can be displayed when the client JRE software version is at least Java SE 6 update 18.
  • Consider the fact that a splash screen or loading screen may not be displayed at all when a RIA is partially or completely cached.
  • When developing a customized loading progress indicator, consider the following items:
    • Keep the size of the loading progress indicator JAR file small. RIA resources are downloaded concurrently. If the loading progress indicator JAR file is large, then it may be downloaded at approximately the same time as other resources. In this case, the loading progress indicator may be displayed for a very short time or may not be displayed at all.
    • Limit the amount of resources required by the loading progress indicator. Avoid using ImageIO or service lookups as this may cause other resources to be downloaded.
    • A loading progress indicator can use the same top level window as the Java Web Start application itself. In this case, limit the amount of resources that are used when the application's constructor is invoked. Specify resource lookups in the application's main method instead.
    • A loading progress indicator can be integrated into the applet's UI. In this case, create a top level container, such as a javax.swing.JPanel object, and add it to the surfaceContainer object described previously. After the applet's resources have been completely downloaded, remove the top level container from the surfaceContainer object and add it to the applet itself.
    • A signed loading progress indicator implementation may be best for a signed RIA. In this case, security warnings would be displayed and accepted early on and progress can be updated without further interruptions.

Resources

  • Customizing the Loading Experience topic in the Java Tutorials for step-by-step instructions and examples.
  • Client JRE Capabilities - Quick Reference
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Debugger Support

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

< Contents

Debugging Support

This section covers the following topics:

  • How to Debug Applets in Java Plug-in
  • Java Console
  • Java Plug-in Trace File
  • javaplugin.trace property
  • java.security.debug property
  • Documentation
  • Isolating Bugs
  • Submitting Bug Reports
  • Submitting Feature Requests
  • Java Plug-in Feedback Alias

The purpose of this document is to simplify the debugging of applets. It provides techniques and suggestions for developing applets in Java Plug-in and describes some common errors encountered in applet development.

How to Debug Applets in Java Plug-in

Applets should be debugged using the java debugger utility jdb. Also make sure to compile your .java files with -g option with javac. To begin debugging your applet:

  1. Open Java Control Panel. Click Java > View. Specify the following parameters in the Java Runtime Parameters with each parameter separated by a comma as follows:
    -agentlib:jdwp=transport=dt_shmem,address=jdbconn,server=y,suspend=n

    See JPDA Connection and Invocation for the details on the possible runtime parameters for debugging.

  2. Start Internet Explorer or Mozilla browser and load the page which contains the applet to be debugged. Make sure the applet code has been compiled with -g option of javac.
  3. Run the command jdb -attach <address> in a DOS command prompt. <address> is the name mentioned in the step. For example, if <address> is jdbconn, you will run the command as
                     jdb -attach jdbconn
    To learn more about the Java Debugger (jdb), see The Java Debugger.
  4. Once the jdb is attached to the VM, you can set up breakpoints in the applet.
  5. When the applet in the browser reaches the breakpoint, it will stop executing, and you will see the debugger waiting for your input to continue debugging.

When debugging applets in Java Plug-in, make sure that only one instance of the browser is being used for debugging using the same connection address at the same time. Otherwise, it will result in a conflict, since the Java Runtime for each instance of the browser will try to gain exclusive access to the connection address. To debug applets in both Internet Explorer and supported Mozilla browsers, run either Internet Explorer or supported Mozilla browsers with Java Plug-in—but not both at the same time.

Debugging applets in Java Plug-in with Active Desktop is discouraged because an instance of Internet Explorer will always be running in the desktop process during the lifetime of the user session.

You can use other debuggers from IDEs like Borlands JBuilder or Symantec's VisualCafe, instead of jdb. To use these debuggers, you will need to change the project option in these IDEs to attach Java Plug-in in the browser process on the same machine or remote machine. Different Java Runtime Parameters may also be required in the Java Control Panel. For more information, refer Java debugger or IDE manuals.

Java Console

Java Console is a simple console window for redirecting all the System.out and System.err messages. The console window is disabled by default. It can be enabled from the Java Control Panel or the task bar. If the console is enabled, you will see the console window appear when Java Plug-in is used in the browser. For more information on Java Console see Java Console documentation.

For information on Java Console see the Java Console section of the Deployment Guide.

Java Plug-in Trace File

The Java Plug-in trace file records all the debug, System.out, and System.err messages. The trace file is disabled by default but is automatically enabled when the Java Console is enabled. The trace file is located by default at C:\Documents and Settings\<username>\Application Data\Sun\Java\Deployment\log in the user.dir. The trace file has the naming convention .plugin<version>.trace where <version> indicates the version of Java installed on the system.

The user.dir directory contains various log and trace files. In Windows 2000 and Windows XP this file is located at the following location:
C:\Documents and Settings\<username>\Application Data\Sun\Java\Deployment.

The Application Data folder and its contents are hidden by default in Windows.

javaplugin.trace property

This property controls whether Java Plug-in prints its trace messages during execution. This is useful to applet developers to determine what is occuring within Java Plug-in. To enable tracing follow the steps given below:

  • Open Java Control Panel
  • Click Advanced > Debugging
  • Select Enable Tracing checkbox .

java.security.debug property

This property controls whether the security system of the Java Runtime Environment prints its trace messages during execution. This is usful when a security exception is thrown in an applet or when a signed applet is not working. The following options are supported:

  • access — print all checkPermission results
  • jar — print jar verification information
  • policy — print policy information
  • scl — print permissions SecureClassLoader assigns

The following options can be used with access:

  • stack — include stack trace
  • domain — dumps all domains in context
  • failure — before throwing exception, dump the stack and domain that didn't have permission

For example, to print all checkPermission results and dump all domains in context, perform the following actions:

  • Open Java Control Panel
  • Click Java > View. The Java Runtime Settings dialog box is displayed.
  • Type -Djava.security.debug=access:stack in the Java Runtime Parameters field.

Documentation

Java Plug-in provides a rich set of documentation to help developers use the various features of Java Plug-in. The documentation includes a FAQ, which includes some of the most frequently asked questions by developers. Make sure you read and understand these documents before applet development, as it may save you hundreds of hours in debugging.

Isolating Bugs

Although Java Plug-in provides the Java 2 Runtime Environment within Internet Explorer and supported Mozilla browsers, most of the facilities are provided by the Java 2 Runtime itself, rather than by Java Plug-in. Therefore, if a problem occurs in Java Plug-in, it may be either a problem in Java Plug-in, the Java 2 Runtime itself or a user error. It is extremely important to determine where bugs originate, as it will affect the speed of bug evaluation and fixing. Here are some suggestions for isolating bugs:

  1. Run the applets in both Internet Explorer and supported Mozilla browsers through Java Plug-in.
  2. Run the applets in appletviewer. Java Plug-in is mainly derived from appletviewer and has inherited problems from appletviewer as well. This step should be performed only if the applet doesn't require specific browser facilities that Java Plug-in provides, like HTTPS or RSA signing.
  3. If the applet fails in appletviewer, it is likely the problem is in the Java 2 Runtime Environment—and not in Java Plug-in.
  4. If the applet fails in only one of the browsers, IE or supported Mozilla browsers, it is likely a Java Plug-in problem.
  5. If the applet fails in both browsers but not appletviewer, it could be either a Java Plug-in problem or user error. Please examine the applet code to see if it makes any assumptions about the execution environment. For example, in appletviewer the current directory is set to the current directory in the shell when appletviewer is launched, whereas the current directory in Java Plug-in may be set to the browser's directory. Therefore, loading resources from the current directory may work in appletviewer but not in Java Plug-in.
  6. Try to reproduce the problem on other machines or platforms. In some cases, the root of the problem may be in the machine configuration, e.g., an improper DNS setup.
  7. If you have identified the problems in the Java 2 Runtime Environment or Java Plug-in, please follow the instructions in the next section to submit a bug report to the appropriate product categories.

Submitting Bug Reports

To submit a bug report, go to the Java Development Connection's Bug Database . Before submitting a bug, search the Bug Database to determine if the bug has already been reported. In some cases, a workaround may also have been suggested. If the bug is not already reported, submit a new bug report to the Java Plug-in team. In the bug report, include the following information:

  • Complete description of the problem and step-by-step instructions for reproducing it;
  • Error messages captured by Java Console or trace file;
  • Proxy configuration information, e.g., auto proxy configuration with proxy configuration file attached;
  • Browser and platform information, e.g., supported Mozilla browsers on Win 2000;
  • A test case demonstrating the problem;
  • Specify whether the problem occurs in other browsers and appletviewer;
  • Specify any workaround available;
  • Specify personal information—your name and email address—so you may be contacted if additional information is required.

Submitting Feature Requests

To submit a feature request, do so through the Report A Bug or Request a Feature page.In the feature request, please make sure the following information is included:

  • Complete description of the requested feature;
  • How this feature will improve the quality of your product or Java Plug-in in general.

Java Plug-in Feedback Alias

The purpose of the Java Plug-in Feedback alias, java-plugin-feedback@sun.com, is for customers to provide feedback on product features and the product in general. This alias is not intended for bug report submission. To submit a bug report, please follow the instructions given above.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java(TM) Rich Internet Applications Decision Guide

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Rich Internet Applications Decision Guide

Rich Internet Applications Development and Deployment > Rich Internet Applications Decision Guide

Applet or Java Web Start Application?

Both applets and Java Web Start applications are rich internet applications (RIAs). RIAs are easier to distribute than standard applications, because they're launched over the web. They're also more secure--they can only access the user's system in highly controlled ways, unless and until the developer signs the code and the user accepts the security certificate. (On the other hand, extended access to the user's system may require that certificate--something a standard application doesn't need).

Here's a table that summarizes the differences:

Feature Applet Java Web Start
Java version

New Plug-in:

Individual applets may specify the exact version, or version range, of the Java platform it will use. The new Java Plug-in (released in Java SE 6 update 10) supports both static version requests (such as "5.0 update 9") and family version requests (such as "5.0 family"), and supports several backward compatibility mechanisms such as static and family ClassIDs in Internet Explorer. See Applet Deployment parameters for details.

Old Plug-in:

Java Plug-in can run only the version of Java with which it was distributed. This means that to take advantage of the latest features in Java Plug-in, you must also use the latest version of Java. Further, recent changes in the Deployment Security Policy require that only the latest version deployed on the client machine be used. This is usually not a problem, since versions of Java are generally forward compatible.
For cases where compatibility between major releases is an issue, we have also provided a feature called the Family ClassID (for Microsoft Internet Explorer only).

Java Web Start will also be used only from the latest Java version installed on a system, but the version of Java Web Start run is independent of the version of the Java platform used. A Java Web Start application can specify the exact version, or version range, of the Java platform that it will use.
Cookies

Java Plug-in applets run in the same session as the browser, and so have access to both "persistent" cookies and "session" cookies already stored in the browser session.

Java Web Start runs outside the browser process. It can access "persistent" cookies stored by the browser (it does this by using the WinINet API on Windows), but has no access to "session" cookies unless set in that application using the java.net.CookieManager and java.net.CookieHandler API's.
Browser Interactions

Java Plug-in includes the ability for applets to interact with the current browser session using the Common DOM API, Java to JavaScript, and JavaScript to Java communications

Java Web Start is limited to invoking the default browser to display specific URL's (see JNLP API).
Java Runtime

New Plug-in:

An applet may specify Java Runtime parameters used to launch that particular applet instance, without affecting the parameters used to launch other applets. Specifying Java Runtime parameters via the Java Control Panel is also supported for backward compatibility purposes. See Determining final deployment information for details on how Java Runtime parameters are reconciled.

Old Plug-in:

Java Plug-in shares one Java Runtime Environment among multiple Java applets. As such, no applet can have control over the startup parameters of the JRE (Java Runtime parameters). Java Runtime parameters must be set by the user (for all applets) in the Java Control Panel.

Java Web Start applications have (limited) control over the Java Runtime parameters that is used to launch that application.
JNLP API

Applets launched using Java Network Launching Protocol (JNLP) have access to JNLP API which allows unsigned applications access to persistent storage, download control, file I/O, and more.

Java Web Start includes access to the JNLP API,
Shortcuts

Applets cannot create shortcuts.

Java Web Start applications can install shortcuts that allow the application to be rerun, either online or offline, independent of the browser.

Other differences

There are several other minor differences caused by need to maintain compatibility with earlier versions. For further information on the specific differences between Java Web Start and Java Plug-in can be found in the Migration Guide.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.mirror.declaration.Declaration (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.declaration.Declaration

  • Packages that use Declaration
    Package Description
    com.sun.mirror.apt
    Classes used to communicate information between annotation processors and an annotation processing tool.
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of Declaration in com.sun.mirror.apt

      Methods in com.sun.mirror.apt that return types with arguments of type Declaration
      Modifier and Type Method and Description
      Collection<Declaration> AnnotationProcessorEnvironment.getDeclarationsAnnotatedWith(AnnotationTypeDeclaration a)
      Deprecated.
      Returns the declarations annotated with the given annotation type.

    • Uses of Declaration in com.sun.mirror.declaration

      Subinterfaces of Declaration in com.sun.mirror.declaration
      Modifier and Type Interface and Description
      interface  AnnotationTypeDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in TypeElement.
      interface  AnnotationTypeElementDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in ExecutableElement.
      interface  ClassDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in TypeElement.
      interface  ConstructorDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in ExecutableElement.
      interface  EnumConstantDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in VariableElement.
      interface  EnumDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in TypeElement.
      interface  ExecutableDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is ExecutableElement.
      interface  FieldDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in VariableElement.
      interface  InterfaceDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in TypeElement.
      interface  MemberDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is Element.
      interface  MethodDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in ExecutableElement.
      interface  PackageDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is PackageElement.
      interface  ParameterDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in VariableElement.
      interface  TypeDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in TypeElement.
      interface  TypeParameterDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is TypeParameterElement.
      Methods in com.sun.mirror.declaration that return Declaration
      Modifier and Type Method and Description
      Declaration TypeParameterDeclaration.getOwner()
      Deprecated.
      Returns the type, method, or constructor declaration within which this type parameter is declared.

    • Uses of Declaration in com.sun.mirror.util

      Methods in com.sun.mirror.util with type parameters of type Declaration
      Modifier and Type Method and Description
      <D extends Declaration>
      Collection<D>             		DeclarationFilter.filter(Collection<? extends Declaration> decls, Class<D> resType)
      Deprecated.
      Returns the declarations matched by this filter, with the result being restricted to declarations of a given kind.
      <D extends Declaration>
      Collection<D>             		DeclarationFilter.filter(Collection<D> decls)
      Deprecated.
      Returns the declarations matched by this filter.
      Methods in com.sun.mirror.util with parameters of type Declaration
      Modifier and Type Method and Description
      boolean DeclarationFilter.matches(Declaration decl)
      Deprecated.
      Tests whether this filter matches a given declaration.
      void SimpleDeclarationVisitor.visitDeclaration(Declaration d)
      Deprecated.
      Visits a declaration.
      void DeclarationVisitor.visitDeclaration(Declaration d)
      Deprecated.
      Visits a declaration.
      Method parameters in com.sun.mirror.util with type arguments of type Declaration
      Modifier and Type Method and Description
      <D extends Declaration>
      Collection<D>             		DeclarationFilter.filter(Collection<? extends Declaration> decls, Class<D> resType)
      Deprecated.
      Returns the declarations matched by this filter, with the result being restricted to declarations of a given kind.
      static DeclarationFilter DeclarationFilter.getFilter(Class<? extends Declaration> kind)
      Deprecated.
      Returns a filter that selects declarations of a particular kind.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.mirror.util.DeclarationFilter (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.mirror.util.DeclarationFilter

  • Packages that use DeclarationFilter
    Package Description
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of DeclarationFilter in com.sun.mirror.util

      Fields in com.sun.mirror.util declared as DeclarationFilter
      Modifier and Type Field and Description
      static DeclarationFilter DeclarationFilter.FILTER_PACKAGE
      Deprecated.
      A filter that selects only package-private (default) declarations.
      static DeclarationFilter DeclarationFilter.FILTER_PRIVATE
      Deprecated.
      A filter that selects only private declarations.
      static DeclarationFilter DeclarationFilter.FILTER_PROTECTED
      Deprecated.
      A filter that selects only protected declarations.
      static DeclarationFilter DeclarationFilter.FILTER_PUBLIC
      Deprecated.
      A filter that selects only public declarations.
      static DeclarationFilter DeclarationFilter.FILTER_PUBLIC_OR_PROTECTED
      Deprecated.
      A filter that selects only public or protected declarations.
      Methods in com.sun.mirror.util that return DeclarationFilter
      Modifier and Type Method and Description
      DeclarationFilter DeclarationFilter.and(DeclarationFilter f)
      Deprecated.
      Returns a filter that selects those declarations selected by both this filter and another.
      static DeclarationFilter DeclarationFilter.getFilter(Class<? extends Declaration> kind)
      Deprecated.
      Returns a filter that selects declarations of a particular kind.
      static DeclarationFilter DeclarationFilter.getFilter(Collection<Modifier> mods)
      Deprecated.
      Returns a filter that selects declarations containing all of a collection of modifiers.
      DeclarationFilter DeclarationFilter.not()
      Deprecated.
      Returns a filter that selects those declarations not selected by this filter.
      DeclarationFilter DeclarationFilter.or(DeclarationFilter f)
      Deprecated.
      Returns a filter that selects those declarations selected by either this filter or another.
      Methods in com.sun.mirror.util with parameters of type DeclarationFilter
      Modifier and Type Method and Description
      DeclarationFilter DeclarationFilter.and(DeclarationFilter f)
      Deprecated.
      Returns a filter that selects those declarations selected by both this filter and another.
      DeclarationFilter DeclarationFilter.or(DeclarationFilter f)
      Deprecated.
      Returns a filter that selects those declarations selected by either this filter or another.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.util.Declarations (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.util.Declarations

  • Packages that use Declarations
    Package Description
    com.sun.mirror.apt
    Classes used to communicate information between annotation processors and an annotation processing tool.

    • Uses of Declarations in com.sun.mirror.apt

      Methods in com.sun.mirror.apt that return Declarations
      Modifier and Type Method and Description
      Declarations AnnotationProcessorEnvironment.getDeclarationUtils()
      Deprecated.
      Returns an implementation of some utility methods for operating on declarations.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.util.DeclarationVisitor (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.util.DeclarationVisitor

  • Packages that use DeclarationVisitor
    Package Description
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of DeclarationVisitor in com.sun.mirror.declaration

      Methods in com.sun.mirror.declaration with parameters of type DeclarationVisitor
      Modifier and Type Method and Description
      void Declaration.accept(DeclarationVisitor v)
      Deprecated.
      Applies a visitor to this declaration.

    • Uses of DeclarationVisitor in com.sun.mirror.util

      Classes in com.sun.mirror.util that implement DeclarationVisitor
      Modifier and Type Class and Description
      class  SimpleDeclarationVisitor
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this class is SimpleElementVisitor6.
      Fields in com.sun.mirror.util declared as DeclarationVisitor
      Modifier and Type Field and Description
      static DeclarationVisitor DeclarationVisitors.NO_OP
      Deprecated.
      A visitor that has no side effects and keeps no state.
      Methods in com.sun.mirror.util that return DeclarationVisitor
      Modifier and Type Method and Description
      static DeclarationVisitor DeclarationVisitors.getDeclarationScanner(DeclarationVisitor pre, DeclarationVisitor post)
      Deprecated.
      Return a DeclarationVisitor that will scan the declaration structure, visiting declarations contained in another declaration.
      static DeclarationVisitor DeclarationVisitors.getSourceOrderDeclarationScanner(DeclarationVisitor pre, DeclarationVisitor post)
      Deprecated.
      Return a DeclarationVisitor that will scan the declaration structure, visiting declarations contained in another declaration in source code order.
      Methods in com.sun.mirror.util with parameters of type DeclarationVisitor
      Modifier and Type Method and Description
      static DeclarationVisitor DeclarationVisitors.getDeclarationScanner(DeclarationVisitor pre, DeclarationVisitor post)
      Deprecated.
      Return a DeclarationVisitor that will scan the declaration structure, visiting declarations contained in another declaration.
      static DeclarationVisitor DeclarationVisitors.getSourceOrderDeclarationScanner(DeclarationVisitor pre, DeclarationVisitor post)
      Deprecated.
      Return a DeclarationVisitor that will scan the declaration structure, visiting declarations contained in another declaration in source code order.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.mirror.util.DeclarationVisitors (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.mirror.util.DeclarationVisitors

No usage of com.sun.mirror.util.DeclarationVisitors
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.type.DeclaredType (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.type.DeclaredType

  • Packages that use DeclaredType
    Package Description
    com.sun.mirror.type
    Interfaces used to model types.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of DeclaredType in com.sun.mirror.type

      Subinterfaces of DeclaredType in com.sun.mirror.type
      Modifier and Type Interface and Description
      interface  AnnotationType
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in DeclaredType.
      interface  ClassType
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in DeclaredType.
      interface  EnumType
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in DeclaredType.
      interface  InterfaceType
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in DeclaredType.
      Methods in com.sun.mirror.type that return DeclaredType
      Modifier and Type Method and Description
      DeclaredType DeclaredType.getContainingType()
      Deprecated.
      Returns the type that contains this type as a member.

    • Uses of DeclaredType in com.sun.mirror.util

      Methods in com.sun.mirror.util that return DeclaredType
      Modifier and Type Method and Description
      DeclaredType Types.getDeclaredType(DeclaredType containing, TypeDeclaration decl, TypeMirror... typeArgs)
      Deprecated.
      Returns the type corresponding to a type declaration and actual arguments, given a containing type of which it is a member.
      DeclaredType Types.getDeclaredType(TypeDeclaration decl, TypeMirror... typeArgs)
      Deprecated.
      Returns the type corresponding to a type declaration and actual type arguments.
      Methods in com.sun.mirror.util with parameters of type DeclaredType
      Modifier and Type Method and Description
      DeclaredType Types.getDeclaredType(DeclaredType containing, TypeDeclaration decl, TypeMirror... typeArgs)
      Deprecated.
      Returns the type corresponding to a type declaration and actual arguments, given a containing type of which it is a member.
      void TypeVisitor.visitDeclaredType(DeclaredType t)
      Deprecated.
      Visits a declared type.
      void SimpleTypeVisitor.visitDeclaredType(DeclaredType t)
      Deprecated.
      Visits a declared type.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Internet/Intranet Deployment of the Java Runtime Environment

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Internet/Intranet Deployment of the Java™ Runtime Environment (JRE™) Software

Internet deployment

If you would like to have your internet customers download Sun JRE to run your applets inside Internet Explorer, you should consider hosting the Java technology logos at your web site.

When users click on any one of these logos, a security dialog box pops-up the screen to confirm whether the user would like to install and run Java Plug-in, signed and distributed by Sun Microsystems. If they agree to install, the browser will download and launch the installer. The user will have to go through a few installer dialogs to successfully install Java Plug-in on their system. After the successfull installation, the browser will display a confirmation message, and the system tray will contain a Java icon, indicating the system is running the Sun JRE.

Intranet deployment

You can distribute Sun JRE to intranet users by hosting the .msi file on an internal web site and asking users to launch the installer through msiexec. The other option is to install the JRE through Active Directory. If you are using Active Directory, you may have to customize the .msi file, which is known as creating a transform.

You can obtain the .msi file for the JRE installer by installing the JRE offline Windows installer. After installation, the .msi file, jre1.6.0.msi, will be available in the directory AppDataFolder\jre1.6.0, where AppDataFolder is the user's "Application Data" folder (typically something like C:\Documents and Settings\username\Application Data), and CLSID is a long string like 7148F0A6-6813-11D6-A77b-00B0D0142010, depending on the release.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Rich Internet Applications Deployment Advice

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java™ Rich Internet Applications Deployment Advice

Rich Internet Applications Development and Deployment > Rich Internet Applications Deployment Advice

Contents

  • Unified Deployment Mechanism - Java Network Launch Protocol
  • Deployment Toolkit Script
  • Deploying Java Plug-in Applets
    • Using Applet Tag Attributes
    • Using JNLP
    • Using Applet Tag and JNLP Parameters
    • Determining final deployment information
  • Deploying Java Web Start Applications
  • Customizing the RIA Loading Experience
  • Pack200 and Version Download
  • Other Deployment Considerations
    • Order of Installation of JRE's
    • ClassLoader and Accessing Resources
    • Lazy Downloading
  • Resources

Unified Deployment Mechanism - Java Network Launch Protocol

Starting in release Java SE 6 update 10, Java Network Launch Protocol (JNLP) provides a unified mechanism for deploying rich internet applications (RIAs – applets and Java Web Start applications). RIAs launched using JNLP have the following powerful capabilities at their disposal:

  • Access to JNLP extensions – Powerful JNLP extensions such as the Java binding to the OpenGL 3D API, the scene graph for the JavaFX run-time, and the NASA World Wind Java planetary and extra-planetary visualization system can now be used from applets and Java Web Start applications.
  • Access to the JNLP APIs – Applets and Java Web Start applications have access to the JNLP APIs to gain user-controlled access to persistent storage (the PersistenceService), lazily-downloaded parts (the DownloadService), the local file system (the FileOpenService and FileSaveService), and much more. See the Java Tutorial lesson, Accessing the Client Using JNLP API for step by step instructions about using JNLP API.
  • Auto-download, version selection and more – Building on the new Java Plug-in's architecture, applets launched via JNLP may utilize all of the features previously available to Java Web Start applications, such as JRE version selection, auto-download of a particular version of the JRE, passing command-line arguments and system properties to the JVM, and much more.

Deployment Toolkit Script

To avoid browser compatibility issues, the Deployment Toolkit script provides JavaScript functions that automatically generate the HTML required to deploy RIAs. Developers should invoke these functions to deploy their solutions in a consistent fashion across various browsers.

The script exposes a single object, named deployJava, which contains the following public functions:

  • createWebStartLaunchButton(jnlp, minimumVersion) - Outputs a launch button for the specified JNLP URL. When clicked, the button will ensure that an appropriate JRE is installed and then launch the JNLP application.

  • createWebStartLaunchButtonEx(jnlp, minimumVersion) - Outputs a launch button for the specified JNLP URL. When clicked, the button will ensure that an appropriate JRE is installed and then launch the JNLP application. The JNLP file does not require a value for the codebase attribute. This function requires that the Java SE 6 update 18 release be present on the client. If the Java SE 6 update 18 release is not present on the client, then the user will be instructed to install the required software.

  • getBrowser() - Returns the name of the browser currently running.

  • getJREs() - Returns an array of currently-installed JRE version strings.

  • installJRE(requestVersion) - Triggers the installation of the specified requestVersion, the latest version matching the specified requestVersion, or the latest JRE.

  • installLatestJRE() - Triggers the installation of the latest JRE

  • isPlugin2() - Determines if the next generation Java Plug-in is the default.

  • isWebStartInstalled(minimumVersion) - Returns true if an installation of Java Web Start of the specified minimumVersion can be detected.

  • launch- Launches JNLP application.

  • runApplet(attributes, parameters, minimumVersion) - Ensures that an appropriate JRE is installed and then runs an applet.

  • setAdditionalPackages(packageList) - Sets additional package list to be used by kernel installer.

  • setInstallerType(type) - Sets the preferred install type : null, online, kernel.

  • versionCheck(version) - Returns true if there is a matching JRE version currently installed (among those detected by the getJREs() function).

  • writeAppletTag(attributes, parameters) - Outputs an applet tag with the specified attributes and parameters. The parameters argument is optional.

See the human readable version of the Deployment Toolkit for a detailed description of these public functions. See the following Java Tutorial lessons for more information about deploying RIAs:

  • Deploying an Applet
  • Deploying a Java Web Start application
  • Deployment In-Depth

Deploying Java Plug-in Applets

In the old Java Plug-in, applets always run with the latest version of JRE installed on a client machine. The old Deployment Security Policy provides more information about this behavior.

With the next generation Java Plug-in introduced in the Java SE 6 update 10 release, you can specify that the Java kernel (core set of Java classes absolutely required by the JRE) or normal online installer be automatically downloaded, if the specified minimum JRE version is not already installed on the client. If the specified minimum JRE version does not exist, the latest version of the JRE is downloaded from www.java.com.

In the case of a Java kernel download, any additional packages may also be specified for download as required by the applet.

Using Applet Tag Attributes

Applets can be deployed via the applet tag. Parameters to configure deployment may be specified as attributes and parameters to the applet tag.

Use the runApplet() function in deployJava to ensure that a minimum Java Runtime Environment is available on a client machine before launching the applet.

<script src="http://www.java.com/js/deployJava.js"></script>
<script>
    var attributes = {codebase:'http://java.sun.com/products/plugin/1.5.0/demos/jfc/Java2D',
                      code:'java2d.Java2DemoApplet.class',
                      archive:'Java2Demo.jar',
                      width:710, height:540} ;
    var parameters = {fontSize:16} ;
    var version = '1.6' ;
    deployJava.runApplet(attributes, parameters, version);
</script>

The above code will launch the Java 2D applet on JRE version 1.6.0 or higher with one parameter (fontSize).

To trigger the installation of Java kernel and additional packages, add the following before the deployJava.runApplet() function:

   deployJava.setInstallerType('kernel');
   // include any required packages as shown below
   deployJava.setAdditionalPackages('javax.swing, javax.xml');

Using JNLP

To deploy applets using JNLP, specify the jnlp_href parameter in the applet tag as follows:

 <script src="http://www.java.com/js/deployJava.js"></script>
 <script>
    var attributes = { code:'java2d.Java2DemoApplet',  width:710, height:540} ;
    var parameters = {jnlp_href: 'java2d.jnlp'} ;
    deployJava.runApplet(attributes, parameters, '1.6');
 </script>

In this example, java2d.jnlp has the following deployment information

 <?xml version="1.0" encoding="UTF-8"?>
 <jnlp href="java2d.jnlp">
     <information>
       <title>Java2D Demo</title>
       <vendor>My Company, Inc.</vendor>
       <offline-allowed />
     </information>
     <resources>
       <j2se version="1.4+"
             href="http://java.sun.com/products/autodl/j2se" />
       <jar href="Java2Demo.jar" main="true" />
       <!-- Specify if using JNLP extensions
                                <extension name="SomeExtension"
                  href="http://some.server.com/some_extension.jnlp" />
                                -->
     </resources>
     <applet-desc
         name="Java2D Demo"
         main-class="java2d.Java2DemoApplet"
         width="710"
         height="540">
     </applet-desc>
 </jnlp>

Using Applet Tag Attributes and JNLP parameters:

To deploy an applet that runs on the old and new Java Plug-ins, specify the applet tag attributes and JNLP parameters as shown in the example below:

var attributes = {codebase:'http://java.sun.com/products/plugin/1.5.0/demos/jfc/Java2D',
                      code:'java2d.Java2DemoApplet.class', archive:'Java2Demo.jar', width:710, height:540} ;
var parameters = {fontSize:16, jnlp_href:'java2d.jnlp'} ;
var version = '1.6' ;
deployJava.runApplet(attributes, parameters, version);

Determining final deployment information

The applet tag and JNLP file provide overlapping mechanisms to specify the same information. For example, width, height, code etc. may be specified both as attributes of the applet tag and in the JNLP file. The following rules are applied to various attributes in order to determine the final deployment information:

  • width and height: These attributes are always taken from the <applet> tag and not from the JNLP file. The assumption is that the browser knows best how big the applet should be on the web page, and only the browser can support page-relative width and height (for example, width="50%").
  • codebase: It is recommended that you either:
    • leave the jnlp tag's codebase attribute empty for both the main and extension JNLP file, allowing the referencing JNLP file or <applet> tag to implicitly specify the codebase, or
    • specify an absolute URL for the codebase of any main or extension JNLP file

    Refer to CodeBase Determination for further information.

  • code: The code attribute in the <applet> tag will be ignored.
  • Any applet parameters specified using the <param> tag are merged with those specified in the JNLP file. If the same parameter is specified via both the <applet> tag and the JNLP file, the <applet> tag's version overrides the JNLP file's version, except for the java_arguments and java_version parameters.
  • The new java_arguments and java_version parameters are unnecessary in JNLP applets. The mechanisms in the JNLP file for requesting a JRE version, or passing command-line arguments to the JVM, are used instead. Command-line arguments and JRE version requests from the JNLP file override those specified in the HTML for the applet.
  • It may be advantageous to specify certain parameters desired early on in the applet's startup process, such as image, boxbgcolor, etc. in the HTML instead of in the JNLP file, because these are available immediately upon loading the web page rather than requiring the JNLP file to be downloaded separately first.

Deploying Java Web Start Applications

A Java Web Start Application can be deployed simply by creating a JNLP file that describes only the title, vendor, java version, jar file(s), and main class of the application. Here is an example of a Java Web Start application's JNLP file:

<jnlp spec="0.2 1.0"
      codebase="http://java.sun.com/javase/technologies/desktop/javawebstart/apps"
      href="notepad.jnlp">
   <information>
      <title>Notepad App</title>
      <vendor>Sun Microsystems, Inc.</vendor>
      <homepage href="http://java.sun.com/javase/technologies/desktop/javawebstart/demos.html"/>
      <description>Notepad Demo Description</description>
      <description kind="short">Notepad Demo Short Description</description>
      <icon href="images/notepad.gif"/>
      <offline-allowed/>
   </information>
   <resources>
      <j2se version="1.3+" href="http://java.sun.com/products/autodl/j2se"/>
      <j2se version="1.3+"/>
      <jar href="notepad.jar" main="true" download="eager"/>
   </resources>
   <application-desc main-class="Notepad"/>
</jnlp>

The application can then be deployed simply by providing a link to the JNLP file on your web page:

<a href="http://java.sun.com/javase/technologies/desktop/javawebstart/apps/notepad.jnlp">Launch Notepad</a>

Many other elements can be added to the JNLP file to control the user experience, security, and update process of the application, or to take advantage of several other features of the Java Network Launching Protocol (JNLP).

Java Web Start can use its Auto-Download mechanism to download the version of the JRE that it requires to run an application, but if the application wants to use advanced features of JNLP and Java Web Start that were added to a particular version, you may want to ensure that at least that version is installed before launching Java Web Start.

Suppose an application wants to use the SingleInstance Service (introduced in 1.5.0). Instead of just specifying <jnlp spec="1.5.0" .../> and letting the application fail on systems where only 1.4.2 or earlier is installed, you can use the deployJava javascript to ensure that at least version 1.5.0 is installed before launching Java Web Start.

<script src="http://www.java.com/js/deployJava.js"></script>
<script>
        var url = "http://java.sun.com/javase/technologies/desktop/javawebstart/apps/notepad.jnlp";
    deployJava.createWebStartLaunchButton(url, '1.6.0');
</script>

For an application not having specific version requirements you can just use the function without supplying minimumVersion.

<script>
    var url = "http://java.sun.com/javase/technologies/desktop/javawebstart/apps/notepad.jnlp";
    deployJava.createWebStartLaunchButton(url);
</script>

Customizing the RIA Loading Experience

Customize the RIA loading experience by providing a splash screen or a customized loading progress indicator to engage the end user during the loading process and to communicate measurable progress information. See the following topics for more information:

  • Customizing the Rich Internet Application Loading Experience
  • Customizing the Loading Experience topic in the Java Tutorials for step-by-step instructions and examples.

Other Deployment Considerations

Order of Installation of JRE's

If multiple JRE's are required to run various Java Plug-in applets on the same machine, it is recommended to install the JRE's in the order of their versions. The oldest version should be installed first and the newest version installed last. This will avoid the problem of the dynamic clsid {8AD9C840-044E-11D1-B3E9-00805F499D93} being used in an object tag that is not using the latest version of the JRE on the machine.

Starting from JRE 5.0u6 with SSV support, the above is not an issue because the latest version of JRE on the machine will be used. In addition, we have added a new dynamic version clsid {CAFEEFAC-FFFF-FFFF-FFFF-ABCDEFFEDCBA}. If the new dynamic clsid is used in the object tag, the latest version of the JRE will be used independently of the installation order of the JRE's.

Installation order should have no effect on Java Web Start. In any case the highest version of the JRE on the system will contain the version of Java Web Start that is run.

ClassLoader and Accessing Resources

Resources accessed in a Java Web Start application or Java Plug-in applet may be cached on the client machine in the Deployment Cache. It is unwise to assume the format or content of this cache, as it may change between versions.

When porting stand alone programs to Java Web Start or Java Plug-in, problems can occur when code has inherent assumptions that it is loaded by the SystemClassLoader. In Java Plug-in resources are loaded by the PluginClassLoader (which extends sun.applet.AppletClassLoader, which in turn extends java.net.URLClassLoader). In Java Web Start resources are loaded by the JNLPClassLoader (which as of JDK 6 extends java.net.URLClassLoader).

Access the ClassLoader being used with:

    ClassLoader cl = Thread.getCurrent().getContextClassLoader();

ClassLoader.getResource() returns a URL, but any code that assumes the URL is a JarURL to a FileURL, and then tries to decompose that FileURL to find the underlying file path will fail. The correct way to access resources is to use getResourceAsStream() which will return the correct content whatever type of ClassLoader is used to access the resource. If the resource is already cached, the contents of the resource will be returned from the cache directly, so there won't be extra network connections to the resource itself.

We do not recommend modifying the contents of the Java deployment cache directly. The cache is a private implementation of Java Web Start / Java Plug-in, and is subject to change anytime.

Many applications and libraries try to deploy properties files and other "resources" by including them in the same directory as the jar file that uses them, and then expect to be able to decompose the the URL returned from getResource() to construct the path to these files. Developers argue that this is needed so the application can later modify these property files or other "resources" for use in subsequent launchings of the app. When porting to web deployed applications, they then find they need to repackage these into the jar files of the app, and consider them only the "default" content, and use one of several other mechanisms to persist the modified versions on the client machine (by writing files or by using either the Preference API or the JNLP PersistenceService.)

Lazy Downloading

When applications are large, it can be useful to only download the part of the application that is required to start up, and then download the rest on demand. This process is referred to as lazy downloading.

Java Web Start has support for lazy downloading, but few developers use it. It can be a way to significantly improve the download and startup time in some applications. To effectively use lazy downloading, Java Web Start must be aware which jar to download to resolve a request for a specific resource. Previous versions of Java Web Start required a complex specification of parts and packages to provide this information. Beginning with version 6.0, the same thing can be accomplished using Jar Indexing.

Jar Indexing is a simple and effective way to download only the required jars, and avoid downloading everything when a nonexistent resource is requested. See Jar Indexing.

Java Plug-in has built-in support for lazy downloading (that is, downloading is lazy by default), and also supports Jar Indexing. Developers should also try to NOT use individual classes but package them as JARs instead.

Resources

  • Client JRE Capabilities - Quick Reference
  • Deployment trail in the Java Tutorials
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


How and When To Deprecate APIs

  • What "Deprecated" Means
  • When to Deprecate
  • How to Deprecate
    • Using the @Deprecated Annotation
    • Using the @deprecated Javadoc Tag

What "Deprecated" Means

You may have heard the term, "self-deprecating humor," or humor that minimizes the speaker's importance. A deprecated class or method is like that. It is no longer important. It is so unimportant, in fact, that you should no longer use it, since it has been superseded and may cease to exist in the future.

Java provides a way to express deprecation because, as a class evolves, its API (application programming interface) inevitably changes: methods are renamed for consistency, new and better methods are added, and fields change. But such changes introduce a problem. You need to keep the old API around until developers make the transition to the new one, but you don't want them to continue programming to the old API.

The ability to deprecate a class, method, or member field solves the problem. Java supports two mechanisms for deprecation: and an annotation, (supported starting with J2SE 5.0) and a Javadoc tag (supported since 1.1). Existing calls to the old API continue to work, but the annotation causes the compiler to issue a warning when it finds references to deprecated program elements. The Javadoc tag and associated comments warn users against using the deprecated item and tell them what to use instead.

When to Deprecate

When you design an API, carefully consider whether it supersedes an old API. If it does, and you wish to encourage developers (users of the API) to migrate to the new API, then deprecate the old API. Valid reasons to deprecate an API include:

  • It is insecure, buggy, or highly inefficient
  • It is going away in a future release
  • It encourages bad coding practices

Deprecation is a reasonable choice in all these cases because it preserves "backward compatibility" while encouraging developers to change to the new API. Also, the deprecation comments help developers decide when to move to the new API, and so should briefly mention the technical reasons for deprecation.

It is not necessary to deprecate individual member fields (properties) of a deprecated class, unless of course you want to explain a specific point about a property.

How to Deprecate

Starting with J2SE 5.0, you deprecate a class, method, or field by using the @Deprecated annotation. Additionally, you can use the @deprecated Javadoc tag tell developers what to use instead.

Using the annotation causes the Java compiler to generate warnings when the deprecated class, method, or field is used. The compiler suppresses deprecation warnings if a deprecated item is used within an entity which itself is deprecated or is used within the same outermost class or is used in an entity that is annotated to suppress the warning.

You are strongly recommended to use the Javadoc @deprecated tag with appropriate comments explaining how to use the new API. This ensures developers will have a workable migration path from the old API to the new API. For more information, see Using the @deprecated Javadoc Tag.

NOTE: The Java Language Specification requires compilers to issue warnings when classes, methods, or fields marked with the @Deprecated annotation are used. Compilers are not required by the Java Language Specification to issue warnings when classes, methods, or fields marked with the @deprecated Javadoc tag are accessed, although the Sun compilers currently do so. However, there is no guarantee that the Sun compiler will always issue such warnings.

Using the @Deprecated Annotation

J2SE 5.0 introduces a new language feature called annotations (also called metadata). One of the Java language's built-in annotations is the @Deprecated annotation. To use it, you simply precede the class, method, or member declaration with "@Deprecated."

Using the @Deprecated annotation to deprecate a class, method, or field ensures that all compilers will issue warnings when code uses that program element. In contrast, there is no guarantee that all compilers will always issue warnings based on the @deprecated Javadoc tag, though the Sun compilers currently do so. Other compilers may not issue such warnings. Thus, using the @Deprecated annotation to generate warnings is more portable that relying on the @deprecated Javadoc tag.

In addition, the @Deprecated annotation causes the javadoc-generated documentation to be marked "Deprecated" wherever that program element appears.

NOTE: Deprecation applies to classes and to individual methods or properties, not to their names. It is possible for a single method to have deprecated and non-deprecated overloadings. It is possible for a non-deprecated property to hide or override a deprecated one, which removes deprecation. As developer of an API, it is your responsibility to deprecate overrides of a deprecated method, if in fact they should be deprecated.

Example

The following is a simple example of using the @Deprecated annotation from java.lang.Thread:

public
class Thread implements Runnable {
...
@Deprecated
    public final void stop() {
  synchronized (this) {
...

Using the @deprecated Javadoc Tag

You can use the @deprecated tag to make Javadoc show a program element as deprecated. The @deprecated tag must be followed by a space or newline. In the paragraph following the @deprecated tag, explain why the item has been deprecated and suggest what to use instead.

Javadoc generates special HTML based on @deprecated tags: it moves the paragraph following the @deprecated tag to the front of the description, placing it in italics and preceding it with a warning, "Note: foo is deprecated", in bold. It also adds "Deprecated" in bold to any index entries mentioning the deprecated entity.

The tagged paragraph can be empty, but empty deprecation paragraphs are bad form, because they do not help the user fix the warnings that arise from the deprecation. Include paragraphs marked with @link or @see tags that refer to the new versions of the same functionality. It is usually not a good idea to mention a timetable for phase-out of the deprecated API; this is a business decision that is best communicated other ways.

For more information on using the @deprecated Javadoc tag, see Javadoc - The Java API Documentation Generator.

Example

The following examples show how to use the @deprecated Javadoc tag. They also illustrate the @Deprecated annotation, to emphasize that the two should be used together.

Here is an example of the most common form of a deprecated method (for Javadoc 1.2 and later):

/**
 * @deprecated  As of release 1.3, replaced by {@link #getPreferredSize()}
 */
@Deprecated public Dimension preferredSize() {
return getPreferredSize();
}

If the API reorganization was more than renaming, the deprecation may be more complex. Here is an example of a method that is being retracted:

/**
 * Delete multiple items from the list.
 *
 * @deprecated  Not for public use.
 *    This method is expected to be retained only as a package
 *    private method.  Replaced by
 *    {@link #remove(int)} and {@link #removeAll()}
 */
@Deprecated public synchronized void delItems(int start, int end) {
...
}
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Description of Java SE Conceptual Diagram

The Java SE conceptual diagram categorizes each of the component technologies in the Java SE platform in a level. The following lists these levels, from top to bottom, and the technologies that are part of each one. Technologies that are part of a lower level serve as a foundation for those that are part of a higher level.

  • Java Language
    • Java Language
  • Tools & Tool APIs
    • java
    • javac
    • javadoc
    • jar
    • javap
    • JPDA
    • JConsole
    • Java VisualVM
    • Security
    • Int'l
    • RMI
    • IDL
    • Deploy
    • Monitoring
    • Troubleshoot
    • Scripting
    • JVM TI
  • RIAs
    • Java Web Start
    • Applet / Java Plug-in
  • User Interface Toolkits
    • AWT
    • Swing
    • Java 2D
    • Accessibility
    • Drag n Drop
    • Input Methods
    • Image I/O
    • Print Service
    • Sound
  • Integration Libraries
    • IDL
    • JDBC
    • JNDI
    • RMI
    • RMI-IIOP
    • Scripting
  • Other Base Libraries
    • Beans
    • Intl Support
    • Input/Output
    • JMX
    • JNI
    • Math
    • Networking
    • Override Mechanism
    • Security
    • Serialization
    • Extension Mechanism
    • XML JAXP
  • lang and util Base Libraries
    • lang and util
    • Collections
    • Concurrency Utilities
    • JAR
    • Logging
    • Management
    • Preferences API
    • Ref Objects
    • Reflection
    • Regular Expressions
    • Versioning
    • Zip
    • Instrumentation
  • Java Virtual Machine
    • Java Hotspot Client and Server VM

The JDK consists of all levels.

The JRE consists of the following levels:

  • RIAs
  • User Interface Toolkits
  • Integration Libraries
  • Other Base Libraries
  • lang and util Base Libraries
  • Java Virtual Machine

The Java SE API consists of the following levels:

  • User Interface Toolkits
  • Integration Libraries
  • Other Base Libraries
  • lang and util Base Libraries
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Design Overview

Chapter 2

This chapter focuses on major design issues in the JNI. Most design issues in this section are related to native methods. The design of the Invocation API is covered in Chapter 5.

JNI Interface Functions and Pointers

Native code accesses Java VM features by calling JNI functions. JNI functions are available through an interface pointer. An interface pointer is a pointer to a pointer. This pointer points to an array of pointers, each of which points to an interface function. Every interface function is at a predefined offset inside the array. Figure 2-1 illustrates the organization of an interface pointer.

The previous context describes this image.

Figure 2-1 Interface Pointer

The JNI interface is organized like a C++ virtual function table or a COM interface. The advantage to using an interface table, rather than hard-wired function entries, is that the JNI name space becomes separate from the native code. A VM can easily provide multiple versions of JNI function tables. For example, the VM may support two JNI function tables:

  • one performs thorough illegal argument checks, and is suitable for debugging;
  • the other performs the minimal amount of checking required by the JNI specification, and is therefore more efficient.

The JNI interface pointer is only valid in the current thread. A native method, therefore, must not pass the interface pointer from one thread to another. A VM implementing the JNI may allocate and store thread-local data in the area pointed to by the JNI interface pointer.

Native methods receive the JNI interface pointer as an argument. The VM is guaranteed to pass the same interface pointer to a native method when it makes multiple calls to the native method from the same Java thread. However, a native method can be called from different Java threads, and therefore may receive different JNI interface pointers.

Compiling, Loading and Linking Native Methods

Since the Java VM is multithreaded, native libraries should also be compiled and linked with multithread aware native compilers. For example, the -mt flag should be used for C++ code compiled with the Sun Studio compiler. For code complied with the GNU gcc compiler, the flags -D_REENTRANT or -D_POSIX_C_SOURCE should be used. For more information please refer to the native compiler documentation.

Native methods are loaded with the System.loadLibrary method. In the following example, the class initialization method loads a platform-specific native library in which the native method f is defined:

package pkg;

class Cls {

     native double f(int i, String s);

     static {

         System.loadLibrary(“pkg_Cls”);

     }

}

The argument to System.loadLibrary is a library name chosen arbitrarily by the programmer. The system follows a standard, but platform-specific, approach to convert the library name to a native library name. For example, a Solaris system converts the name pkg_Cls to libpkg_Cls.so, while a Win32 system converts the same pkg_Cls name to pkg_Cls.dll.

The programmer may use a single library to store all the native methods needed by any number of classes, as long as these classes are to be loaded with the same class loader. The VM internally maintains a list of loaded native libraries for each class loader. Vendors should choose native library names that minimize the chance of name clashes.

If the underlying operating system does not support dynamic linking, all native methods must be prelinked with the VM. In this case, the VM completes the System.loadLibrary call without actually loading the library.

The programmer can also call the JNI function RegisterNatives() to register the native methods associated with a class. The RegisterNatives() function is particularly useful with statically linked functions.

Resolving Native Method Names

Dynamic linkers resolve entries based on their names. A native method name is concatenated from the following components:

  • the prefix Java_
  • a mangled fully-qualified class name
  • an underscore (“_”) separator
  • a mangled method name
  • for overloaded native methods, two underscores (“__”) followed by the mangled argument signature

The VM checks for a method name match for methods that reside in the native library. The VM looks first for the short name; that is, the name without the argument signature. It then looks for the long name, which is the name with the argument signature. Programmers need to use the long name only when a native method is overloaded with another native method. However, this is not a problem if the native method has the same name as a nonnative method. A nonnative method (a Java method) does not reside in the native library.

In the following example, the native method g does not have to be linked using the long name because the other method g is not a native method, and thus is not in the native library.

class Cls1 {

  int g(int i);

  native int g(double d);

}

We adopted a simple name-mangling scheme to ensure that all Unicode characters translate into valid C function names. We use the underscore (“_”) character as the substitute for the slash (“/”) in fully qualified class names. Since a name or type descriptor never begins with a number, we can use _0, ..., _9 for escape sequences, as Table 2-1 illustrates:

Table 2-1 Unicode Character Translation
Escape Sequence | Denotes
_0XXXX | a Unicode character XXXX. Note that lower case is used to represent non-ASCII Unicode characters, e.g., _0abcd as opposed to _0ABCD.
_1 | the character “_”
_2 | the character “;” in signatures
_3 | the character “[“ in signatures

Both the native methods and the interface APIs follow the standard library-calling convention on a given platform. For example, UNIX systems use the C calling convention, while Win32 systems use __stdcall.

Native Method Arguments

The JNI interface pointer is the first argument to native methods. The JNI interface pointer is of type JNIEnv. The second argument differs depending on whether the native method is static or nonstatic. The second argument to a nonstatic native method is a reference to the object. The second argument to a static native method is a reference to its Java class.

The remaining arguments correspond to regular Java method arguments. The native method call passes its result back to the calling routine via the return value. Chapter 3 describes the mapping between Java and C types.

Code Example 2-1 illustrates using a C function to implement the native method f. The native method f is declared as follows:

package pkg;

class Cls {

     native double f(int i, String s);

     ...

}

The C function with the long mangled name Java_pkg_Cls_f_ILjava_lang_String_2 implements native method f:

Code Example 2-1 Implementing a Native Method Using C
jdouble Java_pkg_Cls_f__ILjava_lang_String_2 (
     JNIEnv *env,        /* interface pointer */
     jobject obj,        /* "this" pointer */
     jint i,             /* argument #1 */
     jstring s)          /* argument #2 */
{
     /* Obtain a C-copy of the Java string */
     const char *str = (*env)->GetStringUTFChars(env, s, 0);

     /* process the string */
     ...

     /* Now we are done with str */
     (*env)->ReleaseStringUTFChars(env, s, str);

     return ...
}

Note that we always manipulate Java objects using the interface pointer env . Using C++, you can write a slightly cleaner version of the code, as shown in Code Example 2-2:

Code Example 2-2 Implementing a Native Method Using C++

extern "C" /* specify the C calling convention */

jdouble Java_pkg_Cls_f__ILjava_lang_String_2 (

     JNIEnv *env,        /* interface pointer */

     jobject obj,        /* "this" pointer */

     jint i,             /* argument #1 */

     jstring s)          /* argument #2 */

{

     const char *str = env->GetStringUTFChars(s, 0);

     ...

     env->ReleaseStringUTFChars(s, str);

     return ...

}

With C++, the extra level of indirection and the interface pointer argument disappear from the source code. However, the underlying mechanism is exactly the same as with C. In C++, JNI functions are defined as inline member functions that expand to their C counterparts.

Referencing Java Objects

Primitive types, such as integers, characters, and so on, are copied between Java and native code. Arbitrary Java objects, on the other hand, are passed by reference. The VM must keep track of all objects that have been passed to the native code, so that these objects are not freed by the garbage collector. The native code, in turn, must have a way to inform the VM that it no longer needs the objects. In addition, the garbage collector must be able to move an object referred to by the native code.

Global and Local References

The JNI divides object references used by the native code into two categories: local and global references. Local references are valid for the duration of a native method call, and are automatically freed after the native method returns. Global references remain valid until they are explicitly freed.

Objects are passed to native methods as local references. All Java objects returned by JNI functions are local references. The JNI allows the programmer to create global references from local references. JNI functions that expect Java objects accept both global and local references. A native method may return a local or global reference to the VM as its result.

In most cases, the programmer should rely on the VM to free all local references after the native method returns. However, there are times when the programmer should explicitly free a local reference. Consider, for example, the following situations:

  • A native method accesses a large Java object, thereby creating a local reference to the Java object. The native method then performs additional computation before returning to the caller. The local reference to the large Java object will prevent the object from being garbage collected, even if the object is no longer used in the remainder of the computation.
  • A native method creates a large number of local references, although not all of them are used at the same time. Since the VM needs a certain amount of space to keep track of a local reference, creating too many local references may cause the system to run out of memory. For example, a native method loops through a large array of objects, retrieves the elements as local references, and operates on one element at each iteration. After each iteration, the programmer no longer needs the local reference to the array element.

The JNI allows the programmer to manually delete local references at any point within a native method. To ensure that programmers can manually free local references, JNI functions are not allowed to create extra local references, except for references they return as the result.

Local references are only valid in the thread in which they are created. The native code must not pass local references from one thread to another.

Implementing Local References

To implement local references, the Java VM creates a registry for each transition of control from Java to a native method. A registry maps nonmovable local references to Java objects, and keeps the objects from being garbage collected. All Java objects passed to the native method (including those that are returned as the results of JNI function calls) are automatically added to the registry. The registry is deleted after the native method returns, allowing all of its entries to be garbage collected.

There are different ways to implement a registry, such as using a table, a linked list, or a hash table. Although reference counting may be used to avoid duplicated entries in the registry, a JNI implementation is not obliged to detect and collapse duplicate entries.

Note that local references cannot be faithfully implemented by conservatively scanning the native stack. The native code may store local references into global or heap data structures.

Accessing Java Objects

The JNI provides a rich set of accessor functions on global and local references. This means that the same native method implementation works no matter how the VM represents Java objects internally. This is a crucial reason why the JNI can be supported by a wide variety of VM implementations.

The overhead of using accessor functions through opaque references is higher than that of direct access to C data structures. We believe that, in most cases, Java programmers use native methods to perform nontrivial tasks that overshadow the overhead of this interface.

Accessing Primitive Arrays

This overhead is not acceptable for large Java objects containing many primitive data types, such as integer arrays and strings. (Consider native methods that are used to perform vector and matrix calculations.) It would be grossly inefficient to iterate through a Java array and retrieve every element with a function call.

One solution introduces a notion of “pinning” so that the native method can ask the VM to pin down the contents of an array. The native method then receives a direct pointer to the elements. This approach, however, has two implications:

  • The garbage collector must support pinning.
  • The VM must lay out primitive arrays contiguously in memory. Although this is the most natural implementation for most primitive arrays, boolean arrays can be implemented as packed or unpacked. Therefore, native code that relies on the exact layout of boolean arrays will not be portable.

We adopt a compromise that overcomes both of the above problems.

First, we provide a set of functions to copy primitive array elements between a segment of a Java array and a native memory buffer. Use these functions if a native method needs access to only a small number of elements in a large array.

Second, programmers can use another set of functions to retrieve a pinned-down version of array elements. Keep in mind that these functions may require the Java VM to perform storage allocation and copying. Whether these functions in fact copy the array depends on the VM implementation, as follows:

  • If the garbage collector supports pinning, and the layout of the array is the same as expected by the native method, then no copying is needed.
  • Otherwise, the array is copied to a nonmovable memory block (for example, in the C heap) and the necessary format conversion is performed. A pointer to the copy is returned.

Lastly, the interface provides functions to inform the VM that the native code no longer needs to access the array elements. When you call these functions, the system either unpins the array, or it reconciles the original array with its non-movable copy and frees the copy.

Our approach provides flexibility. A garbage collector algorithm can make separate decisions about copying or pinning for each given array. For example, the garbage collector may copy small objects, but pin the larger objects.

A JNI implementation must ensure that native methods running in multiple threads can simultaneously access the same array. For example, the JNI may keep an internal counter for each pinned array so that one thread does not unpin an array that is also pinned by another thread. Note that the JNI does not need to lock primitive arrays for exclusive access by a native method. Simultaneously updating a Java array from different threads leads to nondeterministic results.

Accessing Fields and Methods

The JNI allows native code to access the fields and to call the methods of Java objects. The JNI identifies methods and fields by their symbolic names and type signatures. A two-step process factors out the cost of locating the field or method from its name and signature. For example, to call the method f in class cls, the native code first obtains a method ID, as follows:

jmethodID mid =      env->GetMethodID(cls, “f”, “(ILjava/lang/String;)D”);

The native code can then use the method ID repeatedly without the cost of method lookup, as follows:

jdouble result = env->CallDoubleMethod(obj, mid, 10, str);

A field or method ID does not prevent the VM from unloading the class from which the ID has been derived. After the class is unloaded, the method or field ID becomes invalid. The native code, therefore, must make sure to:

  • keep a live reference to the underlying class, or
  • recompute the method or field ID

if it intends to use a method or field ID for an extended period of time.

The JNI does not impose any restrictions on how field and method IDs are implemented internally.

Reporting Programming Errors

The JNI does not check for programming errors such as passing in NULL pointers or illegal argument types. Illegal argument types includes such things as using a normal Java object instead of a Java class object. The JNI does not check for these programming errors for the following reasons:

  • Forcing JNI functions to check for all possible error conditions degrades the performance of normal (correct) native methods.
  • In many cases, there is not enough runtime type information to perform such checking.

Most C library functions do not guard against programming errors. The printf() function, for example, usually causes a runtime error, rather than returning an error code, when it receives an invalid address. Forcing C library functions to check for all possible error conditions would likely result in such checks to be duplicated--once in the user code, and then again in the library.

The programmer must not pass illegal pointers or arguments of the wrong type to JNI functions. Doing so could result in arbitrary consequences, including a corrupted system state or VM crash.

Java Exceptions

The JNI allows native methods to raise arbitrary Java exceptions. The native code may also handle outstanding Java exceptions. The Java exceptions left unhandled are propagated back to the VM.

Exceptions and Error Codes

Certain JNI functions use the Java exception mechanism to report error conditions. In most cases, JNI functions report error conditions by returning an error code and throwing a Java exception. The error code is usually a special return value (such as NULL) that is outside of the range of normal return values. Therefore, the programmer can:

  • quickly check the return value of the last JNI call to determine if an error has occurred, and
  • call a function, ExceptionOccurred(), to obtain the exception object that contains a more detailed description of the error condition.

There are two cases where the programmer needs to check for exceptions without being able to first check an error code:

  • The JNI functions that invoke a Java method return the result of the Java method. The programmer must call ExceptionOccurred() to check for possible exceptions that occurred during the execution of the Java method.
  • Some of the JNI array access functions do not return an error code, but may throw an ArrayIndexOutOfBoundsException or ArrayStoreException.

In all other cases, a non-error return value guarantees that no exceptions have been thrown.

Asynchronous Exceptions

In cases of multiple threads, threads other than the current thread may post an asynchronous exception. An asynchronous exception does not immediately affect the execution of the native code in the current thread, until:

  • the native code calls one of the JNI functions that could raise synchronous exceptions, or
  • the native code uses ExceptionOccurred() to explicitly check for synchronous and asynchronous exceptions.

Note that only those JNI function that could potentially raise synchronous exceptions check for asynchronous exceptions.

Native methods should insert ExceptionOccurred()checks in necessary places (such as in a tight loop without other exception checks) to ensure that the current thread responds to asynchronous exceptions in a reasonable amount of time.

Exception Handling

There are two ways to handle an exception in native code:

  • The native method can choose to return immediately, causing the exception to be thrown in the Java code that initiated the native method call.
  • The native code can clear the exception by calling ExceptionClear(), and then execute its own exception-handling code.

After an exception has been raised, the native code must first clear the exception before making other JNI calls. When there is a pending exception, the JNI functions that are safe to call are:

  ExceptionOccurred()
  ExceptionDescribe()
  ExceptionClear()
  ExceptionCheck()
  ReleaseStringChars()
  ReleaseStringUTFChars()
  ReleaseStringCritical()
  Release<Type>ArrayElements()
  ReleasePrimitiveArrayCritical()
  DeleteLocalRef()
  DeleteGlobalRef()
  DeleteWeakGlobalRef()
  MonitorExit()
  PushLocalFrame()
  PopLocalFrame()

Contents | Previous | Next
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Preferences API Design FAQ

Design FAQ

Following is a collection of frequently asked questions concerning the design of the Preferences API.

  1. How does this Preferences API relate to Properties API?

    It is intended to replace most common uses of Properties, rectifying many of its deficiencies, while retaining its light weight. When using Properties, the programmer must explicitly specify a pathname for each properties file, but there is no standard location or naming convention. Properties files are "brittle", as they are hand-editable but easily corrupted by careless editing. Support for non-string data types in properties is non-existent. Properties cannot easily be used with a persistence mechanism other than the file system. In sum, the Properties facility does not scale.

  2. How does Preferences API relate to JNDI?

    Like JNDI, it provides back-end neutral access to persistent key-value data. JNDI, however, is far more powerful, and correspondingly heavyweight. JNDI is appropriate for enterprise applications that need its power. Preferences API is intended as a simple, ubiquitous, back-end neutral preferences-management facility, enabling any Java application to easily tailor its behavior to user preferences and maintain small amounts of state from run to run.

  3. Why do all of the get methods require the caller to pass in a default?

    This forces the application authors to provide reasonable default values, so that applications have a reasonable chance of running even if the repository is unavailable.

  4. How was it decided which methods should throw BackingStoreException?

    Only methods whose semantics absolutely require the ability to communicate with the backing store throw this exception. Typical applications will have no need to call these methods. As long as these methods are avoided, applications will be able to run even if the backing store is unavailable, which was an explicit design goal.

  5. Why doesn't this API provide stronger guarantees concerning concurrent access by multiple VMs? Similarly, why doesn't the API allow multiple Preferences updates to be combined into a single "transaction", with all or nothing semantics?

    While the API does provide rudimentary persistent data storage, it is not intended as a substitute for a database. It is critical that it be possible to implement this API atop standard preference/configuration repositories, most of which do not provide database-like guarantees and functionality. Such repositories have proven adequate for the purposes for which this API is intended.

  6. Why does this API have case-sensitive keys and node-names, while other APIs playing in a similar space (such as the Microsoft Windows Registry and LDAP) do not?

    In the Java programming universe, case-sensitive String keys are ubiquitous. In particular, they are provided by the Properties class, which this API is intended to replace. It is not uncommon for people to use Properties in a fashion that demands case-sensitivity. For example, Java package names (which are case-sensitive) are sometimes used as keys. It is recognized that this design decision complicates the life of the systems programmer who implements Preferences atop a backing store with case-insensitive keys, but this is considered an acceptable price to pay, as far more programmers will use the Preferences API than will implement it.

  7. Why doesn't this API use the Java 2 Collections Framework?

    This API is designed for a very particular purpose, and is optimized for that purpose. In the absence of generic types (see JSR-14), the API would be less convenient for typical users. It would lack compile-time type safety, if forced to conform to the Map API. Also, it is not anticipated that interoperability with other Map implementations will be required (though it would be straightforward to implement an adapter class if this assumption turned out to be wrong). Preferences API is, by design, so similar to Map that programmers familiar with the latter should have no difficulties using the former.

  8. Why don't the put and remove methods return the old values?

    It is desirable that both of these methods be executable even if the backing store is unavailable. This would not be possible if they were required to return the old value. Further, it would have negative performance impact if the API were implemented atop some common back-end data stores.

  9. Why does the API permit, but not require, stored defaults?

    This functionality is required in enterprise settings for scalable, cost-effective administration of preferences across the enterprise, but would be overkill in a self-administered single-user setting.

  10. Why doesn't this API contain methods to read and write arbitrary serializable objects?

    Serialized objects are somewhat fragile: if the version of the program that reads such a property differs from the version that wrote it, the object may not deserialize properly (or at all). It is not impossible to store serialized objects using this API, but we do not encourage it, and have not provided a convenience method.

  11. Why is Preferences an abstract class rather than an interface?

    It was decided that the ability to add new methods in an upward compatible fashion outweighed the disadvantage that Preferences cannot be used as a "mixin" (That is to say, arbitrary classes cannot also be made to serve as Preferences objects.) Also, this obviates the need for a separate class for the static methods. (Interfaces cannot contain static methods.)

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Developer Information

This section includes the following topics:

  • Information for Web-Page Authors
  • Information for Applet Developers
  • Information for System Administrators

Information for Web Page Authors

Q: As a web page author, how do I use Java Plug-in Software?

A: To utilize all of the features and capabilities of Java Standard Edition, web page authors must modify the page's HTML to specify the use of Sun's JRE via Java Plug-in. Sun provides a specification—Using OBJECT, EMBED and APPLET Tags in Java Plug-in—to guide web page authors on how to make these changes. In addition, Sun provides the Java Plug-in free of charge.

Q: For Windows, the above specification mentions JRE releases that can be autodownloaded via .cab files. Where do I find a complete list of such JRE releases?

A: See Autodownload Files (Windows Only).

Q: How do I specify a JAR file as part of an OBJECT or EMBED tag?

A: You can specify one or more JAR files by defining an archive, cache_archive, or cache_archive_ex parameter in the OBJECT or EMBED tag.

The archive parameter with the OBJECT tag this looks like:

<PARAM NAME="archive" VALUE="demo.jar,fred.jar">

For more information on the cache_archive and cache_archive_ex parameters, see Applet Caching.

With the EMBED tag this looks like:

<EMBED ... archive="demo.jar,fred.jar" ... >

Q: Does Java Plug-in Software support multiple JAR files in the archive attribute in the APPLET tag? If so, why can't I get this to work?

A: The archive attribute is supported in both the EMBED and OBJECT tags. The most common mistake is to put the JAR files in the wrong order. For example, if you use the Swing set with Java Plug-in and specify archive="Myjar.jar,swing.jar,...", Java Plug-in will fail to load the applet because when Myjar.jar is loaded and Java Plug-in tries to initialize the applet, swing.jar is not yet loaded. The JAR files in the archive should be in the order of dependency; since Myjar.jar depends on other JARs, it should be put at the end of the list. The other common mistake is to put spaces or paths with the JAR file lists.

Information for Applet Developers

Q: Do developers need to modify their applets in order to support Java Plug-in?

A: No. Any Java SDK, Standard Edition, 100% Pure Java applets should run unmodified using the Java Plug-in.

Q: What is the applet lifecycle in Java Plug-in Software?

A: When an applet is encountered on an HTML page, the applet will be initialized and started. When the HTML page is closed, or the back button is pushed, the applet with be stopped and destroyed immediately.

When the same HTML page is encountered again, the applet will be initialized and started again.

Q: Does Java Plug-in Software support Drag and Drop between applets and the native environment? If so, why can't I get it to work?

A: Yes, Java Plug-in Software does support Drag and Drop. You must make sure to grant the applet the correct socket permissions using policytool to use this feature. Please see the SocketPermission class documentation for more information.

Q: How can I speed up applet download time?

A: There are several ways:

  • JAR files—bundle your applets as JAR files.
  • JAR indexing—optimize the class loading process. See the JAR File Specification for details.
  • Applet caching—cache your applets in a permanent cache (see Applet Caching).

Q: How do I prevent the warning banner from covering my GUI state?

A: You should use the getInsets() method to find the size of your frame's decorative border. This includes the warning banner. For example, if you create a Frame with size 100x100, you might find it has insets [top=42,left=5,bottom=5,right=6] giving you a drawable area of 89x53. You need to position your work within the drawable area.

If you need to create a drawable area of a particular size:

  1. create and show the Frame
  2. use getInsets to find the insets' sizes
  3. figure out the desired frame size by adding your desired size to the insets
  4. then use frame.setSize() to set your frame to that size.

Q: Why does InetAddress.getLocalHost().getHostName() return localhost?

A: This is a deliberate security feature in the Java platform. Untrusted applets will not be given the real host name. Trusted applets (such as signed applets) will be given the real host name.

Information for System Administrators

Q: I would like to change the Java Plug-in setting in thousands of machines through system management tools. What should I do?

A: Java Plug-in stores user specific settings under <user.home>/.java/properties<version>. Therefore, if administrators would like to change the Java Plug-in settting globally, they may use system managment tools to update the file in all machines.

Q: Does Java Plug-in Software replace Microsoft's or Netscape's Java runtime with Sun's JRE?

A: No. Java Plug-in Software does not replace the browser's underlying virtual machine if it has one. (Netscape 6 and later versions of Internet Explorere 6 do not have a Java virtual machine.) Rather, Java Plug-in Software simply enables web-page authors to specify that Sun's JRE be used instead of the default Java runtime.

Q: We are trying to deploy Java Plug-in Software within our intranet environment. The chapter called Using OBJECT, EMBED and APPLET Tags in Java Plug-in and other documents say we should set up an installation page within our intranet for Netscape users to install Java Plug-in. What does this page do and how should we set it up?

A: The purpose of this installation page is to act as an entry point for Netscape users to install Java Plug-in Software. If a user encounters an HTML page that requires Java Plug-in, the user will get redirected to this installation page according to the pluginspage attribute in the EMBED tag. At that point, the users should be able to download and install the correct version of Java Plug-in Software for their platform. Thus, the installation page should have links to download the Java Plug-in binary.

An simple example page would look like:

<HTML>
<HEAD>
<TITLE>Java Plug-in Software Download Page</TITLE>
</HEAD>
<BODY>
<P><A HREF="ftp://myhost.com/public/jre14-win32.exe">
    Java Plug-in Software for Microsoft Windows</A>
</P>
<P><A HREF="ftp://myhost.com/public/plugin-14-solaris.bin">
        Java Plug-in Software for Solaris</A>
</P>
</BODY>
</HTML>
Depending on how your webserver is configured, you may want to consider using CGI scripting instead of FTP for the download. Contact your webmaster for more information.

Q: Why is the experience of downloading and installing Netscape Navigator different from Internet Explorer?

A: The releases of Netscape Navigator supported by Java Plug-in Software do not provide mechanisms that allow for the automatic download and installation of Java Plug-in, as in Internet Explorer. The first time Netscape Navigator comes across a web page that is enabled for Java Plug-in (the activated page), it redirects the user to another web page to download and install Java Plug-in Software on the user's system. The user must then return to the activated page to render the applet using Java Plug-in Software. From that point on, the browser automatically invokes Java Plug-in whenever it encounters an activated page.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Application Development Considerations

This chapter includes the following topics:

  • Introduction
  • Retrieving Resources from JAR files
  • Accessing the Client Using JNLP API
  • Security and Code Signing
  • Signing JAR Files With a Test Certificate
  • How to Encode JNLP Files
  • Dynamic Download of HTTPS Certificates

Introduction

Developing applications for deployment with Java Web Start is generally the same as developing stand-alone applications for the Java(TM) Platform Standard Edition. For instance, the entry point for the application is the standard public static void main(String[] argv).

However, in order to support Web deployment—automatic download and launching of an application—and to ensure that an application can run in a secure sandbox, there are some additional considerations:

  • An application must be delivered as a set of JAR files.
  • All application resources, such as files and images must be stored in JAR files; and they must be referenced using the getResource mechanism in the Java(TM) Platform Standard Edition (see below).
  • If an application is written to run in a secure sandbox, it must follow these restrictions:
    • No access to local disk.
    • All JAR files must be downloaded from the same host.
    • Network connections are enabled only to the host from which the JAR files are downloaded.
    • No security manager can be installed.
    • No native libraries may be used.
    • Limited access to system properties. The application has read/write access to all system properties defined in the JNLP File, as well as read-only access to the same set of properties that an Applet has access to.
    Some of these restrictions can be overcome by the use of JNLP API to access the file system and other system resources.
  • An application is allowed to use the System.exit call.
  • An application that needs unrestricted access to the system will need to be delivered in a set of signed JAR files. All entries in each JAR file must be signed.

Retrieving Resources from JAR files

Java Web Start only transfers JAR files from the Web server to the client machine. It determines where to store the JAR files on the local machine. Thus, an application cannot use disk-relative references to resources such as images and configuration files.

All application resources must be retrieved from the JAR files specified in the resources section of the JNLP file, or retrieved explicitly using an HTTP request to the Web server. Storing resources in JAR files is recommended, since they will be cached on the local machine by Java Web Start.

The following code example shows how to retrieve images from a JAR file:

// Get current classloader
ClassLoader cl = this.getClass().getClassLoader();
// Create icons
Icon saveIcon  = new ImageIcon(cl.getResource("images/save.gif"));
Icon cutIcon   = new ImageIcon(cl.getResource("images/cut.gif"));
...

The example assumes that the following entries exist in one of the JAR files for the application:

images/save.gif
images/cut.gif

Accessing the Client Using JNLP API

JNLP API can be used to access the client's file system and other resources. See the following topics for more information about using JNLPI API to access the client:

  • JNLP API Examples
  • Accessing Client the Using JNLP API (Topic in the Deployment Trail of the Java Tutorials. Although the sample shown is an applet, the information applies to Java Web Start applications also.)

Security and Code Signing

Java Web Start addresses the security issues:

  • Protecting users against malicious code (intentional & unintentional) that may affect local files;
  • Protecting enterprises against code that may attempt to access or destroy data on networks.

Applications launched with Java Web Start are, by default, run in a restricted environment where they have limited access to local computing resources, such as storage devices and the local network. In this sandbox environment, Java Web Start can guarantee that a downloaded and potentially untrusted application cannot compromise the security of the local files or the network.

An additional security feature supported by Java Web Start is digital code signing. If an application being invoked is delivered in one or more signed JAR files, Java Web Start will verify that the contents of the JAR file have not been modified since they were signed. If verification of a digital signature fails, Java Web Start will not run the application, since it may have been compromised by a third-party.

The support for code signing is important for both users and for application service providers. This service makes it possible for users to verify that an application comes from a trusted source. Because the application service provider signs the code, both can be ensured that no other party can impersonate the application on the Web. A signed application that is trusted by the user can also request additional system privileges, such as access to a local disk.

Java Web Start presents a dialog displaying the application's origin, based on the signer's certificate, before the application is launched. This allows the user to make an informed decision about whether or not to grant additional privileges to the downloaded code.

By including the following settings in the JNLP file, an application can request full access to a client system if all its JAR files are signed :

<security>
   <all-permissions/>
</security>

The implementation of code signing in Java Web Start is based on the security API in the core Java(TM) Platform Standard Edition. The Java 2 SE JRE 1.4.2 supports code signing with the SHA1withDSA and MD5withRSA algorithms.

Developers sign code for use with Java Web Start in the same way as for Java Applets—by using the standard jarsigner tool from the Java(TM) Platform Standard Edition. The jarsigner tool documentation provides examples of how to sign code and create test certificates, and it discusses other issues related to signing.

Signing JAR Files With a Test Certificate

Here are the steps needed to sign a JAR file with a test certificate:

1. Make sure that you have an SDK 1.4.2 keytool and jarsigner in your path. These tools are located in the SDK bin directory.

2. Create a new key in a new keystore as follows:

keytool -genkey -keystore myKeystore -alias myself

You will get prompted for a information about the new key, such as password, name, etc. This will create the myKeystore file on disk.

3. Then create a self-signed test certificate as follows:

keytool -selfcert -alias myself -keystore myKeystore

This will prompt for the password. Generating the certificate may take a few minutes.

4. Check to make sure that everything is okay. To list the contents of the keystore, use this command:

keytool -list -keystore myKeystore

It should list something like:

Keystore type: jks
Keystore provider: SUN

Your keystore contains 1 entry:

myself, Tue Jan 23 19:29:32 PST 2001, keyEntry,
Certificate fingerprint (MD5):
C2:E9:BF:F9:D3:DF:4C:8F:3C:5F:22:9E:AF:0B:42:9D

5. Finally, sign the JAR file with the test certificate as follows:

jarsigner -keystore myKeystore test.jar myself

Repeat this step with all of your JAR files.

Note that a self-signed test certificate should only be used for internal testing, since it does not guarantee the identity of the user and therefore cannot be trusted. A trust-worthy certificate can be obtained from a certificate authority, such as VeriSign or Thawte, and should be used when the application is put into production.

How to Encode JNLP Files

Beginning with Java Web Start version 1.2, JNLP files may be encoded in any character encoding supported by the Java(TM) Platform Standard Edition. (See the Java(TM) Platform Standard Edition documentation for a list of supported encodings.)

To encode a JNLP file, specify an encoding in the XML prolog of that file. For example, the following line indicates that the JNLP file will be encoded in UTF-16.

<?xml version="1.0" encoding="utf-16"?>

The XML prolog itself must be UTF-8-encoded.

Dynamic Download of HTTPS Certificates

Beginning with 1.4.2, Java Web Start dynamically imports certificates in much the same way as browsers do. In order to make this work, Java Web Start now sets its own https handler, using the java.protocol.handler.pkgs system properties, to initialize defaults for SSLSocketFactory and HostnameVerifier. It sets the defaults with HttpsURLConnection.setDefaultSSLSocketFactory and HttpsURLConnection.setDefaultHostnameVerifier.

If your application uses those two method, make sure they are called after the Java Web Start https handler is initialized, otherwise your custom handler will be replaced by the Java Web Start default handler. You can ensure that your own customized SSLSocketFactory and HostnameVerifiter are used by doing either of the following:

  1. Installing your own https handler, which will completely replace the Java Web Start https handler (for more information, see A New Era for Java Protocol Handlers);
  2. Calling HttpsURLConnection.setDefaultSSLSocketFactory or HttpsURLConnection.setDefaultHostnameVerifier only after the first https url object is created, which will execute the Java Web Start https handler initialization code first.

For information on creating a download servlet see the next chapter, JnlpDownloadServlet Guide.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.security.auth.callback.DialogCallbackHandler (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.callback.DialogCallbackHandler

No usage of com.sun.security.auth.callback.DialogCallbackHandler
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.DisjunctiveTypeTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.DisjunctiveTypeTree

  • Packages that use DisjunctiveTypeTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of DisjunctiveTypeTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type DisjunctiveTypeTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitDisjunctiveType(DisjunctiveTypeTree node, P p)

    • Uses of DisjunctiveTypeTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type DisjunctiveTypeTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitDisjunctiveType(DisjunctiveTypeTree node, P p)
      R | SimpleTreeVisitor.visitDisjunctiveType(DisjunctiveTypeTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Swing Data Transfer

For the JavaTM 2 Platform, Standard Edition, v 1.4 release, Swing has added support for data transfer between applications. A drag and drop operation is a data transfer request that has been specified by a gesture with a graphical pointing device. In the case of copy/paste, data transfer is often initiated with the keyboard. The ability to transfer data takes two forms:

  • Drag and drop (DnD) support
  • Clipboard transfer via cut/copy/paste
When adding data transfer support to Swing, the goal was to make it easy for developers using Swing components to add clipboard transfer as well as drag and drop to an application. Previous AWT support for drag and drop provided a great deal of flexibility, but also a fair amount of complexity, to implement. Also, AWT support for clipboard transfer had not been integrated into Swing in a natural way. For this release, data transfer support has been implemented so that the developer may take advantage of these powerful features with minimal effort.

Because the state of each Swing component is independent of the definition of the data model, it was easy to implement a mechanism for moving the data between components without worrying about the details of the data itself. The data transfer amounts to transferring part of one model to another model. (In the case of cut/copy/paste, the data is transferred between the model and the clipboard.) To support data transfer, we:

  • Added a small amount of API to enable data transfer with a few method calls.
  • Made it possible to disable the Swing DnD implementation so that the user can use the support provided by AWT to customize any special behavior.
  • Implemented the necessary changes in the look and feel implementations we provide.

Quick Reference: Components That Support DnD

Component | Supports Drag | Supports Drop
JColorChooser | X | X
JEditorPane | X | X
JFileChooser | X | X
JFormattedTextField | X | X
JLabel | see here | see here
JList | X | X
JPasswordField | X | X
JTable | X | X
JTextArea | X | X
JTextField | X | X
JTextPane | X | X
JTree | X | X

This document has the following sections:

  • Data Transfer Support
    • Default TransferHandler Support
    • Example of Adding Support to JLabel
  • Drag Support
    • Default Drag Support
    • Adding Drag Support to Subclasses of Swing Classes
    • Operation of TransferHandler.exportAsDrag
  • Drop Support
    • Default Drop Support
    • Using the Drop Support in Subclasses of Swing Classes
  • Clipboard Transfer Support
    • Default Clipboard Transfer
    • Using the Clipboard Transfer Support in Subclasses of Swing Classes
  • Implementation Details
  • Changes Since Beta
  • Known Bugs

Data Transfer Support

The foundation of data transfer is support for handling the transfer of data into and out of a component. With this functionality available on the component, the mechanics of managing a drag and drop can be provided automatically. In addition, support for cut/copy/paste can also be provided automatically. The crux of this implementation is the new class TransferHandler. The JComponent property methods, setTransferHandler and getTransferHandler, provide an entrypoint to the data transfer mechanism for any component which extends JComponent.

The table below details the extent of the cut, copy, paste, and drop support for each of the components when a non-null TransferHandler is installed. Note that this support is enabled by the look and feel code. Support for dragging is initially disabled, but may be enabled by calling setDragEnabled(true) on the component. If the component doesn't have such a method, the drag may be enabled by binding some kind of gesture to it.

Default TransferHandler Support

For the components listed below, Swing installs default implementations of TransferHandler. For those components that have default Swing support, the TransferHandler is installed by the ComponentUI if the value of the transferHandler property is null or marked by the presence of the UIResource interface. The default TransferHandler implementation installed by the ComponentUI is marked by the UIResource interface, enabling developers to override the default TransferHandler. The following table shows the support provided.

Components That Support DnD

Component | Exports (Drag, Cut, Copy) | Imports (Drop, Paste)
JColorChooser | The selected color is offered through the JavaBeansTM property handling of TransferHandler. The flavor offered is application/x-java-jvm-local-objectref; class=java.awt.Color. The value transferred is determined by getColor. | Accepts inserts of type Color. The data is imported by using setColor (from the bean property handling). Any flavor having class=java.awt.Color (or a subclass of java.awt.Color) is accepted.
JEditorPane | 1.4: If the content-type of the JEditorPane is text/plain, the selected text is offered as text/plain through the write method of the EditorKit. If the content-type is OTHER, it is exported both as text/plain using the getSelectedText method, and as OTHER using the write method of the EditorKit. 1.4.1: The selected text, as returned by the getSelectedText method, is exported as text/plain. In addition, if the content-type of the JEditorPane is other than text/plain, the selected content is also offered in that other flavor using the EditorKit's write method. | 1.4: Accepts inserts of type text/plain and whatever the current type returned by getContentType. If a type is found matching the current type (including text/plain), it is imported using the EditorKit's read method. Otherwise, text/plain is imported through the component's replaceSelection method. Paste: the contents of the selection, if any, are replaced. Drop: the data is inserted at the caret position. 1.4.1: Accepts inserts of type text/plain and whatever the current type returned by getContentType. If a type is found matching the current type (excluding text/plain), it is imported using the EditorKit's read method. Otherwise, text/plain is imported through the component's replaceSelection method. Paste: the contents of the selection, if any, are replaced. Drop: the data is inserted at the caret position.
JFileChooser | The selection is offered in the same manner as those from the native file chooser. | Imports not accepted. As the mouse is moved over the list, the potential drop point is indicated by highlighting the file/directory under the cursor. See Default Drop Support.
JFormattedTextField | The selected text is offered as text/plain. | Accepts inserts of type text/plain. Paste: the contents of the selection, if any, are replaced; otherwise the data is inserted at the caret position. Drop: the data is inserted at the caret position. Note that paste and drop employ the same code paths as typing from the keyboard, therefore code validation is preserved.
JList | If the selection is a single item, it is offered as text/plain. If multiple items are selected, they are offered as text/html. The format of the text/html is a <UL> tag followed by the selected list items each starting with an <LI> tag. | Imports not accepted. As the mouse is moved over the list, the potential drop point is indicated by highlighting the list item under the cursor. See Default Drop Support.
JPasswordField | For security reasons, cut, copy, and drag are not supported. | Accepts inserts of type text/plain. Paste: the contents of the selection, if any, are replaced; otherwise the data is inserted at the caret position. Drop: the data is inserted at the caret position.
JTable | If the selection is a single item, it is offered as text/plain. If multiple items are selected, they are offered as text/html. The format of the text/html is a <TABLE> tag followed by a <TR> tag for each row and a <TD> tag for each cell. | Imports not accepted. As the mouse is moved over the table, the potential drop point is indicated by highlighting the cell under the cursor. See Default Drop Support.
JTextArea | The selected text is offered as text/plain. | Accepts inserts of type text/plain. Paste: the contents of the selection, if any, are replaced; otherwise the data is inserted at the caret position. Drop: the data is inserted at the caret position.
JTextField | The selected text is offered as text/plain. | Accepts inserts of type text/plain. Paste: the contents of the selection, if any, are replaced; otherwise the data is inserted at the caret position. Drop: the data is inserted at the caret position.
JTextPane | Same as JEditorPane. | Same as JEditorPane.
JTree | If the selection is a single item, it is offered as text/plain. If multiple items are selected, they are offered as text/html. The format of the text/html is nested lists, similar to the format used for JList. | Imports not accepted. As the mouse is moved over the table, the potential drop point is indicated by highlighting the tree node under the cursor. See Default Drop Support.

Example of Adding Support to JLabel

The JLabel component does not support DnD by default. The following code fragment creates a JLabel that supports drag and drop on the "text" property (a String):

JLabel componentType = new JLabel();
componentType.setTransferHandler(new TransferHandler("text"));
MouseListener ml = new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
        JComponent c = (JComponent)e.getSource();
        TransferHandler th = c.getTransferHandler();
        th.exportAsDrag(c, e, TransferHandler.COPY);
    }
};
componentType.addMouseListener(ml);

We have included a small example that implements drag and drop using a JTextField and a JLabel. You can type a value into the text field, highlight the text, then hold the mouse button down over the textfield and drag a few pixels. An icon appears under the cursor. Release the icon over the JLabel and see the text replace the "Drop Here" text. Simultaneously with the drop, the text is removed from the source textfield. The default behavior for drag and drop is MOVE. To change the behavior to COPY, hold down the CONTROL key while selecting the text. On Windows, a plus sign appears in the icon. When the text is released on the target, it is left intact in the source. You can likewise drag from the JLabel to the text field. Note that JLabel does not have bindings for copy/paste and is unable to get the focus that is required to support this feature.

See the JLabelDragNDrop.java example here.

Drag Support

Some components, such as text fields, support selections. For those kinds of components, a drag operation is typically initiated by dragging an existing selection with the mouse. A controller for this type of component can recognize this condition and initiate a drag. For those components that don't have selections, Swing can't automatically initiate the drag, but Swing can handle the mechanics of the drag if told that a drag attempt has been initiated as shown in the JLabel example.

With this level of drag support, the Swing developer can focus on implementing a TransferHandler that represents the desired transfer, and setting properties on the Swing component. This greatly simplifies the burden to the Swing developer wanting to support dragging in an application.

Note that we are currently investigating providing different visual appearances of the drag, hence the reference to Icon in the API. Stay tuned for future developments.

Default Drag Support

The simplest level of support is to set a flag that indicates the developer would like the default support enabled. The components that offer default support for dragging are described in the Exports column of the Components That Support DnD table; but to summarize, the classes that directly implement setDragEnabled and getDragEnabled are: JColorChooser, JFileChooser, JList, JTable, JTree, and JTextComponent. The drag gesture is defined as the press of the first mouse button over a selection and dragging a few pixels. Setting the dragEnabled property to true therefore has a subtle effect on mouse behavior.

When dragging is enabled on a component, the Swing controller (in the corresponding ComponentUI subclass) begins looking for a drag gesture, and if the transferHandler property is null, or marked by the presence of the UIResource interface, a default implementation is installed. The implementation provided by Swing is marked with the UIResource interface, so a developer can insert a new TransferHandler by replacing the default TransferHandler property with a custom implementation. When a drag gesture is recognized, the exportAsDrag method is called on the TransferHandler which initiates the drag mechanism. The actual transfer is handled by the java.awt.dnd mechanism, requiring no further effort from the developer.

Adding Drag Support to Subclasses of Swing Classes

The drag support provided by Swing is activated by the TransferHandler.exportAsDrag method. This makes adding drag support as easy as:

  1. Installing a TransferHandler implementation (so there is something to drag) by calling the setTransferHandler method.
  2. Recognizing a drag gesture.
  3. Calling the exportAsDrag method.

Some scenarios for accomplishing this are:

  • Add a MouseListener that watches for the desired gesture, then call getTransferHandler on the component and call the exportAsDrag method when the desired gesture is found. See the JLabel example.
  • Reimplement the processMouseEvent method in a subclass and call the exportAsDrag method on the ComponentUI variable when a drag gesture is seen, otherwise execute the superclass behavior.
  • In a component with a custom UI implementation, have the controller call exportAsDrag when a drag gesture has been seen.

Operation of TransferHandler.exportAsDrag

When the exportAsDrag method is called on TransferHandler, the drag is handled by Swing provided functionality. When this method is called, it is assumed that a valid drag gesture has been recognized. The method performs the following steps:

  1. A Swing implementation of a DragSource and DragListener is used to start the drag using the Transferable implementation returned by createTransferable as data transfer object.
  2. When the drop has completed, the exportDone method is called on the TransferHandler. For some operations, such as MOVE, it may be necessary to remove the data from the source. The default behavior for text-based components, for example, is that a standard drag implements MOVE behavior (following the drop the selected text is removed from the source component). The user may override this behavior by holding down the control key when the text is selected for dragging. On Windows, the drag icon visually reflects this behavior with a small plus-sign.

Drop Support

The primary support for handling a drop is the same as for a paste operation, the importData method on the TransferHandler. The semantics of inserting data into a component are generally more meaningful at the application level than the toolkit level. Users of an application can drop all kinds of Transferable implementations on components that are completely unknown to the Swing toolkit. It is up to the Swing developer to provide a TransferHandler with meaningful import semantics if the default TransferHandler is insufficient.

A drop operation does have some differences from a paste however:

  • Typically a potential drop site provides feedback of where the data would be accepted.
  • For components with selection capabilities, the insertion point is moved to indicate where the data would be placed.

Default Drop Support

To assist Swing developers in adding drop support to an application, Swing provides DropTarget implementations that use the TransferHandler property on the Swing component. For those components that have a non-null TransferHandler property, the drop target is installed by the ComponentUI if the value of the dropTarget property is null or marked by the presence of the UIResource interface. The default DropTarget implementations installed by the ComponentUI is marked by the UIResource interface, enabling developers to override the default DropTarget.

The components that provide a complete drop implementation by default are indicated in the Imports column of the Components That Support DnD table. There are four components that provide only some support for drop. JFileChooser, JList, JTable, and JTree by default have an installed DropTarget that indicates a potential insertion point. However, to fully support imports of data the developer must write and install a custom TransferHandler.

Using the Drop Support in Subclasses of Swing Classes

A well behaved DropTarget implementation uses the transferHandler property on JComponent to perform the drop. The Swing developer automatically gets a simple DropTarget implementation that links the drop to the TransferHandler when the transferHandler property is set and the dropTarget property is null.

Clipboard Transfer Support

Cut, copy, and paste operations perform data transfer in a manner that is more useful to those without a mouse, as they are typically initiated via a keyboard gesture. These operations can use the same TransferHandler services as the drag and drop support. This improves the accessibility of the data transfers, and enables Swing to provide keyboard bindings for these operations even though Swing may not know how to actually transfer the data to/from the clipboard. The keyboard bindings for clipboard transfer are dependent upon the current look and feel that is installed.

Default Clipboard Transfer

As with drag and drop, clipboard transfers are the most useful for those components that support selections. The list of components shown in the Exports column of the Components That Support DnD table have cut, copy, and paste actions in the component action map, along with a LAF dependent set of keyboard bindings in the input map of the component. Having Swing provide these bindings frees the developer from trying to track the current look and feel and change the bindings.

Using the Clipboard Transfer Support in Subclasses of Swing Classes

A well behaved cut, copy, and paste implementation uses the transferHandler property on JComponent to perform the transfer. When the transferHandler property is set on a JComponent, a simple Action implementation that links the transfer of between a Clipboard and TransferHandler is installed in the component's action map under the keys cut, copy, and paste if there is no action currently installed.

Implementation Details

Note: The following information outlines private implementation details and is subject to change. We are providing this information only to satisfy the curiosity of those who have access to the source code and feel compelled to thump the tires and peek under the hood.

If a TransferHandler is installed on a JComponent, the look and feel then enables cut, copy, and paste using the following TransferHandler methods:

  • getCutAction
  • getCopyAction
  • getPasteAction
If you bind some event to TransferHandler.exportAsDrag you also get drag support. This plumbing is located in package-private nested classes inside of the TransferHandler class.

The following package-private classes were added to the javax.swing.plaf.basic package for creating the default support:

BasicTransferable
The basis of the various Transferable implementations.
BasicDropTargetListener
Adds scrolling support and drop target feedback for those components supporting selection.
BasicDragGestureRecognizer
Supports the "select and move a few pixels" drag gesture recognition.

Each of the ComponentUI classes that support DnD then have some additional nested classes:

BasicTreeUI:

TreeTransferHandler
Default import/export support.
TreeTransferable
The actual tree data.
TreeDragGestureRecognizer
Tree drag gesture recognition, enabled by JTree.setDragEnabled.
TreeDropHandler
Shows drop target location.

BasicListUI, BasicTableUI, BasicTextUI all have a pattern similar to as BasicTreeUI.

BasicFileChooserUI
Uses the list support, but has a FileTransferHandler that produces the FileTransferable that extends the ListTransferable with the flavor used for file transfers.
BasicColorChooserUI
Uses the TransferHandler bean support and binds the "color" property. A mouse listener is added to the preview area to bind a mouse press to the exportAsDrag method on the TransferHandler.

Changes Since Beta

TransferHandler Actions Should be Registered by UI

The bugtraq report that corresponds to this change is: 4460011.

To implement drag and drop, bindings were provided in the Action class to support copying and pasting the data. In order for a look and feel, or other code, to override these Actions, the UI must install them - Actions are no longer automatically installed by the TransferHandler. The package-private methods getCutAction, getCopyAction, and getPasteAction in TransferHandler are now made public.

Ability to Disable DropTarget

The bugtraq report that corresponds to this change is: 4485914.

The drag and drop implementation causes a DropTarget to be added to a JComponent if that component has a TransferHandler installed. This may affect applications that are manually adding DropTargets. Therefore the System property suppressSwingDropSupport has been added. The JComponent methods setTransferHandler(TransferHandler) and getTransferHandler can be used to enable or disable this property.

Known Bugs

Drop Clobbers Selected Text in JTextComponent

The bugtraq report that corresponds to this problem is: 4513715.

Selecting text and then dragging and dropping that text within the selected region of the same text component causes the selected text to be clobbered and nothing to be pasted. This bug is fixed in release 1.4.1.

Occasional Errors in Restoring Caret when Exiting a Component

The bugtraq report that corresponds to this problem is: 4513720.

With the built-in drop support, Swing text components respond to DnD dragovers by setting the Caret to visible and using it to display the potential insert location. When the drag exits the component, the Caret's visibility is restored. Unfortunately, since the Caret uses the same "visible" property to represent the usual meaning of visible as well as when it is in mid-flash, we sometimes restore the Caret's visibility incorrectly.

Cut/Copy/Drag Broken for JEditorPane with RTFEditorKit

The bugtraq report that corresponds to this problem is: 4513638.

When using an RTFEditorKit set explicitly on a JEditorPane using setEditorKit, or by setting the content-type to text/rtf, cut, copy and drag no longer work. Note that this bug, filed against release 1.4, is fixed in release 1.4.1.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Drag and Drop Subsystem for the Java 2 Platform Standard Edition 5.0

This document has these sections:

  • 1.0 Requirements
  • 2.0 API
  • 2.1 Overview
  • 2.2 Drag Gesture Recognition
    • 2.2.1 DragGestureRecognizer
  • 2.3 Drag Source
    • 2.3.1 The DragSource Definition
    • 2.3.2 The DragSourceContext Definition
    • 2.3.3 The DragSourceListener Definition
    • 2.3.4 The DragSourceEvent Definition
    • 2.3.5 The DragSourceDragEvent Definition
    • 2.3.6 The DragSourceDropEvent Definition
  • 2.4 Drop Target
    • 2.4.1 java.awt.Component additions for DropTarget (de)registration
    • 2.4.2 The DropTarget Definition
    • 2.4.3 The DropTargetContext Definition
    • 2.4.4 The DropTargetListener Definition
    • 2.4.5 The DropTargetDragEvent and DropTargetDropEvent Definitions
    • 2.4.6 Autoscrolling Support
  • 2.5 Data Transfer Phase
    • 2.5.1 FlavorMap and SystemFlavorMap
    • 2.5.2 Transferring Data across the JVM boundary
    • 2.5.3 Transferring lists of files across the JVM boundary
    • 2.5.4 Transferring java.rmi.Remote references across the JVM boundary
  • 3.0 Issues
    • 3.0.1 What are the implications of the various platform protocol engines?
    • 3.0.2 Inter/Intra VM transfers?
    • 3.0.3 Lifetime of the Transferable(s)?
    • 3.0.4 Implications of ACTION_MOVE semantics on source objects exposed via Transferable?
    • 3.0.5 Semantics of ACTION_REFERENCE operation
  • Appendix A: DropTargetPeer definition
  • Appendix B: DragSourceContextPeer definition
  • Appendix C: DropTargetContextPeer definition

1.0 Requirements

This specification defines the API for the drag and drop facilities for the Java 2 Platform.

The primary requirements that this specification addresses, are:

  1. Provision of a platform-independent drag and drop facility for Java GUI clients implemented through AWT and Swing classes.
  2. Integration with platform dependent drag and drop facilities, permitting Java clients to be able to participate in DnD operation with native applications using:
    • OLE (Win32) DnD
    • XDND protocol
    • CDE/Motif dynamic protocol
    • MacOS
    • OS/2
  3. Support for 100% pure JavaOS/Java implementation.
  4. Leverages the existing java.awt.datatransfer.* package to enable the transfer of data, described by an extensible data type system based on the MIME standard.
  5. Does not preclude the use of "accessibility" features where available.
  6. Extensible to support diverse input devices.

The specification derives from the previous work mentioned above, but incorporates significant differences from that original work as a result of the advent of the JavaBeans event model, lightweight (Swing) components, and an increasing understanding of the cross-platform integration and interoperability issues.

2.0 API

The following sections cover the drag and drop API.

2.1 Overview

Drag and drop is a direct manipulation gesture found in many graphical user interface systems that provides a mechanism to transfer information between two entities logically associated with presentation elements in the GUI. Normally driven by a physical gesture of a human user using an appropriate input device, drag and drop provides both a mechanism to enable continuous feedback regarding the possible outcome of any subsequent data transfer to the user during navigation over the presentation elements in the GUI, and the facilities to provide for any subsequent data negotiation and transfer.

A typical drag and drop operation can be decomposed into the following states (not entirely sequentially):

  • A DragSource comes into existence, associated with some presentation element (Component) in the GUI, to initiate a drag and drop of some potentially Transferable data.
  • 1 or more DropTargets come into/go out of existence, associated with presentation elements in the GUI (Components), potentially capable of consuming Transferable data types.
  • A DragGestureRecognizer is obtained from the DragSource and is associated with a Component in order to track and identify any drag initiating gesture by the user over the Component.
  • A human user makes a drag gesture over the Component, which the registered DragGestureRecognizer detects, and notifies its DragGestureListener of.

    Note: Although the body of this document consistently refers to the stimulus for a drag and drop operation being a physical gesture by a human user this does not preclude a programmatically driven DnD operation given the appropriate implementation of a DragSource.

  • The DragGestureListener causes the DragSource to initiate the drag and drop operation on behalf of the user, perhaps animating the GUI Cursor and/or rendering an Image of the item(s) that are the subject of the operation.
  • As the user gestures navigate over Component(s) in the GUI with associated DropTarget(s), the DragSource receives notifications in order to provide "Drag Over" feedback effects, and the DropTarget(s) receive notifications in order to provide "Drag Under" feedback effects based upon the operation(s) supported and the data type(s) involved.

    The gesture itself moves a logical cursor across the GUI hierarchy, intersecting the geometry of GUI Component(s), possibly resulting in the logical "Drag" cursor entering, crossing, and subsequently leaving Component(s) and associated DropTarget(s).

    The DragSource object manifests "Drag Over" feedback to the user, in the typical case by animating the GUI Cursor associated with the logical cursor.

    DropTarget objects manifest "Drag Under" feedback to the user, in the typical case, by rendering animations into their associated GUI Component(s) under the GUI Cursor.

  • The determination of the feedback effects, and the ultimate success or failure of the data transfer, should one occur, is parameterized as follows:
  • By the transfer "operation" selected by the user, and supported by both the DragSource and DropTarget: Copy, Move or Reference(link).
  • By the intersection of the set of data types provided by the DragSource and the set of data types comprehensible by the DropTarget.
  • When the user terminates the drag operation, normally resulting in a successful Drop, both the DragSource and DropTarget receive notifications that include, and result in the type negotiation and transfer of, the information associated with the DragSource via a Transferable object.

The remainder of this document details the proposed API changes to support this model.

2.2 Drag Gesture Recognition

The gesture(s) that can initiate a drag and drop operation vary, not only per platform, but also per Component, and per device. Therefore a mechanism is required in order to encapsulate these dependencies, thus making the task of the author of a Component that wishes to initiate a drag and drop operation much simpler.

2.2.1 DragGestureRecognizer

The DragGestureRecognizer is an abstract base class for all device/platform/Component specific drag and drop gesture recognizers, and is defined as:

public abstract DragGestureRecognizer {
    protected DragGestureRecognizer(
        DragSource  ds,
        Component c,
        int  srcActions,
        DragGestureListener dgl
    );
    public Component getComponent();
    public void      setComponent(Component c);
    public int  getSourceActions();
    public void setSourceActions(int actions);
    public java.awt.InputEvent getTriggerEvent();
    public void resetRecognizer();
    public void addDragGestureListener(
        DragGestureListener dgl
    ) throws TooManyListenerExceptions;
    public void removeDragGestureListener(
       DragGestureListener dgl
    );
    protected abstract void registerListeners();
    protected abstract void unregisterListeners();
    protected void fireDragGestureRecognized(
       int dragAction
    );
    protected void appendEvent(InputEvent awtie);
}

An appropriate concrete subclasses of DragGestureRecognizer for a particular may be obtained in a variety of ways; from a DragSource instance, from the Toolkit, or by other means. Concrete implementation subclasses are obtained through standard APIs' by specifying a Class reference to an abstract DragGestureRecognizer superclass, an instance of a concrete subclass of this actual parameter is instantiated and returned to the requestor.

Once a DragGestureRecognizer instance is associated with a Component and a DragSource it registers its own particular set of EventListeners' with the target Component in order to monitor the appropriate events being delivered to that Component to detect an initiating gesture. (Using registerListeners and unregisterListeners to add/remove these monitoring EventListeners').

Note that a DragGestureRecognizer may throw either an IllegalStateException or an IllegalArgumentException if either the Component or DragSource specified is either not in the correct state for, or is not interoperable with, that DragGestureRecognizer.

When a concrete DragGestureRecognizer instance detects a drag-initiating user gesture on the Component it is associated with, it will fire a DragGestureEvent to the DragGestureListener registered on its unicast event source for DragGestureListener events. This DragGestureListener is responsible for causing the associated DragSource to start the drag and drop operation (if appropriate).

The implementation provides (at least) an abstract subclass for recognizing mouse device gestures MouseDragGestureRecognizer. Other abstract subclasses may be provided by the platform to support other input devices or particular Component class semantics. Concrete superclasses of this MouseDragGestureRecognizer that encapsulate platform dependent mouse based gestures are available from the Toolkit object via its createDragGestureRecognizer(Class adgrc, DragSource ds, Component c, int sa, DragGestureListener dgl) method. This Toolkit API provides platform dependent concrete implementations that extend particular platform independent abstract definitions (classes).

The MouseDragGestureRecognizer abstract class is defined as:

public abstract   MouseDragGestureRecognizer
       extends    DragGestureRecognizer
          implements MouseListener, MouseMotionListener {

    public MouseDragGestureRecognizer(
        DragSource  ds,
        Component   c,
        int  sa,
        DragGestureListener dsl
    );
    //...
}

The DragGestureListener is defined as:

public interface DragGestureListener extends EventListener {
    void dragGestureRecognized(DragGestureEvent dge);
}

Usually the dragGestureRecognized() method will simply, via the DragGestureEvent's convenience API startDrag, start a drag and drop operation on the associated DragSource.

Note that per Component (class or instance) behavior that may effect the initiating gesture would usually be implemented in this DragGestureListener method, or in the DragGestureRecognizer subclass where appropriate or possible.

The DragGestureEvent is defined as:

publc class DragGestureEvent extends EventObject {
        public DragGestureEvent(DragGestureRecognizer dgr,
             int  dragAction,
             java.util.List  events
     );
    public DragGestureRecognizer getSourceAsDragGestureRecognizer();
    public Component  getComponent();
    public DragSource getDragSource();
    public java.util.Iterator iterator();
    public Object[] toArray();
    public Object[] toArray(Object[] array);
    public int getDragAction();
    public startDrag(Cursor             dragCursor,
                     Transferable       t,
                     DragSourceListener dsl
    );
    public startDrag(Cursor             dragCursor,
                     Image              dragImage,
                     Point              imageOffset,
                     Transferable       t,
                     DragSourceListener dsl
    );
    //...
}

The DragGestureEvent encapsulates all the information regarding the nature of the gesture that has just been recognized, including:

  • The DragGestureRecognizer that recognized the gesture
  • The Component that the gesture occurred on
  • The DragSource that will process the operation
  • The List of InputEvent objects that comprise the gesture.
  • The action (ACTION_COPY, ACTION_MOVE or ACTION_LINK, selected by the user's gesture.

2.3 Drag Source

The DragSource is the entity responsible for the initiation of the drag and drop operation:

2.3.1 The DragSource definition

The DragSource and associated constant interfaces are defined as follows:

The DnDConstants class defines the operations that may be applied to the subject of the transfer:

public final class java.awt.dnd.DnDConstants {
     public static int ACTION_NONE = 0x0;
     public static int ACTION_COPY = 0x1;
     public static int ACTION_MOVE = 0x2;
     public static int ACTION_COPY_OR_MOVE= ACTION_COPY | ACTION_MOVE;
     public static int ACTION_REFERENCE = 0x40000000;
}

public class java.awt.dnd.DragSource {
     public static Cursor     DefaultCopyDrop;
     public static Cursor     DefaultMoveDrop;
     public static Cursor     DefaultLinkDrop;
     public static Cursor     DefaultCopyNoDrop;
     public static Cursor     DefaultMoveNoDrop;
     public static Cursor     DefaultLinkNoDrop;
     public static DragSource getDefaultDragSource();
     public static boolean isDragImageSupported();
     public void startDrag(DragGestureEvent trigger,
                        Cursor             dragCursor,
                        Image              dragImage,
                        Point              dragImageOffset,
                        Transferable       transferable,
                        DragSourceListener dsl,
                        FlavorMap          fm)
                  throws InvalidDnDOperationException;
     protected DragSourceContext  createDragSourceContext(
                        DragSourceContextPeer dscp,
                        DragGestureEvent      trigger,
                        Cursor                dragCursor,
                        Image                 dragImage,
                        Point                 dragImageOffset,
                        Transferable          transferable,
                        DragSourceListener    dsl
      );
      public FlavorMap getFlavorMap();
      public DragGestureRecongizer createDragGestureRecognizer(
              Class               abstractRecognizerClass,
              Component           c,
              int                 srcActions,
              DragGestureListener dgl
     );
     public DragGestureRecongizer createDefaultDragGestureRecognizer(
              Component           c,
              int                 srcActions,
              DragGestureListener dgl
     );
     //...
}

The DragSource may be used in a number of scenarios:

  • 1 default instance per JVM for the lifetime of that JVM. (defined by this spec)
  • 1 instance per class of potential Drag Initiator object (e.g TextField). [implementation dependent]
  • 1 per instance of a particular Component, or application specific object associated with a Component instance in the GUI. [implementation dependent]
  • some other arbitrary association. [implementation dependent]

A controlling object, shall obtain a DragSource instance prior to a user's gesture, effecting an associated Component, in order to process the operation. Once obtained a DragGestureRecognizer should be obtained and used to associate the DragSource with a Component.

The initial interpretation of the user's gesture, and the subsequent starting of the drag operation are the responsibility of the implementing Component, this is usually implemented by a DragGestureRecognizer.

When a gesture occurs, the DragSource's startDrag method shall be invoked in order to cause processing of the user's navigational gestures and delivery of drag and drop protocol notifications. A DragSource shall only permit a single drag and drop operation to be current at any one time, and shall reject any further startDrag requests by throwing an IllegalDnDOperationException until such time as the extant operation is complete.

In order to start a drag operation the caller of the startDrag method shall provide the following parameters:

  • The DragGestureEvent for the gesture.
  • A Cursor representing the initial "Drag Over" feedback for the operation(s) specified. (This shall be a Cursor that provides "No Drop" visual feedback to the user).
  • An (optional) Image to visually represent the item, or item(s) that are the subject(s) of the operation.

  • On platforms that can support this feature, a "Drag" image may be associated with the operation to enhance the fidelity of the "Drag Over" feedback. This image would typically be a small "iconic" representation of the object, or objects being dragged, and would be rendered by the underlying system, tracking the movement of, and coincident with, but typically in addition to the Cursor animation.

    Where this facility is not available, or where the image is not of a suitable type to be rendered by the underlying system, this parameter is ignored and only Cursor "Drag Over" animation results, so applications should not depend upon this feature. The presence of the facility on a particular platform may be tested by invoking the static method isDragImageSupported.

  • Where an Image is provided; a Point (in the co-ordinate space of the Component) specifying the initial origin of that Image relative to the co-ordinates of the "hotspot" of the drag "Cursor", in the co-ordinate space of the Component, at the time of the initial gesture, for the purposes of initiating a correctly positioned "Drag Over" animation of that Image relative to that "hotspot".
  • A Transferable that describes the various DataFlavor(s) that represent the subject(s) of any subsequent data transfer that may result from a successful Drop.

    The Transferable instance associated with the DragSource at the start of the drag operation, represents the object(s) or data that are the operand(s), or the subject(s), of the Drag and Drop operation, that is the information that will subsequently be passed from the DragSource to the DropTarget as a result of a successful Drop on the Component associated with that DropTarget.

    Note that multiple (collections) of either homogeneous, or heterogeneous, objects may be subject of a Drag and Drop operation, by creating a container object, that is the subject of the transfer, and implements Transferable. However it should be noted that since none of the targeted native platforms systems support a standard mechanism for describing and thus transferring such collections it is not possible to implement such transfers in a transparent, or platform portable fashion.

  • A DragSourceListener instance, which will subsequently receive events notifying it of changes in the state of the ongoing operation in order to provide the "Drag Over" feedback to the user.

As stated above, the primary role of the startDrag method is to initiate a Drag on behalf of the user. In order to accomplish this, the startDrag method must create a DragSourceContext instance to track the operation itself, and more importantly it must initiate the operation itself in the underlying platform implementation. In order to accomplish this, the DragSource must first obtain a DragSourceContextPeer from the underlying system (usually via an invocation of java.awt.Toolkit.createDragSourceContextPeer method) and subsequently associate this newly created DragSourceContextPeer (which provides a platform independent interface to the underlying systems capabilities) with a DragSourceContext.The startDrag method invokes the createDragSourceContext method to instantiate an appropriate DragSourceContext and associate the DragSourceContextPeer with that.

If the drag and drop system is unable to initiate a drag operation for some reason the startDrag method shall throw a java.awt.dnd.InvalidDnDOperationException to signal such a condition. Typically this exception is thrown when the underlying platform system is either not in a state to initiate a drag, or the parameters specified are invalid.

Note that during the drag neither the set of operations the source exposed at the start of the drag operation may change for the duration of the operation, in other words the operation(s) and are constant for the duration of the operation with respect to the DragSource.

The getFlavorMap method is used by the underlying system to obtain a FlavorMap object in order to map the DataFlavors exposed by the Transferable to data type names of the underlying DnD platform. [see later for details of the FlavorMap]

A "private" FlavorMap may be provided to the startDrag() method of the DragSource, or null, in which case the "default" FlavorMap for that DragSource class or instance is used.

2.3.2 The DragSourceContext Definition

As a result of a DragSource's startDrag method being successfully invoked an instance of the DragSourceContext class is created. This instance is responsible for tracking the state of the operation on behalf of the DragSource and dispatching state changes to the DragSourceListener.

The DragSourceContext class is defined as follows:

public class DragSourceContext implements DragSourceListener {
        public DragSourceContext(
                DragSourceContextPeer dscp,
                DragGestureEvent  trigger,
                Cursor  dragCursor,
                Image  dragImage,
                Point  dragOffset,
                Transferable  transferable,
                DragSourceListener  dsl
        );
        public DragSource  getDragSource();
        public Component  getComponent();
        public DragGestureEvent getTrigger();
        public Image     getDragImage();
        public Point     getDragImageOffset();
        public void transferablesFlavorsChanged();
        public int getSourceActions();
        public Cursor getCursor();
        pbulic void   setCursor(Cursor Cursor)
                    throws InvalidDnDOperationException;
        public void addDragSourceListener(DragSourceListener dsl)
                    throws TooManyListenersException;
        public void removeDragSourceListener(DragSourceListener dsl);
        protected updateCurrentCursor(int dropOperation,
                                   int targetActions,
                                   int status
        );
        // values for status parameter above.
        protected static final int DEFAULT = 0;
        protected static final int ENTER   = 1;
        protected static final int OVER    = 2;
        protected static final int CHANGED = 3;

        //...
}

Note that the DragSourceContext itself implements DragSourceListener, this is to allow the platform peer, the DragSourceContextPeer instance, created by the DragSource, to notify the DragSourceContext of changes in state in the ongoing operation, and thus allows the DragSourceContext to interpose itself between the platform and the DragSourceListener provided by the initiator of the operation.

The state machine the platform exposes, with respect to the source, or initiator of the Drag and Drop operation is detailed below:

Following context describes this graphic

Notifications of changes in state with respect to the initiator during a drag and drop operation, as illustrated above, are delivered from the DragSourceContextPeer, to the appropriate DragSourceContext, which delegates notifications, via a unicast JavaBeans compliant EventListener subinterface, to an arbitrary object that implements DragSourceListener registered with the DragSource via startDrag.

The primary responsibility of the DragSourceListener is to monitor the progress of the user's navigation during the drag and drop operation and provide the "Drag-Over" effects feedback to the user. Typically this is accomplished via changes to the "Drag Cursor".

Every drag operation has 2 logical cursor states (Drag Cursors) associated with it:

  • The Drop Cursor, the cursor displayed when dragging over a valid DropTarget.
  • The NoDrop Cursor, the cursor displayed when dragging over everything else (the initial state of the cursor at the start of a drag).

The state of the Cursor may be modified by calling the setCursor method of the DragSourceContext.

2.3.3 The DragSourceListener Definition

The DragSourceListener interface is defined as follows:

public interface java.awt.dnd.DragSourceListener
        extends java.util.EventListener {
        void dragEnter  (DragSourceDragEvent dsde);
        void dragOver   (DragSourceDragEvent dsde);
        void dropActionChanged (DragSourceDragEvent dsde);
        void dragExit   (DragSourceEvent     dse);
        void dragDropEnd  (DragSourceDropEvent dsde);
}

As the drag operation progresses, the DragSourceListener's dragEnter, dragOver, and dragExit methods shall be invoked as a result of the user's navigation of the logical "Drag" cursor's location intersecting the geometry of GUI Component(s) with associated DropTarget(s). [See below for details of the DropTarget's protocol interactions].

The DragSourceListener's dragEnter method is invoked when the following conditions are true:

  • The logical cursor's hotspot initially intersects a GUI Component's visible geometry.
  • That Component has an active DropTarget associated.

The DropTarget's registered DropTargetListener dragEnter method is invoked and returns successfully.

The registered DropTargetListener invokes the DropTargetDragEvent's acceptDrag method to accept the drag based upon interrogation of the source's potential drop actions and available data types (DataFlavors).

The DragSourceListener's dragOver method is invoked when the following conditions are true:

  • The cursor's logical hotspot has moved but still intersects the visible geometry of the Component associated with the previous dragEnter invocation.
  • That Component still has a DropTarget associated.
  • That DropTarget is still active.
  • The DropTarget's registered DropTargetListener dragOver method is invoked and returns successfully.
  • The DropTarget does not reject the drag via rejectDrag.

The DragSourceListener's dragExit method is invoked when one of the following conditions is true:

  • The cursor's logical hotspot no longer intersects the visible geometry of the Component associated with the previous dragEnter invocation.

    Or:

  • The Component that the logical cursor's hotspot intersected that resulted in the previous dragEnter invocation, no longer has an active DropTarget (or DropTargetListener) associated.

    Or:

  • The current DropTarget's DropTargetListener has invoked rejectDrag since the last dragEnter or dragOver invocation.

The DragSourceListener's dropActionChanged() method is invoked when the state of the input device(s), typically the mouse buttons or keyboard modifiers, that the user is interacting with in order to perform the drag operation, changes.

The dragDropEnd() method is invoked to signify that the operation is completed. The getDropSuccess method of the DragSourceDropEvent can be used to determine the termination state. The getDropAction method returns the operation that the DropTarget selected (via the DropTargetDropEvent acceptDrop parameter) to apply to the drop operation.

Once this method is complete the current DragSourceContext and the associated resources are invalid.

2.3.4 The DragSourceEvent Definition

The DragSourceEvent class is the root Event class for all events pertaining to the DragSource, and is defined as follows:

public class   java.awt.dnd.DragSourceEvent extends java.util.EventObject {
        public DragSourceEvent(DragSourceContext dsc);
        public DragSourceContext getDragSourceContext();
        //...
};

An instance of this event is passed to the DragSourceListener dragExit method.

2.3.5 The DragSourceDragEvent Definition

The DragSourceDragEvent class is defined as follows:

public class java.awt.dnd.DragSourceDragEvent extends DragSourceEvent {
        public int getTargetActions();
        public int getUserAction();
        public int getGestureModifiers();
        public int getGestureModifiersEx();
        public int getDropAction();
}

An instance of the above class is passed to a DragSourceListener's dragEnter, dragOver, and dragGestureChanged methods.

The getDragSourceContext method returns the DragSourceContext associated with the current drag and drop operation.

The getUserAction method returns the action that is currently selected by the user's gesture.

The getTargetActions method returns the drop action selected by the current drop target if this drop action is supported by the drag source or DnDConstants.ACTION_NONE if this drop action is not supported by the drag source.

The logical intersection of these two results and the set of drop actions supported by the drag source defines the actual effect of a drop and is returned via getDropAction.

The getGestureModifiers method returns the current state of the input device modifiers, usually the mouse buttons and keyboard modifiers, associated with the user's gesture.

The getGestureModifiersEx method returns the current state of the input device extended modifiers associated with the user's gesture.

2.3.6 The DragSourceDropEvent Definition

The DragSourceDropEvent class is defined as follows:

public public class java.awt.dnd.DragSourceDropEvent
                        extends java.util.EventObject {
       public DragSourceDropEvent(DragSourceContext dsc);
       public DragSourceDropEvent(DragSourceContext dsc,
                                int  action,
                                boolean success);
       public boolean getDropSuccess();
       public int getDropAction();
}

An instance of the above class is passed to a DragSourceListener's dragDropEnd method. This event encapsulates the termination state of the drag and drop operation for the DragSource.

If the drop occurs, then the participating DropTarget will signal the success or failure of the data transfer via the DropTargetContext's dropComplete method, this status is made available to the initiator via the getDropSuccess method. The operation that the destination DropTarget selected to perform on the subject of the drag (passed by the DropTarget's acceptDrop method) is returned via the getDropAction method.

If the drag operation was aborted for any reason prior to a drop occurring, for example if the user ends the gesture outside a DropTarget, or if the DropTarget invokes rejectDrop, the getDropSuccess method will return false, otherwise true.

2.4 Drop Target

2.4.1 java.awt.Component additions for DropTarget (de)registration.

The java.awt.Component class has two additional methods added to allow the (dis)association with a DropTarget. In particular:

public class java.awt.Component /* ... */ {
        //...
        public synchronized void setDropTarget(DropTarget dt);
        public synchronized DropTarget getDropTarget(DropTarget df);
        //...
}

To associate a DropTarget with a Component one may invoke either; DropTarget.setCompononent or Component.setDropTarget methods. Thus conforming implementations of both methods are required to guard against mutual recursive invocations.

To disassociate a DropTarget with a
Component one may invoke either;
DropTarget.setCompononent(null) or
Component.setDropTarget(null) methods.

Conformant implementations of both setter methods in DropTarget and Component should be implemented in terms of each other to ensure proper maintenance of each other's state.

The setDropTarget method throws IllegalArgumentException if the DropTarget actual parameter is not suitable for use with this class/instance of Component. It may also throw UnsupportedOperationException if, for instance, the Component does not support external setting of a DropTarget.

2.4.2 The DropTarget Definition

A DropTarget encapsulates all of the platform-specific handling of the Drag and Drop protocol with respect to the role of the recipient or destination of the operation.

A single DropTarget instance may typically be associated with any arbitrary instance of java.awt.Component. Establishing such a relationship exports the associated Components geometry to the client desktop as being receptive to drag and drop operations when the coordinates of the logical cursor intersects that visible geometry.

The DropTarget class is defined as follows:

public class java.awt.dnd.DropTarget
       implements DropTargetListener, Serializable {

        public DropTarget(Component          c,
                       int                actions,
                       DropTargetListener dsl,
                       boolean            isActive,
                       FlavorMap          fm
        );
        public DropTarget();
        public DropTarget(Component c);
        public DropTarget(Component c, DropTargetListener dsl);
        public Component getComponent();
        public void      setComponent(Component c);
        public DropTargetContext getDropTargetContext();
        public void addDropTargetListener(DropTargetListener dte)
                  throws TooManyListenersException;
        public void removeDropTargetListener(DropTargetListener dte);
        public void setActive(boolean active);
        public boolean isActive();
        public FlavorMap getFlavorMap();
        public void      setFlavorMap(FlavorMap fm);
        public void setDefaultActions(int actions);
        public int  getDefaultActions();
        protected DropTargetContext createDropTargetContext();
        public void addNotify(ComponentPeer cp);
        public void removeNotify(ComponentPeer cp);
        // ...
}

The setComponent method throws IllegalArgumentException if the Component actual parameter is not appropriate for use with this class/instance of DropTarget, and may also throw UnsupportedOperationException if the Component specified disallows the external setting of a DropTarget.

The addDropTargetListener and removeDropTargetListener methods allow the unicast DropTargetListener to be changed.

The setActive and isActive methods allow the DropTarget to be made active or otherwise and for its current state to be determined.

The getFlavorMap methods is used to obtain the FlavorMap associated with this DropTarget for the purposes of mapping any platform dependent type names to/from their corresponding platform independent DataFlavors.

The setFlavorMap method allows a new FlavorMap to be assigned to the DropTarget, a parameter of null causes a "default" FlavorMap to be installed for the DropTarget.

The createDropTargetContext method is only invoked to provide the underlying platform dependent peer with an instantiation of a new DropTargetContext as a Drag operation initially encounters the Component associated with the DropTarget. If no DropTargetContext is currently associated with a DropTarget, a permitted side-effect of an invocation of getDropTargetContext is to instantiate a new DropTargetContext.

The addNotify and removeNotify methods are only called from Component to notify the DropTarget of the Component's (dis)association with its ComponentPeer.

Note that the DropTarget itself implements DropTargetListener, this is to allow the platform peer, the DropTargetContextPeer instance, created by the platform, to notify the DropTarget of changes in state in the ongoing operation, and thus allows the DropTarget to interpose itself between the platform and the DropTargetListener registered with the DropTarget.

2.4.3 The DropTargetContext Definition

As the logical cursor associated with an ongoing drag and drop operation first intersects the visible geometry of a Component with an associated DropTarget, the DropTargetContext associated with the DropTarget is the interface, through which, access to, and control over state of the recipient protocol is achieved from the DropTargetListener.

A DropTargetContext is created by a DropTarget, via it's createDropTargetContext method, as a side effect of a call to a DropTarget's getDropTargetContext method, if no <>DropTargetContext currently exists for that DropTarget.

The DropTargetContext interface is defined as follows:

public class DropTargetContext {
        public DropTarget getDropTarget();
        public Component getComponent();
        public void  dropComplete(boolean success)
                                throws InvalidDnDOperationException;
        public void acceptDrag(int dropAction);
        public void rejectDrag();
        public void acceptDrop(int dropAction);
        public void rejectDrop();
        public void addNotify(DropTargetContextPeer dtcp);
        public void removeNotify();
        protected Transferable createTransferableProxy(Transferable t,
                   boolean isLocal
        );
        protected void setTargetActions(int actions);
        protected int  getTargetActions();
        protected DataFlavor[] getCurrentDataFlavors();
        protected List getCurrentDataFlavorsAsList();
        protected boolean isDataFlavorSupported(DataFlavor df);
        protected Transferable getTransferable();
        // ...
}

Most of the access and control methods are protected, since public access to their state is usually achieved by calling through a particular DropTargetEvent subclass that delegates the request to the DropTargetContext.

The getDropTarget() method return the DropTarget that created this DropTargetContext.

The getComponent method returns the Component associated with the DropTarget that created this DropTargetContext.

The acceptDrag method is delegated from the similar method on DropTargetDragEvent and is invoked from one of the DropTargetListener's methods; dragEnter(), dragOver or dropActionChanged to signify that the recipient is prepared to accept a drop with the operation specified, which is usually the user's currently selected action.

The rejectDrag method is delegated from the similar method on DropTargetDragEvent and is invoked from one of the DropTargetListener's methods; dragEnter, dragOver or dropActionChanged to signify that the recipient is unable to accept a drop with the user's currently selected action.

The acceptDrop method is delegated from the similar method on DropTargetDropEvent and is invoked from the DropTargetListener's drop method to signify that the recipient is prepared to accept a drop with the operation specified, which is usually the user's currently selected action.

The rejectDrop method is delegated from the similar method on DropTargetDropEvent and is invoked from the DropTargetListener's drop method to signify that the recipient is unable to accept a drop with the user's currently selected action. This terminates a drag and drop operation without a data transfer.

The dropComplete method signals to the originating DragSource that the DropTargetListener has completed the transfer(s) that comprise the subject of the drag and drop operation and that the operation is complete. The success (or failure) of the transfer(s) and the subsequent application of the operation specified is signaled by the value of the actual parameter.

The getDataFlavors method returns an array of the DataFlavors available from the DragSource.

The getTransferable method returns a Transferable (not necessarily the one the DragSource registered, it may be a proxy, and certainly shall be in the inter-JVM case) to enable data transfers to occur via its getTransferData method. Note that it is illegal to invoke getTransferable without first invoking an acceptDrop.

The addNotify and removeNotify methods are exclusively called by the underlying platform's DropTargetContextPeer in order to notify the DropTargetContext that a drag and drop operation is occurring/ceasing on the DropTargetContext and associated DropTarget.

The createTransferableProxy method enables a DropTargetContext implementation to interpose a Transferable between the DropTargetListener and the Transferable provided by the caller, which is typically the underlying platform DropTargetContextPeer.

2.4.4 The DropTargetListener Definition

Providing the appropriate "Drag-under" feedback semantics, and processing of any subsequent Drop, is enabled through the DropTargetListener asssociated with a DropTarget.

The DropTargetListener determines the appropriate "Drag-under" feedback and its response to the DragSource regarding drop eligibility by inspecting the sources suggested actions, the data types available and the data itself.

A particular DropTargetListener instance may be associated with a DropTarget via addDropTargetListener and removed via removeDropTargetListener methods.

public interface java.awt.dnd.DropTargetListener
        extends java.util.EventListener {
        void dragEnter            (DropTargetDragEvent dtde);
        void dragOver             (DropTargetDragEvent dtde);
        void dropActionChanged    (DropTargetDragEvent dtde);
        void dragExit             (DropTargetDragEvent dtde);
        void drop                 (DropTargetDropEvent dtde);
}

The following context describes this graphic.

The dragEnter method of the DropTargetListener is invoked when the hotspot of the logical "Drag" Cursor intersects a visible portion of the DropTarget's associated Component's geometry. The DropTargetListener, upon receipt of this notification, shall interrogate the operations or actions, and the types of the data (DataFlavors) and the data itself as supplied by the DragSource to determine the appropriate actions and "Drag-under" feedback to respond with invocation of either acceptDrag or rejectDrag.

The dragOver method of the DropTargetListener is invoked while the hotspot of the logical "Drag" Cursor, in motion, continues to intersect a visible portion of the DropTarget's associated Component's geometry. The DropTargetListener, upon receipt of this notification, shall interrogate the operation "actions" the types of the data and the data itself as supplied by the DragSource to determine the appropriate "actions" and "Drag-under" feedback to respond with an invocation of either acceptDrag or rejectDrag.

The dragExit method of the DropTargetListener is invoked when the hotspot of the logical "Drag" Cursor ceases to intersect a visible portion of the DropTarget's associated Component's geometry, or immediately prior to a drop notification. The DropTargetListener, upon receipt of this notification, shall undo any "Drag-under" feedback effects it has previously applied. Note that the DropTargetContext associated with the DropTarget is invalidated as a side-effect.

The drop method of the DropTargetListener is invoked as a result of the user terminating their drag gesture while intersecting. The DropTargetListener, upon receipt of this notification, shall perform the operation specified by the return value of the getSourceActions method on the DropTargetDropEvent object, upon the Transferable object returned from the getTransferable method, and subsequently invoke the dropComplete method of the associated DropTargetContext to signal the success, or otherwise, of the operation.

2.4.5 The DropTargetDragEvent and DropTargetDropEvent Definitions

The DropTargetEvent and DropTargetDragEvent are defined as follows:

public abstract class java.awt.dnd.DropTargetEvent
          extends java.util.EventObject {

        public DropTargetContext getDropTargetContext();
        //...
}

A DropTargetEvent is passed to the DropTargetListener's dragExit method.

public class   java.awt.dnd.DropTargetDragEvent
                         extends java.awt.dnd.DropTargetEvent {
        public Transferable getTransferable();
        public Point  getLocation();
        public int   getSourceActions();
        public getDropAction();
        public DataFlavor[] getCurrentDataFlavors();
        public List  getCurrentDataFlavorsAsList();
        public boolean isDataFlavorSupported();
        public void acceptDrag(int operation);
        public void rejectDrag();
        //...
}

A DropTargetDragEvent is passed to the DropTargetListener's dragEnter, dragOver and dropActionChanged methods.

The getLocation method return the current co-ordinates, relative to the associated Component's origin, of the hotspot of the logical "Drag" cursor.

The getSourceActions method returns the current "actions", or operations (ACTION_MOVE, ACTION_COPY, or ACTION_REFERENCE) the DragSource associates with the current drag and drop gesture.

The return value of the getDropAction method is the action that is selected by the user's gesture.

The getCurrentDataFlavors, getCurrentDataFlavorsAsList and isDataFlavorSupported methods are provided in order for the recipient to interrogate the list of types available from the source.

The getTransferable method is provided in order for the recipient to interrogate the data available from the source. Note that getTransferable on the DropTargetDragEvent instance should only be called within the respective DropTargetListener's method, and all the necessary data should be retrieved from the returned Transferable before that method returns.

The DropTargetDropEvent is defined as follows:

public class java.awt.dnd.DropTargetDropEvent
          extends java.awt.dnd.DropTargetEvent {

        public Point      getLocation();
        public int getSourceActions();
        public int getDropAction();
        public void acceptDrop(int dropAction);
        public void rejectDrop();
        public boolean isLocalTransfer();
        public DataFlavor[] getCurrentDataFlavors();
        public List  getCurrentDataFlavorsAsList();
        public boolean isDataFlavorSupported(DataFlavor df);
        public Transferable getTransferable();
        public void dropComplete(boolean success);
        //...
}

A DropTargetDropEvent is passed to the DropTargetListener's drop method, as the drop occurs. The DropTargetDropEvent provides the DropTargetListener with access to the data associated with the operation, via the Transferable returned from the getTransferable method.

The return value of the getSourceActions method is defined to be the action(s) defined by the source at the time at which the drop occurred.

The return value of the getDropAction method is the action that is selected by the user's gesture.

The return value of the getLocation method is defined to be the location at which the drop occurred.

The getCurrentDataFlavors, getCurrentDataFlavorsAsList, and isDataFlavorSupported, methods are provided in order for the recipient to interrogate the list of types available from the source for subsequent transfer via the getTransferData method of the Transferable.

A typical implementation of the drop method will inspect the actions and the DataFlavors' available to determine if a successful exchange can occur or not.

When an exchange may occur, a DropTargetListener.drop implementation shall invoke acceptDrop with the selected operation as an actual parameter, prior to any invocation of getTransferable. Calling getTransferable prior to acceptDrop shall result in an InvalidDnDOperationException.

The rejectDrop shall be called to reject the drop operation. Once called no further interaction can occur between the two participants, therefore it is typical to return from the drop method immediately after calling this.

The isLocalTransfer method shall return true, if the source of the drag and drop operation resides within the same physical JVM as the recipient of the drop notification, and false otherwise.

This distinction is significant to the recipient when it receives object references back from invoking Transferable.getTransferData in the local case, since in this case the object reference it receives is the same object reference held by the source (i.e it is not a copy, proxy or distinct object) thus the recipient must treat such a shared object reference differently in the local case as follows:

  • If the action is ACTION_COPY then the recipient shall, depending upon the nature of the object(s) and data transferred, either take a copy of; the object itself, the data encapsulated within, or both.
  • If the action is ACTION_MOVE, then the recipient shall not modify the state of the object or the data encapsulated within until after it has signalled to the source, via an invocation of dropCompete that the transfer is effected. (Note that a source is also prohibited from modifying the state of such an object after it has returned such an object from it's getTransferData method, until such time as it receives a dragDropEnd notification.)
  • If the action is ACTION_LINK, neither the recipient nor the source shall alter the state of either the object exchanged or any data contained therein until after the dropComplete and dragDropEnd methods have been processed. Thereafter the sharing semantics are implementation dependent upon the object(s) shared.

The dropComplete method signals the end of the associated drag and drop operation, and indicates the success (or failure) of the transfers performed by the recipient. Invoking this method results in the DragSourceListener's dragDropEnd method being called with the appropriate state available from it's DragSourceDropEvent. Failure to invoke this method will result in the drag and drop operation failing to terminate properly.

2.4.6 Autoscrolling Support

Many GUI Components present a scrollable "viewport" over a (potentially) large dataset. During a drag and drop operation it is desirable to be able to "autoscroll" such "viewports" to allow a user to navigate over such a dataset, scrolling to locate a particular member (initially not visible through the "viewport") that they wish to drop the subject of the operation upon.

Components that are scrollable provide drag "autoscrolling" support to their DropTarget by implementing the following interface:

public interface Autoscroll {
        Insets getAutoscrollInsets();
        void autoScrollContent(Point cursorLocn);
}

An implementing DropTarget shall periodically call the autoscroll method of its associated Component (if present), passing the current logical cursor location in Component co-ordinates, when the following conditions are met:

  • If the logical cursor's hotspot intersects with the associated Component's visible geometry and the boundary region described by the Insets returned by the getAutoscrollInsets method.
  • If the logical cursor's hotspot has not moved (subject to the next condition below) for an implementation defined period (millisecs)
  • If any cursor movement subsequent to the initial triggering occurrence does not exceed a platform dependent hysteresis value (pixels).

Should any of the above conditions cease to be valid, autoscrolling shall terminate until the next triggering condition occurs.

Both the initial delay prior to autoscrolling commencing, the interval between autoscrolling notifications, and the pixel hysteresis value are externally configurable and can be queried from the Toolkit.getDesktopProperty method.

2.5 Data Transfer Phase

In the case where a valid drop occurs, the DropTargetListener's drop method is responsible for undertaking the transfer of the data associated with the gesture. The DropTargetDropEvent provides a means to obtain a Transferable object that represent that data object(s) to be transferred.

From the drop method, the DropTargetListener shall initially either rejectDrop (immediately returning thereafter) or acceptDrop specifying the selected operation from those returned by getSourceActions.

Subsequent to an acceptDrop, but not before, getTransferable may be invoked, and any data transfers performed via the returned Transferable's getTransferData method. Finally, once the destination of the drop has completed the transfer(s) of the objects from the source it shall signal the success, or immediate failure, of the transfer(s) via an invocation of DropTargetContext.dropComplete.

Upon returning from the DropTargetContext.dropComplete method the Transferable and DragSourceContext instances are no longer guaranteed to be valid and all references to them shall be discarded by the recipient to allow them to be subsequently garbage collected.

When using the ACTION_REFERENCE operation the source and destination should take care to agree upon the object and the associated semantics of the transfer. Typically in intra-JVM transfers a live object reference would be passed between source and destination, but in the case of inter-JVM transfers, or transfers between native and Java applications, live object references do not make sense, so some other ‘reference' type should be exchanged such as a URI for example. Both the DragSource and DropTarget can detect if the transfer is intra-JVM or not.

2.5.1 FlavorMap and SystemFlavorMap

All the target DnD platforms represent their transfer data types using a similar mechanism, however the representations do differ. The Java platform uses MIME types encapsulated within a DataFlavor to represent its data types. Unfortunately in order to permit the transfer of data between Java and platform native applications the existence of these platform names need to be exposed, thus a mechanism is required in order to create an extensible (platform independent) mapping between these platform dependent type names, their representations, and the Java MIME based DataFlavors.

The implementation will provide a mechanism to externally specify a mapping between platform native data types (strings) and MIME types (strings) used to construct DataFlavors. This external mapping will be used by the underlying platform specific implementation code in order to expose the appropriate DataFlavors (MIME types), exported by the source, to the destination, via the underlying platform DnD mechanisms.

Both the DragSource and DropTarget classes provide access for the underlying system to map platform dependent names to and from DataFlavors.

public interface java.awt.datatransfer.FlavorMap {
        java.util.Map getNativesForFlavors(DataFlavor[] dfs);
        java.util.Map getFlavorsForNatives(String[] natives);
}

The getNativesForFlavors method takes an array of DataFlavors and returns a Map object containing zero or more keys of type DataFlavor, from the actual parameter dfs, with associated values of type String, which correspond to the platform-dependent type name for that MIME type.

The getFlavorsForNatives method takes an array of String types and returns a Map object containing zero or more keys of type String, from the actual parameter natives, with associated values of type DataFlavor, which correspond to the platform-independent type for that platform-dependent type name.

The Map object returned by both methods may be mutable but is not required to be.

If NULL is passed to either of these methods they should return their current map of all keys and values known to the implementation at the time of the call.

For example on Win32 the Clipboard Format Name for simple text is "CF_TEXT" (actually it is the integer 1) and on Motif it is the X11 Atom named "STRING", the MIME type one may use to represent this would be "text/plain;charset=us-ascii". Therefore a platform portable FlavorMap would map between these names; CF_TEXT on win32 and STRING on Motif/X11.

Typically, as implemented in the SystemFlavorMap these mappings are held in an external persistent configuration format (a properties file or URL) and are loaded from the platform to configure the FlavorMap appropriately for a given platform.

The SystemFlavorMap class is provided to implement a simple, platform configurable mechanism for specifying a system-wide set of common mappings, and is defined as follows:

public class  java.awt.datatransfer.SystemFlavorMap implements FlavorMap, FlavorTable {
        public static FlavorMap getSystemFlavorMap();
        public synchronized Map getNativesForFlavors(DataFlavor[] dfs);
        public synchronized Map getFlavorsForNatives(String[] natives);
        public static String encodeDataFlavor(DataFlavor flav);
        public static String encodeJavaMIMEType(String mimeType);
        public static boolean isJavaMIMEType(String mimeStr);
        public static String decodeJavaMIMEType(String nat);
        public static DataFlavor decodeDataFlavor(String nat);
        //...
}

The SystemFlavorMap class provides a simple implementation, using a properties file (see java.awt.Properties), of a persistent platform FlavorMap. Using the value of the AWT property "AWT.flavorMapFileURL" (see Toolkit.getProperty) or the default file location of System.getProperty("java.home") + File.separator + "lib" + File.separator + "flavormap.properties", this class creates the appropriate Maps from the properties found therein.

In addition the class provides several static convenience functions used to encode and decode Java MimeTypes to and from a platform dependent namespace. The syntax of the properties file is:

{ <platform_type_name> ‘=' <IETF_MIME_RFC_conformant_specification> <nl> } *

The default implementations of DragSource and DropTarget return the SystemFlavorMap from their getFlavorMap method, unless they have been provided with an overriding implementation.

2.5.2 Transferring Data across the JVM boundary

Since one of the primary goals of this API is to allow drag and drop of data between Java and native applications this has some significant consequences upon the method and mechanism of the actual data encoding and exchange when data is passed across the boundary of the Java Virtual Machine.

Since one of the participants in such an exchange may be a native application, and thus has no knowledge of the Java type system, the drag and drop system cannot just exchange a Java object reference since the other participant may have no knowledge of, or capability to manipulate such a type.

When any exchange occurs, it can only do so, regardless of the implementation of the participants, if and only if both participants are agreed upon a familiar data type and encoding. Thus, sadly the burden of the exchange is born mostly by the participants themselves.

What this means in practical terms is that for "native" data formats, such as platform-dependent image, document, or other "Content-Types" the encoding and decoding of their associated external data format is the responsibility of the source and destination of the transfer.

The drag and drop system shall expose the external representation of such "native" data types across the boundary of the Java Virtual Machine as encapsulated within a java.io.InputStream or a subclass thereof.

This means that any DataFlavor with a representation class that extends java.io.InputStream can be transferred, and will be exposed for transfer, across the Java Virtual Machine boundary.

To implement the exchange of such a native data type, a developer would define a DataFlavor with a MIME "Content-Type" that describes the nature of the "native" data type, with a representation class that extends a java.io.InputStream class that encodes the data encapsulated into a stream of bytes.

In particular such InputStream subclasses shall implement the following semantics:

  • Provide a public constructor with a single argument of type java.io.InputStream.

    Provision of this constructor by a subclass of java.io.InputStream will allow the drag and drop system (associated with the DropTarget) to automatically re-construct an instance of the representation class specified by the requested DataFlavor, and initialize it with an InputStream containing the encapsulated data formatted according to the expectations of that subclass. Once initialized this instance is returned to the caller of the Transferable.getTransferData method, thus allowing the caller to subsequently re-read and interpret the formatted content of the data stream transferred.

  • Provide an implementation of InputStream.read(byte b[], int off, int len).

Provision of this method (or inheriting a superclasses implementation) enables the drag and drop system (associated with the DragSource) to automatically extract an encoded stream of the encapsulated data from the Transferable, thus enabling the transfer of the data across the JVM boundary as a simple byte stream to the requestor of the particular DataFlavor.

2.5.3 Transferring lists of files across the JVM boundary.

A typical subject of a Drag and Drop transfer is a list of one or more platform dependent filenames. In order to ease the programming task of developers either producing or consuming such lists the drag and drop system treats them as a special case.

If a DataFlavor is specified with a MIME "Content-Type" of application/x-java-file-list;class=java.util.List the drag and drop system will expect the list elements to be a homogeneous list of objects of type java.io.File. Thus a source shall, if supporting the transfer of a list of files, construct such a List of File objects when such a DataFlavor is requested, and a recipient shall expect such a List of File objects if it requests such a valid DataFlavor from its source. This special case provides a simple mechanism for the transfer of lists of files between source and target.

2.5.4 Transferring java.rmi.Remote references across the JVM boundary.

It is possible to Drag and Drop object references between JVMs' by using the facilities of the RMI mechanism. The Drag and Drop system will automatically arrange for the transfer of any object reference that adheres to these requirements:

  • The representation class of interface associated with the requested DataFlavor implements both java.rmi.Remote and java.io.Serializable.

    (the MIME "Content-Type" can be any suitable, arbitrary type or application/x-java-remote-object)

    (effectively the object implementation class transferred should be extended from java.rmi.server.UnicastRemoteObject since the RMI system implements some required initialization, without which the transfer will not complete properly).

  • The drop action is ACTION_LINK.

If these conditions are met, then if an appropriate DataFlavor is requested, then the object returned to the requestor (if it is in a difference JVM from the source) will be an RMI reference to an instance of the Remote object subinterface specified as the representation class of the DataFlavor.

3.0 Issues

3.0.1 What are the implications of the various platform protocol engines?

Due to limitations of particular underlying platform drag and drop and window system implementations, the interaction of a drag operation, and the event delivery semantics to AWT Components is platform dependent. Therefore during a drag operation a DragSource may process platform Window System Events pertaining to that drag to the exclusion of normal event processing.

Due to interactions between the single-threaded design center of the platform native DnD systems, and the native window system event dispatching implementations in AWT, "callbacks" into DropTargetListener and DragSourceListener will occur either on, or synchronized with the AWT system event dispatch thread. This behavior is highly undesirable for security reasons but is an implementation, not architectural feature, and is unavoidable.

3.0.2 Inter/Intra VM transfers?

To enable intra-JVM Drag and Drop Transfers the existing DataFlavor class will be extended to enable it to represent the type of a "live" object reference, as opposed to a Serialized (persistent) representation of one. Such objects may be transferred between source and destination within the same JVM and ClassLoader context.

The MIME Content-Type shall be application/x-java-local-objectref.

3.0.3 Lifetime of the Transferable(s)?

Transferable objects, their associated DataFlavors', and the objects that encapsulate the underlying data specified as the operand(s) of a drag and drop operation shall remain valid until, at least, the DragSourceListener associated with the DragSource controlling the operation, receives a dragDropEnd. The lifetime of the subject(s) of the operation, transferred between source and target is implementation defined beyond that point in time.

3.0.4 Implications of ACTION_MOVE semantics on source objects exposed via Transferable?

The "source" of a successful Drag and Drop (ACTION_MOVE) operation is required to delete/relinquish all references to the object(s) that are the subject of the Transferable immediately after transfer has been successfully completed. That is before returning from the DragSourceListener.dragDropEnd notification.

3.0.5 Semantics of ACTION_REFERENCE operation.

As a result of significant input from developers to an earlier version of the specification an additional operation/action tag; ACTION_REFERENCE was added to include existing platform Drag and Drop"Link" semantics.

It is believed that Reference, or Link, semantics are already sufficiently poorly specified for the platform native Drag and Drop to render it essentially useless even between native applications, thus between native and platform independent Java applications it is not recommended.

For Java to Java usage the required semantic; within the same JVM/ClassLoader, is defined such that the destination shall obtain a Java object reference to the subject(s) of the transfer. Between Java JVM's or ClassLoaders, the semantic is implementation defined, but could be implemented through transferring either a URL from the source to the destination or an RMI Remote reference.

Appendix A : DropTargetPeer definition

Although not a normative part of this specification this definition is included for clarity:

public interface DropTargetPeer {
        void addDropTarget(DropTarget dt);
        void removeDropTarget(DropTarget dt);
}

Appendix B : DragSourceContextPeer definition

Although not a normative part of this specification this definition is included for clarity:

public interface DragSourceContextPeer {
    void startDrag(DragSourceContext dsc,
                   Cursor            c,
                   Image             di,
                   Point             ioff
    ) throws InvalidDnDOperationException;
    Cursor getCursor();
    void   setCursor(Cursor c) throws InvalidDnDOperationException;
    void transferablesFlavorsChanged();
}

Appendix C : DropTargetContextPeer definition

Although not a normative part of this specification this definition is included for clarity:

public interface DropTargetContextPeer {
    int  getTargetActions();
    void setTargetActions(int actions);
    DropTarget getDropTarget();
    DataFlavor[] getTransferDataFlavors();
    Transferable getTransferable() throws InvalidDnDOperationException;
    boolean isTransferableJVMLocal();
    void acceptDrag(int dragAction);
    void rejectDrag();
    void acceptDrop(int dropAction);
    void rejectDrop();
    void dropComplete(boolean success);
}
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.javadoc.Doc (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.javadoc.Doc

    • Uses of Doc in com.sun.javadoc

      Subinterfaces of Doc in com.sun.javadoc
      Modifier and Type Interface and Description
      interface  AnnotationTypeDoc
      Represents an annotation type.
      interface  AnnotationTypeElementDoc
      Represents an element of an annotation type.
      interface  ClassDoc
      Represents a java class or interface and provides access to information about the class, the class's comment and tags, and the members of the class.
      interface  ConstructorDoc
      Represents a constructor of a java class.
      interface  ExecutableMemberDoc
      Represents a method or constructor of a java class.
      interface  FieldDoc
      Represents a field in a java class.
      interface  MemberDoc
      Represents a member of a java class: field, constructor, or method.
      interface  MethodDoc
      Represents a method of a java class.
      interface  PackageDoc
      Represents a java package.
      interface  ProgramElementDoc
      Represents a java program element: class, interface, field, constructor, or method.
      interface  RootDoc
      Represents the root of the program structure information for one run of javadoc.
      Methods in com.sun.javadoc that return Doc
      Modifier and Type Method and Description
      Doc Tag.holder()
      Return the containing Doc of this Tag element.
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.javadoc.DocErrorReporter (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.javadoc.DocErrorReporter

    • Uses of DocErrorReporter in com.sun.javadoc

      Subinterfaces of DocErrorReporter in com.sun.javadoc
      Modifier and Type Interface and Description
      interface  RootDoc
      Represents the root of the program structure information for one run of javadoc.
      Methods in com.sun.javadoc with parameters of type DocErrorReporter
      Modifier and Type Method and Description
      static boolean Doclet.validOptions(String[][] options, DocErrorReporter reporter)
      Check that options have the correct arguments.
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Java Print Service API User Guide: 3 - Specifying Document Types

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT
CHAPTER 3

Specifying Document Types

From the user's perspective, a document can take many different forms, including: a PDF file, an image from a digital camera, an email, a word processor document, or a web page. Before printing a document of a particular format, the client needs to ensure that the printer can understand the format. Sometimes a printer can directly print documents of a given format: photo printers can directly print images of various formats, and PostScript™ printers can directly print a PostScript™ document. However, there are few printers that can directly print a wide range of formats; most printers require some higher-level software support to translate the source document into a format they can print.

A printing API needs to provide a way to describe document types so that:

  • The printer can report what formats it can print.
  • The client can describe the format of the data it wants to print.
  • The client can describe the encoding of text data.
The Java™ Print Service API describes document types using the DocFlavor class. A DocFlavor is comprised of:
  • A MIME type that tells the printer how to interpret the data.
  • A representation class name indicating the Java class that describes how the data is sent to the printer.
To describe an HTML page to a print service, a client might choose to use a DocFlavor with a MIME type string of "text/html; charset=utf-16" and a representation class name of "java.io.InputStream". The client can obtain this DocFlavor in one of two ways:
  • Construct a DocFlavor:DocFlavor htmlStreamFlavor = new DocFlavor("text/html; charset=utf-16", "java.io.InputStream");
  • Use the pre-defined instance that represents this type of DocFlavor:DocFlavor.INPUT_STREAM TEXT_HTML_UTF_16 . The Java Print Service API provides a set of pre-defined instances for common doc flavors as a convenience.
Because the HTML page contains text data, the MIME type String includes the text encoding, which is charset=utf-16 in this example. The client is responsible for accurately describing the print data to the print service. The section, Client-Formatted Print Data, explains how to properly construct a DocFlavor to accomplish this. If the text encoding is not included in the MIME type, unexpected results can occur, as explained in the section, Importance of Character Encoding. The client can allow the service to determine the format of data that the client supplies as a Java object. The Service-Formatted Print Data section describes using a DocFlavor to represent service-formatted print data.

Keep in mand that, just because the DocFlavor API has a pre-declared doc flavor, this doesn't mean that an implementation of the particular flavor is available. For example, even if you use the pre-defined DocFlavor representing HTML text in UTF-16, you won't be able to print the HTML unless you have a print service that supports printing HTML. Again, it is the user's responsibility to ensure that a printer supports a particular format.

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 3 - Specifying Document Types

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

Client-Formatted Print Data

The client uses the DocFlavor to describe the print data format and to indicate how the data will be delivered to the print service. The MIME type specifies the data format. The representation class name specifies how the data will be delivered to the printer.

The DocFlavor class has an inner class for each of the common representation class names. Each inner class contains a set of DocFlavor object constants representing formats that can be delivered using the representation class. For example, an input stream can stream many different kinds of print data formats, including GIF, represented by DocFlavor.INPUT_STREAM.GIF, and PostScript™, represented by DocFlavor.INPUT_STREAM.POSTSCRIPT. If one of the DocFlavor object constants accurately describes the format of a given piece of print data, the client can use this constant instead of constructing a DocFlavor.

If the appropriate DocFlavor is not already defined in the JPS API, a client can create it with the DocFlavor constructor. The client can use the MIME types and representation class names explained in the next two sections to construct the DocFlavor.

MIME Types for Preformatted Data

The four most common types of preformatted data are: text data, page description language documents, image data, and autosense print data. This section describes each one of these data types and lists their corresponding MIME types.

Text Data

Preformatted text data is usually provided in a character-oriented representation class, such as a character array, String, or Reader, or in a byte-oriented representation class, such as a byte array, input stream, or URL. Plain text and HTML are two common forms of preformatted text data. You can use these MIME type strings to represent the format of the data when constructing a DocFlavor:

MIME type | Format of data
"text/plain" | Plain text in the default character set US-ASCII
"text/plain;charset=xxx" | Plain text in character set xxx
"text/html" | HyperText Markup Languge in the default character set (US-ASCII)
"text/html;charset=xxx" | HyperText Markup Languge in the character set xxx

Page Description Language Documents

Preformatted page description language (PDL) documents are usually provided in a byte-oriented representation class, such as byte array, InputStream, or URL. You can use these MIME type strings to represent the format of the data when constructing a DocFlavor:

MIME type | Format of data
"application/pdf" | Portable Document Format document
"application/postscript" | PostScript™ document
"application/vnd.hp-PCL" | Printer Control Language document

Image Data

Preformatted image data is provided in a byte-oriented representation class: byte array, InputStream, or URL. You can use these MIME type strings to represent the format of the data when constructing a DocFlavor:

MIME type | Format of data
"image/gif" | Graphics Interchange Format image
"image/jpeg" | Joint Photographic Experts Group image
"image/png" | Portable Network Graphics image

Autosense Print Data

Preformatted autosense print data allows the printer to decide how to interpret the print data. This type of data is usually provided in a byte-oriented representation class. You can use this MIME type string to represent the format of the data when constructing a DocFlavor:

"application/octet-stream"

Representation Classes

For client-formatted print data, the print data representation class is usually one of the following:

Print data representation class | Description
Character array (char[]) | The print data consists of the Unicode characters in the array. This representation class can provide text data and PDL data.
java.lang.String | The print data consists of the Unicode characters in the string. This representation class can provide text data.
A Character stream represented by java.io.Reader | The print data consists of the Unicode characters read from the stream up to the end-of-stream. This representation class can provide text data.
Byte array (byte[]) | The print data consists of the bytes in the array. The bytes are encoded in the character set specified by the doc flavor's MIME type. If the MIME type does not specify a character set, the default character set is US-ASCII. This representation class can provide text data, PDL documents, and image data.
A Byte stream represented by java.io.InputStream | The print data consists of the bytes read from the stream up to the end-of-stream. The bytes are encoded in the character set specified by the doc flavor's MIME type. If the MIME type does not specify a character set, the default character set is US-ASCII. This representation class can provide text data, PDL documents, and image data.
Uniform Resource Locator, java.net.URL | The print data consists of the bytes read from the URL location. The bytes are encoded in the character set specified by the doc flavor's MIME type. If the MIME type does not specify a character set, the default character set is US-ASCII. This representation class can provide text data, PDL documents, and image data. To print documents to a network print service that might not have access to the URL, open an input stream on the URL and use an input stream data flavor instead.

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 3 - Specifying Document Types

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

Importance of Character Encoding

If a MIME type for byte print data does not include a charset parameter, indicating the encoding, the Java Print Service assumes a character set of US-ASCII. This behavior is different than that of the Java runtime, which always assumes the default encodi ng for the user's locale on the underlying operating system, which might be different than US-ASCII.

Every instance of the Java™ Virtual Machine* has a default character encoding determined during virtual-machine startup that usually depends upon the locale and charset used by the underlying operating system. In a distributed environment, two JVM's might n ot share the same default encoding. Thus clients who want to stream platform-encoded text data from the host platform to a Java Print Service instance must explicitly declare the charset and not rely on defaults.

For these reasons, applications that stream text data should always specify the charset in the MIME type. To specify a MIME type, an application needs to determine the host platform's encoding, which it does by calling the DocFlavor.hostEncoding metho d. The MIME type returned from this method is guaranteed to be understood by the current JVM.

See character encodings for more information on the character encodings supported on the Java platform.

*As used on this web site, the terms "Java Virtual Machine" or "JVM" mean a virtual machine for the Java platform.
CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 3 - Specifying Document Types

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

Service-Formatted Print Data

Rather than the client describing the print data format with a MIME type, the client can supply a Java object from which a print service determines the print data format. For example, the Java object can encapsulate a PostScript™ document. Instead of the client explicitly describing the document as PostScript™ with a MIME type, the client can wrap a reference to the document in a Java object, which the print service inspects to determine that the format is PostScript™. Because the print data is delivered to the print service through the Java object, the class that the Java object implements is the representation class.

The DocFlavor class has an inner class called DocFlavor.SERVICE_FORMATTED that contains DocFlavor object constants representing service-formatted print data. Each of these constants has a MIME type of "application/x-java-jvm-local-objectref", which indicates that the client will supply a reference to a Java object implementing the interface named as the representation class.

The three DocFlavor object constants contained in DocFlavor.SERVICE_FORMATTED each represent a common representation class name used with service-formatted print data:

  • DocFlavor.SERVICE_FORMATTED.PAGEABLE:The client supplies an object that implements thejava.awt.print.Pageable interface, which represents a set of pages to be printed. The printer calls methods in that interface to obtain the pages to be printed, one by one. For each page, the printer supplies a graphics context and prints whatever the client draws in that graphics context.
  • DocFlavor.SERVICE_FORMATTED.PRINTABLE:The client supplies an object that implements the java.awt.print.Printable interface, which is responsible for drawing the contents of each page. The printer calls methods in that interface to obtain the pages to be printed, one by one. For each page, the printer supplies a graphics context and prints whatever the client draws in that graphics context.
  • DocFlavor.SERVICE_FORMATTED.RENDERABLE_IMAGE:The client supplies an object that implements interface java.awt.image.renderable.RenderableImage, which represents an image that can be manipulated in a rendering-independent manner and can be rendered to various contexts, such as a printer, without compromising quality. The printer calls methods in the interface to obtain the image to be printed.
  • As stated in the Introduction, applications that wrap 2D graphics into a Java object can use the service-formatted print data DocFlavor constants. See Printing and Streaming 2D Graphics for more information.

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 3 - Specifying Document Types

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

How to Use DocFlavor

These steps illustrate the role of the DocFlavor in a typical application:
  1. A client determines the format of the print data and decides how to present the data to the printer. The client then creates or obtains a DocFlavorrepresenting the format:DocFlavor flavor = DocFlavor.INPUT_STREAM.GIF;
  2. The client uses the DocFlavor to find printers that can understand the format specified by the DocFlavor and has the capabilities specified in the client's attribute set:PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, aset);
  3. From a print service, the client creates a print job, represented by a DocPrintJob object:DocPrintJob printJob = services[0].createPrintJob();
  4. The client creates a Doc representing the document to be printed:Doc doc = new InputStreamDoc("duke.gif", flavor);
  5. The client prints the document by calling the print method of the DocPrintJob object:printJob.print(doc, aset);When the client passes the Doc object to the print method, the DocPrintJob object obtains the print data from the Doc object and determines the doc flavor that the client can supply. The doc flavor's representation class is a conduit for the DocPrintJob to obtain a sequence of characters or bytes from the client.
The Printing and Streaming Documents chapter demonstrates a complete printing application.

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.javadoc.Doclet (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.javadoc.Doclet

No usage of com.sun.javadoc.Doclet
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.Document (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.Document

  • Packages that use Document
    Package Description
    com.sun.java.browser.dom
    org.w3c.dom
    Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.
    org.w3c.dom.html
    org.w3c.dom.ls

    • Uses of Document in com.sun.java.browser.dom

      Methods in com.sun.java.browser.dom that return Document
      Modifier and Type Method and Description
      abstract Document DOMServiceProvider.getDocument(Object obj)
      Returns the Document object of the DOM.
      Document DOMAccessor.getDocument(Object obj)
      Returns the Document object of the DOM.

    • Uses of Document in org.w3c.dom

      Methods in org.w3c.dom that return Document
      Modifier and Type Method and Description
      Document DOMImplementation.createDocument(String namespaceURI, String qualifiedName, DocumentType doctype)
      Creates a DOM Document object of the specified type with its document element.
      Document Node.getOwnerDocument()
      The Document object associated with this node.

    • Uses of Document in org.w3c.dom.html

      Subinterfaces of Document in org.w3c.dom.html
      Modifier and Type Interface and Description
      interface  HTMLDocument
      An HTMLDocument is the root of the HTML hierarchy and holds the entire content.
      Methods in org.w3c.dom.html that return Document
      Modifier and Type Method and Description
      Document HTMLObjectElement.getContentDocument()
      The document this object contains, if there is any and it is available, or null otherwise.
      Document HTMLIFrameElement.getContentDocument()
      The document this frame contains, if there is any and it is available, or null otherwise.
      Document HTMLFrameElement.getContentDocument()
      The document this frame contains, if there is any and it is available, or null otherwise.

    • Uses of Document in org.w3c.dom.ls

      Methods in org.w3c.dom.ls that return Document
      Modifier and Type Method and Description
      Document LSLoadEvent.getNewDocument()
      The document that finished loading.
      Document LSParser.parse(LSInput input)
      Parse an XML document from a resource identified by a LSInput.
      Document LSParser.parseURI(String uri)
      Parse an XML document from a location identified by a URI reference [IETF RFC 2396].
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.css.DocumentCSS (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.css.DocumentCSS

No usage of org.w3c.dom.css.DocumentCSS
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.events.DocumentEvent (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.events.DocumentEvent

No usage of org.w3c.dom.events.DocumentEvent
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.DocumentFragment (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.DocumentFragment

  • Packages that use DocumentFragment
    Package Description
    org.w3c.dom
    Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.
    org.w3c.dom.ranges
    Document Object Model Level 2 Traversal and Range is a platform and language-neutral interfaces that allow programs and scripts to dynamically traverse and identify a range of content in a document.

    • Uses of DocumentFragment in org.w3c.dom

      Methods in org.w3c.dom that return DocumentFragment
      Modifier and Type Method and Description
      DocumentFragment Document.createDocumentFragment()
      Creates an empty DocumentFragment object.

    • Uses of DocumentFragment in org.w3c.dom.ranges

      Methods in org.w3c.dom.ranges that return DocumentFragment
      Modifier and Type Method and Description
      DocumentFragment Range.cloneContents()
      Duplicates the contents of a Range
      DocumentFragment Range.extractContents()
      Moves the contents of a Range from the containing document or document fragment to a new DocumentFragment.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.ranges.DocumentRange (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.ranges.DocumentRange

No usage of org.w3c.dom.ranges.DocumentRange
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.stylesheets.DocumentStyle (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.stylesheets.DocumentStyle

  • Packages that use DocumentStyle
    Package Description
    org.w3c.dom.css

    • Uses of DocumentStyle in org.w3c.dom.css

      Subinterfaces of DocumentStyle in org.w3c.dom.css
      Modifier and Type Interface and Description
      interface  DocumentCSS
      This interface represents a document with a CSS view.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.traversal.DocumentTraversal (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.traversal.DocumentTraversal

No usage of org.w3c.dom.traversal.DocumentTraversal
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.DocumentType (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.DocumentType

  • Packages that use DocumentType
    Package Description
    org.w3c.dom
    Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.

    • Uses of DocumentType in org.w3c.dom

      Methods in org.w3c.dom that return DocumentType
      Modifier and Type Method and Description
      DocumentType DOMImplementation.createDocumentType(String qualifiedName, String publicId, String systemId)
      Creates an empty DocumentType node.
      DocumentType Document.getDoctype()
      The Document Type Declaration (see DocumentType) associated with this document.
      Methods in org.w3c.dom with parameters of type DocumentType
      Modifier and Type Method and Description
      Document DOMImplementation.createDocument(String namespaceURI, String qualifiedName, DocumentType doctype)
      Creates a DOM Document object of the specified type with its document element.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.views.DocumentView (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.views.DocumentView

  • Packages that use DocumentView
    Package Description
    org.w3c.dom.views

    • Uses of DocumentView in org.w3c.dom.views

      Methods in org.w3c.dom.views that return DocumentView
      Modifier and Type Method and Description
      DocumentView AbstractView.getDocument()
      The source DocumentView of which this is an AbstractView.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.java.browser.dom.DOMAccessException (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.java.browser.dom.DOMAccessException

  • Packages that use DOMAccessException
    Package Description
    com.sun.java.browser.dom

    • Uses of DOMAccessException in com.sun.java.browser.dom

      Methods in com.sun.java.browser.dom that throw DOMAccessException
      Modifier and Type Method and Description
      abstract Object DOMService.invokeAndWait(DOMAction action)
      Causes action.run() to be executed synchronously on the DOM action dispatching thread.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.java.browser.dom.DOMAccessor (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.java.browser.dom.DOMAccessor

  • Packages that use DOMAccessor
    Package Description
    com.sun.java.browser.dom

    • Uses of DOMAccessor in com.sun.java.browser.dom

      Methods in com.sun.java.browser.dom with parameters of type DOMAccessor
      Modifier and Type Method and Description
      Object DOMAction.run(DOMAccessor accessor)
      When an object implementing interface DOMAction is passed to DOMService.invokeAndWait() or DOMService.invokeLater(), run method is called in the DOM access dispatch thread.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.java.browser.dom.DOMAction (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.java.browser.dom.DOMAction

  • Packages that use DOMAction
    Package Description
    com.sun.java.browser.dom

    • Uses of DOMAction in com.sun.java.browser.dom

      Methods in com.sun.java.browser.dom with parameters of type DOMAction
      Modifier and Type Method and Description
      abstract Object DOMService.invokeAndWait(DOMAction action)
      Causes action.run() to be executed synchronously on the DOM action dispatching thread.
      abstract void DOMService.invokeLater(DOMAction action)
      Causes action.run() to be executed asynchronously on the DOM action dispatching thread.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.DOMConfiguration (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.DOMConfiguration

  • Packages that use DOMConfiguration
    Package Description
    org.w3c.dom
    Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.
    org.w3c.dom.ls

    • Uses of DOMConfiguration in org.w3c.dom

      Methods in org.w3c.dom that return DOMConfiguration
      Modifier and Type Method and Description
      DOMConfiguration Document.getDomConfig()
      The configuration used when Document.normalizeDocument() is invoked.

    • Uses of DOMConfiguration in org.w3c.dom.ls

      Methods in org.w3c.dom.ls that return DOMConfiguration
      Modifier and Type Method and Description
      DOMConfiguration LSSerializer.getDomConfig()
      The DOMConfiguration object used by the LSSerializer when serializing a DOM node.
      DOMConfiguration LSParser.getDomConfig()
      The DOMConfiguration object used when parsing an input source.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.DOMError (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.DOMError

  • Packages that use DOMError
    Package Description
    org.w3c.dom
    Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.

    • Uses of DOMError in org.w3c.dom

      Methods in org.w3c.dom with parameters of type DOMError
      Modifier and Type Method and Description
      boolean DOMErrorHandler.handleError(DOMError error)
      This method is called on the error handler when an error occurs.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.DOMErrorHandler (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.DOMErrorHandler

No usage of org.w3c.dom.DOMErrorHandler
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Class org.w3c.dom.DOMException (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
org.w3c.dom.DOMException

  • Packages that use DOMException
    Package Description
    com.sun.java.browser.dom
    org.w3c.dom
    Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.
    org.w3c.dom.css
    org.w3c.dom.events
    org.w3c.dom.html
    org.w3c.dom.ls
    org.w3c.dom.ranges
    Document Object Model Level 2 Traversal and Range is a platform and language-neutral interfaces that allow programs and scripts to dynamically traverse and identify a range of content in a document.
    org.w3c.dom.stylesheets
    org.w3c.dom.traversal

    • Uses of DOMException in com.sun.java.browser.dom

      Methods in com.sun.java.browser.dom that throw DOMException
      Modifier and Type Method and Description
      Document DOMAccessor.getDocument(Object obj)
      Returns the Document object of the DOM.

    • Uses of DOMException in org.w3c.dom

      Methods in org.w3c.dom that throw DOMException
      Modifier and Type Method and Description
      Node Document.adoptNode(Node source)
      Attempts to adopt a node from another document to this document.
      Node Node.appendChild(Node newChild)
      Adds the node newChild to the end of the list of children of this node.
      void CharacterData.appendData(String arg)
      Append the string to the end of the character data of the node.
      short Node.compareDocumentPosition(Node other)
      Compares the reference node, i.e.
      Attr Document.createAttribute(String name)
      Creates an Attr of the given name.
      Attr Document.createAttributeNS(String namespaceURI, String qualifiedName)
      Creates an attribute of the given qualified name and namespace URI.
      CDATASection Document.createCDATASection(String data)
      Creates a CDATASection node whose value is the specified string.
      Document DOMImplementation.createDocument(String namespaceURI, String qualifiedName, DocumentType doctype)
      Creates a DOM Document object of the specified type with its document element.
      DocumentType DOMImplementation.createDocumentType(String qualifiedName, String publicId, String systemId)
      Creates an empty DocumentType node.
      Element Document.createElement(String tagName)
      Creates an element of the type specified.
      Element Document.createElementNS(String namespaceURI, String qualifiedName)
      Creates an element of the given qualified name and namespace URI.
      EntityReference Document.createEntityReference(String name)
      Creates an EntityReference object.
      ProcessingInstruction Document.createProcessingInstruction(String target, String data)
      Creates a ProcessingInstruction node given the specified name and data strings.
      void CharacterData.deleteData(int offset, int count)
      Remove a range of 16-bit units from the node.
      Attr Element.getAttributeNodeNS(String namespaceURI, String localName)
      Retrieves an Attr node by local name and namespace URI.
      String Element.getAttributeNS(String namespaceURI, String localName)
      Retrieves an attribute value by local name and namespace URI.
      String CharacterData.getData()
      The character data of the node that implements this interface.
      NodeList Element.getElementsByTagNameNS(String namespaceURI, String localName)
      Returns a NodeList of all the descendant Elements with a given local name and namespace URI in document order.
      Node NamedNodeMap.getNamedItemNS(String namespaceURI, String localName)
      Retrieves a node specified by local name and namespace URI.
      String Node.getNodeValue()
      The value of this node, depending on its type; see the table above.
      Object DOMConfiguration.getParameter(String name)
      Return the value of a parameter if known.
      String Node.getTextContent()
      This attribute returns the text content of this node and its descendants.
      boolean Element.hasAttributeNS(String namespaceURI, String localName)
      Returns true when an attribute with a given local name and namespace URI is specified on this element or has a default value, false otherwise.
      Node Document.importNode(Node importedNode, boolean deep)
      Imports a node from another document to this document, without altering or removing the source node from the original document; this method creates a new copy of the source node.
      Node Node.insertBefore(Node newChild, Node refChild)
      Inserts the node newChild before the existing child node refChild.
      void CharacterData.insertData(int offset, String arg)
      Insert a string at the specified 16-bit unit offset.
      void Element.removeAttribute(String name)
      Removes an attribute by name.
      Attr Element.removeAttributeNode(Attr oldAttr)
      Removes the specified attribute node.
      void Element.removeAttributeNS(String namespaceURI, String localName)
      Removes an attribute by local name and namespace URI.
      Node Node.removeChild(Node oldChild)
      Removes the child node indicated by oldChild from the list of children, and returns it.
      Node NamedNodeMap.removeNamedItem(String name)
      Removes a node specified by name.
      Node NamedNodeMap.removeNamedItemNS(String namespaceURI, String localName)
      Removes a node specified by local name and namespace URI.
      Node Document.renameNode(Node n, String namespaceURI, String qualifiedName)
      Rename an existing node of type ELEMENT_NODE or ATTRIBUTE_NODE.
      Node Node.replaceChild(Node newChild, Node oldChild)
      Replaces the child node oldChild with newChild in the list of children, and returns the oldChild node.
      void CharacterData.replaceData(int offset, int count, String arg)
      Replace the characters starting at the specified 16-bit unit offset with the specified string.
      Text Text.replaceWholeText(String content)
      Replaces the text of the current node and all logically-adjacent text nodes with the specified text.
      void Element.setAttribute(String name, String value)
      Adds a new attribute.
      Attr Element.setAttributeNode(Attr newAttr)
      Adds a new attribute node.
      Attr Element.setAttributeNodeNS(Attr newAttr)
      Adds a new attribute.
      void Element.setAttributeNS(String namespaceURI, String qualifiedName, String value)
      Adds a new attribute.
      void ProcessingInstruction.setData(String data)
      The content of this processing instruction.
      void CharacterData.setData(String data)
      The character data of the node that implements this interface.
      void Element.setIdAttribute(String name, boolean isId)
      If the parameter isId is true, this method declares the specified attribute to be a user-determined ID attribute .
      void Element.setIdAttributeNode(Attr idAttr, boolean isId)
      If the parameter isId is true, this method declares the specified attribute to be a user-determined ID attribute .
      void Element.setIdAttributeNS(String namespaceURI, String localName, boolean isId)
      If the parameter isId is true, this method declares the specified attribute to be a user-determined ID attribute .
      Node NamedNodeMap.setNamedItem(Node arg)
      Adds a node using its nodeName attribute.
      Node NamedNodeMap.setNamedItemNS(Node arg)
      Adds a node using its namespaceURI and localName.
      void Node.setNodeValue(String nodeValue)
      The value of this node, depending on its type; see the table above.
      void DOMConfiguration.setParameter(String name, Object value)
      Set the value of a parameter.
      void Node.setPrefix(String prefix)
      The namespace prefix of this node, or null if it is unspecified.
      void Node.setTextContent(String textContent)
      This attribute returns the text content of this node and its descendants.
      void Attr.setValue(String value)
      On retrieval, the value of the attribute is returned as a string.
      void Document.setXmlStandalone(boolean xmlStandalone)
      An attribute specifying, as part of the XML declaration, whether this document is standalone.
      void Document.setXmlVersion(String xmlVersion)
      An attribute specifying, as part of the XML declaration, the version number of this document.
      Text Text.splitText(int offset)
      Breaks this node into two nodes at the specified offset, keeping both in the tree as siblings.
      String CharacterData.substringData(int offset, int count)
      Extracts a range of data from the node.

    • Uses of DOMException in org.w3c.dom.css

      Methods in org.w3c.dom.css that throw DOMException
      Modifier and Type Method and Description
      CSSStyleSheet DOMImplementationCSS.createCSSStyleSheet(String title, String media)
      Creates a new CSSStyleSheet.
      void CSSStyleSheet.deleteRule(int index)
      Used to delete a rule from the style sheet.
      void CSSMediaRule.deleteRule(int index)
      Used to delete a rule from the media block.
      Counter CSSPrimitiveValue.getCounterValue()
      This method is used to get the Counter value.
      float CSSPrimitiveValue.getFloatValue(short unitType)
      This method is used to get a float value in a specified unit.
      Rect CSSPrimitiveValue.getRectValue()
      This method is used to get the Rect value.
      RGBColor CSSPrimitiveValue.getRGBColorValue()
      This method is used to get the RGB color.
      String CSSPrimitiveValue.getStringValue()
      This method is used to get the string value.
      int CSSStyleSheet.insertRule(String rule, int index)
      Used to insert a new rule into the style sheet.
      int CSSMediaRule.insertRule(String rule, int index)
      Used to insert a new rule into the media block.
      String CSSStyleDeclaration.removeProperty(String propertyName)
      Used to remove a CSS property if it has been explicitly set within this declaration block.
      void CSS2Properties.setAzimuth(String azimuth)
      See the azimuth property definition in CSS2.
      void CSS2Properties.setBackground(String background)
      See the background property definition in CSS2.
      void CSS2Properties.setBackgroundAttachment(String backgroundAttachment)
      See the background-attachment property definition in CSS2.
      void CSS2Properties.setBackgroundColor(String backgroundColor)
      See the background-color property definition in CSS2.
      void CSS2Properties.setBackgroundImage(String backgroundImage)
      See the background-image property definition in CSS2.
      void CSS2Properties.setBackgroundPosition(String backgroundPosition)
      See the background-position property definition in CSS2.
      void CSS2Properties.setBackgroundRepeat(String backgroundRepeat)
      See the background-repeat property definition in CSS2.
      void CSS2Properties.setBorder(String border)
      See the border property definition in CSS2.
      void CSS2Properties.setBorderBottom(String borderBottom)
      See the border-bottom property definition in CSS2.
      void CSS2Properties.setBorderBottomColor(String borderBottomColor)
      See the border-bottom-color property definition in CSS2.
      void CSS2Properties.setBorderBottomStyle(String borderBottomStyle)
      See the border-bottom-style property definition in CSS2.
      void CSS2Properties.setBorderBottomWidth(String borderBottomWidth)
      See the border-bottom-width property definition in CSS2.
      void CSS2Properties.setBorderCollapse(String borderCollapse)
      See the border-collapse property definition in CSS2.
      void CSS2Properties.setBorderColor(String borderColor)
      See the border-color property definition in CSS2.
      void CSS2Properties.setBorderLeft(String borderLeft)
      See the border-left property definition in CSS2.
      void CSS2Properties.setBorderLeftColor(String borderLeftColor)
      See the border-left-color property definition in CSS2.
      void CSS2Properties.setBorderLeftStyle(String borderLeftStyle)
      See the border-left-style property definition in CSS2.
      void CSS2Properties.setBorderLeftWidth(String borderLeftWidth)
      See the border-left-width property definition in CSS2.
      void CSS2Properties.setBorderRight(String borderRight)
      See the border-right property definition in CSS2.
      void CSS2Properties.setBorderRightColor(String borderRightColor)
      See the border-right-color property definition in CSS2.
      void CSS2Properties.setBorderRightStyle(String borderRightStyle)
      See the border-right-style property definition in CSS2.
      void CSS2Properties.setBorderRightWidth(String borderRightWidth)
      See the border-right-width property definition in CSS2.
      void CSS2Properties.setBorderSpacing(String borderSpacing)
      See the border-spacing property definition in CSS2.
      void CSS2Properties.setBorderStyle(String borderStyle)
      See the border-style property definition in CSS2.
      void CSS2Properties.setBorderTop(String borderTop)
      See the border-top property definition in CSS2.
      void CSS2Properties.setBorderTopColor(String borderTopColor)
      See the border-top-color property definition in CSS2.
      void CSS2Properties.setBorderTopStyle(String borderTopStyle)
      See the border-top-style property definition in CSS2.
      void CSS2Properties.setBorderTopWidth(String borderTopWidth)
      See the border-top-width property definition in CSS2.
      void CSS2Properties.setBorderWidth(String borderWidth)
      See the border-width property definition in CSS2.
      void CSS2Properties.setBottom(String bottom)
      See the bottom property definition in CSS2.
      void CSS2Properties.setCaptionSide(String captionSide)
      See the caption-side property definition in CSS2.
      void CSS2Properties.setClear(String clear)
      See the clear property definition in CSS2.
      void CSS2Properties.setClip(String clip)
      See the clip property definition in CSS2.
      void CSS2Properties.setColor(String color)
      See the color property definition in CSS2.
      void CSS2Properties.setContent(String content)
      See the content property definition in CSS2.
      void CSS2Properties.setCounterIncrement(String counterIncrement)
      See the counter-increment property definition in CSS2.
      void CSS2Properties.setCounterReset(String counterReset)
      See the counter-reset property definition in CSS2.
      void CSS2Properties.setCssFloat(String cssFloat)
      See the float property definition in CSS2.
      void CSSValue.setCssText(String cssText)
      A string representation of the current value.
      void CSSStyleDeclaration.setCssText(String cssText)
      The parsable textual representation of the declaration block (excluding the surrounding curly braces).
      void CSSRule.setCssText(String cssText)
      The parsable textual representation of the rule.
      void CSS2Properties.setCue(String cue)
      See the cue property definition in CSS2.
      void CSS2Properties.setCueAfter(String cueAfter)
      See the cue-after property definition in CSS2.
      void CSS2Properties.setCueBefore(String cueBefore)
      See the cue-before property definition in CSS2.
      void CSS2Properties.setCursor(String cursor)
      See the cursor property definition in CSS2.
      void CSS2Properties.setDirection(String direction)
      See the direction property definition in CSS2.
      void CSS2Properties.setDisplay(String display)
      See the display property definition in CSS2.
      void CSS2Properties.setElevation(String elevation)
      See the elevation property definition in CSS2.
      void CSS2Properties.setEmptyCells(String emptyCells)
      See the empty-cells property definition in CSS2.
      void CSSCharsetRule.setEncoding(String encoding)
      The encoding information used in this @charset rule.
      void CSSPrimitiveValue.setFloatValue(short unitType, float floatValue)
      A method to set the float value with a specified unit.
      void CSS2Properties.setFont(String font)
      See the font property definition in CSS2.
      void CSS2Properties.setFontFamily(String fontFamily)
      See the font-family property definition in CSS2.
      void CSS2Properties.setFontSize(String fontSize)
      See the font-size property definition in CSS2.
      void CSS2Properties.setFontSizeAdjust(String fontSizeAdjust)
      See the font-size-adjust property definition in CSS2.
      void CSS2Properties.setFontStretch(String fontStretch)
      See the font-stretch property definition in CSS2.
      void CSS2Properties.setFontStyle(String fontStyle)
      See the font-style property definition in CSS2.
      void CSS2Properties.setFontVariant(String fontVariant)
      See the font-variant property definition in CSS2.
      void CSS2Properties.setFontWeight(String fontWeight)
      See the font-weight property definition in CSS2.
      void CSS2Properties.setHeight(String height)
      See the height property definition in CSS2.
      void CSS2Properties.setLeft(String left)
      See the left property definition in CSS2.
      void CSS2Properties.setLetterSpacing(String letterSpacing)
      See the letter-spacing property definition in CSS2.
      void CSS2Properties.setLineHeight(String lineHeight)
      See the line-height property definition in CSS2.
      void CSS2Properties.setListStyle(String listStyle)
      See the list-style property definition in CSS2.
      void CSS2Properties.setListStyleImage(String listStyleImage)
      See the list-style-image property definition in CSS2.
      void CSS2Properties.setListStylePosition(String listStylePosition)
      See the list-style-position property definition in CSS2.
      void CSS2Properties.setListStyleType(String listStyleType)
      See the list-style-type property definition in CSS2.
      void CSS2Properties.setMargin(String margin)
      See the margin property definition in CSS2.
      void CSS2Properties.setMarginBottom(String marginBottom)
      See the margin-bottom property definition in CSS2.
      void CSS2Properties.setMarginLeft(String marginLeft)
      See the margin-left property definition in CSS2.
      void CSS2Properties.setMarginRight(String marginRight)
      See the margin-right property definition in CSS2.
      void CSS2Properties.setMarginTop(String marginTop)
      See the margin-top property definition in CSS2.
      void CSS2Properties.setMarkerOffset(String markerOffset)
      See the marker-offset property definition in CSS2.
      void CSS2Properties.setMarks(String marks)
      See the marks property definition in CSS2.
      void CSS2Properties.setMaxHeight(String maxHeight)
      See the max-height property definition in CSS2.
      void CSS2Properties.setMaxWidth(String maxWidth)
      See the max-width property definition in CSS2.
      void CSS2Properties.setMinHeight(String minHeight)
      See the min-height property definition in CSS2.
      void CSS2Properties.setMinWidth(String minWidth)
      See the min-width property definition in CSS2.
      void CSS2Properties.setOrphans(String orphans)
      See the orphans property definition in CSS2.
      void CSS2Properties.setOutline(String outline)
      See the outline property definition in CSS2.
      void CSS2Properties.setOutlineColor(String outlineColor)
      See the outline-color property definition in CSS2.
      void CSS2Properties.setOutlineStyle(String outlineStyle)
      See the outline-style property definition in CSS2.
      void CSS2Properties.setOutlineWidth(String outlineWidth)
      See the outline-width property definition in CSS2.
      void CSS2Properties.setOverflow(String overflow)
      See the overflow property definition in CSS2.
      void CSS2Properties.setPadding(String padding)
      See the padding property definition in CSS2.
      void CSS2Properties.setPaddingBottom(String paddingBottom)
      See the padding-bottom property definition in CSS2.
      void CSS2Properties.setPaddingLeft(String paddingLeft)
      See the padding-left property definition in CSS2.
      void CSS2Properties.setPaddingRight(String paddingRight)
      See the padding-right property definition in CSS2.
      void CSS2Properties.setPaddingTop(String paddingTop)
      See the padding-top property definition in CSS2.
      void CSS2Properties.setPage(String page)
      See the page property definition in CSS2.
      void CSS2Properties.setPageBreakAfter(String pageBreakAfter)
      See the page-break-after property definition in CSS2.
      void CSS2Properties.setPageBreakBefore(String pageBreakBefore)
      See the page-break-before property definition in CSS2.
      void CSS2Properties.setPageBreakInside(String pageBreakInside)
      See the page-break-inside property definition in CSS2.
      void CSS2Properties.setPause(String pause)
      See the pause property definition in CSS2.
      void CSS2Properties.setPauseAfter(String pauseAfter)
      See the pause-after property definition in CSS2.
      void CSS2Properties.setPauseBefore(String pauseBefore)
      See the pause-before property definition in CSS2.
      void CSS2Properties.setPitch(String pitch)
      See the pitch property definition in CSS2.
      void CSS2Properties.setPitchRange(String pitchRange)
      See the pitch-range property definition in CSS2.
      void CSS2Properties.setPlayDuring(String playDuring)
      See the play-during property definition in CSS2.
      void CSS2Properties.setPosition(String position)
      See the position property definition in CSS2.
      void CSSStyleDeclaration.setProperty(String propertyName, String value, String priority)
      Used to set a property value and priority within this declaration block.
      void CSS2Properties.setQuotes(String quotes)
      See the quotes property definition in CSS2.
      void CSS2Properties.setRichness(String richness)
      See the richness property definition in CSS2.
      void CSS2Properties.setRight(String right)
      See the right property definition in CSS2.
      void CSSStyleRule.setSelectorText(String selectorText)
      The textual representation of the selector for the rule set.
      void CSSPageRule.setSelectorText(String selectorText)
      The parsable textual representation of the page selector for the rule.
      void CSS2Properties.setSize(String size)
      See the size property definition in CSS2.
      void CSS2Properties.setSpeak(String speak)
      See the speak property definition in CSS2.
      void CSS2Properties.setSpeakHeader(String speakHeader)
      See the speak-header property definition in CSS2.
      void CSS2Properties.setSpeakNumeral(String speakNumeral)
      See the speak-numeral property definition in CSS2.
      void CSS2Properties.setSpeakPunctuation(String speakPunctuation)
      See the speak-punctuation property definition in CSS2.
      void CSS2Properties.setSpeechRate(String speechRate)
      See the speech-rate property definition in CSS2.
      void CSS2Properties.setStress(String stress)
      See the stress property definition in CSS2.
      void CSSPrimitiveValue.setStringValue(short stringType, String stringValue)
      A method to set the string value with the specified unit.
      void CSS2Properties.setTableLayout(String tableLayout)
      See the table-layout property definition in CSS2.
      void CSS2Properties.setTextAlign(String textAlign)
      See the text-align property definition in CSS2.
      void CSS2Properties.setTextDecoration(String textDecoration)
      See the text-decoration property definition in CSS2.
      void CSS2Properties.setTextIndent(String textIndent)
      See the text-indent property definition in CSS2.
      void CSS2Properties.setTextShadow(String textShadow)
      See the text-shadow property definition in CSS2.
      void CSS2Properties.setTextTransform(String textTransform)
      See the text-transform property definition in CSS2.
      void CSS2Properties.setTop(String top)
      See the top property definition in CSS2.
      void CSS2Properties.setUnicodeBidi(String unicodeBidi)
      See the unicode-bidi property definition in CSS2.
      void CSS2Properties.setVerticalAlign(String verticalAlign)
      See the vertical-align property definition in CSS2.
      void CSS2Properties.setVisibility(String visibility)
      See the visibility property definition in CSS2.
      void CSS2Properties.setVoiceFamily(String voiceFamily)
      See the voice-family property definition in CSS2.
      void CSS2Properties.setVolume(String volume)
      See the volume property definition in CSS2.
      void CSS2Properties.setWhiteSpace(String whiteSpace)
      See the white-space property definition in CSS2.
      void CSS2Properties.setWidows(String widows)
      See the widows property definition in CSS2.
      void CSS2Properties.setWidth(String width)
      See the width property definition in CSS2.
      void CSS2Properties.setWordSpacing(String wordSpacing)
      See the word-spacing property definition in CSS2.
      void CSS2Properties.setZIndex(String zIndex)
      See the z-index property definition in CSS2.

    • Uses of DOMException in org.w3c.dom.events

      Methods in org.w3c.dom.events that throw DOMException
      Modifier and Type | Method and Description
      Event | DocumentEvent.createEvent(String eventType)

    • Uses of DOMException in org.w3c.dom.html

      Methods in org.w3c.dom.html that throw DOMException
      Modifier and Type Method and Description
      void HTMLSelectElement.add(HTMLElement element, HTMLElement before)
      Add a new element to the collection of OPTION elements for this SELECT .
      void HTMLTableRowElement.deleteCell(int index)
      Delete a cell from the current row.
      void HTMLTableSectionElement.deleteRow(int index)
      Delete a row from this section.
      void HTMLTableElement.deleteRow(int index)
      Delete a table row.
      HTMLElement HTMLTableRowElement.insertCell(int index)
      Insert an empty TD cell into this row.
      HTMLElement HTMLTableSectionElement.insertRow(int index)
      Insert a row into this section.
      HTMLElement HTMLTableElement.insertRow(int index)
      Insert a new empty row in the table.

    • Uses of DOMException in org.w3c.dom.ls

      Methods in org.w3c.dom.ls that throw DOMException
      Modifier and Type Method and Description
      LSParser DOMImplementationLS.createLSParser(short mode, String schemaType)
      Create a new LSParser.
      Document LSParser.parse(LSInput input)
      Parse an XML document from a resource identified by a LSInput.
      Document LSParser.parseURI(String uri)
      Parse an XML document from a location identified by a URI reference [IETF RFC 2396].
      Node LSParser.parseWithContext(LSInput input, Node contextArg, short action)
      Parse an XML fragment from a resource identified by a LSInput and insert the content into an existing document at the position specified with the context and action arguments.
      String LSSerializer.writeToString(Node nodeArg)
      Serialize the specified node as described above in the general description of the LSSerializer interface.

    • Uses of DOMException in org.w3c.dom.ranges

      Methods in org.w3c.dom.ranges that throw DOMException
      Modifier and Type Method and Description
      DocumentFragment Range.cloneContents()
      Duplicates the contents of a Range
      Range Range.cloneRange()
      Produces a new Range whose boundary-points are equal to the boundary-points of the Range.
      void Range.collapse(boolean toStart)
      Collapse a Range onto one of its boundary-points
      short Range.compareBoundaryPoints(short how, Range sourceRange)
      Compare the boundary-points of two Ranges in a document.
      void Range.deleteContents()
      Removes the contents of a Range from the containing document or document fragment without returning a reference to the removed content.
      void Range.detach()
      Called to indicate that the Range is no longer in use and that the implementation may relinquish any resources associated with this Range.
      DocumentFragment Range.extractContents()
      Moves the contents of a Range from the containing document or document fragment to a new DocumentFragment.
      boolean Range.getCollapsed()
      TRUE if the Range is collapsed
      Node Range.getCommonAncestorContainer()
      The deepest common ancestor container of the Range's two boundary-points.
      Node Range.getEndContainer()
      Node within which the Range ends
      int Range.getEndOffset()
      Offset within the ending node of the Range.
      Node Range.getStartContainer()
      Node within which the Range begins
      int Range.getStartOffset()
      Offset within the starting node of the Range.
      void Range.insertNode(Node newNode)
      Inserts a node into the Document or DocumentFragment at the start of the Range.
      void Range.selectNode(Node refNode)
      Select a node and its contents
      void Range.selectNodeContents(Node refNode)
      Select the contents within a node
      void Range.setEnd(Node refNode, int offset)
      Sets the attributes describing the end of a Range.
      void Range.setEndAfter(Node refNode)
      Sets the end of a Range to be after a node
      void Range.setEndBefore(Node refNode)
      Sets the end position to be before a node.
      void Range.setStart(Node refNode, int offset)
      Sets the attributes describing the start of the Range.
      void Range.setStartAfter(Node refNode)
      Sets the start position to be after a node
      void Range.setStartBefore(Node refNode)
      Sets the start position to be before a node
      void Range.surroundContents(Node newParent)
      Reparents the contents of the Range to the given node and inserts the node at the position of the start of the Range.
      String Range.toString()
      Returns the contents of a Range as a string.

    • Uses of DOMException in org.w3c.dom.stylesheets

      Methods in org.w3c.dom.stylesheets that throw DOMException
      Modifier and Type Method and Description
      void MediaList.appendMedium(String newMedium)
      Adds the medium newMedium to the end of the list.
      void MediaList.deleteMedium(String oldMedium)
      Deletes the medium indicated by oldMedium from the list.
      void MediaList.setMediaText(String mediaText)
      The parsable textual representation of the media list.

    • Uses of DOMException in org.w3c.dom.traversal

      Methods in org.w3c.dom.traversal that throw DOMException
      Modifier and Type Method and Description
      NodeIterator DocumentTraversal.createNodeIterator(Node root, int whatToShow, NodeFilter filter, boolean entityReferenceExpansion)
      Create a new NodeIterator over the subtree rooted at the specified node.
      TreeWalker DocumentTraversal.createTreeWalker(Node root, int whatToShow, NodeFilter filter, boolean entityReferenceExpansion)
      Create a new TreeWalker over the subtree rooted at the specified node.
      Node NodeIterator.nextNode()
      Returns the next node in the set and advances the position of the NodeIterator in the set.
      Node NodeIterator.previousNode()
      Returns the previous node in the set and moves the position of the NodeIterator backwards in the set.
      void TreeWalker.setCurrentNode(Node currentNode)
      The node at which the TreeWalker is currently positioned.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.DOMImplementation (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.DOMImplementation

  • Packages that use DOMImplementation
    Package Description
    com.sun.java.browser.dom
    org.w3c.dom
    Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.
    org.w3c.dom.bootstrap
    org.w3c.dom.css
    org.w3c.dom.html

    • Uses of DOMImplementation in com.sun.java.browser.dom

      Methods in com.sun.java.browser.dom that return DOMImplementation
      Modifier and Type Method and Description
      abstract DOMImplementation DOMServiceProvider.getDOMImplementation()
      Returns the DOMImplemenation object of the DOM.
      DOMImplementation DOMAccessor.getDOMImplementation()
      Returns a DOMImplementation object.

    • Uses of DOMImplementation in org.w3c.dom

      Methods in org.w3c.dom that return DOMImplementation
      Modifier and Type Method and Description
      DOMImplementation DOMImplementationSource.getDOMImplementation(String features)
      A method to request the first DOM implementation that supports the specified features.
      DOMImplementation Document.getImplementation()
      The DOMImplementation object that handles this document.
      DOMImplementation DOMImplementationList.item(int index)
      Returns the indexth item in the collection.

    • Uses of DOMImplementation in org.w3c.dom.bootstrap

      Methods in org.w3c.dom.bootstrap that return DOMImplementation
      Modifier and Type Method and Description
      DOMImplementation DOMImplementationRegistry.getDOMImplementation(String features)
      Return the first implementation that has the desired features, or null if none is found.

    • Uses of DOMImplementation in org.w3c.dom.css

      Subinterfaces of DOMImplementation in org.w3c.dom.css
      Modifier and Type Interface and Description
      interface  DOMImplementationCSS
      This interface allows the DOM user to create a CSSStyleSheet outside the context of a document.

    • Uses of DOMImplementation in org.w3c.dom.html

      Subinterfaces of DOMImplementation in org.w3c.dom.html
      Modifier and Type Interface and Description
      interface  HTMLDOMImplementation
      The HTMLDOMImplementation interface extends the DOMImplementation interface with a method for creating an HTML document instance.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.css.DOMImplementationCSS (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.css.DOMImplementationCSS

No usage of org.w3c.dom.css.DOMImplementationCSS
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.DOMImplementationList (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.DOMImplementationList

  • Packages that use DOMImplementationList
    Package Description
    org.w3c.dom
    Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.
    org.w3c.dom.bootstrap

    • Uses of DOMImplementationList in org.w3c.dom

      Methods in org.w3c.dom that return DOMImplementationList
      Modifier and Type Method and Description
      DOMImplementationList DOMImplementationSource.getDOMImplementationList(String features)
      A method to request a list of DOM implementations that support the specified features and versions, as specified in .

    • Uses of DOMImplementationList in org.w3c.dom.bootstrap

      Methods in org.w3c.dom.bootstrap that return DOMImplementationList
      Modifier and Type Method and Description
      DOMImplementationList DOMImplementationRegistry.getDOMImplementationList(String features)
      Return a list of implementations that support the desired features.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.ls.DOMImplementationLS (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.ls.DOMImplementationLS

No usage of org.w3c.dom.ls.DOMImplementationLS
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Class org.w3c.dom.bootstrap.DOMImplementationRegistry (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
org.w3c.dom.bootstrap.DOMImplementationRegistry

  • Packages that use DOMImplementationRegistry
    Package Description
    org.w3c.dom.bootstrap

    • Uses of DOMImplementationRegistry in org.w3c.dom.bootstrap

      Methods in org.w3c.dom.bootstrap that return DOMImplementationRegistry
      Modifier and Type Method and Description
      static DOMImplementationRegistry DOMImplementationRegistry.newInstance()
      Obtain a new instance of a DOMImplementationRegistry.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.DOMImplementationSource (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.DOMImplementationSource

  • Packages that use DOMImplementationSource
    Package Description
    org.w3c.dom.bootstrap

    • Uses of DOMImplementationSource in org.w3c.dom.bootstrap

      Methods in org.w3c.dom.bootstrap with parameters of type DOMImplementationSource
      Modifier and Type Method and Description
      void DOMImplementationRegistry.addSource(DOMImplementationSource s)
      Register an implementation.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.DOMLocator (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.DOMLocator

  • Packages that use DOMLocator
    Package Description
    org.w3c.dom
    Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.

    • Uses of DOMLocator in org.w3c.dom

      Methods in org.w3c.dom that return DOMLocator
      Modifier and Type Method and Description
      DOMLocator DOMError.getLocation()
      The location of the error.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.java.browser.dom.DOMService (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.java.browser.dom.DOMService

  • Packages that use DOMService
    Package Description
    com.sun.java.browser.dom

    • Uses of DOMService in com.sun.java.browser.dom

      Methods in com.sun.java.browser.dom that return DOMService
      Modifier and Type Method and Description
      static DOMService DOMService.getService(Object obj)
      Returns new instance of a DOMService.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.java.browser.dom.DOMServiceProvider (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.java.browser.dom.DOMServiceProvider

No usage of com.sun.java.browser.dom.DOMServiceProvider
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.DOMStringList (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.DOMStringList

  • Packages that use DOMStringList
    Package Description
    org.w3c.dom
    Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.

    • Uses of DOMStringList in org.w3c.dom

      Methods in org.w3c.dom that return DOMStringList
      Modifier and Type Method and Description
      DOMStringList DOMConfiguration.getParameterNames()
      The list of the parameters supported by this DOMConfiguration object and for which at least one value can be set by the application.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.java.browser.dom.DOMUnsupportedException (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.java.browser.dom.DOMUnsupportedException

  • Packages that use DOMUnsupportedException
    Package Description
    com.sun.java.browser.dom

    • Uses of DOMUnsupportedException in com.sun.java.browser.dom

      Methods in com.sun.java.browser.dom that throw DOMUnsupportedException
      Modifier and Type Method and Description
      abstract Document DOMServiceProvider.getDocument(Object obj)
      Returns the Document object of the DOM.
      static DOMService DOMService.getService(Object obj)
      Returns new instance of a DOMService.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Privileged Block API

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

API for Privileged Blocks

Overview

This document provides background information about what "privileged" code is and what it is used for, followed by illustrations of the use of the API, with special attention to issues of:
  • returning values
  • type safety
  • exception handling
  • reflection

Background: What It Means to Have "Privileged" Code

The policy for an SDK installation specifies what permissions -- which types of system resource accesses -- are allowed for code from specified code sources. A "code source" (of type CodeSource) essentially consists of the code location (URL) and a reference to the certificate(s) containing the public key(s) corresponding to the private key(s) used to sign the code (if it was signed).

The policy is represented by a Policy object. More specifically, it is represented by a Policy subclass providing an implementation of the abstract methods in the Policy class (which is in the java.security package).

The source location for the policy information utilized by the Policy object is up to the Policy implementation. The Policy reference implementation obtains its information from policy configuration files. See Default Policy Implementation and Policy File Syntax for information about the Policy reference implementation and the syntax that must be used in policy files it reads. For information about using the Policy Tool to create a policy file (without needing to know the required syntax), see the Policy Tool documentation (for Solaris) (for Windows).

A "protection domain" encompasses a CodeSource and the permissions granted to code from that CodeSource, as determined by the security policy currently in effect. Thus, classes signed by the same keys and from the same URL are placed in the same domain, and a class belongs to one and only one protection domain. Classes that have the same permissions but are from different code sources belong to different domains.

Today all code shipped as part of the SDK is considered system code and run inside the unique system domain. System code automatically has all permissions.

Each applet or application runs in its appropriate domain, determined by its code source. In order for an applet (or an application running under a security manager) to be allowed to perform a secured action (such as reading or writing a file), the applet or application must be granted permission for that particular action.

More specifically, whenever a resource access is attempted, all code traversed by the execution thread up to that point must have permission for that resource access, unless some code on the thread has been marked as "privileged". That is, suppose access control checking occurs in a thread of execution that has a chain of multiple callers. (Think of this as multiple method calls that potentially cross the protection domain boundaries.) When the AccessController checkPermission method is invoked by the most recent caller, the basic algorithm for deciding whether to allow or deny the requested access is as follows:

If the code for any caller in the call chain does not have the requested permission, AccessControlException is thrown, unless the following is true - a caller whose code is granted the said permission has been marked as "privileged" (see below) and all parties subsequently called by this caller (directly or indirectly) all have the said permission.

Marking code as "privileged" enables a piece of trusted code to temporarily enable access to more resources than are available directly to the code that called it. This is necessary in some situations. For example, an application may not be allowed direct access to files that contain fonts, but the system utility to display a document must obtain those fonts, on behalf of the user. In order to do this, the system utility becomes privileged while obtaining the fonts.

Using the doPrivileged API

The use of the "privileged" feature is described in the following sections.

No return value, no exception thrown

If you don't need to return a value from within the "privileged" block, your call to doPrivileged can look like the following:

   somemethod() {
        ...normal code here...
        AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                // privileged code goes here, for example:
                System.loadLibrary("awt");
                return null; // nothing to return
            }
        });
       ...normal code here...
  }

The AccessController.doPrivileged method takes an object of type java.security.PrivilegedAction and invokes its run method in privileged mode. The implementation guarantees that privileges will be revoked after the run method is executed, even if execution of doPrivileged is interrupted by an asynchronous exception.

PrivilegedAction is an interface with a single method, named run, that returns an Object. The above example shows creation of an implementation of that interface using an anonymous inner class; a concrete implementation of the run method is supplied. When the call to doPrivileged is made, an instance of the PrivilegedAction implementation is passed to it. The doPrivileged method calls the run method from the PrivilegedAction implementation after enabling privileges, and returns the run method's return value as the doPrivileged return value (which is ignored in this example).

Note that depending on what "privileged code" actually consisted of, you might have to make some changes due to the way inner classes work. For example, if "privileged code" throws an exception or attempts to access local variables then you will have to make some changes, as shown in subsequent sections of this document.

You can also call doPrivileged without using an anonymous inner class, as in:

    somemethod() {
        ...normal code here...
        MyAction mya = new MyAction();
        // become privileged:
        AccessController.doPrivileged(mya);
       ...normal code here...
    }

    class MyAction implements PrivilegedAction {
        public MyAction() {};
        public Object run() {
            // privileged code goes here, for example:
            System.loadLibrary("awt");
            return null; // nothing to return
        }
    }

Be very careful in your use of the "privileged" construct, and always remember to make the privileged code section as small as possible, that is, try and limit the code within the run method to only the code that needs to be run with privileges, and do more general things outside the run method. Also note that the call to doPrivileged should be made in the code that wants to enable its privileges. Do not be tempted to write a utility class that itself calls doPrivileged as that could lead to security holes. You can write utility classes for PrivilegedAction classes though, as shown in the example above.

Returning values

If you need to return a value, you can do something like the following:

   somemethod() {
        ...normal code here...
        String user = (String) AccessController.doPrivileged(
          new PrivilegedAction() {
            public Object run() {
                return System.getProperty("user.name");
            }
          }
        );
        ...normal code here...
  }

Note that this usage requires a dynamic cast on the value returned by doPrivileged. An alternative is to use a final local variable:

   somemethod() {
        ...normal code here...
        final String user[] = {null};
        AccessController.doPrivileged(
          new PrivilegedAction() {
            public Object run() {
                user[0] = System.getProperty("user.name");
                return null; // still need this
            }
          }
        );
        ...normal code here...
  }
Yet another alternative would be to write a non-anonymous class that safely handles types for you:
   somemethod() {
        ...normal code here...
        GetPropertyAction gpa = new GetPropertyAction("user.name");
        AccessController.doPrivileged(gpa);
        String user = gpa.getValue();
        ...normal code here...
   }

   class GetPropertyAction implements PrivilegedAction {
      private String property;
      private String value;
      public GetPropertyAction(String prop) { property = prop;}
      public Object run() {
               value = System.getProperty(property);
               return value;
      }
      public String getValue() {return value;}

   }

Note there are now no type-casts involved, although the run method still returns a value, so you could still have a "one-liner" if you wanted to:

   somemethod() {
        ...normal code here...
        String user = (String) AccessController.doPrivileged(
                                   new GetPropertyAction("user.name"));
        ...normal code here...
   }

Accessing local variables

If you are using an anonymous inner class, any local variables you access must be final. For example:

   somemethod() {
        ...normal code here...
        final String lib = "awt";
        AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                // privileged code goes here, for example:
                System.loadLibrary(lib);
                return null; // nothing to return
            }
        });
       ...normal code here...
  }

The variable lib must be declared final if you intend to use it within the privileged block. See the "Inner Classes" spec for more information on this topic.

If there are cases where you can't make an existing variable final (because it gets set multiple times), then you can create a new final variable right before invoking doPrivileged, and set that variable equal to the other variable. For example:

   somemethod() {
        ...normal code here...
        String lib;
        ...
        // lib gets set multiple times so we can't make it final
        ...
        // create a final String that we can use inside of the run method
        final String fLib = lib;
        AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                // privileged code goes here, for example:
                System.loadLibrary(fLib);
                return null; // nothing to return
            }
        });
       ...normal code here...
  }

Handling Exceptions

If the action performed in your run method could throw a "checked" exception (one that must be listed in the throws clause of a method), then you need to use the PrivilegedExceptionAction interface instead of the PrivilegedAction interface:

   somemethod() throws FileNotFoundException {
        ...normal code here...
      try {
        FileInputStream fis = (FileInputStream) AccessController.doPrivileged(
          new PrivilegedExceptionAction() {
            public Object run() throws FileNotFoundException {
                return new FileInputStream("someFile");
            }
          }
        );
      } catch (PrivilegedActionException e) {
        // e.getException() should be an instance of FileNotFoundException,
        // as only "checked" exceptions will be "wrapped" in a
        // PrivilegedActionException.
        throw (FileNotFoundException) e.getException();
      }
        ...normal code here...
  }

If a checked exception is thrown during execution of the run method, it is placed in a PrivilegedActionException "wrapper" exception that is then thrown and should be caught by your code, as illustrated in the above example..

Reflection

One subtlety that must be considered is the interaction of this API with reflection. The doPrivileged() method can be invoked reflectively using java.lang.reflect.Method.invoke(). In this case, the privileges granted in privileged mode are not those of Method.invoke() but of the non-reflective code that invoked it. Otherwise, system privileges could erroneously (or maliciously) be conferred on user code. Note that similar requirements exist when using the existing API via reflection.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.DoubleType (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.DoubleType

No usage of com.sun.jdi.DoubleType
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.DoubleValue (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.DoubleValue

  • Packages that use DoubleValue
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of DoubleValue in com.sun.jdi

      Methods in com.sun.jdi that return DoubleValue
      Modifier and Type Method and Description
      DoubleValue VirtualMachine.mirrorOf(double value)
      Creates a DoubleValue for the given value.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.DoWhileLoopTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.DoWhileLoopTree

  • Packages that use DoWhileLoopTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of DoWhileLoopTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type DoWhileLoopTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitDoWhileLoop(DoWhileLoopTree node, P p)

    • Uses of DoWhileLoopTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type DoWhileLoopTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitDoWhileLoop(DoWhileLoopTree node, P p)
      R | SimpleTreeVisitor.visitDoWhileLoop(DoWhileLoopTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


DownloadService (JNLP API Reference 1.7.0)

  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method
javax.jnlp

Interface DownloadService

  • public interface DownloadService
    DownloadService service allows an application to control how its own resources are cached, to determine which of its resources are currently cached, to force resources to be cached, and to remove resources from the cache. The JNLP Client is responsible for providing a specific implementation of this service.
    Since:
    1.0

    • Method Summary

      Methods
      Modifier and Type Method and Description
      DownloadServiceListener getDefaultProgressWindow()
      Return a default DownloadServiceListener implementation which, when passed to a load method, should pop up and update a progress window as the load progresses.
      boolean isExtensionPartCached(java.net.URL ref, java.lang.String version, java.lang.String part)
      Returns true if the given part of the given extension is cached, and the extension and part are mentioned in the JNLP file for the application.
      boolean isExtensionPartCached(java.net.URL ref, java.lang.String version, java.lang.String[] parts)
      Returns true if the given parts of the given extension are cached, and the extension and parts are mentioned in the JNLP file for the application.
      boolean isPartCached(java.lang.String part)
      Returns true if the part referred to by the given string is cached, and that part is mentioned in the JNLP file for the application.
      boolean isPartCached(java.lang.String[] parts)
      Returns true if the parts referred to by the given array are cached, and those parts are mentioned in the JNLP file for the application.
      boolean isResourceCached(java.net.URL ref, java.lang.String version)
      Returns true if the resource referred to by the given URL and version is cached, and that resource is either mentioned in the calling applications JNLP file, is within the codebase of the calling applications JNLP file, or the calling application has been granted all-permissions.
      void loadExtensionPart(java.net.URL ref, java.lang.String version, java.lang.String[] parts, DownloadServiceListener progress)
      Downloads the given parts of the given extension, if the parts and the extension are mentioned in the JNLP file for the application.
      void loadExtensionPart(java.net.URL ref, java.lang.String version, java.lang.String part, DownloadServiceListener progress)
      Downloads the given part of the given extension, if the part and the extension are mentioned in the JNLP file for the application.
      void loadPart(java.lang.String[] parts, DownloadServiceListener progress)
      Downloads the given parts, if the parts are mentioned in the JNLP file for the application.
      void loadPart(java.lang.String part, DownloadServiceListener progress)
      Downloads the given part, if the part is mentioned in the JNLP file for the application.
      void loadResource(java.net.URL ref, java.lang.String version, DownloadServiceListener progress)
      Downloads the given resource, if the resource is either mentioned in the calling applications JNLP file, is within the codebase of the calling applications JNLP file, or if the calling application has been granted all-permissions.
      void removeExtensionPart(java.net.URL ref, java.lang.String version, java.lang.String part)
      Removes the given part of the given extension from the cache, if the part and the extension are mentioned in the JNLP file for the application.
      void removeExtensionPart(java.net.URL ref, java.lang.String version, java.lang.String[] parts)
      Removes the given parts of the given extension from the cache, if the parts and the extension are mentioned in the JNLP file for the application.
      void removePart(java.lang.String part)
      Removes the given part from the cache, if the part is mentioned in the JNLP file for the application.
      void removePart(java.lang.String[] parts)
      Removes the given parts from the cache, if the parts are mentioned in the JNLP file for the application.
      void removeResource(java.net.URL ref, java.lang.String version)
      Removes the given resource from the cache, if the resource is either mentioned in the calling applications JNLP file, is within the codebase of the calling applications JNLP file, or if the calling application has been granted all-permissions.

    • Method Detail

      • isResourceCached

        boolean isResourceCached(java.net.URL ref,
                       java.lang.String version)
        Returns true if the resource referred to by the given URL and version is cached, and that resource is either mentioned in the calling applications JNLP file, is within the codebase of the calling applications JNLP file, or the calling application has been granted all-permissions. .
        Parameters:
        ref - The URL for the resource.
        version - The version string, or null for no version.
        Returns:
        true if the above conditions are met, and false otherwise.

      • isPartCached

        boolean isPartCached(java.lang.String part)
        Returns true if the part referred to by the given string is cached, and that part is mentioned in the JNLP file for the application.
        Parameters:
        part - The name of the part.
        Returns:
        true if the above conditions are met, and false otherwise.

      • isPartCached

        boolean isPartCached(java.lang.String[] parts)
        Returns true if the parts referred to by the given array are cached, and those parts are mentioned in the JNLP file for the application.
        Parameters:
        parts - An array of part names.
        Returns:
        true if the above conditions are met, and false otherwise.

      • isExtensionPartCached

        boolean isExtensionPartCached(java.net.URL ref,
                            java.lang.String version,
                            java.lang.String part)
        Returns true if the given part of the given extension is cached, and the extension and part are mentioned in the JNLP file for the application.
        Parameters:
        ref - The URL for the resource.
        version - The version string, or null for no version.
        part - The name of the part.
        Returns:
        true if the above conditions are met, and false otherwise.

      • isExtensionPartCached

        boolean isExtensionPartCached(java.net.URL ref,
                            java.lang.String version,
                            java.lang.String[] parts)
        Returns true if the given parts of the given extension are cached, and the extension and parts are mentioned in the JNLP file for the application.
        Parameters:
        ref - The URL for the resource.
        version - The version string, or null for no version.
        parts - An array of part names.
        Returns:
        true if the above conditions are met, and false otherwise.

      • loadResource

        void loadResource(java.net.URL ref,
                java.lang.String version,
                DownloadServiceListener progress)
                  throws java.io.IOException
        Downloads the given resource, if the resource is either mentioned in the calling applications JNLP file, is within the codebase of the calling applications JNLP file, or if the calling application has been granted all-permissions. This method will block until the download is completed or an exception occurs.
        Parameters:
        ref - The URL for the resource.
        version - The version string, or null for no version.
        progress - Download progress callback object.
        Throws:
        java.io.IOException

      • loadPart

        void loadPart(java.lang.String part,
            DownloadServiceListener progress)
              throws java.io.IOException
        Downloads the given part, if the part is mentioned in the JNLP file for the application. This method will block until the download is completed or an exception occurs.
        Parameters:
        part - The name of the part.
        progress - Download progress callback object.
        Throws:
        java.io.IOException

      • loadPart

        void loadPart(java.lang.String[] parts,
            DownloadServiceListener progress)
              throws java.io.IOException
        Downloads the given parts, if the parts are mentioned in the JNLP file for the application. This method will block until the download is completed or an exception occurs.
        Parameters:
        parts - An array of part names.
        progress - Download progress callback object.
        Throws:
        java.io.IOException

      • loadExtensionPart

        void loadExtensionPart(java.net.URL ref,
                     java.lang.String version,
                     java.lang.String part,
                     DownloadServiceListener progress)
                       throws java.io.IOException
        Downloads the given part of the given extension, if the part and the extension are mentioned in the JNLP file for the application. This method will block until the download is completed or an exception occurs.
        Parameters:
        ref - The URL for the resource.
        version - The version string, or null for no version.
        part - The name of the part.
        progress - Download progress callback object.
        Throws:
        java.io.IOException

      • loadExtensionPart

        void loadExtensionPart(java.net.URL ref,
                     java.lang.String version,
                     java.lang.String[] parts,
                     DownloadServiceListener progress)
                       throws java.io.IOException
        Downloads the given parts of the given extension, if the parts and the extension are mentioned in the JNLP file for the application. This method will block until the download is completed or an exception occurs.
        Parameters:
        ref - The URL for the resource.
        version - The version string, or null for no version.
        parts - An array of part names to load.
        progress - Download progress callback object.
        Throws:
        java.io.IOException

      • removeResource

        void removeResource(java.net.URL ref,
                  java.lang.String version)
                    throws java.io.IOException
        Removes the given resource from the cache, if the resource is either mentioned in the calling applications JNLP file, is within the codebase of the calling applications JNLP file, or if the calling application has been granted all-permissions.
        Parameters:
        ref - The URL for the resource.
        version - The version string, or null for no version.
        Throws:
        java.io.IOException

      • removePart

        void removePart(java.lang.String part)
                throws java.io.IOException
        Removes the given part from the cache, if the part is mentioned in the JNLP file for the application.
        Parameters:
        part - The name of the part.
        Throws:
        java.io.IOException

      • removePart

        void removePart(java.lang.String[] parts)
                throws java.io.IOException
        Removes the given parts from the cache, if the parts are mentioned in the JNLP file for the application.
        Parameters:
        parts - An array of part names.
        Throws:
        java.io.IOException

      • removeExtensionPart

        void removeExtensionPart(java.net.URL ref,
                       java.lang.String version,
                       java.lang.String part)
                         throws java.io.IOException
        Removes the given part of the given extension from the cache, if the part and the extension are mentioned in the JNLP file for the application.
        Parameters:
        ref - The URL for the resource.
        version - The version string, or null for no version.
        part - The name of the part.
        Throws:
        java.io.IOException

      • removeExtensionPart

        void removeExtensionPart(java.net.URL ref,
                       java.lang.String version,
                       java.lang.String[] parts)
                         throws java.io.IOException
        Removes the given parts of the given extension from the cache, if the parts and the extension are mentioned in the JNLP file for the application.
        Parameters:
        ref - The URL for the resource.
        version - The version string, or null for no version.
        parts - An array of part names.
        Throws:
        java.io.IOException

      • getDefaultProgressWindow

        DownloadServiceListener getDefaultProgressWindow()
        Return a default DownloadServiceListener implementation which, when passed to a load method, should pop up and update a progress window as the load progresses.
        Returns:
        A DownloadServiceListener object representing a download progress listener.
  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.


DownloadService2 (JNLP API Reference 1.7.0)

  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method
javax.jnlp

Interface DownloadService2

  • public interface DownloadService2
    Provides cache query services to JNLP applications. Together with methods in DownloadService, this allows for advanced programmatic cache management.
    Since:
    6.0.18

    • Nested Class Summary

      Nested Classes
      Modifier and Type Interface and Description
      static class  DownloadService2.ResourceSpec
      Specifies patterns for resource queries as arguments and holds results in getCachedResources(javax.jnlp.DownloadService2.ResourceSpec) and getUpdateAvailableResources(javax.jnlp.DownloadService2.ResourceSpec).

    • Field Summary

      Fields
      Modifier and Type Field and Description
      static int ALL
      Matches all resources in getCachedResources(javax.jnlp.DownloadService2.ResourceSpec) and getUpdateAvailableResources(javax.jnlp.DownloadService2.ResourceSpec).
      static int APPLET
      Matches applets in getCachedResources(javax.jnlp.DownloadService2.ResourceSpec) and getUpdateAvailableResources(javax.jnlp.DownloadService2.ResourceSpec).
      static int APPLICATION
      Matches applications in getCachedResources(javax.jnlp.DownloadService2.ResourceSpec) and getUpdateAvailableResources(javax.jnlp.DownloadService2.ResourceSpec).
      static int CLASS
      Matches class files in getCachedResources(javax.jnlp.DownloadService2.ResourceSpec) and getUpdateAvailableResources(javax.jnlp.DownloadService2.ResourceSpec).
      static int EXTENSION
      Matches extensions in getCachedResources(javax.jnlp.DownloadService2.ResourceSpec) and getUpdateAvailableResources(javax.jnlp.DownloadService2.ResourceSpec).
      static int IMAGE
      Matches image files in getCachedResources(javax.jnlp.DownloadService2.ResourceSpec) and getUpdateAvailableResources(javax.jnlp.DownloadService2.ResourceSpec).
      static int JAR
      Matches JARs in getCachedResources(javax.jnlp.DownloadService2.ResourceSpec) and getUpdateAvailableResources(javax.jnlp.DownloadService2.ResourceSpec).

    • Method Summary

      Methods
      Modifier and Type Method and Description
      DownloadService2.ResourceSpec[] getCachedResources(DownloadService2.ResourceSpec spec)
      Returns all resources in the cache that match one of the specified resource specs.
      DownloadService2.ResourceSpec[] getUpdateAvailableResources(DownloadService2.ResourceSpec spec)
      Returns all resources in the cache that match one of the specified resource specs AND have an update available from their server.

    • Field Detail

      • ALL

        static final int ALL
        Matches all resources in getCachedResources(javax.jnlp.DownloadService2.ResourceSpec) and getUpdateAvailableResources(javax.jnlp.DownloadService2.ResourceSpec).
        See Also:
        Constant Field Values

      • APPLICATION

        static final int APPLICATION
        Matches applications in getCachedResources(javax.jnlp.DownloadService2.ResourceSpec) and getUpdateAvailableResources(javax.jnlp.DownloadService2.ResourceSpec).
        See Also:
        Constant Field Values

      • APPLET

        static final int APPLET
        Matches applets in getCachedResources(javax.jnlp.DownloadService2.ResourceSpec) and getUpdateAvailableResources(javax.jnlp.DownloadService2.ResourceSpec).
        See Also:
        Constant Field Values

      • EXTENSION

        static final int EXTENSION
        Matches extensions in getCachedResources(javax.jnlp.DownloadService2.ResourceSpec) and getUpdateAvailableResources(javax.jnlp.DownloadService2.ResourceSpec).
        See Also:
        Constant Field Values

      • JAR

        static final int JAR
        Matches JARs in getCachedResources(javax.jnlp.DownloadService2.ResourceSpec) and getUpdateAvailableResources(javax.jnlp.DownloadService2.ResourceSpec).
        See Also:
        Constant Field Values

      • IMAGE

        static final int IMAGE
        Matches image files in getCachedResources(javax.jnlp.DownloadService2.ResourceSpec) and getUpdateAvailableResources(javax.jnlp.DownloadService2.ResourceSpec).
        See Also:
        Constant Field Values

      • CLASS

        static final int CLASS
        Matches class files in getCachedResources(javax.jnlp.DownloadService2.ResourceSpec) and getUpdateAvailableResources(javax.jnlp.DownloadService2.ResourceSpec).
        See Also:
        Constant Field Values

    • Method Detail

      • getCachedResources

        DownloadService2.ResourceSpec[] getCachedResources(DownloadService2.ResourceSpec spec)
        Returns all resources in the cache that match one of the specified resource specs.
        For supported patterns in the query arguments, see DownloadService2.ResourceSpec. The returned ResourceSpec objects have specific URL and version properties (i.e. no patterns).
        Parameters:
        spec - the spec to match resources against
        Returns:
        all resources that match one of the specs
        Throws:
        java.lang.IllegalArgumentException -
        if the ResourceSpec is null, or
        if the ResourceSpec contains a null or empty URL string, or
        if the ResourceSpec contains invalid regular expressions.
        if the ResourceSpec contains a type that is not one of:
        ALL, APPLICATION, APPLET, EXTENSION, JAR, IMAGE, or CLASS.

      • getUpdateAvailableResources

        DownloadService2.ResourceSpec[] getUpdateAvailableResources(DownloadService2.ResourceSpec spec)
                                                            throws java.io.IOException
        Returns all resources in the cache that match one of the specified resource specs AND have an update available from their server.
        For supported patterns in the query arguments, see DownloadService2.ResourceSpec. The returned ResourceSpec objects have specific URL and version properties (i.e. no patterns).
        NOTE: This call may attempt HTTP GET request to check for update.
        Parameters:
        spec - the spec to match resources against
        Returns:
        all resources for which an update is available that match one of the specs
        Throws:
        java.io.IOException - if something went wrong during update checks
        java.lang.IllegalArgumentException -
        if the ResourceSpec is null, or
        if the ResourceSpec contains a null or empty URL string, or
        if the ResourceSpec contains invalid regular expressions.
        if the ResourceSpec contains a type that is not one of:
        ALL, APPLICATION, APPLET, EXTENSION, JAR, IMAGE, or CLASS.
  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.


DownloadService2.ResourceSpec (JNLP API Reference 1.7.0)

  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method
javax.jnlp

Class DownloadService2.ResourceSpec

  • java.lang.Object
    • javax.jnlp.DownloadService2.ResourceSpec
  • Enclosing interface:
    DownloadService2

    public static class DownloadService2.ResourceSpec
extends java.lang.Object
    Specifies patterns for resource queries as arguments and holds results in DownloadService2.getCachedResources(javax.jnlp.DownloadService2.ResourceSpec) and DownloadService2.getUpdateAvailableResources(javax.jnlp.DownloadService2.ResourceSpec).
    For the url and version properties, standard regular expressions as documented in {code java.util.regex} are supported.

    • Constructor Summary

      Constructors
      Constructor and Description
      DownloadService2.ResourceSpec(java.lang.String url, java.lang.String version, int type)
      Creates a new ResourceSpec instance.

    • Method Summary

      Methods
      Modifier and Type Method and Description
      long getExpirationDate()
      Returns the time of expiration of the resource.
      long getLastModified()
      Returns the time of last modification of the resource.
      long getSize()
      Returns the size of a resource.
      int getType()
      Returns the type of this resource.
      java.lang.String getUrl()
      Returns the URL of this resource.
      java.lang.String getVersion()
      Returns the version of this resource.

      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

    • Constructor Detail

      • DownloadService2.ResourceSpec

        public DownloadService2.ResourceSpec(java.lang.String url,
                             java.lang.String version,
                             int type)
        Creates a new ResourceSpec instance.
        Parameters:
        url - the URL pattern
        version - the version pattern
        type - the resource type. This should be one of the following constants defined in DownloadService2: ALL, APPLICATION, APPLET, EXTENSION, JAR, IMAGE, or CLASS.

    • Method Detail

      • getUrl

        public java.lang.String getUrl()
        Returns the URL of this resource.
        Returns:
        the URL of this resource

      • getVersion

        public java.lang.String getVersion()
        Returns the version of this resource.
        Returns:
        the version of this resource

      • getType

        public int getType()
        Returns the type of this resource.
        Returns:
        the type of this resource

      • getSize

        public long getSize()
        Returns the size of a resource. This is only useful for ResourceSpecs that have been returned as a result of DownloadService2.getCachedResources(javax.jnlp.DownloadService2.ResourceSpec) or DownloadService2.getUpdateAvailableResources(javax.jnlp.DownloadService2.ResourceSpec).
        Returns:
        the size of a resource

      • getLastModified

        public long getLastModified()
        Returns the time of last modification of the resource.
        The returned value has the same semantics as the return value of System.currentTimeMillis().
        A value of 0 means unknown.
        Returns:
        the time of last modification of the resource

      • getExpirationDate

        public long getExpirationDate()
        Returns the time of expiration of the resource.
        The returned value has the same semantics as the return value of System.currentTimeMillis().
        A value of 0 means unknown.
        Returns:
        the time of expiration of the resource
  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.


DownloadServiceListener (JNLP API Reference 1.7.0)

  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method
javax.jnlp

Interface DownloadServiceListener

  • public interface DownloadServiceListener
    The DownloadServiceListener provides an interface for a callback object implementation, which may be used by a DownloadService implementation. The DownloadServiceListener implementation's methods should be invoked by the DownloadService implementation at various stages of the download, allowing an application that uses the JNLP API to display a progress bar during a DownloadService download.
    Since:
    1.0
    See Also:
    DownloadService

    • Method Summary

      Methods
      Modifier and Type Method and Description
      void downloadFailed(java.net.URL url, java.lang.String version)
      A JNLP client's DownloadService implementation should call this method if a download fails or aborts unexpectedly.
      void progress(java.net.URL url, java.lang.String version, long readSoFar, long total, int overallPercent)
      A JNLP client's DownloadService implementation should call this method several times during a download.
      void upgradingArchive(java.net.URL url, java.lang.String version, int patchPercent, int overallPercent)
      A JNLP client's DownloadService implementation should call this method at least several times when applying an incremental update to an in-cache resource.
      void validating(java.net.URL url, java.lang.String version, long entry, long total, int overallPercent)
      A JNLP client's DownloadService implementation should call this method at least several times during validation of a download.

    • Method Detail

      • progress

        void progress(java.net.URL url,
            java.lang.String version,
            long readSoFar,
            long total,
            int overallPercent)
        A JNLP client's DownloadService implementation should call this method several times during a download. A DownloadServiceListener implementation may display a progress bar and / or update information based on the parameters.
        Parameters:
        url - The URL representing the resource being downloaded.
        version - The version of the resource being downloaded.
        readSoFar - The number of bytes downloaded so far.
        total - The total number of bytes to be downloaded, or -1 if the number is unknown.
        overallPercent - The percentage of the overall update operation that is complete, or -1 if the percentage is unknown.

      • validating

        void validating(java.net.URL url,
              java.lang.String version,
              long entry,
              long total,
              int overallPercent)
        A JNLP client's DownloadService implementation should call this method at least several times during validation of a download. Validation often includes ensuring that downloaded resources are authentic (appropriately signed). A DownloadServiceListener implementation may display a progress bar and / or update information based on the parameters.
        Parameters:
        url - The URL representing the resource being validated.
        version - The version of the resource being validated.
        entry - The number of JAR entries validated so far.
        total - The total number of entries to be validated.
        overallPercent - The percentage of the overall update operation that is complete, or -1 if the percentage is unknown.

      • upgradingArchive

        void upgradingArchive(java.net.URL url,
                    java.lang.String version,
                    int patchPercent,
                    int overallPercent)
        A JNLP client's DownloadService implementation should call this method at least several times when applying an incremental update to an in-cache resource. A DownloadServiceListener implementation may display a progress bar and / or update information based on the parameters.
        Parameters:
        url - The URL representing the resource being patched.
        version - The version of the resource being patched.
        patchPercent - The percentage of the patch operation that is complete, or -1 if the percentage is unknown.
        overallPercent - The percentage of the overall update operation that is complete, or -1 if the percentage is unknown.

      • downloadFailed

        void downloadFailed(java.net.URL url,
                  java.lang.String version)
        A JNLP client's DownloadService implementation should call this method if a download fails or aborts unexpectedly. In response, a DownloadServiceListener implementation may display update information to the user to reflect this.
        Parameters:
        url - The URL representing the resource for which the download failed.
        version - The version of the resource for which the download failed.
  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.


JnlpDownloadServlet Guide

Table of Contents

Introduction
Using JnlpDownloadServlet
Substitutions
Version, Extension, and Platform Requests
Incremental Updates with JARDiff
Faster Downloads with Pack200
Other Features
Building JnlpDownloadServlet
Reference

Introduction

JnlpDownloadServlet is a servlet that simplifies the process of deploying Java Web Start applications on a web server as well as providing enhanced functionality. JnlpDownloadServlet is available in the sample/jnlp/servlet directory of the JDK, both as compiled JAR files and as source code.

In the simplest case of JNLP deployment, you put your application files and a JNLP file on a web server. After you configure the web server for the JNLP MIME type, you have basic JNLP functionality — the user clicks on a JNLP file link in a browser and your application is downloaded and run.

However, this approach has some drawbacks. First, the explicit URL of the application codebase must appear in the JNLP file. This means it must be changed if you decide to host your application elsewhere, or if you're moving from a local test server to a more public production server. In addition, the file system time stamp on your application files will be used to report the time stamp of your application, which might not be what you want. Finally, only the most basic parts of the JNLP protocol are implemented through HTTP. Versioning and other features are not supported.

Features

JnlpDownloadServlet acts as a liaison between your application files and the client. It provides the following features:

  • You do not have to hardcode codebase URLs in the JNLP file. This simplifies moving from one server to another.
  • You can specify an explicit time stamp for your application files, instead of relying on file system time stamps.
  • The servlet supports the full set of download protocols defined by the JNLP specification.
  • Version information can be specified per file or per directory.
  • The servlet generates JARDiff files.
  • The servlet supports Pack200 compression for application files.

Baseline Example

To understand the useful features that JnlpDownloadServlet brings to application deployment, you must first understand the simplest way an application can be distributed using JNLP and Java Web Start.

The app1 example (in the sample/jnlp/servlet directory of the JDK) contains a simple application and, perhaps more valuable, an Ant build script that builds the application and bundles it in a WAR file for distribution on a web server.

The application itself consists of a single class, Pie, and an image file, key-lime.jpg, which are packaged into the pie.jar JAR file.

The pie.jar archive is packaged into a web application file, app1.war, which has these contents:

WEB-INF/web.xml
index.html
pie.jnlp
pie.jar

The JNLP file describes the application, assuming it is deployed on a server at http://localhost:8080/, which works for a locally installed Tomcat server.

<?xml version="1.0" encoding="UTF-8"?>
<jnlp spec="1.0+" codebase="http://localhost:8080/app1">
    <information>
        <title>Pie</title>
        <vendor>Example Vendor</vendor>
    </information>
    <resources>
        <j2se version="1.2+"/>
        <jar href="pie.jar" main="true" />
    </resources>
    <application-desc/>
</jnlp>

Consider the interaction between client and server as a dialog:

[User clicks a link in the browser.]

Client browser: May I please have pie.jnlp?

Server: Yes, here you go.

Client browser: I notice the MIME type is application/x-java-jnlp-file. Java Web Start, would you please handle pie.jnlp for me?

Client Java Web Start: Let me see what resources are required for this application. Hey Server, can I please have pie.jar?

Server: Here you go.

Client Java Web Start: Now I'll launch the JAR file using its Main-class manifest attribute.

[Application appears on the user's screen.]

Other Examples

The app2 example shows how to bundle JnlpDownloadServlet with an application and how to use it to perform simple substitutions in a JNLP file.

The app3 example shows how a versioned resource request is handled by JnlpDownloadServlet.

Both app2 and app3 will be referenced from the following sections.

Using JnlpDownloadServlet

To take advantage of JnlpDownloadServlet, perform these steps.

  1. Package JnlpDownloadServlet in your web application WAR file. You must use two JAR files to have the full functionality, jnlp-servlet.jar and jardiff.jar. These two JAR files are put in the WEB-INF/lib directory of your WAR file.
  2. Map requests for *.jnlp and *.jar to JnlpDownloadServlet using your web application's web.xml file. It must contain lines that identify JnlpDownloadServlet and makes it the handler for JNLP and JAR files. Here is a complete example:
    <?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

  <servlet>
    <servlet-name>JnlpDownloadServlet</servlet-name>
    <servlet-class>jnlp.sample.servlet.JnlpDownloadServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>JnlpDownloadServlet</servlet-name>
    <url-pattern>*.jnlp</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>JnlpDownloadServlet</servlet-name>
    <url-pattern>*.jar</url-pattern>
  </servlet-mapping>

</web-app>

The app2 and app3 examples show how to package JnlpDownloadServlet in a web application. Review the Ant build script app2/build.xml or app3/build.xml for more information.

Substitutions

JnlpDownloadServlet makes convenient substitutions in your JNLP files. When the client requests a JNLP file, the servlet reads the original file, substitutes values, and returns the results.

Time Stamp

If the first line of your JNLP file contains a time stamp, JnlpDownloadServlet uses the value as a time stamp for your application. If you do not specify a time stamp, JnlpDownloadServlet uses the last modified time stamp from the file system.

Using an explicit time stamp is useful if you copy a JNLP file to multiple servers for load balancing. The explicit time stamp ensures that clients see consistent results, regardless of which server they consult.

To use an explicit time stamp, add a line to the top of your JNLP file. Begin the line with TS:. The rest of the line must contain a time stamp in ISO 8601 format, which has this basic format:

YYYY-MM-DD hh:mm:ss

Here is one example:

TS: 2010-08-07 21:19:05

Consult the Reference section for a more complete description of the time stamp string.

Codebase and Other Values

JnlpDownloadServlet makes substitutions for strings that begin with two dollar signs. For example, consider this line in a JNLP file:

<jnlp spec="1.0+" codebase="$$codebase">

When a client requests the JNLP file, JnlpDownloadServlet substitutes the correct value for $$codebase, wherever it is deployed. This is convenient because you do not have to hardcode this value in the JNLP file, making it easier to move from server to server.

The full list of substitutions is shown in the following table:

Name | Substituted value
$$codebase | The URL of the request except for the name of the JNLP file
$$name | The name of the JNLP file
$$context | The base URL of the web application
$$site | The web server address
$$hostname | The name of the server

For example, suppose the app2 example is deployed at example.com. The values of each substitution would be as follows:

Name | Substituted value
$$codebase | http://example.com/app2/
$$name | pie.jnlp
$$context | http://example.com/app2
$$site | http://example.com
$$hostname | example.com

The app2/pie.jnlp and app3/pie.jnlp examples use only $$codebase.

Version, Extension, and Platform Requests

The JNLP specification supports requesting application resources with explicit version numbers or resources for certain locales, operating systems, and system architectures. This means that you can deploy an application that has different libraries for different operating systems or different resource files for different locales.

JnlpDownloadServlet provides support for special requests with two different mechanisms. The first is a scheme for naming resource files where locales, operating systems, and other parameters are embedded in the file name. The second mechanism involves an XML file that describes the parameters of resource files in the same directory.

File Naming Convention

JnlpDownloadServlet enables you to specify information about files by embedding it in a file name. If the file name contains two underscores in a row, the file name is treated as containing attributes. A prefix letter specifies the attribute information, as shown here:

Prefix | Meaning
V | Version number
O | Operating system
A | Architecture
L | Locale

Only one version is allowed per file, but a file can be associated with multiple operating system, architecture, or locale attributes. For example, application__V1.2__Len_US__Len.jar means that the resource application.jar has a version of 1.2, and associated locales of en_US and en.

For example, consider a JNLP file that contains this resource line:

<jar href="app-lib.jar" version="2.0" />

When Java Web Start encounters this line in the JNLP file, it sends a request to the server for version 2.0 of app-lib.jar. If you have placed a file app-lib__V2.0.jar in your web application, JnlpDownloadServlet returns it to the client as version 2.0 of app-lib.jar. Note how the actual file name in your web application gets remapped to be visible to the client as app-lib.jar.

XML Version File

The file naming convention can be cumbersome, especially if you have multiple resource files that each have multiple associations for operating systems, architectures, or locales.

JnlpDownloadServlet supports an alternate mechanism, where all attributes are described in a separate XML file. The servlet looks for a version.xml file in the same directory as the resource. The version.xml file contains information about the other files in the same directory.

For example, the following version.xml file describes a resource that is available to a client as application.jar. The actual file is stored in the same directory as application-1_2-us.jar.

<jnlp-versions>
  <resource>
    <pattern>
      <name>application.jar</name>
      <version-id>1.2</version-id>
      <locale>en_US</locale>
      <locale>en</locale>
    </pattern>
    <file>application-1_2-us.jar</file>
  </resource>
</jnlp-versions>

The app3 example shows how to respond to a versioned request for a resource using the XML version file. In particular, the JNLP file contains this resource line:

<jar href="app-lib.jar" version="2.0" />

The WAR file contains the library, app-lib.jar, and this XML version file version.xml that describes the library:

<jnlp-versions>
  <resource>
    <pattern>
      <name>app-lib.jar</name>
      <version-id>2.0</version-id>
    </pattern>
    <file>app-lib-2.0.jar</file>
  </resource>
</jnlp-versions>

Note how the actual name of the file, app-lib-2.0.jar, is remapped so that the file name visible from the client is app-lib.jar.

Incremental Updates with JARDiff

JnlpDownloadServlet generates and returns incremental updates to JAR files, if possible. If the current-version-id parameter is included in the request, and the servlet can find both a match on the current-version-id and the requested version, and the request is for a JAR file, then a JARDiff file is generated by the servlet. The JARDiff file is returned if its size is less than that of the requested version.

The JARDiff file is generated and stored in a temporary directory that is specific to the web container. The servlet finds the temporary working directory using the javax.servlet.context.tempdir context attribute.

Faster Downloads with Pack200

Pack200 is an efficient compression technology for JAR files. Download and installation times for applications are important factors in how users perceive applications. Making your application resources as small as possible reduces the amount of time users must wait for your application to download.

JnlpDownloadServlet can supply resources for clients, such as Java Web Start, that support GZIP and Pack200 downloads. Place *.jar.pack.gz or *.jar.gz files together with your original *.jar files on the server. For example, JnlpDownloadServlet chooses the best of the following files, based upon what the client supports:

pie.jar
pie.jar.gz
pie.jar.pack.gz

You can create Pack200 files using the pack200 tool that is included with the Java Development Kit. The app3 example creates a Pack200 version of the pie.jar file. Look at build.xml to see how the Pack200 file is created. Because pie.jar is simple, the Pack200 file is negligibly smaller; however, for a larger JAR file, the compression is much greater.

Other Features

JNLP substitutions, Pack200 support, and file attribute support are the most useful features of JnlpDownloadServlet. The servlet also supports a logging system and MIME type mapping.

Logging

The servlet has logging capabilities that enable you to monitor its behavior. Logging messages are generated in different categories:

  • FATAL means a malfunction or internal error occurred inside the servlet.
  • WARNING indicates an error processing some of the information in the WAR file or parsing the version.xml file.
  • INFORMATIONAL logs all requests, replies, directory scanning, and so on.
  • DEBUG displays detailed internal information about how a request is processed.

Logging output is controlled by two servlet initialization parameters, logLevel and logPath. The log level can be set to either NONE, FATAL, WARNING, INFORMATIONAL, or DEBUG. The log path specifies a file where the output is written. If no path is specified, logging is done to the standard log for servlets (using ServletContext.log()). Here is an example:

<servlet>
  <servlet-name>
    JnlpDownloadServlet
  </servlet-name>
  <servlet-class>
    jnlp.sample.servlet.JnlpDownloadServlet
  </servlet-class>

  <init-param>
    <param-name>
      logLevel
    </param-name>

    <param-value>
      DEBUG
    </param-value>
  </init-param>

  <init-param>
    <param-name>
      logPath
    </param-name>

    <param-value>
      /logs/jnlpdownloadservlet.log
    </param-value>
  </init-param>

</servlet>

MIME Types

The servlet treats JNLP and JAR files specially. Substitutions are made in JNLP files as desribed in Substitutions. A version-based request for a JAR file can result in the generation of an incremental update. The servlet uses extensions to determine if a file is a JNLP or JAR file. The default extension of JNLP files is .jnlp and for JAR files is .jar. These default extensions can be overwritten by the initialization parameters: jnlp-extension and jar-extension. Here is an example:

<init-param>
  <param-name>
    jnlp-extension
  </param-name>

  <param-value>
    .xjnlp
  </param-value>
</init-param>

The MIME type that is returned for a file is also based on its extension. The MIME type is looked up in the configuration files for the web container and the WAR file. If no mapping is specified, the default MIME types are assigned:

Extension | Default MIME Type
.jnlp | application/x-java-jnlp-file
.jar | application/x-java-archive
.jardiff | application/x-java-archive-diff

To change the MIME type JnlpDownloadServlet returns, use the <mime-type> element in the web.xml file. Here is an example:

<web-app>
   ...
   <mime-mapping>
      <extension>jnlp</extension>
      <mime-type>text/ascii</mime-type>
   </mime-mapping>
   ...
</web-app>

Building JnlpDownloadServlet

Most of the time, you will use JnlpDownloadServlet directly. In rare cases, you might want to add functionality to JnlpDownloadServlet. The full source code is available, and the build is relatively straightforward.

You must have GNU make, a Java Development Kit (JDK), and you must define environment variables. Here is one example on a Linux system.

$ export CLASS_PATH=/home/edmond/Applications/apache-tomcat-7.0.2/lib/servlet-api.jar
$ export FILE_SEPARATOR=:
$ export TMPDIR=/tmp
$ export SDK_HOME=/home/edmond/jdk1.7.0
$ make
.
.
.

The output of the build is lib/jnlp-servlet.jar and lib/jardiff.jar.

Reference

More Information About ISO 8601 Time Stamps

The general format of a time stamp is:

   YYYY-MM-DD hh:mm:ss

The dashes, colons, and seconds are optional:

   YYYYMMDDhhmm

The hh is in 24-hour notation. By default, the local time zone is used. Universal Time (UTC), also known as GMT time, can be specified by appending the capital letter Z to a time:

     23:59:59Z or 235959Z

The strings +hh:mm, +hhmm, or +hh can be added to the time to indicate that the local time zone is hh hours and mm minutes ahead of UTC. For time zones west of the zero meridian, which are behind UTC, the notation -hh:mm, -hhmm, or -hh is used instead. For example, Central European Time (CET) is +0100 and U.S./Canadian Eastern Standard Time (EST) is -0500. The following strings all indicate the same point in time:

     12:00Z = 13:00+01:00 = 0700-0500

Specification of the XML Version File

The complete document type definition (DTD) for the version.xml file is shown here:

<!ELEMENT jnlp-versions <resource*, platform*)>
<!ELEMENT resource (pattern, file)>
<!ELEMENT platform (pattern, file, product-version-id)>
<!ELEMENT pattern (name, version-id, os*, arch*, locale*)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT version-id (#PCDATA)>
<!ELEMENT os (#PCDATA)>
<!ELEMENT arch (#PCDATA)>
<!ELEMENT locale (#PCDATA)>
<!ELEMENT file (#PCDATA)>
<!ELEMENT product-version-id (#PCDATA)>
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


DTrace Probes in HotSpot VM

  • Overview
  • The hotspot Provider
    • VM Lifecycle Probes
    • Thread Lifecycle Probes
    • Classloading Probes
    • Garbage Collection Probes
    • Method Compilation Probes
    • Monitor Probes
    • Application Tracking Probes
  • The hotspot_jni Provider
  • Reference

Overview

With the introduction of DTrace on Solaris 10, DTrace support has been added to the Java SE 6 HotSpot VM. The hotspot and hotspot_jni providers make available probes that can be used to monitor JVM internal state and activities as well as the Java application that is running. All of the probes are USDT probes and are accessed using the process-id of the JVM process. The probe details are listed in the next section, and the API is provided in the reference section.

The hotspot Provider

The hotspot provider makes available probes that can be used to track the lifespan of the VM, thread start and stop events, GC and memory pool statistics, method compilations, and monitor activity. With a startup flag, additional probes are enabled which can be used to monitor the running Java program, such as method enter and return probes, and object allocations. All of the hotspot probes originate in the VM library (libjvm.so), so they are also provided from programs which embed the VM.

Many of the probes in the provider have arguments that can be examined to provide further details on the state of the VM. Many of these probes' arguments are opaque IDs which can be used to link probe firings to each other, however strings and other data are also provided. When string values are provided, they are always present as a pair: a pointer to unterminated modified UTF-8 data (see JVM spec :4.4.7) , and a length value which indicates the extent of that data. Because the string data (even when none of the characters are outside the ASCII range) is not guaranteed to be terminated by a NUL character, it is necessary to use the length-terminated copyinstr() intrinsic to read the string data from the process.

VM Life-cycle Probes

The probes that relate to the VM life-cycle are indicated below. None have any arguments at this time.

vm-init-begin | Probe that fires just as the VM initialization begins
vm-init-end | Probe that fires when the VM initialization finishes, and the VM is ready to start running application code
vm-shutdown | Probe that fires as the VM is shutting down due to program termination or an error

Thread Lifecycle Probes

Two probes are available for tracking thread start and stop events.

thread-start | Probe that fires when a thread is started. Provides the arguments listed below
thread-stop | Probe that fires when the thread has completed. Provides the arguments listed below

Each of these probes has the following arguments:

args[0] | A pointer to UTF-8 string data which contains the thread name
args[1] | The length of the thread name data (in bytes)
args[2] | The Java thread ID. This is the value that will match other HotSpot VM probes which contain a thread argument
args[3] | The native/OS thread ID. This is the ID assigned by the host operating system
args[4] | A boolean value which indicates if this thread is a daemon or not. A value of 0 indicates a non-daemon thread

Classloading Probes

Two probes are available for tracking class loading and unloading activity.

class-loaded | Probe that fires when a class has been loaded
class-unloaded | Probe that fires when a class has been unloaded from the system

Each of these probes has the following arguments:

args[0] | A pointer to UTF-8 string data which contains the name of the class that was loaded
args[1] | The length of the class name data (in bytes)
args[2] | The class loader ID, which is a unique identifier for a class loader in the VM. This is the class loader that loaded the class
args[3] | A boolean value which indicates if the class is a shared class (if the class was loaded from the shared archive)

Garbage Collection Probes

Probes are available that can be used to measure the duration of a system-wide garbage collection cycle (for those garbage collectors that have a defined begin and end). Each memory pool can be tracked independently. The probes for individual pools pass the memory manager's name, the pool name, and pool usage information at both the begin and end of pool collection.

The provided GC-related probes are:

gc-begin | Probe that fires when a system-wide collection is about to start. It's one argument (arg[0]) is a boolean value which indicates if this is to be a Full GC.
gc-end | Probe that fires when a system-wide collection has completed. No arguments.
mem-pool-gc-begin | Probe that fires when an individual memory pool is about to be collected. Provides the arguments listed below
mem-pool-gc-end | Probe that fires after an individual memory pool has been collected. Provides the arguments listed below

Memory pool probe arguments:

args[0] | A pointer to UTF-8 string data which contains the name of the manager which manages this memory pool
args[1] | The length of the manager name data (in bytes)
args[2] | A pointer to UTF-8 string data which contains the name of the memory pool
args[3] | The length of the memory pool name data (in bytes)
args[4] | The initial size of the memory pool (in bytes)
args[5] | The amount of memory in use in the memory pool (in bytes)
args[6] | The number of committed pages in the memory pool
args[7] | The maximum size of the memory pool

Method Compilation Probes

Probes are available to indicate which methods are being compiled and by which compiler. Probes are also available to track the installing and uninstalling of compiled methods.

Probes that mark the begin and end of method compilation:

method-compile-begin | Probe that fires as method compilation begins. Provides the arguments listed below
method-compile-end | Probe that fires when method compilation completes. In addition to the arguments listed below, argv[8] is a boolean value which indicates if the compilation was successful

Method compilation probe arguments:

args[0] | A pointer to UTF-8 string data which contains the name of the compiler which is compiling this method
args[1] | The length of the compiler name data (in bytes)
args[2] | A pointer to UTF-8 string data which contains the name of the class of the method being compiled
args[3] | The length of the class name data (in bytes)
args[4] | A pointer to UTF-8 string data which contains the name of the method being compiled
args[5] | The length of the method name data (in bytes)
args[6] | A pointer to UTF-8 string data which contains the signature of the method being compiled
args[7] | The length of the signature data (in bytes)

When compiled methods are installed for execution or uninstalled, the following probes are fired:

compiled-method-load | Probe that fires when a compiled method is installed. In addition to the arguments listed below, argv[6] contains a pointer to the compiled code, and argv[7] is the size of the compiled code
compiled-method-unload | Probe that fires when a compiled method is uninstalled. Provides the arguments listed below

Compiled method loading probe arguments:

args[0] | A pointer to UTF-8 string data which contains the name of the class of the method being installed
args[1] | The length of the class name data (in bytes)
args[2] | A pointer to UTF-8 string data which contains the name of the method being installed
args[3] | The length of the method name data (in bytes)
args[4] | A pointer to UTF-8 string data which contains the signature of the method being installed
args[5] | The length of the signature data (in bytes)

Monitor Probes

As the Java application runs, threads will enter and exit monitors, wait on monitors, and perform notifications. Probes are available for all wait and notification events, as well as for contended monitor entry and exit events. A contended monitor entry is the situation where a thread attempts to enter a monitor when another thread is already in the monitor. A contended monitor exit event occurs when a thread leaves a monitor and other threads are waiting to enter to the monitor. Thus, contended enter and contended exit events may not match up to each other in relation to the thread that encounters these events, though it is expected that a contended exit from one thread should match up to a contended enter on another thread (the thread waiting to enter the monitor).

All monitor events provide the thread ID, a monitor ID, and the type of the class of the object as arguments. It is expected that the thread and the class will help map back to the Java program, while the monitor ID can provide matching information between probe firings.

Since the existence of these probes in the VM causes performance degradation, they will only fire if the VM flag -XX:+ExtendedDTraceProbes is set on the java command line. This flag can be turned on and off dynamically at runtime by using the jinfo utility.

If the above flag is off, the monitor probes are still present in the probe listing obtainable from dtrace, but will remain dormant and will never fire. It is intended that this restriction be removed in future releases of the VM, where these probes will be enabled all the time with no impact to performance.

The available probes:

monitor-contended-enter | Probe that fires as a thread attempts to enter a contended monitor
monitor-contended-entered | Probe that fires when a thread successfully enters the contended monitor
monitor-contended-exit | Probe that fires when a thread leaves a monitor and other threads are waiting to enter
monitor-wait | Probe that fires as a thread begins a wait on a monitor via Object.wait(). The probe has an additional argument, args[4] which is a 'long' value which indicates the timeout being used.
monitor-waited | Probe that fires when a thread completes an Object.wait().
monitor-notify | Probe that fires when a thread calls Object.notify() to notify waiters on a monitor
monitor-notifyAll | Probe that fires when a thread calls Object.notifyAll() to notify waiters on a monitor

Monitor probe arguments:

args[0] | The Java thread identifier for the thread performing the monitor operation
args[1] | A unique, but opaque identifier for the specific monitor that the action is performed upon
args[2] | A pointer to UTF-8 string data which contains the class name of the object being acted upon
args[3] | The length of the class name data (in bytes)

Application Tracking Probes

A few probes are provided to allow fine-grained examination of Java thread execution. These consist of probes that fire anytime a method is entered or returned from, as well as a probe that fires whenever a Java object has been allocated.

Since the existence of these probes in the VM causes performance degradation, they will only fire if the VM has the ExtendedDTraceProbes flag enabled. By default the probes are all present in any listing of the probes in the VM, but are dormant without the appropriate flag. It is intended that this restriction be removed in future releases of the VM, where these probes will be enabled all the time with no impact to performance.

The method entry and return probes:

method-entry | Probe that fires when a method is being entered.
method-return | Probe that fires when a method returns, either normally or due to an exception.

Method probe arguments:

args[0] | The Java thread ID of the thread that is entering or leaving the method
args[1] | A pointer to UTF-8 string data which contains the name of the class of the method
args[2] | The length of the class name data (in bytes)
args[3] | A pointer to UTF-8 string data which contains the name of the method
args[4] | The length of the method name data (in bytes)
args[5] | A pointer to UTF-8 string data which contains the signature of the method
args[6] | The length of the signature data (in bytes)

The available allocation probe:

object-alloc Probe that fires when any object is allocated, provided that the ExtendedDTraceProbes flag is enabled.

The object allocation probe has the following arguments:

args[0] | The Java thread ID of the thread that is allocating the object
args[1] | A pointer to UTF-8 string data which contains the class name of the object being allocated
args[2] | The length of the class name data (in bytes)
args[3] | The size of the object being allocated

The hotspot_jni Provider

In order to call from native code to Java code, due to embedding of the VM in an application or execution of native code within a Java application, the native code must make a call through the JNI interface. The JNI interface provides a number of methods for invoking Java code and examining the state of the VM. DTrace probes are provided at the entry point and return point for each of these methods. The probes are provided by the hotspot_jni provider. The name of the probe is the name of the JNI method, appended with "-entry" for entry probes, and "-return" for return probes. The arguments available at each entry probe are the arguments that were provided to the function (with the exception of the Invoke* methods, which omit the arguments that are passed to the Java method). The return probes have the return value of the method as an argument (if available).

Reference

provider hotspot {
  probe vm-init-begin();
  probe vm-init-end();
  probe vm-shutdown();
  probe class-loaded(
      char* class_name, uintptr_t class_name_len, uintptr_t class_loader_id, bool is_shared);
  probe class-unloaded(
      char* class_name, uintptr_t class_name_len, uintptr_t class_loader_id, bool is_shared);
  probe gc-begin(bool is_full);
  probe gc-end();
  probe mem-pool-gc-begin(
      char* mgr_name, uintptr_t mgr_name_len, char* pool_name, uintptr_t pool_name_len,
      uintptr_t initial_size, uintptr_t used, uintptr_t committed, uintptr_t max_size);
  probe mem-pool-gc-end(
      char* mgr_name, uintptr_t mgr_name_len, char* pool_name, uintptr_t pool_name_len,
      uintptr_t initial_size, uintptr_t used, uintptr_t committed, uintptr_t max_size);
  probe thread-start(
      char* thread_name, uintptr_t thread_name_length,
      uintptr_t java_thread_id, uintptr_t native_thread_id, bool is_daemon);
  probe thread-stop(
      char* thread_name, uintptr_t thread_name_length,
      uintptr_t java_thread_id, uintptr_t native_thread_id, bool is_daemon);
  probe method-compile-begin(
      char* class_name, uintptr_t class_name_len,
      char* method_name, uintptr_t method_name_len,
      char* signature, uintptr_t signature_len);
  probe method-compile-end(
      char* class_name, uintptr_t class_name_len,
      char* method_name, uintptr_t method_name_len,
      char* signature, uintptr_t signature_len,
      bool is_success);
  probe compiled-method-load(
      char* class_name, uintptr_t class_name_len,
      char* method_name, uintptr_t method_name_len,
      char* signature, uintptr_t signature_len,
      void* code, uintptr_t code_size);
  probe compiled-method-unload(
      char* class_name, uintptr_t class_name_len,
      char* method_name, uintptr_t method_name_len,
      char* signature, uintptr_t signature_len);
  probe monitor-contended-enter(
      uintptr_t java_thread_id, uintptr_t monitor_id,
      char* class_name, uintptr_t class_name_len);
  probe monitor-contended-entered(
      uintptr_t java_thread_id, uintptr_t monitor_id,
      char* class_name, uintptr_t class_name_len);
  probe monitor-contended-exit(
      uintptr_t java_thread_id, uintptr_t monitor_id,
      char* class_name, uintptr_t class_name_len);
  probe monitor-wait(
      uintptr_t java_thread_id, uintptr_t monitor_id,
      char* class_name, uintptr_t class_name_len,
      uintptr_t timeout);
  probe monitor-waited(
      uintptr_t java_thread_id, uintptr_t monitor_id,
      char* class_name, uintptr_t class_name_len);
  probe monitor-notify(
      uintptr_t java_thread_id, uintptr_t monitor_id,
      char* class_name, uintptr_t class_name_len);
  probe monitor-notifyAll(
      uintptr_t java_thread_id, uintptr_t monitor_id,
      char* class_name, uintptr_t class_name_len);
  probe method-entry(
      uintptr_t java_thread_id, char* class_name, uintptr_t class_name_len,
      char* method_name, uintptr_t method_name_len,
      char* signature, uintptr_t signature_len);
  probe method-return(
      uintptr_t java_thread_id, char* class_name, uintptr_t class_name_len,
      char* method_name, uintptr_t method_name_len,
      char* signature, uintptr_t signature_len);
  probe object-alloc(
      uintptr_t java_thread_id, char* class_name, uintptr_t class_name_len,
      uintptr_t size);
};

provider hotspot_jni {
  probe AllocObject-entry(void*, void*);
  probe AllocObject-return(void*);
  probe AttachCurrentThreadAsDaemon-entry(void*, void**, void*);
  probe AttachCurrentThreadAsDaemon-return(uint32_t);
  probe AttachCurrentThread-entry(void*, void**, void*);
  probe AttachCurrentThread-return(uint32_t);
  probe CallBooleanMethodA-entry(void*, void*, uintptr_t);
  probe CallBooleanMethodA-return(uintptr_t);
  probe CallBooleanMethod-entry(void*, void*, uintptr_t);
  probe CallBooleanMethod-return(uintptr_t);
  probe CallBooleanMethodV-entry(void*, void*, uintptr_t);
  probe CallBooleanMethodV-return(uintptr_t);
  probe CallByteMethodA-entry(void*, void*, uintptr_t);
  probe CallByteMethodA-return(char);
  probe CallByteMethod-entry(void*, void*, uintptr_t);
  probe CallByteMethod-return(char);
  probe CallByteMethodV-entry(void*, void*, uintptr_t);

  probe CallByteMethodV-return(char);
  probe CallCharMethodA-entry(void*, void*, uintptr_t);
  probe CallCharMethodA-return(uint16_t);
  probe CallCharMethod-entry(void*, void*, uintptr_t);
  probe CallCharMethod-return(uint16_t);
  probe CallCharMethodV-entry(void*, void*, uintptr_t);
  probe CallCharMethodV-return(uint16_t);
  probe CallDoubleMethodA-entry(void*, void*, uintptr_t);
  probe CallDoubleMethodA-return(double);
  probe CallDoubleMethod-entry(void*, void*, uintptr_t);
  probe CallDoubleMethod-return(double);
  probe CallDoubleMethodV-entry(void*, void*, uintptr_t);
  probe CallDoubleMethodV-return(double);
  probe CallFloatMethodA-entry(void*, void*, uintptr_t);
  probe CallFloatMethodA-return(float);
  probe CallFloatMethod-entry(void*, void*, uintptr_t);
  probe CallFloatMethod-return(float);
  probe CallFloatMethodV-entry(void*, void*, uintptr_t);
  probe CallFloatMethodV-return(float);
  probe CallIntMethodA-entry(void*, void*, uintptr_t);
  probe CallIntMethodA-return(uint32_t);
  probe CallIntMethod-entry(void*, void*, uintptr_t);
  probe CallIntMethod-return(uint32_t);
  probe CallIntMethodV-entry(void*, void*, uintptr_t);
  probe CallIntMethodV-return(uint32_t);
  probe CallLongMethodA-entry(void*, void*, uintptr_t);
  probe CallLongMethodA-return(uintptr_t);
  probe CallLongMethod-entry(void*, void*, uintptr_t);
  probe CallLongMethod-return(uintptr_t);
  probe CallLongMethodV-entry(void*, void*, uintptr_t);
  probe CallLongMethodV-return(uintptr_t);
  probe CallNonvirtualBooleanMethodA-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualBooleanMethodA-return(uintptr_t);
  probe CallNonvirtualBooleanMethod-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualBooleanMethod-return(uintptr_t);
  probe CallNonvirtualBooleanMethodV-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualBooleanMethodV-return(uintptr_t);
  probe CallNonvirtualByteMethodA-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualByteMethodA-return(char);
  probe CallNonvirtualByteMethod-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualByteMethod-return(char);
  probe CallNonvirtualByteMethodV-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualByteMethodV-return(char);
  probe CallNonvirtualCharMethodA-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualCharMethodA-return(uint16_t);
  probe CallNonvirtualCharMethod-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualCharMethod-return(uint16_t);
  probe CallNonvirtualCharMethodV-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualCharMethodV-return(uint16_t);
  probe CallNonvirtualDoubleMethodA-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualDoubleMethodA-return(double);
  probe CallNonvirtualDoubleMethod-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualDoubleMethod-return(double);
  probe CallNonvirtualDoubleMethodV-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualDoubleMethodV-return(double);
  probe CallNonvirtualFloatMethodA-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualFloatMethodA-return(float);
  probe CallNonvirtualFloatMethod-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualFloatMethod-return(float);
  probe CallNonvirtualFloatMethodV-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualFloatMethodV-return(float);
  probe CallNonvirtualIntMethodA-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualIntMethodA-return(uint32_t);
  probe CallNonvirtualIntMethod-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualIntMethod-return(uint3t);
  probe CallNonvirtualIntMethodV-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualIntMethodV-return(uint32_t);
  probe CallNonvirtualLongMethodA-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualLongMethodA-return(uintptr_t);
  probe CallNonvirtualLongMethod-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualLongMethod-return(uintptr_t);
  probe CallNonvirtualLongMethodV-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualLongMethodV-return(uintptr_t);
  probe CallNonvirtualObjectMethodA-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualObjectMethodA-return(void*);
  probe CallNonvirtualObjectMethod-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualObjectMethod-return(void*);
  probe CallNonvirtualObjectMethodV-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualObjectMethodV-return(void*);
  probe CallNonvirtualShortMethodA-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualShortMethodA-return(uint16_t);
  probe CallNonvirtualShortMethod-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualShortMethod-return(uint16_t);
  probe CallNonvirtualShortMethodV-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualShortMethodV-return(uint16_t);
  probe CallNonvirtualVoidMethodA-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualVoidMethodA-return();
  probe CallNonvirtualVoidMethod-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualVoidMethod-return();
  probe CallNonvirtualVoidMethodV-entry(void*, void*, void*, uintptr_t);
  probe CallNonvirtualVoidMethodV-return();
  probe CallObjectMethodA-entry(void*, void*, uintptr_t);
  probe CallObjectMethodA-return(void*);
  probe CallObjectMethod-entry(void*, void*, uintptr_t);
  probe CallObjectMethod-return(void*);
  probe CallObjectMethodV-entry(void*, void*, uintptr_t);
  probe CallObjectMethodV-return(void*);
  probe CallShortMethodA-entry(void*, void*, uintptr_t);
  probe CallShortMethodA-return(uint16_t);
  probe CallShortMethod-entry(void*, void*, uintptr_t);
  probe CallShortMethod-return(uint16_t);
  probe CallShortMethodV-entry(void*, void*, uintptr_t);
  probe CallShortMethodV-return(uint16_t);
  probe CallStaticBooleanMethodA-entry(void*, void*, uintptr_t);
  probe CallStaticBooleanMethodA-return(uintptr_t);
  probe CallStaticBooleanMethod-entry(void*, void*, uintptr_t);
  probe CallStaticBooleanMethod-return(uintptr_t);
  probe CallStaticBooleanMethodV-entry(void*, void*, uintptr_t);
  probe CallStaticBooleanMethodV-return(uintptr_t);
  probe CallStaticByteMethodA-entry(void*, void*, uintptr_t);
  probe CallStaticByteMethodA-return(char);
  probe CallStaticByteMethod-entry(void*, void*, uintptr_t);
  probe CallStaticByteMethod-return(char);
  probe CallStaticByteMethodV-entry(void*, void*, uintptr_t);
  probe CallStaticByteMethodV-return(char);
  probe CallStaticCharMethodA-entry(void*, void*, uintptr_t);
  probe CallStaticCharMethodA-return(uint16_t);
  probe CallStaticCharMethod-entry(void*, void*, uintptr_t);
  probe CallStaticCharMethod-return(uint16_t);
  probe CallStaticCharMethodV-entry(void*, void*, uintptr_t);
  probe CallStaticCharMethodV-return(uint16_t);
  probe CallStaticDoubleMethodA-entry(void*, void*, uintptr_t);
  probe CallStaticDoubleMethodA-return(double);
  probe CallStaticDoubleMethod-entry(void*, void*, uintptr_t);
  probe CallStaticDoubleMethod-return(double);
  probe CallStaticDoubleMethodV-entry(void*, void*, uintptr_t);
  probe CallStaticDoubleMethodV-return(double);
  probe CallStaticFloatMethodA-entry(void*, void*, uintptr_t);
  probe CallStaticFloatMethodA-return(float);
  probe CallStaticFloatMethod-entry(void*, void*, uintptr_t);
  probe CallStaticFloatMethod-return(float);
  probe CallStaticFloatMethodV-entry(void*, void*, uintptr_t);
  probe CallStaticFloatMethodV-return(float);
  probe CallStaticIntMethodA-entry(void*, void*, uintptr_t);
  probe CallStaticIntMethodA-return(uint32_t);
  probe CallStaticIntMethod-entry(void*, void*, uintptr_t);
  probe CallStaticIntMethod-return(uint32_t);
  probe CallStaticIntMethodentry(void*, void*, uintptr_t);
  probe CallStaticIntMethodV-return(uint32_t);
  probe CallStaticLongMethodA-entry(void*, void*, uintptr_t);
  probe CallStaticLongMethodA-return(uintptr_t);
  probe CallStaticLongMethod-entry(void*, void*, uintptr_t);
  probe CallStaticLongMethod-return(uintptr_t);
  probe CallStaticLongMethodV-entry(void*, void*, uintptr_t);
  probe CallStaticLongMethodV-return(uintptr_t);
  probe CallStaticObjectMethodA-entry(void*, void*, uintptr_t);
  probe CallStaticObjectMethodA-return(void*);
  probe CallStaticObjectMethod-entry(void*, void*, uintptr_t);
  probe CallStaticObjectMethod-return(void*);
  probe CallStaticObjectMethodV-entry(void*, void*, uintptr_t);
  probe CallStaticObjectMethodV-return(void*);
  probe CallStaticShortMethodA-entry(void*, void*, uintptr_t);
  probe CallStaticShortMethodA-return(uint16_t);
  probe CallStaticShortMethod-entry(void*, void*, uintptr_t);
  probe CallStaticShortMethod-return(uint16_t);
  probe CallStaticShortMethodV-entry(void*, void*, uintptr_t);
  probe CallStaticShortMethodV-return(uint16_t);
  probe CallStaticVoidMethodA-entry(void*, void*, uintptr_t);
  probe CallStaticVoidMethodA-return();
  probe CallStaticVoidMethod-entry(void*, void*, uintptr_t);
  probe CallStaticVoidMethod-return();
  probe CallStaticVoidMethodV-entry(void*, void*, uintptr_t);
  probe CallStaticVoidMethodV-return();
  probe CallVoidMethodA-entry(void*, void*, uintptr_t);
  probe CallVoidMethodA-return();
  probe CallVoidMethod-entry(void*, void*, uintptr_t);
  probe CallVoidMethod-return();
  probe CallVoidMethodV-entry(void*, void*, uintptr_t);
  probe CallVoidMethodV-return();
  probe CreateJavaVM-entry(void**, void**, void*);
  probe CreateJavaVM-return(uint32_t);
  probe DefineClass-entry(void*, const char*, void*, char, uintptr_t);
  probe DefineClass-return(void*);
  probe DeleteGlobalRef-entry(void*, void*);
  probe DeleteGlobalRef-return();
  probe DeleteLocalRef-entry(void*, void*);
  probe DeleteLocalRef-return();
  probe DeleteWeakGlobalRef-entry(void*, void*);
  probe DeleteWeakGlobalRef-return();
  probe DestroyJavaVM-entry(void*);
  probe DestroyJavaVM-return(uint32_t);
  probe DetachCurrentThread-entry(void*);
  probe DetachCurrentThread-return(uint32_t);
  probe EnsureLocalCapacity-entry(void*, uint32_t);
  probe EnsureLocalCapacity-return(uint32_t);
  probe ExceptionCheck-entry(void*);
  probe ExceptionCheck-return(uintptr_t);
  probe ExceptionClear-entry(void*);
  probe ExceptionClear-return();
  probe ExceptionDescribe-entry(void*);
  probe ExceptionDescribe-return();
  probe ExceptionOccurred-entry(void*);
  probe ExceptionOccurred-return(void*);
  probe FatalError-entry(void* env, const char*);
  probe FatalError-return();
  probe FindClass-entry(void*, const char*);
  probe FindClass-return(void*);
  probe FromReflectedField-entry(void*, void*);
  probe FromReflectedField-return(uintptr_t);
  probe FromReflectedMethod-entry(void*, void*);
  probe FromReflectedMethod-return(uintptr_t);
  probe GetArrayLength-entry(void*, void*);
  probe GetArrayLength-return(uintptr_t);
  probe GetBooleanArrayElements-entry(void*, void*, uintptr_t*);
  probe GetBooleanArrayElements-return(uintptr_t*);
  probe GetBooleanArrayRegion-entry(void*, void*, uintptr_t, uintptr_t, uintptr_t*);
  probe GetBooleanArrayRegion-return();
  probe GetBooleanField-entry(void*, void*, uintptr_t);
  probe GetBooleanField-return(uintptr_t);
  probe GetByteArrayElements-entry(void*, void*, uintptr_t*);
  probe GetByteArrayElements-return(char*);
  probe GetByteArrayRegion-entry(void*, void*, uintptr_t, uintptr_t, char*);
  probe GetByteArrayRegion-return();
  probe GetByteField-entry(void*, void*, uintptr_t);
  probe GetByteField-return(char);
  probe GetCharArrayElements-entry(void*, void*, uintptr_t*);
  probe GetCharArrayElements-return(uint16_t*);
  probe GetCharArrayRegion-entry(void*, void*, uintptr_t, uintptr_t, uint16_t*);
  probe GetCharArrayRegion-return();
  probe GetCharField-entry(void*, void*, uintptr_t);
  probe GetCharField-return(uint16_t);
  probe GetCreatedJavaVMs-eintptr_t*);
  probe GetCreatedJavaVMs-return(uintptr_t);
  probe GetCreateJavaVMs-entry(void*, uintptr_t, uintptr_t*);
  probe GetCreateJavaVMs-return(uint32_t);
  probe GetDefaultJavaVMInitArgs-entry(void*);
  probe GetDefaultJavaVMInitArgs-return(uint32_t);
  probe GetDirectBufferAddress-entry(void*, void*);
  probe GetDirectBufferAddress-return(void*);
  probe GetDirectBufferCapacity-entry(void*, void*);
  probe GetDirectBufferCapacity-return(uintptr_t);
  probe GetDoubleArrayElements-entry(void*, void*, uintptr_t*);
  probe GetDoubleArrayElements-return(double*);
  probe GetDoubleArrayRegion-entry(void*, void*, uintptr_t, uintptr_t, double*);
  probe GetDoubleArrayRegion-return();
  probe GetDoubleField-entry(void*, void*, uintptr_t);
  probe GetDoubleField-return(double);
  probe GetEnv-entry(void*, void*, void*);
  probe GetEnv-return(uint32_t);
  probe GetFieldID-entry(void*, void*, const char*, const char*);
  probe GetFieldID-return(uintptr_t);
  probe GetFloatArrayElements-entry(void*, void*, uintptr_t*);
  probe GetFloatArrayElements-return(float*);
  probe GetFloatArrayRegion-entry(void*, void*, uintptr_t, uintptr_t, float*);
  probe GetFloatArrayRegion-return();
  probe GetFloatField-entry(void*, void*, uintptr_t);
  probe GetFloatField-return(float);
  probe GetIntArrayElements-entry(void*, void*, uintptr_t*);
  probe GetIntArrayElements-return(uint32_t*);
  probe GetIntArrayRegion-entry(void*, void*, uintptr_t, uintptr_t, uint32_t*);
  probe GetIntArrayRegion-return();
  probe GetIntField-entry(void*, void*, uintptr_t);
  probe GetIntField-return(uint32_t);
  probe GetJavaVM-entry(void*, void**);
  probe GetJavaVM-return(uint32_t);
  probe GetLongArrayElements-entry(void*, void*, uintptr_t*);
  probe GetLongArrayElements-return(uintptr_t*);
  probe GetLongArrayRegion-entry(void*, void*, uintptr_t, uintptr_t, uintptr_t*);
  probe GetLongArrayRegion-return();
  probe GetLongField-entry(void*, void*, uintptr_t);
  probe GetLongField-return(uintptr_t);
  probe GetMethodID-entry(void*, void*, const char*, const char*);
  probe GetMethodID-return(uintptr_t);
  probe GetObjectArrayElement-entry(void*, void*, uintptr_t);
  probe GetObjectArrayElement-return(void*);
  probe GetObjectClass-entry(void*, void*);
  probe GetObjectClass-return(void*);
  probe GetObjectField-entry(void*, void*, uintptr_t);
  probe GetObjectField-return(void*);
  probe GetObjectRefType-entry(void*, void*);
  probe GetObjectRefType-return(void*);
  probe GetPrimitiveArrayCritical-entry(void*, void*, uintptr_t*);
  probe GetPrimitiveArrayCritical-return(void*);
  probe GetShortArrayElements-entry(void*, void*, uintptr_t*);
  probe GetShortArrayElements-return(uint16_t*);
  probe GetShortArrayRegion-entry(void*, void*, uintptr_t, uintptr_t, uint16_t*);
  probe GetShortArrayRegion-return();
  probe GetShortField-entry(void*, void*, uintptr_t);
  probe GetShortField-return(uint16_t);
  probe GetStaticBooleanField-entry(void*, void*, uintptr_t);
  probe GetStaticBooleanField-return(uintptr_t);
  probe GetStaticByteField-entry(void*, void*, uintptr_t);
  probe GetStaticByteField-return(char);
  probe GetStaticCharField-entry(void*, void*, uintptr_t);
  probe GetStaticCharField-return(uint16_t);
  probe GetStaticDoubleField-entry(void*, void*, uintptr_t);
  probe GetStaticDoubleField-return(double);
  probe GetStaticFieldID-entry(void*, void*, const char*, const char*);
  probe GetStaticFieldID-return(uintptr_t);
  probe GetStaticFloatField-entry(void*, void*, uintptr_t);
  probe GetStaticFloatField-return(float);
  probe GetStaticIntField-entry(void*, void*, uintptr_t);
  probe GetStaticIntField-return(uint32_t);
  probe GetStaticLongField-entry(void*, void*, uintptr_t);
  probe GetStaticLongField-return(uintptr_t);
  probe GetStaticMethodID-entry(void*, void*, const char*, const char*);
  probe GetStaticMethodID-return(uintptr_t);
  probe GetStaticObjectField-entry(void*, void*, uintptr_t);
  probe GetStaticObjectField-return(void*);
  probe GetStaticShortField-entry(void*, void*, uintptr_t);
  probe GetStaticShortField-return(uint16_t);
  pro GetStringChars-entry(void*, void*, uintptr_t*);
  probe GetStringChars-return(const uint16_t*);
  probe GetStringCritical-entry(void*, void*, uintptr_t*);
  probe GetStringCritical-return(const uint16_t*);
  probe GetStringLength-entry(void*, void*);
  probe GetStringLength-return(uintptr_t);
  probe GetStringRegion-entry(void*, void*, uintptr_t, uintptr_t, uint16_t*);
  probe GetStringRegion-return();
  probe GetStringUTFChars-entry(void*, void*, uintptr_t*);
  probe GetStringUTFChars-return(const char*);
  probe GetStringUTFLength-entry(void*, void*);
  probe GetStringUTFLength-return(uintptr_t);
  probe GetStringUTFRegion-entry(void*, void*, uintptr_t, uintptr_t, char*);
  probe GetStringUTFRegion-return();
  probe GetSuperclass-entry(void*, void*);
  probe GetSuperclass-return(void*);
  probe GetVersion-entry(void*);
  probe GetVersion-return(uint32_t);
  probe IsAssignableFrom-entry(void*, void*, void*);
  probe IsAssignableFrom-return(uintptr_t);
  probe IsInstanceOf-entry(void*, void*, void*);
  probe IsInstanceOf-return(uintptr_t);
  probe IsSameObject-entry(void*, void*, void*);
  probe IsSameObject-return(uintptr_t);
  probe MonitorEnter-entry(void*, void*);
  probe MonitorEnter-return(uint32_t);
  probe MonitorExit-entry(void*, void*);
  probe MonitorExit-return(uint32_t);
  probe NewBooleanArray-entry(void*, uintptr_t);
  probe NewBooleanArray-return(void*);
  probe NewByteArray-entry(void*, uintptr_t);
  probe NewByteArray-return(void*);
  probe NewCharArray-entry(void*, uintptr_t);
  probe NewCharArray-return(void*);
  probe NewDirectByteBuffer-entry(void*, void*, uintptr_t);
  probe NewDirectByteBuffer-return(void*);
  probe NewDoubleArray-entry(void*, uintptr_t);
  probe NewDoubleArray-return(void*);
  probe NewFloatArray-entry(void*, uintptr_t);
  probe NewFloatArray-return(void*);
  probe NewGlobalRef-entry(void*, void*);
  probe NewGlobalRef-return(void*);
  probe NewIntArray-entry(void*, uintptr_t);
  probe NewIntArray-return(void*);
  probe NewLocalRef-entry(void*, void*);
  probe NewLocalRef-return(void*);
  probe NewLongArray-entry(void*, uintptr_t);
  probe NewLongArray-return(void*);
  probe NewObjectA-entry(void*, void*, uintptr_t);
  probe NewObjectA-return(void*);
  probe NewObjectArray-entry(void*, uintptr_t, void*, void*);
  probe NewObjectArray-return(void*);
  probe NewObject-entry(void*, void*, uintptr_t);
  probe NewObject-return(void*);
  probe NewObjectV-entry(void*, void*, uintptr_t);
  probe NewObjectV-return(void*);
  probe NewShortArray-entry(void*, uintptr_t);
  probe NewShortArray-return(void*);
  probe NewString-entry(void*, const uint16_t*, uintptr_t);
  probe NewString-return(void*);
  probe NewStringUTF-entry(void*, const char*);
  probe NewStringUTF-return(void*);
  probe NewWeakGlobalRef-entry(void*, void*);
  probe NewWeakGlobalRef-return(void*);
  probe PopLocalFrame-entry(void*, void*);
  probe PopLocalFrame-return(void*);
  probe PushLocalFrame-entry(void*, uint32_t);
  probe PushLocalFrame-return(uint32_t);
  probe RegisterNatives-entry(void*, void*, const void*, uint32_t);
  probe RegisterNatives-return(uint32_t);
  probe ReleaseBooleanArrayElements-entry(void*, void*, uintptr_t*, uint32_t);
  probe ReleaseBooleanArrayElements-return();
  probe ReleaseByteArrayElements-entry(void*, void*, char*, uint32_t);
  probe ReleaseByteArrayElements-return();
  probe ReleaseCharArrayElements-entry(void*, void*, uint16_t*, uint32_t);
  probe ReleaseCharArrayElements-return();
  probe ReleaseDoubleArrayElements-entry(void*, void*, double*, uint32_t);
  probe ReleaseDoubleArrayElements-return();
  probe ReleaseFloatArrayElements-entry(void*, void*, float*, uint32_t);
  probe ReleaseFloatArrayElements-return();
  probe ReleaseIntArrayElements-entry(void*, void*, uint32_t*, uint32_t);
  probe ReleaseIntArrayElements-return();
  probe ReleaseLongArrayElements-entry(void*, void*, uintptr_t*, uint32_t);
  probe ReleaseLongArrayElements-return();
  probe ReleaseObjectArrayElements-entry(void*, void*, void**, uint32_t);
  probe ReleaseObjectArrayElements-return();
  probe Releasey(void*, void*, void*, uint32_t);
  probe ReleasePrimitiveArrayCritical-return();
  probe ReleaseShortArrayElements-entry(void*, void*, uint16_t*, uint32_t);
  probe ReleaseShortArrayElements-return();
  probe ReleaseStringChars-entry(void*, void*, const uint16_t*);
  probe ReleaseStringChars-return();
  probe ReleaseStringCritical-entry(void*, void*, const uint16_t*);
  probe ReleaseStringCritical-return();
  probe ReleaseStringUTFChars-entry(void*, void*, const char*);
  probe ReleaseStringUTFChars-return();
  probe SetBooleanArrayRegion-entry(void*, void*, uintptr_t, uintptr_t, const uintptr_t*);
  probe SetBooleanArrayRegion-return();
  probe SetBooleanField-entry(void*, void*, uintptr_t, uintptr_t);
  probe SetBooleanField-return();
  probe SetByteArrayRegion-entry(void*, void*, uintptr_t, uintptr_t, const char*);
  probe SetByteArrayRegion-return();
  probe SetByteField-entry(void*, void*, uintptr_t, char);
  probe SetByteField-return();
  probe SetCharArrayRegion-entry(void*, void*, uintptr_t, uintptr_t, const uint16_t*);
  probe SetCharArrayRegion-return();
  probe SetCharField-entry(void*, void*, uintptr_t, uint16_t);
  probe SetCharField-return();
  probe SetDoubleArrayRegion-entry(void*, void*, uintptr_t, uintptr_t, const double*);
  probe SetDoubleArrayRegion-return();
  probe SetDoubleField-entry(void*, void*, uintptr_t, double);
  probe SetDoubleField-return();
  probe SetFloatArrayRegion-entry(void*, void*, uintptr_t, uintptr_t, const float*);
  probe SetFloatArrayRegion-return();
  probe SetFloatField-entry(void*, void*, uintptr_t, float);
  probe SetFloatField-return();
  probe SetIntArrayRegion-entry(void*, void*, uintptr_t, uintptr_t, const uint32_t*);
  probe SetIntArrayRegion-return();
  probe SetIntField-entry(void*, void*, uintptr_t, uint32_t);
  probe SetIntField-return();
  probe SetLongArrayRegion-entry(void*, void*, uintptr_t, uintptr_t, const uintptr_t*);
  probe SetLongArrayRegion-return();
  probe SetLongField-entry(void*, void*, uintptr_t, uintptr_t);
  probe SetLongField-return();
  probe SetObjectArrayElement-entry(void*, void*, uintptr_t, void*);
  probe SetObjectArrayElement-return();
  probe SetObjectField-entry(void*, void*, uintptr_t, void*);
  probe SetObjectField-return();
  probe SetShortArrayRegion-entry(void*, void*, uintptr_t, uintptr_t, const uint16_t*);
  probe SetShortArrayRegion-return();
  probe SetShortField-entry(void*, void*, uintptr_t, uint16_t);
  probe SetShortField-return();
  probe SetStaticBooleanField-entry(void*, void*, uintptr_t, uintptr_t);
  probe SetStaticBooleanField-return();
  probe SetStaticByteField-entry(void*, void*, uintptr_t, char);
  probe SetStaticByteField-return();
  probe SetStaticCharField-entry(void*, void*, uintptr_t, uint16_t);
  probe SetStaticCharField-return();
  probe SetStaticDoubleField-entry(void*, void*, uintptr_t, double);
  probe SetStaticDoubleField-return();
  probe SetStaticFloatField-entry(void*, void*, uintptr_t, float);
  probe SetStaticFloatField-return();
  probe SetStaticIntField-entry(void*, void*, uintptr_t, uint32_t);
  probe SetStaticIntField-return();
  probe SetStaticLongField-entry(void*, void*, uintptr_t, uintptr_t);
  probe SetStaticLongField-return();
  probe SetStaticObjectField-entry(void*, void*, uintptr_t, void*);
  probe SetStaticObjectField-return();
  probe SetStaticShortField-entry(void*, void*, uintptr_t, uint16_t);
  probe SetStaticShortField-return();
  probe Throw-entry(void*, void*);
  probe ThrowNew-entry(void*, void*, const char*);
  probe ThrowNew-return(uint32_t);
  probe Throw-return(uint32_t);
  probe ToReflectedField-entry(void*, void*, uintptr_t, uintptr_t);
  probe ToReflectedField-return(void*);
  probe ToReflectedMethod-entry(void*, void*, uintptr_t, uintptr_t);
  probe ToReflectedMethod-return(void*);
  probe UnregisterNatives-entry(void*, void*);
  probe UnregisterNatives-return(uint32_t);
};
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.jdi.request.DuplicateRequestException (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.request.DuplicateRequestException

No usage of com.sun.jdi.request.DuplicateRequestException
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.Element (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.Element

  • Packages that use Element
    Package Description
    org.w3c.dom
    Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.
    org.w3c.dom.css
    org.w3c.dom.html
    org.w3c.dom.ls

    • Uses of Element in org.w3c.dom

      Methods in org.w3c.dom that return Element
      Modifier and Type Method and Description
      Element Document.createElement(String tagName)
      Creates an element of the type specified.
      Element Document.createElementNS(String namespaceURI, String qualifiedName)
      Creates an element of the given qualified name and namespace URI.
      Element Document.getDocumentElement()
      This is a convenience attribute that allows direct access to the child node that is the document element of the document.
      Element Document.getElementById(String elementId)
      Returns the Element that has an ID attribute with the given value.
      Element Attr.getOwnerElement()
      The Element node this attribute is attached to or null if this attribute is not in use.

    • Uses of Element in org.w3c.dom.css

      Methods in org.w3c.dom.css with parameters of type Element
      Modifier and Type Method and Description
      CSSStyleDeclaration ViewCSS.getComputedStyle(Element elt, String pseudoElt)
      This method is used to get the computed style as it is defined in [CSS2].
      CSSStyleDeclaration DocumentCSS.getOverrideStyle(Element elt, String pseudoElt)
      This method is used to retrieve the override style declaration for a specified element and a specified pseudo-element.

    • Uses of Element in org.w3c.dom.html

      Subinterfaces of Element in org.w3c.dom.html
      Modifier and Type Interface and Description
      interface  HTMLAnchorElement
      The anchor element.
      interface  HTMLAppletElement
      An embedded Java applet.
      interface  HTMLAreaElement
      Client-side image map area definition.
      interface  HTMLBaseElement
      Document base URI.
      interface  HTMLBaseFontElement
      Base font.
      interface  HTMLBodyElement
      The HTML document body.
      interface  HTMLBRElement
      Force a line break.
      interface  HTMLButtonElement
      Push button.
      interface  HTMLDirectoryElement
      Directory list.
      interface  HTMLDivElement
      Generic block container.
      interface  HTMLDListElement
      Definition list.
      interface  HTMLElement
      All HTML element interfaces derive from this class.
      interface  HTMLFieldSetElement
      Organizes form controls into logical groups.
      interface  HTMLFontElement
      Local change to font.
      interface  HTMLFormElement
      The FORM element encompasses behavior similar to a collection and an element.
      interface  HTMLFrameElement
      Create a frame.
      interface  HTMLFrameSetElement
      Create a grid of frames.
      interface  HTMLHeadElement
      Document head information.
      interface  HTMLHeadingElement
      For the H1 to H6 elements.
      interface  HTMLHRElement
      Create a horizontal rule.
      interface  HTMLHtmlElement
      Root of an HTML document.
      interface  HTMLIFrameElement
      Inline subwindows.
      interface  HTMLImageElement
      Embedded image.
      interface  HTMLInputElement
      Form control.
      interface  HTMLIsIndexElement
      This element is used for single-line text input.
      interface  HTMLLabelElement
      Form field label text.
      interface  HTMLLegendElement
      Provides a caption for a FIELDSET grouping.
      interface  HTMLLIElement
      List item.
      interface  HTMLLinkElement
      The LINK element specifies a link to an external resource, and defines this document's relationship to that resource (or vice versa).
      interface  HTMLMapElement
      Client-side image map.
      interface  HTMLMenuElement
      Menu list.
      interface  HTMLMetaElement
      This contains generic meta-information about the document.
      interface  HTMLModElement
      Notice of modification to part of a document.
      interface  HTMLObjectElement
      Generic embedded object.
      interface  HTMLOListElement
      Ordered list.
      interface  HTMLOptGroupElement
      Group options together in logical subdivisions.
      interface  HTMLOptionElement
      A selectable choice.
      interface  HTMLParagraphElement
      Paragraphs.
      interface  HTMLParamElement
      Parameters fed to the OBJECT element.
      interface  HTMLPreElement
      Preformatted text.
      interface  HTMLQuoteElement
      For the Q and BLOCKQUOTE elements.
      interface  HTMLScriptElement
      Script statements.
      interface  HTMLSelectElement
      The select element allows the selection of an option.
      interface  HTMLStyleElement
      Style information.
      interface  HTMLTableCaptionElement
      Table caption See the CAPTION element definition in HTML 4.0.
      interface  HTMLTableCellElement
      The object used to represent the TH and TD elements.
      interface  HTMLTableColElement
      Regroups the COL and COLGROUP elements.
      interface  HTMLTableElement
      The create* and delete* methods on the table allow authors to construct and modify tables.
      interface  HTMLTableRowElement
      A row in a table.
      interface  HTMLTableSectionElement
      The THEAD , TFOOT , and TBODY elements.
      interface  HTMLTextAreaElement
      Multi-line text field.
      interface  HTMLTitleElement
      The document title.
      interface  HTMLUListElement
      Unordered list.

    • Uses of Element in org.w3c.dom.ls

      Methods in org.w3c.dom.ls with parameters of type Element
      Modifier and Type Method and Description
      short LSParserFilter.startElement(Element elementArg)
      The parser will call this method after each Element start tag has been scanned, but before the remainder of the Element is processed.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.css.ElementCSSInlineStyle (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.css.ElementCSSInlineStyle

No usage of org.w3c.dom.css.ElementCSSInlineStyle
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.EmptyStatementTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.EmptyStatementTree

  • Packages that use EmptyStatementTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of EmptyStatementTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type EmptyStatementTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitEmptyStatement(EmptyStatementTree node, P p)

    • Uses of EmptyStatementTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type EmptyStatementTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitEmptyStatement(EmptyStatementTree node, P p)
      R | SimpleTreeVisitor.visitEmptyStatement(EmptyStatementTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Supported Encodings

The java.io.InputStreamReader, java.io.OutputStreamWriter, java.lang.String classes, and classes in the java.nio.charset package can convert between Unicode and a number of other character encodings. The supported encodings vary between different implementations of the Java Platform, Standard Edition 7 (Java SE 7). The class description for java.nio.charset.Charset lists the encodings that any implementation of the Java Platform, Standard Edition 7 is required to support.

Oracle's Java SE Development Kit 7 (Java SE 7) for all platforms (Solaris, Linux, and Microsoft Windows) and the Java SE Runtime Environment 7 (JRE 7) for Solaris and Linux support all encodings shown on this page. Oracle's JRE 7 for Microsoft Windows may be installed as a complete international version or as a European languages version. By default, the JRE 7 installer installs a European languages version if it recognizes that the host operating system only supports European languages. If the installer recognizes that any other language is needed, or if the user requests support for non-European languages in a customized installation, a complete international version is installed. The European languages version only supports the encodings shown in the following Basic Encoding Set table. The international version (which includes the lib/charsets.jar file) supports all encodings shown on this page.

The following tables show the encoding sets supported by Java SE 7. The canonical names used by the new java.nio APIs are in many cases not the same as those used in the java.io and java.lang APIs.

Basic Encoding Set (contained in lib/rt.jar)

Canonical Name for java.nio API | Canonical Name for java.io API and java.lang API | Description
IBM00858 | Cp858 | Variant of Cp850 with Euro character
IBM437 | Cp437 | MS-DOS United States, Australia, New Zealand, South Africa
IBM775 | Cp775 | PC Baltic
IBM850 | Cp850 | MS-DOS Latin-1
IBM852 | Cp852 | MS-DOS Latin-2
IBM855 | Cp855 | IBM Cyrillic
IBM857 | Cp857 | IBM Turkish
IBM862 | Cp862 | PC Hebrew
IBM866 | Cp866 | MS-DOS Russian
ISO-8859-1 | ISO8859_1 | ISO-8859-1, Latin Alphabet No. 1
ISO-8859-2 | ISO8859_2 | Latin Alphabet No. 2
ISO-8859-4 | ISO8859_4 | Latin Alphabet No. 4
ISO-8859-5 | ISO8859_5 | Latin/Cyrillic Alphabet
ISO-8859-7 | ISO8859_7 | Latin/Greek Alphabet (ISO-8859-7:2003)
ISO-8859-9 | ISO8859_9 | Latin Alphabet No. 5
ISO-8859-13 | ISO8859_13 | Latin Alphabet No. 7
ISO-8859-15 | ISO8859_15 | Latin Alphabet No. 9
KOI8-R | KOI8_R | KOI8-R, Russian
KOI8-U | KOI8_U | KOI8-U, Ukrainian
US-ASCII | ASCII | American Standard Code for Information Interchange
UTF-8 | UTF8 | Eight-bit Unicode (or UCS) Transformation Format
UTF-16 | UTF-16 | Sixteen-bit Unicode (or UCS) Transformation Format, byte order identified by an optional byte-order mark
UTF-16BE | UnicodeBigUnmarked | Sixteen-bit Unicode (or UCS) Transformation Format, big-endian byte order
UTF-16LE | UnicodeLittleUnmarked | Sixteen-bit Unicode (or UCS) Transformation Format, little-endian byte order
UTF-32 | UTF_32 | 32-bit Unicode (or UCS) Transformation Format, byte order identified by an optional byte-order mark
UTF-32BE | UTF_32BE | 32-bit Unicode (or UCS) Transformation Format, big-endian byte order
UTF-32LE | UTF_32LE | 32-bit Unicode (or UCS) Transformation Format, little-endian byte order
x-UTF-32BE-BOM | UTF_32BE_BOM | 32-bit Unicode (or UCS) Transformation Format, big-endian byte order, with byte-order mark
x-UTF-32LE-BOM | UTF_32LE_BOM | 32-bit Unicode (or UCS) Transformation Format, little-endian byte order, with byte-order mark
windows-1250 | Cp1250 | Windows Eastern European
windows-1251 | Cp1251 | Windows Cyrillic
windows-1252 | Cp1252 | Windows Latin-1
windows-1253 | Cp1253 | Windows Greek
windows-1254 | Cp1254 | Windows Turkish
windows-1257 | Cp1257 | Windows Baltic
Not available | UnicodeBig | Sixteen-bit Unicode (or UCS) Transformation Format, big-endian byte order, with byte-order mark
x-IBM737 | Cp737 | PC Greek
x-IBM874 | Cp874 | IBM Thai
x-UTF-16LE-BOM | UnicodeLittle | Sixteen-bit Unicode (or UCS) Transformation Format, little-endian byte order, with byte-order mark

Extended Encoding Set (contained in lib/charsets.jar)

Canonical Name for java.nio API | Canonical Name for java.io API and java.lang API | Description
Big5 | Big5 | Big5, Traditional Chinese
Big5-HKSCS | Big5_HKSCS | Big5 with Hong Kong extensions, Traditional Chinese (incorporating 2001 revision)
EUC-JP | EUC_JP | JISX 0201, 0208 and 0212, EUC encoding Japanese
EUC-KR | EUC_KR | KS C 5601, EUC encoding, Korean
GB18030 | GB18030 | Simplified Chinese, PRC standard
GB2312 | EUC_CN | GB2312, EUC encoding, Simplified Chinese
GBK | GBK | GBK, Simplified Chinese
IBM-Thai | Cp838 | IBM Thailand extended SBCS
IBM01140 | Cp1140 | Variant of Cp037 with Euro character
IBM01141 | Cp1141 | Variant of Cp273 with Euro character
IBM01142 | Cp1142 | Variant of Cp277 with Euro character
IBM01143 | Cp1143 | Variant of Cp278 with Euro character
IBM01144 | Cp1144 | Variant of Cp280 with Euro character
IBM01145 | Cp1145 | Variant of Cp284 with Euro character
IBM01146 | Cp1146 | Variant of Cp285 with Euro character
IBM01147 | Cp1147 | Variant of Cp297 with Euro character
IBM01148 | Cp1148 | Variant of Cp500 with Euro character
IBM01149 | Cp1149 | Variant of Cp871 with Euro character
IBM037 | Cp037 | USA, Canada (Bilingual, French), Netherlands, Portugal, Brazil, Australia
IBM1026 | Cp1026 | IBM Latin-5, Turkey
IBM1047 | Cp1047 | Latin-1 character set for EBCDIC hosts
IBM273 | Cp273 | IBM Austria, Germany
IBM277 | Cp277 | IBM Denmark, Norway
IBM278 | Cp278 | IBM Finland, Sweden
IBM280 | Cp280 | IBM Italy
IBM284 | Cp284 | IBM Catalan/Spain, Spanish Latin America
IBM285 | Cp285 | IBM United Kingdom, Ireland
IBM297 | Cp297 | IBM France
IBM420 | Cp420 | IBM Arabic
IBM424 | Cp424 | IBM Hebrew
IBM500 | Cp500 | EBCDIC 500V1
IBM860 | Cp860 | MS-DOS Portuguese
IBM861 | Cp861 | MS-DOS Icelandic
IBM863 | Cp863 | MS-DOS Canadian French
IBM864 | Cp864 | PC Arabic
IBM865 | Cp865 | MS-DOS Nordic
IBM868 | Cp868 | MS-DOS Pakistan
IBM869 | Cp869 | IBM Modern Greek
IBM870 | Cp870 | IBM Multilingual Latin-2
IBM871 | Cp871 | IBM Iceland
IBM918 | Cp918 | IBM Pakistan (Urdu)
ISO-2022-CN | ISO2022CN | GB2312 and CNS11643 in ISO 2022 CN form, Simplified and Traditional Chinese (conversion to Unicode only)
ISO-2022-JP | ISO2022JP | JIS X 0201, 0208, in ISO 2022 form, Japanese
ISO-2022-KR | ISO2022KR | ISO 2022 KR, Korean
ISO-8859-3 | ISO8859_3 | Latin Alphabet No. 3
ISO-8859-6 | ISO8859_6 | Latin/Arabic Alphabet
ISO-8859-8 | ISO8859_8 | Latin/Hebrew Alphabet
JIS_X0201 | JIS_X0201 | JIS X 0201
JIS_X0212-1990 | JIS_X0212-1990 | JIS X 0212
Shift_JIS | SJIS | Shift-JIS, Japanese
TIS-620 | TIS620 | TIS620, Thai
windows-1255 | Cp1255 | Windows Hebrew
windows-1256 | Cp1256 | Windows Arabic
windows-1258 | Cp1258 | Windows Vietnamese
windows-31j | MS932 | Windows Japanese
x-Big5-Solaris | Big5_Solaris | Big5 with seven additional Hanzi ideograph character mappings for the Solaris zh_TW.BIG5 locale
x-euc-jp-linux | EUC_JP_LINUX | JISX 0201, 0208, EUC encoding Japanese
x-EUC-TW | EUC_TW | CNS11643 (Plane 1-7,15), EUC encoding, Traditional Chinese
x-eucJP-Open | EUC_JP_Solaris | JISX 0201, 0208, 0212, EUC encoding Japanese
x-IBM1006 | Cp1006 | IBM AIX Pakistan (Urdu)
x-IBM1025 | Cp1025 | IBM Multilingual Cyrillic: Bulgaria, Bosnia, Herzegovinia, Macedonia (FYR)
x-IBM1046 | Cp1046 | IBM Arabic - Windows
x-IBM1097 | Cp1097 | IBM Iran (Farsi)/Persian
x-IBM1098 | Cp1098 | IBM Iran (Farsi)/Persian (PC)
x-IBM1112 | Cp1112 | IBM Latvia, Lithuania
x-IBM1122 | Cp1122 | IBM Estonia
x-IBM1123 | Cp1123 | IBM Ukraine
x-IBM1124 | Cp1124 | IBM AIX Ukraine
x-IBM1381 | Cp1381 | IBM OS/2, DOS People's Republic of China (PRC)
x-IBM1383 | Cp1383 | IBM AIX People's Republic of China (PRC)
x-IBM33722 | Cp33722 | IBM-eucJP - Japanese (superset of 5050)
x-IBM834 | Cp834 | IBM EBCDIC DBCS-only Korean
x-IBM856 | Cp856 | IBM Hebrew
x-IBM875 | Cp875 | IBM Greek
x-IBM921 | Cp921 | IBM Latvia, Lithuania (AIX, DOS)
x-IBM922 | Cp922 | IBM Estonia (AIX, DOS)
x-IBM930 | Cp930 | Japanese Katakana-Kanji mixed with 4370 UDC, superset of 5026
x-IBM933 | Cp933 | Korean Mixed with 1880 UDC, superset of 5029
x-IBM935 | Cp935 | Simplified Chinese Host mixed with 1880 UDC, superset of 5031
x-IBM937 | Cp937 | Traditional Chinese Host miexed with 6204 UDC, superset of 5033
x-IBM939 | Cp939 | Japanese Latin Kanji mixed with 4370 UDC, superset of 5035
x-IBM942 | Cp942 | IBM OS/2 Japanese, superset of Cp932
x-IBM942C | Cp942C | Variant of Cp942
x-IBM943 | Cp943 | IBM OS/2 Japanese, superset of Cp932 and Shift-JIS
x-IBM943C | Cp943C | Variant of Cp943
x-IBM948 | Cp948 | OS/2 Chinese (Taiwan) superset of 938
x-IBM949 | Cp949 | PC Korean
x-IBM949C | Cp949C | Variant of Cp949
x-IBM950 | Cp950 | PC Chinese (Hong Kong, Taiwan)
x-IBM964 | Cp964 | AIX Chinese (Taiwan)
x-IBM970 | Cp970 | AIX Korean
x-ISCII91 | ISCII91 | ISCII91 encoding of Indic scripts
x-ISO2022-CN-CNS | ISO2022_CN_CNS | CNS11643 in ISO 2022 CN form, Traditional Chinese (conversion from Unicode only)
x-ISO2022-CN-GB | ISO2022_CN_GB | GB2312 in ISO 2022 CN form, Simplified Chinese (conversion from Unicode only)
x-iso-8859-11 | x-iso-8859-11 | Latin/Thai Alphabet
x-JIS0208 | x-JIS0208 | JIS X 0208
x-JISAutoDetect | JISAutoDetect | Detects and converts from Shift-JIS, EUC-JP, ISO 2022 JP (conversion to Unicode only)
x-Johab | x-Johab | Korean, Johab character set
x-MacArabic | MacArabic | Macintosh Arabic
x-MacCentralEurope | MacCentralEurope | Macintosh Latin-2
x-MacCroatian | MacCroatian | Macintosh Croatian
x-MacCyrillic | MacCyrillic | Macintosh Cyrillic
x-MacDingbat | MacDingbat | Macintosh Dingbat
x-MacGreek | MacGreek | Macintosh Greek
x-MacHebrew | MacHebrew | Macintosh Hebrew
x-MacIceland | MacIceland | Macintosh Iceland
x-MacRoman | MacRoman | Macintosh Roman
x-MacRomania | MacRomania | Macintosh Romania
x-MacSymbol | MacSymbol | Macintosh Symbol
x-MacThai | MacThai | Macintosh Thai
x-MacTurkish | MacTurkish | Macintosh Turkish
x-MacUkraine | MacUkraine | Macintosh Ukraine
x-MS950-HKSCS | MS950_HKSCS | Windows Traditional Chinese with Hong Kong extensions
x-mswin-936 | MS936 | Windows Simplified Chinese
x-PCK | PCK | Solaris version of Shift_JIS
x-SJIS_0213 | x-SJIS_0213 | Shift_JISX0213
x-windows-50220 | Cp50220 | Windows Codepage 50220 (7-bit implementation)
x-windows-50221 | Cp50221 | Windows Codepage 50221 (7-bit implementation)
x-windows-874 | MS874 | Windows Thai
x-windows-949 | MS949 | Windows Korean
x-windows-950 | MS950 | Windows Traditional Chinese
x-windows-iso2022jp | x-windows-iso2022jp | Variant ISO-2022-JP (MS932 based)
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.source.tree.EnhancedForLoopTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.EnhancedForLoopTree

  • Packages that use EnhancedForLoopTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of EnhancedForLoopTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type EnhancedForLoopTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitEnhancedForLoop(EnhancedForLoopTree node, P p)

    • Uses of EnhancedForLoopTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type EnhancedForLoopTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitEnhancedForLoop(EnhancedForLoopTree node, P p)
      R | SimpleTreeVisitor.visitEnhancedForLoop(EnhancedForLoopTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Java(TM) Attach API Enhancements

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink= "#000077" alink="#FF0000">
Java

Java™ Attach API Enhancements

JNI Contents
  • Enhancements in Java SE 6
  • Enhancements in J2SE 5.0
  • Enhancements in J2SDK 1.4
  • Previous Enhancements

Enhancements in Java SE 6

No changes to report.

Enhancements in J2SE 5.0

No changes to report.

Enhancements in Java 2 SDK v1.4

No changes to report.

Previous Enhancements

No changes to report.

Copyright © 2007 Sun Microsystems, Inc. All Rights Reserved.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


enhancements

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java Web Start enhancements in version 6

  • JNLP Specification addition of the <update> element with its "policy" and "check" attributes.

The new <update> element with its "policy" and "check" attributes is now supported. The update element describes the applications preferences on how Java Web Start should check for updates on the web, and what to do when it is known before launching that an update is available.
In the previous versions of Java Web Start, the <offline-allowed> element was overloaded to mean two things. First, it meant that the application was allowed to run in "offline" mode. (An application can be run in offline mode either from the command line by adding the "-offline" argument, or from the Cache Viewer.) Second, it meant that attempts to check for update before launching an application (when not run in offline mode) could time out. When a check for update times out, the application would be launched from the cache while the update check continued in the background.
With the advent of the <update> element and its check attribute in 6.0, the <offline-allowed> element no longer has this second meaning. The default values: <update check="timeout"/>. which is the same behavior as previous versions where <offline-allowed> was specified. For the behavior that previously used whenever <offline-allowed> was omitted, you need to specify <update check="always"/>. A third value <update check="background"/> can be specified to always immediately launch from the cache while spawning a check for update in the background. The second attribute, "policy", is used to determine what to do when it is known before starting the application that there is an update available. You can either always get the update, or prompt the user. The policy attribute values can be either "always" (this is default) , "prompt-update" or "prompt-run".

  • JNLP Specification relaxation of requirements for the DownloadService API.

In the previous versions, the URLs passed as arguments to all of the APIs were restricted to be URLs to resources listed in the jnlp file(s) of the running application. This restriction is changed such that there are no restrictions for signed and trusted code, and the restriction on untrusted code is not that it be listed in the jnlp file(s), but only that it be from the same codebase.
Further, URLs to jnlp file(s) themselves are allowed, so that calling DownloadService.removeResource() can now be used to remove a whole application from the cache, and DownloadService.loadResource() can be used to import an application.
One effect of this change is that resources not listed in any jnlp file can now be used in an application. For example, after determining the locale is set to en_xx, an application can then load resources_en_xx.jar using the DownloadService, without listing all the available resource jars in the jnlp file. (Allowing you to dynamically add support for more locales without changing the jnlp file).

  • Implementation of a SocketService

Another significant specification change is a clarification in the definition of the sandbox, that it is only the default sandbox, and that the implementation is free to prompt the user to allow actions that wouldn't be allowed by the sandbox. You already saw in 1.5.0 that this was done for printing, so that just by using the normal printing api in awt, you could expand the sandbox to allow the application to access the printer (if the user agreed). In 6.0 this is also done for socket connections, so that if an untrusted application attempts to connect to a url, the user can be prompted to allow the connection.

  • New <java> element in jnlp file to replace <j2se> element.

For jnlp files that will be used only with Java Web Start version 6.0 or later, the <java> element can be used to replace the <j2se> tag. (This is mainly because the Java Platform Standard Edition is no longer called j2se.) For backward compatibility, the <j2se> tag will continue to work. The <java> element will be identical to the <j2se> element..

  • The <association> element now may contain the <icon> and <description> sub-elements.

When creating file extension and mime type associations with your Java Web Start application, you can now specify a separate icon to be used for each association (as opposed to using the default icon for the application). Now, you can also specify a description.

  • Jar Indexing is fully supported now, and the JNLPClassLoader is now an instance of the URLClassLoader.

The JNLPClassLoader was rewritten to extend URLClassLoader. This gives several powerful advantages.
First, Jar Indexing is now fully supported. If you have several jar files, and create a jar index in the main jar file that indexes all the jar files, you can then mark each additional jar as lazy, and it will not be downloaded until and unless a resource or class in it is referenced. This makes the old part and package elements unnecessary for insuring that lazy jars are not downloaded prematurely.
Second, since the JNLPClassLoader now extends URLClassLoader, an Application can call getURLs() to get a list of the jar elements that are listed in the jnlp files (or have been downloaded using the DownloadService API, even if not listed in any jnlp file, see above).
Finally, the URL returned for calls to ClassLoader.getResource() is now the proper JAR URL of the item on the net. In previous versions, this URL returned was a jar url of the file url item in the cache. By extending URLClassLoader, the cached location (if it exists) is meaningless, and it allows Java Web Start to operate without caching.

  • Enhanced icon support.

Java Web Start now supports two new icon formats, ".png", and ".ico". This allows you to specify an icon that will not need to be translated into a different format depending on its use. You can also now specify kind="shortcut", and Java Web Start will now honor the width and height hints. This means if you specify:
<icon kind="shortcut" href="menushortcut.ico" width="16" height="16"/>
<icon kind="shortcut" href="desktopshortcut.ico" width="32" height="32"/>
you can specify separate images for any desktop and menu shortcuts that are created. (note: for desktop shortcuts, Java Web Start will use the icon whose size is closer to 32X32, and for menu shortcuts Java Web Start will use the icon whose size is closer to 16X16 )

  • Enhanced support for Add/Remove program entries on Windows.

The Windows Add/Remove program entries for Java Web Start applications will now include the publisher, publisher web site, install date, and application icon from the information block of the jnlp file.

  • Desktop shortcut tooltips.

Desktop shortcuts created by Java Web Start will now use the <description> element in the jnlp file to create a toolkit describing the application.

  • JNLPDownloadServlet enhancements.

The JnlpDownloadServlet now contains both a $$hostname and a $$site macro. The $$hostname macro is expanded to contain the host name. The $$site macro is expanded to contain the web site address without the WAR context portion.

  • The list of safe vm args and safe properties has been expanded.

See the developers guide for the current list of safe properties and vm args.

  • Several Command Line Interface (CLI) items have been changed or added. See the developers guide for the current Javaws CLI.

Enhancements Common to Java Web Start and Java Plug-in

  • All dialogs have been redesigned to be more user friendly.

All of the dialogs and screens shown by Java Web Start and Java Plug-in have been redesigned with help from the User Experience team to be more user friendly, intuitive, and accessible.

  • DownloadEngine and cache consolidation and redesign.

The entire caching mechanism and download engine has been redesigned and consolidated between Java Web Start and Java Plug-in.
This brings several new features to Java Web Start, previously available only in Java Plug-in and vice versa.

  • Caching can be disabled now entirely via the Java Control Panel.

  • The cache max size set in the JCP is now honored in Java Web Start, and a cleanup thread may be started by Java Web Start to removed LRU items from the cache when it is approaching the max size set by the user.
  • The "cache-control: no-cache" HTTP header is now supported. "no-cache" means cached contents cannot be used without re-validation. When the no-cache directive is used , an update check is always made to make sure the cached content is the same as the server copy pointed to, by the resource URL. If so, cached copy can be used. If not, server copy will be downloaded. Expiration field is ignored, which means that even if the cached resource is not expired yet, update check will still be performed.
  • The expiration-date will be honored. If a downloaded resource contains an expiration date, it will not be used after that date.

Note: The format of the cache is completely changed and should never be assumed. Any existing code that assumed the previous format of the cache, for either Java Web Start or Java Plug-in will no longer work. Existing applications in the Java Web Start cache will be upgraded and converted to the new cache format the first time you run a Java Web Start application, or if you launch the cache viewer using "javaws -viewer". Likewise, the system cache will be upgraded and converted to the new format the first time you launch Java Web Start in system mode, or if you just launch "javaws -system".

  • The Java Console is now excluded from modality.

By using the new modality features added by AWT in Java 6, you can interact with the Java Console even when the Application displays a modal Dialog.

  • New support for OCSP/CRL

Java Web Start and Java Java Plug-in support CRL (Certificate Revocation Lists) and OCSP (Online Certificate Status Protocol) for verifying the certificates.

  • New Support for SSL/TSL

An Option has been added to the Java Control Panel to select the default SSL handshaking protocol.
The default is set to SSLv3 and SSLv2, but then user or enterprise can change it to TSL.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java SE 7 Release Security Enhancements

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java™ SE 7 Release Security Enhancements

The Java SE 7 release adds the following features:

  • Elliptic Curve Cryptography (ECC)
    A new native provider has been added to the Java SE 7 release that provides several ECC-based algorithms (ECDSA/ECDH).

  • CertPath Algorithm Disabling
    Weak cryptographic algorithms can now be disabled. For example, the MD2 digest algorithm is no longer considered secure. The Java SE 7 release provides a mechanism for denying the use of specific algorithms in certification path processing and TLS handshaking.

  • JSSE (SSL/TLS)
    • TLS 1.1
      The SunJSSE provider now supports TLS 1.1 as described in RFC 4346. The most important update is protection against cipher block chaining (CBC) attacks.

    • TLS 1.2
      The SunJSSE provider now supports TLS 1.2 as described in RFC 5246. Among other things, it specifies different internal hashing algorithms, adds new cipher suites, and contains improved flexibility, particularly for negotiation of cryptographic algorithms.

    • Weak cipher suites deprecated
      Per RFC 4346, RFC 5246, and RFC 5469, some cipher suites have been made obsolete and should not be used. These obsolete suites are all disabled by default in SunJSSE. For details, consult the cipher suite lists in the documentation about the SunJSSE provider.

    • Connection-sensitive trust management
      Both trust managers and key managers now have the ability to examine parameters of the TLS connection, specifically the SSLSession under construction, during the handshake. For example, a trust manager might restrict the types of certificates used based on the list of valid signature algorithms.

    • Endpoint verification
      An endpoint identification algorithm can be specified to verify that a remote computer's host address matches its supplied certificate. Although this type of verification was previously performed for the HTTPS protocol (see HttpsURLConnection and HostnameVerifier), such verification can now be optionally performed at the TLS level.

    • TLS renegotiation
      Java SE supports RFC 5746, which fixes a renegotiation issue in the TLS protocol.

    • SSLv2Hello disabled by default
      In Java SE 7, SSLv2Hello is removed from the default enabled protocol list.

    • Algorithm disabling
      Weak cryptographic algorithms can now be disabled, as previously described.

    • Server Name Indication (SNI) for JSSE client
      The Java SE 7 release supports the Server Name Indication (SNI) extension in the JSSE client. SNI is described in RFC 4366. This enables TLS clients to connect to virtual servers.

    • Tighter checking of EncryptedPreMasterSecret version numbers
      Java SE 7 tightens version number checking during TLS 1.1 and TLS 1.2 handshaking. See the JSSE Reference Guide for more information.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Networking Features

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Networking Features and Enhancements

in Java SE version 1.4

IPv6 (Internet Protocol version 6)

J2SE™ 1.4 supports IPv6 in TCP and UDP-based applications, including multicast, and will support most end-user applications in use today. See the IPv6 User Guide.

HTTP Digest Authentication

The HTTP digest authentication implementation has been updated to support proxies as well as origin servers, and has also been updated to provide all capabilities defined in RFC2617, except for the auth-int mode.

A number of system properties have been added which modify the behavior of the digest authentication mechanism. These are identified in the Networking Properties document.

Unconnected/Unbound Socket Support

Allows more flexible socket creation, binding, and connection. Enables manipulation of socket options before establishing or accepting connections. In addition a timeout can be specified when establishing a connection.

New class javax.net.ssl.SSLSocket is a subclass of java.net.Socket that provides security through encryption. The mechanism is called the Java Secure Socket Extension (JSSE), and it provides encryption for data sent via sockets. See the JSSE Reference Guide for further information.

Connected UDP Socket Support

The DatagramSocket.connect method now establishes the address association at native level. Where supported, this allows an application to have visibility of ICMP port unreachable messages as an indication that the remote application is unavailable.

Uniform Resource Indentifier (URI)

Class java.net.URI is new in J2SE 1.4. It allows URI construction and parsing without the presence of a protocol handler, which is not possible with the URL class. The URI class is compliant with RFC 2396 and RFC 2732.

FTP Protocol Handler

Significant overhaul to make the functionality conform as much as possible to the current standards (RFC 1738 & 959). This enhancement fixes several bugs associated with FTP functionality. For example, passive mode for FTP works in J2SE 1.4.

JNDI DNS SP Support in InetAddress

This enhancement in class java.net.InetAddress enables applications to configure a pure Java name service provider by using a DNS name service provider through JNDI. See JNDI DNS service provider settings in the Network Properties document for information on enabling this support.

URLEncoder and URLDecoder Improvements

Methods URLEncoder.encode(String s, String enc) and URLDecoder.decode(String s, String enc) have been added to enable applications to use other character encoding/decoding schemes.

TCP Out-of-Band Data

Two new methods in class java.net.Socket, sendUrgentData() and getOOBInline(), provide limited support for TCP urgent data for support certain legacy applications. Urgent data may be sent on any TCP socket. However, only partial support for receiving urgent data is provided.

SOCKS

Full V5 (RFC 1928) & V4 TCP support with autonegociation with the proxy of which version to use. See the SOCKS protocol support settings in the Network Properties document for information about using properties to specify the SOCKS proxy server.

NetworkInterface

Class java.net.NetworkInterface is new in J2SE 1.4. It allows enumeration of interfaces and addresses. This new class should be useful to applications deployed on multihomed and machines with multiple network interfaces.

Other Major Improvements

J2SE 1.4 also offers the following.

  • Improved Http streaming performance.
  • Request and response headers processing functionality in the form of these new methods in class java.net.URLConnection"

    addRequestProperty
    getRequestProperties
    getHeaderFields

  • Improved error handling implementation for method HttpURLConnection.getErrorStream().

New Classes

Here are links to the API specifications for the new classes and exceptions in the java.net package.

  • Inet4Address
  • Inet6Address
  • InetSocketAddress
  • NetworkInterface
  • SocketAddress
  • URI
  • PortUnreachableException
  • SocketTimeoutException
  • URISyntaxException
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Image I/O Enhancements in Java SE 6.0

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Image I/O Enhancements in Java™ SE 6.0

Major Features
  • A writer plug-in for the GIF image format
  • New methods for file formats filtering
Fixed Bugs
  • API and doc changes
  • BMP plugin improvements
  • Performance and resource management
  • Robustness
  • Quality
  • Miscellaneous

Major Features

A writer plug-in for the GIF file format

While reading capabilities for the GIF file format have been available since Java SE 1.4, the com.sun.media.imageio.plugins.gif package lacked a writer. The newly added GIF image writer enables writing images which satisfy the following requirements:

  • The number of bands is 1
  • The number of bits per sample is not greater than 8
  • The size of a color component is not greater than 8

Additionally, the GIF images writer supports the animated GIF images creation through the standard methods defined in the ImageWriter class. See more details about the GIF images writer in the Standard plug-in for GIF image format notes.

New methods for file formats filtering

Two new methods were introduced in the ImageIO class that obtain file suffixes to be filtered. The getReaderFileSuffixes() and getWriterFileSuffixes methods return an array of Strings listing all of the file suffixes associated with the formats recognized by the current set of registered readers and writers.

Fixed Bugs

API and doc changes

4953566 The mark() or reset() methods of the ImageInputStream class do not work properly with PNG ImageReader:

The following note was added to the ImageInputStream class specification to clarify that ImageReader classes are allowed to call the flushBefore() as part of the decoding process:

Note that it is valid for an ImageReader to call flushBefore as part of a read operation. Therefore, if an application calls the mark prior to passing that stream to an ImageReader, the application should not assume that the marked position will remain valid after the read operation has completed.

5068322 The javax.imageio.plugins.jpeg.JPEGQTable.toString() method produces incorrect description:

The toString() method of the JPEGQTable class in the package javax.imageio.plugins.jpeg was supposed to return a String object containing the values of the table, but instead repeated only the first line of the table. The performed fix eliminate this error.

6359957 Wrong doc URL reference for PNG specification:

The link to the PNG specification in the javax.imageio.metadata package was corrected to the following URL:

http://www.libpng.org/pub/png/spec/

6457035 javadoc for ImageInputStreamImpl.read() method is missing:

The ImageInputStreamImpl.java file had a missing '*' character at the beginning of the javadoc for the abstract read() method definition.The fix fills in the missing character.

BMP plugin improvements

6294920 The BMPImageReader class fails to read 3BYTE_BGR images encoded using BMP Writer with BI_JPEG compression:

While attempting to write an image of the BI_JPEG compression type, the java.io.EOFException was thrown by the BMPImageReader class. The problem was that the BMPImageReader class did not process embedded images both of BI_JPEG and BI_PNG types. To resolve this problem, the embedded image handling is moved to separate code.

6297016 Output BMP image is distorted when writing TYPE_3BYTE_BGR buffered image with BI_BITFIELDS compression:

While attempting to write a buffered image of the TYPE_3BYTE_BGR type to a file using the BMPWriter class and the BI_BITFIELDS compression type, the output image was distorted and unusable. This problem was caused by the bitfileds masks which were applied to a bmp image. However, an image data layout was not changed according to the BMP format requirements. To fix this problem the writePixels() method is used to copy image data correctly.

5076878 ImageIO BMP Writer writes 32 bit files for 24 bit images:

The ImageIO.write method presented a BMP file as a 32 bit image even if the source image had 24 bits per pixel presentation. The fix enables the writePixels procedure whenever the number of bits per pixel is smaller than the size of a databuffer type (for example, with TYPE_INT_RGB, the actual number of bits per pixel is 24 while the size of the databuffer type is 32).

6332480 The BMPReader class fails to read the TYPE_BYTE_GRAY image encoded by the BMPWriter class with BI_RLE8 compression:

The BMPReader class did not properly read the TYPE_BYTE_GRAY image written with the BMPWriter class using the BI_RLE8 compression. The problem was that the RLE decoding procedures (both RLE4 and RLE8) mistakenly used the width of the destination region instead of the height to calculate the range of image lines for copying. The performed fix uses the height of the destination region to calculate the range.

6399660 Using subsampling with compression alters the colors for some of the image types for BMP:

While using all the supported compression types for BMP, different affects on image were detected including blurring, a different color appearance, and slight image corruption. The performed fix separates processing BI_RGB compression and BI_RGB compression as follows:

  • For BI_RGB compression the BGR order of raster data should be used (except the case of 16bpp images where RGB data order is defined by the BMP spec)
  • For BI_BITFIELDS compression the order of raster data should be defined using corresponding masks. The RGB order of raster data is used for the default bitfields masks.

Performance and resource management

6299405 The ImageInputStreamImpl class still uses the finalize() method which causes the java.lang.OutOfMemoryError:

The finalize() method had to be emptied and its functionality (closing the stream) must be replaced with a more prompt mechanism. The finalize() method cannot be easily emptied at the ImageInputStreamImpl level, since third-party IISI subclasses may rely on the finalize() method calling their close() method as per the spec. However, for ImageInputStreamImpl subclasses under Sun control, the finalize() methods can be emptied. The Java2D Disposer mechanism is used instead.

6266748 The JPEGImageWriter.write() method makes a copy of the raster:

The write() method of the JPEGImageWriter class contained memory-inefficient code. The suggested fix helps to improve performance for simple rendered images.

6336804 The javax.imageio.ImageIO class can handle leaks in some methods:

Some of the read() and write() convenience methods in the javax.imageio.ImageIO class did not properly close streams and dispose reader or writer instances in a try and finally blocks. As a fix the appropriate notes were added to each method's javadocs indicating whether it is the caller's responsibility to close the provided stream or not.

6347575 FileImageInputStream.readInt() and similar methods are inefficient:

Calling the read() method of the FileImageInputStream 4x was much more expensive than making a single call to the read(byte[]) method with a cached byte array. This fact had a profound impact on performance of reading small PNG and other images. The fixes were performed for the readShort() and readInt() methods of the ImageInputStreamImpl class.

6348744 The PNGImageReader class should skip metadata if the ignoreMetadata flag has the true value:

Before JDK 6, the PNGImageReader class read all image metadata, even if the ignoreMetadata flag was set. The fix reduces overhead and improves performance when reading small PNG images by skipping metadata blocks if the ignoreMetadata flag is true.

6354056 The JPEGImageReader class could be optimized:

The JPEG image reader copied decoded data into memory, but not in an optimized way. The performed fix improves this operation by using the memcpy() method instead of copying one byte at a time.

6354112 Increase compiler optimization level for libjpeg to improve runtime performance:

The libjpeg library in the JDK was built with default compiler optimization flags. The values of these flags are increased to a higher level to enable the native IJG JPEG libraries to run faster.

6404011 IllegalArgumentException: "Invalid ICC Profile Data" when reading a certain JPEG image:

This bug was an unchecked exception and could cause a system crash on some platforms. The fix catches the IllegalArgumentException, which is thrown by ICC_Profile, and handles images without taking into account invalid color profiles.

Robustness

6291034 The IFileCacheImageInputStream and FileCacheImageOutputStream should avoid using the File.deleteOnExit method:

Both the FileCacheImageInputStream and FileCacheImageOutputStream classes used the functionality of the deleteOnExit method of the File class. The fix has replaced the File.deleteOnExit() functionality with the shutdown hook that closes streams that are still open before the VM shutdown.

4892630 The ImageReader class does not validate the image index which is passed to some of the methods:

The getWidth(imgIndex), getHeight(imgIndex), and getAspectRatio(imgIndex) methods of the ImageReader class did not throw the IndexOutOfBoundsException if the given PNG image index was out of range. The performed fix resolves this issue by throwing the exception appropriately.

4895547 JPEGImageMetadata obtained from reader throws NullPointerException when calling the mergeTree() method:

The list of parent attributes did not contain attributes related to the child node and this fact caused the NullPointerException in the MarkerSegment.getAttributeValue() method while trying to get child related attribute. The performed fix obtains the attribute list from the child node.

4528643 Native JPEG code makes JNI calls in scope of GetPrimitiveArrayCritical:

Running any application that reads or writes JPEG images with the non-standard -Xcheck:jni flag caused the following error in several methods of the JPEGImageReader class:

Calling other JNI functions in the scope of Get/ReleasePrimitiveArrayCritical or Get/ReleaseStringCritical

In the fix, the affected methods are surrounded with the RELEASE/GET_ARRAYS macros.

5076692 Installed Extensions Image I/O reader-writer plug-ins unusable in applet context:

The problem was that the imageio registry initialization code did not have read access to jars in the java.ext.dirs when the registry code was called from applet context. Therefore, the imageio plugins installed to java.ext.dirs were not available in case of applets. The fix idea is to register plugins from java.ext.dirs in the privileged action block.

6342404 The ImageIO plugin failure causes all readers to fail:

Removing an ImageIO plugin's code from the classpath, but still including an entry for the plugin's ImageReader in META-INF/services made using any of the ImageIO plugins impossible. To fix this bug, a 'try and catch' block was added to the IIORegistry.registerApplicationClasspathSpis() method to catch the ServiceConfigurationError.

6395551 Setting the destination type to type specifier returned by redr.getImageTypes() throws exception for JPG:

The problem was that a new ColorSpace instance was re-created for embedded color profiles whenever an image header was read. In addition, there was no means for correct comparison of ColorSpace and ICC_Profile classes. This omission made comparing instances of ImageTypeSpecifier class impossible. The proposed workaround for this problem is as follows: to detect the case when the iccCS instance contains the same profile data as a newly read. If so, the 'old' instance is left; otherwise (if the profile data seems to be different) a new color space instance is created for the embedded color profile.

6399616 PIT: JPGReader throws an exception when using the TYPE_CUSTOM TypeSpecifier returned by the Reader.getImageTypes method:

The regression was caused by the fix for 4705399, where color conversion was removed (JPEGImageReader.java lines 783 -786) because it caused extra color conversion for images with embedded color profiles. However, this conversion was required when the destination type defined different color spaces for images that do not contain embedded profiles. The fix for this case converts image data from sRGB (produced by the decoder) to the color space used in the destination image.

Quality

5028259 Setting the destination image type for jpeg images increases the size of the result file:

If the write parameter with the destination type was used explicitly to write a jpeg image, then the size of the result file was bigger than if the same destination type was used implicitly. The problem was revealed when the destination type was specified but the corresponding metadata object was not specified. The fix creates the metadata object using the given destination type in order to build a SOF marker object, which will be used to change the default values of the QtableSelectors.

4881314 ImageIO does not correctly read certain standard JPG files:

The ImageIO incorrectly reads some JPG files. The result was a red or green image that looked like a photographic negative. The fix eliminates color space conversion for EXIF images. To detect EXIF images, the check for the APP1 marker in the image header is added.

5098176 Some PNG images fail to load with the ImageIO class:

The PNGImageReader failed to create the ImageTypeSpecifier instance corresponding to the indexed PNG image if the length of the image palette in smaller than 2 bitDepth. To avoid this limitation new palette arrays of the appropriate power of 2 size were created. These arrays are padded with the last value from original arrays in order to avoid the appearance of colors that do not exist in the original palette.

6372769 The ImageIO.read method improperly decodes Nikon Jpegs:

The ImageIO jpeg reader performed extra color conversion if an image contained the embedded color profile. The bug was fixed by removing the extra color conversion operation.

Miscellaneous

4972087 Quality Desc and Quality Values arrays are of the same length for JPG:

The JPEGImageWriteParam class was updated so that the getCompressionQualityValues() method returns an array whose length is one larger than the array returned by getCompressionQualityDescriptions(), as per the specification.

6195593 REGRESSION: The javax/imageio/IRPTest.java file fails:

The problem was caused by the fix for the bug 5039494. Starting with this fix, the ImageReader.computeRegion() method was used to calculate the destination region. In order to avoid discrepancies between calculated destination regions and destinations offset from the parameter, the destinationOffset is updated according to the calculated values.

6304433 Test bug: the regression test for the bug 6291034 fails on all platforms:

The regression test failure was caused by the creation of an output image file. This file was created after counting the existing files in the work directory and was not deleted on regression test finish. So, after regression test execution, the work directory always contained one extra file, although all temporary files were deleted upon VM exit. The solution is to use byte array input or output streams instead of file input or output streams in order to avoid creating extra files in the work directory.

6356926 PIT: The regression test javax/imageio/stream/DeleteOnExit.sh is failing:

The problem was caused by the fix for the bug 6299405. The affected code is fixed and the corresponding comment has been added.

6459309 The NoAPP0Test.java regression test failed on all platforms:

The difference in pixel values is caused by using new version of sRGB profile that was updated as part of fix for 6279846. New profile was integrated in the b92 build.

6363748 The close() method of the FileCacheImageInputStream class fails:

The problem was caused by the fix for the bug 6299405. As a part of that fix the FileCacheImageInputStream.close() method was changed so that it nulled out its reference to the cache object. To eliminate this issue the FCIIS.read() method is updated to call the checkClosed() method as it is supposed to do.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java 2D Enhancements in the Java SE 7

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java 2D Enhancements in the Java™ SE 7

Major Features:
  • Improved Rendering Pipeline
  • Support for OpenType/CFF Fonts
  • TextLayout now Supports Tibetan Script
  • Better Support for Linux Fonts

Major Features

Improved Rendering Pipeline

A new XRender-based Java 2D rendering pipeline is supported for modern X11-based desktops, offering improved graphics performance. The pipeline is disabled by default, but may be enabled by setting the command line property -Dsun.java2d.xrender=true. Older X11 configurations may not be able to support XRender. The verbose form, -Dsun.java2d.xrender=True, can be used to enable a message to stdout indicating whether the pipeline was actually enabled.

This flag is listed in the System Properties for Java 2D Technology page.

Support for OpenType/CFF Fonts

The JDK will now enumerate and display the OpenType/CFF fonts installed on the platform, and also recognize them via the Font.createFont API.

TextLayout now Supports Tibetan Script

Better Support for Linux Fonts

For Solaris and Windows, the logical fonts for the JDK are statically specified in the fontconfig.properties file. On various implementations of Linux, there is no assurance of the presence of particular fonts to support particular locales. As of Java SE 7, libfontconfig is used to select fonts to use for the logical fonts for "unrecognized" Linux platforms.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


J2SE 5 Network Enhancements

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Networking Features and Enhancements

in J2SE 5.0

  • Complete support for IPv6 on Windows XP (SP1) and 2003 server has been provided in this release. (4608529)
  • The networking API now provides a way of setting timeouts on connect and read operations for protocol handlers. This will benefit any HTTP client application that must behave robustly in the event of server failure. (4700777)
  • A new API provides a mean for Java applications, which includes RMI applications, to be launched via inetd. (4295885, 4673940)
  • The InetAddress class now provides an API to allow testing for the reachability of a host. This features provides a ping-like capability in Java. (4639861)
  • Cookie support has been improved. Applications and web containers can provide Cookie management by implementing the new CookieHandler API. (4696506)
  • Proxy server configuration has been improved. It can now be dynamic and controlable by web containers and applications through the ProxySelector API, which can also handle failures to connect to the proxy. (4696512)
  • A new framework provides a way for protocol handlers to access a file caching mechanism implemented by the platform or by a third party. (4837267)
  • The specification of the URL class now mandates a minimum set of URL protocol handlers that are guaranteed to be present in J2SE. They are http, https, file, jar and ftp. (4180636)
  • There have been a number of enhancements for JSSE (SSL/TLS). For more information, please see: J2SE 5 Security Enhancements

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Networking Features

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Networking Features and Enhancements

in Java SE version 6.0

Enhancement to Network Interface

Provides a number of new methods for accessing state and configuration information relating to a system's network adapters. This includes information such as the broadcast address, subnet mask, MAC addresses, and MTU size. See java.net.NetworkInterface

The new class java.net.InterfaceAddress encapsulates all information about a NetworkInterface's IP addresses, including the broadcast address, and subnet prefix length (subnet mask)

Support for Internationalized Domain Names

RFCs 3490, 3491, 3492, 3454 define a mechanism where domain names comprised of characters in alphabets other than US ASCII can be stored in the DNS. An algorithm is defined which provides a conversion from arbitrary Unicode strings to and from a "mangled" ASCII form. This feature provides a new class java.net.IDN, which allows applications to do this conversion so that IDNs can be looked up via java.net.InetAddress.

HTTP Negotiate authentication

This adds support for the "Negotiate" HTTP authentication scheme defined by Microsoft. Negotiate allows multiple underlying authentication mechanisms to be supported, and in each instance, one of these mechanisms is chosen for use. Currently, Kerberos is the only supported mechanism. This feature is described in more detail in the guide to Http Authentication.

Cross platform NTLM

Previously, the Microsoft defined NTLM authentication protocol for HTTP was only supported on Windows. Now, this protocol is supported on all platforms.

Default CookieManager implementation

The CookieHandler class was added in 1.5, but no implementation was provided in java.net. This feature provides a simple extensible implementation which separates the storage of cookies from the policy surrounding their acceptance. The default manager provides a number of standard policies and a simple in-memory storage mechanism. User defined policies and storage mechanisms can be used with this implementation. The following are the new classes related to this feature:

  • java.net.CookieManager
  • java.net.CookiePolicy
  • java.net.CookieStore
  • java.net.HttpCookie

Light-weight HTTP server

This provides a simple set of classes and interfaces for building light-weight HTTP server applications. The feature defines two new packages com.sun.net.httpserver and com.sun.net.httpserver.spi. The server supports HTTP and HTTPS.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Networking Features

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Networking Features and Enhancements

Enhancements in Java SE 7

Enhancement to ClassLoader

See Closing a URLClassLoader.

InfiniBand Support Using Sockets Direct Protocol (SDP)

The Sockets Direct Protocol (SDP) provides access to high performance network connections, such as that provided by InfiniBand. See the Understanding the Sockets Direct Procotol tutorial for more information.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Internationalization Enhancements in Java SE 6

This page provides an overview of internationalization enhancements in Java SE Development Kit 6 (JDK):

  • Core Java Internationalization
  • Desktop Java Internationalization

Core Java Internationalization

Locale Sensitive Services SPIs

To enable plug-in of locale sensitive data (e.g., date format strings) and services (e.g., date formatters), some Service Provider Interfaces (SPIs) for locale-sensitive classes in the java.text and java.util packages have been added. These SPIs make it much easier for developers to provide support of more locales in addition to the currently available locales in Java SE. For example, your own implementation of BreakIterator for Chinese could become available through the BreakIterator.getSentenceInstance factory in the Java runtime.

Unicode Normalizer API

The new java.text.Normalizer class supports the Unicode text normalization defined in Unicode Standard Annex #15.

Internationalized Domain Names Support

The new java.net.IDN class provides Internationalized Domain Names (IDNs) support based on RFC 3490, 3491, 3454, and 3492.

Japanese Imperial Calendar Support

A new Calendar implementation has been added to support the Japanese imperial era-based year numbering, such as Heisei 17 for 2005 (Gregorian). An instance of this Japanese imperial calendar can be created through the Calendar.getInstance factory by specifying a Locale("ja", "JP", "JP"). The java.text.SimpleDateFormat class now supports calendar specific eras and date formats for non-Gregorian calendar systems. Refer to the Supported Calendars documentation for details.

ResourceBundle Enhancements

The new nested java.util.ResourceBundle.Control class has been added to give applications more control over the resource bundle loading process. The class defines a set of callback methods that are invoked by the ResourceBundle.getBundle factory during the resource bundle loading. Applications can override those callback methods to change the factory method behavior.

Additional Locales Support

The following locales are now available.

  • zh_SG - Chinese (Simplified), Singapore
  • en_MT - English, Malta
  • en_PH - English, Philippines
  • en_SG - English, Singapore
  • el_CY - Greek, Cyprus
  • id_ID - Indonesian, Indonesia
  • ga_IE - Irish, Ireland
  • ms_MY - Malay, Malaysia
  • mt_MT - Maltese, Malta
  • pt_BR - Portuguese, Brazil
  • pt_PT - Portuguese, Portugal
  • es_US - Spanish, United States

Refer to the Supported Locales documentation for details.

Desktop Java Internationalization

Key Input in non-English Locales

The keyboard related AWT code has been re-architected to fix various problems on key input in non-English locales for Solaris and Linux operating systems.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Internationalization Enhancements in Java SE 7

The Internationalization enhancements for Java SE 7 include the following:
  • New Scripts and Characters from Unicode 6.0.0
  • Extensible Support for ISO 4217 Currency Codes
  • Category Locale Support
  • Locale Class Supports BCP47 and UTR35
  • New NumericShaper Methods
  • Unicode 6.0 Support in Regular Expressions API

New Scripts and Characters from Unicode 6.0.0

Early versions of the Java SE 7 release added support for Unicode 5.1.0. The final version of the Java SE 7 release supports Unicode 6.0.0. Unicode 6.0.0 is a major version of the Unicode Standard and adds support for over 2000 additional characters, as well as support for properties and data files.

The Java Tutorial has a new section that discusses Unicode.

Extensible Support for ISO 4217 Currency Codes

Currencies are identified by their ISO 4217 codes. These codes maintained by an external agency and are released independent of the Java SE platform. As of Java SE 7, it is possible to accommodate new currencies without requiring a new release of the JDK.

To supersede the default currency at runtime, create a properties file named <JAVA_HOME>/lib/currency.properties. This file contains the key/value pairs of the ISO 3166 country code, and the ISO 4217 currency data. The value part consists of three comma-separated ISO 4217 currency values: an alphabetic code, a numeric code, and a minor unit. Any lines beginning with the hash character, #, are treated as comment lines. For example:

# Sample currency property for Japan
JP=JPZ,999,0
The new API for this feature includes the following methods, all in the Currency class:
  • getAvailableCurrencies – Returns the set of available currencies.
  • getNumericCode – Returns the ISO 4217 numeric code of this currency
  • getDisplayName – Gets the name suitable for displaying this currency for the default locale.
  • getDisplayName(Locale) – Gets the name suitable for displaying the specified locale.

Category Locale Support

The default locale can be independently set for two types of uses: the format setting is used for formatting resources, and the display setting is used in menus and dialogs. The new getDefault(Locale.Category) method takes a Locale.Category parameter. Passing the FORMAT enum to the method returns the default locale for formatting resources. Similarly, passing the DISPLAY enum returns the default locale used by the UI. The setDefault(Locale.Category, Locale) method is used to set the locale for the specified category. The no-argument getDefault method returns the DISPLAY default value.

On Microsoft Windows, these default values are initialized according to the "Standard and Formats" and "Display Language" settings in the Windows control panel.

Locale Class Supports BCP47 and UTR35

The Locale class has been updated to implement identifiers interchangeable with BCP 47 (IETF BCP 47, "Tags for Identifying Languages"), with support for the LDML (UTS#35, "Unicode Locale Data Markup Language") BCP 47-compatible extensions for locale data exchange.

The following nested classes have been added to the Locale class in this release:

  • Locale.Builder can be used to create a Locale instance and to configure that instance using setter methods.
The following methods have been added to the Locale class:
  • getExtensionKeys()
  • getExtension(char)
  • getUnicodeLocaleType(String
  • getUnicodeLocaleKeys()
  • getUnicodeLocaleAttributes()
  • forLanguageTag(String)
  • toLanguageTag()
  • getScript()
  • getDisplayScript()
  • getDisplayScript(Locale)
The following constants have been added to the LOCALE class:
  • UNICODE_LOCALE_EXTENSION
  • PRIVATE_USE_EXTENSION
For more information, see the Creating a Locale and BCP 47 Extensions lessons in the Java Tutorial.

New NumericShaper Methods

The NumericShaper class is used to convert Latin-1 (European) digits to other Unicode decimal digits. For the Java SE 7 release, the NumericShaper.Range enum has been added to represent a Unicode range of a script having its own decimal digits. The following methods, using the NumericShaper.Range enum have been added to the Java SE 7 release:
  • getShaper(NumericShaper.Range) - returns a shaper for the provided Unicode range.
  • getContextualShaper(Set<NumericShaper.Range>) - returns a contextual shaper for the provided Unicode range(s). The shaper assumes European as the starting context.
  • getContextualShaper(Set<NumericShaper.Range> NumericShaper.Range) - returns a contextual shaper for the provided Unicode range(s). The shaper uses the defaultContext as the starting context.
  • shape(char[], int, int, NumericShaper.Range) - converts the digits in the text that occur between start and start + count, using the provided context.
For more information, see the Converting Latin Digits to Other Unicode Digits lesson in the Java Tutorial.

Unicode 6.0 Support in Regular Expressions API

The Regular Expressions pattern matching functionality has been expanded to support Unicode 6.0. You can match Unicode code points using either the \u or the \x escape sequence.

The Unicode Support page in the Java Tutorial has more information.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Sound Enhancements in JDK 5.0

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

JavaTM Sound Enhancements in JDKTM 5.0

The following enhancements took effect at JDK 5.0.

  • Ports are available on all platforms (RFE 4782900).
  • MIDI device i/o is available on all platforms (RFE's 4812168, 4782924).
  • Optimized direct audio access is implemented on all platforms (RFEs 4908240 and 4908879). It is enabled by default on systems which offer native mixing (i.e. Linux ALSA with hardware mixing, Solaris Mixer enabled, Windows DirectSound).
  • The new real-time Sequencer works with all MIDI devices and allows unlimited Transmitters (RFE 4773012).
  • The sound.properties configuration file allows choice of default devices (RFE 4776511). For details, see MidiSystem and AudioSystem for details.
  • MidiDevices can query connected Receivers and Transmitters (RFE 4931387, methods MidiDevice.getReceiver and MidiDevice.getTransmitter).
  • AudioFormat, AudioFileFormat, and MidiFileFormat now have properties that allow further description and qualification of the format (RFEs 4925767 and 4666845).
  • A set of ease-of-use methods allow easier retrieval of lines from AudioSystem (RFE 4896221).
  • The Sequencer interface is extended with loop methods, for seamless looping of specific portions of a MIDI sequence (RFE 4204105).
  • Java Sound no longer prevents the VM from exiting (bug 4735740).
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface org.w3c.dom.Entity (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.Entity

No usage of org.w3c.dom.Entity
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.EntityReference (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.EntityReference

  • Packages that use EntityReference
    Package Description
    org.w3c.dom
    Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.

    • Uses of EntityReference in org.w3c.dom

      Methods in org.w3c.dom that return EntityReference
      Modifier and Type Method and Description
      EntityReference Document.createEntityReference(String name)
      Creates an EntityReference object.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.declaration.EnumConstantDeclaration (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.declaration.EnumConstantDeclaration

  • Packages that use EnumConstantDeclaration
    Package Description
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of EnumConstantDeclaration in com.sun.mirror.declaration

      Methods in com.sun.mirror.declaration that return types with arguments of type EnumConstantDeclaration
      Modifier and Type Method and Description
      Collection<EnumConstantDeclaration> EnumDeclaration.getEnumConstants()
      Deprecated.
      Returns the enum constants defined for this enum.

    • Uses of EnumConstantDeclaration in com.sun.mirror.util

      Methods in com.sun.mirror.util with parameters of type EnumConstantDeclaration
      Modifier and Type Method and Description
      void SimpleDeclarationVisitor.visitEnumConstantDeclaration(EnumConstantDeclaration d)
      Deprecated.
      Visits an enum constant declaration.
      void DeclarationVisitor.visitEnumConstantDeclaration(EnumConstantDeclaration d)
      Deprecated.
      Visits an enum constant declaration.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.declaration.EnumDeclaration (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.declaration.EnumDeclaration

  • Packages that use EnumDeclaration
    Package Description
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.
    com.sun.mirror.type
    Interfaces used to model types.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of EnumDeclaration in com.sun.mirror.declaration

      Methods in com.sun.mirror.declaration that return EnumDeclaration
      Modifier and Type Method and Description
      EnumDeclaration EnumConstantDeclaration.getDeclaringType()
      Deprecated.
      Returns the type declaration within which this member or constructor is declared.
      Methods in com.sun.mirror.declaration that return types with arguments of type EnumDeclaration
      Modifier and Type Method and Description
      Collection<EnumDeclaration> PackageDeclaration.getEnums()
      Deprecated.
      Returns the declarations of the top-level enum types in this package.

    • Uses of EnumDeclaration in com.sun.mirror.type

      Methods in com.sun.mirror.type that return EnumDeclaration
      Modifier and Type Method and Description
      EnumDeclaration EnumType.getDeclaration()
      Deprecated.
      Returns the declaration of this type.

    • Uses of EnumDeclaration in com.sun.mirror.util

      Methods in com.sun.mirror.util with parameters of type EnumDeclaration
      Modifier and Type Method and Description
      void SimpleDeclarationVisitor.visitEnumDeclaration(EnumDeclaration d)
      Deprecated.
      Visits an enum declaration.
      void DeclarationVisitor.visitEnumDeclaration(EnumDeclaration d)
      Deprecated.
      Visits an enum declaration.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Enums

In prior releases, the standard way to represent an enumerated type was the int Enum pattern:
// int Enum Pattern - has severe problems!
public static final int SEASON_WINTER = 0;
public static final int SEASON_SPRING = 1;
public static final int SEASON_SUMMER = 2;
public static final int SEASON_FALL   = 3;
This pattern has many problems, such as:
  • Not typesafe - Since a season is just an int you can pass in any other int value where a season is required, or add two seasons together (which makes no sense).
  • No namespace - You must prefix constants of an int enum with a string (in this case SEASON_) to avoid collisions with other int enum types.
  • Brittleness - Because int enums are compile-time constants, they are compiled into clients that use them. If a new constant is added between two existing constants or the order is changed, clients must be recompiled. If they are not, they will still run, but their behavior will be undefined.
  • Printed values are uninformative - Because they are just ints, if you print one out all you get is a number, which tells you nothing about what it represents, or even what type it is.
It is possible to get around these problems by using the Typesafe Enum pattern (see Effective Java Item 21), but this pattern has its own problems: It is quite verbose, hence error prone, and its enum constants cannot be used in switch statements.

In 5.0, the Java™ programming language gets linguistic support for enumerated types. In their simplest form, these enums look just like their C, C++, and C# counterparts:

enum Season { WINTER, SPRING, SUMMER, FALL }

But appearances can be deceiving. Java programming language enums are far more powerful than their counterparts in other languages, which are little more than glorified integers. The new enum declaration defines a full-fledged class (dubbed an enum type). In addition to solving all the problems mentioned above, it allows you to add arbitrary methods and fields to an enum type, to implement arbitrary interfaces, and more. Enum types provide high-quality implementations of all the Object methods. They are Comparable and Serializable, and the serial form is designed to withstand arbitrary changes in the enum type.

Here is an example of a playing card class built atop a couple of simple enum types. The Card class is immutable, and only one instance of each Card is created, so it need not override equals or hashCode:

import java.util.*;

public class Card {
    public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX,
        SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }

    public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }

    private final Rank rank;
    private final Suit suit;
    private Card(Rank rank, Suit suit) {
        this.rank = rank;
        this.suit = suit;
    }

    public Rank rank() { return rank; }
    public Suit suit() { return suit; }
    public String toString() { return rank + " of " + suit; }

    private static final List<Card> protoDeck = new ArrayList<Card>();

    // Initialize prototype deck
    static {
        for (Suit suit : Suit.values())
            for (Rank rank : Rank.values())
                protoDeck.add(new Card(rank, suit));
    }

    public static ArrayList<Card> newDeck() {
        return new ArrayList<Card>(protoDeck); // Return copy of prototype deck
    }
}
The toString method for Card takes advantage of the toString methods for Rank and Suit. Note that the Card class is short (about 25 lines of code). If the typesafe enums (Rank and Suit) had been built by hand, each of them would have been significantly longer than the entire Card class.

The (private) constructor of Card takes two parameters, a Rank and a Suit. If you accidentally invoke the constructor with the parameters reversed, the compiler will politely inform you of your error. Contrast this to the int enum pattern, in which the program would fail at run time.

Note that each enum type has a static values method that returns an array containing all of the values of the enum type in the order they are declared. This method is commonly used in combination with the for-each loop to iterate over the values of an enumerated type.

The following example is a simple program called Deal that exercises Card. It reads two numbers from the command line, representing the number of hands to deal and the number of cards per hand. Then it creates a new deck of cards, shuffles it, and deals and prints the requested hands.

import java.util.*;

public class Deal {
    public static void main(String args[]) {
        int numHands = Integer.parseInt(args[0]);
        int cardsPerHand = Integer.parseInt(args[1]);
        List<Card> deck  = Card.newDeck();
        Collections.shuffle(deck);
        for (int i=0; i < numHands; i++)
            System.out.println(deal(deck, cardsPerHand));
    }

    public static ArrayList<Card> deal(List<Card> deck, int n) {
         int deckSize = deck.size();
         List<Card> handView = deck.subList(deckSize-n, deckSize);
         ArrayList<Card> hand = new ArrayList<Card>(handView);
         handView.clear();
         return hand;
     }
}

$ java Deal 4 5
[FOUR of HEARTS, NINE of DIAMONDS, QUEEN of SPADES, ACE of SPADES, NINE of SPADES]
[DEUCE of HEARTS, EIGHT of SPADES, JACK of DIAMONDS, TEN of CLUBS, SEVEN of SPADES]
[FIVE of HEARTS, FOUR of DIAMONDS, SIX of DIAMONDS, NINE of CLUBS, JACK of CLUBS]
[SEVEN of HEARTS, SIX of CLUBS, DEUCE of DIAMONDS, THREE of SPADES, EIGHT of CLUBS]

Suppose you want to add data and behavior to an enum. For example consider the planets of the solar system. Each planet knows its mass and radius, and can calculate its surface gravity and the weight of an object on the planet. Here is how it looks:

public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7),
    PLUTO   (1.27e+22,  1.137e6);

    private final double mass;   // in kilograms
    private final double radius; // in meters
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    public double mass()   { return mass; }
    public double radius() { return radius; }

    // universal gravitational constant  (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;

    public double surfaceGravity() {
        return G * mass / (radius * radius);
    }
    public double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }
}

The enum type Planet contains a constructor, and each enum constant is declared with parameters to be passed to the constructor when it is created.

Here is a sample program that takes your weight on earth (in any unit) and calculates and prints your weight on all of the planets (in the same unit):

    public static void main(String[] args) {
        double earthWeight = Double.parseDouble(args[0]);
        double mass = earthWeight/EARTH.surfaceGravity();
        for (Planet p : Planet.values())
           System.out.printf("Your weight on %s is %f%n",
                             p, p.surfaceWeight(mass));
    }

$ java Planet 175
Your weight on MERCURY is 66.107583
Your weight on VENUS is 158.374842
Your weight on EARTH is 175.000000
Your weight on MARS is 66.279007
Your weight on JUPITER is 442.847567
Your weight on SATURN is 186.552719
Your weight on URANUS is 158.397260
Your weight on NEPTUNE is 199.207413
Your weight on PLUTO is 11.703031

The idea of adding behavior to enum constants can be taken one step further. You can give each enum constant a different behavior for some method. One way to do this by switching on the enumeration constant. Here is an example with an enum whose constants represent the four basic arithmetic operations, and whose eval method performs the operation:

public enum Operation {
    PLUS, MINUS, TIMES, DIVIDE;

    // Do arithmetic op represented by this constant
    double eval(double x, double y){
        switch(this) {
            case PLUS:   return x + y;
            case MINUS:  return x - y;
            case TIMES:  return x * y;
            case DIVIDE: return x / y;
        }
        throw new AssertionError("Unknown op: " + this);
    }
}
This works fine, but it will not compile without the throw statement, which is not terribly pretty. Worse, you must remember to add a new case to the switch statement each time you add a new constant to Operation. If you forget, the eval method with fail, executing the aforementioned throw statement

There is another way give each enum constant a different behavior for some method that avoids these problems. You can declare the method abstract in the enum type and override it with a concrete method in each constant. Such methods are known as constant-specific methods. Here is the previous example redone using this technique:

public enum Operation {
  PLUS   { double eval(double x, double y) { return x + y; } },
  MINUS  { double eval(double x, double y) { return x - y; } },
  TIMES  { double eval(double x, double y) { return x * y; } },
  DIVIDE { double eval(double x, double y) { return x / y; } };

  // Do arithmetic op represented by this constant
  abstract double eval(double x, double y);
}

Here is a sample program that exercises the Operation class. It takes two operands from the command line, iterates over all the operations, and for each operation, performs the operation and prints the resulting equation:

    public static void main(String args[]) {
        double x = Double.parseDouble(args[0]);
        double y = Double.parseDouble(args[1]);
        for (Operation op : Operation.values())
            System.out.printf("%f %s %f = %f%n", x, op, y, op.eval(x, y));
    }

$ java Operation 4 2
4.000000 PLUS 2.000000 = 6.000000
4.000000 MINUS 2.000000 = 2.000000
4.000000 TIMES 2.000000 = 8.000000
4.000000 DIVIDE 2.000000 = 2.000000
Constant-specific methods are reasonably sophisticated, and many programmers will never need to use them, but it is nice to know that they are there if you need them.

Two classes have been added to java.util in support of enums: special-purpose Set and Map implementations called EnumSet and EnumMap. EnumSet is a high-performance Set implementation for enums. All of the members of an enum set must be of the same enum type. Internally, it is represented by a bit-vector, typically a single long. Enum sets support iteration over ranges of enum types. For example given the following enum declaration:

    enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
you can iterate over the weekdays. The EnumSet class provides a static factory that makes it easy:
    for (Day d : EnumSet.range(Day.MONDAY, Day.FRIDAY))
        System.out.println(d);
Enum sets also provide a rich, typesafe replacement for traditional bit flags:
    EnumSet.of(Style.BOLD, Style.ITALIC)

Similarly, EnumMap is a high-performance Map implementation for use with enum keys, internally implemented as an array. Enum maps combine the richness and safety of the Map interface with speed approaching that of an array. If you want to map an enum to a value, you should always use an EnumMap in preference to an array.

The Card class, above, contains a static factory that returns a deck, but there is no way to get an individual card from its rank and suit. Merely exposing the constructor would destroy the singleton property (that only a single instance of each card is allowed to exist). Here is how to write a static factory that preserves the singleton property, using a nested EnumMap:

private static Map<Suit, Map<Rank, Card>> table =
    new EnumMap<Suit, Map<Rank, Card>>(Suit.class);
static {
    for (Suit suit : Suit.values()) {
        Map<Rank, Card> suitTable = new EnumMap<Rank, Card>(Rank.class);
        for (Rank rank : Rank.values())
            suitTable.put(rank, new Card(rank, suit));
        table.put(suit, suitTable);
    }
}

public static Card valueOf(Rank rank, Suit suit) {
    return table.get(suit).get(rank);
}
The EnumMap (table) maps each suit to an EnumMap that maps each rank to a card. The lookup performed by the valueOf method is internally implemented as two array accesses, but the code is much clearer and safer. In order to preserve the singleton property, it is imperative that the constructor invocation in the prototype deck initialization in Card be replaced by a call to the new static factory:
    // Initialize prototype deck
    static {
        for (Suit suit : Suit.values())
            for (Rank rank : Rank.values())
                protoDeck.add(Card.valueOf(rank, suit));
    }
It is also imperative that the initialization of table be placed above the initialization of protoDeck, as the latter depends on the former.

So when should you use enums? Any time you need a fixed set of constants. That includes natural enumerated types (like the planets, days of the week, and suits in a card deck) as well as other sets where you know all possible values at compile time, such as choices on a menu, rounding modes, command line flags, and the like. It is not necessary that the set of constants in an enum type stay fixed for all time. The feature was specifically designed to allow for binary compatible evolution of enum types.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.mirror.type.EnumType (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.type.EnumType

  • Packages that use EnumType
    Package Description
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of EnumType in com.sun.mirror.util

      Methods in com.sun.mirror.util with parameters of type EnumType
      Modifier and Type Method and Description
      void TypeVisitor.visitEnumType(EnumType t)
      Deprecated.
      Visits an enum type.
      void SimpleTypeVisitor.visitEnumType(EnumType t)
      Deprecated.
      Visits an enum type.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.ErroneousTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.ErroneousTree

  • Packages that use ErroneousTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of ErroneousTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type ErroneousTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitErroneous(ErroneousTree node, P p)

    • Uses of ErroneousTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type ErroneousTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitErroneous(ErroneousTree node, P p)
      R | SimpleTreeVisitor.visitErroneous(ErroneousTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


An unexpected exception has been detected in native code outside the VM.
Unexpected Signal : EXCEPTION_ACCESS_VIOLATION occurred at PC=0xe6a1067
Function name=Java_NativeSEGV_foo
Library=D:\testcases\NativeSEGV\NativeSEGV.dll
Source file = NativeSEGV.c : 7

Current Java thread:
    at NativeSEGV.foo(Native Method)
    at NativeSEGV.main(NativeSEGV.java:26)

Dynamic libraries:
0x00400000 - 0x00405000 	d:\jdk1.3.1\bin\java.exe
0x77F60000 - 0x77FBE000 	C:\WINNT\System32\ntdll.dll
0x77DC0000 - 0x77DFF000 	C:\WINNT\system32\ADVAPI32.dll
0x77F00000 - 0x77F5E000 	C:\WINNT\system32\KERNEL32.dll
0x77E70000 - 0x77EC4000 	C:\WINNT\system32\USER32.dll
0x77ED0000 - 0x77EFC000 	C:\WINNT\system32\GDI32.dll
0x77E10000 - 0x77E67000 	C:\WINNT\system32\RPCRT4.dll
0x78000000 - 0x78040000 	C:\WINNT\system32\MSVCRT.dll
0x10000000 - 0x10018000 	C:\WINNT\System32\NVDESK32.DLL
0x08000000 - 0x08273000 	d:\jdk1.3.1\jre\bin\server\jvm.dll
0x77FD0000 - 0x77FFA000 	C:\WINNT\System32\WINMM.dll
0x4FA00000 - 0x4FA77000 	C:\WINNT\System32\cwcmmsys.dll
0x50220000 - 0x50227000 	d:\jdk1.3.1\jre\bin\hpi.dll
0x503B0000 - 0x503BD000 	d:\jdk1.3.1\jre\bin\verify.dll
0x50250000 - 0x50266000 	d:\jdk1.3.1\jre\bin\java.dll
0x503C0000 - 0x503CD000 	d:\jdk1.3.1\jre\bin\zip.dll
0x0E6A0000 - 0x0E6C2000 	D:\testcases\NativeSEGV\NativeSEGV.dll
0x77920000 - 0x77942000 	C:\WINNT\System32\imagehlp.dll
0x72A00000 - 0x72A2D000 	C:\WINNT\System32\DBGHELP.dll
0x731B0000 - 0x731BA000 	C:\WINNT\System32\PSAPI.DLL

Local Time = Fri Dec 15 17:14:02 2000
Elapsed Time = 1
#
# The exception above was detected in native code outside the VM
#
# Java VM: Java HotSpot(TM) Server VM (internal-release mixed mode)
#
# An error report file has been saved as hs_err_pid102.log.
# Please refer to the file for further information.
#


Error Reporting

When the Java Virtual Machine (JVM) detects a crash in native code such as JNI code written by the developer or when the JVM itself crashes, it will print debug information about the crash. This error message normally will include information such as the function name, library name, source-file name and line number at which the error occurred. (Currently, information about file name and line number are available only available on Microsoft Windows platforms.) For an example of a message emitted by the error handler, see JNI Error example.

The information provided by the new error-reporting mechanism will allow developers to more easily and efficiently debug their applications. If an error message indicates a problem in the JVM code itself, it will allow a developer to submit a more accurate and helpful bug report.

Sometimes the error-reporting mechanism won't be able to determine the information that might be helpful in locating the source of a crash. To get the most out of the error handler, developers should be aware of the following guidelines and limitations.

Compile in debug mode

In some circumstances, the error-reporting mechanism won't be able to determine symbol names. The most common reason for this is that the binary code that crashed was not compiled in debug mode and therefore doesn't have symbol tables. Developers should compile their code in debug mode to ensure that it contains the necessary debug information. In Visual Studio, for example, this means choosing "Debug" rather than "Release" as the project's build mode. When using gcc or cc on Linux or on the Solaris operating environment, compile using the -g command-line option.

Non-exported functions

Even without debug information in the binary code, the error handler can still print the function name of the crash site. However, the function name might not be correct if the problematic function is not "exported" from the dynamic library. On Linux and Solaris, all functions are exported except those declared static. On Microsoft Windows platforms, no functions are exported unless explicitly declared so (using JNIEXPORT or __declspec(dllexport)).

Visual Studio limitation on Windows 98 and Windows NT

On Windows 98 and Windows NT platforms, the error handler uses the system's imagehlp.dll file to help determine the function name, source file, and line number of a crash site. (Windows 2000 and Windows ME use two files, imagehlp.dll and debughlp.dll to perform this task.) However, the imagehlp.dll file in Windows 98 and Windows NT does not work well with binary code and DLLs generated by Visual Studio 6.0.

This problem may cause the error handler to generate error messages with incorrect information about the function name, source file and line number of the crash site, though other information in the error message will be correct.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Contents | Previous | Next Java Management Extensions (JMX) Technology Tutorial

Chapter 2

Essentials of the JMX API

This chapter introduces the fundamental notion of the Java Management Extensions (JMX) API, namely managed beans, or MBeans.

An MBean is a managed Java object, similar to a JavaBeanTM, that follows the design patterns set forth in the instrumentation level of the JMX specification. An MBean can represent a device, an application, or any resource that needs to be managed. MBeans expose a management interface: a set of readable and/or writable attributes and a set of invokable operations, along with a self-description. The management interface does not change throughout the life of an MBean instance. MBeans can also emit notifications when certain defined events occur.

The JMX specification defines four types of MBean: standard MBeans, dynamic MBeans, open MBeans and model MBeans. The examples in this chapter demonstrate the simplest type of MBean, namely standard MBeans.

Standard MBeans

A standard MBean is defined by writing a Java interface called SomethingMBean and a Java class called Something that implements that interface. Every method in the interface defines either an attribute or an operation in the MBean. By default every method defines an operation. Attributes and operations are simply methods which follow certain design patterns. A standard MBean is composed of the MBean interface which lists the methods for all exposed attributes and operations, and the class which implements this interface and provides the functionality of the instrumented resource.

The following sections dissect an example standard MBean, and a simple JMX agent that manages the MBean. The code samples are taken from the directory work_dir/jmx_examples/Essential/com/example/mbeans.

MBean Interface

An example of a very basic MBean interface, named HelloMBean, is shown in CODE EXAMPLE 2-1.

CODE EXAMPLE 2-1 Example MBean Interface, HelloMBean

package com.example.mbeans;

public interface HelloMBean {

    public void sayHello();
    public int add(int x, int y);

    public String getName();

    public int getCacheSize();
    public void setCacheSize(int size);
}

As stated previously, by convention an MBean interface takes the name of the Java class that implements it, with the suffix MBean added. So, in this case, the interface is called HelloMBean. The Hello class that implements this interface is described in Section "MBean Implementation".

According to the JMX specification, an MBean interface consists of named and typed attributes that are readable and possibly writable, and named and typed operations that can be invoked by the applications that are managed by the MBean. The HelloMBean interface shown in CODE EXAMPLE 2-1, declares two operations: the Java methods add() and sayHello().

Of the two attributes that are declared by HelloMbean, Name is a read-only string, and CacheSize is an integer that can be both read and written. Getter and setter methods are declared, to allow the managed application to access and possibly change the attribute values. As defined by the JMX specification, a getter is any public method whose name begins with get and which does not return void. A getter enables a manager to read the value of the attribute, whose type is that of the returned object. A setter is any public method whose name begins with set and which takes a single parameter. A setter enables a manager to write a new value in the attribute, whose type is the same as that of the parameter.

The implementation of these operations and attributes is shown in the following section.

MBean Implementation

The Hello class shown in CODE EXAMPLE 2-1 implements HelloMBean.

CODE EXAMPLE 2-1 Example MBean Implementation Class, Hello

package com.example.mbeans;

public class Hello implements HelloMBean {
    public void sayHello() {
        System.out.println("hello, world");
    }

    public int add(int x, int y) {
        return x + y;
    }

    public String getName() {
        return this.name;
    }

    public int getCacheSize() {
        return this.cacheSize;
    }

    public synchronized void setCacheSize(int size) {
        this.cacheSize = size;

        System.out.println("Cache size now " + this.cacheSize);
    }

    private final String name = "Reginald";
    private int cacheSize = DEFAULT_CACHE_SIZE;
    private static final int DEFAULT_CACHE_SIZE = 200;
}

The straightforward Java class Hello provides the definitions of the operations and attributes declared by HelloMBean. As you can see, the sayHello() and add() operations are extremely simple, but real-life operations can be as simple or as sophisticated as you like.

Methods to get the Name attribute and to get and set the cacheSize attribute are also defined. In this example, the Name attribute value never changes, but in a real scenario it might change as the managed resource runs. For example, the attribute might represent statistics such as uptime or memory usage. Here, it is merely the name “Reginald”.

Calling the setCacheSize method allows you to alter the cacheSize attribute from its declared default value of 200. In reality, changing the cacheSize attribute could require other operations to be performed, such as discarding entries or allocating new ones. This example merely prints a message to confirm that the cache size has changed, but more sophisticated operations could be defined in the place of the simple call to println().

With the simple Hello MBean and its interface thus defined, they can now be used to manage the resource they represent, as shown in the following section.

Managing a Resource

As presented in the Java Management Extensions (JMX) Technology Overview, once a resource has been instrumented by MBeans, the management of that resource is performed by a JMX agent.

The core component of a JMX agent is the MBean server, a managed object server in which MBeans are registered (see the API documentation for the MBeanServer interface for details of the MBean server implementation). A JMX agent also includes a set of services to manage MBeans.

CODE EXAMPLE 2-1 presents a basic JMX agent, named Main.

CODE EXAMPLE 2-1 Creating a JMX Agent

package com.example.mbeans;

import java.lang.management.*;
import javax.management.*;

public class Main {

   public static void main(String[] args) throws Exception {

      MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

      ObjectName name = new ObjectName("com.example.mbeans:type=Hello");

      Hello mbean = new Hello();

      mbs.registerMBean(mbean, name);

      System.out.println("Waiting forever...");
      Thread.sleep(Long.MAX_VALUE);
   }
}

The JMX agent Main begins by obtaining any MBean server that is running on the platform, by calling the getPlatformMBeanServer() method of the java.lang.management.ManagementFactory class. If there is no MBean server already running on the platform, then getPlatformMBeanServer() creates one automatically by calling the JMX method MBeanServerFactory.createMBeanServer(). The MBeanServer instance obtained by Main is named mbs.

Next, Main defines an object name for the MBean instance it will create. Every JMX MBean must have an object name. The object name is an instance of the JMX class ObjectName, and must conform to the syntax defined by the JMX specification, namely it must comprise a domain, and a list of key-properties (see the API documentation for the ObjectName class for details of this syntax). In the object name defined by Main, name, the domain is com.example.mbeans (the package in which the example MBeans are contained) and the key-property declares that this object is of the type Hello.

An instance of a Hello object is created, named mbean. This Hello object is itself an instance of the MBean Hello that was defined in Section "MBean Implementation".

The Hello object named mbean is then registered as an MBean in the MBean server mbs with the object name name, by passing the object and the object name into a call to the JMX method MBeanServer.registerMBean().

With the Hello MBean registered in the MBean server, Main will simply wait for management operations to be performed on Hello. In the scope of this example, these management operations are invoking sayHello(), and add(), and getting and setting the attribute values.

Running the Standard MBean Example

Having examined the example classes, you can now run the example. The Java Platform, Standard Edition comes with a management and monitoring console, named JConsole, that is used to interact with the MBean in this example. JConsole is located in JavaSE_HOME/bin/jconsole, in which JavaSE_HOME is the installation directory of the Java Platform, Standard Edition (Java SE platform).

To run the example, follow the steps below, or see the README file:

  2. If you have not done so already, open work_dir/jmx_examples/Essential.

    $ cd work_dir/jmx_examples/Essential

  3. Compile the example Java classes.

    $ javac com/example/mbeans/*.java

  4. Start the Main application.

    $ java com.example.mbeans.Main

    You will see confirmation that Main is waiting for something to happen.

  5. Start JConsole in a different terminal window on the same machine.

    $ jconsole

    You will see the JConsole tool open, presenting a list of running JMX agents that you can connect to.

  6. Select com.example.mbeans.Main from the list in the “New Connection” window, and click on “Connect”.

    You will see a summary of your platform’s current activity.

  7. Click on the “MBeans” tab.

    This panel shows you all the MBeans currently registered in the MBean server.

  8. In the left-hand frame, expand the com.example.mbeans node in the MBean tree.

    You will see the example MBean Hello, that was created and registered by Main. If you click on Hello, you will see its associated Attributes and Operations nodes in the MBean tree.

  9. Click on the Hello MBean node in the MBean tree.

    The Hello MBean’s metadata and its associated Descriptor will be displayed.

  10. Click on the Attributes node of the Hello MBean in the MBean tree.

    This displays the MBean attributes that were defined by the Hello class.

  11. Change the value of the CacheSize attribute to 150

    In the terminal window in which you started Main, you will see confirmation of this change of attribute.

  12. Click on the Operations node of the Hello MBean in the MBean tree.

    Here you will see the two operations declared by the Hello MBean, sayHello() and add().

  13. Invoke the sayHello() operation, by clicking on the sayHello button.

    A JConsole dialogue box will inform you that the method was invoked successfully, and you will see the message “hello, world” in the terminal window in which Main is running.

  14. Provide two integers for the add() operation to add up, and click on the add button.

    You will be informed of the answer in a JConsole dialogue box.

  15. Click on “Connection” and then “Exit”, to exit JConsole.

Sending Notifications

MBeans can generate notifications, for example to signal a state change, a detected event, or a problem.

For an MBean to generate notifications, it must implement the interface NotificationBroadcaster, or its subinterface NotificationEmitter. All you need to do to send a notification is to construct an instance of the class javax.management.Notification or a subclass (such as AttributeChangedNotification), and pass it to NotificationBroadcasterSupport.sendNotification.

Every notification has a source. The source is the object name of the MBean that emitted the notification.

Every notification has a sequence number. This number can be used to order notifications coming from the same source when order matters and there is a danger of the notifications being handled in the wrong order. It is all right for the sequence number to be zero, but it is better for it to increment for each notification from a given MBean.

There is an example of a standard MBean that emits notifications in the directory work_dir/jmx_examples/Notification/com/example/mbeans. This example is essentially the same as the example seen in Section "Standard MBeans", except that the Hello MBean implements the NotificationBroadcaster interface.

NotificationBroadcaster Interface

As stated above, the only difference between this example and the one presented in Section "Standard MBeans" is the fact that the MBean implementation allows for the sending of notifications.

Notifications are activated by implementing the NotificationBroadcaster interface, as shown in CODE EXAMPLE 2-1.

CODE EXAMPLE 2-1 Implementing MBean Notifications

package com.example.mbeans;

import javax.management.*;

public class Hello
        extends NotificationBroadcasterSupport implements HelloMBean {

    public void sayHello() {
        System.out.println("hello, world");
    }

    public int add(int x, int y) {
        return x + y;
    }

    public String getName() {
        return this.name;
    }

    public int getCacheSize() {
        return this.cacheSize;
    }

    public synchronized void setCacheSize(int size) {
        int oldSize = this.cacheSize;
        this.cacheSize = size;

        System.out.println("Cache size now " + this.cacheSize);

        Notification n =
            new AttributeChangeNotification(this,
                                            sequenceNumber++,
                                            System.currentTimeMillis(),
                                            "CacheSize changed",
                                            "CacheSize",
                                            "int",
                                            oldSize,
                                            this.cacheSize);

        sendNotification(n);
    }

    @Override
    public MBeanNotificationInfo[] getNotificationInfo() {
        String[] types = new String[] {
            AttributeChangeNotification.ATTRIBUTE_CHANGE
        };
        String name = AttributeChangeNotification.class.getName();
        String description = "An attribute of this MBean has changed";
        MBeanNotificationInfo info =
            new MBeanNotificationInfo(types, name, description);
        return new MBeanNotificationInfo[] {info};
    }

    private final String name = "Reginald";
    private int cacheSize = DEFAULT_CACHE_SIZE;
    private static final int DEFAULT_CACHE_SIZE = 200;

    private long sequenceNumber = 1;
}

As you can see in CODE EXAMPLE 2-1, this Hello MBean implementation extends the NotificationBroadcasterSupport class, that itself implements the NotificationEmitter interface.

The operations and attributes are set in the same way as before, with the only exception that the cacheSize attribute’s setter method now defines a new value oldSize, which records the cacheSize attribute’s value prior to the set operation.

The notification is constructed from an instance, n, of the JMX class AttributeChangeNotification, which extends javax.management.Notification. The notification is constructed within the definition of the setCacheSize() method, from the following information, that is passed to AttributeChangeNotification as parameters:

  • The object name of the source of the notification, namely the Hello MBean, represented simply by this
  • A sequence number, which in this example is a long named sequenceNumber, that is set at 1 and that increases incrementally
  • A timestamp
  • The content of the notification message
  • The name of the attribute that has changed, in this case cacheSize
  • The type of attribute that has changed
  • The old attribute value, in this case oldSize
  • The new attribute value, in this case this.cacheSize

The notification n is then passed to the NotificationBroadcasterSupport.sendNotification() method.

Finally, the MBeanNotification is defined to describe the characteristics of the different notification instances emitted by the MBean for a given Java class of notification, which in this case is AttributeChangeNotification notifications.

The MBean interface, HelloMBean, and the JMX agent Main are identical to those used in the previous example.

Running the MBean Notification Example

Having examined the example classes, you can now run the example. This example again uses JConsole to interact with the Hello MBean.To run the example, follow the steps below, or see the README file:

  2. If you have not done so already, open work_dir/jmx_examples/Notification.

    $ cd work_dir/jmx_examples/Notification

  3. Compile the example Java classes.

    $ javac com/example/mbeans/*.java

  4. Start the Main application.

    $ java com.example.mbeans.Main

    You will see confirmation that Main is waiting for something to happen.

  5. Start JConsole in a different terminal window on the same machine.

    $ jconsole

    You will see the JConsole tool open, presenting a list of running JMX agents that you can connect to.

  6. Select com.example.mbeans.Main from the list in the “New Connection” window, and click on “Connect”.

    You will see a summary of your platform’s current activity.

  7. Click on the “MBeans” tab.

    This panel shows you all the MBeans currently registered in the MBean server.

  8. In the left-hand frame, expand the com.example.mbeans node in the MBean tree.

    You will see the example MBean Hello, that was created and registered by Main. If you click on Hello, you will see its associated Attributes, Operations and Notifications nodes in the MBean tree.

  9. Click on the Hello MBean node in the MBean tree.

    This displays the MBean’s metadata and its associated Descriptor.

  10. Click on the Notifications node of the Hello MBean in the MBean tree.

    You will see that the panel is blank.

  11. Click on the “Subscribe” button.

    The current number of notifications received (0), will be displayed in the Notifications node label.

  12. Click on the Attributes node of the Hello MBean in the MBean tree, and change the value of the CacheSize attribute to 150

    In the terminal window in which you started Main, you will see confirmation of this change of attribute. You will also see that the number of notifications received displayed in the Notifications node has changed to 1.

  13. Click on the Notifications node of the Hello MBean in the MBean tree again.

    You will see the details of the notification that was sent.

  14. Click on “Connection” and then “Exit”, to exit JConsole.

Introducing MXBeans

An MXBean is a new type of MBean that provides a simple way to code an MBean that only references a pre-defined set of types. In this way, you can be sure that your MBean will be usable by any client, including remote clients, without any requirement that the client have access to model-specific classes representing the types of your MBeans. MXBeans provide a convenient way to bundle related values together without requiring clients to be specially configured to handle the bundles.

In the same way as for standard MBeans, an MXBean is defined by writing a Java interface called Something MXBean and a Java class that implements that interface. However, unlike standard MBeans, MXBeans do not require the Java class to be called Something. Every method in the interface defines either an attribute or an operation in the MXBean. The annotation @MXBean can be also used to annotate the Java interface instead of requiring the interface’s name to be followed by the MXBean suffix.

MXBeans provide a convenient way to bundle related values together in an MBean without requiring clients to be specially configured to handle the bundles when interacting with that MBean. MXBeans already existed in the Java 2 Platform, Standard Edition (J2SE) 5.0, in the package java.lang.management. With the Java SE 6 platform, users can now define their own MXBeans, in addition to the standard set defined in java.lang.management.

The key idea behind MXBeans is that types such as java.lang.management.MemoryUsage that are referenced in the MXBean interface, java.lang.management.MemoryMXBean in this case, are mapped into a standard set of types, the so-called Open Types that are defined in the package javax.management.openmbean. The exact mapping rules appear in the MXBean specification, but to oversimplify we could say that simple types like int or String are unchanged, while complex types like MemoryUsage get mapped to the standard type CompositeDataSupport.

The operation of MXBeans is demonstrated by example programs that you will find in the directory work_dir/jmx_examples/MXBean/com/example/mxbeans after you have downloaded and unzipped the jmx_examples.zip file. The MXBean example contains the following files:

  • QueueSamplerMXBean interface.
  • QueueSampler class that implements the MXBean interface.
  • QueueSample Java type returned by the getQueueSample() method in the MXBean interface.
  • Main, the program that sets up and runs the example.

The MXBean example performs the following actions.

  • Defines a simple MXBean that manages a resource of type Queue<String>.
  • Declares a getter, getQueueSample, in the MXBean that takes a snapshot of the queue when invoked and returns a Java class QueueSample that bundles the following values together:
  • The time the snapshot was taken.
  • The queue size.
  • The head of the queue at that given time.
  • Registers the MXBean in an MBean server.

QueueSamplerMXBean Interface

CODE EXAMPLE 2-1 shows the code of the sample QueueSamplerMXBean interface.

CODE EXAMPLE 2-1 QueueSamplerMXBean interface

package com.example.mxbeans;

public interface QueueSamplerMXBean {
    public QueueSample getQueueSample();
    public void clearQueue();
}

As you can see, you declare an MXBean interface in exactly the same way as you declare a standard MBean. The QueueSamplerMXBean interface declares two operations, getQueueSample and clearQueue.

QueueSampler Class

The QueueSampler class implements the QueueSamplerMXBean interface, as shown in CODE EXAMPLE 2-1.

CODE EXAMPLE 2-1 QueueSampler Class
package com.example.mxbeans;

import java.util.Date;
import java.util.Queue;

public class QueueSampler implements QueueSamplerMXBean {

    private Queue<String> queue;

    public QueueSampler(Queue<String> queue) {
       this.queue = queue;
    }

    public QueueSample getQueueSample() {
        synchronized (queue) {
            return new QueueSample(new Date(), queue.size(), queue.peek());
        }
    }

    public void clearQueue() {
        synchronized (queue) {
            queue.clear();
        }
    }
}

The MXBean operations getQueueSample() and clearQueue() declared by the MXBean interface are defined in QueueSampler. The getQueueSample() operation simply returns an instance of the QueueSample Java type, created with the values returned by the java.util.Queue methods peek() and size() and an instance of java.util.Date.

QueueSample Class

The QueueSample instance returned by QueueSampler is defined in the QueueSample class shown in CODE EXAMPLE 2-1.

CODE EXAMPLE 2-1 QueueSample Class
package com.example.mxbeans;

import java.beans.ConstructorProperties;
import java.util.Date;

public class QueueSample {

    private final Date date;
    private final int size;
    private final String head;

    @ConstructorProperties({"date", "size", "head"})
    public QueueSample(Date date, int size, String head) {
        this.date = date;
        this.size = size;
        this.head = head;
    }

    public Date getDate() {
        return date;
    }

    public int getSize() {
        return size;
    }

    public String getHead() {
        return head;
    }
}

In QueueSample class, the MXBean framework calls all the getters in QueueSample to convert the given instance into a CompositeData and uses the @ConstructorProperties annotation to reconstruct a QueueSample instance from a CompositeData.

Creating and Registering the MXBean in the MBean Server

Having defined an MXBean interface and the class that implements it, as well as the Java type that is returned, the MXBean must now be created and registered in an MBean server. These actions are performed by the example class Main.

CODE EXAMPLE 2-1 MXBean example Main class
package com.example.mxbeans;

import java.lang.management.ManagementFactory;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import javax.management.MBeanServer;
import javax.management.ObjectName;

public class Main {

    public static void main(String[] args) throws Exception {
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

        ObjectName name =
                new ObjectName("com.example.mxbeans:type=QueueSampler");

        Queue<String> queue = new ArrayBlockingQueue<String>(10);
        queue.add("Request-1");
        queue.add("Request-2");
        queue.add("Request-3");
        QueueSampler mxbean = new QueueSampler(queue);

        mbs.registerMBean(mxbean, name);

        System.out.println("Waiting...");
        Thread.sleep(Long.MAX_VALUE);
    }
}

The Main class gets the platform MBean server, creates an object name for the MXBean QueueSampler, creates a Queue instance for the QueueSampler MXBean to process, and feeds this Queue instance to a newly created QueueSampler MXBean. The MXBean is then registered in the MBean server in exactly the same way as a standard MBean.

Running the MXBean Example

To run the example, follow the steps below, or see the README file:

  2. If you have not done so already, open work_dir/jmx_examples/MXBean.

    $ cd work_dir/jmx_examples/MXBean

  3. Compile the example Java classes.

    $ javac com/example/mxbeans/*.java

  4. Start the Main application.

    $ java com.example.mxbeans.Main

    You will see confirmation that Main is waiting for something to happen.

  5. Start JConsole in a different terminal window on the same machine.

    $ jconsole

    You will see the JConsole tool open, presenting a list of running JMX agents that you can connect to.

  6. Select com.example.mxbeans.Main from the list in the “New Connection” window, and click on “Connect”.

    You will see a summary of your platform’s current activity.

  7. Click on the “MBeans” tab.

    This panel shows you all the MBeans currently registered in the MBean server.

  8. In the left-hand frame, expand the com.example.mxbeans node in the MBean tree.

    You will see the example MBean QueueSampler, that was created and registered by Main. If you click on QueueSampler, you will see its associated Attributes and Operations nodes in the MBean tree.

  9. Select the Attributes node.

    You will see the QueueSample attribute appear in the right-hand pane, with its value of javax.management.openmbean.CompositeDataSupport.

  10. Double-click on the CompositeDataSupport value.

    You can see the QueueSample values date, head and size because the MXBean framework has converted the QueueSample instance into CompositeData. If you had defined QueueSampler as a Standard MBean rather than as an MXBean, JConsole would not have found the QueueSample class because it would not be in its class path. If QueueSampler had been a standard MBean, you would have received a ClassNotFoundException when retrieving the QueueSample attribute value. This demonstrates the usefulness of using MXBeans when connecting to JMX agents through generic JMX clients, like JConsole.

  11. Select the Operations node.

    You will see a button to invoke the clearQueue operation.

  12. Click on the clearQueue button.

    You will be informed that the method was invoked successfully.

  13. Select the Attributes node again and double click on the CompositeDataSupport value.

    The queue has been reset now.

  14. Click on “Connection” and then “Exit”, to exit JConsole.

In this example JConsole has been used as the JMX client but if you were to access your MXBean programmatically in a JMX client you write yourself, then you could do so in one of two ways:

  • Generically, using the following code.
CODE EXAMPLE 2-1 Accessing an MXBean directly

MBeanServer mbs = ...whatever...;
ObjectName name = new ObjectName("com.example.mxbeans:type=QueueSampler");
CompositeData queueSample = (CompositeData) mbs.getAttribute(name,
                             "QueueSample");
int size = (Integer) queueSample.get("size");
  • Via a proxy, using the following code.
CODE EXAMPLE 2-2 Accessing an MXBean via a proxy

MBeanServer mbs = ...whatever...;
ObjectName name = new ObjectName("com.example.mxbeans:type=QueueSampler");
QueueSamplerMXBean proxy = JMX.newMXBeanProxy(mbs, name,
                                              QueueSamplerMXBean.class);
QueueSample queueSample = proxy.getQueueSample();
int size = queueSample.getSize();

CODE EXAMPLE 2-2 uses the newMXBeanProxy method to create the MXBean proxy. An equivalent method, newMBeanProxy, exists to create proxies for other types of MBeans. The newMBeanProxy and newMXBeanProxy methods are used in exactly the same way.

MBean Descriptors

Descriptors allow you to give additional information about MBeans to management clients. For example, a Descriptor on an MBean attribute might say what units it is measured in, or what its minimum and maximum possible values are. As of Java SE 6, Descriptors are an integrated part of the JMX API and are available in all types of MBeans.

Descriptors give you a convenient way to attach arbitrary extra metadata to your MBeans. Descriptors have always existed in the JMX API, but until Java SE 6 they were only available in conjunction with Model MBeans.

For most constructors in the classes MBean*Info (MBeanInfo, MBeanAttributeInfo, and so on), a parallel constructor exists with the same parameters plus an additional javax.management.Descriptor parameter. The same is true for OpenMBean*InfoSupport. The MBean*Info and OpenMBean*InfoSupport classes contain a getDescriptor() method.

Open MBeans return information about default and legal values from the getDefaultValue(), getLegalValues(), getMaxValue(), getMinValue() methods of OpenMBeanParameterInfo and OpenMBeanAttributeInfo. This information is now also present in the corresponding Descriptors, and other types of MBean can also return the information in their Descriptors.

MBean Descriptors are demonstrated in the example classes you will find in the directory work_dir/jmx_examples/Descriptors/com/example/mxbeans after you have downloaded and unzipped the jmx_examples.zip file. The MBean Descriptor example contains the following files.

  • Author, an annotation the supplies the name of the author of the MBean interface.
  • DisplayName, an annotation that supplies a display name for methods in the MBean interface.
  • Main, the program that sets up and runs the example.
  • QueueSamplerMXBean interface.
  • QueueSampler class that implements the MXBean interface.
  • QueueSample Java type returned by the getQueueSample() method in the MXBean interface.
  • Version, an annotation that supplies the current version of the MBean interface.

The QueueSampler MXBean in this example basically performs the same actions as the MXBean example presented in Chapter 2, "Introducing MXBeans", except with the addition of MBean Descriptors. This example shows how the DescriptorKey meta-annotation can be used to add new descriptor items to the Descriptors for a standard MBean (or an MXBean) via annotations in the standard MBean (or MXBean) interface.

DescriptorKey Annotations

A new annotation DescriptorKey can be used to add information to the Descriptors for a standard MBean (or MXBean) via annotations in the Standard MBean (or MXBean) interface. This makes it possible for a tool that generates standard MBeans from an existing management model to include information from the model in the generated MBean interfaces, rather than in separate files.

CODE EXAMPLE 2-1 shows the definition of the annotation Author.

CODE EXAMPLE 2-1 Author Annotation

package com.example.mxbeans;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.management.DescriptorKey;

@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Author {
    @DescriptorKey("author")
    String value();
}

This annotation supplies the name of the creator of the MBean interface. A new field author will be added to the MBeanInfo Descriptor with the value defined by the @Author annotation. The files Version and DisplayName define annotations of those names in exactly the same way as for Author above. In each of Version and DisplayName, the @DescriptorKey value is “version” and “displayname” respectively.

In the case of Version, a new field version will be added to the MBeanInfo Descriptor with the value defined by the @Version annotation.

For DisplayName, new field displayName will be added to the MBeanAttributeInfo Descriptor or the MBeanOperationInfo Descriptor with the value defined by the @DisplayName annotation depending on whether the annotated method is a getter/setter or an operation, respectively.

Using MBean Descriptors

The QueueSamplerMXBean interface used in this example is slightly different from the one used in the MXBeans example, in as much as it implements MBean Descriptors to publish some of its information.

CODE EXAMPLE 2-1 QueueSamplerMXBean with Descriptors.

package com.example.mxbeans;

@Author("Mr Bean")
@Version("1.0")
public interface QueueSamplerMXBean {
    @DisplayName("GETTER: QueueSample")
    public QueueSample getQueueSample();
    @DisplayName("OPERATION: clearQueue")
    public void clearQueue();
}

Here, you see that the @Author annotation is set to Mr. Bean, the @Version annotation is set to 1.0, and the @DisplayName is set to the names either of the attribute QueueSample or the operation clearQueue.

Running the MBean Descriptors Example

To run the example, follow the steps below, or see the README file:

  2. If you have not done so already, open work_dir/jmx_examples/Descriptors.

    $ cd work_dir/jmx_examples/Descriptors

  3. Compile the example Java classes.

    $ javac com/example/mxbeans/*.java

  4. Start the Main application.

    $ java com.example.mxbeans.Main

    You will see confirmation that Main is waiting for something to happen.

  5. Start JConsole in a different terminal window on the same machine.

    $ jconsole

    You will see the JConsole tool open, presenting a list of running JMX agents that you can connect to.

  6. Select com.example.mxbeans.Main from the list in the “New Connection” window, and click on “Connect”.

    You will see a summary of your platform’s current activity.

  7. Click on the “MBeans” tab.

    This panel shows you all the MBeans currently registered in the MBean server.

  8. In the left-hand frame, expand the com.example.mxbeans node in the MBean tree.

    You will see the example MBean QueueSampler, that was created and registered by Main. If you click on QueueSampler, you will see its associated Attributes and Operations nodes in the MBean tree.You will also see the fields author and version in the MBeanInfo Descriptor table.

  9. Expand the Attributes and Operations nodes under the QueueSampler MBean node.

    You will see the individual Attributes and Operations.

  10. Select the QueueSample node.

    You will see the field displayName in the MBeanAttributeInfo Descriptor table.

  11. Select the clearQueue node.

    You will see the field displayName in the MBeanOperationInfo Descriptor table.

  12. Click on “Connection” and then “Exit”, to exit JConsole.

Contents | Previous | Next

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface org.w3c.dom.events.Event (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.events.Event

  • Packages that use Event
    Package Description
    org.w3c.dom.events
    org.w3c.dom.ls

    • Uses of Event in org.w3c.dom.events

      Subinterfaces of Event in org.w3c.dom.events
      Modifier and Type Interface and Description
      interface  MouseEvent
      The MouseEvent interface provides specific contextual information associated with Mouse events.
      interface  MutationEvent
      The MutationEvent interface provides specific contextual information associated with Mutation events.
      interface  UIEvent
      The UIEvent interface provides specific contextual information associated with User Interface events.
      Methods in org.w3c.dom.events that return Event
      Modifier and Type | Method and Description
      Event | DocumentEvent.createEvent(String eventType)
      Methods in org.w3c.dom.events with parameters of type Event
      Modifier and Type Method and Description
      boolean EventTarget.dispatchEvent(Event evt)
      This method allows the dispatch of events into the implementations event model.
      void EventListener.handleEvent(Event evt)
      This method is called whenever an event occurs of the type for which the EventListener interface was registered.

    • Uses of Event in org.w3c.dom.ls

      Subinterfaces of Event in org.w3c.dom.ls
      Modifier and Type Interface and Description
      interface  LSLoadEvent
      This interface represents a load event object that signals the completion of a document load.
      interface  LSProgressEvent
      This interface represents a progress event object that notifies the application about progress as a document is parsed.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Class org.w3c.dom.events.EventException (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
org.w3c.dom.events.EventException

  • Packages that use EventException
    Package Description
    org.w3c.dom.events

    • Uses of EventException in org.w3c.dom.events

      Methods in org.w3c.dom.events that throw EventException
      Modifier and Type Method and Description
      boolean EventTarget.dispatchEvent(Event evt)
      This method allows the dispatch of events into the implementations event model.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.event.EventIterator (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.event.EventIterator

  • Packages that use EventIterator
    Package Description
    com.sun.jdi.event
    This package defines JDI events and event processing.

    • Uses of EventIterator in com.sun.jdi.event

      Methods in com.sun.jdi.event that return EventIterator
      Modifier and Type Method and Description
      EventIterator EventSet.eventIterator()
      Return an iterator specific to Event objects.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.events.EventListener (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.events.EventListener

  • Packages that use EventListener
    Package Description
    org.w3c.dom.events

    • Uses of EventListener in org.w3c.dom.events

      Methods in org.w3c.dom.events with parameters of type EventListener
      Modifier and Type Method and Description
      void EventTarget.addEventListener(String type, EventListener listener, boolean useCapture)
      This method allows the registration of event listeners on the event target.
      void EventTarget.removeEventListener(String type, EventListener listener, boolean useCapture)
      This method allows the removal of event listeners from the event target.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.event.EventQueue (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.event.EventQueue

  • Packages that use EventQueue
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of EventQueue in com.sun.jdi

      Methods in com.sun.jdi that return EventQueue
      Modifier and Type Method and Description
      EventQueue VirtualMachine.eventQueue()
      Returns the event queue for this virtual machine.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.request.EventRequest (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.request.EventRequest

  • Packages that use EventRequest
    Package Description
    com.sun.jdi.event
    This package defines JDI events and event processing.
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of EventRequest in com.sun.jdi.event

      Methods in com.sun.jdi.event that return EventRequest
      Modifier and Type | Method and Description
      EventRequest | Event.request()

    • Uses of EventRequest in com.sun.jdi.request

      Subinterfaces of EventRequest in com.sun.jdi.request
      Modifier and Type Interface and Description
      interface  AccessWatchpointRequest
      Request for notification when the contents of a field are accessed in the target VM.
      interface  BreakpointRequest
      Identifies a Location in the target VM at which execution should be stopped.
      interface  ClassPrepareRequest
      Request for notification when a class is prepared in the target VM.
      interface  ClassUnloadRequest
      Request for notification when a class is unloaded in the target VM.
      interface  ExceptionRequest
      Request for notification when an exception occurs in the target VM.
      interface  MethodEntryRequest
      Request for notification when a method is invoked in the target VM.
      interface  MethodExitRequest
      Request for notification when a method returns in the target VM.
      interface  ModificationWatchpointRequest
      Request for notification when a field is set.
      interface  MonitorContendedEnteredRequest
      Request for notification of a thread in the target VM entering a monitor after waiting for it to be released by another thread.
      interface  MonitorContendedEnterRequest
      Request for notification of a thread in the target VM attempting to enter a monitor already acquired by another thread.
      interface  MonitorWaitedRequest
      Request for notification when a thread in the target VM has finished waiting on a monitor object.
      interface  MonitorWaitRequest
      Request for notification when a thread in the target VM is about to wait on a monitor object.
      interface  StepRequest
      Request for notification when a step occurs in the target VM.
      interface  ThreadDeathRequest
      Request for notification when a thread terminates in the target VM.
      interface  ThreadStartRequest
      Request for notification when a thread starts execution in the target VM.
      interface  VMDeathRequest
      Request for notification when the target VM terminates.
      interface  WatchpointRequest
      Identifies a Field in the target VM being watched.
      Methods in com.sun.jdi.request with parameters of type EventRequest
      Modifier and Type Method and Description
      void EventRequestManager.deleteEventRequest(EventRequest eventRequest)
      Removes an eventRequest.
      Method parameters in com.sun.jdi.request with type arguments of type EventRequest
      Modifier and Type Method and Description
      void EventRequestManager.deleteEventRequests(List<? extends EventRequest> eventRequests)
      Removes a list of EventRequests.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.request.EventRequestManager (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.request.EventRequestManager

  • Packages that use EventRequestManager
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of EventRequestManager in com.sun.jdi

      Methods in com.sun.jdi that return EventRequestManager
      Modifier and Type Method and Description
      EventRequestManager VirtualMachine.eventRequestManager()
      Returns the event request manager for this virtual machine.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.event.EventSet (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.event.EventSet

  • Packages that use EventSet
    Package Description
    com.sun.jdi.event
    This package defines JDI events and event processing.

    • Uses of EventSet in com.sun.jdi.event

      Methods in com.sun.jdi.event that return EventSet
      Modifier and Type Method and Description
      EventSet EventQueue.remove()
      Waits forever for the next available event.
      EventSet EventQueue.remove(long timeout)
      Waits a specified time for the next available event.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.events.EventTarget (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.events.EventTarget

  • Packages that use EventTarget
    Package Description
    org.w3c.dom.events

    • Uses of EventTarget in org.w3c.dom.events

      Methods in org.w3c.dom.events that return EventTarget
      Modifier and Type Method and Description
      EventTarget Event.getCurrentTarget()
      Used to indicate the EventTarget whose EventListeners are currently being processed.
      EventTarget MouseEvent.getRelatedTarget()
      Used to identify a secondary EventTarget related to a UI event.
      EventTarget Event.getTarget()
      Used to indicate the EventTarget to which the event was originally dispatched.
      Methods in org.w3c.dom.events with parameters of type EventTarget
      Modifier and Type Method and Description
      void MouseEvent.initMouseEvent(String typeArg, boolean canBubbleArg, boolean cancelableArg, AbstractView viewArg, int detailArg, int screenXArg, int screenYArg, int clientXArg, int clientYArg, boolean ctrlKeyArg, boolean altKeyArg, boolean shiftKeyArg, boolean metaKeyArg, short buttonArg, EventTarget relatedTargetArg)
      The initMouseEvent method is used to initialize the value of a MouseEvent created through the DocumentEvent interface.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Legal Notices

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java™ IDL Examples License

See Legal Notices

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Example Applications

Below are two application examples:

  • Bound Properties: boundprop.exe
  • Calendar: cal.exe

Bound Properties

This application consists of an ActiveX container with two beans packaged as ActiveX controls: BoundPropTest, a JavaBeans button; and the JellyBean bean. The applications works because the button is registered as a listener with JellyBean. Every time the JellyBean is clicked, the button receives notification and code is called that changes the text on the button. Download the following resources for this application to set it up and run it: boundprop.exe, BoundPropTest.dll, and JellyBean.dll.

To run the application on your computer, copy BoundPropTest.dll and JellyBean.dll to <jre_home>\axbridge\bin on your computer. Register both .dll files with regsvr32.exe. Then execute boundprop.exe. You should see the following:

Calendar

The Calendar application is similar. It consists of an ActiveX container with an ActiveX control calendar and a JavaBean calendar. In this application, both components are registered with each other as listeners. Changes in one calendar are reflected in the other via change notification. Download the resources for this application to set it uo and run it: cal.exe and JCalendarPanel.dll. (Copy JCalendarPanel.dll to <jre_home>\axbridge\bin and register it; then execute cal.exe. You should see the following.

Sample calendar window

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.event.ExceptionEvent (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.event.ExceptionEvent

No usage of com.sun.jdi.event.ExceptionEvent
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.request.ExceptionRequest (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.request.ExceptionRequest

  • Packages that use ExceptionRequest
    Package Description
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of ExceptionRequest in com.sun.jdi.request

      Methods in com.sun.jdi.request that return ExceptionRequest
      Modifier and Type Method and Description
      ExceptionRequest EventRequestManager.createExceptionRequest(ReferenceType refType, boolean notifyCaught, boolean notifyUncaught)
      Creates a new disabled ExceptionRequest.
      Methods in com.sun.jdi.request that return types with arguments of type ExceptionRequest
      Modifier and Type Method and Description
      List<ExceptionRequest> EventRequestManager.exceptionRequests()
      Return an unmodifiable list of the enabled and disabled exception requests.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Java Object Serialization Specification: - Exceptions In Object Serialization

CONTENTS | PREV | NEXT Java Object Serialization Specification
version 6.0

Exceptions In Object Serialization

APPENDIX B

All exceptions thrown by serialization classes are subclasses of ObjectStreamException which is a subclass of IOException.

Exception | Description
ObjectStreamException | Superclass of all serialization exceptions.
InvalidClassException Thrown when a class cannot be used to restore objects for any of these reasons:
  • The class does not match the serial version of the class in the stream.
  • The class contains fields with invalid primitive data types.
  • The Externalizable class does not have a public no-arg constructor.
  • The Serializable class can not access the no-arg constructor of its closest non-Serializable superclass.
NotSerializableException | Thrown by a readObject or writeObject method to terminate serialization or deserialization.
StreamCorruptedException Thrown:
  • If the stream header is invalid.
  • If control information not found.
  • If control information is invalid.
  • JDK 1.1.5 or less attempts to call readExternal on a PROTOCOL_VERSION_2 stream.
NotActiveException

Thrown if writeObject state is invalid within the following ObjectOutputStream methods:

  • defaultWriteObject
  • putFields
  • writeFields

Thrown if readObject state is invalid within the following ObjectInputStream methods:

  • defaultReadObject
  • readFields
  • registerValidation
InvalidObjectException | Thrown when a restored object cannot be made valid.
OptionalDataException | Thrown by readObject when there is primitive data in the stream and an object is expected. The length field of the exception indicates the number of bytes that are available in the current block.
WriteAbortedException | Thrown when reading a stream terminated by an exception that occurred while the stream was being written.
CONTENTS | PREV | NEXT
Copyright © 2005, 2010, Oracle and/or its affiliates. All rights reserved.


Uses of Interface com.sun.mirror.declaration.ExecutableDeclaration (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.declaration.ExecutableDeclaration

  • Packages that use ExecutableDeclaration
    Package Description
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of ExecutableDeclaration in com.sun.mirror.declaration

      Subinterfaces of ExecutableDeclaration in com.sun.mirror.declaration
      Modifier and Type Interface and Description
      interface  AnnotationTypeElementDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in ExecutableElement.
      interface  ConstructorDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in ExecutableElement.
      interface  MethodDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in ExecutableElement.

    • Uses of ExecutableDeclaration in com.sun.mirror.util

      Methods in com.sun.mirror.util with parameters of type ExecutableDeclaration
      Modifier and Type Method and Description
      void SimpleDeclarationVisitor.visitExecutableDeclaration(ExecutableDeclaration d)
      Deprecated.
      Visits a method or constructor declaration.
      void DeclarationVisitor.visitExecutableDeclaration(ExecutableDeclaration d)
      Deprecated.
      Visits a method or constructor declaration.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.javadoc.ExecutableMemberDoc (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.javadoc.ExecutableMemberDoc

    • Uses of ExecutableMemberDoc in com.sun.javadoc

      Subinterfaces of ExecutableMemberDoc in com.sun.javadoc
      Modifier and Type Interface and Description
      interface  AnnotationTypeElementDoc
      Represents an element of an annotation type.
      interface  ConstructorDoc
      Represents a constructor of a java class.
      interface  MethodDoc
      Represents a method of a java class.
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.ExpressionStatementTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.ExpressionStatementTree

  • Packages that use ExpressionStatementTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of ExpressionStatementTree in com.sun.source.tree

      Methods in com.sun.source.tree that return types with arguments of type ExpressionStatementTree
      Modifier and Type | Method and Description
      List<? extends ExpressionStatementTree> | ForLoopTree.getUpdate()
      Methods in com.sun.source.tree with parameters of type ExpressionStatementTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitExpressionStatement(ExpressionStatementTree node, P p)

    • Uses of ExpressionStatementTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type ExpressionStatementTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitExpressionStatement(ExpressionStatementTree node, P p)
      R | SimpleTreeVisitor.visitExpressionStatement(ExpressionStatementTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.ExpressionTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.ExpressionTree

  • Packages that use ExpressionTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).

    • Uses of ExpressionTree in com.sun.source.tree

      Subinterfaces of ExpressionTree in com.sun.source.tree
      Modifier and Type Interface and Description
      interface  AnnotationTree
      A tree node for an annotation.
      interface  ArrayAccessTree
      A tree node for an array access expression.
      interface  AssignmentTree
      A tree node for an assignment expression.
      interface  BinaryTree
      A tree node for a binary expression.
      interface  CompoundAssignmentTree
      A tree node for compound assignment operator.
      interface  ConditionalExpressionTree
      A tree node for the conditional operator ? :.
      interface  ErroneousTree
      A tree node to stand in for a malformed expression.
      interface  IdentifierTree
      A tree node for an identifier expression.
      interface  InstanceOfTree
      A tree node for an 'instanceof' expression.
      interface  LiteralTree
      A tree node for a literal expression.
      interface  MemberSelectTree
      A tree node for a member access expression.
      interface  MethodInvocationTree
      A tree node for a method invocation expression.
      interface  NewArrayTree
      A tree node for an expression to create a new instance of an array.
      interface  NewClassTree
      A tree node to declare a new instance of a class.
      interface  ParenthesizedTree
      A tree node for a parenthesized expression.
      interface  TypeCastTree
      A tree node for a type cast expression.
      interface  UnaryTree
      A tree node for postfix and unary expressions.
      Methods in com.sun.source.tree that return ExpressionTree
      Modifier and Type | Method and Description
      ExpressionTree | WhileLoopTree.getCondition()
      ExpressionTree | IfTree.getCondition()
      ExpressionTree | ForLoopTree.getCondition()
      ExpressionTree | DoWhileLoopTree.getCondition()
      ExpressionTree | ConditionalExpressionTree.getCondition()
      ExpressionTree | AssertTree.getCondition()
      ExpressionTree | AssertTree.getDetail()
      ExpressionTree | NewClassTree.getEnclosingExpression()
      ExpressionTree | UnaryTree.getExpression()
      ExpressionTree | TypeCastTree.getExpression()
      ExpressionTree | ThrowTree.getExpression()
      ExpressionTree | SynchronizedTree.getExpression()
      ExpressionTree | SwitchTree.getExpression()
      ExpressionTree | ReturnTree.getExpression()
      ExpressionTree | ParenthesizedTree.getExpression()
      ExpressionTree | MemberSelectTree.getExpression()
      ExpressionTree | InstanceOfTree.getExpression()
      ExpressionTree | ExpressionStatementTree.getExpression()
      ExpressionTree | EnhancedForLoopTree.getExpression()
      ExpressionTree | CompoundAssignmentTree.getExpression()
      ExpressionTree | CaseTree.getExpression()
      ExpressionTree | AssignmentTree.getExpression()
      ExpressionTree | ArrayAccessTree.getExpression()
      ExpressionTree | ConditionalExpressionTree.getFalseExpression()
      ExpressionTree | NewClassTree.getIdentifier()
      ExpressionTree | ArrayAccessTree.getIndex()
      ExpressionTree | VariableTree.getInitializer()
      ExpressionTree | BinaryTree.getLeftOperand()
      ExpressionTree | MethodInvocationTree.getMethodSelect()
      ExpressionTree | CompilationUnitTree.getPackageName()
      ExpressionTree | BinaryTree.getRightOperand()
      ExpressionTree | ConditionalExpressionTree.getTrueExpression()
      ExpressionTree | CompoundAssignmentTree.getVariable()
      ExpressionTree | AssignmentTree.getVariable()
      Methods in com.sun.source.tree that return types with arguments of type ExpressionTree
      Modifier and Type | Method and Description
      List<? extends ExpressionTree> | NewClassTree.getArguments()
      List<? extends ExpressionTree> | MethodInvocationTree.getArguments()
      List<? extends ExpressionTree> | AnnotationTree.getArguments()
      List<? extends ExpressionTree> | NewArrayTree.getDimensions()
      List<? extends ExpressionTree> | NewArrayTree.getInitializers()
      List<? extends ExpressionTree> | MethodTree.getThrows()
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


extcheck - Jar conflict detection utility

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

extcheck - A utility to detect jar conflicts

extcheck detects version conflicts between a target jar file and currently installed extension jar files.

SYNOPSIS

extcheck [ -verbose ] targetfile.jar

DESCRIPTION

The extcheck utility checks a specified Jar file for title and version conflicts with any extensions installed in the Java™ SDK. Before installing an extension, you can use this utility to see if the same or a more recent version of the extension is already installed.

The extcheck utility compares the Specification-title and Specification-version headers in the manifest of targetfile.jar file against the corresponding headers in all Jar files currently installed in the extension directory. (The extension directory is jre\lib\ext by default.) The extcheck utility compares version numbers in the same way as the method java.lang.Package.isCompatibleWith.

If no conflict is detected, the return code is 0.

If the manifest of any of the jar file in the extensions directory has the same Specification-title and the same or a newer Specification-version number, a non-zero error code is returned. A non-zero error code is also returned if targetfile.jar does not have the Specification-title or Specification-version attributes in its manifest.

OPTIONS

-verbose
Lists Jar files in the extension directory as they are checked. Additionally, manifest attributes of the target jar file and any conflicting jar files are also reported.
-J option
Pass option to the Java virtual machine, where option is one of the options described on the reference page for the java application launcher. For example, -J-Xms48m sets the startup memory to 48 megabytes.

SEE ALSO

jar
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.security.jgss.ExtendedGSSContext (Java GSS-API Utilities b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java GSS-API Utilities
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.security.jgss.ExtendedGSSContext

No usage of com.sun.security.jgss.ExtendedGSSContext
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java GSS-API Utilities
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2000, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


ExtendedService (JNLP API Reference 1.7.0)

  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method
javax.jnlp

Interface ExtendedService

  • public interface ExtendedService
    ExtendedService provides additional support to the current JNLP API, which allow applications to open a specific file in the client's file system.
    Since:
    1.5

    • Method Summary

      Methods
      Modifier and Type Method and Description
      FileContents openFile(java.io.File file)
      Asks the user the permission to open the specified file if the file has not been opened before.
      FileContents[] openFiles(java.io.File[] files)
      Asks the user the permission to open the specified list of files if any of the files has not been opened before.

    • Method Detail

      • openFile

        FileContents openFile(java.io.File file)
                      throws java.io.IOException
        Asks the user the permission to open the specified file if the file has not been opened before. The contents of the file is returned as a FileContents object. The returned FileContents object contains the contents the file.
        Parameters:
        file - the file object
        Returns:
        A FileContent object with information about the opened file
        Throws:
        java.io.IOException - - if there is any I/O error

      • openFiles

        FileContents[] openFiles(java.io.File[] files)
                         throws java.io.IOException
        Asks the user the permission to open the specified list of files if any of the files has not been opened before. The contents of each file is returned as a FileContents object in the FileContents array. The returned FileContents object contains the contents the file.
        Parameters:
        files - the array of files
        Returns:
        A FileContent[] object with information about each opened file
        Throws:
        java.io.IOException - - if there is any I/O error
  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.


Using Activation: Extending Activatable

This tutorial describes how to implement an activatable remote object by extending the class java.rmi.activation.Activatable. This tutorial uses a Setup program (described in the tutorial Using Activation: the Setup Program) that registers information about an activatable remote object with the JavaTM Remote Method Invocation (Java RMI) activation system daemon (rmid) and then binds a stub for that remote object in an rmiregistry so that clients can look it up. You may want to read that tutorial before this one.

This tutorial has the following steps:

  • Implement the activatable remote object
  • Implement the client
  • Compile the source files
  • Run the Setup program
  • Run the client

The files needed for this tutorial are:

  • MyRemoteInterface.java - a simple remote interface
  • ExtendsActivatable.java - an "activatable" implementation of the remote interface
  • Client.java - a client that uses the remote interface
  • client.policy - the security policy file for the client

Implement the activatable remote object

There are a few basic ways to implement an activatable remote object. This tutorial describes how to implement an activatable remote object by extending the class java.rmi.activation.Activatable which exports an activatable remote object during construction.

A remote object is activated when a client invokes a remote method on a stub for an activatable remote object. A stub for an activatable remote object contains the remote object's activation ID and information on how to contact the Java RMI activation system daemon (rmid) for the remote object. If the stub cannot connect to the last-known address (i.e., host/port) for the remote object, the stub will contact the remote object's activator (rmid) to activate the object. When rmid receives an activation request, it starts the remote object's activation group (or container) VM if the group is not already executing, and then rmid asks the group to make an instance of the remote object. Once the group constructs the remote object, it returns the remote object's stub to rmid which, in turn, returns the actual stub to the initiating stub so that the initiating stub can update its information on how to contact the remote object in the future.

Before any of this activation can take place, an application must register information about the activatable remote objects it needs to use. The following separate tutorial describes the information needed to activatate a remote object and how to register this information with rmid:

  • Using Activation: the Setup program

In this example, the activatable remote object implements the following remote interface examples.activation.MyRemoteInterface:

package examples.activation;

import java.rmi.*;

public interface MyRemoteInterface extends Remote {
    Object remoteMethod(Object obj) throws RemoteException;
}

The implementation class, examples.activation.ExtendsActivatable, for the activatable remote object is as follows:

package examples.activation;

import java.rmi.*;
import java.rmi.activation.*;

public class ExtendsActivatable
        extends Activatable
        implements MyRemoteInterface
{

    public ExtendsActivatable(ActivationID id, MarshalledObject data)
        throws RemoteException
    {
        super(id, 0);
    }

    public Object remoteMethod(Object obj) {
        return obj;
    }
}

The class ExtendsActivatable extends the class Activatable and implements the remote interface MyRemoteInterface.

The class ExtendsActivatable declares a special "activation" constructor that an activation group calls to construct an instance during the activation process. This special constructor takes two parameters:

  • The first parameter, ActivationID, is an identifier for the activatable remote object. When an application registers an activation descriptor with rmid, rmid assigns it an activation ID, which refers to the information associated with the descriptor. This same activation ID (also contained in the remote object's stub) is passed to this constructor when the remote object is activated.
  • The second parameter is a MarshalledObject that contains initialization data pre-registered with rmid. This initialization data may be a filename for the object's persistent state, for example. This example does not require any initialization data to construct the remote object.

The constructor simply calls a constructor in the superclass (Activatable) to export the object on an anoymous port.

Finally, the class implements the remote interface's single method, remoteMethod to return the object passed as an argument.

Implement the client

The Client program looks up a remote object's stub (one that implements the remote interface MyRemoteInterface) in the registry on the host supplied as the optional first argument, and then invokes the stub's remoteMethod method. When this client invokes a remote method on the stub acquired from the registry, the remote object will activate if not already active.

The source for the program is as follows:

package examples.activation;

import java.rmi.*;
import java.rmi.registry.*;

public class Client {

    public static void main(String args[])  throws Exception {

        String hostname = "localhost";
        if (args.length < 1) {
            System.err.println(
                "usage: java [options] examples.activation.Client <hostname>");
            System.exit(1);
        } else {
            hostname = args[0];
        }

        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new SecurityManager());
        }

        String name = System.getProperty("examples.activation.name");
        Registry registry = LocateRegistry.getRegistry(hostname);
        MyRemoteInterface stub =
            (MyRemoteInterface) registry.lookup(name);
        System.err.println("Obtained stub from the registry.");

        System.err.println("Invoking remote method...");
        String result = (String) stub.remoteMethod("hello there!");
        System.err.println("Returned from remote call.");
        System.err.println("Result: " + result);
    }
}

This program should be run as follows:

java -cp clientDir                               \
     -Djava.security.policy=client.policy        \
     -Dexamples.activation.client.codebase=clientCodebase   \
     -Dexamples.activation.name=name             \
     examples.activation.Client [host]

where:

  • clientDir is the root directory for the client program (its class path),
  • client.policy is the security policy file for this program,
  • clientCodebase is the location (URL) for this program's class (used in granting permissions to this program in the client.policy file)
  • name is the name for the object's stub in the registry
  • host is the server's host

Note: rmid must be running on its default port, and rmiregistry must be running on its default port (both on the remote host) prior to running this program.

The following is an example client.policy file that grants the appropriate permissions for the activation examples:

grant codeBase "${examples.activation.client.codebase}" {

    // permissions to read system properties required by the client
    permission java.util.PropertyPermission "examples.activation.name","read";

    // permission to connect to the registry, activation system, and remote host
    permission java.net.SocketPermission "*:1024-","connect";
};

The codebase to which permissions are granted is a file URL specifying the location of the client's classes. This file URL is the value of the examples.activation.client.codebase system property, defined when the client program is run. The client needs two permissions:

  • java.util.PropertyPermission - to read the system property examples.activation.name that specifies the name for the stub in the registry
  • java.net.SocketPermission - to connect to the registry, activation system, and remote object's host

Compile the source files

The source files for this example can be compiled as follows:

javac -d implDir MyRemoteInterface.java ExtendsActivatable.java
javac -d clientDir MyRemoteInterface.java Client.java

where implDir is the destination directory to put the implementation's class files the class files in, and clientDir is the destination directory to put the client's class files in.

Run the Setup program

Once your implementation phase is complete, you need to register information about the activatable object so a client can use it. The Setup program, described by the tutorial Using Activation: the Setup Program, registers an activation descriptor for an activatable object with rmid, and then binds the remote object's stub in an rmiregistry so that clients can look it up.

To run the Setup program for this example, see the section Start rmid, rmiregistry, and the Setup program in the setup program tutorial, which describes how to start rmid, rmiregistry, and the Setup program itself.

After you run rmid and rmiregistry as instructed in the Setup tutorial, you will need to run the Setup program to register an activation descriptor for an activatable object that implements the class examples.activation.ExtendsActivatable. The following command line runs the Setup program, supplying an appropriate file URL for each codebase used:

java -cp setupDir:implDir                       \
     -Djava.security.policy=setup.policy                      \
     -Djava.rmi.server.codebase=file:/implDir/                \
     -Dexamples.activation.setup.codebase=file:/setupDir/     \
     -Dexamples.activation.impl.codebase=file:/impDir/        \
     -Dexamples.activation.name=examples.activation.MyRemoteInterface       \
     -Dexamples.activation.policy=group.policy                \
     examples.activation.Setup examples.activation.ExtendsActivatable

where:

  • setupDir is the root directory for the Setup program's class
  • implDir is the root directory for the implementation's classes
  • setup.policy is the security policy file for the Setup program
  • group.policy is the security policy file for the activation group

Note that the examples.activation.file system property does not need to be specified, because the ExtendsActivatable implementation class does not use it. Also note that each file URL above has the required trailing slash. Examples of group and setup policy files, suitable for this tutorial, are described in the setup tutorial, and are also listed below:

  • setup.policy
  • group.policy

The output from the Setup program should look like this:

Activation group descriptor registered.
Activation descriptor registered.
Stub bound in registry.

Run the client

Once you have successfully registered an activation descriptor for an ExtendsActivatable implementation, you can run the client program, which, during its first execution, will cause the activatable object to activate.

The following command line illustrates how to run the client program, specifying a file URL for the client codebase:

java -cp clientDir                                              \
     -Djava.security.policy=client.policy                       \
     -Dexamples.activation.client.codebase=file:/clientDir/     \
     -Dexamples.activation.name=examples.activation.MyRemoteInterface         \
     examples.activation.Client [host]

where:

  • clientDir is the root directory for the client program (its class path),
  • client.policy is the security policy file for this program,
  • name is the name for the object's stub in the registry
  • host is the server's host

Notes:

  • The client codebase must have a trailing slash.
  • The name must match the name supplied to the Setup program. In this example, we used the name examples.activation.MyRemoteInterface.
  • rmid and rmiregistry must be running on the server's host. If the server's host is not the local host, the host argument must specify the remote host that they are running on.

The output from the client should look like this:

Obtained stub from the registry.
Invoking remote method...
Returned from remote call.
Result: hello there!
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Image I/O API Guide: 4 - Writing Image I/O Plug-ins

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

CHAPTER 4

Writing Image I/O Plug-ins

4.1 The Plug-in Concept

The Image I/O API is designed as a pluggable framework into which any developer may add their own "plug-ins." A plug-in is defined as a set of Java language classes which may be loaded into the API at run-time and which add functionality to the AP I. In the context of the Java Image I/O API, a plug-in may provide the ability to read image data from a new file format, to write image data in a new format, to "transcode" non-image metadata between two formats, or to read or write streaming dat a from or to a new data source or sink. A plug-in may also provide support for the same format as another plug-in, perhaps providing better performance, more features, or a different view of the data stored by the format.

In order for plug-ins to be added to a running JavaTM Virtual Machine*, they must be compiled into Java bytecode files (class files). These class files will contain the code for subclasses of various classes defined by the API. For example, a plug-in that pr ovides the capability to read images will include a new subclass of the abstract javax.imageio.ImageReader class defined by the API. The usual reversed Internet domain name convention may be used to guarantee uniqueness of class names.

Because loading and instantiating an entire plug-in may be expensive, an additional class is used as a "stand-in" to provide information about the plug-in. This class may be used, for example, to determine what formats are handled by the plug-in p rior to actually instantiating the plug-in.

The "stand-in" object is lightweight enough that it can be loaded and a single instance instantiated every time the API is used within a given invocation of the Java virtual machine. This pattern, in which a small class is used to provide informat ion about an available service, is referred to as a "service provider interface."

* As used on this web site, the terms "Java Virtual Machine" or "JVM" mean a virtual machine for the Java platform.
CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Image I/O API Guide: 4 - Writing Image I/O Plug-ins

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

4.2 Embedding Plug-ins in JAR Files

Since a plug-in consists of several classes, the JAR file mechanism is used to allow them to be combined into a single file. In addition to class files, JAR files may contain additional files used to describe their contents. In particular, a JAR file may contain a META-INF/services directory that is used to list any service providers that are contained in the file. For each service provider interface that is implemented by a class stored in the JAR file, a file whose name is the fully-qualified class name of the service provider interface is placed within the services directory. The file should contain the fully-qualified class names of the implementation classes present in the JAR file, one per line. For example, if the JAR file contains a service provider class named com.mycompany.mypackage.MyImageReaderSpi, which implements the javax.imageio.spi.ImageReaderSpi interface, there should be a file named META-INF/services/javax.imageio.spi.ImageReaderSpi containing the line com.mycompany.mypackage.MyImageReaderSpi.

The Image I/O API will automatically examine any JAR files that are found on the class path, and identify those that contain Image I/O plug-ins. For each plug-in found, a single instance of its service provider class will be instantiated and stored in a run-time registry class, javax.iamgeio.spi.IIORegistry.

JAR files on the application class path (i.e., the path set using the CLASSPATH variable), or elsewhere (e.g., available via a network URL) may be loaded by the application. They are not loaded by default in order to minimize startup time.

The javax.imageio.spi.IIORegistry class may also be used at run-time to deregister installed plug-ins and to register new ones. In particular, it is possible to use a ClassLoader to load a plug-in over the network, which may then be registered and used exactly like a locally installed plug-in.

Most applications should not need to deal directly with the registry. Instead, they may make use of convenience methods contained within the javax.imageio.ImageIO class that search for appropriate plug-ins automatically.

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Image I/O API Guide: 4 - Writing Image I/O Plug-ins

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

4.3 Writing Reader Plug-Ins

A minimal reader plug-in consists of an ImageReaderSpi subclass, and an ImageReader subclass. Optionally, it may contain implementations of the IIOMetadata interface representing the stream and image metadata, and an IIOMetadataFormat object describing the structure of the metadata.

In the following sections, we will sketch out the implementation of a simple reader plug-in for a hypothetical format called "MyFormat". It will consist of the classes MyFormatImageReaderSpi, MyFormatImageReader, and MyFormatMetadata.

The format itself is defined to begin with the characters `myformat\n', followed by two four-byte integers representing the width, height, and a single byte indicating the color type of the image, which may be either gray or RGB. Next, after a newline character, metadata values may stored as alternating lines containing a keyword and a value, terminated by the special keyword `END'. The string values are stored using UTF8 encoding followed by a newline. Finally, the image samples are stored in left-to-right, top-to-bottom order as either byte grayscale values, or three bytes representing red, green, and blue.

MyFormatImageReaderSpi The MyFormatImageReaderSpi class provides information about the plug-in, including the vendor name, plug-in version string and description, format name, file suffixes associated with the format, MIME types associated with the format, input source classes that the plug-in can handle, and the ImageWriterSpis of plug-ins that are able to interoperate specially with the reader. It also must provide an implementation of the canDecodeInput method, which is used to locate plug-ins based on the contents of a source image file.

The ImageReaderSpi class provides implementations of most of its methods. These methods mainly return the value of various protected instance variables, which the MyFormatImageReaderSpi may set directly or via the superclass constructor, as in the example below:

package com.mycompany.imageio;

import java.io.IOException;
import java.util.Locale;
import javax.imageio.ImageReader;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.stream.ImageInputStream;

public class MyFormatImageReaderSpi extends ImageReaderSpi {

        static final String vendorName = "My Company";
        static final String version = "1.0_beta33_build9467";
        static final String readerClassName =
                "com.mycompany.imageio.MyFormatImageReader";
        static final String[] names = { "myformat" };
        static final String[] suffixes = { "myf" };
        static final String[] MIMETypes = {
                "image/x-myformat" };
        static final String[] writerSpiNames = {
                "com.mycompany.imageio.MyFormatImageWriterSpi" };

        // Metadata formats, more information below
        static final boolean supportsStandardStreamMetadataFormat = false;
        static final String nativeStreamMetadataFormatName = null
        static final String nativeStreamMetadataFormatClassName = null;
        static final String[] extraStreamMetadataFormatNames = null;
        static final String[] extraStreamMetadataFormatClassNames = null;
        static final boolean supportsStandardImageMetadataFormat = false;
        static final String nativeImageMetadataFormatName =
                "com.mycompany.imageio.MyFormatMetadata_1.0";
        static final String nativeImageMetadataFormatClassName =
                "com.mycompany.imageio.MyFormatMetadata";
        static final String[] extraImageMetadataFormatNames = null;
        static final String[] extraImageMetadataFormatClassNames = null;

        public MyFormatImageReaderSpi() {
                super(vendorName, version,
                      names, suffixes, MIMETypes,
                      readerClassName,
                      STANDARD_INPUT_TYPE, // Accept ImageInputStreams
                      writerSpiNames,
                      supportsStandardStreamMetadataFormat,
                      nativeStreamMetadataFormatName,
                      nativeStreamMetadataFormatClassName,
                      extraStreamMetadataFormatNames,
                      extraStreamMetadataFormatClassNames,
                      supportsStandardImageMetadataFormat,
                      nativeImageMetadataFormatName,
                      extraImageMetadataFormatNames,
                      extraImageMetadataFormatClassNames);
                }

                public String getDescription(Locale locale) {
                        // Localize as appropriate
                        return "Description goes here";
                }

                public boolean canDecodeInput(Object input)
                        throws IOException {
                        // see below
                }

            public ImageReader createReaderInstance(Object extension) {
                return new MyFormatImageReader(this);
            }
        }
Most plug-ins need read only from ImageInputStream sources, since it is possible to "wrap" most other types of input with an appropriate ImageInputStream. However, it is possible for a plug-in to work directly with other Objects, for example an Object that provides an interface to a digital camera or scanner. This interface need not provide a "stream" view of the device at all. Rather, a plug-in that is aware of the interface may use it to drive the device directly.

The plug-in advertises which input classes it can handle via its getInputTypes method, which returns an array of Class objects. An implementation of getInputTypes is provided in the superclass, which returns the value of the inputTypes instance variable, which in turn is set by the seventh argument to the superclass constructor. The value used in the example above, STANDARD_INPUT_TYPE, is shorthand for an array containing the single element javax.imageio.stream.ImageInputStream.class, indicating that the plug-in accepts only ImageInputStreams.

The canDecodeInput method is responsible for determining two things: first, whether the input parameter is an instance of a class that the plug-in can understand, and second, whether the file contents appear to be in the format handled by the plug-in. It must leave its input in the same state as it was when it was passed in. For an ImageInputStream input source, the mark and reset methods may be used. For example, since files in the "MyFormat" format all begin with the characters `myformat', canDecodeInput may be implemented as:

public boolean canDecodeInput(Object input) {
        if (!(input instanceof ImageInputStream)) {
                return false;
        }

        ImageInputStream stream = (ImageInputStream)input;
        byte[] b = new byte[8];
        try {
                stream.mark();
                stream.readFully(b);
                stream.reset();
        } catch (IOException e) {
                return false;
        }

        // Cast unsigned character constants prior to comparison
        return (b[0] == (byte)'m' && b[1] == (byte)'y' &&
                b[2] == (byte)'f' && b[3] == (byte)'o' &&
                b[4] == (byte)'r' && b[5] == (byte)'m' &&
                b[6] == (byte)'a' && b[7] == (byte)'t');
}
MyFormatImageReader The heart of a reader plug-in is its extension of the ImageReader class. This class is responsible for responding to queries about the images actually stored in an input file or stream, as well as the actual reading of images, thumbnails, and metadata. For simplicity, we will ignore thumbnail images in this example.

A sketch of some of the methods of a hypothetical MyFormatImageReader class is shown below:

package com.mycompany.imageio;

public class MyFormatImageReader extends ImageReader {

        ImageInputStream stream = null;
        int width, height;
        int colorType;

        // Constants enumerating the values of colorType
        static final int COLOR_TYPE_GRAY = 0;
        static final int COLOR_TYPE_RGB = 1;

        boolean gotHeader = false;

        public MyFormatImageReader(ImageReaderSpi originatingProvider) {
                super(originatingProvider);
        }

        public void setInput(Object input, boolean isStreamable) {
                super.setInput(input, isStreamable);
                if (input == null) {
                        this.stream = null;
                        return;
                }
                if (input instanceof ImageInputStream) {
                        this.stream = (ImageInputStream)input;
                } else {
                        throw new IllegalArgumentException("bad input");
                }
        }

        public int getNumImages(boolean allowSearch)
                throws IIOException {
                return 1; // format can only encode a single image
        }

        private void checkIndex(int imageIndex) {
                if (imageIndex != 0) {
                        throw new IndexOutOfBoundsException("bad index");
                }
        }

        public int getWidth(int imageIndex)
                throws IIOException {
                checkIndex(imageIndex); // must throw an exception if != 0
                readHeader();
                return width;
        }

        public int getHeight(int imageIndex)
                throws IIOException {
                checkIndex(imageIndex);
                readHeader();
                return height;
        }
The getImageTypes Method The reader is responsible for indicating what sorts of images may be used to hold the decoded output. The ImageTypeSpecifier class is used to hold a SampleModel and ColorModel indicating a legal image layout. The getImageTypes method returns an Iterator of ImageTypeSpecifiers:
        public Iterator getImageTypes(int imageIndex)
                throws IIOException {
                checkIndex(imageIndex);
                readHeader();

                ImageTypeSpecifier imageType = null;
                int datatype = DataBuffer.TYPE_BYTE;
                java.util.List l = new ArrayList();
                switch (colorType) {
                case COLOR_TYPE_GRAY:
                        imageType = ImageTypeSpecifier.createGrayscale(8,
                                                                       datatype,
                                                                       false);
                        break;

                case COLOR_TYPE_RGB:
                        ColorSpace rgb =
                                ColorSpace.getInstance(ColorSpace.CS_sRGB);
                        int[] bandOffsets = new int[3];
                        bandOffsets[0] = 0;
                        bandOffsets[1] = 1;
                        bandOffsets[2] = 2;
                        imageType =
                                ImageTypeSpecifier.createInterleaved(rgb,
                                                                     bandOffsets,
                                                                     datatype,
                                                                     false,
                                                                     false);
                        break;
                }
                l.add(imageType);
                return l.iterator();
        }
Parsing the Image Header Several of the methods above depend on a readHeader method, which is responsible for reading enough of the input stream to determine the width, height, and layout of the image. readHeader is defined so it is safe to be called multiple times (note that we are not concerned with multi-threaded access):
        public void readHeader() {
                if (gotHeader) {
                        return;
                }
                gotHeader = true;

                if (stream == null) {
                        throw new IllegalStateException("No input stream");
                }

                // Read `myformat\n' from the stream
                byte[] signature = new byte[9];
                try {
                        stream.readFully(signature);
                } catch (IOException e) {
                        throw new IIOException("Error reading signature", e);
                }
                if (signature[0] != (byte)'m' || ...) { // etc.
                        throw new IIOException("Bad file signature!");
                }
                // Read width, height, color type, newline
                try {
                        this.width = stream.readInt();
                        this.height = stream.readInt();
                        this.colorType = stream.readUnsignedByte();
                        stream.readUnsignedByte(); // skip newline character
                } catch (IOException e) {
                        throw new IIOException("Error reading header", e)
                }
        }
The actual reading of the image is handled by the read method:
        public BufferedImage read(int imageIndex, ImageReadParam param)
                throws IIOException {
                readMetadata(); // Stream is positioned at start of image data
Handling the ImageReadParam The first section of the method is concerned with using a supplied ImageReadParam object to determine what region of the source image is to be read, what sort of subsampling is to be applied, the selection and rearrangement of bands, and the offset in the destination:

        // Compute initial source region, clip against destination later
        Rectangle sourceRegion = getSourceRegion(param, width, height);

        // Set everything to default values
        int sourceXSubsampling = 1;
        int sourceYSubsampling = 1;
        int[] sourceBands = null;
        int[] destinationBands = null;
        Point destinationOffset = new Point(0, 0);

        // Get values from the ImageReadParam, if any
        if (param != null) {
                sourceXSubsampling = param.getSourceXSubsampling();
                sourceYSubsampling = param.getSourceYSubsampling();
                sourceBands = param.getSourceBands();
                destinationBands = param.getDestinationBands();
                destinationOffset = param.getDestinationOffset();
        }
At this point, the region of interest, subsampling, band selection, and destination offset have been initialized. The next step is to create a suitable destination image. The ImageReader.getDestination method will return any image that was specified using ImageReadParam.setDestination, or else will create a suitable destination image using a supplied ImageTypeSpecifier, in this case determined by calling getImageTypes(0):
        // Get the specified detination image or create a new one
        BufferedImage dst = getDestination(param,
                                           getImageTypes(0),
                                           width, height);
        // Enure band settings from param are compatible with images
        int inputBands = (colorType == COLOR_TYPE_RGB) ? 3 : 1;
        checkReadParamBandSettings(param, inputBands,
                                   dst.getSampleModel().getNumBands());
To reduce the amount of code we have to write, we create a Raster to hold a row's worth of data, and copy the pixels from that Raster into the actual image. In this way, band selection and the details of pixel formatting are taken care of, at the expense of an additional copy.
        int[] bandOffsets = new int[inputBands];
        for (int i = 0; i < inputBands; i++) {
                bandOffsets[i] = i;
        }
        int bytesPerRow = width*inputBands;
        DataBufferByte rowDB = new DataBufferByte(bytesPerRow);
        WritableRaster rowRas =
                Raster.createInterleavedRaster(rowDB,
                                               width, 1, bytesPerRow,
                                               inputBands, bandOffsets,
                                               new Point(0, 0));
        byte[] rowBuf = rowDB.getData();

        // Create an int[] that can a single pixel
        int[] pixel = rowRas.getPixel(0, 0, (int[])null);
Now we have a byte array, rowBuf, which can be filled in from the input data, and which is also the source of pixel data for the Raster rowRaster. We extract the (single) tile of the destination image, and determine its extent. Then we create child rasters of both the source and destination that select and order their bands according to the settings previously extracted from the ImageReadParam:

        WritableRaster imRas = dst.getWritableTile(0, 0);
        int dstMinX = imRas.getMinX();
        int dstMaxX = dstMinX + imRas.getWidth() - 1;
        int dstMinY = imRas.getMinY();
        int dstMaxY = dstMinY + imRas.getHeight() - 1;

        // Create a child raster exposing only the desired source bands
        if (sourceBands != null) {
                rowRas = rowRas.createWritableChild(0, 0,
                                                    width, 1,
                                                    0, 0,
                                                    sourceBands);
        }

        // Create a child raster exposing only the desired dest bands
        if (destinationBands != null) {
                imRas = imRas.createWritableChild(0, 0,
                                                  imRas.getWidth(),
                                                  imRas.getHeight(),
                                                  0, 0,
                                                  destinationBands);
        }
Reading the Pixel Data Now we are ready to begin read pixel data from the image. We will read whole rows, and perform subsampling and destination clipping as we proceed. The horizontal clipping is complicated by the need to take subsampling into account. Here we perform per-pixel clipping; a more sophisticated reader could perform horizontal clipping once:
        for (int srcY = 0; srcY < height; srcY++) {
                // Read the row
                try {
                        stream.readFully(rowBuf);
                } catch (IOException e) {
                        throw new IIOException("Error reading line " + srcY, e);
                }

                // Reject rows that lie outside the source region,
                // or which aren't part of the subsampling
                if ((srcY < sourceRegion.y) ||
                    (srcY >= sourceRegion.y + sourceRegion.height) ||
                    (((srcY - sourceRegion.y) %
                      sourceYSubsampling) != 0)) {
                        continue;
                }

                // Determine where the row will go in the destination
                int dstY = destinationOffset.y +
                        (srcY - sourceRegion.y)/sourceYSubsampling;
                if (dstY < dstMinY) {
                        continue; // The row is above imRas
                }
                if (dstY > dstMaxY) {
                        break; // We're done with the image
                }

                // Copy each (subsampled) source pixel into imRas
                for (int srcX = sourceRegion.x;
                     srcX < sourceRegion.x + sourceRegion.width;
                     srcX++) {
                        if (((srcX - sourceRegion.x) % sourceXSubsampling) != 0) {
                                continue;
                        }
                        int dstX = destinationOffset.x +
                                (srcX - sourceRegion.x)/sourceXSubsampling;
                        if (dstX < dstMinX) {
                                continue;  // The pixel is to the left of imRas
                        }
                        if (dstX > dstMaxX) {
                                break; // We're done with the row
                        }

                        // Copy the pixel, sub-banding is done automatically
                        rowRas.getPixel(srcX, 0, pixel);
                        imRas.setPixel(dstX, dstY, pixel);
                }
        }
        return dst;
For performance, the case where sourceXSubsampling is equal to 1 may be broken out separately, since it is possible to copy multiple pixels at once:
        // Create an int[] that can hold a row's worth of pixels
        int[] pixels = rowRas.getPixels(0, 0, width, 1, (int[])null);

        // Clip against the left and right edges of the destination image
        int srcMinX =
                Math.max(sourceRegion.x,
                     dstMinX - destinationOffset.x + sourceRegion.x);
      int srcMaxX =
                Math.min(sourceRegion.x + sourceRegion.width - 1,
                         dstMaxX - destinationOffset.x + sourceRegion.x);
        int dstX = destinationOffset.x + (srcMinX - sourceRegion.x);
        int w = srcMaxX - srcMinX + 1;
        rowRas.getPixels(srcMinX, 0, w, 1, pixels);
        imRas.setPixels(dstX, dstY, w, 1, pixels);
There are several additional features that readers should implement, namely informing listeners of the progress of the read, and allowing the read process to be aborted from another thread. Listeners There are three types of listeners that may be attached to a reader: IIOReadProgressListener, IIOReadUpdateListener, and IIOReadWarningListener. Any number of each type may be attached to a reader by means of various add and remove methods that are implemented in the ImageReader superclass. ImageReader also contains various process methods that broadcast information to all of the attached listeners of a given type. For example, when the image read begins, the method processImageStarted(imageIndex) should be called to inform all attached IIOReadProgressListeners of the event.

A reader plug-in is normally responsible for calling processImageStarted and processImageComplete at the beginning and end of its read method, respectively. processImageProgress should be called at least every few scanlines with an estimate of the percentage completion of the read. It is important that this percentage never decrease during the read of a single image. If the reader supports thumbnails, the corresponsing thumbnail progress methods should be called as well. The processSequenceStarted and processSequenceComplete methods of IIOReadProgressListener only need to be called if the plug-in overrides the superclass implementation of readAll.

More advanced readers that process incoming data in multiple passes may choose to support IIOReadUpdateListeners, which receive more detauled information about which pixels have been read so far. Applications may use this information to perform selective updates of an on-screen image, for example, or to re-encode image data in a streaming fashion.

Aborting the Read Process While one thread performs an image read, another thread may call the reader's abort method asynchronously. The reading thread should poll the reader's status periodically using the abortRequested method, and attempt to cut the decoding short. The partially decoded image should still be returned, although the reader need not make any guarantees about its contents. For example, it could contain compressed or encrypted data in its DataBuffer that does not make sense visually. IIOReadProgressListener Example A typical set of IIOReadProgressListener calls might look like this:

public BufferedImage read(int imageIndex, ImageReadParam param)
        throws IOException {
        // Clear any previous abort request
        boolean aborted = false;
        clearAbortRequested();

        // Inform IIOReadProgressListeners of the start of the image
        processImageStarted(imageIndex);

        // Compute xMin, yMin, xSkip, ySkip from the ImageReadParam
        // ...

        // Create a suitable image
        BufferedImage theImage = new BufferedImage(...);

        // Compute factors for use in reporting percentages
        int pixelsPerRow = (width - xMin + xSkip - 1)/xSkip;
        int rows = (height - yMin + ySkip - 1)/ySkip;
        long pixelsDecoded = 0L;
        long totalPixels = rows*pixelsPerRow;

        for (int y = yMin; y < height; y += yskip) {
                // Decode a (subsampled) scanline of the image
                // ...

                // Update the percentage estimate
                // This may be done only every few rows if desired
                pixelsDecoded += pixelsPerRow;
                processImageProgress(100.0F*pixelsDecoded/totalPixels);

                // Check for an asynchronous abort request
                if (abortRequested()) {
                        aborted = true;
                        break;
                }
        }

        // Handle the end of decoding
        if (aborted) {
                processImageAborted();
        } else {
                processImageComplete(imageIndex);
        }

        // If the read was aborted, we still return a partially decoded image
        return theImage;
}
Metadata The next set of methods in MyFormatImageReader deal with metadata. Because our hypothetical format only encodes a single image, we may ignore the concept of "stream" metadata, and use "image" metadata only:
        MyFormatMetadata metadata = null; // class defined below

        public IIOMetadata getStreamMetadata()
                throws IIOException {
                return null;
        }

        public IIOMetadata getImageMetadata(int imageIndex)
                throws IIOException {
                if (imageIndex != 0) {
                        throw new IndexOutOfBoundsException("imageIndex != 0!");
                }
                readMetadata();
                return metadata;
        }
The actual work is done by a format-specific method readMetadata, which for this format fills in the keyword/value pairs of the metadata object,
        public void readMetadata() throws IIOException {
                if (metadata != null) {
                        return;
                }
                readHeader();
                this.metadata = new MyFormatMetadata();
                try {
                        while (true) {
                                String keyword = stream.readUTF();
                                stream.readUnsignedByte();
                                if (keyword.equals("END")) {
                                        break;
                                }
                                String value = stream.readUTF();
                                stream.readUnsignedByte();

                                metadata.keywords.add(keyword);
                                metadata.values.add(value);
                        } catch (IIOException e) {
                                throw new IIOException("Exception reading metadata",
                                                       e);
                        }
                }
        }
MyFormatMetadata Finally, the various interfaces for extracting and editing metadata must be defined. We define a class called MyFormatMetadata that extends the IIOMetadata class, and additionally can store the keyword/value pairs that are allowed in the file format:
package com.mycompany.imageio;

import org.w3c.dom.*;
import javax.xml.parsers.*; // Package name may change in J2SDK 1.4

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.imageio.metadata.IIOInvalidTreeException;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataFormat;
import javax.imageio.metadata.IIOMetadataNode;

public class MyFormatMetadata extends IIOMetadata {

        static final boolean standardMetadataFormatSupported = false;
        static final String nativeMetadataFormatName =
                "com.mycompany.imageio.MyFormatMetadata_1.0";
        static final String nativeMetadataFormatClassName =
                "com.mycompany.imageio.MyFormatMetadata";
        static final String[] extraMetadataFormatNames = null;
        static final String[] extraMetadataFormatClassNames = null;

        // Keyword/value pairs
        List keywords = new ArrayList();
        List values = new ArrayList();
The first set of methods are common to most IIOMetadata implementations:
        public MyFormatMetadata() {
                super(standardMetadataFormatSupported,
                      nativeMetadataFormatName,
                      nativeMetadataFormatClassName,
                      extraMetadataFormatNames,
                      extraMetadataFormatClassNames);
        }

        public IIOMetadataFormat getMetadataFormat(String formatName) {
                if (!formatName.equals(nativeMetadataFormatName)) {
                        throw new IllegalArgumentException("Bad format name!");
                }
                return MyFormatMetadataFormat.getDefaultInstance();
        }
The most important method for reader plug-ins is getAsTree:
        public Node getAsTree(String formatName) {
                if (!formatName.equals(nativeMetadataFormatName)) {
                        throw new IllegalArgumentException("Bad format name!");
                }

                // Create a root node
                IIOMetadataNode root =
                        new IIOMetadataNode(nativeMetadataFormatName);

                // Add a child to the root node for each keyword/value pair
                Iterator keywordIter = keywords.iterator();
                Iterator valueIter = values.iterator();
                while (keywordIter.hasNext()) {
                        IIOMetadataNode node =
                                new IIOMetadataNode("KeywordValuePair");
                        node.setAttribute("keyword", (String)keywordIter.next());
                        node.setAttribute("value", (String)valueIter.next());
                        root.appendChild(node);
                }

                return root;
        }
For writer plug-ins, the ability to edit metadata values is obtained by implementing the isReadOnly, reset, and mergeTree methods:
        public boolean isReadOnly() {
            return false;
        }

        public void reset() {
            this.keywords = new ArrayList();
            this.values = new ArrayList();
        }

        public void mergeTree(String formatName, Node root)
                throws IIOInvalidTreeException {
                if (!formatName.equals(nativeMetadataFormatName)) {
                        throw new IllegalArgumentException("Bad format name!");
                }

                Node node = root;
                if (!node.getNodeName().equals(nativeMetadataFormatName)) {
                        fatal(node, "Root must be " + nativeMetadataFormatName);
                }
                node = node.getFirstChild();
                while (node != null) {
                        if (!node.getNodeName().equals("KeywordValuePair")) {
                                fatal(node, "Node name not KeywordValuePair!");
                        }
                        NamedNodeMap attributes = node.getAttributes();
                        Node keywordNode = attributes.getNamedItem("keyword");
                        Node valueNode = attributes.getNamedItem("value");
                        if (keywordNode == null || valueNode == null) {
                                fatal(node, "Keyword or value missing!");
                        }

                        // Store keyword and value
                        keywords.add((String)keywordNode.getNodeValue());
                        values.add((String)valueNode.getNodeValue());

                        // Move to the next sibling
                        node = node.getNextSibling();
                }
        }

        private void fatal(Node node, String reason)
                throws IIOInvalidTreeException {
                throw new IIOInvalidTreeException(reason, node);
        }
}
MyFormatMetadataFormat The tree structure of the metadata may be described using the IIOMetadataFormat interface. An implementation class, IIOMetadataFormatImpl, takes care of maintaining the "database" of information about elements, their attributes, and the parent-child relationships between them:
package com.mycompany.imageio;

import javax.imageio.ImageTypeSpecifier;
import javax.imageio.metadata.IIOMetadataFormatImpl;

public class MyFormatMetadataFormat extends IIOMetadataFormatImpl {

        // Create a single instance of this class (singleton pattern)
        private static MyFormatMetadataFormat defaultInstance =
                new MyFormatMetadataFormat();

        // Make constructor private to enforce the singleton pattern
        private MyFormatMetadataFormat() {
                // Set the name of the root node
                // The root node has a single child node type that may repeat
                super("com.mycompany.imageio.MyFormatMetadata_1.0",
                      CHILD_POLICY_REPEAT);

                // Set up the "KeywordValuePair" node, which has no children
                addElement("KeywordValuePair",
                           "com.mycompany.imageio.MyFormatMetadata_1.0",
                           CHILD_POLICY_EMPTY);

                // Set up attribute "keyword" which is a String that is required
                // and has no default value
                addAttribute("KeywordValuePair", "keyword", DATATYPE_STRING,
                             true, null);
                // Set up attribute "value" which is a String that is required
                // and has no default value
                addAttribute("KeywordValuePair", "value", DATATYPE_STRING,
                             true, null);
        }

        // Check for legal element name
        public boolean canNodeAppear(String elementName,
                                     ImageTypeSpecifier imageType) {
                return elementName.equals("KeywordValuePair");
        }

        // Return the singleton instance
        public static MyFormatMetadataFormat getDefaultInstance() {
                return defaultInstance;
        }
}

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Image I/O API Guide: 4 - Writing Image I/O Plug-ins

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

4.4 Writing Writer Plug-ins

MyFormatImageWriterSpi The MyFormatImageWriterSpi call plays a similar role to the MyFormatImageReaderSpi class discussed in the previous section. However, instead of being responsible for determining whether a given stream can be read, it must deterine whether an image in memory can be written. Rather than inspecting the image itself, an ImageTypeSpecifier is used so that writers may be selected before an actual image is available.
package com.mycompany.imageio;

import java.io.IOException;
import java.util.Locale;
import javax.imageio.ImageWriter;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.spi.ImageWriterSpi;
import javax.imageio.stream.ImageInputStream;

public class MyFormatImageWriterSpi extends ImageWriterSpi {

        static final String vendorName = "My Company";
        static final String version = "1.0_beta33_build9467";
        static final String writerClassName =
                "com.mycompany.imageio.MyFormatImageWriter";
        static final String[] names = { "myformat" };
        static final String[] suffixes = { "myf" };
        static final String[] MIMETypes = { "image/x-myformat" };
        static final String[] readerSpiNames = {
                "com.mycompany.imageio.MyFormatImageReaderSpi" };

        static final boolean supportsStandardStreamMetadataFormat = false;
        static final String nativeStreamMetadataFormatName = null;
        static final String nativeStreamMetadataFormatClassName = null;
        static final String[] extraStreamMetadataFormatNames = null;
        static final String[] extraStreamMetadataFormatClassNames = null;
        static final boolean supportsStandardImageMetadataFormat = false;
        static final String nativeImageMetadataFormatName =
                "com.mycompany.imageio.MyFormatMetadata_1.0";
        static final String nativeImageMetadataFormatClassName =
                "com.mycompany.imageio.MyFormatMetadata";
        static final String[] extraImageMetadataFormatNames = null;
        static final String[] extraImageMetadataFormatClassNames = null;

        public MyFormatImageWriterSpi() {
                super(vendorName, version,
                      names, suffixes, MIMETypes,
                      writerClassName,
                      STANDARD_OUTPUT_TYPE, // Write to ImageOutputStreams
                      readerSpiNames,
                      supportsStandardStreamMetadataFormat,
                      nativeStreamMetadataFormatName,
                      nativeStreamMetadataFormatClassName,
                      extraStreamMetadataFormatNames,
                      extraStreamMetadataFormatClassNames,
                      supportsStandardImageMetadataFormat,
                      nativeImageMetadataFormatName,
                      nativeImageMetadataFormatClassName,
                      extraImageMetadataFormatNames,
                      extraImageMetadataFormatClassNames);
        }

        public boolean canEncodeImage(ImageTypeSpecifier imageType) {
                int bands = imageType.getNumBands();
                return bands == 1 || bands == 3;
        }

        public String getDescription(Locale locale) {
                // Localize as appropriate
                return "Description goes here";
        }

        public ImageWriter createWriterInstance(Object extension) {
            return new MyFormatImageWriter(this);
        }
}
MyFormatImageWriter
package com.mycompany.imageio;

import java.awt.Rectangle;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.IIOException;
import javax.imageio.IIOImage;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.spi.ImageWriterSpi;
import javax.imageio.stream.ImageOutputStream;

public class MyFormatImageWriter extends ImageWriter {

        ImageOutputStream stream = null;

        public MyFormatImageWriter(ImageWriterSpi originatingProvider) {
                super(originatingProvider);
        }

        public void setOutput(Object output) {
                super.setOutput(output);
                if (output != null) {
                        if (!(output instanceof ImageOutputStream)) {
                                throw new IllegalArgumentException
                                        ("output not an ImageOutputStream!");
                        }
                        this.stream = (ImageOutputStream)output;
                } else {
                        this.stream = null;
                }
        }
The ImageWriteParam returned by getDefaultWriteParam must be customized based on the writer's capabilities. Since this writer does not support tiling, progessive encoding, or compression, we pass in values of false or null as appropriate:
        // Tiling, progressive encoding, compression are disabled by default
        public ImageWriteParam getDefaultWriteParam() {
                return new ImageWriteParam(getLocale());
        }
The format only handles image metadata. The convertImageMetadata method does very little; it could be defined to interpret the metadata classes used by other plug-ins.

  public IIOMetadata getDefaultStreamMetadata(ImageWriteParam param) {
                return null;
        }

        public IIOMetadata
                getDefaultImageMetadata(ImageTypeSpecifier imageType,
                                        ImageWriteParam param) {
                return new MyFormatMetadata();
        }

        public IIOMetadata convertStreamMetadata(IIOMetadata inData,
                                                 ImageWriteParam param) {
                return null;
        }

        public IIOMetadata convertImageMetadata(IIOMetadata inData,
                                                ImageTypeSpecifier imageType,
                                                ImageWriteParam param) {
                // We only understand our own metadata
                if (inData instanceof MyFormatMetadata) {
                        return inData;
                } else {
                        return null;
                }
        }
The actual writing of the image requires first applying the source region, source bands, and subsampling factors from the ImageWriteParam. The source region and source bands may be handled by creating a child Raster. For simplicity, we extract a single Raster from the source image. If the source image is tiled, we can save memory by extracting smaller Rasters as needed.
        public void write(IIOMetadata streamMetadata,
                          IIOImage image,
                          ImageWriteParam param) throws IIOException {
                RenderedImage im = image.getRenderedImage();

                Rectangle sourceRegion =
                        new Rectangle(0, 0, im.getWidth(), im.getHeight());
                int sourceXSubsampling = 1;
                int sourceYSubsampling = 1;
                int[] sourceBands = null;
                if (param != null) {
                        sourceRegion =
                                sourceRegion.intersection(param.getSourceRegion());
                        sourceXSubsampling = param.getSourceXSubsampling();
                        sourceYSubsampling = param.getSourceYSubsampling();
                        sourceBands = param.getSourceBands();

                        int subsampleXOffset = param.getSubsamplingXOffset();
                        int subsampleYOffset = param.getSubsamplingYOffset();
                        sourceRegion.x += subsampleXOffset;
                        sourceRegion.y += subsampleYOffset;
                        sourceRegion.width -= subsampleXOffset;
                        sourceRegion.height -= subsampleYOffset;
                }

                // Grab a Raster containing the region of interest
                int width = sourceRegion.width;
                int height = sourceRegion.height;
                Raster imRas = im.getData(sourceRegion);
                int numBands = imRas.getNumBands();

                // Check that sourceBands values are in range
                if (sourceBands != null) {
                        for (int i = 0; i < sourceBands.length; i++) {
                                if (sourceBands[i] >= numBands) {
                                        throw new IllegalArgumentException("bad band!");
                                }
                        }
                }

                // Translate imRas to start at (0, 0) and subset the bands
                imRas = imRas.createChild(sourceRegion.x, sourceRegion.y,
                                          width, height,
                                          0, 0,
                                          sourceBands);

                // Reduce width and height according to subsampling factors
                width = (width + sourceXSubsampling - 1)/sourceXSubsampling;
                height = (height + sourceYSubsampling - 1)/sourceYSubsampling;

                // Assume 1 band image is grayscale, 3 band image is RGB
                int colorType;
                if (numBands == 1) {
                        colorType = MyFormatImageReader.COLOR_TYPE_GRAY;
                } else if (numBands == 3) {
                        colorType = MyFormatImageReader.COLOR_TYPE_RGB;
                } else {
                        throw new IIOException("Image must have 1 or 3 bands!");
                }
Once the image dimensions and color type of the image have been ascertained, the plug-in is ready to write the file header:
                try {
                        byte[] signature = {
                                (byte)'m', (byte)'y',  (byte)'f', (byte)'o',
                                (byte)'r', (byte)'m',  (byte)'a', (byte)'t'
                        };
                        // Output header information
                        stream.write(signature);
                        stream.write(`\n');
                        stream.writeInt(width);
                        stream.writeInt(height);
                        stream.writeByte(colorType);
                        stream.write(`\n');
Next, the plug-in extracts the image metadata from the write method's IIOImage argument, and attempts to convert it into a MyFormatMetadata object by calling convertImageMetadata. If the result is non-null, the keywords and values are extracted from the metadata and written to the output:
                        // Attempt to convert metadata, if present
                        IIOMetadata imd = image.getMetadata();
                        MyFormatMetadata metadata = null;
                        if (imd != null) {
                                ImageTypeSpecifier type =
                                        ImageTypeSpecifier.createFromRenderedImage(im);
                                metadata =
                                        (MyFormatMetadata)convertImageMetadata(imd,
                                                                               type,
                                                                               null);
                        }

                        // Output metadata if present
                        if (metadata != null) {
                                Iterator keywordIter = metadata.keywords.iterator();
                                Iterator valueIter = metadata.values.iterator();
                                while (keywordIter.hasNext()) {
                                        String keyword = (String)keywordIter.next();
                                        String value = (String)valueIter.next();

                                        stream.writeUTF(keyword);
                                        stream.write(`\n');
                                        stream.writeUTF(value);
                                        stream.write(`\n');
                                }
                        }
                        stream.writeUTF("END");
                        stream.write(`\n');
Finally, the plug-in is ready to begin writing the pixel data. The image Raster is copied into an int array, one row at a time using the getPixels method. Then these values are subsampled using the horizontal subsampling factor, and copied into a byte array, which is written to the output with a single write call. The source row is then incremented by the vertical subsampling factor until the end of the source region is reached, and the output stream is flushed:
                        // Output (subsampled) pixel values
                        int rowLength = width*numBands;
                        int xSkip = sourceXSubsampling*numBands;
                        int[] rowPixels = imRas.getPixels(0, 0, width, 1,
                                                          (int[])null);
                        byte[] rowSamples = new byte[rowLength];

                        // Output every (sourceYSubsampling)^th row
                        for (int y = 0; y < height; y += sourceYSubsampling) {
                                imRas.getPixels(0, y, width, 1, rowPixels);

                                // Subsample horizontally and convert to bytes
                                int count = 0;
                                for (int x = 0; x < width; x += xSkip) {
                                        if (colorType ==
                                                MyFormatImageReader.COLOR_TYPE_GRAY) {
                                                rowSamples[count++] = (byte)rowPixels[x];
                                        } else {
                                                rowSamples[count++] = (byte)rowPixels[x];
                                                rowSamples[count++] =
                                                        (byte)rowPixels[x + 1];
                                                rowSamples[count++] =
                                                        (byte)rowPixels[x + 2];
                                        }
                                }

                                // Output a row's worth of bytes
                                stream.write(rowSamples, 0, width*numBands);
                        }
                        stream.flush();
                } catch (IOException e) {
                        throw new IIOException("I/O error!", e);
                }
        }
}

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Image I/O API Guide: 4 - Writing Image I/O Plug-ins

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

4.5 Writing Transcoder Plug-ins

A transcoder plug-in consists of an ImageTranscoderSpi, which performs the same functions as do the Spi classes for other plug-ins, and an object that implements the ImageTranscoder interface:
IIOMetadata convertStreamMetadata(IIOMetadata inData,
                                  ImageWriteParam param);

IIOMetadata convertImageMetadata(IIOMetadata inData,
                                 ImageTypeSpecifier imageType,
                                 ImageWriteParam param);
The ImageTranscoder may use the standard interfaces to unpack the incoming metadata, or it may make use of interfaces that are specific to the actual object at hand. For example, it could access the keywords and values instance variables of the MyFormatMetadata class defined above; these were made public, but not documented, precisely in order to allow a transcoder plug-in developer to access them without having to go through a DOM representation.
CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Image I/O API Guide: 4 - Writing Image I/O Plug-ins

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

4.6 Writing Stream Plug-ins

The standard classes in the javax.imageio.stream package are able to create ImageInputStreams and ImageOutputStreams that:
  • Read from a File
  • Read from an InputStream, using a temporary File as a cache
  • Read from an InputStream, using a byte array in memory as a cache
  • Write to a File
  • Write to an OutputStream, using a temporary File as a cache
  • Write to an OutputStream, using a byte array in memory as a cache
It is possible to write new implementations of ImageInputStream and InmageOutputStream that interface with other I/O primitives (for example, databases or future fast I/O interfaces). The ImageInputStreamImpl and ImageOutputStreamImpl classes provide a base for subclassing. Only a handful of methods are required to be implemented by the subclass, although it is possible to implement more for greater efficiency:
  • int read()
  • int read(byte[] b, int off, int len)
  • write(int b)
  • write(byte[] b, int off, int len)
  • seek(long pos)

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Extending Sockets in JDK 1.1

Some of the improvements to the java.net classes in JDK 1.1 allow sockets (Socket/ServerSocket) to be non-final, extendable classes. The basic goal is to allow extended sockets to be used whereever a base class Socket is used without rewriting application code. So for example an already-existing email client could be handed a subclass of Socket that does peer authentication or encryption, which the Socket subclass would handle transparently. Other examples include sockets that transparently use compression, or which add functionality such as mirroring traffic to multiple servers (e.g. using reliable ordered multicast).

This document has the following sections:

  • JDK 1.0: SocketImpl
  • JDK 1.1: Non-Final Socket and ServerSocket Classes
  • Socket: How to extend Socket
  • ServerSocket: How to extend ServerSocket

JDK 1.0: SocketImpl and SocketImplFactory

JDK 1.0 allows licensees to extend socket functionality in one very particular way: they can subclass java.net.SocketImpl , and provide an enhanced java.net.SocketImplFactory() which returns such classes as needed.

The SocketImpl/SocketImplFactory scheme is useful for, and was designed for, java apps/applications to be portable across environments that use different transport mechanisms. A client application that uses a java.net.Socket can work in the general case (where the runtime uses a PlainSocketImpl), as well as in environments where network connections must do something particular. For example, a java program should be able to work behind a firewall where connections to the Internet must be done through a proxy protocol, like SOCKS, assuming the right kind of SocketImpl is set for the java runtime in that environment.

Though the SocketImpl is useful for things like transparently providing proxy support to java apps, its utility is limited as a way to provide added functionality of network transport, or for layering other protocols on top of TCP. Additionally, it's only possible to have a single type of SocketImpl installed for a java runtime, which limits large-scale applications. It's cleaner and more intuitive to make ServerSocket and Socket extendable.

Note that the SocketImpl mechanism is designed to be orthogonal to the functionality provided by a subclass of Socket: for example, a subclass of Socket that is capable of doing compression on its streams would still want to use the system-default SocketImpl to get proxy support behind certain kinds of firewalls. The system-default SocketImpl can be thought of as an extension of the transport layer that applications needn't be aware of, and subclasses of Socket/ServerSocket provide richer functionality at the application layer.

Change in JDK 1.1

In JDK 1.1, Socket and ServerSocket are made non-final, which is a pretty simple change. The one basic caveat is that subclasses do not have direct access to the underlying SocketImpl in the base classes, primarily for security reasons. But other than that, subclasses of Socket/ServerSocket inherit and can override methods from their superclass.

The JDK changed by:

  • Removing the final modifier from the Socket and ServerSocket classes.
  • Reattaching that final modifier only to methods where it is needed to avoid bypassing security manager calls.
  • Defining a new method in ServerSocket with signature: protected final void implAccept(Socket client) to use when initializing a newly accepted socket.
  • Exposing a default Socket constructor so that Socket subclasses could initialize their superclass without doing an actual connection in the superclass. This is also required so that a ServerSocket subclasses can return the correct Socket subclass from accept() (e.g., FooServerSocket.accept() returns a FooSocket)

Changes to Socket

The public constructors to Socket of the general form:

        Socket(String host, int port) {
          ...
        }
can be used by subclasses to initialize the superclass, but they will also create a system-default SocketImpl and connect it to the specified host, port. Socket also has two protected constructors to intialize the superclass without connecting the Socket:
        protected Socket() {
          /* install system-default SocketImpl */
          ...
        }

        protected Socket(SocketImpl impl) {
          this.impl = impl;
        }
The first constructor installs a system-default SocketImpl (either from the factory or a PlainSocketImpl). The second allows for a subclass of Socket to install its own impl if need be. If the Socket subclass doesn't need the default SocketImpl, it's perfectly valid to use the second constructor and pass it null. (But in this case the subclass should of course override all the base class methods, since they all rely on the underlying SocketImpl).

Changes to ServerSocket

Subclasses of ServerSocket also have a protected constructor exposed to them that creates a default SocketImpl in the base class, but doesn't otherwise initialize it (e.g., doesn't call impl.create(), impl.bind() or impl.listen()). The public constructors of ServerSocket will initialize the underlying SocketImpl.

        protected ServerSocket() {
          /* install system-default SocketImpl */
          ...
        }
The only other thing about extending ServerSocket that should be explained is how to override accept() when the underlying SocketImpl for Socket/ServerSocket isn't accesible to subclasses. Since the base class can do this, ServerSocket has a method to make the necessary calls on the underlying SocketImpl's on behalf of subclasses:
public class ServerSocket {
        ...
        protected final void implAccept(Socket s) throws IOException {
           ...
           // on return from this call s will be connected to a client
        }
        ...
Note that subclasses of Socket/ServerSocket that don't use a SocketImpl needn't use this method. As an example of how this works, here's what some SSL code might look like.

class SSLServerSocket extends ServerSocket {
    ...
    public Socket accept () throws IOException
    {
        SSLSocket s = new SSLSocket (certChain, privateKey);
        // create an unconnected client SSLSocket, that we'll
        // return from accept

        implAccept (s);
        s.handshake ();
        return s;
    }
    ...
}

class SSLSocket extends java.net.Socket {
    ...
    public SSLSocket(CertChain c, PrivateKey k) {
        super();
        ...
    }
    ...
}
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


ExtensionInstallerService (JNLP API Reference 1.7.0)

  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method
javax.jnlp

Interface ExtensionInstallerService

  • public interface ExtensionInstallerService
    The ExtensionInstallerService is used by an extension installer to communicate with the JNLP Client. It provides the following type of functionality:
    • Access to prefered installation location, and other information about the JNLP Client
    • Manipulation of the JNLP Client's download screen
    • Methods for updating the JNLP Client with the installed code

    The normal sequence of events for an installer is:

    1. Get service using ServiceManager.lookup("javax.jnlp.ExtensionInstallerService").
    2. Update status, heading, and progress as install progresses (setStatus, setHeading and updateProgress).
    3. Invoke either setJREInfo or setNativeLibraryInfo depending on if a JRE or a library is installed
    4. If successful invoke installSucceeded, otherwise invoke installFailed.
    Since:
    1.0

    • Method Summary

      Methods
      Modifier and Type Method and Description
      java.net.URL getExtensionLocation()
      Returns the location of the extension being installed
      java.lang.String getExtensionVersion()
      Returns the version of the extension being installed
      java.lang.String getInstalledJRE(java.net.URL url, java.lang.String version)
      Returns the path to the executable for the given JRE.
      java.lang.String getInstallPath()
      Returns the directory where the installer is recommended to install the extension in.
      void hideProgressBar()
      Hides the progress bar.
      void hideStatusWindow()
      Hides the status window.
      void installFailed()
      This should be invoked if the install fails.
      void installSucceeded(boolean needsReboot)
      Installers should invoke this upon a succesful installation of the extension.
      void setHeading(java.lang.String heading)
      Updates the status of the installer process.
      void setJREInfo(java.lang.String platformVersion, java.lang.String jrePath)
      Informs the JNLP Client of the path to the executable for the JRE, if this is an installer for a JRE, and about platform-version this JRE implements.
      void setNativeLibraryInfo(java.lang.String path)
      Informs the JNLP Client of a directory where it should search for native libraries.
      void setStatus(java.lang.String status)
      Updates the status of the installer process.
      void updateProgress(int value)
      Updates the progress bar.

    • Method Detail

      • getInstallPath

        java.lang.String getInstallPath()
        Returns the directory where the installer is recommended to install the extension in. It is not required that the installer install in this directory, this is merely a suggested path.

      • getExtensionVersion

        java.lang.String getExtensionVersion()
        Returns the version of the extension being installed

      • getExtensionLocation

        java.net.URL getExtensionLocation()
        Returns the location of the extension being installed

      • hideProgressBar

        void hideProgressBar()
        Hides the progress bar. Any subsequent calls to updateProgress will force it to be visible.

      • hideStatusWindow

        void hideStatusWindow()
        Hides the status window. You should only invoke this if you are going to provide your own feedback to the user as to the progress of the install.

      • setHeading

        void setHeading(java.lang.String heading)
        Updates the status of the installer process.

      • setStatus

        void setStatus(java.lang.String status)
        Updates the status of the installer process.

      • updateProgress

        void updateProgress(int value)
        Updates the progress bar.
        Parameters:
        value - progress bar value - should be between 0 and 100.

      • installSucceeded

        void installSucceeded(boolean needsReboot)
        Installers should invoke this upon a succesful installation of the extension. This will cause the JNLP Client to regain control and continue its normal operation.
        Parameters:
        needsReboot - If true, a reboot is needed

      • installFailed

        void installFailed()
        This should be invoked if the install fails. The JNLP Client will continue its operation, and inform the user that the install has failed.

      • setJREInfo

        void setJREInfo(java.lang.String platformVersion,
              java.lang.String jrePath)
        Informs the JNLP Client of the path to the executable for the JRE, if this is an installer for a JRE, and about platform-version this JRE implements.

      • setNativeLibraryInfo

        void setNativeLibraryInfo(java.lang.String path)
        Informs the JNLP Client of a directory where it should search for native libraries.

      • getInstalledJRE

        java.lang.String getInstalledJRE(java.net.URL url,
                               java.lang.String version)
        Returns the path to the executable for the given JRE. This method can be used by extensions that needs to find information in a given JRE, or enhance a given JRE.
        Parameters:
        url - product location of the JRE
        version - product version of the JRE
        Returns:
        The path to the executable for the given JRE, or null if the JRE is not installed.
  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.


Deploying Java Extensions

Note: Java Extensions are also referred to as optional packages, standard extensions, or simply extensions.

This section covers the following topics:

  • Overview
  • Manifest of the applet JAR file
  • Manifest of each extension JAR file
  • Manifest of the Implementation-URL JAR file
    • Installing Java Extensions Using Raw installation
    • Installing Java Extensions Using Java Installer
    • Installing Java Extensions Using Native Installer
  • Security
  • Detailed Instructions
  • Known Limitations and Other Notes

Java applets may use Java extensions to provide extra functionality to users. Java Plug-in enables applets to trigger installation of various Java extensions (e.g., JavaHelp, Java 3D, Java Media Framework ...) in the Java Runtime Environment. This document describes the basic steps for deploying installed Java extensions (versus bundled Java extensions) with Java Plug-in. For details about how Java Extensions work, see the The Java Extensions Mechanism.

Overview

An applet that uses extensions is packaged as a signed JAR file including manifest. When an applet is downloaded and run with Java Plug-in, Java Plug-in checks the manifest of the applet JAR file. The manifest will contain a list of all extensions that the applet requires. An extension consists of one or more JAR files to be installed into the <jre>/lib/ext directory.

In general, for each extension the applet manifest will list name, vendor, and version information of the extension JARs; it will also list URLs from which the JARs, or an installer for them, may be obtained if the JARs are not already installed <jre>/lib/ext or are out of date. A URL may directly specify one of the extension JARs, or it may specify an installer, native or Java, that will install the extension JARs. The rules for deciding that an update is required are described in Optional Package Versioning.

To use Java Plug-in for deploying Java Extensions, information about the extensions must be specified in three different manifest files:

  1. Manifest of the applet JAR file

  2. Manifest of each extension JAR

  3. Manifest of the Implementation-URL JAR file

Each of these types of manifest files is described in detail below.

Manifest of the applet JAR file

To deploy Java extensions with an applet, the applet must be packaged as a JAR file. Moreover, the manifest file of the applet JAR must define the list of extensions it requires and specify the URLs from which the extensions can be downloaded, along with other information about the extensions, according to the Optional Package Versioning. For example, below is the manifest file for two extensions:

Extension-List: RectangleArea RectanglePerimeter
RectangleArea-Extension-Name: com.mycompany.RectangleArea
RectangleArea-Specification-Version: 1.2
RectangleArea-Implementation-Version: 1.2
RectangleArea-Implementation-Vendor-Id: com.mycompany
RectangleArea-Implementation-URL: http://mycompany.com/RectangleArea.jar
RectanglePerimeter-Extension-Name: com.mycompany.RectanglePerimeter
RectanglePerimeter-Specification-Version: 1.2
RectanglePerimeter-Implementation-Version: 1.2
RectanglePerimeter-Implementation-Vendor-Id: com.mycompany
RectanglePerimeter-Implementation-URL: http://mycompany.com/RectanglePerimeter.jar

In this example, two extensions are deployed with the applet—RectangleArea and RectanglePerimeter. Each has a single JAR file. If they have not been installed or if updated versions are needed, the proper versions will be downloaded from the Implementation-URL specifications. Notice that an Implementation-URL must point to a JAR file that:

  • is the desired extension JAR itself (for raw installation) or
  • contains a Java installer that will install the extension or
  • contains a native installer that will install the extension.

This will be explained in detail in the section below called The manifest of the Implementation-URL JAR file.

Extension-List names and attribute prefixes

There are two basic scenarios here: An extension may have a single JAR file, or it may have multiple JAR files. Extension-List names and attribute prefixes are discussed below for these two scenarios:

Extension with single JAR file

For an extension with a single JAR file (as in the example above), the name in the Extension-List, and the prefix of the related manifest attributes, should be the name of the extension JAR file.

Extension with multiple JAR files

Some extensions consist of multiple JAR files. For example, the Java 3D extension consists of the following JAR files: j3daudio.jar, j3dcore.jar, j3dutils.jar, and vecmath.jar. There are two scenarios that need to be considered: (1) The JARs are installed by a native or Java installer or (2) no installer is used (i.e., raw installation of the extension JARs).

If a native or Java installer is used to install an extension, then only one of the JAR file names should be used in the Extension-List, and only one set of attributes, using that name as the prefix, should appear. Usually an extension has a main JAR file; if so, you should use its name in the Extension-List and as the prefix for the related manifest attributes. If there is no main JAR file, you can use the name of any JAR file in the optional package.

Here is an example of the applet manifest for the Java 3D extension. j3dcore.jar is the main JAR file.

Extension-List: j3dcore
j3dcore-Extension-Name: javax.media.j3d
 j3dcore-Specification-Version: 1.2
j3dcore-Specification-Vendor: Sun Microsystems, Inc
j3dcore-Implementation-Version: 1.2.1_03
j3dcore-Implementation-Vendor-Id: com.sun
j3dcore-Implementation-URL: http://<myserver>/native/java3d-win.jar

For a raw installation with multiple JAR files, the story is different: You must treat each JAR file as though it were a separate extension and list each according to its name in the Extension-List. Each one listed then must have its own set of manifest attributes, where the prefix for an attribute set is the name of the related JAR file.

Note on JAR Extension Identification:

Note that Java Plug-in checks four manifest attributes of an installed extension JAR file:

  • Extension-Name
  • Specification-Version
  • Implementation-Version
  • Implementation-Vendor-Id

Extension-Name and Implementation-Vendor-Id must match exactly the values specified in the applet manifest file.

  • See Optional Package Versioning for how Java Plug-in evaluates the version attributes of an installed extension to decide if a newer extension needs to be downloaded.
  • See Appendix 6: Sun-Supported Specification-Version and Implemenation-Version Formats for rules about the format of Specification-Version and Implemenation-Version.

Manifest of each extension JAR file

Here we are talking about the JAR files that Plug-in can obtain from the URLs specified by Implemenation-URL. The URL-obtainable extension JARs may be directly obtained (raw installation) or they may be obtained via a Java or native installer. In either case they are installed into <jre>/lib/ext.

The extensions that the applet requires are listed in the applet manifest. This allows Plug-in to examine the JAR files present in the <jre>/lib/ext directory when an applet is launched and to decide if it needs to install missing or out-of-date extensions.

In general, the manifest of an extension JAR obtained via an Implementation-URL needs to include various name, version, and vendor information. Thus, when such an extension JAR is installed, it will be possible in the future for Java Plug-in to compare this information to the information about an extension that an applet requests; and Plug-in will be able to determine if an extension needs to be installed/upgraded. Prior to any applet ever requesting an extension, it is more than likely that no extension is installed in <jre>/lib/ext, or that no or incomplete manifest information is present in the installed extension JAR.

For an extension with a single JAR file, the JAR file must be signed and include a manifest file with the following attributes:

  • Extension-Name
  • Specification-Vendor
  • Specification-Version
  • Implementation-Vendor-Id
  • Implementation-Vendor
  • Implemenation-Version

Example

Extension-Name: javax.help
Specification-Vendor: Sun Microsystems, Inc
Specification-Version: 1.0
Implementation-Vendor-Id: com.sun
Implementation-Vendor: Sun Microsystems, Inc
Implementation-Version: 1.1.3

If an extension consists of more than one JAR file and the extension is installed with a native/Java installer, then only the JAR file whose name is listed in the Extension-List of the applet manifest needs to have extension information (i.e., Extension-Name, Specification-Version, etc.). If no installer is used, then all JAR files must include extension information.

See Optional Package Versioning for more information about these attributes.

Manifest of the Implementation-URL JAR file

This is the JAR file which the applet refers to with the Implementation-URL attribute in its manifest. It is the URL from which the extension can be obtained if no extension is installed in <jre>/lib/ext, or an extension is installed but it is out of date.

If the Implementation-URL JAR is a native or Java installer, this is indicated in the manifest via two special attributes: Main-Class indicates a Java installer; Extension-Installation indicates native installer. Note that if no installer is indicated, then the Implementation-URL JAR file is simply the extension JAR file itself. There are three ways that extensions can be installed by Java Plug-in. They are:

  • Using Raw Installation
  • Using Java Installer
  • Using Native Installer

Each method is discussed below:

Installing Java Extensions Using Raw Installation

With raw installation of an extension, each extension JAR is installed by Java Plug-in into the <jre>/lib/ext directory without an installer (Java or native); i.e., Java Plug-in is the "installer" for each JAR. If an extension has a single JAR file, then the URL of that JAR is shown as the Implementation-URL in the applet JAR manifest; and Java Plug-in knows it is a raw extension because the manifest of the extension JAR file includes neither Main-Class nor Extension-Installation attribute.

Suppose we have an extension called javax.mediax with a single JAR, mediax.jar. Then the applet and extension JAR might be as shown below:

Example: Applet JAR manifest

Extension-List: mediax
mediax-Extension-Name: javax.mediax
mediax-Specification-Version: 1.1
mediax-Implementation-Version: 1.1.2
mediax-Implementation-Vendor-Id: com.sun
mediax-Implementation-URL: http://java.sun.com/products/plugin/extensions/examples/media/mediax.jar

Example: Extension JAR manifest

Extension-Name: javax.mediax
Specification-Vendor: Sun Microsystems, Inc
Specification-Version: 1.1
Implementation-Vendor-Id: com.sun
Implementation-Vendor: Sun Microsystems, Inc
Implementation-Version: 1.1.2
Now suppose we have another version, javax.mediax-2, that has two JARs: mediax_core.jar and mediax_codec.jar. Then we must treat the two JAR files as though they were separate extensions and list each in the applet JAR manifest.

Example: Applet JAR manifest

Extension-List: mediax_core mediax_codec
mediax_core-Extension-Name: javax.mediax_core
mediax_core-Specification-Version: 1.1
mediax_core-Implementation-Version: 1.1.2
mediax_core-Implementation-Vendor-Id: com.sun
mediax_core-Implementation-URL: http://java.sun.com/products/plugin/extensions/examples/media/mediax_core.jar
mediax_codec-Extension-Name: javax.mediax_codec
mediax_codec-Specification-Version: 1.1
mediax_codec-Implementation-Version: 1.1.2
mediax_codec-Implementation-Vendor-Id: com.sun
mediax_codec-Implementation-URL: http://java.sun.com/products/plugin/extensions/examples/media/mediax_codec.jar

Example: Extension JAR manifests

Extension-Name: javax.mediax_core
Specification-Vendor: Sun Microsystems, Inc
Specification-Version: 1.1
Implementation-Vendor-Id: com.sun
Implementation-Vendor: Sun Microsystems, Inc
Implementation-Version: 1.1.2

Extension-Name: javax.mediax_codec
Specification-Vendor: Sun Microsystems, Inc
Specification-Version: 1.1
Implementation-Vendor-Id: com.sun
Implementation-Vendor: Sun Microsystems, Inc
Implementation-Version: 1.1.2

Installing Java Extensions Using Java Installer

An extension can be installed through a Java installer. The Java installer must be bundled as a JAR file, and the resulting JAR file must be specified as Implementation-URL in the applet JAR manifest file. During installation the JAR file will be downloaded and verified, and the Main-Class of the Java installer inside the JAR file will be executed to start the installer. It is the job of the Java installer to copy the extension JAR files, normally bundled with the installer, into the right location of the Java Runtime (i.e., <jre>/lib/ext).

Though we are now dealing with an application JAR file, the attributes in its manifest should be the same as those shown for the extension JAR whose name is listed in the Extension-List of the applet manifest—with the addition of the Main-Class attribute.

Example: Java Installer JAR manifest

Extension-Name: javax.help
Specification-Vendor: Sun Microsystems, Inc
Specification-Version: 1.1
Implementation-Vendor-Id: com.sun
Implementation-Vendor: Sun Microsystems, Inc
Implementation-Version: 1.1.3
Main-Class: com.sun.javahelp.installer
In this case, because Main-Class is present in the manifest, the JAR will be treated as a Java Installer, and Main-class will be invoked. It is the job of the Java installer to copy the extensions JAR files into the <jre>/lib/ext directory. Note that each extension JAR file must contain proper versioning information.

Installing Java Extensions Using Native Installer

An extension can also be installed through a native installer. The native installer must be bundled as a JAR file, and the resulting JAR file must be specified as the Implementation-URL in the applet JAR manifest file. During installation the JAR file will be downloaded and verified, and the native installer will be started. It is the job of the native installer to copy the extension JAR files, normally bundled with the installer, into the right location of the Java Runtime (i.e., <jre>/lib/ext).

Though we are now dealing with an application JAR file, the attributes in its manifest should be the same as those shown for the extension JAR whose name is listed in the Extension-List of the applet manifest—with the addition of the Extension-Installation attribute.

Example: Native Installer Jar Manifest

Extension-Name: javax.media.jmf
Specification-Vendor: Sun Microsystems, Inc
Specification-Version: 2.1
Implementation-Vendor-Id: com.sun
Implementation-Vendor: Sun Microsystems, Inc
Implementation-Version: 2.1.1
Extension-Installation: jmf-2_1_1-win.exe

In this case, because Extension-Installation is present in the manifest, the JAR will be treated as a native installer; and the installer itself will be launched. It is the job of the native installer to copy the Java extensions into the <jre>/lib/ext directory. Note that each Java extension JAR file must contain proper versioning information.

Security

When an installed extension needs to be updated, the extension will be downloaded and verified to ensure that it is correctly signed. If it is valid, the Plug-in may pop-up a security dialog providing user with an option to continue with extension installation or cancel the installation.

Once the user selects the option from the security dialog, the extensions installation will be executed in the corresponding security context. The applet will not be started until the extensions are properly installed.

Because Java extensions are downloaded and installed into the Java Runtime <jre>/lib/ext directory, each must be signed. Once the extensions are installed, they will have the permissions granted to Java extensions through the policy file.

Detailed Instructions

Follow these steps to set up extensions for use with Java Plug-in:

I. Create/obtain the extensions that your applet needs.

Each extension will consist of one or more JAR files, each of which must include a manifest file with version information as described above in Manifest of each extension JAR file, and each must be signed. (See exception to this with mulitple JARs installed with native/Java installer.)

To create a JAR file from any set of files, use this command:

% jar cmf my_manifest my_jar input_files

For more information about the jar tool, see the Tools and Utilities documentation for your platform.

To sign the JAR file is going to take some trouble. In outline form, this is what you can do:

  1. Use the keytool -genkey option to generate a key pair.
  2. Use the keytool -certreq to generate a certificate request for a Certificate Authority (CA), such as VeriSign and Thawte. Email the request to the CA. After the CA has confirmed your identity, it will respond with a certificate chain via email. Copy the certificate chain to a file.
  3. You can then use the keytool -import option to import the chain to the keystore.
  4. You can now use the jarsigner tool to sign the JAR and the -verify option to check that it is signed.

For more information about keytool and jarsigner, see the Tools and Utilities documentation for your platform.

More information on this topic, along with examples, is given in the chapter called How to Sign Applets Using RSA-Signed Certificates. Although that chapter discusses how to sign an applet JAR file, the process is identical to signing an extension JAR file.

II. Create/obtain the Implementation-URL JAR files

If no installer is to be used:

The extension JAR files described in step I are the Implementation-URL JARs.

If an installer is to be used:

  1. Create/obtain the installer.
  2. Create the manifest for the JAR of the installer and any bundled extensions that need to go into it.
    • For a Java installer include the Main-Class attribute in the manifest;
    • for a native installer include the Extension-Installation attribute.
  3. JAR the installer, the manifest, and any bundled extensions that need to be included and sign the JAR. (The steps for JARing and signing are the same as described in step I above.)

Example

Suppose we have an applet that requires Sun's Java Advanced Imaging as an installed extension. You can download this here:

http://java.sun.com/products/java-media/jai/downloads/download.html

Suppose you select the "Windows JRE Install" version. The following file will be downloaded:

jai-1_1_1_01-lib-windows-i586-jre.exe

This installer bundles the following JAR files, which it will install into the <jre>/lib/ext directory:

  • jai_codec.jar
  • jai_core.jar
  • mlibwrapper_jai.core

You need to create the manifest for a JAR file that contains the .exe installer above, and you need to sign the JAR file.

The manifest would look like this:

Extension-Name: javax.media.jai
Specification-Vendor: Sun Microsystems, Inc
Specification-Version: 1.1
Implementation-Vendor-Id: com.sun
Implementation-Vendor: Sun Microsystems, Inc
Implementation-Version: 1.1.1_01
Extension-Installation: jai-1_1_1-01-windows-i586-jre.exe

Now JAR up the installer as jai_win.jar, together with the manifest file. You don't need to include the extension JAR files, as they are bundled with the .exe installer in this case. Be sure to include the .jar extension in the JAR file name.

Now sign jai_win.jar.

III. Create the applet JAR

1. Create a manifest file for the applet. Below is a manifest file for the jai example using a native installer:

Extension-List: jai_core
jai_core-Extension-Name: javax.media.jai
jai_core-Specification-Version: 1.1
jai_core-Implementation-Version: 1.1.1_01
jai_core-Implementation-Vendor-Id: com.sun
jai_core-Implementation-URL: http://myserver.com/jai_win.jar

Some optional packages come packaged in different JAR files for different operating systems. If you want your applet to work on different OSs, you can use the $(os-name)$ construction in the Implementation-URL manifest attribute. The $(os-name)$ will translate to the target OS that the applet is being run on—i.e., SunOS, Linux, Windows-98, Windows-NT, Windows-2000, Windows-Me.

optpkg-Implementation-URL: http://.../optpkg-$(os-name)$.jar

2. JAR up the *.class files, and any other supporting files the applet needs, together with the applet's manifest file, and sign the JAR. (The procedure for JARing your files and signing the JAR is the same as discussed previously.) Be sure to include the .jar extension in the JAR file name.

IV. Generate the HTML to launch the applet

Create the HTML page for the applet. You can do this manually or you can use the HtmlConverter that comes with the JDK. It is recommended that you use the HtmlConverter. But if you want to do it manually, see Using OBJECT, EMBED and APPLET Tags in Java Plug-in for information on how to do it. Note that the applet JAR file should go in the archive attribute.

Suppose your applet is called JaiApplet, the JAR file you created for it is called JaiApplet.jar, and the main class is JaiApplet.class.

Assume the original applet looks like this:

<html>
<head>
<title>JaiApplet</title>
</head>
<body>
<APPLET code="JaiApplet.class" archive="JaiApplet.jar" align="absmiddle" WIDTH="400"HEIGHT="300"> </APPLET>
</body>
</html>

Then if we use the HtmlConverter to convert it for dynamic versioning, we will have this:

<html>
<head>
<title>JaiApplet</title>
</head>
<body>
<!--"CONVERTED_APPLET"-->
<!-- HTML CONVERTER -->
<OBJECT
    classid = "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
    codebase = "http://java.sun.com/update/1.6.0/jinstall-6-windows-i586.cab#Version=6,0,0,99"
    WIDTH = "400" HEIGHT = "300" ALIGN = "absmiddle" >
    <PARAM NAME = CODE VALUE = "JaiApplet.class" >
    <PARAM NAME = ARCHIVE VALUE = "JaiApplet.jar" >
    <PARAM NAME = "type" VALUE = "application/x-java-applet;version=1.6">
    <PARAM NAME = "scriptable" VALUE = "false">
    <COMMENT>
    <EMBED
            type = "application/x-java-applet;version=1.6"
            CODE = "JaiApplet.class"
            ARCHIVE = "JaiApplet.jar"
            WIDTH = "400"
            HEIGHT = "300"
            ALIGN = "absmiddle"
          scriptable = false
         pluginspage = "http://java.sun.com/products/plugin/index.html#download">
       <NOEMBED>
            </NOEMBED>
      </EMBED>
    </COMMENT>
</OBJECT>
<!--
<APPLET CODE = "JaiApplet.class" ARCHIVE = "JaiApplet.jar" WIDTH = "400" HEIGHT = "300" ALIGN = "absmiddle">
</APPLET>
-->
<!--"END_CONVERTED_APPLET"-->
</body>
</html>

When you run the applet, Java Plug-in will display a Java Security Warning if the extension is not already installed, informing you the applet requires installation of extension javax.media.jai from http://myserver.com/jai_win.jar. If you grant permission to install the extension, the installer will install the JAR files in the <jre>/lib/ext directory. Once the installation is complete your applet will run.

See Appendix 5: Complete Example—Deploying Java Media Framework as Java Extension for a complete, working example showing how to deploy the Java Media Framework as a Java Extension.

Known Limitations and Other Notes

  • If an Implementation-URL JAR file is not signed properly, Java Plug-in will fail silently.
  • For any extension be sure that a newer version of the extension contains at least the same set of JAR file names as the older version. Otherwise, installing a newer extensions may not overwrite all the older extensions JARs, and there will be a mix of different versions of an extension in <jre>/lib/ext. The results will be unpredictable.
  • If Java Installer is used, make sure the program does not exit the Main-class until the installation is done. In some cases, Java Installer may create an AWT window and switch control to a different thread and return immediately from the Main-class. Returning control from the Main-class will force the applets to be loaded and started immediately, even if the Java Installer is still in the process of installation. This will cause the applet to fail to load because the extension is not installed yet.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Complete Example: Java Media Framework as Java Extension

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

< Contents

Appendix 3: Complete Example—Deploying Java Media Framework as Java Extension

This section covers the following topics:

  • Introduction
  • Creating the jar File to Be Installed
  • Creating the Applet jar File
  • Creating the HTML for the Applet
  • Testing the Example

Introduction

This is a complete, working example showing how to deploy a single jar file from Java Media Framework (JMF) as a Java Extension. The example uses SimplePlayerApplet.java and jmf.jar to play an .avi media file. It uses the raw installation method for installating a repackaged and signed version of jmf.jar called s_my_jmf.jar. Normally there are other jar files that are installed with JMF, but for SimplePlayerApplet.java only the functionality in jmf.jar is required.

For simplicity sake, this example makes the following assumptions:

  • You are working on a Microsoft Windows system.
  • You have intalled the 1.6 JDK in the following location on your computer: C:\"Program Files"\Java\jdk1.6.0
  • For signing purposes you have set up a keystore in the following directory: C:\plugin\keystores
  • The keystore name is thawte.p12
  • The storepass and the keypass are the same: mypass
  • The keystore alias is "Sun Microsystems Inc.'s Thawte Consulting cc ID"

Creating the jar File to Be Installed

In this case there is no installer. All you need to do is obtain the required jar file, jmf.jar, that needs to be downloaded and copied into <jre_location>/lib/ext. Plug-in, in conjunction with the extension mechanism in the JRE, handles the installation (downloading and copying of the file) for you.

You can get jmf.jar by downloading the cross-platform installation zip file jmf-2_1_1e-alljava.zip from http://java.sun.com/products/java-media/jmf/2.1.1/download.html. Along with other jar files, the zip file contains jmf.jar, which you can extract from the zip.

Once you have obtained jmf.jar, you will want to extract jmf.jar itself into some directory, say C:\plugin\extensions\workspace1. Here you will want to delete the META-INF directory if it exists, as the manifest.mf file contains signing information that you do not want.

Next you need to create your own manifest file for the new jar file to be based on jmf.jar. The manifest file that we create we call jmf_manifest. It will be provided as input to the jar tool. Here is what is used in this example:

Extension-Name: javax.media.s_my_jmf
Specification-Vendor: Sun Microsystems, Inc
Specification-Version: 2.1
Implementation-Vendor-Id: com.sun
Implementation-Vendor: Sun Microsystems, Inc
Implementation-Version: 2.1.1

First we will jar the files in jmf.jar and rename the result my_jmf.jar. Then we will sign the result and call it s_my_jmf.jar.

In order to jar the files in workspace1 with our new manifest file jmf_manifest, we cd to the location of workspace1, then we use the jar tool in the JDK as follows:

C:\plugin\extensions\workspace1>C:\"Program Files"\Java\jdk1.6.0\bin\jar cmf jmf_manifest my_jmf.jar *.class codecLib com javax jmapps

Note that codecLib, com, javax, and jmapps are subdirectories that must be jar'd as well as *.class.

If you have a Thawte keystore called thawte.p12 located in C:\plugin\keystores with the same password, mypass, for both storepass and keypass, and storetype "pkcs12" and keystore alias "Sun Microsystems Inc.'s Thawte Consulting cc ID", then you can skip the next step and proceed to signing of my_jmf.jar and creating a signed jar file called s_my_jmf.jar.

You can create a keystore called thawte.p12 with the same password, mypass, for both storepass and keypass and keystore alias "Sun Microsystems Inc.'s Thawte Consulting cc ID" by running the following command:

C:\plugin\keystores>C:\"Program Files"\Java\jdk1.6.0\bin\keytool -genkey -alias "Sun Microsystems Inc.'s Thawte Consulting cc ID" -keypass mypass -keystore thawte.p12 -storetype pkcs12 -storepass mypass

In this example we use the jarsigner tool to sign the new jar file. Use

C:\plugin\extensions\workspace1>C:\"Program Files"\Java\jdk1.6.0\bin\jarsigner -keystore C:\plugin\keystores\thawte.p12 -storepass mypass -keypass mypass -storetype "pkcs12" -signedjar s_my_jmf.jar my_jmf.jar "Sun Microsystems Inc.'s Thawte Consulting cc ID"

We can verify the new signed jar file as follows:

C:\plugin\extensions\workspace1>C:\"Program Files"\Java\jdk1.6.0\bin\jarsigner -verify s_my_jmf.jar

We now have a signed jar file with the proper manifest.mf file for raw installation.

Next we need to create the applet jar file.

Creating the Applet jar file

The applet consists of a single file, SimplePlayerApplet.class, that can be used to playback a media file. The source code for the applet can be viewed here. What we need to do is create a manifest file called for the applet, which we will call applet_manifest, jar the applet with the manifest, then sign the result..

The applet applet_manifest is as follows:

Extension-List: s_my_jmf
s_my_jmf-Extension-Name: javax.media.s_my_jmf
s_my_jmf-Specification-Version: 2.1
s_my_jmf-Implementation-Version: 2.1.1
s_my_jmf-Implementation-Vendor-Id: com.sun
s_my_jmf-Implementation-URL: http://java.sun.com/products/plugin/extensions/examples/jmf/s_my_jmf.jar

Note that the above manifest says that the extension jar, s_my_jmf.jar, can be downloaded from the java.sun.com web server at http://java.sun.com/products/plugin/extensions/examples/jmf

If the SimplePlayerApplet.class and applet_manifest are located in C:\plugin\extensions\workspace2, we can jar the applet with the manifest with the following command:

C:\plugin\extensions\workspace2>C:\"Program Files"\Java\jdk1.6.0\bin\jar cmf applet_manifest my_SimplePlayerApplet.jar *.class

Again, we use jarsigner to sign the jar file:

C:\plugin\extensions\workspace2>C:\"Program Files"\Java\jdk1.6.0\bin\jarsigner -keystore C:\plugin\keystores\thawte.p12 -storepass mypass -keypass mypass -storetype "pkcs12" -signedjar s_my_SimplePlayerApplet.jar my_SimplePlayerApplet.jar "Sun Microsystems Inc.'s Thawte Consulting cc ID"

and we verify it as follows:

C:\plugin\extensions\workspace2>C:\"Program Files"\Java\jdk1.6.0\bin\jarsigner -verify s_my_SimplePlayerApplet.jar

We now have our signed applet jar file called s_my_SimplePlayerApplet.jar, whose manifest contains the correct information to trigger the installation of the required extension jar file, s_my_jmf.jar if no such file or an older version is found in <jre_location>/lib/ext.

Next we need to create the HTML for the applet.

Creating the HTML for the Applet

We have several choices. We can use the conventional APPLET tag and assume those who visit the page have Java Plug-in version 1.3.1_01 or later installed on their systems. (To use Java Plug-in to launch an applet with the conventional applet tag requires 1.3.1_01 or later.) We can also use the HTML Converter, located in the JDK in the bin directory (<sdk_location>/bin/HtmlConverter.exe) to convert the applet to various forms. Here we use the conventional applet form shown below:

SimplePlayerApplet-1.html

<html>
<head>
<title>SimplePlayerApplet</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body bgcolor="#FFFFFF" text="#000000">
<applet code="SimplePlayerApplet.class" archive="s_my_SimplePlayerApplet.jar" width=320 height=300>
<param name="file" value="0720crt1.avi">
</applet>
</body>
</html>

Note that the media file is 0720crt1.avi.

For this example the following files have been placed on the java.sun.com web server at http://java.sun.com/products/plugin/extensions/examples/jmf:

  • 0720crt1.avi
  • s_my_jmf.jar
  • s_mySiplePlayerApplet.jar
  • SimplePlayerApplet-1.html

Testing the Example

You can test the setup by clicking the link here:

SimplePlayerApplet-1.html

When you point your browser at the URL, the applet jar will first be downloaded and cached; and, if the extension has not already been installed, you will see a Java Request Download dialog that says: 'The applet requires installation of optional package. Do you want to continue?'. You will have the options to continue or cancel. If you continue installation by pressing OK button, you will see the Security Warning dialog for the extension jar file. You can proceed with package installation by pressing Run button. The extension will be installed in <jre_location>/lib/ext and the applet will run.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Applying the Factory Pattern to Java(TM) RMI

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Applying the Factory Pattern to Java™ RMI

What is a "factory" and why would you want to use one? A factory, in this context, is a piece of software that implements one of the "factory" design patterns. In general, a factory implementation is useful when you need one object to control the creation of and/or access to other objects.By using a factory in Java™ Remote Method Invocation (Java RMI), you can reduce the number of objects that you need to register with the Java RMI registry.

Examples of Factories in the Real World:

The Bank

When you go to the bank to make a deposit to your account, you don't walk up to a vault, pull out a drawer with your name on it, drop in your money, shut the drawer and leave. Think about how you originally established, or opened, the account. You probably went to the bank, spoke with an Account Manager, and signed some papers. In return, they gave you some checks, a passbook, or a bank card so you could access your account in the future.

The Account Manager is an example of a factory. The person or Automated Teller Machine (ATM) that acts as account manager controls the creation of and/or access to individual accounts.

The Library

Let's think about how a book, compact disk, or video tape gets from the library shelf into your home. Before you can check out any material, you must first get a library card from the librarian. In this case, the librarian could be viewed as a library card factory because the librarian controls the creation of new library card instances.

Once you have a library card, you can go into the library, and without any further fuss, just walk out with all your materials, right? Of course not. Before you can walk out of the library without setting off the alarm system, you must check out the book, CD, or video tape you wish to take home. So you present your library card to, you guessed it, the librarian, who will use your card to access the library database to see if you owe any late fees, and to register these new materials as having been leased to you. In this case, the librarian could be seen as a book factory because the librarian controls your access to the books.

How Does a Factory Work in Java RMI?

Just like any other Java RMI program, there are a few basic players: a server that produces one or more remote objects, each of which implements a remote interface; a client that accesses a name server (the rmiregistry) to get a reference to one of the remote objects; and the rmiregistry, which facilitates the client's initial contact with the server.

For the picture below and the steps that follow, you may make the following assumptions:

  • There are two remote interfaces that the client understands, Factory and Product
  • The FactoryImpl implements the Factory interface and the ProductImpl implements the Product interface
Illustrates the 6 actions listed below.

  2. The FactoryImpl registers, or is registered, with the rmiregistry
  3. The client requests a reference to a Factory
  4. The rmiregistry returns a remote reference to a FactoryImpl
  5. The client invokes a remote method on the FactoryImpl to obtain a remote reference to a ProductImpl
  6. The FactoryImpl returns a remote reference to an existing ProductImpl or to one that it just created, based on the client request
  7. The client invokes a remote method on the ProductImpl

How Could the Bank and Library be Implemented in Java RMI?

The Bank

In code, AccountManager would be a remote interface with one or more remote methods. These methods would return objects that implement the Account interface. In a similar fashion, Account would be an interface that declared all of the operations a person could perform on an account instance, such as depositing or withdrawing money, getting an account balance, or listing the most recent account transactions.

In Java RMI, only the instance of the AccountManager implementation would be registered with the Java RMI registry. The AccountManager implementation would be the factory, returning remote references to (or serialized instances of) Account implementations, like your savings account.

The Library

In the library example, the Librarian would be a remote interface with one or more methods that would return objects that implement the LibraryCard interface. In addition, the Librarian interface would have methods to allow you access to books, CDs, or videotapes that implemented the Loanable interface.

In Java RMI, only the instance of the Librarian implementation would be registered with the Java RMI registry. The Librarian implementation would be the factory, returning remote references to (or serialized instances of) LibraryCard implementations and Loanable object implementations.

While the bank and library examples presented here may not be entirely complete they are not designed to be complete, but rather instructionally useful in describing the factory pattern in Java RMI.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Windows Online Installation and Java Update FAQ

Questions:

Q. I have "Check for Updates Automatically" checked in the Java Control Panel, but scheduled automatic updates do not seem to happening. Is there something wrong?

Q: I downloaded the installer and it is only 200KB. Why is it so small?

Q: Why does Java Update ask me to reboot?

Q: I had the Java Control Panel open for Java Update and the About tab showed version x.x.x. Then I ran Java Update and it still showed version x.x.x. Why is this?

Q: Netscape/Mozilla is not working correctly with Java Plug-in. Why?

Q: I try to install on the D:\ drive and Java Update is still installing files onto the C:\ drive. Why?

Q: How can I uninstall the Java Update version I just installed?

Q. After the JRE bootstrap installer is downloaded and executed, why does the message "This installer cannot proceed with the current Internet Connection settings of this system. Please check your Control Panel -> Internet Options, and make sure the settings and proxy information are correct, and/or make sure you can view webpages through Internet Explorer" appear?.

Q: I found two processes—jucheck.exe and jusched.exe—running in the background of my system after installing JRE. Is there a way to shut them down?

Q . After Java Update updates my system, my browser still uses the Microsoft VM, or an older version of the Sun Java VM, to run applets. What's wrong?

Q: When I click the Update Now button from the Java Control Panel, it complains about the system being "offline." What does that means?

Q: I followed the instruction to install version x.x.x. After the installation and reboot, a message popped-up from system tray saying an update is available for download. What should I do?

Q: I want to try out Java Update but I am afraid beta software may cause problems on my computer. What should I do?

Q: I encountered the error "Error 1606: Could not access network location file MSI/CAB and still fail after immediate retry." when running the Java SE installer.

Q: I encountered the error "This installation package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer package." when running the Java SE installer.

Q: Error 1311: Source File Not Found. Could not find C:\Downloads\ja555000.cab.

Q: Error 1722. There is a problem with this windows installer package. A program run as part of the setup did not finish as expected. Contact your support personnel or package vender.

Questions and Answers:

Q. I have "Check for Updates Automatically" checked in the Java Control Panel, but scheduled automatic updates do not seem to happening. Is there something wrong?

A: The automatic update feature works only on Windows 2000 with SP3 and WindowsXP. If you are running on one of the other supported operating system, this feature will not work. If you want to do an update, use the Update Now button for manually updating Java.

Q: I downloaded the installer and it is only 200KB. Why is it so small?

A: The Java installer is designed for Install On Demand. It will download more installer files based on user selection and system configuration. Using this installer helps users avoid downloading large amounts of unnecessary files.

Q: Why does Java Update ask me to reboot?

A: Rebooting is sometimes required because installing Windows Installer 2.0 the Microsoft technology used by the Java installer requires rebooting.

Note: Java Installer now detects Java enabled Mozilla browsers locked files and will prompt you to close the browser so that a reboot can be avoided.

Q: I had the Java Control Panel open for Java Update and the About tab showed version x.x.x. Then I ran Java Update and it still showed version x.x.x. Why is this?

A: You need to close and restart the Java Control Panel to get the updated Control Panel.

Q: Netscape/Mozilla is not working correctly with Java Plug-in. Why?

A: First close all the browsers sessions. If this does not work, reboot the system and try again.

Q: I try to install on the D:\ drive and Java Update is still installing files onto the C:\ drive. Why?

A: Regardless of whether an alternate target directory was selected, Java Update needs to install some update files on the Windows system drive . Doing so saves download time on future updates to the latest version of Java.

Q: How can I uninstall the Java Update version I just installed?

There are two ways to accomplish this:

  1. If you want to uninstall the JRE, use the "Add/Remove Programs" utility in the Microsoft Windows Control Panel (Start->Settings->Control Panel to get to "Add/Remove Programs").
  2. Alternatively, if you still have the original installation program that you used to install the JRE, you can double-click on it. This will take you to a screen with Modify and Remove options. Select Remove to uninstall the JRE. Note that you must be connected to the Internet for this to work.

Q. After the JRE bootstrap installer is downloaded and executed, why does the message "This installer cannot proceed with the current Internet Connection settings of your system. In your Windows Control Panel, please check Internet Options -> Connections to make sure the settings and proxy information are correct." appear?.

A: The JRE bootstrap installer uses the system Internet Connection settings to connect to the web for downloading extra files. If you are behind a firewall and require proxy settings, make sure the proxy settings in Internet Options/Internet Properties are set up properly (Start->Control Panel->Internet Options/Internet Properties->Connections->LAN Settings ...).

If you can browser the external web (i.e., outside the firewall) with Internet Explorer, then your proxy settings are properly set up. The installer doesn't understand the proxy settings specified in Netscape/Mozilla.

Q: I found two processes—jucheck.exe and jusched.exe—running in the background of my system after installing JRE. Is there a way to shut them down?

A: jusched.exe is the scheduler process of Java Update; jucheck.exe is the process for checking/performing updates in Java Update. These processes run automatically and transparently to users. To shutdown these processes, simply uncheck the "Check for Updates Automatically" checkbox in the Update tab of Java Control Panel.

Q . After Java Update updates my system, my browser still uses the Microsoft VM, or an older version of the Sun Java VM, to run applets. What's wrong?

A: If you installed the JRE through the Custom option but unchecked the browser selections, you may run into this situation. To fix the problem, go to the Browser tab in Java Control Panel and check the browsers that you want to run the newly installed version of Java.

Q: When I click the "Update Now" button from the Java Control Panel, it complains about the system being "offline." What does that means?

A: Java Update can only be run if the system is connected to the network. A system that is not connected to the network is referred to as being "offline". When the Update Now button is clicked, it will check the online/offline status of your system. If your system is not currently connected to the network or dial-up networking is disconnected, the error message will show up. Check that your system is currently connected to the network and try it again.

Q: I followed the instruction to install version x.x.x. After the installation and reboot, a message popped-up from system tray saying an update is available for download. What should I do?

A: The message is part of the Java Auto Update mechanism, which detects at user login time if a newer version of the JRE is available for download . You may simply click on the system tray Java Update icon to download and install the update.

Q: I want to run Java Update but I am afraid it may cause problems on my computer. What should I do?

A: You may want to backup your Windows registry before testing out Java Update. The following command will export the necessary registry keys to a file:

regedit -e reg.1 -t HKEY_LOCAL_MACHINE
regedit -e reg.2 -t HKEY_CURRENT_USER
regedit -e reg.3 -t HKEY_CLASSES_ROOT

To fully restore the registry keys, the following command can be used to import the exported registry values:

regedit -i reg.1
regedit -i reg.2
regedit -i reg.3

Q: I encountered the error "Error 1606: Could not access network location file MSI/CAB and still fail after immediate retry." when running the Java SE installer.What does it mean?

A: This problem occurs when the server is too busy or when the network is too congested to serve the file. Please retry by running the installer again.

Q: I encountered the error "This installation package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer package." when running the Java SE installer.

A: There are several possible reasons:

  • Network connection fails
  • Download manager software interrupts the download process, e.g., GetRight;
  • TSR (Terminate and Stay Resident) programs, like Norton Anti Virus, may distract the installation process.

To address these problems, please make sure third-party downloader/TSR programs are turned off and the network connection is setup properly. Also, if a proxy is in use, make sure that proxy authentication is turned off.

Q: Error 1311: Source File Not Found. Could not find C:\Downloads\ja555000.cab.

A: This is a known MSI engine problem. See following:

  • http://support.microsoft.com/default.aspx?scid=kb;[LN];Q290106
  • http://support.microsoft.com/default.aspx?scid=kb;[LN];Q307346
  • http://support.microsoft.com/default.aspx?scid=kb;[LN];290896

Q: Error 1722. There is a problem with this windows installer package. A program run as part of the setup did not finish as expected. Contact your support personnel or package vender.

A: If you encounter this error please contact the feedback alias at java-deployment-feedback@sun.com.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.Field (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.Field

  • Packages that use Field
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.
    com.sun.jdi.event
    This package defines JDI events and event processing.
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of Field in com.sun.jdi

      Methods in com.sun.jdi that return Field
      Modifier and Type Method and Description
      Field ReferenceType.fieldByName(String fieldName)
      Finds the visible Field with the given non-ambiguous name.
      Methods in com.sun.jdi that return types with arguments of type Field
      Modifier and Type Method and Description
      List<Field> ReferenceType.allFields()
      Returns a list containing each Field declared in this type, and its superclasses, implemented interfaces, and/or superinterfaces.
      List<Field> ReferenceType.fields()
      Returns a list containing each Field declared in this type.
      Map<Field,Value> ReferenceType.getValues(List<? extends Field> fields)
      Returns a map containing the Value of each static Field in the given list.
      Map<Field,Value> ObjectReference.getValues(List<? extends Field> fields)
      Gets the value of multiple instance and/or static fields in this object.
      List<Field> ReferenceType.visibleFields()
      Returns a list containing each unhidden and unambiguous Field in this type.
      Methods in com.sun.jdi with parameters of type Field
      Modifier and Type Method and Description
      Value ReferenceType.getValue(Field field)
      Gets the Value of a given static Field in this type.
      Value ObjectReference.getValue(Field sig)
      Gets the value of a given instance or static field in this object.
      void ClassType.setValue(Field field, Value value)
      Assigns a value to a static field.
      void ObjectReference.setValue(Field field, Value value)
      Sets the value of a given instance or static field in this object.
      Method parameters in com.sun.jdi with type arguments of type Field
      Modifier and Type Method and Description
      Map<Field,Value> ReferenceType.getValues(List<? extends Field> fields)
      Returns a map containing the Value of each static Field in the given list.
      Map<Field,Value> ObjectReference.getValues(List<? extends Field> fields)
      Gets the value of multiple instance and/or static fields in this object.

    • Uses of Field in com.sun.jdi.event

      Methods in com.sun.jdi.event that return Field
      Modifier and Type Method and Description
      Field WatchpointEvent.field()
      Returns the field that is about to be accessed/modified.

    • Uses of Field in com.sun.jdi.request

      Methods in com.sun.jdi.request that return Field
      Modifier and Type Method and Description
      Field WatchpointRequest.field()
      Gets the Field being watched by this WatchpointRequest.
      Methods in com.sun.jdi.request with parameters of type Field
      Modifier and Type Method and Description
      AccessWatchpointRequest EventRequestManager.createAccessWatchpointRequest(Field field)
      Creates a new disabled watchpoint which watches accesses to the specified field.
      ModificationWatchpointRequest EventRequestManager.createModificationWatchpointRequest(Field field)
      Creates a new disabled watchpoint which watches accesses to the specified field.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.declaration.FieldDeclaration (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.declaration.FieldDeclaration

  • Packages that use FieldDeclaration
    Package Description
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of FieldDeclaration in com.sun.mirror.declaration

      Subinterfaces of FieldDeclaration in com.sun.mirror.declaration
      Modifier and Type Interface and Description
      interface  EnumConstantDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in VariableElement.
      Methods in com.sun.mirror.declaration that return types with arguments of type FieldDeclaration
      Modifier and Type Method and Description
      Collection<FieldDeclaration> TypeDeclaration.getFields()
      Deprecated.
      Returns the fields that are directly declared by this class or interface.

    • Uses of FieldDeclaration in com.sun.mirror.util

      Methods in com.sun.mirror.util with parameters of type FieldDeclaration
      Modifier and Type Method and Description
      void SimpleDeclarationVisitor.visitFieldDeclaration(FieldDeclaration d)
      Deprecated.
      Visits a field declaration.
      void DeclarationVisitor.visitFieldDeclaration(FieldDeclaration d)
      Deprecated.
      Visits a field declaration.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.javadoc.FieldDoc (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.javadoc.FieldDoc

    • Uses of FieldDoc in com.sun.javadoc

      Methods in com.sun.javadoc that return FieldDoc
      Modifier and Type Method and Description
      FieldDoc[] ClassDoc.enumConstants()
      Return the enum constants if this is an enum type.
      FieldDoc[] ClassDoc.fields()
      Return included fields in this class or interface.
      FieldDoc[] ClassDoc.fields(boolean filter)
      Return fields in this class or interface, filtered to the specified access modifier option.
      FieldDoc[] ClassDoc.serializableFields()
      Return the Serializable fields of this class or interface.
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


FileContents (JNLP API Reference 1.7.0)

  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method
javax.jnlp

Interface FileContents

  • public interface FileContents
    FileContents objects encapsulate the name and contents of a file. An implementation of this class is used by the FileOpenService, FileSaveService, and PersistenceService.

    The FileContents implementation returned by PersistenceService.get(java.net.URL), FileOpenService, and FileSaveService should never truncate a file if the maximum file length is set to be less that the current file length.

    Since:
    1.0
    See Also:
    FileOpenService, FileSaveService

    • Method Summary

      Methods
      Modifier and Type Method and Description
      boolean canRead()
      Returns whether the file can be read.
      boolean canWrite()
      Returns whether the file can be written to.
      java.io.InputStream getInputStream()
      Gets an InputStream from the file.
      long getLength()
      Gets the length of the file.
      long getMaxLength()
      Gets the maximum file length for the file, as set by the creator of this object.
      java.lang.String getName()
      Gets the file name as a String.
      java.io.OutputStream getOutputStream(boolean overwrite)
      Gets an OutputStream to the file.
      JNLPRandomAccessFile getRandomAccessFile(java.lang.String mode)
      Returns a JNLPRandomAccessFile representing a random access interface to the file's contents.
      long setMaxLength(long maxlength)
      Sets the maximum file length for the file.

    • Method Detail

      • getName

        java.lang.String getName()
                         throws java.io.IOException
        Gets the file name as a String.
        Returns:
        a string containing the file name.
        Throws:
        java.io.IOException - if an I/O exception occurs.

      • getInputStream

        java.io.InputStream getInputStream()
                                   throws java.io.IOException
        Gets an InputStream from the file.
        Returns:
        an InputStream to the file.
        Throws:
        java.io.IOException - if an I/O exception occurs.

      • getOutputStream

        java.io.OutputStream getOutputStream(boolean overwrite)
                                     throws java.io.IOException
        Gets an OutputStream to the file. A JNLP client may implement this interface to return an OutputStream subclass which restricts the amount of data that can be written to the stream.
        Returns:
        an OutputStream from the file.
        Throws:
        java.io.IOException - if an I/O exception occurs.

      • getLength

        long getLength()
               throws java.io.IOException
        Gets the length of the file.
        Returns:
        the length of the file as a long.
        Throws:
        java.io.IOException - if an I/O exception occurs.

      • canRead

        boolean canRead()
                throws java.io.IOException
        Returns whether the file can be read.
        Returns:
        true if the file can be read, false otherwise.
        Throws:
        java.io.IOException - if an I/O exception occurs.

      • canWrite

        boolean canWrite()
                 throws java.io.IOException
        Returns whether the file can be written to.
        Returns:
        true if the file can be read, false otherwise.
        Throws:
        java.io.IOException - if an I/O exception occurs.

      • getRandomAccessFile

        JNLPRandomAccessFile getRandomAccessFile(java.lang.String mode)
                                         throws java.io.IOException
        Returns a JNLPRandomAccessFile representing a random access interface to the file's contents. The mode argument must either be equal to "r" or "rw", indicating the file is to be opened for input only or for both input and output, respectively. An IllegalArgumentException will be thrown if the mode is not equal to "r" or "rw".
        Parameters:
        mode - the access mode.
        Returns:
        a JNLPRandomAccessFile.
        Throws:
        java.io.IOException - if an I/O exception occurs.

      • getMaxLength

        long getMaxLength()
                  throws java.io.IOException
        Gets the maximum file length for the file, as set by the creator of this object.
        Returns:
        the maximum length of the file.
        Throws:
        java.io.IOException - if an I/O exception occurs.

      • setMaxLength

        long setMaxLength(long maxlength)
                  throws java.io.IOException
        Sets the maximum file length for the file. A JNLP client may enforce restrictions on setting the maximum file length. A JNLP client should not truncate a file if the maximum file length is set that is less than the current file size, but it also should not allow further writes to that file.
        Parameters:
        maxlength - the requested new maximum file length.
        Returns:
        the maximum file length that was granted.
        Throws:
        java.io.IOException - if an I/O exception occurs.
  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.


FileOpenService (JNLP API Reference 1.7.0)

  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method
javax.jnlp

Interface FileOpenService

  • public interface FileOpenService
    FileOpenService service allows the user to choose a file from the local file system, even for applications that are running in the untrusted execution environment. The JNLP Client is the mediator and is therefore responsible for providing the specific implementation of this, if any.

    This service provides a similar function as the file input field for HTML-based forms.

    Since:
    1.0
    See Also:
    FileSaveService, FileContents

    • Method Summary

      Methods
      Modifier and Type Method and Description
      FileContents openFileDialog(java.lang.String pathHint, java.lang.String[] extensions)
      Asks the user to choose a single file.
      FileContents[] openMultiFileDialog(java.lang.String pathHint, java.lang.String[] extensions)
      Asks the user to choose one or more files.

    • Method Detail

      • openFileDialog

        FileContents openFileDialog(java.lang.String pathHint,
                          java.lang.String[] extensions)
                            throws java.io.IOException
        Asks the user to choose a single file. The contents of a potential selected file is returned as a FileContents object. The returned FileContents object contains the contents along with the name of the file. The full path is not returned.
        Parameters:
        pathHint - A hint from the application to the initial directory for the file chooser. This might be ignored by the JNLP Client.
        extensions - A list of default extensions to show in the file chooser. For example, String[] { "txt", "java" }. This might be ignored by the JNLP Client.
        Returns:
        A FileContent object with information about the chosen file, or null if the user did not choose a file.
        Throws:
        IOException - if the request failed in any way other than the user did not choose to select a file.
        java.io.IOException

      • openMultiFileDialog

        FileContents[] openMultiFileDialog(java.lang.String pathHint,
                                 java.lang.String[] extensions)
                                   throws java.io.IOException
        Asks the user to choose one or more files. Otherwise similar to openFileDialog(java.lang.String, java.lang.String[])
        Throws:
        java.io.IOException
  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.


Uses of Interface com.sun.mirror.apt.Filer (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.apt.Filer

  • Packages that use Filer
    Package Description
    com.sun.mirror.apt
    Classes used to communicate information between annotation processors and an annotation processing tool.

    • Uses of Filer in com.sun.mirror.apt

      Methods in com.sun.mirror.apt that return Filer
      Modifier and Type Method and Description
      Filer AnnotationProcessorEnvironment.getFiler()
      Deprecated.
      Returns the filer used to create new source, class, or auxiliary files.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.mirror.apt.Filer.Location (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.mirror.apt.Filer.Location

  • Packages that use Filer.Location
    Package Description
    com.sun.mirror.apt
    Classes used to communicate information between annotation processors and an annotation processing tool.

    • Uses of Filer.Location in com.sun.mirror.apt

      Methods in com.sun.mirror.apt that return Filer.Location
      Modifier and Type Method and Description
      static Filer.Location Filer.Location.valueOf(String name)
      Deprecated.
      Returns the enum constant of this type with the specified name.
      static Filer.Location[] Filer.Location.values()
      Deprecated.
      Returns an array containing the constants of this enum type, in the order they are declared.
      Methods in com.sun.mirror.apt with parameters of type Filer.Location
      Modifier and Type Method and Description
      OutputStream Filer.createBinaryFile(Filer.Location loc, String pkg, File relPath)
      Deprecated.
      Creates a new binary file, and returns a stream for writing to it.
      PrintWriter Filer.createTextFile(Filer.Location loc, String pkg, File relPath, String charsetName)
      Deprecated.
      Creates a new text file, and returns a writer for it.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


FileSaveService (JNLP API Reference 1.7.0)

  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method
javax.jnlp

Interface FileSaveService

  • public interface FileSaveService
    FileSaveService service allows the user to save a file to the local file system, even for applications that are running in the untrusted execution environment. The JNLP Client is the mediator and is therefore responsible for providing the specific implementation of this, if any.

    This service provides similar functionatlity as the Save as... functionality provided by most browsers.

    Since:
    1.0
    See Also:
    FileOpenService, FileContents

    • Method Summary

      Methods
      Modifier and Type Method and Description
      FileContents saveAsFileDialog(java.lang.String pathHint, java.lang.String[] extensions, FileContents contents)
      Asks the users to save a file.
      FileContents saveFileDialog(java.lang.String pathHint, java.lang.String[] extensions, java.io.InputStream stream, java.lang.String name)
      Asks the users to save a file.

    • Method Detail

      • saveFileDialog

        FileContents saveFileDialog(java.lang.String pathHint,
                          java.lang.String[] extensions,
                          java.io.InputStream stream,
                          java.lang.String name)
                            throws java.io.IOException
        Asks the users to save a file.
        Parameters:
        pathHint - A hint from the application to the default directory to be used. This might be ignored by the JNLP Client.
        extensions - A list of default extensions to show in the file chooser. For example, String[] { "txt", "java" }. These might be ignored by the JNLP Client.
        stream - The content of the file to save along represented as an InputStream
        name - The suggested filename, which might be ignored by the JNLP client
        Returns:
        A FileContents object for the saved file if the save was successfully, or null if the user canceled the request.
        Throws:
        IOException - if the requested failed in any way other than the user chose not to save the file
        java.io.IOException

      • saveAsFileDialog

        FileContents saveAsFileDialog(java.lang.String pathHint,
                            java.lang.String[] extensions,
                            FileContents contents)
                              throws java.io.IOException
        Asks the users to save a file.
        Parameters:
        pathHint - A hint from the application to the default directory to be used. This might be ignored by the JNLP Client.
        extensions - A list of default extensions to show in the file chooser. For example, String[] { "txt", "java" }. These might be ignored by the JNLP Client.
        contents - The content of the file to save along with the suggested filename. The suggested filename might be ignored by the JNLP Client.
        Returns:
        A FileContents object for the saved file if the save was successfully, or null if the user canceled the request.
        Throws:
        IOException - if the requested failed in any way other than the user chose not to save the file
        java.io.IOException
  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.


Developing a Custom File System Provider

Introduction

The NIO.2 API introduced in the Java SE 7 release provides the ability to develop a custom file system provider that can be used to manage file system objects. A file system is essentially a container with organized, homogenous elements referred to as file system objects. A file system provides access to file system objects. A file system object can be a file store, file, or directory. A file store is a volume or partition in which files are stored. For example, in a native file system such as on the Windows platform, commonly known drives like c: or d: are file stores. On the Solaris operating system, / (root) and mounted directories are considered file stores.

The java.nio.file.spi.FileSystemProvider class allows you to develop a custom file system provider. A custom file system provider is useful in the following situations:

  • Developing a memory-based or zip-file-based file system
  • Developing a fault-tolerant distributed file system
  • Replacing or supplementing the default file system provider. The custom provider can augment the default provider by performing specific operations, such as logging all system operations, and delegate to the default provider for other routine operations.

Overview of the java.nio.file.spi.FileSystemProvider Class

A custom file system provider must implement the java.nio.file.spi.FileSystemProvider class. A file system provider is identified by a URI scheme such as file, jar, memory, cd.

An implementation of the java.nio.file.spi.FileSystemProvider class is a factory for instances of the java.nio.file.FileSystem class. A file system's URI has a URI scheme that matches the URI scheme of the file system provider that created it.

The newFileSystem method is used to create a file system and the getFileSystem method is used to retrieve a reference to an existing file system.

Implementing a Custom File System Provider

This section describes the high-level steps necessary to create a custom file system provider using the java.nio.file.spi.FileSystemProvider API. The ZipFileSystemProvider class that is shipped in the demo/nio/zipfs of your JDK installation is an example of a custom file system provider. See Resources for information about the zip file system provider.

Implementing the Custom File System Provider Class

Implementing the custom file system provider class involves the following operations:

  • Create a custom file system provider class, such as MyFileSystemProvider, that extends the java.nio.file.spi.FileSystemProvider class.
  • Define a URI scheme such as jar for the file system provider. The getScheme method should return the URI scheme of this provider.
  • Create an internal cache to keep track of file systems created by this provider.
  • Implement the newFileSystem method. The method will create a new custom file system at the specified path and add the file system to cache. This method should throw a java.nio.file.FileSystemAlreadyExistsException exception if a file system already exists at the specified path.
  • Implement the getFileSystem method. This method should search the cache and return a previously created instance of a file system that corresponds to the given URI.
  • Implement the newFileChannel method or the newAsynchronousFileChannel method depending on the requirements of your file system provider. This method should return a FileChannel object that allows a file to be read or written in the file system.

Implementing the Custom File System Class

Implementing the custom file system class involves the following operations:

  • Create a class, such as MyFileSystem, that extends the java.nio.file.FileSystem class.
  • Implement the methods of your file system class depending on the characteristics of the desired file system. Some characteristics of a file system are as follows:
    • Number of roots – A file system can have a single hierarchy of files with one root, or multiple hierarchies.
    • Read and write access – A file system can be read-only or read/write.
    • File store – A file system requires an underlying file store. The attributes that can be set for a file will vary depending on the underlying file store.

Resources

  • Zip File System Provider
  • Zip File System Properties
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.net.httpserver.Filter (Java HTTP Server b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.net.httpserver.Filter

  • Packages that use Filter
    Package Description
    com.sun.net.httpserver
    Provides a simple high-level Http server API, which can be used to build embedded HTTP servers.

    • Uses of Filter in com.sun.net.httpserver

      Methods in com.sun.net.httpserver that return types with arguments of type Filter
      Modifier and Type Method and Description
      abstract List<Filter> HttpContext.getFilters()
      returns this context's list of Filters.
      Constructor parameters in com.sun.net.httpserver with type arguments of type Filter
      Constructor and Description
      Filter.Chain(List<Filter> filters, HttpHandler handler)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.net.httpserver.Filter.Chain (Java HTTP Server b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.net.httpserver.Filter.Chain

  • Packages that use Filter.Chain
    Package Description
    com.sun.net.httpserver
    Provides a simple high-level Http server API, which can be used to build embedded HTTP servers.

    • Uses of Filter.Chain in com.sun.net.httpserver

      Methods in com.sun.net.httpserver with parameters of type Filter.Chain
      Modifier and Type Method and Description
      abstract void Filter.doFilter(HttpExchange exchange, Filter.Chain chain)
      Asks this filter to pre/post-process the given exchange.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


How Classes are Found

  • How the Java Launcher Finds Classes
    • How the Java Launcher Finds Bootstrap Classes
    • How the Java Launcher Finds Extension Classes
    • How the Java Launcher Finds User Classes
    • How the Java Launcher Finds JAR-class-path Classes
  • How Javac and Javadoc Find Classes
  • Class Loading and Security Policies

How the Java Launcher Finds Classes

The Java launcher, java, initiates the Java virtual machine. The virtual machine searches for and loads classes in this order:

  • Bootstrap classes - Classes that comprise the Java platform, including the classes in rt.jar and several other important jar files.
  • Extension classes - Classes that use the Java Extension mechanism. These are bundled as .jar files located in the extensions directory.
  • User classes - Classes defined by developers and third parties that do not take advantage of the extension mechanism. You identify the location of these classes using the -classpath option on the command line (the preferred method) or by using the CLASSPATH environment variable. (See Setting the Classpath for Windows or Solaris.)

In effect, these three search paths are joined to form a simple class path. This is similar to the "flat" class path previously used, but the current model has some important differences:

  • It is relatively difficult to accidentally "hide" or omit the bootstrap classes.
  • In general, you only have to specify the location of user classes. Bootstrap classes and extension classes are found "automatically".
  • The tools classes are now in a separate archive (tools.jar) and can only be used if included in the user class path (to be explained shortly).

How the Java Launcher Finds Bootstrap Classes

Bootstrap classes are the classes that implement the Java 2 Platform. Bootstrap classes are in the rt.jar and several other jar files in the jre/lib directory. These archives are specified by the value of the bootstrap class path which is stored in the sun.boot.class.path system property. This system property is for reference only, and should not be directly modified.

It is very unlikely that you will need to redefine the bootstrap class path. The nonstandard option, -Xbootclasspath, allows you to do so in those rare cicrcumstances in which it is necessary to use a different set of core classes.

Note that the classes which implement the Java 2 SDK tools are in a separate archive from the bootstrap classes. The tools archive is the SDK's/lib/tools.jar file. The development tools add this archive to the user class path when invoking the launcher. However, this augmented user class path is only used to execute the tool. The tools that process source code, javac and javadoc, use the original class path, not the augmented version. (For more information, see How Javac and Javadoc Find Classes, below.)

How the Java Launcher Finds Extension Classes

Extension classes are classes which extend the Java platform. Every .jar file in the extension directory, jre/lib/ext, is assumed to be an extension and is loaded using the Java Extension Framework. Loose class files in the extension directory will not be found. They must be contained in a .jar file (or .zip file). There is no option provided for changing the location of the extension directory.

If the jre/lib/ext directory contains multiple .jar files, and those files contain classes with the same name, such as:

smart-extension1_0.jar contains class smart.extension.Smart
smart-extension1_1.jar contains class smart.extension.Smart

the class that actually gets loaded is undefined.

How the Java Launcher Finds User Classes

User classes are classes which build on the Java platform. To find user classes, the launcher refers to the user class path -- a list of directories, JAR archives, and ZIP archives which contain class files.

A class file has a subpath name that reflects the class's fully-qualified name. For example, if the class com.mypackage.MyClass is stored under /myclasses, then /myclasses must be in the user class path and the full path to the class file must be /myclasses/com/mypackage/MyClass.class. If the class is stored in an archive named myclasses.jar, then myclasses.jar must be in the user class path, and the class file must be stored in the archive as com/mypackage/MyClass.class.

The user class path is specified as a string, with a colon (:) separating the class path entries on Solaris, and a semi-colon (;) separating entries on Microsoft Windows systems. The java launcher puts the user class path string in the java.class.path system property. The possible sources of this value are:

  • The default value, ".", meaning that user class files are all the class files in the current directory (or under it, if in a package).
  • The value of the CLASSPATH environment variable, which overrides the default value.
  • The value of the -cp or -classpath command line option, which overrides both the default value and the CLASSPATH value.
  • The JAR archive specified by the -jar option, which overrides all other values. If this option is used, all user classes must come from the specified archive.

How the Java Launcher Finds JAR-class-path Classes

A JAR file usually contains a "manifest" -- a file which lists the contents of the JAR. The manifest can define a JAR-class-path, which further extends the class path (but only while loading classes from that JAR). Classes accessed by a JAR-class-path are found in the following order:

  • In general, classes referenced by a JAR-class-path entry are found as though they were part of the JAR file. The JAR files that appear in the JAR-class-path are searched after any earlier class path entries, and before any entries that appear later in the class path.
  • However, if the JAR-class-path points to a JAR file that was already searched (for example, an extension, or a JAR file that was listed earlier in the class path) then that JAR file will not be searched again. (This optimization improves efficiency and prevents circular searches.) Such a JAR file is searched at the point that it appears, earlier in the class path.
  • If a JAR file is installed as an extension, then any JAR-class-path it defines is ignored. All the classes required by an extension are presumed to be part of the SDK or to have themselves been installed as extensions.

How Javac and JavaDoc Find Classes

The javac and javadoc tools use class files in two distinct ways:

  • Like any Java application, javac and javadoc must load various class files in order to run.
  • To process the source code they operate on, javac and javadoc must obtain information on object types used in the source code.

The class files used to resolve source code references are mostly the same class files used to run javac and javadoc. But there are some important exceptions:

  • Both javac and javadoc often resolve references to classes and interfaces that having nothing to do with the implementation of javac or javadoc. Information on referenced user classes and interfaces may be present in the form of class files, source code files, or both.
  • The tools classes in tools.jar are only used to run javac and javadoc. The tools classes are not used to resolve source code references unless tools.jar is in the user class path.
  • A programmer may want to resolve boot class or extension class references using an alternative Java platform implementation. Both javac and javadoc support this with their -bootclasspath and -extdirs options. Use of these options does not modify the set of class files used to run the javac or javadoc tools themselves.

If a referenced class is defined in both a class file and source file, javadoc always uses the source file (javadoc never compiles source files). In the same situation javac uses class files, but automatically recompiles any class files it determines to be out of date. The rules for automatic recompilation are documented in the javac document for Windows or Solaris.

By default, javac and javadoc search the user class path for both class files and source code files. If the -sourcepath option is specified, javac and javadoc search for source files only on the specified source file path, while still searching the user class path for class files.

Class Loading and Security Policies

To be used, a class or interface must be loaded by a class loader. Use of a particular class loader determines a security policy associated with the class loader.

A program can load a class or interface by calling the loadClass method of a class loader object. But usually a program loads a class or interface simply by referring to it. This invokes an internal class loader, which can apply a security policy to extension and user classes. If the security policy has not been enabled, all classes are "trusted". Even if the security policy is enabled, it does not apply to bootstrap classes, which are always "trusted."

When enabled, security policy is configured by system and user policy files. The Java 2 SDK includes a system policy file that grants "trusted" status to extension classes and places basic restrictions on user classes.

To enable or configure the security policy, refer to Security Features.

Note: Some security programming techniques that worked with the Java 1.1 platform are incompatible with the class loading model of the Java 2 Platform.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


System Properties for Java 2D(TM) Technology

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

System Properties for Java 2D™ Technology

This document describes several unsupported properties that you can use to customize how the 2D painting system operates. You might use these properties to improve performance, fix incorrect rendering, or avoid system crashes under certain configurations. For example, on a small set of Microsoft Windows computers with bad DirectDraw or Direct3D drivers, the use of hardware-accelerated rendering might cause system crashes. You can use properties to specify that on these computers, the Java 2D system shouldn't use DirectDraw or Direct3D.

Warning: Take care when using these properties. Some of them are unsupported for very practical reasons. For example, some behaviors are disabled by default due to driver instabilities; enabling such behaviors could cause system instabilities on some configurations.

Since these properties have the sole purpose of enabling or disabling implementation-specific behaviors, they are subject to change or removal without notification. Some properties might work only on the exact product releases for which they are documented.

2D properties have the prefix sun.java2d.. To specify them, you can use either command-line flags or the _JAVA_OPTIONS environment variable. For example, you can specify the 2D trace property with a flag when running an application, like this:

java -Dsun.java2d.trace=log SomeApp
Or you can specify it by setting _JAVA_OPTIONS before running the application, like this:
export _JAVA_OPTIONS='-Dsun.java2d.trace=log' (UNIX bash shell)
java SomeApp

Some system properties are also settable using environment variables. For example, the d3d property has the equivalent environment variable J2D_D3D. The property description lists the equivalent environment variable, if one exists.

Note: See the High Performance Graphics White Paper for explanations of terms used in property descriptions.

This document lists the following properties:

  • System Properties for All Platforms
    • opengl
    • trace
    • awt.useSystemAAFontSettings
  • System Properties for Microsoft Windows Platforms
    • accthreshold
    • d3d
    • d3dtexbpp
    • ddforcevram
    • ddoffscreen
    • ddscale
    • noddraw
    • translaccel
  • System Properties for Linux and Solaris Platforms
    • NO_J2D_DGA
    • J2D_PIXMAPS
    • xrender
    • pmoffscreen

System Properties for All Platforms

opengl

Intended use: To enable the OpenGL-based pipeline, which provides hardware acceleration.
Introduced: 1.5 Beta 1 (Solaris/Linux); 1.5 Beta 2 (Microsoft Windows)
Default value: false
How to use: To silently enable the OpenGL-based pipeline, set this property to true:

-Dsun.java2d.opengl=true

To receive verbose console output about whether the OpenGL-based pipeline is initialized successfully for a particular screen, set this property to True (note the uppercase T):

-Dsun.java2d.opengl=True

An OpenGL-based pipeline for Java 2D was introduced in 1.5 Beta 1 for Solaris/Linux and 1.5 Beta 2 for Microsoft Windows platforms. This pipeline is currently disabled by default. It provides hardware acceleration for simple rendering operations (text, images, lines, and filled primitives) as well as those that involve complex transforms, paints, composites, and clips.

For more information: The OpenGL section of New Java 2D Features in the Java 2 SDK, v1.5.

trace

Intended use: To help determine the source of less-than-desirable graphics performance.
Introduced: 1.4
How to use: If your application is experiencing less-than-desirable performance, the trace runtime flag can help you determine the source of the problem. The flag is specified with a list of options:

    -Dsun.java2d.trace=[log[,timestamp]],[count],[out:<filename>],[help],[verbose]

The options are:

log
print out the name of each primitive as it is executed
timestamp
precede each log entry with the currentTimeMillis()
count
at exit, print out a count of each primitive used
out:<filename>
send output (logging and counts) to the indicated file
help
print out a short usage statement
verbose
print out a summary of the options chosen for this run

If you use the log option, the Java runtime will print the executed primitives' names, most of which will be in this format:

    <classname>.<methodname>(<src>,<composite>,<dst>)

The methodname represents the basic graphics operation that is used to do the actual rendering work of a Graphics method invocation. These method names will not necessarily map directly to methods on the Graphics object, nor will the number of calls made on the Graphics object map directly to the number of primitive operations performed.

The src and dst represent the type of surfaces or source data involved in the operation.

The composite names match the names in the AlphaComposite class fairly closely with the suffix "NoEa" meaning that the AlphaComposite instance had an "extra alpha" attribute of 1.0. The "SrcNoEa" type is the most commonly used composite type and represents the simplest way of transferring pixels with no blending required. "SrcNoEa" is often used behind the scenes even though the default composite is "SrcOver" when opaque colors and images are rendered because the two operations are indistinguishable for opaque source pixels.

Platform rendering pipelines are sometimes used for doing opaque operations on surfaces accessible by a platform renderer, such as X11, GDI, or DirectDraw. Their names currently use a simplified naming format, which has a prefix for the platform renderer and the name of the operation but without any classname or operand type list. Examples are "X11DrawLine", "GDIFillOval", and "DXFillRect". In the future these names should more closely approximate the names of the other primitives.

awt.useSystemAAFontSettings

Intended use:To override what text anti-aliasing settings are identified as being "desktop settings".
Introduced: 1.6
Default value:true.
How to use:Set on the command line or in a webstart jnlp file as one of the specified values below to control rendering hints used by Swing text.

Strictly this flag doesn't control Java 2D but is documented here because the values all directly map to Java 2D text antialiasing rendering hints values.

What the flag really does is override what the JRE reads from the user's desktop settings as the user's desktop antialiased text preferences. Swing instructs Java 2D to render Swing text to match that preference, so by overriding it you can control Swing text. This applies to standard Swing components (like JTextArea, JButton) in the Metal L&F (aka Java L&F) and native (Windows, GTK) Swing L&Fs. It should also apply to any custom component or L&F which picks up the same property.

For information on the desktop setting this overrides see AWT Desktop Properties

There aren't many reasons for you to specify this property but a couple are

  • The desktop setting you want isn't supported on your desktop (eg you want LCD text on Windows 2000)
  • JRE doesn't recognise your desktop setting (eg KDE)
  • You are automating testing under each of these conditions
System Property Value   | java.awt.RenderingHint value
"off"|"false"|"default" : VALUE_TEXT_ANTIALIAS_DEFAULT
"on"                    : VALUE_TEXT_ANTIALIAS_ON
"gasp"                  : VALUE_TEXT_ANTIALIAS_GASP
"lcd"|"lcd_hrgb"        : VALUE_TEXT_ANTIALIAS_LCD_HRGB
"lcd_hbgr"              : VALUE_TEXT_ANTIALIAS_LCD_HBGR
"lcd_vrgb"              : VALUE_TEXT_ANTIALIAS_LCD_VRGB
"lcd_vbgr"              : VALUE_TEXT_ANTIALIAS_LCD_VBGR

System Properties for Microsoft Windows Platforms

accthreshold

Obsoleted in: Java SE 6 Update 10
Intended use: To determine how many copies from managed images will occur before a VRAM version of the image is automatically created.
Introduced: 1.4.1_02
Default value: 1
How to use: To force accelerated surfaces to be created during image initialization, set the value to 0, as follows:

-Dsun.java2d.accthreshold=0

This property can be used to eliminate the initial delay in rendering when the images are being copied to the VRAM after the first few copies. Instead, the delay is effectively shifted to the image creation time.

This could be useful behavior when you know that your application will be able to take advantage of image management; just get the overhead of the copy over with at the start instead of incurring some number of slower copies to begin with and then having the copy overhead at some later time.

d3d

Intended use: To turn off the Java 2D system's use of Direct3D.
Introduced: 1.4.1_02
Equivalent environment variable: J2D_D3D
How to use: On a small subset of Windows 2000 systems with buggy Direct3D drivers, the use of Direct3D can cause a system crash. To turn off the use of Direct3D, set this property to false:
-Dsun.java2d.d3d=false
If problems persist, try setting the ddoffscreen property to false. If that doesn't solve the problems, try setting noddraw to true.

d3dtexbpp

Obsoleted in: Java SE 6 Update 10
Intended use: To specify that accelerated surfaces for managed or translucent images should be in 16-bit (4444) format, which saves VRAM and system memory but at the cost of decreased quality.
Introduced: 1.4.1_02
Default value: 32
How to use: To turn on 4444 format, set this property to 16:

-Dsun.java2d.d3dtexbpp=16
Note: The d3dtexbpp property has no effect if the OpenGL pipeline is in use.

When this property is set to 16, it forces the accelerated surfaces for managed images (created with GraphicsConfiguration.createCompatibleImage(w,h, TRANSLUCENT)) or translucent images loaded with Toolkit.getImage to be in 4444 format. The system memory surface for these images will be in 4444 format as well.

This option is useful when you have lots of images to be stored in VRAM. The downside is poorer quality.

This option is also useful for computers with video boards (such as 3dfx Voodoo3) that don't support 32-bit textures. When the Java 2D system uses 32-bit textures, as it does by default, then when it encounters a card without 32-bit texture support it disables support for accelerated translucent images. If you want acceleration of translucent images on a video board that doesn't support 32-bit textures, set the d3dtexbpp property to 16.

ddforcevram

Obsoleted in: Java SE 6 Update 10
Intended use: To specify whether VolatileImages should be kept in VRAM.
Introduced: 1.4.1_02
Default value: false in 1.4; as of 1.5 Beta 1, true if translaccel is true, and otherwise false
How to use: Normally, if the 2D system is using the DirectDraw/Direct3D pipeline and detects that an image in video memory is being read from too often (an expensive operation), it punts it to a system memory surface, which is faster to read from. Later, if the system detects that the user is copying from this surface to an accelerated surface again, it promotes it to the video memory. Setting this property to true disables the punting mechanism and always keeps the image in video memory.

Note: The ddforcevram property has no effect if the OpenGL pipeline is in use.

Although this property is often used with the translaccel property, it can be used separately. To set this property to true, either set translaccel to true in a 1.5 release, or set it separately:

-Dsun.java2d.ddforcevram=true

ddoffscreen

Obsoleted in: Java SE 6 Update 10, which contains a new implementation of D3D support. Setting sun.java2d.ddoffscreen=false is now interpreted exactly the same as disabling that via sun.java2d.d3d=false.
Intended use: To turn off the Java 2D system's use of DirectDraw and Direct3D for offscreen surfaces such as the Swing back buffer.
Introduced: 1.4
Default value: true
How to use: Setting this flag to false turns off DirectDraw offscreen surfaces acceleration.

ddscale

Obsoleted in: Java SE 6 Update 10
Intended use: To turn on hardware-accelerated scaling when the DirectDraw/Direct3D pipeline is in use.
Introduced: 1.2
Default value: false
How to use: Setting this flag to true enables hardware-accelerated scaling if the DirectDraw/Direct3D pipeline is in use. DirectDraw/Direct3D hardware scaling is disabled by default to avoid rendering artifacts in existing applications. These rendering artifacts are caused by possible inconsistencies between the scale method that the software scaling operation uses (nearest neighbor) and the different scale methods that video cards use. Certain events that occur while an application is running might cause a scaled image to be rendered partially with hardware scaling operations and partially with software scaling operations, resulting in an inconsistent appearance. For now, you can enable acceleration by setting the ddscale flag to true.

Note: The ddscale property has no effect if the OpenGL pipeline is in use.

For more information: High Performance Graphics White Paper

noddraw

Obsoleted in: Java SE 6 Update 10, which contains a new implementation of D3D support. Setting sun.java2d.noddraw=true is now interpreted exactly the same as disabling that via sun.java2d.d3d=false.
Intended use: To turn off the Java 2D system's use of DirectDraw and Direct3D completely.
Introduced: 1.2
Default value: false
How to use: Setting this flag to true turns off DirectDraw usage, which sometimes helps to get rid of rendering problems on Win32.

translaccel

Obsoleted in: Java SE 6 Update 10
Intended use: To specify whether translucent images should be hardware-accelerated when the DirectDraw/Direct3D pipeline is in use.
Introduced: 1.4.1_02
Default value: false
How to use: When the DirectDraw/Direct3D pipeline is being used, both translaccel and ddforcevram must be true for translucent images to be accelerated.

Note: The translaccel property has no effect if the OpenGL pipeline is in use.

To turn on acceleration of translucent images in 1.4 and 1.5:

-Dsun.java2d.translaccel=true
-Dsun.java2d.ddforcevram=true //unnecessary as of 1.5 Beta 1

When both these properties are true, the Java 2D system attempts to put translucent images into VRAM and use Direct3D for rendering (compositing) them to the screen or to a VolatileImage. Only translation transforms are supported (no rotation, scaling, and so on). Before 1.5, to be accelerated a translucent image had to be created in one of the following ways:

  • GraphicsConfiguration.createCompatibleImage(w,h, Transparency.TRANSLUCENT)
  • Images loaded with Toolkit.getImage() that have a translucent color model
As of 1.5, translucent images created with a BufferedImage constructor can also be accelerated. To find out whether an image can be accelerated on a particular device, you can use the Image getCapabilities method (added in 1.5) to get an ImageCapabilities object, which you can query using the isAccelerated method. Note that a managed image gets accelerated only after a certain number of copies to the screen or to another accelerated surface.

The following code fragment illustrates the use of accelerated images. The fragment assumes that back buffer is a VolatileImage. BufferStrategy can be used as well.

Image translucentImage = gc.createCompatibleImage(w, h, Transparency.TRANSLUCENT);
//...
Graphics2D g2 = (Grahics2D)backBuffer.getGraphics();
g2.drawImage(translucentImage, x, y, null);

Compositing with extra alpha with SRC_OVER rule (which is the default Graphics2D compositing rule) is accelerated, so the following code will allow the use of hardware for compositing: Code:

Image translucentImage = gc.createCompatibleImage(w, h, Transparency.TRANSLUCENT);
// ...
float ea = 0.5;
Graphics2D g2 = (Grahics2D)backBuffer.getGraphics();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, ea));
g2.drawImage(translucentImage, x, y, null);

System Properties for Linux and Solaris Platforms

NO_J2D_DGA

Intended use: To turn off DGA support and hardware acceleration on Solaris Sparc, which sometimes helps to reduce rendering artifacts.
Introduced: 1.2
Default value: (unset)
How to use: This property is settable only as an environment variable; it has no command-line flag equivalent. To turn off DGA support and hardware acceleration on Solaris Sparc, define the variable:
setenv NO_J2D_DGA

Setting this variable automatically enables the use of pixmaps, in effect setting pmoffscreen to true. The reverse, however, is not true: setting pmoffscreen to true doesn't disable DGA.

J2D_PIXMAPS

Intended use: To determine whether the 2D system uses shared memory pixmaps in the local display environment for storing images that experience frequent reads.
Introduced: 1.4 Beta 3
Default value: (unset)
How to use: This property is settable only as an environment variable; it has no command-line flag equivalent. As of 1.4 Beta 3, Java 2D starts out using normal pixmaps to store images, but changes the storage of frequently read images to use Shared Memory Pixmaps in the local display environment. You can override this default behavior — and force only one type of pixmap to be used — with J2D_PIXMAPS environment flag:
    setenv J2D_PIXMAPS=shared
    setenv J2D_PIXMAPS=server

If you set this flag to shared, all images are stored in Shared Memory Pixmaps if you are working in a local display environment. Conversely, if you set this flag to server, all images are stored in normal pixmaps, not Shared Memory Pixmaps; the normal pixmaps can be stored in VRAM at the discretion of the device driver.

For more information: High Performance Graphics White Paper

xrender

Intended use: To enable the XRender-based Java 2D rendering pipeline for modern X11-based desktops, offering improved graphics performance.
Introduced: Java SE 7
Default value: false
How to use: The pipeline is disabled by default, but may be enabled by setting the command line property -Dsun.java2d.xrender=true. Older X11 configurations may not be able to support XRender. The verbose form, -Dsun.java2d.xrender=True, can be used to enable a message to stdout indicating whether the pipeline was actually enabled.

pmoffscreen

Intended use: To determine whether Java 2D stores images in pixmaps by default when DGA is not available.
Introduced: 1.4 Beta 3
Default value: (unset)
How to use: As of 1.4 Beta 3, Java 2D stores images in pixmaps by default when DGA is not available, whether you are working in a local or remote display environment. You can override this behavior with the pmoffscreen flag:

    -Dsun.java2d.pmoffscreen=true
    -Dsun.java2d.pmoffscreen=false

Setting this flag to false disables offscreen pixmap support, which can solve some rendering problems. When the flag is true, offscreen pixmap support is enabled even if DGA is available.

For more information: High Performance Graphics White Paper

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.FloatType (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.FloatType

No usage of com.sun.jdi.FloatType
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.FloatValue (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.FloatValue

  • Packages that use FloatValue
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of FloatValue in com.sun.jdi

      Methods in com.sun.jdi that return FloatValue
      Modifier and Type Method and Description
      FloatValue VirtualMachine.mirrorOf(float value)
      Creates a FloatValue for the given value.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Focus API changes

This document outlines the API changes that have been done to AWT and Swing to accomodate the new focus model. For a general overview of the changes, you may want to first read this.

Modifications to existing classes:

  • java.awt.AWTEvent
  • java.awt.Component
  • java.awt.Container
  • java.awt.Window
  • java.awt.Frame
  • java.awt.Dialog
  • java.awt.FocusEvent
  • java.awt.event.WindowEvent
  • java.awt.event.WindowListener
  • java.awt.event.WindowAdapter
  • java.awt.AWTEventMulticaster
  • javax.swing.FocusManager
  • javax.swing.DefaultFocusManager
  • javax.swing.JComponent
  • javax.swing.JInternalFrame
  • javax.swing.KeyStroke
  • javax.swing.SwingUtilities

New classes:

  • java.awt.KeyboardFocusManager
  • java.awt.KeyEventDispatcher
  • java.awt.DefaultKeyboardFocusManager
  • java.awt.FocusTraversalPolicy
  • java.awt.ContainerOrderFocusTraversalPolicy
  • java.awt.DefaultFocusTraversalPolicy
  • java.awt.AWTKeyStroke
  • java.awt.event.WindowFocusListener
  • javax.swing.SortingFocusTraversalPolicy
  • javax.swing.LayoutFocusTraversalPolicy
  • javax.swing.InternalFrameFocusTraversalPolicy

Add the following to java.awt.AWTEvent:

    public void setSource(Object newSource)

Changes to java.awt.Component:

    public boolean isFocusTraversable()

    public boolean isFocusable()

    public void setFocusable(boolean focusable)

    public void setFocusTraversalKeys(int id, Set keystroke)

    public Set getFocusTraversalKeys(int id)

    public void setFocusTraversalKeysEnabled(boolean focusTraversalKeysEnabled)

    public boolean getFocusTraversalKeysEnabled()

    public void requestFocus()

    protected boolean requestFocus(boolean temporary)

    public boolean requestFocusInWindow()

    protected boolean requestFocusInWindow(boolean temporary)

    public void transferFocus()

    public void transferFocusBackward()

    public void transferFocusUpCycle()

    public Container getFocusCycleRootAncestor()

    public boolean isFocusCycleRoot(Container container)

    public boolean hasFocus()

    public boolean isFocusOwner()

    public void addPropertyChangeListener(PropertyChangeListener listener)

    public void removePropertyChangeListener(PropertyChangeListener listener)

    public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener)

    public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener)

    public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue)

    public void firePropertyChange(String propertyName, int oldValue, int newValue)

    public boolean isFontSet()

    public boolean isBackgroundSet()

    public boolean isForegroundSet()

    public boolean isCursorSet()

    public boolean areFocusTraversalKeysSet(int id)

Changes to java.awt.Container:

    public void setFocusTraversalKeys(int id, Set keystroke)

    public Set getFocusTraversalKeys(int id)

    public void setFocusTraversalPolicy(FocusTraversalPolicy policy)

    public FocusTraversalPolicy getFocusTraversalPolicy()

    public void setFocusCycleRoot(boolean focusCycleRoot)

    public boolean isFocusCycleRoot()

    public boolean isFocusCycleRoot(Container container)

    public void transferFocusDownCycle()

    public void addPropertyChangeListener(PropertyChangeListener listener)

    public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener)

    public boolean areFocusTraversalKeysSet(int id)

    public boolean isFocusTraversalPolicySet()

Changes to java.awt.Window:

    public void toFront()

    public void toBack()

    public Component getFocusOwner()

    public Component getMostRecentFocusOwner()

    public boolean isActive()

    public boolean isFocused()

    public final void setFocusCycleRoot(boolean focusCycleRoot)

    public final boolean isFocusCycleRoot()

    public final Container getFocusCycleRootAncestor()

    public boolean isFocusableWindow()

    public void setFocusableWindowState(boolean focusableWindowState)

    public void addPropertyChangeListener(PropertyChangeListener listener)

    public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener)

Add the following to the javadoc of java.awt.Frame:

/**
 * Frames are capable of generating the following types of WindowEvents:
 * WindowOpened, WindowClosing, WindowClosed, WindowIconified,
 * WindowDeiconified, WindowActivated, WindowDeactivated, WindowGainedFocus,
 * WindowLostFocus.
 */

Add the following to the javadoc of java.awt.Dialog:

/**
 * Dialogs are capable of generating the following WindowEvents:
 * WindowOpened, WindowClosing, WindowClosed, WindowActivated,
 * WindowDeactivated, WindowGainedFocus, WindowLostFocus.
 */

Add the following to java.awt.event.FocusEvent:

    public FocusEvent(Component source, int id, boolean temporary, Component opposite)

    public Component getOppositeComponent()

Add the following to the javadoc of java.awt.event.WindowEvent:

/**
 * A low-level event that indicates that a window has changed its status. This
 * low-level event is generated by a Window object when it is opened, closed,
 * activated, deactivated, iconified, or deiconified, or when focus is
 * transfered into or out of the Window.
 */

Add the following to java.awt.event.WindowEvent:

    public static final int WINDOW_ACTIVATED

    public static final int WINDOW_DEACTIVATED

    public static final int WINDOW_GAINED_FOCUS

    public static final int WINDOW_LOST_FOCUS

    public WindowEvent(Window source, int id, Window opposite)

    public Window getOppositeWindow()

Add the following to java.awt.event.WindowListener:

    public void windowActivated(WindowEvent e)

    public void windowDeactivated(WindowEvent e)

Add the following to java.awt.event.WindowAdapter:

    public void windowGainedFocus(WindowEvent e)

    public void windowLostFocus(WindowEvent e)

Add the following to java.awt.AWTEventMulticaster:

    public void windowGainedFocus(WindowEvent e)

    public void windowLostFocus(WindowEvent e)

Modifications to javax.swing.FocusManager

This class has been obsoleted. New applications should use java.awt.KeyboardFocusManager exclusively. Nevertheless, we have preserved backward compatibility for existing applications (but not applets) which define their own FocusManager.

The Swing FocusManager has been changed to be a subclass of the new, AWT KeyboardFocusManager. FocusManager.setCurrentManager(FocusManager) and FocusManager.getCurrentManager() have been changed to wrappers around KeyboardFocusManager.setCurrentKeyboardFocusManager(KeyboardFocusManager) and KeyboardFocusManager.getCurrentKeyboardFocusManager(), respectively.

There was much discussion over these changes because KeyboardFocusManager.setCurrentKeyboardFocusManager(KeyboardFocusManager) will throw a SecurityException if the calling thread was not granted the "replaceKeyboardFocusManager" permission. Previously, FocusManager.setCurrentManager(FocusManager) would never throw a SecurityException. Although we were able to design a convoluted class organization which avoided this problem, we felt that the elegance and simplicity of the proposed design outweighed the rather small backward compatibility concern.

disableSwingFocusManager() and isFocusManagerEnabled() should not be used. Disabling the Swing FocusManager now has the semantics of reverting the default FocusTraversalPolicy from the Swing default of javax.swing.LayoutFocusTraversalPolicy to the AWT default of java.awt.DefaultFocusTraversalPolicy.

Modifications to javax.swing.DefaultFocusManager

This class has been obsoleted. New applications should use java.awt.KeyboardFocusManager exclusively. Nevertheless, we have preserved backward compatibility for existing applications (but not applets) which define their own DefaultFocusManager.

If client code installs a legacy DefaultFocusManager, we provide backward compatibility by installing a non-public LegacyGlueFocusTraversalPolicy which routes FocusTraversalPolicy method invocations to the corresponding methods on DefaultFocusManager.

Modifications to javax.swing.JComponent

isManagingFocus: This method has been obsoleted. It changed a JComponent's focus traversal keys from TAB and SHIFT-TAB to CTRL-TAB and CTRL-SHIFT-TAB. It also marked the JComponent in such a way that focus traversal would not automatically enter the JComponent. This was similar to, but different from, marking a JComponent as a focus cycle root. Its functionality is superseded by the FocusTraversalPolicy class, per-Component focus traversal keys, and the ability to disable a Component's focus traversal keys en masse.

setNextFocusableComponent/getNextFocusableComponents: These methods have been obsoleted FocusTraversalPolicies are more reliable because they allow an algorithmic expression of focus traversal. These methods force applications to hard-code focus traversal Component by Component.

The spec for setRequestFocusEnabled/isRequestFocusEnabled has changed, such that the requestFocusEnabled property is now a hint to the current look and feel.

requestDefaultFocus: This method has been obsoleted. Its functionality is superseded by FocusTraversalPolicy.getDefaultComponent(Container).requestFocus().

Modifications to javax.swing.JInternalFrame

getMostRecentFocusOwner: Like java.awt.Window, JInternalFrame has a getFocusOwner() method left over from before centralization of focus management in java.awt.KeyboardFocusManager. To round out the API, and to remain consistent with Window, getMostRecentFocusOwner() has been added to JInternalFrame with the same specification as the corresponding method on Window.

setFocusCycleRoot/isFocusCycleRoot: These methods give JInternalFrames similar semantics to top-level Windows in AWT. Since a JInternalFrame must always be a focus cycle root, these methods are overridden and declared final to enforce that restriction. However, unlike an AWT Window, a JInternalFrame can have a focus-cycle-root ancestor, such as a JDesktopPane. Thus, Component.getFocusCycleRootAncestor() is not declared final in JInternalFrame as it is in Window.

Modifications to javax.swing.KeyStroke

Because the existing KeyStroke class was useful for designing per-Component focus traversal key APIs, this class was promoted with minor modifications to AWT as java.awt.AWTKeyStroke. The Swing class is now a subclass of the AWT class.

The one deprecated method in KeyStroke, getKeyStroke(char, boolean), was not promoted to AWT. Because of this, there is no simple way for this method to participate in the standard AWTKeyStroke caching scheme. The specification of this method has been changed to note that implementations need not cache the instances returned by this method.

Modifications to javax.swing.SwingUtilities

findFocusOwner: This method has been obsoleted. Its functionality is superseded by KeyboardFocusManager.getFocusOwner().

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Supported Fonts

The set of supported fonts varies between different implementations of the Java Platform. This page documents font support in Sun's Java SE Development Kit 6 (JDK), and Java SE Runtime Environment 6 (JRE). For the terminology used, see the Font class description.

  • Support for Physical Fonts
  • Support for Logical Fonts
  • The Lucida Fonts

Support for Physical Fonts

Sun's Java SE Runtime Environment supports TrueType and PostScript Type 1 fonts.

Physical fonts need to be installed in locations known to the Java runtime environment. Sun's Java SE Runtime Environments look in two locations: the lib/fonts directory within the JRE itself, and the normal font location(s) defined by the host operating system. If fonts with the same name exist in both locations, the one in the lib/fonts directory is used.

Users can add physical fonts that use a supported font technology by installing them either in the lib/fonts directory within the JRE, or by installing them in a way supported by the host operating system (dropping them into the Fonts folder on Windows, using the pkgadd command on Solaris).

Support for Logical Fonts

Logical font names are mapped to physical fonts in implementation dependent ways. Typically one logical font name maps to several physical fonts in order to cover a large range of characters. Sun's Java SE Runtime Environments use font configuration files to define the mapping.

Users can add a physical font as a fallback font to logical fonts used in Java 2D rendering by installing it in the lib/fonts/fallback directory within the JRE.

The Lucida Fonts

Sun's Java SE Development Kit and Java SE Runtime Environments bundle several physical fonts of the "Lucida" design family. These fonts are also licensed for use in other implementations of the Java Platform. These fonts are physical fonts, but since they come with the Java SE Runtime, they don't depend on the host operating system. Using them provides the benefit of a consistent look and feel across platforms and implementations for a large set of languages.

There are three different type families: "Lucida Sans", "Lucida Sans Typewriter", and"Lucida Bright". Each family has plain, bold, italic, and bold-italic styles. Not all of these are present in all Java SE implementations. For example, the default download bundle of Sun's Java SE Runtime Environment for Windows only contains the Lucida Sans plain font (but note that application developers can include all Lucida fonts with a JRE that they redistribute with an application).

The following table shows which Unicode character blocks are covered by each font family:

Unicode Block | Lucida Sans | Lucida Sans Typewriter | Lucida Bright
Basic Latin | yes | yes | yes
Latin-1 Supplement | yes | yes | yes
Latin Extended-A | yes | yes | yes
Latin Extended-B | partial | partial | partial
IPA Extensions | partial | no | no
Spacing Modifier Letter | partial | partial | partial
Combining Diacritical Marks | partial | no | partial
Greek | yes | yes | yes
Cyrillic | partial | partial | partial
Hebrew | yes | yes | no
Arabic | partial | partial | partial
Devanagari | yes | no | no
Thai | yes | yes | no
General Punctuation | partial | partial | partial
Superscripts and Subscripts | partial | partial | partial
Currency Symbols | partial | partial | partial
Letterlike Symbols | partial | partial | partial
Number Forms | partial | partial | no
Arrows | partial | partial | partial
Mathematical Operators | yes | partial | yes
Enclosed Alphanumerics | partial | no | no
Box Drawings | partial | partial | no
Block Elements | partial | partial | no
Geometric Shapes | partial | partial | partial
Miscellaneous Symbols | partial | partial | no
Dingbats | yes | no | no
Alphabetic Presentation Forms | partial | partial | no
Arabic Presentation Forms-A | partial | partial | partial
Arabic Presentation Forms-B | yes | yes | yes

Note that of the writing systems that are generally fully supported by Sun's Java SE Runtime Environments, the Lucida fonts do not support Chinese (Simplified), Chinese (Traditional), Japanese, and Korean.

The fonts are installed in the Java SE Runtime Environment's lib/fonts directory as the following files (not all of them may be present):

LucidaSansDemiBold.ttf
LucidaSansRegular.ttf
LucidaTypewriterBold.ttf
LucidaTypewriterRegular.ttf
LucidaBrightDemiBold.ttf
LucidaBrightDemiItalic.ttf
LucidaBrightItalic.ttf
LucidaBrightRegular.ttf
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Font Configuration Files

The Java Platform defines five logical font names that every implementation must support: Serif, SansSerif, Monospaced, Dialog, and DialogInput. These logical font names are mapped to physical fonts in implementation dependent ways.

Sun's Java SE Runtime Environments use font configuration files to map logical font names to physical fonts. There are several files to support different mappings depending on the host operating system version. The files are located in the lib directory within the JRE installation. Users can edit or create their own font configuration files to adjust the mappings to their particular system setup. Note however that this is a modification of the JRE, and Sun does not support modified JREs.

Font configuration files come in two formats: A properties format and a binary format. The properties format is described in detail in this document and can be used for user-defined configurations. The binary format is undocumented and used only for the JRE's predefined configurations; the corresponding files in properties format are available for reference as files with the ".properties.src" extension.

Note that font configuration files are implementation dependent. Not all implementations of the Java Platform use them, and the format and content vary between different runtime environments as well as between releases. This document describes the format used by version 6 of Sun's Java SE Runtime Environments.

  1. Loading Font Configuration Files
  2. Names Used in Font Configuration Files
  3. Properties for All Platforms
  4. Properties for Windows
  5. Properties for Solaris and Linux

Loading Font Configuration Files

To find the appropriate font configuration file for a host operating system, the following information is used:

  • JavaHome - the JRE's directory, as given by the "java.home" system property.
  • OS - a string identifying an operating system variant:
    • For Windows, "98", "2000", "Me", "XP", "2003".
    • For Solaris, empty.
    • For Linux, "Sun", "RedHat", "Turbo", "SuSE".
  • Version - a string identifying the operating system version.

The runtime uses the first of the following files it finds:

        JavaHome/lib/fontconfig.OS.Version.properties
        JavaHome/lib/fontconfig.OS.Version.bfc
        JavaHome/lib/fontconfig.OS.properties
        JavaHome/lib/fontconfig.OS.bfc
        JavaHome/lib/fontconfig.Version.properties
        JavaHome/lib/fontconfig.Version.bfc
        JavaHome/lib/fontconfig.properties
        JavaHome/lib/fontconfig.bfc

Files with a ".properties" suffix are assumed to be properties files as specified by the Properties class and are loaded through that class. Files without this suffix are assumed to be in binary format.

Names Used in Font Configuration Files

Throughout the font configuration files, a number of different names are used:

  • LogicalFontName - one of the five logical font names: serif, sansserif, monospaced, dialog, and dialoginput. In font configuration files, these names are always in lowercase.
  • StyleName - one of the four standard font styles: plain, bold, italic, and bolditalic. Again, these names are always in lowercase.
  • PlatformFontName - the name of a physical font, in a format typically used on the platform:
    • On Windows, a font face name, such as "Courier New" or "\uad74\ub9bc".
    • On Solaris and Linux, an xlfd name, such as "-monotype-times new roman-regular-r---*-%d-*-*-p-*-iso8859-1". Note that "%d" is used for the font size - the actual font size is filled in at runtime.
  • CharacterSubsetName - a name for a subset of the Unicode character set which certain component fonts can render. For Windows, the following names are predefined: alphabetic, arabic, chinese-ms936, chinese-gb18030, chinese-ms950, chinese-hkscs, cyrillic-iso8859-5, cyrillic-cp1251, cyrillic-koi8-r, devanagari, dingbats, greek, hebrew, japanese, korean, latin, symbol, thai. For Solaris and Linux, the following names are predefined: arabic, chinese-gb2312, chinese-gbk, chinese-gb18030-0, chinese-gb18030-1, chinese-cns11643-1, chinese-cns11643-2, chinese-cns11643-3, chinese-big5, chinese-hkscs, cyrillic, devanagari, dingbats, greek, hebrew, japanese-x0201, japanese-x0208, japanese-x0212, korean, korean-johab, latin-1, latin-2, latin-4, latin-5, latin-7, latin-9, symbol,thai. A font configuration file may define additional names to identify additional character subsets.
  • Encoding - the canonical name of the default encoding, as provided by java.nio.charset.Charset.defaultCharset().name().
  • Language - the language of the initial default locale.
  • Country - the country of the initial default locale.

Properties for All Platforms

Version Property

The version property identifies the font configuration format version. This document specifies version 1.

The complete property has the form:

version=1

Component Font Mappings

Component font mapping properties describe which physical font to use to render characters from a given character subset with a given logical font in a given style.

The keys have the forms:

        allfonts.CharacterSubsetName
        LogicalFontName.StyleName.CharacterSubsetName

The first form is used if the same font is used for a character subset independent of logical font and style (in this case, the font rendering engines apply algorithmic styles to the font). The second form is used if different physical fonts are used for a character subset for different logical fonts and styles. In this case, properties must be specified for each combination of logical font and style, so 20 properties for one character subset. If a property of the first form is present for a character subset, then properties of the second form for the same character subset are ignored.

The values are platform font names, as described above.

Since the character subsets supported by given fonts often overlap, separate search sequence properties are used to define in which order to try the fonts when rendering a character.

Search Sequences

The Java runtime uses sequence properties to determine search sequences for the five logical fonts. However, a font configuration file may specify properties that are specific to a combination of encoding, language, and country, and the runtime will then use a lookup to determine the search sequence property for each logical font.

The keys have the form:

     sequence.allfonts.Encoding.Language.Country
        sequence.LogicalFontName.Encoding.Language.Country
        sequence.allfonts.Encoding.Language
        sequence.LogicalFontName.Encoding.Language
        sequence.allfonts.Encoding
        sequence.LogicalFontName.Encoding
        sequence.allfonts
        sequence.LogicalFontName

The allfonts forms are used if the sequence is used for all five logical fonts. The forms specifying logical font names are used if different sequences are used for different logical fonts.

For each logical font, the Java runtime uses the property value with the first of the above keys. This property determines the primary search sequence for the logical font.

The file may also define a single fallback search sequence. The key for the fallback search sequence property is:

     sequence.fallback

The values of all search sequence properties have the form:

SearchSequenceValue:
        CharacterSubsetName
        CharacterSubsetName , SearchSequenceValue

The primary search sequence properties specify character subset names for required fonts, which are used for both AWT and 2D font rendering. The fallback search sequence property gives character subset names for optional fonts, which are used as fallbacks for all logical fonts, but only for 2D font rendering. The runtime automatically adds the Lucida Sans Regular font as a fallback font for 2D rendering if it's not already specified. If the runtime environment has a directory lib/fonts/fallback and this directory contains valid TrueType or Type 1 fonts, the runtime automatically adds these fonts as fallback fonts for 2D rendering. On Windows, if there is a system EUDC (End User Defined Characters) font registered with Windows, the runtime automatically adds this font as well as a fallback font for 2D rendering.

The sequence properties determine in which sequence component fonts are tried to render a given character. For example, given the following properties:

sequence.monospaced=japanese,alphabetic
sequence.fallback=korean
monospaced.plain.alphabetic=Arial
monospaced.plain.japanese=MSGothic
monospaced.plain.korean=Gulim

the runtime will first attempt to render a character with the MSGothic font. If that font doesn't provide a glyph for the character, it will attempt the Arial font. For 2D rendering, it will also try the Gulim and the Lucida Sans Regular font as well as any TrueType or Type 1 fonts in the runtime's lib/fonts/fallback directory. For 2D rendering on Windows, if there is a system EUDC font registered with Windows, the runtime will finally try this EUDC font.

When calculating font metrics for a logical font without reference to a string, only the required fonts are taken into consideration. For the example above, the FontMetrics.getMaxDescent method would return results based on the MSGothic and Arial fonts, but not the Gulim and Lucida Sans fonts. In this way, simple user interface elements such as buttons, which sometimes calculate their size based on font metrics, are not affected by an extended list of component fonts which their labels usually don't use. On the other hand, text components typically calculate metrics based on the text they contain and thus will obtain correct results.

The sequence properties that the runtime obtains for the five logical fonts should list the same character subsets, but may list them in different order.

Exclusion Ranges

The exclusion range properties specify Unicode character ranges which should be excluded from being rendered with the fonts corresponding to a given character subset. This is used if a font with a large character repertoire needs to be placed early in the search sequence (for example, for performance reasons), but some characters that it supports should be drawn with a different font instead. These properties are optional, so there's at most one per character subset.

The keys have the form:

     exclusion.CharacterSubsetName

The values have the form:

ExclusionRangeValue:
        Range
        Range , ExclusionRangeValue

Range:
        Char - Char

Char:
        HexDigit HexDigit HexDigit HexDigit
        HexDigit HexDigit HexDigit HexDigit HexDigit HexDigit

A Char is a Unicode character represented as a hexadecimal value.

Proportional Fonts

The proportional font properties describe the relationship between proportional and non-proportional variants of otherwise equivalent fonts. These properties are used to implement preferences specified by the GraphicsEnvironment.preferProportionalFonts method.

The keys have the form:

     proportional.PlatformFontName

Space characters in the platform font name must be replaced with underscore characters ("_").

The values have the form:

     PlatformFontName

In values, space characters are left unmodified.

Each property indicates that the font named in the value is the proportional equivalent of the font named in the key, and also that the font named in the key is the non-proportional equivalent of the font named in the value.

Font File Names

Font file name properties provide the names of the files containing the physical fonts used in the font configuration file. File names are required for all physical fonts on Windows and recommended for all physical fonts on Solaris and Linux.

The keys have the form:

     filename.PlatformFontName

Space characters in the platform font name must be replaced with underscore characters ("_").

The values are the file names of the files containing the fonts. On Windows, simple file names are used; and the runtime environment looks for each file first in its own lib/fonts directory, then in the Windows fonts directory. On Solaris and Linux, absolute path names, path names starting with "$JRE_LIB_FONTS" for the runtime environment's own lib/fonts directory, or xlfd names are used.

Appended Font Path

The Java runtime can automatically determine a number of directories that contain font files, such as its own lib/fonts directory or the Windows fonts folder. Additional directories can be specified to be appended to the font path.

The key has the form:

     appendedfontpath

The value has the form:

AppendedFontPathValue:
        Directory
        Directory PathSeparator AppendedFontPathValue

The path separator is the platform dependent value of java.io.File.pathSeparator.

Properties for Windows

There are no platform-specific properties for Windows. However, there is a special form of the character subset name used in search sequences. The name "alphabetic" can take a suffix indicating the character encoding associated with the subset:

     alphabetic
        alphabetic/default
        alphabetic/1252

This information is only used for AWT, not for 2D. The "/default" suffix restricts use of the component fonts for this character subset to the character set of the default encoding; the "/1252" suffix to the Windows-1252 character set. For accessing component font mappings and exclusion ranges, the character encoding suffix is omitted. For all other character subsets, the AWT character encoding is determined internally by the Java runtime.

Properties for Solaris and Linux

Motif Component Font Mappings

The AWT text components, which rely on Motif-based peers for text rendering, cannot always use the same platform fonts as other AWT components and 2D. When looking up component fonts for these components, additional keys are recognized. The complete set of keys looked up in this case is:

     allfonts.CharacterSubsetName.motif
        LogicalFontName.StyleName.CharacterSubsetName.motif
        allfonts.CharacterSubsetName
        LogicalFontName.StyleName.CharacterSubsetName

AWT X11 Font Path

The AWT font path properties specify platform directories which should be added to the X11 server font path. The keys have the form:

   awtfontpath.CharacterSubsetName

The values have the form:

AWTFontPathValue:
        Directory
        Directory : AWTFontPathValue

The directories must be valid X11 font directories. The Java runtime ensures that the directories for all character subsets of a primary search sequence found by the search sequence lookup are part of the X11 font path. The implementation assumes that all logical fonts use the same set of character subsets for a given environment of encoding, language, and country.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


The For-Each Loop

Iterating over a collection is uglier than it needs to be. Consider the following method, which takes a collection of timer tasks and cancels them:
void cancelAll(Collection<TimerTask> c) {
    for (Iterator<TimerTask> i = c.iterator(); i.hasNext(); )
        i.next().cancel();
}

The iterator is just clutter. Furthermore, it is an opportunity for error. The iterator variable occurs three times in each loop: that is two chances to get it wrong. The for-each construct gets rid of the clutter and the opportunity for error. Here is how the example looks with the for-each construct:

void cancelAll(Collection<TimerTask> c) {
    for (TimerTask t : c)
        t.cancel();
}

When you see the colon (:) read it as "in." The loop above reads as "for each TimerTask t in c." As you can see, the for-each construct combines beautifully with generics. It preserves all of the type safety, while removing the remaining clutter. Because you don't have to declare the iterator, you don't have to provide a generic declaration for it. (The compiler does this for you behind your back, but you need not concern yourself with it.)

Here is a common mistake people make when they are trying to do nested iteration over two collections:

List suits = ...;
List ranks = ...;
List sortedDeck = new ArrayList();

// BROKEN - throws NoSuchElementException!
for (Iterator i = suits.iterator(); i.hasNext(); )
    for (Iterator j = ranks.iterator(); j.hasNext(); )
        sortedDeck.add(new Card(i.next(), j.next()));

Can you spot the bug? Don't feel bad if you can't. Many expert programmers have made this mistake at one time or another. The problem is that the next method is being called too many times on the "outer" collection (suits). It is being called in the inner loop for both the outer and inner collections, which is wrong. In order to fix it, you have to add a variable in the scope of the outer loop to hold the suit:

// Fixed, though a bit ugly
for (Iterator i = suits.iterator(); i.hasNext(); ) {
    Suit suit = (Suit) i.next();
    for (Iterator j = ranks.iterator(); j.hasNext(); )
        sortedDeck.add(new Card(suit, j.next()));
}

So what does all this have to do with the for-each construct? It is tailor-made for nested iteration! Feast your eyes:

for (Suit suit : suits)
    for (Rank rank : ranks)
        sortedDeck.add(new Card(suit, rank));

The for-each construct is also applicable to arrays, where it hides the index variable rather than the iterator. The following method returns the sum of the values in an int array:

>// Returns the sum of the elements of a>
int sum(int[] a) {
    int result = 0;
    for (int i : a)
        result += i;
    return result;
}

So when should you use the for-each loop? Any time you can. It really beautifies your code. Unfortunately, you cannot use it everywhere. Consider, for example, the expurgate method. The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over multiple collections in parallel. These shortcomings were known by the designers, who made a conscious decision to go with a clean, simple construct that would cover the great majority of cases.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.source.tree.ForLoopTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.ForLoopTree

  • Packages that use ForLoopTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of ForLoopTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type ForLoopTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitForLoop(ForLoopTree node, P p)

    • Uses of ForLoopTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type ForLoopTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitForLoop(ForLoopTree node, P p)
      R | SimpleTreeVisitor.visitForLoop(ForLoopTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Formatted Text Fields

This document outlines the Swing implementation of formatted text fields. Formatted text fields provide a way for developers to specify the legal set of characters that can be input into a text component. This document is arranged in the following sections:

  • Using JFormattedTextField
  • How JFormattedTextField Works
  • Filtering Input
  • Filtering Navigation
  • JFormattedTextField.AbstractFormatter
  • JFormattedTextField.AbstractFormatterFactory
  • DefaultFormatter
  • AbstractFormatter implementations
  • java.text.Format changes
  • JavaDoc

Using JFormattedTextField

JFormattedTextField will allow formatting of dates, numbers, Strings and arbitrary Objects. JFormattedTextField will rely on the java.text.Format classes to handle formatting of dates and numbers. To create a JFormattedTextField to input dates in the current locale-specific format:

    new JFormattedTextField(new Date());

If you need to display the dates in a specific format, you can use one of the SimpleDateFormat constructors:

    new JFormattedTextField(new SimpleDateFormat("MM/dd/yy"));

Numbers will be handled by an instance of java.text.NumberFormat. The following shows several ways to create a JFormattedTextField to edit numbers.

   new JFormattedTextField(new Number(1000));
   new JFormattedTextField(new DecimalFormat("#,###"));
   new JFormattedTextField(new DecimalFormat("0.###E0"));

JFormattedTextField will also support editing of strings given a mask that specifies what the legal characters are at a given character position. To create a JFormattedTextField to edit US phone numbers the following could be used:

   new JFormattedTextField(new MaskFormatter("(###) ###-####"));

How JFormattedTextField Works

JFormattedTextField itself exposes a minimal amount of API in addition to that of its super class, JTextField. In its simplest terms, JFormattedTextField can be thought of as a JTextField with an additional value property (of type Object) and an object to handle the formatting (instance of AbstractFormatter).

As the value property is of type Object, it is necessary for the developer to cast the return type based on how the JFormattedTextField has been configured. The following shows a typical scenario of using a JFormattedTextField with dates:

  JFormattedTextField ftf = new JFormattedTextField();
  ftf.setValue(new Date());
  ...
  Date date = (Date)ftf.getValue();

A typical session for editing numbers looks like:

  JFormattedTextField ftf = new JFormattedTextField();
  ftf.setValue(new Integer(1000));
  ...
  int intValue = ((Number)ftf.getValue()).intValue();

Filtering Input

Constraining the input into a text component previously required creating a subclass of Document. This is a rather heavy operation for such a simple, and common, usage. To make this task easier, we have created a class, DocumentFilter, that can be plugged into a Document (Document is an interface, which has not changed, instead AbstractDocument now has a setter/getter for a DocumentFilter, and a property is set for Documents that do not descend from AbstractDocument so that others can support DocumentFilter should they want to). When a Document with a DocumentFilter is messaged to remove or insert content, the Document invokes the corresponding method on the DocumentFilter. It is the DocumentFilter's responsibility to issue a callback if the operation should proceed. In this manner the DocumentFilter has total control over how the Document can be mutated. DocumentFilter is defined by:

  public void remove(FilterBypass fb, int offset, int length) throws BadLocationException;
  public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException;
  public void replace(FilterBypass fb, int offset, int length, String string, AttributeSet attr) throws BadLocationException;

If the DocumentFilter wants to mutate the Document from inside the remove or insertString methods, it should either invoke super's implementation, or invoke the method on the FilterBypass. Invoking the method on super or FilterBypass provides a way to circumvent the filter so that the caller doesn't get stuck in stack recursion. The DocumentFilter is not limited to only invoking one method back on the FilterBypass. It can invoke any of the methods exposed by FilterBypass, and can invoke them as many times as it wishes (within the scope of one of DocumentFilter's methods). FilterBypass is defined by:

  public abstract Document getDocument();
  public abstract void remove(int offset, int length) throws BadLocationException;
  public abstract void insertString(int offset, String string, AttributeSet attr) throws BadLocationException;
  public abstract void replace(int offset, int length, String string, AttributeSet attr) throws BadLocationException;

The following example illustrates creating a DocumentFilter that maps lower case to upper case letters:

   DocumentFilter upperDF = new DocumentFilter() {
      public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
          super.insertString(fb, offset, string.toUpperCase(), attr);
      }

      public void replace(FilterBypass fb, int offset, int length, String string, AttributeSet attr) throws BadLocationException {
          if (string != null) {
              string = text.toUpperCase();
          }
          super.replace(fb, offset, length, string, attr);
      }
   };

Filtering Navigation

Similar to DocumentFilter, a new class, NavigationFilter, allows for filtering where the selection can be placed. NavigationFilter is called by the navigation actions (such as left, right, center) to determine the next position to place the selection from a given position. NavigationFilter is a property on JTextComponent, and is defined by:

    public void setDot(FilterBypass fb, int dot, Position.Bias bias);
    public void moveDot(FilterBypass fb, int dot, Position.Bias bias);
    public int getNextVisualPositionFrom(JTextComponent text, int pos, Position.Bias bias, int direction, Position.Bias[] biasRet) throws BadLocationException;

Note that getNextVisualPositionFrom is defined in View; for consistency, the method in NavigationFilter is named the same.

Similar to DocumentFilter, NavigationFilter is passed a FilterBypass that should be invoked to handle the actual mutation. NavigationFilter.FilterBypass is defined by:

    public abstract Caret getCaret();
    public abstract void setDot(int dot, Position.Bias bias);
    public abstract void moveDot(int dot, Position.Bias bias);

JFormattedTextField.AbstractFormatter

As previously mentioned, an instance of AbstractFormatter is used to format a particular Object value. AbstractFormatter can also impose an editing policy by defining a DocumentFilter; it can also impose a navigation policy by defining a NavigationFilter. AbstractFormatter is defined by:

    public void install(JFormattedTextField ftf);
    public void uninstall();
    public abstract Object stringToValue(String text) throws ParseException;
    public abstract String valueToString(Object value) throws ParseException;
    protected JFormattedTextField getFormattedTextField();
    protected void setEditValid(boolean valid);
    protected void invalidEdit();
    protected Action[] getActions();
    protected DocumentFilter getDocumentFilter();
    protected NavigationFilter getNavigationFilter();

Once JFormattedTextField is ready to use an AbstractFormatter it invokes install. AbstractFormatter.install performs the following:

  1. Sets the text of the JFormattedTextField to the return value of valueToString (if a ParseException is thrown, an empty String is used and setEditValid(false) is invoked).
  2. Installs the DocumentFilter returned from getDocumentFilter onto the JFormattedTextField's Document.
  3. Installs the NavigationFilter returned from getNavigationFilter onto the JFormattedTextField.
  4. Installs the Actions returned from getActions onto the JFormattedTextField's ActionMap.

Subclasses will typically only override install if they need to install additional Listeners beyond the DocumentFilter and NavigationFilter, or perhaps place the caret at an initial location.

Some AbstractFormatters allow the JFormattedTextField to contain an invalid value when editing. To allow the JFormattedTextField to provide an indication of this, the AbstractFormatter should invoke setEditValid(false) when the user enters an invalid value, and then invoke setEditValid(true) when the value is valid again.

When JFormattedTextField is done with an AbstractFormatter, it invokes uninstall. uninstall removes the previously installed Listeners.

JFormattedTextField.AbstractFormatterFactory

JFormattedTextField delegates the creation of AbstractFormatters to an instance of AbstractFormatterFactory (a public static inner class of JFormattedTextField). This makes it easy for developers to provide different formatters for different states of the JFormattedTextField. For example, you could provide a special AbstractFormatter if the current value is null, or one formatter when editing and another when displaying. AbstractFormatterFactory is defined by:

    public abstract AbstractFormatter getFormatter(JFormattedTextField ftf);

If the developer has not supplied an AbstractFormatterFactory, one will be created based on the Class of the value.

DefaultFormatter

DefaultFormatter extends JFormattedTextField.AbstractFormatter and is the superclass for all of the formatter implementations we provide. DefaultFormatter formats Objects using toString and creates the Object using the constructor that takes a String. DefaultFormatter allows a number of configuration options:

Option | Description
CommitsOnValidEdit | Determines when edits are published back to the JFormattedTextField. If true, commitEdit is invoked on the JFormattedTextField after every successful edit, otherwise commitEdit is invoked only when return is pressed.
OverwriteMode | Configures the behavior when inserting characters. If overwriteMode is true (the default), new characters overwrite existing characters in the model as they are inserted.
AllowsInvalid | Determines whether the value being edited is allowed to be invalid. It is often convenient to allow the user to enter invalid values until a commit is attempted.

AbstractFormatter implementations

The following table lists the AbstractFormatter implementations that we provide, as well as intended use:

AbstractFormatter | Object Type | Notes
DefaultFormatter | Object | valueToString uses Object.toString(), and stringToValue uses the single argument constructor that takes a String.
MaskFormatter | Strings | Behavior is dictated by a per character mask that specifies legal values (e.g. "###-####").
InternationalFormatter | Objects | Uses an instance of java.text.Format to handle valueToString and stringToValue.
NumberFormatter | Numbers | Uses an instance of NumberFormat to handle formatting, descends from InternationalFormatter.
DateFormatter | Date | Uses an instance of DateFormat to handle formatting, descends from InternationalFormatter.

java.text.Format changes

The Swing support for formatted dates and numbers made extensive use of the Format classes in the java.text package. The following problems were encountered using the previous API:

  • You could only get the limits of one field at a time. If you wanted more, you had to invoke format repeatedly.
  • The previous field constants were not sufficient to describe the entire text of the formatted strings. One glaring omission was the exponential part of formatted numbers.
  • Using integer IDs for a set of constants that pretended to be extensible wasn't very elegant. When new constants were added, there could potentially be a conflict with any Format subclasses out there that we didn't know about. Note that the constants for DateFormat and NumberFormat already overlap, so a NumberFormat would have happily interpreted YEAR_FIELD as FRACTION_FIELD. The problem was exacerbated by the existence of the polymorphic Format.format(Object, StringBuffer, FieldPosition) method.
  • The specification didn't define the behavior if a field didn't exist in a formatted string, and the actual results varied between different releases.
  • The specification didn't define the behavior if a field wasn't recognized by a formatter; for example, if I asked a NumberFormat for the MONTH_FIELD (the actual implementation of this case returned 0 for both begin index and end index).
  • Because of that, a caller could not find out which fields a Format subclass actually supported unless it knew the specific subclass. This, along with the fact that not all characters in a formatted string are part of fields, makes the implementation of a generic method that returns all fields impossible.

These issues have largely been addressed by adding the following method to java.text.Format:

    public AttributedCharacterIterator formatToCharacterIterator(Object obj);

Each Format class uses a type safe enumeration for the constants it supports.

JavaDoc

New Classes

The following classes are new to the 1.4 release:

  • JFormattedTextField
  • DocumentFilter
  • NavigationFilter
  • JFormattedTextField.AbstractFormatter
  • JFormattedTextField.AbstractFormatterFactory
  • DefaultFormatterFactory
  • DefaultFormatter
  • MaskFormatter
  • InternationalFormatter
  • Number Formatter
  • DateFormatter

Constants are renamed to conform to Java naming conventions

The bugtraq report that corresponds to this change is: 4468474.

The following constants have been replaced to conform Java to naming conventions:

  • CommitValueOnFocusLost has been replaced with COMMIT.
  • CommitOrRevertValueOnFocusLost has been replaced with COMMIT_OR_REVERT.
  • RevertValueOnFocusLost has been replaced with REVERT.
  • PersistValueOnFocusLost has been replaced with PERSIST.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JNI Functions

Chapter 4

This chapter serves as the reference section for the JNI functions. It provides a complete listing of all the JNI functions. It also presents the exact layout of the JNI function table.

Note the use of the term “must” to describe restrictions on JNI programmers. For example, when you see that a certain JNI function must receive a non-NULL object, it is your responsibility to ensure that NULL is not passed to that JNI function. As a result, a JNI implementation does not need to perform NULL pointer checks in that JNI function.

A portion of this chapter is adapted from Netscape’s JRI documentation.

The reference material groups functions by their usage. The reference section is organized by the following functional areas:

  • Version Information
  • Class Operations
  • Exceptions
  • Global and Local References
  • Weak Global References
  • Object Operations
  • Accessing Fields of Objects
  • Calling Instance Methods
  • Accessing Static Fields
  • Calling Static Methods
  • String Operations
  • Array Operations
  • Registering Native Methods
  • Monitor Operations
  • NIO Support
  • Reflection Support
  • Java VM Interface

Interface Function Table

Each function is accessible at a fixed offset through the JNIEnv argument. The JNIEnv type is a pointer to a structure storing all JNI function pointers. It is defined as follows:

typedef const struct JNINativeInterface *JNIEnv;

The VM initializes the function table, as shown by Code Example 4-1. Note that the first three entries are reserved for future compatibility with COM. In addition, we reserve a number of additional NULL entries near the beginning of the function table, so that, for example, a future class-related JNI operation can be added after FindClass, rather than at the end of the table.

Note that the function table can be shared among all JNI interface pointers.

Code Example 4-1
const struct JNINativeInterface ... = {

    NULL,
    NULL,
    NULL,
    NULL,
    GetVersion,

    DefineClass,
    FindClass,

    FromReflectedMethod,
    FromReflectedField,
    ToReflectedMethod,

    GetSuperclass,
    IsAssignableFrom,

    ToReflectedField,

    Throw,
    ThrowNew,
    ExceptionOccurred,
    ExceptionDescribe,
    ExceptionClear,
    FatalError,

    PushLocalFrame,
    PopLocalFrame,

    NewGlobalRef,
    DeleteGlobalRef,
    DeleteLocalRef,
    IsSameObject,
    NewLocalRef,
    EnsureLocalCapacity,

    AllocObject,
    NewObject,
    NewObjectV,
    NewObjectA,

    GetObjectClass,
    IsInstanceOf,

    GetMethodID,

    CallObjectMethod,
    CallObjectMethodV,
    CallObjectMethodA,
    CallBooleanMethod,
    CallBooleanMethodV,
    CallBooleanMethodA,
    CallByteMethod,
    CallByteMethodV,
    CallByteMethodA,
    CallCharMethod,
    CallCharMethodV,
    CallCharMethodA,
    CallShortMethod,
    CallShortMethodV,
    CallShortMethodA,
    CallIntMethod,
    CallIntMethodV,
    CallIntMethodA,
    CallLongMethod,
    CallLongMethodV,
    CallLongMethodA,
    CallFloatMethod,
    CallFloatMethodV,
    CallFloatMethodA,
    CallDoubleMethod,
    CallDoubleMethodV,
    CallDoubleMethodA,
    CallVoidMethod,
    CallVoidMethodV,
    CallVoidMethodA,

    CallNonvirtualObjectMethod,
    CallNonvirtualObjectMethodV,
    CallNonvirtualObjectMethodA,
    CallNonvirtualBooleanMethod,
    CallNonvirtualBooleanMethodV,
    CallNonvirtualBooleanMethodA,
    CallNonvirtualByteMethod,
    CallNonvirtualByteMethodV,
    CallNonvirtualByteMethodA,
    CallNonvirtualCharMethod,
    CallNonvirtualCharMethodV,
    CallNonvirtualCharMethodA,
    CallNonvirtualShortMethod,
    CallNonvirtualShortMethodV,
    CallNonvirtualShortMethodA,
    CallNonvirtualIntMethod,
    CallNonvirtualIntMethodV,
    CallNonvirtualIntMethodA,
    CallNonvirtualLongMethod,
    CallNonvirtualLongMethodV,
    CallNonvirtualLongMethodA,
    CallNonvirtualFloatMethod,
    CallNonvirtualFloatMethodV,
    CallNonvirtualFloatMethodA,
    CallNonvirtualDoubleMethod,
    CallNonvirtualDoubleMethodV,
    CallNonvirtualDoubleMethodA,
    CallNonvirtualVoidMethod,
    CallNonvirtualVoidMethodV,
    CallNonvirtualVoidMethodA,

    GetFieldID,

    GetObjectField,
    GetBooleanField,
    GetByteField,
    GetCharField,
    GetShortField,
    GetIntField,
    GetLongField,
    GetFloatField,
    GetDoubleField,
    SetObjectField,
    SetBooleanField,
    SetByteField,
    SetCharField,
    SetShortField,
    SetIntField,
    SetLongField,
    SetFloatField,
    SetDoubleField,

    GetStaticMethodID,

    CallStaticObjectMethod,
    CallStaticObjectMethodV,
    CallStaticObjectMethodA,
    CallStaticBooleanMethod,
    CallStaticBooleanMethodV,
    CallStaticBooleanMethodA,
    CallStaticByteMethod,
    CallStaticByteMethodV,
    CallStaticByteMethodA,
    CallStaticCharMethod,
    CallStaticCharMethodV,
    CallStaticCharMethodA,
    CallStaticShortMethod,
    CallStaticShortMethodV,
    CallStaticShortMethodA,
    CallStaticIntMethod,
    CallStaticIntMethodV,
    CallStaticIntMethodA,
    CallStaticLongMethod,
    CallStaticLongMethodV,
    CallStaticLongMethodA,
    CallStaticFloatMethod,
    CallStaticFloatMethodV,
    CallStaticFloatMethodA,
    CallStaticDoubleMethod,
    CallStaticDoubleMethodV,
    CallStaticDoubleMethodA,
    CallStaticVoidMethod,
    CallStaticVoidMethodV,
    CallStaticVoidMethodA,

    GetStaticFieldID,

    GetStaticObjectField,
    GetStaticBooleanField,
    GetStaticByteField,
    GetStaticCharField,
    GetStaticShortField,
    GetStaticIntField,
    GetStaticLongField,
    GetStaticFloatField,
    GetStaticDoubleField,

    SetStaticObjectField,
    SetStaticBooleanField,
    SetStaticByteField,
    SetStaticCharField,
    SetStaticShortField,
    SetStaticIntField,
    SetStaticLongField,
    SetStaticFloatField,
    SetStaticDoubleField,

    NewString,

    GetStringLength,
    GetStringChars,
    ReleaseStringChars,

    NewStringUTF,
    GetStringUTFLength,
    GetStringUTFChars,
    ReleaseStringUTFChars,

    GetArrayLength,

    NewObjectArray,
    GetObjectArrayElement,
    SetObjectArrayElement,

    NewBooleanArray,
    NewByteArray,
    NewCharArray,
    NewShortArray,
    NewIntArray,
    NewLongArray,
    NewFloatArray,
    NewDoubleArray,

    GetBooleanArrayElements,
    GetByteArrayElements,
    GetCharArrayElements,
    GetShortArrayElements,
    GetIntArrayElements,
    GetLongArrayElements,
    GetFloatArrayElements,
    GetDoubleArrayElements,

    ReleaseBooleanArrayElements,
    ReleaseByteArrayElements,
    ReleaseCharArrayElements,
    ReleaseShortArrayElements,
    ReleaseIntArrayElements,
    ReleaseLongArrayElements,
    ReleaseFloatArrayElements,
    ReleaseDoubleArrayElements,

    GetBooleanArrayRegion,
    GetByteArrayRegion,
    GetCharArrayRegion,
    GetShortArrayRegion,
    GetIntArrayRegion,
    GetLongArrayRegion,
    GetFloatArrayRegion,
    GetDoubleArrayRegion,
    SetBooleanArrayRegion,
    SetByteArrayRegion,
    SetCharArrayRegion,
    SetShortArrayRegion,
    SetIntArrayRegion,
    SetLongArrayRegion,
    SetFloatArrayRegion,
    SetDoubleArrayRegion,

    RegisterNatives,
    UnregisterNatives,

    MonitorEnter,
    MonitorExit,

    GetJavaVM,

    GetStringRegion,
    GetStringUTFRegion,

    GetPrimitiveArrayCritical,
    ReleasePrimitiveArrayCritical,

    GetStringCritical,
    ReleaseStringCritical,

    NewWeakGlobalRef,
    DeleteWeakGlobalRef,

    ExceptionCheck,

    NewDirectByteBuffer,
    GetDirectBufferAddress,
    GetDirectBufferCapacity,

    GetObjectRefType
  };

Version Information

GetVersion

jint GetVersion(JNIEnv *env);

Returns the version of the native method interface.

LINKAGE:

Index 4 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

RETURNS:

Returns the major version number in the higher 16 bits and the minor version number in the lower 16 bits.

In JDK/JRE 1.1, GetVersion() returns 0x00010001.

In JDK/JRE 1.2, GetVersion() returns 0x00010002.

In JDK/JRE 1.4, GetVersion() returns 0x00010004.

In JDK/JRE 1.6, GetVersion() returns 0x00010006.

Constants

SINCE JDK/JRE 1.2:

#define JNI_VERSION_1_1 0x00010001
#define JNI_VERSION_1_2 0x00010002

/* Error codes */
#define JNI_EDETACHED    (-2)              /* thread detached from the VM */
#define JNI_EVERSION     (-3)              /* JNI version error

SINCE JDK/JRE 1.4:

    #define JNI_VERSION_1_4 0x00010004

SINCE JDK/JRE 1.6:

    #define JNI_VERSION_1_6 0x00010006

Class Operations

DefineClass

jclass DefineClass(JNIEnv *env, const char *name, jobject loader,
const jbyte *buf, jsize bufLen);

Loads a class from a buffer of raw class data. The buffer containing the raw class data is not referenced by the VM after the DefineClass call returns, and it may be discarded if desired.

LINKAGE:

Index 5 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

name: the name of the class or interface to be defined. The string is encoded in modified UTF-8.

loader: a class loader assigned to the defined class.

buf: buffer containing the .class file data.

bufLen: buffer length.

RETURNS:

Returns a Java class object or NULL if an error occurs.

THROWS:

ClassFormatError: if the class data does not specify a valid class.

ClassCircularityError: if a class or interface would be its own superclass or superinterface.

OutOfMemoryError: if the system runs out of memory.

SecurityException: if the caller attempts to define a class in the "java" package tree.

FindClass

jclass FindClass(JNIEnv *env, const char *name);

In JDK release 1.1, this function loads a locally-defined class. It searches the directories and zip files specified by the CLASSPATH environment variable for the class with the specified name.

Since Java 2 SDK release 1.2, the Java security model allows non-system classes to load and call native methods. FindClass locates the class loader associated with the current native method; that is, the class loader of the class that declared the native method. If the native method belongs to a system class, no class loader will be involved. Otherwise, the proper class loader will be invoked to load and link the named class.

Since Java 2 SDK release 1.2, when FindClass is called through the Invocation Interface, there is no current native method or its associated class loader. In that case, the result of ClassLoader.getSystemClassLoader is used. This is the class loader the virtual machine creates for applications, and is able to locate classes listed in the java.class.path property.

The name argument is a fully-qualified class name or an array type signature . For example, the fully-qualified class name for the java.lang.String class is:

                   "java/lang/String"

The array type signature of the array class java.lang.Object[] is:

                   "[Ljava/lang/Object;"

LINKAGE:

Index 6 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

name: a fully-qualified class name (that is, a package name, delimited by “/”, followed by the class name). If the name begins with “[“ (the array signature character), it returns an array class. The string is encoded in modified UTF-8.

RETURNS:

Returns a class object from a fully-qualified name, or NULL if the class cannot be found.

THROWS:

ClassFormatError: if the class data does not specify a valid class.

ClassCircularityError: if a class or interface would be its own superclass or superinterface.

NoClassDefFoundError: if no definition for a requested class or interface can be found.

OutOfMemoryError: if the system runs out of memory.

GetSuperclass

jclass GetSuperclass(JNIEnv *env, jclass clazz);

If clazz represents any class other than the class Object, then this function returns the object that represents the superclass of the class specified by clazz.

If clazz specifies the class Object, or clazz represents an interface, this function returns NULL.

LINKAGE:

Index 10 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

RETURNS:

Returns the superclass of the class represented by clazz, or NULL.

IsAssignableFrom

jboolean IsAssignableFrom(JNIEnv *env, jclass clazz1,
jclass clazz2);

Determines whether an object of clazz1 can be safely cast to clazz2.

LINKAGE:

Index 11 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

clazz1: the first class argument.

clazz2: the second class argument.

RETURNS:

Returns JNI_TRUE if either of the following is true:

  • The first and second class arguments refer to the same Java class.
  • The first class is a subclass of the second class.
  • The first class has the second class as one of its interfaces.

Exceptions

Throw

jint Throw(JNIEnv *env, jthrowable obj);

Causes a java.lang.Throwable object to be thrown.

LINKAGE:

Index 13 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

obj: a java.lang.Throwable object.

RETURNS:

Returns 0 on success; a negative value on failure.

THROWS:

the java.lang.Throwable object obj.

ThrowNew

jint ThrowNew(JNIEnv *env, jclass clazz,
const char *message);

Constructs an exception object from the specified class with the message specified by message and causes that exception to be thrown.

LINKAGE:

Index 14 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

clazz: a subclass of java.lang.Throwable.

message: the message used to construct the java.lang.Throwable object. The string is encoded in modified UTF-8.

RETURNS:

Returns 0 on success; a negative value on failure.

THROWS:

the newly constructed java.lang.Throwable object.

ExceptionOccurred

jthrowable ExceptionOccurred(JNIEnv *env);

Determines if an exception is being thrown. The exception stays being thrown until either the native code calls ExceptionClear(), or the Java code handles the exception.

LINKAGE:

Index 15 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

RETURNS:

Returns the exception object that is currently in the process of being thrown, or NULL if no exception is currently being thrown.

ExceptionDescribe

void ExceptionDescribe(JNIEnv *env);

Prints an exception and a backtrace of the stack to a system error-reporting channel, such as stderr. This is a convenience routine provided for debugging.

LINKAGE:

Index 16 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

ExceptionClear

void ExceptionClear(JNIEnv *env);

Clears any exception that is currently being thrown. If no exception is currently being thrown, this routine has no effect.

LINKAGE:

Index 17 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

FatalError

void FatalError(JNIEnv *env, const char *msg);

Raises a fatal error and does not expect the VM to recover. This function does not return.

LINKAGE:

Index 18 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

msg: an error message. The string is encoded in modified UTF-8.

ExceptionCheck

We introduce a convenience function to check for pending exceptions without creating a local reference to the exception object.

jboolean ExceptionCheck(JNIEnv *env);

Returns JNI_TRUE when there is a pending exception; otherwise, returns JNI_FALSE.

LINKAGE:

Index 228 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

Global and Local References

Global References

NewGlobalRef

jobject NewGlobalRef(JNIEnv *env, jobject obj);

Creates a new global reference to the object referred to by the obj argument. The obj argument may be a global or local reference. Global references must be explicitly disposed of by calling DeleteGlobalRef().

LINKAGE:

Index 21 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

obj: a global or local reference.

RETURNS:

Returns a global reference, or NULL if the system runs out of memory.

DeleteGlobalRef

void DeleteGlobalRef(JNIEnv *env, jobject globalRef);

Deletes the global reference pointed to by globalRef.

LINKAGE:

Index 22 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

globalRef: a global reference.

Local References

Local references are valid for the duration of a native method call. They are freed automatically after the native method returns. Each local reference costs some amount of Java Virtual Machine resource. Programmers need to make sure that native methods do not excessively allocate local references. Although local references are automatically freed after the native method returns to Java, excessive allocation of local references may cause the VM to run out of memory during the execution of a native method.

DeleteLocalRef

void DeleteLocalRef(JNIEnv *env, jobject localRef);

Deletes the local reference pointed to by localRef.

LINKAGE:

Index 23 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

localRef: a local reference.

Note

JDK/JRE 1.1 provides the DeleteLocalRef function above so that programmers can manually delete local references. For example, if native code iterates through a potentially large array of objects and uses one element in each iteration, it is a good practice to delete the local reference to the no-longer-used array element before a new local reference is created in the next iteration.

As of JDK/JRE 1.2 an additional set of functions are provided for local reference lifetime management. They are the four functions listed below.

EnsureLocalCapacity

jint EnsureLocalCapacity(JNIEnv *env, jint capacity);

Ensures that at least a given number of local references can be created in the current thread. Returns 0 on success; otherwise returns a negative number and throws an OutOfMemoryError.

Before it enters a native method, the VM automatically ensures that at least 16 local references can be created.

For backward compatibility, the VM allocates local references beyond the ensured capacity. (As a debugging support, the VM may give the user warnings that too many local references are being created. In the JDK, the programmer can supply the -verbose:jni command line option to turn on these messages.) The VM calls FatalError if no more local references can be created beyond the ensured capacity.

LINKAGE:

Index 26 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

PushLocalFrame

jint PushLocalFrame(JNIEnv *env, jint capacity);

Creates a new local reference frame, in which at least a given number of local references can be created. Returns 0 on success, a negative number and a pending OutOfMemoryError on failure.

Note that local references already created in previous local frames are still valid in the current local frame.

LINKAGE:

Index 19 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

PopLocalFrame

jobject PopLocalFrame(JNIEnv *env, jobject result);

Pops off the current local reference frame, frees all the local references, and returns a local reference in the previous local reference frame for the given result object.

Pass NULL as result if you do not need to return a reference to the previous frame.

LINKAGE:

Index 20 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

NewLocalRef

jobject NewLocalRef(JNIEnv *env, jobject ref);

Creates a new local reference that refers to the same object as ref. The given ref may be a global or local reference. Returns NULL if ref refers to null.

LINKAGE:

Index 25 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

Weak Global References

Weak global references are a special kind of global reference. Unlike normal global references, a weak global reference allows the underlying Java object to be garbage collected. Weak global references may be used in any situation where global or local references are used. When the garbage collector runs, it frees the underlying object if the object is only referred to by weak references. A weak global reference pointing to a freed object is functionally equivalent to NULL. Programmers can detect whether a weak global reference points to a freed object by using IsSameObject to compare the weak reference against NULL.

Weak global references in JNI are a simplified version of the Java Weak References, available as part of the Java 2 Platform API ( java.lang.ref package and its classes).

Clarification (added June 2001)

Since garbage collection may occur while native methods are running, objects referred to by weak global references can be freed at any time. While weak global references can be used where global references are used, it is generally inappropriate to do so, as they may become functionally equivalent to NULL without notice.

While IsSameObject can be used to determine whether a weak global reference refers to a freed object, it does not prevent the object from being freed immediately thereafter. Consequently, programmers may not rely on this check to determine whether a weak global reference may used (as a non-NULL reference) in any future JNI function call.

To overcome this inherent limitation, it is recommended that a standard (strong) local or global reference to the same object be acquired using the JNI functions NewLocalRef or NewGlobalRef, and that this strong reference be used to access the intended object. These functions will return NULL if the object has been freed, and otherwise will return a strong reference (which will prevent the object from being freed). The new reference should be explicitly deleted when immediate access to the object is no longer required, allowing the object to be freed.

The weak global reference is weaker than other types of weak references (Java objects of the SoftReference or WeakReference classes). A weak global reference to a specific object will not become functionally equivalent to NULL until after SoftReference or WeakReference objects referring to that same specific object have had their references cleared.

The weak global reference is weaker than Java's internal references to objects requiring finalization. A weak global reference will not become functionally equivalent to NULL until after the completion of the finalizer for the referenced object, if present.

Interactions between weak global references and PhantomReferences are undefined. In particular, implementations of a Java VM may (or may not) process weak global references after PhantomReferences, and it may (or may not) be possible to use weak global references to hold on to objects which are also referred to by PhantomReference objects. This undefined use of weak global references should be avoided.

NewWeakGlobalRef

jweak NewWeakGlobalRef(JNIEnv *env, jobject obj);

Creates a new weak global reference. Returns NULL if obj refers to null, or if the VM runs out of memory. If the VM runs out of memory, an OutOfMemoryError will be thrown.

LINKAGE:

Index 226 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

DeleteWeakGlobalRef

void DeleteWeakGlobalRef(JNIEnv *env, jweak obj);

Delete the VM resources needed for the given weak global reference.

LINKAGE:

Index 227 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

Object Operations

AllocObject

jobject AllocObject(JNIEnv *env, jclass clazz);

Allocates a new Java object without invoking any of the constructors for the object. Returns a reference to the object.

The clazz argument must not refer to an array class.

LINKAGE:

Index 27 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

RETURNS:

Returns a Java object, or NULL if the object cannot be constructed.

THROWS:

InstantiationException: if the class is an interface or an abstract class.

OutOfMemoryError: if the system runs out of memory.

NewObject
NewObjectA
NewObjectV

jobject NewObject(JNIEnv *env, jclass clazz,
jmethodID methodID, ...);

jobject NewObjectA(JNIEnv *env, jclass clazz,
jmethodID methodID, const jvalue *args);

jobject NewObjectV(JNIEnv *env, jclass clazz,
jmethodID methodID, va_list args);

Constructs a new Java object. The method ID indicates which constructor method to invoke. This ID must be obtained by calling GetMethodID() with <init> as the method name and void (V) as the return type.

The clazz argument must not refer to an array class.

NewObject

Programmers place all arguments that are to be passed to the constructor immediately following the methodID argument. NewObject() accepts these arguments and passes them to the Java method that the programmer wishes to invoke.

LINKAGE:

Index 28 in the JNIEnv interface function table.

NewObjectA

Programmers place all arguments that are to be passed to the constructor in an args array of jvalues that immediately follows the methodID argument. NewObjectA() accepts the arguments in this array, and, in turn, passes them to the Java method that the programmer wishes to invoke.

LINKAGE:

Index 30 in the JNIEnv interface function table.

NewObjectV

Programmers place all arguments that are to be passed to the constructor in an args argument of type va_list that immediately follows the methodID argument. NewObjectV() accepts these arguments, and, in turn, passes them to the Java method that the programmer wishes to invoke.

LINKAGE:

Index 29 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

methodID: the method ID of the constructor.

Additional Parameter for NewObject:

arguments to the constructor.

Additional Parameter for NewObjectA:

args: an array of arguments to the constructor.

Additional Parameter for NewObjectV:

args: a va_list of arguments to the constructor.

RETURNS:

Returns a Java object, or NULL if the object cannot be constructed.

THROWS:

InstantiationException: if the class is an interface or an abstract class.

OutOfMemoryError: if the system runs out of memory.

Any exceptions thrown by the constructor.

GetObjectClass

jclass GetObjectClass(JNIEnv *env, jobject obj);

Returns the class of an object.

LINKAGE:

Index 31 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

obj: a Java object (must not be NULL).

RETURNS:

Returns a Java class object.

GetObjectRefType

jobjectRefType GetObjectRefType(JNIEnv* env, jobject obj);

Returns the type of the object referred to by the obj argument. The argument obj can either be a local, global or weak global reference.

LINKAGE:

Index 232 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

obj: a local, global or weak global reference.

vm: the virtual machine instance from which the interface will be retrieved.

env: pointer to the location where the JNI interface pointer for the current thread will be placed.

version: the requested JNI version.

RETURNS:

The function GetObjectRefType returns one of the following enumerated values defined as a jobjectRefType:

JNIInvalidRefType = 0,
JNILocalRefType = 1,
JNIGlobalRefType = 2,
JNIWeakGlobalRefType = 3

If the argument obj is a weak global reference type, the return will be JNIWeakGlobalRefType.

If the argument obj is a global reference type, the return value will be JNIGlobalRefType.

If the argument obj is a local reference type, the return will be JNILocalRefType.

If the obj argument is not a valid reference, the return value for this function will be JNIInvalidRefType.

An invalid reference is a reference which is not a valid handle. That is, the obj pointer address does not point to a location in memory which has been allocated from one of the Ref creation functions or returned from a JNI function.

As such, NULL would be an invalid reference and GetObjectRefType(env,NULL) would return JNIInvalidRefType.

On the other hand, a null reference, which is a reference that points to a null, would return the type of reference that the null reference was originally created as.

GetObjectRefType cannot be used on deleted references.

Since references are typically implemented as pointers to memory data structures that can potentially be reused by any of the reference allocation services in the VM, once deleted, it is not specified what value the GetObjectRefType will return.

SINCE:

JDK/JRE 1.6

IsInstanceOf

jboolean IsInstanceOf(JNIEnv *env, jobject obj,
jclass clazz);

Tests whether an object is an instance of a class.

LINKAGE:

Index 32 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

obj: a Java object.

clazz: a Java class object.

RETURNS:

Returns JNI_TRUE if obj can be cast to clazz; otherwise, returns JNI_FALSE. A NULL object can be cast to any class.

IsSameObject

jboolean IsSameObject(JNIEnv *env, jobject ref1,
jobject ref2);

Tests whether two references refer to the same Java object.

LINKAGE:

Index 24 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

ref1: a Java object.

ref2: a Java object.

RETURNS:

Returns JNI_TRUE if ref1 and ref2 refer to the same Java object, or are both NULL; otherwise, returns JNI_FALSE.

Accessing Fields of Objects

GetFieldID

jfieldID GetFieldID(JNIEnv *env, jclass clazz,
const char *name, const char *sig);

Returns the field ID for an instance (nonstatic) field of a class. The field is specified by its name and signature. The Get<type>Field and Set<type>Field families of accessor functions use field IDs to retrieve object fields.

GetFieldID() causes an uninitialized class to be initialized.

GetFieldID() cannot be used to obtain the length field of an array. Use GetArrayLength() instead.

LINKAGE:

Index 94 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

name: the field name in a 0-terminated modified UTF-8 string.

sig: the field signature in a 0-terminated modified UTF-8 string.

RETURNS:

Returns a field ID, or NULL if the operation fails.

THROWS:

NoSuchFieldError: if the specified field cannot be found.

ExceptionInInitializerError: if the class initializer fails due to an exception.

OutOfMemoryError: if the system runs out of memory.

Get<type>Field Routines

NativeType Get<type>Field(JNIEnv *env, jobject obj,
jfieldID fieldID);

This family of accessor routines returns the value of an instance (nonstatic) field of an object. The field to access is specified by a field ID obtained by calling GetFieldID().

The following table describes the Get<type>Field routine name and result type. You should replace type in Get<type>Field with the Java type of the field, or use one of the actual routine names from the table, and replace NativeType with the corresponding native type for that routine.

Table 4-1a Get<type>Field Family of Accessor Routines
Get<type>Field Routine Name | Native Type
GetObjectField() | jobject
GetBooleanField() | jboolean
GetByteField() | jbyte
GetCharField() | jchar
GetShortField() | jshort
GetIntField() | jint
GetLongField() | jlong
GetFloatField() | jfloat
GetDoubleField() | jdouble

LINKAGE:

Indices in the JNIEnv interface function table:
Table 4-1b Get<type>Field Family of Accessor Routines
Get<type>Field Routine Name | Index
GetObjectField() | 95
GetBooleanField() | 96
GetByteField() | 97
GetCharField() | 98
GetShortField() | 99
GetIntField() | 100
GetLongField() | 101
GetFloatField() | 102
GetDoubleField() | 103

PARAMETERS:

env: the JNI interface pointer.

obj: a Java object (must not be NULL).

fieldID: a valid field ID.

RETURNS:

Returns the content of the field.

Set<type>Field Routines

void Set<type>Field(JNIEnv *env, jobject obj, jfieldID fieldID,
 NativeType value);

This family of accessor routines sets the value of an instance (nonstatic) field of an object. The field to access is specified by a field ID obtained by calling GetFieldID().

The following table describes the Set<type>Field routine name and value type. You should replace type in Set<type>Field with the Java type of the field, or use one of the actual routine names from the table, and replace NativeType with the corresponding native type for that routine.

Table 4-2a Set<type>Field Family of Accessor Routines
Set<type>Field Routine | Native Type
SetObjectField() | jobject
SetBooleanField() | jboolean
SetByteField() | jbyte
SetCharField() | jchar
SetShortField() | jshort
SetIntField() | jint
SetLongField() | jlong
SetFloatField() | jfloat
SetDoubleField() | jdouble

LINKAGE:

Indices in the JNIEnv interface function table.

Table 4-2b Set<type>Field Family of Accessor Routines
Set<type>Field Routine | Index
SetObjectField() | 104
SetBooleanField() | 105
SetByteField() | 106
SetCharField() | 107
SetShortField() | 108
SetIntField() | 109
SetLongField() | 110
SetFloatField() | 111
SetDoubleField() | 112

PARAMETERS:

env: the JNI interface pointer.

obj: a Java object (must not be NULL).

fieldID: a valid field ID.

value: the new value of the field.

Calling Instance Methods

GetMethodID

jmethodID GetMethodID(JNIEnv *env, jclass clazz,
const char *name, const char *sig);

Returns the method ID for an instance (nonstatic) method of a class or interface. The method may be defined in one of the clazz’s superclasses and inherited by clazz. The method is determined by its name and signature.

GetMethodID() causes an uninitialized class to be initialized.

To obtain the method ID of a constructor, supply <init> as the method name and void (V) as the return type.

LINKAGE:

Index 33 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

name: the method name in a 0-terminated modified UTF-8 string.

sig: the method signature in 0-terminated modified UTF-8 string.

RETURNS:

Returns a method ID, or NULL if the specified method cannot be found.

THROWS:

NoSuchMethodError: if the specified method cannot be found.

ExceptionInInitializerError: if the class initializer fails due to an exception.

OutOfMemoryError: if the system runs out of memory.

Call<type>Method Routines
Call<type>MethodA Routines
Call<type>MethodV Routines

NativeType Call<type>Method(JNIEnv *env, jobject obj,
jmethodID methodID, ...);

NativeType Call<type>MethodA(JNIEnv *env, jobject obj,
jmethodID methodID, const jvalue *args);

NativeType Call<type>MethodV(JNIEnv *env, jobject obj,
jmethodID methodID, va_list args);

Methods from these three families of operations are used to call a Java instance method from a native method.They only differ in their mechanism for passing parameters to the methods that they call.

These families of operations invoke an instance (nonstatic) method on a Java object, according to the specified method ID. The methodID argument must be obtained by calling GetMethodID().

When these functions are used to call private methods and constructors, the method ID must be derived from the real class of obj, not from one of its superclasses.

Call<type>Method Routines

Programmers place all arguments that are to be passed to the method immediately following the methodID argument. The Call<type>Method routine accepts these arguments and passes them to the Java method that the programmer wishes to invoke.

Call<type>MethodA Routines

Programmers place all arguments to the method in an args array of jvalues that immediately follows the methodID argument. The Call<type>MethodA routine accepts the arguments in this array, and, in turn, passes them to the Java method that the programmer wishes to invoke.

Call<type>MethodV Routines

Programmers place all arguments to the method in an args argument of type va_list that immediately follows the methodID argument. The Call<type>MethodV routine accepts the arguments, and, in turn, passes them to the Java method that the programmer wishes to invoke.

The following table describes each of the method calling routines according to their result type. You should replace type in Call<type>Method with the Java type of the method you are calling (or use one of the actual method calling routine names from the table) and replace NativeType with the corresponding native type for that routine.

Table 4-3a Instance Method Calling Routines
Call<type>Method Routine Name | Native Type
CallVoidMethod() CallVoidMethodA() CallVoidMethodV() | void
CallObjectMethod() CallObjectMethodA() CallObjectMethodV() | jobject
CallBooleanMethod() CallBooleanMethodA() CallBooleanMethodV() | jboolean
CallByteMethod() CallByteMethodA() CallByteMethodV() | jbyte
CallCharMethod() CallCharMethodA() CallCharMethodV() | jchar
CallShortMethod() CallShortMethodA() CallShortMethodV() | jshort
CallIntMethod() CallIntMethodA() CallIntMethodV() | jint
CallLongMethod() CallLongMethodA() CallLongMethodV() | jlong
CallFloatMethod() CallFloatMethodA() CallFloatMethodV() | jfloat
CallDoubleMethod() CallDoubleMethodA() CallDoubleMethodV() | jdouble

LINKAGE:

Indices in the JNIEnv interface function table:

Table 4-3b Instance Method Calling Routines
Call<type>Method Routine Name | Index
CallVoidMethod() CallVoidMethodA() CallVoidMethodV() | 61 63 62
CallObjectMethod() CallObjectMethodA() CallObjectMethodV() | 34 36 35
CallBooleanMethod() CallBooleanMethodA() CallBooleanMethodV() | 37 39 38
CallByteMethod() CallByteMethodA() CallByteMethodV() | 40 42 41
CallCharMethod() CallCharMethodA() CallCharMethodV() | 43 45 44
CallShortMethod() CallShortMethodA() CallShortMethodV() | 46 48 47
CallIntMethod() CallIntMethodA() CallIntMethodV() | 49 51 50
CallLongMethod() CallLongMethodA() CallLongMethodV() | 52 54 53
CallFloatMethod() CallFloatMethodA() CallFloatMethodV() | 55 57 56
CallDoubleMethod() CallDoubleMethodA() CallDoubleMethodV() | 58 60 59

PARAMETERS:

env: the JNI interface pointer.

obj: a Java object.

methodID: a method ID.

Additional Parameter for Call<type>Method Routines:

arguments to the Java method.

Additional Parameter for Call<type>MethodA Routines:

args: an array of arguments.

Additional Parameter for Call<type>MethodV Routines:

args: a va_list of arguments.

RETURNS:

Returns the result of calling the Java method.

THROWS:

Exceptions raised during the execution of the Java method.

CallNonvirtual<type>Method Routines
CallNonvirtual<type>MethodA Routines
CallNonvirtual<type>MethodV Routines

NativeType CallNonvirtual<type>Method(JNIEnv *env, jobject obj,
jclass clazz, jmethodID methodID, ...);

NativeType CallNonvirtual<type>MethodA(JNIEnv *env, jobject obj,
jclass clazz, jmethodID methodID, const jvalue *args);

NativeType CallNonvirtual<type>MethodV(JNIEnv *env, jobject obj,
jclass clazz, jmethodID methodID, va_list args);

These families of operations invoke an instance (nonstatic) method on a Java object, according to the specified class and method ID. The methodID argument must be obtained by calling GetMethodID() on the class clazz.

The CallNonvirtual<type>Method families of routines and the Call<type>Method families of routines are different. Call<type>Method routines invoke the method based on the class of the object, while CallNonvirtual<type>Method routines invoke the method based on the class, designated by the clazz parameter, from which the method ID is obtained. The method ID must be obtained from the real class of the object or from one of its superclasses.

CallNonvirtual<type>Method Routines

Programmers place all arguments that are to be passed to the method immediately following the methodID argument. The CallNonvirtual<type>Method routine accepts these arguments and passes them to the Java method that the programmer wishes to invoke.

CallNonvirtual<type>MethodA Routines

Programmers place all arguments to the method in an args array of jvalues that immediately follows the methodID argument. The CallNonvirtual<type>MethodA routine accepts the arguments in this array, and, in turn, passes them to the Java method that the programmer wishes to invoke.

CallNonvirtual<type>MethodV Routines

Programmers place all arguments to the method in an args argument of type va_list that immediately follows the methodID argument. The CallNonvirtualMethodV routine accepts the arguments, and, in turn, passes them to the Java method that the programmer wishes to invoke.

The following table describes each of the method calling routines according to their result type. You should replace type in CallNonvirtual<type>Method with the Java type of the method, or use one of the actual method calling routine names from the table, and replace NativeType with the corresponding native type for that routine.

Table 4-4a CallNonvirtual<type>Method Routines
CallNonvirtual<type>Method Routine Name | Native Type
CallNonvirtualVoidMethod() CallNonvirtualVoidMethodA() CallNonvirtualVoidMethodV() | void
CallNonvirtualObjectMethod() CallNonvirtualObjectMethodA() CallNonvirtualObjectMethodV() | jobject
CallNonvirtualBooleanMethod() CallNonvirtualBooleanMethodA() CallNonvirtualBooleanMethodV() | jboolean
CallNonvirtualByteMethod() CallNonvirtualByteMethodA() CallNonvirtualByteMethodV() | jbyte
CallNonvirtualCharMethod() CallNonvirtualCharMethodA() CallNonvirtualCharMethodV() | jchar
CallNonvirtualShortMethod() CallNonvirtualShortMethodA() CallNonvirtualShortMethodV() | jshort
CallNonvirtualIntMethod() CallNonvirtualIntMethodA() CallNonvirtualIntMethodV() | jint
CallNonvirtualLongMethod() CallNonvirtualLongMethodA() CallNonvirtualLongMethodV() | jlong
CallNonvirtualFloatMethod() CallNonvirtualFloatMethodA() CallNonvirtualFloatMethodV() | jfloat
CallNonvirtualDoubleMethod() CallNonvirtualDoubleMethodA() CallNonvirtualDoubleMethodV() | jdouble

LINKAGE:

Indices in the JNIEnv interface function table.

Table 4-4b CallNonvirtual<type>Method Routines
CallNonvirtual<type>Method Routine Name | Index
CallNonvirtualVoidMethod() CallNonvirtualVoidMethodA() CallNonvirtualVoidMethodV() | 91 93 92
CallNonvirtualObjectMethod() CallNonvirtualObjectMethodA() CallNonvirtualObjectMethodV() | 64 66 65
CallNonvirtualBooleanMethod() CallNonvirtualBooleanMethodA() CallNonvirtualBooleanMethodV() | 67 69 68
CallNonvirtualByteMethod() CallNonvirtualByteMethodA() CallNonvirtualByteMethodV() | 70 72 71
CallNonvirtualCharMethod() CallNonvirtualCharMethodA() CallNonvirtualCharMethodV() | 73 75 74
CallNonvirtualShortMethod() CallNonvirtualShortMethodA() CallNonvirtualShortMethodV() | 76 78 77
CallNonvirtualIntMethod() CallNonvirtualIntMethodA() CallNonvirtualIntMethodV() | 79 81 80
CallNonvirtualLongMethod() CallNonvirtualLongMethodA() CallNonvirtualLongMethodV() | 82 84 83
CallNonvirtualFloatMethod() CallNonvirtualFloatMethodA() CallNonvirtualFloatMethodV() | 85 87 86
CallNonvirtualDoubleMethod() CallNonvirtualDoubleMethodA() CallNonvirtualDoubleMethodV() | 88 90 89

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class.

obj: a Java object.

methodID: a method ID.

Additional Parameter for CallNonvirtual<type>Method Routines:

arguments to the Java method.

Additional Parameter for CallNonvirtual<type>MethodA Routines:

args: an array of arguments.

Additional Parameter for CallNonvirtual<type>MethodV Routines:

args: a va_list of arguments.

RETURNS:

Returns the result of calling the Java method.

THROWS:

Exceptions raised during the execution of the Java method.

Accessing Static Fields

GetStaticFieldID

jfieldID GetStaticFieldID(JNIEnv *env, jclass clazz,
const char *name, const char *sig);

Returns the field ID for a static field of a class. The field is specified by its name and signature. The GetStatic<type>Field and SetStatic<type>Field families of accessor functions use field IDs to retrieve static fields.

GetStaticFieldID() causes an uninitialized class to be initialized.

LINKAGE:

Index 144 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

name: the static field name in a 0-terminated modified UTF-8 string.

sig: the field signature in a 0-terminated modified UTF-8 string.

RETURNS:

Returns a field ID, or NULL if the specified static field cannot be found.

THROWS:

NoSuchFieldError: if the specified static field cannot be found.

ExceptionInInitializerError: if the class initializer fails due to an exception.

OutOfMemoryError: if the system runs out of memory.

GetStatic<type>Field Routines

NativeType GetStatic<type>Field(JNIEnv *env, jclass clazz,
jfieldID fieldID);

This family of accessor routines returns the value of a static field of an object. The field to access is specified by a field ID, which is obtained by calling GetStaticFieldID().

The following table describes the family of get routine names and result types. You should replace type in GetStatic<type>Field with the Java type of the field, or one of the actual static field accessor routine names from the table, and replace NativeType with the corresponding native type for that routine.

Table 4-5a GetStatic<type>Field Family of Accessor Routines
GetStatic<type>Field Routine Name | Native Type
GetStaticObjectField() | jobject
GetStaticBooleanField() | jboolean
GetStaticByteField() | jbyte
GetStaticCharField() | jchar
GetStaticShortField() | jshort
GetStaticIntField() | jint
GetStaticLongField() | jlong
GetStaticFloatField() | jfloat
GetStaticDoubleField() | jdouble

LINKAGE:

Indices in the JNIEnv interface function table.

Table 4-5b GetStatic<type>Field Family of Accessor Routines
GetStatic<type>Field Routine Name | Index
GetStaticObjectField() | 145
GetStaticBooleanField() | 146
GetStaticByteField() | 147
GetStaticCharField() | 148
GetStaticShortField() | 149
GetStaticIntField() | 150
GetStaticLongField() | 151
GetStaticFloatField() | 152
GetStaticDoubleField() | 153

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

fieldID: a static field ID.

RETURNS:

Returns the content of the static field.

SetStatic<type>Field Routines

void SetStatic<type>Field(JNIEnv *env, jclass clazz,
jfieldID fieldID, NativeType value);

This family of accessor routines sets the value of a static field of an object. The field to access is specified by a field ID, which is obtained by calling GetStaticFieldID().

The following table describes the set routine name and value types. You should replace type in SetStatic<type>Field with the Java type of the field, or one of the actual set static field routine names from the table, and replace NativeType with the corresponding native type for that routine.

Table 4-6a SetStatic<type>Field Family of Accessor Routines
SetStatic<type>Field Routine Name | NativeType
SetStaticObjectField() | jobject
SetStaticBooleanField() | jboolean
SetStaticByteField() | jbyte
SetStaticCharField() | jchar
SetStaticShortField() | jshort
SetStaticIntField() | jint
SetStaticLongField() | jlong
SetStaticFloatField() | jfloat
SetStaticDoubleField() | jdouble

LINKAGE:

Indices in the JNIEnv interface function table.

Table 4-6b SetStatic<type>Field Family of Accessor Routines
SetStatic<type>Field Routine Name | Index
SetStaticObjectField() | 154
SetStaticBooleanField() | 155
SetStaticByteField() | 156
SetStaticCharField() | 157
SetStaticShortField() | 158
SetStaticIntField() | 159
SetStaticLongField() | 160
SetStaticFloatField() | 161
SetStaticDoubleField() | 162

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

fieldID: a static field ID.

value: the new value of the field.

Calling Static Methods

GetStaticMethodID

jmethodID GetStaticMethodID(JNIEnv *env, jclass clazz,
const char *name, const char *sig);

Returns the method ID for a static method of a class. The method is specified by its name and signature.

GetStaticMethodID() causes an uninitialized class to be initialized.

LINKAGE:

Index 113 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

name: the static method name in a 0-terminated modified UTF-8 string.

sig: the method signature in a 0-terminated modified UTF-8 string.

RETURNS:

Returns a method ID, or NULL if the operation fails.

THROWS:

NoSuchMethodError: if the specified static method cannot be found.

ExceptionInInitializerError: if the class initializer fails due to an exception.

OutOfMemoryError: if the system runs out of memory.

CallStatic<type>Method Routines
CallStatic<type>MethodA Routines
CallStatic<type>MethodV Routines

NativeType CallStatic<type>Method(JNIEnv *env, jclass clazz,
jmethodID methodID, ...);

NativeType CallStatic<type>MethodA(JNIEnv *env, jclass clazz,
jmethodID methodID, jvalue *args);

NativeType CallStatic<type>MethodV(JNIEnv *env, jclass clazz,
jmethodID methodID, va_list args);

This family of operations invokes a static method on a Java object, according to the specified method ID. The methodID argument must be obtained by calling GetStaticMethodID().

The method ID must be derived from clazz, not from one of its superclasses.

CallStatic<type>Method Routines

Programmers should place all arguments that are to be passed to the method immediately following the methodID argument. The CallStatic<type>Method routine accepts these arguments and passes them to the Java method that the programmer wishes to invoke.

CallStatic<type>MethodA Routines

Programmers should place all arguments to the method in an args array of jvalues that immediately follows the methodID argument. The CallStaticMethodA routine accepts the arguments in this array, and, in turn, passes them to the Java method that the programmer wishes to invoke.

CallStatic<type>MethodV Routines

Programmers should place all arguments to the method in an args argument of type va_list that immediately follows the methodID argument. The CallStaticMethodV routine accepts the arguments, and, in turn, passes them to the Java method that the programmer wishes to invoke.

The following table describes each of the method calling routines according to their result types. You should replace type in CallStatic<type>Method with the Java type of the method, or one of the actual method calling routine names from the table, and replace NativeType with the corresponding native type for that routine.

Table 4-7a CallStatic<type>Method Calling Routines
CallStatic<type>Method Routine Name | Native Type
CallStaticVoidMethod() CallStaticVoidMethodA() CallStaticVoidMethodV() | void
CallStaticObjectMethod() CallStaticObjectMethodA() CallStaticObjectMethodV() | jobject
CallStaticBooleanMethod() CallStaticBooleanMethodA() CallStaticBooleanMethodV() | jboolean
CallStaticByteMethod() CallStaticByteMethodA() CallStaticByteMethodV() | jbyte
CallStaticCharMethod() CallStaticCharMethodA() CallStaticCharMethodV() | jchar
CallStaticShortMethod() CallStaticShortMethodA() CallStaticShortMethodV() | jshort
CallStaticIntMethod() CallStaticIntMethodA() CallStaticIntMethodV() | jint
CallStaticLongMethod() CallStaticLongMethodA() CallStaticLongMethodV() | jlong
CallStaticFloatMethod() CallStaticFloatMethodA() CallStaticFloatMethodV() | jfloat
CallStaticDoubleMethod() CallStaticDoubleMethodA() CallStaticDoubleMethodV() | jdouble

LINKAGE:

Indices in the JNIEnv interface function table.

Table 4-7b CallStatic<type>Method Calling Routines
CallStatic<type>Method Routine Name | Index
CallStaticVoidMethod() CallStaticVoidMethodA() CallStaticVoidMethodV() | 141 143 142
CallStaticObjectMethod() CallStaticObjectMethodA() CallStaticObjectMethodV() | 114 116 115
CallStaticBooleanMethod() CallStaticBooleanMethodA() CallStaticBooleanMethodV() | 117 119 118
CallStaticByteMethod() CallStaticByteMethodA() CallStaticByteMethodV() | 120 122 121
CallStaticCharMethod() CallStaticCharMethodA() CallStaticCharMethodV() | 123 125 124
CallStaticShortMethod() CallStaticShortMethodA() CallStaticShortMethodV() | 126 128 127
CallStaticIntMethod() CallStaticIntMethodA() CallStaticIntMethodV() | 129 131 130
CallStaticLongMethod() CallStaticLongMethodA() CallStaticLongMethodV() | 132 134 133
CallStaticFloatMethod() CallStaticFloatMethodA() CallStaticFloatMethodV() | 135 137 136
CallStaticDoubleMethod() CallStaticDoubleMethodA() CallStaticDoubleMethodV() | 138 140 139

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

methodID: a static method ID.

Additional Parameter for CallStatic<type>Method Routines:

arguments to the static method.

Additional Parameter for CallStatic<type>MethodA Routines:

args: an array of arguments.

Additional Parameter for CallStatic<type>MethodV Routines:

args: a va_list of arguments.

RETURNS:

Returns the result of calling the static Java method.

THROWS:

Exceptions raised during the execution of the Java method.

String Operations

NewString

jstring NewString(JNIEnv *env, const jchar *unicodeChars,
jsize len);

Constructs a new java.lang.String object from an array of Unicode characters.

LINKAGE:

Index 163 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

unicodeChars: pointer to a Unicode string.

len: length of the Unicode string.

RETURNS:

Returns a Java string object, or NULL if the string cannot be constructed.

THROWS:

OutOfMemoryError: if the system runs out of memory.

GetStringLength

jsize GetStringLength(JNIEnv *env, jstring string);

Returns the length (the count of Unicode characters) of a Java string.

LINKAGE:

Index 164 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

string: a Java string object.

RETURNS:

Returns the length of the Java string.

GetStringChars

const jchar * GetStringChars(JNIEnv *env, jstring string,
jboolean *isCopy);

Returns a pointer to the array of Unicode characters of the string. This pointer is valid until ReleaseStringchars() is called.

If isCopy is not NULL, then *isCopy is set to JNI_TRUE if a copy is made; or it is set to JNI_FALSE if no copy is made.

LINKAGE:

Index 165 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

string: a Java string object.

isCopy: a pointer to a boolean.

RETURNS:

Returns a pointer to a Unicode string, or NULL if the operation fails.

ReleaseStringChars

void ReleaseStringChars(JNIEnv *env, jstring string,
const jchar *chars);

Informs the VM that the native code no longer needs access to chars. The chars argument is a pointer obtained from string using GetStringChars().

LINKAGE:

Index 166 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

string: a Java string object.

chars: a pointer to a Unicode string.

NewStringUTF

jstring NewStringUTF(JNIEnv *env, const char *bytes);

Constructs a new java.lang.String object from an array of characters in modified UTF-8 encoding.

LINKAGE:

Index 167 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

bytes: the pointer to a modified UTF-8 string.

RETURNS:

Returns a Java string object, or NULL if the string cannot be constructed.

THROWS:

OutOfMemoryError: if the system runs out of memory.

GetStringUTFLength

jsize GetStringUTFLength(JNIEnv *env, jstring string);

Returns the length in bytes of the modified UTF-8 representation of a string.

LINKAGE:

Index 168 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

string: a Java string object.

RETURNS:

Returns the UTF-8 length of the string.

GetStringUTFChars

const char * GetStringUTFChars(JNIEnv *env, jstring string,
jboolean *isCopy);

Returns a pointer to an array of bytes representing the string in modified UTF-8 encoding. This array is valid until it is released by ReleaseStringUTFChars().

If isCopy is not NULL, then *isCopy is set to JNI_TRUE if a copy is made; or it is set to JNI_FALSE if no copy is made.

LINKAGE:

Index 169 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

string: a Java string object.

isCopy: a pointer to a boolean.

RETURNS:

Returns a pointer to a modified UTF-8 string, or NULL if the operation fails.

ReleaseStringUTFChars

void ReleaseStringUTFChars(JNIEnv *env, jstring string,
const char *utf);

Informs the VM that the native code no longer needs access to utf. The utf argument is a pointer derived from string using GetStringUTFChars().

LINKAGE:

Index 170 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

string: a Java string object.

utf: a pointer to a modified UTF-8 string.

Note

In JDK/JRE 1.1, programmers can get primitive array elements in a user-supplied buffer. As of JDK/JRE 1.2 additional set of functions are provided allowing native code to obtain characters in Unicode (UTF-16) or modified UTF-8 encoding in a user-supplied buffer. See the functions below.

GetStringRegion

void GetStringRegion(JNIEnv *env, jstring str, jsize start, jsize len, jchar *buf);

Copies len number of Unicode characters beginning at offset start to the given buffer buf.

Throws StringIndexOutOfBoundsException on index overflow.

LINKAGE:

Index 220 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

GetStringUTFRegion

< void GetStringUTFRegion(JNIEnv *env, jstring str, jsize start, jsize len, char *buf);

Translates len number of Unicode characters beginning at offset start into modified UTF-8 encoding and place the result in the given buffer buf.

Throws StringIndexOutOfBoundsException on index overflow.

LINKAGE:

Index 221 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

GetStringCritical
ReleaseStringCritical

const jchar * GetStringCritical(JNIEnv *env, jstring string, jboolean *isCopy);
void ReleaseStringCritical(JNIEnv *env, jstring string, const jchar *carray);

The semantics of these two functions are similar to the existing Get/ReleaseStringChars functions. If possible, the VM returns a pointer to string elements; otherwise, a copy is made. However, there are significant restrictions on how these functions can be used. In a code segment enclosed by Get/ReleaseStringCritical calls, the native code must not issue arbitrary JNI calls, or cause the current thread to block.

The restrictions on Get/ReleaseStringCritical are similar to those on Get/ReleasePrimitiveArrayCritical.

LINKAGE (GetStringCritical):

Index 224 in the JNIEnv interface function table.

LINKAGE (ReleaseStingCritical):

Index 225 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

Array Operations

GetArrayLength

jsize GetArrayLength(JNIEnv *env, jarray array);

Returns the number of elements in the array.

LINKAGE:

Index 171 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

array: a Java array object.

RETURNS:

Returns the length of the array.

NewObjectArray

jobjectArray NewObjectArray(JNIEnv *env, jsize length,
jclass elementClass, jobject initialElement);

Constructs a new array holding objects in class elementClass. All elements are initially set to initialElement.

LINKAGE:

Index 172 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

length: array size.

elementClass: array element class.

initialElement: initialization value.

RETURNS:

Returns a Java array object, or NULL if the array cannot be constructed.

THROWS:

OutOfMemoryError: if the system runs out of memory.

GetObjectArrayElement

jobject GetObjectArrayElement(JNIEnv *env,
jobjectArray array, jsize index);

Returns an element of an Object array.

LINKAGE:

Index 173 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

array: a Java array.

index: array index.

RETURNS:

Returns a Java object.

THROWS:

ArrayIndexOutOfBoundsException: if index does not specify a valid index in the array.

SetObjectArrayElement

void SetObjectArrayElement(JNIEnv *env, jobjectArray array,
jsize index, jobject value);

Sets an element of an Object array.

LINKAGE:

Index 174 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

array: a Java array.

index: array index.

value: the new value.

THROWS:

ArrayIndexOutOfBoundsException: if index does not specify a valid index in the array.

ArrayStoreException: if the class of value is not a subclass of the element class of the array.

New<PrimitiveType>Array Routines

ArrayType New<PrimitiveType>Array(JNIEnv *env, jsize length);

A family of operations used to construct a new primitive array object. Table 4-8 describes the specific primitive array constructors. You should replace New<PrimitiveType>Array with one of the actual primitive array constructor routine names from the following table, and replace ArrayType with the corresponding array type for that routine.

Table 4-8a New<PrimitiveType>Array Family of Array Constructors
New<PrimitiveType>Array Routines | Array Type
NewBooleanArray() | jbooleanArray
NewByteArray() | jbyteArray
NewCharArray() | jcharArray
NewShortArray() | jshortArray
NewIntArray() | jintArray
NewLongArray() | jlongArray
NewFloatArray() | jfloatArray
NewDoubleArray() | jdoubleArray

LINKAGE:

Indices in the JNIEnv interface function table.

Table 4-8b New<PrimitiveType>Array Family of Array Constructors
New<PrimitiveType>Array Routines | Index
NewBooleanArray() | 175
NewByteArray() | 176
NewCharArray() | 177
NewShortArray() | 178
NewIntArray() | 179
NewLongArray() | 180
NewFloatArray() | 181
NewDoubleArray() | 182

PARAMETERS:

env: the JNI interface pointer.

length: the array length.

RETURNS:

Returns a Java array, or NULL if the array cannot be constructed.

Get<PrimitiveType>ArrayElements Routines

NativeType *Get<PrimitiveType>ArrayElements(JNIEnv *env,
 ArrayType array, jboolean *isCopy);

A family of functions that returns the body of the primitive array. The result is valid until the corresponding Release<PrimitiveType>ArrayElements() function is called. Since the returned array may be a copy of the Java array, changes made to the returned array will not necessarily be reflected in the original array until Release<PrimitiveType>ArrayElements() is called.

If isCopy is not NULL, then *isCopy is set to JNI_TRUE if a copy is made; or it is set to JNI_FALSE if no copy is made.

The following table describes the specific primitive array element accessors. You should make the following substitutions:

  • Replace Get<PrimitiveType>ArrayElements with one of the actual primitive element accessor routine names from the table.
  • Replace ArrayType with the corresponding array type.
  • Replace NativeType with the corresponding native type for that routine.

Regardless of how boolean arrays are represented in the Java VM, GetBooleanArrayElements() always returns a pointer to jbooleans, with each byte denoting an element (the unpacked representation). All arrays of other types are guaranteed to be contiguous in memory.

Table 4-9a Get<PrimitiveType>ArrayElements Family of Accessor Routines
Get<PrimitiveType>ArrayElements Routines | Array Type | Native Type
GetBooleanArrayElements() | jbooleanArray | jboolean
GetByteArrayElements() | jbyteArray | jbyte
GetCharArrayElements() | jcharArray | jchar
GetShortArrayElements() | jshortArray | jshort
GetIntArrayElements() | jintArray | jint
GetLongArrayElements() | jlongArray | jlong
GetFloatArrayElements() | jfloatArray | jfloat
GetDoubleArrayElements() | jdoubleArray | jdouble

LINKAGE:

Indices in the JNIEnv interface function table.

Table 4-9b Get<PrimitiveType>ArrayElements Family of Accessor Routines
Get<PrimitiveType>ArrayElements Routines | Index
GetBooleanArrayElements() | 183
GetByteArrayElements() | 184
GetCharArrayElements() | 185
GetShortArrayElements() | 186
GetIntArrayElements() | 187
GetLongArrayElements() | 188
GetFloatArrayElements() | 189
GetDoubleArrayElements() | 190

PARAMETERS:

env: the JNI interface pointer.

array: a Java string object.

isCopy: a pointer to a boolean.

RETURNS:

Returns a pointer to the array elements, or NULL if the operation fails.

Release<PrimitiveType>ArrayElements Routines

void Release<PrimitiveType>ArrayElements(JNIEnv *env,
 ArrayType array, NativeType *elems, jint mode);

A family of functions that informs the VM that the native code no longer needs access to elems. The elems argument is a pointer derived from array using the corresponding Get<PrimitiveType>ArrayElements() function. If necessary, this function copies back all changes made to elems to the original array.

The mode argument provides information on how the array buffer should be released. mode has no effect if elems is not a copy of the elements in array. Otherwise, mode has the following impact, as shown in the following table:

Table 4-10 Primitive Array Release Modes
mode | actions
0 | copy back the content and free the elems buffer
JNI_COMMIT | copy back the content but do not free the elems buffer
JNI_ABORT | free the buffer without copying back the possible changes

In most cases, programmers pass “0” to the mode argument to ensure consistent behavior for both pinned and copied arrays. The other options give the programmer more control over memory management and should be used with extreme care.

The next table describes the specific routines that comprise the family of primitive array disposers. You should make the following substitutions:

  • Replace Release<PrimitiveType>ArrayElements with one of the actual primitive array disposer routine names from Table 4-11.
  • Replace ArrayType with the corresponding array type.
  • Replace NativeType with the corresponding native type for that routine.

Table 4-11a Release<PrimitiveType>ArrayElements Family of Array Routines
Release<PrimitiveType>ArrayElements Routines | Array Type | Native Type
ReleaseBooleanArrayElements() | jbooleanArray | jboolean
ReleaseByteArrayElements() | jbyteArray | jbyte
ReleaseCharArrayElements() | jcharArray | jchar
ReleaseShortArrayElements() | jshortArray | jshort
ReleaseIntArrayElements() | jintArray | jint
ReleaseLongArrayElements() | jlongArray | jlong
ReleaseFloatArrayElements() | jfloatArray | jfloat
ReleaseDoubleArrayElements() | jdoubleArray | jdouble

LINKAGE:

Indices in the JNIEnv interface function table.

Table 4-11b Release<PrimitiveType>ArrayElements Family of Array Routines
Release<PrimitiveType>ArrayElements Routines | Index
ReleaseBooleanArrayElements() | 191
ReleaseByteArrayElements() | 192
ReleaseCharArrayElements() | 193
ReleaseShortArrayElements() | 194
ReleaseIntArrayElements() | 195
ReleaseLongArrayElements() | 196
ReleaseFloatArrayElements() | 197
ReleaseDoubleArrayElements() | 198

PARAMETERS:

env: the JNI interface pointer.

array: a Java array object.

elems: a pointer to array elements.

mode: the release mode.

Get<PrimitiveType>ArrayRegion Routines

void Get<PrimitiveType>ArrayRegion(JNIEnv *env, ArrayType array,
jsize start, jsize len, NativeType *buf);

A family of functions that copies a region of a primitive array into a buffer.

The following table describes the specific primitive array element accessors. You should do the following substitutions:

  • Replace Get<PrimitiveType>ArrayRegion with one of the actual primitive element accessor routine names from Table 4-12.
  • Replace ArrayType with the corresponding array type.
  • Replace NativeType with the corresponding native type for that routine.

Table 4-12a Get<PrimitiveType>ArrayRegion Family of Array Accessor Routines
Get<PrimitiveType>ArrayRegion Routine | Array Type | Native Type
GetBooleanArrayRegion() | jbooleanArray | jboolean
GetByteArrayRegion() | jbyteArray | jbyte
GetCharArrayRegion() | jcharArray | jchar
GetShortArrayRegion() | jshortArray | jhort
GetIntArrayRegion() | jintArray | jint
GetLongArrayRegion() | jlongArray | jlong
GetFloatArrayRegion() | jfloatArray | jloat
GetDoubleArrayRegion() | jdoubleArray | jdouble

LINKAGE:

Indices in the JNIEnv interface function table.

Table 4-12b Get<PrimitiveType>ArrayRegion Family of Array Accessor Routines
Get<PrimitiveType>ArrayRegion Routine | Index
GetBooleanArrayRegion() | 199
GetByteArrayRegion() | 200
GetCharArrayRegion() | 201
GetShortArrayRegion() | 202
GetIntArrayRegion() | 203
GetLongArrayRegion() | 204
GetFloatArrayRegion() | 205
GetDoubleArrayRegion() | 206

PARAMETERS:

env: the JNI interface pointer.

array: a Java array.

start: the starting index.

len: the number of elements to be copied.

buf: the destination buffer.

THROWS:

ArrayIndexOutOfBoundsException: if one of the indexes in the region is not valid.

Set<PrimitiveType>ArrayRegion Routines

void Set<PrimitiveType>ArrayRegion(JNIEnv *env, ArrayType array,
jsize start, jsize len, const NativeType *buf);

A family of functions that copies back a region of a primitive array from a buffer.

The following table describes the specific primitive array element accessors. You should make the following replacements:

  • Replace Set<PrimitiveType>ArrayRegion with one of the actual primitive element accessor routine names from the table.
  • Replace ArrayType with the corresponding array type.
  • Replace NativeType with the corresponding native type for that routine.
    Table 4-13a Set<PrimitiveType>ArrayRegion Family of Array Accessor Routines
    Set<PrimitiveType>ArrayRegion Routine
    Array Type
    Native Type
    SetBooleanArrayRegion()
    jbooleanArray
    jboolean
    SetByteArrayRegion()
    jbyteArray
    jbyte
    SetCharArrayRegion()
    jcharArray
    jchar
    SetShortArrayRegion()
    jshortArray
    jshort
    SetIntArrayRegion()
    jintArray
    jint
    SetLongArrayRegion()
    jlongArray
    jlong
    SetFloatArrayRegion()
    jfloatArray
    jfloat
    SetDoubleArrayRegion()
    jdoubleArray
    jdouble

LINKAGE:

Indices in the JNIEnv interface function table.

Table 4-13b Set<PrimitiveType>ArrayRegion Family of Array Accessor Routines
Set<PrimitiveType>ArrayRegion Routine | Index
SetBooleanArrayRegion() | 207
SetByteArrayRegion() | 208
SetCharArrayRegion() | 209
SetShortArrayRegion() | 210
SetIntArrayRegion() | 211
SetLongArrayRegion() | 212
SetFloatArrayRegion() | 213
SetDoubleArrayRegion() | 214

PARAMETERS:

env: the JNI interface pointer.

array: a Java array.

start: the starting index.

len: the number of elements to be copied.

buf: the source buffer.

THROWS:

ArrayIndexOutOfBoundsException: if one of the indexes in the region is not valid.

Note

As of JDK/JRE 1.1, programmers can use Get/Release<primitivetype>ArrayElements functions to obtain a pointer to primitive array elements. If the VM supports pinning, the pointer to the original data is returned; otherwise, a copy is made.

New functions introduced as of JDK/JRE 1.3 allow native code to obtain a direct pointer to array elements even if the VM does not support pinning.

GetPrimitiveArrayCritical
ReleasePrimitiveArrayCritical

void * GetPrimitiveArrayCritical(JNIEnv *env, jarray array, jboolean *isCopy);
void ReleasePrimitiveArrayCritical(JNIEnv *env, jarray array, void *carray, jint mode);

The semantics of these two functions are very similar to the existing Get/Release<primitivetype>ArrayElements functions. If possible, the VM returns a pointer to the primitive array; otherwise, a copy is made. However, there are significant restrictions on how these functions can be used.

After calling GetPrimitiveArrayCritical, the native code should not run for an extended period of time before it calls ReleasePrimitiveArrayCritical. We must treat the code inside this pair of functions as running in a "critical region." Inside a critical region, native code must not call other JNI functions, or any system call that may cause the current thread to block and wait for another Java thread. (For example, the current thread must not call read on a stream being written by another Java thread.)

These restrictions make it more likely that the native code will obtain an uncopied version of the array, even if the VM does not support pinning. For example, a VM may temporarily disable garbage collection when the native code is holding a pointer to an array obtained via GetPrimitiveArrayCritical.

Multiple pairs of GetPrimtiveArrayCritical and ReleasePrimitiveArrayCritical may be nested. For example:

  jint len = (*env)->GetArrayLength(env, arr1);
  jbyte *a1 = (*env)->GetPrimitiveArrayCritical(env, arr1, 0);
  jbyte *a2 = (*env)->GetPrimitiveArrayCritical(env, arr2, 0);
  /* We need to check in case the VM tried to make a copy. */
  if (a1 == NULL || a2 == NULL) {
    ... /* out of memory exception thrown */
  }
  memcpy(a1, a2, len);
  (*env)->ReleasePrimitiveArrayCritical(env, arr2, a2, 0);
  (*env)->ReleasePrimitiveArrayCritical(env, arr1, a1, 0);

Note that GetPrimitiveArrayCritical might still make a copy of the array if the VM internally represents arrays in a different format. Therefore we need to check its return value against NULL for possible out of memory situations.

LINKAGE (GetPrimitiveArrayCritical):

Linkage Index 222 in the JNIEnv interface function table.

LINKAGE (ReleasePrimitiveArrayCritical):

Linkage Index 223 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

Registering Native Methods

RegisterNatives

jint RegisterNatives(JNIEnv *env, jclass clazz,
const JNINativeMethod *methods, jint nMethods);

Registers native methods with the class specified by the clazz argument. The methods parameter specifies an array of JNINativeMethod structures that contain the names, signatures, and function pointers of the native methods. The name and signature fields of the JNINativeMethod structure are pointers to modified UTF-8 strings. The nMethods parameter specifies the number of native methods in the array. The JNINativeMethod structure is defined as follows:

typedef struct {

    char *name;

    char *signature;

    void *fnPtr;

} JNINativeMethod;

The function pointers nominally must have the following signature:

ReturnType (*fnPtr)(JNIEnv *env, jobject objectOrClass, ...);

LINKAGE:

Index 215 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

methods: the native methods in the class.

nMethods: the number of native methods in the class.

RETURNS:

Returns “0” on success; returns a negative value on failure.

THROWS:

NoSuchMethodError: if a specified method cannot be found or if the method is not native.

UnregisterNatives

jint UnregisterNatives(JNIEnv *env, jclass clazz);

Unregisters native methods of a class. The class goes back to the state before it was linked or registered with its native method functions.

This function should not be used in normal native code. Instead, it provides special programs a way to reload and relink native libraries.

LINKAGE:

Index 216 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

clazz: a Java class object.

RETURNS:

Returns “0” on success; returns a negative value on failure.

Monitor Operations

MonitorEnter

jint MonitorEnter(JNIEnv *env, jobject obj);

Enters the monitor associated with the underlying Java object referred to by obj.

Enters the monitor associated with the object referred to by obj. The obj reference must not be NULL.

Each Java object has a monitor associated with it. If the current thread already owns the monitor associated with obj, it increments a counter in the monitor indicating the number of times this thread has entered the monitor. If the monitor associated with obj is not owned by any thread, the current thread becomes the owner of the monitor, setting the entry count of this monitor to 1. If another thread already owns the monitor associated with obj, the current thread waits until the monitor is released, then tries again to gain ownership.

A monitor entered through a MonitorEnter JNI function call cannot be exited using the monitorexit Java virtual machine instruction or a synchronized method return. A MonitorEnter JNI function call and a monitorenter Java virtual machine instruction may race to enter the monitor associated with the same object.

To avoid deadlocks, a monitor entered through a MonitorEnter JNI function call must be exited using the MonitorExit JNI call, unless the DetachCurrentThread call is used to implicitly release JNI monitors.

LINKAGE:

Index 217 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

obj: a normal Java object or class object.

RETURNS:

Returns “0” on success; returns a negative value on failure.

MonitorExit

jint MonitorExit(JNIEnv *env, jobject obj);

The current thread must be the owner of the monitor associated with the underlying Java object referred to by obj. The thread decrements the counter indicating the number of times it has entered this monitor. If the value of the counter becomes zero, the current thread releases the monitor.

Native code must not use MonitorExit to exit a monitor entered through a synchronized method or a monitorenter Java virtual machine instruction.

LINKAGE:

Index 218 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

obj: a normal Java object or class object.

RETURNS:

Returns “0” on success; returns a negative value on failure.

EXCEPTIONS:

IllegalMonitorStateException: if the current thread does not own the monitor.

NIO Support

The NIO-related entry points allow native code to access java.nio direct buffers. The contents of a direct buffer can, potentially, reside in native memory outside of the ordinary garbage-collected heap. For information about direct buffers, please see New I/O APIs and the specification of the java.nio.ByteBuffer class.

Three new functions introduced in JDK/JRE 1.4 allow JNI code to create, examine, and manipulate direct buffers:
  • NewDirectByteBuffer
  • GetDirectBufferAddress
  • GetDirectBufferCapacity

Every implementation of the Java virtual machine must support these functions, but not every implementation is required to support JNI access to direct buffers. If a JVM does not support such access then the NewDirectByteBuffer and GetDirectBufferAddress functions must always return NULL, and the GetDirectBufferCapacity function must always return -1. If a JVM does support such access then these three functions must be implemented to return the appropriate values.

NewDirectByteBuffer

jobject NewDirectByteBuffer(JNIEnv* env, void* address, jlong capacity);

Allocates and returns a direct java.nio.ByteBuffer referring to the block of memory starting at the memory address address and extending capacity bytes.

Native code that calls this function and returns the resulting byte-buffer object to Java-level code should ensure that the buffer refers to a valid region of memory that is accessible for reading and, if appropriate, writing. An attempt to access an invalid memory location from Java code will either return an arbitrary value, have no visible effect, or cause an unspecified exception to be thrown.

LINKAGE:

Index 229 in the JNIEnv interface function table.

PARAMETERS:

env: the JNIEnv interface pointer

address: the starting address of the memory region (must not be NULL)

capacity: the size in bytes of the memory region (must be positive)

RETURNS:

Returns a local reference to the newly-instantiated java.nio.ByteBuffer object. Returns NULL if an exception occurs, or if JNI access to direct buffers is not supported by this virtual machine.

EXCEPTIONS:

OutOfMemoryError: if allocation of the ByteBuffer object fails

SINCE:

JDK/JRE 1.4

GetDirectBufferAddress

void* GetDirectBufferAddress(JNIEnv* env, jobject buf);

Fetches and returns the starting address of the memory region referenced by the given direct java.nio.Buffer.

This function allows native code to access the same memory region that is accessible to Java code via the buffer object.

LINKAGE:

Index 230 in the JNIEnv interface function table.

PARAMETERS:

env: the JNIEnv interface pointer

buf: a direct java.nio.Buffer object (must not be NULL)

RETURNS:

Returns the starting address of the memory region referenced by the buffer. Returns NULL if the memory region is undefined, if the given object is not a direct java.nio.Buffer, or if JNI access to direct buffers is not supported by this virtual machine.

SINCE:

JDK/JRE 1.4

GetDirectBufferCapacity

jlong GetDirectBufferCapacity(JNIEnv* env, jobject buf);

Fetches and returns the capacity of the memory region referenced by the given direct java.nio.Buffer. The capacity is the number of elements that the memory region contains.

LINKAGE:

Index 231 in the JNIEnv interface function table.

PARAMETERS:

env: the JNIEnv interface pointer

buf: a direct java.nio.Buffer object (must not be NULL)

RETURNS:

Returns the capacity of the memory region associated with the buffer. Returns -1 if the given object is not a direct java.nio.Buffer, if the object is an unaligned view buffer and the processor architecture does not support unaligned access, or if JNI access to direct buffers is not supported by this virtual machine.

SINCE:

JDK/JRE 1.4

Reflection Support

Programmers can use the JNI to call Java methods or access Java fields if they know the name and type of the methods or fields. The Java Core Reflection API allows programmers to introspect Java classes at runtime. JNI provides a set of conversion functions between field and method IDs used in the JNI to field and method objects used in the Java Core Reflection API.

FromReflectedMethod

jmethodID FromReflectedMethod(JNIEnv *env, jobject method);

Converts a java.lang.reflect.Method or java.lang.reflect.Constructor object to a method ID.

LINKAGE:

Index 7 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

FromReflectedField

jfieldID FromReflectedField(JNIEnv *env, jobject field);

Converts a java.lang.reflect.Field to a field ID.

LINKAGE:

Index 8 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

ToReflectedMethod

jobject ToReflectedMethod(JNIEnv *env, jclass cls,
   jmethodID methodID, jboolean isStatic);

Converts a method ID derived from cls to a java.lang.reflect.Method or java.lang.reflect.Constructor object. isStatic must be set to JNI_TRUE if the method ID refers to a static field, and JNI_FALSE otherwise.

Throws OutOfMemoryError and returns 0 if fails.

LINKAGE:

Index 9 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

ToReflectedField

jobject ToReflectedField(JNIEnv *env, jclass cls,
   jfieldID fieldID, jboolean isStatic);

Converts a field ID derived from cls to a java.lang.reflect.Field object. isStatic must be set to JNI_TRUE if fieldID refers to a static field, and JNI_FALSE otherwise.

Throws OutOfMemoryError and returns 0 if fails.

LINKAGE:

Index 12 in the JNIEnv interface function table.

SINCE:

JDK/JRE 1.2

Java VM Interface

GetJavaVM

jint GetJavaVM(JNIEnv *env, JavaVM **vm);

Returns the Java VM interface (used in the Invocation API) associated with the current thread. The result is placed at the location pointed to by the second argument, vm.

LINKAGE:

Index 219 in the JNIEnv interface function table.

PARAMETERS:

env: the JNI interface pointer.

vm: a pointer to where the result should be placed.

RETURNS:

Returns “0” on success; returns a negative value on failure.

Contents | Previous | Next
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL: Concepts

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Concepts

  • Distributed Application Concepts
  • CORBA and the Java Platform
  • Glossary
Home Concepts Programming Reference Tutorial
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Garbage-First Collector

What is the Garbage-First Collector?

Garbage-First (G1) Collector is a server-style garbage collector, targeted for multi-processors with large memories, that meets a soft real-time goal with high probability, while achieving high throughput. G1 is the long term replacement of the Concurrent Mark-Sweep Collector (CMS). Whole-heap operations, such as global marking, are performed concurrently with the application threads, to prevent interruptions proportional to heap or live-data size. Concurrent marking provides both collection "completeness" and identifies regions ripe for reclamation via compacting evacuation. This evacuation is performed in parallel on multi-processors, to decrease pause times and increase throughput.

The G1 collector achieves these goals through several techniques. The heap is partitioned into a set of equal-sized heap regions, each a contiguous range of virtual memory. G1 compacts as it proceeds. It copies objects from one area of the heap to the other. Thus, it will not encounter fragmentation issues that CMS might encounter. There will always be areas of contiguous free space from which to allocate, allowing G1 to have consistent pauses over time. G1 uses a pause prediction model to meet a user-defined pause time target. It achieves smoother pause times than CMS at comparable throughput.

After G1 performs a global marking phase determining the liveness of objects throughout the heap, it will immediately know where in the heap there are regions that are mostly empty. It will tackle those regions first, potentially making a lot of space available. This way, the garbage collector will obtain more breathing space, decreasing the probability of a full GC. This is also why the garbage collector is called Garbage-First. As its name suggests, G1 concentrates its collection and compaction activity first on the areas of the heap that are likely to be full of reclaimable objects, thus improving its efficiency.

While most real-time collectors work at the highly granular level of individual objects, G1 collects at the region level. If any region contains no live objects it is immediately reclaimed. The user can specify a goal for the pauses and G1 will do an estimate of how many regions can be collected in that time based on previous collections. So, the collector has a reasonably accurate model of the cost of collecting the regions, and therefore "the collector can choose a set of regions that can be collected within a given pause time limit with high probability." In other words, G1 is not a hard real-time collector - it meets the soft real-time goal with high probability but not absolute certainty. G1 attempts to yield higher throughput in return for the softer, but still moderately stringent, real-time constraints. This is a good fit for large-scale server applications which often have large amounts of live heap data and considerable thread-level parallelism. G1 also provides some finer control, allowing a user to specify a fraction of time during a period of execution to be spent on garbage collection. For example, for every 250ms of execution spend no more than 50ms on garbage collection.

G1 is planned to replace CMS in the Hotspot JVM. There are two major differences between CMS and G1. The first is that G1 is a compacting collector. G1 compacts sufficiently to completely avoid the use of fine-grain free lists for allocation, which considerably simplifies parts of the collector and mostly eliminates potential fragmentation issues. As well as compacting, G1 offers more predictable garbage collection pauses than the CMS collector and allows users to set their desired pause targets.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.management.GarbageCollectorMXBean (Monitoring and Management Interface for the Java Platform b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Monitoring and Management Interface for the Java Platform
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.management.GarbageCollectorMXBean

No usage of com.sun.management.GarbageCollectorMXBean
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Monitoring and Management Interface for the Java Platform
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2003, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Garbage Collection Ergonomics

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Garbage Collector Ergonomics

The following changes take effect with J2SE 5.0.

Garbage Collector of Server VM Changed to Parallel Garbage Collector

On server-class machines running the server VM, the garbage collector (GC) has changed from the previous serial collector (-XX:+UseSerialGC) to a parallel collector (-XX:+UseParallelGC). You can override this default by using the -XX:+UseSerialGC command-line option to the java command.

Initial Heap Size and Maximum Heap Size Changed for Parallel Garbage Collector

On server-class machines running either VM (client or server) with the parallel garbage collector (-XX:+UseParallelGC) the initial heap size and maximum heap size have changed as follows.

initial heap size

Larger of 1/64th of the machine's physical memory on the machine or some reasonable minimum. Before J2SE 5.0, the default initial heap size was a reasonable minimum, which varies by platform. You can override this default using the -Xms command-line option.

maximum heap size

Smaller of 1/4th of the physical memory or 1GB. Before J2SE 5.0, the default maximum heap size was 64MB. You can override this default using the -Xmx command-line option.

Note: The boundaries and fractions given for the heap size are correct for J2SE 5.0. They are likely to be different in subsequent releases as computers get more powerful.

Parallel Garbage Collector Throws Exception if Excessive Amount of Time Spent Collecting Small Amount of Heap

The parallel garbage collector (UseParallelGC) throws an out-of-memory exception if an excessive amount of time is being spent collecting a small amount of the heap. To avoid this exception, you can increase the size of the heap. You can also set the parameters -XX:GCTimeLimit=time-limit and -XX:GCHeapFreeLimit=space-limit where:

time-limit:

The upper limit on the amount of time spent in garbage collection in percent of total time (default is 98).

space-limit:

The lower limit on the amount of space freed during a garbage collection in percent of the maximum heap (default is 2).

Implementation of -XX:+UseAdaptiveSizePolicy Used by Parallel Garbage Collector Changed

The implementation of -XX:+UseAdaptiveSizePolicy used by default with the -XX:+UseParallelGC garbage collector has changed to consider three goals:
  • a desired maximum GC pause goal
  • a desired application throughput goal
  • minimum footprint

The implementation checks (in this order):

  1. If the GC pause time is greater than the pause time goal then reduce the generations sizes to better attain the goal.
  2. If the pause time goal is being met then consider the application's throughput goal. If the application's throughput goal is not being met, then increase the sizes of the generations to better attain the goal.
  3. If both the pause time goal and the throughput goal are being met, then the size of the generations are decreased to reduce footprint.

Flags

-XX:MaxGCPauseMillis=nnn
A hint to the virtual machine that pause times of nnn milliseconds or less are desired. The VM will adjust the java heap size and other GC-related parameters in an attempt to keep GC-induced pauses shorter than nnn milliseconds. Note that this may cause the VM to reduce overall throughput, and in some cases the VM will not be able to meet the desired pause time goal.

By default there is no pause time goal. There are definite limitations on how well a pause time goal can be met. The pause time for a GC depends on the amount of live data in the heap. The minor and major collections depend in different ways on the amount of live data. This parameter should be used with caution. A value that is too small will cause the system to spend an excessive amount of time doing garbage collection.

-XX:GCTimeRatio=nnn
A hint to the virtual machine that it's desirable that not more than 1 / (1 + nnn) of the application execution time be spent in the collector.

For example -XX:GCTimeRatio=19 sets a goal of 5% of the total time for GC and throughput goal of 95%. That is, the application should get 19 times as much time as the collector.

By default the value is 99, meaning the application should get at least 99 times as much time as the collector. That is, the collector should run for not more than 1% of the total time. This was selected as a good choice for server applications. A value that is too high will cause the size of the heap to grow to its maximum.

Suggested strategy

Do not choose a maximum value for the heap unless you know that the heap is greater than the default maximum heap size. Choose a throughput goal that is sufficient for your application.

In an ideal situation the heap will grow to a value (less than the maximum) that will support the chosen throughput goal.

If the heap grows to its maximum, the throughput cannot be met within that maximum. Set the maximum heap as large as you can, but no larger than the size of physical memory on the platform, and execute the application again. If the throughput goal can still not be met, then it is too high for the available memory on the platform.

If the throughput goal can be met but there are pauses that are too long, select a pause time goal. This will likely mean that your throughput goal will not be met, so choose values that are an acceptable compromise for the application.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.management.GcInfo (Monitoring and Management Interface for the Java Platform b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Monitoring and Management Interface for the Java Platform
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.management.GcInfo

    • Uses of GcInfo in com.sun.management

      Methods in com.sun.management that return GcInfo
      Modifier and Type Method and Description
      static GcInfo GcInfo.from(CompositeData cd)
      Returns a GcInfo object represented by the given CompositeData.
      GcInfo GarbageCollectorMXBean.getLastGcInfo()
      Returns the GC information about the most recent GC.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Monitoring and Management Interface for the Java Platform
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2003, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


JAAS Authorization Tutorial

This tutorial expands the program and policy file developed in the JAAS Authentication tutorial to demonstrate the JAAS authorization component, which ensures the authenticated caller has the access control rights (permissions) required to do subsequent security-sensitive operations. Since the authorization component requires that the user authentication first be completed, please read the JAAS Authentication tutorial first if you have not already done so.

The rest of this tutorial consists of the following sections:

  • What is JAAS Authorization?
  • How is JAAS Authorization Performed?
    • How Do You Make Principal-Based Policy File Statements?
    • How Do You Associate a Subject with an Access Control Context?
  • The Authorization Tutorial Code
  • The Login Configuration File
  • The Policy File
  • Running the Authorization Tutorial Code

If you want to first see the tutorial code in action, you can skip directly to Running the Authorization Tutorial Code and then go back to the other sections to learn more.

What is JAAS Authorization?

JAAS authorization extends the existing Java security architecture that uses a security policy to specify what access rights are granted to executing code. That architecture, introduced in the Java 2 platform, is code-centric. That is, the permissions are granted based on code characteristics: where the code is coming from and whether it is digitally signed and if so by whom. We saw an example of this in the sampleacn.policy file used in the JAAS Authentication tutorial. That file contains the following:

grant codebase "file:./SampleAcn.jar" {

   permission javax.security.auth.AuthPermission
                    "createLoginContext.Sample";
};

This grants the code in the SampleAcn.jar file, located in the current directory, the specified permission. (No signer is specified, so it doesn't matter whether the code is signed or not.)

JAAS authorization augments the existing code-centric access controls with new user-centric access controls. Permissions can be granted based not just on what code is running but also on who is running it.

When an application uses JAAS authentication to authenticate the user (or other entity such as a service), a Subject is created as a result. The purpose of the Subject is to represent the authenticated user. A Subject is comprised of a set of Principals, where each Principal represents an identity for that user. For example, a Subject could have a name Principal ("Susan Smith") and a Social Security Number Principal ("987-65-4321"), thereby distinguishing this Subject from other Subjects.

Permissions can be granted in the policy to specific Principals. After the user has been authenticated, the application can associate the Subject with the current access control context. For each subsequent security-checked operation (a local file access, for example), the Java runtime will automatically determine whether the policy grants the required permission only to a specific Principal and if so, the operation will be allowed only if the Subject associated with the access control context contains the designated Principal.

How is JAAS Authorization Performed?

To make JAAS authorization take place, the following is required:

  • The user must be authenticated, as described in the JAAS Authentication tutorial.
  • Principal-based entries must be configured in the security policy.
  • The Subject that is the result of authentication must be associated with the current access control context.

How Do You Make Principal-Based Policy File Statements?

Policy file grant statements can now optionally include one or more Principal fields. Inclusion of a Principal field indicates that the user or other entity represented by the specified Principal, executing the specified code, has the designated permissions.

Thus, the basic format of a grant statement is now

grant <signer(s) field>, <codeBase URL>
  <Principal field(s)> {
    permission perm_class_name "target_name", "action";
    ....
    permission perm_class_name "target_name", "action";
  };
where each of the signer, codeBase and Principal fields is optional and the order between the fields doesn't matter.

A Principal field looks like the following:

Principal Principal_class "principal_name"

That is, it is the word "Principal" (where case doesn't matter) followed by the (fully qualified) name of a Principal class and a principal name.

A Principal class is a class that implements the java.security.Principal interface. All Principal objects have an associated name that can be obtained by calling their getName method. The format used for the name is dependent on each Principal implementation.

The type of Principal placed in the Subject created by the basic authentication mechanism used by this tutorial is SamplePrincipal, so that is what should be used as the Principal_class part of our grant statement's Principal designation. User names for SamplePrincipals are of the form "name", and the only user name accepted for this tutorial is "testUser", so the principal_name designation to use in the grant statement is "testUser".

It is possible to include more than one Principal field in a grant statement. If multiple Principal fields are specified, then the permissions in that grant statement are granted only if the Subject associated with the current access control context contains all of those Principals.

To grant the same set of permissions to different Principals, create multiple grant statements where each lists the permissions and contains a single Principal field designating one of the Principals.

The policy file for this tutorial includes one grant statement with a Principal field:

grant codebase "file:./SampleAction.jar",
        Principal sample.principal.SamplePrincipal "testUser" {

   permission java.util.PropertyPermission "java.home", "read";
   permission java.util.PropertyPermission "user.home", "read";
   permission java.io.FilePermission "foo.txt", "read";
};

This specifies that the indicated permissions are granted to the specified principal executing the code in SampleAction.jar. (Note: the SamplePrincipal class is in the sample.principal package.)

How Do You Associate a Subject with an Access Control Context?

To create and associate a Subject with the current access control context, you need the following:

  • The user must first be authenticated, as described in JAAS Authentication.
  • The static doAs method from the Subject class must be called, passing it an authenticated Subject and a java.security.PrivilegedAction or java.security.PrivilegedExceptionAction. (See API for Privileged Blocks for a comparison of PrivilegedAction and PrivilegedExceptionAction.) The doAs method associates the provided Subject with the current access control context and then invokes the run method from the action. The run method implementation contains all the code to be executed as the specified Subject. The action thus executes as the specified Subject.

    The static doAsPrivileged method from the Subject class may be called instead of the doAs method, as will be done for this tutorial. In addition to the parameters passed to doAs, doAsPrivileged requires a third parameter: an AccessControlContext. Unlike doAs, which associates the provided Subject with the current access control context, doAsPrivileged associates the Subject with the provided access control context or with an empty access control context if the parameter passed in is null, as is the case for this tutorial. See doAs vs. doAsPrivileged in the JAAS Reference Guide for a comparison of those methods.

The Authorization Tutorial Code

The code for this tutorial consists of four files:

  • SampleAzn.java is exactly the same as the SampleAcn.java application file from the JAAS Authentication tutorial except for the additional code needed to call Subject.doAsPrivileged.
  • SampleAction.java contains the SampleAction class. This class implements PrivilegedAction and has a run method that contains all the code we want to be executed with Principal-based authorization checks.
  • SampleLoginModule.java is the class specified by the tutorial's login configuration file as the class implementing the desired underlying authentication. SampleLoginModule's user authentication consists of simply verifying that the name and password specified by the user have specific values. This class was also used by the JAAS Authentication tutorial and will not be discussed further here.
  • SamplePrincipal.java is a sample class implementing the java.security.Principal interface. It is used by SampleLoginModule. This class was also used by the JAAS Authentication tutorial and will not be discussed further here.

The SampleLoginModule.java and SamplePrincipal.java files were also used in the JAAS Authentication tutorial, so they are not described further here. The other source files are described below.

SampleAzn.java

Like SampleAcn, the SampleAzn class instantiates a LoginContext lc and calls its login method to perform the authentication. If successful, the authenticated Subject (which includes a SamplePrincipal representing the user) is obtained by calling the LoginContext's getSubject method:

Subject mySubject = lc.getSubject();

After providing the user some information about the Subject, such as which Principals it has, the main method then calls Subject.doAsPrivileged, passing it the authenticated Subject mySubject, a PrivilegedAction (SampleAction) and a null AccessControlContext, as described in the following.

The SampleAction class is instantiated via the following:

PrivilegedAction action = new SampleAction();

The call to Subject.doAsPrivileged is performed via:

Subject.doAsPrivileged(mySubject, action, null);

The doAsPrivileged method invokes execution of the run method in the PrivilegedAction action (SampleAction) to initiate execution of the rest of the code, which is considered to be executed on behalf of the Subject mySubject.

Passing null as the AccessControlContext (third) argument to doAsPrivileged indicates that mySubject should be associated with a new empty AccessControlContext. The result is that security checks occurring during execution of SampleAction will only require permissions for the SampleAction code itself (or other code it invokes), running as mySubject. Note that the caller of doAsPrivileged (and the callers on the execution stack at the time doAsPrivileged was called) do not require any permissions while the action executes.

SampleAction.java

SampleAction.java contains the SampleAction class. This class implements java.security.PrivilegedAction and has a run method that contains all the code we want to be executed as the Subject mySubject. For this tutorial, we will perform three operations, each of which cannot be done unless code has been granted required permissions. We will:

  • Read and print the value of the java.home system property,
  • Read and print the value of the user.home system property, and
  • Determine whether or not a file named foo.txt exists in the current directory.

Here is the code:

package sample;

import java.io.File;
import java.security.PrivilegedAction;

public class SampleAction implements PrivilegedAction {

  public Object run() {

    System.out.println("\nYour java.home property value is: "
                + System.getProperty("java.home"));

    System.out.println("\nYour user.home property value is: "
                + System.getProperty("user.home"));

    File f = new File("foo.txt");
    System.out.print("\nfoo.txt does ");
    if (!f.exists())
        System.out.print("not ");
    System.out.println("exist in the current working directory.");
    return null;
  }
}

The Login Configuration File

The login configuration file used for this tutorial can be exactly the same as that used by the JAAS Authentication tutorial. Thus we can use sample_jaas.config, which contains just one entry:

Sample {
  sample.module.SampleLoginModule required debug=true;
};

This entry is named "Sample" and that is the name that both our tutorial applications SampleAcn and SampleAzn use to refer to it. The entry specifies that the LoginModule to be used to do the user authentication is the SampleLoginModule in the sample.module package and that this SampleLoginModule is required to "succeed" in order for authentication to be considered successful. The SampleLoginModule succeeds only if the name and password supplied by the user are the one it expects ("testUser" and "testPassword", respectively).

The SampleLoginModule also defines a "debug" option that can be set to true as shown. If this option is set to true, SampleLoginModule outputs extra information about the progress of authentication.

The Policy File

The application for this authorization tutorial consists of two classes, SampleAzn and SampleAction. The code in each class contains some security-sensitive operations and thus relevant permissions are required in a policy file in order for the operations to be executed.

The LoginModule used by this tutorial, SampleLoginModule, also contains an operation requiring a permission.

The permissions required by each of these classes are described below, followed by a link to the full policy file.

Permissions Required by SampleAzn

The main method of the SampleAzn class does two operations for which permissions are required. It

  • creates a LoginContext, and
  • calls the doAsPrivileged static method of the Subject class.

The LoginContext creation is exactly the same as was done in the authentication tutorial, and it thus needs the same javax.security.auth.AuthPermission permission with target "createLoginContext.Sample".

In order to call the doAsPrivileged method of the Subject class, you need to have a javax.security.auth.AuthPermission with target "doAsPrivileged".

Assuming the SampleAzn class is placed in a JAR file named SampleAzn.jar, these permissions can be granted to the SampleAzn code via the following grant statement in the policy file:

grant codebase "file:./SampleAzn.jar" {
   permission javax.security.auth.AuthPermission
                    "createLoginContext.Sample";
   permission javax.security.auth.AuthPermission "doAsPrivileged";
};

Permissions Required by SampleAction

The SampleAction code does three operations for which permissions are required. It

  • reads the value of the "java.home" system property.
  • reads the value of the "user.home" system property.
  • checks to see whether or not a file named foo.txt exists in the current directory.

The permissions required for these operations are the following:

permission java.util.PropertyPermission "java.home", "read";
permission java.util.PropertyPermission "user.home", "read";
permission java.io.FilePermission "foo.txt", "read";

We need to grant these permissions to the code in SampleAction.class, which we will place in a JAR file named SampleAction.jar. However, for this particular grant statement we want to grant the permissions not just to the code but to a specific user executing the code, to demonstrate how to restrict access to a particular user.

Thus, as explained in How Do You Make Principal-Based Policy File Statements?, our grant statement looks like the following:

grant codebase "file:./SampleAction.jar",
        Principal sample.principal.SamplePrincipal "testUser" {

   permission java.util.PropertyPermission "java.home", "read";
   permission java.util.PropertyPermission "user.home", "read";
   permission java.io.FilePermission "foo.txt", "read";
};

Permissions Required by SampleLoginModule

The SampleLoginModule code does one operation for which permissions are required. It needs a javax.security.auth.AuthPermission with target "modifyPrincipals" in order to populate a Subject with a Principal. The grant statement is the following:

grant codebase "file:./SampleLM.jar" {
    permission javax.security.auth.AuthPermission "modifyPrincipals";
};

The Full Policy File

The full policy file is sampleazn.policy.

Running the Authorization Tutorial Code

To execute our JAAS authorization tutorial code, all you have to do is

  1. Place the following files into a directory:
    • The sample_jaas.config login configuration file.
    • The sampleazn.policy policy file.
  2. Create a subdirectory named "sample" of that top-level directory, and place the following into it (note the SampleAzn and SampleAction classes are in a package named sample):
    • The SampleAzn.java source file.
    • The SampleAction.java source file.
  3. Create a subdirectory of the "sample" directory and name it "module". Place the following into it (note the SampleLoginModule class is in a package named sample.module):
    • the SampleLoginModule.java source file
  4. Create another subdirectory of the "sample" directory and name it "principal". Place the following into it (note the SamplePrincipal class is in a package named sample.principal):
    • the SamplePrincipal.java source file
  5. While in the top-level directory, compile all the source files:
    javac sample/SampleAction.java sample/SampleAzn.java
sample/module/SampleLoginModule.java sample/principal/SamplePrincipal.java
    (Type all that on one line.)
  6. Create a JAR file named SampleAzn.jar containing SampleAzn.class and MyCallbackHandler.class (Note the sources for both these classes are in SampleAzn.java):
    jar -cvf SampleAzn.jar sample/SampleAzn.class
sample/MyCallbackHandler.class

    (Type all that on one line.)

  7. Create a JAR file named SampleAction.jar containing SampleAction.class:
    jar -cvf SampleAction.jar sample/SampleAction.class
  8. Create a JAR file containing SampleLoginModule.class and SamplePrincipal.class:
    jar -cvf SampleLM.jar sample/module/SampleLoginModule.class
sample/principal/SamplePrincipal.class
  9. Execute the SampleAzn application, specifying
    1. by an appropriate -classpath clause that classes should be searched for in the SampleAzn.jar, SampleAction.jar, and SampleLM.jar JAR files,
    2. by -Djava.security.manager that a security manager should be installed,
    3. by -Djava.security.policy==sampleazn.policy that the policy file to be used is sampleazn.policy, and
    4. by -Djava.security.auth.login.config==sample_jaas.config that the login configuration file to be used is sample_jaas.config.

    Below are the full commands to use for both Microsoft Windows and Unix systems. The only difference is that on Windows systems you use semicolons to separate classpath items, while you use colons for that purpose on Unix systems.

    Here is the full command for Windows systems:

    java -classpath SampleAzn.jar;SampleAction.jar;SampleLM.jar
 -Djava.security.manager
 -Djava.security.policy==sampleazn.policy
 -Djava.security.auth.login.config==sample_jaas.config sample.SampleAzn

    Here is the full command for UNIX systems:

    java -classpath SampleAzn.jar:SampleAction.jar:SampleLM.jar
 -Djava.security.manager
 -Djava.security.policy==sampleazn.policy
 -Djava.security.auth.login.config==sample_jaas.config sample.SampleAzn

    Type the full command on one line. Multiple lines are used here for legibility. If the command is too long for your system, you may need to place it in a .bat file (for Windows) or a .sh file (for UNIX) and then run that file to execute the command.

    You will be prompted for a user name and password (use "testUser" and "testPassword"), and the SampleLoginModule specified in the login configuration file will check the name and password. If your login is successful, you will see the message "Authentication succeeded!" and if not, you will see "Authentication failed:" followed by a reason for the failure.

    Once authentication is successfully completed, the rest of the program (in SampleAction) will be executed on behalf of you, the user, requiring you to have been granted appropriate permissions. The sampleazn.policy policy file grants you the required permissions, so you will see a display of the values of your java.home and user.home system properties and a statement as to whether or not you have a file named foo.txt in the current directory.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JAAS Authentication Tutorial

The Java Authentication and Authorization Service (JAAS) was introduced as an optional package to the Java 2 SDK, Standard Edition (J2SDK), v 1.3. JAAS was integrated into the Java Standard Edition Development Kit starting with J2SDK 1.4.

JAAS can be used for two purposes:

  • for authentication of users, to reliably and securely determine who is currently executing Java code, regardless of whether the code is running as an application, an applet, a bean, or a servlet; and
  • for authorization of users to ensure they have the access control rights (permissions) required to do the actions performed.

This section provides a basic tutorial for the authentication component. The authorization component will be described in the JAAS Authorization Tutorial.

JAAS authentication is performed in a pluggable fashion. This permits Java applications to remain independent from underlying authentication technologies. New or updated technologies can be plugged in without requiring modifications to the application itself. An implementation for a particular authentication technology to be used is determined at runtime. The implementation is specified in a login configuration file. The authentication technology used for this tutorial is very basic, just ensuring that the user specifies a particular name and password.

The rest of this tutorial consists of the following sections:

  1. The Authentication Tutorial Code
  2. The Login Configuration
  3. Running the Code
  4. Running the Code with a Security Manager

If you want to first see the tutorial code in action, you can skip directly to Running the Code and then go back to the other sections to learn about coding and configuration file details.

The Authentication Tutorial Code

The code for this tutorial consists of three files:

  • SampleAcn.java contains the sample application class (SampleAcn) and another class used to handle user input (MyCallbackHandler). The code in this file is the only code you need to understand for this tutorial. Your application will only indirectly use the other source files.
  • SampleLoginModule.java is the class specified by the tutorial's login configuration file as the class implementing the desired underlying authentication. SampleLoginModule's user authentication consists of simply verifying that the name and password specified by the user have specific values.
  • SamplePrincipal.java is a sample class implementing the java.security.Principal interface. It is used by SampleLoginModule.

SampleAcn.java

Our authentication tutorial application code is contained in a single source file, SampleAcn.java. That file contains two classes:

  • The SampleAcn Class
  • The MyCallbackHandler Class

The SampleAcn Class

The main method of the SampleAcn class performs the authentication and then reports whether or not authentication succeeded.

The code for authenticating the user is very simple, consisting of just two steps:

  1. Instantiate a LoginContext.
  2. Call the LoginContext's login method.

First the basic code is shown, followed by a complete listing of the SampleAcn class, complete with the import statement it requires and error handling.

Instantiating a LoginContext

In order to authenticate a user, you first need a javax.security.auth.login.LoginContext. Here is the basic way to instantiate a LoginContext:

import javax.security.auth.login.*;
. . .
LoginContext lc =
    new LoginContext(<config file entry name>,
           <CallbackHandler to be used for user interaction>);
and here is the specific way our tutorial code does the instantiation:
import javax.security.auth.login.*;
. . .
LoginContext lc =
    new LoginContext("Sample",
          new MyCallbackHandler());

The arguments are the following:

  1. The name of an entry in the JAAS login configuration file

    This is the name for the LoginContext to use to look up an entry for this application in the JAAS login configuration file, described here. Such an entry specifies the class(es) that implement the desired underlying authentication technology(ies). The class(es) must implement the LoginModule interface, which is in the javax.security.auth.spi package.

    In our sample code, we use the SampleLoginModule supplied with this tutorial. The SampleLoginModule performs authentication by ensuring that the user types a particular name and password.

    The entry in the login configuration file we use for this tutorial (see sample_jaas.config) has the name "Sample", so that is the name we specify as the first argument to the LoginContext constructor.

  2. A CallbackHandler instance.

    When a LoginModule needs to communicate with the user, for example to ask for a user name and password, it does not do so directly. That is because there are various ways of communicating with a user, and it is desirable for LoginModules to remain independent of the different types of user interaction. Rather, the LoginModule invokes a javax.security.auth.callback.CallbackHandler to perform the user interaction and obtain the requested information, such as the user name and password.

    An instance of the particular CallbackHandler to be used is specified as the second argument to the LoginContext constructor. The LoginContext forwards that instance to the underlying LoginModule (in our case SampleLoginModule). An application typically provides its own CallbackHandler implementation. Two simple CallbackHandlers, TextCallbackHandler and DialogCallbackHandler, are provided in the com.sun.security.auth.callback package as sample implementations. For this tutorial we could use the TextCallbackHandler, which outputs information to and reads input from the command line. However, we instead demonstrate the more typical case of an application providing its own CallbackHandler implementation, described in The MyCallbackHandler Class.

Calling the LoginContext's login Method

Once we have a LoginContext lc, we can call its login method to carry out the authentication process:

lc.login();

The LoginContext instantiates a new empty javax.security.auth.Subject object (which represents the user or service being authenticated). The LoginContext constructs the configured LoginModule (in our case SampleLoginModule) and initializes it with this new Subject and MyCallbackHandler.

The LoginContext's login method then calls methods in the SampleLoginModule to perform the login and authentication. The SampleLoginModule will utilize the MyCallbackHandler to obtain the user name and password. Then the SampleLoginModule will check that the name and password are the ones it expects.

If authentication is successful, the SampleLoginModule populates the Subject with a Principal representing the user. The Principal the SampleLoginModule places in the Subject is an instance of SamplePrincipal, which is a sample class implementing the java.security.Principal interface.

See Subjects, Principals, Authentication, and Credentials for information on these terms.

The calling application can subsequently retrieve the authenticated Subject by calling the LoginContext's getSubject method, although doing so is not necessary for this tutorial.

The Complete SampleAcn Class Code

Now that you have seen the basic code required to authenticate the user, we can put it all together into the full class in SampleAcn.java, which includes relevant import statements and error handling:

package sample;

import javax.security.auth.login.*;
// . . . other import statements needed by MyCallbackHandler . . .

/**
 * This Sample application attempts to authenticate a user
 * and reports whether or not the authentication was
 * successful.
 */
public class SampleAcn {

   /**
    * Attempt to authenticate the user.
    *
    * @param args input arguments for this application.
    * These are ignored.
    */
    public static void main(String[] args) {

      // Obtain a LoginContext, needed for authentication.
      // Tell it to use the LoginModule implementation
      // specified by the entry named "Sample" in the
      // JAAS login configuration file and to also use the
      // specified CallbackHandler.
      LoginContext lc = null;
      try {
          lc = new LoginContext("Sample",
                          new MyCallbackHandler());
      } catch (LoginException le) {
          System.err.println("Cannot create LoginContext. "
              + le.getMessage());
          System.exit(-1);
      } catch (SecurityException se) {
          System.err.println("Cannot create LoginContext. "
              + se.getMessage());
          System.exit(-1);
      }

      // the user has 3 attempts to authenticate successfully
      int i;
      for (i = 0; i < 3; i++) {
          try {

              // attempt authentication
              lc.login();

              // if we return with no exception,
              // authentication succeeded
              break;

          } catch (LoginException le) {

              System.err.println("Authentication failed:");
              System.err.println("  " + le.getMessage());
              try {
                  Thread.currentThread().sleep(3000);
              } catch (Exception e) {
                  // ignore
              }

          }
      }

      // did they fail three times?
      if (i == 3) {
          System.out.println("Sorry");
          System.exit(-1);
      }

      System.out.println("Authentication succeeded!");

    }
}

The MyCallbackHandler Class

In some cases a LoginModule must communicate with the user to obtain authentication information. LoginModules use a javax.security.auth.callback.CallbackHandler for this purpose. An application can either use one of the sample implementations provided in the com.sun.security.auth.callback package or, more typically, write a CallbackHandler implementation. The application passes the CallbackHandler as an argument to the LoginContext instantiation. The LoginContext forwards the CallbackHandler directly to the underlying LoginModules.

The tutorial sample code supplies its own CallbackHandler implementation, the MyCallbackHandler class in SampleAcn.java.

CallbackHandler is an interface with one method to implement:

     void handle(Callback[] callbacks)
         throws java.io.IOException, UnsupportedCallbackException;

The LoginModule passes the CallbackHandler handle method an array of appropriate javax.security.auth.callback.Callbacks, for example a NameCallback for the user name and a PasswordCallback for the password, and the CallbackHandler performs the requested user interaction and sets appropriate values in the Callbacks.

The MyCallbackHandler handle method is structured as follows:

public void handle(Callback[] callbacks)
  throws IOException, UnsupportedCallbackException {

  for (int i = 0; i < callbacks.length; i++) {
    if (callbacks[i] instanceof TextOutputCallback) {

      // display a message according to a specified type
      . . .

    } else if (callbacks[i] instanceof NameCallback) {

      // prompt the user for a username
      . . .

    } else if (callbacks[i] instanceof PasswordCallback) {

      // prompt the user for a password
      . . .

    } else {
        throw new UnsupportedCallbackException
         (callbacks[i], "Unrecognized Callback");
    }
  }
}

A CallbackHandler handle method is passed an array of Callback instances, each of a particular type (NameCallback, PasswordCallback, etc.). It must handle each Callback, performing user interaction in a way that is appropriate for the executing application.

MyCallbackHandler handles three types of Callbacks: NameCallback to prompt the user for a user name, PasswordCallback to prompt for a password, and TextOutputCallback to report any error, warning, or other messages the SampleLoginModule wishes to send to the user.

The handle method handles a TextOutputCallback by extracting the message to be reported and then printing it to System.out, optionally preceded by additional wording that depends on the message type. The message to be reported is determined by calling the TextOutputCallback's getMessage method and the type by calling its getMessageType method. Here is the code for handling a TextOutputCallback:

if (callbacks[i] instanceof TextOutputCallback) {

  // display the message according to the specified type
  TextOutputCallback toc = (TextOutputCallback)callbacks[i];
  switch (toc.getMessageType()) {
     case TextOutputCallback.INFORMATION:
        System.out.println(toc.getMessage());
        break;
     case TextOutputCallback.ERROR:
        System.out.println("ERROR: " + toc.getMessage());
        break;
     case TextOutputCallback.WARNING:
        System.out.println("WARNING: " + toc.getMessage());
        break;
     default:
        throw new IOException("Unsupported message type: " +
            toc.getMessageType());
   }

The handle method handles a NameCallback by prompting the user for a user name. It does this by printing the prompt to System.err. It then sets the name for use by the SampleLoginModule by calling the NameCallback's setName method, passing it the name typed by the user:

} else if (callbacks[i] instanceof NameCallback) {

  // prompt the user for a username
  NameCallback nc = (NameCallback)callbacks[i];

  System.err.print(nc.getPrompt());
  System.err.flush();
  nc.setName((new BufferedReader
      (new InputStreamReader(System.in))).readLine());

Similarly, the handle method handles a PasswordCallback by printing a prompt to System.err to prompt the user for a password. It then sets the password for use by the SampleLoginModule by calling the PasswordCallback's setPassword method, passing it the password typed by the user, which it reads by calling the readPassword method (shown below):

} else if (callbacks[i] instanceof PasswordCallback) {

  // prompt the user for sensitive information
  PasswordCallback pc = (PasswordCallback)callbacks[i];

  System.err.print(pc.getPrompt());
  System.err.flush();
  pc.setPassword(readPassword(System.in));

The readPassword method is a basic method for reading a password from an InputStream:

private char[] readPassword(InputStream in) throws IOException {

    char[] lineBuffer;
    char[] buf;
    int i;

    buf = lineBuffer = new char[128];

    int room = buf.length;
    int offset = 0;
    int c;

  loop:
    while (true) {
      switch (c = in.read()) {
         case -1:
         case '\n':
            break loop;

         case '\r':
             int c2 = in.read();
             if ((c2 != '\n') && (c2 != -1)) {
                 if (!(in instanceof PushbackInputStream)) {
                     in = new PushbackInputStream(in);
                 }
                 ((PushbackInputStream)in).unread(c2);
             } else
                 break loop;

         default:
             if (--room < 0) {
                 buf = new char[offset + 128];
                 room = buf.length - offset - 1;
                 System.arraycopy(lineBuffer, 0, buf, 0, offset);
                 Arrays.fill(lineBuffer, ' ');
                 lineBuffer = buf;
             }
             buf[offset++] = (char) c;
             break;
        }
    }

    if (offset == 0) {
        return null;
    }

    char[] ret = new char[offset];
    System.arraycopy(buf, 0, ret, 0, offset);
    Arrays.fill(buf, ' ');

    return ret;
  }
}

SampleLoginModule.java and SamplePrincipal.java

SampleLoginModule.java implements the LoginModule interface. SampleLoginModule is the class specified by the tutorial's login configuration file as the class implementing the desired underlying authentication. SampleLoginModule's user authentication consists of simply verifying that the name and password specified by the user have specific values. This SampleLoginModule is specified by the tutorial's login configuration file as the LoginModule to use because (1) It performs a basic type of authentication suitable for any environment and thus is appropriate for a tutorial for all users, and (2) It provides an example LoginModule implementation for experienced programmers who require the ability to write a LoginModule implementing an authentication technology.

SamplePrincipal.java is a sample class implementing the java.security.Principal interface. If authentication is successful, the SampleLoginModule populates a Subject with a SamplePrincipal representing the user.

Important: If you are an application writer, you do not need to know how to write a LoginModule or a Principal implementation. You do not need to examine the SampleLoginModule or SamplePrincipal code. All you have to know is how to write your application and specify configuration information (such as in a login configuration file) such that the application will be able to utilize the LoginModule specified by the configuration to authenticate the user. You need to determine which LoginModule(s) you want to use and read the LoginModule's documentation to learn about what options you can specify values for (in the configuration) to control the LoginModule's behavior.

Any vendor can provide a LoginModule implementation that you can use. Some implementations are supplied with the JRE from Sun Microsystems, as listed in the JAAS Login Configuration File document.

Information for programmers who want to write a LoginModule can be found in the JAAS LoginModule Developer's Guide.

The Login Configuration

JAAS authentication is performed in a pluggable fashion, so applications can remain independent from underlying authentication technologies. A system administrator determines the authentication technologies, or LoginModules, to be used for each application and configures them in a login Configuration. The source of the configuration information (for example, a file or a database) is up to the current javax.security.auth.login.Configuration implementation. The default Configuration implementation from Sun Microsystems reads configuration information from configuration files, as described in com.sun.security.auth.login.ConfigFile.html.

See JAAS Login Configuration File for information as to what a login configuration file is, what it contains, and how to specify which login configuration file should be used.

The Login Configuration File for This Tutorial

As noted, the login configuration file we use for this tutorial, sample_jaas.config, contains just one entry, which is

Sample {
  sample.module.SampleLoginModule required debug=true;
};

This entry is named "Sample" and that is the name that our tutorial application, SampleAcn, uses to refer to this entry. The entry specifies that the LoginModule to be used to do the user authentication is the SampleLoginModule in the sample.module package and that this SampleLoginModule is required to "succeed" in order for authentication to be considered successful. The SampleLoginModule succeeds only if the name and password supplied by the user are the one it expects ("testUser" and "testPassword", respectively).

The SampleLoginModule also defines a "debug" option that can be set to true as shown. If this option is set to true, SampleLoginModule outputs extra information about the progress of authentication. A LoginModule can define as many options as it wants. The LoginModule documentation should specify the possible option names and values you can set in your configuration file.

Running the Code

To execute our JAAS authentication tutorial code, all you have to do is

  1. Place the following file into a directory:
    • the sample_jaas.config login configuration file
  2. Create a subdirectory named "sample" of that top-level directory, and place the following into it (note the SampleAcn and MyCallbackHandler classes, both in SampleAcn.java, are in a package named sample):
    • the SampleAcn.java application source file
  3. Create a subdirectory of the "sample" directory and name it "module". Place the following into it (note the SampleLoginModule class is in a package named sample.module):
    • the SampleLoginModule.java source file
  4. Create another subdirectory of the "sample" directory and name it "principal". Place the following into it (note the SamplePrincipal class is in a package named sample.principal):
    • the SamplePrincipal.java source file
  5. While in the top-level directory, compile SampleAcn.java, SampleLoginModule.java, and SamplePrincipal.java:
    javac sample/SampleAcn.java sample/module/SampleLoginModule.java
sample/principal/SamplePrincipal.java
    (Type all that on one line.)
  6. Execute the SampleAcn application, specifying
    • by -Djava.security.auth.login.config==sample_jaas.config that the login configuration file to be used is sample_jaas.config.

The full command is below.

java -Djava.security.auth.login.config==sample_jaas.config sample.SampleAcn

You will be prompted for your user name and password, and the SampleLoginModule specified in the login configuration file will check to ensure these are correct. The SampleLoginModule expects "testUser" for the user name and "testPassword" for the password.

You will see some messages output by SampleLoginModule as a result of the debug option being set to true in the login configuration file. Then, if your login is successful, you will see the following message output by SampleAcn:

Authentication succeeded!
If the login is not successful (for example, if you misspell the password), you will see
Authentication failed:
followed by a reason for the failure. For example, if you mistype the password, you may see a message like the following:
Authentication failed:
  Password Incorrect

SampleAcn gives you three chances to successfully log in.

Running the Code with a Security Manager

When a Java program is run with a security manager installed, the program is not allowed to access resources or otherwise perform security-sensitive operations unless it is explicitly granted permission to do so by the security policy in effect. In Java platforms that are compatible with J2SE v 1.2 and later, the permission must be granted by an entry in a policy file.

Most browsers install a security manager, so applets typically run under the scrutiny of a security manager. Applications, on the other hand, do not, since a security manager is not automatically installed when an application is running. Thus an application, like our SampleAcn application, by default has full access to resources.

To run an application with a security manager, simply invoke the interpreter with a -Djava.security.manager argument included on the command line.

If you try invoking SampleAcn with a security manager but without specifying any policy file, you will get the following (unless you have a default policy setup elsewhere that grants the required permissions or grants AllPermission):

% java -Djava.security.manager \
 -Djava.security.auth.login.config==sample_jaas.config sample.SampleAcn
Exception in thread "main" java.security.AccessControlException:
  access denied (
  javax.security.auth.AuthPermission createLoginContext.Sample)

As you can see, you get an AccessControlException, because we haven't created and used a policy file granting our code the permission that is required in order to be allowed to create a LoginContext.

Here are the complete steps required in order to be able to run our SampleAcn application with a security manager installed. You can skip the first five steps if you have already done them, as described in Running the Code.

  1. Place the following file into a directory:
    • the sample_jaas.config login configuration file
  2. Create a subdirectory named "sample" of that top-level directory, and place the following into it (note the SampleAcn and MyCallbackHandler classes, both in SampleAcn.java, are in a package named sample):
    • the SampleAcn.java application source file
  3. Create a subdirectory of the "sample" directory and name it "module". Place the following into it (note the SampleLoginModule class is in a package named sample.module):
    • the SampleLoginModule.java source file
  4. Create another subdirectory of the "sample" directory and name it "principal". Place the following into it (note the SamplePrincipal class is in a package named sample.principal):
    • the SamplePrincipal.java source file
  5. While in the top-level directory, compile SampleAcn.java, SampleLoginModule.java, and SamplePrincipal.java:
    javac sample/SampleAcn.java sample/module/SampleLoginModule.java
sample/principal/SamplePrincipal.java
    (Type all that on one line.)
  6. Create a JAR file containing SampleAcn.class and MyCallbackHandler.class:
    jar -cvf SampleAcn.jar sample/SampleAcn.class
sample/MyCallbackHandler.class

    (Type all that on one line.) This command creates a JAR file, SampleAcn.jar, and places the SampleAcn.class and MyCallbackHandler.class files inside it.

  7. Create a JAR file containing SampleLoginModule.class and SamplePrincipal.class:
    jar -cvf SampleLM.jar sample/module/SampleLoginModule.class
sample/principal/SamplePrincipal.class
  8. Create a policy file granting the required permissions.

    The permission that is needed by code attempting to instantiate a LoginContext is a javax.security.auth.AuthPermission with target "createLoginContext.<entry name>". Here, <entry name> refers to the name of the login configuration file entry that the application references in its instantiation of LoginContext. The name used by our SampleAcn application's LoginContext instantiation is "Sample", as you can see in the code:

    LoginContext lc =
    new LoginContext("Sample",
          new MyCallbackHandler());

    Thus, the permission that needs to be granted to SampleAcn.jar is

    permission javax.security.auth.AuthPermission
  "createLoginContext.Sample";

    The SampleLM.jar file also needs to be granted a permission. The documentation for a LoginModule should tell you what permissions it needs to be granted. In the case of SampleLoginModule, it needs a javax.security.auth.AuthPermission with target "modifyPrincipals" in order to populate a Subject with a Principal:

    permission javax.security.auth.AuthPermission
  "modifyPrincipals";

    Copy the policy file sampleacn.policy to the same directory as that in which you stored SampleAcn.java, etc. The policy file contains the following grant statement to grant SampleAcn.jar (in the current directory) its required permission:

    grant codebase "file:./SampleAcn.jar" {
   permission javax.security.auth.AuthPermission
                    "createLoginContext.Sample";
};

    The policy file also contains the following grant statement to grant SampleLM.jar (also in the current directory) its required permission:

    grant codebase "file:./SampleLM.jar" {
   permission javax.security.auth.AuthPermission
                    "modifyPrincipals";
};

    Note: Policy files and the structure of entries within them are described in Default Policy Implementation and Policy File Syntax. Permissions are described here.

  9. Execute the SampleAcn application, specifying
    1. by an appropriate -classpath clause that classes should be searched for in the SampleAcn.jar and SampleLM.jar JAR files,
    2. by -Djava.security.manager that a security manager should be installed,
    3. by -Djava.security.policy==sampleacn.policy that the policy file to be used is sampleacn.policy, and
    4. by -Djava.security.auth.login.config==sample_jaas.config that the login configuration file to be used is sample_jaas.config.

    Below are the full commands to use for both Microsoft Windows and Unix systems. The only difference is that on Microsoft Windows systems you use semicolons to separate classpath items, while you use colons for that purpose on Unix systems.

    Here is the full command for Microsoft Windows systems:

    java -classpath SampleAcn.jar;SampleLM.jar
 -Djava.security.manager
 -Djava.security.policy==sampleacn.policy \
 -Djava.security.auth.login.config==sample_jaas.config \
 sample.SampleAcn

    Here is the full command for UNIX systems:

    java -classpath SampleAcn.jar:SampleLM.jar
 -Djava.security.manager
 -Djava.security.policy==sampleacn.policy \
 -Djava.security.auth.login.config==sample_jaas.config \
 sample.SampleAcn

    Type all that on one line. Multiple lines are used here for legibility. If the command is too long for your system, you may need to place it in a .bat file (for Microsoft Windows) or a .sh file (for UNIX) and then run that file to execute the command.

    Since the specified policy file contains an entry granting the code the required permissions, execution should proceed without any exceptions indicating a required permission was not granted. You will be prompted for a user name and password (use "testUser" and "testPassword"), and the SampleLoginModule specified in the login configuration file will check the name and password. If your login is successful, you will see the message "Authentication succeeded!" and if not, you will see "Authentication failed:" followed by a reason for the failure.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Generics

When you take an element out of a Collection, you must cast it to the type of element that is stored in the collection. Besides being inconvenient, this is unsafe. The compiler does not check that your cast is the same as the collection's type, so the cast can fail at run time.

Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection.

Here is a simple example taken from the existing Collections tutorial:

// Removes 4-letter words from c. Elements must be strings
static void expurgate(Collection c) {
    for (Iterator i = c.iterator(); i.hasNext(); )
      if (((String) i.next()).length() == 4)
        i.remove();
}

Here is the same example modified to use generics:

// Removes the 4-letter words from c
static void expurgate(Collection<String> c) {
    for (Iterator<String> i = c.iterator(); i.hasNext(); )
      if (i.next().length() == 4)
        i.remove();
}

When you see the code <Type>, read it as "of Type"; the declaration above reads as "Collection of String c.” The code using generics is clearer and safer. We have eliminated an unsafe cast and a number of extra parentheses. More importantly, we have moved part of the specification of the method from a comment to its signature, so the compiler can verify at compile time that the type constraints are not violated at run time. Because the program compiles without warnings, we can state with certainty that it will not throw a ClassCastException at run time. The net effect of using generics, especially in large programs, is improved readability and robustness.

To paraphrase Generics Specification Lead Gilad Bracha, when we declare c to be of type Collection<String>, this tells us something about the variable c that holds true wherever and whenever it is used, and the compiler guarantees it (assuming the program compiles without warnings). A cast, on the other hand, tells us something the programmer thinks is true at a single point in the code, and the VM checks whether the programmer is right only at run time.

While the primary use of generics is collections, there are many other uses. "Holder classes," such as WeakReference and ThreadLocal, have all been generified, that is, they have been retrofitted to make use of generics. More surprisingly, class Class has been generified. Class literals now function as type tokens, providing both run-time and compile-time type information. This enables a style of static factories exemplified by the getAnnotation method in the new AnnotatedElement interface:

    <T extends Annotation> T getAnnotation(Class<T> annotationType);
This is a generic method. It infers the value of its type parameter T from its argument, and returns an appropriate instance of T, as illustrated by the following snippet:
    Author a = Othello.class.getAnnotation(Author.class);
Prior to generics, you would have had to cast the result to Author. Also you would have had no way to make the compiler check that the actual parameter represented a subclass of Annotation.

Generics are implemented by type erasure: generic type information is present only at compile time, after which it is erased by the compiler. The main advantage of this approach is that it provides total interoperability between generic code and legacy code that uses non-parameterized types (which are technically known as raw types). The main disadvantages are that parameter type information is not available at run time, and that automatically generated casts may fail when interoperating with ill-behaved legacy code. There is, however, a way to achieve guaranteed run-time type safety for generic collections even when interoperating with ill-behaved legacy code.

The java.util.Collections class has been outfitted with wrapper classes that provide guaranteed run-time type safety. They are similar in structure to the synchronized and unmodifiable wrappers. These "checked collection wrappers" are very useful for debugging. Suppose you have a set of strings, s, into which some legacy code is mysteriously inserting an integer. Without the wrapper, you will not find out about the problem until you read the problem element from the set, and an automatically generated cast to String fails. At this point, it is too late to determine the source of the problem. If, however, you replace the declaration:

    Set<String> s = new HashSet<String>();
with this declaration:
    Set<String> s = Collections.checkedSet(new HashSet<String>(), String.class);
the collection will throw a ClassCastException at the point where the legacy code attempts to insert the integer. The resulting stack trace will allow you to diagnose and repair the problem.

You should use generics everywhere you can. The extra effort in generifying code is well worth the gains in clarity and type safety. It is straightforward to use a generic library, but it requires some expertise to write a generic library, or to generify an existing library. There is one caveat: You may not use generics (or any other Tiger features) if you intend to deploy the compiled code on a pre-5.0 virtual machine.

If you are familiar with C++'s template mechanism, you might think that generics are similar, but the similarity is superficial. Generics do not generate a new class for each specialization, nor do they permit "template metaprogramming."

There is much more to learn about generics. See the Generics Tutorial.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Getting Started with the Annotation Processing Tool, apt

The following topics are covered

  • The apt Tool Has Been Deprecated
  • What is apt?
  • Why Should I Use apt?
  • How to use apt
  • How the apt Tool Operates
  • Declarations and Types
  • FAQs
  • See Also

The apt Tool Has Been Deprecated

The apt tool and its associated API contained in the package com.sun.mirror have been deprecated since JDK 7 and are planned to be removed in the next major JDK release. Use the options available in the javac tool and the APIs contained in the packages javax.annotation.processing and javax.lang.model to process annotations.

Summary of apt API Replacements

The following tables summarize apt API replacements:

Package com.sun.mirror.apt
apt type | Standard Replacement
AnnotationProcessor | javax.annotation.processing.Processor
AnnotationProcessorEnvironment | javax.annotation.processing.ProcessingEnvironment
AnnotationProcessorFactory | javax.annotation.processing.Processor
AnnotationProcessorListener | No analog.
AnnotationProcessors | No analog.
Filer | javax.annotation.processing.Filer
Filer.Location | javax.tools.StandardLocation
Messager | javax.annotation.processing.Messager
RoundCompleteEvent | No analog.
RoundCompleteListener | No analog.
RoundState | javax.annotation.processing.RoundEnvironment
Package com.sun.mirror.declaration
apt type | Standard Replacement
AnnotationMirror | javax.lang.model.element.AnnotationMirror
AnnotationTypeDeclaration | javax.lang.model.element.TypeElement
AnnotationTypeElementDeclaration | javax.lang.model.element.ExecutableElement
AnnotationValue | javax.lang.model.element.AnnotationValue
ClassDeclaration | javax.lang.model.element.TypeElement
ConstructorDeclaration | javax.lang.model.element.ExecutableElement
Declaration | javax.lang.model.element.Element
EnumConstantDeclaration | javax.lang.model.element.VariableElement
EnumDeclaration | javax.lang.model.element.TypeElement
ExecutableDeclaration | javax.lang.model.element.ExecutableElement
FieldDeclaration | javax.lang.model.element.VariableElement
InterfaceDeclaration | javax.lang.model.element.TypeElement
MemberDeclaration | javax.lang.model.element.Element
MethodDeclaration | javax.lang.model.element.ExecutableElement
Modifier | javax.lang.model.element.Modifier
PackageDeclaration | javax.lang.model.element.PackageElement
ParameterDeclaration | javax.lang.model.element.VariableElement
TypeDeclaration | javax.lang.model.element.TypeElement
TypeParameterDeclaration | javax.lang.model.element.TypeParameterElement
Package com.sun.mirror.type
apt type | Standard Replacement
AnnotationType | javax.lang.model.type.DeclaredType
ArrayType | javax.lang.model.type.ArrayType
ClassType | javax.lang.model.type.DeclaredType
DeclaredType | javax.lang.model.type.DeclaredType
EnumType | javax.lang.model.type.DeclaredType
InterfaceType | javax.lang.model.type.DeclaredType
MirroredTypeException | javax.lang.model.type.MirroredTypeException
MirroredTypesException | javax.lang.model.type.MirroredTypesException
PrimitiveType | javax.lang.model.type.PrimitiveType
PrimitiveType.Kind | javax.lang.model.type.TypeKind
ReferenceType | javax.lang.model.type.ReferenceType
TypeMirror | javax.lang.model.type.TypeMirror
TypeVariable | javax.lang.model.type.TypeVariable
VoidType | javax.lang.model.type.NoType
WildcardType | javax.lang.model.type.WildcardType
Package com.sun.mirror.util
apt type | Standard Replacement
DeclarationFilter | javax.lang.model.util.ElementFilter
DeclarationScanner | javax.lang.model.util.ElementScanner6
DeclarationVisitor | javax.lang.model.element.ElementVisitor
DeclarationVisitors | No replacement.
Declarations | javax.lang.model.util.Elements
SimpleDeclarationVisitor | javax.lang.model.util.SimpleElementVisitor6
SimpleTypeVisitor | javax.lang.model.util.SimpleTypeVisitor6
SourceOrderDeclScanner | javax.lang.model.util.SimpleElementVisitor6
SourcePosition | No replacement.
TypeVisitor | javax.lang.model.element.TypeVisitor
Types | javax.lang.model.util.Types

What is apt?

The command-line utility apt, annotation processing tool, finds and executes annotation processors based on the annotations present in the set of specified source files being examined. The annotation processors use a set of reflective APIs and supporting infrastructure to perform their processing of program annotations (JSR 175). The apt reflective APIs provide a build-time, source-based, read-only view of program structure. These reflective APIs are designed to cleanly model the JavaTM programming language's type system after the addition of generics (JSR 14). First, apt runs annotation processors that can produce new source code and other files. Next, apt can cause compilation of both original and generated source files, thus easing the development cycle.

Why Should I Use apt?

Many of the intended use cases for annotations involve having annotations in a base file hold information that is used to generate new derived files (source files, class files, deployment descriptors, etc.) that are logically consistent with the base file and its annotations. In other words, instead of manually maintaining consistency among the entire set of files, only the base file would need to be maintained since the derived files are generated. The apt tool is designed for creating the derived files.

Compared to using a doclet to generate the derived files based on annotations, apt

  • has a cleaner model of the declarations and current type structure of programs
  • uses a more contemporary API design, such as returning generic collections instead of arrays and providing visitors to operate on declarations and types
  • supports recursive processing of newly generated files and can automatically cause compilation of original and generated source files
While intended for annotation processing, apt can be used for other reflective programming tasks too.

How to use apt

Overview

First, apt determines what annotations are present on the source code being operated on. Next, apt looks for annotation processor factories you've written. The tool asks the factories what annotations they process. Then apt asks a factory to provide an annotation processor if the factory processes an annotation present in source files being operated on. Next, the annotation processors are run. If the processors have generated new source files, apt will repeat this process until no new source files are generated.

Developing an Annotation Processor

Writing an annotation processor relies on four packages:
  • com.sun.mirror.apt: interfaces to interact with the tool
  • com.sun.mirror.declaration: interfaces to model the source code declarations of fields, methods, classes, etc.
  • com.sun.mirror.type: interfaces to model types found in the source code
  • com.sun.mirror.util: various utilities for processing types and declarations, including visitors
Each processor implements the AnnotationProcessor interface in the package com.sun.mirror.apt. This interface has one method -- process -- used by the apt tool to invoke the processor. A processor will "process" one or more annotation types.

A processor instance is returned by its corresponding factory -- an AnnotationProcessorFactory. The apt tool calls the factory's getProcessorFor method to get hold of the processor. During this call, the tool provides an AnnotationProcessorEnvironment. In the environment the processor will find everything it needs to get started, including references to the program structure on which it is operating, and the means to communicate and cooperate with the apt tool by creating new files and passing on warning and error messages.

There are two ways a factory can be found; the factory to use can be specified via the "-factory" command line option or the factory can be located during the apt discovery procedure. Using the "-factory" option is the simplest way to run a single known factory; this option may also be used when a factory needs more control over how it is run. To locate the factories on a particular path, the discovery procedure retrieves from jar files META-INF/services information in the format described below.

To create and use an annotation processor using the "-factory" option:

  1. Write an AnnotationProcessorFactory that in turn can create an AnnotationProcessor for the annotation type(s) of interest.
  2. Compile the processors and factories using javac with tools.jar on the classpath; tools.jar contains the com.sun.mirror.* interfaces.
  3. Put the compiled class files, or jar files containing the class files, on the appropriate path when invoking apt
To create and use an annotation processor with the default discovery procedure use the same first two steps then,
  3. Create a UTF-8 encoded text file in META-INF/services named com.sun.mirror.apt.AnnotationProcessorFactory whose contents are a list of fully qualified names of the concrete factory classes, one per line. (This is the same format used by sun.misc.Service.)
  4. Package the factory, processor, and META-INF/services information into a jar file
  5. Place the jar file on the appropriate path when invoking apt. The appropriate path is discussed in the Discovery section.

A Simple Sample Annotation Processor

import com.sun.mirror.apt.*;
import com.sun.mirror.declaration.*;
import com.sun.mirror.type.*;
import com.sun.mirror.util.*;

import java.util.Collection;
import java.util.Set;
import java.util.Arrays;

import static java.util.Collections.*;
import static com.sun.mirror.util.DeclarationVisitors.*;

/*
 * This class is used to run an annotation processor that lists class
 * names.  The functionality of the processor is analogous to the
 * ListClass doclet in the Doclet Overview.
 */
public class ListClassApf implements AnnotationProcessorFactory {
    // Process any set of annotations
    private static final Collection<String> supportedAnnotations
        = unmodifiableCollection(Arrays.asList("*"));

    // No supported options
    private static final Collection<String> supportedOptions = emptySet();

    public Collection<String> supportedAnnotationTypes() {
        return supportedAnnotations;
    }

    public Collection<String> supportedOptions() {
        return supportedOptions;
    }

    public AnnotationProcessor getProcessorFor(
            Set<AnnotationTypeDeclaration> atds,
            AnnotationProcessorEnvironment env) {
        return new ListClassAp(env);
    }

    private static class ListClassAp implements AnnotationProcessor {
        private final AnnotationProcessorEnvironment env;
        ListClassAp(AnnotationProcessorEnvironment env) {
            this.env = env;
        }

        public void process() {
            for (TypeDeclaration typeDecl : env.getSpecifiedTypeDeclarations())
                typeDecl.accept(getDeclarationScanner(new ListClassVisitor(),
                                                      NO_OP));
        }

        private static class ListClassVisitor extends SimpleDeclarationVisitor {
            public void visitClassDeclaration(ClassDeclaration d) {
                System.out.println(d.getQualifiedName());
            }
        }
    }
}

A number of new language and library features are used in the sample processor. First, static imports are used so that the simple name of various utility methods can be used; for example
"unmodifiableCollection"
instead of
"Collections.unmodifiableCollection".
Second, generic collections are used throughout. The Arrays.asList method is now a var-args method so it can accept a comma separated list of strings and create a list with the desired elements. The Collections.emptySet method is a generic method and can be used to create a type-safe empty set. The for loop in the process method is an enhanced for loop that can iterate over collections.

Specifying the Annotations to Process

To tell the tool what annotations it processes, a factory returns a collection of import-style strings, as shown in the example. A particular string entry may have one of the following three forms:
*
Process all annotations. This also processes an empty list of annotations; in other words, a factory that processes * could be asked to provide a non-trivial processor even if no annotations are present. This capability allows the com.sun.mirror APIs to be used to write general source code processing tools.
foo.bar.Baz
Process an annotation whose canonical name is "foo.bar.Baz".
foo.bar.*
Process annotations whose canonical names start with "foo.bar.".

The apt tool presents the factory with a set of annotations for the factory to process. Based on the set of annotations and the annotation processor environment, the factory returns a single annotation processor. What if the factory wants to return multiple annotation processors? The factory can use com.sun.mirror.apt.AnnotationProcessors.getCompositeAnnotationProcessor to combine and sequence the operation of multiple annotation processors.

Specifying the Command Line Options to Recognize

The supportedOptions method allows a factory to communicate to apt which command line options it recognizes. Command line options starting with "-A" are reserved for communicating with annotation processors. For example, if this factory recognizes options such as -Adebug and -Aloglevel=3, it will return the strings "-Adebug" and "-Aloglevel". In the future, apt may give an indication if -A options are given that no factory recognizes.

The apt Command Line

In addition to its own options, the apt tool accepts all of the command-line options accepted by javac. The javac options are passed to the final javac call, if any.

The apt specific options are:

-s dir
Specify the directory root under which processor-generated source files will be placed; files are placed in subdirectories based on package namespace
-nocompile
Do not compile source files to class files.
-print
Print out textual representation of specified types; perform no annotation processing or compilation.
-A[key[=val]]
Options to pass to annotation processors -- these are not interpreted by apt directly, but are made available for use by individual processors
-factorypath path
Specify where to find annotation processor factories; if this option is used, the classpath is not searched for factories.
-factory classname
Name of AnnotationProcessorFactory to use; bypasses default discovery process
How apt shares some of javac's options:
-d dir
Specify where to place processor and javac generated class files
-cp path or -classpath path
Specify where to find user class files and annotation processor factories. If -factorypath is given, the classpath is not searched for factories.
There are a few apt hidden options that may be useful for debugging:
-XListAnnotationTypes
List found annotation types
-XListDeclarations
List specified and included declarations
-XPrintAptRounds
Print information about initial and recursive apt rounds
-XPrintFactoryInfo
Print information about which annotations a factory is asked to process

How the apt Tool Operates

Discovery

After scanning the source files on the command line to determine what annotations are present, by default the apt tool looks for annotation processor factories on the appropriate path. If the -factorypath option is used, that path is the appropriate path to search for factories; otherwise, the classpath is the appropriate path. The factories are queried to determine what annotations they process. If a factory processes one of the annotations present, that annotation is considered claimed. Once all annotations are claimed, the tool does not look for additional factories. After the annotations are all claimed or no more factories can be found, apt will call the factories' getProcessorFor methods, passing in the set of annotations that factory has claimed. Each factory returns a single processor to perform the appropriate processing for the set of annotations in question. After all processors are returned, apt calls each processor in turn. If any processor generated a new source file, a recursive round of apt will occur. In recursive apt rounds, discovery calls getProcessorFor on any factory that provided a processor in a previous round, even if that factory processes none of the current annotations. This allows the factory to register a listener in subsequent apt rounds; though most factories will simply return AnnotationProcessors.NO_OP in this case. After a round where no new source files are generated, apt will invoke javac on the original and generated source files. If no processors are found or the processors found don't process the annotations present, calling apt is essentially equivalent to calling javac directly on the source files.

If a factory class is used by more than one round of annotation processing, the factory class is loaded once and the factory's getProcessorFor method will be called once per round. This allows a factory to store static state across rounds.

If the -factory option is used, the named factory is the only one queried.

Rounds of apt Processing

The first round of apt analyzes the input source files, runs the discovery procedure, and calls the resulting annotation processors. The second round of apt analyzes the new source files produced by the first round (if any), runs the discovery procedure on those new files, and calls the resulting annotation processors. Likewise, if the second round has produced new source files, the third round analyzes the new source, runs discovery, etc. The apt rounds continue until no new source files are generated. Finally, after the last round, by default the apt tool will run javac on the original and generated source files.

Listeners

Annotation processors or factories can register listeners for the end of a round using the addListener method in the environment. The tool calls the registered listeners after all annotation processors for that round have run to completion. The listener is passed information about the status of the round, such as if any new source files were written, if an error was raised, and if the just completed round was the last round. Listeners can be used to write out trailing ends of files when all annotation processing has completed. The same class can implement both the AnnotationProcessor and RoundCompleteListener interfaces so the same object can serve in both contexts.

Return Code

If javac is invoked after the last apt round, the return code of apt will be the return code of javac compiling those files. If javac is not invoked, apt will have a 0 exit status if no errors were reported, either by the tool itself or by processors. Operating on malformed or incomplete source files in and of itself is not sufficient to cause apt to have a nonzero exit status.

Declarations and Types

The mirror API represents source code constructs principally through the Declaration interface and its hierarchy of subinterfaces, in the package com.sun.mirror.declaration. A Declaration represents a program element such as a package, class, or method, and typically corresponds one-to-one with a particular fragment of source code. Declarations are the structures that may be annotated.

Types are represented by the TypeMirror interface and its hierarchy of subinterfaces in the package com.sun.mirror.type. Types include primitive types, class and interface types, array types, type variables, and wildcard types.

The API is careful to distinguish between declarations and types. This is most significant for generic types, where a single declaration can define a whole family of types. For example, the declaration of the class java.util.Set corresponds to

  • the parameterized type java.util.Set<String>
  • the parameterized type java.util.Set<Number>
  • the parameterized type java.util.Set<T> for some type T other than String or Number
  • the raw type java.util.Set.
A declaration has doc comments, a source position, modifiers, and annotations. A declaration may have different kinds of names (simple, qualified). More specific declaration subclasses provide additional information appropriate for that construct. For example, class declarations provide access to constructors and the superclass. A declaration for an enum has a method to provide the enum constants.

TypeMirrors are used to model the return types, parameter types, etc., in source code. A TypeMirror for a reference type provides a mapping from a type to corresponding declaration; for example from the type mirror for java.util.Set<String> to the declaration for java.util.Set.

FAQs

  • Do you know about the Debian Advanced Packaging Tool?
    Yes.
  • How does an annotation processor compare to a doclet?
    The two entities certainly have some similarities; both use build-time reflective APIs to process source code. However, the mirror APIs used in annotation processors better model the current type system of the Java programming language. Also, by default the annotation processor(s) to run are determined by the annotations present in the source code rather than only on a mechanism analogous to the -doclet option. In other words, instead of running a single fixed doclet, apt dynamically chooses potentially multiple processors to run.
  • How can I process annotations on local variables?
    Annotations on local variables are invisible since the declaration hierarchy does not model program structure inside a method or constructor.
  • Why are there separate factory and processor interfaces in com.sun.mirror.apt?
    It would be possible to combine determining how to process and controlling when to process; however, we choose to distinguish and separate the two steps with factory and processor interfaces.
  • What is a mirror?
    Somewhere you find a reflection. In reflective programming, a mirror design maintains a consistent separation between the objects being represented and the objects doing the representing.
  • Why were the annotations a factory supports and the options a factory supports returned by methods instead of being encoded as annotations on the factory class?
    Implementing an interface is the usual mechanism to indicate a class has a desired capability, such as providing an indication of what annotations it processes. There is no language mechanism to require a class be annotated with a particular annotation type. Therefore, while it would have been technically possible to encode such information in annotations, doing so would have lacked the type safety of just having methods in an interface.
  • I'm not familiar with visitors, do I have to use them?
    The visitor pattern is one of the standard patterns in the "Gang of Four" Design Patterns book. The pattern provides a powerful mechanism to invoke a type-dependent operation without explicitly testing for the type. However, using visitors is not mandatory.

See Also

  • apt Tool Reference Page
  • Mirror API Specification
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


GLOBALS

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Overview File Class Tree Index Help
jrunscript JavaScript built-ins
PREV CLASS NEXT CLASS
SUMMARY: FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

Class GLOBALS

Object
   |
   +--GLOBALS
class GLOBALS
Method Summary
<static> void | cat(obj, pattern) Shows the content of a file, URL or InputStream
<static> void | cd(target) Changes the present working directory to the given directory
<static> void | cp(from, to) Copies a file, URL, or stream to another file or stream
<static> void | date() Prints the current date using the current locale
<static> void | del(pathname) A synonym for 'rm'
<static> void | dir(d, filter) A synonym for 'ls'.
<static> Object | dirname(pathname) Returns the directory part of a filename
<static> void | echo(x) Echoes the given string arguments
<static> void | exec(cmd) Execs a child process, waits for completion & returns exit code
<static> void | exit(code) Exit the shell program.
<static> void | find(dir, pattern, callback) Find in files.
<static> void | grep(pattern, files ) Unix-like grep, but accepts JavaScript regex patterns
<static> void | ip(name) Prints the IP addresses of a given domain name
<static> void | load(str) Loads and evaluates JavaScript code from a stream, file, or URL
<static> void | ls(dir, filter) Lists the files in a directory
<static> void | mkdir(dir) Creates a new directory of a given name
<static> void | mkdirs(dir) Creates a directory, including any necessary but nonexistent parent directories.
<static> void | mv(from, to) Moves a file to another
<static> Object | printf(format, args) A C-like printf
<static> void | pwd() Print the working directory
<static> void | quit(code) synonym for exit
<static> Object | read(prompt, multiline) Reads one or more lines from stdin after printing a prompt
<static> void | ren(from, to) A synonym for 'mv'.
<static> Object | rm(pathname) Removes a given file
<static> void | rmdir(pathname) Removes a given directory
<static> void | which(cmd) Prints which command is selected from PATH
<static> Object | XMLDocument(inp) Converts input to DOM Document object
<static> Object | XMLResult(out) Converts an arbitrary stream, file to an XMLResult
<static> Object | XMLSource(inp) Converts an arbitrary stream, file, URL to an XMLSource
<static> void | XSLTransform(inp, style, out) Perform XSLT transform

Method Detail

cat

<static> void cat(obj, pattern)
    Shows the content of a file, URL, or InputStream
    Examples:

    cat('test.txt'); // show test.txt file contents
    cat('http://java.net'); // show the contents from the URL http://java.net
    Parameters:
      obj - input to show
      pattern - optional. Show only the lines matching the pattern

cd

<static> void cd(target)
    Changes the present working directory to the given directory
    Parameters:
      target - the directory to change to. optional, defaults to user's HOME

cp

<static> void cp(from, to)
    Copies a file, URL, or stream to another file or stream
    Parameters:
      from - the input file, URL, or stream
      to - the output stream or file

date

<static> void date()
    Prints the current date using the current locale

del

<static> void del(pathname)
    A synonym for 'rm'

dir

<static> void dir(d, filter)
    A synonym for 'ls'.

dirname

<static> Object dirname(pathname)
    Returns the directory part of a filename
    Parameters:
      pathname - the input path name
    Returns:
      the directory part of the given file name

echo

<static> void echo(x)
    Echoes the given string arguments

exec

<static> void exec(cmd)
    Execs a child process, waits for completion & returns the exit code
    Parameters:
      cmd - the command to execute in child process

exit

<static> void exit(exitCode)
    Exit the shell program.
    Parameters:
      exitCode - the integer code to be returned to the OS shell. Optional, defaults to 0

find

<static> void find(dir, pattern, callback)
    Find in files. Calls a specified callback function for each matching file.
    Examples:

    find('.')
    find('.', '.*\.class', rm);  // remove all .class files
    find('.', '.*\.java');       // print fullpath of each .java file
    find('.', '.*\.java', cat);  // print all .java files
    Parameters:
      dir - the directory of files to search
      pattern - the pattern to search for
      callback - the function to call for matching files

grep

<static> void grep(pattern, files )
    Unix-like grep, but accepts JavaScript regex patterns
    Parameters:
      pattern - the pattern to search for
      files - one or more files to be searched

ip

<static> void ip(name)
    Prints the IP addresses of given domain name
    Parameters:
      name - the domain name

load

<static> void load(str)
    Loads and evaluates JavaScript code from a stream, file, or URL
    Examples:

    load('test.js'); // load script file 'test.js'
    load('http://java.sun.com/foo.js'); // load from a URL
    Parameters:
      str - the input from which the script is loaded and evaluated

ls

<static> void ls(dir, filter)
    Lists the files in a directory
    Parameters:
      dir - the directory from which to list the files. Optional, default to pwd
      filter - a pattern to filter the files listed. Optional, default is '.'

mkdir

<static> void mkdir(dir)
    Creates a new directory
    Parameters:
      dir - the name of the new directory

mkdirs

<static> void mkdirs(dir)
    Creates a directory, including any necessary but nonexistent parent directories.
    Parameters:
      dir - the pathname of the directory to be created

mv

<static> void mv(from, to)
    Moves a file to another
    Parameters:
      from - the original name of the file
      to - the new name for the file

printf

<static> Object printf(format, args)
    A C-like printf
    Parameters:
      format - the string to format the rest of the print items
      args - the variadic argument list

pwd

<static> void pwd()
    Print the working directory

quit

<static> void quit(code)
    A synonym for exit

read

<static> Object read(prompt, multiline)
    Reads one or more lines from stdin after printing a prompt
    Parameters:
      prompt - the prompt. Optional, default is '>'
      multiline - if 0, read a single line, else read multiple lines

ren

<static> void ren(from, to)
    A synonym for 'mv'.

rm

<static> Object rm(pathname)
    Removes a given file
    Parameters:
      pathname - the name of the file

rmdir

<static> void rmdir(pathname)
    Removes a given directory
    Parameters:
      pathname - the name of the directory

which

<static> void which(cmd)
    Print the pathname of a command located on PATH
    Parameters:
      cmd - the name of the command searched from PATH

XMLDocument

<static> Object XMLDocument(inp)
    Converts input to a DOM Document object
    Parameters:
      inp - a file or reader. Optional, If missing a new DOM Document is returned.
    Returns:
      returns a DOM Document object

XMLResult

<static> Object XMLResult(out)
    Convert an arbitrary stream or file to an XMLResult
    Parameters:
      inp - the input stream or file
    Returns:
      XMLResult object

XMLSource

<static> Object XMLSource(inp)
    Converts an arbitrary stream, file, or URL to an XMLSource
    Parameters:
      inp - the input stream, file, or URL
    Returns:
      XMLSource object

XSLTransform

<static> void XSLTransform(inp, style, out)
    Perform an XSLT transform
    Parameters:
      inp - the input XML to transform (URL, File or InputStream)
      style - the XSL Stylesheet to be used (URL, File or InputStream). Optional.
      out - the output XML (File or OutputStream)
Overview File Class Tree Index Help
PREV CLASS NEXT CLASS
SUMMARY: FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Subjects, Principals, Authentication, and Credentials

To authorize access to resources, applications first need to authenticate the source of the request. The JAAS framework defines the term subject to represent the source of a request. A subject may be any entity, such as a person or service. A subject is represented by the javax.security.auth.Subject class.

Authentication represents the process by which the identity of a subject is verified, and must be performed in a secure fashion; otherwise a perpetrator may impersonate others to gain access to a system. Authentication typically involves the subject demonstrating some form of evidence to prove its identity. Such evidence may be information only the subject would likely know or have (such as a password or fingerprint), or it may be information only the subject could produce (such as signed data using a private key).

Once authenticated, a Subject is populated with associated identities, or Principals (of type java.security.Principal). A Subject may have many Principals. For example, a person may have a name Principal ("John Doe") and an SSN Principal ("123-45-6789"), which distinguish it from other Subjects.

In addition to associated Principals, a Subject may own security-related attributes, which are referred to as credentials. A credential may contain information used to authenticate the subject to new services. Such credentials include passwords, Kerberos tickets, and public key certificates. Credentials might also contain data that simply enables the subject to perform certain activities. Cryptographic keys, for example, represent credentials that enable the subject to sign or encrypt data. Public and private credential classes are not part of the core JAAS class library. Any class, therefore, can represent a credential.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Image I/O API Guide: 2 - Goals

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

CHAPTER 2

Goals

2.1 API Goals

The design of the Image I/O API was influenced by the desire to support a number of primary goals. Each goal provides the justification for a particular set of API features. These goals may be divided into those motivated mainly by the needs of client-side applications, and those motivated by the needs of server applications. Naturally, these primary goals represent only a fraction of the capabilities of the API. They are listed here in order to provide a sense of the motivations that went into the design of the API.

As a general rule of thumb, whenever a tradeoff between ease of use for application developers and plug-in developers was identified, the application developer was given a higher priority. Since relatively few users of the API are expected to write plug-ins, and even those developers who do write plug-ins will typically write no more than a handful in order to support formats of immediate use to them, it makes sense to push complexity into the plug-ins rather than into applications.

To ameliorate the complexity of plug-in development, some utility methods and implementation classes are provided that perform common functions. However, it is not possible to provide implementation classes to cover every situation, and providing an excessive number of utility classes and methods would increase the footprint for all API users even if they did not use non-standard plug-ins. We expect that plug-in developers will be able to incorporate source code from existing plug-ins and sample code into their plug-ins. While this might lead to some redundancy when using multiple, independently developed plug-ins, most users will probably use only a small number of plug-ins at a time in any case. Thus, we believe the cost of having to load code that might theoretically be shared but actually is not will tend to outweight the cost of loading some redundant code when many plug-ins are used.

2.1.1 Client-Side Application Goals

Pluggability An application written to use the Image I/O API should be able to automatically take advantage of new plug-ins without any rewriting or recompilation. This requires that plug-ins follow, as much as possible, a set of format-neutral interfaces. However, every image format has unique properties and capabilities, which plug-ins must be able to expose to applications. This is accomplished by allowing plug-ins to extend a number of interfaces within the API. Applications that are unaware of the plug-in specific extensions may continue to make use of the normal plug-in capabilities, while aware applications may use the extended interfaces.

Both generic and plug-in specific access to metadata (non-image data) is supported by allowing plug-ins to provide access to metadata in multiple formats. These may include plug-in specific formats, a plug-in neutral format defined by the API, and industry standard formats.

Automatic and Manual Plug-in Installation and Selection For simple applications that wish to load images without user intervention, it is important to allow a reader plug-in to be selected automatically based on file contents. However, it is desirable to avoid the loading and instantiation of complex classes unless they are needed. A plug-in must be able to determine whether it can handle a particular image without loading all of its code. In order to meet this goal, plug-ins are instantiated via a service provider interface mechanism that allows simple queries to be performed without loading the main body of plug-in code.

All of the bytecode (.class) files associated with a plug-in may be combined into a JAR file, which may be installed permanently into a Java Runtime Environment, or loaded dynamically using the application CLASSPATH mechanism.

Manual Plug-in Selection Although automatic plug-in selection is convenient for many applications, it must be possible for more sophisticated applications to exercise greater control over the plug-in selection process. This is accomplished by means of a run-time registry of plug-ins that may be queried and manipulated by an application. Network, Disk-based, and Direct I/O Increasingly, applications must deal with both disk-based and network-based data. In many cases, even disk-based data must be dealt with in the form of an InputStream due to the needs of other APIs. The Image I/O API offers a set of interfaces that allow data from Files, InputStreams, or other sources to be handled in a unified manner while preserving the ability to seek backwards and forwards. The API is future-proofed to allow new I/O interfaces, including direct interfaces to image acquisition and output devices, to be used without rewriting application code. Access to Metadata The metadata stored alongside an image may be as important as the image data. The Java Image I/O API provides thorough yet flexible access to metadata. Since metadata may take many forms, and contain very specialized information, it is difficult to provide direct access to such metadata in a general-purpose API. Instead, the API requires plug-ins to cast their metadata into the form of an XML Document structure, possibly enhanced with Object references in addition to textual data. Once this has been done, the metadata may be accessed and edited using standard XML DOM (Document Object Model) interfaces. The syntax of the Documents will vary from plug-in to plug-in, but the structure may be traversed, displayed, and edited without specific knowledge of the plug-in being used. Support for Advanced Applications In order to support advanced applications, the API must provide access to features such as "thumbnail" images, multiple images stored in a file, muli-resolution imagery, and tiled imagery. It must provide the capability to decode portions of a larger image, and to perform subsampling during decoding in order to allow panning over very large images. When writing images, it must be possible to write image data piece-by-piece, without storing the entire image in memory at once.

2.1.2 Server Use Cases

Dynamic image generation Modern web servers typically generate a large portion of their content dynamically. The Java Servlet and Java Server Pages (JSP) APIs provide portable ways to generate HTML pages in response to requests from web browsers. Just as unique, custom HTML may be generated for each user, it is possible to customize image content.

In many cases, image content must be generated dynamically. For example, consider supplying stock price charts. While it might be possible to generate and store a limited set of charts for each listed stock in advance, if the user is allowed to add customizations such as the time interval over which the price should be displayed, or a set of indices or other stocks against which the stock price should be compared, the number of possible images grows exponentially. Only a dynamic approach can possibly allow such customization.

Image Customization Web images are typically one-size-fits-all, with the same image data being delivered regardless of the display capabilities of the receiver. The increasing use of wireless and handheld devices will require images that are customized for their limited bandwidth and display capabilities. Desktop computers have seen increases in their display resolution, causing many web images to appear too small. The lack of scalable images also causes problems for visually impaired users. Server-side image customization can be used to provide optimal images for all users, with the image resolution and color characteristics being chosen based on user preferences.
CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Image I/O API Guide: 2 - Goals

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

2.2 Non-Goals

Thread Safety A particular instance of an ImageReader or ImageWriter is not required to support re-entrant (simultaneous) calls to its methods (with the exception of the abort method that requests current read or writes to halt). However, it must be possible for multiple instances of the same plug-in class to operate simultaneously. For the sake of brevity, we will only discuss reader plug-ins below.

Supporting full re-entrancy would require that the reader bundle all of its state information (e.g., the current input source) into a separate state object, which would allow methods in progress to continue to work with the settings that were in effect at the time they began, while allowing a separate thread to modify the state to be used by the next operation.

Rather than forcing each ImageReader to keep track of its state in this way, it is simpler to require the application to instantiate multiple instances of the same ImageReader class if it wishes to perform multithreaded processing. This means that the state of an ImageReader must be maintained using non-static instance variables only, which should not be a burden for plug-in developers.

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Getting Started with Java IDL: Developing a Client Application

This topic introduces the basics of writing a CORBA client application. Included in this lesson are:

  1. Creating HelloClient.java
  2. Understanding HelloClient.java
  3. Compiling HelloClient.java

Creating HelloClient.java

To create HelloClient.java,

  1. Start your text editor and create a file named HelloClient.java in your main project directory, Hello.
  2. Enter the following code for HelloClient.java in the text file. The following section, Understanding HelloClient.java, explains each line of code in some detail.

    HelloClient.java

    // Copyright and License

import HelloApp.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;

public class HelloClient
{
  static Hello helloImpl;

  public static void main(String args[])
    {
      try{
        // create and initialize the ORB
        ORB orb = ORB.init(args, null);

        // get the root naming context
        org.omg.CORBA.Object objRef =
            orb.resolve_initial_references("NameService");
        // Use NamingContextExt instead of NamingContext. This is
        // part of the Interoperable naming Service.
        NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

        // resolve the Object Reference in Naming
        String name = "Hello";
        helloImpl = HelloHelper.narrow(ncRef.resolve_str(name));

        System.out.println("Obtained a handle on server object: " + helloImpl);
        System.out.println(helloImpl.sayHello());
        helloImpl.shutdown();

        } catch (Exception e) {
          System.out.println("ERROR : " + e) ;
          e.printStackTrace(System.out);
          }
    }

}

  3. Save and close HelloClient.java.

Understanding HelloClient.java

This section explains each line of HelloClient.java, describing what the code does, as well as why it is needed for this application.

Performing Basic Setup

The basic shell of a CORBA client is the same as many Java applications: You import required library packages, declare the application class, define a main method, and handle exceptions.

Importing Required Packages

First, we import the packages required for the client class:

import HelloApp.*; // the package containing our stubs
import org.omg.CosNaming.*; // HelloClient will use the Naming Service
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*; // All CORBA applications need these classes

Declaring the Client Class

The next step is to declare the client class:

public class HelloClient
{
  // The main() method goes here.
}

Defining a main() Method

Every Java application needs a main() method. It is declared within the scope of the HelloClient class, as follows:

  public static void main(String args[])
  {
    // The try-catch block goes here.
  }

Handling CORBA System Exceptions

Because all CORBA programs can throw CORBA system exceptions at runtime, all of the main() functionality is placed within a try-catch block. CORBA programs throw system exceptions whenever trouble occurs during any of the processes (marshaling, unmarshaling, upcall) involved in invocation.

Our exception handler simply prints the name of the exception and its stack trace to standard output so you can see what kind of thing has gone wrong.

The try-catch block is set up inside main(),

    try{

      // Add the rest of the HelloClient code here.

    } catch(Exception e) {
        System.out.println("ERROR : " + e);
        e.printStackTrace(System.out);
      }

Creating an ORB Object

A CORBA client needs a local ORB object to perform all of its marshaling and IIOP work. Every client instantiates an org.omg.CORBA.ORB object and initializes it by passing to the object certain information about itself.

The ORB variable is declared and initialized inside the try-catch block.

        ORB orb = ORB.init(args, null);

The call to the ORB's init() method passes in your application's command line arguments, allowing you to set certain properties at runtime.

Finding the Hello Server

Now that the application has an ORB, it can ask the ORB to locate the actual service it needs, in this case the Hello server. There are a number of ways for a CORBA client to get an initial object reference; our client application will use the COS Naming Service specified by OMG and provided with Java IDL. See Using Stringified Object References for information on how to get an initial object reference when there is no naming service available.

The two options for Naming Services shipped with J2SE v.1.4 are orbd, which is a daemon process containing a Bootstrap Service, a Transient Naming Service, a Persistent Naming Service, and a Server Manager, and tnameserv, a transient naming service. This example uses orbd.

Obtaining the Initial Naming Context

The first step in using the naming service is to get the initial naming context. In the try-catch block, below your ORB initialization, you call orb.resolve_initial_references() to get an object reference to the name server:

        org.omg.CORBA.Object objRef =
            orb.resolve_initial_references("NameService");

The string "NameService" is defined for all CORBA ORBs. When you pass in that string, the ORB returns the initial naming context, an object reference to the name service. The string "NameService" indicates:

  • The persistent naming service will be used when using ORBD as the naming service.
  • The transient naming service will be used when using tnameserv as the naming service.

The string "TNameService" indicates that the transient naming service will be used when ORBD is the naming service. In this example, we are using the persistent naming service that is a part of orbd.

Narrowing the Object Reference

As with all CORBA object references, objRef is a generic CORBA object. To use it as a NamingContextExt object, you must narrow it to its proper type.

        NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

Here we see the use of an idlj-generated helper class, similar in function to HelloHelper. The ncRef object is now an org.omg.CosNaming.NamingContextExt and you can use it to access the naming service and find other services. You will do that in the next step.

The NamingContextExt object is new to J2SE v.1.4, and is part of the Interoperable Naming Service.

Resolve the Object Reference in Naming

To publish a reference in the Naming Service to the Hello object implementing the Hello interface, you first need an identifying string for the Hello object.

      String name = "Hello";

Finally, we pass name to the naming service's resolve_str() method to get an object reference to the Hello server and narrow it to a Hello object:

        helloImpl = HelloHelper.narrow(ncRef.resolve-str(name));
        System.out.println("Obtained a handle on server object: " + helloImpl);

Here you see the HelloHelper helper class at work. The resolve-str() method returns a generic CORBA object as you saw above when locating the name service itself. Therefore, you immediately narrow it to a Hello object, which is the object reference you need to perform the rest of your work. Then, you send a message to the screen confirming that the object reference has been obtained.

Invoking the sayHello() Operation

CORBA invocations look like a method call on a local object. The complications of marshaling parameters to the wire, routing them to the server-side ORB, unmarshaling, and placing the upcall to the server method are completely transparent to the client programmer. Because so much is done for you by generated code, invocation is really the easiest part of CORBA programming.

Finally, we print the results of the invocation to standard output and explicitly shutdown the ORB:

        System.out.println(helloImpl.sayHello());
        helloImpl.shutdown();

Compiling HelloClient.java

Now we will compile HelloClient.java so that we can correct any errors before continuing with this tutorial.

Windows users note that you should substitute backslashes (\) for the slashes (/) in all paths in this document.

To compile HelloClient.java,

  1. Change to the Hello directory.
  2. Run the Java compiler on HelloClient.java:
    javac HelloClient.java HelloApp/*.java
  3. Correct any errors in your file and recompile if necessary.
  4. The HelloClient.class is generated to the Hello directory.

Running the Client Application

Running the Hello World application is covered in Running the Hello World Application.

For More Information

Developing Clients
Covers topics of interest to CORBA client programmers
Exceptions: System Exceptions
Explains how CORBA system exceptions work and provides details on the minor codes of Java IDL's system exceptions
Initialization: System Properties
Explains what properties can be passed to the ORB at initialization
Naming Service
Covers the COS Naming Service in greater detail
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Getting Started with Java IDL: Running the Hello World Application

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Getting Started with Java IDL
Running the Hello World Application

This topic walks you through running the server and client program that together make up the "Hello World" application.

Running the Hello World Application

Despite its simple design, the Hello World program lets you learn and experiment with all the tasks required to develop almost any CORBA program that uses static invocation.

This example requires a naming service to make the servant object's operations available to clients. The server needs an object reference to the naming service so that it can publish the references to the objects implementing various interfaces. These object references are used by the clients for invoking methods. The two options for Naming Services shipped with J2SE v.1.4 are tnameserv, a transient naming service, and orbd, which is a daemon process containing a Bootstrap Service, a Transient Naming Service, a Persistent Naming Service, and a Server Manager. This example uses orbd.

When running this example, remember that, when using Solaris software, you must become root to start a process on a port under 1024. For this reason, we recommend that you use a port number greater than or equal to 1024. The -ORBInitialPort option is used to override the default port number in this example. The following instructions assume you can use port 1050 for the Java IDL Object Request Broker Daemon, orbd. You can substitute a different port if necessary. When running these examples on a Windows machine, subtitute a backslash (\) in path names.

To run this client-server application on your development machine:

  1. Start orbd.

    To start orbd from a UNIX command shell, enter:

      orbd -ORBInitialPort 1050 -ORBInitialHost localhost&

    From an MS-DOS system prompt (Windows), enter:

      start orbd -ORBInitialPort 1050 -ORBInitialHost localhost

    Note that 1050 is the port on which you want the name server to run. -ORBInitialPort is a required command-line argument. Note that when using Solaris software, you must become root to start a process on a port under 1024. For this reason, we recommend that you use a port number greater than or equal to 1024.

    Note that -ORBInitialHost is also a required command-line argument. For this example, since both client and server on running on the development machine, we have set the host to localhost. When developing on more than one machine, you will replace this with the name of the host. For an example of how to run this program on two machines, see The Hello World Example on Two Machines.

  2. Start the Hello server.

    To start the Hello server from a UNIX command shell, enter:

      java HelloServer -ORBInitialPort 1050 -ORBInitialHost localhost&

    From an MS-DOS system prompt (Windows), enter:

      start java HelloServer -ORBInitialPort 1050 -ORBInitialHost localhost

    For this example, you can omit -ORBInitialHost localhost since the name server is running on the same host as the Hello server. If the name server is running on a different host, use -ORBInitialHost nameserverhost to specify the host on which the IDL name server is running.

    Specify the name server (orbd) port as done in the previous step, for example, -ORBInitialPort 1050.

  3. Run the client application:
      java HelloClient -ORBInitialPort 1050 -ORBInitialHost localhost

    For this example, you can omit -ORBInitialHost localhost since the name server is running on the same host as the Hello client. If the name server is running on a different host, use -ORBInitialHost nameserverhost to specify the host on which the IDL name server is running.

    Specify the name server (orbd) port as done in the previous step, for example, -ORBInitialPort 1050.

  4. The client prints the string from the server to the command line:
    Hello world!!

The name server, like many CORBA servers, runs until you explicitly stop it. To avoid having many servers running, kill the name server process after the client application returns successfully. To do this from a DOS prompt, select the window that is running the server and enter Ctrl+C to shut it down. To do this from a Unix shell, find the process, and kill it.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Getting Started with Java IDL

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Getting Started with Java™ IDL

Java™ IDL is a technology for distributed objects – that is, objects interacting on different platforms across a network. Java IDL enables objects to interact regardless of whether they're written in the Java programming language or another language such as C, C++, COBOL, or others.

This is possible because Java IDL is based on the Common Object Request Brokerage Architecture (CORBA), an industry-standard distributed object model. A key feature of CORBA is IDL, a language-neutral Interface Definition Language. Each language that supports CORBA has its own IDL mapping--and as its name implies, Java IDL supports the mapping for Java. To learn more about the IDL-to-Java language mapping, see IDL-to-Java Language Mapping.

To support interaction between objects in separate programs, Java IDL provides an Object Request Broker, or ORB. The ORB is a class library that enables low-level communication between Java IDL applications and other CORBA-compliant applications.

This tutorial teaches the basic tasks needed to build a CORBA distributed application using Java IDL. You will build the classic "Hello World" program as a distributed application. The Hello World program has a single operation that returns a string to be printed.

Any relationship between distributed objects has two sides: the client and the server. The server provides a remote interface, and the client calls a remote interface. These relationships are common to most distributed object standards, including Java Remote Method Invocation (RMI, RMI-IIOP) and CORBA. Note that in this context, the terms client and server define object-level rather than application-level interaction--any application could be a server for some objects and a client of others. In fact, a single object could be the client of an interface provided by a remote object and at the same time implement an interface to be called remotely by other objects.

This figure shows how a one-method distributed object is shared between a CORBA client and server to implement the classic "Hello World" application.

A one-method distributed object shared between a CORBA client and server.

On the client side, the application includes a reference for the remote object. The object reference has a stub method, which is a stand-in for the method being called remotely. The stub is actually wired into the ORB, so that calling it invokes the ORB's connection capabilities, which forwards the invocation to the server.

On the server side, the ORB uses skeleton code to translate the remote invocation into a method call on the local object. The skeleton translates the call and any parameters to their implementation-specific format and calls the method being invoked. When the method returns, the skeleton code transforms results or errors, and sends them back to the client via the ORBs.

Between the ORBs, communication proceeds by means of a shared protocol, IIOP--the Internet Inter-ORB Protocol. IIOP, which is based on the standard TCP/IP internet protocol, defines how CORBA-compliant ORBs pass information back and forth. Like CORBA and IDL, the IIOP standard is defined by OMG, the Object Management Group.

The Java IDL Development Process and the Hello World Tutorial

This tutorial teaches the basic tasks in building a CORBA distributed application using Java IDL. You will build the classic "Hello World" program as a distributed application. The "Hello World" program has a single operation that returns a string to be printed.

Despite its simple design, the Hello World program lets you learn and experiment with all the tasks required to develop almost any CORBA program that uses static invocation. The following steps provide a general guide to designing and developing a distributed object application with Java IDL. Links to the relevant steps of the tutorial will guide you through creating this sample application.

  1. Define the remote interface

    You define the interface for the remote object using the OMG's Interface Definition Langauge (IDL). You use IDL instead of the Java language because the idlj compiler automatically maps from IDL, generating all Java language stub and skeleton source files, along with the infrastructure code for connecting to the ORB. Also, by using IDL, you make it possible for developers to implement clients and servers in any other CORBA-compliant language.

    Note that if you're implementing a client for an existing CORBA service, or a server for an existing client, you would get the IDL interfaces from the implementer--such as a service provider or vendor. You would then run the idlj compiler over those interfaces and follow these steps.

    Writing the IDL file in this tutorial walks you through defining the remote interface for the simple "Hello World" example.

  2. Compile the remote interface

    When you run the idlj compiler over your interface definition file, it generates the Java version of the interface, as well as the class code files for the stubs and skeletons that enable your applications to hook into the ORB.

    Mapping Hello.idl to Java in this tutorial walks you through these steps for the simple "Hello World" example.

  3. Implement the server

    Once you run the idlj compiler, you can use the skeletons it generates to put together your server application. In addition to implementing the methods of the remote interface, your server code includes a mechanism to start the ORB and wait for invocation from a remote client.

    Developing the Hello World Server walks you through writing a simple server for the "Hello World" application.

  4. Implement the client

    Similarly, you use the stubs generated by the idlj compiler as the basis of your client application. The client code builds on the stubs to start its ORB, look up the server using the name service provided with Java IDL, obtain a reference for the remote object, and call its method.

    Developing a Client Application walks you through writing a simple client application.

  5. Start the applications

    Once you implement a server and a client, you can start the name service, then start the server, then run the client.

    Running the Hello World Application walks you through running the server and client program that together make up the "Hello World" application, and the name service that enables them to find one another.

Using Stringified Object References walks you through making an object reference when there is no naming service.

Running the Hello World Application on Two Machines describes one way of distributing the simple application across two machines - a client and a server.

For More Information

Although concepts are explained as they are introduced in the tutorial, you will find more information in the Concepts section. New terms are linked to their definitions throughout the tutorial.

The Object Management Group no longer maintains this site, but the CORBA for Beginnners page contains links to web pages that provide introductory CORBA information.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Getting Started with Java IDL: Writing the Interface Definition

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Getting Started with Java IDL:
Writing the Interface Definition

Before you start working with Java IDL, you need to install version 1.4 (or later) of the Java platform. Version 1.4 (and later) provides the Application Programming Interface (API) and Object Request Broker (ORB) needed to enable CORBA-based distributed object interaction, as well as the idlj compiler. The idlj compiler uses the IDL-to-Java language mapping to convert IDL interface definitions to corresponding Java interfaces, classes, and methods, which you can then use to implement your client and server code.

This section teaches you how to write a simple IDL interface definition and how to translate the IDL interface to Java. It also describes the purpose of each file generated by the idlj compiler.

These topics are included in this section:

  1. Writing Hello.idl
  2. Understanding the IDL file
  3. Mapping Hello.idl to Java
  4. Understanding the idlj Compiler Output

Writing Hello.idl

To create the Hello.idl file,
  1. Create a new directory, named Hello, for this application.
  2. Start your favorite text editor and create a file named Hello.idl in this directory.
  3. In your file, enter the code for the interface definition, Hello.idl:
    module HelloApp
{
  interface Hello
  {
    string sayHello();
    oneway void shutdown();
  };
};
  4. Save the file.

Understanding the IDL file

OMG IDL is the language used to describe the interfaces that client objects call and object implementations provide. An interface definition written in OMG IDL completely defines the interface and fully specifies each operation's parameters. An OMG IDL interface provides the information needed to develop clients that use the interface's operations.

Clients are written in languages for which mappings from OMG IDL concepts have been defined. The mapping of an OMG IDL concept to a client language construct will depend on the facilities available in the client language. OMG specifies a mapping from IDL to several different programming languages, including C, C++, Smalltalk, COBOL, Ada, Lisp, Python, and Java. When mapped, each statement in OMG IDL is translated to a corresponding statement in the programming language of choice.

For example, you could use the tool idlj to map an IDL interface to Java and implement the client class. When you mapped the same IDL to C++ and implemented the server in that language, the Java client (through the Java ORB) and C++ server (through the C++ ORB) interoperate as though they were written in the same language.

The IDL for "Hello World" is extremely simple; its single interface has but two operations. You need perform only three steps:

  1. Declare the CORBA IDL module
  2. Declare the interface
  3. Declare the operations

Declaring the CORBA IDL Module

A CORBA module is a namespace that acts as a container for related interfaces and declarations. It corresponds closely to a Java package. Each module statement in an IDL file is mapped to a Java package statement.

The module statement looks like this:

module HelloApp
{
    // Subsequent lines of code here.
};

When you compile the IDL, the module statement will generate a package statement in the Java code.

Declaring the Interface

Like Java interfaces, CORBA interfaces declare the API contract an object has with other objects. Each interface statement in the IDL maps to a Java interface statement when mapped.

In your Hello.idl file, the interface statement looks like this:

module HelloApp
{
  interface Hello  // These lines
  {                // declare the
                   // interface
  };               // statement.
};

When you compile the IDL, this statement will generate an interface statement in the Java code.

Declaring the Operations

CORBA operations are the behavior that servers promise to perform on behalf of clients that invoke them. Each operation statement in the IDL generates a corresponding method statement in the generated Java interface.

In your Hello.idl file, the operation statement looks like this:

module HelloApp
{
  interface Hello
  {
    string sayHello();        // This line is an operation statement.
    oneway void shutdown();   // This line is another
  };
};
The interface definition for our little "Hello World" application is now complete.

Mapping Hello.idl to Java

The tool idlj reads OMG IDL files and creates the required Java files. The idlj compiler defaults to generating only the client-side bindings. If you need both client-side bindings and server-side skeletons (as you do for our "Hello World" program), you must use the -fall option when running the idlj compiler. For more information on compiler options, see IDL-to-Java compiler options.

The default server-side mapping generated when either the -fall or -fserver arguments are used conform to Chapter 11, Portable Object Adapter (POA) of the CORBA 2.3.1 Specification (formal/99-10-07). For more information on the POA, see Portable Object Adapter.

The advantages of using the Portable Object Adaptor (POA) are:

  • Allow programmers to construct object implementations that are portable between different ORB products.
  • Provide support for objects with persistent identities.
  • Provide support for transparent activation of objects.
  • Allow a single servant to support multiple object identities simultaneously.
  1. Make sure that the jdk/bin directory (or the directory containing idlj, java, javac, and orbd) are in your path.
  2. Go to a command line prompt.
  3. Change to the directory containing your Hello.idl file.
  4. Enter the compiler command:

        idlj -fall Hello.idl

If you list the contents of the directory, you will see that a directory called HelloApp has been created and that it contains six files. Open Hello.java in your text editor. Hello.java is the signature interface and is used as the signature type in method declarations when interfaces of the specified type are used in other interfaces. It looks like this:

//Hello.java
package HelloApp;

/**
* HelloApp/Hello.java
* Generated by the IDL-to-Java compiler (portable), version "3.0"
* from Hello.idl
*/

public interface Hello extends HelloOperations, org.omg.CORBA.Object,
org.omg.CORBA.portable.IDLEntity
{
} // interface Hello

With an interface this simple, it is easy to see how the IDL statements map to the generated Java statements.

IDL Statement | Java Statement
module HelloApp | package HelloApp;
interface Hello | public interface Hello

The single surprising item is the extends statement. All CORBA objects are derived from org.omg.CORBA.Object to ensure required CORBA functionality. The required code is generated by idlj; you do not need to do any mapping yourself.

In previous versions of the idlj compiler (known as idltojava), the operations defined on the IDL interface would exist in this file as well. Starting with J2SDK v1.3.0, in conformance with the CORBA 2.3.1 Specification (formal/99-10-07), the IDL-to-Java mapping puts all of the operations defined on the IDL interface in the operations interface, HelloOperations.java. The operations interface is used in the server-side mapping and as a mechanism for providing optimized calls for co-located clients and servers. For Hello.idl, this file looks like this:

//HelloOperations.java
package HelloApp;

/**
* HelloApp/HelloOperations.java
* Generated by the IDL-to-Java compiler (portable), version "3.0"
* from Hello.idl
*/

public interface HelloOperations
{
  String sayHello ();
  void Shutdown ();
} // interface HelloOperations

Because there are only two operations defined in this interface, it is easy to see how the IDL statements map to the generated Java statements.

IDL Statement | Java Statement
string sayHello(); | String sayHello();
oneway void shutdown(); | void Shutdown ();

Understanding the idlj Compiler Output

The idlj compiler generates a number of files. The actual number of files generated depends on the options selected when the IDL file is compiled. The generated files provide standard functionality, so you can ignore them until it is time to deploy and run your program. Under J2SE v.1.4, the files generated by the idlj compiler for Hello.idl, with the -fall command line option, are:

  • HelloPOA.java

    This abstract class is the stream-based server skeleton, providing basic CORBA functionality for the server. It extends org.omg.PortableServer.Servant, and implements the InvokeHandler interface and the HelloOperations interface. The server class, HelloServant, extends HelloPOA.

  • _HelloStub.java

    This class is the client stub, providing CORBA functionality for the client. It extends org.omg.CORBA.portable.ObjectImpl and implements the Hello.java interface.

  • Hello.java

    This interface contains the Java version of our IDL interface. The Hello.java interface extends org.omg.CORBA.Object, providing standard CORBA object functionality. It also extends the HelloOperations interface and org.omg.CORBA.portable.IDLEntity.

  • HelloHelper.java

    This class provides auxiliary functionality, notably the narrow() method required to cast CORBA object references to their proper types. The Helper class is responsible for reading and writing the data type to CORBA streams, and inserting and extracting the data type from Anys. The Holder class delegates to the methods in the Helper class for reading and writing.

  • HelloHolder.java

    This final class holds a public instance member of type Hello. Whenever the IDL type is an out or an inout parameter, the Holder class is used. It provides operations for org.omg.CORBA.portable.OutputStream and org.omg.CORBA.portable.InputStream arguments, which CORBA allows, but which do not map easily to Java's semantics. The Holder class delegates to the methods in the Helper class for reading and writing. It implements org.omg.CORBA.portable.Streamable.

  • HelloOperations.java

    This interface contains the methods sayHello() and shutdown(). The IDL-to-Java mapping puts all of the operations defined on the IDL interface into this file, which is shared by both the stubs and skeletons.

When you write the IDL interface, you do all the programming required to generate all these files for your distributed application. The next steps are to implement the client and server classes. In the steps that follow, you will create the HelloClient.java client class and the HelloServer.java server class.

Troubleshooting

  • Error Message: "idlj" not found

    If you try to run idlj on the file Hello.idl and the system cannot find idlj, it is most likely not in your path. Make certain that the location of idlj (the JDK bin directory) is in your path, and try again.

For More Information

  • IDL to Java Language Mapping Overview

    Provides the basics for mapping IDL constructs to the corresponding Java statements.

  • Chapter 3 of the OMG CORBA 2.3.1 specification, formal/99-10-07

    Provides the complete specification for OMG Interface Definition Language. The specification can be downloaded from formal/99-10-07.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Getting Started with Java IDL: Developing the Hello World Server

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Getting Started with Java IDL:
Developing the Hello World Server

The example server consists of two classes, the servant and the server. The servant, HelloImpl, is the implementation of the Hello IDL interface; each Hello instance is implemented by a HelloImpl instance. The servant is a subclass of HelloPOA, which is generated by the idlj compiler from the example IDL.

The servant contains one method for each IDL operation, in this example, the sayHello() and shutdown() methods. Servant methods are just like ordinary Java methods; the extra code to deal with the ORB, with marshaling arguments and results, and so on, is provided by the skeleton.

The server class has the server's main() method, which:

  • Creates and initializes an ORB instance
  • Gets a reference to the root POA and activates the POAManager
  • Creates a servant instance (the implementation of one CORBA Hello object) and tells the ORB about it
  • Gets a CORBA object reference for a naming context in which to register the new CORBA object
  • Gets the root naming context
  • Registers the new object in the naming context under the name "Hello"
  • Waits for invocations of the new object from the client

This lesson introduces the basics of writing a CORBA server. For an example of the "Hello World" program with a persistent object server, see Example 2: Hello World with Persistent State. For more discussion of CORBA servers, see Developing Servers.

The steps in this lesson cover:

  1. Creating HelloServer.java
  2. Understanding HelloServer.java
  3. Compiling the Hello World Server

Creating HelloServer.java

To create HelloServer.java,

  1. Start your text editor and create a file named HelloServer.java in your main project directory, Hello.
  2. Enter the following code for HelloServer.java in the text file. The following section, Understanding HelloServer.java, explains each line of code in some detail.
    // HelloServer.java
import HelloApp.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;
import org.omg.PortableServer.*;
import org.omg.PortableServer.POA;

import java.util.Properties;

class HelloImpl extends HelloPOA {
  private ORB orb;

  public void setORB(ORB orb_val) {
    orb = orb_val;
  }

  // implement sayHello() method
  public String sayHello() {
    return "\nHello world !!\n";
  }

  // implement shutdown() method
  public void shutdown() {
    orb.shutdown(false);
  }
}

public class HelloServer {

  public static void main(String args[]) {
    try{
      // create and initialize the ORB
      ORB orb = ORB.init(args, null);

      // get reference to rootpoa & activate the POAManager
      POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
      rootpoa.the_POAManager().activate();

      // create servant and register it with the ORB
      HelloImpl helloImpl = new HelloImpl();
      helloImpl.setORB(orb);

      // get object reference from the servant
      org.omg.CORBA.Object ref = rootpoa.servant_to_reference(helloImpl);
      Hello href = HelloHelper.narrow(ref);

      // get the root naming context
      org.omg.CORBA.Object objRef =
          orb.resolve_initial_references("NameService");
      // Use NamingContextExt which is part of the Interoperable
      // Naming Service (INS) specification.
      NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

      // bind the Object Reference in Naming
      String name = "Hello";
      NameComponent path[] = ncRef.to_name( name );
      ncRef.rebind(path, href);

      System.out.println("HelloServer ready and waiting ...");

      // wait for invocations from clients
      orb.run();
    }

      catch (Exception e) {
        System.err.println("ERROR: " + e);
        e.printStackTrace(System.out);
      }

      System.out.println("HelloServer Exiting ...");

  }
}

  3. Save and close HelloServer.java.

Understanding HelloServer.java

This section explains each line of HelloServer.java, describing what the code does, as well as why it is needed for this application.

Performing Basic Setup

The structure of a CORBA server program is the same as most Java applications: You import required library packages, declare the server class, define a main() method, and handle exceptions.

Importing Required Packages

First, we import the packages required for the server class:

// The package containing our stubs
import HelloApp.*;

// HelloServer will use the naming service
import org.omg.CosNaming.*;

// The package containing special exceptions thrown by the name service
import org.omg.CosNaming.NamingContextPackage.*;

// All CORBA applications need these classes
import org.omg.CORBA.*;

// Classes needed for the Portable Server Inheritance Model
import org.omg.PortableServer.*;
import org.omg.PortableServer.POA;

// Properties to initiate the ORB
import java.util.Properties;

Defining the Servant Class

In this example, we are defining the class for the servant object within HelloServer.java, but outside the HelloServer class.

class HelloImpl extends HelloPOA
{
  // The sayHello() and shutdown() methods go here.
}

The servant is a subclass of HelloPOA so that it inherits the general CORBA functionality generated for it by the compiler.

First, we create a private variable, orb that is used in the setORB(ORB) method. The setORB method is a private method defined by the application developer so that they can set the ORB value with the servant. This ORB value is used to invoke shutdown() on that specific ORB in response to the shutdown() method invocation from the client.

  private ORB orb;

  public void setORB(ORB orb_val) {
    orb = orb_val;
  }

Next, we declare and implement the required sayHello() method:

  public String sayHello()
  {
    return "\nHello world!!\n";
  }

And last of all, we implement the shutdown() method in a similar way. The shutdown() method calls the org.omg.CORBA.ORB.shutdown(boolean) method for the ORB. The shutdown(false) operation indicate that the ORB should shut down immediately, without waiting for processing to complete.

  public void shutdown() {
    orb.shutdown(false);
  }

Declaring the Server Class

The next step is to declare the server class:

public class HelloServer
{
  // The main() method goes here.
}

Defining the main() Method

Every Java application needs a main method. It is declared within the scope of the HelloServer class:

  public static void main(String args[])
  {
    // The try-catch block goes here.
  }

Handling CORBA System Exceptions

Because all CORBA programs can throw CORBA system exceptions at runtime, all of the main() functionality is placed within a try-catch block. CORBA programs throw runtime exceptions whenever trouble occurs during any of the processes (marshaling, unmarshaling, upcall) involved in invocation. The exception handler simply prints the exception and its stack trace to standard output so you can see what kind of thing has gone wrong.

The try-catch block is set up inside main(), as shown:

    try{

      // The rest of the HelloServer code goes here.

    } catch(Exception e) {
        System.err.println("ERROR: " + e);
        e.printStackTrace(System.out);
      }

Creating and Initializing an ORB Object

A CORBA server needs a local ORB object, as does the CORBA client. Every server instantiates an ORB and registers its servant objects so that the ORB can find the server when it receives an invocation for it.

The ORB variable is declared and initialized inside the try-catch block.

      ORB orb = ORB.init(args, null);

The call to the ORB's init() method passes in the server's command line arguments, allowing you to set certain properties at runtime.

Get a Reference to the Root POA and Activate the POAManager

The ORB obtains the initial object references to services such as the Name Service using the method resolve_initial_references.

The reference to the root POA is retrieved and the POAManager is activated from within the try-catch block.

      POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
      rootpoa.the_POAManager().activate();

The activate() operation changes the state of the POA manager to active, causing associated POAs to start processing requests. The POA manager encapsulates the processing state of the POAs with which it is associated. Each POA object has an associated POAManager object. A POA manager may be associated with one or more POA objects.

Managing the Servant Object

A server is a process that instantiates one or more servant objects. The servant inherits from the interface generated by idlj and actually performs the work of the operations on that interface. Our HelloServer needs a HelloImpl.

Instantiating the Servant Object

We instantiate the servant object inside the try-catch block, just after activating the POA manager, as shown:

      HelloImpl helloImpl = new HelloImpl();

The section of code describing the servant class was explained previously.

In the next line of code, setORB(orb) is defined on the servant so that ORB.shutdown() can be called as part of the shutdown operation. This step is required because of the shutdown() method defined in Hello.idl.

      helloImpl.setORB(orb);

There are other options for implementing the shutdown operation. In this example, the shutdown() method called on the Object takes care of shutting down an ORB. In another implementation, the shutdown method implementation could have simply set a flag, which the server could have checked and called shutdown().

The next set of code is used to get the object reference associated with the servant. The narrow() method is required to cast CORBA object references to their proper types.

      org.omg.CORBA.Object ref = rootpoa.servant_to_reference(helloImpl);
      Hello href = HelloHelper.narrow(ref);

Working with COS Naming

The HelloServer works with the Common Object Services (COS) Naming Service to make the servant object's operations available to clients. The server needs an object reference to the naming service so that it can publish the references to the objects implementing various interfaces. These object references are used by the clients for invoking methods. Another way a servant can make the objects available to clients for invocations is by stringifying the object references to a file.

The two options for Naming Services shipped with J2SE v.1.4 are:

  • orbd, which includes both a Transient Naming Service and a Persistent Naming Service, in addition to a Server Manager.
  • tnameserv - a Transient Naming Service.

This example uses orbd.

Obtaining the Initial Naming Context

In the try-catch block, below getting the object reference for the servant, we call orb.resolve_initial_references() to get an object reference to the name server:

      org.omg.CORBA.Object objRef =
          orb.resolve_initial_references("NameService");

The string "NameService" is defined for all CORBA ORBs. When you pass in that string, the ORB returns a naming context object that is an object reference for the name service. The string "NameService" indicates:

  • The naming service will be persistent when using ORBD's naming service, as we do in this example.
  • The naming service will be transient when using tnameserv.

The proprietary string "TNameService" indicates that the naming service will be transient when using ORBD's naming service.

Narrowing the Object Reference

As with all CORBA object references, objRef is a generic CORBA object. To use it as a NamingContextExt object, you must narrow it to its proper type. The call to narrow() is just below the previous statement:

      NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

Here you see the use of an idlj-generated helper class, similar in function to HelloHelper. The ncRef object is now an org.omg.CosNaming.NamingContextExt and you can use it to access the naming service and register the server, as shown in the next topic.

The NamingContextExt object is part of the Interoperable Naming Service specification.

Registering the Servant with the Name Server

Just below the call to narrow(), we create a new NameComponent array. Because the path to Hello has a single element, we create the single-element array that NamingContext.resolve requires for its work:

      String name = "Hello";
      NameComponent path[] = ncRef.to_name( name );

Finally, we pass path and the servant object to the naming service, binding the servant object to the "Hello" id:

      ncRef.rebind(path, href);

Now, when the client calls resolve("Hello") on the initial naming context, the naming service returns an object reference to the Hello servant.

Waiting for Invocation

The previous sections describe the code that makes the server ready; the next section explains the code that enables it to simply wait around for a client to request its service. The following code, which is at the end of (but within) the try-catch block, shows how to accomplish this.

      orb.run();

When called by the main thread, ORB.run() enables the ORB to perform work using the main thread, waiting until an invocation comes from the ORB. Because of its placement in main(), after an invocation completes and sayHello() returns, the server will wait again. This is the reason that the HelloClient explicitly shuts down the ORB after completing its task.

Compiling the Hello World Server

Now we will compile the HelloServer.java so that we can correct any errors before continuing with this tutorial.

Windows users note that you should substitute backslashes (\) for the slashes (/) in all paths in this document.

To compile HelloServer.java,

  1. Change to the Hello directory.
  2. Run the Java compiler on HelloServer.java:
    javac HelloServer.java HelloApp/*.java
  3. Correct any errors in your file and recompile if necessary.
  4. The files HelloServer.class and HelloImpl.class are generated in the Hello directory.

Running the Hello World Server

Running the Hello World Application discusses running HelloServer and the rest of the application.

Understanding The Server-Side Implementation Models

CORBA supports at least two different server-side mappings for implementing an IDL interface:

  • The Inheritance Model

    Using the Inheritance Model, you implement the IDL interface using an implementation class that also extends the compiler-generated skeleton.

    Inheritance models include:

    • The OMG-standard, POA. Given an interface My defined in My.idl, the file MyPOA.java is generated by the idlj compiler. You must provide the implementation for My and it must inherit from MyPOA, a stream-based skeleton that extends org.omg.PortableServer.Servant, which serves as the base class for all POA servant implementations.

      The default server-side mapping generated when either the -fall or -fserver arguments are used conform to Chapter 11, Portable Object Adapter (POA) of the CORBA 2.3.1 Specification (formal/99-10-07). For more information on the POA, see Portable Object Adapter.

      The advantages of using the Portable Object Adaptor (POA) are:

      • Allow programmers to construct object implementations that are portable between different ORB products.
      • Provide support for objects with persistent identities.
      • Provide support for transparent activation of objects.
      • Allow a single servant to support multiple object identities simultaneously.
    • ImplBase. Given an interface My defined in My.idl, the file _MyImplBase.java is generated. You must provide the implementation for My and it must inherit from _MyImplBase.

      NOTE: ImplBase is obsoleted in favor of the POA model, but is provided to allow compatibility with servers written in J2SE 1.3 and prior. We do not recommend creating new servers using this nonstandard model.

  • The Delegation Model

    Using the Delegation Model, you implement the IDL interface using two classes:

    • An IDL-generated Tie class that inherits from the compiler-generated skeleton, but delegates all calls to an implementation class.
    • A class that implements the IDL-generated operations interface (such as HelloOperations), which defines the IDL function.

    The Delegation model is also known as the Tie model, or the Tie Delegation model. It inherits from either the POA or ImplBase compiler-generated skeleton, so the models will be described as POA/Tie or ImplBase/Tie models in this document.

This tutorial presents the POA Inheritance model for server-side implementation. For tutorials using the other server-side implementations, see the following documents:

  • Java IDL: The "Hello World" Example with the POA/Tie Server-Side Model

    You might want to use the Tie model instead of the typical Inheritance model if your implementation must inherit from some other implementation. Java allows any number of interface inheritance, but there is only one slot for class inheritance. If you use the inheritance model, that slot is used up . By using the Tie Model, that slot is freed up for your own use. The drawback is that it introduces a level of indirection: one extra method call occurs when invoking a method.

  • Java IDL: The "Hello World" Example with the ImplBase Server-Side Model

    The ImplBase server-side model is an Inheritance Model, as is the POA model. Use the idlj compiler with the -oldImplBase flag to generate server-side bindings that are compatible with older version of Java IDL (prior to J2SE 1.4).

    Note that using the -oldImplBase flag is non-standard: these APIs are obsoleted. You would use this flag ONLY for compatibility with existing servers written in J2SE 1.3 or earlier. In that case, you would need to modify an existing MAKEFILE to add the -oldImplBase flag to the idlj compiler, otherwise POA-based server-side mappings will be generated.

For More Information

Exceptions: System Exceptions
Explains how CORBA system exceptions work and provides details on the minor codes of Java IDL's system exceptions
Developing Servers
Covers topics of interest to CORBA server programmers
Java IDL Naming Service
Covers the COS Naming Service in greater detail
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Getting Started with Java IDL: Using Stringified Object References

This document was not updated for this release.

To invoke an operation on a CORBA object, a client application needs a reference to the object. You can get such references in a number of ways, such as calling ORB.resolve_initial_references() or using another CORBA object (like the name service). In previous sections of this tutorial, you used both of these methods to get an initial object reference.

Often, however, there is no naming service available in the distributed environment. In that situation, CORBA clients use a stringified object reference to find their first object.

When updated, this lesson will teach you how to create a stringified object reference as a part of the server startup, and how the client gets that reference and destringifies it for use as a real object reference.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.security.jgss.GSSUtil (Java GSS-API Utilities b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java GSS-API Utilities
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.jgss.GSSUtil

No usage of com.sun.security.jgss.GSSUtil
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java GSS-API Utilities
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2000, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.net.httpserver.Headers (Java HTTP Server b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.net.httpserver.Headers

  • Packages that use Headers
    Package Description
    com.sun.net.httpserver
    Provides a simple high-level Http server API, which can be used to build embedded HTTP servers.

    • Uses of Headers in com.sun.net.httpserver

      Methods in com.sun.net.httpserver that return Headers
      Modifier and Type Method and Description
      abstract Headers HttpExchange.getRequestHeaders()
      Returns an immutable Map containing the HTTP headers that were included with this request.
      abstract Headers HttpExchange.getResponseHeaders()
      Returns a mutable Map into which the HTTP response headers can be stored and which will be transmitted as part of this response.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Java VisualVM

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java VisualVM - Browsing a Heap Dump

You can use Java VisualVM to browse the contents of a heap dump file and quickly see the allocated objects in the heap. Heap dumps are displayed in the heap dump sub-tab in the main window. You can open binary format heap dump files (.hprof) saved on your local system or use Java VisualVM to take heap dumps of running applications.

A heap dump is a snapshot of all the objects in the Java Virtual Machine (JVM) heap at a certain point in time. The JVM software allocates memory for objects from the heap for all class instances and arrays. The garbage collector reclaims the heap memory when an object is no longer needed and there are no references to the object. By examining the heap you can locate where objects are created and find the references to those objects in the source. If the JVM software is failing to remove unneeded objects from the heap, Java VisualVM can help you locate the nearest garbage collecting root for the object.

Opening a Heap Dump File

If you have a heap dump file saved on your local system, you can open the file in Java VisualVM by choosing File > Load from the main menu. Java VisualVM can open heap dumps saved in the .hprof file format. When you open a saved heap dump, the heap dump opens as a tab in the main window.

Taking a Heap Dump

You can use Java VisualVM to take a heap dump of a local running application. When you use Java VisualVM to take a heap dump, the file is only temporary until you explicitly save it. If you do not save the file, the file will be deleted when the application terminates.

You can take a heap dump by doing either of the following:

  • Right-click the application in the Applications window and choose Heap Dump.
  • Click Heap Dump in the Monitor tab of the application.

Heap dumps for a local application open as sub-tabs in the application's tab. The heap dump also appears as a time-stamped heap dump node under the application node in the Applications window. To save a heap dump to your local system, right-click the heap dump in the Applications window and choose Save As.

Browsing a Heap Dump

Java VisualVM enables you to visually browse heap dumps in the following views:

Summary View

When you open a heap dump, Java VisualVM displays the Summary view by default. The Summary view displays the running environment where the heap dump was taken and other system properties.

screenshot of Summary view of heap dump

Classes View

The Classes view displays a list of classes and the number and percentage of instances referenced by that class. You can view a list of the instances of a specific class by right-clicking the name and choosing Show in Instances View.

You can sort how results are displayed by clicking a column heading. You can use the filter below the list to filter the classes by name or limit the displayed results to sub-classes of a class by right-clicking a class name and choosing Show Only Subclasses.

screenshot of Classes view of heap dump

Instances View

The Instance view displays object instances for a selected class. When you select an instance from the Instance pane, Java VisualVM displays the fields of that class and references to that class in the respective panes. In the References pane, you can right-click an item and choose Show Nearest GC Root to display the nearest garbage collection root object.

screenshot of Instances view of heap dump
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Getting Started Using Java RMI

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Getting Started Using Java™ RMI

This tutorial shows you the steps to follow to create a distributed version of the classic Hello World program using Java™ Remote Method Invocation (Java RMI). While you work through this example, you will probably come up with a number of related questions. You are encouraged to look for answers in the Java RMI FAQ and the archives of the RMI-USERS mailing list. If you'd like to subscribe to the RMI-USERS mailing list, click here.

The distributed Hello World example uses a simple client to make a remote method invocation to a server which may be running on a remote host. The client receives the "Hello, world!" message from the server.

This tutorial has the following steps:

  • Define the remote interface
  • Implement the server
  • Implement the client
  • Compile the source files
  • Start the Java RMI registry, server, and client
The files needed for this tutorial are:
  • Hello.java - a remote interface
  • Server.java - a remote object implementation that implements the remote interface
  • Client.java - a simple client that invokes a method of the remote interface
Note: For the remainder of this tutorial, the terms "remote object implementation" and "implementation class" are used interchangeably to refer to the class example.hello.Server, which implements a remote interface.

Define the remote interface

A remote object is an instance of a class that implements a remote interface. A remote interface extends the interface java.rmi.Remote and declares a set of remote methods. Each remote method must declare java.rmi.RemoteException (or a superclass of RemoteException) in its throws clause, in addition to any application-specific exceptions.

Here is the interface definition for the remote interface used in this example, example.hello.Hello. It declares just one method, sayHello, which returns a string to the caller:

package example.hello;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Hello extends Remote {
    String sayHello() throws RemoteException;
}
Remote method invocations can fail in many additional ways compared to local method invocations (such as network-related communication problems and server problems), and remote methods will report such failures by throwing a java.rmi.RemoteException. For more information about the issues of failure and recovery in distributed systems, see A Note on Distributed Computing.

Implement the server

A "server" class, in this context, is the class which has a main method that creates an instance of the remote object implementation, exports the remote object, and then binds that instance to a name in a Java RMI registry. The class that contains this main method could be the implementation class itself, or another class entirely.

In this example, the main method for the server is defined in the class Server which also implements the remote interface Hello. The server's main method does the following:

  • Create and export a remote object
  • Register the remote object with a Java RMI registry
Here is the source code for the class Server. Descriptions for writing this server class follow the source code:
package example.hello;

import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class Server implements Hello {

    public Server() {}

    public String sayHello() {
        return "Hello, world!";
    }

    public static void main(String args[]) {

        try {
            Server obj = new Server();
            Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);

            // Bind the remote object's stub in the registry
            Registry registry = LocateRegistry.getRegistry();
            registry.bind("Hello", stub);

            System.err.println("Server ready");
        } catch (Exception e) {
            System.err.println("Server exception: " + e.toString());
            e.printStackTrace();
        }
    }
}

The implementation class Server implements the remote interface Hello, providing an implementation for the remote method sayHello. The method sayHello does not need to declare that it throws any exception because the method implementation itself does not throw RemoteException nor does it throw any other checked exceptions.

Note: A class can define methods not specified in the remote interface, but those methods can only be invoked within the virtual machine running the service and cannot be invoked remotely.

Create and export a remote object

The main method of the server needs to create the remote object that provides the service. Additionally, the remote object must be exported to the Java RMI runtime so that it may receive incoming remote calls. This can be done as follows:
Server obj = new Server();
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);
The static method UnicastRemoteObject.exportObject exports the supplied remote object to receive incoming remote method invocations on an anonymous TCP port and returns the stub for the remote object to pass to clients. As a result of the exportObject call, the runtime may begin to listen on a new server socket or may use a shared server socket to accept incoming remote calls for the remote object. The returned stub implements the same set of remote interfaces as the remote object's class and contains the host name and port over which the remote object can be contacted.

Note: As of the J2SE 5.0 release, stub classes for remote objects no longer need to be pregenerated using the rmic stub compiler, unless the remote object needs to support clients running in pre-5.0 VMs. If your application needs to support such clients, you will need to generate stub classes for the remote objects used in the application and deploy those stub classes for clients to download. For details on how to generate stub classes, see the tools documentation for rmic [Solaris, Windows]. For details on how to deploy your application along with pregenerated stub classes, see the codebase tutorial.

Register the remote object with a Java RMI registry

For a caller (client, peer, or applet) to be able to invoke a method on a remote object, that caller must first obtain a stub for the remote object. For bootstrapping, Java RMI provides a registry API for applications to bind a name to a remote object's stub and for clients to look up remote objects by name in order to obtain their stubs.

A Java RMI registry is a simplified name service that allows clients to get a reference (a stub) to a remote object. In general, a registry is used (if at all) only to locate the first remote object a client needs to use. Then, typically, that first object would in turn provide application-specific support for finding other objects. For example, the reference can be obtained as a parameter to, or a return value from, another remote method call. For a discussion on how this works, please take a look at Applying the Factory Pattern to Java RMI.

Once a remote object is registered on the server, callers can look up the object by name, obtain a remote object reference, and then invoke remote methods on the object.

The following code in the server obtains a stub for a registry on the local host and default registry port and then uses the registry stub to bind the name "Hello" to the remote object's stub in that registry:

Registry registry = LocateRegistry.getRegistry();
registry.bind("Hello", stub);
The static method LocateRegistry.getRegistry that takes no arguments returns a stub that implements the remote interface java.rmi.registry.Registry and sends invocations to the registry on server's local host on the default registry port of 1099. The bind method is then invoked on the registry stub in order to bind the remote object's stub to the name "Hello" in the registry.

Note: The call to LocateRegistry.getRegistry simply returns an appropriate stub for a registry. The call does not check to see if a registry is actually running. If no registry is running on TCP port 1099 of the local host when the bind method is invoked, the server will fail with a RemoteException.

Implement the client

The client program obtains a stub for the registry on the server's host, looks up the remote object's stub by name in the registry, and then invokes the sayHello method on the remote object using the stub.

Here is the source code for the client:

package example.hello;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Client {

    private Client() {}

    public static void main(String[] args) {

        String host = (args.length < 1) ? null : args[0];
        try {
            Registry registry = LocateRegistry.getRegistry(host);
            Hello stub = (Hello) registry.lookup("Hello");
            String response = stub.sayHello();
            System.out.println("response: " + response);
        } catch (Exception e) {
            System.err.println("Client exception: " + e.toString());
            e.printStackTrace();
        }
    }
}

This client first obtains the stub for the registry by invoking the static LocateRegistry.getRegistry method with the hostname specified on the command line. If no hostname is specified, then null is used as the hostname indicating that the local host address should be used.

Next, the client invokes the remote method lookup on the registry stub to obtain the stub for the remote object from the server's registry.

Finally, the client invokes the sayHello method on the remote object's stub, which causes the following actions to happen:

  • The client-side runtime opens a connection to the server using the host and port information in the remote object's stub and then serializes the call data.
  • The server-side runtime accepts the incoming call, dispatches the call to the remote object, and serializes the result (the reply string "Hello, world!") to the client.
  • The client-side runtime receives, deserializes, and returns the result to the caller.

The response message returned from the remote invocation on the remote object is then printed to System.out.

Compile the source files

The source files for this example can be compiled as follows:

javac -d destDir Hello.java Server.java Client.java
where destDir is the destination directory to put the class files in.

Note: If the server needs to support clients running on pre-5.0 VMs, then a stub class for the remote object implementation class needs to be pregenerated using the rmic compiler, and that stub class needs to be made available for clients to download. See the codebase tutorial for more details.

Start the Java RMI registry, server, and client

To run this example, you will need to do the following:

  • Start the Java RMI registry
  • Start the server
  • Run the client

Start the Java RMI registry

To start the registry, run the rmiregistry command on the server's host. This command produces no output (when successful) and is typically run in the background. For more information, see the tools documentation for rmiregistry [Solaris, Windows].

For example, on the Solaris(tm) Operating System:

rmiregistry &

Or, on Windows platforms:

start rmiregistry

By default, the registry runs on TCP port 1099. To start a registry on a different port, specify the port number from the command line. For example, to start the registry on port 2001 on a Windows platform:

start rmiregistry 2001

If the registry will be running on a port other than 1099, you'll need to specify the port number in the calls to LocateRegistry.getRegistry in the Server and Client classes. For example, if the registry is running on port 2001 in this example, the call to getRegistry in the server would be:

Registry registry = LocateRegistry.getRegistry(2001);

Start the server

To start the server, run the Server class using the java command as follows:

On the Solaris Operating System:

java -classpath classDir -Djava.rmi.server.codebase=file:classDir/ example.hello.Server &

On Windows platforms:

start java -classpath classDir -Djava.rmi.server.codebase=file:classDir/ example.hello.Server

where classDir is the root directory of the class file tree (see destDir in the section "Compiling the source files"). Setting the java.rmi.server.codebase system property ensures that the registry can load the remote interface definition (note that the trailing slash is important); for more information about using this property, see the codebase tutorial.

The output from the server should look like this:

Server ready

The server remains running until the process is terminated by the user (typically by killing the process).

Run the client

Once the server is ready, the client can be run as follows:

java  -classpath classDir example.hello.Client

where classDir is the root directory of the class file tree (see destDir in the section "Compiling the source files").

The output from the client is the following message:

response: Hello, world!

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Design of Shutdown Hooks API

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Design of the Shutdown Hooks API

The following Q&A addresses some of the design issues of the Shutdown Hooks API.

Isn't this what runFinalizersOnExit is for?

You can use the Runtime.runFinalizersOnExit method, or the equivalent method in the System class, to schedule actions to take place when the VM shuts down due to exit. This technique does not, however, work for termination-triggered shutdowns. It is also is inherently unsafe, and in fact these methods were deprecated in version 1.2 of the JavaTM 2 Platform.

Why don't you provide information as to why the VM is shutting down?

On some platforms a native process can't distinguish a shutdown due to exit from a shutdown due to termination. Other platforms provide much richer capabilities, in some cases including notification of system suspension and restart or of imminent power failure. In short, it's impossible to generalize such information in a portable way.

Will shutdown hooks be run if the VM crashes?

If the VM crashes due to an error in native code then no guarantee can be made about whether or not the hooks will be run.

Why are shutdown hooks run concurrently? Wouldn't it make more sense to run them in reverse order of registration?

Invoking shutdown hooks in their reverse order of registration is certainly intuitive, and is in fact how the C runtime library's atexit procedure works. This technique really only makes sense, however, in a single-threaded system. In a multi-threaded system such as Java platform the order in which hooks are registered is in general undetermined and therefore implies nothing about which hooks ought to be run before which other hooks. Invoking hooks in any particular sequential order also increases the possibility of deadlocks. Note that if a particular subsystem needs to invoke shutdown actions in a particular order then it is free to synchronize them internally.

Why are hooks just threads, and unstarted ones at that? Wouldn't it be simpler to use Runnable objects, or Beans-style event and listener patterns?

The approach taken here has two advantages over the more obvious, and more frequently suggested, callback-oriented designs based upon Runnable objects or Beans-style event listeners.

First, it gives the user complete control over the thread upon which a shutdown action is executed. The thread can be created in the proper thread group, given the correct priority, context, and privileges, and so forth.

Second, it simplifies both the specification and the implementation by isolating the VM from the hooks themselves. If shutdown actions were executed as callbacks then a robust implementation would wind up having to create a separate thread for each hook anyway in order for them to run concurrently. The specification would also have to include explicit language about how the threads that execute the callbacks are created.

Aren't threads pretty expensive things to keep around, especially if they won't be started until the VM shuts down?

Most implementations of the Java platform don't actually allocate resources to a thread until it's started, so maintaining a set of unstarted threads is actually very cheap. If you look at the internals of java.lang.Thread you can see that its various constructors just do security checks and initialize private fields. The native start() method does the real work of allocating a thread stack, etc., to get things going.

What about Personal and Embedded Java? Won't starting threads during shutdown be too expensive on those platforms?

This API may not be suitable for the smaller Java platforms. Threads in the Java 2 Platform carry more information than threads in JDK 1.1 and p/eJava. A thread has a class loader, it may have some inherited thread-local variables, and, in the case of GUI apps, it may be associated with a specific application context. Threads will come to carry even more information as the platform evolves; for example, the security team is planning to introduce a notion of per-thread user identity in their upcoming authentication framework.

Because of all this contextual information, shutdown hooks would be harder to write and maintain if they were just Runnable objects or Beans-style event listeners. Suppose that a Runnable shutdown hook, or an equivalent event listener, needed a specific bit of thread-contextual information in order to carry out its operations. Such information could be saved in some shared location before the hook is registered. While this is merely awkward, suppose further that threads acquire some new type of contextual information in a future release. If an operation invoked by the hook also evolves to need that information then the code that registers the hook would have to be amended to save that information as well. Making hooks be threads instead of Runnables or event listeners insulates them from this sort of future change.

Okay, but won't I have to write a lot of code just to register a simple shutdown hook?

No. Simple shutdown hooks can often be written as anonymous inner classes, as in this example:
Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() { database.close(); }
});
This idiom is fine as long as you'll never need to cancel the hook, in which case you'd need to save a reference to the hook when you create it.

What about security? Can an untrusted applet register a shutdown hook?

If there is a security manager installed then the addShutdownHook and removeShutdownHook methods check that the caller's security context permits RuntimePermission("shutdownHooks"). An untrusted applet will not have this permission, and will therefore not be able to register or de-register a shutdown hook.

What happens if a shutdown hook throws an exception and the exception is not caught?

Uncaught exceptions are handled in shutdown hooks just as in any other thread, by invoking the uncaughtException method of the thread's ThreadGroup object. The default implementation of this method prints the exception's stack trace to System.err and terminates the thread. Note that uncaught exceptions do not cause the VM to exit; this happens only when all non-daemon threads have finished or when the Runtime.exit method is invoked.

Why did you add the Runtime.halt method? Isn't it pretty dangerous?

The new halt method is certainly powerful, and it should be used with the utmost caution. It's provided so that applications can insulate themselves from shutdown hooks that deadlock or run for inordinate amounts of time. It also allows applications to force a quick exit in situations where that is necessary.

What happens if finalization-on-exit is enabled? Will finalizers be run before, during, or after shutdown hooks?

Finalization-on-exit processing is done after all shutdown hooks have finished. Otherwise a hook may fail if some live objects are finalized prematurely.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.management.HotSpotDiagnosticMXBean (Monitoring and Management Interface for the Java Platform b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Monitoring and Management Interface for the Java Platform
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.management.HotSpotDiagnosticMXBean

No usage of com.sun.management.HotSpotDiagnosticMXBean
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Monitoring and Management Interface for the Java Platform
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2003, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


How to Implement a Provider

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

How to Implement a Provider in the Java Cryptography Architecture

  • Introduction
    • Who Should Read This Document
    • Related Documentation
      • Notes on Terminology
  • Engine Classes and Corresponding SPI Classes
  • Steps to Implement and Integrate a Provider
    • Step 1: Write your Service Implementation Code
      • Step 1.1: Additional JCA Provider Requirements and Recommendations for Encryption Implementations
    • Step 2: Give your Provider a Name
    • Step 3: Write your Master Class, a subclass of Provider
      • Step 3.1: Additional Steps for Cipher Implementations
    • Step 4: Compile your Code
    • Step 5: Place your Provider in a Jar File
    • Step 6: Optional -- Sign your JAR File
      • Step 6.1: Get a Code-Signing Certificate
      • Step 6.2: Sign Your Provider
    • Step 7: Prepare for Testing
      • Step 7.1: Install the Provider
      • Step 7.2: Set Provider Permissions
    • Step 8: Write and Compile your Test Programs
    • Step 9: Run your Test Programs
    • Step 10: Apply for U.S. Government Export Approval if Required
    • Step 11: Document your Provider and its Supported Services
      • Message Digests and MACs
    • Step 12: Make your Class Files and Documentation Available to Clients
  • How a Provider Can Do Self-Integrity Checking
    • Notes on the Sample Code
    • Finding the Provider JAR File: Basics
      • Determining the Provider's JAR File URL
      • Creating a JarFile Referring to the JAR File
    • Verifying the Provider JAR File: Basics
      • Verification Setup
      • JAR File Signature Check
      • Verifying Signatures
      • Ensuring Signers Are Trusted
        • Getting the List of Certificates
        • Identifying Each of the Signers and Determining If One is Trusted
    • Verifying Signatures
    • Ensuring Signers Are Trusted
      • Getting the List of Certificates
      • Identifying Each of the Signers and Determining If One is Trusted
      • Notes on myJCE Sample Code
  • Further Implementation Details and Requirements
    • Alias Names
    • Service Interdependencies
    • Default Initializations
    • Default Key Pair Generator Parameter Requirements
    • The Provider.Service Class
    • Signature Formats
    • DSA Interfaces and their Required Implementations
    • RSA Interfaces and their Required Implementations
    • Diffie-Hellman Interfaces and their Required Implementations
    • Interfaces for Other Algorithm Types
    • Algorithm Parameter Specification Interfaces and Classes
    • Key Specification Interfaces and Classes Required by Key Factories
    • Secret-Key Generation
    • Ensuring Exportability
  • Appendix A: The Sun Provider Master Class
  • Appendix B: The SunJCE Provider Master Class
  • Appendix C: The java.security Properties File

Introduction

The Java platform defines a set of APIs spanning major security areas, including cryptography, public key infrastructure, authentication, secure communication, and access control. These APIs allow developers to easily integrate security into their application code. They were designed around the following principles:

  1. Implementation independence

    Applications do not need to implement security themselves. Rather, they can request security services from the Java platform. Security services are implemented in providers (see below), which are plugged into the Java platform via a standard interface. An application may rely on multiple independent providers for security functionality.

  2. Implementation interoperability

    Providers are interoperable across applications. Specifically, an application is not bound to a specific provider, and a provider is not bound to a specific application.

  3. Algorithm extensibility

    The Java platform includes a number of built-in providers that implement a basic set of security services that are widely used today. However, some applications may rely on emerging standards not yet implemented, or on proprietary services. The Java platform supports the installation of custom providers that implement such services.

A Cryptographic Service Provider (provider) refers to a package (or a set of packages) that supply a concrete implementation of a subset of the cryptography aspects of the JDK Security API.

The java.security.Provider class encapsulates the notion of a security provider in the Java platform. It specifies the provider's name and lists the security services it implements. Multiple providers may be configured at the same time, and are listed in order of preference. When a security service is requested, the highest priority provider that implements that service is selected.

Figures 1 and 2 illustrate these options for requesting an MD5 message digest implementation. Both figures show three providers that implement message digest algorithms. The providers are ordered by preference from left to right (1-3). In Figure 1, an application requests an MD5 algorithm implementation without specifying a provider name. The providers are searched in preference order and the implementation from the first provider supplying that particular algorithm, ProviderB, is returned. In Figure 2, the application requests the MD5 algorithm implementation from a specific provider, ProviderC. This time the implementation from that provider is returned, even though a provider with a higher preference order, ProviderB, also supplies an MD5 implementation.

<Image of the General JCA Architecture>

Figure 1: Provider searching Figure 2: Specific provider requested

Figures 1 and 2 illustrate these options for requesting an MD5 message digest implementation. Both figures show three providers that implement message digest algorithms. The providers are ordered by preference from left to right (1-3). In Figure 1, an application requests an MD5 algorithm implementation without specifying a provider name. The providers are searched in preference order and the implementation from the first provider supplying that particular algorithm, ProviderB, is returned. In Figure 2, the application requests the MD5 algorithm implementation from a specific provider, ProviderC. This time the implementation from that provider is returned, even though a provider with a higher preference order, ProviderB, also supplies an MD5 implementation.

Each installation has one or more provider packages installed. Clients may configure their runtimes with different providers, and specify a preference order for each of them. The preference order is the order in which providers are searched for requested algorithms when no particular provider is requested.

Sun's version of the Java runtime environment comes standard with a default provider, named "SUN". Other Java runtime environments may not necessarily supply the "SUN" provider.

Who Should Read This Document

Programmers that only need to use the Java Security API to access existing cryptography algorithms and other services do not need to read this document.

This document is intended for experienced programmers wishing to create their own provider packages supplying cryptographic service implementations. It documents what you need to do in order to integrate your provider into Java so that your algorithms and other services can be found when Java Security API clients request them.

Related Documentation

This document assumes you have already read the Java Cryptography Architecture Reference Guide.

It documents the packages which contain the various classes and interfaces in the Security API.

  • java.security
  • java.security.spec
  • java.security.interfaces
  • javax.crypto
  • javax.crypto.spec
  • javax.crypto.interfaces

Notes on Terminology

  • Prior to JDK 1.4, the JCE was an unbundled product, and as such, the JCA and JCE were regularly referred to as separate, distinct components. As JCE is now bundled in JDK, the distinction is becoming less apparent. Since the JCE uses the same architecture as the JCA, the JCE should be more properly thought of as a subset of the JCA.
  • The JCA within the JDK includes two software components:
    • the framework that defines and supports cryptographic services for which providers supply implementations. This framework includes packages such as java.security, javax.crypto, javax.crypto.spec, and javax.crypto.interfaces.
    • the actual providers such as Sun, SunRsaSign, SunJCE, which contain the actual cryptographic implementations.

Throughout this document, the terms JCA by itself refers to the JCA framework. Whenever this document notes a specific JCA provider, it will be referred to explicitly by the provider name.

Engine Classes and Corresponding Service Provider Interface Classes

An engine class defines a cryptographic service in an abstract fashion (without a concrete implementation).

A cryptographic service is always associated with a particular algorithm or type. It either provides cryptographic operations (like those for digital signatures or message digests, ciphers or key agreement protocols); generates or supplies the cryptographic material (keys or parameters) required for cryptographic operations; or generates data objects (keystores or certificates) that encapsulate cryptographic keys (which can be used in a cryptographic operation) in a secure fashion.

For example, here are four engine classes:

  • The Signature class provides access to the functionality of a digital signature algorithm.
  • A DSA KeyFactory class supplies a DSA private or public key (from its encoding or transparent specification) in a format usable by the initSign or initVerify methods, respectively, of a DSA Signature object.
  • The Cipher class provides access to the functionality of an encryption algorithm (such as DES)
  • the KeyAgreement class provides access to the functionality of a key agreement protocol (such as Diffie-Hellman)

The Java Cryptography Architecture encompasses the classes comprising the Security package that relate to cryptography, including the engine classes. Users of the API request and utilize instances of the engine classes to carry out corresponding operations. The JDK defines the following engine classes:

  • MessageDigest - used to calculate the message digest (hash) of specified data.
  • Signature - used to sign data and verify digital signatures.
  • KeyPairGenerator - used to generate a pair of public and private keys suitable for a specified algorithm.
  • KeyFactory - used to convert opaque cryptographic keys of type Key into key specifications (transparent representations of the underlying key material), and vice versa.
  • KeyStore - used to create and manage a keystore. A keystore is a database of keys. Private keys in a keystore have a certificate chain associated with them, which authenticates the corresponding public key. A keystore also contains certificates from trusted entities.
  • CertificateFactory - used to create public key certificates and Certificate Revocation Lists (CRLs).
  • AlgorithmParameters - used to manage the parameters for a particular algorithm, including parameter encoding and decoding.
  • AlgorithmParameterGenerator - used to generate a set of parameters suitable for a specified algorithm.
  • SecureRandom - used to generate random or pseudo-random numbers.
  • Cipher: used to encrypt or decrypt some specified data.
  • KeyAgreement: used to execute a key agreement (key exchange) protocol between 2 or more parties.
  • KeyGenerator: used to generate a secret (symmetric) key suitable for a specified algorithm.
  • Mac: used to compute the message authentication code of some specified data.
  • SecretKeyFactory: used to convert opaque cryptographic keys of type SecretKey into key specifications (transparent representations of the underlying key material), and vice versa.
  • ExemptionMechanism: used to provide the functionality of an exemption mechanism such as key recovery, key weakening, key escrow, or any other (custom) exemption mechanism. Applications or applets that use an exemption mechanism may be granted stronger encryption capabilities than those which don't. However, please note that cryptographic restrictions are no longer required for most countries, and thus exemption mechanisms may only be useful in those few countries whose governments mandate restrictions.

Note: A generator creates objects with brand-new contents, whereas a factory creates objects from existing material (for example, an encoding).

An engine class provides the interface to the functionality of a specific type of cryptographic service (independent of a particular cryptographic algorithm). It defines Application Programming Interface (API) methods that allow applications to access the specific type of cryptographic service it provides. The actual implementations (from one or more providers) are those for specific algorithms. For example, the Signature engine class provides access to the functionality of a digital signature algorithm. The actual implementation supplied in a SignatureSpi subclass (see next paragraph) would be that for a specific kind of signature algorithm, such as SHA1 with DSA, SHA1 with RSA, or MD5 with RSA.

The application interfaces supplied by an engine class are implemented in terms of a Service Provider Interface (SPI). That is, for each engine class, there is a corresponding abstract SPI class, which defines the Service Provider Interface methods that cryptographic service providers must implement.

Architecture of Service Provider Interface

An instance of an engine class, the "API object", encapsulates (as a private field) an instance of the corresponding SPI class, the "SPI object". All API methods of an API object are declared "final", and their implementations invoke the corresponding SPI methods of the encapsulated SPI object. An instance of an engine class (and of its corresponding SPI class) is created by a call to the getInstance factory method of the engine class.

The name of each SPI class is the same as that of the corresponding engine class, followed by "Spi". For example, the SPI class corresponding to the Signature engine class is the SignatureSpi class.

Each SPI class is abstract. To supply the implementation of a particular type of service and for a specific algorithm, a provider must subclass the corresponding SPI class and provide implementations for all the abstract methods.

Another example of an engine class is the MessageDigest class, which provides access to a message digest algorithm. Its implementations, in MessageDigestSpi subclasses, may be those of various message digest algorithms such as SHA-1, MD5, or MD2.

As a final example, the KeyFactory engine class supports the conversion from opaque keys to transparent key specifications, and vice versa. See Key Specification Interfaces and Classes Required by Key Factories for details. The actual implementation supplied in a KeyFactorySpi subclass would be that for a specific type of keys, e.g., DSA public and private keys.

Steps to Implement and Integrate a Provider

Follow the steps below to implement a provider and integrate it into the JCA framework:

  • Step 1: Write your Service Implementation Code
    • Step 1.1: Additional JCA Provider Requirements and Recommendations for Encryption Implementations
  • Step 2: Give your Provider a Name
  • Step 3: Write your Master Class, a subclass of Provider
    • Step 3.1: Additional Steps for Cipher Implementations
  • Step 4: Compile your Code
  • Step 5: Place your Provider in a Jar File
  • Step 6: Optional -- Sign your JAR File
    • Step 6.1: Get a Code-Signing Certificate
    • Step 6.2: Sign Your Provider
  • Step 7: Prepare for Testing
    • Step 7.1: Install the Provider
    • Step 7.2: Set Provider Permissions
  • Step 8: Write and Compile your Test Programs
  • Step 9: Run your Test Programs
  • Step 10: Apply for U.S. Government Export Approval if Required
  • Step 11: Document your Provider and its Supported Services
    • Message Digests and MACs
  • Step 12: Make your Class Files and Documentation Available to Clients

Step 1: Write your Service Implementation Code

The first thing you need to do is to write the code that provides algorithm-specific implementations of the cryptographic services you want to support.

Note that your provider may supply implementations of cryptographic services already available in one or more of the security components of the JDK.

For cryptographic services not defined in JCA (For example; signatures and message digests), please refer to Java Cryptography Architecture Reference Guide.

For each cryptographic service you wish to implement, create a subclass of the appropriate SPI class. JCA defines the following engine classes:

  • SignatureSpi
  • MessageDigestSpi
  • KeyPairGeneratorSpi
  • SecureRandomSpi
  • AlgorithmParameterGeneratorSpi
  • AlgorithmParametersSpi
  • KeyFactorySpi
  • CertificateFactorySpi
  • KeyStoreSpi
  • CipherSpi
  • KeyAgreementSpi
  • KeyGeneratorSpi
  • MacSpi
  • SecretKeyFactorySpi
  • ExemptionMechanismSpi

(See Engine Classes and Corresponding SPI Classes in this document for information on the JCA and other cryptographic classes.)

In your subclass, you need to:

  1. Supply implementations for the abstract methods, whose names usually begin with engine. See Further Implementation Details and Requirements for additional information.
  2. Ensure there is a public constructor without any arguments. Here's why: When one of your services is requested, Java Security looks up the subclass implementing that service, as specified by a property in your "master class" (see Step 3). Java Security then creates the Class object associated with your subclass, and creates an instance of your subclass by calling the newInstance method on that Class object. newInstance requires your subclass to have a public constructor without any parameters.
  3. A default constructor without arguments will automatically be generated if your subclass doesn't have any constructors. But if your subclass defines any constructors, you must explicitly define a public constructor without arguments.

Step 1.1: Additional JCA Provider Requirements and Recommendations for Encryption Implementations

When instantiating a provider's implementation (class) of a Cipher, KeyAgreement, KeyGenerator, MAC or SecretKey factory, the framework will determine the provider's codebase (JAR file) and verify its signature. In this way, JCA authenticates the provider and ensures that only providers signed by a trusted entity can be plugged into JCA. Thus, one requirement for encryption providers is that they must be signed, as described in later steps.

In addition, each provider should perform self-integrity checking to ensure that the JAR file containing its code has not been manipulated in an attempt to invoke provider methods directly rather than through JCA. For further information, see How a Provider Can Do Self-Integrity Checking.

In order for provider classes to become unusable if instantiated by an application directly, bypassing JCA, providers should implement the following:

  • All SPI implementation classes in a provider package should be declared final (so that they cannot be subclassed), and their (SPI) implementation methods should be declared protected.
  • All crypto-related helper classes in a provider package should have package-private scope, so that they cannot be accessed from outside the provider package.

For providers that may be exported outside the U.S., CipherSpi implementations must include an implementation of the engineGetKeySize method which, given a Key, returns the key size. If there are restrictions on available cryptographic strength specified in jurisdiction policy files, each Cipher initialization method calls engineGetKeySize and then compares the result with the maximum allowable key size for the particular location and circumstances of the applet or application being run. If the key size is too large, the initialization method throws an exception.

Additional optional features that providers may implement are

  • the engineWrap and engineUnwrap methods of CipherSpi. Wrapping a key enables secure transfer of the key from one place to another. Information about wrapping and unwrapping keys is provided in the Wrapping and Unwrapping Keys section of the Java Cryptography Architecture Reference Guide.
  • one or more exemption mechanisms. An exemption mechanism is something such as key recovery, key escrow, or key weakening which, if implemented and enforced, may enable reduced cryptographic restrictions for an application (or applet) that uses it. For information on the requirements for apps that utilize exemption mechanisms, see How to Make Applications "Exempt" from Cryptographic Restrictions in the Java Cryptography Architecture Reference Guide.

Step 2: Give your Provider a Name

Decide on a name for your provider. This is the name to be used by client applications to refer to your provider.

Step 3: Write your Master Class, a subclass of Provider

The third step is to create a subclass of the java.security.Provider class.

Your subclass should be a final class, and its constructor should

  • call super, specifying the provider name (see Step 2), version number, and a string of information about the provider and algorithms it supports. For example:
        super("CryptoX", 1.0, "CryptoX provider v1.0, implementing " +
        "RSA encryption and key pair generation, and DES encryption.");
  • set the values of various properties that are required for the Java Security API to look up the cryptographic services implemented by the provider. For each service implemented by the provider, there must be a property whose name is the type of service (for example; Signature, MessageDigest, Cipher, KeyAgreement) Signature, MessageDigest, KeyPairGenerator, SecureRandom, KeyFactory, KeyStore, CertificateFactory, AlgorithmParameterGenerator, AlgorithmParameters, Cipher, KeyAgreement, KeyGenerator, Mac, SecretKeyFactory, or ExemptionMechanism) followed by a period and the name of the algorithm to which the service applies. The property value must specify the fully qualified name of the class implementing the service.

  • The list below shows the various types of JCA services, where the actual algorithm name is substitued for algName:

    • Signature.algName
    • MessageDigest.algName
    • KeyPairGenerator.algName
    • SecureRandom.algName
    • AlgorithmParameterGenerator.algName
    • AlgorithmParameters.algName
    • KeyFactory.algName
    • CertificateFactory.algName
    • KeyStore.algName
    • Cipher.algName
    • KeyAgreement.algName
    • KeyGenerator.algName
    • Mac.algName
    • SecretKeyFactory.algName
    • ExemptionMechanism.algName

    In all of these except ExemptionMechanism and Cipher, algName, certType , or storeType is the "standard" name of the algorithm, certificate type, or keystore type. See Appendix A of the Java Cryptography Architecture Reference Guide for the standard names that should be used.)

    In the case of ExemptionMechanism, algName refers to the name of the exemption mechanism, which can be one of the following: KeyRecovery, KeyEscrow, or KeyWeakening. Case does not matter.

    In the case of Cipher, algName may actually represent a transformation, and may be composed of an algorithm name, a particular mode, and a padding scheme. See Appendix A of the Java Cryptography Architecture Reference Guide for details.

    The value of each property must be the fully qualified name of the class implementing the specified algorithm, certificate type, or keystore type. That is, it must be the package name followed by the class name, where the two are separated by a period.

    As an example, the default provider named SUN implements the Digital Signature Algorithm (whose standard name is SHA1withDSA) in a class named DSA in the sun.security.provider package. Its subclass of Provider (which is the Sun class in the sun.security.provider package) sets the Signature.SHA1withDSA property to have the value sun.security.provider.DSA via the following:

        put("Signature.SHA1withDSA", "sun.security.provider.DSA")

    The list below shows more properties that can be defined for the various types of services, where the actual algorithm name is substitued for algName, certificate type for certType, keystore type for storeType, and attribute name for attrName:

    • Signature.algName [one or more spaces] attrName
    • MessageDigest.algName [one or more spaces] attrName
    • KeyPairGenerator.algName [one or more spaces] attrName
    • SecureRandom.algName [one or more spaces] attrName
    • KeyFactory.algName [one or more spaces] attrName
    • CertificateFactory.certType [one or more spaces] attrName
    • KeyStore.storeType [one or more spaces] attrName
    • AlgorithmParameterGenerator.algName [one or more spaces] attrName
    • AlgorithmParameters.algName [one or more spaces] attrName
    • Cipher.algName [one or more spaces] attrName
    • KeyAgreement.algName [one or more spaces] attrName
    • KeyGenerator.algName [one or more spaces] attrName
    • Mac.algName [one or more spaces] attrName
    • SecretKeyFactory.algName [one or more spaces] attrName
    • ExemptionMechanism.algName [one or more spaces] attrName

In each of these, algName, certType, storeType, or attrName is the "standard" name of the algorithm, certificate type, keystore type, or attribute. (See Appendix A of the Java Cryptography Architecture Reference Guide for the standard names that should be used.)

For a property in the above format, the value of the property must be the value for the corresponding attribute. (See Appendix A of the Java Cryptography Architecture API Specification & Reference for the definition of each standard attribute.)

As an example, the default provider named "SUN" implements the SHA1withDSA Digital Signature Algorithm in software. In the master class for the provider "SUN", it sets the Signature.SHA1withDSA ImplementedIn to have the value Software via the following:

    put("Signature.SHA1withDSA ImplementedIn", "Software")

For further master class property setting examples, see Appendix A to view the current Sun.java source file or Appendix B to see the SunJCE provider. These files show how the Sun and SunJCE providers set properties.

Step 3.1: Additional Steps for Cipher Implementations

As mentioned above, in the case of a Cipher property, algName may actually represent a transformation. A transformation is a string that describes the operation (or set of operations) to be performed by a Cipher object on some given input. A transformation always includes the name of a cryptographic algorithm (e.g., DES), and may be followed by a mode and a padding scheme.

A transformation is of the form:

  • algorithm/mode/padding, or
  • algorithm

(In the latter case, provider-specific default values for the mode and padding scheme are used). For example, the following is a valid transformation:

    Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");

When requesting a block cipher in stream cipher mode (for example; DES in CFB or OFB mode), a client may optionally specify the number of bits to be processed at a time, by appending this number to the mode name as shown in the following sample transformations:

    Cipher c1 = Cipher.getInstance("DES/CFB8/NoPadding");
    Cipher c2 = Cipher.getInstance("DES/OFB32/PKCS5Padding");

If a number does not follow a stream cipher mode, a provider-specific default is used. (For example, the SunJCE provider uses a default of 64 bits.)

A provider may supply a separate class for each combination of algorithm/mode/padding. Alternatively, a provider may decide to provide more generic classes representing sub-transformations corresponding to algorithm or algorithm/mode or algorithm//padding (note the double slashes); in this case the requested mode and/or padding are set automatically by the getInstance methods of Cipher, which invoke the engineSetMode and engineSetPadding methods of the provider's subclass of CipherSpi.

That is, a Cipher property in a provider master class may have one of the formats shown in the table below.

Cipher Property Format | Description
Cipher.algName | A provider's subclass of CipherSpi implements algName with pluggable mode and padding
Cipher.algName/mode | A provider's subclass of CipherSpi implements algName in the specified mode, with pluggable padding
Cipher.algName//padding | A provider's subclass of CipherSpi implements algName with the specified padding, with pluggable mode
Cipher.algName/mode/padding | A provider's subclass of CipherSpi implements algName with the specified mode and padding

(See Appendix A of the Java Cryptography Architecture Reference Guide for the standard algorithm names, modes, and padding schemes that should be used.)

For example, a provider may supply a subclass of CipherSpi that implements DES/ECB/PKCS5Padding, one that implements DES/CBC/PKCS5Padding, one that implements DES/CFB/PKCS5Padding, and yet another one that implements DES/OFB/PKCS5Padding. That provider would have the following Cipher properties in its master class:

  • Cipher.DES/ECB/PKCS5Padding
  • Cipher.DES/CBC/PKCS5Padding
  • Cipher.DES/CFB/PKCS5Padding
  • Cipher.DES/OFB/PKCS5Padding

Another provider may implement a class for each of the above modes (i.e., one class for ECB, one for CBC, one for CFB, and one for OFB), one class for PKCS5Padding, and a generic DES class that subclasses from CipherSpi. That provider would have the following Cipher properties in its master class:

  • Cipher.DES
  • Cipher.DES SupportedModes
    Example: "ECB|CBC|CFB|OFB"
  • Cipher.DES SupportedPaddings
    Example: "NOPADDING|PKCS5Padding"

The getInstance factory method of the Cipher engine class follows these rules in order to instantiate a provider's implementation of CipherSpi for a transformation of the form "algorithm":

  1. Check if the provider has registered a subclass of CipherSpi for the specified "algorithm".

    If the answer is YES, instantiate this class, for whose mode and padding scheme default values (as supplied by the provider) are used.

    If the answer is NO, throw a NoSuchAlgorithmException exception.

The getInstance factory method of the Cipher engine class follows these rules in order to instantiate a provider's implementation of CipherSpi for a transformation of the form "algorithm/mode/padding":

  1. Check if the provider has registered a subclass of CipherSpi for the specified "algorithm/mode/padding" transformation.

    If the answer is YES, instantiate it.

    If the answer is NO, go to the next step.
  2. Check if the provider has registered a subclass of CipherSpi for the sub-transformation "algorithm/mode".

    If the answer is YES, instantiate it, and call engineSetPadding(padding) on the new instance.

    If the answer is NO, go to the next step.
  3. Check if the provider has registered a subclass of CipherSpi for the sub-transformation "algorithm//padding" (note the double slashes).

    If the answer is YES, instantiate it, and call engineSetMode(mode) on the new instance.

    If the answer is NO, go to the next step.
  4. Check if the provider has registered a subclass of CipherSpi for the sub-transformation "algorithm".

    If the answer is YES, instantiate it, and call engineSetMode(mode) and engineSetPadding(padding) on the new instance.

    If the answer is NO, throw a NoSuchAlgorithmException exception.

Step 4: Compile your Code

After you have created your implementation code (Step 1), given your provider a name (Step 2), and created the master class (Step 3), use the Java compiler to compile your files.

Step 5: Place Your Provider in a JAR File

Place your provider code in a JAR file, in preparation for signing it in the next step. For more information on the jar tool, see jar (for Solaris) (for Microsoft Windows).

    jar cvf <JAR file name> <list of classes, separated by spaces>

This command creates a JAR file with the specified name containing the specified classes.

Step 6: Optional -- Sign your JAR File

If your provider is supplying encryption algorithms through the Cipher KeyAgreement, KeyGenerator, Mac, or SecretKeyFactory classes, you will need to sign your JAR file so that the JCA can authenticate the code at runtime. For details, see Step 1a. If you are NOT providing an implementation of this type you can skip this step.

Step 6.1: Get a Code-Signing Certificate

The next step is to request a code-signing certificate so that you can use it to sign your provider prior to testing. The certificate will be good for both testing and production. It will be valid for 5 years.

Below are the steps you should use to get a code-signing certificate. For more information on the keytool tool, see keytool (for Solaris) (for Microsoft Windows).

  1. Use keytool to generate a DSA keypair, using DSA algorithm as an example:
        keytool -genkeypair -alias <alias> \
        -keyalg DSA -keysize 1024 \
        -dname "cn=<Company Name>, \
        ou=Java Software Code Signing,\
        o=Sun Microsystems Inc" \
        -keystore <keystore file name>\
        -storepass <keystore password>

    This will generate a DSA keypair (a public key and an associated private key) and store it in an entry in the specified keystore. The public key is stored in a self-signed certificate. The keystore entry can subsequently be accessed using the specified alias.

    The option values in angle brackets ("<" and ">") represent the actual values that must be supplied. For example, <alias> must be replaced with whatever alias name you wish to be used to refer to the newly-generated keystore entry in the future, and <keystore file name> must be replaced with the name of the keystore to be used. Note: Do not surround actual values with angle brackets. For example, if you want your alias to be myTestAlias, specify the -alias option as follows:

        -alias myTestAlias
    If you specify a keystore that doesn't yet exist, it will be created.

    Note: If command lines you type are not allowed to be as long as the keytool -genkeypair command you want to execute (for example, if you are typing to a Microsoft Windows DOS prompt), you can create and execute a plain-text batch file containing the command. That is, create a new text file that contains nothing but the full keytool -genkeypair command. (Remember to type it all on one line.) Save the file with a .bat extension. Then in your DOS window, type the file name (with its path, if necessary). This will cause the command in the batch file to be executed.

  2. Use keytool to generate a certificate signing request.
        keytool -certreq -alias <alias> \
        -file <csr file name> \
        -keystore <keystore file name> \
        -storepass <keystore password>
    Here, <alias> is the alias for the DSA keypair entry created in the previous step. This command generates a Certificate Signing Request (CSR), using the PKCS#10 format. It stores the CSR in the file whose name is specified in <csr file name>.
  3. Send the CSR, contact information, and other required documentation to the JCA Code Signing Certification Authority. Send, via email, the CSR and contact information (see below) to javasoft-cert-request@sun.com. Put the following in the Subject line of your email message:
        Request a Certificate for Signing a JCA Provider
    Put the contact information in the body of the message and send the CSR file as a plain text attachment to the message. If your mail tool has an option for specifying the encoding format to be used for attachments, select the "MIME" option.

    Note: The CSR file is just a plain text file, in Base 64 encoding. Only the first and last lines are human-readable.

    Include the following contact information in the body of your message:
    • Company Name
    • Street Address (Not a post office box)
    • City
    • State/Province
    • Country
    • Company Telephone Number
    • Company Fax Number
    • Requester Name
    • Requester Telephone Number
    • Requester Email Address
    • Brief description of your company (size, line of business, etc.)

    All of the above information is required.

  4. After the JCA Code Signing Certification Authority has received your email message, they will send you a request number via email. Please allow five business days for processing.

    Once you receive this request number, you should print, fill out and mail the Certification Form for CSPs. This form should be mailed to the address below. Be sure to include the request number on the form so that your hardcopy mailing can be matched to the email message containing your CSR and contact information.

    Sun Microsystems, Inc.
    International Trade Services/Export Compliance
    Attn: Encryption Export
    10 Network Circle MS: UMPK10-144 Menlo Park, CA 94025 .

    You can also fax paperwork as follows:

    Fax #: 408-668-0918

    Subject Line: CSR #___
    Attention: Encryption Export
    Sun Microsystems, Inc.
    International Trade Services/Export Compliance

    After the JCA Code Signing Certification Authority has received both your email message and the required form, they will authenticate you, the requester. Then they will create and sign a code-signing certificate valid for 5 years. You will receive an email message containing two plain-text file attachments: one file containing this code-signing certificate and another file containing its own CA certificate, which authenticates its public key. Please also allow five business days from receipt of your request for processing.

  5. Use keytool to import the certificates received from the CA.

    Once you have received the two certificates from the JCA Code Signing Certification Authority, you can use keytool to import them into your keystore.

    First import the CA's certificate as a "trusted certificate":
        keytool -import -alias <alias for the CA cert> \
        -file <CA cert file name> \
        -keystore <keystore file name> \
        -storepass <keystore password>
    Then import the code-signing certificate:
        keytool -import -alias <alias> \
        -file <code-signing cert file name> \
        -keystore <keystore file name> \
        -storepass <keystore password>
    Here, <alias> is the same alias as that which you created in step 1 where you generated a DSA keypair. This command replaces the self-signed certificate in the keystore entry specified by <alias> with the one signed by the JCA Code Signing Certification Authority.

Now that you have in your keystore a certificate from an entity trusted by JCA (the JCA Code Signing Certification Authority), you can place your provider code in a JAR file (Step 5) and then use that certificate to sign the JAR file (Step 6.2).

Step 6.2: Sign Your Provider

Sign the JAR file created step five with the code-signing certificate obtained in Step 6. For more information on the jarsigner tool, see jarsigner (for Solaris) (for Microsoft Windows).

    jarsigner -keystore <keystore file name> \
        -storepass <keystore password> \
        <JAR file name> <alias>

Here, <alias> is the alias into the keystore for the entry containing the code-signing certificate received from the JCA Code Signing Certification Authority (the same alias as that specified in the commands in Step 6.1).

You can test verification of the signature via the following:

    jarsigner -verify <JAR file name>

The text "jar verified" will be displayed if the verification was successful.

Step 7: Prepare for Testing

The next steps describe how to install and configure your new provider so that it is available via the JCA.

Step 7.1: Install the Provider

In order to prepare for testing your provider, you must install it in the same manner as will be done by clients wishing to use it. The installation enables Java Security to find your algorithm implementations when clients request them.

Installing a provider is done in two steps: installing the provider package classes, and configuring the provider.

Installing the Provider Classes

The first thing you must do is make your classes available so that they can be found when requested. You ship your provider classes as a JAR (Java ARchive) file.

There are a two possible ways to install provider classes:

  • Install the JAR file containing the provider classes as an installed or bundled extension.
  • Place the JAR file containing the provider classes in your CLASSPATH.

The provider JAR file will be considered an installed extension if it is placed in the standard place for the JAR files of an installed extension:

    <java-home>/lib/ext           [Solaris]
    <java-home>\lib\ext           [Windows]

Here <java-home> refers to the directory where the runtime software is installed, which is the top-level directory of the Java™ 2 Runtime Environment (JRE) or the jre directory in the Java™ SE (JDK) software. For example, if you have JDK 6 installed on Solaris in a directory named /home/user1/jdk1.6.0, or on Microsoft Windows in a directory named C:\jdk1.6.0, then you need to install the JAR file in the following directory:

    /home/user1/jdk1.6.0/jre/lib/ext    [Solaris]
    C:\jdk1.6.0\jre\lib\ext             [Windows]

Similarly, if you have JRE 6 installed on Solaris in a directory named /home/user1/jre1.6.0, or on Microsoft Windows in a directory named C:\jre1.6.0, you need to install the JAR file in the following directory:

    /home/user1/jre1.6.0/lib/ext        [Solaris]
    C:\jre1.6.0\lib\ext                 [Windows]

For more information on installed extensions, see Installed Extensions.

For more information on bundled extensions, see Bundled Extensions.

Configuring the Provider

The next step is to add the provider to your list of approved providers. This is done statically by editing the security properties file

    <java-home>/lib/security/java.security        [Solaris]
    <java-home>\lib\security\java.security        [Windows]

Here <java-home> refers to the directory where the JRE was installed. For example, if you have JDK 6 installed on Solaris in a directory named /home/user1/jdk1.6.0, or on Microsoft indows in a directory named C:\jdk1.6.0, then you need to edit the following file:

    /home/user1/jdk1.6.0/jre/lib/security/java.security [Solaris]
    C:\jdk1.6.0\jre\lib\security\java.security          [Windows]

Similarly, if you have the JRE 6 installed on Solaris in a directory named /home/user1/jre1.6.0, or on Windows in a directory named C:\jre1.6.0, then you need to edit this file:

    /home/user1/jre1.6.0/lib/security/java.security     [Solaris]
    C:\jre1.6.0\lib\security\java.security              [Windows]

For each provider, this file should have a statement of the following form:

    security.provider.n=masterClassName

This declares a provider, and specifies its preference order n. The preference order is the order in which providers are searched for requested algorithms when no specific provider is requested. The order is 1-based; 1 is the most preferred, followed by 2, and so on.

masterClassName must specify the fully qualified name of the provider's "master class", which you implemented in Step 3. This class is always a subclass of the Provider class.

Java comes standard with providers named SUN, SunRsaSign, and SunJCE which are automatically configured as a static provider in the java.security properties file, as follows:

    security.provider.2=sun.security.provider.Sun
    security.provider.3=sun.security.rsa.SunRsaSign
    security.provider.4=sun.security.provider.SunJCE

(The Sun provider's master class is the Sun class in the sun.security.provider package.)

The JCA provider SunJCE and other security-related providers shipped with the Java platform are also automatically configured as static providers.

To utilize another JCA provider, add a line registering the alternate provider, giving it a lower preference order than the SUN and SunRsaSign providers.

Suppose that your master class is the CryptoX class in the com.cryptox.provider package, and that you would like to make your provider the fourth preferred provider. To do so, edit the java.security file as seen below:

    security.provider.2=sun.security.provider.Sun
    security.provider.3=sun.security.rsa.SunRsaSign
    security.provider.4=com.cryptox.provider.CryptoX
    security.provider.5=sun.security.provider.SunJCE

Note: Providers may also be registered dynamically. To do so, a program (such as your test program, to be written in Step 8) can call either the addProvider or insertProviderAt method in the Security class. This type of registration is not persistent and can only be done by code which is granted the following permission:

    java.security.SecurityPermission "insertProvider.{name}"

where {name} is replaced by the actual provider name.

For example, if the provider name is "MyJCE" and if the provider's code is in the myjce_provider.jar file in the /localWork directory, then here is a sample policy file grant statement granting that permission:

    grant codeBase "file:/localWork/myjce_provider.jar" {
        permission java.security.SecurityPermission
            "insertProvider.MyJCE";
    };

Step 7.2: Set Provider Permissions

Whenever providers are not installed extensions, permissions must be granted for when applets or applications are run while a security manager is installed. There is typically a security manager installed whenever an applet is running, and a security manager may be installed for an application either via code in the application itself or via a command-line argument. Permissions do not need to be granted to installed extensions, since the default system policy file grants all permissions to installed extensions.

Whenever a client does not install your provider as an installed extension, your provider may need the following permissions granted to it in the client environment:

  • java.lang.RuntimePermission to get class protection domains. The provider may need to get its own protection domain in the process of doing self-integrity checking.
  • java.security.SecurityPermission to set provider properties.

To ensure your provider works when a security manager is installed and the provider is not an installed extension, you need to test such an installation and execution environment. In addition, prior to testing you need to grant appropriate permissions to your provider and to any other providers it uses. For example, a sample statement granting permissions to a provider whose name is "MyJCE" and whose code is in myjce_provider.jar appears below. Such a statement could appear in a policy file. In this example, the myjce_provider.jar file is assumed to be in the /localWork directory.

    grant codeBase "file:/localWork/myjce_provider.jar" {
        permission java.lang.RuntimePermission "getProtectionDomain";
        permission java.security.SecurityPermission
            "putProviderProperty.MyJCE";
    };

Step 8: Write and Compile your Test Programs

Write and compile one or more test programs that test your provider's incorporation into the Security API as well as the correctness of its algorithm(s). Create any supporting files needed, such as those for test data to be encrypted.

The first tests your program should perform are ones to ensure that your provider is found, and that its name, version number, and additional information is as expected. To do so, you could write code like the following, substituting your provider name for MyPro:

    import java.security.*;

    Provider p = Security.getProvider("MyPro");

    System.out.println("MyPro provider name is " + p.getName());
    System.out.println("MyPro provider version # is " + p.getVersion());
    System.out.println("MyPro provider info is " + p.getInfo());

Next, you should ensure that your services are found. For instance, if you implemented the DES encryption algorithm, you could check to ensure it's found when requested by using the following code (again substituting your provider name for "MyPro"):

    Cipher c = Cipher.getInstance("DES", "MyPro");

    System.out.println("My Cipher algorithm name is " + c.getAlgorithm());

If you don't specify a provider name in the call to getInstance, all registered providers will be searched, in preference order (see Configuring the Provider), until one implementing the algorithm is found.

If your provider implements an exemption mechanism, you should write a test applet or application that uses the exemption mechanism. Such an applet/application also needs to be signed, and needs to have a "permission policy file" bundled with it. See How to Make Applications "Exempt" from Cryptographic Restrictions in the Java Cryptography Architecture Reference Guide for complete information on creating and testing such an application.

Step 9: Run your Test Programs

Run your test program(s). Debug your code and continue testing as needed. If the Java Security API cannot seem to find one of your algorithms, review the steps above and ensure they are all completed.

Be sure to include testing of your programs using different installation options (e.g. making the provider an installed extension or placing it on the class path) and execution environments (with or without a security manager running). Installation options are discussed in Step 7.1. In particular, you need to ensure your provider works when a security manager is installed and the provider is not an installed extension -- and thus the provider must have permissions granted to it; therefore, you need to test such an installation and execution environment, after granting required permissions to your provider and to any other providers it uses, as described in Step 7.2.

If you find during testing that your code needs modification, make the changes, recompile (Step 4), place the updated provider code in a JAR file (Step 6), sign the JAR file if necessary (Step 6.2), re-install the provider (Step 7.1), if needed fix or add to the permissions (Step 7.2), and then re-test your programs. Repeat these steps as needed.

Step 10: Apply for U.S. Government Export Approval If Required

All U.S. vendors whose providers may be exported outside the U.S. should apply to the Bureau of Industry and Security in the U.S. Department of Commerce for export approval. Please consult your export counsel for more information.

Note: If your provider calls Cipher.getInstance() and the returned Cipher object needs to perform strong cryptography regardless of what cryptographic strength is allowed by the user's downloaded jurisdiction policy files, you should include a copy of the cryptoPerms permission policy file which you intend to bundle in the JAR file for your provider and which specifies an appropriate permission for the required cryptographic strength. The necessity for this file is just like the requirement that applets and applications "exempt" from cryptographic restrictions must include a cryptoPerms permission policy file in their JAR file. For more information on the creation and inclusion of such a file, see How to Make Applications "Exempt" from Cryptographic Restrictions in the Java Cryptography Architecture Reference Guide.

Here are two URLs that may be useful:

  • U.S. Department of Commerce: http://www.commerce.gov
  • Bureau of Industry and Security: http://www.bis.doc.gov

Step 11: Document your Provider and its Supported Services

The next step is to write documentation for your clients. At the minimum, you need to specify:

  • the name programs should use to refer to your provider. Note: As of this writing, provider name searches are case-sensitive. That is, if your master class specifies your provider name as "CryptoX" but a user requests "CRYPTOx", your provider will not be found. This behavior may change in the future, but for now be sure to warn your clients to use the exact case you specify.
  • the types of algorithms and other services implemented by your provider.
  • instructions for installing the provider, similar to those provided in Step 7.1, except that the information and examples should be specific to your provider.
  • the permissions your provider will require if it is not installed as an installed extension and if a security manager is run, as described in Step 7.2.

In addition, your documentation should specify anything else of interest to clients, such as any default algorithm parameters.

Message Digests and MACs

For each Message Digest and MAC algorithm, indicate whether or not your implementation is cloneable. This is not technically necessary, but it may save clients some time and coding by telling them whether or not intermediate Message Digests or MACs may be possible through cloning. Clients who do not know whether or not a MessageDigest or Mac implementation is cloneable can find out by attempting to clone the object and catching the potential exception, as illustrated by the following example:

    try {
        // try and clone it
        /* compute the MAC for i1 */
        mac.update(i1);
        byte[] i1Mac = mac.clone().doFinal();

        /* compute the MAC for i1 and i2 */
        mac.update(i2);
        byte[] i12Mac = mac.clone().doFinal();

        /* compute the MAC for i1, i2 and i3 */
        mac.update(i3);
        byte[] i123Mac = mac.doFinal();
    } catch (CloneNotSupportedException cnse) {
        // have to use an approach not involving cloning
    }

where:

  • mac is the MAC object they received when they requested one via a call to Mac.getInstance,
  • i1, i2 and i3 are input byte arrays, and
  • they want to calculate separate hashes for:
    • i1
    • i1 and i2
    • i1, i2, and i3

Key Pair Generators

For a key pair generator algorithm, in case the client does not explicitly initialize the key pair generator (via a call to an initialize method), each provider must supply and document a default initialization. For example, the Diffie-Hellman key pair generator supplied by the SunJCE provider uses a default prime modulus size (keysize) of 1024 bits.

Key Factories

A provider should document all the key specifications supported by its (secret-)key factory.

Algorithm Parameter Generators

In case the client does not explicitly initialize the algorithm parameter generator (via a call to an init method in the AlgorithmParameterGenerator engine class), each provider must supply and document a default initialization. For example, the SunJCE provider uses a default prime modulus size (keysize) of 1024 bits for the generation of Diffie-Hellman parameters, the Sun provider a default modulus prime size of 1024 bits for the generation of DSA parameters.

Signature Algorithms

If you implement a signature algorithm, you should document the format in which the signature (generated by one of the sign methods) is encoded. For example, the SHA1withDSA signature algorithm supplied by the "SUN" provider encodes the signature as a standard ASN.1 SEQUENCE of two integers, r and s.

Random Number Generation (SecureRandom) Algorithms

For a random number generation algorithm, provide information regarding how "random" the numbers generated are, and the quality of the seed when the random number generator is self-seeding. Also note what happens when a SecureRandom object (and its encapsulated SecureRandomSpi implementation object) is deserialized: If subsequent calls to the nextBytes method (which invokes the engineNextBytes method of the encapsulated SecureRandomSpi object) of the restored object yield the exact same (random) bytes as the original object would, then let users know that if this behaviour is undesirable, they should seed the restored random object by calling its setSeed method.

Certificate Factories

A provider should document what types of certificates (and their version numbers, if relevant), can be created by the factory.

Keystores

A provider should document any relevant information regarding the keystore implementation, such as its underlying data format.

Step 12: Make your Class Files and Documentation Available to Clients

After writing, configuring, testing, installing and documenting your provider software, make documentation available to your customers.

How a Provider Can Do Self-Integrity Checking

Each provider should do self-integrity checking to ensure that the JAR file containing its code has not been tampered with, for example in an attempt to invoke provider methods directly rather than through JCA. Providers that provide implementations for encryption services (Cipher, KeyAgreement, KeyGenerator, MAC or SecretKey factory) must be digitally signed and should be signed with a certificate issued by "trusted" Certification Authorities. Currently, the following two Certification Authorities are considered "trusted":

  • Sun Microsystems' JCA Code Signing CA, and
  • IBM JCA Code Signing CA.

Please refer to Step 6.2 for detailed information on how to get a code-signing certificate from Sun Microsystems' JCA Code Signing CA and the certificate of that CA.

After getting the signing certificate from above Certification Authority, provider packages should embed within themselves the bytes for its own signing certificate, for example in an array like the bytesOfProviderCert array referred to in the Identifying Each of the Signers and Determining If One is Trusted section below. At runtime, the embedded certificate will be used in determining whether or not the provider code is authentic.

The basic approach a provider can use to check its own integrity is:

  1. Determine the URL of the JAR file containing the provider code, and
  2. Verify the JAR file's digital signatures to ensure that at least one signer of each entry of the JAR file is trusted.

Each of these steps is described in the following sections:

  • Notes on the Sample Code
  • Finding the Provider JAR File: Basics
    • Determining the Provider's JAR File URL
    • Creating a JarFile Referring to the JAR File
  • Verifying the Provider JAR File: Basics
    • Verification Setup
    • JAR File Signature Check
    • Verifying Signatures
    • Ensuring Signers Are Trusted
      • Getting the List of Certificates
      • Identifying Each of the Signers and Determining If One is Trusted
  • Verifying Signatures
  • Ensuring Signers Are Trusted
    • Getting the List of Certificates
    • Identifying Each of the Signers and Determining If One is Trusted
    • Notes on myJCE Sample Code
Notes on the Sample Code

Note: The sample code MyJCE.java is a complete code example that implements these steps. You can download this code for your reference. The Notes on the Sample Code section traces how these concepts are implemented in the sample code.

IMPORTANT NOTE: In the unbundled version of JCE 1.2.x, (used with JDKs 1.2.x and 1.3.x), providers needed to include code to authenticate the JCA framework to assure themselves of the integrity and authenticity of the JCA that they plugged into. In JDK 6, this is no longer necessary.

One implication is that a provider written just for JCE 1.2.2 will not work in JDK 6 because the provider's JCE framework authentication check will not work; the JCE framework code is no longer where the provider expects it to be. If you want your provider to work only with the JDK 6, it should not have code to authenticate the JCE framework. On the other hand, if you want your provider to work both with JCE 1.2.2 and with the JDK 6, then add a conditional statement. This way the provider code to authenticate the JCE framework is executed only when the provider is run with JCE 1.2.2. The following is sample code:

    Class cipherCls = Class.forName("javax.crypto.Cipher");

    CodeSource cs = cipherCls.getProtectionDomain().getCodeSource();
    if (cs != null) {
        // Authenticate JCE framework
         . . .
    }

Finding the Provider JAR File: Basics

Determining the Provider's JAR File URL

The URL for the provider's JAR file can be obtained by determining the provider's CodeSource and then calling the getLocation method on the CodeSource.

    URL providerURL = (URL) AccessController.doPrivileged(
        new PrivilegedAction) {
            public Object run() {
                CodeSource cs =
                    MyJCE.class.getProtectionDomain().getCodeSource();
                return cs.getLocation();
            }
        });

Creating a JarFile Referring to the JAR File

Once you have the URL for the provider's JAR file, you can create a java.util.jar.JarFile referring to the JAR file. This instance is needed in the step for verifying the Provider JAR file.

To create the JAR file, first open a connection to the specified URL by calling its openConnection method. Since the URL is a JAR URL, the type is java.net.JarURLConnection. Here's the basic code:

    // Prep the url with the appropriate protocol.
    jarURL =
        url.getProtocol().equalsIgnoreCase("jar") ? url :
            new URL("jar:" + url.toString() + "!/");

    // Retrieve the jar file using JarURLConnection
    JarFile jf = (JarFile) AccessController.doPrivileged(
        new PrivilegedExceptionAction() {
            public Object run() throws Exception {
                JarURLConnection conn =
                    (JarURLConnection) jarURL.openConnection();
        ...

Now that you have a JarURLConnection, you can call its getJarFile method to get the JAR file:

    // Always get a fresh copy, so we don't have to
    // worry about the stale file handle when the
    // cached jar is closed by some other application.
    conn.setUseCaches(false);
    jf = conn.getJarFile();

Verifying the Provider JAR File: Basics

Once you have determined the URL for your provider JAR file and you have created a JarFile referring to the JAR file, as shown in the steps above, you can then verify the file.

The basic approach is:

  1. Ensure that at least one of each entry's signer's certificates is equal to the provider's own code signing certificate.
  2. Go through all the entries in the JAR file and ensure the signature on each one verifies correctly.
  3. Ensure that at least one of each entry's signer's certificates can be traced back to a trusted Certification Authority.

Sample code for each of these steps is presented and described in the following sections:

  • Verification Setup
  • JAR File Signature Check
  • Verifying Signatures
  • Ensuring Signers Are Trusted
    • Getting the List of Certificates
    • Identifying Each of the Signers and Determining If One is Trusted

Verification Setup

Our approach is to define a class JarVerifier to handle the retrieval of a JAR file from a given URL and verify whether the JAR file is signed with the specified certificate.

The constructor of JarVerifier takes the provider URL as a parameter which will be used to retrieve the JAR file later.

The actual jar verification is implemented in the verify method which takes the provider code signing certificate as a parameter.

    public void verify(X509Certificate targetCert) throws IOException {
        // variable 'jarFile' is a JarFile object created
        // from the provider's Jar URL.
        ...
        Vector entriesVec = new Vector();

Basically the verify method will go through the JAR file entries twice: the first time checking the signature on each entry and the second time verifying the signer is trusted.

Note: In our code snippets the jarFile variable is the JarFile object of the provider's jar file.

JAR File Signature Check

An authentic provider JAR file is signed. So the JAR file has been tampered with if it isn't signed:

    // Ensure the jar file is signed.
    Manifest man = jarFile.getManifest();
    if (man == null) {
        throw new SecurityException("The provider is not signed");
    }

Verifying Signatures

The next step is to go through all the entries in the JAR file and ensure the signature on each one verifies correctly. One possible way to verify the signature on a JAR file entry is to simply read the file. If a JAR file is signed, the read method itself automatically performs the signature verification. Here is sample code:

    // Ensure all the entries' signatures verify correctly
    byte[] buffer = new byte[8192];
    Enumeration entries = jarFile.entries();

    while (entries.hasMoreElements()) {
        JarEntry je = (JarEntry) entries.nextElement();

        // Skip directories.
        if (je.isDirectory())
            continue;

        entriesVec.addElement(je);
        InputStream is = jarFile.getInputStream(je);

        // Read in each jar entry. A security exception will
        // be thrown if a signature/digest check fails.
        int n;
        while ((n = is.read(buffer, 0, buffer.length)) != -1) {
            // Don't care
        }
        is.close();
    }

Ensuring Signers Are Trusted

The code in the previous section verified the signatures of all the provider JAR file entries. The fact that they all verify correctly is a requirement, but it is not sufficient to verify the authenticity of the JAR file. A final requirement is that the signatures were generated by the same entity as the one that developed this provider. To test that the signatures are trusted, we can again go through each entry in the JAR file (this time using the entriesVec built in the previous step), and for each entry that must be signed (that is, each entry that is not a directory and that is not in the META-INF directory):

  1. Get the list of signer certificates for the entry.
  2. Identify each of the certificate chains and determine whether any of the certificate chains are trusted. At least one of the certificate chains must be trusted.

The loop setup is the following:

    Enumeration e = entriesVec.elements();
    while (e.hasMoreElements()) {
        JarEntry je = (JarEntry) e.nextElement();
        ...
    }

Getting the List of Certificates

The certificates for the signers of a JAR file entry JarEntry can be obtained simply by calling the JarEntry getCertificates method:

    Certificate[] certs = je.getCertificates();

Adding this line of code to the previous loop setup code, and adding code to ignore directories and files in the META-INF directory gives us:

    while (e.hasMoreElements()) {
        JarEntry je = (JarEntry) e.nextElement();

        // Every file must be signed except files in META-INF.
        Certificate[] certs = je.getCertificates();
        if ((certs == null) || (certs.length == 0)) {
            if (!je.getName().startsWith("META-INF"))
                throw new SecurityException(
                    "The provider has unsigned class files.");
            } else {
                // Check whether the file is signed by the expected
                // signer. The jar may be signed by multiple signers.
                // See if one of the signers is 'targetCert'.
                ...
            }
        ...

Identifying Each of the Signers and Determining If One is Trusted

The certificate array returned by the JarEntry getCertificates method contains one or more certificate chains. There is one chain per signer of the entry. Each chain contains one or more certificates. Each certificate in a chain authenticates the public key in the previous certificate.

The first certificate in a chain is the signer's certificate which contains the public key corresponding to the private key actually used to sign the entry. Each subsequent certificate is a certificate for the issuer of the previous certificate. Since the self-integrity check is based on whether the JAR file is signed with the provider's signing cert, the trust decision will be made upon only the first certificate, the signer's certificate.

We need to go through the array of certificate chains and check each chain and the associated signers until we find a trusted entity. For each JAR file entry, at least one of the signers must be trusted. A signer is considered "trusted" if and only if its certificate is equals to the embedded provider signing certificate.

The following sample code loops through all the certificate chains, compares the first certificate in a chain to the embedded provider signing certificate, and only returns true if a match is found.

    int startIndex = 0;
    X509Certificate[] certChain;
    boolean signedAsExpected = false;

    while ((certChain = getAChain(certs, startIndex)) != null) {
        if (certChain[0].equals(targetCert)) {
            // Stop since one trusted signer is found.
            signedAsExpected = true;
            break;
        }

        // Proceed to the next chain.
        startIndex += certChain.length;
    }

    if (!signedAsExpected) {
        throw new SecurityException(
            "The provider is not signed by a trusted signer");
    }

The getAChain method is defined as follows:

    /**
     * Extracts ONE certificate chain from the specified certificate array
     * which may contain multiple certificate chains, starting from index
     * 'startIndex'.
     */
    private static X509Certificate[] getAChain(
            Certificate[] certs, int startIndex) {

        if (startIndex > certs.length - 1)
            return null;

        int i;
        // Keep going until the next certificate is not the
        // issuer of this certificate.
        for (i = startIndex; i < certs.length - 1; i++) {
            if (!((X509Certificate)certs[i + 1]).getSubjectDN().
                    equals(((X509Certificate)certs[i]).getIssuerDN())) {
                break;
            }
        }

        // Construct and return the found certificate chain.
        int certChainSize = (i-startIndex) + 1;
        X509Certificate[] ret = new X509Certificate[certChainSize];
        for (int j = 0; j < certChainSize; j++ ) {
            ret[j] = (X509Certificate) certs[startIndex + j];
        }
        return ret;
    }

Notes on the myJCE Code Sample

The sample code, MyJCE.java, is a sample provider which has a method selfIntegrityChecking which performs self-integrity checking. It first determines the URL of its own provider JAR file and then verifies that the provider JAR file is signed with the embedded code-signing certificate.

Note: The method selfIntegrityChecking should be called by all the constructors of its cryptographic engine classes to ensure that its integrity is not compromised.

Provider MyJCE performs self-integrity checking in the following steps:

  1. Determine the URL to access the provider JAR file using its own class, MyJCE.class.
  2. Instantiate a JarVerifier object with the provider URL in Step 1.
  3. Create a X509Certificate object from the embedded byte array bytesOfProviderCert.
  4. Call the JarVerifier.verify method to verify all entries in the provider JAR file are signed and are signed with the same certificate instantiated in Step 3.

Note: The class JarVerifier will retrieve the JAR file from the given URL, make sure the JAR file is signed, all entries have valid signatures, and that entries are signed with the specified X509Certificate.

A security exception is thrown by JarVerifier.verify in several cases:

  • The certificate passed to verify is null (invalid).
  • When unable to retrieve JAR file from the given URL.
  • The provider is not signed. (The jar has no manifest.)
  • The provider has unsigned class files.
  • The provider is not signed with the specified certificate.

The MyJCE.java sample code is comprised of the code snippets shown above. In addition, it includes error handling, sample code signing certificate bytes, and code for instantiating a X509Certificate object from the embedded sample code signing certificate bytes.

Regarding the use of AccessController.doPrivileged, please see API For Privileged Blocks for information on the use of doPrivileged.

Further Implementation Details and Requirements

Alias Names

For many cryptographic algorithms and types, there is a single official "standard name" defined in Appendix A of the Java Cryptography Architecture Reference Guide.

For example, "MD5" is the standard name for the RSA-MD5 Message Digest algorithm defined by RSA DSI in RFC 1321. DiffieHellman is the standard for the Diffie-Hellman key agreement algorithm defined in PKCS3.

In the JDK, there is an aliasing scheme that enables clients to use aliases when referring to algorithms or types, rather than their standard names. For example, the "SUN" provider's master class (Sun.java) defines the alias "SHA1/DSA" for the algorithm whose standard name is "SHA1withDSA". Thus, the following statements are equivalent:

    Signature sig = Signature.getInstance("SHA1withDSA", "SUN");

    Signature sig = Signature.getInstance("SHA1/DSA", "SUN");

Aliases can be defined in your "master class" (see Step 3). To define an alias, create a property named

    Alg.Alias.engineClassName.aliasName

where engineClassName is the name of an engine class (e.g., Signature), and aliasName is your alias name. The value of the property must be the standard algorithm (or type) name for the algorithm (or type) being aliased.

As an example, the "SUN" provider defines the alias "SHA1/DSA" for the signature algorithm whose standard name is "SHA1withDSA" by setting a property named Alg.Alias.Signature.SHA1/DSA to have the value SHA1withDSA via the following:

    put("Alg.Alias.Signature.SHA1/DSA", "SHA1withDSA");

Note that aliases defined by one provider are available only to that provider and not to any other providers. Thus, aliases defined by the SunJCE provider are available only to the SunJCE provider.

Service Interdependencies

Some algorithms require the use of other types of algorithms. For example, a PBE algorithm usually needs to use a message digest algorithm in order to transform a password into a key.

If you are implementing one type of algorithm that requires another, you can do one of the following:

  1. Provide your own implementations for both.
  2. Let your implementation of one algorithm use an instance of the other type of algorithm, as supplied by the default Sun provider that is included with every Java SE Platform installation. For example, if you are implementing a PBE algorithm that requires a message digest algorithm, you can obtain an instance of a class implementing the MD5 message digest algorithm by calling
        MessageDigest.getInstance("MD5", "SUN")
  3. Let your implementation of one algorithm use an instance of the other type of algorithm, as supplied by another specific provider. This is only appropriate if you are sure that all clients who will use your provider will also have the other provider installed.
  4. Let your implementation of one algorithm use an instance of the other type of algorithm, as supplied by another (unspecified) provider. That is, you can request an algorithm by name, but without specifying any particular provider, as in
        MessageDigest.getInstance("MD5")
    This is only appropriate if you are sure that there will be at least one implementation of the requested algorithm (in this case, MD5) installed on each Java platform where your provider will be used.

Here are some common types of algorithm interdependencies:

Signature and Message Digest Algorithms

A signature algorithm often requires use of a message digest algorithm. For example, the SHA1withDSA signature algorithm requires the SHA-1 message digest algorithm.

Signature and (Pseudo-)Random Number Generation Algorithms

A signature algorithm often requires use of a (pseudo-)random number generation algorithm. For example, such an algorithm is required in order to generate a DSA signature.

Key Pair Generation and Message Digest Algorithms

A key pair generation algorithm often requires use of a message digest algorithm. For example, DSA keys are generated using the SHA-1 message digest algorithm.

Algorithm Parameter Generation and Message Digest Algorithms

An algorithm parameter generator often requires use of a message digest algorithm. For example, DSA parameters are generated using the SHA-1 message digest algorithm.

KeyStores and Message Digest Algorithms

A keystore implementation will often utilize a message digest algorithm to compute keyed hashes (where the key is a user-provided password) to check the integrity of a keystore and make sure that the keystore has not been tampered with.

Key Pair Generation Algorithms and Algorithm Parameter Generators

A key pair generation algorithm sometimes needs to generate a new set of algorithm parameters. It can either generate the parameters directly, or use an algorithm parameter generator.

Key Pair Generation, Algorithm Parameter Generation, and (Pseudo-)Random Number Generation Algorithms

A key pair generation algorithm may require a source of randomness in order to generate a new key pair and possibly a new set of parameters associated with the keys. That source of randomness is represented by a SecureRandom object. The implementation of the key pair generation algorithm may generate the key parameters itself, or may use an algorithm parameter generator to generate them, in which case it may or may not initialize the algorithm parameter generator with a source of randomness.

Algorithm Parameter Generators and Algorithm Parameters

An algorithm parameter generator's engineGenerateParameters method must return an AlgorithmParameters instance.

Signature and Key Pair Generation Algorithms or Key Factories

If you are implementing a signature algorithm, your implementation's engineInitSign and engineInitVerify methods will require passed-in keys that are valid for the underlying algorithm (e.g., DSA keys for the DSS algorithm). You can do one of the following:

  1. Also create your own classes implementing appropriate interfaces (e.g. classes implementing the DSAPrivateKey and DSAPublicKey interfaces from the package java.security.interfaces), and create your own key pair generator and/or key factory returning keys of those types. Require the keys passed to engineInitSign and engineInitVerify to be the types of keys you have implemented, that is, keys generated from your key pair generator or key factory. Or you can,
  2. Accept keys from other key pair generators or other key factories, as long as they are instances of appropriate interfaces that enable your signature implementation to obtain the information it needs (such as the private and public keys and the key parameters). For example, the engineInitSign method for a DSS Signature class could accept any private keys that are instances of java.security.interfaces.DSAPrivateKey.

KeyStores and Key and Certificate Factories

A keystore implementation will often utilize a key factory to parse the keys stored in the keystore, and a certificate factory to parse the certificates stored in the keystore.

Default Initializations

In case the client does not explicitly initialize a key pair generator or an algorithm parameter generator, each provider of such a service must supply (and document) a default initialization. For example, the Sun provider uses a default modulus size (strength) of 1024 bits for the generation of DSA parameters, and the "SunJCE" provider uses a default modulus size (keysize) of 1024 bits for the generation of Diffie-Hellman parameters.

Default Key Pair Generator Parameter Requirements

If you implement a key pair generator, your implementation should supply default parameters that are used when clients don't specify parameters. The documentation you supply (Step 11) should state what the default parameters are.

For example, the DSA key pair generator in the Sun provider supplies a set of pre-computed p, q, and g default values for the generation of 512, 768, and 1024-bit key pairs. The following p, q, and g values are used as the default values for the generation of 1024-bit DSA key pairs:

p = fd7f5381 1d751229 52df4a9c 2eece4e7 f611b752 3cef4400 c31e3f80
    b6512669 455d4022 51fb593d 8d58fabf c5f5ba30 f6cb9b55 6cd7813b
    801d346f f26660b7 6b9950a5 a49f9fe8 047b1022 c24fbba9 d7feb7c6
    1bf83b57 e7c6a8a6 150f04fb 83f6d3c5 1ec30235 54135a16 9132f675
    f3ae2b61 d72aeff2 2203199d d14801c7

q = 9760508f 15230bcc b292b982 a2eb840b f0581cf5

g = f7e1a085 d69b3dde cbbcab5c 36b857b9 7994afbb fa3aea82 f9574c0b
    3d078267 5159578e bad4594f e6710710 8180b449 167123e8 4c281613
    b7cf0932 8cc8a6e1 3c167a8b 547c8d28 e0a3ae1e 2bb3a675 916ea37f
    0bfa2135 62f1fb62 7a01243b cca4f1be a8519089 a883dfe1 5ae59f06
    928b665e 807b5525 64014c3b fecf492a

(The p and q values given here were generated by the prime generation standard, using the 160-bit

SEED:  8d515589 4229d5e6 89ee01e6 018a237e 2cae64cd

With this seed, the algorithm found p and q when the counter was at 92.)

The Provider.Service Class

Since its introduction, security providers have published their service information via appropriately formatted key-value String pairs they put in their Hashtable entries. While this mechanism is simple and convenient, it limits the amount customization possible. As a result, JDK 5.0 introduced a second option, the Provider.Service class. It offers an alternative way for providers to advertise their services and supports additional features as described below. Note that this addition is fully compatible with the older method of using String valued Hashtable entries. A provider on JDK 5.0 can choose either method as it prefers, or even use both at the same time.

A Provider.Service object encapsulates all information about a service. This is the provider that offers the service, its type (e.g. MessageDigest or Signature), the algorithm name, and the name of the class that implements the service. Optionally, it also includes a list of alternate algorithm names for this service (aliases) and attributes, which are a map of (name, value) String pairs. In addition, it defines the methods newInstance() and supportsParameter(). They have default implementations, but can be overridden by providers if needed, as may be the case with providers that interface with hardware security tokens.

The newInstance() method is used by the security framework when it needs to construct new implementation instances. The default implementation uses reflection to invoke the standard constructor for the respective type of service. For all standard services except CertStore, this is the no-args constructor. The constructorParameter to newInstance() must be null in theses cases. For services of type CertStore, the constructor that takes a CertStoreParameters object is invoked, and constructorParameter must be a non-null instance of CertStoreParameters. A security provider can override the newInstance() method to implement instantiation as appropriate for that implementation. It could use direct invocation or call a constructor that passes additional information specific to the Provider instance or token. For example, if multiple Smartcard readers are present on the system, it might pass information about which reader the newly created service is to be associated with. However, despite customization all implementations must follow the conventions about constructorParameter described above.

The supportsParameter() tests whether the Service can use the specified parameter. It returns false if this service cannot use the parameter. It returns true if this service can use the parameter, if a fast test is infeasible, or if the status is unknown. It is used by the security framework with some types of services to quickly exclude non-matching implementations from consideration. It is currently only defined for the following standard services: Signature, Cipher, Mac, and KeyAgreement. The parameter must be an instance of Key in these cases. For example, for Signature services, the framework tests whether the service can use the supplied Key before instantiating the service. The default implementation examines the attributes SupportedKeyFormats and SupportedKeyClasses as described below. Again, a provider may override this methods to implement additional tests.

The SupportedKeyFormats attribute is a list of the supported formats for encoded keys (as returned by key.getFormat()) separated by the "|" (pipe) character. For example, X.509|PKCS#8. The SupportedKeyClasses attribute is a list of the names of classes of interfaces separated by the "|" character. A key object is considered to be acceptable if it is assignable to at least one of those classes or interfaces named. In other words, if the class of the key object is a subclass of one of the listed classes (or the class itself) or if it implements the listed interface. An example value is "java.security.interfaces.RSAPrivateKey|java.security.interfaces.RSAPublicKey" .

Four methods have been added to the Provider class for adding and looking up Services. As mentioned earlier, the implementation of those methods and also of the existing Properties methods have been specifically designed to ensure compatibility with existing Provider subclasses. This is achieved as follows:

If legacy Properties methods are used to add entries, the Provider class makes sure that the property strings are parsed into equivalent Service objects prior to lookup via getService(). Similarly, if the putService() method is used, equivalent property strings are placed into the provider's hashtable at the same time. If a provider implementation overrides any of the methods in the Provider class, it has to ensure that its implementation does not interfere with this conversion. To avoid problems, we recommend that implementations do not override any of the methods in the Provider class.

Signature Formats

If you implement a signature algorithm, the documentation you supply (Step 11) should specify the format in which the signature (generated by one of the sign methods) is encoded.

For example, the SHA1withDSA signature algorithm supplied by the Sun provider encodes the signature as a standard ASN.1 sequence of two ASN.1 INTEGER values: r and s, in that order:

SEQUENCE ::= {
        r INTEGER,
        s INTEGER }

DSA Interfaces and their Required Implementations

The Java Security API contains the following interfaces (in the java.security.interfaces package) for the convenience of programmers implementing DSA services:

  • DSAKey
  • DSAKeyPairGenerator
  • DSAParams
  • DSAPrivateKey
  • DSAPublicKey

The following sections discuss requirements for implementations of these interfaces.

DSAKeyPairGenerator Implementation

This interface is obsolete. It used to be needed to enable clients to provide DSA-specific parameters to be used rather than the default parameters your implementation supplies. However, in Java it is no longer necessary; a new KeyPairGenerator initialize method that takes an AlgorithmParameterSpec parameter enables clients to indicate algorithm-specific parameters.

DSAParams Implementation

If you are implementing a DSA key pair generator, you need a class implementing DSAParams for holding and returning the p, q, and g parameters.

A DSAParams implementation is also required if you implement the DSAPrivateKey and DSAPublicKey interfaces. DSAPublicKey and DSAPrivateKey both extend the DSAKey interface, which contains a getParams method that must return a DSAParams object. See DSAPrivateKey and DSAPublicKey Implementations for more information.

Note: there is a DSAParams implementation built into the JDK: the java.security.spec.DSAParameterSpec class.

DSAPrivateKey and DSAPublicKey Implementations

If you implement a DSA key pair generator or key factory, you need to create classes implementing the DSAPrivateKey and DSAPublicKey interfaces.

If you implement a DSA key pair generator, your generateKeyPair method (in your KeyPairGeneratorSpi subclass) will return instances of your implementations of those interfaces.

If you implement a DSA key factory, your engineGeneratePrivate method (in your KeyFactorySpi subclass) will return an instance of your DSAPrivateKey implementation, and your engineGeneratePublic method will return an instance of your DSAPublicKey implementation.

Also, your engineGetKeySpec and engineTranslateKey methods will expect the passed-in key to be an instance of a DSAPrivateKey or DSAPublicKey implementation. The getParams method provided by the interface implementations is useful for obtaining and extracting the parameters from the keys and then using the parameters, for example as parameters to the DSAParameterSpec constructor called to create a parameter specification from parameter values that could be used to initialize a KeyPairGenerator object for DSA.

If you implement a DSA signature algorithm, your engineInitSign method (in your SignatureSpi subclass) will expect to be passed a DSAPrivateKey and your engineInitVerify method will expect to be passed a DSAPublicKey.

Please note: The DSAPublicKey and DSAPrivateKey interfaces define a very generic, provider-independent interface to DSA public and private keys, respectively. The engineGetKeySpec and engineTranslateKey methods (in your KeyFactorySpi subclass) could additionally check if the passed-in key is actually an instance of their provider's own implementation of DSAPrivateKey or DSAPublicKey, e.g., to take advantage of provider-specific implementation details. The same is true for the DSA signature algorithm engineInitSign and engineInitVerify methods (in your SignatureSpi subclass).

To see what methods need to be implemented by classes that implement the DSAPublicKey and DSAPrivateKey interfaces, first note the following interface signatures:

In the java.security.interfaces package:

   public interface DSAPrivateKey extends DSAKey,
                java.security.PrivateKey

   public interface DSAPublicKey extends DSAKey,
                java.security.PublicKey

   public interface DSAKey

In the java.security package:

   public interface PrivateKey extends Key

   public interface PublicKey extends Key

   public interface Key extends java.io.Serializable

In order to implement the DSAPrivateKey and DSAPublicKey interfaces, you must implement the methods they define as well as those defined by interfaces they extend, directly or indirectly.

Thus, for private keys, you need to supply a class that implements

  • the getX method from the DSAPrivateKey interface.
  • the getParams method from the java.security.interfaces.DSAKey interface, since DSAPrivateKey extends DSAKey. Note: The getParams method returns a DSAParams object, so you must also have a DSAParams implementation.
  • the getAlgorithm, getEncoded, and getFormat methods from the java.security.Key interface, since DSAPrivateKey extends java.security.PrivateKey, and PrivateKey extends Key.

    Similarly, for public DSA keys, you need to supply a class that implements:

    • the getY method from the DSAPublicKey interface.
    • the getParams method from the java.security.interfaces.DSAKey interface, since DSAPublicKey extends DSAKey. Note: The getParams method returns a DSAParams object, so you must also have a DSAParams implementation.
    • the getAlgorithm, getEncoded, and getFormat methods from the java.security.Key interface, since DSAPublicKey extends java.security.PublicKey, and PublicKey extends Key.

RSA Interfaces and their Required Implementations

The Java Security API contains the following interfaces (in the java.security.interfaces package) for the convenience of programmers implementing RSA services:

  • RSAPrivateKey
  • RSAPrivateCrtKey
  • RSAPublicKey

The following sections discuss requirements for implementations of these interfaces.

RSAPrivateKey , RSAPrivateCrtKey , and RSAPublicKey Implementations

If you implement an RSA key pair generator or key factory, you need to create classes implementing the RSAPrivateKey (and/or RSAPrivateCrtKey) and RSAPublicKey interfaces. (RSAPrivateCrtKey is the interface to an RSA private key, using the Chinese Remainder Theorem (CRT) representation.)

If you implement an RSA key pair generator, your generateKeyPair method (in your KeyPairGeneratorSpi subclass) will return instances of your implementations of those interfaces.

If you implement an RSA key factory, your engineGeneratePrivate method (in your KeyFactorySpi subclass) will return an instance of your RSAPrivateKey (or RSAPrivateCrtKey) implementation, and your engineGeneratePublic method will return an instance of your RSAPublicKey implementation.

Also, your engineGetKeySpec and engineTranslateKey methods will expect the passed-in key to be an instance of an RSAPrivateKey, RSAPrivateCrtKey, or RSAPublicKey implementation.

If you implement an RSA signature algorithm, your engineInitSign method (in your SignatureSpi subclass) will expect to be passed either an RSAPrivateKey or an RSAPrivateCrtKey, and your engineInitVerify method will expect to be passed an RSAPublicKey.

Please note: The RSAPublicKey, RSAPrivateKey, and RSAPrivateCrtKey interfaces define a very generic, provider-independent interface to RSA public and private keys. The engineGetKeySpec and engineTranslateKey methods (in your KeyFactorySpi subclass) could additionally check if the passed-in key is actually an instance of their provider's own implementation of RSAPrivateKey, RSAPrivateCrtKey, or RSAPublicKey, e.g., to take advantage of provider-specific implementation details. The same is true for the RSA signature algorithm engineInitSign and engineInitVerify methods (in your SignatureSpi subclass).

To see what methods need to be implemented by classes that implement the RSAPublicKey, RSAPrivateKey, and RSAPrivateCrtKey interfaces, first note the following interface signatures:

In the java.security.interfaces package:

    public interface RSAPrivateKey extends java.security.PrivateKey

    public interface RSAPrivateCrtKey extends RSAPrivateKey

    public interface RSAPublicKey extends java.security.PublicKey

In the java.security package:

    public interface PrivateKey extends Key

    public interface PublicKey extends Key

    public interface Key extends java.io.Serializable

In order to implement the RSAPrivateKey, RSAPrivateCrtKey, and RSAPublicKey interfaces, you must implement the methods they define as well as those defined by interfaces they extend, directly or indirectly.

Thus, for RSA private keys, you need to supply a class that implements:

  • the getModulus and getPrivateExponent methods from the RSAPrivateKey interface.
  • the getAlgorithm, getEncoded, and getFormat methods from the java.security.Key interface, since RSAPrivateKey extends java.security.PrivateKey, and PrivateKey extends Key.

Similarly, for RSA private keys using the Chinese Remainder Theorem (CRT) representation, you need to supply a class that implements:

  • all the methods listed above for RSA private keys, since RSAPrivateCrtKey extends java.security.interfaces.RSAPrivateKey.
  • the getPublicExponent, getPrimeP, getPrimeQ, getPrimeExponentP, getPrimeExponentQ, and getCrtCoefficient methods from the RSAPrivateKey interface.

For public RSA keys, you need to supply a class that implements:

  • the getModulus and getPublicExponent methods from the RSAPublicKey interface.
  • the getAlgorithm, getEncoded, and getFormat methods from the java.security.Key interface, since RSAPublicKey extends java.security.PublicKey, and PublicKey extends Key.

JCA contains a number of AlgorithmParameterSpec implementations for the most frequently used cipher and key agreement algorithm parameters. If you are operating on algorithm parameters that should be for a different type of algorithm not provided by JCA, you will need to supply your own AlgorithmParameterSpec implementation appropriate for that type of algorithm.

Diffie-Hellman Interfaces and their Required Implementations

JCA contains the following interfaces (in the javax.crypto.interfaces package) for the convenience of programmers implementing Diffie-Hellman services:

  • DHKey
  • DHPrivateKey
  • DHPublicKey

The following sections discuss requirements for implementations of these interfaces.

DHPrivateKey and DHPublicKey Implementations

If you implement a Diffie-Hellman key pair generator or key factory, you need to create classes implementing the DHPrivateKey and DHPublicKey interfaces.

If you implement a Diffie-Hellman key pair generator, your generateKeyPair method (in your KeyPairGeneratorSpi subclass) will return instances of your implementations of those interfaces.

If you implement a Diffie-Hellman key factory, your engineGeneratePrivate method (in your KeyFactorySpi subclass) will return an instance of your DHPrivateKey implementation, and your engineGeneratePublic method will return an instance of your DHPublicKey implementation.

Also, your engineGetKeySpec and engineTranslateKey methods will expect the passed-in key to be an instance of a DHPrivateKey or DHPublicKey implementation. The getParams method provided by the interface implementations is useful for obtaining and extracting the parameters from the keys. You can then use the parameters, for example, as parameters to the DHParameterSpec constructor called to create a parameter specification from parameter values used to initialize a KeyPairGenerator object for Diffie-Hellman.

If you implement the Diffie-Hellman key agreement algorithm, your engineInit method (in your KeyAgreementSpi subclass) will expect to be passed a DHPrivateKey and your engineDoPhase method will expect to be passed a DHPublicKey.

Note: The DHPublicKey and DHPrivateKey interfaces define a very generic, provider-independent interface to Diffie-Hellman public and private keys, respectively. The engineGetKeySpec and engineTranslateKey methods (in your KeyFactorySpi subclass) could additionally check if the passed-in key is actually an instance of their provider's own implementation of DHPrivateKey or DHPublicKey, e.g., to take advantage of provider-specific implementation details. The same is true for the Diffie-Hellman algorithm engineInit and engineDoPhase methods (in your KeyAgreementSpi subclass).

To see what methods need to be implemented by classes that implement the DHPublicKey and DHPrivateKey interfaces, first note the following interface signatures:

In the javax.crypto.interfaces package:

    public interface DHPrivateKey extends DHKey, java.security.PrivateKey

    public interface DHPublicKey extends DHKey, java.security.PublicKey

    public interface DHKey

In the java.security package:

    public interface PrivateKey extends Key

    public interface PublicKey extends Key

    public interface Key extends java.io.Serializable

To implement the DHPrivateKey and DHPublicKey interfaces, you must implement the methods they define as well as those defined by interfaces they extend, directly or indirectly.

Thus, for private keys, you need to supply a class that implements:

  • the getX method from the DHPrivateKey interface.
  • the getParams method from the javax.crypto.interfaces.DHKey interface, since DHPrivateKey extends DHKey.
  • the getAlgorithm, getEncoded, and getFormat methods from the java.security.Key interface, since DHPrivateKey extends java.security.PrivateKey, and PrivateKey extends Key.

Similarly, for public Diffie-Hellman keys, you need to supply a class that implements:

  • the getY method from the DHPublicKey interface.
  • the getParams method from the javax.crypto.interfaces.DHKey interface, since DHPublicKey extends DHKey.
  • the getAlgorithm, getEncoded, and getFormat methods from the java.security.Key interface, since DHPublicKey extends java.security.PublicKey, and PublicKey extends Key.

Interfaces for Other Algorithm Types

As noted above, the Java Security API contains interfaces for the convenience of programmers implementing services like DSA, RSA and ECC. If there are services without API support, you need to define your own APIs.

If you are implementing a key pair generator for a different algorithm, you should create an interface with one or more initialize methods that clients can call when they want to provide algorithm-specific parameters to be used rather than the default parameters your implementation supplies. Your subclass of KeyPairGeneratorSpi should implement this interface.

For algorithms without direct API support, it is recommended that you create similar interfaces and provide implementation classes. Your public key interface should extend the PublicKey interface. Similarly, your private key interface should extend the PrivateKey interface.

Algorithm Parameter Specification Interfaces and Classes

An algorithm parameter specification is a transparent representation of the sets of parameters used with an algorithm.

A transparent representation of parameters means that you can access each value individually, through one of the get methods defined in the corresponding specification class (e.g., DSAParameterSpec defines getP, getQ, and getG methods, to access the p, q, and g parameters, respectively).

This is contrasted with an opaque representation, as supplied by the AlgorithmParameters engine class, in which you have no direct access to the key material values; you can only get the name of the algorithm associated with the parameter set (via getAlgorithm) and some kind of encoding for the parameter set (via getEncoded).

If you supply an AlgorithmParametersSpi, AlgorithmParameterGeneratorSpi, or KeyPairGeneratorSpi implementation, you must utilize the AlgorithmParameterSpec interface, since each of those classes contain methods that take an AlgorithmParameterSpec parameter. Such methods need to determine which actual implementation of that interface has been passed in, and act accordingly.

JCA contains a number of AlgorithmParameterSpec implementations for the most frequently used signature, cipher and key agreement algorithm parameters. If you are operating on algorithm parameters that should be for a different type of algorithm not provided by JCA, you will need to supply your own AlgorithmParameterSpec implementation appropriate for that type of algorithm.

Java defines the following algorithm parameter specification interfaces and classes in the java.security.spec and javax.crypto.spec packages:

The AlgorithmParameterSpec Interface

AlgorithmParameterSpec is an interface to a transparent specification of cryptographic parameters.

This interface contains no methods or constants. Its only purpose is to group (and provide type safety for) all parameter specifications. All parameter specifications must implement this interface.

The DSAParameterSpec Class

This class (which implements the AlgorithmParameterSpec and DSAParams interfaces) specifies the set of parameters used with the DSA algorithm. It has the following methods:

    public BigInteger getP()

    public BigInteger getQ()

    public BigInteger getG()

These methods return the DSA algorithm parameters: the prime p, the sub-prime q, and the base g.

Many types of DSA services will find this class useful - for example, it is utilized by the DSA signature, key pair generator, algorithm parameter generator, and algorithm parameters classes implemented by the Sun provider. As a specific example, an algorithm parameters implementation must include an implementation for the getParameterSpec method, which returns an AlgorithmParameterSpec. The DSA algorithm parameters implementation supplied by Sun returns an instance of the DSAParameterSpec class.

The IvParameterSpec Class

This class (which implements the AlgorithmParameterSpec interface) specifies the initialization vector (IV) used with a cipher in feedback mode.

Method in IvParameterSpec
Method | Description
byte[] getIV() | Returns the initialization vector (IV).

The OAEPParameterSpec Class

This class specifies the set of parameters used with OAEP Padding, as defined in the PKCS #1 standard.

Methods in OAEPParameterSpec
Method | Description
String getDigestAlgorithm() | Returns the message digest algorithm name.
String getMGFAlgorithm() | Returns the mask generation function algorithm name.
AlgorithmParameterSpec getMGFParameters() | Returns the parameters for the mask generation function.
PSource getPSource() | Returns the source of encoding input P.

The PBEParameterSpec Class

This class (which implements the AlgorithmParameterSpec interface) specifies the set of parameters used with a password-based encryption (PBE) algorithm.

Methods in PBEParameterSpec
Method | Description
int getIterationCount() | Returns the iteration count.
byte[] getSalt() | Returns the salt.

The RC2ParameterSpec Class

This class (which implements the AlgorithmParameterSpec interface) specifies the set of parameters used with the RC2 algorithm.

Methods in RC2ParameterSpec
Method | Description
boolean equals(Object obj) | Tests for equality between the specified object and this object.
int getEffectiveKeyBits() | Returns the effective key size in bits.
byte[] getIV() | Returns the IV or null if this parameter set does not contain an IV.
int hashCode() | Calculates a hash code value for the object.

The RC5ParameterSpec Class

This class (which implements the AlgorithmParameterSpec interface) specifies the set of parameters used with the RC5 algorithm.

Methods in RC5ParameterSpec
Method | Description
boolean equals(Object obj) | Tests for equality between the specified object and this object.
byte[] getIV() | Returns the IV or null if this parameter set does not contain an IV.
int getRounds() | Returns the number of rounds.
int getVersion() | Returns the version.
int getWordSize() | Returns the word size in bits.
int hashCode() | Calculates a hash code value for the object.

The DHParameterSpec Class

This class (which implements the AlgorithmParameterSpec interface) specifies the set of parameters used with the Diffie-Hellman algorithm.

Methods in DHParameterSpec
Method | Description
BigInteger getG() | Returns the base generator g.
int getL() | Returns the size in bits, l, of the random exponent (private value).
BigInteger getP() | Returns the prime modulus p.

Many types of Diffie-Hellman services will find this class useful; for example, it is used by the Diffie-Hellman key agreement, key pair generator, algorithm parameter generator, and algorithm parameters classes implemented by the "SunJCE" provider. As a specific example, an algorithm parameters implementation must include an implementation for the getParameterSpec method, which returns an AlgorithmParameterSpec. The Diffie-Hellman algorithm parameters implementation supplied by "SunJCE" returns an instance of the DHParameterSpec class.

Key Specification Interfaces and Classes Required by Key Factories

A key factory provides bi-directional conversions between opaque keys (of type Key) and key specifications. If you implement a key factory, you thus need to understand and utilize key specifications. In some cases, you also need to implement your own key specifications.

Further information about key specifications, the interfaces and classes supplied in Java, and key factory requirements with respect to specifications, is provided below.

Key specifications are transparent representations of the key material that constitutes a key. If the key is stored on a hardware device, its specification may contain information that helps identify the key on the device.

A transparent representation of keys means that you can access each key material value individually, through one of the get methods defined in the corresponding specification class. For example, java.security.spec.DSAPrivateKeySpec defines getX, getP, getQ, and getG methods, to access the private key x, and the DSA algorithm parameters used to calculate the key: the prime p, the sub-prime q, and the base g.

This is contrasted with an opaque representation, as defined by the Key interface, in which you have no direct access to the parameter fields. In other words, an "opaque" representation gives you limited access to the key - just the three methods defined by the Key interface: getAlgorithm, getFormat, and getEncoded.

A key may be specified in an algorithm-specific way, or in an algorithm-independent encoding format (such as ASN.1). For example, a DSA private key may be specified by its components x, p, q, and g (see DSAPrivateKeySpec), or it may be specified using its DER encoding (see PKCS8EncodedKeySpec).

Java defines the following key specification interfaces and classes in the java.security.spec and javax.crypto.spec packages:

The KeySpec Interface

This interface contains no methods or constants. Its only purpose is to group (and provide type safety for) all key specifications. All key specifications must implement this interface.

Java supplies several classes implementing the KeySpec interface: DSAPrivateKeySpec, DSAPublicKeySpec, RSAPrivateKeySpec, RSAPublicKeySpec, EncodedKeySpec, PKCS8EncodedKeySpec, and X509EncodedKeySpec.

If your provider uses key types (e.g., Your_PublicKey_type and Your_PrivateKey_type) for which the JDK does not already provide corresponding KeySpec classes, there are two possible scenarios, one of which requires that you implement your own key specifications:

  1. If your users will never have to access specific key material values of your key type, you will not have to provide any KeySpec classes for your key type.

    In this scenario, your users will always create Your_PublicKey_type and Your_PrivateKey_type keys through the appropriate KeyPairGenerator supplied by your provider for that key type. If they want to store the generated keys for later usage, they retrieve the keys' encodings (using the getEncoded method of the Key interface). When they want to create an Your_PublicKey_type or Your_PrivateKey_type key from the encoding (e.g., in order to initialize a Signature object for signing or verification), they create an instance of X509EncodedKeySpec or PKCS8EncodedKeySpec from the encoding, and feed it to the appropriate KeyFactory supplied by your provider for that algorithm, whose generatePublic and generatePrivate methods will return the requested PublicKey (an instance of Your_PublicKey_type) or PrivateKey (an instance of Your_PrivateKey_type) object, respectively.
  2. If you anticipate a need for users to access specific key material values of your key type, or to construct a key of your key type from key material and associated parameter values, rather than from its encoding (as in the above case), you have to specify new KeySpec classes (classes that implement the KeySpec interface) with the appropriate constructor methods and get methods for returning key material fields and associated parameter values for your key type. You will specify those classes in a similar manner as is done by the DSAPrivateKeySpec and DSAPublicKeySpec classes provided in JDK 6. You need to ship those classes along with your provider classes, for example, as part of your provider JAR file.

The DSAPrivateKeySpec Class

This class (which implements the KeySpec Interface) specifies a DSA private key with its associated parameters. It has the following methods:

Method in DSAPrivateKeySpec | Description
public BigInteger getX() | Returns the private key x.
public BigInteger getP() | Returns the prime p.
public BigInteger getQ() | Returns the sub-prime q.
public BigInteger getG() | Returns the base g.

These methods return the private key x, and the DSA algorithm parameters used to calculate the key: the prime p, the sub-prime q, and the base g.

The DSAPublicKeySpec Class

This class (which implements the KeySpec Interface) specifies a DSA public key with its associated parameters. It has the following methods:

Method in DSAPublicKeySpec | Description
public BigInteger getY() | returns the public key y.
public BigInteger getP() | Returns the prime p.
public BigInteger getQ() | Returns the sub-prime q.
public BigInteger getG() | Returns the base g.

These methods return the public key y, and the DSA algorithm parameters used to calculate the key: the prime p, the sub-prime q, and the base g.

The RSAPrivateKeySpec Class

This class (which implements the KeySpec Interface) specifies an RSA private key. It has the following methods:

Method in RSAPrivateKeySpec | Description
public BigInteger getModulus() | Returns the modulus.
public BigInteger getPrivateExponent() | Returns the private exponent.

These methods return the RSA modulus n and private exponent d values that constitute the RSA private key.

The RSAPrivateCrtKeySpec Class

This class (which extends the RSAPrivateKeySpec class) specifies an RSA private key, as defined in the PKCS#1 standard, using the Chinese Remainder Theorem (CRT) information values. It has the following methods (in addition to the methods inherited from its superclass RSAPrivateKeySpec ):

Method in RSAPrivateCrtKeySpec | Description
public BigInteger getPublicExponent() | Returns the public exponent.
public BigInteger getPrimeP() | Returns the prime P.
public BigInteger getPrimeQ() | Returns the prime Q.
public BigInteger getPrimeExponentP() | Returns the primeExponentP.
public BigInteger getPrimeExponentQ() | Returns the primeExponentQ.
public BigInteger getCrtCoefficient() | Returns the crtCoefficient.

These methods return the public exponent e and the CRT information integers: the prime factor p of the modulus n, the prime factor q of n, the exponent d mod (p-1), the exponent d mod (q-1), and the Chinese Remainder Theorem coefficient (inverse of q) mod p.

An RSA private key logically consists of only the modulus and the private exponent. The presence of the CRT values is intended for efficiency.

The RSAPublicKeySpec Class

This class (which implements the KeySpec Interface) specifies an RSA public key. It has the following methods:

Method in RSAPublicKeySpec | Description
public BigInteger getModulus() | Returns the modulus.
public BigInteger getPublicExponent() | Returns the public exponent.

These methods return the RSA modulus n and public exponent e values that constitute the RSA public key.

The EncodedKeySpec Class

This abstract class (which implements the KeySpec Interface) represents a public or private key in encoded format.

Method in EncodedKeySpec | Description
public abstract byte[] getEncoded() | Returns the encoded key.
public abstract String getFormat() | Returns the name of the encoding format.

JDK 6 supplies two classes implementing the EncodedKeySpec interface: PKCS8EncodedKeySpec and X509EncodedKeySpec. If desired, you can supply your own EncodedKeySpec implementations for those or other types of key encodings.

The PKCS8EncodedKeySpec Class

This class, which is a subclass of EncodedKeySpec, represents the DER encoding of a private key, according to the format specified in the PKCS #8 standard.

Its getEncoded method returns the key bytes, encoded according to the PKCS #8 standard. Its getFormat method returns the string "PKCS#8".

The X509EncodedKeySpec Class

This class, which is a subclass of EncodedKeySpec, represents the DER encoding of a public or private key, according to the format specified in the X.509 standard.

Its getEncoded method returns the key bytes, encoded according to the X.509 standard. Its getFormat method returns the string "X.509". DHPrivateKeySpec, DHPublicKeySpec, DESKeySpec, DESedeKeySpec, PBEKeySpec, and SecretKeySpec.

The DHPrivateKeySpec Class

This class (which implements the KeySpec interface) specifies a Diffie-Hellman private key with its associated parameters.

Method in DHPrivateKeySpec | Description
BigInteger getG() | Returns the base generator g.
BigInteger getP() | Returns the prime modulus p.
BigInteger getX() | Returns the private value x.

The DHPublicKeySpec Class

This class (which implements the KeySpec interface) specifies a Diffie-Hellman public key with its associated parameters.

Method in DHPublicKeySpec | Description
BigInteger getG() | Returns the base generator g.
BigInteger getP() | Returns the prime modulus p.
BigInteger getY() | Returns the public value y.

The DESKeySpec Class

This class (which implements the KeySpec interface) specifies a DES key.

Method in DESKeySpec | Description
byte[] getKey() | Returns the DES key bytes.
static boolean isParityAdjusted(byte[] key, int offset) | Checks if the given DES key material is parity-adjusted.
static boolean isWeak(byte[] key, int offset) | Checks if the given DES key material is weak or semi-weak.

The DESedeKeySpec Class

This class (which implements the KeySpec interface) specifies a DES-EDE (Triple DES) key.

Method in DESedeKeySpec | Description
byte[] getKey() | Returns the DES-EDE key.
static boolean isParityAdjusted(byte[] key, int offset) | Checks if the given DES-EDE key is parity-adjusted.

The PBEKeySpec Class

This class implements the KeySpec interface. A user-chosen password can be used with password-based encryption (PBE); the password can be viewed as a type of raw key material. An encryption mechanism that uses this class can derive a cryptographic key from the raw key material.

Method in PBEKeySpec | Description
void clearPassword | Clears the internal copy of the password.
int getIterationCount | Returns the iteration count or 0 if not specified.
int getKeyLength | Returns the to-be-derived key length or 0 if not specified.
char[] getPassword | Returns a copy of the password.
byte[] getSalt | Returns a copy of the salt or null if not specified.

The SecretKeySpec Class

This class implements the KeySpec interface. Since it also implements the SecretKey interface, it can be used to construct a SecretKey object in a provider-independent fashion, i.e., without having to go through a provider-based SecretKeyFactory.

Method in SecretKeySpec | Description
boolean equals (Object obj) | Indicates whether some other object is "equal to" this one.
String getAlgorithm() | Returns the name of the algorithm associated with this secret key.
byte[] getEncoded() | Returns the key material of this secret key.
String getFormat() | Returns the name of the encoding format for this secret key.
int hashCode() | Calculates a hash code value for the object.

Secret-Key Generation

If you provide a secret-key generator (subclass of javax.crypto.KeyGeneratorSpi) for a particular secret-key algorithm, you may return the generated secret-key object (which must be an instance of javax.crypto.SecretKey, see engineGenerateKey) in one of the following ways:

  • You implement a class whose instances represent secret-keys of the algorithm associated with your key generator. Your key generator implementation returns instances of that class. This approach is useful if the keys generated by your key generator have provider-specific properties.
  • Your key generator returns an instance of SecretKeySpec, which already implements the javax.crypto.SecretKey interface. You pass the (raw) key bytes and the name of the secret-key algorithm associated with your key generator to the SecretKeySpec constructor. This approach is useful if the underlying (raw) key bytes can be represented as a byte array and have no key-parameters associated with them.

Adding New Object Identifiers

The following information applies to providers who supply an algorithm that is not listed as one of the standard algorithms in Appendix A of the Java Cryptography Architecture Reference Guide.

Mapping from OID to Name

Sometimes the JCA needs to instantiate a cryptographic algorithm implementation from an algorithm identifier (for example, as encoded in a certificate), which by definition includes the object identifier (OID) of the algorithm. For example, in order to verify the signature on an X.509 certificate, the JCA determines the signature algorithm from the signature algorithm identifier that is encoded in the certificate, instantiates a Signature object for that algorithm, and initializes the Signature object for verification.

For the JCA to find your algorithm, you must provide the object identifier of your algorithm as an alias entry for your algorithm in the provider master file.

    put("Alg.Alias.<engine_type>.1.2.3.4.5.6.7.8",
        "<algorithm_alias_name>");

Note that if your algorithm is known under more than one object identifier, you need to create an alias entry for each object identifier under which it is known.

An example of where the JCA needs to perform this type of mapping is when your algorithm ("Foo") is a signature algorithm and users run the keytool command and specify your (signature) algorithm alias.

    % keytool -genkeypair -sigalg 1.2.3.4.5.6.7.8

In this case, your provider master file should contain the following entries:

    put("Signature.Foo", "com.xyz.MyFooSignatureImpl");
    put("Alg.Alias.Signature.1.2.3.4.5.6.7.8", "Foo");

Other examples of where this type of mapping is performed are (1) when your algorithm is a keytype algorithm and your program parses a certificate (using the X.509 implementation of the SUN provider) and extracts the public key from the certificate in order to initialize a Signature object for verification, and (2) when keytool users try to access a private key of your keytype (for example, to perform a digital signature) after having generated the corresponding keypair. In these cases, your provider master file should contain the following entries:

    put("KeyFactory.Foo", "com.xyz.MyFooKeyFactoryImpl");
    put("Alg.Alias.KeyFactory.1.2.3.4.5.6.7.8", "Foo");

Mapping from Name to OID

If the JCA needs to perform the inverse mapping (that is, from your algorithm name to its associated OID), you need to provide an alias entry of the following form for one of the OIDs under which your algorithm should be known:

    put("Alg.Alias.Signature.OID.1.2.3.4.5.6.7.8", "MySigAlg");

If your algorithm is known under more than one object identifier, prefix the preferred one with "OID."

An example of where the JCA needs to perform this kind of mapping is when users run keytool in any mode that takes a -sigalg option. For example, when the -genkeypair and -certreq commands are invoked, the user can specify your (signature) algorithm with the -sigalg option.

Ensuring Exportability

A key feature of JCA is the exportability of the JCA framework and of the provider cryptography implementations if certain conditions are met.

Due to import control restrictions by the governments of a few countries, the jurisdiction policy files shipped with the JDK 6 from Sun Microsystems specify that "strong" but limited cryptography may be used. An "unlimited" version of these files indicating no restrictions on cryptographic strengths is available for those living in eligible countries (which is most countries). But only the "strong" version can be imported into those countries whose governments mandate restrictions. The JCA framework will enforce the restrictions specified in the installed jurisdiction policy files.

As noted elsewhere, you can write just one version of your provider software, implementing cryptography of maximum strength. It is up to JCA, not your provider, to enforce any jurisdiction policy file-mandated restrictions regarding the cryptographic algorithms and maximum cryptographic strengths available to applets/applications in different locations.

The conditions that must be met by your provider in order to enable it to be plugged into JCA are the following:

  • The constructor of each SPI implementation class should do self-integrity checking, as described in How a Provider Can Do Self-Integrity Checking.
  • The provider code should be written in such a way that provider classes become unusable if instantiated by an application directly, bypassing JCA. See Step 1: Write Your Service Implementation Code in the Steps to Implement and Integrate a Provider section.
  • The provider package must be signed by an entity trusted by the JCA framework. (See Step 6.1 through Step 6.2.) U.S. vendors whose providers may be exported outside the U.S. first need to apply for U.S. government export approval. (See Step 10.)

Appendix A: The Sun Provider Master Class

Below is an edited version of the Sun.java file, which contains a class named Sun that is the master class for the provider named Sun.

As with all master classes, this class is a subclass of Provider. It specifies the class names and package locations of all service implementations supplied by the Sun provider. This information is used by the getInstance methods of the engine classes to look up the various algorithms and other services when they are requested.

This code is supplied as an example of a provider master class.

/*
 * @(#)Sun.java 1.28 99/05/27
 *
 * Copyright (c) 1996, 1998, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package sun.security.provider;

import java.io.*;
import java.util.*;
import java.security.*;

/**
 * The SUN Security Provider.
 *
 * @author Benjamin Renaud
 *
 * @version 1.28, 05/27/99
 */

/**
 * Defines the SUN provider.
 *
 * Algorithms supported, and their names:
 *
 * - SHA is the message digest scheme described in FIPS 180-1.
 *   Aliases for SHA are SHA-1 and SHA1.
 *
 * - SHA1withDSA is the signature scheme described in FIPS 186.
 *   (SHA used in DSA is SHA-1: FIPS 186 with Change No 1.)
 *   Aliases for SHA1withDSA are DSA, DSS, SHA/DSA, SHA-1/DSA, SHA1/DSA,
 *   SHAwithDSA, DSAWithSHA1, and the object
 *   identifier strings "OID.1.3.14.3.2.13", "OID.1.3.14.3.2.27" and
 *   "OID.1.2.840.10040.4.3".
 *
 * - DSA is the key generation scheme as described in FIPS 186.
 *   Aliases for DSA include the OID strings "OID.1.3.14.3.2.12"
 *   and "OID.1.2.840.10040.4.1".
 *
 * - MD5 is the message digest scheme described in RFC 1321.
 *   There are no aliases for MD5.
 */

public final class Sun extends Provider {

    private static final String INFO = "SUN " +
    "(DSA key/parameter generation; DSA signing; " +
    "SHA-1, MD5 digests; SecureRandom; X.509 certificates; JKS keystore)";

    public Sun() {
        /* We are the SUN provider */
        super("SUN", 1.2, INFO);

        AccessController.doPrivileged(new java.security.PrivilegedAction() {
            public Object run() {

                /*
                 * Signature engines
                 */
                put("Signature.SHA1withDSA", "sun.security.provider.DSA");

                put("Alg.Alias.Signature.DSA", "SHA1withDSA");
                put("Alg.Alias.Signature.DSS", "SHA1withDSA");
                put("Alg.Alias.Signature.SHA/DSA", "SHA1withDSA");
                put("Alg.Alias.Signature.SHA-1/DSA", "SHA1withDSA");
                put("Alg.Alias.Signature.SHA1/DSA", "SHA1withDSA");
                put("Alg.Alias.Signature.SHAwithDSA", "SHA1withDSA");
                put("Alg.Alias.Signature.DSAWithSHA1", "SHA1withDSA");
                put("Alg.Alias.Signature.OID.1.2.840.10040.4.3",
                    "SHA1withDSA");
                put("Alg.Alias.Signature.1.2.840.10040.4.3", "SHA1withDSA");
                put("Alg.Alias.Signature.1.3.14.3.2.13", "SHA1withDSA");
                put("Alg.Alias.Signature.1.3.14.3.2.27", "SHA1withDSA");

                /*
                 *  Key Pair Generator engines
                 */
                put("KeyPairGenerator.DSA",
                    "sun.security.provider.DSAKeyPairGenerator");
                put("Alg.Alias.KeyPairGenerator.OID.1.2.840.10040.4.1", "DSA");
                put("Alg.Alias.KeyPairGenerator.1.2.840.10040.4.1", "DSA");
                put("Alg.Alias.KeyPairGenerator.1.3.14.3.2.12", "DSA");

                /*
                 * Digest engines
                 */
                put("MessageDigest.MD5", "sun.security.provider.MD5");
                put("MessageDigest.SHA", "sun.security.provider.SHA");

                put("Alg.Alias.MessageDigest.SHA-1", "SHA");
                put("Alg.Alias.MessageDigest.SHA1", "SHA");

                /*
                 * Algorithm Parameter Generator engines
                 */
                put("AlgorithmParameterGenerator.DSA",
                    "sun.security.provider.DSAParameterGenerator");

                /*
                 * Algorithm Parameter engines
                 */
                put("AlgorithmParameters.DSA",
                    "sun.security.provider.DSAParameters");
                put("Alg.Alias.AlgorithmParameters.1.3.14.3.2.12", "DSA");
                put("Alg.Alias.AlgorithmParameters.1.2.840.10040.4.1", "DSA");

                /*
                 * Key factories
                 */
                put("KeyFactory.DSA", "sun.security.provider.DSAKeyFactory");
                put("Alg.Alias.KeyFactory.1.3.14.3.2.12", "DSA");
                put("Alg.Alias.KeyFactory.1.2.840.10040.4.1", "DSA");

                /*
                 * SecureRandom
                 */
                 put("SecureRandom.SHA1PRNG",
                     "sun.security.provider.SecureRandom");

                /*
                 * Certificates
                 */
                put("CertificateFactory.X509",
                    "sun.security.provider.X509Factory");
                put("Alg.Alias.CertificateFactory.X.509", "X509");

                /*
                 * KeyStore
                 */
                put("KeyStore.JKS", "sun.security.provider.JavaKeyStore");

                /*
                 * KeySize
                 */
                put("Signature.SHA1withDSA KeySize", "1024");
                put("KeyPairGenerator.DSA KeySize", "1024");
                put("AlgorithmParameterGenerator.DSA KeySize", "1024");

                /*
                 * Implementation type: software or hardware
                 */
                put("Signature.SHA1withDSA ImplementedIn", "Software");
                put("KeyPairGenerator.DSA ImplementedIn", "Software");
                put("MessageDigest.MD5 ImplementedIn", "Software");
                put("MessageDigest.SHA ImplementedIn", "Software");
                put("AlgorithmParameterGenerator.DSA ImplementedIn",
                    "Software");
                put("AlgorithmParameters.DSA ImplementedIn", "Software");
                put("KeyFactory.DSA ImplementedIn", "Software");
                put("SecureRandom.SHA1PRNG ImplementedIn", "Software");
                put("CertificateFactory.X509 ImplementedIn", "Software");
                put("KeyStore.JKS ImplementedIn", "Software");

                return null;
            }
        });
    }
}

Appendix B: The SunJCE Provider Master Class

Below is an edited version of the SunJCE.java file, which contains a class named SunJCE that is the master class for the provider named SunJCE.

As with all master classes, this class is a subclass of Provider. It specifies the class names and package locations of all the cryptographic service implementations supplied by the SunJCE provider. This information is used by the getInstance methods of the engine classes to look up the various algorithms and other services when they are requested.

This code is supplied as an example of a provider master class.

/*
 * @(#)SunJCE.java      1.73 05/12/13
 *
 * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package com.sun.crypto.provider;

import java.security.*;
import java.security.cert.*;
import java.net.URL;
import java.io.ByteArrayInputStream;

/**
 * The "SunJCE" Cryptographic Service Provider.
 *
 * @author Jan Luehe
 * @author Sharon Liu
 *
 * @version 1.73, 12/13/05
 */

/**
 * Defines the "SunJCE" provider.
 *
 * Supported algorithms and their names:
 *
 * ...edited for space...
 *
 */

public final class SunJCE extends Provider {

    private static final String info = "SunJCE Provider " +
    "(implements RSA, DES, Triple DES, AES, Blowfish, ARCFOUR, RC2, PBE, "
    + "Diffie-Hellman, HMAC)";

    private static final String OID_PKCS5_MD5_DES = "1.2.840.113549.1.5.3";
    private static final String OID_PKCS3 = "1.2.840.113549.1.3.1";

    public SunJCE() {
        /* We are the "SunJCE" provider */
        super("SunJCE", 1.6d, info);

        final String BLOCK_MODES = "ECB|CBC|PCBC|CTR|CTS|CFB|OFB" +
            "|CFB8|CFB16|CFB24|CFB32|CFB40|CFB48|CFB56|CFB64" +
            "|OFB8|OFB16|OFB24|OFB32|OFB40|OFB48|OFB56|OFB64";
        final String BLOCK_MODES128 = BLOCK_MODES +
            "|CFB72|CFB80|CFB88|CFB96|CFB104|CFB112|CFB120|CFB128" +
            "|OFB72|OFB80|OFB88|OFB96|OFB104|OFB112|OFB120|OFB128";
        final String BLOCK_PADS = "NOPADDING|PKCS5PADDING|ISO10126PADDING";

        AccessController.doPrivileged(new java.security.PrivilegedAction() {
                public Object run() {

                /*
                 * Cipher engines
                 */
                put("Cipher.RSA", "com.sun.crypto.provider.RSACipher");
                put("Cipher.RSA SupportedModes", "ECB");
                put("Cipher.RSA SupportedPaddings",
                        "NOPADDING|PKCS1PADDING|OAEPWITHMD5ANDMGF1PADDING"
                        + "|OAEPWITHSHA1ANDMGF1PADDING"
                        + "|OAEPWITHSHA-1ANDMGF1PADDING"
                        + "|OAEPWITHSHA-256ANDMGF1PADDING"
                        + "|OAEPWITHSHA-384ANDMGF1PADDING"
                        + "|OAEPWITHSHA-512ANDMGF1PADDING");
                put("Cipher.RSA SupportedKeyClasses",
                        "java.security.interfaces.RSAPublicKey" +
                        "|java.security.interfaces.RSAPrivateKey");

                put("Cipher.PBEWithMD5AndDES",
                    "com.sun.crypto.provider.PBEWithMD5AndDESCipher");
                put("Alg.Alias.Cipher.OID."+OID_PKCS5_MD5_DES,
                    "PBEWithMD5AndDES");
                put("Alg.Alias.Cipher."+OID_PKCS5_MD5_DES,
                    "PBEWithMD5AndDES");

                put("Cipher.AES", "com.sun.crypto.provider.AESCipher");
                put("Alg.Alias.Cipher.Rijndael", "AES");
                put("Cipher.AES SupportedModes", BLOCK_MODES128);
                put("Cipher.AES SupportedPaddings", BLOCK_PADS);
                put("Cipher.AES SupportedKeyFormats", "RAW");

                put("Cipher.AESWrap", "com.sun.crypto.provider.AESWrapCipher");
                put("Cipher.AESWrap SupportedModes", "ECB");
                put("Cipher.AESWrap SupportedPaddings", "NOPADDING");
                put("Cipher.AESWrap SupportedKeyFormats", "RAW");

                put("Cipher.ARCFOUR",
                    "com.sun.crypto.provider.ARCFOURCipher");
                put("Alg.Alias.Cipher.RC4", "ARCFOUR");
                put("Cipher.ARCFOUR SupportedModes", "ECB");
                put("Cipher.ARCFOUR SupportedPaddings", "NOPADDING");
                put("Cipher.ARCFOUR SupportedKeyFormats", "RAW");

                /*
                 *  Key(pair) Generator engines
                 */
                put("KeyGenerator.AES",
                    "com.sun.crypto.provider.AESKeyGenerator");
                put("Alg.Alias.KeyGenerator.Rijndael", "AES");

                put("KeyGenerator.ARCFOUR",
                    "com.sun.crypto.provider.KeyGeneratorCore$" +
                    "ARCFOURKeyGenerator");
                put("Alg.Alias.KeyGenerator.RC4", "ARCFOUR");

                put("KeyGenerator.HmacMD5",
                    "com.sun.crypto.provider.HmacMD5KeyGenerator");

                put("KeyGenerator.HmacSHA256",
                    "com.sun.crypto.provider.KeyGeneratorCore$HmacSHA256KG");

                put("KeyPairGenerator.DiffieHellman",
                    "com.sun.crypto.provider.DHKeyPairGenerator");
                put("Alg.Alias.KeyPairGenerator.DH", "DiffieHellman");
                put("Alg.Alias.KeyPairGenerator.OID."+OID_PKCS3,
                    "DiffieHellman");
                put("Alg.Alias.KeyPairGenerator."+OID_PKCS3,
                    "DiffieHellman");

                /*
                 * Algorithm parameter generation engines
                 */
                put("AlgorithmParameterGenerator.DiffieHellman",
                    "com.sun.crypto.provider.DHParameterGenerator");
                put("Alg.Alias.AlgorithmParameterGenerator.DH",
                    "DiffieHellman");
                put("Alg.Alias.AlgorithmParameterGenerator.OID."+OID_PKCS3,
                    "DiffieHellman");
                put("Alg.Alias.AlgorithmParameterGenerator."+OID_PKCS3,
                    "DiffieHellman");

                /*
                 * Key Agreement engines
                 */
                put("KeyAgreement.DiffieHellman",
                    "com.sun.crypto.provider.DHKeyAgreement");
                put("Alg.Alias.KeyAgreement.DH", "DiffieHellman");
                put("Alg.Alias.KeyAgreement.OID."+OID_PKCS3, "DiffieHellman");
                put("Alg.Alias.KeyAgreement."+OID_PKCS3, "DiffieHellman");

                put("KeyAgreement.DiffieHellman SupportedKeyClasses",
                    "javax.crypto.interfaces.DHPublicKey" +
                    "|javax.crypto.interfaces.DHPrivateKey");

                /*
                 * Algorithm Parameter engines
                 */
                put("AlgorithmParameters.DiffieHellman",
                    "com.sun.crypto.provider.DHParameters");
                put("Alg.Alias.AlgorithmParameters.DH", "DiffieHellman");
                put("Alg.Alias.AlgorithmParameters.OID."+OID_PKCS3,
                    "DiffieHellman");
                put("Alg.Alias.AlgorithmParameters."+OID_PKCS3,
                    "DiffieHellman");

                put("AlgorithmParameters.PBEWithMD5AndDES",
                    "com.sun.crypto.provider.PBEParameters");
                put("Alg.Alias.AlgorithmParameters.OID."+OID_PKCS5_MD5_DES,
                    "PBEWithMD5AndDES");
                put("Alg.Alias.AlgorithmParameters."+OID_PKCS5_MD5_DES,
                    "PBEWithMD5AndDES");

                put("AlgorithmParameters.OAEP",
                    "com.sun.crypto.provider.OAEPParameters");

                /*
                 * Key factories
                 */
                put("KeyFactory.DiffieHellman",
                    "com.sun.crypto.provider.DHKeyFactory");
                put("Alg.Alias.KeyFactory.DH", "DiffieHellman");
                put("Alg.Alias.KeyFactory.OID."+OID_PKCS3,
                    "DiffieHellman");
                put("Alg.Alias.KeyFactory."+OID_PKCS3, "DiffieHellman");

                /*
                 * Secret-key factories
                 */
                put("SecretKeyFactory.PBEWithMD5AndDES",
                    "com.sun.crypto.provider.PBEKeyFactory$PBEWithMD5AndDES"
                    );
                put("Alg.Alias.SecretKeyFactory.OID."+OID_PKCS5_MD5_DES,
                    "PBEWithMD5AndDES");
                put("Alg.Alias.SecretKeyFactory."+OID_PKCS5_MD5_DES,
                    "PBEWithMD5AndDES");

                /*
                 * MAC
                 */
                put("Mac.HmacMD5", "com.sun.crypto.provider.HmacMD5");
                put("Mac.HmacSHA256",
                    "com.sun.crypto.provider.HmacCore$HmacSHA256");

                put("Mac.HmacMD5 SupportedKeyFormats", "RAW");
                put("Mac.HmacSHA256 SupportedKeyFormats", "RAW");

                /*
                 * KeyStore
                 */
                put("KeyStore.JCEKS", "com.sun.crypto.provider.JceKeyStore");

                return null;
            }
        });
    }
}

Appendix C: The java.security.properties File

Below is part of the java.security file that shows the default list of installed providers. It appears in every JRE installation. The file also contains other entries, but for brevity, we show only part of the file here. See the complete file at:

<java-home>/lib/security/java.security     [Solaris]
<java-home>\lib\security\java.security     [Win32]

Here <java-home> refers to the directory where the JRE was installed.

See Step 5 for an example of adding information about your provider to this file.

#
# This is the "master security properties file".
#
# In this file, various security properties are set for use by
# java.security classes. This is where users can statically register
# Cryptography Package Providers ("providers" for short). The term
# "provider" refers to a package or set of packages that supply a
# concrete implementation of a subset of the cryptography aspects of
# the Java Security API. A provider may, for example, implement one or
# more digital signature algorithms or message digest algorithms.
#
# Each provider must implement a subclass of the Provider class.
# To register a provider in this master security properties file,
# specify the Provider subclass name and priority in the format
#
#    security.provider.<n>=<className>
#
# This declares a provider, and specifies its preference
# order n. The preference order is the order in which providers are
# searched for requested algorithms (when no specific provider is
# requested). The order is 1-based; 1 is the most preferred, followed
# by 2, and so on.
#
# <className> must specify the subclass of the Provider class whose
# constructor sets the values of various properties that are required
# for the Java Security API to look up the algorithms or other
# facilities implemented by the provider.
#
# There must be at least one provider specification in java.security.
# There is a default provider that comes standard with the JDK. It
# is called the "SUN" provider, and its Provider subclass
# named Sun appears in the sun.security.provider package. Thus, the
# "SUN" provider is registered via the following:
#
#    security.provider.1=sun.security.provider.Sun
#
# (The number 1 is used for the default provider.)
#
# Note: Providers can be dynamically registered instead by calls to
# either the addProvider or insertProviderAt method in the Security
# class.

#
# List of providers and their preference orders (see above):
#

security.provider.1=sun.security.pkcs11.SunPKCS11 \
    ${java.home}/lib/security/sunpkcs11-solaris.cfg
security.provider.2=sun.security.provider.Sun
security.provider.3=sun.security.rsa.SunRsaSign
security.provider.4=com.sun.net.ssl.internal.ssl.Provider
security.provider.5=com.sun.crypto.provider.SunJCE
security.provider.6=sun.security.jgss.SunProvider
security.provider.7=com.sun.security.sasl.Provider
security.provider.8=org.jcp.xml.dsig.internal.dom.XMLDSigRI
security.provider.9=sun.security.smartcardio.SunPCSC

# Rest of file deleted
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface org.w3c.dom.html.HTMLAnchorElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLAnchorElement

No usage of org.w3c.dom.html.HTMLAnchorElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLAppletElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLAppletElement

No usage of org.w3c.dom.html.HTMLAppletElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLAreaElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLAreaElement

No usage of org.w3c.dom.html.HTMLAreaElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLBaseElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLBaseElement

No usage of org.w3c.dom.html.HTMLBaseElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLBaseFontElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLBaseFontElement

No usage of org.w3c.dom.html.HTMLBaseFontElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLBodyElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLBodyElement

No usage of org.w3c.dom.html.HTMLBodyElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLBRElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLBRElement

No usage of org.w3c.dom.html.HTMLBRElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLButtonElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLButtonElement

No usage of org.w3c.dom.html.HTMLButtonElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLCollection (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLCollection

  • Packages that use HTMLCollection
    Package Description
    org.w3c.dom.html

    • Uses of HTMLCollection in org.w3c.dom.html

      Methods in org.w3c.dom.html that return HTMLCollection
      Modifier and Type Method and Description
      HTMLCollection HTMLDocument.getAnchors()
      A collection of all the anchor (A ) elements in a document with a value for the name attribute.
      HTMLCollection HTMLDocument.getApplets()
      A collection of all the OBJECT elements that include applets and APPLET ( deprecated ) elements in a document.
      HTMLCollection HTMLMapElement.getAreas()
      The list of areas defined for the image map.
      HTMLCollection HTMLTableRowElement.getCells()
      The collection of cells in this row.
      HTMLCollection HTMLFormElement.getElements()
      Returns a collection of all control elements in the form.
      HTMLCollection HTMLDocument.getForms()
      A collection of all the forms of a document.
      HTMLCollection HTMLDocument.getImages()
      A collection of all the IMG elements in a document.
      HTMLCollection HTMLDocument.getLinks()
      A collection of all AREA elements and anchor ( A ) elements in a document with a value for the href attribute.
      HTMLCollection HTMLSelectElement.getOptions()
      The collection of OPTION elements contained by this element.
      HTMLCollection HTMLTableSectionElement.getRows()
      The collection of rows in this table section.
      HTMLCollection HTMLTableElement.getRows()
      Returns a collection of all the rows in the table, including all in THEAD , TFOOT , all TBODY elements.
      HTMLCollection HTMLTableElement.getTBodies()
      Returns a collection of the defined table bodies.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLDirectoryElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLDirectoryElement

No usage of org.w3c.dom.html.HTMLDirectoryElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLDivElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLDivElement

No usage of org.w3c.dom.html.HTMLDivElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLDListElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLDListElement

No usage of org.w3c.dom.html.HTMLDListElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLDocument (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLDocument

  • Packages that use HTMLDocument
    Package Description
    org.w3c.dom.html

    • Uses of HTMLDocument in org.w3c.dom.html

      Methods in org.w3c.dom.html that return HTMLDocument
      Modifier and Type Method and Description
      HTMLDocument HTMLDOMImplementation.createHTMLDocument(String title)
      Creates an HTMLDocument object with the minimal tree made of the following elements: HTML , HEAD , TITLE , and BODY .
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLDOMImplementation (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLDOMImplementation

No usage of org.w3c.dom.html.HTMLDOMImplementation
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLElement

  • Packages that use HTMLElement
    Package Description
    org.w3c.dom.html

    • Uses of HTMLElement in org.w3c.dom.html

      Subinterfaces of HTMLElement in org.w3c.dom.html
      Modifier and Type Interface and Description
      interface  HTMLAnchorElement
      The anchor element.
      interface  HTMLAppletElement
      An embedded Java applet.
      interface  HTMLAreaElement
      Client-side image map area definition.
      interface  HTMLBaseElement
      Document base URI.
      interface  HTMLBaseFontElement
      Base font.
      interface  HTMLBodyElement
      The HTML document body.
      interface  HTMLBRElement
      Force a line break.
      interface  HTMLButtonElement
      Push button.
      interface  HTMLDirectoryElement
      Directory list.
      interface  HTMLDivElement
      Generic block container.
      interface  HTMLDListElement
      Definition list.
      interface  HTMLFieldSetElement
      Organizes form controls into logical groups.
      interface  HTMLFontElement
      Local change to font.
      interface  HTMLFormElement
      The FORM element encompasses behavior similar to a collection and an element.
      interface  HTMLFrameElement
      Create a frame.
      interface  HTMLFrameSetElement
      Create a grid of frames.
      interface  HTMLHeadElement
      Document head information.
      interface  HTMLHeadingElement
      For the H1 to H6 elements.
      interface  HTMLHRElement
      Create a horizontal rule.
      interface  HTMLHtmlElement
      Root of an HTML document.
      interface  HTMLIFrameElement
      Inline subwindows.
      interface  HTMLImageElement
      Embedded image.
      interface  HTMLInputElement
      Form control.
      interface  HTMLIsIndexElement
      This element is used for single-line text input.
      interface  HTMLLabelElement
      Form field label text.
      interface  HTMLLegendElement
      Provides a caption for a FIELDSET grouping.
      interface  HTMLLIElement
      List item.
      interface  HTMLLinkElement
      The LINK element specifies a link to an external resource, and defines this document's relationship to that resource (or vice versa).
      interface  HTMLMapElement
      Client-side image map.
      interface  HTMLMenuElement
      Menu list.
      interface  HTMLMetaElement
      This contains generic meta-information about the document.
      interface  HTMLModElement
      Notice of modification to part of a document.
      interface  HTMLObjectElement
      Generic embedded object.
      interface  HTMLOListElement
      Ordered list.
      interface  HTMLOptGroupElement
      Group options together in logical subdivisions.
      interface  HTMLOptionElement
      A selectable choice.
      interface  HTMLParagraphElement
      Paragraphs.
      interface  HTMLParamElement
      Parameters fed to the OBJECT element.
      interface  HTMLPreElement
      Preformatted text.
      interface  HTMLQuoteElement
      For the Q and BLOCKQUOTE elements.
      interface  HTMLScriptElement
      Script statements.
      interface  HTMLSelectElement
      The select element allows the selection of an option.
      interface  HTMLStyleElement
      Style information.
      interface  HTMLTableCaptionElement
      Table caption See the CAPTION element definition in HTML 4.0.
      interface  HTMLTableCellElement
      The object used to represent the TH and TD elements.
      interface  HTMLTableColElement
      Regroups the COL and COLGROUP elements.
      interface  HTMLTableElement
      The create* and delete* methods on the table allow authors to construct and modify tables.
      interface  HTMLTableRowElement
      A row in a table.
      interface  HTMLTableSectionElement
      The THEAD , TFOOT , and TBODY elements.
      interface  HTMLTextAreaElement
      Multi-line text field.
      interface  HTMLTitleElement
      The document title.
      interface  HTMLUListElement
      Unordered list.
      Methods in org.w3c.dom.html that return HTMLElement
      Modifier and Type Method and Description
      HTMLElement HTMLTableElement.createCaption()
      Create a new table caption object or return an existing one.
      HTMLElement HTMLTableElement.createTFoot()
      Create a table footer row or return an existing one.
      HTMLElement HTMLTableElement.createTHead()
      Create a table header row or return an existing one.
      HTMLElement HTMLDocument.getBody()
      The element that contains the content for the document.
      HTMLElement HTMLTableRowElement.insertCell(int index)
      Insert an empty TD cell into this row.
      HTMLElement HTMLTableSectionElement.insertRow(int index)
      Insert a row into this section.
      HTMLElement HTMLTableElement.insertRow(int index)
      Insert a new empty row in the table.
      Methods in org.w3c.dom.html with parameters of type HTMLElement
      Modifier and Type | Method and Description
      void HTMLSelectElement.add(HTMLElement element, HTMLElement before)
      Add a new element to the collection of OPTION elements for this SELECT .
      void | HTMLDocument.setBody(HTMLElement body)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLFieldSetElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLFieldSetElement

No usage of org.w3c.dom.html.HTMLFieldSetElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLFontElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLFontElement

No usage of org.w3c.dom.html.HTMLFontElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLFormElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLFormElement

  • Packages that use HTMLFormElement
    Package Description
    org.w3c.dom.html

    • Uses of HTMLFormElement in org.w3c.dom.html

      Methods in org.w3c.dom.html that return HTMLFormElement
      Modifier and Type Method and Description
      HTMLFormElement HTMLTextAreaElement.getForm()
      Returns the FORM element containing this control.
      HTMLFormElement HTMLSelectElement.getForm()
      Returns the FORM element containing this control.
      HTMLFormElement HTMLOptionElement.getForm()
      Returns the FORM element containing this control.
      HTMLFormElement HTMLObjectElement.getForm()
      Returns the FORM element containing this control.
      HTMLFormElement HTMLLegendElement.getForm()
      Returns the FORM element containing this control.
      HTMLFormElement HTMLLabelElement.getForm()
      Returns the FORM element containing this control.
      HTMLFormElement HTMLIsIndexElement.getForm()
      Returns the FORM element containing this control.
      HTMLFormElement HTMLInputElement.getForm()
      Returns the FORM element containing this control.
      HTMLFormElement HTMLFieldSetElement.getForm()
      Returns the FORM element containing this control.
      HTMLFormElement HTMLButtonElement.getForm()
      Returns the FORM element containing this control.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLFrameElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLFrameElement

No usage of org.w3c.dom.html.HTMLFrameElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLFrameSetElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLFrameSetElement

No usage of org.w3c.dom.html.HTMLFrameSetElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLHeadElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLHeadElement

No usage of org.w3c.dom.html.HTMLHeadElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLHeadingElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLHeadingElement

No usage of org.w3c.dom.html.HTMLHeadingElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLHRElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLHRElement

No usage of org.w3c.dom.html.HTMLHRElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLHtmlElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLHtmlElement

No usage of org.w3c.dom.html.HTMLHtmlElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLIFrameElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLIFrameElement

No usage of org.w3c.dom.html.HTMLIFrameElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLImageElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLImageElement

No usage of org.w3c.dom.html.HTMLImageElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLInputElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLInputElement

No usage of org.w3c.dom.html.HTMLInputElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLIsIndexElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLIsIndexElement

No usage of org.w3c.dom.html.HTMLIsIndexElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLLabelElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLLabelElement

No usage of org.w3c.dom.html.HTMLLabelElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLLegendElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLLegendElement

No usage of org.w3c.dom.html.HTMLLegendElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLLIElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLLIElement

No usage of org.w3c.dom.html.HTMLLIElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLLinkElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLLinkElement

No usage of org.w3c.dom.html.HTMLLinkElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLMapElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLMapElement

No usage of org.w3c.dom.html.HTMLMapElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLMenuElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLMenuElement

No usage of org.w3c.dom.html.HTMLMenuElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLMetaElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLMetaElement

No usage of org.w3c.dom.html.HTMLMetaElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLModElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLModElement

No usage of org.w3c.dom.html.HTMLModElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLObjectElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLObjectElement

No usage of org.w3c.dom.html.HTMLObjectElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLOListElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLOListElement

No usage of org.w3c.dom.html.HTMLOListElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLOptGroupElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLOptGroupElement

No usage of org.w3c.dom.html.HTMLOptGroupElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLOptionElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLOptionElement

No usage of org.w3c.dom.html.HTMLOptionElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLParagraphElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLParagraphElement

No usage of org.w3c.dom.html.HTMLParagraphElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLParamElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLParamElement

No usage of org.w3c.dom.html.HTMLParamElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLPreElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLPreElement

No usage of org.w3c.dom.html.HTMLPreElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLQuoteElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLQuoteElement

No usage of org.w3c.dom.html.HTMLQuoteElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLScriptElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLScriptElement

No usage of org.w3c.dom.html.HTMLScriptElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLSelectElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLSelectElement

No usage of org.w3c.dom.html.HTMLSelectElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLStyleElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLStyleElement

No usage of org.w3c.dom.html.HTMLStyleElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLTableCaptionElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLTableCaptionElement

  • Packages that use HTMLTableCaptionElement
    Package Description
    org.w3c.dom.html

    • Uses of HTMLTableCaptionElement in org.w3c.dom.html

      Methods in org.w3c.dom.html that return HTMLTableCaptionElement
      Modifier and Type Method and Description
      HTMLTableCaptionElement HTMLTableElement.getCaption()
      Returns the table's CAPTION , or void if none exists.
      Methods in org.w3c.dom.html with parameters of type HTMLTableCaptionElement
      Modifier and Type | Method and Description
      void | HTMLTableElement.setCaption(HTMLTableCaptionElement caption)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLTableCellElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLTableCellElement

No usage of org.w3c.dom.html.HTMLTableCellElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLTableColElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLTableColElement

No usage of org.w3c.dom.html.HTMLTableColElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLTableElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLTableElement

No usage of org.w3c.dom.html.HTMLTableElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLTableRowElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLTableRowElement

No usage of org.w3c.dom.html.HTMLTableRowElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLTableSectionElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLTableSectionElement

  • Packages that use HTMLTableSectionElement
    Package Description
    org.w3c.dom.html

    • Uses of HTMLTableSectionElement in org.w3c.dom.html

      Methods in org.w3c.dom.html that return HTMLTableSectionElement
      Modifier and Type Method and Description
      HTMLTableSectionElement HTMLTableElement.getTFoot()
      Returns the table's TFOOT , or null if none exists.
      HTMLTableSectionElement HTMLTableElement.getTHead()
      Returns the table's THEAD , or null if none exists.
      Methods in org.w3c.dom.html with parameters of type HTMLTableSectionElement
      Modifier and Type | Method and Description
      void | HTMLTableElement.setTFoot(HTMLTableSectionElement tFoot)
      void | HTMLTableElement.setTHead(HTMLTableSectionElement tHead)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLTextAreaElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLTextAreaElement

No usage of org.w3c.dom.html.HTMLTextAreaElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLTitleElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLTitleElement

No usage of org.w3c.dom.html.HTMLTitleElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.html.HTMLUListElement (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.html.HTMLUListElement

No usage of org.w3c.dom.html.HTMLUListElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Http Authentication

Overview

The HTTP protocol handler implements a number of authentication schemes. Sun's implementation of Java SE Version 6 supports the following:
  • HTTP Basic authentication (RFC2617)
  • HTTP Digest authentication (RFC2617)
  • NTLM (defined by Microsoft)
  • Http SPNEGO Negotiate (defined by Microsoft), with the following underlying mechanisms:
    • Kerberos
    • NTLM
Each of these schemes is described in more detail below, but they are typically used by application code in much the same way. The java.net.Authenticator class is used to enable authentication and to provide access to a store of usernames and passwords which are then used in the respective authentication schemes.

Generally, all authentication schemes work with both proxies and servers. Some (basic and digest) can be used simultaneously with proxies and servers. See below for how to distinguish between proxy and server authentication.

How to use the Authenticator class

Authenticator is an abstract class which is extended by applications and once installed, is invoked to obtain usernames and passwords for authentication interactions.

Extending java.net.Authenticator

Application code must override the getPasswordAuthentication() method. Note, the method is not abstract, and the default implementation does nothing. The following is a minimal example:
    class MyAuthenticator extends Authenticator {

        public PasswordAuthentication getPasswordAuthentication () {
            return new PasswordAuthentication ("user", "pass1".toCharArray());
        }
    }

This simple example returns the username "user" and the password "pass1" for every HTTP authentication interaction. A more realistic example would use the other methods of java.net.Authenticator to get more information about the HTTP request that needs to be authenticated. Any of the following methods may be called by the implementation of getPasswordAuthentication() in order to decide how to handle each request for credentials.

  • getRequestingHost()
  • getRequestingPort()
  • getRequestingPrompt()
  • getRequestingProtocol()
  • getRequestingScheme()
  • getRequestingURL()
  • getRequestingSite()
  • getRequestorType(). Returns whether requestor is a proxy or server.

Enabling authentication

Having defined a suitable authenticator implementation class, authentication is enabled by calling
        Authenticator.setDefault (authinstance);

where authinstance is an instance of the declared implementation class. If this is not called, then authentication is disabled, and server authentication errors will be returned to user code via IOException objects. Once installed, the http implementation will try to authenticate automatically where possible (via cached credentials, or credentials that can be acquired from the system). If the correct credentials are not available then the user's authenticator is invoked to provide them.

Controlling which authentication scheme is used

When a server needs a client to authenticate, it may propose a number of schemes to the client (for example digest and ntlm) and the client may choose from among them. Normally, applications do not care which scheme is used to and the implementation automatically chooses the strongest (most secure) protocol transparently.

If the user needs to ensure that a particular scheme is used, then the following system property can be set to modify the default behavior.

        -Dhttp.auth.preference="scheme"

-D is specified if the property is being set on the command line. "http.auth.preference" is the property name, and scheme is the name of the scheme to use. If the server does not include this scheme in its list of proposed schemes, then the default choice is made.

Details of each authentication scheme

Http Basic

Basic authentication is a simple and not very secure authentication scheme which is defined in RFC 2317. The username and password are encoded in base 64 and are therefore easily obtainable by anyone who has access to the packet data. The security of basic authentication can be improved when used with HTTPS, thus encrypting the request and response.

The getRequestingPrompt() method returns the Basic authentication realm as provided by the server.

Http digest

Digest is a relatively secure scheme based on cryptographic hashes of the username and password, using the MD5 hash algorithm. Digest also provides the ability for the server to prove to the client that it also knows the shared secret (password). This behavior is normally disabled, because not all servers support it. This can be switched on with the following system properties:
        -Dhttp.auth.digest.validateServer="true"
        -Dhttp.auth.digest.validateProxy="true"

The getRequestingPrompt() method returns the Digest authentication realm as provided by the server.

NTLM

NTLM is a scheme defined by Microsoft. It is more secure scheme than Basic, but less secure than Digest. NTLM can be used with proxies or servers, but not with both at the same time. If a proxy is being used, then it cannot be used for server authentication. This is because the protocol actually authenticates the TCP connection rather than the individual HTTP interactions.

On Microsoft Windows platforms, NTLM authentication attempts to acquire the user credentials from the system without prompting the user's authenticator object. If these credentials are not accepted by the server then the user's authenticator will be called.

Because the Authenticator class was defined prior to NTLM being supported, it was not possible to add support in the API for the NTLM domain field. There are three options for specifying the domain:

  1. Do not specify it. In some environments, the domain is not actually required and the application need not specify it.
  2. The domain name can be encoded within the username by prefixing the domain name followed by a back-slash '\' before the username. With this method, existing applications that use the Authenticator class do not need to be modified, so long as users are made aware that this notation must be used.
  3. If a domain name is not specified as in method 2) and the system property "http.auth.ntlm.domain" is defined, then the value of this property will be used as the domain name.

Http Negotiate (SPNEGO)

Negotiate is a scheme which potentially allows any GSS authentication mechanism to be used as a HTTP authentication protocol. Currently, the scheme only supports Kerberos and NTLM. NTLM has already been described above, so this section only describes how to set up Kerberos for Http authentication.

Kerberos 5 Configuration

Since the SPNEGO mechanism will call JGSS, which in turns calls the Kerberos V5 login module to do real works. Kerberos 5 configurations are needed. which includes:
  • Some way to provide Kerberos configurations. This can be achieved with the Java system property java.security.krb5.conf. For example:
            java -Djava.security.krb5.conf=krb5.conf \
                 -Djavax.security.auth.useSubjectCredsOnly=false \
                 ClassName
  • A JAAS config file denoting what login module to use. HTTP SPNEGO codes will look for the standard entry named com.sun.security.jgss.krb5.initiate.
For example, you can provide a file spnegoLogin.conf:
          com.sun.security.jgss.krb5.initiate {
              com.sun.security.auth.module.Krb5LoginModule
                  required useTicketCache=true;
          };
and run java with:
            java -Djava.security.krb5.conf=krb5.conf \
                 -Djava.security.auth.login.config=spnegoLogin.conf \
                 -Djavax.security.auth.useSubjectCredsOnly=false \
                 ClassName

Username and Password Retrieval

Just like any other HTTP authentication scheme, the client can provide a customized java.net.Authenticator to feed username and password to the HTTP SPNEGO module if they are needed (i.e. there is no credential cache available). The only authentication information needed to be checked in your Authenticator is the scheme which can be retrieved with getRequestingScheme(). The value should be "Negotiate". This means your Authenticator implementation will look like:
    class MyAuthenticator extends Authenticator {

        public PasswordAuthentication getPasswordAuthentication () {
            if (getRequestingScheme().equalsIgnoreCase("negotiate")) {
                String krb5user;
                char[] krb5pass;
                // get krb5user and krb5pass in your own way
                ....
                return (new PasswordAuthentication (krb5user,
                            krb5pass));
            } else {
                ....
            }
        }
    }
Attention : According to the specification of java.net.Authenticator, it's designed to get the username and password at the same time, so do not specify principal=xxx in the JAAS config file.

Scheme Preference

The client can still provide system property http.auth.preference to denote that a certain scheme should always be used as long as the server request for it. You can use "SPNEGO" or "Kerberos" for this system property. "SPNEGO" means you prefer to response the Negotiate scheme using the GSS/SPNEGO mechanism; "Kerberos" means you prefer to response the Negotiate scheme using the GSS/Kerberos mechanism. Normally, when authenticating against a Microsoft product, you can use "SPNEGO". The value "Kerberos" also works for Microsoft servers. It's only needed when you encounter a server which knows Negotiate but doesn't know about SPNEGO. If http.auth.preference is not set, the internal order choosen is:
  • GSS/SPNEGO -> Digest -> NTLM -> Basic
Noticed that Kerberos does not appear in this list, since whenever Negotiate is supported, GSS/SPNEGO is always chosen.

Fallback

If the server has provided more than one authentication schemes (including Negotiate), according to the processing order mentioned in the last section, Java will try to challenge the Negotiate scheme. However, if the protocol cannot be established successfully (e.g. The kerberos configuration is not correct, or the server's hostname is not recorded in the KDC principal DB, or the username and password provided by Authenticator is wrong), then the 2nd strongest scheme will be automatically used. Attention : If http.auth.preference is set to SPNEGO or Kerberos, then we assume you only want to try the Negotiate scheme even if it fails. we won't fallback to any other scheme and your program will result in throwing an IOException saying it receives a 401 or 407 error from the HTTP response.

Example

Suppose you have an IIS Server running on a Windows Server within an Active Directory. A web page on this server is configured to be protected by Integrated Windows Authentication. This means the server will prompt for both Negotiate and NTLM authentication.

You need to prepare these files to get the protected file:

Code listing for RunHttpSpnego.java

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;

public class RunHttpSpnego {

    static final String kuser = "username"; // your account name
    static final String kpass = "password"; // your password for the account

    static class MyAuthenticator extends Authenticator {
        public PasswordAuthentication getPasswordAuthentication() {
            // I haven't checked getRequestingScheme() here, since for NTLM
            // and Negotiate, the usrname and password are all the same.
            System.err.println("Feeding username and password for " + getRequestingScheme());
            return (new PasswordAuthentication(kuser, kpass.toCharArray()));
        }
    }

    public static void main(String[] args) throws Exception {
        Authenticator.setDefault(new MyAuthenticator());
        URL url = new URL(args[0]);
        InputStream ins = url.openConnection().getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
        String str;
        while((str = reader.readLine()) != null)
            System.out.println(str);
    }
}

Code listing for krb5.conf

[libdefaults]
    default_realm = AD.LOCAL
[realms]
    AD.LOCAL = {
        kdc = kdc.ad.local
    }

Code listing for login.conf

com.sun.security.jgss.krb5.initiate {
  com.sun.security.auth.module.Krb5LoginModule required doNotPrompt=false useTicketCache=true;
};

Then, compile RunHttpSpnego.java and run:

java -Djava.security.krb5.conf=krb5.conf \
    -Djava.security.auth.login.config=login.conf \
    -Djavax.security.auth.useSubjectCredsOnly=false \
    RunHttpSpnego \
    http://www.ad.local/hello/hello.html

You will see:

Feeding username and password for Negotiate
<h1>Hello, You got me!</h1>

In fact, if you are running on a Windows machine as a domain user, or, you are running on a Linux or Solaris machine that has already issued the kinit command and got the credential cache. The class MyAuthenticator will be completely ignored, and the output will be simply

<h1>Hello, You got me!</h1>
which shows the username and password are not consulted. This is the so-called Single Sign-On. Also, You can just run
java RunHttpSpnego \
    http://www.ad.local/hello/hello.html
to see how the fallback is done, in which case you will see
Feeding username and password for ntlm
<h1>Hello, You got me!</h1>
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


URLConnection caching API

HTTP is typically used for distributed information systems, where performance can be improved by the use of response caches. While HTTP proxy servers normally caches recently visited web resources, it is sometimes also desirable to have a local cache. Examples are browser caches.

In Tiger, a new framework provides a way for protocol handlers to access a response caching mechanism implemented by the platform or by a third party.

Here is the API:

We have introduced three abstract classes in the java.net package. They are:

  • ResponseCache
  • CacheRequest
  • CacheResponse

A concrete subclass of ResponseCache represents the URLConnection cache itself. An instance of such a class can be registered with the system by calling ResponseCache.setDefault(), and the system will call this object in order to:

  • store resource data which has been retrieved from an external source into the cache;
  • try to fetch a requested resource that may have been stored in the cache.

ResponseCache has two methods: get() returns a CacheResponse based on URI and request headers; and put() allows cache to decide if resource should be cached, returns a CacheRequest.

A concrete subclass of CacheRequest is used to write an entry in the ResponseCache. Instances of such a class provide an OutputStream object which is called by protocol handlers to store the resource data into the cache, and also an abort() method which allows a cache store operation to be interrupted and abandoned.

CacheRequest class has two methods: getBody() returns a stream for writing the request body into cache; and abort() abandons a cache write.

A concrete subclass of CacheResponse returns an entry from the ResponseCache. Instances of such a class provide an InputStream that returns the entity body, and also a getHeaders() method which returns the associated response headers.

CacheResponse class has two methods: getBody() returns a stream for reading the request body from cache; and getHeaders() returns the headers stored.

Caching logic flow

The following example shows a simple file based caching. However, it is equally viable to use other mechanisms such as a database for caching.

MyCacheResponse class is an implementation of CacheResponse. What it does is to take a file name and retrieve the HTTP response headers and body from it.

class MyCacheResponse extends CacheResponse {
FileInputStream fis;
Map<String, List<String>> headers;
public MyCacheResponse(String filename) {
        try {
         fis = new FileInputStream(new File(filename));
         ObjectInputStream ois = new ObjectInputStream (fis);
         headers = (Map<String, List<String>>)  ois.readObject();
   } catch (IOException ex) {
        // handle exception
   }
}

public InputStream getBody() throws IOException {
   return fis;
}

 public Map getHeaders() throws IOException {
   return headers;
 }
}

MyCacheRequest is an implementation of the CacheRequest. It takes a filename and the response headers and stores the headers in the file and also returns an outputstream directed to the same file so that any response body can be cached there.

class MyCacheRequest extends CacheRequest {
FileOutputStream fos;
public MyCacheRequest(String filename,
   Map<String, List<String>> rspHeaders) {
   try {
        File file = new File(filename);
        fos = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(rspHeaders);
   } catch (Exception ex) {
        throw new RuntimeException(ex.getMessage());
   }
}
public OutputStream getBody() throws IOException {
   return fos;
}

public void abort() {
   // we abandon the cache by close the stream,
   // and delete the file
   fos.close();
   file.delete();
 }
}

Finally, we can tie it altogether with our implementation of the ResponseCache, it checks the URI for the network resource that is being retrieved or to be cached and returns the appropriate instantiations of our implementations of CacheResponse or CacheRequest. In this example, we only handles the case when the URI is equal to uri1 for retrieving from the cache, and for URI equals uri2 for storing to the cache. But it is easily expanded to handle a more complicated file based cache.

class MyResponseCache extends ResponseCache {
 public CacheResponse
 get(URI uri, String rqstMethod, Map rqstHeaders)
   throws IOException {
   // get the response from a cached file if available
   if (uri.equals(ParseUtil.toURI(uri1))) {
        return new MyCacheResponse(FNPrefix+"file1.cache");
   }
   return null;

public CacheRequest put(URI uri, URLConnection conn)
   throws IOException {
   // save cache to a file
   // 1. serialize headers into file2.cache
   // 2. write data to file2.cache
   if (uri.equals(ParseUtil.toURI(uri2))) {
       return new MyCacheRequest(OutFNPrefix+"file2.cache",
        conn.getHeaderFields());
   }
   return null;
 }
}

Once we have developed our own ResponseCache implementation, all left to be done is to register it and the JVM will use it.

public static void main(String args[]) throws Exception {
        ......
        ResponseCache.setDefault(new MyResponseCache());
        HttpURLConnection http = (HttpURLConnection)url1.openConnection();
        InputStream is = null;
        ......
}

There is no default implementation of URLConnection caching in the Java 2 Standard Edition. However, Java Plugin and Java WebStart do provide one out of the box.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Cookie Management

Introduction

The HTTP state management mechanism specifies a way to create a stateful session with HTTP requests and responses. The specification for it can be found in RFC 2965: HTTP State Management Mechanism at http://www.ietf.org/rfc/rfc2965.txt?number=2965.

Pre-Tiger support

Prior to Tiger, it was possible to add Cookie management to applications. But the supporting API was somewhat rudimentary. There was no single point of hook up with cookie management. Each application had to handle cookies for each HTTP request/response separately by using the following two methods from java.net.URLConnection class:

setRequestProperty()
getHeaderFields()

The first method should be called before sending out a HTTP request in order to set the appropriate cookies for the current URL in the HTTP headers. The second method should be used to retrieve the cookies from the response headers sent by the HTTP server.

Although doable, adding Cookie support in this way results in fragmented code, which is error prone and incurs high maintenance.

What's new in Tiger?

We have introduced a new callback mechanism via an abstract class to hook up a HTTP state management policy implementation into the HTTP protocol handler. Applications and web containers can introduce Cookie management by providing a concrete subclass of the new API.

The new abstract class is called java.net.CookieHandler. It provides a mechanism to register and retrieve the current CookieHandler for the JVM, as well as methods to retrieve and record relevant cookies for a specific URI.

There are two static methods in CookieHandler getDefault() and setDefault() for retrieving and registering the default CookieHandler in the VM. As well as two instance methods get() and put() for returning a list of cookies based on a URL and stores a list of cookies from the response headers, respectively.

Cookies are represented as Map<String,List<String>>, a Map from the header field name for cookies to a list of cookies represented by Strings. There are two state management headers defined so far, "Set-Cookie2" and "Cookie". The former is used for returning cookies in response headers; while the latter is for setting cookies in HTTP request headers.

Here is an example from RFC2965:

1. User Agent -> Server

POST /acme/login HTTP/1.1
[form data]

2. Server -> User Agent

HTTP/1.1 200 OK
Set-Cookie2: Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"

3. User Agent -> Server

POST /acme/pickitem HTTP/1.1
Cookie: $Version="1"; Customer="WILE_E_COYOTE"; $Path="/acme"
[form data]

A simple Example

Here's a simple example of a CookieHandler implementation. Basically there are two methods to implement, given a request URI and request headers (except the cookie headers), retrieve all the relevant cookies from your cookie cache; and record the applicable cookies to your cookie cache given the request URI and the response headers.

class MyCookieHandler extends CookieHandler {
        public Map<String, List<String>>
                get(URI uri, Map<String, List<String>> requestHeaders)
                throws IOException {
                // the cookies will be included in request
                Map<String, List<String>> map = new HashMap<String, List<String>>();
                List<String> l = retrieveCookies(uri, rqstHdrs);
                map.put("Cookie",l);
                return Collections.unmodifiableMap(map);
        }

        public void
                put(URI uri, Map responseHeaders)
                throws IOException {
            // check response has cookies[1]
                List l = (List)responseHeaders.get("Set-Cookie2");
            if (l != null) {
                        // save the cookies in a cookie cache
                 storeCookies(uri, l);
            }
        }
}

The methods retrieveCookies() and storeCookies() are "magic" functions for interacting with a backend cookie management facility, which is omitted in this example.

Once it is registered with the VM, it will take effect when you issue HTTP transactions.

public static void main(String args[]) throws Exception {
        ......
        CookieHandler.setDefault(new MyCookieHandler());
        HttpURLConnection http = (HttpURLConnection)url.openConnection();

        int respCode = http.getResponseCode();
        http.disconnect();
        ......
}

There is no default implementation of a cookie manager in J2SE. However, this may change in the future. Java Plugin and Java WebStart provides a default CookieHandler in their environment.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


HTTP Persistent Connections

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Persistent Connections

What is HTTP Persistent Connections?

HTTP persistent connections, also called HTTP keep-alive, or HTTP connection reuse, is the idea of using the same TCP connection to send and receive multiple HTTP requests/responses, as opposed to opening a new one for every single request/response pair. Using persistent connections is very important for improving HTTP performance.

There are several advantages of using persistent connections, including:

  • Network friendly. Less network traffic due to fewer setting up and tearing down of TCP connections.
  • Reduced latency on subsequent request. Due to avoidance of initial TCP handshake
  • Long lasting connections allowing TCP sufficient time to determine the congestion state of the network, thus to react appropriately.

The advantages are even more obvious with HTTPS or HTTP over SSL/TLS. There, persistent connections may reduce the number of costly SSL/TLS handshake to establish security associations, in addition to the initial TCP connection set up.

In HTTP/1.1, persistent connections are the default behavior of any connection. That is, unless otherwise indicated, the client SHOULD assume that the server will maintain a persistent connection, even after error responses from the server. However, the protocol provides means for a client and a server to signal the closing of a TCP connection.

What makes a connection reusable?

Since TCP by its nature is a stream based protocol, in order to reuse an existing connection, the HTTP protocol has to have a way to indicate the end of the previous response and the beginning of the next one. Thus, it is required that all messages on the connection MUST have a self-defined message length (i.e., one not defined by closure of the connection). Self demarcation is achieved by either setting the Content-Length header, or in the case of chunked transfer encoded entity body, each chunk starts with a size, and the response body ends with a special last chunk.

What happens if there are proxy servers in between?

Since persistent connections applies to only one transport link, it is important that proxy servers correctly signal persistent/or-non-persistent connections separately with its clients and the origin servers (or to other proxy servers). From a HTTP client or server's perspective, as far as persistence connection is concerned, the presence or absence of proxy servers is transparent.

What does the current JDK do for Keep-Alive?

The JDK supports both HTTP/1.1 and HTTP/1.0 persistent connections.

When the application finishes reading the response body or when the application calls close() on the InputStream returned by URLConnection.getInputStream(), the JDK's HTTP protocol handler will try to clean up the connection and if successful, put the connection into a connection cache for reuse by future HTTP requests.

The support for HTTP keep-Alive is done transparently. However, it can be controlled by system properties http.keepAlive, and http.maxConnections, as well as by HTTP/1.1 specified request and response headers.

The system properties that control the behavior of Keep-Alive are:

http.keepAlive=<boolean>
default: true

Indicates if keep alive (persistent) connections should be supported.

http.maxConnections=<int>
default: 5

Indicates the maximum number of connections per destination to be kept alive at any given time

HTTP header that influences connection persistence is:

Connection: close

If the "Connection" header is specified with the value "close" in either the request or the response header fields, it indicates that the connection should not be considered 'persistent' after the current request/response is complete.

The current implementation doesn't buffer the response body. Which means that the application has to finish reading the response body or call close() to abandon the rest of the response body, in order for that connection to be reused. Furthermore, current implementation will not try block-reading when cleaning up the connection, meaning if the whole response body is not available, the connection will not be reused.

What's new in Tiger?

When the application encounters a HTTP 400 or 500 response, it may ignore the IOException and then may issue another HTTP request. In this case, the underlying TCP connection won't be Kept-Alive because the response body is still there to be consumed, so the socket connection is not cleared, therefore not available for reuse. What the application needs to do is call HttpURLConnection.getErrorStream() after catching the IOException , read the response body, then close the stream. However, some existing applications are not doing this. As a result, they do not benefit from persistent connections. To address this problem, we have introduced a workaround.

The workaround involves buffering the response body if the response is >=400, up to a certain amount and within a time limit, thus freeing up the underlying socket connection for reuse. The rationale behind this is that when the server responds with a >=400 error (client error or server error. One example is "404: File Not Found" error), the server usually sends a small response body to explain whom to contact and what to do to recover.

Several new Sun implementation specific properties are introduced to help clean up the connections after error response from the server.

The major one is:

sun.net.http.errorstream.enableBuffering=<boolean>
default: false

With the above system property set to true (default is false), when the response code is >=400, the HTTP handler will try to buffer the response body. Thus freeing up the underlying socket connection for reuse. Thus, even if the application doesn't call getErrorStream(), read the response body, and then call close(), the underlying socket connection may still be kept-alive and reused.

The following two system properties provide further control to the error stream buffering behavior:

sun.net.http.errorstream.timeout=<int> in millisecond
default: 300 millisecond

sun.net.http.errorstream.bufferSize=<int> in bytes
default: 4096 bytes

What can you do to help with Keep-Alive?

Do not abandon a connection by ignoring the response body. Doing so may results in idle TCP connections. That needs to be garbage collected when they are no longer referenced.

If getInputStream() successfully returns, read the entire response body.

When calling getInputStream() from HttpURLConnection, if an IOException occurs, catch the exception and call getErrorStream() to get the response body (if there is any).

Reading the response body cleans up the connection even if you are not interested in the response content itself. But if the response body is long and you are not interested in the rest of it after seeing the beginning, you can close the InputStream. But you need to be aware that more data could be on its way. Thus the connection may not be cleared for reuse.

Here's a code example that complies to the above recommendation:

try {
        URL a = new URL(args[0]);
        URLConnection urlc = a.openConnection();
        is = conn.getInputStream();
        int ret = 0;
        while ((ret = is.read(buf)) > 0) {
          processBuf(buf);
        }
        // close the inputstream
        is.close();
} catch (IOException e) {
        try {
                respCode = ((HttpURLConnection)conn).getResponseCode();
                es = ((HttpURLConnection)conn).getErrorStream();
                int ret = 0;
                // read the response body
                while ((ret = es.read(buf)) > 0) {
                        processBuf(buf);
                }
                // close the errorstream
                es.close();
        } catch(IOException ex) {
                // deal with the exception
        }
}

If you know ahead of time that you won't be interested in the response body, you should issue a HEAD request instead of a GET request. For example when you are only interested in the meta info of the web resource or when testing for its validity, accessibility and recent modification. Here's a code snippet:

URL a = new URL(args[0]);
URLConnection urlc = a.openConnection();
HttpURLConnection httpc = (HttpURLConnection)urlc;
// only interested in the length of the resource
httpc.setRequestMethod("HEAD");
int len = httpc.getContentLength();

Changes in Java SE 6

Prior to Java SE 6, if an application closes a HTTP InputStream when more than a small amount of data remains to be read, then the connection had to be closed, rather than being cached. Now in Java SE 6, the behavior is to read up to 512 Kbytes off the connection in a background thread, thus allowing the connection to be reused. The exact amount of data which may be read is configurable through the http.KeepAlive.remainingData system property.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.net.httpserver.HttpContext (Java HTTP Server b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.net.httpserver.HttpContext

  • Packages that use HttpContext
    Package Description
    com.sun.net.httpserver
    Provides a simple high-level Http server API, which can be used to build embedded HTTP servers.

    • Uses of HttpContext in com.sun.net.httpserver

      Methods in com.sun.net.httpserver that return HttpContext
      Modifier and Type Method and Description
      abstract HttpContext HttpServer.createContext(String path)
      Creates a HttpContext without initially specifying a handler.
      abstract HttpContext HttpServer.createContext(String path, HttpHandler handler)
      Creates a HttpContext.
      abstract HttpContext HttpExchange.getHttpContext()
      Get the HttpContext for this exchange
      Methods in com.sun.net.httpserver with parameters of type HttpContext
      Modifier and Type Method and Description
      abstract void HttpServer.removeContext(HttpContext context)
      Removes the given context from the server.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.net.httpserver.HttpExchange (Java HTTP Server b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.net.httpserver.HttpExchange

  • Packages that use HttpExchange
    Package Description
    com.sun.net.httpserver
    Provides a simple high-level Http server API, which can be used to build embedded HTTP servers.

    • Uses of HttpExchange in com.sun.net.httpserver

      Subclasses of HttpExchange in com.sun.net.httpserver
      Modifier and Type Class and Description
      class  HttpsExchange
      This class encapsulates a HTTPS request received and a response to be generated in one exchange and defines the extensions to HttpExchange that are specific to the HTTPS protocol.
      Methods in com.sun.net.httpserver with parameters of type HttpExchange
      Modifier and Type | Method and Description
      Authenticator.Result | BasicAuthenticator.authenticate(HttpExchange t)
      abstract Authenticator.Result Authenticator.authenticate(HttpExchange exch)
      called to authenticate each incoming request.
      void Filter.Chain.doFilter(HttpExchange exchange)
      calls the next filter in the chain, or else the users exchange handler, if this is the final filter in the chain.
      abstract void Filter.doFilter(HttpExchange exchange, Filter.Chain chain)
      Asks this filter to pre/post-process the given exchange.
      void HttpHandler.handle(HttpExchange exchange)
      Handle the given request and generate an appropriate response.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.net.httpserver.HttpHandler (Java HTTP Server b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.net.httpserver.HttpHandler

  • Packages that use HttpHandler
    Package Description
    com.sun.net.httpserver
    Provides a simple high-level Http server API, which can be used to build embedded HTTP servers.

    • Uses of HttpHandler in com.sun.net.httpserver

      Methods in com.sun.net.httpserver that return HttpHandler
      Modifier and Type Method and Description
      abstract HttpHandler HttpContext.getHandler()
      returns the handler for this context
      Methods in com.sun.net.httpserver with parameters of type HttpHandler
      Modifier and Type Method and Description
      abstract HttpContext HttpServer.createContext(String path, HttpHandler handler)
      Creates a HttpContext.
      abstract void HttpContext.setHandler(HttpHandler h)
      Sets the handler for this context, if not already set.
      Constructors in com.sun.net.httpserver with parameters of type HttpHandler
      Constructor and Description
      Filter.Chain(List<Filter> filters, HttpHandler handler)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.net.httpserver.HttpPrincipal (Java HTTP Server b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.net.httpserver.HttpPrincipal

  • Packages that use HttpPrincipal
    Package Description
    com.sun.net.httpserver
    Provides a simple high-level Http server API, which can be used to build embedded HTTP servers.

    • Uses of HttpPrincipal in com.sun.net.httpserver

      Methods in com.sun.net.httpserver that return HttpPrincipal
      Modifier and Type Method and Description
      abstract HttpPrincipal HttpExchange.getPrincipal()
      If an authenticator is set on the HttpContext that owns this exchange, then this method will return the HttpPrincipal that represents the authenticated user for this HttpExchange.
      HttpPrincipal Authenticator.Success.getPrincipal()
      returns the authenticated user Principal
      Constructors in com.sun.net.httpserver with parameters of type HttpPrincipal
      Constructor and Description
      Authenticator.Success(HttpPrincipal p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.net.httpserver.HttpsConfigurator (Java HTTP Server b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.net.httpserver.HttpsConfigurator

  • Packages that use HttpsConfigurator
    Package Description
    com.sun.net.httpserver
    Provides a simple high-level Http server API, which can be used to build embedded HTTP servers.

    • Uses of HttpsConfigurator in com.sun.net.httpserver

      Methods in com.sun.net.httpserver that return HttpsConfigurator
      Modifier and Type Method and Description
      abstract HttpsConfigurator HttpsServer.getHttpsConfigurator()
      Gets this server's HttpsConfigurator object, if it has been set.
      abstract HttpsConfigurator HttpsParameters.getHttpsConfigurator()
      Returns the HttpsConfigurator for this HttpsParameters.
      Methods in com.sun.net.httpserver with parameters of type HttpsConfigurator
      Modifier and Type Method and Description
      abstract void HttpsServer.setHttpsConfigurator(HttpsConfigurator config)
      Sets this server's HttpsConfigurator object.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.net.httpserver.HttpServer (Java HTTP Server b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.net.httpserver.HttpServer

  • Packages that use HttpServer
    Package Description
    com.sun.net.httpserver
    Provides a simple high-level Http server API, which can be used to build embedded HTTP servers.
    com.sun.net.httpserver.spi
    Provides a pluggable service provider interface, which allows the HTTP server implementation to be replaced with other implementations.

    • Uses of HttpServer in com.sun.net.httpserver

      Subclasses of HttpServer in com.sun.net.httpserver
      Modifier and Type Class and Description
      class  HttpsServer
      This class is an extension of HttpServer which provides support for HTTPS.
      Methods in com.sun.net.httpserver that return HttpServer
      Modifier and Type Method and Description
      static HttpServer HttpServer.create()
      creates a HttpServer instance which is initially not bound to any local address/port.
      static HttpServer HttpServer.create(InetSocketAddress addr, int backlog)
      Create a HttpServer instance which will bind to the specified InetSocketAddress (IP address and port number) A maximum backlog can also be specified.
      abstract HttpServer HttpContext.getServer()
      returns the server this context was created with

    • Uses of HttpServer in com.sun.net.httpserver.spi

      Methods in com.sun.net.httpserver.spi that return HttpServer
      Modifier and Type Method and Description
      abstract HttpServer HttpServerProvider.createHttpServer(InetSocketAddress addr, int backlog)
      creates a HttpServer from this provider
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.net.httpserver.spi.HttpServerProvider (Java HTTP Server b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.net.httpserver.spi.HttpServerProvider

  • Packages that use HttpServerProvider
    Package Description
    com.sun.net.httpserver.spi
    Provides a pluggable service provider interface, which allows the HTTP server implementation to be replaced with other implementations.

    • Uses of HttpServerProvider in com.sun.net.httpserver.spi

      Methods in com.sun.net.httpserver.spi that return HttpServerProvider
      Modifier and Type Method and Description
      static HttpServerProvider HttpServerProvider.provider()
      Returns the system wide default HttpServerProvider for this invocation of the Java virtual machine.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.net.httpserver.HttpsExchange (Java HTTP Server b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.net.httpserver.HttpsExchange

No usage of com.sun.net.httpserver.HttpsExchange
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.net.httpserver.HttpsParameters (Java HTTP Server b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.net.httpserver.HttpsParameters

  • Packages that use HttpsParameters
    Package Description
    com.sun.net.httpserver
    Provides a simple high-level Http server API, which can be used to build embedded HTTP servers.

    • Uses of HttpsParameters in com.sun.net.httpserver

      Methods in com.sun.net.httpserver with parameters of type HttpsParameters
      Modifier and Type Method and Description
      void HttpsConfigurator.configure(HttpsParameters params)
      Called by the HttpsServer to configure the parameters for a https connection currently being established.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.net.httpserver.HttpsServer (Java HTTP Server b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.net.httpserver.HttpsServer

  • Packages that use HttpsServer
    Package Description
    com.sun.net.httpserver
    Provides a simple high-level Http server API, which can be used to build embedded HTTP servers.
    com.sun.net.httpserver.spi
    Provides a pluggable service provider interface, which allows the HTTP server implementation to be replaced with other implementations.

    • Uses of HttpsServer in com.sun.net.httpserver

      Methods in com.sun.net.httpserver that return HttpsServer
      Modifier and Type Method and Description
      static HttpsServer HttpsServer.create()
      creates a HttpsServer instance which is initially not bound to any local address/port.
      static HttpsServer HttpsServer.create(InetSocketAddress addr, int backlog)
      Create a HttpsServer instance which will bind to the specified InetSocketAddress (IP address and port number) A maximum backlog can also be specified.

    • Uses of HttpsServer in com.sun.net.httpserver.spi

      Methods in com.sun.net.httpserver.spi that return HttpsServer
      Modifier and Type Method and Description
      abstract HttpsServer HttpServerProvider.createHttpsServer(InetSocketAddress addr, int backlog)
      creates a HttpsServer from this provider
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java HTTP Server
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.IdentifierTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.IdentifierTree

  • Packages that use IdentifierTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of IdentifierTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type IdentifierTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitIdentifier(IdentifierTree node, P p)

    • Uses of IdentifierTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type IdentifierTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitIdentifier(IdentifierTree node, P p)
      R | SimpleTreeVisitor.visitIdentifier(IdentifierTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


idlj - The IDL-to-Java Compiler

idlj generates Java bindings from a given IDL file.

Synopsis

idlj [ options ] idl-file

where idl-file is the name of a file containing Interface Definition Language (IDL) definitions. Options may appear in any order, but must precede the idl-file.

Description

The IDL-to-Java Compiler generates the Java bindings for a given IDL file. For binding details, see the OMG IDL to Java Language Language Mapping Specification. Some previous releases of the IDL-to-Java compiler were named idltojava.

Emitting Client and Server Bindings

To generate Java bindings for an IDL file named My.idl:

idlj My.idl

This generates the client-side bindings and is equivalent to:

idlj -fclient My.idl

The client-side bindings do not include the server-side skeleton. If you want to generate the server-side bindings for the interfaces:

idlj -fserver My.idl

Server-side bindings include the client-side bindings plus the skeleton, all of which are POA (that is, Inheritance Model) classes. If you want to generate both client and server-side bindings, use one of the following (equivalent) commands:

idlj -fclient -fserver My.idl
idlj -fall My.idl

There are two possible server-side models: the Inheritance Model and the Tie Delegation Model.

The default server-side model is the Portable Servant Inheritance Model. Given an interface My defined in My.idl, the file MyPOA.java is generated. You must provide the implementation for My and it must inherit from MyPOA.

MyPOA.java is a stream-based skeleton that extends org.omg.PortableServer.Servant and implements the InvokeHandler interface and the operations interface associated with the IDL interface the skeleton implements.

The PortableServer module for the Portable Object Adapter (POA) defines the native Servant type. In the Java programming language, the Servant type is mapped to the Java org.omg.PortableServer.Servant class. It serves as the base class for all POA servant implementations and provides a number of methods that may be invoked by the application programmer, as well as methods which are invoked by the POA itself and may be overridden by the user to control aspects of servant behavior.

Another option for the Inheritance Model is to use the -oldImplBase flag in order to generate server-side bindings that are compatible with versions of the Java programming language prior to J2SE 1.4. Note that using the -oldImplBase flag is non-standard: these APIs are being deprecated. You would use this flag ONLY for compatibility with existing servers written in J2SE 1.3. In that case, you would need to modify an existing MAKEFILE to add the -oldImplBase flag to the idlj compiler, otherwise POA-based server-side mappings will be generated. To generate server-side bindings that are backwards compatible:

idlj -fclient -fserver -oldImplBase My.idl
idlj -fall -oldImplBase My.idl

Given an interface My defined in My.idl, the file _MyImplBase.java is generated. You must provide the implementation for My and it must inherit from _MyImplBase.

The other server-side model is called the Tie Model. This is a delegation model. Because it is not possible to generate ties and skeletons at the same time, they must be generated separately. The following commands generate the bindings for the Tie Model:

idlj -fall My.idl
idlj -fallTIE My.idl

For the interface My, the second command generates MyPOATie.java. The constructor to MyPOATie takes a delegate. In this example, using the default POA model, the constructor also needs a poa. You must provide the implementation for delegate, but it does not have to inherit from any other class, only the interface MyOperations. But to use it with the ORB, you must wrap your implementation within MyPOATie. For instance:

    ORB orb = ORB.init(args, System.getProperties());

    // Get reference to rootpoa & activate the POAManager
    POA rootpoa = (POA)orb.resolve_initial_references("RootPOA");
    rootpoa.the_POAManager().activate();

    // create servant and register it with the ORB
    MyServant myDelegate = new MyServant();
    myDelegate.setORB(orb);

    // create a tie, with servant being the delegate.
    MyPOATie tie = new MyPOATie(myDelegate, rootpoa);

    // obtain the objectRef for the tie
    My ref = tie._this(orb);

You might want to use the Tie model instead of the typical Inheritance model if your implementation must inherit from some other implementation. Java allows any number of interface inheritance, but there is only one slot for class inheritance. If you use the inheritance model, that slot is used up . By using the Tie Model, that slot is freed up for your own use. The drawback is that it introduces a level of indirection: one extra method call occurs when invoking a method.

To generate server-side, Tie model bindings that are compatible with versions of the IDL to Java language mapping in versions prior to J2SE 1.4.

idlj -oldImplBase -fall My.idl
idlj -oldImplBase -fallTIE My.idl

For the interface My, this will generate My_Tie.java. The constructor to My_Tie takes a impl. You must provide the implementation for impl, but it does not have to inherit from any other class, only the interface HelloOperations. But to use it with the ORB, you must wrap your implementation within My_Tie. For instance:

    ORB orb = ORB.init(args, System.getProperties());

    // create servant and register it with the ORB
    MyServant myDelegate = new MyServant();
    myDelegate.setORB(orb);

    // create a tie, with servant being the delegate.
    MyPOATie tie = new MyPOATie(myDelegate);

    // obtain the objectRef for the tie
    My ref = tie._this(orb);

Specifying Alternate Locations for Emitted Files

If you want to direct the emitted files to a directory other than the current directory, invoke the compiler as:

idlj -td /altdir My.idl

For the interface My, the bindings will be emitted to /altdir/My.java, etc., instead of ./My.java.

Specifying Alternate Locations for Include Files

If My.idl included another idl file, MyOther.idl, the compiler assumes that MyOther.idl resides in the local directory. If it resides in /includes, for example, then you would invoke the compiler with the following command:

idlj -i /includes My.idl

If My.idl also included Another.idl that resided in /moreIncludes, for example, then you would invoke the compiler with the following command:

idlj -i /includes -i /moreIncludes My.idl

Since this form of include can become irritatingly long, another means of indicating to the compiler where to search for included files is provided. This technique is similar to the idea of an environment variable. Create a file named idl.config in a directory that is listed in your CLASSPATH. Inside of idl.config, provide a line with the following form:

includes=/includes;/moreIncludes

The compiler will find this file and read in the includes list. Note that in this example the separator character between the two directories is a semicolon (;). This separator character is platform dependent. On the Windows platform, use a semicolon, on the Unix platform, use a colon, etc. For more information on includes, see the Setting the Classpath.

Emitting Bindings for Include Files

By default, only those interfaces, structs, etc, that are defined in the idl file on the command line have Java bindings generated for them. The types defined in included files are not generated. For example, assume the following two idl files:

My.idl

#include <MyOther.idl>
interface My
{
};

MyOther.idl

interface MyOther
{
};

The following command will only generate the java bindings for My:

idlj My.idl

To generate all of the types in My.idl and all of the types in the files that My.idl includes (in this example, MyOther.idl), use the following command:

idlj -emitAll My.idl

There is a caveat to the default rule. #include statements which appear at global scope are treated as described. These #include statements can be thought of as import statements. #include statements which appear within some enclosing scope are treated as true #include statements, meaning that the code within the included file is treated as if it appeared in the original file and, therefore, Java bindings are emitted for it. Here is an example:

My.idl

#include <MyOther.idl>
interface My
{
  #include <Embedded.idl>
};

MyOther.idl

interface MyOther
{
};

Embedded.idl

enum E {one, two, three};

Running the following command:

idlj My.idl

will generate the following list of Java files:

./MyHolder.java
./MyHelper.java
./_MyStub.java
./MyPackage
./MyPackage/EHolder.java
./MyPackage/EHelper.java
./MyPackage/E.java
./My.java

Notice that MyOther.java was not generated because it is defined in an import-like #include. But E.java was generated because it was defined in a true #include. Also notice that since Embedded.idl was included within the scope of the interface My, it appears within the scope of My (that is,in MyPackage).

If the -emitAll flag had been used in the previous example, then all types in all included files would be emitted.

Inserting Package Prefixes

Suppose that you work for a company named ABC that has constructed the following IDL file:

Widgets.idl

module Widgets
{
  interface W1 {...};
  interface W2 {...};
};

Running this file through the IDL-to-Java compiler will place the Java bindings for W1 and W2 within the package Widgets. But there is an industry convention that states that a company's packages should reside within a package named com.<company name>. The Widgets package is not good enough. To follow convention, it should be com.abc.Widgets. To place this package prefix onto the Widgets module, execute the following:

idlj -pkgPrefix Widgets com.abc Widgets.idl

If you have an IDL file which includes Widgets.idl, the -pkgPrefix flag must appear in that command also. If it does not, then your IDL file will be looking for a Widgets package rather than a com.abc.Widgets package.

If you have a number of these packages that require prefixes, it might be easier to place them into the idl.config file described above. Each package prefix line should be of the form:

PkgPrefix.<type>=<prefix>
So the line for the above example would be:
PkgPrefix.Widgets=com.abc

The use of this option does not affect the Repository ID.

Defining Symbols Before Compilation

You may need to define a symbol for compilation that is not defined within the IDL file, perhaps to include debugging code in the bindings. The command

idlj -d MYDEF My.idl

is the equivalent of putting the line #define MYDEF inside My.idl.

Preserving Pre-Existing Bindings

If the Java binding files already exist, the -keep flag will keep the compiler from overwriting them. The default is to generate all files without considering if they already exist. If you've customized those files (which you should not do unless you are very comfortable with their contents), then the -keep option is very useful. The command

idlj -keep My.idl

emits all client-side bindings that do not already exist.

Viewing Progress of Compilation

The IDL-to-Java compiler will generate status messages as it progresses through its phases of execution. Use the -v option to activate this "verbose" mode:

idlj -v My.idl

By default the compiler does not operate in verbose mode.

Displaying Version Information

To display the build version of the IDL-to-Java compiler, specify the -version option on the command-line:

idlj -version

Version information also appears within the bindings generated by the compiler. Any additional options appearing on the command-line are ignored.

Options

-d symbol
This is equivalent to the following line in an IDL file:
#define symbol

-emitAll
Emit all types, including those found in #include files.

-fside
Defines what bindings to emit. side is one of client, server, serverTIE, all, or allTIE. The -fserverTIE and -fallTIE options cause delegate model skeletons to be emitted. Assumes -fclient if the flag is not specified.

-i include-path
By default, the current directory is scanned for included files. This option adds another directory.

-keep
If a file to be generated already exists, do not overwrite it. By default it is overwritten.

-noWarn
Suppresses warning messages.

-oldImplBase
Generates skeletons compatible with pre-1.4 JDK ORBs. By default, the POA Inheritance Model server-side bindings are generated. This option provides backward-compatibility with older versions of the Java programming language by generating server-side bindings that are ImplBase Inheritance Model classes.

-pkgPrefix type prefix
Wherever type is encountered at file scope, prefix the generated Java package name with prefix for all files generated for that type. The type is the simple name of either a top-level module, or an IDL type defined outside of any module.

-pkgTranslate type package
Whenever the module name type is encountered in an identifier, replace it in the identifier with package for all files in the generated Java package. Note that pkgPrefix changes are made first. type is the simple name of either a top-level module, or an IDL type defined outside of any module, and must match the full package name exactly.

If more than one translation matches an identifier, the longest match is chosen. For example, if the arguments include:

  -pkgTranslate foo bar -pkgTranslate foo.baz buzz.fizz

The following translations would occur:

foo          =>	bar
foo.boo      =>	bar.boo
foo.baz      =>	buzz.fizz
foo.baz.bar  =>	buzz.fizz.bar

The following package names cannot be translated:

  • org
  • org.omg or any subpackages of org.omg

Any attempt to translate these packages will result in uncompilable code, and the use of these packages as the first argument after -pkgTranslate will be treated as an error.

-skeletonName xxx%yyy
Use xxx%yyy as the pattern for naming the skeleton. The defaults are:
  • %POA for the POA base class (-fserver or -fall)
  • _%ImplBase for the oldImplBase class (-oldImplBase and (-fserver or -fall))

-td dir
Use dir for the output directory instead of the current directory.

-tieName xxx%yyy
Name the tie according to the pattern. The defaults are:
  • %POATie for the POA tie base class (-fserverTie or -fallTie)
  • %_Tie for the oldImplBase tie class (-oldImplBase and (-fserverTie or -fallTie))

-nowarn, -verbose
Verbose mode.

-version
Display version information and terminate.
See the Description section for more option information.

Restrictions:

  • Escaped identifiers in the global scope may not have the same spelling as IDL primitive types, Object, or ValueBase. This is because the symbol table is pre-loaded with these identifiers; allowing them to be redefined would overwrite their original definitions. (Possible permanent restriction).
  • The fixed IDL type is not supported.

Known Problems:

  • No import generated for global identifiers. If you invoke on an unexported local impl, you do get an exception, but it seems to be due to a NullPointerException in the ServerDelegate DSI code.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.source.tree.IfTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.IfTree

  • Packages that use IfTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of IfTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type IfTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitIf(IfTree node, P p)

    • Uses of IfTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type IfTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitIf(IfTree node, P p)
      R | SimpleTreeVisitor.visitIf(IfTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.jdi.connect.IllegalConnectorArgumentsException (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.connect.IllegalConnectorArgumentsException

  • Packages that use IllegalConnectorArgumentsException
    Package Description
    com.sun.jdi.connect
    This package defines connections between the virtual machine using the JDI and the target virtual machine.

    • Uses of IllegalConnectorArgumentsException in com.sun.jdi.connect

      Methods in com.sun.jdi.connect that throw IllegalConnectorArgumentsException
      Modifier and Type Method and Description
      VirtualMachine ListeningConnector.accept(Map<String,? extends Connector.Argument> arguments)
      Waits for a target VM to attach to this connector.
      VirtualMachine AttachingConnector.attach(Map<String,? extends Connector.Argument> arguments)
      Attaches to a running application and and returns a mirror of its VM.
      VirtualMachine LaunchingConnector.launch(Map<String,? extends Connector.Argument> arguments)
      Launches an application and connects to its VM.
      String ListeningConnector.startListening(Map<String,? extends Connector.Argument> arguments)
      Listens for one or more connections initiated by target VMs.
      void ListeningConnector.stopListening(Map<String,? extends Connector.Argument> arguments)
      Cancels listening for connections.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Java Image I/O API Guide

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
PREV | NEXT

1. Introduction
1.1 The Java Image I/O API
1.2 About This Document
1.3 Platforms
1.4 Target Audience
1.5 Acknowledgements
2. Goals
2.1 API Goals
2.1.1 Client-Side Application Goals
2.1.2 Server Use Cases
2.2 Non-Goals
3. Writing Image I/O Applications
3.1 Reading and Writing Images
3.2 Going Further
3.3 ImageReader
3.3.1 ImageReadParam
3.3.2 IIOParamController
3.3.3 Reading From Multi-Image Files
3.3.4 Reading "Thumbnail" Images
3.4 The ImageWriter Class
3.4.1 Writing Multiple Images
3.5 Handling Metadata
3.5.1 The IIOMetadataFormat Interface
3.6 Transcoding
3.7 Listening for Events
3.7.1 The IIOReadProgressListener Interface
3.7.2 The IIOReadUpdateListener Interface
3.7.3 The IIOReadWarningListener Interface
3.7.4 The IIOWriteProgressListener and IIOWriteWarningListener Interfaces
3.8 Handling Errors using IIOException
4. Writing Image I/O Plug-ins
4.1 The Plug-in Concept
4.2 Embedding Plug-ins in JAR Files
4.3 Writing Reader Plug-Ins
4.4 Writing Writer Plug-ins
4.5 Writing Transcoder Plug-ins
4.6 Writing Stream Plug-ins

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Input Method Framework Demo

Download and install the Java Runtime Environment (JRE) to view the applet.

This applet contains four text components that show the different ways of interacting with input methods in the Java 2 platform. This applet can be run in two ways:
  • with an implementation of the Java 2 Platform Standard Edition v1.2 or higher, running on a platform/locale that uses native input methods. Examples: Japanese Windows NT, Macintosh with Chinese Language Kit, Solaris with Korean locale.
  • with an implementation of the Java 2 Platform Standard Edition v1.3 or higher, with an input method installed that's implemented in the Java programming language. The Java runtime environment may be running on a platform/locale that does not support native input methods.

The first three components are lightweight components, i.e., they handle events and render text using Java APIs. The last one is a peered component, that is, event handling and text rendering are handled by a text editing engine provided by the underlying platform. Peered components were used widely in JDK 1.0 AWT, while lightweight components were introduced in JDK 1.1 and are the basis of the Swing class library.

The lightweight components have different capabilities:

  • The active client uses the input method framework API to implement on-the-spot (also called "inline") text composition.
  • The passive client works with input methods in the simplest way - it relies on the input method framework to handle all composition and only accepts committed text.
  • The non-client refuses to work with input methods.

To test with the different components with native Japanese input methods, click into the components to focus on them, turn on an input method (Alt-` on Windows, choosing from the keyboard menu on Macintosh, Control-Space on Solaris), then type "nihongo". The behavior you should see is:

  • Active client: The word is entered in the component directly and gets converted to four hiragana characters as you type.
  • Passive client: A separate window shows up, the word is entered in that window and gets converted to four hiragana characters as you type.
  • Non-client: The text "nihongo" is entered into the component.
  • Peered component: The behavior depends on the platform, but most likely it's similar to the active client (the text may be drawn over the pre-existing text or push it to the right).

For all components except the non-client, you can now convert the text (Space on Windows and Macintosh, Control-N or Space on Solaris) and then commit it (Enter on all three platforms - how could that happen?). Conversion should result in three kanji characters, which after committing are shown in the component without highlight.

To test with the different components with the sample input method implemented in the Java programming language, "City Input Method", install the input method's JAR file into the extensions directory of the Java runtime environment before running the applet. Then click into the components to focus on them, and select the input method. The selection mechanism is implementation dependent; on Sun's Java runtime environments choose the "Select Input Method" menu item from the system menu in the top left corner of the window, then choose the input method from the pop-up menu that comes up. Then type "TYO". The behavior you should see:

  • Active client: The text is entered in the component directly and is highlighted.
  • Passive client: A separate window shows up, the text is entered in that window and is highlighted.
  • Non-client: The text is entered into the component, but not highlighted.
  • Peered component: The behavior depends on the platform.

For all components except the non-client and, on some platforms, the peered component, you can now convert the text using the Space key. The conversion result depends on your default language - it's the name "Tokyo" in Japanese, Japanese yomi, English, German, simplified or traditional Chinese. To see all options, press Space again - this time, you'll get a look-up window showing all the possibilities. You can use Space to go through all possible selections, or type the number of the conversion you like. Pressing the Enter key will commit the selected conversion and remove the highlight.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.source.tree.ImportTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.ImportTree

  • Packages that use ImportTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of ImportTree in com.sun.source.tree

      Methods in com.sun.source.tree that return types with arguments of type ImportTree
      Modifier and Type | Method and Description
      List<? extends ImportTree> | CompilationUnitTree.getImports()
      Methods in com.sun.source.tree with parameters of type ImportTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitImport(ImportTree node, P p)

    • Uses of ImportTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type ImportTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitImport(ImportTree node, P p)
      R | SimpleTreeVisitor.visitImport(ImportTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.jdi.IncompatibleThreadStateException (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.IncompatibleThreadStateException

  • Packages that use IncompatibleThreadStateException
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of IncompatibleThreadStateException in com.sun.jdi

      Methods in com.sun.jdi that throw IncompatibleThreadStateException
      Modifier and Type Method and Description
      ObjectReference ThreadReference.currentContendedMonitor()
      Returns an ObjectReference for the monitor, if any, for which this thread is currently waiting.
      int ObjectReference.entryCount()
      Returns the number times this object's monitor has been entered by the current owning thread.
      void ThreadReference.forceEarlyReturn(Value value)
      Force a method to return before it reaches a return statement.
      StackFrame ThreadReference.frame(int index)
      Returns the StackFrame at the given index in the thread's current call stack.
      int ThreadReference.frameCount()
      Returns the number of stack frames in the thread's current call stack.
      List<StackFrame> ThreadReference.frames()
      Returns a List containing each StackFrame in the thread's current call stack.
      List<StackFrame> ThreadReference.frames(int start, int length)
      Returns a List containing a range of StackFrame mirrors from the thread's current call stack.
      Value ClassType.invokeMethod(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Invokes the specified static Method in the target VM.
      Value ObjectReference.invokeMethod(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Invokes the specified Method on this object in the target VM.
      ObjectReference ClassType.newInstance(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Constructs a new instance of this type, using the given constructor Method in the target VM.
      List<ObjectReference> ThreadReference.ownedMonitors()
      Returns a List containing an ObjectReference for each monitor owned by the thread.
      List<MonitorInfo> ThreadReference.ownedMonitorsAndFrames()
      Returns a List containing a MonitorInfo object for each monitor owned by the thread.
      ThreadReference ObjectReference.owningThread()
      Returns an ThreadReference for the thread, if any, which currently owns this object's monitor.
      void ThreadReference.popFrames(StackFrame frame)
      Pop stack frames.
      List<ThreadReference> ObjectReference.waitingThreads()
      Returns a List containing a ThreadReference for each thread currently waiting for this object's monitor.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.jdi.InconsistentDebugInfoException (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.InconsistentDebugInfoException

No usage of com.sun.jdi.InconsistentDebugInfoException
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Java Object Serialization Specification: 3 - Object Input Classes

CONTENTS | PREV | NEXT Java Object Serialization Specification
version 6.0

Object Input Classes

CHAPTER 3

Topics:

  • The ObjectInputStream Class
  • The ObjectInputStream.GetField Class
  • The ObjectInputValidation Interface
  • The readObject Method
  • The readExternal Method
  • The readResolve Method

3.1 The ObjectInputStream Class

Class ObjectInputStream implements object deserialization. It maintains the state of the stream including the set of objects already deserialized. Its methods allow primitive types and objects to be read from a stream written by ObjectOutputStream. It manages restoration of the object and the objects that it refers to from the stream.

package java.io;

public class ObjectInputStream
    extends InputStream
    implements ObjectInput, ObjectStreamConstants
{
    public ObjectInputStream(InputStream in)
        throws StreamCorruptedException, IOException;

    public final Object readObject()
        throws OptionalDataException, ClassNotFoundException,
            IOException;

    public Object readUnshared()
        throws OptionalDataException, ClassNotFoundException,
            IOException;

    public void defaultReadObject()
        throws IOException, ClassNotFoundException,
            NotActiveException;

    public GetField readFields()
        throws IOException;

    public synchronized void registerValidation(
        ObjectInputValidation obj, int prio)
        throws NotActiveException, InvalidObjectException;

    protected ObjectStreamClass readClassDescriptor()
        throws IOException, ClassNotFoundException;

    protected Class resolveClass(ObjectStreamClass v)
        throws IOException, ClassNotFoundException;

    protected Object resolveObject(Object obj)
        throws IOException;

    protected boolean enableResolveObject(boolean enable)
        throws SecurityException;

    protected void readStreamHeader()
        throws IOException, StreamCorruptedException;

    public int read() throws IOException;

    public int read(byte[] data, int offset, int length)
        throws IOException

    public int available() throws IOException;

    public void close() throws IOException;

    public boolean readBoolean() throws IOException;

    public byte readByte() throws IOException;

    public int readUnsignedByte() throws IOException;

    public short readShort() throws IOException;

    public int readUnsignedShort() throws IOException;

    public char readChar() throws IOException;

    public int readInt() throws IOException;

    public long readLong() throws IOException;

    public float readFloat() throws IOException;

    public double readDouble() throws IOException;

    public void readFully(byte[] data) throws IOException;

    public void readFully(byte[] data, int offset, int size)
        throws IOException;

    public int skipBytes(int len) throws IOException;

    public String readLine() throws IOException;

    public String readUTF() throws IOException;

    // Class to provide access to serializable fields.
    static abstract public class GetField
    {
        public ObjectStreamClass getObjectStreamClass();

        public boolean defaulted(String name)
            throws IOException, IllegalArgumentException;

        public char get(String name, char default)
            throws IOException, IllegalArgumentException;

        public boolean get(String name, boolean default)
            throws IOException, IllegalArgumentException;

        public byte get(String name, byte default)
            throws IOException, IllegalArgumentException;

        public short get(String name, short default)
            throws IOException, IllegalArgumentException;

        public int get(String name, int default)
            throws IOException, IllegalArgumentException;

        public long get(String name, long default)
            throws IOException, IllegalArgumentException;

        public float get(String name, float default)
            throws IOException, IllegalArgumentException;

        public double get(String name, double default)
            throws IOException, IllegalArgumentException;

        public Object get(String name, Object default)
            throws IOException, IllegalArgumentException;
    }

    protected ObjectInputStream()
        throws StreamCorruptedException, IOException;

    protected readObjectOverride()
        throws OptionalDataException, ClassNotFoundException,
            IOException;
}

The single-argument ObjectInputStream constructor requires an InputStream. The constructor calls readStreamHeader to read and verifies the header and version written by the corresponding ObjectOutputStream.writeStreamHeader method. If a security manager is installed, this constructor checks for the "enableSubclassImplementation" SerializablePermission when invoked directly or indirectly by the constructor of a subclass which overrides the readFields and/or readUnshared methods.

Note - The ObjectInputStream constructor blocks until it completes reading the serialization stream header. Code which waits for an ObjectInputStream to be constructed before creating the corresponding ObjectOutputStream for that stream will deadlock, since the ObjectInputStream constructor will block until a header is written to the stream, and the header will not be written to the stream until the ObjectOutputStream constructor executes. This problem can be resolved by creating the ObjectOutputStream before the ObjectInputStream, or otherwise removing the timing dependency between completion of ObjectInputStream construction and the creation of the ObjectOutputStream.
The readObject method is used to deserialize an object from the stream. It reads from the stream to reconstruct an object.

1. If the ObjectInputStream subclass is overriding the implementation, call the readObjectOverride method and return. Reimplementation is described at the end of this section.
2. If a block data record occurs in the stream, throw a BlockDataException with the number of available bytes.
3. If the object in the stream is null, return null.
4. If the object in the stream is a handle to a previous object, return the object.
5. If the object in the stream is a Class, read its ObjectStreamClass descriptor, add it and its handle to the set of known objects, and return the corresponding Class object.
6. If the object in the stream is an ObjectStreamClass, read in its data according to the formats described in section 4.3. Add it and its handle to the set of known objects. In versions 1.3 and later of the Java 2 SDK, Standard Edition, the readClassDescriptor method is called to read in the ObjectStreamClass if it represents a class that is not a dynamic proxy class, as indicated in the stream data. If the class descriptor represents a dynamic proxy class, call the resolveProxyClass method on the stream to get the local class for the descriptor; otherwise, call the resolveClass method on the stream to get the local class. If the class cannot be resolved, throw a ClassNotFoundException. Return the resulting ObjectStreamClass object.
7. If the object in the stream is a String, read its length information followed by the contents of the string encoded in modified UTF-8. For details, refer to Section 6.2, "Stream Elements". Add the String and its handle to the set of known objects, and proceed to Step 12.
8. If the object in the stream is an array, read its ObjectStreamClass and the length of the array. Allocate the array, and add it and its handle in the set of known objects. Read each element using the appropriate method for its type and assign it to the array. Proceed to Step 12.
9. If the object in the stream is an enum constant, read its ObjectStreamClass and the enum constant name. If the ObjectStreamClass represents a class that is not an enum type, an InvalidClassException is thrown. Obtain a reference to the enum constant by calling the java.lang.Enum.valueOf method, passing the enum type bound to the received ObjectStreamClass along with the received name as arguments. If the valueOf method throws an IllegalArgumentException, an InvalidObjectException is thrown with the IllegalArgumentException as its cause. Add the enum constant and its handle in the set of known objects, and proceed to Step 12.
10. For all other objects, the ObjectStreamClass of the object is read from the stream. The local class for that ObjectStreamClass is retrieved. The class must be serializable or externalizable, and must not be an enum type. If the class does not satisfy these criteria, an InvalidClassException is thrown.
11. An instance of the class is allocated. The instance and its handle are added to the set of known objects. The contents restored appropriately:
a. For serializable objects, the no-arg constructor for the first non-serializable supertype is run. For serializable classes, the fields are initialized to the default value appropriate for its type. Then the fields of each class are restored by calling class-specific readObject methods, or if these are not defined, by calling the defaultReadObject method. Note that field initializers and constructors are not executed for serializable classes during deserialization. In the normal case, the version of the class that wrote the stream will be the same as the class reading the stream. In this case, all of the supertypes of the object in the stream will match the supertypes in the currently-loaded class. If the version of the class that wrote the stream had different supertypes than the loaded class, the ObjectInputStream must be more careful about restoring or initializing the state of the differing classes. It must step through the classes, matching the available data in the stream with the classes of the object being restored. Data for classes that occur in the stream, but do not occur in the object, is discarded. For classes that occur in the object, but not in the stream, the class fields are set to default values by default serialization.
b. For externalizable objects, the no-arg constructor for the class is run and then the readExternal method is called to restore the contents of the object.
12. Process potential substitutions by the class of the object and/or by a subclass of ObjectInputStream:
a. If the class of the object is not an enum type and defines the appropriate readResolve method, the method is called to allow the object to replace itself.
b. Then if previously enabled by enableResolveObject, the resolveObject method is called to allow subclasses of the stream to examine and replace the object. If the previous step did replace the original object, the resolveObject method is called with the replacement object.
If a replacement took place, the table of known objects is updated so the replacement object is associated with the handle. The replacement object is then returned from readObject.

All of the methods for reading primitives types only consume bytes from the block data records in the stream. If a read for primitive data occurs when the next item in the stream is an object, the read methods return -1 or the EOFException as appropriate. The value of a primitive type is read by a DataInputStream from the block data record.

The exceptions thrown reflect errors during the traversal or exceptions that occur on the underlying stream. If any exception is thrown, the underlying stream is left in an unknown and unusable state.

When the reset token occurs in the stream, all of the state of the stream is discarded. The set of known objects is cleared.

When the exception token occurs in the stream, the exception is read and a new WriteAbortedException is thrown with the terminating exception as an argument. The stream context is reset as described earlier.

The readUnshared method is used to read "unshared" objects from the stream. This method is identical to readObject, except that it prevents subsequent calls to readObject and readUnshared from returning additional references to the deserialized instance returned by the original call to readUnshared. Specifically:

  • If readUnshared is called to deserialize a back-reference (the stream representation of an object which has been written previously to the stream), an ObjectStreamException will be thrown.
  • If readUnshared returns successfully, then any subsequent attempts to deserialize back-references to the stream handle deserialized by readUnshared will cause an ObjectStreamException to be thrown.
Deserializing an object via readUnshared invalidates the stream handle associated with the returned object. Note that this in itself does not always guarantee that the reference returned by readUnshared is unique; the deserialized object may define a readResolve method which returns an object visible to other parties, or readUnshared may return a Class object or enum constant obtainable elsewhere in the stream or through external means. If the deserialized object defines a readResolve method and the invocation of that method returns an array, then readUnshared returns a shallow clone of that array; this guarantees that the returned array object is unique and cannot be obtained a second time from an invocation of readObject or readUnshared on the ObjectInputStream, even if the underlying data stream has been manipulated.

The defaultReadObject method is used to read the fields and object from the stream. It uses the class descriptor in the stream to read the fields in the canonical order by name and type from the stream. The values are assigned to the matching fields by name in the current class. Details of the versioning mechanism can be found in Section 5.5, "Compatible Java Type Evolution." Any field of the object that does not appear in the stream is set to its default value. Values that appear in the stream, but not in the object, are discarded. This occurs primarily when a later version of a class has written additional fields that do not occur in the earlier version. This method may only be called from the readObject method while restoring the fields of a class. When called at any other time, the NotActiveException is thrown.

The readFields method reads the values of the serializable fields from the stream and makes them available via the GetField class. The readFields method is only callable from within the readObject method of a serializable class. It cannot be called more than once or if defaultReadObject has been called. The GetFields object uses the current object's ObjectStreamClass to verify the fields that can be retrieved for this class. The GetFields object returned by readFields is only valid during this call to the classes readObject method. The fields may be retrieved in any order. Additional data may only be read directly from stream after readFields has been called.

The registerValidation method can be called to request a callback when the entire graph has been restored but before the object is returned to the original caller of readObject. The order of validate callbacks can be controlled using the priority. Callbacks registered with higher values are called before those with lower values. The object to be validated must support the ObjectInputValidation interface and implement the validateObject method. It is only correct to register validations during a call to a class's readObject method. Otherwise, a NotActiveException is thrown. If the callback object supplied to registerValidation is null, an InvalidObjectException is thrown.

Starting with the Java SDK, Standard Edition, v1.3, the readClassDescriptor method is used to read in all ObjectStreamClass objects. readClassDescriptor is called when the ObjectInputStream expects a class descriptor as the next item in the serialization stream. Subclasses of ObjectInputStream may override this method to read in class descriptors that have been written in non-standard formats (by subclasses of ObjectOutputStream which have overridden the writeClassDescriptor method). By default, this method reads class descriptors according to the format described in Section 6.4, "Grammar for the Stream Format".

The resolveClass method is called while a class is being deserialized, and after the class descriptor has been read. Subclasses may extend this method to read other information about the class written by the corresponding subclass of ObjectOutputStream. The method must find and return the class with the given name and serialVersionUID. The default implementation locates the class by calling the class loader of the closest caller of readObject that has a class loader. If the class cannot be found ClassNotFoundException should be thrown. Prior to JDK 1.1.6, the resolveClass method was required to return the same fully qualified class name as the class name in the stream. In order to accommodate package renaming across releases, method resolveClass only needs to return a class with the same base class name and SerialVersionUID in JDK 1.1.6 and later versions.

The resolveObject method is used by trusted subclasses to monitor or substitute one object for another during deserialization. Resolving objects must be enabled explicitly by calling enableResolveObject before calling readObject for the first object to be resolved. Once enabled, resolveObject is called once for each serializable object just prior to the first time it is being returned from readObject. Note that the resolveObject method is not called for objects of the specially handled classes, Class, ObjectStreamClass, String, and arrays. A subclass's implementation of resolveObject may return a substitute object that will be assigned or returned instead of the original. The object returned must be of a type that is consistent and assignable to every reference of the original object or else a ClassCastException will be thrown. All assignments are type-checked. All references in the stream to the original object will be replaced by references to the substitute object.

The enableResolveObject method is called by trusted subclasses of ObjectOutputStream to enable the monitoring or substitution of one object for another during deserialization. Replacing objects is disabled until enableResolveObject is called with a true value. It may thereafter be disabled by setting it to false. The previous setting is returned. The enableResolveObject method checks if the stream has permission to request substitution during serialization. To ensure that the private state of objects is not unintentionally exposed, only trusted streams may use resolveObject. Trusted classes are those classes with a class loader equal to null or belong to a security protection domain that provides permission to enable substitution.

If the subclass of ObjectInputStream is not considered part of the system domain, a line has to be added to the security policy file to provide to a subclass of ObjectInputStream permission to call enableResolveObject. The SerializablePermission to add is "enableSubstitution". AccessControlException is thrown if the protection domain of the subclass of ObjectStreamClass does not have permission to "enableSubstitution" by calling enableResolveObject. See the document Java Security Architecture (JDK 1.2) for additional information about the security model.

The readStreamHeader method reads and verifies the magic number and version of the stream. If they do not match, the StreamCorruptedMismatch is thrown.

To override the implementation of deserialization, a subclass of ObjectInputStream should call the protected no-arg ObjectInputStream, constructor. There is a security check within the no-arg constructor for SerializablePermission "enableSubclassImplementation" to ensure that only trusted classes are allowed to override the default implementation. This constructor does not allocate any private data for ObjectInputStream and sets a flag that indicates that the final readObject method should invoke the readObjectOverride method and return. All other ObjectInputStream methods are not final and can be directly overridden by the subclass.

3.2 The ObjectInputStream.GetField Class

The class ObjectInputStream.GetField provides the API for getting the values of serializable fields. The protocol of the stream is the same as used by defaultReadObject. Using readFields to access the serializable fields does not change the format of the stream. It only provides an alternate API to access the values which does not require the class to have the corresponding non-transient and non-static fields for each named serializable field. The serializable fields are those declared using serialPersistentFields or if it is not declared the non-transient and non-static fields of the object. When the stream is read the available serializable fields are those written to the stream when the object was serialized. If the class that wrote the stream is a different version not all fields will correspond to the serializable fields of the current class. The available fields can be retrieved from the ObjectStreamClass of the GetField object.

The getObjectStreamClass method returns an ObjectStreamClass object representing the class in the stream. It contains the list of serializable fields.

The defaulted method returns true if the field is not present in the stream. An IllegalArgumentException is thrown if the requested field is not a serializable field of the current class.

Each get method returns the specified serializable field from the stream. I/O exceptions will be thrown if the underlying stream throws an exception. An IllegalArgumentException is thrown if the name or type does not match the name and type of an field serializable field of the current class. The default value is returned if the stream does not contain an explicit value for the field.

3.3 The ObjectInputValidation Interface

This interface allows an object to be called when a complete graph of objects has been deserialized. If the object cannot be made valid, it should throw the ObjectInvalidException. Any exception that occurs during a call to validateObject will terminate the validation process, and the InvalidObjectException will be thrown.

package java.io;

public interface ObjectInputValidation
{
    public void validateObject()
        throws InvalidObjectException;
}

3.4 The readObject Method

For serializable objects, the readObject method allows a class to control the deserialization of its own fields. Here is its signature:

    private void readObject(ObjectInputStream stream)
        throws IOException, ClassNotFoundException;
Each subclass of a serializable object may define its own readObject method. If a class does not implement the method, the default serialization provided by defaultReadObject will be used. When implemented, the class is only responsible for restoring its own fields, not those of its supertypes or subtypes.

The readObject method of the class, if implemented, is responsible for restoring the state of the class. The values of every field of the object whether transient or not, static or not are set to the default value for the fields type. Either ObjectInputStream's defaultReadObject or readFields method must be called once (and only once) before reading any optional data written by the corresponding writeObject method; even if no optional data is read, defaultReadObject or readFields must still be invoked once. If the readObject method of the class attempts to read more data than is present in the optional part of the stream for this class, the stream will return -1 for bytewise reads, throw an EOFException for primitive data reads (e.g., readInt, readFloat), or throw an OptionalDataException with the eof field set to true for object reads.

The responsibility for the format, structure, and versioning of the optional data lies completely with the class. The @serialData javadoc tag within the javadoc comment for the readObject method should be used to document the format and structure of the optional data.

If the class being restored is not present in the stream being read, then its readObjectNoData method, if defined, is invoked (instead of readObject); otherwise, its fields are initialized to the appropriate default values. For further detail, see section 3.5.

Reading an object from the ObjectInputStream is analogous to creating a new object. Just as a new object's constructors are invoked in the order from the superclass to the subclass, an object being read from a stream is deserialized from superclass to subclass. The readObject or readObjectNoData method is called instead of the constructor for each Serializable subclass during deserialization.

One last similarity between a constructor and a readObject method is that both provide the opportunity to invoke a method on an object that is not fully constructed. Any overridable (neither private, static nor final) method called while an object is being constructed can potentially be overridden by a subclass. Methods called during the construction phase of an object are resolved by the actual type of the object, not the type currently being initialized by either its constructor or readObject/readObjectNoData method. Therefore, calling an overridable method from within a readObject or readObjectNoData method may result in the unintentional invocation of a subclass method before the superclass has been fully initialized.

3.5 The readObjectNoData Method

For serializable objects, the readObjectNoData method allows a class to control the initialization of its own fields in the event that a subclass instance is deserialized and the serialization stream does not list the class in question as a superclass of the deserialized object. This may occur in cases where the receiving party uses a different version of the deserialized instance's class than the sending party, and the receiver's version extends classes that are not extended by the sender's version. This may also occur if the serialization stream has been tampered; hence, readObjectNoData is useful for initializing deserialized objects properly despite a "hostile" or incomplete source stream.

  private void readObjectNoData() throws ObjectStreamException;

Each serializable class may define its own readObjectNoData method. If a serializable class does not define a readObjectNoData method, then in the circumstances listed above the fields of the class will be initialized to their default values (as listed in The Java Language Specification); this behavior is consistent with that of ObjectInputStream prior to version 1.4 of the Java 2 SDK, Standard Edition, when support for readObjectNoData methods was introduced. If a serializable class does define a readObjectNoData method and the aforementioned conditions arise, then readObjectNoData will be invoked at the point during deserialization when a class-defined readObject method would otherwise be called had the class in question been listed by the stream as a superclass of the instance being deserialized.

3.6 The readExternal Method

Objects implementing java.io.Externalizable must implement the readExternal method to restore the entire state of the object. It must coordinate with its superclasses to restore their state. All of the methods of ObjectInput are available to restore the object's primitive typed fields and object fields.

    public void readExternal(ObjectInput stream)
        throws IOException;
Note - The readExternal method is public, and it raises the risk of a client being able to overwrite an existing object from a stream. The class may add its own checks to insure that this is only called when appropriate.
A new stream protocol version has been introduced in JDK 1.2 to correct a problem with Externalizable objects. The old definition of Externalizable objects required the local virtual machine to find a readExternal method to be able to properly read an Externalizable object from the stream. The new format adds enough information to the stream protocol so serialization can skip an Externalizable object when the local readExternal method is not available. Due to class evolution rules, serialization must be able to skip an Externalizable object in the input stream if there is not a mapping for the object using the local classes.

An additional benefit of the new Externalizable stream format is that ObjectInputStream can detect attempts to read more External data than is available, and can also skip by any data that is left unconsumed by a readExternal method. The behavior of ObjectInputStream in response to a read past the end of External data is the same as the behavior when a class-defined readObject method attempts to read past the end of its optional data: bytewise reads will return -1, primitive reads will throw EOFExceptions, and object reads will throw OptionalDataExceptions with the eof field set to true.

Due to the format change, JDK 1.1.6 and earlier releases are not able to read the new format. StreamCorruptedException is thrown when JDK 1.1.6 or earlier attempts to read an Externalizable object from a stream written in PROTOCOL_VERSION_2. Compatibility issues are discussed in more detail in Section 6.3, "Stream Protocol Versions."

3.7 The readResolve Method

For Serializable and Externalizable classes, the readResolve method allows a class to replace/resolve the object read from the stream before it is returned to the caller. By implementing the readResolve method, a class can directly control the types and instances of its own instances being deserialized. The method is defined as follows:

    ANY-ACCESS-MODIFIER Object readResolve()
            throws ObjectStreamException;
The readResolve method is called when ObjectInputStream has read an object from the stream and is preparing to return it to the caller. ObjectInputStream checks whether the class of the object defines the readResolve method. If the method is defined, the readResolve method is called to allow the object in the stream to designate the object to be returned. The object returned should be of a type that is compatible with all uses. If it is not compatible, a ClassCastException will be thrown when the type mismatch is discovered.

For example, a Symbol class could be created for which only a single instance of each symbol binding existed within a virtual machine. The readResolve method would be implemented to determine if that symbol was already defined and substitute the preexisting equivalent Symbol object to maintain the identity constraint. In this way the uniqueness of Symbol objects can be maintained across serialization.

Note - The readResolve method is not invoked on the object until the object is fully constructed, so any references to this object in its object graph will not be updated to the new object nominated by readResolve. However, during the serialization of an object with the writeReplace method, all references to the original object in the replacement object's object graph are replaced with references to the replacement object. Therefore in cases where an object being serialized nominates a replacement object whose object graph has a reference to the original object, deserialization will result in an incorrect graph of objects. Furthermore, if the reference types of the object being read (nominated by writeReplace) and the original object are not compatible, the construction of the object graph will raise a ClassCastException.

CONTENTS | PREV | NEXT
Copyright © 2005, 2010, Oracle and/or its affiliates. All rights reserved.


Uses of Class com.sun.security.jgss.InquireSecContextPermission (Java GSS-API Utilities b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java GSS-API Utilities
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.jgss.InquireSecContextPermission

No usage of com.sun.security.jgss.InquireSecContextPermission
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java GSS-API Utilities
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2000, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.jgss.InquireType (Java GSS-API Utilities b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java GSS-API Utilities
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.jgss.InquireType

    • Uses of InquireType in com.sun.security.jgss

      Methods in com.sun.security.jgss that return InquireType
      Modifier and Type Method and Description
      static InquireType InquireType.valueOf(String name)
      Returns the enum constant of this type with the specified name.
      static InquireType[] InquireType.values()
      Returns an array containing the constants of this enum type, in the order they are declared.
      Methods in com.sun.security.jgss with parameters of type InquireType
      Modifier and Type Method and Description
      Object ExtendedGSSContext.inquireSecContext(InquireType type)
      Return the mechanism-specific attribute associated with type.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java GSS-API Utilities
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2000, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


JRE Deployment with Active Directory

This procedure describes how to obtain the .msi file necessary to deploy the Java Runtime Environment (JRE) across a Windows 2000/Windows XP Active Directory-based network. It works for version 1.4.2 and later of the JRE installers. Sun includes an .msi (Microsoft Installer) file bundled up in the JRE Windows Offline installers. The .msi file extracted below can be assigned to an Active Directory software distribution policy.

  1. Download and launch the Sun JRE Windows Offline Installion executable (.exe) file.

  2. Retrieve the ".msi" file from the LocalAppData folder (the user's Application Data folder). The LocalAppData folder will differ for each Windows platform.

  3. Inside this folder you will find a folder named:

    {3248F0A6-6813-11D6-A77b-00B0D0150000}

    The first 2 digits are "71" for version 1.4.2_xx, and "32" for 1.5.0_xx. The last 6 digits of this CLSID and the name of the .msi file correspond to the release number. A CLSID ending with "150000" means version 1.5.0_00, and "142010" means verision 1.4.2_01

  4. From there, you can use Active Directory to distribute this .msi file to as many client Windows platforms as you want.

  5. If you want to register the JRE as the default VM of Internet Explorer and Mozilla, you will have to create a transform that will set the variables IEXPLORER and MOZILLA to 1 in the Property.idt table. You can find instructions on how to generate and use transforms at the Microsoft MSDN site.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Installation for Conventional Applets

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

< Contents

Installation for Conventional Applets (Microsoft Window Only)

This section covers the following topics:

  • Enabling APPLET Tag Support
  • Silent Installation Options

Enabling APPLET Tag Support

Developers should be aware that end users of Java Plug-in can choose to enable or disable APPLET tag support during installation or at any time after installation.

As part of the installation process, the user will see the following panel:

Sample Select Browser window

This panel allows the user to select JRE/Java Plug-in to be the default runtime environment for handling APPLET tags in Microsoft Internet Explorer browsers and/or Mozilla family browsers. The installer will use the Windows registry to determine whether the user's machine has these browsers installed and will check by default the box corresponding to any installed browser(s).

The user can enable or disable APPLET tag support after installation through the Browser panel of the Java Plug-in Control Panel.

On Microsoft Internet Explorer, users also can use the Advanced tab in the Internet Options window to enable/disable Java Plug-in's APPLET tag support. (Tools>Internet Options > Advanced tab.)

sample Advanced tab

Silent Installation Options

Java Plug-in supports silent installation as an alternative to the standard installation wizard. Silent installation might be used, for example, for large-scale deployment. For general information on silent installation of Java Plug-in, see Silent Installation.

Unlike the installation using the wizard, silent installation will not enable APPLET tag support by default for any browsers on the end user's machine. To enable APPLET tag support during silent installation, you must use one or both of the following command-line options:

IEXPLORER=1

If this flag is passed to the installer, APPLET tag support will be enabled for Microsoft Internet Explorer browsers.

MOZILLA=1

If this flag is passed to the installer, APPLET tag support will be enabled for Mozilla family browsers.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.source.tree.InstanceOfTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.InstanceOfTree

  • Packages that use InstanceOfTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of InstanceOfTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type InstanceOfTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitInstanceOf(InstanceOfTree node, P p)

    • Uses of InstanceOfTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type InstanceOfTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitInstanceOf(InstanceOfTree node, P p)
      R | SimpleTreeVisitor.visitInstanceOf(InstanceOfTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Contents | Previous | Next

Chapter 3

Instrumenting Your Resources for JMX Technology

This chapter outlines the concepts behind instrumenting resources for management using JMX technology, in the following sections:

  • "Manageable Resources"
  • "Managed Beans (MBeans)"
  • "Java Virtual Machine Instrumentation"

Manageable Resources

Different types of resource can be managed using JMX technology, for example an application, an implementation of a service, a device or a user. For a given resource to be managed by JMX technology, it must be developed in the Java language, or at least offer a Java language wrapper. It must also be instrumented by one or more Java objects known as managed beans (MBeans), in compliance with the JMX specification.

Developers of applications and devices are free to choose the granularity of objects that are instrumented as MBeans. An MBean might represent the smallest object in an application, or it could represent the entire application. Application components designed with their management interface in mind can typically be written as MBeans. MBeans can also be used as wrappers for legacy code without a management interface or as proxies for code with a legacy management interface.

Managed Beans (MBeans)

The Java objects that implement resources and their instrumentation are called managed beans, or MBeans. MBeans must follow the design patterns and interfaces defined in the JMX specification (JSR 3). This ensures that all MBeans provide the instrumentation of managed resources in a standardized way.

The instrumentation of a given resource is provided by one or more MBeans that are either standard or dynamic. Standard MBeans are Java objects that conform to certain design patterns derived from the JavaBeansTM component model. Dynamic MBeans conform to a specific interface that offers more flexibility at runtime. MXBeans reference only a pre-defined set of types.

The instrumentation of a resource allows it to be manageable through the agent level described in Chapter 4, "Using JMX Agents". MBeans do not require knowledge of the JMX agent with which they operate.

MBeans are designed to be flexible, simple, and easy to implement. Developers of applications, services, or devices can make their products manageable in a standard way without having to understand or invest in complex management systems. Existing objects can easily be evolved to produce standard MBeans or wrapped as dynamic MBeans, thus making existing resources manageable with minimum effort.

In addition, the instrumentation level also specifies a notification mechanism. This allows MBeans to generate and propagate notification events to components of the other levels.

The management interface of an MBean consists of:

  • Named and typed attributes that can be read and/or written
  • Named and typed operations that can be invoked
  • Typed notifications that can be emitted by the MBean

The Java class of a standard MBean exposes the resource to be managed directly through its attributes and operations. Attributes are internal entities that are exposed through getter and setter methods. Operations are the other methods of the class that are available to managers. All these methods are defined statically in the MBean interface and are visible to a JMX agent through introspection. This is the most straightforward way of making a new resource manageable.

A dynamic MBean is an MBean that defines its management interface at runtime. For example, a configuration MBean could determine the names and types of the attributes it exposes by parsing an XML file.

An MXBean is a new type of MBean that provides a simple way to code an MBean that only references a pre-defined set of types. In this way, you can be sure that your MBean will be usable by any client, including remote clients, without any requirement that the client have access to model-specific classes representing the types of your MBeans.

Java Virtual Machine Instrumentation

The Java Virtual Machine (Java VM) is highly instrumented using JMX technology. You can easily start a JMX agent to access the built-in Java VM instrumentation, and thereby monitor and manage the Java VM remotely by means of JMX technology.

To find out more about using JMX technology to monitor and manage the Java VM, see the Java SE Monitoring and Management Guide.

Contents | Previous | Next
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL: Interoperable Naming Service (INS) Example

The Interoperable Naming Service (INS) is an extension to the CosNaming service. It provides the following additional features:

  • Capability to resolve using stringified names (e.g., Department/Accounting/TravelExpenses)
  • URLs for CORBA object references (corbaloc: and corbaname: formats)
  • Convenient APIs in NamingContextExt for handling CosNames and URLs
  • ORB arguments for bootstrapping (ORBInitRef and ORBDefaultInitRef)

The following diagram shows how INS fits into ORBD:

An object reference contains at least three pieces of information: an address, the name of the POA that created an object reference, and an Object ID.

Using INS, you can provide an URL to access the CORBA object, which is more readable than a stringified Interoperable Object References (IOR). The following stringified object reference formats are allowed:

  • Interoperable Object References (IOR)

    An IOR is an object reference that is understood by ORBs that can interoperate using the OMG-defined protocols General Inter-ORB Protocol (GIOP) and Internet Inter-ORB Protocol (IIOP). A client can obtain an object reference using orb.object_to_string(objRef), as shown in the Browsing the Namespace example, or as a result of an invocation on another object reference.

  • Human-Readable URL Formats for CORBA Object References

    The corbaloc and corbaname formats enable you to provide a URL to access CORBA objects. Use the corbaloc format for resolving to a particular CORBAservice without going through a naming service. Use the corbaname format to resolve a stringified name from a specific naming context.

    • corbaloc:

      The corbaloc: format is used to locate CORBA services, is useful for CORBA client programs, and is typically used to resolve the reference using the GIOP LocateRequest or Request message. For example, a corbaloc: object reference might look like this:

              corbaloc:iiop:1.2@MyBank.com:2050/TraderService

      This example show how to get an object reference for TraderService from host myBank.com on port 2050.

      NOTE: The 1.2 in the example URL refers to GIOP version 1.2 for the IOR that corresponds to that corbaloc URL. GIOP 1.2 is the default value for Sun's Java CORBA ORB. It is shown in this example in order to demonstrate how you can plug in a different version.

    • corbaname:

      The corbaname: format provides a mechanism for a client to bootstrap directly, and is typically used to resolve the stringified name from the root naming context. For example, a corbaname: object reference might look like this:

              corbaname::myBank.com:2050#Personal/schedule

      where myBank.com is the host, 2050 is the port. The portion of the reference up to the hash mark (corbaname::myBank.com:2050 ) is the URL that returns the root naming context. This example provides the URL to use to: a) locate the Naming Service, and, b) resolve the name Personal/schedule from the Naming Service.

NamingContextExt API

The NamingContextExt interface, derived from NamingContext provides the operations required to use URLs and stringified names. Some of the APIs in NamingContextExt for converting between CosNames, Stringified Names, and URLs are listed below. See the COS Naming Specification, Section 3.6.4, for more information on these API.

  • to_string

    This operation accepts a Name and returns a stringified name. If the Name is invalid, an InvalidName exception is raised.

  • to_name

    This operation accepts a stringified name and returns a Name. If the stringified name is syntactically malformed or violates an implementation limit, an InvalidName exception is raised.

  • resolve_str

    This is a convenience operation that performs a resolve in the same manner as NamingContext.resolve(). It accepts a stringified name as an argument instead of a Name.

  • to_url

    This operation takes a corbaloc URL <address> and <key_string> component such as

    • :myhost.555xyz.com
    • :myhost.555xyz.com/a/b/c
    • atm:00002112...,:myhost.xyz.com/a/b/c

    for the first parameter, and a stringified name for the second. It then performs any escapes necessary on the parameters and returns a fully formed URL string. An exception is raised if either the corbaloc address and key parameter or name parameter are malformed.

    It is legal for the stringified_name to be empty. If the address is empty, an InvalidAddress exception is raised.

Conversions from URLs to objects are handled by org.omg.CORBA.ORB.string_to_object() as described in the CORBA 2.3 Specification, Section 13.6.6.

The following Java IDL tutorials use NamingContextExt:

  • Java IDL: The "Hello World" Example (using the POA and a transient server)
  • Java IDL: The "Hello World" Example (using the POA, a persistent server, and a persistent naming service)
  • Java IDL: The "Hello World" Example (using the POA-Tie server-side model)

Bootstrap Options for the ORB

The ORB can be configured to return the handle of a customized CORBA service from resolve_initial_references() using either ORBInitRef and/or ORBDefaultInitRef. For example,

  • Use -ORBInitRef to resolve to specific CORBA services, for example,
    -ORBInitRef TraderService=corbaloc::myBank.com:2050/TraderService
  • If no -ORBInitRef is given, -ORBDefaultInitRef is used to resolve. In the TraderService example,
    -ORBDefaultInitRef corbaloc:iiop:1.2:myBank.com:2050

The order of resolution when these options are used is as follows:

  1. Objects registered with register_initial_references
  2. -ORBInitRef
  3. -ORBDefaultInitRef
  4. Proprietary Bootstrap (Sun ORBs only)

For more information about INS, refer to the INS Naming Specification.

INS Example: Publishing a Reference to be Accessed by INS URL's

This document is a high-level overview of how to create a complete CORBA (Common Object Request Broker Architecture) application using the Interoperable Naming Service (INS).

This example makes use of the following files:

  • The IDL for a simple interface for this example
  • A server that creates an object and publishes it to be used by INS URL's
  • The implementation of the Service interface
  • An application client that retrieves a reference from the server using corbaloc: URL
  • Instructions for compiling and running the example

step Each step in the tutorial is indicated by this symbol.

Defining the Interface (Service.idl)

The first step to creating a CORBA application is to specify all of your objects and their interfaces using the OMG's Interface Definition Language (IDL).

The following code is written in the OMG IDL, and describes a CORBA object whose ping() operation pings the INS Service.

step Create the file Service.idl and add the following code:

Service.idl

// A very simple interface to explain this example
interface Service {
    void ping();
};

Implementing the Server (INSServer.java)

The INSServer class has the server's main() method, which:

  • Sets the ORBPeristentServerPort property in order to open up a port to listen for INS requests (Sun proprietary property)
  • Creates and initializes an ORB instance
  • Gets a reference to the root POA and activates its POAManager
  • Creates a servant (the implementation of one CORBA ServiceImpl object)
  • Registers the new object in the naming context under the name "PingService"
  • Waits for invocations of the new object from the client

step Create the file INSServer.java and add the following code:

INSServer.java

// INSServer.java
// Copyright and License
import java.util.Properties;
import org.omg.CORBA.Object;
import org.omg.CORBA.ORB;
import org.omg.CORBA.Policy;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.*;
import org.omg.PortableServer.Servant;

public class INSServer {
    public static void main( String args[] ) {
        try {
            Properties properties = System.getProperties( );
            // STEP 1: Set ORBPeristentServerPort property
            // Set the proprietary property to open up a port to listen to
            // INS requests.
            // Note: This property is subject to change in future releases
            properties.put( "com.sun.CORBA.POA.ORBPersistentServerPort",
                Integer.toString(1060) );

            // STEP 2: Instantiate the ORB, By passing in the
            // ORBPersistentServerPort property set in the previous step
            ORB orb = ORB.init( args, properties );

            // STEP 3: Instantiate the Service Object that needs to be published
            // and associate it with RootPOA.
            ServiceImpl servant = new ServiceImpl( );
            POA rootPOA = POAHelper.narrow( orb.resolve_initial_references( "RootPOA" ));
            rootPOA.the_POAManager().activate();
            rootPOA.activate_object( servant );

            // STEP 4: Publish the INS Service using
            // orb.register_initial_reference( <ObjectKey>, <ObjectReference>
            // NOTE: Sun private internal API, not part of CORBA 2.3.1.
            // May move as our compliance with OMG standards evolves.
            ((com.sun.corba.se.internal.Interceptors.PIORB) orb).
                register_initial_reference(
                "PingService", rootPOA.servant_to_reference(servant) );

            System.out.println( "INS Server is Ready..." );

            // STEP 5: We are ready to receive requests
            orb.run( );
        } catch ( Exception e ) {
             System.err.println( "Error in setup : " + e );
        }
    }
}

Implementing the Service (ServiceImpl.java)

The example implementation, ServiceImpl, is the implementation of the Service IDL interface.

step Create the file ServiceImpl.java and add the following code:

ServiceImpl.java

// ServiceImpl.java
// Copyright and License

// Implementation of Service interface
public class ServiceImpl extends ServicePOA {
    public void ping( ) {
        System.out.println( "PingService.ping called..." );
    }
}

Implementing the Client Application (INSClient.java)

The example application client that follows:

  • Creates and initializes an ORB
  • Retrieves PingService object reference using resolve_initial_references()
  • Invokes the PingService's ping() operation and prints the result

step Create the file INSClient.java and add the following code:

INSClient.java

// INSClient.java
// Copyright and License

import org.omg.CORBA.ORB;

public class INSClient {
    public static void main( String args[] ) {
        try {
            // STEP 1: Instantiate the ORB
            ORB orb = ORB.init( args, null );

            // STEP 2: Resolve PingService using orb.resolve_initial_references()
            // In this example we have used -ORBInitRef argument to locate the
            // PingService. User can also choose to pass the corbaloc: url to
            // orb.string_to_object to resolve the published PingService
            // reference.
            org.omg.CORBA.Object object = orb.resolve_initial_references(
                "PingService" );

            // STEP 3: Narrow the reference and we are ready to invoke method
            // on PingService.
            Service insService = ServiceHelper.narrow( object );

            insService.ping( );
            System.out.println( "The server has been pinged" );

        } catch ( Exception e ) {
            System.err.println( "Exception in INSClient " + e );
            e.printStackTrace( );
        }
    }
}

Building and Running the INS Example

When running this example, we recommend that you use a port number greater than or equal to 1024. This is because you must become root to start a process on a port under 1024 when using Solaris software. The ORBPersistentServerPort property of the server has been set to 1060 in this example.

Compile the Interface Definition

step Change to the directory that contains the file Service.idl, and run the IDL-to-Java compiler as shown below:

  idlj -fall  Service.idl

You must use the -fall option with the idlj compiler to generate both client and server-side bindings. For more information on the idlj options, see IDL-to-Java compiler options.

The files generated by the idlj compiler for Service.idl, with the -fall command line option, are:

  • ServicePOA.java - the server skeleton
  • _ServiceStub.java - client stub
  • Service.java - the Java version of our IDL interface
  • ServiceHelper.java - auxiliary functionality, notably the narrow() method
  • ServiceHolder.java - holds a public instance member of type INS
  • ServiceOperations.java - contains the method ping()

Compile the Java files

step Compile the .java files, including the stubs and skeletons, as follows:

   javac *.java

Start the INS Server

step Start the INS server:

  java -classpath . INSServer

If the INS Server is running correctly, the following message will display:

INS Server is Ready...

Start the Client Application

step Open another terminal window or DOS shell and run the client application:

  java -classpath . INSClient -ORBInitRef
    PingService=corbaloc:iiop:1.2@localhost:1060/PingService

When the client is run with the -ORBInitRef option, it will be able to locate PingService. The following message displays in the client window:

The server has been pinged

And the following message displays in the server window:

PingService.ping called...

When you have finished this tutorial, be sure to shut down or kill the INS server. To do this from a DOS prompt, select the window that is running the server and enter Ctrl+C to shut it down. To do this from a Unix shell, open the shell that was running the client and type pkill INSServer.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.IntegerType (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.IntegerType

No usage of com.sun.jdi.IntegerType
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.IntegerValue (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.IntegerValue

  • Packages that use IntegerValue
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of IntegerValue in com.sun.jdi

      Methods in com.sun.jdi that return IntegerValue
      Modifier and Type Method and Description
      IntegerValue VirtualMachine.mirrorOf(int value)
      Creates an IntegerValue for the given value.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


IntegrationService (JNLP API Reference 1.7.0)

  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method
javax.jnlp

Interface IntegrationService

  • public interface IntegrationService
    Provides desktop integration for JNLP applications. In particular, this service provides API for programmatically request, query and remove shortcuts and request, query and remove mimetype associations.
    Since:
    6.0.18

    • Method Summary

      Methods
      Modifier and Type Method and Description
      boolean hasAssociation(java.lang.String mimetype, java.lang.String[] extensions)
      Checks if this application is associated with the specified mimetype and filename extensions.
      boolean hasDesktopShortcut()
      Checks if the application has a desktop shortcut.
      boolean hasMenuShortcut()
      Checks if the application has a menu shortcut.
      boolean removeAssociation(java.lang.String mimetype, java.lang.String[] extensions)
      Remove an association for this application as handler for the specified mimetype.
      boolean removeShortcuts()
      Requests that all shortcuts for the application are removed.
      boolean requestAssociation(java.lang.String mimetype, java.lang.String[] extensions)
      Requests that this application is registered as the handler for the specified mime type and (optionally) filename extensions.
      boolean requestShortcut(boolean desktop, boolean menu, java.lang.String submenu)
      Requests that a shortcut is created for this application.

    • Method Detail

      • requestShortcut

        boolean requestShortcut(boolean desktop,
                      boolean menu,
                      java.lang.String submenu)
        Requests that a shortcut is created for this application. It can be specified to appear in a system menu, on the desktop or both. For the menu it is possible to specify a submenu path where the shortcut should be placed.
        Parameters:
        desktop - true if the shortcut should appear on the desktop
        menu - true if the shortcut should appear in a system menu
        submenu - the path to the submenu where to place the shortcut (only meaningful if menu is true).
        The path is relative to the (platform dependant) default menu path.
        Returns:
        true if all shortcuts have been created successfully, false otherwise

      • hasDesktopShortcut

        boolean hasDesktopShortcut()
        Checks if the application has a desktop shortcut.
        Returns:
        true if the application has a desktop shortcut, false otherwise

      • hasMenuShortcut

        boolean hasMenuShortcut()
        Checks if the application has a menu shortcut.
        Returns:
        true if the application has a menu shortcut, false otherwise

      • removeShortcuts

        boolean removeShortcuts()
        Requests that all shortcuts for the application are removed.
        Returns:
        true if the shortcuts have been removed successfully false otherwise

      • requestAssociation

        boolean requestAssociation(java.lang.String mimetype,
                         java.lang.String[] extensions)
        Requests that this application is registered as the handler for the specified mime type and (optionally) filename extensions.
        Parameters:
        mimetype - the mimetype to register this application as handler for
        extensions - the filename extensions to register this application as handler for or null
        Returns:
        true if the app has been associated successfully, false otherwise
        Throws:
        java.lang.IllegalArgumentException - if either mimetype or extensions is null, or if mimetype has illegal mime type syntax, or if extensions contains null or empty elements

      • hasAssociation

        boolean hasAssociation(java.lang.String mimetype,
                     java.lang.String[] extensions)
        Checks if this application is associated with the specified mimetype and filename extensions.
        Parameters:
        mimetype - the mimetype to check association for
        extensions - the filename extensions to check association for
        Returns:
        true if this application is associated with the specified mimetype and filename extensions, false otherwise
        Throws:
        java.lang.IllegalArgumentException - if either mimetype or extensions is null, or if mimetype has illegal mime type syntax, or if extensions contains null or empty elements

      • removeAssociation

        boolean removeAssociation(java.lang.String mimetype,
                        java.lang.String[] extensions)
        Remove an association for this application as handler for the specified mimetype.
        Parameters:
        mimetype - the mimetype to remove association for
        extensions - the filename extensions to remove association for
        Returns:
        true if the association has been removed successfully, false otherwise
        Throws:
        java.lang.IllegalArgumentException - if either mimetype or extensions is null, or if mimetype has illegal mime type syntax, or if extensions contains null or empty elements
  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.


Uses of Interface com.sun.mirror.declaration.InterfaceDeclaration (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.declaration.InterfaceDeclaration

  • Packages that use InterfaceDeclaration
    Package Description
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.
    com.sun.mirror.type
    Interfaces used to model types.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of InterfaceDeclaration in com.sun.mirror.declaration

      Subinterfaces of InterfaceDeclaration in com.sun.mirror.declaration
      Modifier and Type Interface and Description
      interface  AnnotationTypeDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in TypeElement.
      Methods in com.sun.mirror.declaration that return types with arguments of type InterfaceDeclaration
      Modifier and Type Method and Description
      Collection<InterfaceDeclaration> PackageDeclaration.getInterfaces()
      Deprecated.
      Returns the declarations of the top-level interfaces in this package.

    • Uses of InterfaceDeclaration in com.sun.mirror.type

      Methods in com.sun.mirror.type that return InterfaceDeclaration
      Modifier and Type Method and Description
      InterfaceDeclaration InterfaceType.getDeclaration()
      Deprecated.
      Returns the declaration of this type.

    • Uses of InterfaceDeclaration in com.sun.mirror.util

      Methods in com.sun.mirror.util with parameters of type InterfaceDeclaration
      Modifier and Type Method and Description
      void SimpleDeclarationVisitor.visitInterfaceDeclaration(InterfaceDeclaration d)
      Deprecated.
      Visits an interface declaration.
      void DeclarationVisitor.visitInterfaceDeclaration(InterfaceDeclaration d)
      Deprecated.
      Visits an interface declaration.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.type.InterfaceType (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.type.InterfaceType

  • Packages that use InterfaceType
    Package Description
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.
    com.sun.mirror.type
    Interfaces used to model types.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of InterfaceType in com.sun.mirror.declaration

      Methods in com.sun.mirror.declaration that return types with arguments of type InterfaceType
      Modifier and Type Method and Description
      Collection<InterfaceType> TypeDeclaration.getSuperinterfaces()
      Deprecated.
      Returns the interface types directly implemented by this class or extended by this interface.

    • Uses of InterfaceType in com.sun.mirror.type

      Subinterfaces of InterfaceType in com.sun.mirror.type
      Modifier and Type Interface and Description
      interface  AnnotationType
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in DeclaredType.
      Methods in com.sun.mirror.type that return types with arguments of type InterfaceType
      Modifier and Type Method and Description
      Collection<InterfaceType> DeclaredType.getSuperinterfaces()
      Deprecated.
      Returns the interface types that are direct supertypes of this type.

    • Uses of InterfaceType in com.sun.mirror.util

      Methods in com.sun.mirror.util with parameters of type InterfaceType
      Modifier and Type Method and Description
      void TypeVisitor.visitInterfaceType(InterfaceType t)
      Deprecated.
      Visits an interface type.
      void SimpleTypeVisitor.visitInterfaceType(InterfaceType t)
      Deprecated.
      Visits an interface type.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.jdi.InternalException (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.InternalException

No usage of com.sun.jdi.InternalException
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Deployment: Internet

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

< Contents

Internet Deployment

Deploying Java Plug-in with Internet Explorer

With Internet Explorer it is recommended that you use the APPLET tag for internet deployment. However, you could use the OBJECT tag in certain cases; e.g., if you want users to use a particular version of Java Plug-in. In the case that the you chose to use the OBJECT tag, the following is recommended.

Recommendations

The following is recommeded for long-term reliability:

  • For the codebase attribute in the OBJECT tag, it is recommended that you use the .exe version, rather than the .cab version, on java.sun.com. That .cab version on java.sun.com may point to an updated version that you do not want to use for your deployment.
  • It is also recommend that you create your own download site for the versions you need so that you do not rely on java.sun.com. Downloads on java.sun.com frequently change.

These are the same recommendations as for the intranet environment.

Deploying Java Plug-in with Mozilla

With supported Mozilla browsers it is recommended that you use the APPLET tag for internet deployment.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Enterprise JavaBeans[tm] Components and CORBA Clients: A Developer Guide

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Enterprise JavaBeansTM Components and CORBA Clients: A Developer Guide

This paper discusses how to enable a client written in any language supported by CORBA to access Enterprise JavaBeansTM components ("EJBTM components"). This paper is directed at programmers with advanced knowledge of both the JavaTM 2 Platform, Enterprise Edition ("J2EETM") and CORBA (Common Object Request Broker Architecture).

J2EE technology simplifies enterprise applications by basing them on standardized, modular and re-usable components based on the Enterprise JavaBeansTM (EJBTM) architecture, providing a complete set of services to those components, and handling many details of application behavior automatically. By automating many of the time-consuming and difficult tasks of application development, J2EE technology allows enterprise developers to focus on adding value, that is, enhancing business logic, rather than building infrastructure.

The EJBTM server-side component model simplifies development of middleware components that are transactional, scalable, and portable. Enterprise JavaBeans servers reduce the complexity of developing middleware by providing automatic support for middleware services such as transactions, security, database connectivity, and more.

CORBA is an Object Management Group (OMG) standard that is an open, vendor-independent architecture and infrastructure that computer applications use to work together over networks. Using the standard Internet Inter-ORB Protocol (IIOP), a CORBA-based program from any vendor, on almost any computer, operating system, programming language, and network, can interoperate with a CORBA-based program from the same or another vendor, on almost any other computer, operating system, programming language, and network. To learn more about CORBA, visit http://www.omg.org/gettingstarted/gettingstartedindex.htm.

CORBA technology complements the Java platform by providing a distributed objects framework, services to support that framework, and interoperability with other languages. CORBA technology is an integral part of the Java 2 platform, being used in Enterprise JavaBeans components, Java Remote Method Invocation APIs running over Internet Inter-ORB Protocol ("Java RMI-IIOP"), and Java IDL APIs ("Java IDL").

OMG Interface Definition Language (IDL) is used to describe the interfaces being implemented by the remote objects. IDL is used to define the name of the interface and the names of each of the attributes and methods. Once you create the IDL file, you can use an IDL compiler to generate the client stub and the server skeleton in any language for which the OMG has defined a specification for such language mapping. To learn more about OMG IDL, visit http://www.omg.org/gettingstarted/omg_idl.htm.

Java IDL makes it possible for distributed Java applications to transparently invoke operations on remote network services using the industry standard OMG IDL and IIOP defined by the Object Management Group (http://www.omg.org). Java RMI over IIOP APIs enable the programming of CORBA servers and applications via the javax.rmi API.

Developers who program EJB components follow the Java RMI programming model for their distributed object model, where the required transport common across all application servers is Java RMI-IIOP. In heterogeneous server environments, the standard mapping of the EJB architecture to CORBA enables the following interoperability:

  • A client using an ORB from one vendor can access enterprise beans residing on a server enabled with Enterprise JavaBeans technology ("EJB server") provided by another vendor.
  • Enterprise beans in one EJB server can access enterprise beans in another EJB server.
  • A CORBA client written in a language other than the Java programming language can access any EJB component as long as there is a mapping from OMG IDL to that programming language.

The rest of this document provides an example of a CORBA client application accessing an enterprise bean object. In this document, a CORBA client means a client application written in any language supported by CORBA, including the Java programming language, C++, C, Smalltalk, COBOL, Ada, Lisp, or Python. While the Java code in this example is specific to enterprise beans, the process for developing a CORBA client that accesses a server created using the Java RMI-IIOP APIs is the same.

Links to similar example applications from other vendors who implement J2EE technology can be found in Links to similar examples.

Developing a CORBA Client that Accesses an Enterprise JavaBean Component

This is an example of how to develop a CORBA client application that accesses an EJB component. In this example, the client is written in the C++ programming language, but the client could be written in any language supported by CORBA.

The general process for developing a CORBA client so that it can access an enterprise bean is demonstrated in the following sections:

  1. Write the Enterprise JavaBean component
  2. Generate the CORBA IDL
  3. Create a CORBA client
  4. Deploy the Enterprise JavaBean component
  5. Run the client executable

This document also includes:

  • Creating a Java RMI-IIOP client application
  • Where to go from here
  • Tips for complex interfaces
  • Links to similar examples

In order to make the example simple, we have taken a few shortcuts. For information on building more advanced solutions, see Tips for complex interfaces.

  1. Part I: Write the Enterprise JavaBean component

    The following examples show the code for an enterprise bean that will accept simple String log messages sent to the application server from Java RMI-IIOP and CORBA clients. The enterprise bean prints them on the server along with the current server time.

  2. Create the files Logger.java , LoggerHome.java , LoggerEJB.java , and LogMessage.java in the /Java/src/ejbinterop directory.

    Logger.java

    The file Logger.java is the enterprise bean's remote interface, and as such, it extends EJBObject . A remote interface provides the remote client view of an EJB object and defines the business methods callable by a remote client.

//Code Example 1: Logger.java
package ejbinterop;

import javax.ejb.EJBObject;
import java.rmi.RemoteException;

/**
 * Accepts simple String log messages and prints
 * them on the server.
 */
public interface Logger extends EJBObject
{
    /**
     * Logs the given message on the server with
     * the current server time.
     */
    void logString(String message) throws RemoteException;
}

    LoggerHome.java

    The file LoggerHome.java extends EJBHome . The EJBHome interface must be extended by all EJB component's remote home interfaces. A home interface defines the methods that allow a remote client to create, find, and remove EJB objects, as well as home business methods that are not specific to an EJB instance.

//Code Example 2: LoggerHome.java
package ejbinterop;

import java.rmi.RemoteException;
import javax.ejb.EJBHome;
import javax.ejb.CreateException;

public interface LoggerHome extends EJBHome
{
    Logger create() throws RemoteException, CreateException;
}

    LoggerEJB.java

    The file LoggerEJB.java contains the code for a session bean. A session bean is an enterprise bean that is created by a client and that usually exists only for the duration of a single client-server session. A session bean performs operations such as calculations or accessing a database for the client. In this example, the enterprise bean accepts simple String log messages from the client and prints them on the server.

//LoggerEJB.java
package ejbinterop;

import javax.ejb.*;
import java.util.*;
import java.rmi.*;
import java.io.*;

/**
 * Accepts simple String log messages and prints
 * them on the server.
 */
public class LoggerEJB implements SessionBean {

    public LoggerEJB() {}
    public void ejbCreate() {}
    public void ejbRemove() {}
    public void ejbActivate() {}
    public void ejbPassivate() {}
    public void setSessionContext(SessionContext sc) {}

    /**
     * Logs the given message on the server with
     * the current server time.
     */
    public void logString(String message) {
        LogMessage msg = new LogMessage(message);

        System.out.println(msg);
    }
}

    LogMessage.java

    The file LogMessage.java takes the current date and time, creates a formatted String showing the message, and prints the message to the server.

    //LogMessage.java
package ejbinterop;

import java.io.Serializable;
import java.util.Date;
import java.text.*;

/**
 * Simple message class that handles pretty
 * printing of log messages.
 */
public class LogMessage implements Serializable
{
    private String message;
    private long datetime;

    /**
     * Constructor taking the message. This will
     * take the current date and time.
     */
    public LogMessage(String msg) {
        message = msg;
        datetime = (new Date()).getTime();
    }

    /**
     * Creates a formatted String showing the message.
     */
    public String toString() {
        StringBuffer sbuf = new StringBuffer();
        DateFormat dformat
            = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
        DateFormat.LONG);
        FieldPosition fpos = new
            FieldPosition(DateFormat.DATE_FIELD);
        dformat.format(new Date(datetime), sbuf, fpos);
        sbuf.append(": ");
        sbuf.append(message);
        return sbuf.toString();
    }
}

  3. Compile the files written in this section, for example,
    javac -classpath $J2EE_HOME/lib/j2ee.jar:.. *.java

    These commands create class files for all of the .java files in the current directory. This command and others in this paper assume that the J2EE_HOME environment variable has been set correctly. Using $J2EE_HOME is a convention of the Unix® operating environment. Substitute %J2EE_HOME% when working in the Microsoft Windows operating environment.

    Part II: Generate the CORBA IDL

    This sections discusses generating the Interface Definition Language (IDL) files from the Java class files generated in the previous section. In this example, we will use the rmic compiler to map the Java code to IDL. IDL provides a purely declarative, programming language-independent way of specifying an object's API.

  4. Run the rmic compiler against the Java class files generated in the previous step as follows:
    rmic -idl -noValueMethods -classpath
  $J2EE_HOME/lib/j2ee.jar:<path_to_ejbinterop_dir>
  -d <path_to_where_idl_files_should_be_generated>
  ejbinterop.Logger ejbinterop.LoggerHome

    In the preceding example, we are including the JAR file containing definitions for the javax.ejb package as well as the directory to our ejbinterop files. If you're using the JavaTM 2 Platform, Enterprise Edition (J2EETM), version 1.3 Reference Implementation (RI), the JAR files are located in $J2EE_HOME/lib/j2ee.jar .

    In the command line for rmic above, we recommend a shortcut -- using the noValueMethods option. This option tells rmic to skip any methods with parameter or return types that would be mapped to CORBA value types. The advantage is that it will prevent us from generating a lot of unnecessary IDL that we might have to implement in the C++ client. The disadvantage is that we can only use primitive data types, arrays, and Strings as parameters or return values, and not our own Java class types. Read more about this in Tips for complex interfaces

    Running the rmic compiler on the Java class files generates the following files to the directory indicated with the -d option in the rmic statement above:

    • java/lang/Ex.idl
    • java/lang/Exception.idl
    • java/lang/Object.idl
    • java/lang/Throwable.idl
    • java/lang/ThrowableEx.idl
    • javax/ejb/CreateEx.idl
    • javax/ejb/CreateException.idl
    • javax/ejb/EJBHome.idl
    • javax/ejb/EJBMetaData.idl
    • javax/ejb/EJBObject.idl
    • javax/ejb/Handle.idl
    • javax/ejb/HomeHandle.idl
    • javax/ejb/RemoveEx.idl
    • javax/ejb/RemoveException.idl
    • ejbinterop/Logger.idl
    • ejbinterop/LoggerHome.idl

    NOTE: A number of these generated files contain API that can only be used within a Java programming environment. For example, the EJBMetaData implementation is currently specific to each application server, and thus it will be difficult to develop equivalents that will continue to work over time on platforms other than the Java platform. One option is to remove these from the IDL, but if you do, you'll have to remove them from the IDL every time you change the Java interface and regenerate the IDL files from the rmic compiler.

    NOTE: Since CORBA exceptions don't support inheritance, the Java language to IDL mapping creates an Ex class that contains a CORBA value type representing the actual Java exception. In this basic example, we're not going to worry much about exception support. More information about exceptions can be found at Exceptions.

  5. Compile the IDL files with your C++ vendor's "IDL to C++" compiler to generate the C++ code corresponding to the IDL. The steps for this procedure vary by vendor, so consult your product documentation for the specific steps for your vendor.

    Part III: Create a CORBA client

    The client application can be written in any language supported by CORBA. The following example provides the code for a simple C++ client that, given an Object Request Broker (ORB) and a corbaname URL for a LoggerHome object, logs a simple String message on the server. You'll have to adjust the include statements and modify the code for registering the value factories based on your C++ ORB vendor's libraries. This example was written for ORBacus for C++ 4.0.5 and some of the C++ code in this example is specific to that product.

    A corbaname URL is a human-readable URL format that enables you to access CORBA objects. It is used to resolve a stringified name from a specific naming context. This is part of the CORBA Interoperable Naming Service (INS). INS is an extension to CORBA Object Services (COS) Naming Service, which was delivered in previous releases of the J2EE platform. To read more about INS, visit Interoperable Naming Service.

    In this example, the client code does the following:

    • Creates an Object Request Broker (ORB). The ORB connects objects requesting services to the objects providing them.
    • Registers value factories.
    • Looks up the LoggerHome object in the naming context pointed to by the corbaname URL.
    • Performs a safe downcast from the object returned to a LoggerHome object.
    • Creates a LoggerEJB object reference.
    • Logs our message.
    • Tells the application server we won't use this EJB reference again.
  6. Create the client using C++ code similar to the following. The exact code may vary with your C++ implementation. This code was written for ORBacus for C++ 4.0.5 and some of the C++ code in this example may be specific to that product.
    //Code Example: Client.cpp
#include <fstream.h>

// C++ ORB Vendor specific include files
// These are from C++ ORBacus 4.0.5

#include <OB/CORBA.h>
#include <OB/OBORB.h>

// Include files generated from our IDL
#include <java/lang/Exception.h>
#include <java/lang/Throwable.h>
#include <javax/ejb/CreateException.h>
#include <javax/ejb/RemoveException.h>
#include <ejbinterop/Logger.h>
#include <ejbinterop/LoggerHome.h>

/**
 * Given an ORB and a corbaname URL for a LoggerHome
 * object, logs a simple string message on the server.
 */
void
run(CORBA::ORB_ptr orb, const char* logger_home_url)
{
  cout << "Looking for: " << logger_home_url << endl;

  // Look up the LoggerHome object in the naming context
  // pointed to by the corbaname URL
  CORBA::Object_var home_obj
    = orb->string_to_object(logger_home_url);

  // Perform a safe downcast
  ejbinterop::LoggerHome_var home
    = ejbinterop::LoggerHome::_narrow(home_obj.in());

  assert(!CORBA::is_nil(home));

  // Create a Logger EJB reference
  ejbinterop::Logger_var logger = home->create();

  CORBA::WStringValue_var msg =
    new CORBA::WStringValue((const CORBA::WChar*)L"Message
      from a C++ client");

  cout << "Logging..." << endl;

  // Log our message
  logger->logString(msg);

  // Tell the application server we won't use this
  // EJB reference any more
  logger->remove();

  cout << "Done" << endl;
}

/**
 * Simple main method that checks arguments, creates an
 * ORB, and handles exceptions.
 */
int
main(int argc, char* argv[])
{
  int exit_code = 0;
  CORBA::ORB_var orb;

  try {

  // Check the arguments
  if (argc != 2) {
    cerr << "Usage: Client <corbaname URL of LoggerHome>" << endl;
    return 1;
  }

  // Create an ORB
  orb = CORBA::ORB_init(argc, argv);

  // Register value factories

  // NOTE: This is overkill for the example since we'll never
  // get these exceptions.  Also, the _OB_id method is a
  // proprietary feature of ORBacus C++ generated code.
  CORBA::ValueFactory factory = new java::lang::Throwable_init;
  orb -> register_value_factory(java::lang::Throwable::_OB_id(),
    factory);
  factory -> _remove_ref();

  factory = new java::lang::Exception_init;
  orb -> register_value_factory(java::lang::Exception::_OB_id(),
    factory);
  factory -> _remove_ref();

  factory = new javax::ejb::CreateException_init;
  orb ->                 register_value_factory(javax::ejb::CreateException::_OB_id(),
      factory);
  factory -> _remove_ref();

  factory = new javax::ejb::RemoveException_init;
  orb ->
    register_value_factory(javax::ejb::RemoveException::_OB_id(),
      factory);
  factory -> _remove_ref();

  // Perform the work
  run(orb, argv[1]);

} catch(const CORBA::Exception& ex) {
  // Handle any CORBA related exceptions
  cerr << ex._to_string() << endl;
  exit_code = 1;
}

  // Release any ORB resources
  if (!CORBA::is_nil(orb)) {
    try {
      orb -> destroy();
    } catch(const CORBA::Exception& ex) {
      cerr << ex._to_string() << endl;
      exit_code = 1;
    }
  }

  return exit_code;
}
  7. Use your C++ compiler to compile all of the C++ files, including the Client.cpp file, to create a Client executable. Such tools vary widely across platforms, so consult your product documentation for instructions.

    Part IV: Deploy the Enterprise JavaBean component

  8. Deploy the enterprise bean using your favorite application server. The following steps describe how to deploy the LoggerEJB component using the J2EE 1.3 Reference Implementation (RI).
    1. Start the RI application from a terminal window or command prompt by typing:
         $J2EE_HOME/bin/j2ee -verbose
    2. When the J2EE 1.3 RI indicates "J2EE server startup complete", run the deployment tool from another terminal window or command prompt by typing:
         $J2EE_HOME/bin/deploytool
    3. From the deployment tool, select File -> New -> Application.
    4. In the Application File Name field, enter Logger.ear to indicate in which file to create the application.
    5. In the Application Display Name field, enter Logger
    6. Select OK to save the settings and close this dialog window.
    7. From the deployment tool, select File -> New -> Enterprise Bean.
    8. Select Next if you get the Introduction screen. If not, continue.
    9. In the New EnterpriseBean Wizard, select Edit in the Contents box.
    10. Expand the Available Files list, and add the following four .class files from our ejbinterop package: Logger.class , LoggerHome.class , LoggerEJB.class , LogMessage.class . Select OK, then Next.
    11. Select Stateless Session Bean Type.
    12. Select ejbinterop.LoggerEJB for the Enterprise Bean Class .
    13. Select ejbinterop.LoggerHome for the Remote Home Interface .
    14. Select ejbinterop.Logger for the Remote Interface .
    15. Select the Next button until you get to the Security Settings page.
    16. Select the Deployment Settings button.
    17. Select Support Client Choice .
    18. Select OK to save the settings and close this dialog window.
    19. Select Finish.
    20. From the deployment tool, select, Tools -> Deploy.
    21. If running the Java RMI-IIOP client only, select Return Client JAR.
    22. Select Next.
    23. Enter ejbinterop/logger in the JNDI Name for our LoggerEJB field.
    24. Select Finish.
    25. Select File -> Exit to exit the deploytool.

    Now, the Logger application with our LoggerEJB components are deployed and ready to receive messages.

    Part V: Run the client executable

  9. Run the client executable. One way you can run the client executable is to enter the following URL in a terminal window from the directory containing the executable client file:
    Client corbaname:iiop:1.2@localhost:1050#ejbinterop/logger

    In this URL,

    • Client is the name of the application to run.
    • corbaname specifies that we will resolve a stringified name from a specific naming context.
    • iiop:1.2 tells the ORB to use the IIOP protocol and GIOP 1.2.
    • The host machine on which to find the reference is localhost, the local machine. To expand this example to run on two machines, enter the IP address or host name of the machine on which the server is running instead of localhost.
    • 1050 is the port on which the naming service is listening for requests. By default in the J2EE v.1.3 RI, the default port the naming service listens on is port 1050. The portion of the reference up to this point at the hash mark (Client corbaname:iiop:1.2@localhost:1050 ) is the URL that returns the root naming context.
    • ejbinterop/logger is the name to resolve in the naming context.

    If you are using the J2EE 1.3 Reference Implementation, you should see a message similar to the following printed on the application server:

Sep 21, 2001 3:33:07 PM PDT: Message from a C++ client ejbinterop/
logger is the name to be resolved from the Naming Service.

    Part VI: Stop the J2EE Server

  10. Stop the J2EE server. To stop the server, enter this command in a terminal window or command prompt.
    $J2EE_HOME/bin/j2ee -stop

    Procedures for stopping running processes vary among operating systems, so if you are running a different server, consult your system documentation for details.

Creating a Java RMI-IIOP client application

Using the same example, we can easily develop a Java RMI-IIOP client that connects to an enterprise bean. The differences from the example using a C++ client are:

  • In your client CLASSPATH, you must include the location of the client JAR file created by the J2EE application server running the desired enterprise bean. That JAR file contains the necessary client stubs.
  • When deploying the application using the J2EE 1.3 RI, check the box Return Client Jar in the Deploytool on the first page of the Deploy screen.

The following code is the Java RMI-IIOP version of a client for our LoggerEJB component. Follow the same steps as those presented for the C++ client example. When running the client, use the same URL as in the C++ example.

//Code Example: LogClient.java
package ejbinterop;

import java.rmi.RemoteException;
import javax.rmi.*;
import java.io.*;
import javax.naming.*;
import javax.ejb.*;

/**
 * Simple Java RMI-IIOP client that uses an EJB component.
 */
public class LogClient
{
    /**
     * Given a corbaname URL for a LoggerHome,
     * log a simple String message on the server.
     */
    public static void run(String loggerHomeURL)
        throws CreateException, RemoveException,
               RemoteException, NamingException
    {
        System.out.println("Looking for: " + loggerHomeURL);

        // Create an InitialContext. This will use the
        // CosNaming provider we will specify at runtime.
        InitialContext ic = new InitialContext();

        // Lookup the LoggerHome in the naming context
        // pointed to by the corbaname URL
        Object homeObj = ic.lookup(loggerHomeURL);

        // Perform a safe downcast
        LoggerHome home
            = (LoggerHome)PortableRemoteObject.narrow(homeObj,
        LoggerHome.class);

        // Create a Logger EJB reference
        Logger logger = home.create();

        System.out.println("Logging...");

        // Log our message
        logger.logString("Message from a Java RMI-IIOP client");

        // Tell the application server we won't use this
        // EJB reference anymore
        logger.remove();

        System.out.println("Done");
    }

    /**
     * Simple main method to check arguments and handle
     * exceptions.
     */
    public static void main(String args[])
    {
        try {

            if (args.length != 1) {
                System.out.println("Args: corbaname URL of LoggerHome");
                System.exit(1);
            }

            LogClient.run(args[0]);

        } catch (Throwable t) {
            t.printStackTrace();
            System.exit(1);
        }
    }
}

Running the application with the Java RMI-IIOP client

When running the example application with a Java RMI-IIOP client instead of a C++ client, follow these steps:

  1. Compile the .java files in the ejbinterop / directory with the following command:
    javac -classpath $J2EE_HOME/lib/j2ee.jar:<ejbinterop_directory> *.java
  2. Deploy the Enterprise JavaBean component as described in Deploy the Enterprise JavaBean component. Remember to select Return Client JAR on the Tools -> Deploy page when running a Java RMI-IIOP client application. The commands in the Deployment topic instruct you to start the J2EE RI or other application server.
  3. Run the client application using a command similar to the following:
    java -classpath $J2EE_HOME/lib/j2ee.jar:
<path to LoggerClient.jar>/LoggerClient.jar:
<directory_above_ejbinterop>:<ejbinterop_directory>
ejbinterop.LogClient
corbaname:iiop:1.2@localhost:1050#ejbinterop/logger

    In the window in which the J2EE RI is running, you will see this:

    Jan 31, 2002 2:27:47 PM PST: Message from a Java RMI-IIOP client

    In the window from where the client is run, you will see this:

    Looking for: corbaname:iiop:1.2@localhost:1050#ejbinterop/logger
Logging...
Done
  4. Stop the J2EE server.

Beyond the Basic Application

This section contains the following information:

  • Where to go from here
  • Tips for complex interfaces
  • Links to similar examples

Where to go from here

To enhance the application you could:

  • Develop the example to use valuetypes.

  • To do this, remove the -noValueMethods switch when you run rmic . Rerun your IDL to C++ language mapping compiler to verify that it supports the valuetypes that have been generated.

  • Add another method to Logger that actually takes a LogMessage .

Tips for complex interfaces

The interfaces are key to the communication between clients and servers speaking different languages. To increase the probability of success in this area, consider the following suggestions:

  • Avoid using complex Java classes, such as collections in java.util , for method parameters or return types.

  • After these types are mapped to IDL, you will be forced to implement them in your client programming language. In addition, since Java Object Serialization and RMI-IIOP APIs allow the wire format and internal representation of classes to evolve over time, your CORBA client applications may be incompatible across JavaTM 2 Platform, Standard Edition (J2SETM) implementations or versions.

  • Start with IDL.

  • You may want complex data structures in your return types or method parameters. In this case, try starting with IDL. Define data structures and even exceptions in IDL, and then use them in your EJB interfaces. This will prevent artifacts of the reverse mapping from creeping into your CORBA interfaces.

    For instance, try defining the LogMessage class in IDL initially, and then using the resulting class of a Java language to IDL compilation as a method parameter in the Logger EJB component.

  • Avoid overloading in EJB interfaces.

  • CORBA IDL does not support method overloading, and the Java language to IDL mapping specification handles this by creating IDL method definitions that combine the method name with all its IDL parameter types. This leads to very unfriendly method names for developers using languages other than the Java programming language.

  • Consider using bridges.

  • If the available options are still too limited or impact the code you wish to write, consider using a server-side bridge. You can read more about constructing such bridges from the sites listed in the links section.

Links to similar examples

Several vendors implementing J2EE technology have excellent examples and tips for integrating CORBA and Enterprise JavaBeans technology:

  • BEA - EJB-to-CORBA/Java Simpapp Sample Application at http://download.oracle.com/docs/cd/E13211_01/wle/wle50/interop/ejbcorba.htm
  • Borland - Sevens steps to build a VisiBroker C++ CORBA Client for an EJB Server at http://www.borland.com/devsupport/appserver/faq/ejbcpp/ejb_cpp.html
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Deployment: Intranet

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

< Contents

Intranet With OBJECT/EMBED Tag

This section includes the following topics:

  • Introduction
  • Deploying Java Plug-in with Internet Explorer
  • Deploying Java Plug-in with Mozilla Browsers

Introduction

The intranet is a more controlled environment than the internet, and you can decide whether you want to deploy your applets via the APPLET, OBJECT, or EMBED tags. This chapter deals with deployment using the OBJECT or EMBED tags.

Java Plug-in can be deployed in an intranet environment so that users can download and install it without leaving the firewall. Deployment details for Internet Explorer and supported Mozilla browsers are described below.

Note

You need to understand the Java Plug-in tagging structure to understand the discussion below. The tagging structure is explained in Using OBJECT, EMBED and APPLET Tags in Java Plug-in.)

Deploying Java Plug-in with Internet Explorer (IE)

To deploy Java Plug-in in intranet environments with IE, you need to download and store the Java Plug-in binary file on a web server. Then you need to modify the codebase attribute inside the <OBJECT> tag in the HTML file to point to the binary. For example, if you want to use the Java Plug-in binary file in http://my_company.com/plugin/, then you should specify the codebase attribute as

"http://my_company.com/plugin/jre-6-rc-windows-i586.exe#Version=6,0,0,99"

(For Internet deployment the above might use a .cab file rather than .exe. The .cab file points to an .exe and provides a download progress bar.)

Note the version number in the above URL. For Java Plug-in 6, the version number is 6,0,0,99. This version number changes for each release, and you must change the version number inside the <OBJECT> tag if you want to specify the newest release of Java Plug-in.

The filejre-6-rc-windows-i586.exe#Version=6,0,0,99 is the same binary that can be download directly from the Java Software web site. It is digitally signed with a VeriSign digital signature signed by Sun Microsystems, Inc. If you are using the Java Plug-in HTML Converter, you can simply change the conversion template file to specify the latest Plug-in version (the CabFileLocation variable) before the conversion. For information about modifying the conversion template, consult the README file in the Java Plug-in HTML Converter. Note that CabFileLocation can be the location of the .cab file or the .exe.

Once you have implemented these changes, when a machine that does not have Java Plug-in installed browses an HTML page with IE, IE will look into your predefined location (http://my_company.com/plugin in the example) and download Java Plug-in. Notice that there is no need to download Java Plug-in over the firewall if the web server is inside the intranet.

Note: Recommendations

The following is recommeded for long-term reliability:

  • For the codebase attribute in the OBJECT tag, it is recommended that you use the .exe version, rather than the .cab version, on java.sun.com. That .cab version on java.sun.com may point to an updated version that you do not want to use for your deployment.
  • It is also recommend that you create your own download site for the versions you need so that you do not rely on java.sun.com. Downloads on java.sun.com frequently change.

Deploying Java Plug-in with Mozilla Browsers

For supported Mozilla browsers you must use the APPLET tag.

To deploy Java Plug-in in intranet environments with Mozilla, you need to download and store the Java Plug-in binary file on one of your web servers. Then you need to set up a Java Plug-in Download page and modify the pluginspage attribute in the EMBED tag to refer to this page. For example, if you have set up the Java Plug-in Download page at "http://my_company.com/plugin/" and the page is called plugin-install.html, you can specify the pluginspage as "http://my_company.com/plugin/plugin-install.html". The Download page should have options to download different versions of Java Plug-in, such as for Windows and Solaris.

When a machine that does not have Java Plug-in installed acceses a web page, a missing-plugin icon is displayed on the HTML page. When the user clicks on this icon, Mozilla browser directs the user to your predefined Java Plug-in Download Page (http://my_company.com/plugin/plugin-install.html in this example). Notice that there is no need to download Java Plug-in over the firewall if the web server is inside the intranet.

Deploying Java Plug-in with Unix/Linux with Mozilla

There are two ways that Java Plug-in might be installed in the Intranet environment with Unix or Linux:

  • It might be installed on a per-user-account basis on individual machines, as it is installed in the Window environment.
  • It might be installed by a system administrator on a shared NSF drive for shared installation.

In either case, for supported Mozilla browsers the environmental variable NPX_PLUGIN_PATH must be set to point to the Java Plug-in. When Java Plug-in is installed on the local machine, then the user needs to set this variable to point to the Java Plug-in in the JRE on the local machine. For a shared installation, the system administrator needs to determine the shared location of the Java Plug-in in the shared JRE on the NSF drive and set the user profile for every machine to point to this via NPX_PLUGIN_PATH.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Contents | Previous | Next Java Management Extensions (JMX) Technology Tutorial

Chapter 1

Getting Started

This chapter explains what you need to do to get started with the Java Management Extensions (JMX) examples. It provides instructions that apply to all the examples described in the subsequent chapters.

Platform Information

All variable assignments and commands in the examples in this tutorial were defined using UNIX Korn shell syntax. If you are running a shell other than the Korn shell on a UNIX or Linux platform, you must adapt these commands to your preferred shell environment.

If you are running a Microsoft Windows operating environment, in the majority of cases, adapting commands will simply involve replacing forward slashes (/) with backward slashes (\) and replacing colons (:) with semi-colons (;) in the paths. A specific Microsoft Windows command is given only when it differs significantly from the UNIX/Linux command provided.

Examples Directory

The examples that form the basis of this tutorial are all accessible from the JMX page in the Java Platform, Standard Edition (Java SE) documentation bundle, found in the following location:

http://java.sun.com/javase/7/docs/technotes/guides/jmx/examples.html

The code excerpts quoted in this tutorial are taken from these example programs. However, some code excerpts might be rearranged and comments might be changed. Program listings in the tutorial usually simplify comments and omit output statements, for space considerations. Some classes or sections of code that deserve special attention have been highlighted using bold text for the purposes of this tutorial.

Working Directory

To preserve untouched copies of the original example files, create a new directory in which to compile and run the examples.

  2. Create a new working directory.

    This working directory is referred to as work_dir throughout this tutorial.

  3. Download the examples ZIP bundle from the following URL:

    http://java.sun.com/javase/7/docs/technotes/guides/jmx/examples/jmx_examples.zip

  4. Unzip all the examples into work_dir.

All the examples will now be contained in work_dir/jmx_examples.

Contents | Previous | Next

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Image I/O API Guide: 1 - Introduction

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

CHAPTER 1

Introduction

1.1 The Java Image I/O API

The Java Image I/O API provides a pluggable architecture for working with images stored in files and accessed across the network. It offers substantially more flexibility and power than the previously available APIs for loading and saving images.

The API provides a framework for the addition of format-specific plug-ins. Plug-ins for several common formats will be included with the standard Java SDK; other plug-ins will be available from Sun and from third parties. A voting process has been established where Java developers may indicate their interest in particular formats. See:

http://bugs.sun.com/view_bug.do?bug_id=4339476

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Image I/O API Guide: 1 - Introduction

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

1.2 About This Document

This document is a brief guide to the API and its goals, including some simple programming examples. However, this document is not intended to be a complete guide to the API. The definitive guide to the specification is the automatically-generated ("javadoc") API documentation. In all cases, the automatically-generated documentation takes precedence over the descriptive materal in this document.
CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Image I/O API Guide: 1 - Introduction

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

1.3 Platforms

The API will be a standard part of the "Merlin" release of the Java Platform Standard Edition (J2SE version 1.4). Sun will provide an implementation of the Java SE platform for the Solaris operating environment, Linux, and Microsoft Windows platforms. The availibility of a particular Java SE release on other platforms is determined by the platform vendor.
CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Image I/O API Guide: 1 - Introduction

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

1.4 Target Audience

The API is intended to be used in a variety of contexts. Client-side applications may use it to load image data from local disk files or across the network. Server-side applications may use it to generate images dynamically in response to client requests, for example by using the Servlet API. The Image I/O API may be used in conjunction with other APIs such as Java Advanced Imaging, Java3D, and the Java Media Framework in order to build sophisticated multimedia applications.
CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Image I/O API Guide: 1 - Introduction

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

1.5 Acknowledgements

The authors would like to thank the following members of the expert group and others who provided valuable assistance with the API design:

Bharti Agrawal, Troy Chinen, Shoji Hara, Fuji FilmSoft

David Clunie, Quintiles Intelligent Imaging

Bob Deen, NASA Jet Propulsion Laboratories

Thomas DeWeese, Eastman Kodak Corp.

Steve Levoe, NASA Jet Propulsion Laboratories

Todd Rowell, Oracle

Jeannette Hung and Ihtisham Kabir provided excellent front-line management and made it possible for the API and its implementation to be devloped with a minimum of red tape. Aastha Bhardwaj, Brian Burkhalter, Jerry Evans, Ivan Wong, and John Zimmerman provided invaluable technical assistance.

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.jdi.InvalidCodeIndexException (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.InvalidCodeIndexException

No usage of com.sun.jdi.InvalidCodeIndexException
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.jdi.InvalidLineNumberException (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.InvalidLineNumberException

No usage of com.sun.jdi.InvalidLineNumberException
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.jdi.request.InvalidRequestStateException (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.request.InvalidRequestStateException

No usage of com.sun.jdi.request.InvalidRequestStateException
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.jdi.InvalidStackFrameException (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.InvalidStackFrameException

No usage of com.sun.jdi.InvalidStackFrameException
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.jdi.InvalidTypeException (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.InvalidTypeException

  • Packages that use InvalidTypeException
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of InvalidTypeException in com.sun.jdi

      Methods in com.sun.jdi that throw InvalidTypeException
      Modifier and Type Method and Description
      void ThreadReference.forceEarlyReturn(Value value)
      Force a method to return before it reaches a return statement.
      Value ClassType.invokeMethod(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Invokes the specified static Method in the target VM.
      Value ObjectReference.invokeMethod(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Invokes the specified Method on this object in the target VM.
      ObjectReference ClassType.newInstance(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Constructs a new instance of this type, using the given constructor Method in the target VM.
      void ClassType.setValue(Field field, Value value)
      Assigns a value to a static field.
      void ObjectReference.setValue(Field field, Value value)
      Sets the value of a given instance or static field in this object.
      void ArrayReference.setValue(int index, Value value)
      Replaces an array component with another value.
      void StackFrame.setValue(LocalVariable variable, Value value)
      Sets the Value of a LocalVariable in this frame.
      void ArrayReference.setValues(int index, List<? extends Value> values, int srcIndex, int length)
      Replaces a range of array components with other values.
      void ArrayReference.setValues(List<? extends Value> values)
      Replaces all array components with other values.
      void ThreadReference.stop(ObjectReference throwable)
      Stops this thread with an asynchronous exception.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


The Invocation API

Chapter 5

The Invocation API allows software vendors to load the Java VM into an arbitrary native application. Vendors can deliver Java-enabled applications without having to link with the Java VM source code.

This chapter begins with an overview of the Invocation API. This is followed by reference pages for all Invocation API functions.

Overview

The following code example illustrates how to use functions in the Invocation API. In this example, the C++ code creates a Java VM and invokes a static method, called Main.test. For clarity, we omit error checking.

    #include <jni.h>       /* where everything is defined */
    ...
    JavaVM *jvm;       /* denotes a Java VM */
    JNIEnv *env;       /* pointer to native method interface */
    JavaVMInitArgs vm_args; /* JDK/JRE 6 VM initialization arguments */
    JavaVMOption* options = new JavaVMOption[1];
    options[0].optionString = "-Djava.class.path=/usr/lib/java";
    vm_args.version = JNI_VERSION_1_6;
    vm_args.nOptions = 1;
    vm_args.options = options;
    vm_args.ignoreUnrecognized = false;
    /* load and initialize a Java VM, return a JNI interface
     * pointer in env */
    JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
    delete options;
    /* invoke the Main.test method using the JNI */
    jclass cls = env->FindClass("Main");
    jmethodID mid = env->GetStaticMethodID(cls, "test", "(I)V");
    env->CallStaticVoidMethod(cls, mid, 100);
    /* We are done. */
    jvm->DestroyJavaVM();

This example uses three functions in the API. The Invocation API allows a native application to use the JNI interface pointer to access VM features. The design is similar to Netscape’s JRI Embedding Interface.

Creating the VM

The JNI_CreateJavaVM() function loads and initializes a Java VM and returns a pointer to the JNI interface pointer. The thread that called JNI_CreateJavaVM() is considered to be the main thread.

Attaching to the VM

The JNI interface pointer (JNIEnv) is valid only in the current thread. Should another thread need to access the Java VM, it must first call AttachCurrentThread() to attach itself to the VM and obtain a JNI interface pointer. Once attached to the VM, a native thread works just like an ordinary Java thread running inside a native method. The native thread remains attached to the VM until it calls DetachCurrentThread() to detach itself.

The attached thread should have enough stack space to perform a reasonable amount of work. The allocation of stack space per thread is operating system-specific. For example, using pthreads, the stack size can be specified in the pthread_attr_t argument to pthread_create.

Detaching from the VM

A native thread attached to the VM must call DetachCurrentThread() to detach itself before exiting. A thread cannot detach itself if there are Java methods on the call stack.

Unloading the VM

The JNI_DestroyJavaVM() function unloads a Java VM. As of JDK/JRE 1.1, only the main thread could unload the VM, by calling DestroyJavaVM. As of JDK/JRE 1.2, the restriction was removed, and any thread may call DestroyJavaVM to unload the VM.

The VM waits until the current thread is the only non-daemon user thread before it actually unloads. User threads include both Java threads and attached native threads. This restriction exists because a Java thread or attached native thread may be holding system resources, such as locks, windows, and so on. The VM cannot automatically free these resources. By restricting the current thread to be the only running thread when the VM is unloaded, the burden of releasing system resources held by arbitrary threads is on the programmer.

Library and Version Management

As of JDK/JRE 1.1, once a native library is loaded, it is visible from all class loaders. Therefore two classes in different class loaders may link with the same native method. This leads to two problems:
  • A class may mistakenly link with native libraries loaded by a class with the same name in a different class loader.
  • Native methods can easily mix classes from different class loaders. This breaks the name space separation offered by class loaders, and leads to type safety problems.

As of JDK/JRE 1.2, each class loader manages its own set of native libraries. The same JNI native library cannot be loaded into more than one class loader. Doing so causes UnsatisfiedLinkError to be thrown. For example, System.loadLibrary throws an UnsatisfiedLinkError when used to load a native library into two class loaders. The benefits of the new approach are:

  • Name space separation based on class loaders is preserved in native libraries. A native library cannot easily mix classes from different class loaders.
  • In addition, native libraries can be unloaded when their corresponding class loaders are garbage collected.

To facilitate version control and resource management, JNI libraries as of JDK/JRE 1.2 optionally export the following two functions:

JNI_OnLoad

jint JNI_OnLoad(JavaVM *vm, void *reserved);

The VM calls JNI_OnLoad when the native library is loaded (for example, through System.loadLibrary). JNI_OnLoad must return the JNI version needed by the native library.

In order to use any of the new JNI functions, a native library must export a JNI_OnLoad function that returns JNI_VERSION_1_2. If the native library does not export a JNI_OnLoad function, the VM assumes that the library only requires JNI version JNI_VERSION_1_1. If the VM does not recognize the version number returned by JNI_OnLoad, the native library cannot be loaded.

LINKAGE:

Exported from native libraries that contain native method implementation.

SINCE:

JDK/JRE 1.4

In order to use the JNI functions introduced in J2SE release 1.2, in addition to those that were available in JDK/JRE 1.1, a native library must export a JNI_OnLoad function that returns JNI_VERSION_1_2.

In order to use the JNI functions introduced in J2SE release 1.4, in addition to those that were available in release 1.2, a native library must export a JNI_OnLoad function that returns JNI_VERSION_1_4.

If the native library does not export a JNI_OnLoad function, the VM assumes that the library only requires JNI version JNI_VERSION_1_1. If the VM does not recognize the version number returned by JNI_OnLoad, the native library cannot be loaded.

JNI_OnUnload

void JNI_OnUnload(JavaVM *vm, void *reserved);

The VM calls JNI_OnUnload when the class loader containing the native library is garbage collected. This function can be used to perform cleanup operations. Because this function is called in an unknown context (such as from a finalizer), the programmer should be conservative on using Java VM services, and refrain from arbitrary Java call-backs.

Note that JNI_OnLoad and JNI_OnUnload are two functions optionally supplied by JNI libraries, not exported from the VM.

LINKAGE:

Exported from native libraries that contain native method implementation.

Invocation API Functions

The JavaVM type is a pointer to the Invocation API function table. The following code example shows this function table.

typedef const struct JNIInvokeInterface *JavaVM;

const struct JNIInvokeInterface ... = {
    NULL,
    NULL,
    NULL,

    DestroyJavaVM,
    AttachCurrentThread,
    DetachCurrentThread,

    GetEnv,

    AttachCurrentThreadAsDaemon
};

Note that three Invocation API functions, JNI_GetDefaultJavaVMInitArgs(), JNI_GetCreatedJavaVMs(), and JNI_CreateJavaVM(), are not part of the JavaVM function table. These functions can be used without a preexisting JavaVM structure.

JNI_GetDefaultJavaVMInitArgs

jint JNI_GetDefaultJavaVMInitArgs(void *vm_args);

Returns a default configuration for the Java VM. Before calling this function, native code must set the vm_args->version field to the JNI version it expects the VM to support. After this function returns, vm_args->version will be set to the actual JNI version the VM supports.

LINKAGE:

Exported from the native library that implements the Java virtual machine.

PARAMETERS:

vm_args: a pointer to a JavaVMInitArgs structure in to which the default arguments are filled.

RETURNS:

Returns JNI_OK if the requested version is supported; returns a JNI error code (a negative number) if the requested version is not supported.

JNI_GetCreatedJavaVMs

jint JNI_GetCreatedJavaVMs(JavaVM **vmBuf, jsize bufLen, jsize *nVMs);

Returns all Java VMs that have been created. Pointers to VMs are written in the buffer vmBuf in the order they are created. At most bufLen number of entries will be written. The total number of created VMs is returned in *nVMs.

As of JDK/JRE 1.2, creation of multiple VMs in a single process is not supported.

LINKAGE:

Exported from the native library that implements the Java virtual machine.

PARAMETERS:

vmBuf: pointer to the buffer where the VM structures will be placed.

bufLen: the length of the buffer.

nVMs: a pointer to an integer.

RETURNS:

Returns JNI_OK on success; returns a suitable JNI error code (a negative number) on failure.

JNI_CreateJavaVM

jint JNI_CreateJavaVM(JavaVM **p_vm, void **p_env, void *vm_args);

Loads and initializes a Java VM. The current thread becomes the main thread. Sets the env argument to the JNI interface pointer of the main thread.

As of JDK/JRE 1.2 , creation of multiple VMs in a single process is not supported.

The second argument to JNI_CreateJavaVM is always a pointer to JNIEnv *, while the third argument is a pointer to a JavaVMInitArgs structure which uses option strings to encode arbitrary VM start up options:

typedef struct JavaVMInitArgs {
    jint version;

    jint nOptions;
    JavaVMOption *options;
    jboolean ignoreUnrecognized;
} JavaVMInitArgs;

The version field must be set to at least JNI_VERSION_1_2. The options field is an array of the following type:

typedef struct JavaVMOption {
    char *optionString;  /* the option as a string in the default platform encoding */
    void *extraInfo;
} JavaVMOption;

The size of the array is denoted by the nOptions field in JavaVMInitArgs. If ignoreUnrecognized is JNI_TRUE, JNI_CreateJavaVM ignore all unrecognized option strings that begin with "-X" or "_". If ignoreUnrecognized is JNI_FALSE, JNI_CreateJavaVM returns JNI_ERR as soon as it encounters any unrecognized option strings. All Java VMs must recognize the following set of standard options:

optionString | meaning
-D<name>=<value> | Set a system property
-verbose[:class|gc|jni] | Enable verbose output. The options can be followed by a comma-separated list of names indicating what kind of messages will be printed by the VM. For example, "-verbose:gc,class" instructs the VM to print GC and class loading related messages. Standard names include: gc, class, and jni. All nonstandard (VM-specific) names must begin with "X".
vfprintf | extraInfo is a pointer to the vfprintf hook.
exit | extraInfo is a pointer to the exit hook.
abort | extraInfo is a pointer to the abort hook.

In addition, each VM implementation may support its own set of non-standard option strings. Non-standard option names must begin with "-X" or an underscore ("_"). For example, the JDK/JRE supports -Xms and -Xmx options to allow programmers specify the initial and maximum heap size. Options that begin with "-X" are accessible from the "java" command line.

Here is the example code that creates a Java VM in the JDK/JRE:

JavaVMInitArgs vm_args;
JavaVMOption options[4];

options[0].optionString = "-Djava.compiler=NONE";           /* disable JIT */
options[1].optionString = "-Djava.class.path=c:\myclasses"; /* user classes */
options[2].optionString = "-Djava.library.path=c:\mylibs";  /* set native library path */
options[3].optionString = "-verbose:jni";                   /* print JNI-related messages */

vm_args.version = JNI_VERSION_1_2;
vm_args.options = options;
vm_args.nOptions = 4;
vm_args.ignoreUnrecognized = TRUE;

/* Note that in the JDK/JRE, there is no longer any need to call
 * JNI_GetDefaultJavaVMInitArgs.
 */
res = JNI_CreateJavaVM(&vm, (void **)&env, &vm_args);
if (res < 0) ...

LINKAGE:

Exported from the native library that implements the Java virtual machine.

PARAMETERS:

p_vm: pointer to the location where the resulting VM structure will be placed.

p_env: pointer to the location where the JNI interface pointer for the main thread will be placed.

vm_args: Java VM initialization arguments.

RETURNS:

Returns JNI_OK on success; returns a suitable JNI error code (a negative number) on failure.

DestroyJavaVM

jint DestroyJavaVM(JavaVM *vm);

Unloads a Java VM and reclaims its resources.

The support for DestroyJavaVM was not complete in JDK/JRE 1.1. As of JDK/JRE 1.1 Only the main thread may call DestroyJavaVM. Since JDK/JRE 1.2, any thread, whether attached or not, can call this function. If the current thread is attached, the VM waits until the current thread is the only non-daemon user-level Java thread. If the current thread is not attached, the VM attaches the current thread and then waits until the current thread is the only non-daemon user-level thread. The JDK/JRE still does not support VM unloading, however.

LINKAGE:

Index 3 in the JavaVM interface function table.

PARAMETERS:

vm: the Java VM that will be destroyed.

RETURNS:

Returns JNI_OK on success; returns a suitable JNI error code (a negative number) on failure.

As of JDK/JRE 1.1.2 unloading of the VM is not supported.

AttachCurrentThread

jint AttachCurrentThread(JavaVM *vm, void **p_env, void *thr_args);

Attaches the current thread to a Java VM. Returns a JNI interface pointer in the JNIEnv argument.

Trying to attach a thread that is already attached is a no-op.

A native thread cannot be attached simultaneously to two Java VMs.

When a thread is attached to the VM, the context class loader is the bootstrap loader.

LINKAGE:

Index 4 in the JavaVM interface function table.

PARAMETERS:

vm: the VM to which the current thread will be attached.

p_env: pointer to the location where the JNI interface pointer of the current thread will be placed.

thr_args: can be NULL or a pointer to a JavaVMAttachArgs structure to specify additional information:

As of JDK/JRE 1.1, the second argument to AttachCurrentThread is always a pointer to JNIEnv. The third argument to AttachCurrentThread was reserved, and should be set to NULL.

As of JDK/JRE 1.2, you pass NULL as the third argument for 1.1 behavior, or pass a pointer to the following structure to specify additional information:

typedef struct JavaVMAttachArgs {
    jint version;  /* must be at least JNI_VERSION_1_2 */
    char *name;    /* the name of the thread as a modified UTF-8 string, or NULL */
    jobject group; /* global ref of a ThreadGroup object, or NULL */
} JavaVMAttachArgs

RETURNS:

Returns JNI_OK on success; returns a suitable JNI error code (a negative number) on failure.

AttachCurrentThreadAsDaemon

jint AttachCurrentThreadAsDaemon(JavaVM* vm, void** penv, void* args);

Same semantics as AttachCurrentThread, but the newly-created java.lang.Thread instance is a daemon.

If the thread has already been attached via either AttachCurrentThread or AttachCurrentThreadAsDaemon, this routine simply sets the value pointed to by penv to the JNIEnv of the current thread. In this case neither AttachCurrentThread nor this routine have any effect on the daemon status of the thread.

LINKAGE:

Index 7 in the JavaVM interface function table.

PARAMETERS:

vm: the virtual machine instance to which the current thread will be attached.

penv: a pointer to the location in which the JNIEnv interface pointer for the current thread will be placed.

args: a pointer to a JavaVMAttachArgs structure.

RETURNS

Returns JNI_OK on success; returns a suitable JNI error code (a negative number) on failure.

EXCEPTIONS

None.

SINCE:

JDK/JRE 1.4

DetachCurrentThread

jint DetachCurrentThread(JavaVM *vm);

Detaches the current thread from a Java VM. All Java monitors held by this thread are released. All Java threads waiting for this thread to die are notified.

As of JDK/JRE 1.2 , the main thread can be detached from the VM.

LINKAGE:

Index 5 in the JavaVM interface function table.

PARAMETERS:

vm: the VM from which the current thread will be detached.

RETURNS:

Returns JNI_OK on success; returns a suitable JNI error code (a negative number) on failure.

GetEnv

jint GetEnv(JavaVM *vm, void **env, jint version);

LINKAGE:

Index 6 in the JavaVM interface function table.

PARAMETERS:

vm: The virtual machine instance from which the interface will be retrieved.
env: pointer to the location where the JNI interface pointer for the current thread will be placed.
version: The requested JNI version.

RETURNS:

If the current thread is not attached to the VM, sets *env to NULL, and returns JNI_EDETACHED. If the specified version is not supported, sets *env to NULL, and returns JNI_EVERSION. Otherwise, sets *env to the appropriate interface, and returns JNI_OK.

SINCE:

JDK/JRE 1.2

Contents | Previous
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.jdi.InvocationException (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.InvocationException

  • Packages that use InvocationException
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of InvocationException in com.sun.jdi

      Methods in com.sun.jdi that throw InvocationException
      Modifier and Type Method and Description
      Value ClassType.invokeMethod(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Invokes the specified static Method in the target VM.
      Value ObjectReference.invokeMethod(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Invokes the specified Method on this object in the target VM.
      ObjectReference ClassType.newInstance(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Constructs a new instance of this type, using the given constructor Method in the target VM.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Character streams (Introduced in JDK(TM) 1.1)

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Character streams (Introduced in JDKTM 1.1)

Version 1.1 of the JavaTM Development Kit introduced support for character streams to the java.io package.

Prior to JDK 1.1, the standard I/O facilities supported only byte streams, via the InputStream and OutputStream classes and their subclasses. Character streams are like byte streams, but they contain 16-bit Unicode characters rather than eight-bit bytes. They are implemented by the Reader and Writer classes and their subclasses. Readers and Writers support essentially the same operations as InputStreams and OutputStreams, except that where byte-stream methods operate on bytes or byte arrays, character-stream methods operate on characters, character arrays, or strings.

Most of the functionality available for byte streams is also provided for character streams. This is reflected in the name of each character-stream class, whose prefix is usually shared with the name of the corresponding byte-stream class. For example, there is a PushbackReader class that provides the same functionality for character streams that is provided by PushbackInputStream for byte streams.

Why use character streams?

The primary advantage of character streams is that they make it easy to write programs that are not dependent upon a specific character encoding, and are therefore easy to internationalize.

Java stores strings in Unicode, an international standard character encoding that is capable of representing most of the world's written languages. Typical user-readable text files, however, use encodings that are not necessarily related to Unicode, or even to ASCII, and there are many such encodings. Character streams hide the complexity of dealing with these encodings by providing two classes that serve as bridges between byte streams and character streams. The InputStreamReader class implements a character-input stream that reads bytes from a byte-input stream and converts them to characters according to a specified encoding. Similarly, the OutputStreamWriter class implements a character-output stream that converts characters into bytes according a specified encoding and writes them to a byte-output stream.

A second advantage of character streams is that they are potentially much more efficient than byte streams. The implementations of many of Java's original byte streams are oriented around byte-at-a-time read and write operations. The character-stream classes, in contrast, are oriented around buffer-at-a-time read and write operations. This difference, in combination with a more efficient locking scheme, allows the character stream classes to make up for the added overhead of encoding conversion in many cases.

API overview

The character-stream classes have been designed to parallel the existing byte-stream classes in the java.io package. As noted above, the name of each character-stream class ends in Reader or Writer, as appropriate, while its prefix is usually shared with the corresponding byte-stream class, if any. The following table summarizes the new classes; in the left column, indentation indicates subclass relationships.
Character-stream class | Description | Corresponding byte class
Reader | Abstract class for character-input streams | InputStream
BufferedReader | Buffers input, parses lines | BufferedInputStream
LineNumberReader | Keeps track of line numbers | LineNumberInputStream
CharArrayReader | Reads from a character array | ByteArrayInputStream
InputStreamReader | Translates a byte stream into a character stream | (none)
FileReader | Translates bytes from a file into a character stream | FileInputStream
FilterReader | Abstract class for filtered character input | FilterInputStream
PushbackReader | Allows characters to be pushed back | PushbackInputStream
PipedReader | Reads from a PipedWriter | PipedInputStream
StringReader | Reads from a String | StringBufferInputStream
Writer | Abstract class for character-output streams | OutputStream
BufferedWriter | Buffers output, uses platform's line separator | BufferedOutputStream
CharArrayWriter | Writes to a character array | ByteArrayOutputStream
FilterWriter | Abstract class for filtered character output | FilterOutputStream
OutputStreamWriter | Translates a character stream into a byte stream | (none)
FileWriter | Translates a character stream into a byte file | FileOutputStream
PrintWriter | Prints values and objects to a Writer | PrintStream
PipedWriter | Writes to a PipedReader | PipedOutputStream
StringWriter | Writes to a String | (none)

Related changes

PrintStream

The PrintStream class has been modified to use the platform's default character encoding and the platform's default line terminator. Thus each PrintStream incorporates an OutputStreamWriter, and it passes all characters through this writer to produce bytes for output. The println methods use the platform's default line terminator, which is defined by the system property line.separator and is not necessarily a single newline character ('\n'). Bytes and byte arrays written via the existing write methods are not passed through the writer.

The primary motivation for changing the PrintStream class is that it will make System.out and System.err more useful to people writing Java programs on platforms where the local encoding is something other than ASCII. PrintStream is, in other words, provided primarily for use in debugging and for compatibility with existing code. Code that produces textual output should use the new PrintWriter class, which allows the character encoding to be specified or the default encoding to be accepted. For convenience, the PrintWriter class provides constructors that take an OutputStream object and create an intermediate OutputStreamWriter object that uses the default encoding.

Other classes

The following constructors and methods have been deprecated because they do not properly convert between bytes and characters:

String | DataInputStream.readLine()
InputStream | Runtime.getLocalizedInputStream(InputStream)
OutputStream | Runtime.getLocalizedOutputStream(OutputStream)
 | StreamTokenizer(InputStream)
 | String(byte ascii[], int hibyte, int offset, int count)
 | String(byte ascii[], int hibyte)
void | String.getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin)

Finally, the following constructor and methods have been added:

 | StreamTokenizer(Reader)
byte[] | String.getBytes()
void | Throwable.printStackTrace(PrintWriter)
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Features of java.io.File in the Java(TM) 2 Platform

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Features of java.io.File in the JavaTM 2 Platform

The File class is a true abstract representation of file and directory pathnames. This allows the File class to better support non-Unix platforms such as Windows, which has a rich pathname syntax involving drive letters, UNC share names, and multiple separator characters. The specification of class File prior to the JavaTM 2 Platform could not handle these cases because it was written in terms of simple string operations.

The following features were introduced in the File class in the Java 2 Platform, v1.2:

  • The ability to create temporary files, and a simple delete-on-exit facility (the new methods createNewFile, createTempFile, and deleteOnExit);
  • Conversion of abstract pathnames to URLs (the new method toURL);
  • Access to the list of filesystem roots (the new method listRoots);
  • Comparability (the new compareTo methods);
  • Access to additional file attributes (the new methods isHidden, setLastModified, and setReadOnly); and
  • A uniform set of methods that accept and return File objects rather than strings (the new methods getParentFile, getAbsoluteFile, getCanonicalFile, and listFiles, and the new interface FileFilter).
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Minor changes to java.io in the Java 2 Platform v1.2

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Minor changes to java.io in the JavaTM 2 Platform v1.2

The following changes to package java.io were introduced in version 1.2 of the JavaTM 2 Platform. Minor changes to this package were:
  • The out field of the PrintWriter class is now protected rather than private, so that subclasses may access it
  • The RandomAccessFile class supports a new setLength method; and
  • The StringWriter(int) constructor is now public.

In the Java 2 Platform, the following constructors check for null input parameters:

  • The constructors PrintStream(OutputStream out) and PrintStream(OutputStream out, boolean autoFlush) will throw a NullPointerException if the parameter out is null.
  • The constructors InputStreamReader(InputStream in) and InputStreamReader(InputStream in, String enc) will throw a NullPointerException if the in parameter is null.
  • The constructors OutputStreamWriter(OutputStream out) and OutputStreamWriter(OutputStream out, String enc) will throw a NullPointerException if the out parameter is null.
  • The protected constructors Reader(Object lock) and Writer(Object lock) now throw NullPointerException if the lock parameter is null.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Contents | Previous | Next

Chapter 2

Rendering with Graphics2D

Graphics2D extends java.awt.Graphics to provide more sophisticated control over the presentation of shapes, text, and images. The Java 2D™ rendering process is controlled through the Graphics2D object and its state attributes.

The Graphics2D state attributes, such as line styles and transformations, are applied to graphic objects when they are rendered. The collection of state attributes associated with a Graphics2D is referred to as the Graphics2D context. To render text, shapes, or images, you set up the Graphics2D context and then call one of the Graphics2D rendering methods, such as draw or fill.

2.1 Interfaces and Classes

The following tables list the interfaces and classes used in conjunction with the Graphics2D context, including the classes that represent state attributes. Most of these classes are part of the java.awt package.

Interface | Description
Composite | Defines methods to compose a draw primitive with the underlying graphics area. Implemented by AlphaComposite.
CompositeContext | Defines the encapsulated and optimized environment for a composite operation. Used by programmers implementing custom compositing rules.
Paint | Extends: Transparency Defines colors for a draw or fill operation. Implemented by Color, GradientPaint and TexturePaint.
PaintContext | Defines the encapsulated and optimized environment for a paint operation. Used by programmers implementing custom paint operations.
Stroke | Generates a Shape that encloses the outline of the Shape to be rendered. Implemented by BasicStroke.
Class | Description
AffineTransform (java.awt.geom) | Represents a 2D affine transform, which performs a linear mapping from 2D coordinates to other 2D coordinates.
AlphaComposite | Implements: Composite Implements basic alpha composite rules for shapes, text, and images.
BasicStroke | Implements: Stroke Defines the “pen style” to be applied to the outline of a Shape.
Color | Implements: Paint Defines a solid color fill for a Shape.
GradientPaint | Implements: Paint Defines a linear color gradient fill pattern for a Shape. This fill pattern changes from color C1 at point P1 to color C2 at point P2.
Graphics2D | Extends: Graphics Fundamental class for 2D rendering. Extends the original java.awt.Graphics class.
TexturePaint | Implements: Paint Defines a texture or pattern fill for a Shape. The texture or pattern is generated from a BufferedImage.

2.2 Rendering Concepts

To render a graphic object using the Java 2D™ API, you set up the Graphics2D context and pass the graphic object to one of the Graphics2D rendering methods.

You can modify the state attributes that form the Graphics2D context to:

  • Vary the stroke width.
  • Change how strokes are joined together.
  • Set a clipping path to limit the area that is rendered.
  • Translate, rotate, scale, or shear objects when they are rendered.
  • Define colors and patterns to fill shapes with.
  • Specify how multiple graphics objects should be composed.

Graphics2D defines several methods for adding and changing attributes in the graphics context. Most of these methods take an object that represents a particular attribute, such as a Paint or Stroke object.

The Graphics2D context holds references to these attribute objects: they are not cloned. If you alter an attribute object that is part of the Graphics2D context, you need to call the appropriate set method to notify the context. Modifying an attribute object during a rendering operation will cause unpredictable and possibly unstable behavior.

2.2.1 Rendering Process

When a graphic object is rendered, the geometry, image, and attribute information are combined to calculate which pixel values must be changed on the display.

The rendering process for a Shape can be broken down into four steps:

  • If the Shape is to be stroked, the Stroke attribute in the Graphics2D context is used to generate a new Shape that encompasses the stroked path.
  • The coordinates of the Shape’s path are transformed from user space into device space according to the transform attribute in the Graphics2D context.
  • The Shape’s path is clipped using the clip attribute in the Graphics2D context.
  • The remaining Shape, if any, is filled using the Paint and Composite attributes in the Graphics2D context.

Rendering text is similar to rendering a Shape, since the text is rendered as individual glyphs and each glyph is a Shape. The only difference is that the Java 2D API must determine what Font to apply to the text and get the appropriate glyphs from the Font before rendering.

Images are handled differently, transformations and clipping operations are performed on the image’s bounding box. The color information is taken from the image itself and its alpha channel is used in conjunction with the current Composite attribute when the image pixels are composited onto the rendering surface.

2.2.2 Controlling Rendering Quality

The Java 2D API lets you indicate whether you want objects to be rendered as quickly as possible, or whether you prefer that the rendering quality be as high as possible. Your preferences are specified as hints through the RenderingHints attribute in the Graphics2D context. Not all platforms support modification of the rendering mode so specifying rendering hints does not guarantee that they will be used.

The RenderingHints class supports the following types of hints:

  • Alpha interpolation—can be set to default, quality, or speed.
  • Antialiasing—can be set to default, on, or off.
  • Color Rendering–can be set to default, quality, or speed.
  • Dithering—can be set to default, disable, or enable.
  • Fractional Metrics—can be set to default, on, or off.
  • Interpolation—can be set to nearest-neighbor, bilinear, or bicubic.
  • Rendering—can be set to default, quality, or speed.
  • Text antialiasing—can be set to default, on, or off.

To set or change the RenderingHints attribute in the Graphics2D context, you call setRenderingHints. When a hint is set to default, the platform rendering default is used is used.

Antialiasing

When graphics primitives are rendered on raster-graphics display devices, their edges can appear jagged because of aliasing. Arcs and diagonal lines take on a jagged appearance because they are approximated by turning on the pixels that are closest to the path of the line or curve. This is particularly noticeable on low-resolution devices, where the jagged edges appear in stark contrast to the smooth edges of horizontal or vertical lines.

Antialiasing is a technique used to render objects with smoother-appearing edges. Instead of simply turning on the pixel that is closest to the line or curve, the intensity of surrounding pixels is set in proportion to the amount of area covered by the geometry being rendered. This softens the edges and spreads the on-off transition over multiple pixels. However, antialiasing requires additional computing resources and can reduce rendering speed

.

This graphic shows examples of aliased and antialiased graphics as described in the previous context.

2.2.3 Stroke Attributes

Stroking a Shape such as a GeneralPath object is equivalent to running a logical pen along the segments of the GeneralPath. The Graphics2D Stroke attribute defines the characteristics of the mark drawn by the pen.

A BasicStroke object is used to define the stroke attributes for a Graphics2D context. BasicStroke defines characteristics such as the line width, endcap style, segment join-style, and the dashing pattern. To set or change the Stroke attribute in the Graphics2D context, you call setStroke.

This graphics shows endcap styles supported by BasicStroke including chopped, round and squared.
Figure 2-1 endcap styles supported by BasicStroke

This graphic shows join styles supported by BasicStroke including bevel, round and miter.
Figure 2-2 Join styles supported by BasicStroke

For example, the first image in Figure 2-3 uses the miter join-style; the second image uses a round join-style, a round endcap style, and a dashing pattern.

The previous context describes this graphic
Figure 2-3 Stroke Styles

The Graphics2D rendering methods that use the Stroke attribute are draw, drawArc, drawLine, drawOval, drawPolygon, drawPolyline, drawRect, and drawRoundRect.When one of these methods is called, the outline of the specified Shape is rendered. The Stroke attribute defines the line characteristics and the Paint attribute defines the color or pattern of the mark drawn by the pen.

For example, when draw(myRectangle) is called:

  • The Stroke is applied to the rectangle’s outline.
  • The stroked outline is converted to a Shape object.
  • The Paint is applied to the pixels that lie within the contour of the outline Shape.

This process is illustrated in Figure 2-4:

The previous context describes this graphic.
Figure 2-4 Stroking a Shape

2.2.4 Fill Attributes

The fill attribute in the Graphics2D context is represented by a Paint object. You add a Paint to the Graphics2D context by calling setPaint.

When a Shape or glyph is drawn (Graphics2D.draw, Graphics2D.drawString), the Paint is applied to all of the pixels that lie inside of the Shape that represents the object’s stroked outline. When a Shape is filled (Graphics2D.fill), the Paint is applied to all of the pixels that lie within the Shape’s contour.

Simple solid color fills can be set with the setColor method. Color is the simplest implementation of the Paint interface.

To fill Shapes with more complex paint styles such as gradients and textures, you use the Java 2D Paint classes GradientPaint and TexturePaint. These classes eliminate the time-consuming task of creating complex fills using simple solid-color paints. Figure 2-5 illustrates two fills that could easily be defined by GradientPaint and TexturePaint.

The previous context describes this graphic.
Figure 2-5 Complex Fill Styles

When fill is called to render a Shape, the system:

  • Determines what pixels comprise the Shape.
  • Gets the color of each pixel from the Paint object.
  • Converts the color to an appropriate pixel value for the output device.
  • Writes the pixel to that device.

Batch Processing

To streamline the processing of pixels, the Java 2D API processes them in batches. A batch can be either a contiguous set of pixels on a given scanline or a block of pixels. This batch processing is done in two steps:

  • The Paint object’s createContext method is called to create a PaintContext. The PaintContext stores the contextual information about the current rendering operation and the information necessary to generate the colors. The createContext method is passed the bounding boxes of the graphics object being filled in user space and in device space, the ColorModel in which the colors should be generated, and the transform used to map user space into device space. The ColorModel is treated as a hint because not all Paint objects can support an arbitrary ColorModel. (For more information about ColorModels, see “Color” on page 89.”)
  • The getColorModel method is called to get the ColorModel of the generated paint color from the PaintContext.

The getRaster method is then called repeatedly to get the Raster that contains the actual color data for each batch. This information is passed to the next stage in the rendering pipeline, which draws the generated color using the current Composite object.

2.2.5 Clipping Paths

A clipping path identifies the portion of a Shape or Image that needs to be rendered. When a clipping path is part of the Graphics2D context, only those parts of a Shape or Image that lie within the path are rendered.

To add a clipping path to the Graphics2D context, you call setClip. Any Shape can be used to define the clipping path.

To change the clipping path, you can either use setClip to specify a new path or call clip to change the clipping path to the intersection of the old clipping path and a new Shape.

2.2.6 Transformations

The Graphics2D context contains a transform that is used to transform objects from user space to device space during rendering. To perform additional transformations, such as rotation or scaling, you can add other transforms to the Graphics2D context. These additional transforms become part of the pipeline of transformations applied during rendering.

Graphics2D provides several different ways to modify the transform in the Graphics2D context. The simplest is to call one of the Graphics2D transformation methods: rotate, scale, shear, or translate. You specify the characteristics of the transform that you want to be applied during rendering, and Graphics2D automatically makes the appropriate changes.

You can also explicitly concatenate an AffineTransform with the current Graphics2D transform. An AffineTransform performs a linear transformation such as translation, scaling, rotation, or shearing on a set of graphics primitives. When a transform is concatenated with an existing transform, the last transform specified is the first to be applied. To concatenate a transform with the current transform, you pass an AffineTransform to Graphics2D.transform.

The Graphics2D class also contains a setTransform method, but this method should never be used to concatenate another coordinate transform onto of an existing transform. The setTransform method overwrites the Graphics2D object’s current transform, which is needed for other purposes, such as:

  • Applying a scaling transform to adjust for printer resolution.
  • Painting a JComponent at non-zero translation from its parent’s origin
  • Scaling up a component for easier viewing.
  • Any other situation in which the supplier of a Graphics2D object might want to transform the rendering for effect .

The setTransform method is intended for setting the Graphics2D object back to the original transform after rendering the transformed graphics, text or images:

AffineTransform aT = g2d.getTransform();
g2d.transform(...);g2d.draw(...);
g2d.setTransform(aT);

Graphics2D also provides a version of drawImage that takes an AffineTransform as a parameter. This enables you to apply a transformation to an image object when it is drawn without permanently modifying the transformation pipeline. The image is drawn as if you had concatenated the transform with the current transform in the Graphics2D context.

Affine Transforms

The Java 2D API provides one transform class, AffineTransform. AffineTransforms are used to transform text, shapes, and images when they are rendered. You can also apply transforms to Font objects to create new font derivations, as discussed in “Creating Font Derivations” on page 65.

An affine transformation performs a linear transformation on a set of graphics primitives. It always transforms straight lines into straight lines and parallel lines into parallel lines; however, the distance between points and the angles between nonparallel lines might be altered.

Affine transformations are based on two-dimensional matrices of the following form:

A 2 by 3 matrix with the top row containing a, c and t sub x. The second row contains b, d and t sub y. where x prime equals a x plus c y plus t sub x and y prime equals b x plus d y plus t sub y

Transforms can be combined, effectively creating a series or pipeline of transformations that can be applied to an object. This combination is referred to as concatenation. When a transform is concatenated with an existing transform, such as with AffineTransform.concatenate, the last transform specified is the first to be applied. A transform can also be pre-concatenated with an existing transform. In this case, the last transform specified is the last to be applied.

Pre-concatenation is used to perform transformations relative to device space instead of user space. For example, you could use AffineTransform.preConcatenate to perform a translation relative to absolute pixel space.

2.2.6.1 Constructing an AffineTransform

AffineTransform provides a set of convenience methods for constructing AffineTransform objects:

  • getTranslateInstance
  • getRotateInstance
  • getScaleInstance
  • getShearInstance

To use these methods, you specify the characteristics of the transform you want to create and AffineTransform generates the appropriate transform matrix. You can also construct an AffineTransform by directly specifying the elements of the transformation matrix.

2.2.7 Composite Attributes

When two graphic objects overlap, it is necessary to determine what colors to render the overlapping pixels. For example, if a red rectangle and a blue rectangle overlap, the pixels that they share could be rendered red, blue, or some combination of the two. The color of the pixels in the overlapping area will determine which rectangle appears to be on top and how transparent it looks. The process of determining what color to render pixels shared by overlapping objects is called compositing.

Two interfaces form the basis of the Java 2D compositing model: Composite and CompositeContext.

To specify the compositing style that should be used, you add an AlphaComposite object to the Graphics2D context by calling setComposite. AlphaComposite, an implementation of the Composite interface, supports a number of different compositing styles. Instances of this class embody a compositing rule that describes how to blend a new color with an existing one.

One of the most commonly used compositing rules in the AlphaComposite class is SRC_OVER, which indicates that the new color (the source color) should be blended over the existing color (the destination color).

AlphaComposite Composition Rule | Description | Example
CLEAR | Clear |
DEST_IN | Destination In |
DEST_OUT | Destination Out |
DEST_OVER | Destination Over |
SRC | Source |
SRC_IN | Source In |
SRC_OUT | Source Out |
SRC_OVER | Source Over |

2.2.7.1 Managing Transparency

A color’s alpha value is a measure of its transparency: it indicates, as a percentage, how much of a previously rendered color should show through when colors overlap. Opaque colors (alpha=1.0) don’t allow any of the underlying color to show through, while transparent colors (alpha=0.0) let all of it show through.

When text and Shapes are rendered, the alpha value is derived from the Paint attribute in the Graphics2D context. When Shapes and text are antialiased, the alpha value from the Paint in the Graphics2D context is combined with pixel coverage information from the rasterized path. Images maintain their own alpha information—see “Transparency and Images” on page 26 for more information.

When you construct an AlphaComposite object, you can specify an additional alpha value. When you add this AlphaComposite object to the Graphics2D context, this extra alpha value increases the transparency of any graphic objects that are rendered—the alpha value of each graphic object is multiplied by the AlphaComposite’s alpha value.

2.2.7.2 Transparency and Images

Images can carry transparency information for each pixel in the image. This information, called an alpha channel, is used in conjunction with the Composite object in the Graphics2D context to blend the image with existing drawings.

For example, Figure 2-6 contains three images with different transparency information. In each case, the image is displayed over a blue rectangle. This example assumes that the Graphics2D context contains an AlphaComposite object that uses SRC_OVER as the compositing operation.

The following context describes this graphic.
Figure 2-6 Transparency and Images

In the first image, all of the pixels are either fully opaque (the dog’s body) or fully transparent (the background). This effect is often used on Web pages. In the second image, all of the pixels in the dog’s body are rendered using a uniform, non-opaque alpha value, allowing the blue background to show through. In the third image, the pixels around the dogs face are fully opaque (alpha=1.0), but as the distance from its face increases, the alpha values for the pixels decrease.

2.3 Setting Up the Graphics2D Context

To configure the Graphics2D context for rendering, you use the Graphics2D set methods to specify attributes such as the RenderingHints, Stroke, Paint, clipping path, Composite, and Transform.

2.3.1 Setting Rendering Hints

A RenderingHints object encapsulates all of your preferences concerning how an object is rendered. To set the rendering hints in the Graphics2D context, you create a RenderingHints object and pass it into Graphics2D.setRenderingHints.

Setting a rendering hint does not guarantee that a particular rendering algorithm will be used: not all platforms support modification of the rendering mode.

In the following example, antialiasing is enabled and the rendering preference is set to quality:

qualityHints = new               RenderingHints(RenderingHints.KEY_ANTIALIASING,               RenderingHints.VALUE_ANTIALIAS_ON);
qualityHints.put(RenderingHints.KEY_RENDERING,               RenderingHints.VALUE_RENDER_QUALITY);
g2.setRenderingHints(qualityHints);

2.3.2 Specifying Stroke Attributes

A BasicStroke defines the characteristics applied to a Shape’s outline, including its width and dashing pattern, how line segments are joined together, and the decoration (if any) applied to the end of a line. To set the stroke attributes in the Graphics2D context, you create a BasicStroke object and pass it into setStroke.

2.3.2.1 Setting the Stroke Width

To set the stroke width, you create a BasicStroke object with the desired width and call setStroke.

In the following example, the stroke width is set to twelve points and the defaults are used for the join and endcap decorations:

wideStroke = new BasicStroke(12.0f);
g2.setStroke(wideStroke);

2.3.2.2 Specifying Join and Endcap Styles

To set the join and endcap styles, you create a BasicStroke object with the desired attributes.

In the following example, the stroke width is set to twelve points and the round join and endcap styles are used instead of the defaults:

roundStroke = new BasicStroke(4.0f, BasicStroke.CAP_ROUND,              BasicStroke.JOIN_ROUND);
g2.setStroke(roundStroke);

2.3.2.3 Setting the Dashing Pattern

Complex dashing patterns can easily be defined with a BasicStroke object. When you create a BasicStroke object, you can specify two parameters that control the dashing pattern:

  • dash—an array that represents the dashing pattern. Alternating elements in the array represent the dash size and the size of the space between dashes. Element 0 represents the first dash, element 1 represents the first space.
  • dash_phase—an offset that defines where the dashing pattern starts.

In the following example, two different dashing patterns are applied to a line. In the first, the size of the dashes and the space between them is constant. The second dashing pattern is more complex, using a six-element array to define the dashing pattern.

float dash1[] = {10.0f};
BasicStroke bs = new BasicStroke(5.0f, BasicStroke.CAP_BUTT,
                 BasicStroke.JOIN_MITER, 10.0f, dash1, 0.0f);
g2.setStroke(bs);
Line2D line = new Line2D.Float(20.0f, 10.0f, 100.0f, 10.0f);
g2.draw(line);

float[] dash2 = {6.0f, 4.0f, 2.0f, 4.0f, 2.0f, 4.0f};
bs = new BasicStroke(5.0f, BasicStroke.CAP_BUTT,
     BasicStroke.JOIN_MITER, 10.0f, dash2, 0.0f);
g2.setStroke(bs);
g2.draw(line);

Both dashing patterns use a dash phase of zero, causing the dashes to be drawn starting at the beginning of the dashing pattern. The two dashing patterns are shown in Figure Figure 2-7

.

The previous context describes this graphic.
Figure 2-7 Dashing Patterns

2.3.3 Specifying Fill Attributes

The Paint attribute in the Graphics2D context determines the fill color or pattern that is used when text and Shapes are rendered.

2.3.3.1 Filling a Shape with a Gradient

The GradientPaint class provides an easy way to fill a shape with a gradient of one color to another. When you create a GradientPaint, you specify a beginning position and color, and an ending position and color. The fill color changes proportionally from one color to the other along the line connecting the two positions, as shown in Figure 2-8.

The previous context describes this graphic.
Figure 2-8 Creating Gradient Fills

In the third star in Figure 2-8, both points lie within the shape. All of the points along the gradient line extending beyond P1 take the beginning color, and the points along the gradient line extending beyond P2 take the ending color.

To fill a shape with a gradient of one color to another:

  • Create a GradientPaint object.
  • Call Graphics2D.setPaint.
  • Create the Shape.
  • Call Graphics2D.fill(shape).

In the following example, a rectangle is filled with a blue-green gradient.

GradientPaint gp = new GradientPaint(50.0f, 50.0f, Color.blue
                   50.0f, 250.0f, Color.green);
g2.setPaint(gp);
g2.fillRect(50, 50, 200, 200);

2.3.3.2 Filling a Shape with a Texture

The TexturePaint class provides an easy way to fill a shape with a repeating pattern. When you create a TexturePaint, you specify a BufferedImage to use as the pattern. You also pass the constructor a rectangle to define the repetition frequency of the pattern, as shown in Figure 2-9.

The previous context describes this graphic.
Figure 2-9 Creating Texture Paints

To fill a shape with a texture:

  • Create a TexturePaint object.
  • Call Graphics2D.setPaint.
  • Create the Shape.
  • Call Graphics2D.fill(shape).

In the following example, a rectangle is filled with a simple texture created from a buffered image.

// Create a buffered image texture patch of size 5x5
BufferedImage bi = new BufferedImage(5, 5,
                       BufferedImage.TYPE_INT_RGB);
Graphics2D big = bi.createGraphics();
// Render into the BufferedImage graphics to create the texture
big.setColor(Color.green);
big.fillRect(0,0,5,5);
big.setColor(Color.lightGray);
big.fillOval(0,0,5,5);

// Create a texture paint from the buffered image
Rectangle r = new Rectangle(0,0,5,5);
TexturePaint tp = new TexturePaint(bi,r,TexturePaint.NEAREST_NEIGHBOR);

// Add the texture paint to the graphics context.
g2.setPaint(tp);

// Create and render a rectangle filled with the texture.
g2.fillRect(0,0,200,200);
}

2.3.4 Setting the Clipping Path

To define a clipping path:

  • Create a Shape that represents the area you want to render.
  • Call Graphics2D.setClip to use the shape as the clipping path for the Graphics2D context.

To shrink the clipping path:

  • Create a Shape that intersects the current clipping path.
  • Call clip to change the clipping path to the intersection of the current clipping path and the new Shape.

In the following example, a clipping path is created from an ellipse and then modified by calling clip.

public void paint(Graphics g) {
  Graphics2D g2 = (Graphics2D) g;

// The width and height of the canvas
  int w = getSize().width;
  int h = getSize().height;
  // Create an ellipse and use it as the clipping path
  Ellipse2D e = new Ellipse2D.Float(w/4.0f,h/4.0f,
                                    w/2.0f,h/2.0f);
  g2.setClip(e);

  // Fill the canvas. Only the area within the clip is rendered
  g2.setColor(Color.cyan);
  g2.fillRect(0,0,w,h);

  // Change the clipping path, setting it to the intersection of
  // the current clip and a new rectangle.
  Rectangle r = new Rectangle(w/4+10,h/4+10,w/2-20,h/2-20);
  g2.clip(r);

  // Fill the canvas. Only the area within the new clip
  // is rendered
  g2.setColor(Color.magenta);
  g2.fillRect(0,0,w,h);
}

2.3.5 Setting the Graphics2D Transform

To transform a Shape, text string, or Image you add a new AffineTransform to the transformation pipeline in the Graphics2D context before rendering. The transformation is applied when the graphic object is rendered.

For example, to draw a rectangle that is rotated 45 degrees:

  • Get the current Graphics2D transform before performing any transformations. Always call getTransform on the Graphics2D before adding a transform to the graphics context because the graphics context might already have a transform that is needed for other reasons, such as positioning Swing and lightweight components within a window.
  • Get a rotation transform by calling AffineTransform. getRotateInstance.
  • Call Graphics2D.transform to add the new transform to the transformation pipeline. Never use the setTransform method to add a new coordinate transform because setTransform will overwrite the current transform in the graphics context.
  • Create a Rectangle2D.Float object.
  • Call Graphics2D.draw to render the rectangle.
  • After you have rendered your transformed rectangle, reset the transform of the Graphics2D back to the original transform that you saved in Step 1 by calling setTransform with the original transform.

In the following example, an instance of AffineTransform is used to rotate a rectangle 45 degrees when it is rendered.

AffineTransform aT = g2.getTransform();Rectangle2D rect = new Rectangle2D.Float(1.0,1.0,2.0,3.0);
AffineTransform rotate45 =
  AffineTransform.getRotateInstance(Math.PI/4.0,0.0,0.0)
g2.transform(rotate45);
g2.draw(rect);g2.setTransform(aT);

In this example, an AffineTransform is used to rotate a text string around a center point:

// Define the rendering transform
AffineTransform at = new AffineTransform();
// Apply a translation transform to make room for the
// rotated text.
at.setToTranslation(400.0, 400.0);
g2.transform(at);
// Create a rotation transform to rotate the text
at.setToRotation(Math.PI / 2.0);
// Render four copies of the string “Java” at 90 degree angles
for (int i = 0; i < 4; i++) {
    g2.drawString(“Java”, 0.0f, 0.0f);
    g2.transform(at);
}

You can transform an image in the same way—the transform in the Graphics2D context is applied during rendering regardless of the type of graphic object being rendered.

To apply a transform to an image without changing the transform in the Graphics2D context, you can pass an AffineTransform to drawImage:

AffineTransform rotate45 =
  AffineTransform.getRotateInstance(Math.PI/4.0,0.0,0.0)
g2.drawImage(myImage, rotate45);

Transforms can also be applied to a Font to create a modified version of the Font, for more information see “Creating Font Derivations” on page 65.

2.3.6 Specifying a Composition Style

An AlphaComposite encapsulates composition rules that determine how colors should be rendered when one object overlaps another. To specify the composition style for the Graphics2D context, you create an AlphaComposite and pass it into setComposite. The most commonly used is composition style is SRC_OVER.

2.3.6.1 Using the Source Over Compositing Rule

The SRC_OVER compositing rule composites the source pixel over the destination pixel such that the shared pixel takes the color of the source pixel. For example, if you render a blue rectangle and then render a red rectangle that partially overlaps it, the overlapping area will be red. In other words, the object that is rendered last will appear to be on top.

To use the SRC_OVER composition rule:

  • Create an AlphaComposite object by calling getInstance and specifying the SRC_OVER rule.
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER);
  • Call setComposite to add the AlphaComposite object to the Graphics2D context.

    g2.setComposite(ac);

Once the composite object is set, overlapping objects will be rendered using the specified composition rule.

2.3.6.2 Increasing the Transparency of Composited Objects

AlphaComposite allows you to specify an additional constant alpha value that is multiplied with the alpha of the source pixels to increase transparency.

For example, to create an AlphaComposite object that renders the source object 50% transparent, specify an alpha of .5:

AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f);

In the following example, a source over alpha composite object is created with an alpha of .5 and added to the graphics context, causing subsequent shapes to be rendered 50% transparent.

public void paint(Graphics g) {
  Graphics2D g2 = (Graphics2D) g;

  g2.setColor(Color.red);
  g2.translate(100,50);
  // radians=degree * pie / 180
  g2.rotate((45*java.lang.Math.PI)/180);
  g2.fillRect(0,0,100,100);
  g2.setTransform(new AffineTransform());  // set to identity
  // Create a new alpha composite
  AlphaComposite ac =
      AlphaComposite.getInstance(AlphaComposite.SRC_OVER,0.5f);
  g2.setComposite(ac);
  g2.setColor(Color.green);
  g2.fillRect(50,0,100,100);
  g2.setColor(Color.blue);
  g2.fillRect(125,75,100,100);
  g2.setColor(Color.yellow);
  g2.fillRect(50,125,100,100);
  g2.setColor(Color.pink);
  g2.fillRect(-25,75,100,100);
}

2.4 Rendering Graphics Primitives

Graphics2D provides rendering methods for Shapes, Text, and Images:

  • draw—strokes a Shape’s path using the Stroke and Paint objects in the Graphics2D context.
  • fill—fills a Shape using the Paint in the Graphics2D context.
  • drawString—renders the specified text string using the Paint in the Graphics2D context.
  • drawImage—renders the specified image.

To stroke and fill a shape, you must call both the draw and fill methods.

Graphics2D also supports the draw and fill methods from previous versions of the JDK software, such as drawOval and fillRect.

2.4.1 Drawing a Shape

The outline of any Shape can be rendered with the Graphics2D.draw method. The draw methods from previous versions of the JDK software are also supported: drawLine, drawRect, drawRoundRect, drawOval, drawArc, drawPolyline, drawPolygon, draw3DRect.

When a Shape is drawn, its path is stroked with the Stroke object in the Graphics2D context. (See “Stroke Attributes” on page 19 for more information.) By setting an appropriate BasicStroke object in the Graphics2D context, you can draw lines of any width or pattern. The BasicStroke object also defines the line’s endcap and join attributes.

To render shape’s outline:

  • Create a BasicStroke object
  • Call Graphics2D.setStroke
  • Create the Shape.
  • Call Graphics2D.draw(shape).

In the following example, a GeneralPath object is used to define a star and a BasicStroke object is added to the Graphics2D context to define the star’s line with and join attributes.

public void paint(Graphics g) {
  Graphics2D g2 = (Graphics2D) g;

  // create and set the stroke
  g2.setStroke(new BasicStroke(4.0f));

  // Create a star using a general path object
  GeneralPath p = new GeneralPath(GeneralPath.NON_ZERO);
  p.moveTo(- 100.0f, - 25.0f);
  p.lineTo(+ 100.0f, - 25.0f);
  p.lineTo(- 50.0f, + 100.0f);
  p.lineTo(+ 0.0f, - 100.0f);
  p.lineTo(+ 50.0f, + 100.0f);
  p.closePath();

  // translate origin towards center of canvas
  g2.translate(100.0f, 100.0f);

  // render the star's path
  g2.draw(p);
}

2.4.2 Filling a Shape

The Graphics2D.fill method can be used to fill any Shape. When a Shape is filled, the area within its path is rendered with the Graphics2D context’s current Paint attribute—a Color, TexturePaint, or GradientPaint.

The fill methods from previous versions of the JDK software are also supported: fillRect, fill3DRect, fillRoundRect, fillOval, fillArc, fillPolygon, clearRect.

To fill a Shape:

  • Set the fill color or pattern on the graphics context using
    Graphics2D.setColor or Graphics2D.setPaint.
  • Create the Shape.
  • Call Graphics2D.fill to render the Shape.

In the following example, setColor is called to define a green fill for a Rectangle2D.

public void paint(Graphics g) {
  Graphics2D g2 = (Graphics2D) g;

  g2.setPaint(Color.green);
  Rectangle2D r2 = new Rectangle2D.Float(25,25,150,150);

   g2.fill(r2);
}

2.4.3 Rendering Text

To render a text string, you call Graphics2D.drawString, passing in the string that you want to render. For more information about rendering text and selecting fonts, see “Fonts and Text Layout” on page 45.

2.4.4 Rendering Images

To render an Image, you create the Image and call Graphics2D.drawImage. For more information about processing and rendering images, see “Imaging” on page 67.

2.5 Defining Custom Composition Rules

You can create an entirely new type of compositing operation by implementing the Composite and CompositeContext interfaces. A Composite object provides a CompositeContext object that actually holds the state and performs the compositing work. Multiple CompositeContext objects can be created from one Composite object to maintain the separate states in a multithreaded environment.

2.6 Rendering in a Multi-Screen Environment

With the release of the JavaTM 2 SDK, version 1.3 and later versions, the Java 2DTM API supports three different multi-screen configurations that can possibly be configured by a native platform:

  • Two or more independent screens
  • Two or more screens where one screen is the primary screen and the other screens display copies of what appears on the primary screen.
  • Two or more screens that form a virtual desktop, which is also called a virtual device.

The Java 2D API enables you to create Frame, JFrame, Window, or JWindow objects with a GraphicsConfiguration to target a screen device for rendering.

In all three configurations, each screen device is represented by a GraphicsDevice. A GraphicsDevice can have multiple GraphicsConfiguration objects associated with it.

When two or more screens are used to form a virtual device, a virtual coordinate system that exists outside of the physical screens is used to represent the virtual device. The bounds of each GraphicsConfiguration in this multi-screen configuration are relative to the virtual coordinate system. One screen in this environment is identified as the primary screen, which is located at (0, 0) in the virtual coordinate system. Depending on the location of the primary screen, the virtual device might have negative coordinates, as shown in Figure 2-10:

example of a virtual device environment
Figure 2-10 Example of a virtual device environment

To determine if your environment is a virtual device environment in which a Window or a Frame can span two or more physical screens, call getBounds on each GraphicsConfiguration in your system and check to see if the origin is something other than (0, 0). The getBounds method of a GraphicsConfiguration returns a Rectangle in the virtual coordinate system. So, if any of the origins are not (0, 0), your environment is a virtual device environment.

In a virtual device environment, the coordinates of the GraphicsConfiguration objects are relative to the virtual coordinate system. So, you must use virtual coordinates when calling the setLocation method of a Frame or Window. For example, this code sample gets the bounds of a GraphicsConfiguration and uses the bounds to set the location of a Frame at (10, 10) relative to the origin of the physical screen of the corresponding GraphicsConfiguration.

Frame f = new Frame(GraphicsConfiguration gc);
Rectangle bounds = gc.getBounds();
f.setLocation(10 + bounds.x, 10 + bounds.y);

If the bounds of the GraphicsConfiguration are not taken into account, the Frame is displayed at (10, 10) on the primary physical screen, which might be different from the physical screen of the specified GraphicsConfiguration.

The getBounds method can also be used to determine the bounds of the virtual device. Call getBounds on each GraphicsConfiguration in your system. To determine the bounds of the virtual device, calculate the union of all the bounds. This technique is used in the following sample.

Rectangle virtualBounds = new Rectangle();
GraphicsEnvironment ge =
   GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
for (int j = 0; j < gs.length; j++) {
   GraphicsDevice gd = gs[j];
   GraphicsConfiguration[] gc = gd.getConfigurations();
   for (int i = 0; i < gc.length; i++) {
      virtualBounds = virtualBounds.union(gc[i].getBounds());
   }
}

The following applet creates a JFrame with every GraphicsConfiguration of every GraphicsDevice in the GraphicsEnvironment. Each JFrame displays a set of red, green and blue stripes, the screen number, the GraphicsConfiguration number and the bounds of the GraphicsConfiguration. This code sample must be run with the JavaTM 2 SDK, version 1.3 or later.

import java.applet.Applet;
import java.awt.*;
import javax.swing.*;

public class MultiFrameApplet extends Applet {

    public MultiFrameApplet() {
        main(null);
    }

    public static void main(String[] argv) {
        GraphicsEnvironment ge =
           GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice[] gs = ge.getScreenDevices();
        for (int j = 0; j < gs.length; j++) {
          GraphicsDevice gd = gs[j];
          GraphicsConfiguration[] gc =
             gd.getConfigurations();
             for (int i=0; i < gc.length; i++) {
               JFrame f =
                  new JFrame(gs[j].getDefaultConfiguration());
               GCCanvas c = new GCCanvas(gc[i]);
               Rectangle gcBounds = gc[i].getBounds();
               int xoffs = gcBounds.x;
               int yoffs = gcBounds.y;
               f.getContentPane().add(c);
               f.setTitle("Screen# "+Integer.toString(j)+",
                  GC# "+Integer.toString(i));
               f.setSize(300, 150);
               f.setLocation((i*50)+xoffs, (i*60)+yoffs);
               f.show();
             }
        }
    }
}

class GCCanvas extends Canvas {

    GraphicsConfiguration gc;
    Rectangle bounds;

    public GCCanvas(GraphicsConfiguration gc) {
        super(gc);
        this.gc = gc;
        bounds = gc.getBounds();
    }

    public Dimension getPreferredSize() {
        return new Dimension(300, 150);
    }

    public void paint(Graphics g) {
        g.setColor(Color.red);
        g.fillRect(0, 0, 100, 150);
        g.setColor(Color.green);
        g.fillRect(100, 0, 100, 150);
        g.setColor(Color.blue);
        g.fillRect(200, 0, 100, 150);
        g.setColor(Color.black);
        g.drawString("ScreenSize="+
           Integer.toString(bounds.width)+
           "X"+ Integer.toString(bounds.height), 10, 15);
        g.drawString(gc.toString(), 10, 30);
    }
}

Contents | Previous | Next
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java 2DTM API Overview 1

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Programmer's Guide to the JavaTM 2D API

JavaTM 2 SDK, Standard Edition
1.4 version

April 24, 2001
Contents | Previous | Next

Java 2DTM API Overview

Enhanced Graphics, Text, and Imaging

Rendering Model

Coordinate Systems

Transforms

Fonts

Images

Fills and Strokes

Composites

Backward Compatibility and Platform Independence

Backward Compatibility

Platform Independence

The Java 2D™ API Packages

Rendering with Graphics2D

Interfaces and Classes

Rendering Concepts

Rendering Process

Controlling Rendering Quality

Stroke Attributes

Fill Attributes

Clipping Paths

Transformations

Composite Attributes

Setting Up the Graphics2D Context

Setting Rendering Hints

Specifying Stroke Attributes

Specifying Fill Attributes

Setting the Clipping Path

Setting the Graphics2D Transform

Specifying a Composition Style

Rendering Graphics Primitives

Drawing a Shape

Filling a Shape

Rendering Text

Rendering Images

Defining Custom Composition Rules

Rendering in a Multi-Screen Environment

Geometries

Interfaces and Classes

Geometry Concepts

Constructive Area Geometry

Bounds and Hit Testing

Combining Areas to Create New Shapes

Creating a Custom Shape

Fonts and Text Layout

Interfaces and Classes

Font Concepts

Text Layout Concepts

Shaping Text

Ordering Text

Measuring and Positioning Text

Supporting Text Manipulation

Performing Text Layout in a Java™ Application

Managing Text Layout

Laying Out Text

Displaying Dual Carets

Moving the Caret

Hit Testing

Highlighting Selections

Querying Layout Metrics

Drawing Text Across Multiple Lines

Implementing a Custom Text Layout Mechanism

Creating Font Derivations

Imaging

Interfaces and Classes

Imaging Interfaces

Image Data Classes

Image Operation Classes

Sample Model Classes

Color Model Classes

Exception Classes

Immediate Mode Imaging Concepts

Terminology

Using BufferedImages

Creating a BufferedImage

Drawing in an Offscreen Buffer

Manipulating BufferedImage Data Directly

Filtering a BufferedImage

Rendering a BufferedImage

Managing and Manipulating Rasters

Creating a Raster

Parent and Child Rasters

Operations on a Raster

The WritableRaster Subclass

Image Data and DataBuffers

Extracting Pixel Data from a SampleModel

ColorModels and Color Data

Lookup Table

Image Processing and Enhancement

Using an Image Processing Operation

Color

Classes

Color Concepts

Describing Colors

Mapping Colors through sRGB and CIEXYZ

Printing

Interfaces and Classes

Printing Concepts

Supporting Printing

Page Painters

Printable Jobs and Pageable Jobs

Typical Life-Cycle of a PrinterJob

Dialogs

Printing with Printables

Using Graphics2D for Rendering

Printing a File

Printing with Pageables and Books

Using a Pageable Job

Using Multiple Page Painters

Contents | Previous | Next
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Contents | Previous | Next

Chapter 6

Color

Color imaging is one of the fundamental components of any graphics system, and it is often a source of great complexity in the imaging model. The Java 2D™ API provides support for high-quality color output that is easy to use and allows advanced clients to make sophisticated use of color.

The key color management classes in the Java 2D API are ColorSpace, Color, ColorModel:

  • A ColorSpace represents a system for measuring colors, typically using three separate numerical values or components. The ColorSpace class contains methods for converting between the color space and two standard color spaces, CIEXYZ and RGB.
  • A Color is a fixed color, defined in terms of its components in a particular ColorSpace. To draw a Shape in a color, such as red, you pass a Color object representing that color to the Graphics2D context. Color is defined in the java.awt package.
  • A ColorModel describes a particular way that pixel values are mapped to colors. A ColorModel is typically associated with an Image or BufferedImage and provides the information necessary to correctly interpret the pixel values. ColorModel is defined in the java.awt.image package.

6.1 Classes

Class | Description
ColorSpace | Identifies the color space of a Color object, Image, BufferedImage, or GraphicsDevice. Has methods to transform between RGB and CIEXYZ color spaces.
ICC_ColorSpace | Extends: ColorSpace Represents device-independent and device-dependent color spaces based on the ICC Profile Format Specification.
ICC_Profile | A representation of color profile data for device independent and device dependent color spaces based on the ICC Profile Format Specification.
ICC_ProfileGray | Extends: ICC_Profile A representation of color space type gray.
ICC_ProfileRGB | Extends: ICC_Profile A representation of color space type RGB.

6.2 Color Concepts

A ColorModel is used to interpret pixel data in an image. This includes mapping components in the bands of an image to components of a particular color space. It might also involve extracting pixel components from packed pixel data, retrieving multiple components from a single band using masks, and converting pixel data through a lookup table.

To determine the color value of a particular pixel in an image, you need to know how color information is encoded in each pixel. The ColorModel associated with an image encapsulates the data and methods necessary for translating a pixel value to and from its constituent color components.

6.2.0 Color

The Java 2D™ API provides two color models in addition to the DirectColorModel and IndexColorModel defined in the JDK 1.1 software release:

  • ComponentColorModel can handle an arbitrary ColorSpace and an array of color components to match the ColorSpace. This model can be used to represent most color models on most types of GraphicsDevices.
  • PackedColorModel is a base class for models that represent pixel values that have their color components embedded directly in the bits of an integer pixel. A PackedColorModel stores the packing information that describes how color and alpha components are extracted from the channel.The DirectColorModel in the JDK 1.1 software release is a PackedColorModel.

6.2.0.1 ColorSpace

A ColorSpace object represents a system for measuring colors, typically using three separate numeric values. For example, RGB and CMYK are color spaces. A ColorSpace object serves as a colorspace tag that identifies the specific color space of a Color object or, through a ColorModel object, of an Image, BufferedImage, or GraphicsConfiguration. ColorSpace provides methods that transform Colors in a specific color space to and from sRGB and to and from a well-defined CIEXYZ color space.

All ColorSpace objects must be able to map a color from the represented color space into sRGB and transform an sRGB color into the represented color space. Since every Color contains a ColorSpace object, set explicitly or by default, every Color can also be converted to sRGB. Every GraphicsConfiguration is associated with a ColorSpace object that in turn has an associated ColorSpace. A color specified in any color space can be displayed by any device by mapping it through sRGB as an intermediate color space.

The methods used for this process are toRGB and fromRGB:

  • toRGB transforms a Color in the represented color space to a Color in sRGB.
  • fromRGB takes a Color in sRGB and transforms it into the represented color space.

Though mapping through sRGB always works, it's not always the best solution. For one thing, sRGB cannot represent every color in the full gamut of CIEXYZ colors. If a color is specified in some space that has a different gamut (spectrum of representable colors) than sRGB, then using sRGB as an intermediate space results in a loss of information. To address this problem, the ColorSpace class can map colors to and from another color space, the “conversion space” CIEXYZ.

The methods toCIEXYZ and fromCIEXYZ map color values from the represented color space to the conversion space. These methods support conversions between any two color spaces at a reasonably high degree of accuracy, one Color at a time. However, it is expected that Java 2D API implementations will support high-performance conversion based on underlying platform color-management systems, operating on entire images. (See ColorConvertOp in “Imaging” on page 67.)

Figure 6-1 and Figure 6-2 illustrate the process of translating a color specified in a CMYK color space for display on an RGB color monitor. Figure 6-1 shows a mapping through sRGB. As this figure illustrates, the translation of the CMYK color to an RGB color is not exact because of a gamut mismatch. 1

The previous context describes this graphic.

Figure 6-1 Mapping Through sRGB

Figure 6-2 shows the same process using CIEXYZ as the conversion space. When CIEXYZ is used, the color is passed through accurately.

The previous context describes this graphic.

Figure 6-2 Mapping Through CIEXYZ

6.2.0.2 ICC_Profile and ICC_ColorSpace

ColorSpace is actually an abstract class. The Java 2D API provides one implementation, ICC_ColorSpace, which is based on ICC Profile data as represented by the ICC_Profile class. You can define your own subclasses to represent arbitrary color spaces, as long as the methods discussed above are implemented. However, most developers can simply use the default sRGB ColorSpace or color spaces that are represented by commonly available ICC Profiles, such as profiles for monitors and printers, or profiles embedded in image data.

“ColorSpace” on page 90 describes how ColorSpace objects represent a color space and how colors in the represented space can be mapped to and from a conversion space. Color management systems are often used to handle the mapping between color spaces. A typical color management system (CMS) manages ICC profiles, which are similar to ColorSpace objects; ICC profiles describe an input space and a connection space, and define how to map between them. Color management systems are very good at figuring out how to map a color tagged with one profile into the color space of another profile.

The Java 2D API defines a class called ICC_Profile that holds data for an arbitrary ICC Profile. ICC_ColorSpace is an implementation of the abstract ColorSpace class. ICC_ColorSpace objects can be constructed from ICC_Profiles. (There are some limitations—not all ICC Profiles are appropriate for defining an ICC_ColorSpace).

ICC_Profile has several subclasses that correspond to specific color space types, such as ICC_ProfileRGB and ICC_ProfileGray. Each subclass of ICC_Profile has a well-defined input space (such as an RGB space) and a well-defined connection space (like CIEXYZ). The Java 2D API can use a platform's CMS to access color profiles for various devices such as scanners, printers, and monitors. It can also use the CMS to find the best mapping between profiles.

6.2.1 Describing Colors

The Color class provides a description of a color in a particular color space. An instance of Color contains the value of the color components and a ColorSpace object. Because a ColorSpace object can be specified in addition to the color components when a new instance of Color is created, the Color class can handle colors in any color space.

The Color class has a number of methods that support a proposed standard RGB color space called sRGB (see http://www.w3.org/pub/WWW/Graphics/Color/sRGB.html). sRGB is the default color space for the Java 2D API. Several constructors defined by the Color class omit the ColorSpace parameter. These constructors assume that the color's RGB values are defined in sRGB, and use a default instance of ColorSpace to represent that space.

The Java 2D API uses sRGB as a convenience to application programmers, not as a reference color space for color conversion. Many applications are primarily concerned with RGB images and monitors, and defining a standard RGB color space makes writing such applications easier. The ColorSpace class defines the methods toRGB and fromRGB so that developers can easily retrieve colors in this standard space. These methods are not intended to be used for highly accurate color correction or conversions. See “ColorSpace” on page 90 for more information.

To create a color in a color space other than sRGB, you use the Color constructor that takes a ColorSpace object and an array of floats that represent the color components appropriate to that space. The ColorSpace object identifies the color space.

To display a rectangle of a certain color, such as the process color cyan, you need a way to describe this color to the system. There are a number of different ways to describe a color; for example, a color could be described as a set of red, green, and blue (RGB) components, or a set of cyan, magenta, yellow, and black (CMYK) components. These different techniques for specifying colors are called color spaces.

As you probably know, colors on a computer screen are generated by blending different amounts of red, green, and blue light. Therefore, using an RGB color space is standard for imaging on computer monitors. Similarly, four-color process printing uses cyan, magenta, yellow, and black ink to produce color on a printed page; the printed colors are specified as percentages in a CMYK color space.

Due to the prevalence of computer monitors and color printing, RGB and CMYK color spaces are both commonly used to describe colors. However, both types of color spaces have a fundamental drawback—they are device-dependent. The cyan ink used by one printer might not exactly match the cyan ink used by another. Similarly, a color described as an RGB color might look blue on one monitor and purplish on another.

6.2.2 Mapping Colors through sRGB and CIEXYZ

The Java 2D API refers to RGB and CMYK as color space types. A particular model of monitor with its particular phosphors defines its own RGB color space. Similarly, a particular model of printer has its own CMYK color space. Different RGB or CMYK color spaces can be related to each other through a device-independent color space.

Standards for the device-independent specification of color have been defined by the International Commission on Illumination (CIE). The most commonly used device-independent color space is the three-component XYZ color space developed by CIE. When you specify a color using CIEXYZ, you are insulated from device dependencies.

Unfortunately, it’s not always practical to describe colors in the CIEXYZ color space—there are valid reasons for representing colors in other color spaces. To obtain consistent results when a color is represented using a device-dependent color space such as a particular RGB space, it is necessary to show how that RGB space relates to a device-independent space like CIEXYZ.

One way to map between color spaces is to attach information to the spaces that describes how the device-dependent space relates to the device-independent space. This additional information is called a profile. A commonly used type of color profile is the ICC Color Profile, as defined by the International Color Consortium. For details, see the ICC Profile Format Specification, version 3.4 available at http://www.color.org.

Figure 6-3 illustrates how a solid color and a scanned image are passed to the Java 2D API, and how they are displayed by various output devices. As you can see in Figure 6-3, both the input color and the image have profiles attached.

using profiles to map between color spaces

Figure 6-3 Using Profiles to Map Between Color Spaces

6.2.2.1 Color Matching

Once the API has an accurately specified color, it must reproduce that color on an output device, such as a monitor or printer. These devices have imaging characteristics of their own that must be taken into account to make sure that they produce the correct results. Another profile is associated with each output device to describe how the colors need to be transformed to produce accurate results.

Achieving consistent and accurate color requires that both input colors and output devices be profiled against a standard color space. For example, an input color could be mapped from its original color space into a standard device-independent space, and then mapped from that space to the output device’s color space. In many respects, the transformation of colors mimics the transformation of graphical objects in an (x, y) coordinate space. In both cases, a transformation is used to specify coordinates in a “standard” space and then map those coordinates to a device-specific space for output.

1Of course, the colors used in these diagrams are illustrative, not accurate. The point is that colors might not be mapped accurately between color spaces unless an appropriate conversion space is used.

Contents | Previous | Next
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Contents | Previous | Next

Chapter 4

Fonts and Text Layout

You can use the Java 2D™ API transformation and drawing mechanisms with text strings. In addition, the Java 2D API provides text-related classes that support fine-grain font control and sophisticated text layout. These include an enhanced Font class and the new TextLayout class.

This chapter focuses on the new font and text layout capabilities supported through interfaces and classes in java.awt, and java.awt.font. For more information about using these features, see the 2D Text Tutorial that’s available through the Java Developer Connection at http://java.sun.com/developer/onlineTraining/Media/2DText/

For information about text analysis and internationalization, refer to the java.text documentation and the “Writing Global Programs” track in the Java Tutorial. For information about using the text layout mechanisms implemented in Swing, see the java.awt.swing.text documentation and “Using the JFC/Swing Packages” in the Java Tutorial.

Note: The information on international text layout contained in this chapter is based on the paper International Text in JDK 1.2 by Mark Davis, Doug Felt, and John Raley, copyright 1997, Taligent, Inc.

4.1 Interfaces and Classes

The following tables list the key font and text layout interfaces and classes. Most of these interfaces and classes are part of the java.awt.font package. Some, like Font, are part of the java.awt package to maintain backward compatibility with earlier versions of the JDK.

Interface | Description
MultipleMaster | Represents Type 1 Multiple Master fonts. Implemented by Font objects that are multiple master fonts to enable access to multiple master design controls.
OpenType | Represents Open Type and True Type fonts. Implemented by Font objects that are Open Type or True Type fonts to enable access to the font’s sfnt tables.
Class | Description
Font (java.awt) | Represents an instance of a font face from the collection of font faces available on the host system. Supports the specification of detailed font information and provides access to information about the font and its glyphs.
FontRenderContext | Encapsulates the information necessary to correctly measure text.
GlyphJustificationInfo | Represents information about the justification properties of a glyph, such as weight, priority, absorb, and limit.
GlyphMetrics | Provides metrics for a single glyph.
GlyphVector | A collection of glyphs and their positions.
GraphicAttribute | Base class for a TextLayout attribute that specifies a graphic to be embedded within text. Implemented by ShapeGraphicAttribute and ImageGraphicAttribute, which enable Shapes and Images to be embedded in a TextLayout. Can be subclassed to implement custom character replacement graphics.
ImageGraphicAttribute | Extends: GraphicAttribute A GraphicsAttribute used to draw Images within a TextLayout.
LineBreakMeasurer | Breaks a block of text that spans multiple lines into TextLayout objects that fit within a specified line length.
LineMetrics | Provides access to the font metrics needed to lay out characters along a line and to lay out a set of lines. These metrics include ascent, descent, leading, height, and baseline information.
ShapeGraphicAttribute | Extends: GraphicAttribute A GraphicsAttribute used to draw Shapes within a TextLayout.
TextAttribute | Defines attribute keys and values used for text rendering.
TextHitInfo | Represents hit test information for characters in a TextLayout.
TextLayout | Implements: Cloneable Provides an immutable graphical representation of styled character data, including bidirectional text.

4.2 Font Concepts

The Font class has been enhanced to support the specification of detailed font information and enable the use of sophisticated typographic features.

A Font object represents an instance of a font face from the collection of font faces available on the system. Examples of common font faces include Helvetica Bold and Courier Bold Italic.

Three names are associated with a Font—its logical name, family name, and font face name:

  • A Font object’s logical name is a name mapped onto one of the specific fonts available on the platform. The logical font name is the name used to specify a Font in JDK 1.1 and earlier releases. When specifying a Font in Java™ 2 SDK, you should use the font face name instead of the logical name.You can get the logical name from the Font by calling getName. To get a list of the logical names that are mapped onto the specific fonts available on a platform, call java.awt.Toolkit.getFontList.
  • A Font object’s family name is the name of the font family that determines the typographic design across several faces, such as Helvetica. You retrieve the family name through the getFamily method.
  • A Font objects’ font face name refers to an actual font installed on the system. This is the name you should use when specifying a font in Java 2 SDK. It’s often referred to as just the font name. You can retrieve the font name by calling getFontName. To determine which font faces are available on the system, you can call GraphicsEnvironment.getAllFonts.

You can access information about a Font through the getAttributes method. A Font’s attributes include its name, size, transform, and font features such as weight and posture.

A LineMetrics object encapsulates the measurement information associated with a Font, such as its ascent, descent, and leading:

  • Ascent is the distance from the baseline to the ascender line. This distance represents the typical height of capital letters, but some characters might extend above the ascender line.
  • Descent is the distance from the baseline to the descender line. The lowest point of most characters will fall within the descent, but some characters might extend below the descender line.
  • Leading is the recommended distance from the bottom of the descender line to the top of the next line.

The previous context describes this graphic.

Figure 4-1 Line Metrics

This information is used to properly position characters along a line, and to position lines relative to one another. You can access these line metrics through the getAscent, getDescent, and getLeading methods. You can also access information about a Font’s height, baseline, and underline and strikethrough characteristics through LineMetrics.

4.3 Text Layout Concepts

Before a piece of text can be displayed, it must be properly shaped and positioned using the appropriate glyphs and ligatures. This process is referred to as text layout. The text layout process involves:

  • Shaping text using the appropriate glyphs and ligatures.
  • Properly ordering the text.
  • Measuring and positioning the text.

The information used to lay out text is also necessary for performing text operations such as caret positioning, hit detection, and highlighting.

To develop software that can be deployed in international markets, text must be laid out in different languages in a way that conforms to the rules of the appropriate writing system.

4.3.1 Shaping Text

A glyph is the visual representation of one or more characters. The shape, size, and position of a glyph is dependent on its context. Many different glyphs can be used to represent a single character or combination of characters, depending on the font and style.

For example, in handwritten cursive text, a particular character can take on different shapes depending on how it is connected to adjacent characters.

In some writing systems, particularly Arabic, the context of a glyph must always be taken into account. Unlike in English, cursive forms are mandatory in Arabic; it is unacceptable to present text without using cursive forms.

Depending on the context, these cursive forms can differ radically in shape. For example, the Arabic letter heh has the four cursive forms shown in Figure 4-2.

Illustration of unconnected, connect on right, connect on both sides and connect on left cursive forms in Arabic.

Figure 4-2 Cursive Forms in Arabic

Although these four forms are quite different from one another, such cursive shape-changing is not fundamentally different from cursive writing in English.

In some contexts, two glyphs can change shape even more radically and merge to form a single glyph. This type of merged glyph is called a ligature. For example, most English fonts contain the ligature fi shown in Figure 4-3. The merged glyph takes into account the overhang on the letter f and combines the characters in a natural-looking way, instead of simply letting the letters collide.

The previous context describes this graphic.

Figure 4-3 English Ligatures

Ligatures are also used in Arabic and the use of some ligatures is mandatory—it is unacceptable to present certain character combinations without using the appropriate ligature. When ligatures are formed from Arabic characters, the shapes change even more radically than they do in English. For example, Figure 4-4 illustrates how two Arabic characters are combined into a single ligature when they appear together.

The previous context describes this graphic.

Figure 4-4 Arabic Ligatures

4.3.2 Ordering Text

In the Java™ programming language, text is encoded using Unicode character encoding. Text that uses Unicode character encoding is stored in memory in logical order. Logical order is the order in which characters and words are read and written. The logical order is not necessarily the same as the visual order, the order in which the corresponding glyphs are displayed.

The visual order for glyphs in a particular writing system (script) is called the script order. For example, the script order for Roman text is left-to-right and the script order for Arabic and Hebrew is right-to-left.

Some writing systems have rules in addition to script order for arranging glyphs and words on lines of text. For example, Arabic and Hebrew numbers run left to right, even though the letters run right to left. (This means that Arabic and Hebrew, even with no embedded English text, are truly bidirectional.)

A writing system’s visual order must be maintained even when languages are mixed together. This is illustrated in Figure 4-5, which displays an Arabic phrase embedded in an English sentence.

Note: In this and subsequent examples, Arabic and Hebrew text is represented by uppercase letters and spaces are represented by underscores. Each illustration contains two parts: a representation of the characters stored in memory (the characters in logical order) followed by a representation of how those characters are displayed (the characters in visual order). The numbers below the character boxes indicate the insertion offsets.

The previous context describes this graphic.

Figure 4-5 Bidirectional Text

Even though they are part of an English sentence, the Arabic words are displayed in the Arabic script order, right-to-left. Because the italicized Arabic word is logically after the Arabic in plain text, it is visually to the left of the plain text.

When a line with a mixture of left-to-right and right-to-left text is displayed, the base direction is significant. The base direction is the script order of the predominant writing system. For example, if the text is primarily English with some embedded Arabic, then the base direction is left-to-right. If the text is primarily Arabic with some embedded English or numbers, then the base direction is right-to-left.

The base direction determines the order in which segments of text with a common direction are displayed. In the example shown in Figure 4-5, the base direction is left-to-right. There are three directional runs in this example: the English text at the beginning of the sentence runs left to right, the Arabic text runs right to left, and the period runs left to right.

Graphics are often embedded in the flow of text. These inline graphics behave like glyphs in terms of how they affect the text flow and line wrapping. Such inline graphics need to be positioned using the same bidirectional layout algorithm so that they appear in the proper location in the flow of characters.

For more information about the precise algorithm used to order glyphs within a line, see the description of the Bidirectional Algorithm in The Unicode Standard, Version 2.0, Section 3.11.

4.3.3 Measuring and Positioning Text

Unless you are working with a monospace font, different characters in a font have different widths. This means that all positioning and measuring of text has to take into account exactly which characters are used, not just how many. For example, to right-align a column of numbers displayed in a proportional font, you can’t simply use extra spaces to position the text. To properly align the column, you need to know the exact width of each number so that you can adjust accordingly.

Text is often displayed using multiple fonts and styles, such as bold or italic. In this case, even the same character can have different shapes and widths, depending on how it is styled. To properly position, measure, and render text, you need to keep track of each individual character and the style applied to that character. Fortunately, TextLayout does this for you.

To properly display text in languages such as Hebrew and Arabic, each individual character needs to be measured and positioned within the context of neighboring characters. Because the shapes and positions of the characters can change depending on the context, measuring and positioning such text without taking the context into account produces unacceptable results.

4.3.4 Supporting Text Manipulation

To allow the user to edit the text that is displayed, you must be able to:

  • Display a caret that indicates where new characters will be inserted when the user enters text.
  • Move the caret and insertion point in response to user input.
  • Detect user selections (hit detection).
  • Highlight selected text.

4.3.4.1 Displaying Carets

In editable text, a caret is used to graphically represent the current insertion point, the position in the text where new characters will be inserted. Typically, a caret is shown as a blinking vertical bar between two glyphs. New characters are inserted and displayed at the caret's location.

Calculating the caret position can be complicated, particularly for bidirectional text. Insertion offsets on directional boundaries have two possible caret positions because the two glyphs that correspond to the character offset are not displayed adjacent to one another. This is illustrated in Figure 4-6. In this figure, the carets are shown as square brackets to indicate the glyph to which the caret corresponds.

The previous context describes this graphic.

Figure 4-6 Dual Carets

Character offset 8 corresponds to the location after the _ and before the A. If the user enters an Arabic character, its glyph is displayed to the right of (before) the A; if the user enters an English character, its glyph is displayed to the right of (after) the _.

To handle this situation, some systems display dual carets, a strong (primary) caret and a weak (secondary) caret. The strong caret indicates where an inserted character will be displayed when that character's direction is the same as the base direction of the text. The weak caret shows where an inserted character will be displayed when the character's direction is the opposite of the base direction. TextLayout automatically supports dual carets; JTextComponent does not.

When you’re working with bidirectional text, you can’t simply add the widths of the glyphs before a character offset to calculate the caret position. If you did, the caret would be drawn in the wrong place, as shown in Figure 4-7.

The previous context describes this graphic.

Figure 4-7 Caret Drawn Incorrectly

For the caret to be properly positioned, the widths of the glyphs to the left of the offset need to be added and the current context taken into account. Unless the context is taken into account, the glyph metrics won’t necessarily match the display. (The context can affect which glyphs are used.)

4.3.4.2 Moving Carets

All text editors allow the user to move the caret with the arrow keys. Users expect the caret to move in the direction of the pressed arrow key. In left-to-right text, moving the insertion offset is simple: the right arrow key increases the insertion offset by one and the left arrow key decreases it by one. In bidirectional text or in text with ligatures, this behavior would cause the caret to jump across glyphs at direction boundaries and move in the reverse direction within different directional runs.

To move the caret smoothly through bidirectional text, you need to take into account the direction of the text runs. You can’t simply increment the insertion offset when the right arrow key is pressed and decrement it when the left arrow key is pressed. If the current insertion offset is within a run of right-to-left characters, the right arrow key should decrease the insertion offset, and the left arrow key should increase it.

Moving the caret across a directional boundary is even more complicated. Figure 4-8 illustrates what happens when a directional boundary is crossed when the user is navigating with the arrow key. Stepping three positions to the right in the displayed text corresponds to moving to the character offsets 7, 19, then 18.

The previous context describes this graphic.

Figure 4-8 Caret Movement

Certain glyphs should never have a caret between them; instead, the caret should move as though the glyphs represented a single character. For example, there should never be a caret between an o and an umlaut if they are represented by two separate characters. (See The Unicode Standard, Version 2.0, Chapter 5, for more information.)

TextLayout provides methods (getNextRightHit and getNextLeftHit) that enable you to easily move the caret smoothly through bidirectional text.

4.3.4.3 Hit Testing

Often, a location in device space must be converted to a text offset. For example, when a user clicks the mouse on selectable text, the location of the mouse is converted to a text offset and used as one end of the selection range. Logically, this is the inverse of positioning a caret.

When you’re working with bidirectional text, a single visual location in the display can correspond to two different offsets in the source text, as shown in Figure 4-9.

The previous context describes this graphic.

Figure 4-9 Hit Testing Bidirectional Text

Because a single visual location can correspond to two different offsets, hit testing bidirectional text isn’t just a matter of measuring glyph widths until the glyph at the correct location is found and then mapping that position back to a character offset. Detecting the side that the hit was on helps distinguish between the two alternatives.

You can perform hit testing using TextLayout.hitTestChar. Hit information is encapsulated in a TextHitInfo object and includes information about the side that the hit was on.

4.3.4.4 Highlighting Selections

A selected range of characters is represented graphically by a highlight region, an area in which glyphs are displayed with inverse video or against a different background color.

Highlight regions, like carets, are more complicated for bidirectional text than for monodirectional text. In bidirectional text, a contiguous range of characters might not have a contiguous highlight region when displayed. Conversely, a highlight region showing a visually contiguous range of glyphs might not correspond to a single, contiguous range of characters.

This results in two strategies for highlighting selections in bidirectional text:

  • Logical highlighting —with logical highlighting, the selected characters are always contiguous in the text model, and the highlight region is allowed to be discontiguous. For an example of logical highlighting, see Figure 4-10.
  • Visual highlighting—with visual highlighting, there might be more than one range of selected characters, but the highlight region is always contiguous. For an example of visual highlighting, see Figure 4-11.

Illustration of logical highlighting (contiguous characters)

Figure 4-10 Logical Highlighting (contiguous characters)

Illustration of visual highlighting (contiguous highlight region)

Figure 4-11 Visual Highlighting (contiguous highlight region)

Logical highlighting is simpler to implement, since the selected characters are always contiguous in the text.

4.3.5 Performing Text Layout in a Java™ Application

Depending on which Java™ APIs you use, you can have as little or as much control over text layout as you need:

  • If you just want to display a block of text or need an editable text control, you can use JTextComponent, which will perform the text layout for you. JTextComponent is designed to handle the needs of most international applications and supports bidirectional text For more information about JTextComponent, see “Using the JFC/Swing Packages” in the Java Tutorial.
  • If you want to display a simple text string, you can call Graphics2D.drawString and let Java 2D™ lay out the string for you. You can also use drawString to render styled strings and strings that contain bidirectional text. For more information about rendering text through Graphics2D, see “Rendering Graphics Primitives” on page 37.
  • If you want to implement your own text editing routines, you can use TextLayout to manage text layout, highlighting, and hit detection. The facilities provided by TextLayout handle most common cases, including text strings with mixed fonts, mixed languages, and bidirectional text. For more information about using TextLayout, see “Managing Text Layout” on page 58.
  • If you want total control over how text is shaped and positioned, you can construct your own GlyphVectors using Font and then render them through Graphics2D. For more information about implementing your own text layout mechanism, see “Implementing a Custom Text Layout Mechanism” on page 64.

Generally, you do not need to perform text layout operations yourself. For most applications, JTextComponent is the best solution for displaying static and editable text. However, JTextComponent does not support the display of dual carets or discontiguous selections in bidirectional text. If your application requires these features, or you prefer to implement your own text editing routines, you can use the Java 2D text layout APIs.

4.4 Managing Text Layout

The TextLayout class supports text that contains multiple styles and characters from different writing systems, including Arabic and Hebrew. (Arabic and Hebrew are particularly difficult to display because you must reshape and reorder the text to achieve an acceptable representation.)

TextLayout simplifies the process of displaying and measuring text even if you are working with English-only text. By using TextLayout, you can achieve high-quality typography with no extra effort.

Text Layout Performance
TextLayout is designed so that there is no significant performance impact when it’s used to display simple, monodirectional text. There is some additional processing overhead when TextLayout is used to display Arabic or Hebrew text. However, it’s typically on the order of microseconds per character and is dominated by the execution of normal drawing code.

The TextLayout class manages the positioning and ordering of glyphs for you. You can use TextLayout to:

  • Lay out monodirectional and bidirectional text
  • Display and move carets
  • Perform hit testing on text
  • Highlight text selections

In some situations, you might want to compute the text layout yourself, so that you can control exactly which glyphs are used and where they are placed. Using information such as glyph sizes, kerning tables, and ligature information, you can construct your own algorithms for computing the text layout, bypassing the system’s layout mechanism. For more information, see “Implementing a Custom Text Layout Mechanism” on page 64.

4.4.1 Laying Out Text

TextLayout automatically lays out text, including bidirectional (BIDI) text, with the correct shaping and ordering. To correctly shape and order the glyphs representing a line of text, TextLayout must know the full context of the text:

  • If the text fits on a single line, such as a single-word label for a button or a line in a dialog box, you can construct a TextLayout directly from the text.
  • If you have more text than can fit on a single line or want to break text on a single line into tabbed segments, you cannot construct a TextLayout directly. You must use a LineBreakMeasurer to provide sufficient context.

The base direction of the text is normally set by an attribute (style) on the text. If that attribute is missing, TextLayout follows the Unicode bidirectional algorithm and derives the base direction from the initial characters in the paragraph.

4.4.2 Displaying Dual Carets

TextLayout maintains caret information such as the caret Shape, position, and angle. You can use this information to easily display carets in both monodirectional and bidirectional text. When you’re drawing carets for bidirectional text, using TextLayout ensures that the carets will be positioned correctly.

TextLayout provides default caret Shapes and automatically supports dual carets. For italic and oblique glyphs, TextLayout produces angled carets, as shown in Figure 4-12. These caret positions are also used as the boundaries between glyphs for highlighting and hit testing, which helps produce a consistent user experience.

The previous context describes this graphic.

Figure 4-12 Angled Carets

Given an insertion offset, the getCaretShapes method returns a two-element array of Shapes: element 0 contains the strong caret and element 1 contains the weak caret, if one exists. To display dual carets, you simply draw both caret Shapes; the carets will be automatically be rendered in the correct positions.

If you want to use custom caret Shapes, you can retrieve the position and angle of the carets from the TextLayout and draw them yourself.

In the following example, the default strong and weak caret Shapes are drawn in different colors. This is a common way to differentiate dual carets.

Shape[] caretShapes = layout.getCaretShapes(hit);
g2.setColor(PRIMARY_CARET_COLOR);
g2.draw(caretShapes[0]);
if (caretShapes[1] != null){
  g2.setColor(SECONDARY_CARET_COLOR);
  g2.draw(caretShapes[1]);
}

4.4.3 Moving the Caret

You can also use TextLayout to determine the resulting insertion offset when a user presses the left or right arrow key. Given a TextHitInfo object that represents the current insertion offset, the getNextRightHit method returns a TextHitInfo object that represents the correct insertion offset if the right arrow key is pressed. The getNextLeftHit method provides the same information for the left arrow key.

In the following example, the current insertion offset is moved in response to a right arrow key.

TextHitInfo newInsertionOffset =             layout.getNextRightHit(insertionOffset);
if (newInsertionOffset != null) {
  Shape[] caretShapes =
          layout.getCaretShapes(newInsertionOffset);
  // draw carets
  ...
  insertionOffset = newInsertionOffset;
}

4.4.4 Hit Testing

TextLayout provides a simple mechanism for hit testing text. The hitTestChar method takes x and y coordinates from the mouse as arguments and returns a TextHitInfo object. The TextHitInfo contains the insertion offset for the specified position and the side that the hit was on. The insertion offset is the offset closest to the hit: if the hit is past the end of the line, the offset at the end of the line is returned.

In the following example, hitTestChar is called on a TextLayout and then getInsertIndex is used to retrieve the offset.

TextHitInfo hit = layout.hitTestChar(x, y);
int insertIndex = hit.getInsertIndex();

4.4.5 Highlighting Selections

You can get a Shape that represents the highlight region from the TextLayout. TextLayout automatically takes the context into account when calculating the dimensions of the highlight region. TextLayout supports both logical and visual highlighting.

In the following example, the highlight region is filled with the highlight color and then the TextLayout is drawn over the filled region. This is one simple way to display highlighted text.

Shape highlightRegion = layout.getLogicalHighlightShape(hit1,      hit2);
graphics.setColor(HIGHLIGHT_COLOR);
graphics.fill(highlightRegion);
graphics.drawString(layout, 0, 0);

4.4.6 Querying Layout Metrics

TextLayout provides access to graphical metrics for the entire range of text it represents. Metrics available from TextLayout include the ascent, descent, leading, advance, visible advance, and the bounding rectangle.

More than one Font can be associated with a TextLayout: different style runs can use different fonts. The ascent and descent values for a TextLayout are the maximum values of all of the fonts used in the TextLayout. The computation of the TextLayout's leading is more complicated; it’s not just the maximum leading value.

The advance of a TextLayout is its length: the distance from the left edge of the leftmost glyph to the right edge of the rightmost glyph. The advance is sometimes referred to as the total advance. The visible advance is the length of the TextLayout without its trailing whitespace.

The bounding box of a TextLayout encloses all of the text in the layout. It includes all the visible glyphs and the caret boundaries. (Some of these might hang over the origin or origin + advance). The bounding box is relative to the origin of the TextLayout, not to any particular screen position.

In the following example, the text in a TextLayout is drawn within the layout’s bounding box.

graphics.drawString(layout, 0, 0);
Rectangle2D bounds = layout.getBounds();
graphics.drawRect(bounds.getX()-1, bounds.getY()-1,
         bounds.getWidth()+2, bounds.getHeight()+2);

4.4.7 Drawing Text Across Multiple Lines

TextLayout can also be used to display a piece of text that spans multiple lines. For example, you might take a paragraph of text, line-wrap the text to a certain width, and display the paragraph as multiple lines of text.

To do this, you do not directly create the TextLayouts that represent each line of text—LineBreakMeasurer generates them for you. Bidirectional ordering cannot always be performed correctly unless all of the text in a paragraph is available. LineBreakMeasurer encapsulates enough information about the context to produce correct TextLayouts.

When text is displayed across multiple lines, the length of the lines is usually determined by the width of the display area. Line breaking (line wrapping) is the process of determining where lines begin and end, given a graphical width in which the lines must fit.

The most common strategy is to place as many words on each line as will fit. This strategy is implemented in LineBreakMeasurer. Other more complex line break strategies use hyphenation, or attempt to minimize the differences in line length within paragraphs. The Java 2D™ API does not provide implementations of these strategies.

To break a paragraph of text into lines, you construct a LineBreakMeasurer with the entire paragraph and then call nextLayout to step through the text and generate TextLayouts for each line.

To do this, LineBreakMeasurer maintains an offset within the text. Initially, the offset is at the beginning of the text. Each call to nextLayout moves the offset by the character count of the TextLayout that was created. When this offset reaches the end of the text, nextLayout returns null.

The visible advance of each TextLayout that the LineBreakMeasurer creates doesn’t exceed the specified line width. By varying the width you specify when you call nextLayout, you can break text to fit complicated areas, such as an HTML page with images in fixed positions or tab-stop fields. You can also pass in a BreakIterator to tell LineBreakMeasurer where valid breakpoints are; if you don't supply one the BreakIterator for the default locale is used.

In the following example, a bilingual text segment is drawn line by line. The lines are aligned to either to the left margin or right margin, depending on whether the base text direction is left-to-right or right-to-left.

Point2D pen = initialPosition;
LineBreakMeasurer measurer = new LineBreakMeasurer(styledText, myBreakIterator);
while (true) {
  TextLayout layout = measurer.nextLayout(wrappingWidth);
  if (layout == null) break;
    pen.y += layout.getAscent();
    float dx = 0;
    if (layout.isLeftToRight())
      dx = wrappingWidth - layout.getAdvance();
    layout.draw(graphics, pen.x + dx, pen.y);
    pen.y += layout.getDescent() + layout.getLeading();
}

4.5 Implementing a Custom Text Layout Mechanism

The GlyphVector class provides a way to display the results of custom layout mechanisms. A GlyphVector object can be thought of as the output of an algorithm that takes a string and computes exactly how the string should be displayed. The system has a built-in algorithm and the Java 2D™ API lets advanced clients define their own algorithms.

A GlyphVector object is basically an array of glyphs and glyph locations. Glyphs are used instead of characters to provide total control over layout characteristics such as kerning and ligatures. For example, when displaying the string “final”, you might want to replace the leading fi substring with the ligature fi. In this case, the GlyphVector object will have fewer glyphs than the number of characters in the original string.

Figure 4-13 and Figure 4-14 illustrate how GlyphVector objects are used by layout mechanisms. Figure 4-13 shows the default layout mechanism. When drawString is called on a String, the built-in layout algorithm:

  • Uses the current Font in the Graphics2D context to determine which glyphs to use.
  • Calculates where each glyph should be placed.
  • Stores the resulting glyph and position information in a GlyphVector.
  • Passes the GlyphVector to a glyph rendering routine that does the actual drawing.

The previous context describes this graphic.

Figure 4-13 Using the Built-in Layout Algorithm

Figure 4-14 shows the process for using a custom layout algorithm. To use a custom layout algorithm, you must assemble all of the information necessary to lay out the text. The basic process is the same:

  • Using the Font, determine which glyphs to use
  • Determine where to place the glyphs
  • Store this layout information in a GlyphVector

To render the text, you pass the GlyphVector to drawString, which in turn passes it to the glyph renderer. In Figure 4-14, the custom layout algorithm replaces the fi substring with the ligature fi.

using a custom layout algorithm

Figure 4-14 Using a Custom Layout Algorithm

4.6 Creating Font Derivations

Using the Font.deriveFont methods, you can create a new Font object with different attributes from an existing Font object. Often, a transform is applied to the existing Font to create a new derived Font. To do this, you:

  • Create a Font object.,
  • Create the AffineTransform you want to apply to the Font.
  • Call Font.deriveFont, passing in the AffineTransform.

In this way, you could easily create a Font in a custom size or a skewed version of an existing Font.

In the following code excerpt, an AffineTransform is applied to create a skewed version of the font Helvetica. The new derived font is then used to render a string.

        // Create a transformation for the font.
AffineTransform fontAT = new AffineTransform();
fontAT.setToShear(-1.2, 0.0);
// Create a Font Object.
Font theFont = new Font("Helvetica", Font.PLAIN, 1);
// Derive a new font using the shear transform
theDerivedFont = theFont.deriveFont(fontAT);
// Add the derived font to the Graphics2D context
g2.setFont(theDerivedFont);
// Render a string using the derived font
g2.drawString(“Java”, 0.0f, 0.0f);

Contents | Previous | Next
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Contents | Previous | Next

Chapter 3

Geometries

The Java 2D™ API provides several classes that define common geometric objects, such as points, lines, curves, and rectangles. These new geometry classes are part of the java.awt.geom package. For backward compatibility, the geometry classes that existed in previous versions of the JDK software, such as Rectangle, Point, and Polygon, remain in the java.awt package.

The Java 2D API geometries such as GeneralPath, Arc2D, and Rectangle2D implement the Shape interface defined in java.awt. Shape provides a common protocol for describing and inspecting geometric path objects. A new interface, PathIterator, defines methods for retrieving elements from a geometry.

Using the geometry classes, you can easily define and manipulate virtually any two-dimensional object.

3.1 Interfaces and Classes

The following tables list the key geometry interfaces and classes. Most of these interfaces and classes are part of the java.awt.geom package. Some, like Shape, are part of the java.awt package, primarily to maintain backward compatibility with earlier versions of the JDK software.

Interface | Description
PathIterator | Defines methods for retrieving elements from a path.
Shape (java.awt) | Provides a common set of methods for describing and inspecting geometric path objects. Implemented by GeneralPath and other geometry classes.

Class
Description
Arc2D
Arc2D.Double
Arc2D.Float
Extends: RectangularShape
Represents an arc defined by a bounding rectangle, start angle, angular extent, and a closure type. Implemented to specify arcs in float and double precision: Arc2D.Float and Arc2D.Double.
Area
Implements: Shape, Cloneable
Represents an area geometry that supports boolean operations.
CubicCurve2D
CubicCurve2D.Double
CubicCurve2D.Float
Implements: Shape
Represents a cubic parametric curve segment in (w) coordinate space. Implemented to specify cubic curves in float and double precision: CubicCurve2D.Float and CubicCurve2D.Double.
Dimension2D
Encapsulates a width and height dimension. Abstract superclass for all objects that store a 2D dimension.
Ellipse2D
Ellipse2D.Double
Ellipse2D.Float
Extends: RectangularShape
Represents an ellipse defined by a bounding rectangle. Implemented to specify ellipses in float and double precision: Ellipse2D.Float and Ellipse2D.Double.
FlatteningPathIterator
Returns a flattened view of a PathIterator object.
Can be used to provide flattening behavior for Shapes that don’t perform the interpolation calculations themselves.
GeneralPath
Implements: Shape
Represents a geometric path constructed from lines and quadratic and cubic curves.
Line2D
Line2D.Double
Line2D.Float
Implements: Shape
Represents a line segment in (x, y) coordinate space. Implemented to specify lines in float and double precision: Line2D.Float and Line2D.Double.
Point2D
Point2D.Double
Point2D.Float
A point representing a location in (x,y) coordinate space. Implemented to specify points in float and double precision: Point2D.Float and Point2D.Double.
QuadCurve2D
QuadCurve2D.Double
QuadCurve2D.Float
Implements: Shape
Represents a quadratic parametric curve segment in (x, y) coordinate space. Implemented to specify quadratic curves in float and double precision: QuadCurve2D.Float and QuadCurve2D.Double.
Rectangle2D
Rectangle2D.Double
Rectangle2D.Float
Extends: RectangularShape
Represents a rectangle defined by a location (x, y) and dimension (w x h). Implemented to specify rectangles in float and double precision: Rectangle2D.Float and Rectangle2D.Double.
RectangularShape
Implements: Shape
Provides common manipulation routines for operating on shapes that have rectangular bounds.
RoundRectangle2D
RoundRectangle2D.Double
RoundRectangle2D.Float
Extends: RectangularShape
Represents a rectangle with rounded corners defined by a location (x, y), a dimension (w x h), and the width and height of the corner arc. Implemented to specify round rectangles in float and double precision: RoundRectangle2D.Float and RoundRectangle2D.Double.

3.2 Geometry Concepts

A Shape is an instance of any class that implements the Shape interface, such as GeneralPath or Rectangle2D.Float. A Shape’s contour (outline) is referred to as its path.

When a Shape is drawn, the pen style defined by the Stroke object in the Graphics2D context is applied to the Shape’s path. When a Shape is filled, the Paint in the Graphics2D context is applied to the area within its path. For more information, see “Rendering with Graphics2D” on page 15.

A Shape’s path can be also used to define a clipping path. A clipping path determines what pixels are rendered—only those pixels that lie within the area defined by the clipping path are rendered. The clipping path is part of the Graphics2D context. For more information, see “Setting the Clipping Path” on page 32.

A GeneralPath is a shape that can be used to represent any two-dimensional object that can be constructed from lines and quadratic or cubic curves. For convenience, java.awt.geom provides additional implementations of the Shape interface that represent common geometric objects such as rectangles, ellipses, arcs, and curves. The Java2D™ API also provides a special type of shape that supports constructive area geometry.

3.2.1 Constructive Area Geometry

Constructive Area Geometry (CAG) is the process of creating new geometric objects by performing boolean operations on existing objects. In the Java 2D API, a special type of Shape called an Area supports boolean operations. You can construct an Area from any Shape.

Areas support the following Boolean operations:

  • Union
  • Intersection
  • Subtraction
  • Exclusive OR (XOR)

These operations are illustrated in Figure 3-1.

Graphic illustration of union, intersection, subtraction and exclusive OR boolean operations

Figure 3-1 Boolean Operations

3.2.2 Bounds and Hit Testing

A bounding box is a rectangle that fully encloses a shape’s geometry. Bounding boxes are used to determine whether or not an object has been selected or “hit” by the user.

The Shape interface defines two methods for retrieving a shape’s bounding box, getBounds and getBounds2D. The getBounds2D method returns a Rectangle2D instead of a Rectangle, providing a higher-precision description of the shape’s bounding box.

Shape also provides methods for determining whether or not:

  • A specified point lies within the bounds of the shape (contains)
  • A specified rectangle lies totally within the bounds of the shape (contains)
  • A specified rectangle intersects the shape (intersects)

3.3 Combining Areas to Create New Shapes

Areas can be used to quickly construct complex Shapes from simple shapes such as circles and squares. To create a new complex Shape by combining Areas:

  • Using Shapes, construct the Areas to be combined.
  • Call the appropriate Boolean operators: add, subtract, intersect, exclusiveOr.

For example, CAG could be used to create a pear like that shown in Figure 3-2 .

The following context describes the graphic

Figure 3-2 Pear constructed from circles

The body of the pear is constructed by performing a union operation on two overlapping Areas: a circle and an oval. The leaves are each created by performing an intersection on two overlapping circles and then joined into a single Shape through a union operation. Overlapping circles are also used to construct the stem through two subtraction operations.

3.4 Creating a Custom Shape

You can implement the Shape interface to create a class that defines a new type of shape. It doesn’t matter how you represent the shape internally, as long as you can implement the Shape interface methods. The Shape must be able to generate a path that specifies its contour.

For example, you could create a simple implementation of Shape that represents polygons as arrays of points. Once the polygon is built, it could be passed to draw, setClip, or any other method that expects a Shape object as an argument.

The PolygonPath class must implement the Shape interface methods:

  • contains
  • getBounds
  • getBounds2D
  • getPathIterator
  • intersects

Contents | Previous | Next
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Contents | Previous | Next

Chapter 5

Imaging

The Java 2D™ API supports three imaging models

  • The producer/consumer (push) model provided in previous versions of the JDK software.
  • The immediate mode model introduced in the Java™ 2 SDK software release.
  • The pipeline (pull) model compatible with the immediate mode model and that will be fully implemented in the forthcoming Java Advanced Imaging API.

The following table contrasts the features of each of these imaging models.
Push Model
Immediate Mode Image Buffer Model
Pull Model
Major Interfaces/Classes
  • Image
  • ImageProducer
  • ImageConsumer
  • ImageObserver
     (JDK 1.0.x, 1.1.x)
  • BufferedImage
  • Raster
  • BufferedImageOp
  • RasterOp
    (JavaTM 2D API)
  • RenderableImage
  • RenderableImageOp
    (Java 2D API)
  • RenderedOp
  • RenderableOp
  • TiledImage
    (Java Advanced Imaging API)
Pros
  • Processing driven by image availability (e.g. over network)
  • Images processed incrementally
  • Simplest programming interface
  • Commonly used model
  • Stores/processes only required data
  • Allows lazy evaluation
Cons
  • Requires transfer (but not processing)
  • More complex programming interface
  • Requires memory allocation of complete images
  • Requires processing of complete images
  • More complex programming interface
  • More complex implementation

This chapter focuses on the objects and techniques of the immediate mode imaging model. The immediate mode imaging classes and interfaces of the Java 2D API provide techniques for dealing with pixel mapped images whose data is stored in memory. This API supports accessing image data in a variety of storage formats and manipulating image data through several types of filtering operations.

5.1 Interfaces and Classes

The immediate mode imaging APIs in the Java 2D™ API can be grouped into six categories: interfaces, image data classes, image operation classes, sample model classes, color model classes, and exceptions.

5.1.1 Imaging Interfaces

Interface | Description
BufferedImageOp | Describes single-input/single-output operations performed on BufferedImage objects. Implemented by AffineTransformOp, ColorConvertOp, ConvolveOp, LookupOp, and RescaleOp.
RasterOp | Defines single-input/single-output operations performed on Raster objects. Implemented by AffineTransformOp, BandCombineOp, ColorConvertOp, ConvolveOp, LookupOp, and RescaleOp.
RenderedImage | Defines a common protocol for objects that contain or can produce image data in the form of Rasters.
WritableRenderedImage | Extends: RenderedImage Defines a common protocol for objects that contain or can produce image data in the form of Rasters which can be modified.
TileObserver | Defines a protocol for objects that want to be notified when the modification state of a WritableRenderedImage changes.

5.1.2 Image Data Classes

Class | Description
BufferedImage | Extends: Image Implements: WriteableRenderedImage An image with an accessible data buffer. A BufferedImage has a ColorModel and a Raster of image data.
ByteLookupTable | Extends: LookupTable A LookupTable that contains byte data.
DataBuffer | Wraps one or more data arrays holding pixel data. Each data array is called a bank.
DataBufferByte | Extends: DataBuffer (Final) A data buffer that stores bytes of data. (Used in Java Advanced Imaging API)
DataBufferInt | Extends: DataBuffer (Final)) A data buffer that stores integer data.(Used in Java Advanced Imaging API)
DataBufferShort | Extends: DataBuffer (Final) A data buffer that stores short data.(Used in Java Advanced Imaging API)
DataBufferUShort | Extends: DataBuffer (Final) A data buffer that stores unsigned short data.
Kernel | A matrix that describes how an input pixel and its surrounding pixels affect the value of an output pixel in a ConvolveOp filtering operation.
LookupTable | Extends: Object A table that maps values from single-banded pixel data to color values.
Raster | A rectangular array of pixels from which you can retrieve image data. A Raster contains a DataBuffer and a SampleModel.
ShortLookupTable | Extends: LookupTable A lookup table that contains short data.
WritableRaster | Extends: Raster A Raster that you can modify.

5.1.3 Image Operation Classes

Class | Description
AffineTransformOp | Implements: BufferedImageOp, RasterOp A class that defines an affine transform to perform a linear mapping from 2D coordinates in a source Image or Raster to 2D coordinates in the destination image or Raster. This class can perform either bilinear or nearest neighbor affine transform operations.
BandCombineOp | Implements: RasterOp Using a specified matrix, this operation performs an arbitrary linear combination of bands in a Raster.
BufferedImageFilter | Extends: ImageFilter An ImageFilter that provides a simple means of using a BufferedImageOp (a single-source/single-destination image operator) to filter a BufferedImage or Raster.
ColorConvertOp | Implements: BufferedImageOp, RasterOp Performs a pixel-by-pixel color conversion of the data in the source image.
ConvolveOp | Implements: BufferedImageOp, RasterOp Uses a Kernel to perform a convolution on the source image. A convolution is a spatial operation where the pixels surrounding the input pixel are multiplied by a kernel value to generate the value of the output pixel. The Kernel mathematically defines the relationship between the pixels in the immediate neighborhood of the input pixel and the output pixel.
LookupOp | Implements: BufferedImageOp, RasterOp Performs a lookup operation from the source to the destination. For Rasters, the lookup operates on sample values. For BufferedImages, the lookup operates on color and alpha components.
RescaleOp | Implements: BufferedImageOp, RasterOp Performs a pixel-by-pixel rescaling of the data in the source image by multiplying each pixel value by a scale factor and then adding an offset.

5.1.4 Sample Model Classes

Class | Description
BandedSampleModel | Extends: ComponentSampleModel (Final) Provides access to image data stored with like samples stored as bands in separate banks of a DataBuffer. A pixel consists of one sample from each band.
ComponentSampleModel | Extends: SampleModel Provides access to image data stored with each sample of a pixel residing in a separate element of a DataBuffer. Different types of pixel interleaving are supported.
MultiPixelPackedSampleModel | Extends: SampleModel Provides access to image data stored with multiple one-sample pixels packed into one element of a DataBuffer.
PixelInterleavedSampleModel | Extends: ComponentSampleModel Provides access to image data stored with the sample data for each pixel in adjacent elements of the data array, and all elements in a single bank of a DataBuffer.
SampleModel | An abstract class that defines a mechanism for extracting sample data from an image without knowing how the underlying data is stored in a DataBuffer.
SinglePixelPackedSampleModel | Extends: SampleModel Provides access to image data stored with all the samples belonging to an individual pixel packed into one element of a DataBuffer.

5.1.5 Color Model Classes

Class | Description
ColorModel | Implements: Transparency JDK1.1 class. An abstract class that defines methods for translating from image pixel values to color components such as red, green, and blue.
ComponentColorModel | Extends: ColorModel A ColorModel that can handle an arbitrary ColorSpace and an array of color components to match the ColorSpace. This class can be used to represent most color models on most types of GraphicsDevices.
DirectColorModel | Extends: PackedColorModel JDK1.1 class. A ColorModel that represents pixel values that have RGB color components embedded directly in the bits of the pixel. This color model is similar to an X11 TrueColor visual. The default RGB ColorModel returned by ColorModel.getRGBdefault is a DirectColorModel.
IndexColorModel | Extends: ColorModel JDK1.1 class. A ColorModel that represents pixel values that are indices into a fixed color map in the sRGB ColorSpace.
PackedColorModel | Extends: ColorModel An abstract ColorModel that represents pixel values that have color components embedded directly in the bits of a pixel. DirectColorModel extends PackedColorModel to support pixels that contain RGB color components.

5.1.6 Exception Classes

Class | Description
ImagingOpException | Extends: RuntimeException Thrown if one of the BufferedImageOp or RasterOp filter methods can’t process the image.
RasterFormatException | Extends: RuntimeException Thrown if there is invalid layout information in the Raster.

5.2 Immediate Mode Imaging Concepts

The immediate mode imaging model supports fixed-resolution images stored in memory. The model also supports filtering operations on image data. A number of classes and interfaces are used in this model.

The following context describes this graphic.

Figure 5-1 BufferedImage and supporting classes

As shown in Figure 5-1, BufferedImage provides general image management. A BufferedImage can be created directly in memory and used to hold and manipulate image data retrieved from a file or URL. A BufferedImage can be displayed using any Graphics2D object for a screen device, or rendered to any other destination using appropriate Graphics2D context. A BufferedImage object contains two other objects: a Raster and a ColorModel.

The Raster class provides image data management. It represents the rectangular coordinates of the image, maintains image data in memory, and provides a mechanism for creating multiple subimages from a single image data buffer. It also provides methods for accessing specific pixels within an image. A Raster object contains two other objects, a DataBuffer and a SampleModel.

The DataBuffer class holds pixel data in memory.

The SampleModel class interprets data in the buffer and provides it as individual pixels or rectangular ranges of pixels.

The ColorModel class provides a color interpretation of pixel data provided by the image’s sample model.

The image package provides additional classes that define filtering operations on BufferedImage and Raster objects. Each image processing operation is embodied in a class that implements the BufferedImageOp interface, the RasterOp interface, or both interfaces. The operation class defines filter methods that performs the actual image manipulation.

Figure 5-2 illustrates the basic model for Java 2D™ API image processing:

Flow diagram shows that the source image flows through an image-processing operation before becoming the destination image.

Figure 5-2 Image Processing Model

The operations supported include:

  • Affine transformation
  • Amplitude scaling
  • Lookup-table modification
  • Linear combination of bands
  • Color conversion
  • Convolution

Note that if you’re interested just in displaying and manipulating images, you only need to understand the BufferedImage class and the filtering operation classes. On the other hand, if you’re planning to write filters or otherwise directly access image data, you’ll need to understand the classes associated with BufferedImage.

5.2.1 Terminology

Here are some terms used throughout the following discussions:

Data Elements: primitive types used as units of storage of image data. Data elements are individual members of a DataBuffer array. The layout of elements in the data buffer is independent of the interpretation of the data as pixels by an image’s SampleModel.

Samples: distinct members of the pixels of an image. A SampleModel provides a mechanism for converting elements in the DataBuffer to pixels and their samples. The samples of a pixel may represent primary values in a particular color model. For example, a pixel in an RGB color model consists of three samples: red, green, and blue.

Components: values of pixels independent of color interpretation. The distinction between component and sample is useful with IndexColorModel, where pixel components are indexes into the LookupTable.

Band: the set of all samples of one type in an image, such as all red samples or all green samples. Pixel data can be stored in a number of ways, the two supported in the Java 2D API being banded and pixel interleaved. Banded storage organizes image data by bands, and a pixel is made up of sample data from the same position in each band. Pixel interleaved storage organizes image data by pixels, with a single array containing all pixels, and bands consisting of the set of samples at the same index position in each pixel.

Primaries: distinct members of a color value in a specific color model; for example the RGB model forms color values from the primaries red, green, and blue.

5.3 Using BufferedImages

The BufferedImage class is the main class supporting the immediate imaging mode. It manages an image in memory, providing ways to store pixel data, interpret pixel data, and to render the pixel data to a Graphics or Graphics2D context.

5.3.1 Creating a BufferedImage

To create a BufferedImage, call the Component.createImage method; this returns a BufferedImage whose drawing characteristics match those of the component used to create it—the created image is opaque, has the foreground and background colors of the Component, and you can’t adjust the transparency of the image. You could use this technique when you want to do double buffered drawing for animation in a component; the discussion “Drawing in an Offscreen Buffer” on page 79 gives more details.

    public Graphics2D createDemoGraphics2D(Graphics g) {
        Graphics2D g2 = null;
        int width = getSize().width;
        int height = getSize().height;

        if (offImg == null || offImg.getWidth() != width ||
                        offImg.getHeight() != height) {
            offImg = (BufferedImage) createImage(width, height);
        }

        if (offImg != null) {
            g2 = offImg.createGraphics();
            g2.setBackground(getBackground());
        }

        // .. clear canvas ..
        g2.clearRect(0, 0, width, height);

        return g2;
    }

You can also create a blank BufferedImage in memory using one of several constructor methods provided.

5.3.2 Drawing in an Offscreen Buffer

The BufferedImage class can be used to prepare graphic elements offscreen then copy them to the screen. This technique is especially useful when a graphic is complex or used repeatedly. For example, if you want to display a complicated shape several times, you could draw it once into an offscreen buffer and then copy it to different locations in the window. By drawing the shape once and copying it, you can display the graphics more quickly.

The java.awt package facilitates the use of offscreen buffers by letting you draw to an Image object the same way that you draw to a window. All of the Java 2D™ API rendering features can be used when drawing to offscreen images.

Offscreen buffers are often used for animation. For example, you could use an offscreen buffer to draw an object once and then move it around in a window. Similarly, you could use an offscreen buffer to provide feedback as a user moves a graphic using the mouse. Instead of redrawing the graphic at every mouse location, you could draw the graphic once to an offscreen buffer, and then copy it to the mouse location as the user drags the mouse.1

The following context describes this graphic.

Figure 5-3 Using an Offscreen Buffer

Figure 5-3 demonstrates how a program can draw to an offscreen image and then copy that image into a window multiple times. The last time the image is copied, it is transformed. Note that transforming the image instead of redrawing it with the transformation might produce unsatisfactory results.

5.3.2.1 Creating an Offscreen Buffer

The simplest way to create an image that you can use as an offscreen buffer is to use the Component.createImage method.

By creating an image whose color space, depth, and pixel layout exactly match the window into which you are drawing, the image can be efficiently blitted to a graphics device. This allows drawImage to do its job quickly.

You can also construct a BufferedImage object directly to use as an offscreen buffer. This is useful when you need control over the offscreen image’s type or transparency.

BufferedImage supports several predefined image types:

  • TYPE_3BYTE_BGR
  • TYPE_4BYTE_ABGR
  • TYPE_4BYTE_ABGR_PRE
  • TYPE_BYTE_BINARY
  • TYPE_BYTE_GRAY
  • TYPE_BYTE_INDEXED
  • TYPE_CUSTOM
  • TYPE_INT_ARGB_PRE
  • TYPE_INT_ARGB
  • TYPE_INT_BGR
  • TYPE_INT_RGB
  • TYPE_USHORT_555_RGB
  • TYPE_USHORT_565_RGB
  • TYPE_INT_GRAY

A BufferedImage object can contain an alpha channel. In Figure 5-3, an alpha channel is used to distinguish painted and unpainted areas, allowing an irregular shape to appear over graphics that have already been painted (in this case, a shaded rectangle). In other cases, you might use alpha channel to blend the colors of the new image into those in the existing image.

Note: unless you need alpha image data for transparency, as with the irregularly shaped images shown in Figure 5-2, you should avoid creating an off-screen buffer with alpha. Using alpha where it’s unnecessary slows rendering performance.

GraphicsConfiguration provides convenience methods that automatically create buffered images in a format compatible with your configuration. You can also query the graphics configuration associated with the graphics device on which the window resides to get the information you need to construct a compatible BufferedImage object.

5.3.2.2 Drawing in an Offscreen Buffer

To draw in a buffered image, you call its BufferedImage.createGraphics method, which returns a Graphics2D object. With this object, you can call all of the Graphics2D methods to draw graphics primitives, place text, and render other images in the image. This drawing technique supports dithering and other enhancements provided by the 2D imaging package. The following code illustrates the use of offscreen buffering:

    public void update(Graphics g){
        Graphics2D g2 = (Graphics2D)g;
        if(firstTime){
            Dimension dim = getSize();
            int w = dim.width;
            int h = dim.height;
            area = new Rectangle(dim);
            bi = (BufferedImage)createImage(w, h);
            big = bi.createGraphics();
            rect.setLocation(w/2-50, h/2-25);
            big.setStroke(new BasicStroke(8.0f));
            firstTime = false;
        }

        // Clears the rectangle that was previously drawn.
        big.setColor(Color.white);
        big.clearRect(0, 0, area.width, area.height);

        // Draws and fills the newly positioned rectangle to the buffer.
        big.setPaint(strokePolka);
        big.draw(rect);
        big.setPaint(fillPolka);
        big.fill(rect);

        // Draws the buffered image to the screen.
        g2.drawImage(bi, 0, 0, this);

    }

5.3.3 Manipulating BufferedImage Data Directly

In addition to drawing directly in a BufferedImage, you can directly access and manipulate the image’s pixel data in a couple of ways. These are useful if you’re implementing the BufferedImageOp filtering interface, as described in “Image Processing and Enhancement” on page 84.

You can use the BufferedImage.setRGB methods to directly set the value of a pixel or a pixel array to a specific RGB value. Note that no dithering is performed when you modify pixels directly. You can also manipulate pixel data by manipulating a WritableRaster object associated with a BufferedImage (see“Managing and Manipulating Rasters” on page 80).

5.3.4 Filtering a BufferedImage

You can apply a filtering operation to a BufferedImage using an object that implements BufferedImageOp interface. Filtering and the classes that provide this filtering interface are discussed in “Image Processing and Enhancement” on page 84.

5.3.5 Rendering a BufferedImage

To render a buffered image into a specific context, call one of the drawImage method of the context’s Graphics object. For example, when rendering within a Component.paint method, you call drawImage on the graphics object passed to the method.

    public void paint(Graphics g) {

        if (getSize().width <= 0 || getSize().height <= 0)
            return;

        Graphics2D g2 = (Graphics2D) g;

        if (offImg != null && isShowing())  {
            g2.drawImage(offImg, 0, 0, this);
        }
    }

5.4 Managing and Manipulating Rasters

A BufferedImage object uses a Raster to manage its rectangular array of pixel data. The Raster class defines fields for the image’s coordinate system—width, height, and origin. A Raster object itself uses two objects to manage the pixel data, a DataBuffer and a SampleModel. The DataBuffer is the object that stores pixel data for the raster (as described on page 82), and the SampleModel provides the interpretation of pixel data from the DataBuffer (as described on page 82).

5.4.1 Creating a Raster

In most cases, you don’t need to create a Raster directly, since one is supplied with any BufferedImage that you create in memory. However, one of the BufferedImage constructor methods allows you to create a Raster by passing in a WritableRaster.

The Raster class provides a number of static factory methods for creating Rasters with the DataBuffers and SampleModels you specify. You can use these factories when implementing RasterOp filtering classes.

5.4.2 Parent and Child Rasters

The Raster class incorporates the concept of parent and child rasters. This can improve storage efficiency by allowing you to construct any number of buffered images from the same parent. The parent and its children all refer to the same data buffer, and each child has a specific offset and bounds to identify its image location in the buffer. A child identifies its ownership through its getParent method.

To create a subraster, you use the Raster.createSubRaster method.When you create a subraster, you identify the area of its parent that it covers and its offset from the parent’s origin.

5.4.3 Operations on a Raster

The Raster class defines a number of ways to access pixels and pixel data. These are useful when you’re implementing the RasterOp interface, which provides raster-level filtering and manipulation of image data, or when implementing any method that needs to perform low-level pixel manipulation.

The Raster.getPixel methods let you get an individual pixel, which is returned as individual samples in an array. The Raster.getDataElements methods return a specified run of uninterpreted image data from the DataBuffer. The Raster.getSample method returns samples of an individual pixel. The getSamples method returns a band for a particular region of an image.

In addition to these methods, you can also access the data buffer and the sample model through instance variables of the Raster class. These objects provide additional ways to access and interpret the Raster’s pixel data.

5.4.4 The WritableRaster Subclass

The WritableRaster subclass provides methods for setting pixel data and samples. The Raster associated with a BufferedImage is actually a WritableRaster, thus providing full access to manipulate its pixel data.

5.5 Image Data and DataBuffers

The DataBuffer belonging to a Raster represents an array of image data. When you create a Raster directly or through the BufferedImage constructors, you specify a width and height in pixels, along with a SampleModel for the image data. This information is used to create a DataBuffer of the appropriate data type and size.

There are three subclasses of DataBuffer, each representing a different type of data element:

  • DataBufferByte (represents 8-bit values)
  • DataBufferInt (represents 32-bit values)
  • DataBufferShort (represents 16-bit values)
  • DataBufferUShort (represents unsigned short values)

As defined earlier, elements are the discrete members of the array of the data buffer, and components or samples are the discrete values that together make up a pixel. There can be various mappings between a particular type of element in a DataBuffer and a particular type of pixel represented by a SampleModel. It is the responsibility of the various SampleModel subclasses to implement that mapping and provide a way to get specific pixels from a specific DataBuffer.

DataBuffer constructors provide ways to create buffers of a specific size and a specific number of banks.

While you can access image data in a DataBuffer directly, it’s generally easier and more convenient to do so through the methods of the Raster and WritableRaster classes.

5.6 Extracting Pixel Data from a SampleModel

The abstract SampleModel class defines methods for extracting samples of an image without knowing how the underlying data is stored. The class provides fields for tracking the height and width of the image data in the associated DataBuffer, and for describing the number of bands and the data type of that buffer. SampleModel methods provide image data as a collection of pixels, with each pixel consisting of a number of samples or components.

The java.awt.image package provides five types of sample models:

  • ComponentSampleModel—used to extract pixels from images that store sample data in separate data array elements in one bank of a DataBuffer.
  • BandedSampleModel—used to extract pixels from images that store each sample in a separate data element with bands stored in a sequence of data elements
  • PixelInterleavedSampleModel—used to extract pixels from images that store each sample in a separate data element with pixels stored in a sequence of data elements.
  • MultiPixelPackedSampleModel—used to extract pixels from single banded images that store multiple one-sample pixels in one data element.
  • SinglePixelPackedSampleModel—used to extract samples from images that store sample data for a single pixel in one data array element in the first bank of a DataBuffer.

Pixel data presented by the SampleModel may or may not correlate directly to a color data representation of a particular color model, depending on the data source. For example, in photographic image data, the samples may represent RGB data. In image data from a medical imaging device, samples can represent different types of data such as temperature or bone density.

There are three categories of methods for accessing image data. The getPixel methods return a whole pixel as an array, with one entry for each sample. The getDataElement methods provide access to the raw, uninterpreted data stored in the DataBuffer. The getSample methods provide access to pixel components for a specific band.

5.7 ColorModels and Color Data

In addition to the Raster object for managing image data, the BufferedImage class includes a ColorModel for interpreting that data as color pixel values. The abstract ColorModel class defines methods for turning an image’s pixel data into a color value in its associated ColorSpace.

The java.awt.image package provides four types of color models:

  • PackedColorModel—An abstract ColorModel that represents pixel values that have color components embedded directly in the bits of an integer pixel. A DirectColorModel is a subclass of PackedColorModel.
  • DirectColorModel—a ColorModel that represents pixel values that have RGB color components embedded directly in the bits of the pixel itself. DirectColorModel model is similar to an X11 TrueColor visual.
  • ComponentColorModel—a ColorModel that can handle an arbitrary ColorSpace and an array of color components to match the ColorSpace.
  • IndexColorModel—a ColorModel that represents pixel values that are indices into a fixed color map in the sRGB color space.

ComponentColorModel and PackedColorModel are new in the Java™ 2 SDK software release.

Based on data in the DataBuffer, the SampleModel provides the ColorModel with a pixel, which the ColorModel then interprets as a color.

5.7.1 Lookup Table

A lookup table contains data for one or more channels or image components; for example, separate arrays for R, G, and B. The java.awt.image package defines two types of lookup tables that extend the abstract LookupTable class, one that contains byte data and one that contains short data (ByteLookupTable and ShortLookupData).

5.8 Image Processing and Enhancement

The image package provides a pair of interfaces that define operations on BufferedImage and Raster objects: BufferedImageOp and RasterOp.

The classes that implement these interfaces include AffineTransformOp, BandCombineOp, ColorConvertOp, ConvolveOp, LookupOp, RescaleOp. These classes can be used to geometrically transform, blur, sharpen, enhance contrast, threshold, and color correct images.

Figure 5-4 illustrates edge detection and enhancement, an operation that emphasizes sharp changes in intensity within an image. Edge detection is commonly used in medical imaging and mapping applications. Edge detection is used to increase the contrast between adjacent structures in an image, allowing the viewer to discriminate greater detail.

The previous context describes this graphic.

Figure 5-4 Edge detection and enhancement

The following code illustrates edge detection:

float[] elements = { 0.0f, -1.0f, 0.0f,
                    -1.0f, 4.f, -1.0f,
                    0.0f, -1.0f, 0.0f};
...

BufferedImage bimg = new BufferedImage(bw,bh,BufferedImage.TYPE_INT_RGB);
Kernel kernel = new Kernel(3, 3, elements);
ConvolveOp cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP,                                             null);
cop.filter(bi,bimg);

Figure 5-5 demonstrates lookup table manipulation. A lookup operation can be used to alter individual components of a pixel.

The previous context describes this graphic.

Figure 5-5 Lookup-table Manipulation

The following code demonstrates Lookup-table manipulation:

        byte reverse[] = new byte[256];
   for (int j=0; j<200; j++){
                reverse[j]=(byte)(256-j);
        }
        ByteLookupTable blut=new ByteLookupTable(0, reverse);
        LookupOp lop = new LookupOp(blut, null);
   lop.filter(bi,bimg);

Figure 5-6 illustrates rescaling. Rescaling can increase or decrease the intensity of all points. Rescaling can be used to increase the dynamic range of an otherwise neutral image, bringing out detail in a region that appears neutral or flat.

The previous context describes this graphic.

Figure 5-6 Rescaling

The following code snippet illustrates rescaling:

        RescaleOp rop = new RescaleOp(1.5f, 1.0f, null);
        rop.filter(bi,bimg);

5.8.1 Using an Image Processing Operation

Convolution is the process that underlies most spatial filtering algorithms. Convolution is the process of weighting or averaging the value of each pixel in an image with the values of neighboring pixels.This allows each output pixel to be affected by the immediate neighborhood in a way that can be mathematically specified with a kernel. Figure 5-7 illustrates Convolution.

The previous context describes this graphic.

Figure 5-7 Blurring with Convolution

The following code fragment illustrates how to use one of the image processing classes, ConvolveOp. In this example, each pixel in the source image is averaged equally with the eight pixels that surround it.

float weight = 1.0f/9.0f;float[] elements = new float[9]; // create 2D array// fill the array with nine equal elements
for (i = 0; i < 9; i++) {   elements[i] = weight;}// use the array of elements as argument to create a Kernelprivate Kernel myKernel = new Kernel(3, 3, elements);public ConvolveOp simpleBlur = new ConvolveOp(myKernel);

// sourceImage and destImage are instances of BufferedImagesimpleBlur.filter(sourceImage, destImage) // blur the image

The variable simpleBlur contains a new instance of ConvolveOp that implements a blur operation on a BufferedImage or a Raster. Suppose that sourceImage and destImage are two instances of BufferedImage. When you call filter, the core method of the ConvolveOp class, it sets the value of each pixel in the destination image by averaging the corresponding pixel in the source image with the eight pixels that surround it.

The convolution kernel in this example could be represented by the following matrix, with elements specified to four significant figures:

A 3 by 3 matrix with all values being 0.1111.

When an image is convolved, the value of each pixel in the destination image is calculated by using the kernel as a set of weights to average the pixel’s value with the values of surrounding pixels. This operation is performed on each channel of the image.

The following formula shows how the weights in the kernel are associated with the pixels in the source image when the convolution is performed. Each value in the kernel is tied to a spatial position in the image.

A 3 by 3 matrix. The first row values are i minus 1, j minus 1, i, j minus 1, and i plus 1, j minus1. The second row values are i minus 1, j, i, j, and i plus1, j. The third row values are i minus 1, j plus 1, i, j plus 1, and i plus 1, j plus 1.

The value of a destination pixel is the sum of the products of the weights in the kernel multiplied by the value of the corresponding source pixel. For many simple operations, the kernel is a matrix that is square and symmetric, and the sum of its weights adds up to one.2

The convolution kernel in this example is relatively simple. It weights each pixel from the source image equally. By choosing a kernel that weights the source image at a higher or lower level, a program can increase or decrease the intensity of the destination image. The Kernel object, which is set in the ConvolveOp constructor, determines the type of filtering that is performed. By setting other values, you can perform other types of convolutions, including blurring (such as Gaussian blur, radial blur, and motion blur), sharpening, and smoothing operations. Figure 5-8 illustrates sharpening using Convolution.

The previous context describes this graphic.

Figure 5-8 Sharpening with Convolution

The following code snippet illustrates sharpening with Convolution:

float[] elements = { 0.0f, -1.0f, 0.0f,
                    -1.0f,  5.f, -1.0f,
                     0.0f, -1.0f,  0.0f};
...

Kernel kernel = new Kernel(3,3,elements);
ConvolveOp cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP,                                                                                                          null);
        cop.filter(bi,bimg);

1It is up to the programmer to “erase” the previous version of the image before making a new copy at a new location. This can be done by redrawing the background or copying the background from another offscreen buffer.
2If the sum of the weights in the matrix is one, the intensity of the destination image is unchanged from the source.

Contents | Previous | Next
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Contents | Previous | Next

Chapter 1

Java 2DTM API Overview

The Java 2D™ API enhances the graphics, text, and imaging capabilities of the Abstract Windowing Toolkit (AWT), enabling the development of richer user interfaces and new types of Java™ applications.

Along with these richer graphics, font, and image APIs, the Java 2D API supports enhanced color definition and composition, hit detection on arbitrary geometric shapes and text, and a uniform rendering model for printers and display devices.

The Java 2D API also enables the creation of advanced graphics libraries, such as CAD-CAM libraries and graphics or imaging special effects libraries, as well as the creation of image and graphic file read/write filters.

When used in conjunction with the Java Media Framework and other Java Media APIs, the Java 2D APIs can be used to create and display animations and other multimedia presentations. The Java Animation and Java Media Framework APIs rely on the Java 2D API for rendering support.

1.1 Enhanced Graphics, Text, and Imaging

Early versions of the AWT provided a simple rendering package suitable for rendering common HTML pages, but not full-featured enough for complex graphics, text, or imaging. As a simplified rendering package, the early AWT embodied specific cases of more general rendering concepts. The Java 2D™ API provides a more flexible, full-featured rendering package by expanding the AWT to support more general graphics and rendering operations.

For example, through the Graphics class you can draw rectangles, ovals, and polygons. Graphics2D enhances the concept of geometric rendering by providing a mechanism for rendering virtually any geometric shape. Similarly, with the Java 2D API you can draw styled lines of any width and fill geometric shapes with virtually any texture.

Geometric shapes are provided through implementations of the Shape interface, for example Rectangle2D and Ellipse2D. Curves and arcs are also specific implementations of Shape.

Fill and pen styles are provided through implementations of the Paint and Stroke interfaces, for example BasicStroke, GradientPaint, TexturePaint, and Color.

AffineTransform defines linear transformations of 2D coordinates, including scale, translate, rotate, and shear.

Clip regions are defined by the same implementations of the Shape interface that are used to define general clipping regions, for example Rectangle2D and GeneralPath.

Color composition is provided by implementations of the Composite interface, for example AlphaComposite.

A Font is defined by collections of Glyphs, which are in turn defined by individual Shapes.

1.2 Rendering Model

The basic graphics rendering model has not changed with the addition of the Java 2D™ APIs. To render a graphic, you set up the graphics context and invoke a rendering method on the Graphics object.

The Java 2D API class Graphics2D extends Graphics to support more graphics attributes and provide new rendering methods. Setting up a Graphics2D context is described in “Rendering with Graphics2D” on page 15.

The Java 2D API automatically compensates for differences in rendering devices and provides a uniform rendering model across different types of devices. At the application level, the rendering process is the same whether the target rendering device is a display or a printer.

With the JavaTM 2 SDK, version 1.3 relsease and later, the Java 2D API provides support for multi-screen environments. See Section 1.2.1, “Coordinate Systems” and “Rendering in a Multi-Screen Environment” on page 39 for more information.

1.2.1 Coordinate Systems

The Java 2D API maintains two coordinate systems:

  • User space is a device-independent, logical coordinate system. Applications use this coordinate system exclusively; all geometries passed into Java 2D rendering routines are specified in user space.
  • Device space is a device-dependent coordinate system that varies according to the target rendering device.
    In a multi-screen environment with a virtual desktop where a window can span more than one physical screen device, the device coordinate system that’s used is the coordinate system of the virtual desktop that encompasses all of the screens. For more information on how the Java 2DTM API supports multi-screen environments, see “Rendering in a Multi-Screen Environment” on page 39.

The Java 2D system automatically performs the necessary conversions between user space and the device space of the target rendering device. Although the coordinate system for a monitor is very different from the coordinate system for a printer, these differences are invisible to applications.

1.2.1.1 User Space

As shown in Figure 1-1, the user space origin is located in the upper-left corner of the space, with x values increasing to the right and y values increasing downward.

The previous context describes the graphic

Figure 1-1 User Space Coordinate System

User space represents a uniform abstraction of all possible device coordinate systems. The device space for a particular device might have the same origin and direction as user space, or it might be different. Regardless, user space coordinates are automatically transformed into the appropriate device space when a graphic object is rendered. Often, the underlying platform device drivers are used to perform this conversion.

1.2.1.2 Device Space

The Java 2D API defines three levels of configuration information that are maintained to support the conversion from user space to device space. This information is encapsulated by three classes:

  • GraphicsEnvironment
  • GraphicsDevice
  • GraphicsConfiguration

Between them, the GraphicsEnvironment, GraphicsDevice, and GraphicsConfiguration represent all of the information necessary for locating a rendering device or font on the Java platform and for converting coordinates from user space to device space. An application can access this information, but does not need to perform any transformations between user space and device space.

The GraphicsEnvironment describes the collection of rendering devices visible to a Java application on a particular platform. Rendering devices include screens, printers, and image buffers. The GraphicsEnvironment also includes a list of all of the available fonts on the platform.

A GraphicsDevice describes an application-visible rendering device, such as a screen or printer. Each possible configuration of the device is represented by a GraphicsConfiguration. For example, an SVGA display device can operate in several modes: 640x480x16 colors, 640x480x256 colors, and 800x600x256 colors. The SVGA screen is represented by a GraphicsDevice object and each of the modes is represented by a GraphicsConfiguration object.

A GraphicsEnvironment can contain one or more GraphicsDevices; in turn, each GraphicsDevice can have one or more GraphicsConfigurations.

1.2.2 Transforms

The Java 2D API has a unified coordinate transformation model. All coordinate transformations, including transformations from user to device space, are represented by AffineTransform objects. AffineTransform defines the rules for manipulating coordinates using matrices.

You can add an AffineTransform to the graphics context to rotate, scale, translate, or shear a geometric shape, text, or image when it is rendered. The added transform is applied to any graphic object rendered in that context. The transform is performed when user space coordinates are converted to device space coordinates.

1.2.3 Fonts

A string is commonly thought of in terms of the characters that comprise the string. When a string is drawn, its appearance is determined by the font that is selected. However, the shapes that the font uses to display the string don’t always correspond to individual characters. For example, in professional publishing, certain combinations of two or more characters are often replaced by a single shape called a ligature.

The shapes that a font uses to represent the characters in the string are called glyphs. A font might represent a character such as a lowercase a acute using multiple glyphs, or represent certain character combinations such as the fi in final with a single glyph. In the Java 2D API, a glyph is simply a Shape that can be manipulated and rendered in the same way as any other Shape.

A font can be thought of as a collection of glyphs. A single font might have many versions, such as heavy, medium, oblique, gothic, and regular. These different versions are called faces. All of the faces in a font have a similar typographic design and can be recognized as members of the same family. In other words, a collection of glyphs with a particular style forms a font face, a collection of font faces forms a font family, and a collection of font families forms the set of fonts available within a particular GraphicsEnvironment.

In the Java 2D API, fonts are specified by a name that describes a particular font face—for example, Helvetica Bold. This is different from the JDK 1.1 software, in which fonts are described by logical names that map onto different font faces depending on which font faces are available on a particular platform. For backward compatibility, the Java 2D API supports the specification of fonts by logical name as well as by font face name.

Using the Java 2D API, you can compose and render strings that contain multiple fonts of different families, faces, sizes, and even languages. The appearance of the text is kept logically separate from the layout of the text. Font objects are used to describe the appearance, and the layout information is stored in TextLayout and TextAttributeSet objects. Keeping the font and layout information separate makes it easier to use the same fonts in different layout configurations.

1.2.4 Images

Images are collections of pixels organized spatially. A pixel defines the appearance of an image at a single display location. A two-dimensional array of pixels is called a raster.

The pixel’s appearance can be defined directly or as an index into a color table for the image.

In images that contain many colors (more than 256), the pixels usually directly represent the color, alpha, and other display characteristics for each screen location. Such images tend to be much larger than indexed-color images, but they look more realistic.

In an indexed-color image, the colors in the image are limited to the colors specified in the color table, often resulting in fewer colors that can be used in the image. However, an index typically requires less storage space than a color value, so images stored as a set of indexed colors are usually smaller. This pixel format is popular for images that contain only 16 or 256 colors.

Images in the Java 2D API have two primary components:

  • The raw image data (the pixels)
  • The information necessary for interpreting the pixels

The rules for interpreting the pixel are encapsulated by a ColorModel object—for example, whether the values should be interpreted as direct or indexed colors. For a pixel to be displayed, it must be paired with a color model.

A band is one component of the color space for an image. For example, the Red, Green, and Blue components are the bands in an RGB image. A pixel in a direct color model image can be thought of as a collection of band values for a single screen location.

The java.awt.image package contains several ColorModel implementations, including those for packed and component pixel representations.

A ColorSpace object encapsulates the rules that govern how a set of numeric measurements corresponds to a particular color. The ColorSpace implementations in the java.awt.color represent the most popular color spaces, including RGB and gray scale. Note that a color space is not a collection of colors—it defines the rules for how to interpret individual color values.

Separating the color space from the color model provides greater flexibility in how colors are represented and converted from one color representation to another.

1.2.5 Fills and Strokes

With the Java 2D API, you can render Shapes using different pen styles and fill patterns. Because text is ultimately represented by a set of glyphs, text strings can also be stroked and filled.

Pen styles are defined by objects that implement the Stroke interface. Strokes enable you to specify different widths and dashing patterns for lines and curves.

Fill patterns are defined by objects that implement the Paint interface. The Color class, which was available in earlier versions of the AWT, is a simple type of Paint object used to define solid-color fills. The Java 2D API provides two additional Paint implementations, TexturePaint and GradientPaint. TexturePaint defines a fill pattern using a simple image fragment that is repeated uniformly. GradientPaint defines a fill pattern as a gradient between two colors.

In Java 2D, rendering a shape’s outline and filling the shape with a pattern are two separate operations:

  • Using one of the draw methods renders the shape’s contour or outline using the pen style specified by the Stroke attribute and the fill pattern specified by the Paint attribute.
  • Using the fill method fills the interior of the shape with the pattern specified by the Paint attribute.

When a text string is rendered, the current Paint attribute is applied to the glyphs that form the string. Note, however, that drawString actually fills the glyphs that are rendered. To stroke the outlines of the glyphs in a text string, you need to get the outlines and render them as shapes using the draw method.

1.2.6 Composites

When you render an object that overlaps an existing object, you need to determine how to combine the colors of the new object with the colors that already occupy the area where you are going to draw. The Java 2D API encapsulates rules for how to combine colors in a Composite object.

Primitive rendering systems provide only basic Boolean operators for combining colors. For example, a Boolean compositing rule might allow the source and destination color values to be ANDed, ORed, or XORed. There are several problems with this approach

  • It’s not “human friendly”—it’s difficult to think in terms of what the resulting color will be if red and blue are ANDed, not added.
  • Boolean composition does not support the accurate composition of colors in different color spaces.
  • Straight Boolean composition doesn’t take into account the color models of the colors. For example, in an indexed color model, the result of a Boolean operation on two pixel values in an image is the composite of two indices, not two colors.

The Java 2D API avoids these pitfalls by implementing alpha-blending1 rules that take color model information into account when compositing colors. An AlphaComposite object includes the color model of both the source and destination colors.

1.3 Backward Compatibility and Platform Independence

The Java 2D™ API maintains backward compatibility with JDK 1.1 software. It is also architected so that applications can maintain platform-independence.

1.3.1 Backward Compatibility

To ensure backward compatibility, the functionality of existing JDK graphics and imaging classes and interfaces was maintained. Existing features were not removed and no package designations were changed for existing classes. The Java 2D API enhances the functionality of the AWT by implementing new methods in existing classes, extending existing classes, and adding new classes and interfaces that don’t affect the legacy APIs.

For example, much of the Java 2D API functionality is delivered through an expanded graphics context, Graphics2D. To provide this extended graphics context while maintaining backward compatibility, Graphics2D extends the Graphics class from the JDK 1.1 release.

The usage model of the graphics context remains unchanged. The AWT passes a graphics context to an AWT Component through the following methods:

  • paint
  • paintAll
  • update
  • print
  • printAll
  • getGraphics

A JDK 1.1 applet interprets the graphics context that’s passed in as an instance of Graphics. To gain access to the new features implemented in Graphics2D, a Java 2D API–compatible applet casts the graphics context to a Graphics2D object:

public void Paint (Graphics g) {

        Graphics2D g2 = (Graphics2D) g;
        ...
        ...
        g2.setTransform (t);
}

In some cases, rather than extending a legacy class, the Java 2D API generalizes it. Two techniques were used to generalize legacy classes:

  • One or more parent classes were inserted in the hierarchy, and the legacy class was updated to extend the new parent classes. This technique is used to add general implemented methods and instance data to the legacy class.
  • One or more interface implementations were added to the legacy class. This technique is used to add general abstract methods to the legacy class.

For example, the Java 2D API generalizes the AWT Rectangle class using both of these techniques. The hierarchy for rectangle now looks like:

java.lang.object
|
+-------java.awt.geom.RectangularShape
             |
             +---------java.awt.geom.Rectangle2D
                               |
                               +-------java.awt.Rectangle

In the JDK 1.1 software, Rectangle simply extended Object. It now extends the new Rectangle2D class and implements both Shape and Serializable. Two parent classes were added to the Rectangle hierarchy: RectangularShape and Rectangle2D. Applets written for JDK 1.1 software are unaware of the new parent classes and interface implementations, but are unaffected because Rectangle still contains the methods and members that were present in earlier versions.

The Java 2D API adds several new classes and interfaces that are “orthogonal” to the legacy API. These additions do not extend or generalize existing classes—they are entirely new and distinct. These new classes and interfaces embody concepts that had no explicit representation in the legacy API.

For example, the Java 2D API implements several new Shape classes, including Arc2D, CubicCurve2D, and QuadCurve2D. Although early versions of the AWT could render arcs using the drawArc and fillArc methods, there was no general curve abstraction and no discrete classes that embodied arcs. These discrete classes could be added to the Java 2D API without disrupting legacy applets because drawArc and fillArc are still supported through the Graphics class.

1.3.2 Platform Independence

To enable the development of platform-independent applications, the Java 2D API makes no assumptions about the resolution, color space, or color model of the target rendering device. Nor does the Java 2D API assume any particular image file format.

Truly platform-independent fonts are possible only when the fonts are built-in (provided as part of the JDK software), or when they are mathematically or programmatically generated. The Java 2D API does not currently support built-in or mathematically generated fonts, but it does enable the programmatic definition of entire fonts through their glyph set. Each glyph can in turn be defined by a Shape that consists of line segments and curves. Many fonts of particular styles and sizes can be derived from a single glyph set.

1.4 The Java 2D™ API Packages

The Java 2D API classes are organized into the following packages:

  • java.awt
  • java.awt.geom
  • java.awt.font
  • java.awt.color
  • java.awt.image
  • java.awt.image.renderable
  • java.awt.print

Package java.awt contains those Java 2D API classes and interfaces that are general in nature or that enhance legacy classes. (Obviously, not all of the classes in java.awt are Java 2D classes.)

AlphaComposite | BasicStroke | Color
Composite | CompositeContext | Font
GradientPaint | Graphics2D | GraphicsConfiguration
GraphicsDevice | GraphicsEnvironment | Paint
PaintContext | Rectangle | Shape
Stroke | TexturePaint | Transparency

Package java.awt.geom contains classes and interfaces related to the definition of geometric primitives:

AffineTransform | Arc2D | Arc2D.Double
Arc2D.Float | Area | CubicCurve2D
CubicCurve2D.Double | CubicCurve2D.Float | Dimension2D
Ellipse2D | Ellipse2D.Double | Ellipse2D.Float
FlatteningPathIterator | GeneralPath | Line2D
Line2D.Double | Line2D.Float | PathIterator
Point2D | Point2D.Double | Point2D.Float
QuadCurve2D | QuadCurve2D.Double | QuadCurve2D.Float
Rectangle2D | Rectangle2D.Double | Rectangle2D.Float
RectangularShape | RoundRectangle2D | RoundRectangle2D.Double
RoundRectangle2D.Float |  |

Many of the geometric primitives have corresponding .Float and .Double implementations. This was done to enable both floating single- and double-precision implementations. Double-precision implementations provide greater rendering precision at the expense of performance on some platforms.

Package java.awt.font contains classes and interfaces used for text layout and the definition of fonts:

FontRenderContext | GlyphJustificationInfo | GlyphMetrics
GlyphVector | GraphicAttribute | ImageGraphicAttribute
LineBreakMeasurer | LineMetrics | MultipleMaster
OpenType | ShapeGrapicAttribute | TextAttribute
TextHitInfo | TextLayout | TransformAttribute

Packagejava.awt.color contains classes and interfaces for the definition of color spaces and color profiles:

ColorSpace | ICC_ColorSpace | ICC_Profile
ICC_ProfileGray | ICC_ProfileRGB |

The java.awt.image and java.awt.image.renderable packages contain classes and interfaces for the definition and rendering of images:

AffineTransformOp | BandCombineOp | BandedSampleModel
BufferedImage | BufferedImageFilter | BufferedImageOp
ByteLookupTable | ColorConvertOp | ColorModel
ComponentColorModel | ComponentSampleModel | ConvolveOp
ContextualRenderedImageFactory |  | DataBuffer
DataBufferByte | DataBufferInt | DataBufferShort
DataBufferUShort | DirectColorModel | IndexColorModel
Kernel | LookupOp | LookupTable
MultiPixelPackedSampleModel | PackedColorModel | ParameterBlock
PixelInterleavedSampleModel | Raster | RasterOp
RenderableImage | RenderableImageOp | RenderableImageProducer
RenderContext | RenderedImageFactory | RenderedImage
RescaleOp | SampleModel | ShortLookupTable
SinglePixelPackedSampleModel |  | TileObserver
WritableRaster | WritableRenderedImage |

Package java.awt.image was present in earlier versions of the AWT. The Java 2D API enhances the following legacy AWT image classes:

  • ColorModel
  • DirectColorModel
  • IndexColorModel

These color model classes remain in the java.awt.image package for backward compatibility. To maintain consistency, the new color model classes are also located in the java.awt.image package.

Package java.awt.print contains classes and interfaces that enable printing of all Java 2D–based text, graphics, and images

Book | Pageable | PageFormat
Paper | Printable | PrinterGraphics
PrinterJob |  |

1For detailed information about alpha blending, see Section 17.6 of Computer Graphics: Principles and Practice. 2nd ed. J.D. Foley, A. van Dam, S.K. Feiner, J.F. Hughes. Addison- Wesley, 1990.

Contents | Previous | Next
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


This guide describes the features provided by the Java 2D™ API and illustrates how you can use the Java 2D API classes to enhance your applications. For additional information about the Java 2D APIs, see:

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Contents | Previous | Next

This guide describes the features provided by the Java 2D™ API and illustrates how you can use the Java 2D API classes to enhance your applications. For additional information about the Java 2D APIs, see:

  • The Java Tutorial, 2nd Volume. Available online at:
    http://download.oracle.com/javase/tutorial/2d/index.html
  • The 2D Text Tutorial. Available online from the Java Developer Connection:
    http://java.sun.com/developer/onlineTraining/Media/2DText/
  • The Java 2D Sample Programs. Available online at:
    http://java.sun.com/products/java-media/2D/samples/index.html
  • The Java 2D Demo. Available from the Java 2D website:
    http://java.sun.com/products/java-media/2D/index.html

This information in this guide is organized into seven chapters:

Overview —introduces the packages and key classes in the Java 2D API.

Rendering with Graphics2D—describes the Java 2D API classes in the java.awt package and how to set up the Graphics2D rendering context.

Geometries—describes the Java 2D API classes in the java.awt.geom package and how to define and manipulate 2D shapes and areas.

Fonts and Text Layout—describes the Java 2D API classes in the java.awt.font package, how to specify and retrieve font information, and how to display and manipulate international text using the Java 2D text layout APIs directly.

Imaging—describes the Java 2D API classes in the java.awt.image, java.awt.image.codec, and java.awt.image.renderable packages and how to display and manipulate images and offscreen buffers.

Color—describes the Java 2D API classes in the java.awt.color package and color management.

Printing—describes the Java 2D API classes in the java.awt.print package and the Java 2D API printing model.

Contents | Previous | Next
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Contents | Previous | Next

Chapter 7

Printing

The Java Printing API enables applications to:

  • Print all AWT and Java 2D™ graphics, including composited graphics and images.
  • Control document-composition functions such as soft collating, reverse order printing, and booklet printing.
  • Invoke printer-specific functions such as duplex (two-sided) printing and stapling.
  • Print on all platforms, including Windows and Solaris. This includes printers directly attached to the computer as well as those that the platform software is able to access using network printing protocols.

Not all of these features are supported in the Java™ 2 SDK Printing API and implementation. The API will be extended to support all of these features in future releases. For example, additional printer controls will be added by augmenting the set of named properties of a print job that the application can control.

7.1 Interfaces and Classes

Interface | Description
Printable | The Printable interface is implemented by each page painter, the application class(es) called by the printing system to render a page. The system calls the page painter’s print method to request that a page be rendered.
Pageable | The Pageable interface is implemented by a document that is to be printed by the printing system. Through the Pageable methods, the system can determine the number of pages in the document, the format to use for each page, and the page painter to use to render each page.
PrinterGraphics | The Graphics2D objects that a page painter uses to render a page implement the PrinterGraphics interface. This enables an application to get the PrinterJob object that is controlling the printing.
Class | Description
Book | Implements: Pageable Represents a document in which pages can have different page formats and page painters. This class uses the Pageable interface to interact with a PrinterJob.
PageFormat | Describes the size and orientation of a page to be printed, as well as the Paper used to print it. For example, portrait and landscape paper orientations are represented by PageFormat.
Paper | Describes the physical characteristics of a piece of paper.
PrinterJob | The principal class that controls printing. The application calls PrinterJob methods to set up a job, display a print dialog to the user (optional), and to print the pages in the job.

7.2 Printing Concepts

The Java Printing API is based on a callback printing model in which the printing system, not the application, controls when pages are printed. The application provides information about the document to be printed and the printing system asks the application to render each page as it needs them.

The printing system might request that a particular page be rendered more than once or request that pages be rendered out of order. The application must be able to generate the proper page image, no matter which page the printing system requests. In this respect, the printing system is similar to the window toolkit, which can request components to repaint at any time, in any order.

The callback printing model is more flexible than traditional application-driven printing models and supports printing on a wider range of systems and printers. For example, if a printer stacks output pages in reverse order, the printing system can ask the application to generate pages in reverse order so that the final stack is in proper reading order.

This model also enables applications to print to a bitmap printer from computers that don’t have enough memory or disk space to buffer a full-page bitmap. In this situation, a page is printed as a series of small bitmaps or bands. For example, if only enough memory to buffer one tenth of a page is available, the page is divided into ten bands. The printing system asks the application to render each page ten times, once to fill each band. The application does not need to be aware of the number or size of the bands; it simply must be able to render each page when requested.

7.2.1 Supporting Printing

An application has to perform two tasks to support printing:

  • Job control—initiating and managing the print job.
  • Imaging—rendering each page when the printing system requests it.

7.2.1.1 Job Control

The user often initiates printing by clicking a button or selecting a menu item in an application. When a print operation is triggered by the user, the application creates a PrinterJob object and uses it to manage the printing process.

The application is responsible for setting up the print job, displaying print dialogs to the user, and starting the printing process.

7.2.1.2 Imaging

When a document is printed, the application has to render each page when the printing system requests it. To support this mechanism, the application provides a page painter that implements the Printable interface. When the printing system needs a page rendered, it calls the page painter’s print method.

When a page painter’s print method is called, it is passed a Graphics context to use to render the page image. It is also passed a PageFormat object that specifies the geometric layout of the page, and an integer page index that identifies the ordinal position of the page in the print job.

The printing system supports both Graphics and Graphics2D rendering, To print Java 2D™ Shapes, Text, and Images, you cast the Graphics object passed into the print method to a Graphics2D.

To print documents in which the pages use different page painters and have different formats, you use a pageable job. To create a pageable job, you can use the Book class or your own implementation of the Pageable interface. To implement simple printing operations, you do not need to use a pageable print job; Printable can be used as long as all of the pages share the same page format and painter.

7.2.2 Page Painters

The principal job of a page painter is to render a page using the graphics context that is provided by the printing system. A page painter implements the Printable.print method:

public int print(Graphics g, PageFormat pf, int pageIndex)

The graphics context passed to the print method is either an instance of Graphics or Graphics2D, depending on the packages loaded in your Java Virtual Machine. To use Graphics2D features, you can cast the Graphics object to a Graphics2D. The Graphics instance passed to print also implements the PrinterGraphics interface.

The PageFormat passed to a Printable describes the geometry of the page being printed. The coordinate system of the graphics context passed to print is fixed to the page: the origin of the coordinate system is at the upper left corner of the paper, X increases to the right, Y increases downward, and the units are 1/72 inch. If the page is in portrait orientation, the x-axis aligns with the paper’s “width,” while the y-axis aligns with the paper’s “height.” (Normally, but not always, a paper’s height exceeds its width.) If the page is in landscape orientation, the roles are reversed: the x-axis aligns with the paper’s “height” and the y-axis with its “width.”

Because many printers cannot print on the entire paper surface, the PageFormat specifies the imageable area of the page: this is the portion of the page in which it’s safe to render. The specification of the imageable area does not alter the coordinate system; it is provided so that the contents of the page can be rendered so that they don’t extend into the area where the printer can’t print.

The graphics context passed to print has a clip region that describes the portion of the imageable area that should be drawn. It is always safe to draw the entire page into the context; the printing system will handle the necessary clipping. However, to eliminate the overhead of drawing portions of the page that won’t be printed, you can use the clipping region to limit the areas that you render. To get the clipping region from the graphics context, call Graphics.getClip. You are strongly encouraged to use the clip region to reduce the rendering overhead.

It is sometimes desirable to launch the entire printing operation “in the background” so that a user can continue to interact with the application while pages are being rendered. To do this, call PrinterJob.print in a separate thread.

If possible, you should avoid graphics operations that require knowledge of the previous image contents, such as copyArea, setXOR, and compositing. These operations can slow rendering and the results might be inconsistent.

7.2.3 Printable Jobs and Pageable Jobs

A Printable job provides the simplest way to print. Only one page painter is used; the application provides a single class that implements the Printable interface. When it’s time to print, the printing system calls the page painter’s print method to render each page. The pages are requested in order, starting with page index 0. However, the page painter might be asked to render each page several times before it advances to the next page. When the last page has been printed, the page painter’s print method returns NO_SUCH_PAGE.

In a Printable job:

  • All pages use the same page painter and PageFormat. If a print dialog is presented, it will not display the number of pages in the document because that information is not available to the printing system.
  • The printing system always asks the page painter to print each page in indexed order, starting with the page at index 0. No pages are skipped. For example, if a user asks to print pages 2 and 3 of a document, the page painter will be called with indices 0, 1, and 2. The printing system might request that a page be rendered multiple times before moving to the next page.
  • The page painter informs the printing system when the end of the document has been reached.
  • All page painters are called in the same thread.
  • Some printing systems might not be able to achieve the ideal output. For example, the stack of pages emerging from the printer might be in the wrong order, or the pages might not be collated if multiple copies are requested.

A Pageable job is more flexible than a Printable job. Unlike the pages in a Printable job, pages in a Pageable job can differ in layout and implementation. To manage a Pageable job, you can use the Book class or implement your own Pageable class. Through the Pageable, the printing system can determine the number of pages to print, the page painter to use for each page, and the PageFormat to use for each page. Applications that need to print documents that have a planned structure and format should use Pageable jobs.

In a Pageable job:

  • Different pages can use different page painters and PageFormats.
  • The printing system can ask page painters to print pages in an arbitrary order and some pages might be skipped. For example, if a user asks to print pages 2 and 3 of a document, the page painter will be called with indices 1 and 2 and page index 0 will be skipped.
  • Pageable jobs do not need to know in advance how many pages are in the document. However, unlike Printable jobs, they must be able to render pages in any order. There might be gaps in the sequencing and the printing system might request that a page be rendered multiple times before moving to the next page. For example, a request to print pages 2 and 3 of a document might result in a sequence of calls that request pages with indices 2,2,1,1, and 1.

7.2.4 Typical Life-Cycle of a PrinterJob

An application steers the PrinterJob object through a sequence of steps to complete a printing job. The simplest sequence used by an application is:

  • Get a new PrinterJob object by calling PrinterJob.getPrinterJob.
  • Determine what PageFormat to use for printing. A default PageFormat can be obtained by calling defaultPage or you can invoke pageDialog to present a dialog box that allows the user to specify a format.
  • Specify the characteristics of the job to be printed to the PrinterJob. For a Printable job, call setPrintable; for a Pageable job, call setPageable. Note that a Book object is ideal for passing to setPageable.
  • Specify additional print job properties, such as the number of copies to print or the name of the job to print on the banner page.
  • Call printDialog to present a dialog box to the user. This is optional. The contents and appearance of this dialog can vary across different platforms and printers. On most platforms, the user can use this dialog to change the printer selection. If the user cancels the print job, the printDialog method returns FALSE.
  • Call Printerjob.print to print the job. This method in turn calls print on the appropriate page painters.

A job can be interrupted during printing if:

  • A PrinterException is thrown—the exception is caught by the print method and the job is halted. A page painter throws a PrinterException if it detects a fatal error.
  • PrinterJob.cancel is called—the printing loop is terminated and the job is canceled. The cancel method can be called from a separate thread that displays a dialog box and allows the user to cancel printing by clicking a button in the box.

Pages generated before a print job is stopped might or might not be printed.

The print job is usually not finished when the print method returns. Work is typically still being done by a printer driver, print server, or the printer itself. The state of the PrinterJob object might not reflect the state of the actual job being printed.

Because the state of a PrinterJob changes during its life cycle, it is illegal to invoke certain methods at certain times. For example, calling setPageable after you’ve called print makes no sense. When illegal calls are detected, the PrinterJob throws a java.lang.IllegalStateException.

7.2.5 Dialogs

The Java Printing API requires that applications invoke user-interface dialogs explicitly. These dialogs might be provided by the platform software (such as Windows) or by a Java™ 2 SDK software implementation. For interactive applications, it is customary to use such dialogs. For production printing applications, however, dialogs are not necessary. For example, you wouldn’t want to display a dialog when automatically generating and printing a nightly database report. A print job that requires no user interaction is sometimes called a silent print job.

7.2.5.1 Page setup dialog

You can allow the user to alter the page setup information contained in a PageFormat by displaying a page setup dialog. To display the page setup dialog, you call PrinterJob.pageDialog. The page setup dialog is initialized using the parameter passed to pageDialog. If the user clicks the OK button in the dialog, the PageFormat instance is cloned, altered to reflect the user’s selections, and then returned. If the user cancels the dialog, pageDialog returns the original unaltered PageFormat.

7.2.5.2 Print dialog

Typically, an application presents a print dialog to the user when a print menu item or button is activated. To display this print dialog, you call the PrinterJob’s printDialog method. The user’s choices in the dialog are constrained based on the number and format of the pages in the Printable or Pageable that have been furnished to the PrinterJob. If the user clicks OK in the print dialog, printDialog returns TRUE. If the user cancels the print dialog, FALSE is returned and the print job should be considered abandoned.

7.3 Printing with Printables

To provide basic printing support:

  • Implement the Printable interface to provide a page painter that can render each page to be printed.
  • Create a PrinterJob.
  • Call setPrintable to tell the PrinterJob how to print your document.
  • Call print on the PrinterJob object to start the job.

In the following example, a Printable job is used to print five pages, each of which displays a green page number. Job control is managed in the main method, which obtains and controls the PrinterJob. Rendering is performed in the page painter’s print method.

import java.awt.*; import java.awt.print.*;
public class SimplePrint implements Printable
{
  private static Font fnt = new Font("Helvetica",Font.PLAIN,24);

  public static void main(String[] args)
  {
    // Get a PrinterJob
    PrinterJob job = PrinterJob.getPrinterJob();
    // Specify the Printable is an instance of SimplePrint
    job.setPrintable(new SimplePrint());
    // Put up the dialog box
    if (job.printDialog())
    {
      // Print the job if the user didn't cancel printing
      try { job.print(); }
      catch (Exception e)
        { /* handle exception */ }
    }
    System.exit(0);
  }

  public int print(Graphics g, PageFormat pf, int pageIndex)
  throws PrinterException
  {
    // pageIndex 0 to 4 corresponds to page numbers 1 to 5.
    if (pageIndex >= 5) return Printable.NO_SUCH_PAGE;
    g.setFont(fnt);
    g.setColor(Color.green);
    g.drawString("Page " + (pageIndex+1), 100, 100);
    return Printable.PAGE_EXISTS;
  }
}

7.3.1 Using Graphics2D for Rendering

You can invoke Graphics2D functions in you page painter’s print method by first casting the Graphics context to a Graphics2D.

In the following example, the page numbers are rendered using a red-green gradient. To do this, a GradientPaint is set in the Graphics2D context.

import java.awt.*; import java.awt.print.*;
public class SimplePrint2D implements Printable
{
  private static Font fnt = new Font("Helvetica",Font.PLAIN,24);

  private Paint pnt = new GradientPaint(100f, 100f, Color.red,                                            136f, 100f, Color.green, true);

  public static void main(String[] args)
  {
    // Get a PrinterJob
    PrinterJob job = PrinterJob.getPrinterJob();
    // Specify the Printable is an instance of SimplePrint2D
    job.setPrintable(new SimplePrint2D());
    // Put up the dialog box
    if (job.printDialog())
    {
      // Print the job if the user didn't cancel printing
      try { job.print(); }
      catch (Exception e) { /* handle exception */ }
    }
  System.exit(0);
  }

  public int print(Graphics g, PageFormat pf, int pageIndex)
  throws PrinterException
  {
    // pageIndex 0 to 4 corresponds to page numbers 1 to 5.
    if (pageIndex >= 5) return Printable.NO_SUCH_PAGE;
    Graphics2D g2 = (Graphics2D) g;
    // Use the font defined above
    g2.setFont(fnt);
    // Use the gradient color defined above
    g2.setPaint(pnt);
    g2.drawString("Page " + (pageIndex+1), 100f, 100f);
    return Printable.PAGE_EXISTS;
  }
}

7.3.2 Printing a File

When a page painter’s print method is invoked several times for the same page, it must generate the same output each time.

There are many ways to ensure that repeated requests to render a page yield the same output. For example, to ensure that the same output is generated each time the printing system requests a particular page of a text file, page painter could either store and reuse file pointers for each page or store the actual page data.

In the following example, a “listing” of a text file is printed. The name of the file is passed as an argument to the main method. The PrintListingPainter class stores the file pointer in effect at the beginning of each new page it is asked to render. When the same page is rendered again, the file pointer is reset to the remembered position.

import java.awt.*;
import java.awt.print.*;
import java.io.*;

public class PrintListing
{
  public static void main(String[] args)
  {
    // Get a PrinterJob
    PrinterJob job = PrinterJob.getPrinterJob();
    // Ask user for page format (e.g., portrait/landscape)
    PageFormat pf = job.pageDialog(job.defaultPage());
    // Specify the Printable is an instance of
    // PrintListingPainter; also provide given PageFormat
    job.setPrintable(new PrintListingPainter(args[0]), pf);
    // Print 1 copy
    job.setCopies(1);
    // Put up the dialog box
    if (job.printDialog())
    {
      // Print the job if the user didn't cancel printing
      try { job.print(); }
      catch (Exception e) { /* handle exception */ }
    }
    System.exit(0);
  }
}

class PrintListingPainter implements Printable
{
  private RandomAccessFile raf;
  private String fileName;
  private Font fnt = new Font("Helvetica", Font.PLAIN, 10);
  private int rememberedPageIndex = -1;
  private long rememberedFilePointer = -1;
  private boolean rememberedEOF = false;

  public PrintListingPainter(String file)
  {
    fileName = file;
    try
    {
      // Open file
      raf = new RandomAccessFile(file, "r");
    }
    catch (Exception e) { rememberedEOF = true; }
  }

  public int print(Graphics g, PageFormat pf, int pageIndex)
  throws PrinterException
  {
  try
  {
    // For catching IOException
    if (pageIndex != rememberedPageIndex)
    {
      // First time we've visited this page
      rememberedPageIndex = pageIndex;
      // If encountered EOF on previous page, done
      if (rememberedEOF) return Printable.NO_SUCH_PAGE;
      // Save current position in input file
      rememberedFilePointer = raf.getFilePointer();
    }
    else raf.seek(rememberedFilePointer);
    g.setColor(Color.black);
    g.setFont(fnt);
        int x = (int) pf.getImageableX() + 10;
        int y = (int) pf.getImageableY() + 12;
    // Title line
    g.drawString("File: " + fileName + ", page: " +                                          (pageIndex+1),  x, y);
    // Generate as many lines as will fit in imageable area
    y += 36;
    while (y + 12 < pf.getImageableY()+pf.getImageableHeight())
    {
      String line = raf.readLine();
      if (line == null)
      {
        rememberedEOF = true;
        break;
                }
        g.drawString(line, x, y);
        y += 12;
      }
      return Printable.PAGE_EXISTS;
    }
    catch (Exception e) { return Printable.NO_SUCH_PAGE;}
  }
}

7.4 Printing with Pageables and Books

Pageable jobs are suited for applications that build an explicit representation of a document, page by page. The Book class is a convenient way to use Pageables, but you can also build your own Pageable structures if Book does not suit your needs. This section shows you how to use Book.

Although slightly more involved, Pageable jobs are preferred over Printable jobs because the printing system has more flexibility. A major advantage of Pageables is that the number of pages in the document is usually known and can be displayed to the user in the print dialog box. This helps the user to confirm that the job is specified correctly or to select a range of pages for printing.

A Book represents a collection of pages. The pages in a book do not have to share the same size, orientation, or page painter. For example, a Book might contain two letter size pages in portrait orientation and a letter size page in landscape orientation.

When a Book is first constructed, it is empty. To add pages to a Book, you use the append method. This method takes a PageFormat object that defines the page’s size, printable area, and orientation and a page painter that implements the Printable interface.

Multiple pages in a Book can share the same page format and painter. The append method is overloaded to enable you to add a series of pages that have the same attributes by specifying a third parameter, the number of pages.

If you don’t know the total number of pages in a Book, you can pass UNKNOWN_NUMBER_OF_PAGES to the append method. The printing system will then call your page painters in order of increasing page index until one of them returns NO_SUCH_PAGE.

The setPage method can be used to change a page’s page format or painter. The page to be changed is identified by a page index that indicates the page’s location in the Book.

You call setPageable and pass in the Book to prepare the print job. The setPageable and setPrintable methods are mutually exclusive; that is, you should call one or the other but not both when preparing the PrinterJob.

7.4.1 Using a Pageable Job

In the following example, a Book is used to reproduce the first simple printing example. (Because this case is so simple, there is little benefit in using a Pageable job instead of a Printable job, but it illustrates the basics of using a Book.) Note that you still have to implement the Printable interface and perform page rendering in the page painter’s print method.

import java.awt.*;
import java.awt.print.*;

public class SimplePrintBook implements Printable
{
  private static Font fnt = new Font("Helvetica",Font.PLAIN,24);
  public static void main(String[] args)
  {
    // Get a PrinterJob
    PrinterJob job = PrinterJob.getPrinterJob();
    // Set up a book
    Book bk = new Book();
    bk.append(new SimplePrintBook(), job.defaultPage(), 5);
    // Pass the book to the PrinterJob
    job.setPageable(bk);
    // Put up the dialog box
    if (job.printDialog())
    {
      // Print the job if the user didn't cancel printing
      try { job.print(); }
      catch (Exception e) { /* handle exception */ }
    }
    System.exit(0);
  }

  public int print(Graphics g, PageFormat pf, int pageIndex)
  throws PrinterException
  {
    g.setFont(fnt);
    g.setColor(Color.green);
    g.drawString("Page " + (pageIndex+1), 100, 100);
    return Printable.PAGE_EXISTS;
  }
}

7.4.2 Using Multiple Page Painters

In the following example, two different page painters are used: one for a cover page and one for content pages. The cover page is printed in landscape mode and the contents pages are printed in portrait mode.

import java.awt.*;
import java.awt.print.*;

public class PrintBook
{
  public static void main(String[] args)
  {
    // Get a PrinterJob
    PrinterJob job = PrinterJob.getPrinterJob();
    // Create a landscape page format
    PageFormat pfl = job.defaultPage();
    pfl.setOrientation(PageFormat.LANDSCAPE);
    // Set up a book
    Book bk = new Book();
    bk.append(new PaintCover(), pfl);
    bk.append(new PaintContent(), job.defaultPage(), 2);
    // Pass the book to the PrinterJob
    job.setPageable(bk);
    // Put up the dialog box
    if (job.printDialog())
    {
      // Print the job if the user didn't cancel printing
      try { job.print(); }
      catch (Exception e) { /* handle exception */ }
    }
  System.exit(0);
  }
}

class PaintCover implements Printable
{
  Font fnt = new Font("Helvetica-Bold", Font.PLAIN, 72);

  public int print(Graphics g, PageFormat pf, int pageIndex)
  throws PrinterException
  {
    g.setFont(fnt);
    g.setColor(Color.black);
         int yc = (int) (pf.getImageableY() +               pf.getImageableHeight()/2);
    g.drawString("Widgets, Inc.", 72, yc+36);
    return Printable.PAGE_EXISTS;
  }
}
class PaintContent implements Printable
{
  public int print(Graphics g, PageFormat pf, int pageIndex)
  throws PrinterException
  {
    Graphics2D g2 = (Graphics2D) g;
    int useRed = 0;
   int xo = (int) pf.getImageableX();
        int yo = (int) pf.getImageableY();
    // Fill page with circles or squares, alternating red & green
        for (int x = 0; x+28 < pf.getImageableWidth(); x += 36)
    for (int y = 0; y+28 < pf.getImageableHeight(); y += 36)
    {
      if (useRed == 0) g.setColor(Color.red);
      else g.setColor(Color.green);
      useRed = 1 - useRed;
      if (pageIndex % 2 == 0) g.drawRect(xo+x+4, yo+y+4, 28, 28);
      else g.drawOval(xo+x+4, yo+y+4, 28, 28);
    }
    return   Printable.PAGE_EXISTS;
  }
}

Contents | Previous | Next
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JAAS

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java Authentication and Authorization Service (JAAS)

LoginModule Developer's Guide

Overview
Who Should Read This Document
Related Documentation
Introduction

Steps to Implement a LoginModule
Step 1: Understand the Authentication Technology
Step 2: Name the LoginModule Implementation
Step 3: Implement the Abstract LoginModule Methods
Step 4: Choose or Write a Sample Application
Step 5: Compile the LoginModule and Application
Step 6: Prepare for Testing
Step 7: Test Use of the LoginModule
Step 8: Document Your LoginModule Implementation
Step 9: Make LoginModule JAR File and Documents Available

Overview

The Java Authentication and Authorization Service (JAAS) was introduced as an optional package to the Java 2 SDK, Standard Edition (J2SDK), v 1.3. JAAS was integrated into the Java Standard Edition Development Kit starting with J2SDK 1.4.

JAAS provides subject-based authorization on authenticated identities. This document focuses on the authentication aspect of JAAS, specifically the LoginModule interface.

Who Should Read This Document

This document is intended for experienced programmers who require the ability to write a LoginModule implementing an authentication technology.

Related Documentation

This document assumes you have already read the following:

  • JAAS Reference Guide

It also discusses various classes and interfaces in the JAAS API. Please reference the javadocs for the JAAS API specification for more detailed information:

  • javax.security.auth Package
  • javax.security.auth.callback Package
  • javax.security.auth.kerberos Package
  • javax.security.auth.login Package
  • javax.security.auth.spi Package
  • javax.security.auth.x500 Package
  • com.sun.security.auth Package
  • com.sun.security.auth.callback Package
  • com.sun.security.auth.login Package
  • com.sun.security.auth.module Package

The following tutorials for JAAS authentication and authorization can be run by everyone:

  • JAAS Authentication Tutorial
  • JAAS Authorization Tutorial

Similar tutorials for JAAS authentication and authorization, but which demonstrate the use of a Kerberos LoginModule and thus which require a Kerberos installation, can be found at

  • JAAS Authentication
  • JAAS Authorization

These two tutorials are a part of the Java GSS-API and JAAS sequence of tutorials that utilize Kerberos as the underlying technology for authentication and secure communication.

Introduction

The LoginModule documentation describes the interface that must be implemented by authentication technology providers. LoginModules are plugged in under applications to provide a particular type of authentication.

While applications write to the LoginContext Application Programming Interface (API), authentication technology providers implement the LoginModule interface. A Configuration specifies the LoginModule(s) to be used with a particular login application. Different LoginModules can be plugged in under the application without requiring any modifications to the application itself.

The LoginContext is responsible for reading the Configuration and instantiating the specified LoginModules. Each LoginModule is initialized with a Subject, a CallbackHandler, shared LoginModule state, and LoginModule-specific options.

The Subject represents the user or service currently being authenticated and is updated by a LoginModule with relevant Principals and credentials if authentication succeeds. LoginModules use the CallbackHandler to communicate with users (to prompt for user names and passwords, for example), as described in the login method description. Note that the CallbackHandler may be null. A LoginModule that requires a CallbackHandler to authenticate the Subject may throw a LoginException if it was initialized with a null CallbackHandler. LoginModules optionally use the shared state to share information or data among themselves.

The LoginModule-specific options represent the options configured for this LoginModule in the login Configuration. The options are defined by the LoginModule itself and control the behavior within it. For example, a LoginModule may define options to support debugging/testing capabilities. Options are defined using a key-value syntax, such as debug=true. The LoginModule stores the options as a Map so that the values may be retrieved using the key. Note that there is no limit to the number of options a LoginModule chooses to define.

The calling application sees the authentication process as a single operation invoked via a call to the LoginContext's login method. However, the authentication process within each LoginModule proceeds in two distinct phases. In the first phase of authentication, the LoginContext's login method invokes the login method of each LoginModule specified in the Configuration. The login method for a LoginModule performs the actual authentication (prompting for and verifying a password for example) and saves its authentication status as private state information. Once finished, the LoginModule's login method returns true (if it succeeded) or false (if it should be ignored), or it throws a LoginException to specify a failure. In the failure case, the LoginModule must not retry the authentication or introduce delays. The responsibility of such tasks belongs to the application. If the application attempts to retry the authentication, each LoginModule's login method will be called again.

In the second phase, if the LoginContext's overall authentication succeeded (calls to the relevant required, requisite, sufficient and optional LoginModules' login methods succeeded), then the commit method for each LoginModule gets invoked. (For an explanation of the LoginModule flags required, requisite, sufficient and optional, please consult the javax.security.auth.login.Configuration documentation and Appendix B: Login Configuration Files in the JAAS Reference Guide.) The commit method for a LoginModule checks its privately saved state to see if its own authentication succeeded. If the overall LoginContext authentication succeeded and the LoginModule's own authentication succeeded, then the commit method associates the relevant Principals (authenticated identities) and credentials (authentication data such as cryptographic keys) with the Subject.

If the LoginContext's overall authentication failed (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules' login methods did not succeed), then the abort method for each LoginModule gets invoked. In this case, the LoginModule removes/destroys any authentication state originally saved.

Logging out a Subject involves only one phase. The LoginContext invokes the LoginModule's logout method. The logout method for the LoginModule then performs the logout procedures, such as removing Principals or credentials from the Subject, or logging session information.

Steps to Implement a LoginModule

The steps required in order to implement and test a LoginModule are the following:

Step 1: Understand the Authentication Technology
Step 2: Name the LoginModule Implementation
Step 3: Implement the Abstract LoginModule Methods
Step 4: Choose or Write a Sample Application
Step 5: Compile the LoginModule and Application
Step 6: Prepare for Testing
Step 6a: Place Your LoginModule and Application Code in JAR Files
Step 6b: Decide Where to Store the JAR Files
Step 6c: Set LoginModule and Application JAR File Permissions
Step 6d: Create a Configuration Referencing the LoginModule
Step 7: Test Use of the LoginModule
Step 8: Document Your LoginModule Implementation
Step 9: Make LoginModule JAR File and Documents Available

The steps required to implement and test a new LoginModule follow. Please reference the SampleLoginModule and other files described in the JAAS Reference Guide for examples of what may be done for the various steps.

Step 1: Understand the Authentication Technology

The first thing you need to do is understand the authentication technology to be implemented by your new LoginModule provider, and determine its requirements.

One thing you will need to determine is whether or not your LoginModule will require some form of user interaction (retrieving a user name and password, for example). If so, you will need to become familiar with the CallbackHandler interface and the javax.security.auth.callback package. In that package you will find several possible Callback implementations to use. (Alternatively, you can create your own Callback implementations.) The LoginModule will invoke the CallbackHandler specified by the application itself and passed to the LoginModule's initialize method. The LoginModule passes the CallbackHandler an array of appropriate Callbacks. See the login method in Step 3.

Note that it is possible for LoginModule implementations not to have any end-user interactions. Such LoginModules would not need to access the callback package.

Another thing you should determine is what configuration options you want to make available to the user, who specifies configuration information in whatever form the current Configuration implementation expects (for example, in files). For each option, decide the option name and possible values. For example, if a LoginModule may be configured to consult a particular authentication server host, decide on the option's key name ("auth_server", for example), as well as the possible server hostnames valid for that option ("server_one.foo.com" and "server_two.foo.com", for example).

Step 2: Name the LoginModule Implementation

Decide on the proper package and class name for your LoginModule.

For example, a LoginModule developed by IBM might be called com.ibm.auth.Module where com.ibm.auth is the package name and Module is the name of the LoginModule class implementation.

Step 3: Implement the Abstract LoginModule Methods

The LoginModule interface specifies five abstract methods that require implementations:

  • initialize
  • login
  • commit
  • abort
  • logout
See below and the LoginModule API for more information on each method above.

In addition to these methods, a LoginModule implementation must provide a public constructor with no arguments. This allows for its proper instantiation by a LoginContext. Note that if no such constructor is provided in your LoginModule implementation, a default no-argument constructor is automatically inherited from the Object class.

LoginModule.initialize Method

public void initialize (
  Subject subject,
  CallbackHandler handler,
  Map<java.lang.String, ?> sharedState,
  Map<java.lang.String, ?> options) { ... }

The initialize method is called to initialize the LoginModule with the relevant authentication and state information.

This method is called by a LoginContext immediately after this LoginModule has been instantiated, and prior to any calls to its other public methods. The method implementation should store away the provided arguments for future use.

The initialize method may additionally peruse the provided sharedState to determine what additional authentication state it was provided by other LoginModules, and may also traverse through the provided options to determine what configuration options were specified to affect the LoginModule's behavior. It may save option values in variables for future use.

Note: JAAS LoginModules may use the options defined in PAM (use_first_pass, try_first_pass, use_mapped_pass, and try_mapped_pass) to achieve single-signon. See Making Login Services Independent from Authentication Technologies for further information.

Below is a list of options commonly supported by LoginModules. Note that the following is simply a guideline. Modules are free to support a subset (or none) of the following options.

  • try_first_pass - If true, the first LoginModule in the stack saves the password entered, and subsequent LoginModules also try to use it. If authentication fails, the LoginModules prompt for a new password and retry the authentication.
  • use_first_pass - If true, the first LoginModule in the stack saves the password entered, and subsequent LoginModules also try to use it. LoginModules do not prompt for a new password if authentication fails (authentication simply fails).
  • try_mapped_pass - If true, the first LoginModule in the stack saves the password entered, and subsequent LoginModules attempt to map it into their service-specific password. If authentication fails, the LoginModules prompt for a new password and retry the authentication.
  • use_mapped_pass - If true, the first LoginModule in the stack saves the password entered, and subsequent LoginModules attempt to map it into their service-specific password. LoginModules do not prompt for a new password if authentication fails (authentication simply fails).
  • moduleBanner - If true, then when invoking the CallbackHandler, the LoginModule provides a TextOutputCallback as the first Callback, which describes the LoginModule performing the authentication.
  • debug - If true, instructs a LoginModule to output debugging information.

The initialize method may freely ignore state or options it does not understand, although it would be wise to log such an event if it does occur.

Note that the LoginContext invoking this LoginModule (and the other configured LoginModules, as well), all share the same references to the provided Subject and sharedState. Modifications to the Subject and sharedState will, therefore, be seen by all.

LoginModule.login Method

boolean login() throws LoginException;

The login method is called to authenticate a Subject. This is phase 1 of authentication.

This method implementation should perform the actual authentication. For example, it may cause prompting for a user name and password, and then attempt to verify the password against a password database. Another example implementation may inform the user to insert their finger into a fingerprint reader, and then match the input fingerprint against a fingerprint database.

If your LoginModule requires some form of user interaction (retrieving a user name and password, for example), it should not do so directly. That is because there are various ways of communicating with a user, and it is desirable for LoginModules to remain independent of the different types of user interaction. Rather, the LoginModule's login method should invoke the handle method of the CallbackHandler passed to the initialize method to perform the user interaction and set appropriate results, such as the user name and password. The LoginModule passes the CallbackHandler an array of appropriate Callbacks, for example a NameCallback for the user name and a PasswordCallback for the password, and the CallbackHandler performs the requested user interaction and sets appropriate values in the Callbacks. For example, to process a NameCallback, the CallbackHandler may prompt for a name, retrieve the value from the user, and call the NameCallback's setName method to store the name.

The authentication process may also involve communication over a network. For example, if this method implementation performs the equivalent of a kinit in Kerberos, then it would need to contact the KDC. If a password database entry itself resides in a remote naming service, then that naming service needs to be contacted, perhaps via the Java Naming and Directory Interface (JNDI). Implementations might also interact with an underlying operating system. For example, if a user has already logged into an operating system like Solaris or Windows NT, this method might simply import the underlying operating system's identity information.

The login method should

  1. Determine whether or not this LoginModule should be ignored. One example of when it should be ignored is when a user attempts to authenticate under an identity irrelevant to this LoginModule (if a user attempts to authenticate as root using NIS, for example). If this LoginModule should be ignored, login should return false. Otherwise, it should do the following:
  2. Call the CallbackHandler handle method if user interaction is required.
  3. Perform the authentication.
  4. Store the authentication result (success or failure).
  5. If authentication succeeded, save any relevant state information that may be needed by the commit method.
  6. Return true if authentication succeeds, or throw a LoginException such as FailedLoginException if authentication fails.

Note that the login method implementation should not associate any new Principal or credential information with the saved Subject object. This method merely performs the authentication, and then stores away the authentication result and corresponding authentication state. This result and state will later be accessed by the commit or abort method. Note that the result and state should typically not be saved in the sharedState Map, as they are not intended to be shared with other LoginModules.

An example of where this method might find it useful to store state information in the sharedState Map is when LoginModules are configured to share passwords. In this case, the entered password would be saved as shared state. By sharing passwords, the user only enters the password once, and can still be authenticated to multiple LoginModules. The standard conventions for saving and retrieving names and passwords from the sharedState Map are the following:

  • javax.security.auth.login.name - Use this as the shared state map key for saving/retrieving a name.
  • javax.security.auth.login.password - Use this as the shared state map key for saving/retrieving a password.

If authentication fails, the login method should not retry the authentication. This is the responsibility of the application. Multiple LoginContext login method calls by an application are preferred over multiple login attempts from within LoginModule.login().

LoginModule.commit Method

boolean commit() throws LoginException;

The commit method is called to commit the authentication process. This is phase 2 of authentication when phase 1 succeeds. It is called if the LoginContext's overall authentication succeeded (that is, if the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules succeeded.)

This method should access the authentication result and corresponding authentication state saved by the login method.

If the authentication result denotes that the login method failed, then this commit method should remove/destroy any corresponding state that was originally saved.

If the saved result instead denotes that this LoginModule's login method succeeded, then the corresponding state information should be accessed to build any relevant Principal and credential information. Such Principals and credentials should then be added to the Subject stored away by the initialize method.

After adding Principals and credentials, dispensable state fields should be destroyed expeditiously. Likely fields to destroy would be user names and passwords stored during the authentication process.

The commit method should save private state indicating whether the commit succeeded or failed.

The following chart depicts what a LoginModule's commit method should return. The different boxes represent the different situations that may occur. For example, the top-left corner box depicts what the commit method should return if both the previous call to login succeeded and the commit method itself succeeded.

LoginModule.commit method return values
 | COMMIT: SUCCESS | COMMIT: FAILURE
LOGIN: SUCCESS | return TRUE | throw EXCEPTION
LOGIN: FAILURE | return FALSE | return FALSE

LoginModule.abort Method

boolean abort() throws LoginException;

The abort method is called to abort the authentication process. This is phase 2 of authentication when phase 1 fails. It is called if the LoginContext's overall authentication failed.

This method first accesses this LoginModule's authentication result and corresponding authentication state saved by the login (and possibly commit) methods, and then clears out and destroys the information. Sample state to destroy would be user names and passwords.

If this LoginModule's authentication attempt failed, then there shouldn't be any private state to clean up.

The following charts depict what a LoginModule's abort method should return. This first chart assumes that the previous call to login succeeded. For instance, the top-left corner box depicts what the abort method should return if both the previous call to login and commit succeeded, and the abort method itself also succeeded.

LoginModule.abort method return values; login succeeded
 | ABORT: SUCCESS | ABORT: FAILURE
COMMIT: SUCCESS | return TRUE | throw EXCEPTION
COMMIT: FAILURE | return TRUE | throw EXCEPTION

The second chart depicts what a LoginModule's abort method should return, assuming that the previous call to login failed. For instance, the top-left corner box depicts what the abort method should return if the previous call to login failed, the previous call to commit succeeded, and the abort method itself also succeeded.

LoginModule.abort method return values; login failed
 | ABORT: SUCCESS | ABORT: FAILURE
COMMIT: SUCCESS | return FALSE | return FALSE
COMMIT: FAILURE | return FALSE | return FALSE

LoginModule.logout Method

boolean logout() throws LoginException;

The logout method is called to log out a Subject.

This method removes Principals, and removes/destroys credentials associated with the Subject during the commit operation. This method should not touch those Principals or credentials previously existing in the Subject, or those added by other LoginModules.

If the Subject has been marked read-only (the Subject's isReadOnly method returns true), then this method should only destroy credentials associated with the Subject during the commit operation (removing the credentials is not possible). If the Subject has been marked as read-only and the credentials associated with the Subject during the commit operation are not destroyable (they do not implement the Destroyable interface), then this method may throw a LoginException.

The logout method should return true if logout succeeds, or otherwise throw a LoginException.

Step 4: Choose or Write a Sample Application

Either choose an existing sample application for your testing, or write a new one. See JAAS Reference Guide for information about application requirements and a sample application you can use for your testing.

Step 5: Compile the LoginModule and Application

Compile your new LoginModule and the application you will use for testing.

Step 6: Prepare for Testing

Step 6a: Place Your LoginModule and Application Code in JAR Files

Place your LoginModule and application code in separate JAR files, in preparation for referencing the JAR files in the policy in Step 6c. Here is a sample command for creating a JAR file:

jar cvf <JAR file name> <list of classes, separated by spaces>

This command creates a JAR file with the specified name containing the specified classes.

For more information on the jar tool, see jar (for Solaris) (for Microsoft Windows).

Step 6b: Decide Where to Store the JAR Files

The application can be stored essentially anywhere you like.

Your LoginModule can also be placed anywhere you (and other clients) like. If the LoginModule is fully trusted, it can be placed in the JRE's lib/ext (standard extension) directory.

You will need to test the LoginModule being located both in the lib/ext directory and elsewhere because in one situation your LoginModule will need to explicitly be granted permissions required for any security-sensitive operations it does, while in the other case such permissions are not needed.

If your LoginModule is placed in the JRE's lib/ext directory, it will be treated as an installed extension and no permissions need to be granted, since the default system policy file grants all permissions to installed extensions.

If your LoginModule is placed anywhere else, the permissions need to be granted, for example by grant statements in a policy file.

Decide where you will store the LoginModule JAR file for testing the case where it is not an installed extension. In the next step, you grant permissions to the JAR file, in the specified location.

Step 6c: Set LoginModule and Application JAR File Permissions

If your LoginModule and/or application performs security-sensitive tasks that will trigger security checks (making network connections, reading or writing files on a local disk, etc), it will need to be granted the required permissions if it is not an installed extension (see Step 6b) and it is run while a security manager is installed.

Since LoginModules usually associate Principals and credentials with an authenticated Subject, some types of permissions a LoginModule will typically require are AuthPermissions with target names "modifyPrincipals", "modifyPublicCredentials", and "modifyPrivateCredentials".

A sample statement granting permissions to a LoginModule whose code is in MyLM.jar appears below. Such a statement could appear in a policy file. In this example, the MyLM.jar file is assumed to be in the /localWork directory.

grant codeBase "file:/localWork/MyLM.jar" {
  permission javax.security.auth.AuthPermission "modifyPrincipals";
  permission javax.security.auth.AuthPermission "modifyPublicCredentials";
  permission javax.security.auth.AuthPermission "modifyPrivateCredentials";
};

Note: Since a LoginModule is always invoked within an AccessController.doPrivileged call, it should not have to call doPrivileged itself. If it does, it may inadvertently open up a security hole. For example, a LoginModule that invokes the application-provided CallbackHandler inside a doPrivileged call opens up a security hole by permitting the application's CallbackHandler to gain access to resources it would otherwise not have been able to access.

Step 6d: Create a Configuration Referencing the LoginModule

Because JAAS supports a pluggable authentication architecture, your new LoginModule can be used without requiring modifications to existing applications. Only the login Configuration needs to be updated in order to indicate use of a new LoginModule.

The default Configuration implementation from Sun Microsystems reads configuration information from configuration files, as described in com.sun.security.auth.login.ConfigFile.html.

Create a configuration file to be used for testing. For example, to configure the previously-mentioned hypothetical IBM LoginModule for an application, the configuration file might look like this:

    AppName {
        com.ibm.auth.Module REQUIRED debug=true;
    };
where AppName should be whatever name the application uses to refer to this entry in the login configuration file. The application specifies this name as the first argument to the LoginContext constructor.

Step 7: Test Use of the LoginModule

Finally, test your application and its use of the LoginModule. When you run the application, specify the login configuration file to be used. For example, suppose your application is named MyApp, it is located in MyApp.jar, and your configuration file is test.conf. You could run the application and specify the configuration file via the following:

java -classpath MyApp.jar
 -Djava.security.auth.login.config=test.conf MyApp

Type all that on one line. Multiple lines are used here for legibility.

To specify a policy file named my.policy and run the application with a security manager installed, do the following:

java -classpath MyApp.jar -Djava.security.manager
 -Djava.security.policy=my.policy
 -Djava.security.auth.login.config=test.conf MyApp

Again, type all that on one line.

You may want to configure the LoginModule with a debug option to help ensure that it is working correctly.

Debug your code and continue testing as needed. If you have problems, review the steps above and ensure they are all completed.

Be sure to vary user input and the LoginModule options specified in the configuration file.

Be sure to also include testing using different installation options (e.g., making the LoginModule an installed extension or placing it on the class path) and execution environments (with or without a security manager running). Installation options are discussed in Step 6b. In particular, in order to ensure your LoginModule works when a security manager is installed and the LoginModule and application are not installed extensions, you need to test such an installation and execution environment, after granting required permissions, as described in Step 6c.

If you find during testing that your LoginModule or application needs modifications, make the modifications, recompile (Step 5), place the updated code in a JAR file (Step 6a), re-install the JAR file (Step 6b), if needed fix or add to the permissions (Step 6c), if needed modify the login configuration file (Step 6d), and then re-run the application and repeat these steps as needed.

Step 8: Document Your LoginModule Implementation

The next step is to write documentation for clients of your LoginModule. Example documentation you may want to include is:

  • A README or User Guide describing
    • the authentication process employed by your LoginModule implementation.
    • information on how to install the LoginModule.
    • configuration options accepted by the LoginModule. For each option, specify the option name and possible values (or types of values), as well as the behavior the option controls.
    • the permissions required by your LoginModule when it is run with a security manager (and it is not an installed extension).
  • An example Configuration file that references your new LoginModule.
  • An example policy file granting your LoginModule the required permissions.
  • API documentation. Putting javadoc comments into your source code as you write it will make the API javadocs easy to generate.

Step 9: Make LoginModule JAR File and Documents Available

The final step is to make your LoginModule JAR file and documentation available to clients.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JAAS Reference Guide

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java Authentication and Authorization Service (JAAS)

Reference Guide

for the Java SE Development Kit 6

Introduction
Who Should Read This Document
Related Documentation

Core Classes and Interfaces
Common Classes
Subject
Principals
Credentials
Authentication Classes and Interfaces
LoginContext
LoginModule
CallbackHandler
Callback
Authorization Classes
Policy
AuthPermission
PrivateCredentialPermission

JAAS Tutorials and Sample Programs

Appendix A: JAAS Settings in the java.security Security Properties File

Appendix B: Example Login Configurations

Introduction

The Java Authentication and Authorization Service (JAAS) was introduced as an optional package (extension) to the Java 2 SDK, Standard Edition (J2SDK), v 1.3. JAAS was integrated into the J2SDK 1.4.

JAAS can be used for two purposes:

  • for authentication of users, to reliably and securely determine who is currently executing Java code, regardless of whether the code is running as an application, an applet, a bean, or a servlet; and
  • for authorization of users to ensure they have the access control rights (permissions) required to do the actions performed.

JAAS implements a Java version of the standard Pluggable Authentication Module (PAM) framework. See Making Login Services Independent from Authentication Technologies for further information.

Traditionally Java has provided codesource-based access controls (access controls based on where the code originated from and who signed the code). It lacked, however, the ability to additionally enforce access controls based on who runs the code. JAAS provides a framework that augments the Java security architecture with such support.

JAAS authentication is performed in a pluggable fashion. This permits applications to remain independent from underlying authentication technologies. New or updated authentication technologies can be plugged under an application without requiring modifications to the application itself. Applications enable the authentication process by instantiating a LoginContext object, which in turn references a Configuration to determine the authentication technology(ies), or LoginModule(s), to be used in performing the authentication. Typical LoginModules may prompt for and verify a username and password. Others may read and verify a voice or fingerprint sample.

Once the user or service executing the code has been authenticated, the JAAS authorization component works in conjunction with the core Java SE access control model to protect access to sensitive resources. Unlike in the J2SDK 1.3 and earlier, where access control decisions are based solely on code location and code signers (a CodeSource), in the J2SDK 1.4 access control decisions are based both on the executing code's CodeSource and on the user or service running the code, who is represented by a Subject object. The Subject is updated by a LoginModule with relevant Principals and credentials if authentication succeeds.

Who Should Read This Document

This document is intended for experienced developers who require the ability to design applications constrained by a CodeSource-based and Subject-based security model. It is also intended to be read by LoginModule developers (developers implementing an authentication technology) prior to reading the JAAS LoginModule Developer's Guide.

You may wish to first read the JAAS Authentication and JAAS Authorization tutorials to get an overview of how to use JAAS and to see sample code in action, and then return to this document for further information.

Related Documentation

This document assumes you have already read the following:

  • Java SE Security Architecture
  • JAAS white paper
  • Java SE Security Tutorial

A supplement to this guide is the JAAS LoginModule Developer's Guide, intended for experienced programmers who require the ability to write a LoginModule implementing an authentication technology.

If you wish to learn more about the standard Pluggable Authentication Module (PAM) framework (JAAS implements a Java version of PAM), see Making Login Services Independent from Authentication Technologies.

The following tutorials for JAAS authentication and authorization can be run by everyone:

  • JAAS Authentication Tutorial
  • JAAS Authorization Tutorial

Similar tutorials for JAAS authentication and authorization, but which demonstrate the use of a Kerberos LoginModule and thus which require a Kerberos installation, can be found at

  • JAAS Authentication
  • JAAS Authorization

These two tutorials are a part of the Java GSS-API and JAAS sequence of tutorials that utilize Kerberos as the underlying technology for authentication and secure communication.

Core Classes and Interfaces

The JAAS-related core classes and interfaces can be broken into three categories: Common, Authentication, and Authorization.
  • Common Classes
    • Subject, Principal, Credential (actually, any Object)
  • Authentication Classes and Interfaces
    • LoginContext, LoginModule, CallbackHandler, Callback
  • Authorization Classes
    • Policy, AuthPermission, PrivateCredentialPermission

Common Classes

Common classes are those shared by both the JAAS authentication and authorization components.

The key JAAS class is javax.security.auth.Subject, which represents a grouping of related information for a single entity such as a person. It encompasses the entity's Principals, public credentials, and private credentials.

Note that the java.security.Principal interface is used to represent a Principal. Also note that a credential, as defined by JAAS, may be any Object.

Subject

To authorize access to resources, applications first need to authenticate the source of the request. The JAAS framework defines the term subject to represent the source of a request. A subject may be any entity, such as a person or a service. Once the subject is authenticated, a javax.security.auth.Subject is populated with associated identities, or Principals. A Subject may have many Principals. For example, a person may have a name Principal ("John Doe") and a SSN Principal ("123-45-6789"), which distinguish it from other subjects.

A Subject may also own security-related attributes, which are referred to as credentials. Sensitive credentials that require special protection, such as private cryptographic keys, are stored within a private credential Set. Credentials intended to be shared, such as public key certificates, are stored within a public credential Set. Different permissions (described below) are required to access and modify the different credential Sets.

Subjects are created using these constructors:

    public Subject();

    public Subject(boolean readOnly, Set principals,
                   Set pubCredentials, Set privCredentials);
The first constructor creates a Subject with empty (non-null) Sets of Principals and credentials. The second constructor creates a Subject with the specified Sets of Principals and credentials. It also has a boolean argument which can be used to make the Subject read-only. In a read-only Subject, the Principal and credential Sets are immutable.

An application writer does not have to instantiate a Subject. If the application instantiates a LoginContext and does not pass a Subject to the LoginContext constructor, the LoginContext instantiates a new empty Subject. See the LoginContext section.

If a Subject was not instantiated to be in a read-only state, it can be set read-only by calling the following method:

    public void setReadOnly();
A javax.security.auth.AuthPermission with target "setReadOnly" is required to invoke this method. Once in a read-only state, any attempt to add or remove Principals or credentials will result in an IllegalStateException being thrown.

The following method may be called to test a Subject's read-only state:

    public boolean isReadOnly();

To retrieve the Principals associated with a Subject, two methods are available:

    public Set getPrincipals();
    public Set getPrincipals(Class c);

The first method returns all Principals contained in the Subject, while the second method only returns those Principals that are an instance of the specified Class c, or an instance of a subclass of Class c. An empty set will be returned if the Subject does not have any associated Principals.

To retrieve the public credentials associated with a Subject, these methods are available:

    public Set getPublicCredentials();
    public Set getPublicCredentials(Class c);

The behavior of these methods is similar to that for the getPrincipals methods, except in this case the public credentials are being obtained.

To access private credentials associated with a Subject, the following methods are available:

    public Set getPrivateCredentials();
    public Set getPrivateCredentials(Class c);

The behavior of these methods is similar to that for the getPrincipals and getPublicCredentials methods.

To modify or operate upon a Subject's Principal Set, public credential Set, or private credential Set, callers use the methods defined in the java.util.Set class. The following example demonstrates this:

    Subject subject;
    Principal principal;
    Object credential;

    . . .

    // add a Principal and credential to the Subject
    subject.getPrincipals().add(principal);
    subject.getPublicCredentials().add(credential);

Note: An AuthPermission with target "modifyPrincipals", "modifyPublicCredentials", or "modifyPrivateCredentials" is required to modify the respective Sets. Also note that only the sets returned via the getPrincipals(), getPublicCredentials(), and getPrivateCredentials() methods with no arguments are backed by the Subject's respective internal sets. Therefore any modification to the returned set affects the internal sets as well. The sets returned via the getPrincipals(Class c), getPublicCredentials(Class c), and getPrivateCredentials(Class c) methods are not backed by the Subject's respective internal sets. A new set is created and returned for each such method invocation. Modifications to these sets will not affect the Subject's internal sets.

In order to iterate through a Set of private credentials, you need a javax.security.auth.PrivateCredentialPermission to access each credential. See the PrivateCredentialPermission API documentation for further information.

A Subject may be associated with an AccessControlContext (see the doAs and doAsPrivileged method descriptions below). The following method returns the Subject associated with the specified AccessControlContext, or null if no Subject is associated with the specified AccessControlContext.

    public static Subject getSubject(final AccessControlContext acc);

An AuthPermission with target "getSubject" is required to call Subject.getSubject.

The Subject class also includes the following methods inherited from java.lang.Object.

    public boolean equals(Object o);
    public String toString();
    public int hashCode();

The doAs methods for performing an action as a particular Subject

The following static methods may be called to perform an action as a particular Subject:
    public static Object
        doAs(final Subject subject,
             final java.security.PrivilegedAction action);

    public static Object
        doAs(final Subject subject,
             final java.security.PrivilegedExceptionAction action)
             throws java.security.PrivilegedActionException;

Both methods first associate the specified subject with the current Thread's AccessControlContext, and then execute the action. This achieves the effect of having the action run as the subject. The first method can throw runtime exceptions but normal execution has it returning an Object from the run method of its action argument. The second method behaves similarly except that it can throw a checked exception from its PrivilegedExceptionAction run method. An AuthPermission with target "doAs" is required to call the doAs methods.

Subject.doAs Example

Here is an example utilizing the first doAs method. Assume that someone named "Bob" has been authenticated by a LoginContext (see the LoginContext section) and as a result a Subject was populated with a Principal of class com.ibm.security.Principal, and that Principal has the name "BOB". Also assume that a SecurityManager has been installed, and that the following exists in the access control policy (see the Policy section for more details on the policy file).

    // grant "BOB" permission to read the file "foo.txt"
    grant Principal com.ibm.security.Principal "BOB" {
        permission java.io.FilePermission "foo.txt", "read";
    };

Here is the sample application code:

    class ExampleAction implements java.security.PrivilegedAction {
        public Object run() {
            java.io.File f = new java.io.File("foo.txt");

            // the following call invokes a security check
            if (f.exists()) {
                System.out.println("File foo.txt exists");
            }
            return null;
        }
    }

    public class Example1 {
        public static void main(String[] args) {

            // Authenticate the subject, "BOB".
            // This process is described in the
            // LoginContext section.

            Subject bob;
            // Set bob to the Subject created during the
            // authentication process

            // perform "ExampleAction" as "BOB"
            Subject.doAs(bob, new ExampleAction());
        }
    }

During execution, ExampleAction will encounter a security check when it makes a call to f.exists(). However, since ExampleAction is running as "BOB", and the policy (above) grants the necessary FilePermission to "BOB", the ExampleAction will pass the security check. If the grant statement in the policy is altered (adding an incorrect CodeBase or changing the Principal to "MOE", for example), then a SecurityException will be thrown.

The doAsPrivileged methods

The following methods also perform an action as a particular Subject.

    public static Object doAsPrivileged(
        final Subject subject,
        final java.security.PrivilegedAction action,
        final java.security.AccessControlContext acc);

    public static Object doAsPrivileged(
        final Subject subject,
        final java.security.PrivilegedExceptionAction action,
        final java.security.AccessControlContext acc)
        throws java.security.PrivilegedActionException;

An AuthPermission with target "doAsPrivileged" is required to call the doAsPrivileged methods.

doAs vs. doAsPrivileged

The doAsPrivileged methods behave exactly the same as the doAs methods, except that instead of associating the provided Subject with the current Thread's AccessControlContext, they use the provided AccessControlContext. In this way, actions can be restricted by AccessControlContexts different from the current one.

An AccessControlContext contains information about all the code executed since the AccessControlContext was instantiated, including the code location and the permissions the code is granted by the policy. In order for an access control check to succeed, the policy must grant each code item referenced by the AccessControlContext the required permissions.

If the AccessControlContext provided to doAsPrivileged is null, then the action is not restricted by a separate AccessControlContext. One example where this may be useful is in a server environment. A server may authenticate multiple incoming requests and perform a separate doAs operation for each request. To start each doAs action "fresh," and without the restrictions of the current server AccessControlContext, the server can call doAsPrivileged and pass in a null AccessControlContext.

Principals

As mentioned previously, Principals may be associated with a Subject if authentication is successful. Principals represent Subject identities, and must implement the java.security.Principal and java.io.Serializable interfaces. The Subject section describes ways to update the Principals associated with a Subject.

Credentials

Public and private credential classes are not part of the core JAAS class library. Any class can represent a credential. Developers, however, may elect to have their credential classes implement two interfaces related to credentials: Refreshable and Destroyable.

Refreshable

The javax.security.auth.Refreshable interface provides the capability for a credential to refresh itself. For example, a credential with a particular time-restricted lifespan may implement this interface to allow callers to refresh the time period for which it is valid. The interface has two abstract methods:

    boolean isCurrent();
This method determines whether the credential is current or valid.
    void refresh() throws RefreshFailedException;
This method updates or extends the validity of the credential. The method implementation should perform an AuthPermission("refreshCredential") security check to ensure the caller has permission to refresh the credential.

Destroyable

The javax.security.auth.Destroyable interface provides the capability of destroying the contents within a credential. The interface has two abstract methods:

    boolean isDestroyed();
Determines whether the credential has been destroyed.
    void destroy() throws DestroyFailedException;
Destroys and clears the information associated with this credential. Subsequent calls to certain methods on this credential will result in an IllegalStateException being thrown. The method implementation should perform an AuthPermission("destroyCredential") security check to ensure the caller has permission to destroy the credential.

Authentication Classes and Interfaces

To authenticate a subject (user or service), the following steps are performed:
  1. An application instantiates a LoginContext.
  2. The LoginContext consults a Configuration to load all of the LoginModules configured for that application.
  3. The application invokes the LoginContext's login method.
  4. The login method invokes all of the loaded LoginModules. Each LoginModule attempts to authenticate the subject. Upon success, LoginModules associate relevant Principals and credentials with a Subject object that represents the subject being authenticated.
  5. The LoginContext returns the authentication status to the application.
  6. If authentication succeeded, the application retrieves the Subject from the LoginContext.

The authentication classes are described below.

LoginContext

The javax.security.auth.login.LoginContext class provides the basic methods used to authenticate subjects, and provides a way to develop an application independent of the underlying authentication technology. The LoginContext consults a Configuration to determine the authentication services, or LoginModule(s), configured for a particular application. Therefore, different LoginModules can be plugged in under an application without requiring any modifications to the application itself.

LoginContext offers four constructors from which to choose:

    public LoginContext(String name) throws LoginException;

    public LoginContext(String name, Subject subject) throws LoginException;

    public LoginContext(String name, CallbackHandler callbackHandler)
           throws LoginException

    public LoginContext(String name, Subject subject,
           CallbackHandler callbackHandler) throws LoginException
All of the constructors share a common parameter: name. This argument is used by the LoginContext as an index into the login Configuration to determine which LoginModules are configured for the application instantiating the LoginContext. Constructors that do not take a Subject as an input parameter instantiate a new Subject. Null inputs are disallowed for all constructors. Callers require an AuthPermission with target "createLoginContext.<name>" to instantiate a LoginContext. Here, <name> refers to the name of the login configuration entry that the application references in the name parameter for the LoginContext instantiation.

See the CallbackHandler section for information on what a CallbackHandler is and when you may need one.

Actual authentication occurs with a call to the following method:

    public void login() throws LoginException;

When login is invoked, all of the configured LoginModules are invoked to perform the authentication. If the authentication succeeded, the Subject (which may now hold Principals, public credentials, and private credentials) can be retrieved by using the following method:

     public Subject getSubject();

To logout a Subject and remove its authenticated Principals and credentials, the following method is provided:

    public void logout() throws LoginException;

The following code sample demonstrates the calls necessary to authenticate and logout a Subject:

    // let the LoginContext instantiate a new Subject
    LoginContext lc = new LoginContext("entryFoo");
    try {
        // authenticate the Subject
        lc.login();
        System.out.println("authentication successful");

        // get the authenticated Subject
        Subject subject = lc.getSubject();

        ...

        // all finished -- logout
        lc.logout();
    } catch (LoginException le) {
        System.err.println("authentication unsuccessful: " +
            le.getMessage());
    }

LoginModule

The LoginModule interface gives developers the ability to implement different kinds of authentication technologies that can be plugged in under an application. For example, one type of LoginModule may perform a username/password-based form of authentication. Other LoginModules may interface to hardware devices such as smart cards or biometric devices.

Note: If you are an application writer, you do not need to understand the workings of LoginModules. All you have to know is how to write your application and specify configuration information (such as in a login configuration file) such that the application will be able to utilize the LoginModule specified by the configuration to authenticate the user.

If, on the other hand, you are a programmer who wishes to write a LoginModule implementing an authentication technology, see the JAAS LoginModule Developer's Guide for detailed step-by-step instructions.

CallbackHandler

In some cases a LoginModule must communicate with the user to obtain authentication information. LoginModules use a javax.security.auth.callback.CallbackHandler for this purpose. Applications implement the CallbackHandler interface and pass it to the LoginContext, which forwards it directly to the underlying LoginModules. A LoginModule uses the CallbackHandler both to gather input from users (such as a password or smart card pin number) or to supply information to users (such as status information). By allowing the application to specify the CallbackHandler, underlying LoginModules can remain independent of the different ways applications interact with users. For example, the implementation of a CallbackHandler for a GUI application might display a window to solicit input from a user. On the other hand, the implementation of a CallbackHandler for a non-GUI tool might simply prompt the user for input directly from the command line.

CallbackHandler is an interface with one method to implement:
     void handle(Callback[] callbacks)
         throws java.io.IOException, UnsupportedCallbackException;

The LoginModule passes the CallbackHandler handle method an array of appropriate Callbacks, for example a NameCallback for the user name and a PasswordCallback for the password, and the CallbackHandler performs the requested user interaction and sets appropriate values in the Callbacks. For example, to process a NameCallback, the CallbackHandler may prompt for a name, retrieve the value from the user, and call the NameCallback's setName method to store the name.

The CallbackHandler documentation has a lengthy example not included in this document that readers may want to examine.

Callback

The javax.security.auth.callback package contains the Callback interface as well as several implementations. LoginModules may pass an array of Callbacks directly to the handle method of a CallbackHandler.

Please consult the various Callback APIs for more information on their use.

Authorization Classes

To make JAAS authorization take place, granting access control permissions based not just on what code is running but also on who is running it, the following is required:

  • The user must be authenticated, as described in the LoginContext section.
  • The Subject that is the result of authentication must be associated with an access control context, as described in the Subject section.
  • Principal-based entries must be configured in the security policy, as described below.

The Policy abstract class and the authorization-specific classes AuthPermission and PrivateCredentialPermission are described below.

Policy

The java.security.Policy class is an abstract class for representing the system-wide access control policy. The Policy API was upgraded in the J2SDK 1.4 to support Principal-based queries.

As a default, the J2SDK provides a file-based subclass implementation, which was upgraded to support Principal-based grant entries in policy files.

Policy files and the structure of entries within them are described in Default Policy Implementation and Policy File Syntax.

AuthPermission

The javax.security.auth.AuthPermission class encapsulates the basic permissions required for JAAS. An AuthPermission contains a name (also referred to as a "target name") but no actions list; you either have the named permission or you don't.

In addition to its inherited methods (from the java.security.Permission class), an AuthPermission has two public constructors:

    public AuthPermission(String name);
    public AuthPermission(String name, String actions);
The first constructor creates a new AuthPermission with the specified name. The second constructor also creates a new AuthPermission object with the specified name, but has an additional actions argument which is currently unused and should be null. This constructor exists solely for the Policy object to instantiate new Permission objects. For most other code, the first constructor is appropriate.

Currently the AuthPermission object is used to guard access to the Policy, Subject, LoginContext, and Configuration objects. Please refer to the AuthPermission javadocs for the list of valid names that are supported.

PrivateCredentialPermission

The javax.security.auth.PrivateCredentialPermission class protects access to a Subject's private credentials and provides one public constructor:

     public PrivateCredentialPermission(String name, String actions);
Please refer to the PrivateCredentialPermission javadocs for more detailed information on this class.

JAAS Tutorials and Sample Programs

The JAAS Authentication and JAAS Authorization tutorials contain the following samples:

  • SampleAcn.java is a sample application demonstrating JAAS authentication.
  • SampleAzn.java is a sample application used by the authorization tutorial. It demonstrates both authentication and authorization.
  • sample_jaas.config is a sample login configuration file used by both tutorials.
  • sampleacn.policy is a sample policy file granting permissions required by the code for the authentication tutorial.
  • sampleazn.policy is a sample policy file granting permissions required by the code for the authorization tutorial.
  • SampleLoginModule.java is the class specified by the tutorials' login configuration file (sample_jaas.config) as the class implementing the desired underlying authentication. SampleLoginModule's user authentication consists of simply verifying that the name and password specified by the user have specific values.
  • SamplePrincipal.java is a sample class implementing the Principal interface. It is used by SampleLoginModule.

See the tutorials for detailed information about the applications, the policy files, and the login configuration file.

Application writers do not need to understand the code for SampleLoginModule.java or SamplePrincipal.java, as explained in the tutorials. Programmers who wish to write LoginModules can learn how to do so by reading the JAAS LoginModule Developer's Guide.

Appendix A: JAAS Settings in the java.security Security Properties File

A number of JAAS-related settings can be configured in the java.security master security properties file, which is located in the lib/security directory of the Java runtime.

JAAS adds two new security properties to java.security:

  • login.configuration.provider
  • login.config.url.n

The following pre-existing properties are also relevant for JAAS users:

  • policy.provider
  • policy.url.n

Login Configuration Provider

The default JAAS login configuration implementation provided by Sun Microsystems gets its configuration information from files and expects the information to be provided in a specific format shown in the tutorials.

The default JAAS login configuration implementation can be replaced by specifying the alternative provider class implementation in the login.configuration.provider property.

For example:

  login.configuration.provider=com.foo.Config
If the Security property login.configuration.provider is not found, or is left unspecified, then it is set to the default value:
  login.configuration.provider=com.sun.security.auth.login.ConfigFile

Note that there is no means to dynamically set the login configuration provider from the command line.

Login Configuration URLs

If you are using a login configuration implementation that expects the configuration information to be specified in files (as does the default implementation from Sun Microsystems), the location of the login configuration file(s) can be statically set by specifying their respective URLs in the login.config.url.n property. 'n' is a consecutively numbered integer starting with 1. If multiple configuration files are specified (if n >= 2), they will be read and unioned into one single configuration.

For example:

  login.config.url.1=file:C:/config/.java.login.config
  login.config.url.2=file:C:/users/foo/.foo.login.config

If the location of the configuration files is not set in the java.security properties file, and also is not specified dynamically from the command line (via the -Djava.security.auth.login.config option), JAAS attempts to load a default configuration from

file:${user.home}/.java.login.config

Policy Provider

The default policy implementation can be replaced by specifying the alternative provider class implementation in the policy.provider property.

For example:

  policy.provider=com.foo.Policy
If the Security property policy.provider is not found, or is left unspecified, then the Policy is set to the default value:
  policy.provider=sun.security.provider.PolicyFile

Note that there is no means to dynamically set the policy provider from the command line.

Policy File URLs

The location of the access control policy files can be statically set by specifying their respective URLs in the auth.policy.url.n property. 'n' is a consecutively numbered integer starting with 1. If multiple policies are specified (if n >= 2), they will be read and unioned into one single policy.

For example:

  policy.url.1=file:C:/policy/.java.policy
  policy.url.2=file:C:/users/foo/.foo.policy

If the location of the policy file(s) is not set in the java.security properties file, and is not specified dynamically from the command line (via the -Djava.security.policy option), the access control policy defaults to the same policy as that of the system policy file installed with the J2SDK. That policy file

  • grants all permissions to standard extensions
  • allows anyone to listen on un-privileged ports
  • allows any code to read certain "standard" properties that are not security-sensitive, such as the "os.name" and "file.separator" properties.

Sample Master Security Properties File

Below is a modified copy of the java.security file provided with the Java SE 6. Example settings for JAAS-related properties are shown in bold. In this example, we leave the values provided in the default java.security file for the policy.provider, policy.url.n, and login.configuration.provider properties. The default java.security file also lists a value for the login.config.url.n property, but it is commented out. In the example below, it is not commented.

#
# This is the "master security properties file".
#
# In this file, various security properties are set for use by
# java.security classes. This is where users can statically register
# Cryptography Package Providers ("providers" for short). The term
# "provider" refers to a package or set of packages that supply a
# concrete implementation of a subset of the cryptography aspects of
# the Java Security API. A provider may, for example, implement one or
# more digital signature algorithms or message digest algorithms.
#
# Each provider must implement a subclass of the Provider class.
# To register a provider in this master security properties file,
# specify the Provider subclass name and priority in the format
#
#    security.provider.<n>=<className>
#
# This declares a provider, and specifies its preference
# order <n>. The preference order is the order in which providers are
# searched for requested algorithms (when no specific provider is
# requested). The order is 1-based; 1 is the most preferred, followed
# by 2, and so on.
#
# <className> must specify the subclass of the Provider class whose
# constructor sets the values of various properties that are required
# for the Java Security API to look up the algorithms or other
# facilities implemented by the provider.
#
# There must be at least one provider specification in java.security.
# There is a default provider that comes standard with the JDK. It
# is called the "SUN" provider, and its Provider subclass
# named Sun appears in the sun.security.provider package. Thus, the
# "SUN" provider is registered via the following:
#
#    security.provider.1=sun.security.provider.Sun
#
# (The number 1 is used for the default provider.)
#
# Note: Statically registered Provider subclasses are instantiated
# when the system is initialized. Providers can be dynamically
# registered instead by calls to either the addProvider or
# insertProviderAt method in the Security class.

#
# List of providers and their preference orders (see above):
#
security.provider.1=sun.security.provider.Sun
security.provider.2=com.sun.net.ssl.internal.ssl.Provider
security.provider.3=com.sun.rsajca.Provider
security.provider.4=com.sun.crypto.provider.SunJCE
security.provider.5=sun.security.jgss.SunProvider

#
# Select the source of seed data for SecureRandom. By default it uses
# a system/thread activity algorithm. Optionally, if the platform supports
# it an entropy gathering device can be selected.
#
#securerandom.source=file:/dev/random
#
# The entropy gathering device is described as a URL and can
# also be specified with the property "java.security.egd". For example,
#   -Djava.security.egd=file:/dev/urandom
# Specifying this property will override the securerandom.source setting.

#
# Class to instantiate as the javax.security.auth.login.Configuration
# provider.
#
login.configuration.provider=com.sun.security.auth.login.ConfigFile

#
# Default login configuration file
#
login.config.url.1=file:${user.home}/.java.login.config

#
# Class to instantiate as the system Policy. This is the name of the class
# that will be used as the Policy object.
#
policy.provider=sun.security.provider.PolicyFile

# The default is to have a single system-wide policy file,
# and a policy file in the user's home directory.
policy.url.1=file:${java.home}/lib/security/java.policy
policy.url.2=file:${user.home}/.java.policy

# whether or not we expand properties in the policy file
# if this is set to false, properties (${...}) will not be expanded in policy
# files.
policy.expandProperties=true

# whether or not we allow an extra policy to be passed on the command line
# with -Djava.security.policy=somefile. Comment out this line to disable
# this feature.
policy.allowSystemProperty=true

# whether or not we look into the IdentityScope for trusted Identities
# when encountering a 1.1 signed JAR file. If the identity is found
# and is trusted, we grant it AllPermission.
policy.ignoreIdentityScope=false

#
# Default keystore type.
#
keystore.type=jks

#
# Class to instantiate as the system scope:
#
system.scope=sun.security.provider.IdentityDatabase

#
# List of comma-separated packages that start with or equal this string
# will cause a security exception to be thrown when
# passed to checkPackageAccess unless the
# corresponding RuntimePermission ("accessClassInPackage."+package) has
# been granted.
package.access=sun.

#
# List of comma-separated packages that start with or equal this string
# will cause a security exception to be thrown when
# passed to checkPackageDefinition unless the
# corresponding RuntimePermission ("defineClassInPackage."+package) has
# been granted.
#
# by default, no packages are restricted for definition, and none of
# the class loaders supplied with the JDK call checkPackageDefinition.
#
#package.definition=

#
# Determines whether this properties file can be appended to
# or overridden on the command line via -Djava.security.properties
#
security.overridePropertiesFile=true

#
# Determines the default key and trust manager factory algorithms for
# the javax.net.ssl package.
#
ssl.KeyManagerFactory.algorithm=SunX509
ssl.TrustManagerFactory.algorithm=SunX509

#
# Determines the default SSLSocketFactory and SSLServerSocketFactory
# provider implementations for the javax.net.ssl package.  If, due to
# export and/or import regulations, the providers are not allowed to be
# replaced, changing these values will produce non-functional
# SocketFactory or ServerSocketFactory implementations.
#
#ssl.SocketFactory.provider=
#ssl.ServerSocketFactory.provider=

Appendix B: Example Login Configurations

Login configurations are located using the login.config.url.n security properties found in the java.security file. For more information about this property and the location of the java.security file, see Appendix A.

The default Configuration implementation, ConfigFile, gets its configuration information from login configuration files. For details about the default login Configuration implementation provided with JAAS, please consult the javadocs for the com.sun.security.auth.login.ConfigFile class.

The following is a sample login configuration file.

    Login1 {
       sample.SampleLoginModule required debug=true;
    };

    Login2 {
       sample.SampleLoginModule required;
       com.sun.security.auth.module.NTLoginModule sufficient;
       com.foo.SmartCard requisite debug=true;
       com.foo.Kerberos optional debug=true;
    };

The application Login1 only has one configured LoginModule, SampleLoginModule. Therefore, an attempt by Login1 to authenticate a subject (user or service) will be successful if and only if the SampleLoginModule succeeds.

The authentication logic for the application Login2 is easier to explain with the table below. Note: the required, sufficient, requisite, and optional flags are described in the Configuration javadocs.

Login2 Authentication Status
SampleLoginModule | required | pass | pass | pass | pass | fail | fail | fail | fail
NTLoginModule | sufficient | pass | fail | fail | fail | pass | fail | fail | fail
SmartCard | requisite | * | pass | pass | fail | * | pass | pass | fail
Kerberos | optional | * | pass | fail | * | * | pass | fail | *
Overall Authentication | not applicable | pass | pass | pass | fail | fail | fail | fail | fail
* = trivial value due to control returning to the application because a previous requisite module failed or a previous sufficient module succeeded.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


jar-The Java Archive Tool

jar combines multiple files into a single JAR archive file.
  • Synopsis
  • Description
  • Options
  • Command Line Argument Files
  • Examples
  • See Also

SYNOPSIS

Create jar file
jar c[v0Mmfe] [manifest] [jarfile] [entrypoint] [-C dir] inputfiles [-J option]
Update jar file
jar u[v0Mmfe] [manifest] [jarfile] [entrypoint] [-C dir] inputfiles [-J option]
Extract jar file
jar x[vf] [jarfile] [inputfiles] [-J option]
List table of contents of jar file
jar t[vf] [jarfile] [inputfiles] [-J option]
Add index to jar file
jar i jarfile [-J option]

where:

cuxtiv0Mmfe
Options that control the jar command.
jarfile
Jar file to be created (c), updated (u), extracted (x), or have its table of contents viewed (t). The -f option and filename jarfile are a pair -- if either is present, they must both appear. Note that omitting f and jarfile accepts a "jar file" from standard input (for x and t) or sends the "jar file" to standard output (for c and u).
inputfiles
Files or directories, separated by spaces, to be combined into jarfile (for c and u), or to be extracted (for x) or listed (for t) from jarfile. All directories are processed recursively. The files are compressed unless option 0 (zero) is used.
manifest
Pre-existing manifest file whose name: value pairs are to be included in MANIFEST.MF in the jar file. The -m option and filename manifest are a pair -- if either is present, they must both appear. The letters m, f and e must appear in the same order that manifest, jarfile, entrypoint appear.
entrypoint
The name of the class that set as the application entry point for stand-alone applications bundled into executable jar file. The -e option and entrypoint are a pair -- if either is present, they must both appear. The letters m, f and e must appear in the same order that manifest, jarfile, entrypoint appear.
-C dir
Temporarily changes directories to dir while processing the following inputfiles argument. Multiple -C dir inputfiles sets are allowed.
-J option
Option to be passed into the Java runtime environment. (There must be no space between -J and option).

DESCRIPTION

The jar tool combines multiple files into a single JAR archive file. jar is a general-purpose archiving and compression tool, based on ZIP and the ZLIB compression format. However, jar was designed mainly package java applets or applications into a single archive. When the components of an applet or application (files, images and sounds) are combined into a single archive, they can be downloaded by a java agent (like a browser) in a single HTTP transaction, rather than requiring a new connection for each piece. This dramatically improves download times. jar also compresses files and so further improves download time. In addition, it allows individual entries in a file to be signed by the applet author so that their origin can be authenticated. The syntax for the jar tool is almost identical to the syntax for the tar command. A jar archive can be used as a class path entry, whether or not it is compressed.

Typical usage to combine files into a jar file is:

% jar cf myFile.jar *.class
In this example, all the class files in the current directory are placed into the file named myFile.jar. The jar tool automatically generates a manifest file entry named META-INF/MANIFEST.MF. It is always the first entry in the jar file. The manifest file declares meta-information about the archive, and stores that data as name : value pairs. Refer to the JAR file specification for details explaining how the jar tool stores meta-information in the manifest file.

If a jar file should include name : value pairs contained in an existing manifest file, specify that file using the -m option:

% jar cmf myManifestFile myFile.jar *.class
An existing manifest file must end with a new line character. jar does not parse the last line of a manifest file if it does not end with a new line character.

Note: A jar command that specifies cfm on the command line instead of cmf (the order of the m and -f options are reversed), the jar command line must specify the name of the jar archive first, followed by the name of the manifest file:
% jar cfm myFile.jar myManifestFile *.class
The manifest is in a text format inspired by RFC822 ASCII format, so it is easy to view and process manifest-file contents.

To extract the files from a jar file, use x:

% jar xf myFile.jar

To extract individual files from a jar file, supply their filenames:

% jar xf myFile.jar foo bar

Beginning with version 1.3 of the JDK, the jar utility supports JarIndex, which allows application class loaders to load classes more efficiently from jar files. If an application or applet is bundled into multiple jar files, only the necessary jar files will be downloaded and opened to load classes. This performance optimization is enabled by running jar with the -ioption. It will generate package location information for the specified main jar file and all the jar files it depends on, which need to be specified in the Class-Path attribute of the main jar file's manifest.

% jar i main.jar

In this example, an INDEX.LIST file is inserted into the META-INF directory of main.jar.

The application class loader uses the information stored in this file for efficient class loading. For details about how location information is stored in the index file, refer to the JarIndex specification.

To copy directories, first compress files in dir1 to stdout, then extract from stdin to dir2 (omitting the -f option from both jar commands):

% (cd dir1; jar c .) | (cd dir2; jar x)

To review command samples which use jar to opeate on jar files and jar file manifests, see Examples, below. Also refer to the jar trail of the Java Tutorial.

OPTIONS

c
Creates a new archive file named jarfile (if f is specified) or to standard output (if f and jarfile are omitted). Add to it the files and directories specified by inputfiles.
u
Updates an existing file jarfile (when f is specified) by adding to it files and directories specified by inputfiles. For example:
jar uf foo.jar foo.class
would add the file foo.class to the existing jar file foo.jar. The -u option can also update the manifest entry, as given by this example:
jar umf manifest foo.jar
updates the foo.jar manifest with the name : value pairs in manifest.
x
Extracts files and directories from jarfile (if f is specified) or standard input (if f and jarfile are omitted). If inputfiles is specified, only those specified files and directories are extracted. Otherwise, all files and directories are extracted. The time and date of the extracted files are those given in the archive.
t
Lists the table of contents from jarfile (if f is specified) or standard input (if f and jarfile are omitted). If inputfiles is specified, only those specified files and directories are listed. Otherwise, all files and directories are listed.
i
Generate index information for the specified jarfile and its dependent jar files. For example:
jar i foo.jar

would generate an INDEX.LIST file in foo.jar which contains location information for each package in foo.jar and all the jar files specified in the Class-Path attribute of foo.jar. See the index example.

f
Specifies the file jarfile to be created (c), updated (u), extracted (x), indexed (i), or viewed (t). The -f option and filename jarfile are a pair -- if present, they must both appear. Omitting f and jarfile accepts a jar file name from stdin(for x and t) or sends jar file to stdout (for c and u).
v
Generates verbose output to standard output. Examples shown below.
0
(zero) Store without using ZIP compression.
M
Do not create a manifest file entry (for c and u), or delete a manifest file entry if one exists (for u).
m
Includes name : value attribute pairs from the specified manifest file manifest in the file at META-INF/MANIFEST.MF. jar adds a name : value pair unless an entry already exists with the same name, in which case jar updates its value.

On the command line, the letters m and f must appear in the same order that manifest and jarfile appear. Example use:

jar cmf myManifestFile myFile.jar *.class
You can add special-purpose name : value attribute pairs to the manifest that aren't contained in the default manifest. For example, you can add attributes specifying vendor information, version information, package sealing, or to make JAR-bundled applications executable. See the JAR Files trail in the Java Tutorial for examples of using the -m option.
e
Sets entrypoint as the application entry point for stand-alone applications bundled into executable jar file. The use of this option creates or overrides the Main-Class attribute value in the manifest file. This option can be used during creation of jar file or while updating the jar file. This option specifies the application entry point without editing or creating the manifest file.

For example, this command creates Main.jar where the Main-Class attribute value in the manifest is set to Main:
jar cfe Main.jar Main Main.class

The java runtime can directly invoke this application by running the following command:

java -jar Main.jar
If the entrypoint class name is in a package it may use either a dot (".") or slash ("/") character as the delimiter. For example, if Main.class is in a package called foo the entry point can be specified in the following ways:
jar -cfe Main.jar foo/Main foo/Main.class
or
jar -cfe Main.jar foo.Main foo/Main.class
Note: specifying both -m and -e options together when the given manifest also contains the Main-Class attribute results in an ambigous Main.class specification, leading to an error and the jar creation or update operation is aborted.

-C dir
Temporarily changes directories (cd dir) during execution of the jar command while processing the following inputfiles argument. Its operation is intended to be similar to the -C option of the UNIX tar utility.

For example, this command changes to the classes directory and adds the bar.class from that directory to foo.jar:
jar uf foo.jar -C classes bar.class
This command changes to the classes directory and adds to foo.jar all files within the classes directory (without creating a classes directory in the jar file), then changes back to the original directory before changing to the bin directory to add xyz.class to foo.jar.
jar uf foo.jar -C classes . -C bin xyz.class
If classes holds files bar1 and bar2, then here's what the jar file will contain using jar tf foo.jar:
META-INF/
META-INF/MANIFEST.MF
bar1
bar2
xyz.class

-Joption
Pass option to the Java runtime environment, where option is one of the options described on the reference page for the java application launcher. For example, -J-Xmx48M sets the maximum memory to 48 megabytes. It is a common convention for -J to pass options to the underlying runtime environment.

COMMAND LINE ARGUMENT FILES

To shorten or simplify the jar command line, you can specify one or more files that themselves contain arguments to the jar command (except -J options). This enables you to create jar commands of any length, overcoming command line limits imposed by the operating system.

An argument file can include options and filenames. The arguments within a file can be space-separated or newline-separated. Filenames within an argument file are relative to the current directory, not relative to the location of the argument file. Wildcards (*) that might otherwise be expanded by the operating system shell are not expanded. Use of the @ character to recursively interpret files is not supported. The -J options are not supported because they are passed to the launcher, which does not support argument files.

When executing jar, pass in the path and name of each argument file with the @ leading character. When jar encounters an argument beginning with the character @, it expands the contents of that file into the argument list.

The example below, classes.list holds the names of files output by a find command:

% find . -name '*.class' -print > classes.list

You can then execute the jar command on Classes.list by passing it to jar using argfile syntax:

% jar cf my.jar @classes.list
An argument file can specify a path, but any filenames inside the argument file that have relative paths are relative to the current working directory, not to the path passed in. Here is an example:
% jar @path1/classes.list

EXAMPLES

To add all the files in a particular directory to an archive (overwriting contents if the archive already exists). Enumerating verbosely (with the -v option) will tell you more information about the files in the archive, such as their size and last modified date.
% ls
1.au          Animator.class    monkey.jpg
2.au          Wave.class        spacemusic.au
3.au          at_work.gif

% jar cvf bundle.jar *
added manifest
adding: 1.au(in = 2324) (out= 67)(deflated 97%)
adding: 2.au(in = 6970) (out= 90)(deflated 98%)
adding: 3.au(in = 11616) (out= 108)(deflated 99%)
adding: Animator.class(in = 2266) (out= 66)(deflated 97%)
adding: Wave.class(in = 3778) (out= 81)(deflated 97%)
adding: at_work.gif(in = 6621) (out= 89)(deflated 98%)
adding: monkey.jpg(in = 7667) (out= 91)(deflated 98%)
adding: spacemusic.au(in = 3079) (out= 73)(deflated 97%)
If you already have separate subdirectories for images, audio files and classes, you can combine them into a single jar file:
% ls -F
audio/ classes/ images/

% jar cvf bundle.jar audio classes images
added manifest
adding: audio/(in = 0) (out= 0)(stored 0%)
adding: audio/1.au(in = 2324) (out= 67)(deflated 97%)
adding: audio/2.au(in = 6970) (out= 90)(deflated 98%)
adding: audio/3.au(in = 11616) (out= 108)(deflated 99%)
adding: audio/spacemusic.au(in = 3079) (out= 73)(deflated 97%)
adding: classes/(in = 0) (out= 0)(stored 0%)
adding: classes/Animator.class(in = 2266) (out= 66)(deflated 97%)
adding: classes/Wave.class(in = 3778) (out= 81)(deflated 97%)
adding: images/(in = 0) (out= 0)(stored 0%)
adding: images/monkey.jpg(in = 7667) (out= 91)(deflated 98%)
adding: images/at_work.gif(in = 6621) (out= 89)(deflated 98%)

% ls -F
audio/ bundle.jar classes/ images/
To see the entry names in the jarfile, use the t option:
% jar tf bundle.jar
META-INF/
META-INF/MANIFEST.MF
audio/1.au
audio/2.au
audio/3.au
audio/spacemusic.au
classes/Animator.class
classes/Wave.class
images/monkey.jpg
images/at_work.gif

To add an index file to the jar file for speeding up class loading, use the i option.

Example:

If you split the inter-dependent classes for a stock trade application into three jar files: main.jar, buy.jar, and sell.jar.

If you specify the Class-path attribute in the main.jar manifest as:
Class-Path: buy.jar sell.jar
then you can use the -i option to speed up the class loading time for your application:
% jar i main.jar
An INDEX.LIST file is inserted to the META-INF directory. This enables the application class loader to download the specified jar files when it is searching for classes or resources.

SEE ALSO

The Jar Overview

The Jar File Specification

The JarIndex Spec

Jar Tutorial

pack200 Reference Page

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Jar Indexing

In the case that an applet uses multiple .jar files, more efficient downloading can be achieved by indexing the .jar files. By indexing, only required .jar files are downloaded. For more information on Jar Indexing, see Java Archive (JAR) Features.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JAR File Overview

What is JAR?

JAR stands for Java ARchive. It's a file format based on the popular ZIP file format and is used for aggregating many files into one. Although JAR can be used as a general archiving tool, the primary motivation for its development was so that Java applets and their requisite components (.class files, images and sounds) can be downloaded to a browser in a single HTTP transaction, rather than opening a new connection for each piece. This greatly improves the speed with which an applet can be loaded onto a web page and begin functioning. The JAR format also supports compression, which reduces the size of the file and improves download time still further. Additionally, individual entries in a JAR file may be digitally signed by the applet author to authenticate their origin.

JAR is:

  • the only archive format that is cross-platform
  • the only format that handles audio and image files as well as class files
  • backward-compatible with existing applet code
  • an open standard, fully extendable, and written in java
  • the preferred way to bundle the pieces of a java applet

JAR consists of a zip archive, as defined by PKWARE, containing a manifest file and potentially signature files, as defined in the JAR File Specification.

The APPLET tag

Changing the APPLET tag in your HTML page to accomodate a JAR file is simple. The JAR file on the server is identified by the ARCHIVE parameter, where the directory location of the jar file should be relative to the location of the html page:
    <applet code=Animator.class
      archive="jars/animator.jar"
      width=460 height=160>
      <param name=foo value="bar">
    </applet>
Note that the familiar CODE=myApplet.class parameter must still be present. The CODE parameter, as always, identifies the name of the applet where execution begins. However, the class file for the applet and all of its helper classes are loaded from the JAR file.

Th ARCHIVE attribute describes one or more JAR files containing classes and other resources that will be "preloaded". The classes are loaded using an instance of an AppletClassLoader with the given CODEBASE. It takes the form archive = archiveList. The archives in archiveList are separated by ",".

Once the archive file is identified, it is downloaded and separated into its components. During the execution of the applet, when a new class, image or audio clip is requested by the applet, it is searched for first in the archives associated with the applet. If the file is not found amongst the archives that were downloaded, it is searched for on the applet's server, relative to the CODEBASE (that is, it is searched for as in JDK1.0.2).

The archive tag may specify multiple JAR files. Each JAR file must be separated by "," (comma). Each file is downloaded in turn:

    <applet code=Animator.class
      archive="classes.jar ,  images.jar ,  sounds.jar"
      width=460 height=160>
      <param name=foo value="bar">
    </applet>
There can be any amount of white space between entries within the archive parameter. In addition, the archive tag itself is case-insensitive; it can be lower-case, upper-case, or any combination of lower- and upper-case letters, such as ArCHiVe.

Executable JAR Files

On Microsoft Windows systems, the Java 2 Runtime Environment's installation program will register a default association for JAR files so that double-clicking a JAR file on the desktop will automatically run it with javaw -jar. Dependent extensions bundled with the application will also be loaded automatically. This feature makes the end-user runtime environment easier to use on Microsoft Windows systems.

The Solaris 2.6 kernel has already been extended to recognize the special "magic" number that identifies a JAR file, and to invoke java -jar on such a JAR file as if it were a native Solaris executable. A application packaged in a JAR file can thus be executed directly from the command line or by clicking an icon on the CDE desktop.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


jarsigner-JAR Signing and Verification Tool

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

jarsigner - JAR Signing and Verification Tool

Generates signatures for Java ARchive (JAR) files, and verifies the signatures of signed JAR files.

SYNOPSIS

jarsigner [ options ] jar-file alias
jarsigner -verify [ options ] jar-file [alias...]

The jarsigner -verify command can take zero or more keystore alias names after the jar filename. When specified, jarsigner will check that the certificate used to verify each signed entry in the jar file matches one of the keystore aliases. The aliases are defined in the keystore specified by -keystore, or the default keystore.

DESCRIPTION

The jarsigner tool is used for two purposes-

  1. to sign Java ARchive (JAR) files, and
  2. to verify the signatures and integrity of signed JAR files.

The JAR feature enables the packaging of class files, images, sounds, and other digital data in a single file for faster and easier distribution. A tool named jar enables developers to produce JAR files. (Technically, any zip file can also be considered a JAR file, although when created by jar or processed by jarsigner, JAR files also contain a META-INF/MANIFEST.MF file.)

A digital signature is a string of bits that is computed from some data (the data being "signed") and the private key of an entity (a person, company, etc.). Like a handwritten signature, a digital signature has many useful characteristics:

  • Its authenticity can be verified, via a computation that uses the public key corresponding to the private key used to generate the signature.
  • It cannot be forged, assuming the private key is kept secret.
  • It is a function of the data signed and thus can't be claimed to be the signature for other data as well.
  • The signed data cannot be changed; if it is, the signature will no longer verify as being authentic.

In order for an entity's signature to be generated for a file, the entity must first have a public/private key pair associated with it, and also one or more certificates authenticating its public key. A certificate is a digitally signed statement from one entity, saying that the public key of some other entity has a particular value.

jarsigner uses key and certificate information from a keystore to generate digital signatures for JAR files. A keystore is a database of private keys and their associated X.509 certificate chains authenticating the corresponding public keys. The keytool utility is used to create and administer keystores.

jarsigner uses an entity's private key to generate a signature. The signed JAR file contains, among other things, a copy of the certificate from the keystore for the public key corresponding to the private key used to sign the file. jarsigner can verify the digital signature of the signed JAR file using the certificate inside it (in its signature block file).

jarsigner can generate signatures that include a timestamp, thus enabling systems/deployer (including Java Plug-in) to check whether the JAR file was signed while the signing certificate was still valid. In addition, APIs will allow applications to obtain the timestamp information.

At this time, jarsigner can only sign JAR files created by the SDK jar tool or zip files. (JAR files are the same as zip files, except they also have a META-INF/MANIFEST.MF file. Such a file will automatically be created when jarsigner signs a zip file.)

The default jarsigner behavior is to sign a JAR (or zip) file. Use the -verify option to instead have it verify a signed JAR file.

Keystore Aliases

All keystore entities are accessed via unique aliases.

When using jarsigner to sign a JAR file, you must specify the alias for the keystore entry containing the private key needed to generate the signature. For example, the following will sign the JAR file named "MyJARFile.jar", using the private key associated with the alias "duke" in the keystore named "mystore" in the "working" directory. Since no output file is specified, it overwrites MyJARFile.jar with the signed JAR file.

    jarsigner -keystore /working/mystore -storepass myspass
      -keypass dukekeypasswd MyJARFile.jar duke

Keystores are protected with a password, so the store password (in this case "myspass") must be specified. You will be prompted for it if you don't specify it on the command line. Similarly, private keys are protected in a keystore with a password, so the private key's password (in this case "dukekeypasswd") must be specified, and you will be prompted for it if you don't specify it on the command line and it isn't the same as the store password.

Keystore Location

jarsigner has a -keystore option for specifying the URL of the keystore to be used. The keystore is by default stored in a file named .keystore in the user's home directory, as determined by the user.home system property. On Solaris systems user.home defaults to the user's home directory.

Note that the input stream from the -keystore option is passed to the KeyStore.load method. If NONE is specified as the URL, then a null stream is passed to the KeyStore.load method. NONE should be specified if the KeyStore is not file-based, for example, if it resides on a hardware token device.

Keystore Implementation

The KeyStore class provided in the java.security package supplies well-defined interfaces to access and modify the information in a keystore. It is possible for there to be multiple different concrete implementations, where each implementation is that for a particular type of keystore.

Currently, there are two command-line tools that make use of keystore implementations (keytool and jarsigner), and also a GUI-based tool named Policy Tool. Since KeyStore is publicly available, Java 2 SDK users can write additional security applications that use it.

There is a built-in default implementation, provided by Sun Microsystems. It implements the keystore as a file, utilizing a proprietary keystore type (format) named "JKS". It protects each private key with its individual password, and also protects the integrity of the entire keystore with a (possibly different) password.

Keystore implementations are provider-based. More specifically, the application interfaces supplied by KeyStore are implemented in terms of a "Service Provider Interface" (SPI). That is, there is a corresponding abstract KeystoreSpi class, also in the java.security package, which defines the Service Provider Interface methods that "providers" must implement. (The term "provider" refers to a package or a set of packages that supply a concrete implementation of a subset of services that can be accessed by the Java Security API.) Thus, to provide a keystore implementation, clients must implement a provider and supply a KeystoreSpi subclass implementation, as described in How to Implement a Provider for the Java Cryptography Architecture.

Applications can choose different types of keystore implementations from different providers, using the "getInstance" factory method supplied in the KeyStore class. A keystore type defines the storage and data format of the keystore information, and the algorithms used to protect private keys in the keystore and the integrity of the keystore itself. Keystore implementations of different types are not compatible.

keytool works on any file-based keystore implementation. (It treats the keystore location that is passed to it at the command line as a filename and converts it to a FileInputStream, from which it loads the keystore information.) The jarsigner and policytool tools, on the other hand, can read a keystore from any location that can be specified using a URL.

For jarsigner and keytool, you can specify a keystore type at the command line, via the -storetype option. For Policy Tool, you can specify a keystore type via the "Change Keystore" command in the Edit menu.

If you don't explicitly specify a keystore type, the tools choose a keystore implementation based simply on the value of the keystore.type property specified in the security properties file. The security properties file is called java.security, and it resides in the SDK security properties directory, java.home/lib/security, where java.home is the runtime environment's directory (the jre directory in the SDK or the top-level directory of the Java 2 Runtime Environment).

Each tool gets the keystore.type value and then examines all the currently-installed providers until it finds one that implements keystores of that type. It then uses the keystore implementation from that provider.

The KeyStore class defines a static method named getDefaultType that lets applications and applets retrieve the value of the keystore.type property. The following line of code creates an instance of the default keystore type (as specified in the keystore.type property):

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

The default keystore type is "jks" (the proprietary type of the keystore implementation provided by Sun). This is specified by the following line in the security properties file:

    keystore.type=jks

Note: Case doesn't matter in keystore type designations. For example, "JKS" would be considered the same as "jks".

To have the tools utilize a keystore implementation other than the default, change that line to specify a different keystore type. For example, if you have a provider package that supplies a keystore implementation for a keystore type called "pkcs12", change the line to

    keystore.type=pkcs12

Note that if you us the PKCS#11 provider package, you should refer to the KeyTool and JarSigner section of the Java PKCS#11 Reference Guide for details.

Supported Algorithms

By default, jarsigner signs a JAR file using one of the following:

  • DSA (Digital Signature Algorithm) with the SHA1 digest algorithm
  • RSA algorithm with the SHA256 digest algorithm.
  • EC (Elliptic Curve) cryptography algorithm with the SHA256 with ECDSA (Elliptic Curve Digital Signature Algorithm).

That is, if the signer's public and private keys are DSA keys, jarsigner will sign the JAR file using the "SHA1withDSA" algorithm. If the signer's keys are RSA keys, jarsigner will attempt to sign the JAR file using the "SHA256withRSA" algorithm. If the signer's keys are EC keys, jarsigner will sign the JAR file using the "SHA256withECDSA" algorithm.

These default signature algorithms can be overridden using the -sigalg option.

The Signed JAR File

When jarsigner is used to sign a JAR file, the output signed JAR file is exactly the same as the input JAR file, except that it has two additional files placed in the META-INF directory:

  • a signature file, with a .SF extension, and
  • a signature block file, with a .DSA, .RSA, or .EC extension.

The base file names for these two files come from the value of the -sigFile option. For example, if the option appears as

-sigFile MKSIGN

The files are named "MKSIGN.SF" and "MKSIGN.DSA".

If no -sigfile option appears on the command line, the base file name for the .SF and .DSA files will be the first 8 characters of the alias name specified on the command line, all converted to upper case. If the alias name has fewer than 8 characters, the full alias name is used. If the alias name contains any characters that are not allowed in a signature file name, each such character is converted to an underscore ("_") character in forming the file name. Legal characters include letters, digits, underscores, and hyphens.

The Signature (.SF) File

A signature file (the .SF file) looks similar to the manifest file that is always included in a JAR file when jarsigner is used to sign the file. That is, for each source file included in the JAR file, the .SF file has three lines, just as in the manifest file, listing the following:

  • the file name,
  • the name of the digest algorithm used (SHA), and
  • a SHA digest value.

In the manifest file, the SHA digest value for each source file is the digest (hash) of the binary data in the source file. In the .SF file, on the other hand, the digest value for a given source file is the hash of the three lines in the manifest file for the source file.

The signature file also, by default, includes a header containing a hash of the whole manifest file. The presence of the header enables verification optimization, as described in JAR File Verification.

The Signature Block File

The .SF file is signed and the signature is placed in the signature block file. This file also contains, encoded inside it, the certificate or certificate chain from the keystore which authenticates the public key corresponding to the private key used for signing. The file has the extension .DSA, .RSA, or .EC depending on the digest algorithm used.

Signature Timestamp

jarsigner tool can generate and store a signature timestamp when signing a JAR file. In addition, jarsigner supports alternative signing mechanisms. This behavior is optional and is controlled by the user at the time of signing through these options:

  • -tsa url
  • -tsacert alias
  • -altsigner class
  • -altsignerpath classpathlist

Each of these options is detailed in the Options section below.

JAR File Verification

A successful JAR file verification occurs if the signature(s) are valid, and none of the files that were in the JAR file when the signatures were generated have been changed since then. JAR file verification involves the following steps:

  1. Verify the signature of the .SF file itself.

    That is, the verification ensures that the signature stored in each signature block (.DSA) file was in fact generated using the private key corresponding to the public key whose certificate (or certificate chain) also appears in the .DSA file. It also ensures that the signature is a valid signature of the corresponding signature (.SF) file, and thus the .SF file has not been tampered with.

  2. Verify the digest listed in each entry in the .SF file with each corresponding section in the manifest.

    The .SF file by default includes a header containing a hash of the entire manifest file. When the header is present, then the verification can check to see whether or not the hash in the header indeed matches the hash of the manifest file. If that is the case, verification proceeds to the next step.

    If that is not the case, a less optimized verification is required to ensure that the hash in each source file information section in the .SF file equals the hash of its corresponding section in the manifest file (see The Signature (.SF) File).

    One reason the hash of the manifest file that is stored in the .SF file header may not equal the hash of the current manifest file would be because one or more files were added to the JAR file (using the jar tool) after the signature (and thus the .SF file) was generated. When the jar tool is used to add files, the manifest file is changed (sections are added to it for the new files), but the .SF file is not. A verification is still considered successful if none of the files that were in the JAR file when the signature was generated have been changed since then, which is the case if the hashes in the non-header sections of the .SF file equal the hashes of the corresponding sections in the manifest file.

  3. Read each file in the JAR file that has an entry in the .SF file. While reading, compute the file's digest, and then compare the result with the digest for this file in the manifest section. The digests should be the same, or verification fails.

If any serious verification failures occur during the verification process, the process is stopped and a security exception is thrown. It is caught and displayed by jarsigner.

Multiple Signatures for a JAR File

A JAR file can be signed by multiple people simply by running the jarsigner tool on the file multiple times, specifying the alias for a different person each time, as in:

  jarsigner myBundle.jar susan
  jarsigner myBundle.jar kevin

When a JAR file is signed multiple times, there are multiple .SF and .DSA files in the resulting JAR file, one pair for each signature. Thus, in the example above, the output JAR file includes files with the following names:

  SUSAN.SF
  SUSAN.DSA
  KEVIN.SF
  KEVIN.DSA

Note: It is also possible for a JAR file to have mixed signatures, some generated by the JDK 1.1 javakey tool and others by jarsigner. That is, jarsigner can be used to sign JAR files already previously signed using javakey.

OPTIONS

The various jarsigner options are listed and described below. Note:

  • All option names are preceded by a minus sign (-).
  • The options may be provided in any order.
  • Items in italics (option values) represent the actual values that must be supplied.
  • The -keystore, -storepass, -keypass, -sigfile, -sigalg, -digestalg, and -signedjar options are only relevant when signing a JAR file, not when verifying a signed JAR file. Similarly, an alias is only specified on the command line when signing a JAR file.
-keystore url
Specifies the URL that tells the keystore location. This defaults to the file .keystore in the user's home directory, as determined by the "user.home" system property.

A keystore is required when signing, so you must explicitly specify one if the default keystore does not exist (or you want to use one other than the default).

A keystore is not required when verifying, but if one is specified, or the default exists, and the -verbose option was also specified, additional information is output regarding whether or not any of the certificates used to verify the JAR file are contained in that keystore.

Note: the -keystore argument can actually be a file name (and path) specification rather than a URL, in which case it will be treated the same as a "file:" URL. That is,

  -keystore filePathAndName

is treated as equivalent to

  -keystore file:filePathAndName

If the Sun PKCS#11 provider has been configured in the java.security security properties file (located in the JRE's $JAVA_HOME/lib/security directory), then keytool and jarsigner can operate on the PKCS#11 token by specifying these options:

  • -keystore NONE
  • -storetype PKCS11

For example, this command lists the contents of the configured PKCS#11 token:

   jarsigner -keystore NONE -storetype PKCS11 -list
-storetype storetype
Specifies the type of keystore to be instantiated. The default keystore type is the one that is specified as the value of the "keystore.type" property in the security properties file, which is returned by the static getDefaultType method in java.security.KeyStore.

The PIN for a PCKS#11 token can also be specified using the -storepass option. If none has been specified, keytool and jarsigner will prompt for the token PIN. If the token has a protected authentication path (such as a dedicated PIN-pad or a biometric reader), then the -protected option must be specified and no password options can be specified.

-storepass[:env | :file] argument

Specifies the password which is required to access the keystore. This is only needed when signing (not verifying) a JAR file. In that case, if a -storepass option is not provided at the command line, the user is prompted for the password.

If the modifier env or file is not specified, then the password has the value argument. Otherwise, the password is retrieved as follows:

  • env: Retrieve the password from the environment variable named argument
  • file: Retrieve the password from the file named argument

Note: The password shouldn't be specified on the command line or in a script unless it is for testing purposes, or you are on a secure system.

-keypass[:env | :file] argument

Specifies the password used to protect the private key of the keystore entry addressed by the alias specified on the command line. The password is required when using jarsigner to sign a JAR file. If no password is provided on the command line, and the required password is different from the store password, the user is prompted for it.

If the modifier env or file is not specified, then the password has the value argument. Otherwise, the password is retrieved as follows:

  • env: Retrieve the password from the environment variable named argument
  • file: Retrieve the password from the file named argument

Note: The password shouldn't be specified on the command line or in a script unless it is for testing purposes, or you are on a secure system.

-sigfile file
Specifies the base file name to be used for the generated .SF and .DSA files. For example, if file is "DUKESIGN", the generated .SF and .DSA files will be named "DUKESIGN.SF" and "DUKESIGN.DSA", and will be placed in the "META-INF" directory of the signed JAR file.

The characters in file must come from the set "a-zA-Z0-9_-". That is, only letters, numbers, underscore, and hyphen characters are allowed. Note: All lowercase characters will be converted to uppercase for the .SF and .DSA file names.

If no -sigfile option appears on the command line, the base file name for the .SF and .DSA files will be the first 8 characters of the alias name specified on the command line, all converted to upper case. If the alias name has fewer than 8 characters, the full alias name is used. If the alias name contains any characters that are not legal in a signature file name, each such character is converted to an underscore ("_") character in forming the file name.

-sigalg algorithm
Specifies the name of the signature algorithm to use to sign the JAR file.

See Appendix A of the Java Cryptography Architecture for a list of standard signature algorithm names. This algorithm must be compatible with the private key used to sign the JAR file. If this option is not specified, SHA1withDSA, SHA256withRSA, or SHA256withECDSA will be used depending on the type of private key. There must either be a statically installed provider supplying an implementation of the specified algorithm or the user must specify one with the -providerClass option, otherwise the command will not succeed.

-digestalg algorithm
Specifies the name of the message digest algorithm to use when digesting the entries of a jar file.

See Appendix A of the Java Cryptography Architecture for a list of standard message digest algorithm names. If this option is not specified, SHA256 will be used. There must either be a statically installed provider supplying an implementation of the specified algorithm or the user must specify one with the -providerClass option, otherwise the command will not succeed.

-signedjar file
Specifies the name to be used for the signed JAR file.

If no name is specified on the command line, the name used is the same as the input JAR file name (the name of the JAR file to be signed); in other words, that file is overwritten with the signed JAR file.

-verify
If this appears on the command line, the specified JAR file will be verified, not signed. If the verification is successful, "jar verified" will be displayed. If you try to verify an unsigned JAR file, or a JAR file signed with an unsupported algorithm (e.g., RSA when you don't have an RSA provider installed), the following is displayed: "jar is unsigned. (signatures missing or not parsable)"

It is possible to verify JAR files signed using either jarsigner or the JDK 1.1 javakey tool, or both.

For further information on verification, see JAR File Verification.

-certs
If this appears on the command line, along with the -verify and -verbose options, the output includes certificate information for each signer of the JAR file. This information includes
  • the name of the type of certificate (stored in the .DSA file) that certifies the signer's public key
  • if the certificate is an X.509 certificate (more specifically, an instance of java.security.cert.X509Certificate): the distinguished name of the signer

The keystore is also examined. If no keystore value is specified on the command line, the default keystore file (if any) will be checked. If the public key certificate for a signer matches an entry in the keystore, then the following information will also be displayed:

  • in parentheses, the alias name for the keystore entry for that signer. If the signer actually comes from a JDK 1.1 identity database instead of from a keystore, the alias name will appear in brackets instead of parentheses.
-certchain file
Specifies the certificate chain to be used, if the certificate chain associated with the private key of the keystore entry, addressed by the alias specified on the command line, is not complete. This may happen if the keystore is located on a hardware token where there is not enough capacity to hold a complete certificate chain. The file can be a sequence of X.509 certificates concatenated together, or a single PKCS#7 formatted data block, either in binary encoding format or in printable encoding format (also known as BASE64 encoding) as defined by the Internet RFC 1421 standard.
-verbose
If this appears on the command line, it indicates "verbose" mode, which causes jarsigner to output extra information as to the progress of the JAR signing or verification.
-internalsf
In the past, the .DSA (signature block) file generated when a JAR file was signed used to include a complete encoded copy of the .SF file (signature file) also generated. This behavior has been changed. To reduce the overall size of the output JAR file, the .DSA file by default doesn't contain a copy of the .SF file anymore. But if -internalsf appears on the command line, the old behavior is utilized. This option is mainly useful for testing; in practice, it should not be used, since doing so eliminates a useful optimization.
-sectionsonly
If this appears on the command line, the .SF file (signature file) generated when a JAR file is signed does not include a header containing a hash of the whole manifest file. It just contains information and hashes related to each individual source file included in the JAR file, as described in The Signature (.SF) File .

By default, this header is added, as an optimization. When the header is present, then whenever the JAR file is verified, the verification can first check to see whether or not the hash in the header indeed matches the hash of the whole manifest file. If so, verification proceeds to the next step. If not, it is necessary to do a less optimized verification that the hash in each source file information section in the .SF file equals the hash of its corresponding section in the manifest file.

For further information, see JAR File Verification.

This option is mainly useful for testing; in practice, it should not be used, since doing so eliminates a useful optimization.

-protected
Either true or false. This value should be specified as true if a password must be given via a protected authentication path such as a dedicated PIN reader.
-providerClass provider-class-name
Used to specify the name of cryptographic service provider's master class file when the service provider is not listed in the security properties file, java.security.

Used in conjunction with the -providerArg ConfigFilePath option, keytool and jarsigner will install the provider dynamically (where ConfigFilePath is the path to the token configuration file). Here's an example of a command to list a PKCS#11 keystore when the Sun PKCS#11 provider has not been configured in the security properties file.

jarsigner -keystore NONE -storetype PKCS11 \
          -providerClass sun.security.pkcs11.SunPKCS11 \
          -providerArg /foo/bar/token.config \
          -list
-providerName providerName
If more than one provider has been configured in the java.security security properties file, you can use the -providerName option to target a specific provider instance. The argument to this option is the name of the provider.

For the Sun PKCS#11 provider, providerName is of the form SunPKCS11-TokenName, where TokenName is the name suffix that the provider instance has been configured with, as detailed in the configuration attributes table. For example, the following command lists the contents of the PKCS#11 keystore provider instance with name suffix SmartCard:

jarsigner -keystore NONE -storetype PKCS11 \
        -providerName SunPKCS11-SmartCard \
        -list
-J javaoption
Passes through the specified javaoption string directly to the Java interpreter. (jarsigner is actually a "wrapper" around the interpreter.) This option should not contain any spaces. It is useful for adjusting the execution environment or memory usage. For a list of possible interpreter options, type java -h or java -X at the command line.

-tsa url
If "-tsa http://example.tsa.url" appears on the command line when signing a JAR file then a timestamp is generated for the signature. The URL, http://example.tsa.url, identifies the location of the Time Stamping Authority (TSA). It overrides any URL found via the -tsacert option. The -tsa option does not require the TSA's public key certificate to be present in the keystore.

To generate the timestamp, jarsigner communicates with the TSA using the Time-Stamp Protocol (TSP) defined in RFC 3161. If successful, the timestamp token returned by the TSA is stored along with the signature in the signature block file.

-tsacert alias
If "-tsacert alias" appears on the command line when signing a JAR file then a timestamp is generated for the signature. The alias identifies the TSA's public key certificate in the keystore that is currently in effect. The entry's certificate is examined for a Subject Information Access extension that contains a URL identifying the location of the TSA.

The TSA's public key certificate must be present in the keystore when using -tsacert.

-altsigner class
Specifies that an alternative signing mechanism be used. The fully-qualified class name identifies a class file that extends the com.sun.jarsigner.ContentSigner abstract class. The path to this class file is defined by the -altsignerpath option. If the -altsigner option is used, jarsigner uses the signing mechanism provided by the specified class. Otherwise, jarsigner uses its default signing mechanism.

For example, to use the signing mechanism provided by a class named com.sun.sun.jarsigner.AuthSigner, use the jarsigner option "-altsigner com.sun.jarsigner.AuthSigner"

-altsignerpath classpathlist
Specifies the path to the class file (the class file name is specified with the -altsigner option described above) and any JAR files it depends on. If the class file is in a JAR file, then this specifies the path to that JAR file, as shown in the example below.

An absolute path or a path relative to the current directory may be specified. If classpathlist contains multiple paths or JAR files, they should be separated with a colon (:) on Solaris and a semi-colon (;) on Windows. This option is not necessary if the class is already in the search path.

Example of specifying the path to a jar file that contains the class file:

-altsignerpath /home/user/lib/authsigner.jar

Note that the JAR file name is included.

Example of specifying the path to the jar file that contains the class file:

-altsignerpath /home/user/classes/com/sun/tools/jarsigner/

Note that the JAR file name is omitted.

-strict
During the signing or verifying process, some warning messages may be shown. If this option appears on the command line, the exit code of the tool will reflect the warning messages that are found. Read the "WARNINGS" section for details.
-verbose:sub-options
For the verifying process, the -verbose option takes sub-options to determine how much information will be shown. If -certs is also specified, the default mode (or sub-option all) displays each entry as it is being processed and following that, the certificate information for each signer of the JAR file. If -certs and the -verbose:grouped sub-option are specified, entries with the same signer info are grouped and displayed together along with their certificate information. If -certs and the -verbose:summary sub-option are specified, then entries with the same signer info are grouped and displayed together along with their certificate information but details about each entry are summarized and displayed as "one entry (and more)". See the examples section for more information.

EXAMPLES

Signing a JAR File

Suppose you have a JAR file named "bundle.jar" and you'd like to sign it using the private key of the user whose keystore alias is "jane" in the keystore named "mystore" in the "working" directory. Suppose the keystore password is "myspass" and the password for jane's private key is "j638klm". You can use the following to sign the JAR file and name the signed JAR file "sbundle.jar":

    jarsigner -keystore /working/mystore -storepass myspass
      -keypass j638klm -signedjar sbundle.jar bundle.jar jane

Note that there is no -sigfile specified in the command above, so the generated .SF and .DSA files to be placed in the signed JAR file will have default names based on the alias name. That is, they will be named JANE.SF and JANE.DSA.

If you want to be prompted for the store password and the private key password, you could shorten the above command to

    jarsigner -keystore /working/mystore
      -signedjar sbundle.jar bundle.jar jane

If the keystore to be used is the default keystore (the one named ".keystore" in your home directory), you don't need to specify a keystore, as in:

    jarsigner -signedjar sbundle.jar bundle.jar jane

Finally, if you want the signed JAR file to simply overwrite the input JAR file (bundle.jar), you don't need to specify a -signedjar option:

    jarsigner bundle.jar jane

Verifying a Signed JAR File

To verify a signed JAR file, that is, to verify that the signature is valid and the JAR file has not been tampered with, use a command such as the following:

    jarsigner -verify sbundle.jar

If the verification is successful,

    jar verified.

is displayed. Otherwise, an error message appears.

You can get more information if you use the -verbose option. A sample use of jarsigner with the -verbose option is shown below, along with sample output:

    jarsigner -verify -verbose sbundle.jar

           198 Fri Sep 26 16:14:06 PDT 1997 META-INF/MANIFEST.MF
           199 Fri Sep 26 16:22:10 PDT 1997 META-INF/JANE.SF
          1013 Fri Sep 26 16:22:10 PDT 1997 META-INF/JANE.DSA
    smk   2752 Fri Sep 26 16:12:30 PDT 1997 AclEx.class
    smk    849 Fri Sep 26 16:12:46 PDT 1997 test.class

      s = signature was verified
      m = entry is listed in manifest
      k = at least one certificate was found in keystore

    jar verified.

Verification with Certificate Information

If you specify the -certs option when verifying, along with the -verify and -verbose options, the output includes certificate information for each signer of the JAR file, including the certificate type, the signer distinguished name information (if and only if it's an X.509 certificate), and, in parentheses, the keystore alias for the signer if the public key certificate in the JAR file matches that in a keystore entry. For example,

    jarsigner -keystore /working/mystore -verify -verbose -certs myTest.jar

           198 Fri Sep 26 16:14:06 PDT 1997 META-INF/MANIFEST.MF
           199 Fri Sep 26 16:22:10 PDT 1997 META-INF/JANE.SF
          1013 Fri Sep 26 16:22:10 PDT 1997 META-INF/JANE.DSA
           208 Fri Sep 26 16:23:30 PDT 1997 META-INF/JAVATEST.SF
          1087 Fri Sep 26 16:23:30 PDT 1997 META-INF/JAVATEST.DSA
    smk   2752 Fri Sep 26 16:12:30 PDT 1997 Tst.class

      X.509, CN=Test Group, OU=Java Software, O=Sun Microsystems, L=CUP, S=CA, C=US (javatest)
      X.509, CN=Jane Smith, OU=Java Software, O=Sun, L=cup, S=ca, C=us (jane)

      s = signature was verified
      m = entry is listed in manifest
      k = at least one certificate was found in keystore

    jar verified.

If the certificate for a signer is not an X.509 certificate, there is no distinguished name information. In that case, just the certificate type and the alias are shown. For example, if the certificate is a PGP certificate, and the alias is "bob", you'd get

      PGP, (bob)

Verification of a JAR File that Includes Identity Database Signers

If a JAR file has been signed using the JDK 1.1 javakey tool, and thus the signer is an alias in an identity database, the verification output includes an "i" symbol. If the JAR file has been signed by both an alias in an identity database and an alias in a keystore, both "k" and "i" appear.

When the -certs option is used, any identity database aliases are shown in square brackets rather than the parentheses used for keystore aliases. For example:

    jarsigner -keystore /working/mystore -verify -verbose -certs writeFile.jar

           198 Fri Sep 26 16:14:06 PDT 1997 META-INF/MANIFEST.MF
           199 Fri Sep 26 16:22:10 PDT 1997 META-INF/JANE.SF
          1013 Fri Sep 26 16:22:10 PDT 1997 META-INF/JANE.DSA
           199 Fri Sep 27 12:22:30 PDT 1997 META-INF/DUKE.SF
          1013 Fri Sep 27 12:22:30 PDT 1997 META-INF/DUKE.DSA
   smki   2752 Fri Sep 26 16:12:30 PDT 1997 writeFile.html

      X.509, CN=Jane Smith, OU=Java Software, O=Sun, L=cup, S=ca, C=us (jane)
      X.509, CN=Duke, OU=Java Software, O=Sun, L=cup, S=ca, C=us [duke]

      s = signature was verified
      m = entry is listed in manifest
      k = at least one certificate was found in keystore
      i = at least one certificate was found in identity scope

    jar verified.

Note that the alias "duke" is in brackets to denote that it is an identity database alias, not a keystore alias.

WARNINGS

During the signing/verifying process, jarsigner may display various warnings. These warning codes are defined as follows:
         hasExpiringCert         2
             This jar contains entries whose signer certificate will expire within six months

         hasExpiredCert          4
             This jar contains entries whose signer certificate has expired.

         notYetValidCert         4
             This jar contains entries whose signer certificate is not yet valid.

         chainNotValidated       4
             This jar contains entries whose certificate chain cannot be correctly validated.

         badKeyUsage             8
             This jar contains entries whose signer certificate's KeyUsage extension doesn't allow code signing.

         badExtendedKeyUsage     8
             This jar contains entries whose signer certificate's ExtendedKeyUsage extension
             doesn't allow code signing.

         badNetscapeCertType     8
             This jar contains entries whose signer certificate's NetscapeCertType extension
             doesn't allow code signing.

         hasUnsignedEntry        16
             This jar contains unsigned entries which have not been integrity-checked.

         notSignedByAlias        32
             This jar contains signed entries which are not signed by the specified alias(es)

         aliasNotInStore         32
             This jar contains signed entries that are not signed by alias in this keystore

When the -strict option is provided, an OR-value of warnings detected will be returned as the exit code of the tool. For example, if a certificate used to sign an entry is expired and has a keyUsage extension that does not allow it to sign a file, an exit code 12 (=4+8) will be returned.

Note: Exit codes are reused because only 0-255 is legal for Unix. In any case, if the signing/verifying process fails, the following exit code will be returned:

failure                 1

Compatibility with JDK 1.1

The keytool and jarsigner tools completely replace the javakey tool provided in JDK 1.1. These new tools provide more features than javakey, including the ability to protect the keystore and private keys with passwords, and the ability to verify signatures in addition to generating them.

The new keystore architecture replaces the identity database that javakey created and managed. There is no backwards compatibility between the keystore format and the database format used by javakey in 1.1. However,

  • It is possible to import the information from an identity database into a keystore, via the keytool -identitydb command.
  • jarsigner can sign JAR files also previously signed using javakey.
  • jarsigner can verify JAR files signed using javakey. Thus, it recognizes and can work with signer aliases that are from a JDK 1.1 identity database rather than a Java 2 SDK keystore.

The following table explains how JAR files that were signed in JDK 1.1.x are treated in the Java 2 platform.

JAR File Type | Identity in 1.1 database | Trusted Identity imported into Java 2 Platform keystore from 1.1 database (4) | Policy File grants privileges to Identity/Alias | Privileges Granted
Signed JAR | NO | NO | NO | Default privileges granted to all code.
Unsigned JAR | NO | NO | NO | Default privileges granted to all code.
Signed JAR | NO | YES | NO | Default privileges granted to all code.
Signed JAR | YES/Untrusted | NO | NO | Default privileges granted to all code. (3)
Signed JAR | YES/Untrusted | NO | YES | Default privileges granted to all code. (1,3)
Signed JAR | NO | YES | YES | Default privileges granted to all code plus privileges granted in policy file.
Signed JAR | YES/Trusted | YES | YES | Default privileges granted to all code plus privileges granted in policy file. (2)
Signed JAR | YES/Trusted | NO | NO | All privileges
Signed JAR | YES/Trusted | YES | NO | All privileges (1)
Signed JAR | YES/Trusted | NO | YES | All privileges (1)

Notes:

  1. If an identity/alias is mentioned in the policy file, it must be imported into the keystore for the policy file to have any effect on privileges granted.
  2. The policy file/keystore combination has precedence over a trusted identity in the identity database.
  3. Untrusted identities are ignored in the Java 2 platform.
  4. Only trusted identities can be imported into Java 2 SDK keystores.

SEE ALSO

  • jar tool documentation
  • keytool tool documentation
  • the Security trail of the Java Tutorial for examples of the use of the jarsigner tool
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


java - the Java application launcher

  • Synopsis
  • Description
  • Options
  • See Also

SYNOPSIS

    java [ options ] class [ argument ... ]
    java [ options ] -jar file.jar [ argument ... ]
options
Command-line options.
class
Name of the class to be invoked.
file.jar
Name of the jar file to be invoked. Used only with -jar.
argument
Argument passed to the main function.

DESCRIPTION

The java tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method.

The method must be declared public and static, it must not return any value, and it must accept a String array as a parameter. The method declaration must look like the following:

public static void main(String args[])

By default, the first non-option argument is the name of the class to be invoked. A fully-qualified class name should be used. If the -jar option is specified, the first non-option argument is the name of a JAR archive containing class and resource files for the application, with the startup class indicated by the Main-Class manifest header.

The Java runtime searches for the startup class, and other classes used, in three sets of locations: the bootstrap class path, the installed extensions, and the user class path.

Non-option arguments after the class name or JAR file name are passed to the main function.

OPTIONS

The launcher has a set of standard options that are supported on the current runtime environment and will be supported in future releases. In addition, the current implementations of the virtual machines support a set of non-standard options that are subject to change in future releases.

Standard Options

-client

Select the Java HotSpot Client VM. A 64-bit capable jdk currently ignores this option and instead uses the Java Hotspot Server VM.

For default VM selection, see Server-Class Machine Detection

-server

Select the Java HotSpot Server VM. On a 64-bit capable jdk only the Java Hotspot Server VM is supported so the -server option is implicit.

For default VM selection, see Server-Class Machine Detection

-agentlib:libname[=options]
Load native agent library libname, e.g.

-agentlib:hprof

-agentlib:jdwp=help

-agentlib:hprof=help

For more information, see JVMTI Agent Command Line Options.

-agentpath:pathname[=options]
Load a native agent library by full pathname. For more information, see JVMTI Agent Command Line Options.
-classpath classpath
-cp classpath
Specify a list of directories, JAR archives, and ZIP archives to search for class files. Class path entries are separated by colons (:). Specifying -classpath or -cp overrides any setting of the CLASSPATH environment variable.

If -classpath and -cp are not used and CLASSPATH is not set, the user class path consists of the current directory (.).

As a special convenience, a class path element containing a basename of * is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR (a java program cannot tell the difference between the two invocations).

For example, if directory foo contains a.jar and b.JAR, then the class path element foo/* is expanded to a A.jar:b.JAR, except that the order of jar files is unspecified. All jar files in the specified directory, even hidden ones, are included in the list. A classpath entry consisting simply of * expands to a list of all the jar files in the current directory. The CLASSPATH environment variable, where defined, will be similarly expanded. Any classpath wildcard expansion occurs before the Java virtual machine is started -- no Java program will ever see unexpanded wildcards except by querying the environment. For example; by invoking System.getenv("CLASSPATH").

For more information on class paths, see Setting the Class Path.

-D property=value
Set a system property value.
-d32
-d64
Request that the program to be run in a 32-bit or 64-bit environment, respectively. If the requested environment is not installed or is not supported, an error is reported.

Currently only the Java HotSpot Server VM supports 64-bit operation, and the "-server" option is implicit with the use of -d64. And the "-client" option is ignored with the use of -d64. This is subject to change in a future release.

If neither -d32 nor -d64 is specified, the default is to run in a 32-bit environment, except for 64-bit only systems. This is subject to change in a future release.

-enableassertions[:<package name>"..." | :<class name> ]
-ea[:<package name>"..." | :<class name> ]
Enable assertions. Assertions are disabled by default.

With no arguments, enableassertions or -ea enables assertions. With one argument ending in "...", the switch enables assertions in the specified package and any subpackages. If the argument is simply "...", the switch enables assertions in the unnamed package in the current working directory. With one argument not ending in "...", the switch enables assertions in the specified class.

If a single command line contains multiple instances of these switches, they are processed in order before loading any classes. So, for example, to run a program with assertions enabled only in package com.wombat.fruitbat (and any subpackages), the following command could be used:

java -ea:com.wombat.fruitbat... <Main Class>

The -enableassertions and -ea switches apply to all class loaders and to system classes (which do not have a class loader). There is one exception to this rule: in their no-argument form, the switches do not apply to system. This makes it easy to turn on asserts in all classes except for system classes. A separate switch is provided to enable asserts in all system classes; see -enablesystemassertions below.

-disableassertions[:<package name>"..." | :<class name> ]
-da[:<package name>"..." | :<class name> ]
Disable assertions. This is the default.

With no arguments, disableassertions or -da disables assertions. With one argument ending in "...", the switch disables assertions in the specified package and any subpackages. If the argument is simply "...", the switch disables assertions in the unnamed package in the current working directory. With one argument not ending in "...", the switch disables assertions in the specified class.

To run a program with assertions enabled in package com.wombat.fruitbat but disabled in class com.wombat.fruitbat.Brickbat, the following command could be used:

java -ea:com.wombat.fruitbat... -da:com.wombat.fruitbat.Brickbat <Main Class>

The -disableassertions and -da switches apply to all class loaders and to system classes (which do not have a class loader). There is one exception to this rule: in their no-argument form, the switches do not apply to system. This makes it easy to turn on asserts in all classes except for system classes. A separate switch is provided to enable asserts in all system classes; see -disablesystemassertions below.

-enablesystemassertions
-esa
Enable asserts in all system classes (sets the default assertion status for system classes to true).
-disablesystemassertions
-dsa
Disables asserts in all system classes.
-jar
Execute a program encapsulated in a JAR file. The first argument is the name of a JAR file instead of a startup class name. In order for this option to work, the manifest of the JAR file must contain a line of the form Main-Class: classname. Here, classname identifies the class having the public static void main(String[] args) method that serves as your application's starting point. See the Jar tool reference page and the Jar trail of the Java Tutorial for information about working with Jar files and Jar-file manifests.

When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

Note that JAR files that can be run with the "java -jar" option can have their execute permissions set so they can be run without using "java -jar". Refer to Java Archive (JAR) Files.

-javaagent:jarpath[=options]
Load a Java programming language agent, see java.lang.instrument.
-jre-restrict-search
Include user-private JREs in the version search.
-no-jre-restrict-search
Exclude user-private JREs in the version search.
-verbose
-verbose:class
Display information about each class loaded.
-verbose:gc
Report on each garbage collection event.
-verbose:jni
Report information about use of native methods and other Java Native Interface activity.
-version
Display version information and exit.
-version:release
Specifies that the version specified by release is required by the class or jar file specified on the command line. If the version of the java command invoked does not meet this specification and an appropriate implementation is found on the system, the appropriate implementation will be used.

release not only can specify an exact version, but can also specify a list of versions called a version string. A version string is an ordered list of version ranges separated by spaces. A version range is either a version-id, a version-id followed by a star (*), a version-id followed by a plus sign (+) , or two version-ranges combined using an ampersand (&). The star means prefix match, the plus sign means this version or greater, and the ampersand means the logical anding of the two version-ranges. For example:

-version:"1.6.0_13 1.6*&1.6.0_10+"
The meaning of the above is that the class or jar file requires either version 1.6.0_13, or a version with 1.6 as a version-id prefix and that is not less than 1.6.0_10.. The exact syntax and definition of version strings may be found in Appendix A of the Java Network Launching Protocol & API Specification (JSR-56).

For jar files, the usual preference is to specify version requirements in the jar file manifest rather than on the command line.

See the following NOTES section for important policy information on the use of this option.

-showversion
Display version information and continue.
-?
-help
Display usage information and exit.
-splash:imagepath
Show splash screen with image specified by imagepath.
-X
Display information about non-standard options and exit.

Non-Standard Options

-Xint
Operate in interpreted-only mode. Compilation to native code is disabled, and all bytecodes are executed by the interpreter. The performance benefits offered by the Java HotSpot VMs' adaptive compiler will not be present in this mode.
-Xbatch
Disable background compilation. Normally the VM will compile the method as a background task, running the method in interpreter mode until the background compilation is finished. The -Xbatch flag disables background compilation so that compilation of all methods proceeds as a foreground task until completed.
-Xbootclasspath:bootclasspath
Specify a colon-separated list of directories, JAR archives, and ZIP archives to search for boot class files. These are used in place of the boot class files included in the Java platform JDK. Note: Applications that use this option for the purpose of overriding a class in rt.jar should not be deployed as doing so would contravene the Java Runtime Environment binary code license.
-Xbootclasspath/a:path
Specify a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path.
-Xbootclasspath/p:path
Specify a colon-separated path of directires, JAR archives, and ZIP archives to prepend in front of the default bootstrap class path. Note: Applications that use this option for the purpose of overriding a class in rt.jar should not be deployed as doing so would contravene the Java Runtime Environment binary code license.
-Xcheck:jni
Perform additional checks for Java Native Interface (JNI) functions. Specifically, the Java Virtual Machine validates the parameters passed to the JNI function as well as the runtime environment data before processing the JNI request. Any invalid data encountered indicates a problem in the native code, and the Java Virtual Machine will terminate with a fatal error in such cases. Expect a performance degradation when this option is used.
-Xfuture
Perform strict class-file format checks. For purposes of backwards compatibility, the default format checks performed by the JDK's virtual machine are no stricter than the checks performed by 1.1.x versions of the JDK software. The -Xfuture flag turns on stricter class-file format checks that enforce closer conformance to the class-file format specification. Developers are encouraged to use this flag when developing new code because the stricter checks will become the default in future releases of the Java application launcher.
-Xnoclassgc
Disable class garbage collection. Use of this option will prevent memory recovery from loaded classes thus increasing overall memory usage. This could cause OutOfMemoryError to be thrown in some applications.
-Xincgc
Enable the incremental garbage collector. The incremental garbage collector, which is off by default, will reduce the occasional long garbage-collection pauses during program execution. The incremental garbage collector will at times execute concurrently with the program and during such times will reduce the processor capacity available to the program.
-Xloggc:file
Report on each garbage collection event, as with -verbose:gc, but log this data to file. In addition to the information -verbose:gc gives, each reported event will be preceeded by the time (in seconds) since the first garbage-collection event.

Always use a local file system for storage of this file to avoid stalling the JVM due to network latency. The file may be truncated in the case of a full file system and logging will continue on the truncated file. This option overrides -verbose:gc if both are given on the command line.

-Xms n
Specify the initial size, in bytes, of the memory allocation pool. This value must be a multiple of 1024 greater than 1MB. Append the letter k or K to indicate kilobytes, or m or M to indicate megabytes. The default value is chosen at runtime based on system configuration. For more information, see HotSpot Ergonomics

Examples:

       -Xms6291456
       -Xms6144k
       -Xms6m
-Xmx n
Specify the maximum size, in bytes, of the memory allocation pool. This value must a multiple of 1024 greater than 2MB. Append the letter k or K to indicate kilobytes, or m or M to indicate megabytes. The default value is chosen at runtime based on system configuration. For more information, see HotSpot Ergonomics
Examples:
       -Xmx83886080
       -Xmx81920k
       -Xmx80m
On Solaris 7 and Solaris 8 SPARC platforms, the upper limit for this value is approximately 4000m minus overhead amounts. On Solaris 2.6 and x86 platforms, the upper limit is approximately 2000m minus overhead amounts. On Linux platforms, the upper limit is approximately 2000m minus overhead amounts.
-Xprof
Profiles the running program, and sends profiling data to standard output. This option is provided as a utility that is useful in program development and is not intended to be used in production systems.
-Xrs
Reduces use of operating-system signals by the Java virtual machine (JVM).

In a previous release, the Shutdown Hooks facility was added to allow orderly shutdown of a Java application. The intent was to allow user cleanup code (such as closing database connections) to run at shutdown, even if the JVM terminates abruptly.

Sun's JVM catches signals to implement shutdown hooks for abnormal JVM termination. The JVM uses SIGHUP, SIGINT, and SIGTERM to initiate the running of shutdown hooks.

The JVM uses a similar mechanism to implement the pre-1.2 feature of dumping thread stacks for debugging purposes. Sun's JVM uses SIGQUIT to perform thread dumps.

Applications embedding the JVM frequently need to trap signals like SIGINT or SIGTERM, which can lead to interference with the JVM's own signal handlers. The -Xrs command-line option is available to address this issue. When -Xrs is used on Sun's JVM, the signal masks for SIGINT, SIGTERM, SIGHUP, and SIGQUIT are not changed by the JVM, and signal handlers for these signals are not installed.

There are two consequences of specifying -Xrs:

  • SIGQUIT thread dumps are not available.
  • User code is responsible for causing shutdown hooks to run, for example by calling System.exit() when the JVM is to be terminated.
-Xss n
Set thread stack size.
-XX:+UseAltSigs
The VM uses SIGUSR1 and SIGUSR2 by default, which can sometimes conflict with applications that signal-chain SIGUSR1 and SIGUSR2. The -XX:+UseAltSigs option will cause the VM to use signals other than SIGUSR1 and SIGUSR2 as the default.

NOTES

The -version:release command line option places no restrictions on the complexity of the release specification. However, only a restricted subset of the possible release specifications represent sound policy and only these are fully supported. These policies are:

  1. Any version, represented by not using this option.
  2. Any version greater than an arbitrarily precise version-id. For example:
    "1.6.0_10+"
    This would utilize any version greater than 1.6.0_10. This is useful for a case where an interface was introduced (or a bug fixed) in the release specified.
  3. A version greater than an arbitrarily precise version-id, bounded by the upper bound of that release family. For example:
    "1.6.0_10+&1.6*"
  4. "Or" expressions of items 2. or 3. above. For example:
    "1.6.0_10+&1.6* 1.7+"
    Similar to item 2. this is useful when a change was introduced in a release (1.7) but also made available in updates to previous releases.

EXIT STATUS

The following exit values are generally returned by the launcher, typically when the launcher is called with the wrong arguments, serious errors, or exceptions thrown from the Java Virtual Machine. However, a Java application may choose to return any value using the API call System.exit(exitValue).

  • 0: Successful completion
  • >0: An error occurred

SEE ALSO

  • javac - the Java programming language compiler
  • jdb - Java Application Debugger
  • javah - C Header and Stub File Generator
  • jar - JAR Archive Tool
  • The Java Extensions Framework
  • Security Features.
  • HotSpot VM Specific Options.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Update

Installing the JRE automatically installs the Java Update feature. Java Update can keep your computer up to date automatically with the latest JRE releases. You no longer need to search for critical JRE updates; Java Update delivers the latest version of the JRE directly to your computer. Java Update recognizes when you are online and, using your Internet connection, searches for available updates from the Java Update web site. Whenever an update becomes available, an icon will appear in the status area of the taskbar.

You can specify how and when you want Java Update to update your computer. For example, you can set up Java Update to automatically download and install updates on a schedule that you specify. And you can choose to be notified before the download and the installation of the update occurs, or only before the installation of the update. You can also disable the option for automatic updates altogether and do them manually. It's your choice, and you can reset the options anytime you want.

For more detailed information, see Update Panel in Java Control Panel.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java-to-Javascript Communication

This section includes the following topics:

  • Introduction
  • JSObject
    • How JSObject Works
    • Enabling JSObject support in Java Plug-in
  • Common DOM API

Introduction

Java Plug-in offers two ways to access the DOM: Through JSObject and through the Common DOM API. Each method is described below, along with security considerations.

JSObject

Java applets may need to perform Java-to-JavaScript communication to access the Document Object Model (DOM) or to call JavaScript functions on an HTML page. Browsers allow communication between Java and JavaScript through the Java wrapper class netscape.javascript.JSObject. For more information, see Java Packages for LiveConnect.

Because the JavaScript rendering engine is implemented differently between browsers, Java Plug-in provides different degrees of support for JSObject in Internet Explorer and Navigator. This document specifies how JSObject support works in different browser environments.

How JSObject Works

JSObject provides an easy way to access the DOM of an HTML page. But because different browsers implement the DOM differently, using JSObject in a Java applet may yield different behaviors in Java Plug-in. For details about the DOM implementation in a particular browser, consult the developer guide for that browser.

In general, applets access JSObject as follows:

import netscape.javascript.*;
import java.applet.*;
import java.awt.*;
class MyApplet extends Applet {
     public void init() {
         JSObject win = JSObject.getWindow(this);
         JSObject doc = (JSObject) win.getMember("document");
         JSObject loc = (JSObject) doc.getMember("location");

         String s = (String) loc.getMember("href");  // document.location.href
         win.call("f", null);                      // Call f() in HTML page
     }
}

The starting point is the static method

public static JSObject getWindow(Applet a)

which returns a JSObject representing the Window that contains the given applet. Since this method takes only java.applet.Applet as parameter, JSObject can be accessed from an applet, but not from a bean unless the bean is also an applet.

Once the Window object is obtained, the applet can navigate the DOM of the HTML page using the following methods:

  • public Object call(String methodName, Object args[])
  • public Object eval(String s)
  • public Object getMember(String name)
  • public Object getSlot(int index)
  • public void removeMember(String name)
  • public void setMember(String name, Object value)
  • public void setSlot(int index, Object value)
  • public String toString()
  • public boolean equals(Object obj)

We recommend using only getWindow(), call(), eval(), setMember() and getMember() in Java Plug-in. The implementations of getSlot(), setSlot(), removeMember() and toString() are browser-dependent; i.e., the result of execution may vary depending on the version and platform of the browser in which Java Plug-in is running.

For more information about using JSObject, please read the section called "Java to JavaScript Communication" on the LiveConnect page.

To compile Java code to take advantage of JSObject, you must have the package netscape.javascript in the CLASSPATH. Since 1.4.2 Java Plug-In ships netscape.javascript in a JAR file called plugin.jar. To compile an applet which uses JSObject, add plugin.jar in the CLASSPATH before compilation.

Note that although JSObject is supported in Java Plug-in, it is not supported in AppletViewer in the Java SE platform. As a result, applets using JSObject may not run in AppletViewer or result in exceptions.

Enabling JSObject Support in Java Plug-in

Due to security reasons, JSObject support is not enabled in Java Plug-in by default. To enable JSObject support in Java Plug-in, a new attribute called MAYSCRIPT needs to be present in the EMBED/OBJECT tag as follows:

Original APPLET tag:

<APPLET code="XYZApp.class" codebase="html/" align="baseline"
     width="200" height="200" MAYSCRIPT>
<PARAM NAME="model" VALUE="models/HyaluronicAcid.xyz">
     No JDK 1.3 support for APPLET!!
</APPLET>

New OBJECT tag:

<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
     width="200" height="200" align="baseline"
     codebase="http://java.sun.com/products/plugin/1.3/jinstall-13-win32.cab#Version=1,3,0,0">
     <PARAM NAME="code" VALUE="XYZApp.class">
     <PARAM NAME="codebase" VALUE="html/">
     <PARAM NAME="type" VALUE="application/x-java-applet;version=1.3">
     <PARAM NAME="MAYSCRIPT" VALUE="true">
     <PARAM NAME="model" VALUE="models/HyaluronicAcid.xyz">
        No JDK 1.3 support for APPLET!!
</OBJECT>

New EMBED tag:

<EMBED type="application/x-java-applet;version=1.3" width="200"
   height="200" align="baseline" code="XYZApp.class"
   codebase="html/" model="models/HyaluronicAcid.xyz" MAYSCRIPT=true
   pluginspage="http://java.sun.com/products/plugin/1.3/plugin-install.html">
<NOEMBED>
   No JDK 1.3 support for APPLET!!
</NOEMBED>
</EMBED>

If MAYSCRIPT is specified as false, or if MAYSCRIPT is absent, JSObject is disabled. For more information about the MAYSCRIPT attribute in the EMBED/OBJECT tag, see Using OBJECT, EMBED and APPLET Tags in Java Plug-in.

JavaScript and LiveConnect are technologies from Netscape Communications Corporation. Due to the differences in the Javascript engine implemented by Mozilla and Microsoft, data marshalling between Java and JavaScript via LiveConnect may result in different datatypes for different browsers. The main differences in JavaScript implementations from vendors are in JavaScript datatype support, mapping of datatypes between Java and JavaScript, and DOM element implementation.

Note

The original JavaScript specification is available at http://devedge-temp.mozilla.org/library/manuals/2000/javascript/1.3/guide/index.html.

The original LiveConnect specification is available at http://devedge-temp.mozilla.org/library/manuals/2000/javascript/1.3/guide/lc.html#1037078.

Common DOM API

Overview

This section discusses the Common DOM API in Java Plug-in 6. It provides a standard API for accessing the DOM in the browser for browsers from different browser vendors running on various platforms.

Note

Full support is provided with Internet Explorer 6 and supported Mozilla browsers. Support is limited with other browsers.

This API is built upon the Document Object Model (DOM) Level 2 recommendation. (See http://www.w3.org/DOM/ for various w3c recommendations.) The Document Object Model (DOM) is a set of interfaces defined using Interface Definition Language (IDL) and including Java Language bindings.

The Common DOM API includes the following w3c-defined interface packages:

  • org.w3c.dom.*
  • org.w3c.dom.css.*
  • org.w3c.dom.events.*
  • org.w3c.dom.html.*
  • org.w3c.dom.stylesheets.*
  • org.w3c.dom.views.*

DOMService

The Common DOM classes allow an application to access the underlying DOM of the browser through the APIs in the org.w3c.dom and org.w3c.dom.html packages.

Each DOM represents the underlying representation of a single XML/HTML document within the browser, and each browser may display more than one XML/HTML document in multiple browser frames/windows. Thus, when an application requests to access the DOM through the Common DOM classes, it is important to return the DOM associated with the application. In order to obtain the proper DOM associated with the application, a Java object will be passed to DOMService.getService(). DOMService will return the proper DOMService implementations associated with the object, or an exception will be thrown. Ordinarily the Java object is an applet or JavaBeans component. However, this specification doesn't preclude other Java object types from being used, if the DOMServiceProvider can handle it.

To perform an action on the DOM, an object that implements DOMAction will need to be passed to DOMService.invokeAndWait() or DOMService.invokeLater(). DOMAction.run() will then be executed on the DOM access dispatch thread.

Here is a simple example of obtaining the title of the Document object:

DOMService service = null;

try
{
    service = DOMService.getService(MyApplet);

    String title = (String) service.invokeAndWait(new DOMAction()
                            {
                                public Object run(DOMAccessor accessor)
                                {
                                     HTMLDocument doc = (HTMLDocument) accessor.getDocument(MyApplet);
                                     return doc.getTitle();
                                }
                            });
}
catch (DOMUnsupportedException e1)
{
}
catch (DOMAccessException e2)
{
}

DOMService Plugability

Since there may be more than one DOMServiceProvider, it is important to allow third parties to plug their DOMServiceProvider implementations into the Common DOM classes. To achieve that, a new Java property, com.sun.browser.dom.DOMServiceProvider, is defined.

If this property is defined, it should contain a list of class names of the DOMServiceProvider implementations, each separated by a character "|".

When DOMService.getService() is called, DOMServiceProvider implementations specified by the com.sun.browser.dom.DOMServiceProvider will be called one-by-one to determine if the provide can determine the DOM association of the object, according to the order that is specified in the property. In case two DOMServiceProvider implementations may be able to handle the same object, the provider that is specified first in the property will be used.

Thread Safety

Because the DOM of each browser is implemented differently, DOM access is not expected to be thread safe. Accessing implementation of DOM objects in this specification must be restricted on the DOM access dispatch thread only, so thread safely can be ensured. To accomplish that, code accessing the DOM objects must be scoped within the DOMAction.run() block. To invoke the action, either DOMService.invokeAndWait() or DOMService.invokeLater() should be used, so that DOMAction.run() will be executed in the DOM access dispatch thread.

Although implementations of DOM objects should not be called outside the DOMAction.run() block, the application may cache these DOM objects around as instance member of a class, or pass these DOM objects between threads. However, caching the DOM objects as static members of any object is prohibited, since static members tend to stay around much longer than the lifecycle of the underlying DOM object.

The only object in the Common DOM classes that can be called from any thread is DOMService. Access to other objects in the Common DOM classes is restricted within the DOMAction.run() block; otherwise, an exception will be thrown.

Security

The browser DOM provides access to every service in the browser, so it is important to ensure that security is checked properly during each call into the DOM. When DOMService.invokeAndWait() or DOMService.invokeLater() is called, the security context of the caller will be captured. Later, when the corresponding DOMAction.run() is executed on the DOM access dispatch thread, the caller's security context will be passed to the browser DOM when implementations of the DOM objects are called. DOMAccessException will be thrown if the original caller doesn't have the required privileges to access the DOM.

Security policy of DOM access in each browser is different. As a result, even if a Java application is signed and fully trusted, accessing the DOM objects in the browser may still result in DOMAccessException.

DOM Object Lifetime

Implementation of the DOM objects represents the real underlying objects in the browser DOM. As the XML/HTML document is changed on-the-fly, DOM objects in Java may no longer be valid. Accessing an invalid DOM object will result in org.w3c.dom.DOMException, according to the W3C DOM Level 2 Specification. Developers who write code to access DOM objects in DOMAction.run() should not assume the validity of the DOM objects at any given moment.

Conformance Requirements

Third parties implementing this specification must provide implementations of the Common DOM classes in the com.sun.browser.dom package. Implementations of the W3C DOM Level 2 APIs must also conformance to the W3C DOM Level 2 Specification. However, because each browser may implement a different subset of the W3C DOM APIs, third parties are not required to provide implementations of all org.w3c.dom and org.w3c.dom.html classes.

Package com.sun.browser.dom

This section defines the API of the com.sun.browser.dom package.

public abstract class DOMService

The DOMService defines a service API that enables applications to access a document object representing the underlying DOM of the browser window that embeds the applications.

public abstract class DOMService
{
        /**
         * Returns new instance of a DOMService. The implementation
         * of the DOMService returns depending on the setting of the
         * javax.browser.dom.DOMServiceProvider property or, if the
         * property is not set, a platform-specific default.
         *
         * Throws DOMUnsupportedException if the DOMService is not
         * available to the obj.
         *
         * @param obj Object to leverage the DOMService
         */
        public static DOMService getService(Object obj) throws DOMUnsupportedException;

        /**
         * An empty constructor is provided. Implementations of this
         * abstract class must provide a protected no-argument constructor
         * in order for the static getService() method to work correctly.
         * Application programmers should not be able to directly
         * construct implementation subclasses of this abstract subclass.
         */
        protected DOMService();

        /**
         * Causes action.run() to be executed synchronously on the
         * DOM action dispatching thread. This call will block until all
         * pending DOM actions have been processed and (then)
         * action.run() returns. This method should be used when an
         * application thread needs to access the browser's DOM.
         * It should not be called from the DOMActionDispatchThread.
         *
         * Note that if the DOMAction.run() method throws an uncaught
         * exception (on the DOM action dispatching thread), it's caught
         * and re-thrown as an DOMAccessException on the caller's thread.
         *
         * @param action DOMAction.
         */
        public abstract Object invokeAndWait(DOMAction action) throws DOMAccessException;

        /**
         * Causes action.run() to be executed asynchronously on the
         * DOM action dispatching thread. This method should be used
         * when an application thread needs to access the browser's
         * DOM. It should not be called from the DOMActionDispatchThread.
         *
         * Note that if the DOMAction.run() method throws an uncaught
         * exception (on the DOM action dispatching thread),  it will not be
         * caught and re-thrown on the caller's thread.
         *
         * @param action DOMAction.
         */
        public abstract void invokeLater(DOMAction action);
}

Note that Object obj in the getService(Object obj) method above is the applet or the bean.

public abstract class DOMServiceProvider

Implementation instances of the public abstract class DOMServiceProvider enable access to the underlying browser DOM for a given Java object. Instances of DOMServiceProvider should not be obtained by the application directly.

public abstract class DOMServiceProvider
{
        /**
         * An empty constructor is provided. Implementations should
         * provide a protected constructor so that the DOMService
         * can instantiate instances of the implementation class.
         * Application programmers should not be able to directly
         * construct implementation subclasses of this abstract subclass.
         * The only way an application should be able to obtain a
         * reference to a DOMServiceProvider implementation
         * instance is by using the appropriate methods of the
         * DOMService.
         */
        protected DOMServiceProvider();

        /**
         * Returns true if the DOMService can determine the association
         * between the obj and the underlying DOM in the browser.
         */
        public abstract boolean canHandle(Object obj);

        /**
         * Returns the Document object of the DOM.
         */
        public abstract org.w3c.dom.Document getDocument(Object obj) throws DOMUnsupportedException;

        /**
         * Returns the DOMImplemenation object of the DOM.
         */
        public abstract org.w3c.dom.DOMImplementation getDOMImplementation();
}

Note that Object obj in the canHandle(Object obj) and getDocument(Object obj) methods above is the applet or the bean.

public interface DOMAccessor

DOMAccessor represents the interface that can be used within DOMAction.run() to access the entry point of the browser DOM.

public interface DOMAccessor
{
        /**
         * Returns the Document object of the DOM.
         */
        public org.w3c.dom.Document getDocument(Object obj) throws org.w3c.dom.DOMException;

        /**
         * Returns a DOMImplementation object.
         */
        public org.w3c.dom.DOMImplementation getDOMImplementation();
}

Note that Object obj in the getDocument(Object obj) method above is the applet or the bean.

public interface DOMAction

DOMAction encapsulates all the actions of the applications that will be performed on the browser's DOM.

public interface DOMAction
{
        /**
         * When an object implementing interface DOMAction is passed
         * to DOMService.invokeAndWait() or DOMService.invokeLater(),
         * the run method is called in the DOM access dispatch thread.
         *
         * accessor is used for the DOMAction to access the entry point of
         * the browser's DOM, if necessary.
         *
         * @param accessor DOMAccessor
         */
        public Object run(DOMAccessor accessor);
}

public class DOMUnsupportedException

This exception is thrown from DOMService.getService() and DOMServiceProvider.getDocument() if the association between the Java object and the DOM cannot be found.

public class DOMUnsupportedException extends Exception
{
        /**
         * Constructs a new DOMUnsupportedException with no detail message.
         */
        public DOMUnsupportedException();

        /**
         * Constructs a new DOMUnsupportedException with the given detail message.
         *
         * @param msg Detail message.
         */
        public DOMUnsupportedException(String msg);

        /**
         * Constructs a new DOMUnsupportedException with the given exception as a root clause.
         *
         * @param e Exception.
         */
        public DOMUnsupportedException(Exception e);

        /**
         * Constructs a new DOMUnsupportedException with the given exception as a root clause and the given          * detail message.
         *
         * @param e Exception.
         * @param msg Detail message.
         */
        public DOMUnsupportedException(Exception e, String msg);

        /**
         * Returns the detail message of the error or null if there is no detail message.
         */
        public String getMessage();

        /**
         * Returns the root cause of the error or null if there is none.
         */
        public Exception getException();
}

public class DOMAccessException

This exception is thrown from DOMService.accessAndWait() if any DOM objects throws any exception when it is accessed within DOMAction.run().

public class DOMAccessException  extends Exception
{
        /**
         * Constructs a new DOMAccessException with no detail message.
         */
        public DOMAccessException();

        /**
         * Constructs a new DOMAccessException with the given detail message.
         *
         * @param msg Detail message.
         */
        public DOMAccessException(String msg);

        /**
         * Constructs a new DOMAccessException with the given exception as a root clause.
         *
         * @param e Exception.
         */
        public DOMAccessException(Exception e);

        /**
         * Constructs a new DOMAccessException with the given exception as a root clause and the given          * detail message.
         *
         * @param e Exception.
         * @param msg Detail message.
         */
        public DOMAccessException(Exception e, String msg);

        /**
         * Returns the detail message of the error or null if there is no detail message.
         */
        public String getMessage();

        /**
         * Returns the root cause of the error or null if there is none.
         */
        public Exception getException();
}
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


javac - Java programming language compiler

  • Synopsis
  • Description
  • Options
  • Command Line Argument Files
  • Annotation Processing
  • Searching for Types
  • Programmatic Interface
  • Examples
  • See Also

SYNOPSIS

        javac [ options ] [ sourcefiles ] [ classes ] [ @argfiles ]

Arguments may be in any order.

options
Command-line options.
sourcefiles
One or more source files to be compiled (such as MyClass.java).
classes
One or more classes to be processed for annotations (such as MyPackage.MyClass).
@argfiles
One or more files that lists options and source files. The -J options are not allowed in these files.

DESCRIPTION

The javac tool reads class and interface definitions, written in the Java programming language, and compiles them into bytecode class files. It can also process annotations in Java source files and classes.

There are two ways to pass source code file names to javac:

  • For a small number of source files, simply list the file names on the command line.
  • For a large number of source files, list the file names in a file, separated by blanks or line breaks. Then use the list file name on the javac command line, preceded by an @ character.

Source code file names must have .java suffixes, class file names must have .class suffixes, and both source and class files must have root names that identify the class. For example, a class called MyClass would be written in a source file called MyClass.java and compiled into a bytecode class file called MyClass.class.

Inner class definitions produce additional class files. These class files have names combining the inner and outer class names, such as MyClass$MyInnerClass.class.

You should arrange source files in a directory tree that reflects their package tree. For example, if you keep all your source files in C:\workspace, the source code for com.mysoft.mypack.MyClass should be in C:\workspace\com\mysoft\mypack\MyClass.java.

By default, the compiler puts each class file in the same directory as its source file. You can specify a separate destination directory with -d (see Options, below).

OPTIONS

The compiler has a set of standard options that are supported on the current development environment and will be supported in future releases. An additional set of non-standard options are specific to the current virtual machine and compiler implementations and are subject to change in the future. Non-standard options begin with -X.

Standard Options

-A key[=value]
Options to pass to annotation processors. These are not interpreted by javac directly, but are made available for use by individual processors. key should be one or more identifiers separated by ".".
-cp path or -classpath path
Specify where to find user class files, and (optionally) annotation processors and source files. This class path overrides the user class path in the CLASSPATH environment variable. If neither CLASSPATH, -cp nor -classpath is specified, the user class path consists of the current directory. See Setting the Class Path for more details.

If the -sourcepath option is not specified, the user class path is also searched for source files.

If the -processorpath option is not specified, the class path is also searched for annotation processors.

-Djava.ext.dirs=directories
Override the location of installed extensions.
-Djava.endorsed.dirs=directories
Override the location of endorsed standards path.
-d directory
Set the destination directory for class files. The directory must already exist; javac will not create it. If a class is part of a package, javac puts the class file in a subdirectory reflecting the package name, creating directories as needed. For example, if you specify -d C:\myclasses and the class is called com.mypackage.MyClass, then the class file is called C:\myclasses\com\mypackage\MyClass.class.

If -d is not specified, javac puts each class files in the same directory as the source file from which it was generated.

Note: The directory specified by -d is not automatically added to your user class path.

-deprecation
Show a description of each use or override of a deprecated member or class. Without -deprecation, javac shows a summary of the source files that use or override deprecated members or classes. -deprecation is shorthand for -Xlint:deprecation.
-encoding encoding
Set the source file encoding name, such as EUC-JP and UTF-8. If -encoding is not specified, the platform default converter is used.
-endorseddirs directories
Override the location of endorsed standards path.
-extdirs directories
Overrides the location of the ext directory. The directories variable is a colon-separated list of directories. Each JAR archive in the specified directories is searched for class files. All JAR archives found are automatically part of the class path.

If you are cross-compiling (compiling classes against bootstrap and extension classes of a different Java platform implementation), this option specifies the directories that contain the extension classes. See Cross-Compilation Options for more information.

-g
Generate all debugging information, including local variables. By default, only line number and source file information is generated.
-g:none
Do not generate any debugging information.
-g:{keyword list}
Generate only some kinds of debugging information, specified by a comma separated list of keywords. Valid keywords are:
source
Source file debugging information
lines
Line number debugging information
vars
Local variable debugging information
-help
Print a synopsis of standard options.
-implicit:{class,none}
Controls the generation of class files for implicitly loaded source files. To automatically generate class files, use -implicit:class. To suppress class file generation, use -implicit:none. If this option is not specified, the default is to automatically generate class files. In this case, the compiler will issue a warning if any such class files are generated when also doing annotation processing. The warning will not be issued if this option is set explicitly. See Searching For Types.
-J option
Pass option to the java launcher called by javac. For example, -J-Xms48m sets the startup memory to 48 megabytes. It is a common convention for -J to pass options to the underlying VM executing applications written in Java.

Note: CLASSPATH, -classpath, -bootclasspath, and -extdirs do not specify the classes used to run javac. Fiddling with the implementation of the compiler in this way is usually pointless and always risky. If you do need to do this, use the -J option to pass through options to the underlying java launcher.

-nowarn
Disable warning messages. This has the same meaning as -Xlint:none.
-proc: {none,only}
Controls whether annotation processing and/or compilation is done. -proc:none means that compilation takes place without annotation processing. -proc:only means that only annotation processing is done, without any subsequent compilation.
-processor class1[,class2,class3...]
Names of the annotation processors to run. This bypasses the default discovery process.
-processorpath path
Specify where to find annotation processors; if this option is not used, the class path will be searched for processors.
-s dir
Specify the directory where to place generated source files. The directory must already exist; javac will not create it. If a class is part of a package, the compiler puts the source file in a subdirectory reflecting the package name, creating directories as needed. For example, if you specify -s C:\mysrc and the class is called com.mypackage.MyClass, then the source file will be placed in C:\mysrc\com\mypackage\MyClass.java.
-source release
Specifies the version of source code accepted. The following values for release are allowed:
1.3
The compiler does not support assertions, generics, or other language features introduced after JDK 1.3.
1.4
The compiler accepts code containing assertions, which were introduced in JDK 1.4.
1.5
The compiler accepts code containing generics and other language features introduced in JDK 5.
5
Synonym for 1.5.
1.6
This is the default value. No language changes were introduced in Java SE 6. However, encoding errors in source files are now reported as errors, instead of warnings, as previously.
6
Synonym for 1.6.
1.7
The compiler accepts code with features introduced in JDK 7.
7
Synonym for 1.7.
-sourcepath sourcepath
Specify the source code path to search for class or interface definitions. As with the user class path, source path entries are separated by semicolons (;) and can be directories, JAR archives, or ZIP archives. If packages are used, the local path name within the directory or archive must reflect the package name.

Note: Classes found through the class path may be subject to automatic recompilation if their sources are also found. See Searching For Types.

-verbose
Verbose output. This includes information about each class loaded and each source file compiled.
-version
Print version information.
-Werror
Terminate compilation if warnings occur.
-X
Display information about non-standard options and exit.

Cross-Compilation Options

By default, classes are compiled against the bootstrap and extension classes of the platform that javac shipped with. But javac also supports cross-compiling, where classes are compiled against a bootstrap and extension classes of a different Java platform implementation. It is important to use -bootclasspath and -extdirs when cross-compiling; see Cross-Compilation Example below.

-target version
Generate class files that target a specified version of the VM. Class files will run on the specified target and on later versions, but not on earlier versions of the VM. Valid targets are 1.1 1.2 1.3 1.4 1.5 (also 5) 1.6 (also 6) and 1.7 (also 7).

The default for -target depends on the value of -source:

  • If -source is not specified, the value of -target is 1.7
  • If -source is 1.2, the value of -target is 1.4
  • If -source is 1.3, the value of -target is 1.4
  • For all other values of -source, the value of -target is the value of -source.
-bootclasspath bootclasspath
Cross-compile against the specified set of boot classes. As with the user class path, boot class path entries are separated by colons (:) and can be directories, JAR archives, or ZIP archives.

Non-Standard Options

-Xbootclasspath/p:path
Prepend to the bootstrap class path.
-Xbootclasspath/a:path
Append to the bootstrap class path.
-Xbootclasspath/:path
Override location of bootstrap class files.
-Xlint
Enable all recommended warnings. In this release, enabling all available warnings is recommended.
-Xlint:all
Enable all recommended warnings. In this release, enabling all available warnings is recommended.
-Xlint:none
Disable all warnings.
-Xlint:name
Enable warning name. See the section Warnings That Can Be Enabled or Disabled with -Xlint Option for a list of warnings you can enable with this option.
-Xlint:-name
Disable warning name. See the section Warnings That Can Be Enabled or Disabled with -Xlint Option for a list of warnings you can disable with this option.
-Xmaxerrs number
Set the maximum number of errors to print.
-Xmaxwarns number
Set the maximum number of warnings to print.
-Xstdout filename
Send compiler messages to the named file. By default, compiler messages go to System.err.
-Xprefer:{newer,source}
Specify which file to read when both a source file and class file are found for a type. (See Searching For Types). If -Xprefer:newer is used, it reads the newer of the source or class file for a type (default). If the -Xprefer:source option is used, it reads source file. Use -Xprefer:source when you want to be sure that any annotation processors can access annotations declared with a retention policy of SOURCE.
-Xpkginfo:{always,legacy,nonempty}
Specify handling of package-info files
-Xprint
Print out textual representation of specified types for debugging purposes; perform neither annotation processing nor compilation. The format of the output may change.
-XprintProcessorInfo
Print information about which annotations a processor is asked to process.
-XprintRounds
Print information about initial and subsequent annotation processing rounds.

Warnings That Can Be Enabled or Disabled with -Xlint Option

Enable warning name with the option -Xlint:name, where name is one of the following warning names. Similarly, you can disable warning name with the option -Xlint:-name:

cast
Warn about unnecessary and redundant casts. For example:
String s = (String)"Hello!"
classfile
Warn about issues related to classfile contents.
deprecation
Warn about use of deprecated items. For example:
    java.util.Date myDate = new java.util.Date();
    int currentDay = myDate.getDay();

The method java.util.Date.getDay has been deprecated since JDK 1.1.

dep-ann
Warn about items that are documented with an @deprecated Javadoc comment, but do not have a @Deprecated annotation. For example:
  /**
   * @deprecated As of Java SE 7, replaced by {@link #newMethod()}
   */

  public static void deprecatedMethood() { }

  public static void newMethod() { }
divzero
Warn about division by constant integer 0. For example:
    int divideByZero = 42 / 0;
empty
Warn about empty statements after if statements. For example:
class E {
    void m() {
        if (true) ;
    }
}
fallthrough
Check switch blocks for fall-through cases and provide a warning message for any that are found. Fall-through cases are cases in a switch block, other than the last case in the block, whose code does not include a break statement, allowing code execution to "fall through" from that case to the next case. For example, the code following the case 1 label in this switch block does not end with a break statement:
switch (x) {
case 1:
       System.out.println("1");
       //  No break statement here.
case 2:
       System.out.println("2");
}

If the -Xlint:fallthrough flag were used when compiling this code, the compiler would emit a warning about "possible fall-through into case," along with the line number of the case in question.

finally
Warn about finally clauses that cannot complete normally. For example:
  public static int m() {
    try {
      throw new NullPointerException();
    } catch (NullPointerException e) {
      System.err.println("Caught NullPointerException.");
      return 1;
    } finally {
      return 0;
    }
  }

The compiler generates a warning for finally block in this example. When this method is called, it returns a value of 0, not 1. A finally block always executes when the try block exits. In this example, if control is transferred to the catch, then the method exits. However, the finally block must be executed, so it is executed, even though control has already been transferred outside the method.

options
Warn about issues relating to the use of command line options. See Cross-Compilation Example for an example of this kind of warning.
overrides
Warn about issues regarding method overrides. For example, consider the following two classes:
public class ClassWithVarargsMethod {
  void varargsMethod(String... s) { }
}

public class ClassWithOverridingMethod extends ClassWithVarargsMethod {
  @Override
  void varargsMethod(String[] s) { }
}

The compiler generates a warning similar to the following:

warning: [override] varargsMethod(String[]) in ClassWithOverridingMethod overrides varargsMethod(String...) in ClassWithVarargsMethod; overriding method is missing '...'

When the compiler encounters a varargs method, it translates the varargs formal parameter into an array. In the method ClassWithVarargsMethod.varargsMethod, the compiler translates the varargs formal parameter String... s to the formal parameter String[] s, an array, which matches the formal parameter of the method ClassWithOverridingMethod.varargsMethod. Consequently, this example compiles.

path
Warn about invalid path elements and nonexistent path directories on the command line (with regards to the class path, the source path, and other paths). Such warnings cannot be suppressed with the @SuppressWarnings annotation. For example:
javac -Xlint:path -classpath C:\nonexistentpath Example.java
processing
Warn about issues regarding annotation processing. The compiler generates this warning if you have a class that has an annotation, and you use an annotation processor that cannot handle that type of exception. For example, the following is a simple annotation processor:

Source file AnnoProc.java:

import java.util.*;
import javax.annotation.processing.*;
import javax.lang.model.*;
import javax.lang.model.element.*;

@SupportedAnnotationTypes("NotAnno")
public class AnnoProc extends AbstractProcessor {
    public boolean process(Set<? extends TypeElement> elems, RoundEnvironment renv) {
        return true;
    }

    public SourceVersion getSupportedSourceVersion() {
        return SourceVersion.latest();
    }
}

Source file AnnosWithoutProcessors.java:

@interface Anno { }

@Anno
class AnnosWithoutProcessors { }

The following commands compile the annotation processor AnnoProc, then run this annotation processor against the source file AnnosWithoutProcessors.java:

% javac AnnoProc.java
% javac -cp . -Xlint:processing -processor AnnoProc -proc:only AnnosWithoutProcessors.java

When the compiler runs the annotation processor against the source file AnnosWithoutProcessors.java, it generates the following warning:

warning: [processing] No processor claimed any of these annotations: Anno

To resolve this issue, you can rename the annotation defined and used in the class AnnosWithoutProcessors from Anno to NotAnno.

rawtypes
Warn about unchecked operations on raw types. The following statement generates a rawtypes warning:
void countElements(List l) { ... }

The following does not generate a rawtypes warning:

void countElements(List<?> l) { ... }

List is a raw type. However, List<?> is a unbounded wildcard parameterized type. Because List is a parameterized interface, you should always specify its type argument. In this example, the List formal argument is specified with a unbounded wildcard (?) as its formal type parameter, which means that the countElements method can accept any instantiation of the List interface.

serial
Warn about missing serialVersionUID definitions on serializable classes. For example:
public class PersistentTime implements Serializable
{
  private Date time;

   public PersistentTime() {
     time = Calendar.getInstance().getTime();
   }

   public Date getTime() {
     return time;
   }
}

The compiler generates the following warning:

warning: [serial] serializable class PersistentTime has no definition of serialVersionUID

If a serializable class does not explicitly declare a field named serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values because the default process of computing serialVersionUID vales is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different Java compiler implementations, a serializable class must declare an explicit serialVersionUID value.

static
Warn about issues relating to use of statics. For example:
class XLintStatic {
    static void m1() { }
    void m2() { this.m1(); }
}

The compiler generates the following warning:

warning: [static] static method should be qualified by type name, XLintStatic, instead of by an expression

To resolve this issue, you can call the static method m1 as follows:

XLintStatic.m1();

Alternatively, you can remove the static keyword from the declaration of the method m1.

try
Warn about issues relating to use of try blocks, including try-with-resources statements. For example, a warning is generated for the following statement because the resource ac declared in the try statement is not used:
try ( AutoCloseable ac = getResource() ) {
    // do nothing
}
unchecked
Give more detail for unchecked conversion warnings that are mandated by the Java Language Specification. For example:
    List l = new ArrayList<Number>();
    List<String> ls = l;       // unchecked warning

During type erasure, the types ArrayList<Number> and List<String> become ArrayList and List, respectively.

The variable ls has the parameterized type List<String>. When the List referenced by l is assigned to ls, the compiler generates an unchecked warning; the compiler is unable to determine at compile time, and moreover knows that the JVM will not be able to determine at runtime, if l refers to a List<String> type; it does not. Consequently, heap pollution occurs.

In detail, a heap pollution situation occurs when the List object l, whose static type is List<Number>, is assigned to another List object, ls, that has a different static type, List<String>. However, the compiler still allows this assignment. It must allow this assignment to preserve backwards compatibility with versions of Java SE that do not support generics. Because of type erasure, List<Number> and List<String> both become List. Consequently, the compiler allows the assignment of the object l, which has a raw type of List, to the object ls.

varargs
Warn about unsafe usages of variable arguments (varargs) methods, in particular, those that contain non-reifiable arguments. For example:
public class ArrayBuilder {
  public static <T> void addToList (List<T> listArg, T... elements) {
    for (T x : elements) {
      listArg.add(x);
    }
  }
}

The compiler generates the following warning for the definition of the method ArrayBuilder.addToList:

warning: [varargs] Possible heap pollution from parameterized vararg type T

When the compiler encounters a varargs method, it translates the varargs formal parameter into an array. However, the Java programming language does not permit the creation of arrays of parameterized types. In the method ArrayBuilder.addToList, the compiler translates the varargs formal parameter T... elements to the formal parameter T[] elements, an array. However, because of type erasure, the compiler converts the varargs formal parameter to Object[] elements. Consequently, there is a possibility of heap pollution.

COMMAND LINE ARGUMENT FILES

To shorten or simplify the javac command line, you can specify one or more files that themselves contain arguments to the javac command (except -J options). This enables you to create javac commands of any length on any operating system.

An argument file can include javac options and source filenames in any combination. The arguments within a file can be space-separated or newline-separated. If a filename contains embedded spaces, put the whole filename in double quotes, and double each backslash ("My Files\\Stuff.java").

Filenames within an argument file are relative to the current directory, not the location of the argument file. Wildcards (*) are not allowed in these lists (such as for specifying *.java). Use of the '@' character to recursively interpret files is not supported. The -J options are not supported because they are passed to the launcher, which does not support argument files.

When executing javac, pass in the path and name of each argument file with the '@' leading character. When javac encounters an argument beginning with the character `@', it expands the contents of that file into the argument list.

Example - Single Arg File

You could use a single argument file named "argfile" to hold all javac arguments:

  C:> javac @argfile

This argument file could contain the contents of both files shown in the next example.

Example - Two Arg Files

You can create two argument files -- one for the javac options and the other for the source filenames: (Notice the following lists have no line-continuation characters.)

Create a file named "options" containing:

     -d classes
     -g
     -sourcepath C:\java\pubs\ws\1.3\src\share\classes

Create a file named "classes" containing:

     MyClass1.java
     MyClass2.java
     MyClass3.java

You would then run javac with:

  C:> javac @options @classes

Example - Arg Files with Paths

The argument files can have paths, but any filenames inside the files are relative to the current working directory (not path1 or path2):

  C:> javac @path1\options @path2\classes

ANNOTATION PROCESSING

javac provides direct support for annotation processing, superseding the need for the separate annotation processing tool, apt.

The API for annotation processors is defined in the javax.annotation.processing and javax.lang.model packages and subpackages.

Overview of annotation processing

Unless annotation processing is disabled with the -proc:none option, the compiler searches for any annotation processors that are available. The search path can be specified with the -processorpath option; if it is not given, the user class path is used. Processors are located by means of service provider-configuration files named META-INF/services/javax.annotation.processing.Processor on the search path. Such files should contain the names of any annotation processors to be used, listed one per line. Alternatively, processors can be specified explicitly, using the -processor option.

After scanning the source files and classes on the command line to determine what annotations are present, the compiler queries the processors to determine what annotations they process. When a match is found, the processor will be invoked. A processor may "claim" the annotations it processes, in which case no further attempt is made to find any processors for those annotations. Once all annotations have been claimed, the compiler does not look for additional processors.

If any processors generate any new source files, another round of annotation processing will occur: any newly generated source files will be scanned, and the annotations processed as before. Any processors invoked on previous rounds will also be invoked on all subsequent rounds. This continues until no new source files are generated.

After a round occurs where no new source files are generated, the annotation processors will be invoked one last time, to give them a chance to complete any work they may need to do. Finally, unless the -proc:only option is used, the compiler will compile the original and all the generated source files.

Implicitly loaded source files

To compile a set of source files, the compiler may need to implicitly load additional source files. (See Searching For Types). Such files are currently not subject to annotation processing. By default, the compiler will give a warning if annotation processing has occurred and any implicitly loaded source files are compiled. See the -implicit option for ways to suppress the warning.

SEARCHING FOR TYPES

When compiling a source file, the compiler often needs information about a type whose definition did not appear in the source files given on the command line. The compiler needs type information for every class or interface used, extended, or implemented in the source file. This includes classes and interfaces not explicitly mentioned in the source file but which provide information through inheritance.

For example, when you subclass java.applet.Applet, you are also using Applet's ancestor classes: java.awt.Panel, java.awt.Container, java.awt.Component, and java.lang.Object.

When the compiler needs type information, it looks for a source file or class file which defines the type. The compiler searches for class files first in the bootstrap and extension classes, then in the user class path (which by default is the current directory). The user class path is defined by setting the CLASSPATH environment variable or by using the -classpath command line option. (For details, see Setting the Class Path).

If you set the -sourcepath option, the compiler searches the indicated path for source files; otherwise the compiler searches the user class path for both class files and source files.

You can specify different bootstrap or extension classes with the -bootclasspath and -extdirs options; see Cross-Compilation Options below.

A successful type search may produce a class file, a source file, or both. If both are found, you can use the -Xprefer option to instruct the compiler which to use. If newer is given, the compiler will use the newer of the two files. If source is given, it will use the source file. The default is newer.

If a type search finds a source file for a required type, either by itself, or as a result of the setting for -Xprefer, the compiler will read the source file to get the information it needs. In addition, it will by default compile the source file as well. You can use the -implicit option to specify the behavior. If none is given, no class files will be generated for the source file. If class is given, class files will be generated for the source file.

The compiler may not discover the need for some type information until after annotation processing is complete. If the type information is found in a source file and no -implicit option is given, the compiler will give a warning that the file is being compiled without being subject to annotation processing. To disable the warning, either specify the file on the command line (so that it will be subject to annotation processing) or use the -implicit option to specify whether or not class files should be generated for such source files.

PROGRAMMATIC INTERFACE

javac supports the new Java Compiler API defined by the classes and interfaces in the javax.tools package.

Example

To perform a compilation using arguments as you would give on the command line, you can use the following:

JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
int rc = javac.run(null, null, null, args);

This will write any diagnostics to the standard output stream, and return the exit code that javac would give when invoked from the command line.

You can use other methods on the javax.tools.JavaCompiler interface to handle diagnostics, control where files are read from and written to, and so on.

Old Interface

Note: This API is retained for backwards compatibility only; all new code should use the Java Compiler API, described above.

The com.sun.tools.javac.Main class provides two static methods to invoke the compiler from a program:

public static int compile(String[] args);
public static int compile(String[] args, PrintWriter out);

The args parameter represents any of the command line arguments that would normally be passed to the javac program and are outlined in the above Synopsis section.

The out parameter indicates where the compiler's diagnostic output is directed.

The return value is equivalent to the exit value from javac.

Note that all other classes and methods found in a package whose name starts with com.sun.tools.javac (informally known as sub-packages of com.sun.tools.javac) are strictly internal and subject to change at any time.

EXAMPLES

Compiling a Simple Program

One source file, Hello.java, defines a class called greetings.Hello. The greetings directory is the package directory both for the source file and the class file and is off the current directory. This allows us to use the default user class path. It also makes it unnecessary to specify a separate destination directory with -d.

C:> dir
greetings
C:> dir greetings
Hello.java
C:> cat greetings\Hello.java
package greetings;

public class Hello {
    public static void main(String[] args) {
        for (int i=0; i < args.length; i++) {
            System.out.println("Hello " + args[i]);
        }
    }
}
C:> javac greetings\Hello.java
C:> dir greetings
Hello.class   Hello.java
C:> java greetings.Hello World Universe Everyone
Hello World
Hello Universe
Hello Everyone

Compiling Multiple Source Files

This example compiles all the source files in the package greetings.

C:> dir
greetings\
C:> dir greetings
Aloha.java         GutenTag.java      Hello.java         Hi.java
C:> javac greetings\*.java
C:> dir greetings
Aloha.class         GutenTag.class      Hello.class         Hi.class
Aloha.java          GutenTag.java       Hello.java          Hi.java

Specifying a User Class Path

Having changed one of the source files in the previous example, we recompile it:

C:> cd
\examples
C:> javac greetings\Hi.java

Since greetings.Hi refers to other classes in the greetings package, the compiler needs to find these other classes. The example above works, because our default user class path happens to be the directory containing the package directory. But suppose we want to recompile this file and not worry about which directory we're in? Then we need to add \examples to the user class path. We can do this by setting CLASSPATH, but here we'll use the -classpath option.

C:>javac -classpath \examples \examples\greetings\Hi.java

If we change greetings.Hi again, to use a banner utility, that utility also needs to be accessible through the user class path.

C:>javac -classpath \examples;\lib\Banners.jar \
            \examples\greetings\Hi.java

To execute a class in greetings, we need access both to greetings and to the classes it uses.

C:>java -classpath \examples;\lib\Banners.jar greetings.Hi

Separating Source Files and Class Files

It often makes sense to keep source files and class files in separate directories, especially on large projects. We use -d to indicate the separate class file destination. Since the source files are not in the user class path, we use -sourcepath to help the compiler find them.

C:> dir
classes\  lib\      src\
C:> dir src
farewells\
C:> dir src\farewells
Base.java      GoodBye.java
C:> dir lib
Banners.jar
C:> dir classes
C:> javac -sourcepath src -classpath classes;lib\Banners.jar \
            src\farewells\GoodBye.java -d classes
C:> dir classes
farewells\
C:> dir classes\farewells
Base.class      GoodBye.class

Note: The compiler compiled src\farewells\Base.java, even though we didn't specify it on the command line. To trace automatic compiles, use the -verbose option.

Cross-Compilation Example

Here we use javac to compile code that will run on a 1.7 VM.

% javac -target 1.7 -bootclasspath jdk1.7.0\lib\rt.jar \
            -extdirs "" OldCode.java

The -target 1.7 option ensures that the generated class files will be compatible with 1.7 VMs. By default, javac compiles for JDK 6.

The Java Platform JDK's javac would also by default compile against its own bootstrap classes, so we need to tell javac to compile against JDK 1.7 bootstrap classes instead. We do this with -bootclasspath and -extdirs. Failing to do this might allow compilation against a Java Platform API that would not be present on a 1.7 VM and would fail at runtime.

SEE ALSO

  • javac Guide
  • java - the Java Application Launcher
  • jdb - Java Application Debugger
  • javah - C Header and Stub File Generator
  • javap - Class File Disassembler
  • javadoc - API Documentation Generator
  • jar - JAR Archive Tool
  • The Java Extensions Framework
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.source.util.JavacTask (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.source.util.JavacTask

No usage of com.sun.source.util.JavacTask
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


javadoc-The Java API Documentation Generator

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

javadoc - The Java API Documentation Generator

Generates HTML pages of API documentation from Java source files. This document contains Javadoc™ examples for Microsoft Windows.

CONTENTS

Reference Guide
  • Synopsis
  • Description
    • Processing of Source Files
    • Javadoc Doclets
    • Related Documentation
    • Terminology
  • Source Files
    • Class Source Code Files
    • Package Comment Files
    • Overview Comment File
    • Miscellaneous Unprocessed Files
    • Test Files and Template Files
  • Generated Files
    • Generated API Declarations
  • Documentation Comments
    • Commenting the Source Code
    • Automatic Copying of Method Comments
  • Javadoc Tags (@tag)
    • Where Tags Can Be Used
  • Options (-option)
    • Javadoc Options
    • Options Provided by the Standard Doclet
  • Command Line Argument Files
Running
  • Running Javadoc
  • Simple Examples
    • Documenting One or More Packages
    • Documenting One or More Classes
    • Documenting Both Packages and Classes
  • Real World Example
    • Command Line Example
    • Makefile Example
  • Troubleshooting
    • General Troubleshooting
    • Errors and Warnings
  • Environment
    • CLASSPATH
  • Troubleshooting
  • See Also

Reference Guide

SYNOPSIS

javadoc [ options ] [ packagenames ] [ sourcefilenames ] [ -subpackages pkg1:pkg2:... ] [ @argfiles ]

Arguments can be in any order. See processing of Source Files for details on how the Javadoc tool determines which ".java" files to process.

options
Command-line options, as specified in this document. To see a typical use of javadoc options, see Real-World Example.
packagenames
A series of names of packages, separated by spaces, such as java.lang java.lang.reflect java.awt. You must separately specify each package you want to document. Wildcards are not allowed; use -subpackages for recursion. The Javadoc tool uses -sourcepath to look for these package names. See Example - Documenting One or More Packages
sourcefilenames
A series of source file names, separated by spaces, each of which can begin with a path and contain a wildcard such as asterisk (*). The Javadoc tool will process every file whose name ends with ".java", and whose name, when stripped of that suffix, is actually a legal class name (see information about Identifiers in the Java Language Specification). Therefore, you can name files with dashes (such as X-Buffer), or other illegal characters, to prevent them from being documented. This is useful for test files and template files The path that precedes the source file name determines where javadoc will look for the file. (The Javadoc tool does not use -sourcepath to look for these source file names.) Relative paths are relative to the current directory, so passing in Button.java is identical to ./Button.java. A source file name with an absolute path and a wildcard, for example, is /home/src/java/awt/Graphics*.java. See Example - Documenting One or More Classes. You can also mix packagenames and sourcefilenames, as in Example - Documenting Both Packages and Classes
-subpackages pkg1:pkg2:...
Generates documentation from source files in the specified packages and recursively in their subpackages. An alternative to supplying packagenames or sourcefilenames.
@argfiles
One or more files that contain a list of Javadoc options, packagenames and sourcefilenames in any order. Wildcards (*) and -J options are not allowed in these files.

DESCRIPTION

The Javadoc™ tool parses the declarations and documentation comments in a set of Java source files and produces a corresponding set of HTML pages describing (by default) the public and protected classes, nested classes (but not anonymous inner classes), interfaces, constructors, methods, and fields. You can use it to generate the API (Application Programming Interface) documentation or the implementation documentation for a set of source files.

You can run the Javadoc tool on entire packages, individual source files, or both. When documenting entire packages, you can either use -subpackages for traversing recursively down from a top-level directory, or pass in an explicit list of package names. When documenting individual source files, you pass in a list of source (.java) filenames. Examples are given at the end of this document. How Javadoc processes source files is covered next.

Processing of source files

The Javadoc tool processes files that end in ".java" plus other files described under Source Files. If you run the Javadoc tool by explicitly passing in individual source filenames, you can determine exactly which ".java" files are processed. However, that is not how most developers want to work, as it is simpler to pass in package names. The Javadoc tool can be run three ways without explicitly specifying the source filenames. You can (1) pass in package names, (2) use -subpackages, and (3) use wildcards with source filenames (*.java). In these cases, the Javadoc tool processes a ".java" file only if it fulfills all of the following requirements:
  • Its name, after stripping off the ".java" suffix, is actually a legal class name (see the Java Language Specification for legal characters)
  • Its directory path relative to the root of the source tree is actually a legal package name (after converting its separators to dots)
  • Its package statement contains the legal package name (specified in the previous bullet)

Processing of links - During a run, the Javadoc tool automatically adds cross-reference links to package, class and member names that are being documented as part of that run. Links appear in several places:

  • Declarations (return types, argument types, field types)
  • "See Also" sections generated from @see tags
  • In-line text generated from {@link} tags
  • Exception names generated from @throws tags
  • "Specified by" links to members in interfaces and "Overrides" links to members in classes
  • Summary tables listing packages, classes and members
  • Package and class inheritance trees
  • The index
You can add hyperlinks to existing text for classes not included on the command line (but generated separately) by way of the -link and -linkoffline options.

Other processing details - The Javadoc tool produces one complete document each time it is run; it cannot do incremental builds -- that is, it cannot modify or directly incorporate results from previous runs of the Javadoc tool. However, it can link to results from other runs, as just mentioned.

As implemented, the Javadoc tool requires and relies on the java compiler to do its job. The Javadoc tool calls part of javac to compile the declarations, ignoring the member implementation. It builds a rich internal representation of the classes, including the class hierarchy, and "use" relationships, then generates the HTML from that. The Javadoc tool also picks up user-supplied documentation from documentation comments in the source code.

In fact, the Javadoc tool will run on .java source files that are pure stub files with no method bodies. This means you can write documentation comments and run the Javadoc tool in the earliest stages of design while creating the API, before writing the implementation.

Relying on the compiler ensures that the HTML output corresponds exactly with the actual implementation, which may rely on implicit, rather than explicit, source code. For example, the Javadoc tool documents default constructors ( see the Java Language Specification) that are present in the .class files but not in the source code.

In many cases, the Javadoc tool allows you to generate documentation for source files whose code is incomplete or erroneous. This is a benefit that enables you to generate documentation before all debugging and troubleshooting is done. For example, according to the Java Language Specification, a class that contains an abstract method should itself be declared abstract. The Javadoc tool does not check for this, and would proceed without a warning, whereas the javac compiler stops on this error. The Javadoc tool does do some primitive checking of doc comments. Use the DocCheck doclet to check the doc comments more thoroughly.

When the Javadoc tool builds its internal structure for the documentation, it loads all referenced classes. Because of this, the Javadoc tool must be able to find all referenced classes, whether bootstrap classes, extensions, or user classes. For more about this, see How Classes Are Found. Generally speaking, classes you create must either be loaded as an extension or in the Javadoc tool's class path.

Javadoc Doclets

You can customize the content and format of the Javadoc tool's output by using doclets. The Javadoc tool has a default "built-in" doclet, called the standard doclet, that generates HTML-formatted API documentation. You can modify or subclass the standard doclet, or write your own doclet to generate HTML, XML, MIF, RTF or whatever output format you'd like. Information about doclets and their use is at the following locations:
  • Javadoc Doclets
  • The -doclet command-line option
When a custom doclet is not specified with the -doclet command line option, the Javadoc tool will use the default standard doclet. The javadoc tool has several command line options that are available regardless of which doclet is being used. The standard doclet adds a supplementary set of command line options. Both sets of options are described below in the options section.

Related Documentation and Doclets

  • Javadoc Enhancements for details about improvements added in Javadoc.
  • Javadoc FAQ for answers to common questions, information about Javadoc-related tools, and workarounds for bugs.
  • How to Write Doc Comments for Javadoc for more information about Sun conventions for writing documentation comments.
  • Requirements for Writing API Specifications - Standard requirements used when writing the Java SE Platform Specification. It can be useful whether you are writing API specifications in source file documentation comments or in other formats. It covers requirements for packages, classes, interfaces, fields and methods to satisfy testable assertions.
  • Documentation Comment Specification - The original specification on documentation comments, Chapter 18, Documentation Comments, in the Java Language Specification, First Edition, by James Gosling, Bill Joy, and Guy Steele. (This chapter was removed from the second edition.)
  • DocCheck Doclet - Checks doc comments in source files and generates a report listing the errors and irregularities it finds. It is part of the Sun Doc Check Utilities.
  • MIF Doclet - Can automate the generation of API documentation in MIF, FrameMaker and PDF formats. MIF is Adobe FrameMaker's interchange format.

Terminology

The terms documentation comment, doc comment, main description, tag, block tag, and in-line tag are described at Documentation Comments. These other terms have specific meanings within the context of the Javadoc tool:
generated document
The document generated by the javadoc tool from the doc comments in Java source code. The default generated document is in HTML and is created by the standard doclet.

name
A name of a program element written in the Java Language -- that is, the name of a package, class, interface, field, constructor or method. A name can be fully-qualified, such as java.lang.String.equals(java.lang.Object), or partially-qualified, such as equals(Object).

documented classes
The classes and interfaces for which detailed documentation is generated during a javadoc run. To be documented, the source files must be available, their source filenames or package names must be passed into the javadoc command, and they must not be filtered out by their access modifier (public, protected, package-private or private). We also refer to these as the classes included in the javadoc output, or the included classes.

included classes
Classes and interfaces whose details are documented during a run of the Javadoc tool. Same as documented classes.

excluded classes
Classes and interfaces whose details are not documented during a run of the Javadoc tool.

referenced classes
The classes and interfaces that are explicitly referred to in the definition (implementation) or doc comments of the documented classes and interfaces. Examples of references include return type, parameter type, cast type, extended class, implemented interface, imported classes, classes used in method bodies, @see, {@link}, {@linkplain}, and {@inheritDoc} tags. (Notice this definition has changed since 1.3.) When the Javadoc tool is run, it should load into memory all of the referenced classes in javadoc's bootclasspath and classpath. (The Javadoc tool prints a "Class not found" warning for referenced classes not found.) The Javadoc tool can derive enough information from the .class files to determine their existence and the fully-qualified names of their members.

external referenced classes
The referenced classes whose documentation is not being generated during a javadoc run. In other words, these classes are not passed into the Javadoc tool on the command line. Links in the generated documentation to those classes are said to be external references or external links. For example, if you run the Javadoc tool on only the java.awt package, then any class in java.lang, such as Object, is an external referenced class. External referenced classes can be linked to using the -link and -linkoffline options. An important property of an external referenced class is that its source comments are normally not available to the Javadoc run. In this case, these comments cannot be inherited.

SOURCE FILES

The Javadoc tool will generate output originating from four different types of "source" files: Java language source files for classes (.java), package comment files, overview comment files, and miscellaneous unprocessed files. This section also covers test files and template files that can also be in the source tree, but which you want to be sure not to document.

Class Source Code Files

Each class or interface and its members can have their own documentation comments, contained in a .java file. For more details about these doc comments, see Documentation Comments.

Package Comment Files

Each package can have its own documentation comment, contained in its own "source" file, that the Javadoc tool will merge into the package summary page that it generates. You typically include in this comment any documentation that applies to the entire package.

To create a package comment file, you have a choice of two files to place your comments:

  • package-info.java - Can contain a package declaration, package annotations, package comments and Javadoc tags. This file is generally preferred over package.html.
  • package.html - Can contain only package comments and Javadoc tags, no package annotations.

A package may have a single package.html file or a single package-info.java file but not both. Place either file in the package directory in the source tree along with your .java files.

package-info.java This file can contain a package comment of the following structure -- the comment is placed before the package declaration:

File: java/applet/package-info.java

/**
 * Provides the classes necessary to create an
 * applet and the classes an applet uses
 * to communicate with its applet context.
 * <p>
 * The applet framework involves two entities:
 * the applet and the applet context.
 * An applet is an embeddable window (see the
 * {@link java.awt.Panel} class) with a few extra
 * methods that the applet context can use to
 * initialize, start, and stop the applet.
 *
 * @since 1.0
 * @see java.awt
 */
package java.lang.applet;

Note that while the comment separators /** and /* must be present, the leading asterisks on the intermediate lines can be omitted. package.html - This file can contain a package comment of the following structure -- the comment is placed in the <body> element:

File: java/applet/package.html

<HTML>
<BODY>
Provides the classes necessary to create an applet and the
classes an applet uses to communicate with its applet context.
<p>
The applet framework involves two entities: the applet
and the applet context. An applet is an embeddable
window (see the {@link java.awt.Panel} class) with a
few extra methods that the applet context can use to
initialize, start, and stop the applet.

@since 1.0
@see java.awt
</BODY>
</HTML>

Notice this is just a normal HTML file and does not include a package declaration. The content of the package comment file is written in HTML, like all other comments, with one exception: The documentation comment should not include the comment separators /** and */ or leading asterisks. When writing the comment, you should make the first sentence a summary about the package, and not put a title or any other text between <body> and the first sentence. You can include package tags; as with any documentation comment, all block tags must appear after the main description. If you add a @see tag in a package comment file, it must have a fully-qualified name. For more details, see the example of package.html.

Processing of package comment file - When the Javadoc tool runs, it will automatically look for the package comment file; if found, the Javadoc tool does the following:

  • Copies the comment for processing. (For package.html, copies all content between <body> and </body> HTML tags. You can include a <head> section to put a <title>, source file copyright statement, or other information, but none of these will appear in the generated documentation.)
  • Processes any package tags that are present.
  • Inserts the processed text at the bottom of the package summary page it generates, as shown in Package Summary.
  • Copies the first sentence of the package comment to the top of the package summary page. It also adds the package name and this first sentence to the list of packages on the overview page, as shown in Overview Summary. The end-of-sentence is determined by the same rules used for the end of the first sentence of class and member main descriptions.

Overview Comment File

Each application or set of packages that you are documenting can have its own overview documentation comment, kept in its own "source" file, that the Javadoc tool will merge into the overview page that it generates. You typically include in this comment any documentation that applies to the entire application or set of packages.

To create an overview comment file, you can name the file anything you want, typically overview.html and place it anywhere, typically at the top level of the source tree. For example, if the source files for the java.applet package are contained in C:\user\src\java\applet directory, you could create an overview comment file at C:\user\src\overview.html.

Notice you can have multiple overview comment files for the same set of source files, in case you want to run javadoc multiple times on different sets of packages. For example, you could run javadoc once with -private for internal documentation and again without that option for public documentation. In this case, you could describe the documentation as public or internal in the first sentence of each overview comment file.

The content of the overview comment file is one big documentation comment, written in HTML, like the package comment file described previously. See that description for details. To re-iterate, when writing the comment, you should make the first sentence a summary about the application or set of packages, and not put a title or any other text between <body> and the first sentence. You can include overview tags; as with any documentation comment, all tags except in-line tags, such as {@link}, must appear after the main description. If you add a @see tag, it must have a fully-qualified name.

When you run the Javadoc tool, you specify the overview comment file name with the -overview option. The file is then processed similar to that of a package comment file.

  • Copies all content between <body> and </body> tags for processing.
  • Processes any overview tags that are present.
  • Inserts the processed text at the bottom of the overview page it generates, as shown in Overview Summary.
  • Copies the first sentence of the overview comment to the top of the overview summary page.

Miscellaneous Unprocessed Files

You can also include in your source any miscellaneous files that you want the Javadoc tool to copy to the destination directory. These typically includes graphic files, example Java source (.java) and class (.class) files, and self-standing HTML files whose content would overwhelm the documentation comment of a normal Java source file.

To include unprocessed files, put them in a directory called doc-files which can be a subdirectory of any package directory that contains source files. You can have one such subdirectory for each package. You might include images, example code, source files, .class files, applets and HTML files. For example, if you want to include the image of a button button.gif in the java.awt.Button class documentation, you place that file in the /home/user/src/java/awt/doc-files/ directory. Notice the doc-files directory should not be located at /home/user/src/java/doc-files because java is not a package -- that is, it does not directly contain any source files.

All links to these unprocessed files must be hard-coded, because the Javadoc tool does not look at the files -- it simply copies the directory and all its contents to the destination. For example, the link in the Button.java doc comment might look like:

    /**
     * This button looks like this:
     * <img src="doc-files/Button.gif">
     */

Test Files and Template Files

Some developers have indicated they want to store test files and templates files in the source tree near their corresponding source files. That is, they would like to put them in the same directory, or a subdirectory, of those source files.

If you run the Javadoc tool by explicitly passing in individual source filenames, you can deliberately omit test and templates files and prevent them from being processed. However, if you are passing in package names or wildcards, you need to follow certain rules to ensure these test files and templates files are not processed.

Test files differ from template files in that the former are legal, compilable source files, while the latter are not, but may end with ".java".

Test files - Often developers want to put compilable, runnable test files for a given package in the same directory as the source files for that package. But they want the test files to belong to a package other than the source file package, such as the unnamed package (so the test files have no package statement or a different package statement from the source). In this scenario, when the source is being documented by specifying its package name specified on the command line, the test files will cause warnings or errors. You need to put such test files in a subdirectory. For example, if you want to add test files for source files in com.package1, put them in a subdirectory that would be an invalid package name (because it contains a hyphen):

    com/package1/test-files/
The test directory will be skipped by the Javadoc tool with no warnings.

If your test files contain doc comments, you can set up a separate run of the Javadoc tool to produce documentation of the test files by passing in their test source filenames with wildcards, such as com/package1/test-files/*.java.

Templates for source files - Template files have names that often end in ".java" and are not compilable. If you have a template for a source file that you want to keep in the source directory, you can name it with a dash (such as Buffer-Template.java), or any other illegal Java character, to prevent it from being processed. This relies on the fact that the Javadoc tool will only process source files whose name, when stripped of the ".java" suffix, is actually a legal class name (see information about Identifiers in the Java Language Specification).

GENERATED FILES

By default, javadoc uses a standard doclet that generates HTML-formatted documentation. This doclet generates the following kinds of files (where each HTML "page" corresponds to a separate file). Note that javadoc generates files with two types of names: those named after classes/interfaces, and those that are not (such as package-summary.html). Files in the latter group contain hyphens to prevent filename conflicts with those in the former group.

Basic Content Pages

  • One class or interface page (classname.html) for each class or interface it is documenting.
  • One package page (package-summary.html) for each package it is documenting. The Javadoc tool will include any HTML text provided in a file named package.html or package-info.java in the package directory of the source tree.
  • One overview page (overview-summary.html) for the entire set of packages. This is the front page of the generated document. The Javadoc tool will include any HTML text provided in a file specified with the -overview option. Note that this file is created only if you pass into javadoc two or more package names. For further explanation, see HTML Frames.)

Cross-Reference Pages

  • One class hierarchy page for the entire set of packages (overview-tree.html). To view this, click on "Overview" in the navigation bar, then click on "Tree".
  • One class hierarchy page for each package (package-tree.html) To view this, go to a particular package, class or interface page; click "Tree" to display the hierarchy for that package.
  • One "use" page for each package (package-use.html) and a separate one for each class and interface (class-use/classname.html). This page describes what packages, classes, methods, constructors and fields use any part of the given class, interface or package. Given a class or interface A, its "use" page includes subclasses of A, fields declared as A, methods that return A, and methods and constructors with parameters of type A. You can access this page by first going to the package, class or interface, then clicking on the "Use" link in the navigation bar.
  • A deprecated API page (deprecated-list.html) listing all deprecated names. (A deprecated name is not recommended for use, generally due to improvements, and a replacement name is usually given. Deprecated APIs may be removed in future implementations.)
  • A constant field values page (constant-values.html) for the values of static fields.
  • A serialized form page (serialized-form.html) for information about serializable and externalizable classes. Each such class has a description of its serialization fields and methods. This information is of interest to re-implementors, not to developers using the API. While there is no link in the navigation bar, you can get to this information by going to any serialized class and clicking "Serialized Form" in the "See also" section of the class comment. The standard doclet automatically generates a serialized form page: any class (public or non-public) that implements Serializable is included, along with readObject and writeObject methods, the fields that are serialized, and the doc comments from the @serial, @serialField, and @serialData tags. Public serializable classes can be excluded by marking them (or their package) with @serial exclude, and package-private serializable classes can be included by marking them (or their package) with @serial include. As of 1.4, you can generate the complete serialized form for public and private classes by running javadoc without specifying the -private option.
  • An index (index-*.html) of all class, interface, constructor, field and method names, alphabetically arranged. This is internationalized for Unicode and can be generated as a single file or as a separate file for each starting character (such as A-Z for English).

Support Files

  • A help page (help-doc.html) that describes the navigation bar and the above pages. You can provide your own custom help file to override the default using -helpfile.
  • One index.html file which creates the HTML frames for display. This is the file you load to display the front page with frames. This file itself contains no text content.
  • Several frame files (*-frame.html) containing lists of packages, classes and interfaces, used when HTML frames are being displayed.
  • A package list file (package-list), used by the -link and -linkoffline options. This is a text file, not HTML, and is not reachable through any links.
  • A style sheet file (stylesheet.css) that controls a limited amount of color, font family, font size, font style and positioning on the generated pages.
  • A doc-files directory that holds any image, example, source code or other files that you want copied to the destination directory. These files are not processed by the Javadoc tool in any manner -- that is, any javadoc tags in them will be ignored. This directory is not generated unless it exists in the source tree.

HTML Frames

The Javadoc tool will generate either two or three HTML frames, as shown in the figure below. It creates the minimum necessary number of frames by omitting the list of packages if there is only one package (or no packages). That is, when you pass a single package name or source files (*.java) belonging to a single package as arguments into the javadoc command, it will create only one frame (C) in the left-hand column -- the list of classes. When you pass into javadoc two or more package names, it creates a third frame (P) listing all packages, as well as an overview page (Detail). This overview page has the filename overview-summary.html. Thus, this file is created only if you pass in two or more package names. You can bypass frames by clicking on the "No Frames" link or entering at overview-summary.html.

If you are unfamiliar with HTML frames, you should be aware that frames can have focus for printing and scrolling. To give a frame focus, click on it. Then on many browsers the arrow keys and page keys will scroll that frame, and the print menu command will print it.

Load one of the following two files as the starting page depending on whether you want HTML frames or not:

  • index.html (for frames)
  • overview-summary.html (for no frames)
Generated File Structure

The generated class and interface files are organized in the same directory hierarchy that Java source files and class files are organized. This structure is one directory per subpackage.

For example, the document generated for the class java.applet.Applet class would be located at java\applet\Applet.html. The file structure for the java.applet package follows, given that the destination directory is named apidocs. All files that contain the word "frame" appear in the upper-left or lower-left frames, as noted. All other HTML files appear in the right-hand frame.

NOTE: Directories are shown in bold. The asterisks (*) indicate the files and directories that are omitted when the arguments to javadoc are source filenames (*.java) rather than package names. Also when arguments are source filenames, package-list is created but is empty. The doc-files directory will not be created in the destination unless it exists in the source tree.

apidocs                             Top directory
   index.html                       Initial page that sets up HTML frames
 * overview-summary.html            Lists all packages with first sentence summaries
   overview-tree.html               Lists class hierarchy for all packages
   deprecated-list.html             Lists deprecated API for all packages
   constant-values.html             Lists values of static fields for all packages
   serialized-form.html             Lists serialized form for all packages
 * overview-frame.html              Lists all packages, used in upper-left frame
   allclasses-frame.html            Lists all classes for all packages, used in lower-left frame
   help-doc.html                    Lists user help for how these pages are organized
   index-all.html                   Default index created without -splitindex option
   index-files                      Directory created with -splitindex option
       index-<number>.html          Index files created with -splitindex option
   package-list                     Lists package names, used only for resolving external refs
   stylesheet.css                   HTML style sheet for defining fonts, colors and positions
   java                             Package directory
       applet                       Subpackage directory
            Applet.html             Page for Applet class
            AppletContext.html      Page for AppletContext interface
            AppletStub.html         Page for AppletStub interface
            AudioClip.html          Page for AudioClip interface
          * package-summary.html    Lists classes with first sentence summaries for this package
          * package-frame.html      Lists classes in this package, used in lower left-hand frame
          * package-tree.html       Lists class hierarchy for this package
            package-use             Lists where this package is used
            doc-files               Directory holding image and example files
            class-use               Directory holding pages API is used
                Applet.html         Page for uses of Applet class
                AppletContext.html  Page for uses of AppletContext interface
                AppletStub.html     Page for uses of AppletStub interface
                AudioClip.html      Page for uses of AudioClip interface
   src-html                         Source code directory
       java                         Package directory
           applet                   Subpackage directory
                Applet.html         Page for Applet source code
                AppletContext.html  Page for AppletContext source code
                AppletStub.html     Page for AppletStub source code
                AudioClip.html      Page for AudioClip source code

Generated API Declarations

The Javadoc tool generates a declaration at the start of each class, interface, field, constructor, and method description for that API item. For example, the declaration for the Boolean class is:

public final class Boolean
extends Object
implements Serializable

and the declaration for the Boolean.valueOfmethod is:

public static Boolean valueOf(String s)

The Javadoc tool can include the modifiers public, protected, private, abstract, final, static, transient, and volatile, but not synchronized or native. These last two modifiers are considered implementation detail and not part of the API specification.

Rather than relying on the keyword synchronized, APIs should document their concurrency semantics in the comment's main description, as in "a single Enumeration cannot be used by multiple threads concurrently". The document should not describe how to achieve these semantics. As another example, while Hashtable should be thread-safe, there's no reason to specify that we achieve this by synchronizing all of its exported methods. We should reserve the right to synchronize internally at the bucket level, thus offering higher concurrency.

DOCUMENTATION COMMENTS

The original "Documentation Comment Specification" can be found under related documentation.

Commenting the Source Code

You can include documentation comments ("doc comments") in the source code, ahead of declarations for any class, interface, method, constructor, or field. You can also create doc comments for each package and another one for the overview, though their syntax is slightly different. Doc comments are also known informally as "Javadoc comments" (but this term violates its trademark usage). A doc comment consists of the characters between the characters /** that begin the comment and the characters */ that end it. Leading asterisks are allowed on each line and are described further below. The text in a comment can continue onto multiple lines.
/**
 * This is the typical format of a simple documentation comment
 * that spans two lines.
 */
To save space you can put a comment on one line:
/** This comment takes up only one line. */
Placement of comments - Documentation comments are recognized only when placed immediately before class, interface, constructor, method, or field declarations -- see the class example, method example, and field example. Documentation comments placed in the body of a method are ignored. Only one documentation comment per declaration statement is recognized by the Javadoc tool.

A common mistake is to put an import statement between the class comment and the class declaration. Avoid this, as the Javadoc tool will ignore the class comment.

   /**
    * This is the class comment for the class Whatever.
    */

    import com.sun;   // MISTAKE - Important not to put import statement here

    public class Whatever {
    }
A doc comment is composed of a main description followed by a tag section - The main description begins after the starting delimiter /** and continues until the tag section. The tag section starts with the first block tag, which is defined by the first @ character that begins a line (ignoring leading asterisks, white space, and leading separator /**). It is possible to have a comment with only a tag section and no main description. The main description cannot continue after the tag section begins. The argument to a tag can span multiple lines. There can be any number of tags – some types of tags can be repeated while others cannot. For example, this @see starts the tag section:
/**
 * This sentence would hold the main description for this doc comment.
 * @see java.lang.Object
 */
Block tags and in-line tags - A tag is a special keyword within a doc comment that the Javadoc tool can process. There are two kinds of tags: block tags, which appear as @tag (also known as "standalone tags"), and in-line tags, which appear within curly braces, as {@tag}. To be interpreted, a block tag must appear at the beginning of a line, ignoring leading asterisks, white space, and separator (/**). This means you can use the @ character elsewhere in the text and it will not be interpreted as the start of a tag. If you want to start a line with the @ character and not have it be interpreted, use the HTML entity &#064;. Each block tag has associated text, which includes any text following the tag up to, but not including, either the next tag, or the end of the doc comment. This associated text can span multiple lines. An in-line tag is allowed and interpreted anywhere that text is allowed. The following example contains the block tag @deprecated and in-line tag {@link}.
/**
 * @deprecated  As of JDK 1.1, replaced by {@link #setBounds(int,int,int,int)}
 */

Comments are written in HTML - The text must be written in HTML, in that they should use HTML entities and can use HTML tags. You can use whichever version of HTML your browser supports; we have written the standard doclet to generate HTML 3.2-compliant code elsewhere (outside of the documentation comments) with the inclusion of cascading style sheets and frames. (We preface each generated file with "HTML 4.0" because of the frame sets.)

For example, entities for the less-than (<) and greater-than (>) symbols should be written &lt; and &gt;. Likewise, the ampersand (&) should be written &amp;. The bold HTML tag <b> is shown in the following example.

Here is a doc comment:

/**
 * This is a <b>doc</b> comment.
 * @see java.lang.Object
 */

Leading asterisks - When javadoc parses a doc comment, leading asterisk (*) characters on each line are discarded; blanks and tabs preceding the initial asterisk (*) characters are also discarded. Starting with 1.4, if you omit the leading asterisk on a line, the leading white space is no longer removed. This enables you to paste code examples directly into a doc comment inside a <PRE> tag, and its indentation will be honored. Spaces are generally interpreted by browsers more uniformly than tabs. Indentation is relative to the left margin (rather than the separator /** or <PRE> tag).

First sentence - The first sentence of each doc comment should be a summary sentence, containing a concise but complete description of the declared entity. This sentence ends at the first period that is followed by a blank, tab, or line terminator, or at the first block tag. The Javadoc tool copies this first sentence to the member summary at the top of the HTML page.

Declaration with multiple fields - Java allows declaring multiple fields in a single statement, but this statement can have only one documentation comment, which is copied for all fields. Therefore if you want individual documentation comments for each field, you must declare each field in a separate statement. For example, the following documentation comment doesn't make sense written as a single declaration and would be better handled as two declarations:

/**
 * The horizontal and vertical distances of point (x,y)
 */
public int x, y;      // Avoid this
The Javadoc tool generates the following documentation from the above code:
public int x
The horizontal and vertical distances of point (x,y)
public int y
The horizontal and vertical distances of point (x,y)
Use header tags carefully - When writing documentation comments for members, it's best not to use HTML heading tags such as <H1> and <H2>, because the Javadoc tool creates an entire structured document and these structural tags might interfere with the formatting of the generated document. However, it is fine to use these headings in class and package comments to provide your own structure.

Automatic Copying of Method Comments

The Javadoc tool has the ability to copy or "inherit" method comments in classes and interfaces under the following two circumstances. Constructors, fields and nested classes do not inherit doc comments.
  • Automatically inherit comment to fill in missing text - When a main description, or @return, @param or @throws tag is missing from a method comment, the Javadoc tool copies the corresponding main description or tag comment from the method it overrides or implements (if any), according to the algorithm below.

    More specifically, when a @param tag for a particular parameter is missing, then the comment for that parameter is copied from the method further up the inheritance hierarchy. When a @throws tag for a particular exception is missing, the @throws tag is copied only if that exception is declared.

    This behavior contrasts with version 1.3 and earlier, where the presence of any main description or tag would prevent all comments from being inherited.

  • Explicitly inherit comment with {@inheritDoc} tag - Insert the inline tag {@inheritDoc} in a method main description or @return, @param or @throws tag comment – the corresponding inherited main description or tag comment is copied into that spot.

The source file for the inherited method need only be on the path specified by -sourcepath for the doc comment to actually be available to copy. Neither the class nor its package needs to be passed in on the command line. This contrasts with 1.3.x and earlier releases, where the class had to be a documented class

Inherit from classes and interfaces - Inheriting of comments occurs in all three possible cases of inheritance from classes and interfaces:

  • When a method in a class overrides a method in a superclass
  • When a method in an interface overrides a method in a superinterface
  • When a method in a class implements a method in an interface

In the first two cases, for method overrides, the Javadoc tool generates a subheading "Overrides" in the documentation for the overriding method, with a link to the method it is overriding, whether or not the comment is inherited.

In the third case, when a method in a given class implements a method in an interface, the Javadoc tool generates a subheading "Specified by" in the documentation for the overriding method, with a link to the method it is implementing. This happens whether or not the comment is inherited.

Algorithm for Inheriting Method Comments - If a method does not have a doc comment, or has an {@inheritDoc} tag, the Javadoc tool searches for an applicable comment using the following algorithm, which is designed to find the most specific applicable doc comment, giving preference to interfaces over superclasses:

  1. Look in each directly implemented (or extended) interface in the order they appear following the word implements (or extends) in the method declaration. Use the first doc comment found for this method.
  2. If step 1 failed to find a doc comment, recursively apply this entire algorithm to each directly implemented (or extended) interface, in the same order they were examined in step 1.
  3. If step 2 failed to find a doc comment and this is a class other than Object (not an interface):
    1. If the superclass has a doc comment for this method, use it.
    2. If step 3a failed to find a doc comment, recursively apply this entire algorithm to the superclass.

JAVADOC TAGS

The Javadoc tool parses special tags when they are embedded within a Java doc comment. These doc tags enable you to autogenerate a complete, well-formatted API from your source code. The tags start with an "at" sign (@) and are case-sensitive – they must be typed with the uppercase and lowercase letters as shown. A tag must start at the beginning of a line (after any leading spaces and an optional asterisk) or it is treated as normal text. By convention, tags with the same name are grouped together. For example, put all @see tags together.

Tags come in two types:

  • Block tags - Can be placed only in the tag section that follows the main description. Block tags are of the form: @tag.
  • Inline tags - Can be placed anywhere in the main description or in the comments for block tags. Inline tags are denoted by curly braces: {@tag}.
For information about tags we might introduce in future releases, see Proposed Tags.

The current tags are:

Tag | Introduced in JDK/SDK
@author | 1.0
{@code} | 1.5
{@docRoot} | 1.3
@deprecated | 1.0
@exception | 1.0
{@inheritDoc} | 1.4
{@link} | 1.2
{@linkplain} | 1.4
{@literal} | 1.5
@param | 1.0
@return | 1.0
@see | 1.0
@serial | 1.2
@serialData | 1.2
@serialField | 1.2
@since | 1.1
@throws | 1.2
{@value} | 1.4
@version | 1.0

For custom tags, see the -tag option.

@author name-text
Adds an "Author" entry with the specified name-text to the generated docs when the -author option is used. A doc comment may contain multiple @author tags. You can specify one name per @author tag or multiple names per tag. In the former case, the Javadoc tool inserts a comma (,) and space between names. In the latter case, the entire text is simply copied to the generated document without being parsed. Therefore, you can use multiple names per line if you want a localized name separator other than comma.

For more details, see Where Tags Can Be Used and writing @author tags.

@deprecated deprecated-text
Note: Starting with JDK 5.0, you can deprecate a program element using the @Deprecated annotation. Adds a comment indicating that this API should no longer be used (even though it may continue to work). The Javadoc tool moves the deprecated-text ahead of the main description, placing it in italics and preceding it with a bold warning: "Deprecated". This tag is valid in all doc comments: overview, package, class, interface, constructor, method and field.

The first sentence of deprecated-text should at least tell the user when the API was deprecated and what to use as a replacement. The Javadoc tool copies just the first sentence to the summary section and index. Subsequent sentences can also explain why it has been deprecated. You should include a {@link} tag (for Javadoc 1.2 or later) that points to the replacement API:

For more details, see writing @deprecated tags.

  • For Javadoc 1.2 and later, use a {@link} tag. This creates the link in-line, where you want it. For example:
    /**
 * @deprecated  As of JDK 1.1, replaced by {@link #setBounds(int,int,int,int)}
 */
  • For Javadoc 1.1, the standard format is to create a @see tag (which cannot be in-line) for each @deprecated tag.

For more about deprecation, see The @deprecated tag.

{@code text}
Equivalent to <code>{@literal}</code>.

Displays text in code font without interpreting the text as HTML markup or nested javadoc tags. This enables you to use regular angle brackets (< and >) instead of the HTML entities (&lt; and &gt;) in doc comments, such as in parameter types (<Object>), inequalities (3 < 4), or arrows (<-). For example, the doc comment text:

     {@code A<B>C}
displays in the generated HTML page unchanged, as:
     A<B>C
The noteworthy point is that the <B> is not interpreted as bold and is in code font.

If you want the same functionality without the code font, use {@literal}.

{@docRoot}
Represents the relative path to the generated document's (destination) root directory from any generated page. It is useful when you want to include a file, such as a copyright page or company logo, that you want to reference from all generated pages. Linking to the copyright page from the bottom of each page is common.

This {@docRoot} tag can be used both on the command line and in a doc comment: This tag is valid in all doc comments: overview, package, class, interface, constructor, method and field, including the text portion of any tag (such as @return, @param and @deprecated).

  1. On the command line, where the header/footer/bottom are defined:
       javadoc -bottom '<a href="{@docRoot}/copyright.html">Copyright</a>'
    NOTE - When using {@docRoot} this way in a make file, some makefile programs require special escaping for the brace {} characters. For example, the Inprise MAKE version 5.2 running on Windows requires double braces: {{@docRoot}}. It also requires double (rather than single) quotes to enclose arguments to options such as -bottom (with the quotes around the href argument omitted).
  2. In a doc comment:
       /**
    * See the <a href="{@docRoot}/copyright.html">Copyright</a>.
    */
The reason this tag is needed is because the generated docs are in hierarchical directories, as deep as the number of subpackages. This expression:
  <a href="{@docRoot}/copyright.html">
would resolve to:
  <a href="../../copyright.html">      for java/lang/Object.java
and
  <a href="../../../copyright.html">   for java/lang/ref/Reference.java

@exception class-name description
The @exception tag is a synonym for @throws.

{@inheritDoc}
Inherits (copies) documentation from the "nearest" inheritable class or implementable interface into the current doc comment at this tag's location. This allows you to write more general comments higher up the inheritance tree, and to write around the copied text.

This tag is valid only in these places in a doc comment:

  • In the main description block of a method. In this case, the main description is copied from a class or interface up the hierarchy.
  • In the text arguments of the @return, @param and @throws tags of a method. In this case, the tag text is copied from the corresponding tag up the hierarchy.

See Automatic Copying of Method Comments for a more precise description of how comments are found in the inheritance hierarchy. Note that if this tag is missing, the comment is or is not automatically inherited according to rules described in that section.

{@link package.class#member label}
Inserts an in-line link with visible text label that points to the documentation for the specified package, class or member name of a referenced class. This tag is valid in all doc comments: overview, package, class, interface, constructor, method and field, including the text portion of any tag (such as @return, @param and @deprecated).

This tag is very simliar to @see – both require the same references and accept exactly the same syntax for package.class#member and label. The main difference is that {@link} generates an in-line link rather than placing the link in the "See Also" section. Also, the {@link} tag begins and ends with curly braces to separate it from the rest of the in-line text. If you need to use "}" inside the label, use the HTML entity notation &#125;

There is no limit to the number of {@link} tags allowed in a sentence. You can use this tag in the main description part of any documentation comment or in the text portion of any tag (such as @deprecated, @return or @param).

For example, here is a comment that refers to the getComponentAt(int, int) method:

Use the {@link #getComponentAt(int, int) getComponentAt} method.
From this, the standard doclet would generate the following HTML (assuming it refers to another class in the same package):
Use the <a href="Component.html#getComponentAt(int, int)">getComponentAt</a> method.
Which appears on the web page as:
Use the getComponentAt method.
You can extend {@link} to link to classes not being documented by using the -link option.

For more details, see writing {@link} tags.

{@linkplain package.class#member label}
Identical to {@link}, except the link's label is displayed in plain text than code font. Useful when the label is plain text. Example:
     Refer to {@linkplain add() the overridden method}.
This would display as:
          Refer to the overridden method.
{@literal text}
Displays text without interpreting the text as HTML markup or nested javadoc tags. This enables you to use regular angle brackets (< and >) instead of the HTML entities (&lt; and &gt;) in doc comments, such as in parameter types (<Object>), inequalities (3 < 4), or arrows (<-). For example, the doc comment text:
     {@literal A<B>C}
displays unchanged in the generated HTML page in your browser, as:

     A<B>C

The noteworthy point is that the <B> is not interpreted as bold (and it is not in code font).

If you want the same functionality but with the text in code font, use {@code}.

@param parameter-name description
Adds a parameter with the specified parameter-name followed by the specified description to the "Parameters" section. When writing the doc comment, you may continue the description onto multiple lines. This tag is valid only in a doc comment for a method, constructor or class.

The parameter-name can be the name of a parameter in a method or constructor, or the name of a type parameter of a class, method or constructor. Use angle brackets around this parameter name to specify the use of a type parameter.

Example of a type parameter of a class:

     /**
      * @param <E> Type of element stored in a list
      */
     public interface List<E> extends Collection<E> {
     }

Example of a type parameter of a method:

     /**
      * @param string  the string to be converted
      * @param type    the type to convert the string to
      * @param <T>     the type of the element
      * @param <V>     the value of the element
      */
     <T, V extends T> V convert(String string, Class<T> type) {
     }
For more details, see writing @param tags.

@return description
Adds a "Returns" section with the description text. This text should describe the return type and permissible range of values. This tag is valid only in a doc comment for a method.

For more details, see writing @return tags.

@see reference
Adds a "See Also" heading with a link or text entry that points to reference. A doc comment may contain any number of @see tags, which are all grouped under the same heading. The @see tag has three variations; the third form below is the most common. This tag is valid in any doc comment: overview, package, class, interface, constructor, method or field. For inserting an in-line link within a sentence to a package, class or member, see {@link}.
@see "string"
Adds a text entry for string. No link is generated. The string is a book or other reference to information not available by URL. The Javadoc tool distinguishes this from the previous cases by looking for a double-quote (") as the first character. For example:
@see "The Java Programming Language"
This generates text such as:
See Also:
     "The Java Programming Language"
@see <a href="URL#value">label</a>
Adds a link as defined by URL#value. The URL#value is a relative or absolute URL. The Javadoc tool distinguishes this from other cases by looking for a less-than symbol (<) as the first character. For example:
@see <a href="spec.html#section">Java Spec</a>
This generates a link such as:
See Also:
      Java Spec
@see package.class#member label
Adds a link, with visible text label, that points to the documentation for the specified name in the Java Language that is referenced. The label is optional; if omitted, the name appears instead as the visible text, suitably shortened – see How a name is displayed. Use -noqualifier to globally remove the package name from this visible text. Use the label when you want the visible text to be different from the auto-generated visible text.

Only in version 1.2, just the name but not the label would automatically appear in <code> HTML tags, Starting with 1.2.2, the <code> is always included around the visible text, whether or not a label is used.

  • package.class#member is any valid program element name that is referenced – a package, class, interface, constructor, method or field name – except that the character ahead of the member name should be a hash character (#). The class represents any top-level or nested class or interface. The member represents any constructor, method or field (not a nested class or interface). If this name is in the documented classes, the Javadoc tool will automatically create a link to it. To create links to external referenced classes, use the -link option. Use either of the other two @see forms for referring to documentation of a name that does not belong to a referenced class. This argument is described at greater length below under Specifying a Name.
  • label is optional text that is visible as the link's label. The label can contain whitespace. If label is omitted, then package.class.member will appear, suitably shortened relative to the current class and package – see How a name is displayed.
  • A space is the delimiter between package.class#member and label. A space inside parentheses does not indicate the start of a label, so spaces may be used between parameters in a method.

Example - In this example, an @see tag (in the Character class) refers to the equals method in the String class. The tag includes both arguments: the name "String#equals(Object)" and the label "equals".

 /**
  * @see String#equals(Object) equals
  */
The standard doclet produces HTML something like this:
<dl>
<dt><b>See Also:</b>
<dd><a href="../../java/lang/String#equals(java.lang.Object)"><code>equals<code></a>
</dl>
Which looks something like this in a browser, where the label is the visible link text:
See Also:
      equals

Specifying a name - This package.class#member name can be either fully-qualified, such as java.lang.String#toUpperCase() or not, such as String#toUpperCase() or #toUpperCase(). If less than fully-qualified, the Javadoc tool uses the normal Java compiler search order to find it, further described below in Search order for @see. The name can contain whitespace within parentheses, such as between method arguments.

Of course the advantage of providing shorter, "partially-qualified" names is that they are shorter to type and there is less clutter in the source code. The following table shows the different forms of the name, where Class can be a class or interface, Type can be a class, interface, array, or primitive, and method can be a method or constructor.

Typical forms for @see package.class#member
Referencing a member of the current class
@see #field
@see #method(Type, Type,...)
@see #method(Type argname, Type argname,...)
@see #constructor(Type, Type,...)
@see #constructor(Type argname, Type argname,...)

Referencing another class in the current or imported packages
@see Class#field
@see Class#method(Type, Type,...)
@see Class#method(Type argname, Type argname,...)
@see Class#constructor(Type, Type,...)
@see Class#constructor(Type argname, Type argname,...)
@see Class.NestedClass
@see Class

Referencing an element in another package (fully qualified)
@see package.Class#field
@see package.Class#method(Type, Type,...)
@see package.Class#method(Type argname, Type argname,...)
@see package.Class#constructor(Type, Type,...)
@see package.Class#constructor(Type argname, Type argname,...)
@see package.Class.NestedClass
@see package.Class
@see package

The following notes apply to the above table:

  • The first set of forms (with no class or package) will cause the Javadoc tool to search only through the current class's hierarchy. It will find a member of the current class or interface, one of its superclasses or superinterfaces, or one of its enclosing classes or interfaces (search steps 1-3). It will not search the rest of the current package or other packages (search steps 4-5).
  • If any method or constructor is entered as a name with no parentheses, such as getValue, and if there is no field with the same name, the Javadoc tool will correctly create a link to it, but will print a warning message reminding you to add the parentheses and arguments. If this method is overloaded, the Javadoc tool will link to the first method its search encounters, which is unspecified.
  • Nested classes must be specified as outer.inner, not simply inner, for all forms.
  • As stated, the hash character (#), rather than a dot (.) separates a member from its class. This enables the Javadoc tool to resolve ambiguities, since the dot also separates classes, nested classes, packages, and subpackages. However, the Javadoc tool is generally lenient and will properly parse a dot if you know there is no ambiguity, though it will print a warning.

Search order for @see - the Javadoc tool will process a @see tag that appears in a source file (.java), package file (package.html or package-info.java) or overview file (overview.html). In the latter two files, you must fully-qualify the name you supply with @see. In a source file, you can specify a name that is fully-qualified or partially-qualified.

When the Javadoc tool encounters a @see tag in a .java file that is not fully qualified, it searches for the specified name in the same order as the Java compiler would (except the Javadoc tool will not detect certain namespace ambiguities, since it assumes the source code is free of these errors). This search order is formally defined in the Java Language Specification. The Javadoc tool searches for that name through all related and imported classes and packages. In particular, it searches in this order:

  1. the current class or interface
  2. any enclosing classes and interfaces, searching closest first
  3. any superclasses and superinterfaces, searching closest first
  4. the current package
  5. any imported packages, classes and interfaces, searching in the order of the import statement

The Javadoc tool continues to search recursively through steps 1-3 for each class it encounters until it finds a match. That is, after it searches through the current class and its enclosing class E, it will search through E's superclasses before E's enclosing classes. In steps 4 and 5, the Javadoc tool does not search classes or interfaces within a package in any specified order (that order depends on the particular compiler). In step 5, the Javadoc tool looks in java.lang, since that is automatically imported by all programs.

The Javadoc tool does not necessarily look in subclasses, nor will it look in other packages even if their documentation is being generated in the same run. For example, if the @see tag is in the java.awt.event.KeyEvent class and refers to a name in the java.awt package, javadoc does not look in that package unless that class imports it.

How a name is displayed - If label is omitted, then package.class.member appears. In general, it is suitably shortened relative to the current class and package. By "shortened", we mean the Javadoc tool displays only the minimum name necessary. For example, if the String.toUpperCase() method contains references to a member of the same class and to a member of a different class, the class name is displayed only in the latter case, as shown in the following table.

Use -noqualifier to globally remove the package names.

Type of Reference Example in String.toUpperCase() Displays As
@see tag refers to member of the same class, same package @see String#toLowerCase()
 toLowerCase()
(omits the package and class names)
@see tag refers to member of a different class, same package @see Character#toLowerCase(char)
 Character.toLowerCase(char)
(omits the package name, includes the class name)
@see tag refers to member of a different class, different package @see java.io.File#exists()
 java.io.File.exists()
(includes the package and class names)

Examples of @see
The comment to the right shows how the name would be displayed if the @see tag is in a class in another package, such as java.applet.Applet.

                                           See also:
@see java.lang.String                   //  String
@see java.lang.String The String class  //  The String class
@see String                             //  String
@see String#equals(Object)              //  String.equals(Object)
@see String#equals                      //  String.equals(java.lang.Object)
@see java.lang.Object#wait(long)        //  java.lang.Object.wait(long)
@see Character#MAX_RADIX                //  Character.MAX_RADIX
@see <a href="spec.html">Java Spec</a>  //  Java Spec
@see "The Java Programming Language"    //  "The Java Programming Language"
You can extend @see to link to classes not being documented by using the -link option.

For more details, see writing @see tags.

@serial field-description | include | exclude
Used in the doc comment for a default serializable field.

An optional field-description should explain the meaning of the field and list the acceptable values. If needed, the description can span multiple lines. The standard doclet adds this information to the serialized form page.

If a serializable field was added to a class some time after the class was made serializable, a statement should be added to its main description to identify at which version it was added.

The include and exclude arguments identify whether a class or package should be included or excluded from the serialized form page. They work as follows:

  • A public or protected class that implements Serializable is included unless that class (or its package) is marked @serial exclude.
  • A private or package-private class that implements Serializable is excluded unless that class (or its package) is marked @serial include.

Examples: The javax.swing package is marked @serial exclude (in package.html or package-info.java). The public class java.security.BasicPermission is marked @serial exclude. The package-private class java.util.PropertyPermissionCollection is marked @serial include.

The tag @serial at a class level overrides @serial at a package level.

For more information about how to use these tags, along with an example, see "Documenting Serializable Fields and Data for a Class," Section 1.6 of the Java Object Serialization Specification. Also see the Serialization FAQ, which covers common questions, such as "Why do I see javadoc warnings stating that I am missing @serial tags for private fields if I am not running javadoc with the -private switch?". Also see Sun's criteria for including classes in the serialized form specification.

@serialField field-name field-type field-description
Documents an ObjectStreamField component of a Serializable class's serialPersistentFields member. One @serialField tag should be used for each ObjectStreamField component.

@serialData data-description
The data-description documents the types and order of data in the serialized form. Specifically, this data includes the optional data written by the writeObject method and all data (including base classes) written by the Externalizable.writeExternal method.

The @serialData tag can be used in the doc comment for the writeObject, readObject, writeExternal, readExternal, writeReplace, and readResolve methods.

@since since-text
Adds a "Since" heading with the specified since-text to the generated documentation. The text has no special internal structure. This tag is valid in any doc comment: overview, package, class, interface, constructor, method or field. This tag means that this change or feature has existed since the software release specified by the since-text. For example:
    @since 1.5
For source code in the Java platform, this tag indicates the version of the Java platform API specification (not necessarily when it was added to the reference implementation). Multiple @since tags are allowed and are treated like multiple @author tags. You could use multiple tags if the prgram element is used by more than one API.

@throws class-name description
The @throws and @exception tags are synonyms. Adds a "Throws" subheading to the generated documentation, with the class-name and description text. The class-name is the name of the exception that may be thrown by the method. This tag is valid only in the doc comment for a method or constructor. If this class is not fully-specified, the Javadoc tool uses the search order to look up this class. Multiple @throws tags can be used in a given doc comment for the same or different exceptions.

To ensure that all checked exceptions are documented, if a @throws tag does not exist for an exception in the throws clause, the Javadoc tool automatically adds that exception to the HTML output (with no description) as if it were documented with @throws tag.

The @throws documentation is copied from an overridden method to a subclass only when the exception is explicitly declared in the overridden method. The same is true for copying from an interface method to an implementing method. You can use {@inheritDoc} to force @throws to inherit documentation.

For more details, see writing @throws tags.

{@value package.class#field}
When {@value} is used (without any argument) in the doc comment of a static field, it displays the value of that constant:
    /**
     * The value of this constant is {@value}.
     */
    public static final String SCRIPT_START = "<script>"
When used with argument package.class#field in any doc comment, it displays the value of the specified constant:
    /**
     * Evaluates the script starting with {@value #SCRIPT_START}.
     */
    public String evalScript(String script) {
    }
The argument package.class#field takes a form identical to that of the @see argument, except that the member must be a static field.

These values of these constants are also displayed on the Constant Field Values page.

@version version-text
Adds a "Version" subheading with the specified version-text to the generated docs when the -version option is used. This tag is intended to hold the current version number of the software that this code is part of (as opposed to @since, which holds the version number where this code was introduced). The version-text has no special internal structure. To see where the version tag can be used, see Where Tags Can Be Used.

A doc comment may contain multiple @version tags. If it makes sense, you can specify one version number per @version tag or multiple version numbers per tag. In the former case, the Javadoc tool inserts a comma (,) and space between names. In the latter case, the entire text is simply copied to the generated document without being parsed. Therefore, you can use multiple names per line if you want a localized name separator other than comma.

For more details, see writing @version tags.

Where Tags Can Be Used

The following sections describe where the tags can be used. Note that these tags can be used in all doc comments: @see, @since, @deprecated, {@link}, {@linkplain}, and {@docroot}.

Overview Documentation Tags

Overview tags are tags that can appear in the documentation comment for the overview page (which resides in the source file typically named overview.html). Like in any other documentation comments, these tags must appear after the main description.

NOTE - The {@link} tag has a bug in overview documents in version 1.2 – the text appears properly but has no link. The {@docRoot} tag does not currently work in overview documents.

Overview Tags
@see
@since
@author
@version
{@link}
{@linkplain}
{@docRoot}

Package Documentation Tags

Package tags are tags that can appear in the documentation comment for a package (which resides in the source file named package.html or package-info.java). The @serial tag can only be used here with the include or exclude argument.
Package Tags
@see
@since
@serial
@author
@version
{@link}
{@linkplain}
{@docRoot}

Class and Interface Documentation Tags

The following are tags that can appear in the documentation comment for a class or interface. The @serial tag can only be used here with the include or exclude argument.
Class/Interface Tags
@see
@since
@deprecated
@serial
@author
@version
{@link}
{@linkplain}
{@docRoot}
An example of a class comment:
/**
 * A class representing a window on the screen.
 * For example:
 * <pre>
 *    Window win = new Window(parent);
 *    win.show();
 * </pre>
 *
 * @author  Sami Shaio
 * @version 1.15, 13 Dec 2006
 * @see     java.awt.BaseWindow
 * @see     java.awt.Button
 */
class Window extends BaseWindow {
   ...
}

Field Documentation Tags

The following are the tags that can appear in the documentation comment for a field.
Field Tags
@see
@since
@deprecated
@serial
@serialField
{@link}
{@linkplain}
{@docRoot}
{@value}
An example of a field comment:
    /**
     * The X-coordinate of the component.
     *
     * @see #getLocation()
     */
    int x = 1263732;

Constructor and Method Documentation Tags

The following are the tags that can appear in the documentation comment for a constructor or method, except for @return, which cannot appear in a constructor, and {@inheritDoc}, which has certain restrictions. The @serialData tag can only be used in the doc comment for certain serialization methods.
Method/Constructor Tags
@see
@since
@deprecated
@param
@return
@throws and @exception
@serialData
{@link}
{@linkplain}
{@inheritDoc}
{@docRoot}
An example of a method doc comment:
    /**
     * Returns the character at the specified index. An index
     * ranges from <code>0</code> to <code>length() - 1</code>.
     *
     * @param     index  the index of the desired character.
     * @return    the desired character.
     * @exception StringIndexOutOfRangeException
     *              if the index is not in the range <code>0</code>
     *              to <code>length()-1</code>.
     * @see       java.lang.Character#charValue()
     */
    public char charAt(int index) {
       ...
    }

OPTIONS

The javadoc tool uses doclets to determine its output. The Javadoc tool uses the default standard doclet unless a custom doclet is specified with the -doclet option. The Javadoc tool provides a set of command-line options that can be used with any doclet – these options are described below under the sub-heading Javadoc Options. The standard doclet provides an additional set of command-line options that are described below under the sub-heading Options Provided by the Standard Doclet. All option names are case-insensitive, though their arguments can be case-sensitive.

The options are:

-1.1
-author
-bootclasspath
-bottom
-breakiterator
-charset
-classpath
-d
-docencoding
-docfilessubdirs
-doclet
-docletpath
-doctitle
-encoding
-exclude
-excludedocfilessubdir
-extdirs
-footer
-group
 -header
-help
-helpfile
-J
-keywords
-link
-linkoffline
-linksource
-locale
-nocomment
-nodeprecated
-nodeprecatedlist
-nohelp
-noindex
-nonavbar
-noqualifier
-nosince
-notimestamp
-notree
-overview
-package
 -private
-protected
-public
-quiet
-serialwarn
-source
-sourcepath
-sourcetab
-splitindex
-stylesheetfile
-subpackages
-tag
-taglet
-tagletpath
-title
-top
-use
-verbose
-version
-windowtitle
Options shown in italic are the Javadoc core options, which are provided by the front end of the Javadoc tool and are available to all doclets. The standard doclet itself provides the non-italic options.

Javadoc Options

-overview path\filename
Specifies that javadoc should retrieve the text for the overview documentation from the "source" file specified by path/filename and place it on the Overview page (overview-summary.html). The path/filename is relative to the current directory.

While you can use any name you want for filename and place it anywhere you want for path, a typical thing to do is to name it overview.html and place it in the source tree at the directory that contains the topmost package directories. In this location, no path is needed when documenting packages, since -sourcepath will point to this file. For example, if the source tree for the java.lang package is C:\src\classes\java\lang\, then you could place the overview file at C:\src\classes\overview.html. See Real World Example.

For information about the file specified by path/filename, see overview comment file.

Note that the overview page is created only if you pass into javadoc two or more package names. For further explanation, see HTML Frames.)

The title on the overview page is set by -doctitle.

-public
Shows only public classes and members.

-protected
Shows only protected and public classes and members. This is the default.

-package
Shows only package, protected, and public classes and members.

-private
Shows all classes and members.

-help
Displays the online help, which lists these javadoc and doclet command line options.

-doclet class
Specifies the class file that starts the doclet used in generating the documentation. Use the fully-qualified name. This doclet defines the content and formats the output. If the -doclet option is not used, javadoc uses the standard doclet for generating the default HTML format. This class must contain the start(Root) method. The path to this starting class is defined by the -docletpath option.

For example, to call the MIF doclet, use:

    -doclet com.sun.tools.doclets.mif.MIFDoclet

For full, working examples of running a particular doclet, see the MIF Doclet documentation.

-docletpath classpathlist
Specifies the path to the doclet starting class file (specified with the -doclet option) and any jar files it depends on. If the starting class file is in a jar file, then this specifies the path to that jar file, as shown in the example below. You can specify an absolute path or a path relative to the current directory. If classpathlist contains multiple paths or jar files, they should be separated with a colon (:) on Solaris and a semi-colon (;) on Windows. This option is not necessary if the doclet starting class is already in the search path.

Example of path to jar file that contains the starting doclet class file. Notice the jar filename is included.

-docletpath C:\user\mifdoclet\lib\mifdoclet.jar
Example of path to starting doclet class file. Notice the class filename is omitted.
-docletpath C:\user\mifdoclet\classes\com\sun\tools\doclets\mif\
For full, working examples of running a particular doclet, see the MIF Doclet documentation.

-1.1
This feature has been removed from Javadoc 1.4. There is no replacement for it. This option created documentation with the appearance and functionality of documentation generated by Javadoc 1.1 (it never supported nested classes). If you need this option, use Javadoc 1.2 or 1.3 instead.

-source release
Specifies the version of source code accepted. The following values for release are allowed:
Release Value | Notes
1.5 | javadoc accepts code containing generics and other language features introduced in JDK 1.5. The compiler defaults to the 1.5 behavior if the -source flag is not used.
1.4 | javadoc accepts code containing assertions, which were introduced in JDK 1.4.
1.3 | javadoc does not support assertions, generics, or other language features introduced after JDK 1.3.

Use the value of release corresponding to that used when compiling the code with javac.

-sourcepath sourcepathlist
Specifies the search paths for finding source files (.java) when passing package names or -subpackages into the javadoc command. The sourcepathlist can contain multiple paths by separating them with a semicolon (;). The Javadoc tool will search in all subdirectories of the specified paths. Note that this option is not only used to locate the source files being documented, but also to find source files that are not being documented but whose comments are inherited by the source files being documented.

Note that you can use the -sourcepath option only when passing package names into the javadoc command – it will not locate .java files passed into the javadoc command. (To locate .java files, cd to that directory or include the path ahead of each file, as shown at Documenting One or More Classes.) If -sourcepath is omitted, javadoc uses the class path to find the source files (see -classpath). Therefore, the default -sourcepath is the value of class path. If -classpath is omitted and you are passing package names into javadoc, it looks in the current directory (and subdirectories) for the source files.

Set sourcepathlist to the root directory of the source tree for the package you are documenting. For example, suppose you want to document a package called com.mypackage whose source files are located at:

C:\user\src\com\mypackage\*.java
In this case you would specify the sourcepath to C:\user\src, the directory that contains com\mypackage, and then supply the package name com.mypackage:
  C:> javadoc -sourcepath C:\user\src com.mypackage
This is easy to remember by noticing that if you concatenate the value of sourcepath and the package name together and change the dot to a backslash "\", you end up with the full path to the package: C:\user\src\com\mypackage.

To point to two source paths:

  C:> javadoc -sourcepath C:\user1\src;C:\user2\src com.mypackage

-classpath classpathlist
Specifies the paths where javadoc will look for referenced classes (.class files) – these are the documented classes plus any classes referenced by those classes. The classpathlist can contain multiple paths by separating them with a semicolon (;). The Javadoc tool will search in all subdirectories of the specified paths. Follow the instructions in class path documentation for specifying classpathlist.

If -sourcepath is omitted, the Javadoc tool uses -classpath to find the source files as well as class files (for backward compatibility). Therefore, if you want to search for source and class files in separate paths, use both -sourcepath and -classpath.

For example, if you want to document com.mypackage, whose source files reside in the directory C:\user\src\com\mypackage, and if this package relies on a library in C:\user\lib, you would specify:

  C:> javadoc -classpath \user\lib -sourcepath \user\src com.mypackage
As with other tools, if you do not specify -classpath, the Javadoc tool uses the CLASSPATH environment variable, if it is set. If both are not set, the Javadoc tool searches for classes from the current directory.

For an in-depth description of how the Javadoc tool uses -classpath to find user classes as it relates to extension classes and bootstrap classes, see How Classes Are Found.

As a special convenience, a class path element containing a basename of * is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR (a java program cannot tell the difference between the two invocations).

For example, if directory foo contains a.jar and b.JAR, then the class path element foo/* is expanded to a A.jar:b.JAR, except that the order of jar files is unspecified. All jar files in the specified directory, even hidden ones, are included in the list. A classpath entry consisting simply of * expands to a list of all the jar files in the current directory. The CLASSPATH environment variable, where defined, will be similarly expanded. Any classpath wildcard expansion occurs before the Java virtual machine is started – no Java program will ever see unexpanded wildcards except by querying the environment. For example; by invoking System.getenv("CLASSPATH").

-subpackages package1:package2:...
Generates documentation from source files in the specified packages and recursively in their subpackages. This option is useful when adding new subpackages to the source code, as they are automatically included. Each package argument is any top-level subpackage (such as java) or fully qualified package (such as javax.swing) that does not need to contain source files. Arguments are separated by colons (on all operating systmes). Wildcards are not needed or allowed. Use -sourcepath to specify where to find the packages. This option is smart about not processing source files that are in the source tree but do not belong to the packages, as described at processing of source files.

For example:

  C:> javadoc -d docs -sourcepath C:\user\src -subpackages java:javax.swing
This command generates documentation for packages named "java" and "javax.swing" and all their subpackages.

You can use -subpackages in conjunction with -exclude to exclude specific packages.

-exclude packagename1:packagename2:...
Unconditionally excludes the specified packages and their subpackages from the list formed by -subpackages. It excludes those packages even if they would otherwise be included by some previous or later -subpackages option. For example:
  C:> javadoc -sourcepath C:\user\src -subpackages java -exclude java.net:java.lang
would include java.io, java.util, and java.math (among others), but would exclude packages rooted at java.net and java.lang. Notice this excludes java.lang.ref, a subpackage of java.lang).

-bootclasspath classpathlist
Specifies the paths where the boot classes reside. These are nominally the Java platform classes. The bootclasspath is part of the search path the Javadoc tool will use to look up source and class files. See How Classes Are Found. for more details. Separate directories in classpathlist with semicolons (;).

-extdirs dirlist
Specifies the directories where extension classes reside. These are any classes that use the Java Extension mechanism. The extdirs is part of the search path the Javadoc tool will use to look up source and class files. See -classpath (above) for more details. Separate directories in dirlist with semicolons (;).

-verbose
Provides more detailed messages while javadoc is running. Without the verbose option, messages appear for loading the source files, generating the documentation (one message per source file), and sorting. The verbose option causes the printing of additional messages specifying the number of milliseconds to parse each java source file.

-quiet
Shuts off non-error and non-warning messages, leaving only the warnings and errors appear, making them easier to view. Also suppresses the version string.

-breakiterator
Uses the internationalized sentence boundary of java.text.BreakIterator to determine the end of the first sentence for English (all other locales already use BreakIterator), rather than an English language, locale-specific algorithm. By first sentence, we mean the first sentence in the main description of a package, class or member. This sentence is copied to the package, class or member summary, and to the alphabetic index.

From JDK 1.2 forward, the BreakIterator class is already used to determine the end of sentence for all languages but English. Therefore, the -breakiterator option has no effect except for English from 1.2 forward. English has its own default algorithm:

  • English default sentence-break algorithm - Stops at a period followed by a space or a HTML block tag, such as <P>.
  • Breakiterator sentence-break algorithm - In general, stops at a period, question mark or exclamation mark followed by a space if the next word starts with a capital letter. This is meant to handle most abbreviations (such as "The serial no. is valid", but won't handle "Mr. Smith"). Doesn't stop at HTML tags or sentences that begin with numbers or symbols. Stops at the last period in "../filename", even if embedded in an HTML tag.
NOTE: We removed the breakiterator warning messages from 1.5.0 that were in 1.4.x and left the default sentence-break algorithm unchanged. That is, the -breakiterator option is not the default in 1.5.0, nor do we expect it to become the default. This is a reversal from our former intention that the default would change in the "next major release" (1.5.0). This means if you have not modified your source code to eliminate the breakiterator warnings in 1.4.x, then you don't have to do anything, and the warnings go away starting with 1.5.0. The reason for this reversal is because any benefit to having breakiterator become the default would be outweighed by the incompatible source change it would require. We regret any extra work and confusion this has caused.
-locale language_country_variant
Important - The -locale option must be placed ahead (to the left) of any options provided by the standard doclet or any other doclet. Otherwise, the navigation bars will appear in English. This is the only command-line option that is order-dependent.

Specifies the locale that javadoc uses when generating documentation. The argument is the name of the locale, as described in java.util.Locale documentation, such as en_US (English, United States) or en_US_WIN (Windows variant).

Specifying a locale causes javadoc to choose the resource files of that locale for messages (strings in the navigation bar, headings for lists and tables, help file contents, comments in stylesheet.css, and so forth). It also specifies the sorting order for lists sorted alphabetically, and the sentence separator to determine the end of the first sentence. It does not determine the locale of the doc comment text specified in the source files of the documented classes.

-encoding name
Specifies the encoding name of the source files, such as EUCJIS/SJIS. If this option is not specified, the platform default converter is used.

Also see -docencoding and -charset.

-J flag
Passes flag directly to the runtime system java that runs javadoc. Notice there must be no space between the J and the flag. For example, if you need to ensure that the system sets aside 32 megabytes of memory in which to process the generated documentation, then you would call the -Xmx option of java as follows (-Xms is optional, as it only sets the size of initial memory, which is useful if you know the minimum amount of memory required):
   C:> javadoc -J-Xmx32m -J-Xms32m com.mypackage
To tell what version of javadoc you are using, call the "-version" option of java:
   C:> javadoc -J-version
   java version "1.2"
   Classic VM (build JDK-1.2-V, green threads, sunwjit)
(The version number of the standard doclet appears in its output stream.)

Options Provided by the Standard Doclet

-d directory
Specifies the destination directory where javadoc saves the generated HTML files. (The "d" means "destination.") Omitting this option causes the files to be saved to the current directory. The value directory can be absolute, or relative to the current working directory. As of 1.4, the destination directory is automatically created when javadoc is run.

For example, the following generates the documentation for the package com.mypackage and saves the results in the C:\user\doc\ directory:

  C:> javadoc -d \user\doc com.mypackage

-use
Includes one "Use" page for each documented class and package. The page describes what packages, classes, methods, constructors and fields use any API of the given class or package. Given class C, things that use class C would include subclasses of C, fields declared as C, methods that return C, and methods and constructors with parameters of type C.

For example, let's look at what might appear on the "Use" page for String. The getName() method in the java.awt.Font class returns type String. Therefore, getName() uses String, and you will find that method on the "Use" page for String.

Note that this documents only uses of the API, not the implementation. If a method uses String in its implementation but does not take a string as an argument or return a string, that is not considered a "use" of String.

You can access the generated "Use" page by first going to the class or package, then clicking on the "Use" link in the navigation bar.

-version
Includes the @version text in the generated docs. This text is omitted by default. To tell what version of the Javadoc tool you are using, use the -J-version option.

-author
Includes the @author text in the generated docs.

-splitindex
Splits the index file into multiple files, alphabetically, one file per letter, plus a file for any index entries that start with non-alphabetical characters.

-windowtitle title
Specifies the title to be placed in the HTML <title> tag. This appears in the window title and in any browser bookmarks (favorite places) that someone creates for this page. This title should not contain any HTML tags, as the browser will not properly interpret them. Any internal quotation marks within title may have to be escaped. If -windowtitle is omitted, the Javadoc tool uses the value of -doctitle for this option.
  C:> javadoc -windowtitle "Java SE Platform" com.mypackage
-doctitle title
Specifies the title to be placed near the top of the overview summary file. The title will be placed as a centered, level-one heading directly beneath the upper navigation bar. The title may contain html tags and white space, though if it does, it must be enclosed in quotes. Any internal quotation marks within title may have to be escaped.
  C:> javadoc -doctitle "Java™" com.mypackage
-title title
This option no longer exists. It existed only in Beta versions of Javadoc 1.2. It has been renamed to -doctitle. This option is being renamed to make it clear that it defines the document title rather than the window title.

-header header
Specifies the header text to be placed at the top of each output file. The header will be placed to the right of the upper navigation bar. header may contain HTML tags and white space, though if it does, it must be enclosed in quotes. Any internal quotation marks within header may have to be escaped.
  C:> javadoc -header "<b>Java 2 Platform </b><br>v1.4" com.mypackage

-footer footer
Specifies the footer text to be placed at the bottom of each output file. The footer will be placed to the right of the lower navigation bar. footer may contain html tags and white space, though if it does, it must be enclosed in quotes. Any internal quotation marks within footer may have to be escaped.

-top
Specifies the text to be placed at the top of each output file.

-bottom text
Specifies the text to be placed at the bottom of each output file. The text will be placed at the bottom of the page, below the lower navigation bar. The text may contain HTML tags and white space, though if it does, it must be enclosed in quotes. Any internal quotation marks within text may have to be escaped.

-link extdocURL
Creates links to existing javadoc-generated documentation of external referenced classes. It takes one argument:

  • extdocURL is the absolute or relative URL of the directory containing the external javadoc-generated documentation you want to link to. Examples are shown below. The package-list file must be found in this directory (otherwise, use -linkoffline). The Javadoc tool reads the package names from the package-list file and then links to those packages at that URL. When the Javadoc tool is run, the extdocURL value is copied literally into the <A HREF> links that are created. Therefore, extdocURL must be the URL to the directory, not to a file.

    You can use an absolute link for extdocURL to enable your docs to link to a document on any website, or can use a relative link to link only to a relative location. If relative, the value you pass in should be the relative path from the destination directory (specified with -d) to the directory containing the packages being linked to.

    When specifying an absolute link you normally use an http: link. However, if you want to link to a file system that has no web server, you can use a file: link – however, do this only if everyone wanting to access the generated documentation shares the same file system.

    In all cases, and on all operating systems, you should use a forward slash as the separator, whether the URL is absolute or relative, and "http:" or "file:" based (as specified in the URL Memo).

    Absolute http: based link:
    -link http://<host>/<directory>/<directory>/.../<name>
    Absolute file: based link:
    -link file://<host>/<directory>/<directory>/.../<name>
    Relative link:
    -link <directory>/<directory>/.../<name>

You can specify multiple -link options in a given javadoc run to link to multiple documents.

Choosing between -linkoffline and -link:
Use -link:
  • when using a relative path to the external API document, or
  • when using an absolute URL to the external API document, if your shell allows a program to open a connection to that URL for reading.
Use -linkoffline:
  • when using an absolute URL to the external API document, if your shell does not allow a program to open a connection to that URL for reading. This can occur if you are behind a firewall and the document you want to link to is on the other side.

Example using absolute links to the external docs - Let us say you want to link to the java.lang, java.io and other Java SE Platform packages at http://download.oracle.com/javase/7/docs/api/, The following command generates documentation for the package com.mypackage with links to the Java SE Platform packages. The generated documentation will contain links to the Object class, for example, in the class trees. (Other options, such as -sourcepath and -d, are not shown.)

  C:> javadoc -link http://download.oracle.com/javase/7/docs/api/ com.mypackage
Example using relative links to the external docs - Let's say you have two packages whose docs are generated in different runs of the Javadoc tool, and those docs are separated by a relative path. In this example, the packages are com.apipackage, an API, and com.spipackage, an SPI (Service Provide Interface). You want the documentation to reside in docs/api/com/apipackage and docs/spi/com/spipackage. Assuming the API package documentation is already generated, and that docs is the current directory, you would document the SPI package with links to the API documentation by running:
  C:> javadoc -d ./spi -link ../api com.spipackage

Notice the -link argument is relative to the destination directory (docs/spi).

Details - The -link option enables you to link to classes referenced to by your code but not documented in the current javadoc run. For these links to go to valid pages, you must know where those HTML pages are located, and specify that location with extdocURL. This allows, for instance, third party documentation to link to java.* documentation on http://java.sun.com.

Omit the -link option for javadoc to create links only to API within the documentation it is generating in the current run. (Without the -link option, the Javadoc tool does not create links to documentation for external references, because it does not know if or where that documentation exists.)

This option can create links in several places in the generated documentation.

Another use is for cross-links between sets of packages: Execute javadoc on one set of packages, then run javadoc again on another set of packages, creating links both ways between both sets.

How a Class Must be Referenced - For a link to an external referenced class to actually appear (and not just its text label), the class must be referenced in the following way. It is not sufficient for it to be referenced in the body of a method. It must be referenced in either an import statement or in a declaration. Here are examples of how the class java.io.File can be referenced:

  • In any kind of import statement: by wildcard import, import explicitly by name, or automatically import for java.lang.*. For example, this would suffice:
    import java.io.*;
    In 1.3.x and 1.2.x, only an explicit import by name works – a wildcard import statement does not work, nor does the automatic import java.lang.*.
  • In a declaration:
    void foo(File f) {}
    The reference and be in the return type or parameter type of a method, constructor, field, class or interface, or in an implements, extends or throws statement.

An important corollary is that when you use the -link option, there may be many links that unintentionally do not appear due to this constraint. (The text would appear without a hypertext link.) You can detect these by the warnings they emit. The most innocuous way to properly reference a class and thereby add the link would be to import that class, as shown above.

Package List - The -link option requires that a file named package-list, which is generated by the Javadoc tool, exist at the URL you specify with -link. The package-list file is a simple text file that lists the names of packages documented at that location. In the earlier example, the Javadoc tool looks for a file named package-list at the given URL, reads in the package names and then links to those packages at that URL.

For example, the package list for the Java SE API is located at http://download.oracle.com/javase/7/docs/api/package-list and starts as follows:

  java.applet
  java.awt
  java.awt.color
  java.awt.datatransfer
  java.awt.dnd
  java.awt.event
  java.awt.font
  etc.

When javadoc is run without the -link option, when it encounters a name that belongs to an external referenced class, it prints the name with no link. However, when the -link option is used, the Javadoc tool searches the package-list file at the specified extdocURL location for that package name. If it finds the package name, it prefixes the name with extdocURL.

In order for there to be no broken links, all of the documentation for the external references must exist at the specified URLs. The Javadoc tool will not check that these pages exist – only that the package-list exists.

Multiple Links - You can supply multiple -link options to link to any number of external generated documents. Javadoc 1.2 has a known bug which prevents you from supplying more than one -link command. This was fixed in 1.2.2.

Specify a different link option for each external document to link to:

C:> javadoc -link extdocURL1 -link extdocURL2 ... -link extdocURLn com.mypackage

where extdocURL1, extdocURL2, ... extdocURLn point respectively to the roots of external documents, each of which contains a file named package-list.

Cross-links - Note that "bootstrapping" may be required when cross-linking two or more documents that have not previously been generated. In other words, if package-list does not exist for either document, when you run the Javadoc tool on the first document, the package-list will not yet exist for the second document. Therefore, to create the external links, you must re-generate the first document after generating the second document.

In this case, the purpose of first generating a document is to create its package-list (or you can create it by hand it if you're certain of the package names). Then generate the second document with its external links. The Javadoc tool prints a warning if a needed external package-list file does not exist.

-linkoffline extdocURL packagelistLoc
This option is a variation of -link; they both create links to javadoc-generated documentation for external referenced classes. Use the -linkoffline option when linking to a document on the web when the Javadoc tool itself is "offline" – that is, it cannot access the document through a web connection.

More specifically, use -linkoffline if the external document's package-list file is not accessible or does not exist at the extdocURL location but does exist at a different location, which can be specified by packageListLoc (typically local). Thus, if extdocURL is accessible only on the World Wide Web, -linkoffline removes the constraint that the Javadoc tool have a web connection when generating the documentation.

Another use is as a "hack" to update docs: After you have run javadoc on a full set of packages, then you can run javadoc again on onlya smaller set of changed packages, so that the updated files can be inserted back into the original set. Examples are given below.

The -linkoffline option takes two arguments – the first for the string to be embedded in the <a href> links, the second telling it where to find package-list:

  • extdocURL is the absolute or relative URL of the directory containing the external javadoc-generated documentation you want to link to. If relative, the value should be the relative path from the destination directory (specified with -d) to the root of the packages being linked to. For more details, see extdocURL in the -link option.
  • packagelistLoc is the path or URL to the directory containing the package-list file for the external documentation. This can be a URL (http: or file:) or file path, and can be absolute or relative. If relative, make it relative to the current directory from where javadoc was run. Do not include the package-list filename.

You can specify multiple -linkoffline options in a given javadoc run. (Prior to 1.2.2, it could be specified only once.)

Example using absolute links to the external docs - Let us say you want to link to the java.lang, java.io and other Java SE Platform packages at http://download.oracle.com/javase/7/docs/api/, but your shell does not have web access. You could open the package-list file in a browser at http://download.oracle.com/javase/7/docs/api/package-list, save it to a local directory, and point to this local copy with the second argument, packagelistLoc. In this example, the package list file has been saved to the current directory "." . The following command generates documentation for the package com.mypackage with links to the Java SE Platform packages. The generated documentation will contain links to the Object class, for example, in the class trees. (Other necessary options, such as -sourcepath, are not shown.)

C:> javadoc -linkoffline http://download.oracle.com/javase/7/docs/api/ . com.mypackage

Example using relative links to the external docs - It's not very common to use -linkoffline with relative paths, for the simple reason that -link usually suffices. When using -linkoffline, the package-list file is generally local, and when using relative links, the file you are linking to is also generally local. So it is usually unnecessary to give a different path for the two arguments to -linkoffline. When the two arguments are identical, you can use -link. See the -link relative example.

Manually Creating a package-list File - If a package-list file does not yet exist, but you know what package names your document will link to, you can create your own copy of this file by hand and specify its path with packagelistLoc. An example would be the previous case where the package list for com.spipackage did not exist when com.apipackage was first generated. This technique is useful when you need to generate documentation that links to new external documentation whose package names you know, but which is not yet published. This is also a way of creating package-list files for packages generated with Javadoc 1.0 or 1.1, where package-list files were not generated. Likewise, two companies can share their unpublished package-list files, enabling them to release their cross-linked documentation simultaneously.

Linking to Multiple Documents - You can include -linkoffline once for each generated document you want to refer to (each option is shown on a separate line for clarity):

C:> javadoc -linkoffline extdocURL1 packagelistLoc1 \
          -linkoffline extdocURL2 packagelistLoc2 \
          ...

Updating docs - Another use for -linkoffline option is useful if your project has dozens or hundreds of packages, if you have already run javadoc on the entire tree, and now, in a separate run, you want to quickly make some small changes and re-run javadoc on just a small portion of the source tree. This is somewhat of a hack in that it works properly only if your changes are only to doc comments and not to declarations. If you were to add, remove or change any declarations from the source code, then broken links could show up in the index, package tree, inherited member lists, use page, and other places.

First, you create a new destination directory (call it update) for this new small run. Let's say the original destination directory was named html. In the simplest example, cd to the parent of html. Set the first argument of -linkoffline to the current directory "." and set the second argument to the relative path to html, where it can find package-list, and pass in only the package names of the packages you want to update:

  C:> javadoc -d update -linkoffline . html com.mypackage
When the Javadoc tool is done, copy these generated class pages in update\com\package (not the overview or index), over the original files in html\com\package.

-linksource
Creates an HTML version of each source file (with line numbers) and adds links to them from the standard HTML documentation. Links are created for classes, interfaces, constructors, methods and fields whose declarations are in a source file. Otherwise, links are not created, such as for default constructors and generated classes.

This option exposes all private implementation details in the included source files, including private classes, private fields, and the bodies of private methods, regardless of the -public, -package, -protected and -private options. Unless you also use the -private option, not all private classes or interfaces will necessarily be accessible via links.

Each link appears on the name of the identifier in its declaration. For example, the link to the source code of the Button class would be on the word "Button":

    public class Button
    extends Component
    implements Accessible
and the link to the source code of the getLabel() method in the Button class would be on the word "getLabel":
    public String getLabel()

-group groupheading packagepattern:packagepattern:...
Separates packages on the overview page into whatever groups you specify, one group per table. You specify each group with a different -group option. The groups appear on the page in the order specified on the command line; packages are alphabetized within a group. For a given -group option, the packages matching the list of packagepattern expressions appear in a table with the heading groupheading.
  • groupheading can be any text, and can include white space. This text is placed in the table heading for the group.
  • packagepattern can be any package name, or can be the start of any package name followed by an asterisk (*). The asterisk is a wildcard meaning "match any characters". This is the only wildcard allowed. Multiple patterns can be included in a group by separating them with colons (:).
NOTE: If using an asterisk in a pattern or pattern list, the pattern list must be inside quotes, such as "java.lang*:java.util"

If you do not supply any -group option, all packages are placed in one group with the heading "Packages". If the all groups do not include all documented packages, any leftover packages appear in a separate group with the heading "Other Packages".

For example, the following option separates the four documented packages into core, extension and other packages. Notice the trailing "dot" does not appear in "java.lang*" – including the dot, such as "java.lang.*" would omit the java.lang package.

  C:> javadoc -group "Core Packages" "java.lang*:java.util"
            -group "Extension Packages" "javax.*"
            java.lang java.lang.reflect java.util javax.servlet java.new

This results in the groupings:

Core Packages
java.lang
java.lang.reflect
java.util
Extension Packages
javax.servlet
Other Packages
java.new

-nodeprecated
Prevents the generation of any deprecated API at all in the documentation. This does what -nodeprecatedlist does, plus it does not generate any deprecated API throughout the rest of the documentation. This is useful when writing code and you don't want to be distracted by the deprecated code.

-nodeprecatedlist
Prevents the generation of the file containing the list of deprecated APIs (deprecated-list.html) and the link in the navigation bar to that page. (However, javadoc continues to generate the deprecated API throughout the rest of the document.) This is useful if your source code contains no deprecated API, and you want to make the navigation bar cleaner.

-nosince
Omits from the generated docs the "Since" sections associated with the @since tags.

-notree
Omits the class/interface hierarchy pages from the generated docs. These are the pages you reach using the "Tree" button in the navigation bar. The hierarchy is produced by default.

-noindex
Omits the index from the generated docs. The index is produced by default.

-nohelp
Omits the HELP link in the navigation bars at the top and bottom of each page of output.

-nonavbar
Prevents the generation of the navigation bar, header and footer, otherwise found at the top and bottom of the generated pages. Has no affect on the "bottom" option. The -nonavbar option is useful when you are interested only in the content and have no need for navigation, such as converting the files to PostScript or PDF for print only.

-helpfile path\filename
Specifies the path of an alternate help file path\filename that the HELP link in the top and bottom navigation bars link to. Without this option, the Javadoc tool automatically creates a help file help-doc.html that is hard-coded in the Javadoc tool. This option enables you to override this default. The filename can be any name and is not restricted to help-doc.html – the Javadoc tool will adjust the links in the navigation bar accordingly. For example:
  C:> javadoc -helpfile C:\user\myhelp.html java.awt
-stylesheetfile path\filename
Specifies the path of an alternate HTML stylesheet file. Without this option, the Javadoc tool automatically creates a stylesheet file stylesheet.css that is hard-coded in the Javadoc tool. This option enables you to override this default. The filename can be any name and is not restricted to stylesheet.css. For example:
  C:> javadoc -stylesheetfile C:\user\mystylesheet.css com.mypackage
-serialwarn
Generates compile-time warnings for missing @serial tags. By default, Javadoc 1.2.2 (and later versions) generates no serial warnings. (This is a reversal from earlier versions.) Use this option to display the serial warnings, which helps to properly document default serializable fields and writeExternal methods.

-charset name
Specifies the HTML character set for this document. The name should be a preferred MIME name as given in the IANA Registry. For example:
  C:> javadoc -charset "iso-8859-1" mypackage
would insert the following line in the head of every generated page:
   <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
This META tag is described in the HTML standard. (4197265 and 4137321)

Also see -encoding and -docencoding.

-docencoding name
Specifies the encoding of the generated HTML files. The name should be a preferred MIME name as given in the IANA Registry. If you omit this option but use -encoding, then the encoding of the generated HTML files is determined by -encoding. Example:
  % javadoc -docencoding "ISO-8859-1" mypackage
Also see -encoding and -charset.

-keywords
Adds HTML meta keyword tags to the generated file for each class. These tags can help the page be found by search engines that look for meta tags. (Most search engines that search the entire Internet do not look at meta tags, because pages can misuse them; but search engines offered by companies that confine their search to their own website can benefit by looking at meta tags.)

The meta tags include the fully qualified name of the class and the unqualified names of the fields and methods. Constructors are not included because they are identical to the class name. For example, the class String starts with these keywords:

     <META NAME="keywords" CONTENT="java.lang.String class">
     <META NAME="keywords" CONTENT="CASE_INSENSITIVE_ORDER">
     <META NAME="keywords" CONTENT="length()">
     <META NAME="keywords" CONTENT="charAt()">

-tag tagname:Xaoptcmf:"taghead"
Enables the Javadoc tool to interpret a simple, one-argument custom block tag @tagname in doc comments. So the Javadoc tool can "spell-check" tag names, it is important to include a -tag option for every custom tag that is present in the source code, disabling (with X) those that are not being output in the current run.

The colon (:) is always the separator. To use a colon in tagname, see Use of Colon in Tag Name.

The -tag option outputs the tag's heading taghead in bold, followed on the next line by the text from its single argument, as shown in the example below. Like any block tag, this argument's text can contain inline tags, which are also interpreted. The output is similar to standard one-argument tags, such as @return and @author. Omitting taghead causes tagname to appear as the heading.

Placement of tags - The Xaoptcmf part of the argument determines where in the source code the tag is allowed to be placed, and whether the tag can be disabled (using X). You can supply either a, to allow the tag in all places, or any combination of the other letters:

X (disable tag)
a (all)
o (overview)
p (packages)
t (types, that is classes and interfaces)
c (constructors)
m (methods)
f (fields)

Examples of single tags - An example of a tag option for a tag that can be used anywhere in the source code is:

-tag todo:a:"To Do:"
If you wanted @todo to be used only with constructors, methods and fields, you would use:
-tag todo:cmf:"To Do:"
Notice the last colon (:) above is not a parameter separator, but is part of the heading text (as shown below). You would use either tag option for source code that contains the tag @todo, such as:
@todo The documentation for this method needs work.
This line would produce output something like:
To Do:
      The documentation for this method needs work.
Use of Colon in Tag Name - A colon can be used in a tag name if it is escaped with a backslash. For this doc comment:
    /**
     * @ejb:bean
     */
use this tag option:
    -tag ejb\:bean:a:"EJB Bean:"
Spell-checking tag names (Disabling tags) - Some developers put custom tags in the source code that they don't always want to output. In these cases, it is important to list all tags that are present in the source code, enabling the ones you want to output and disabling the ones you don't want to output. The presence of X disables the tag, while its absence enables the tag. This gives the Javadoc tool enough information to know if a tag it encounters is unknown, probably the results of a typo or a misspelling. It prints a warning in these cases.

You can add X to the placement values already present, so that when you want to enable the tag, you can simply delete the X. For example, if @todo is a tag that you want to suppress on output, you would use:

    -tag todo:Xcmf:"To Do:"
or, if you'd rather keep it simple:
    -tag todo:X

The syntax -tag todo:X works even if @todo is defined by a taglet.

Order of tags - The order of the -tag (and -taglet) options determine the order the tags are output. You can mix the custom tags with the standard tags to intersperse them. The tag options for standard tags are placeholders only for determining the order – they take only the standard tag's name. (Subheadings for standard tags cannot be altered.) This is illustrated in the following example.

If -tag is missing, then the position of -taglet determines its order. If they are both present, then whichever appears last on the command line determines its order. (This happens because the tags and taglets are processed in the order that they appear on the command line. For example, if -taglet and -tag both have the name "todo", the one that appears last on the command line will determine its order.

Example of a complete set of tags - This example inserts "To Do" after "Parameters" and before "Throws" in the output. By using "X", it also specifies that @example is a tag that might be encountered in the source code that should not be output during this run. Notice that if you use @argfile, you can put the tags on separate lines in an argument file like this (no line continuation characters needed):

   -tag param
   -tag return
   -tag todo:a:"To Do:"
   -tag throws
   -tag see
   -tag example:X

When javadoc parses the doc comments, any tag encountered that is neither a standard tag nor passed in with -tag or -taglet is considered unknown, and a warning is thrown.

The standard tags are initially stored internally in a list in their default order. Whenever -tag options are used, those tags get appended to this list – standard tags are moved from their default position. Therefore, if a -tag option is omitted for a standard tag, it remains in its default position.

Avoiding Conflicts - If you want to slice out your own namespace, you can use a dot-separated naming convention similar to that used for packages: com.mycompany.todo. Sun will continue to create standard tags whose names do not contain dots. Any tag you create will override the behavior of a tag by the same name defined by Sun. In other words, if you create a tag or taglet @todo, it will always have the same behavior you define, even if Sun later creates a standard tag of the same name.

Annotations vs. Javadoc Tags - In general, if the markup you want to add is intended to affect or produce documentation, it should probably be a javadoc tag; otherwise, it should be an annotation. See Comparing Annotations and Javadoc Tags

You can also create more complex block tags, or custom inline tags with the -taglet option.

-taglet class
Specifies the class file that starts the taglet used in generating the documentation for that tag. Use the fully-qualified name for class. This taglet also defines the number of text arguments that the custom tag has. The taglet accepts those arguments, processes them, and generates the output. For extensive documentation with example taglets, see:
  • Taglet Overview

Taglets are useful for block or inline tags. They can have any number of arguments and implement custom behavior, such as making text bold, formatting bullets, writing out the text to a file, or starting other processes.

Taglets can only determine where a tag should appear and in what form. All other decisions are made by the doclet. So a taglet cannot do things such as remove a class name from the list of included classes. However, it can execute side effects, such as printing the tag's text to a file or triggering another process.

Use the -tagletpath option to specify the path to the taglet. Here is an example that inserts the "To Do" taglet after "Parameters" and ahead of "Throws" in the generated pages:

    -taglet com.sun.tools.doclets.ToDoTaglet
    -tagletpath /home/taglets
    -tag return
    -tag param
    -tag todo
    -tag throws
    -tag see

Alternatively, you can use the -taglet option in place of its -tag option, but that may be harder to read.

-tagletpath tagletpathlist
Specifies the search paths for finding taglet class files (.class). The tagletpathlist can contain multiple paths by separating them with a colon (:). The Javadoc tool will search in all subdirectories of the specified paths.

-docfilessubdirs
Enables deep copying of "doc-files" directories. In other words, subdirectories and all contents are recursively copied to the destination. For example, the directory doc-files/example/images and all its contents would now be copied. There is also an option to exclude subdirectories.

-excludedocfilessubdir name1:name2...
Excludes any "doc-files" subdirectories with the given names. This prevents the copying of SCCS and other source-code-control subdirectories.

-noqualifier all | packagename1:packagename2:...
Omits qualifying package name from ahead of class names in output. The argument to -noqualifier is either "all" (all package qualifiers are omitted) or a colon-separate list of packages, with wildcards, to be removed as qualifiers. The package name is removed from places where class or interface names appear.

The following example omits all package qualifiers:

    -noqualifier all
The following example omits "java.lang" and "java.io" package qualifiers:
    -noqualifier java.lang:java.io
The following example omits package qualifiers starting with "java", and "com.sun" subpackages (but not "javax"):
    -noqualifier java.*:com.sun.*
Where a package qualifier would appear due to the above behavior, the name can be suitably shortened – see How a name is displayed. This rule is in effect whether or not -noqualifier is used.

-notimestamp
Suppresses the timestamp, which is hidden in an HTML comment in the generated HTML near the top of each page. Useful when you want to run javadoc on two source bases and diff them, as it prevents timestamps from causing a diff (which would otherwise be a diff on every page). The timestamp includes the javadoc version number, and currently looks like this:
     <!-- Generated by javadoc (build 1.5.0_01) on Thu Apr 02 14:04:52 IST 2009 -->

-nocomment
Suppress the entire comment body, including the main description and all tags, generating only declarations. This option enables re-using source files originally intended for a different purpose, to produce skeleton HTML documentation at the early stages of a new project.

-sourcetab tabLength
Specify the number of spaces each tab takes up in the source.

COMMAND LINE ARGUMENT FILES

To shorten or simplify the javadoc command line, you can specify one or more files that themselves contain arguments to the javadoc command (except -J options). This enables you to create javadoc commands of any length on any operating system.

An argument file can include javadoc options and source filenames in any combination. The arguments within a file can be space-separated or newline-separated. If a filename contains embedded spaces, put the whole filename in double quotes, and double each backslash ("My Files\\Stuff.java").

Filenames within an argument file are relative to the current directory, not the location of the argument file. Wildcards (*) are not allowed in these lists (such as for specifying *.java). Use of the '@' character to recursively interpret files is not supported. The -J options are not supported because they are passed to the launcher, which does not support argument files.

When executing javadoc, pass in the path and name of each argument file with the '@' leading character. When javadoc encounters an argument beginning with the character `@', it expands the contents of that file into the argument list.

Example - Single Arg File

You could use a single argument file named "argfile" to hold all Javadoc arguments:
  C:> javadoc @argfile
This argument file could contain the contents of both files shown in the next example.

Example - Two Arg Files

You can create two argument files – one for the Javadoc options and the other for the package names or source filenames: (Notice the following lists have no line-continuation characters.)

Create a file named "options" containing:

     -d docs-filelist
     -use
     -splitindex
     -windowtitle 'Java SE 7 API Specification'
     -doctitle 'Java SE 7 API Specification'
     -header '<b>Java™ SE 7</b>'
     -bottom 'Copyright &copy; 1993-2011 Oracle and/or its affiliates. All rights reserved.'
     -group "Core Packages" "java.*"
     -overview \java\pubs\ws\1.7.0\src\share\classes\overview-core.html
     -sourcepath \java\pubs\ws\1.7.0\src\share\classes

Create a file named "packages" containing:

     com.mypackage1
     com.mypackage2
     com.mypackage3
You would then run javadoc with:
  C:> javadoc @options @packages

Example - Arg Files with Paths

The argument files can have paths, but any filenames inside the files are relative to the current working directory (not path1 or path2):
  C:> javadoc @path1\options @path2\packages

Example - Option Arguments

Here's an example of saving just an argument to a javadoc option in an argument file. We'll use the -bottom option, since it can have a lengthy argument. You could create a file named "bottom" containing its text argument:

'<font size="-1">
      <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a><br/>
      Copyright &copy; 1993, 2011, Oracle and/or its affiliates. All rights reserved.<br/>
      Oracle is a registered trademark of Oracle Corporation and/or its affiliates.
      Other names may be trademarks of their respective owners.</font>'
Then run the Javadoc tool with:
  C:> javadoc -bottom @bottom @packages
Or you could include the -bottom option at the start of the argument file, and then just run it as:
  C:> javadoc @bottom @packages

Running

RUNNING JAVADOC

Version Numbers - The version number of javadoc can be determined using javadoc -J-version. The version number of the standard doclet appears in its output stream. It can be turned off with -quiet.

Public programmatic interface - To invoke the Javadoc tool from within programs written in the Java language. This interface is in com.sun.tools.javadoc.Main (and javadoc is re-entrant). For more details, see Standard Doclet.

Running Doclets - The instructions given below are for invoking the standard HTML doclet. To invoke a custom doclet, use the -doclet and -docletpath options. For full, working examples of running a particular doclet, see the MIF Doclet documentation.

SIMPLE EXAMPLES

You can run javadoc on entire packages or individual source files. Each package name has a corresponding directory name. In the following examples, the source files are located at C:\home\src\java\awt\*java. The destination directory is C:\home\html.

Documenting One or More Packages

To document a package, the source files (*.java) for that package must be located in a directory having the same name as the package. If a package name is made up of several identifiers (separated by dots, such as java.awt.color), each subsequent identifier must correspond to a deeper subdirectory (such as java/awt/color). You may split the source files for a single package among two such directory trees located at different places, as long as -sourcepath points to them both – for example src1\java\awt\color and src2\java\awt\color.

You can run javadoc either by changing directories (with cd) or by using -sourcepath option. The examples below illustrate both alternatives.

  • Case 1 - Run recursively starting from one or more packages - This example uses -sourcepath so javadoc can be run from any directory and -subpackages (a new 1.4 option) for recursion. It traverses the subpackages of the java directory excluding packages rooted at java.net and java.lang. Notice this excludes java.lang.ref, a subpackage of java.lang).
      % javadoc -d \home\html -sourcepath \home\src -subpackages java -exclude java.net:java.lang

    To also traverse down other package trees, append their names to the -subpackages argument, such as java:javax:org.xml.sax.

  • Case 2 - Run on explicit packages after changing to the "root" source directory - Change to the parent directory of the fully-qualified package. Then run javadoc, supplying names of one or more packages you want to document:
      C:> cd C:\home\src\
  C:> javadoc -d C:\home\html java.awt java.awt.event
  • Case 3 - Run from any directory on explicit packages in a single directory tree - In this case, it doesn't matter what the current directory is. Run javadoc supplying -sourcepath with the parent directory of the top-level package, and supplying names of one or more packages you want to document:
      C:> javadoc -d C:\home\html -sourcepath C:\home\src java.awt java.awt.event
  • Case 4 - Run from any directory on explicit packages in multiple directory trees - This is the same as case 3, but for packages in separate directory trees. Run javadoc supplying -sourcepath with the path to each tree's root (colon-separated) and supply names of one or more packages you want to document. All source files for a given package do not need to be located under a single root directory – they just need to be found somewhere along the sourcepath.
      C:> javadoc -d C:\home\html -sourcepath C:\home\src1;C:\home\src2 java.awt java.awt.event
Result: All cases generate HTML-formatted documentation for the public and protected classes and interfaces in packages java.awt and java.awt.event and save the HTML files in the specified destination directory (C:\home\html). Because two or more packages are being generated, the document has three HTML frames – for the list of packages, the list of classes, and the main class pages.

Documenting One or More Classes

The second way to run the Javadoc tool is by passing in one or more source files (.java). You can run javadoc either of the following two ways – by changing directories (with cd) or by fully-specifying the path to the .java files. Relative paths are relative to the current directory. The -sourcepath option is ignored when passing in source files. You can use command line wildcards, such as asterisk (*), to specify groups of classes.
  • Case 1 - Changing to the source directory - Change to the directory holding the .java files. Then run javadoc, supplying names of one or more source files you want to document.
      C:> cd C:\home\src\java\awt
  C:> javadoc -d C:\home\html Button.java Canvas.java Graphics*.java
    This example generates HTML-formatted documentation for the classes Button, Canvas and classes beginning with Graphics. Because source files rather than package names were passed in as arguments to javadoc, the document has two frames – for the list of classes and the main page.
  • Case 2 - Changing to the package root directory - This is useful for documenting individual source files from different subpackages off the same root. Change to the package root directory, and supply the source files with paths from the root.
      C:> cd C:\home\src
  C:> javadoc -d \home\html java\awt\Button.java java\applet\Applet.java
    This example generates HTML-formatted documentation for the classes Button and Applet.
  • Case 3 - From any directory - In this case, it doesn't matter what the current directory is. Run javadoc supplying the absolute path (or path relative to the current directory) to the .java files you want to document.
      C:> javadoc -d C:\home\html C:\home\src\java\awt\Button.java C:\home\src\java\awt\Graphics*.java
    This example generates HTML-formatted documentation for the class Button and classes beginning with Graphics.

Documenting Both Packages and Classes

You can document entire packages and individual classes at the same time. Here's an example that mixes two of the previous examples. You can use -sourcepath for the path to the packages but not for the path to the individual classes.
  C:> javadoc -d C:\home\html -sourcepath C:\home\src java.awt C:\home\src\java\applet\Applet.java
This example generates HTML-formatted documentation for the package java.awt and class Applet. (The Javadoc tool determines the package name for Applet from the package declaration, if any, in the Applet.java source file.)

REAL WORLD EXAMPLE

The Javadoc tool has many useful options, some of which are more commonly used than others. Here is effectively the command we use to run the Javadoc tool on the Java platform API. We use 180MB of memory to generate the documentation for the 1500 (approx.) public and protected classes in the Java SE Platform, Standard Edition, v1.2.

The same example is shown twice – first as executed on the command line, then as executed from a makefile. It uses absolute paths in the option arguments, which enables the same javadoc command to be run from any directory.

Command Line Example

The following command line may be too long for some shells such as DOS. You can use a command line argument file (or write a shell script) to workaround this limitation.
C:\> javadoc -sourcepath \java\jdk\src\share\classes ^
    -overview \java\jdk\src\share\classes\overview.html ^
    -d \java\jdk\build\api ^
    -use ^
    -splitIndex ^
    -windowtitle 'Java Platform, Standard Edition 7 API Specification' ^
    -doctitle 'Java Platform, Standard Edition 7 API Specification' ^
    -header '<b>Java™ SE 7</b>' ^
    -bottom '<font size="-1">
      <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a><br/>
      Copyright &copy; 1993, 2011, Oracle and/or its affiliates. All rights reserved.<br/>
      Oracle is a registered trademark of Oracle Corporation and/or its affiliates.
      Other names may be trademarks of their respective owners.</font>'
    -group "Core Packages" "java.*:com.sun.java.*:org.omg.*" ^
    -group "Extension Packages" "javax.*" ^
    -J-Xmx180m ^
    @packages
where packages is the name of a file containing the packages to process, such as java.applet java.lang. None of the options should contain any newline characters between the single quotes. (For example, if you copy and paste this example, delete the newline characters from the -bottom option.) See the other notes listed below.

Makefile Example

This is an example of a GNU makefile. For an example of a Windows makefile, see creating a makefile for Windows.
javadoc -sourcepath $(SRCDIR)              ^   /* Sets path for source files     */
        -overview $(SRCDIR)\overview.html  ^   /* Sets file for overview text    */
        -d \java\jdk\build\api             ^   /* Sets destination directory     */
        -use                               ^   /* Adds "Use" files               */
        -splitIndex                        ^   /* Splits index A-Z               */
        -windowtitle $(WINDOWTITLE)        ^   /* Adds a window title            */
        -doctitle $(DOCTITLE)              ^   /* Adds a doc title               */
        -header $(HEADER)                  ^   /* Adds running header text       */
        -bottom $(BOTTOM)                  ^   /* Adds text at bottom            */
        -group $(GROUPCORE)                ^   /* 1st subhead on overview page   */
        -group $(GROUPEXT)                 ^   /* 2nd subhead on overview page   */
        -J-Xmx180m                         ^   /* Sets memory to 180MB           */
        java.lang java.lang.reflect        ^   /* Sets packages to document      */
        java.util java.io java.net         ^
        java.applet

WINDOWTITLE = 'Java™ Platform, Standard Edition 6 API Specification'
DOCTITLE = 'Java™ Platform, Standard Edition 6 API Specification'
HEADER = '<b>Java™ Platform, Standard Edition 6'
BOTTOM = '<font size="-1">
      <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a><br/>
      Copyright &copy; 1993, 2011, Oracle and/or its affiliates. All rights reserved.<br/>
      Oracle is a registered trademark of Oracle Corporation and/or its affiliates.
      Other names may be trademarks of their respective owners.</font>'
GROUPCORE = '"Core Packages" "java.*:com.sun.java.*:org.omg.*"'
GROUPEXT  = '"Extension Packages" "javax.*"'
SRCDIR = '/java/jdk/1.7.0/src/share/classes'

Single quotes are used to surround makefile arguments.

NOTES

  • If you omit the -windowtitle option, the Javadoc tool copies the doc title to the window title. The -windowtitle text is basically the same as the -doctitle but without HTML tags, to prevent those tags from appearing as raw text in the window title.
  • If you omit the -footer option, as done here, the Javadoc tool copies the header text to the footer.
  • Other important options you might want to use but not needed in this example are -classpath and -link.

TROUBLESHOOTING

General Troubleshooting

  • Javadoc FAQ - Commonly-encountered bugs and troubleshooting tips can be found on the Javadoc FAQ
  • Bugs and Limitations - You can also see some bugs listed at Important Bug Fixes and Changes.
  • Version number - See version numbers.
  • Documents only legal classes - When documenting a package, javadoc only reads files whose names are composed of legal class names. You can prevent javadoc from parsing a file by including, for example, a hyphen "-" in its filename.

Errors and Warnings

Error and warning messages contain the filename and line number to the declaration line rather than to the particular line in the doc comment.
  • "error: cannot read: Class1.java" the Javadoc tool is trying to load the class Class1.java in the current directory. The class name is shown with its path (absolute or relative), which in this case is the same as ./Class1.java.

ENVIRONMENT

CLASSPATH
Environment variable that provides the path which javadoc uses to find user class files. This environment variable is overridden by the -classpath option. Separate directories with a semicolon, for example:
.;C:\classes;C:\home\java\classes

SEE ALSO

  • javac
  • java
  • jdb
  • javah
  • javap
  • Javadoc Home Page
  • How to Write Doc Comments for Javadoc
  • Setting the Class Path
  • How Javac and Javadoc Find Classes (tools.jar)
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Platform Debugger Architecture

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Release notes for the javadt debugger

As a demonstration of the Java Debug Interface (JDI), we are providing source code for a simple GUI debugging tool - javadt. It is included as an example and demonstration of JDI. It is not a finished or polished debugger and is missing many features of importance for real debugging work.

Invoking javadt

javadt can be run by executing:

   java gui.GUI <options>.. <class-name>

where <class-name> is the name you would normally place on the java command line. Note: the paths to the JDI Library and to the compiled javadt class files must be on the class path used to invoke gui.GUI. Be sure that the Java 2 SDK's lib/tools.jar file on your class path.

For example, you can invoke the javadt debugger as follows:

   javadt gui.GUI -classpath . Hello
Note: this -classpath option controls the class path for the Hello application. Once the window appears, you can issue the 'run' command to begin execution immediately. It is also possible to give the class name in the 'run' command, in which case it may be omitted when invoking the debugger from the shell.

The classpath may also be set from within the debugger, using the 'classpath' command. Currently, other arguments to the VM must be given on the shell command line when the debugger is initially invoked. The most recently mentioned classpath, VM arguments, main class name, and program arguments are retained as defaults for later 'run' and 'load' commands. (Unfortunately, at present, the debugger will likely crash if you attempt to begin another debugging session with another debuggee process from within the same invocation of the debugger. You should exit to the shell and start a new debugger process.)

Using javadt

The javadt normally displays context related to the "current thread", that is, the thread that most recently encountered a breakpoint, threw an uncaught exception, or was single-stepped by the user. When program execution is suspended on account of one of these events, a current thread exists, and the javadt displays the following information about it:

  • A stack backtrace.
  • The source code surrounding the line corresponding to the instruction counter for the thread, if the source code is available.

In addition, a tabbed pane allows the user to view one of three additional views:

  • A tree of all source files available on the source path.
  • A tree of all loaded class files, organized hierarchically by package.
  • A tree of all active threads, organized hierarchically by thread group.

By clicking on the name of a source file, the source view can be directed to display it. Likewise, clicking on a thread will make that thread the current thread. These features are normally used while the program is suspended, e.g, at a breakpoint. Upon resumption and encountering another breakpoint, for example, the current thread will be automatically reset and the views will be updated. The views tile the javadt display, and are adjustable in size.

The javadt functionality is rather basic, thus a command-line interaction window is also provided that allows access to functions that are not yet exposed in the javadt. In particular, it is necessary to use the command line in order to set breakpoints and examine variables. The javadt debugger command interpreter implements roughly a subset of the jdb functionality, but adds a few commands of its own. The 'help' command lists the complete set of commands and their function. Shortcuts for a set of the most common commands is provided on a button-bar at the top of the display.

The program to be debugged may be started either as a child of the debugger, or the debugger can be attached to an existing process, provided that its VM is prepared to accept the connection. If the debuggee is started by the debugger as a child, a line-oriented interface to its standard input, output, and error streams is provided in an application interaction pane.

The debugger expects to find the program source code on its sourcepath, set with the 'use' or 'sourcepath' command. If you find that sources are not being displayed because the sourcepath is incorrect, you may change it at that time, and the source view will be immediately updated.

The message "No current thread" is often encountered when stepping through a program. This message does not mean that the thread or the VM has died, merely that a current thread is undefined. This situation can easily occur unexpectedly when the program being stepped is waiting, eg., for input. The VM appears to be stopped, as it would be after the successful completion of a step, but it is considered to be "running", not "interrupted". The prompt in the command interaction pane indicates the state by changing to a thread name and frame number when the VM is interrupted. When it is running, the prompt "Command:" is displayed.

Source for javadt

Full source code for javadt is included in the com/sun/tools/example/debug directory of examples.jar. Note: this directory also includes the source for jdb. Source code of these example applications is included to provide concrete examples for debugger developers. Example code may be used, modified and redistributed by debugger developers providing they adhere to the terms in the copyright notice.

javadt uses the following packages (found in the com/sun/tools/example/debug directory of examples.jar):

gui
User interface code
bdi
Debugger core code
events
Event Set code
expr
Expression processing code

Building javadt

To build the javadt classes from the provided source files in the debuggers directory, you need only to compile them. No special options are required, aside from those which set your classpath to include the JDI Library. However, if want to modify the expression parser in the file Expr.jj, you will need the JavaCC parser generator.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


javah - C Header and Stub File Generator

javah produces C header files and C source files from a Java class. These files provide the connective glue that allow your Java and C code to interact.

SYNOPSIS

javah [ options ] fully-qualified-classname. . .

DESCRIPTION

javah generates C header and source files that are needed to implement native methods. The generated header and source files are used by C programs to reference an object's instance variables from native source code. The .h file contains a struct definition whose layout parallels the layout of the corresponding class. The fields in the struct correspond to instance variables in the class.

The name of the header file and the structure declared within it are derived from the name of the class. If the class passed to javah is inside a package, the package name is prepended to both the header file name and the structure name. Underscores (_) are used as name delimiters.

By default javah creates a header file for each class listed on the command line and puts the files in the current directory. Use the -stubs option to create source files. Use the -o option to concatenate the results for all listed classes into a single file.

The new native method interface, Java Native Interface (JNI), does not require header information or stub files. javah can still be used to generate native method function proptotypes needed for JNI-style native methods. javah produces JNI-style output by default, and places the result in the .h file.

OPTIONS

-o outputfile
Concatenates the resulting header or source files for all the classes listed on the command line into outputfile. Only one of -o or -d may be used.
-d directory
Sets the directory where javah saves the header files or the stub files. Only one of -d or -o may be used.
-stubs
Causes javah to generate C declarations from the Java object file.
-verbose
Indicates verbose output and causes javah to print a message to stdout concerning the status of the generated files.
-help
Print help message for javah usage.
-version
Print out javah version information.
-jni
Causes javah to create an output file containing JNI-style native method function prototypes. This is the default output, so use of -jni is optional.
-classpath path
Specifies the path javah uses to look up classes. Overrides the default or the CLASSPATH environment variable if it is set. Directories are separated by semi-colons. Thus the general format for path is:
   .;<your_path>
For example:
   .;C:\users\dac\classes;C:\tools\java\classes

As a special convenience, a class path element containing a basename of * is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR (a java program cannot tell the difference between the two invocations).

For example, if directory foo contains a.jar and b.JAR, then the class path element foo/* is expanded to a A.jar:b.JAR, except that the order of jar files is unspecified. All jar files in the specified directory, even hidden ones, are included in the list. A classpath entry consisting simply of * expands to a list of all the jar files in the current directory. The CLASSPATH environment variable, where defined, will be similarly expanded. Any classpath wildcard expansion occurs before the Java virtual machine is started -- no Java program will ever see unexpanded wildcards except by querying the environment. For example; by invoking System.getenv("CLASSPATH").

-bootclasspath path
Specifies path from which to load bootstrap classes. By default, the bootstrap classes are the classes implementing the core Java platform located in jre\lib\rt.jar and several other jar files.
-old
Specifies that old JDK1.0-style header files should be generated.
-force
Specifies that output files should always be written.
-J option
Pass option to the Java virtual machine, where option is one of the options described on the reference page for the java application launcher. For example, -J-Xms48m sets the startup memory to 48 megabytes.

ENVIRONMENT VARIABLES

CLASSPATH
Used to provide the system a path to user-defined classes. Directories are separated by semi-colons, for example,
   .;C:\users\dac\classes;C:\tools\java\classes

SEE ALSO

javac, java, jdb, javap, javadoc

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


javap - The Java Class File Disassembler

Disassembles class files.

SYNOPSIS

javap [ options ] classes

DESCRIPTION

The javap command disassembles one or more class files. Its output depends on the options used. If no options are used, javap prints out the package, protected, and public fields and methods of the classes passed to it. javap prints its output to stdout.

options
Command-line options.
classes
List of one or more classes (separated by spaces) to be processed for annotations (such as DocFooter.class). You may specify a class that can be found in the class path, by its file name (for example, /home/user/myproject/src/DocFooter.class), or with a URL (for example, file:///home/user/myproject/src/DocFooter.class).

For example, compile the following class declaration:

import java.awt.*;
import java.applet.*;

public class DocFooter extends Applet {
        String date;
        String email;

        public void init() {
                resize(500,100);
                date = getParameter("LAST_UPDATED");
                email = getParameter("EMAIL");
        }

        public void paint(Graphics g) {
                g.drawString(date + " by ",100, 15);
                g.drawString(email,290,15);
        }
}

The output from javap DocFooter.class yields:

Compiled from "DocFooter.java"
public class DocFooter extends java.applet.Applet {
  java.lang.String date;
  java.lang.String email;
  public DocFooter();
  public void init();
  public void paint(java.awt.Graphics);
}

The output from javap -c DocFooter.class yields:

Compiled from "DocFooter.java"
public class DocFooter extends java.applet.Applet {
  java.lang.String date;

  java.lang.String email;

  public DocFooter();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/applet/Applet."<init>":()V
       4: return

  public void init();
    Code:
       0: aload_0
       1: sipush        500
       4: bipush        100
       6: invokevirtual #2                  // Method resize:(II)V
       9: aload_0
      10: aload_0
      11: ldc           #3                  // String LAST_UPDATED
      13: invokevirtual #4                  // Method getParameter:(Ljava/lang/String;)Ljava/lang/String;
      16: putfield      #5                  // Field date:Ljava/lang/String;
      19: aload_0
      20: aload_0
      21: ldc           #6                  // String EMAIL
      23: invokevirtual #4                  // Method getParameter:(Ljava/lang/String;)Ljava/lang/String;
      26: putfield      #7                  // Field email:Ljava/lang/String;
      29: return

  public void paint(java.awt.Graphics);
    Code:
       0: aload_1
       1: new           #8                  // class java/lang/StringBuilder
       4: dup
       5: invokespecial #9                  // Method java/lang/StringBuilder."<init>":()V
       8: aload_0
       9: getfield      #5                  // Field date:Ljava/lang/String;
      12: invokevirtual #10                 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      15: ldc           #11                 // String  by
      17: invokevirtual #10                 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      20: invokevirtual #12                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
      23: bipush        100
      25: bipush        15
      27: invokevirtual #13                 // Method java/awt/Graphics.drawString:(Ljava/lang/String;II)V
      30: aload_1
      31: aload_0
      32: getfield      #7                  // Field email:Ljava/lang/String;
      35: sipush        290
      38: bipush        15
      40: invokevirtual #13                 // Method java/awt/Graphics.drawString:(Ljava/lang/String;II)V
      43: return
}

OPTIONS

-help
--help
-?
Prints out help message for javap.
-version
Prints out version information.
-l
Prints out line and local variable tables.
-public
Shows only public classes and members.
-protected
Shows only protected and public classes and members.
-package
Shows only package, protected, and public classes and members. This is the default.
-private
-p
Shows all classes and members.
-Jflag
Pass flag directly to the runtime system. Some examples:
javap -J-version
javap -J-Djava.security.manager -J-Djava.security.policy=MyPolicy MyClassName
-s
Prints internal type signatures.
-sysinfo
Shows system information (path, size, date, MD5 hash) of the class being processed.
-constants
Shows static final constants.
-c
Prints out disassembled code, i.e., the instructions that comprise the Java bytecodes, for each of the methods in the class. These are documented in the Java Virtual Machine Specification.
-verbose
Prints stack size, number of locals and args for methods.
-classpath path
Specifies the path javap uses to look up classes. Overrides the default or the CLASSPATH environment variable if it is set.
-bootclasspath path
Specifies path from which to load bootstrap classes. By default, the bootstrap classes are the classes implementing the core Java platform located in jre/lib/rt.jar and several other jar files.
-extdirs dirs
Overrides location at which installed extensions are searched for. The default location for extensions is the value of java.ext.dirs.

SEE ALSO

javac, java, jdb, javah, javadoc

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


java.rmi Properties

Please Note: Unless otherwise stated, any output from these properties is sent to System.err.

Properties that are useful to set on virtual machines (VMs) that export remote objects

java.rmi.activation.port
This property is used to set the TCP port number on which this VM should communicate with rmid (by default, rmid listens on port 1098, but can be set to listen on a different port by using the -port option on the rmid command line). The default value of this property is 1098, so this property only needs to be set on VMs that need to communicate with an instance of rmid that is running on a port other than 1098.

java.rmi.dgc.leaseValue
The value of this property represents the lease duration (in milliseconds) granted to other VMs that hold remote references to objects which have been exported by this VM. Clients usually renew a lease when it is 50% expired, so a very short value will increase network traffic and risk late renewals in exchange for reduced latency in calls to Unreferenced.unreferenced. The default value of this property is 600000 milliseconds (10 minutes).
java.rmi.server.codebase
This property specifies the locations from which classes that are published by this VM (for example: stub classes, custom classes that implement the declared return type of a remote method call, or interfaces used by a proxy or stub class) may be downloaded. The value of this property is a string in URL format or a space-separated list of URLs that will be the codebase annotation for all classes loaded from the CLASSPATH of (and subsequently marshalled by) this VM.

Note: This property must be set correctly in order to dynamically download classes and interfaces using JavaTM Remote Method Invocation (Java RMI). If this property is not set correctly, you will likely encounter exceptions when attempting to run your server or client. For more information on this property, see Dynamic code downloading using Java RMI (Using the java.rmi.server.codebase Property).

java.rmi.server.hostname
The value of this property represents the host name string that should be associated with remote stubs for locally created remote objects, in order to allow clients to invoke methods on the remote object. The default value of this property is the IP address of the local host, in "dotted-quad" format.
java.rmi.server.logCalls
If this value is true, incoming calls and exceptions thrown from incoming calls will be logged to System.err. Setting this property to true will greatly assist you in debugging your RMI programs. See also sun.rmi.server.exceptionTrace.
java.rmi.server.randomIDs
If this value is true, object identifiers for remote objects exported by this VM will be generated by using a cryptographically secure random number generator. The default value is false.
java.rmi.server.useCodebaseOnly
If this value is true, automatic loading of classes is prohibited except from the local CLASSPATH and from the java.rmi.server.codebase property set on this VM. Use of this property prevents client VMs from dynamically downloading bytecodes from other codebases. This property is ignored in the implementations of 1.2 and 1.2.1 because of a bug.
java.rmi.server.useLocalHostname
Java RMI now uses an IP address to identify the local host when the java.rmi.server.hostname property is not specified and a fully qualified domain name for the localhost cannot be obtained. In order to force Java RMI to use the fully qualified domain name by default, you need to set the this property to true.

Properties that are useful to set on VMs that make remote method calls

java.rmi.server.codebase
This property specifies the locations from which classes that are published by this VM (for example, custom classes that implement an interface that is the declared parameter type of a remote method call) may be downloaded. The value of this property is a string in URL format (or a space-separated list of URLs in 1.2 and later) that will be the codebase annotation for all classes loaded from the CLASSPATH of (and subsequently marshalled by) this VM.

Note: Classes that exist in both the server's codebase and the client's CLASSPATH will be loaded from the client's CLASSPATH, rather than from the server's codebase as intended. For more information on this property, see Dynamic code downloading using Java RMI (Using the java.rmi.server.codebase Property).

java.rmi.server.disableHttp
If this value is true, HTTP tunneling is disabled, even when http.proxyHost is set. The default value is false. If you know that your program will never need to use HTTP tunneling, then by disabling HTTP tunneling, you should see shorter timeouts for failed connections.
java.rmi.server.useCodebaseOnly
If this value is true, automatic loading of classes is prohibited except from the local CLASSPATH and from the java.rmi.server.codebase property set on this VM. Use of this property prevents client VMs from dynamically downloading bytecodes from other codebases. This property is ignored in the implementations of 1.2 and 1.2.1 because of a bug.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


javaws Command Line

NAME

javaws - Java Web Start launcher command

SYNOPSIS

javaws [run-options] <jnlp>

javaws [control-options]

PARAMETERS

[run-options]

Command-line run-options. run-options may be in any order. For a discussion of the various run-options, see RUN-OPTIONS below.

<jnlp>

This can be either the path of, or the Uniform Resource Locater (URL) of the JNLP (Java Network Launching Protocol) file.

[control-options]

Command-line control-options. control-options may be in any order. For a discussion of the various control-options, see CONTROL-OPTIONS below.

DESCRIPTION

The javaws command launches Java Web Start, which is the reference implementation of the Java Network Launching Protocol (JNLP). Java Web Start launches Java applications/applets hosted on a network.

If a JNLP file is specified, javaws will launch the Java application/applet specified in the JNLP file.

The javaws launcher has a set of options that are supported in the current release. However, the options may be removed in a future release.

RUN-OPTIONS

-offline

Run Java Web Start in offline mode.

-Xnosplash

Do not display the initial splash screen.

-open <arguments>

If specified, replaces the arguments in the jnlp file with -open <arguments>.

-print <arguments>

If specified, replaces the arguments in the jnlp file with -print <arguments>.

-online

Use online mode (default behavior).

-wait

If specified, the javaws process will not exit until the application exits. This option does not function as described on Windows platforms.

-verbose

Display additional output.

-J<option>

Supply options to the VM.

-system

Run the application from the system cache only.

CONTROL-OPTIONS

-viewer

Show the Cache Viewer in the Java Control Panel.

-clearcache

Remove all non-installed applications from the cache.

-userConfig <property name>

Clear the specified deployment property.

-userConfig <property name> <property value>

Set the specified deployment property to the specified value.

-uninstall

Remove all applications from the cache.

-uninstall <jnlp>

Remove the application from the cache.

-import [import-options] <jnlp>

Import the application to the cache.

IMPORT-OPTIONS

-silent

Import silently (with no user interface).

-system

Import application to the system cache.

-codebase <url>

Retrieve resources from the given codebase.

-shortcut

Install shortcuts as if user allowed prompt. This option has no effect unless -silent option is also used.

-association

Install associations as if user allowed prompt. This option has no effect unless -silent option is also used.

FILES

For information about the user and system cache and deployment.properties files, see System- and User-Level Properties.

MORE INFORMATION

For more information about Java Web Start, see Java Web Start.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JAXP Compatibility

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

JAXP Compatibility Guide
for the J2SE 6 Platform

Contents

  • What's New

  • DOM Level 3

    • Methods added to DOM interfaces

    • Preserving the XML format

  • SAX 2.0.2

  • Invoking XSLT

    • Programmatic Access to Xalan XPath

  • Package Name Changes

    • What Changed, and Why

  • Security Issue Posed by Nested Entity Definitions

Introduction

The Java 2 Platform, Standared Edition (J2SE) 1.4 included the Crimson reference implementation for JAXP 1.1. The Java platform, Standard Edition (Java SE platform) 6 includes a reference implementation for JAXP 1.4 based on the Apache Xerces library.

Because these implementations come from entirely different codebases, and because the JAXP standard has evolved from 1.1 to 1.4, there are some subtle differences between the implementations, even they both conform to the JAXP standard. These two factors combine to create the compatibility issues described in this guide.

What's New

See Release Notes.

DOM Level 3

While the reference implementation in J2SE 1.4 supported the DOM Level 2 API, the implementation in J2SE 6 supports the DOM Level 3 family of APIs. This section covers the impact of those changes on programs that used the JAXP 1.1 reference implementation:

  • Methods added to DOM interfaces

  • Preserving the XML format

For more information, see the complete list of changes in the DOM Level 3 Changes appendix.

Methods added to DOM interfaces

In DOM level 3, additional methods were defined in the following interfaces:

  • Attr

  • Document

  • DOMImplementation

  • Element

  • Entity

  • Node

  • Text

The added methods only affect applications that implement the interfaces directly, and only when the application is recompiled. Applications that use the factory methods to obtain implementation classes for these interfaces will have no problems.

Preserving the XML format

These changes affect an application that reads in XML data into a DOM, makes modifications, and then writes it out in a way that preserves the original formatting.

In JAXP 1.1, extraneous whitespace was automatically removed on input, and a single property (ignoringLexicalInfo) was set to false to preserve entity nodes and CDATA nodes, for example. Including the additional nodes made the DOM somewhat more complex to process, but because they were there, adding whitespace output (indentation and newlines) produced highly readable, formatted version of the XML data which closely approximated the input.

In JAXP 1.4, there are four APIs that the application uses to determine how much lexical (formatting) information is available to process, using the following DocumentBuilderFactory methods:

  • setCoalescing()
    To convert CDATA nodes to Text node and append
    to an adjacent Text node (if any).

  • setExpandEntityReferences()
    To expand entity reference nodes.

  • setIgnoringComments()
    To ignore comments.

  • setIgnoringElementContentWhitespace()
    To ignore whitespace that is not a significant part
    of element content.

The default values for all of these properties is false, which preserves all the lexical information necessary to reconstruct the incoming document in its original form. Setting them all to true lets you construct the simplest possible DOM, so the application can focus on the data's semantic content, without having to worry about lexical syntax details.

Note:
When adding new nodes, the application must add any indentation and newline formatting that is needed for readability, since it is not provided automatically.

SAX 2.0.2

Following are the changes made between SAX 2.0.0 and SAX 2.0.2 that might affect compatibility.

  • DeclHandler.externalEntityDecl now requires the parser to return the absolute system identifier for consistency with DTDHandler.unparsedEntityDecl. This may cause some incompatibilities.

  • In SAX 2.0.1, an application can set ErrorHandler, EntityResolver, ContentHandler, or DTDHandler to null. This is a relaxation of the previous restriction in SAX 2.0, which generated a NullPointerException (NPE) in such circumstances.

    So the following code is legal in JAXP 1.3:

    SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader reader = sp.getXMLReader();
reader.setErrorHandler(null);
reader.setContentHandler(null);
reader.setEntityResolver(null);
reader.setDTDHandler(null);

  • The resolveEntity() method in the EntityResolver API now throws IOException, as well as SAXException. (Before, it only threw SAXException.)

    The vast majority of applications are unaffected by this change, because the DefaultHandler implementation class has been modified to declare the additional exception, and very few applications use the DefaultHandler in such a way that they will run into a problem.

    The only way an application can be affected is if it overrides the resolveEntity() method and also invokes super.resolveEntity(). In that case, the application won't compile in J2SE 5 until the method is modified to handle the IOExceptions that super.resolveEntity() could throw.

  • The following new features are recognized :

    • http://xml.org/sax/features/external-general-entities
      To include external general entities.

    • http://xml.org/sax/features/external-parameter-entities
      To include external parameter entities and the external DTD subset.

    and the following new property:

    • http://xml.org/sax/properties/xml-string
      To get the string of characters associated with the current event.

    For a complete list of Xerces features and properties, see http://xerces.apache.org/xerces2-j/features.html and http://xerces.apache.org/xerces2-j/properties.html.

Note:
One point of compatibility is also worth mentioning. Namespace recognition was turned off by default in J2SE 1.4 (JAXP 1.1). For backward compatibility, that policy is continued in J2SE 6 (JAXP 1.4). However, namespace recognition is turned on by default in the official SAX implementation at www.saxproject.org. While not strictly a compatibility issue from the standpoint of JAXP, it is an issue that sometimes comes as a surprise.

Using XSLT

Code that uses the standard JAXP APIs to create and access an XSL transformer does not need to be changed. The output will be the same, but will in general be produced much faster, since the XSLTC compiling transformer will be used by default, instead of the interpreting Xalan transformer.

Note:
There may be no significant difference between Xalan and XSLTC performance for a single run on a small data set, as when you are developing and testing an XSL stylesheet. But there is a major performance benefit when using XSLTC on anything larger.

Programmatic Access to Xalan XPath

JAXP 1.4 provides the standard XPath API for evaluating XPath expressions. We encourage users to use this API. Xalan-interpretive is not included in the reference implementation. If an application explicitly uses the Xalan XPath API to evaluate a standalone XPath expression (one that is not part of an XSLT stylesheet), you'll need to download and install the Apache libraries for Xalan.

Package Name Changes

This change does not affect applications that confine themselves to using the standard JAXP APIs. But applications that access implementation-specific features of the XML processors defined in JAXP versions prior to 1.3 will have to be modified.

The change has several effects on previous applications:

  1. The property-values that were used to access the internal implementations must be changed.

  2. Applications that used internal APIs that from the Xalan implementation classes must change the import statements that gave them access to those APIs.

  3. Applications that used internal APIs from the Crimson implementation must be re-coded -- ideally, by using newer JAXP APIs or, if necessary, by using Xerces APIs.

What Changed, and Why

In J2SE 1.4, the fact that JAXP was built into the Java platform was a mixed blessing. On the one hand, an application could rely on that fact that it was there. On the other, most applications needed features and bug fixes that were available in later versions.

But adding new libraries had no effect, because internal classes always take precedence over the classpath. The solution for that problem in 1.4 was to use the endorsed standards mechanism. However, that was a new mechanism, and one which frequently placed an additional burden on the end user, as well as the application developer.

The solution since JAXP 1.3 is to change the package names of the Apache libraries used in the implementation. That change lets a user reference newer Apache libraries in the classpath, so application developers can use them in the same way that would use any other additions to the Java platform.

The new names given to the Apache packages in the JAXP 1.3 reference implementation are shown below:

Changes in JAXP package names

JAXP 1.1

Since JAXP 1.3

org.apache.crimson

-/-
com.sun.org.apache.xerces.internal

org.apache.xml

com.sun.org.apache.xml.internal

Changes in XSLT package names

JAXP 1.1

Since JAXP 1.3

org.apache.xalan
org.apache.xpath
org.apache.xalan.xsltc

com.sun.org.apache.xalan.internal
com.sun.org.apache.xpath.internal
com.sun.org.apache.xalan.internal.xsltc

Security Issue Posed by Nested Entity Definitions

While XML does not allow recursive entity definitions, it does permit nested entity definitions, which produces the potential for Denial of Service attacks on a server which accepts XML data from external sources. For example, a SOAP document like the following that has very deeply nested entity definitions can consume 100% of CPU time and large amounts of memory in entity expansions:

<?xml version="1.0" encoding ="UTF-8"?>
 <!DOCTYPE foobar[
 <!ENTITY x100 "foobar">
 <!ENTITY  x99 "&x100;&x100;">
 <!ENTITY  x98 "&x99;&x99;">
 ...
 <!ENTITY   x2 "&x3;&x3;">
 <!ENTITY   x1 "&x2;&x2;">
 ]>
<SOAP-ENV:Envelope xmlns:SOAP-ENV=...>
<SOAP-ENV:Body>
<ns1:aaa xmlns:ns1="urn:aaa" SOAP-ENV:encodingStyle="...">
<foobar xsi:type="xsd:string">&x1;</foobar>
</ns1:aaa>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

A system that doesn't take in external XML data need not be concerned with the issue, but one that does can utilize one of the following safeguards to prevent the problem:

New system property to limit entity expansion
The entityExpansionLimit system property lets existing applications constrain the total number of entity expansions without recompiling the code. The parser throws a fatal error once it has reached the entity expansion limit. (By default, the limit is set to 64000.)

To set the entity expansion limit using the system property, use an option like the following on the java command line: -DentityExpansionLimit=100000

New parser property to disallow DTDs
The application can also set the http://apache.org/xml/features/disallow-doctype-decl parser property to true. A fatal error is then thrown if the incoming XML document contains a DOCTYPE declaration. (The default value for this property is false.) This property is typically useful for SOAP based applications where a SOAP message must not contain a Document Type Declaration.
New feature for Secure Processing
JAXP 1.3 includes a new secure processing feature in which an application can configure the SAXParserFactory or DocumentBuilderFactory to get an XML processor that behaves in a secured fashion. Setting this feature to true sets the entity expansion limit to 64000. Note that the default limit can be increased using the entityExpansionLimit system property.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Using JConsole - Java SE Monitoring and Management Guide

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
previous Previous Contents Next next
Chapter 3

Using JConsole

The JConsole graphical user interface is a monitoring tool that complies to the Java Management Extensions (JMX) specification. JConsole uses the extensive instrumentation of the Java Virtual Machine (Java VM) to provide information about the performance and resource consumption of applications running on the Java platform.

In the Java Platform, Standard Edition (Java SE platform) 6, JConsole has been updated to present the look and feel of the Windows and GNOME desktops (other platforms will present the standard Java graphical look and feel). The screen captures presented in this document were taken from an instance of the interface running on Windows XP.

Starting JConsole

The jconsole executable can be found in JDK_HOME/bin, where JDK_HOME is the directory in which the Java Development Kit (JDK) is installed. If this directory is in your system path, you can start JConsole by simply typing jconsole in a command (shell) prompt. Otherwise, you have to type the full path to the executable file.

Command Syntax

You can use JConsole to monitor both local applications, namely those running on the same system as JConsole, as well as remote applications, namely those running on other systems.

Note - Using JConsole to monitor a local application is useful for development and for creating prototypes, but is not recommended for production environments, because JConsole itself consumes significant system resources. Remote monitoring is recommended to isolate the JConsole application from the platform being monitored.

For a complete reference on the syntax of the jconsole command, see the manual page for the jconsole command: Java Monitoring and Management Console.

Setting up Local Monitoring

You start JConsole by typing the following command at the command line.

% jconsole

When JConsole starts, you will be given a choice of all the Java applications that are running locally that JConsole can connect to.

If you want to monitor a specific application, and you know that application's process ID, then you can also start JConsole so that it connects to that application. This application must be running with the same user ID as JConsole. The command syntax to start JConsole for local monitoring of a specific application is the following.

% jconsole processID

In the command above processID is the application's process ID (PID). You can determine an application's PID in the following ways:

  • On UNIX or Linux systems, you can use the ps command to find the PID of the java instance that is running.

  • On Windows systems, you can use the Task Manager to find the PID of java or javaw.

  • You can also use the jps command-line utility to determine PIDs. See the manual page for the Java Virtual Machine Process Status Tool.

For example, if you determined that the process ID of the Notepad application is 2956, then you would start JConsole with the following command.

% jconsole 2956

Both JConsole and the application must by executed by the same user. The management and monitoring system uses the operating system's file permissions. If you do not specify a process ID, JConsole will automatically detect all local Java applications, and display a dialog box that lets you select which one you want to monitor (see Connecting to a JMX Agent).

For more information, see Local Monitoring and Management.

Setting up Remote Monitoring

To start JConsole for remote monitoring, you use the following command syntax.

% jconsole hostName:portNum

In the command above, hostName is the name of the system running the application and portNum is the port number you specified when you enabled the JMX agent when you started the Java VM. For more information, see Remote Monitoring and Management.

If you do not specify a host name/port number combination, then JConsole will display a connection dialog box (Connecting to a JMX Agent) to enable you to enter a host name and port number.

Setting up Secure Remote Monitoring

You can also start JConsole so that monitoring will be performed over a connection that is secured using Secure Sockets Layer (SSL). The command to start JConsole with a secure connection is given in Remote Monitoring with JConsole with SSL Enabled in Chapter 2, Monitoring and Management Using JMX Technology.

Connecting to a JMX Agent

If you start JConsole with arguments specifying a JMX agent to connect to, it will automatically start monitoring the specified Java VM. You can connect to a different host at any time by choosing Connection | New Connection and entering the necessary information.

Otherwise, if you do not provide any arguments when you start JConsole, the first thing you see is the connection dialog box. This dialog box has two options, allowing connections to either Local or Remote processes.

Dynamic Attach

Under previous releases of the Java SE platform, applications that you wanted to monitor with JConsole needed to be started with the following option.

% -Dcom.sun.management.jmxremote

However, the version of JConsole provided with the Java SE 6 platform can attach to any application that supports the Attach API. In other words, any application that is started in the Java SE 6 HotSpot VM is detected automatically by JConsole, and does not need to be started using the above command-line option.

Connecting JConsole to a Local Process

If you start JConsole without providing a specific JMX agent to connect to, you will see the following dialog window.

Figure 3-1 Creating a Connection to a Local Process

The dialog window for creating connections to local processes

The Local Process option lists any Java VMs running on the local system that were started with the same user ID as JConsole, along with their process ID and their class and/or argument information. To connect JConsole to your application, select the application you want to monitor, then click the Connect button. The list of local processes includes applications running in the following types of Java VM.

  • Applications with the management agent enabled. These include applications on the Java SE 6 platform or on the J2SE 5.0 platform that were started with the -Dcom.sun.management.jmxremote option or with the -Dcom.sun.management.jmxremote.port option specified. In addition, the list also includes any applications that were started on the Java SE 6 platform without any management properties but which are later attached to by JConsole, which enables the management agent at runtime.

  • Applications that are attachable, with the management agent disabled. An attachable application supports loading the management agent at runtime. Attachable applications include applications that are started on the Java SE 6 platform that support the Attach API. Applications which support dynamic attach do not require the management agent to be started by specifying the com.sun.management.jmxremote or com.sun.management.jmxremote.port options at the command line, and JConsole does not need to connect to the management agent before the application is started. If you select this application, you will be informed in a note onscreen that the management agent will be enabled when the connection is made. In the example connection dialog shown in Figure 3-1, the NetBeans IDE and JConsole itself were both started within a Java SE 6 platform VM. Both appear in normal text, meaning that JConsole can connect to them. In Figure 3-1, JConsole is selected, and the note is visible.

  • Applications that are not attachable, with the management agent disabled. These include applications started on a J2SE 1.4.2 platform or started on a J2SE 5.0 platform without the -Dcom.sun.management.jmxremote or com.sun.management.jmxremote.port options. These applications appear grayed-out in the table and JConsole cannot connect to them. In the example connection dialog shown in Figure 3-1, the Anagrams application was started with a J2SE 5.0 platform VM without any of the management properties to enable the JMX agent, and consequently shows up in gray and cannot be selected.

Figure 3-2 Attempting to Connect to an Application without the Management Agent Enabled

Attempting to connect to a local process without the management agent enabled. JConsole cannot connect to this application.

In the example connection dialog shown in Figure 3-2, you can see that the Anagrams application has been selected by clicking on it, but the Connect button remains grayed-out and a note has appeared informing you that the management agent is not enabled for this process. JConsole cannot connect to Anagrams because it was not started with the correct Java VM or with the correct options.

Connecting JConsole to a Remote Process

When the connection dialog opens, you are also given the option of connecting to a remote process.

Figure 3-3 Creating a Connection to a Remote Process

The dialog window for creating connections to remote processes

To monitor a process running on a remote Java VM, you must provide the following information.

  • Host name: name of the machine on which the Java VM is running.

  • Port number: the JMX agent port number you specified when you started the Java VM.

  • User name and password: the user name and password to use (required only if monitoring a Java VM through a JMX agent that requires password authentication).

For information about setting the port number of the JMX agent, see Enabling the Out-of-the-Box Management. For information about user names and passwords, see Using Password and Access Files.

To monitor the Java VM that is running JConsole, simply click Connect, using host localhost and the port 0.

Connecting Using a JMX Service URL

You can also use the Remote Process option to connect to other JMX agents by specifying their JMX service URL, and the user name and password. The syntax of a JMX service URL requires that you provide the transport protocol used to make the connection, as well as a service access point. The full syntax for a JMX service URL is described in the API documentation for javax.management.remote.JMXServiceURL.

Figure 3-4 Connecting to a JMX Agent Using the JMX Service URL

Connecting to a JMX Agent Using the JMX Service URL

If the JMX agent uses a connector which is not included in the Java platform, you need to add the connector classes to the class path when you run the jconsole command, as follows.

% jconsole -J-Djava.class.path=JAVA_HOME/lib/jconsole.jar:JAVA_HOME/lib/tools.jar:connector-path

In the command above, connector-path is the directory or the Java archive (Jar) file containing the connector classes that are not included in the JDK, that are to be used by JConsole.

Presenting the JConsole Tabs

Once you have connected JConsole to an application, JConsole is composed of six tabs.

  • Overview: Displays overview information about the Java VM and monitored values.

  • Memory: Displays information about memory use.

  • Threads: Displays information about thread use.

  • Classes: Displays information about class loading.

  • VM: Displays information about the Java VM.

  • MBeans: Displays information about MBeans.

You can use the green connection status icon in the upper right-hand corner of JConsole at any time, to disconnect from or reconnect to a running Java VM. You can connect to any number of running Java VMs at a time by selecting Connection then New Connection from the drop-down menu.

Viewing Overview Information

The Overview tab displays graphical monitoring information about CPU usage, memory usage, thread counts, and the classes loaded in the Java VM, all in a single screen.

Figure 3-5 Overview Tab

The JConsole Overview tab

The Overview tab provides an easy way to correlate information that was previously only available by switching between multiple tabs.

Saving Chart Data

JConsole allows you to save the data presented in the charts in a Comma Separated Values (CSV) file. To save data from a chart, simply right-click on any chart, select Save data as..., and then specify the file in which the data will be saved. You can save the data from any of the charts displayed in any of JConsole's different tabs in this way.

The CSV format is commonly used for data exchange between spreadsheet applications. The CSV file can be imported into spreadsheet applications and can be used to create diagrams in these applications. The data is presented as two or more named columns, where the first column represents the time stamps. After importing the file into a spreadsheet application, you will usually need to select the first column and change its format to be "date" or "date/time" as appropriate.

Monitoring Memory Consumption

The Memory tab provides information about memory consumption and memory pools.

Figure 3-6 Memory Tab

The JConsole Memory tab.

The Memory tab features a “Perform GC” button that you can click to perform garbage collection whenever you want. The chart shows the memory use of the Java VM over time, for heap and non-heap memory, as well as for specific memory pools. The memory pools available depend on which version of the Java VM is being used. For the HotSpot Java VM, the memory pools for serial garbage collection are the following.

  • Eden Space (heap): The pool from which memory is initially allocated for most objects.

  • Survivor Space (heap): The pool containing objects that have survived the garbage collection of the Eden space.

  • Tenured Generation (heap): The pool containing objects that have existed for some time in the survivor space.

  • Permanent Generation (non-heap): The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.

  • Code Cache (non-heap): The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.

You can display different charts for charting the consumption of these memory pools by choosing from the options in the Chart drop-down menu. Also, clicking on either of the Heap or Non-Heap bar charts in the bottom right-hand corner will switch the chart displayed. Finally, you can specify the time range over which you track memory usage by selecting from the options in the Time Range drop-down menu.

For more information about these memory pools, see Garbage Collection below.

The Details area shows several current memory metrics:

  • Used: the amount of memory currently used, including the memory occupied by all objects, both reachable and unreachable.

  • Committed: the amount of memory guaranteed to be available for use by the Java VM. The amount of committed memory may change over time. The Java virtual machine may release memory to the system and the amount of committed memory could be less than the amount of memory initially allocated at start up. The amount of committed memory will always be greater than or equal to the amount of used memory.

  • Max: the maximum amount of memory that can be used for memory management. Its value may change or be undefined. A memory allocation may fail if the Java VM attempts to increase the used memory to be greater than committed memory, even if the amount used is less than or equal to max (for example, when the system is low on virtual memory).

  • GC time: the cumulative time spent on garbage collection and the total number of invocations. It may have multiple rows, each of which represents one garbage collector algorithm used in the Java VM.

The bar chart on the lower right-hand side shows the memory consumed by the memory pools in heap and non-heap memory. The bar will turn red when the memory used exceeds the memory usage threshold. You can set the memory usage threshold through an attribute of the MemoryMXBean.

Heap and Non-Heap Memory

The Java VM manages two kinds of memory: heap and non-heap memory, both of which are created when the Java VM starts.

  • Heap memory is the runtime data area from which the Java VM allocates memory for all class instances and arrays. The heap may be of a fixed or variable size. The garbage collector is an automatic memory management system that reclaims heap memory for objects.

  • Non-heap memory includes a method area shared among all threads and memory required for the internal processing or optimization for the Java VM. It stores per-class structures such as a runtime constant pool, field and method data, and the code for methods and constructors. The method area is logically part of the heap but, depending on the implementation, a Java VM may not garbage collect or compact it. Like the heap memory, the method area may be of a fixed or variable size. The memory for the method area does not need to be contiguous.

In addition to the method area, a Java VM may require memory for internal processing or optimization which also belongs to non-heap memory. For example, the Just-In-Time (JIT) compiler requires memory for storing the native machine code translated from the Java VM code for high performance.

Memory Pools and Memory Managers

Memory pools and memory managers are key aspects of the Java VM's memory system.

  • A memory pool represents a memory area that the Java VM manages. The Java VM has at least one memory pool and it may create or remove memory pools during execution. A memory pool can belong either to heap or to non-heap memory.

  • A memory manager manages one or more memory pools. The garbage collector is a type of memory manager responsible for reclaiming memory used by unreachable objects. A Java VM may have one or more memory managers. It may add or remove memory managers during execution. A memory pool can be managed by more than one memory manager.

Garbage Collection

Garbage collection (GC) is how the Java VM frees memory occupied by objects that are no longer referenced. It is common to think of objects that have active references as being "alive" and non-referenced (or unreachable) objects as "dead." Garbage collection is the process of releasing memory used by the dead objects. The algorithms and parameters used by GC can have dramatic effects on performance.

The Java HotSpot VM garbage collector uses generational GC. Generational GC takes advantage of the observation that most programs conform to the following generalizations.

  • They create many objects that have short lives, for example, iterators and local variables.

  • They create some objects that have very long lives, for example, high level persistent objects.

Generational GC divides memory into several generations, and assigns one or more memory pools to each. When a generation uses up its allotted memory, the VM performs a partial GC (also called a minor collection) on that memory pool to reclaim memory used by dead objects. This partial GC is usually much faster than a full GC.

The Java HotSpot VM defines two generations: the young generation (sometimes called the "nursery") and the old generation. The young generation consists of an "Eden space" and two "survivor spaces." The VM initially assigns all objects to the Eden space, and most objects die there. When it performs a minor GC, the VM moves any remaining objects from the Eden space to one of the survivor spaces. The VM moves objects that live long enough in the survivor spaces to the "tenured" space in the old generation. When the tenured generation fills up, there is a full GC that is often much slower because it involves all live objects. The permanent generation holds all the reflective data of the virtual machine itself, such as class and method objects.

The default arrangement of generations looks something like Figure 3-7.

Figure 3-7 Generations of Data in Garbage Collection

The different generations of data defined by the Garbage Collector

If the garbage collector has become a bottleneck, you can improve performance by customizing the generation sizes. Using JConsole, you can investigate the sensitivity of your performance metric by experimenting with the garbage collector parameters. For more information, see Tuning Garbage Collection with the 5.0 HotSpot VM.

Monitoring Thread Use

The Threads tab provides information about thread use.

Figure 3-8 Threads Tab

The JConsole Threads tab.

The Threads list in the lower left corner lists all the active threads. If you enter a string in the Filter field, the Threads list will show only those threads whose name contains the string you enter. Click on the name of a thread in the Threads list to display information about that thread to the right, including the thread name, state, and stack trace.

The chart shows the number of live threads over time. Two lines are shown.

  • Red: peak number of threads

  • Blue: number of live threads.

The Threading MXBean provides several other useful operations that are not covered by the Threads tab.

  • findMonitorDeadlockedThreads: Detects if any threads are deadlocked on the object monitor locks. This operation returns an array of deadlocked thread IDs.

  • getThreadInfo: Returns the thread information. This includes the name, stack trace, and the monitor lock that the thread is currently blocked on, if any, and which thread is holding that lock, as well as thread contention statistics.

  • getThreadCpuTime: Returns the CPU time consumed by a given thread

You can access these additional features via the MBeans tab by selecting the Threading MXBean in the MBeans tree. This MXBean lists all the attributes and operations for accessing threading information in the Java VM being monitored. See Monitoring and Managing MBeans.

Detecting Deadlocked Threads

To check if your application has run into a deadlock (for example, your application seems to be hanging), deadlocked threads can be detected by clicking on the "Detect Deadlock" button. If any deadlocked threads are detected, these are displayed in a new tab that appears next to the "Threads" tab, as shown in Figure 3-9.

Figure 3-9 Deadlocked Threads

Deadlocked threads detected by JConsole.

The Detect Deadlock button will detect deadlock cycles involving object monitors and java.util.concurrent ownable synchronizers (see the API specification documentation for java.lang.management.LockInfo). Monitoring support for java.util.concurrent locks has been added in Java SE 6. If JConsole connects to a J2SE 5.0 VM, the Detect Deadlock mechanism will only find deadlocks related to object monitors. JConsole will not show any deadlocks related to ownable synchronizers.

See the API documentation for java.lang.Thread for more information about threads and daemon threads.

Monitoring Class Loading

The Classes tab displays information about class loading.

Figure 3-10 Classes Tab

The chart plots the number of classes loaded over time.

  • The red line is the total number of classes loaded (including those subsequently unloaded).

  • The blue line is the current number of classes loaded.

The Details section at the bottom of the tab displays the total number of classes loaded since the Java VM started, the number currently loaded and the number unloaded. You can set the tracing of class loading to verbose output by checking the checkbox in the top right-hand corner.

Viewing VM Information

The VM Summary tab provides information about the Java VM.

Figure 3-11 VM Summary Tab

The JConsole VM Summary tab.

The information presented in this tab includes the following.

  • Summary

    • Uptime: Total amount of time since the Java VM was started.

    • Process CPU Time: Total amount of CPU time that the Java VM has consumed since it was started.

    • Total Compile Time: Total accumulated time spent in JIT compilation. The Java VM determines when JIT compilation occurs. The Hotspot VM uses adaptive compilation, in which the VM launches an application using a standard interpreter, but then analyzes the code as it runs to detect performance bottlenecks, or "hot spots".

  • Threads

    • Live threads: Current number of live daemon threads plus non-daemon threads.

    • Peak: Highest number of live threads since Java VM started.

    • Daemon threads: Current number of live daemon threads.

    • Total threads started: Total number of threads started since Java VM started, including daemon, non-daemon, and terminated threads.

  • Classes

    • Current classes loaded: Number of classes currently loaded into memory.

    • Total classes loaded: Total number of classes loaded into memory since the Java VM started, including those that have subsequently been unloaded.

    • Total classes unloaded: Number of classes unloaded from memory since the Java VM started.

  • Memory

    • Current heap size: Number of kilobytes currently occupied by the heap.

    • Committed memory: Total amount of memory allocated for use by the heap.

    • Maximum heap size: Maximum number of kilobytes occupied by the heap.

    • Objects pending for finalization: Number of objects pending for finalization.

    • Garbage collector: Information about garbage collection, including the garbage collector names, number of collections performed, and total time spent performing GC.

  • Operating System

    • Total physical memory: Amount of random-access memory (RAM) the operating system has.

    • Free physical memory: Amount of free RAM available to the operating system.

    • Committed virtual memory: Amount of virtual memory guaranteed to be available to the running process.

  • Other Information

    • VM arguments: The input arguments the application passed to the Java VM, not including the arguments to the main method.

    • Class path: The class path that is used by the system class loader to search for class files.

    • Library path: The list of paths to search when loading libraries.

    • Boot class path: The boot class path is used by the bootstrap class loader to search for class files.

Monitoring and Managing MBeans

The MBeans tab displays information about all the MBeans registered with the platform MBean server in a generic way. The MBeans tab allows you to access the full set of the platform MXBean instrumentation, including that which is not visible in the other tabs. In addition, you can monitor and manage your application's MBeans using the MBeans tab.

Figure 3-12 MBeans Tab

The JConsole MBeans tab.

The tree on the left shows all the MBeans currently running. When you select an MBean in the tree, its MBeanInfo and its MBean Descriptor are both displayed on the right, and any attributes, operations or notifications appear in the tree below it.

All the platform MXBeans and their various operations and attributes are accessible via JConsole's MBeans tab.

Constructing the MBean Tree

By default, the MBeans are displayed in the tree based on their object names. The order of key properties specified when the object names are created is preserved by JConsole when it adds MBeans to the MBean tree. The exact key property list that JConsole will use to build the MBean tree will be the one returned by the method ObjectName.getKeyPropertyListString(), with type as the first key, and j2eeType, if present, as the second key.

However, relying on the default order of the ObjectName key properties can sometimes lead to unexpected behavior when JConsole renders the MBean tree. For example, if two object names have similar keys but their key order differs, then the corresponding MBeans will not be created under the same node in the MBean tree.

For example, suppose you create Triangle MBean objects with the following names.

com.sun.example:type=Triangle,side=isosceles,name=1
com.sun.example:type=Triangle,name=2,side=isosceles
com.sun.example:type=Triangle,side=isosceles,name=3

As far as the JMX technology is concerned, these objects will be treated in exactly the same way. The order of the keys in the object name makes no difference to the JMX technology. However, if JConsole connects to these MBeans and the default MBean tree rendering is used, then the object com.sun.example:type=Triangle,name=2,side=isosceles will end up being created under the Triangle node, in a node called 2, which in turn will contain a sub-node called isosceles. The other two isosceles triangles, name=1 and name=3, will be grouped together under Triangle in a different node called isosceles, as shown in Figure 3-13.

Figure 3-13 Example of Unexpected MBean Tree Rendering

Example of Unexpected MBean Tree Rendering

To avoid this problem, you can specify the order in which the MBeans are displayed in the tree by supplying an ordered key property list when you start JConsole at the command line. This is achieved by setting the system property com.sun.tools.jconsole.mbeans.keyPropertyList, as shown in the following command.

% jconsole -J-Dcom.sun.tools.jconsole.mbeans.keyPropertyList=key[,key]*

The key property list system property takes a comma-separated list of keys, in the order of your choosing, where key must be a string representing an object name key or an empty string. If a key specified in the list does not apply to a particular MBean, then that key will be discarded. If an MBean has more keys than the ones specified in the key property list, then the key order defined by the value returned by ObjectName.getKeyPropertyListString() will be used to complete the key order defined by keyPropertyList. Therefore, specifying an empty list of keys simply means that JConsole will display keys in the order they appear in the MBean's ObjectName.

So, returning to the example of the Triangle MBeans cited above, you could choose to start JConsole specifying the keyPropertyList system property, so that all your MBeans will be grouped according to their side key property first, and their name key property second. To do this, you would start JConsole with the following command.

% jconsole -J-Dcom.sun.tools.jconsole.mbeans.keyPropertyList=side,name

Starting JConsole with this system property specified would produce the MBean tree shown in Figure 3-14.

Figure 3-14 Example of MBean Tree Constructed Using keyPropertyList

Example of MBean Tree Constructed Using keyPropertyList

In Figure 3-14, the side key comes first, followed by the name key. The type key comes at the end because it was not specified in the key property list, so the MBean tree algorithm applied the original key order for the remaining keys. Consequently, the type key is appended at the end, after the keys which were defined by the keyPropertyList system property.

According to the object name convention defined by the JMX Best Practices Guidelines, the type key should always come first. So, to respect this convention you should start JConsole with the following system property.

% jconsole -J-Dcom.sun.tools.jconsole.mbeans.keyPropertyList=type,side,name

The above command will cause JConsole to render the MBean tree for the Triangle MBeans as shown in Figure 3-15.

Figure 3-15 Example of MBean Tree Constructed Respecting JMX Best Practices

Example of MBean Tree Constructed Respecting JMX Best Practices

This is obviously much more comprehensible than the MBean trees shown in Figure 3-13 and Figure 3-14.

MBean Attributes

Selecting the Attributes node displays all the attributes of an MBean. Figure 3-16 shows all the attributes of the Threading platform MXBean.

Figure 3-16 Viewing All MBean Attributes

Viewing the attributes of the Threading MBean.

Selecting an individual MBean attribute from the tree then displays the attribute's value, its MBeanAttributeInfo, and the associated Descriptor in the right pane, as you can see in Figure 3-17.

Figure 3-17 Viewing an Individual MBean Attribute

Viewing MBean attributes in the MBeans tab.

You can display additional information about an attribute by double-clicking on the attribute value, if it appears in bold text. For example, if you click on the value of the HeapMemoryUsage attribute of the java.lang.Memory MBean, you will see a chart that looks something like Figure 3-18.

Figure 3-18 Displaying Attribute Values

Viewing the values of MBean attributes.

Double-clicking on numeric attribute values will display a chart that plots changes in that numeric value. For example, double-clicking on the CollectionTime attribute of the Garbage Collector MBean PS Marksweep will plot the time spent performing garbage collection.

You can also use JConsole to set the values of writable attributes. The value of a writable attribute is displayed in blue. Here you can see the Memory MBean's Verbose attribute.

Figure 3-19 Setting Writable Attribute Values

Setting an MBean's writable attribute value.

You can set attributes by clicking on them and then editing them. For example, to enable or disable the verbose tracing of the garbage collector in JConsole, select the Memory MXBean in the MBeans tab and set the Verbose attribute to true or false. Similarly, the class loading MXBean also has the Verbose attribute, which can be set to enable or disable class loading verbose tracing.

MBean Operations

Selecting the Operations node displays all the operations of an MBean. The MBean operations appear as buttons, that you can click to invoke the operation.Figure 3-20 shows all the operations of the Threading platform MXBean.

Figure 3-20 Viewing All MBean Operations

Viewing the Threading platform MXBean's operations.

Selecting an individual MBean operation in the tree displays the button for invoking the MBean operation, and the operation's MBeanOperationInfo and its Descriptor, as shown in Figure 3-21.

Figure 3-21 Viewing Individual MBean Operations

Invoking an MBean's operations.
MBean Notifications

You can subscribe to receive notifications by selecting the Notifications node in the left-hand tree, and clicking the Subscribe button that appears on the right. The number of notifications received is displayed in square brackets, and the Notifications node itself will appear in bold text when new notifications are received. The notifications of the Memory platform MXBean are shown in Figure 3-22.

Figure 3-22 Viewing MBean Notifications

Viewing an MBean's notifications.

Selecting an individual MBean notification displays the MBeanNotificationInfo in the right pane, as shown in Figure 3-23.

Figure 3-23 Viewing Individual MBean Notifications

Subscribing to receive MBean Notifications.
HotSpot Diagnostic MXBean

JConsole's MBeans tab also allows you to tell the HotSpot VM to perform a heap dump, and to get or set a VM option via the HotSpotDiagnostic MXBean.

Figure 3-24 Viewing the HotSpot Diagnostic MBean

Performing heap dumps using the HotSpot VM Diagnostic MBean.

You can perform a heap dump manually by invoking the com.sun.management.HotSpotDiagnostic MXBean's dumpHeap operation. In addition, you can specify the HeapDumpOnOutOfMemoryError Java VM option using the setVMOption operation, so that the VM performs a heap dump automatically whenever it receives an OutOfMemoryError.

Creating Custom Tabs

In addition to the existing standard tabs, you can add your own custom tabs to JConsole, to perform your own monitoring activities. The JConsole plug-in API provides a mechanism by which you can, for example, add a tab to access your own application's MBeans. The JConsole plug-in API defines the com.sun.tools.jconsole.JConsolePlugin abstract class that you can extend to build your custom plug-in.

As stated above, your plug-in must extend JConsolePlugin, and implement the JConsolePlugin getTabs and newSwingWorker methods. The getTabs method returns either the list of tabs to be added to JConsole, or an empty list. The newSwingWorker method returns the SwingWorker to be responsible for the plug-in's GUI update.

Your plug-in must be provided in a Java archive (JAR) file that contains a file named META-INF/services/com.sun.tools.jconsole.JConsolePlugin. This JConsolePlugin file itself contains a list of all the fully-qualified class names of the plug-ins you want to add as new JConsole tabs. JConsole uses the service-provider loading facility to look up and load the plug-ins. You can have multiple plug-ins, with one entry per plug-in in the JConsolePlugin.

To load the new custom plug-ins into JConsole, start JConsole with the following command:

%  jconsole -pluginpath plugin-path

In the above command, plugin-path specifies the paths to the JConsole plug-ins to be looked up. These paths can either be to directory names or to JAR files, and multiple paths can be specified, using your platform's standard separator character.

An example JConsole plug-in is provided with the Java SE 6 platform. The JTop application is a JDK demonstration that shows the CPU usage of all threads running in the application. This demo is useful for identifying threads that have high CPU consumption, and it has been updated to be used as a JConsole plug-in as well as a standalone GUI. JTop is bundled with the Java SE 6 platform, as a demo application. You can run JConsole with the JTop plug-in by running the following command:

% JDK_HOME/bin/jconsole -pluginpath JDK_HOME/demo/management/JTop/JTop.jar

If you connect to this instance of JConsole, you will see that the JTop tab has been added, showing CPU usage of the various threads running.

Figure 3-25 Viewing a Custom Plug-in Tab

A custom tab showing connected to the JTop example program.
previous Previous Contents Next next
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.tools.jconsole.JConsoleContext (JConsole API b138)

  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
JConsole API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.tools.jconsole.JConsoleContext

    • Uses of JConsoleContext in com.sun.tools.jconsole

      Methods in com.sun.tools.jconsole that return JConsoleContext
      Modifier and Type Method and Description
      JConsoleContext JConsolePlugin.getContext()
      Returns the JConsoleContext object representing the connection to an application.
      Methods in com.sun.tools.jconsole with parameters of type JConsoleContext
      Modifier and Type Method and Description
      void JConsolePlugin.setContext(JConsoleContext context)
      Sets the JConsoleContext object representing the connection to an application.
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
JConsole API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2006, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.tools.jconsole.JConsoleContext.ConnectionState (JConsole API b138)

  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
JConsole API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.tools.jconsole.JConsoleContext.ConnectionState

    • Uses of JConsoleContext.ConnectionState in com.sun.tools.jconsole

      Methods in com.sun.tools.jconsole that return JConsoleContext.ConnectionState
      Modifier and Type Method and Description
      JConsoleContext.ConnectionState JConsoleContext.getConnectionState()
      Returns the current connection state.
      static JConsoleContext.ConnectionState JConsoleContext.ConnectionState.valueOf(String name)
      Returns the enum constant of this type with the specified name.
      static JConsoleContext.ConnectionState[] JConsoleContext.ConnectionState.values()
      Returns an array containing the constants of this enum type, in the order they are declared.
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
JConsole API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2006, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.tools.jconsole.JConsolePlugin (JConsole API b138)

  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
JConsole API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.tools.jconsole.JConsolePlugin

No usage of com.sun.tools.jconsole.JConsolePlugin
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
JConsole API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2006, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Java Control Panel

The Java Control Panel is a multipurpose control panel. It allows you to view and set a wide range of parameters controlling how Java technology runs on your computer. It lets you view and delete temporary files used for Java Plug-in, which allows Java technology to be used by your Web browser to run applets; and Java Web Start, which allows you to run Java applications over the network. It allows you to control certificates, making it safe to run applets and applications over the network. It allows you to set runtime parameters for applets that run with Java Plug-in and applications that run with Java Web Start. It provides a mechanism for updating your version of the Java platform so that you always have the latest. And it allows you to set options for debugging, desktop integration, applet handling, etc. The Java Control Panel includes the following separately viewable panels:

Contents

  • General
  • Update
  • Java
  • Security
  • Advanced

General

The General panel looks like this:

It includes three subpanels: About, Network Settings, and Temporary Internet Files.

About

The About... button displays version information for the latest JRE installed on the computer.

Network Settings

These settings are for network connections. Press the Network Settings... button to get the Network Settings dialog. There are four choices:

Use browser settings

Check this to use the browser default proxy settings. This is the default setting (checked).

Use proxy server

You have two choices here:

  • You can set the Address and the Port for a proxy server with the option to bypass it for local addresses.
  • You can press the Advanced ... button to get the Advanced Network Settings dialog. In this panel you can individually set the proxy server for HTTP, Secure, FTP, and Socks connections. You can also provide a list of addresses for which you do not want to use a proxy server. The Advanced Network Settings panel looks like this:

Advanced Network Settings panel

Use automatic proxy configuration script

You can specify the location (URL) for the JavaScript file (.js or .pac extension) that contains the FindProxyForURL function. FindProxyForURL has the logic to determine the proxy server to use for a connection request.

Direct Connection

Select this for situations where you do not want to use a proxy.

Temporary Internet Files

You can do the following:

  • Press the Settings... button to get the Temporary Files Settings dialog from which you can perform the following:
    • Specify if you want to keep temporary files on your computer.
    • Specify the location where temporary files are kept.
    • Specify the compression level for JAR files.
    • Specify the amount of disk space for storing temporary files.
    • Delete temporary files by pressing the Delete Files... button, which displays the Delete Temporary Files dialog. From this dialog, you can specify which files you want to delete:
      • Trace and Log Files
      • Cached Applications and Applets
      • Installed Applications and Applets
    • Restore default settings for the Temporary Files Settings dialog by pressing the Restore Defaults button.
  • Press the View... button to get the Java Cache Viewer dialog. This dialog enables you to list applications, resources, and deleted applications stored in the Java cache. In addition, you may perform the following:
    • Run and visit the Web page of applications.
    • View the JNLP file of applications and resources.

Update

The Update panel looks like this:

Note

This panel is only available on Windows for 1.4.2_01 and higher releases and only for users with Administrative privileges.

The Update panel, in conjunction with the Java Update Scheduler (jusched.exe), is used to provide the latest Java updates to the end user.

Update Panel Options

There are two basic options on the Update tab:

  • Automatic update: Available only on Windows XP, 2003, 2000 (SP2 or higher) and set by default for those operating systems
  • Manual update

Automatic update is performed on a scheduled basis and it is selected by checking the Check for Updates Automatically check box.

Manual update is performed by pressing the Update Now button.

If you select automatic update, you can then set the notification via the Notify Me: drop-down menu, and you can set the update schedule via the Advanced... button.

With notification, you can chose to be notified before an update is downloaded and before it is installed; or you can chose to be notified only before an update is installed (i.e., the download is automatic).

The Advanced... allows you to select the desired frequency for updates: daily, weekly (default), or monthly. For daily updates, you can select the time of the day for the update; for weekly updates, you can select the day of the week and the time of the day; for monthly updates, you can select the day of the month and the time of the day.

You can do manual updates at any time by pressing the Update Now button. This allows you to do immediate, unscheduled updates.

Java Update Scheduler

The Java Update Scheduler (jusched.exe) is used for launching automatic updates when Update Automatically is selected in the Update tab. jusched.exe runs as a background process that launches the Update Manager at predefined intervals set by the user through the Advanced... button of the Update tab. The Update Manager coordinates the update process.

jusched.exe is launched when the user reboots the computer after installing the SDK/JRE. It is normally transparent to the user but can be viewed in the Processes tab of the Windows Task Manager. Should a user for some reason not want the scheduler to run, it can be killed via End Process button of the Processes tab.

Java

The Java panel looks like this:

Click the View... button to access the Java Runtime Environment Settings dialog.

Java Runtime Environment Settings

These settings will be used when a Java application is launched. The Java Runtime Environment Settings dialog looks like the following on Windows:

Java Runtime Environment Settings dialog

Note that on Unix there will also be Add and Remove buttons.

Notes

There will always be at least one entry. It will be the most recently installed JRE; i.e., the JRE associated with the Java Control Panel.

Windows will show all JREs installed on a computer. The Java Control Panel finds the JREs by looking in the registry. On Unix the situation is different. There is no registry so there is no easy way to find the JREs that a user may have installed. Thus, for Unix there are Add and Remove buttons.

For Unix, only version 5.0 or higher should be added. For Windows, where all JREs are found in the registry, only version 5.0 or higher will be displayed.

Example:

Assume you are running on Microsoft Windows with Microsoft Internet Explorer, have first installed version 1.4.2, then version 5.0, and you want to run 1.4.2.

  1. Go to the j2re1.4.2\bin directory where JRE 1.4.2 was installed. On a Windows default installation, this would be here: C:\Program Files\Java\j2re1.4.2\bin
  2. Double-click the jpicpl32.exe file located there. It will launch the control panel for 1.4.2.
  3. Select the Browser tab. Microsoft Internet Explorer might still appear to be set (checked). However, when 5.0 was installed, the registration of the 1.4.2 JRE with Internet Explorer was overwritten by the 5.0 JRE.
  4. If Microsoft Internet Explorer is shown as checked, uncheck it and click Apply. You will see a confirmation dialog stating that browser settings have changed.
  5. Check Microsoft Internet Explorer and click Apply. You should see a confirmation dialog.
  6. Restart the browser. It should now use the 1.4.2 JRE for conventional APPLET tags.

On Unix you can add a JRE by pressing Add and specifying its location (see notes above).

For Window and Unix you can optionally set Java Runtime Settings for the JRE.

Java Runtime Parameters

You can override the Java Plug-in default startup parameters by specifying custom options in the Java Runtime Parameters field. With the exception of setting classpath and cp (see Setting classpath and cp below), the syntax is the same as used with parameters to the java command line invocation. See the java launcher for a full list of command line options:

java launcher: Windows, Solaris and Linux.

Below are some examples of Java runtime parameters.

Setting classpath and cp

The following format should be used for setting classpath and cp in Java Plug-in. It differs slightly from the java command line format, which uses a space instead of the equal (=) sign.

-classpath=<path>
-cp=<path>

Enabling and disabling assertion support

To enable assertion support, the following system property must be specified in the Java Runtime Parameters:

-[ enableassertions | ea ][:<package name>"..." | : <class name> ]

To disable assertion in the Java Plug-in, specify the following in the Java Runtime Parameters:

-[ disableassertions | da ][:<package name>"..." | : <class name> ]

See Assertion Facility for more details on enabling/disabling assertions.

Assertion is disabled in Java Plug-in code by default. Since the effect of assertion is determined during Java Plug-in startup, changing assertion settings in the Java Plug-in Control Panel will require a browser restart in order for the new settings to take effect.

Because Java code in Java Plug-in also has built-in assertion, it is possible to enable the assertion in Java Plug-in code through the following:

-[ enableassertions | ea ]:sun.plugin

Tracing and logging support

Tracing is a facility to redirect any output in the Java Console to a trace file (.plugin<version>.trace).

-Djavaplugin.trace=true
-Djavaplugin.trace.option=basic|net|security|ext|liveconnect

If you do not want to use the default trace file name:

-Djavaplugin.trace.filename=<tracefilename>

Similar to tracing, logging is a facility to redirect any output in the Java Console to a log file (.plugin<version>.log) using the Java Logging API. Logging can be turned on by enabling the property javaplugin.logging.

-Djavaplugin.logging=true

If you do not want to use the default log file name, enter:

-Djavaplugin.log.filename=<logfilename>

Furthermore, if you do not want to overwrite the trace and log files each session, you can set the property:

-Djavaplugin.outputfiles.overwrite=false

If the property is set to false, then trace and log files will be uniquely named for each session. If the default trace and log file names are used, then the files would be named as follows

.plugin<username><date hash code>.trace
.plugin<username><date hash code>.log

Tracing and logging set through the Control Panel will take effect when the Plug-in is launched, but changes made through the Control Panel while a Plug-in is running will have no effect until a restart.

For more information about tracing and logging, see the chapter called Tracing and Logging.

Debugging applets in Java Plug-in

The following options are used when debugging applets in the Java Plug-in. For more information on this topic see the Debugging Support in the Java Plug-in Developer Guide.

-Djava.compiler=NONE
-Xnoagent
-Xdebug
-Xrunjdwp:transport=dt_shmem,address=<connect-address>,server=y,suspend=n

The <connect-address> can be any string (example: 2502) which is used by the Java Debugger (jdb) later to connect to the JVM

Default connection timeout

When a connection is made by an applet to a server and the server doesn't respond properly, the applet may appear to hang and may also cause the browser to hang, since by default there is no network connection timeout.

To avoid this problem, Java Plug-in 1.4 has added a default network timeout value (2 minutes) for all HTTP connections. You can override this setting in the Java Runtime Parameters:

-Dsun.net.client.defaultConnectTimeout=<value in
milliseconds>

Another networking property that you can set is sun.net.client.defaultReadTimeout.

-Dsun.net.client.defaultReadTimeout=<value in milliseconds>

Note

Java Plug-in does not set sun.net.client.defaultReadTimeout by default. If you want to set it, do so through the Java Runtime Parameters as shown above.

Networking properties description:

sun.net.client.defaultConnectTimeout
sun.net.client.defaultReadTimeout

These properties specify, respectively, the default connect and read timeout values for the protocol handlers used by java.net.URLConnection. The default value set by the protocol handlers is -1, which means there is no timeout set.

sun.net.client.defaultConnectTimeout specifies the timeout (in milliseconds) to establish the connection to the host. For example, for http connections it is the timeout when establishing the connection to the http server. For ftp connections it is the timeout when establishing the connection to ftp servers.

sun.net.client.defaultReadTimeout specifies the timeout (in milliseconds) when reading from an input stream when a connection is established to a resource.

For the official description of these properties, see Networking Properties.

Security

Notes

  1. Some information in this section depends on an understanding of System- and User-Level Properties Files. Please read that section.
  2. System-Level keystore files do not exist by default; they are created and managed by a System Administrator using keytool. (See Security Tools.)

The Security panel looks like this:

Press the Certificates... button to get the Certificates dialog, which looks like this:

Certificate Types

It handles both User- and System-Level (enterprise-wide) certificates of the following types:

  • Trusted
  • Secure Site
  • Signer CA
  • Secure site CA
  • Client Authentication

Trusted Certificates

These are certificates for signed applets and applications that are trusted.

Secure site

These are certificates for secure sites.

Signer CA

These are certificates of Certificate Authorities (CAs) for Trusted Certificates; Certificate Authorities are the ones who issue the certificates to the signers of Trusted Certificates.

Secure site CA

These are certificates of Certificate Authorities (CAs) for secure sites; Certificate Authorities are the ones who issue the certificates for secure sites.

Client Authentication

These are certificates for a client to authenticate itself to a server.

User-Level Certificates

Options

For Trusted, Secure site, and Client Authentication certificates, there are four options: Import, Export, Remove, and Details. The user can import, export, remove, and view the details of a certificate.

For Signer CA and Secure site CA, there is only one option: Details. The user can only view the details of a certificate.

Default Keystore Location

The default locations of the of the keystore files for Unix and Windows are as follows:

Operating System | Location
Unix | ${user.home}/.java/deployment/security.
Windows | ${deployment.user.home}\security

For instance, on Windows 2000/XP, the default location of the keystore files for user jsmith would be as follows:

C:\Documents and Settings\jsmith\ApplicationData\Sun\Java\Deployment\security

Non-Default Keystore Location

For non-default locations of the certificate keystore files, specify them in the User-Level deployment.properties file with the following property names:

Certificate Type | Property Name
Trusted Certificates | deployment.user.security.trusted.certs
Secure site | deployment.user.security.trusted.jssecerts
Signer CA | deployment.user.security.trusted.cacerts
Secure site CA | deployment.user.security. trusted.jssecacerts
Client Authentication | deployment.user.security.trusted.clientcerts

System-Level Certificates

Options

For System-Level certificates, the only options a user has are Export and Details.

Default Keystore Location

Trusted, Secure Site, and Client Authentication certificate keystore files do not exist by default. Thus there are no default locations for them.

The default location for the Signer CA keystore is:

Operating System | Location
Unix | $JAVA_HOME/lib/security/cacerts
Windows | $JAVA_HOME\lib\security\cacerts

The default location for the Secure Site CA keystore is:

Operating System | Location
Unix | $JAVA_HOME/lib/security/jssecacerts
Windows | $JAVA_HOME\lib\security\jssecacerts

Non-Default Keystore Location

The location of the keystore files for the various types of certificates can also be set in a System-Level deployment.properties file, if it exists. (The System-Level deployment.properties file does not exist by default. It is specified in a deployment.config file. See System-Level deployment.properties file.) The following properties may be specified:

Certificate Type | Property Name
Trusted Certificates | deployment.system.security.trusted.certs
Secure site | deployment.system.security.trusted.jssecerts
Signer CA | deployment.system.security.trusted.cacerts
Secure site CA | deployment.system.security. trusted.jssecacerts
Client Authentication | deployment.system.security.trusted.clientcerts

Advanced

The Advanced panel looks like this:

It includes options for Debugging, Java console, Default Java for Browsers, Java Plug-in, JavaFX Client Stack, Shortcut creation, JNLP File/MIME Association, Application Installation, JRE Auto-Download, Security, and Miscellaneous.

Debugging

You can enable tracing and logging. For more information on tracing and logging and how to set runtime parameters for tracing and logging, see Tracing and Logging.

Java Console

There are three options:

  • Show the console
  • Hide the console (default)
  • Do not start the console

See Java Console for information about it.

Default Java for Browsers

There are two options; both are selected by default:

  • Microsoft Internet Explorer
  • Mozilla Family

This option enables settings in your browser that enable you to use the JRE installed in your computer.

For example, if you enable this option for Microsoft Internet Explorer, then the option Use JRE <version number> for <applet> (requires restart) is available, where <version number> is the version of the JRE installed in your computer. (Find this option by going to Tools, then Internet Options, then click the tab Advanced.)

In addition, if you enable this option for Mozilla Family, and your browser is Firefox, then the extension Java Console <version number> appears in the Add-ons list, where <version number> is the version of the JRE installed in your computer. (Access the Add-ons list from the Tools menu in the menu bar.)

Java Plug-in

There is only one option, which is selected by default: Enable the next-generation Java Plug-in (requires browser restart).

If this option is selected, then the implementation of the Java Plug-In introduced in Java SE 6 update 10 is used. If this option is not selected, the Java Plug-In implementation prior to the one introduced in Java SE 6u10 is used.

JavaFX Client Stack (Windows only)

There is only one option, which is selected by default: Enable JavaFX Client Stack. Use this option to enable or disable JavaFX.

Shortcut Creation (Windows only)

This provides options for Java Web Start for creating shortcuts on the desktop. The options are:

  • Always allow
  • Always allow if hinted
  • Prompt user
  • Prompt user if hinted (default)
  • Never allow

JNLP File/MIME Association (Windows only)

This allows you to associate files with the JNLP MIME type. The options are (radio button, select only one):

  • Always allow
  • Prompt user (default)
  • Never allow

Application Installation

There are four options:

  • Install if hinted (default)
  • Install if shortcut created
  • Install if hinted and shortcut
  • Never install

A Java application or applet that is launched with Java Web Start can either be installed or cached on the client computer. If the Java application is cached, then Java Web Start stores the entire application in its cache; the application is removed from the client computer when Java Web Start empties its cache. If the Java application is installed, then the application will have an entry in the Add or Remove Programs applet in Windows Control Panel.

A Java application or applet can specify if it prefers to be cached or installed; if the Java application specifies that it prefers to be installed, then it is hinted. By default, Java applications that are hinted are installed on the client computer. You can also specify that a Java application is installed if it creates a shortcut on the client computer's desktop.

JRE Auto-Download

There are three options:

  • Always Auto-Download (default)
  • Prompt user
  • Never Auto-Download

If a JNLP file requests a JRE that is not installed, then this option specifies what action is performed.

Security

The General options are check boxes. You can select any number of available options. All options are checked by default except for those specified. The Mixed code options are radio buttons. You can select only one option. The following are the various Java security options:

  • General: The following options are check boxes:
    • Allow user to grant permissions to signed content
    • Allow user to grant permissions to content from an untrusted authority
    • Use certificates and keys in browser keystore
    • Don't prompt for client certificate selection when no certificates or only one exists
    • Warn if site certification does not match host name
    • Show site certificate from server even if it is valid (not checked by default)
    • Show sandbox warning banner
    • Allow user to accept JNLP security requests
    • Check certificates for revocation using Certificate Revocation Lists (CRLs) (not checked by default) (not checked by default)
    • Enable online certificate validation (not checked by default) (not checked by default)
    • Enable list of trusted publishers
    • Enable blacklist revocation check
    • Enable caching password for authentication
    • Use SSL 2.0 compatible ClientHello format (not checked by default)
    • Use SSL 3.0
    • Use TLS 1.0
    • Use TLS 1.1 (not checked by default)
  • Mixed code (sandboxed vs. trusted) security verification
    • Enable - show warning if needed (selected by default)
    • Enable - hide warning and don't run untrusted code
    • Enable - hide warning and don't run untrusted code
    • Disable verification (not recommended)

Miscellaneous (Window only)

There are two options; both are checked by default:

  • Place Java icon in system tray
  • Java Quick Starter

Command to launch default browser (Unix only, not shown above)

Allows you to specify the location of the default browser to be launched.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Platform Debugger Architecture

As a demonstration of the Java Debug Interface (JDI), we are providing source code for the jdb debugger.

jdb man pages

jdb man pages for Windows

jdb man pages for Solaris

Invoking jdb

The jdb sample can be run by executing:

   java tty.TTY <options>.. <class-name>
where <class-name> is the name you would normally place on the java command line. The -help option provides information on options. Note: Be sure that the Java 2 SDK's lib/tools.jar file is on the class path used to invoke tty.TTY. The tools.jar file includes the JDI Library and to the compiled jdb class files.

For more information on invoking and connecting see Connection and Invocation Details section of the JPDA documentation, particularly the section on jdb.

Source for jdb

Full source code for jdb is included as part of the example code in the Java 2 SDK's lib/jpda directory, in examples.jar. (Use jar xvf examples.jar to extract the contents of examples.jar.) Note: this file also includes the source for javadt. Source code of these example application is included to provide concrete examples for debugger developers. Example code may be used, modified and redistributed by debugger developers providing they adhere to the terms in the copyright notice.

jdb uses the following packages (found in the examples.jar file):

tty
Application code
expr
Expression processing code

Building jdb

To completely rebuild the jdb classes from the provided source files, you need only to compile them. No special options are required, aside from those which set your classpath to include the JDI Library. However, if want to modify the expression parser in the file Expr.jj, you will need the JavaCC parser generator.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JDBC 4.1

JDBC 4.1, which is part of Java SE 7, introduces the following features:

  • The ability to use a try-with-resources statement to automatically close resources of type Connection, ResultSet, and Statement
  • RowSet 1.1: The introduction of the RowSetFactory interface and the RowSetProvider class, which enable you to create all types of row sets supported by your JDBC driver.

Using try-with-resources Statements to Automatically Close JDBC Resources

You can use a try-with-resources statement to automatically close java.sql.Connection, java.sql.Statement, and java.sql.ResultSet objects, regardless of whether a SQLException or any other exception has been thrown. A try-with-resources statement consists of a try statement and one or more declared resources (which are separated by semicolons).

See The try-with-resources Statement for more information

The following example uses a try-with-resources statement to close the Statement object, stmt, automatically:

  public static void viewTable(Connection con) throws SQLException {

    String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";

    try (Statement stmt = con.createStatement()) {

      ResultSet rs = stmt.executeQuery(query);

      while (rs.next()) {
        String coffeeName = rs.getString("COF_NAME");
        int supplierID = rs.getInt("SUP_ID");
        float price = rs.getFloat("PRICE");
        int sales = rs.getInt("SALES");
        int total = rs.getInt("TOTAL");
        System.out.println(coffeeName + ", " + supplierID + ", " + price +
                           ", " + sales + ", " + total);
      }

    } catch (SQLException e) {
      JDBCTutorialUtilities.printSQLException(e);
    }
  }

The following statement is a try-with-resources statement that declares one resource, stmt, which will be automatically closed then the try block terminates:

    try (Statement stmt = con.createStatement()) {

      // ...

    }

RowSet 1.1: Creating Row Sets with RowSetFactory Interface and RowSetProvider Class

You can use an instance of RowSetFactory to create a RowSet object. The following example uses an instance of RowSetFactory to create the JdbcRowSet object, jdbcRs:

  public void testJdbcRowSet() throws SQLException {

    RowSetFactory myRowSetFactory = null;
    JdbcRowSet jdbcRs = null;
    ResultSet rs = null;
    Statement stmt = null;

    try {

      myRowSetFactory = RowSetProvider.newFactory();
      jdbcRs = myRowSetFactory.createJdbcRowSet();

      jdbcRs.setUrl("jdbc:myDriver:myAttribute");
      jdbcRs.setUsername("username");
      jdbcRs.setPassword("password");

      jdbcRs.setCommand("select * from COFFEES");
      jdbcRs.execute();

      // ...

The following statement creates the RowSetProvider object myRowSetFactory with the default RowSetFactory implementation, com.sun.rowset.RowSetFactoryImpl:

      myRowSetFactory = RowSetProvider.newFactory();

Alternatively, if your JDBC driver has its own RowSetFactory implementation, you can specify it as an argument of newFactory.

The following statements create the JdbcRowSet object jdbcRs and configure its database connection properties:

      jdbcRs = myRowSetFactory.createJdbcRowSet();

      jdbcRs.setUrl("jdbc:myDriver:myAttribute");
      jdbcRs.setUsername("username");
      jdbcRs.setPassword("password");

The RowSetFactory interface contains methods to create the different types of RowSet implementations available in JDBC 4.1 and later:

  • createCachedRowSet
  • createFilteredRowSet
  • createJdbcRowSet
  • createJoinRowSet
  • createWebRowSet
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.jdi.JDIPermission (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.JDIPermission

No usage of com.sun.jdi.JDIPermission
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


JDK File Structure for Windows

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

JDK and JRE File Structure

This page provides an introductory overview of the JDK directories and the files they contain. Note that the file structure of the JRE is identical to that of the JDK's jre directory.

Development Files and Directories

This section describes the most important files and directories required to develop applications for the Java platform.

(Note that some of the directories that are not required include demos, Java source code, and C header files. These are mentioned in the Additional Files and Directories section.)

Assuming the JDK software is installed at c:\jdk1.7.0, here are some of the most important directories:

c:\jdk1.7.0
Root directory of the JDK software installation. Contains copyright, license, and README files. Also contains src.zip, the archive of source code for the Java platform.
c:\jdk1.7.0\bin
Executable files for the development tools contained in the Java Development Kit. The PATH environment variable should contain an entry for this directory. For more information on the tools, see the JDK Tools.
c:\jdk1.7.0\lib
Files used by the development tools. These include tools.jar, which contains non-core classes for support of the tools and utilities in the JDK. Also includes dt.jar, the DesignTime archive of BeanInfo files that tell interactive development environments (IDE's) how to display the Java components and how to let the developer customize them for an application.
c:\jdk1.7.0\jre
Root directory of the Java runtime environment used by the JDK development tools. The runtime environment is an implementation of the Java platform. This is the directory represented by the java.home system property.
c:\jdk1.7.0\jre\bin
Executable files and DLLs for tools and libraries used by the Java platform. The executable files are identical to files in /jdk1.7.0/bin. The java launcher tool serves as an application launcher (and replaced the old jre tool that shipped with 1.1 versions of the JDK). This directory does not need to be in the PATH environment variable.
c:\jdk1.7.0\jre\bin\client
Contains the DLL files used by the Java HotSpot™ Client Virtual Machine.
c:\jdk1.7.0\jre\bin\server
Contains the DLL files used by the Java HotSpot™ Server Virtual Machine.
c:\jdk1.7.0\jre\lib
Code libraries, property settings, and resource files used by the Java runtime environment. For example:
  • rt.jar -- the bootstrap classes (the RunTime classes that comprise the Java platform's core API).
  • charsets.jar -- character conversion classes.
Aside from the ext subdirectory (described below) there are several additional resource subdirectories not described here.
c:\jdk1.7.0\jre\lib\ext
Default installation directory for Extensions to the Java platform.
  • localedata.jar -- locale data for java.text and java.util.
c:\jdk1.7.0\jre\lib\security
Contains files used for security management. These include the security policy (java.policy) and security properties (java.security) files.
c:\jdk1.7.0\jre\lib\applet
Jar files containing support classes for applets can be placed in the lib/applet/ directory. This reduces startup time for large applets by allowing applet classes to be pre-loaded from the local file system by the applet class loader, providing the same protections as if they had been downloaded over the net.
c:\jdk1.7.0\jre\lib\fonts
Contains TrueType font files for use by the platform.

Additional Files and Directories

This section describes the directory structure for the demos, Java source code, and C header files.

The additional directories shown above are:

c:\jdk1.7.0\src.zip
Archive containing source code for the Java platform.
c:\jdk1.7.0\demo
Examples, with source code, that show you how to program for the Java platform.
c:\jdk1.7.0\demo\applets
Applets that can be used on a web page.
c:\jdk1.7.0\demo\jfc
Examples that use Java 2D™ and JFC\Swing functionality.
c:\jdk1.7.0\demo\jpda
Examples of using the Java Platform Debugging Architecture. Includes source code for the javadt and jdb utilities.
c:\jdk1.7.0\demo\plugin
Contains demos for use with the Java Plug-in product.
c:\jdk1.7.0\include
C-language header files that support native-code programming using the Java Native Interface and the Java Virtual Machine Debugger Interface.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java(tm) Debug Wire Protocol

  • VirtualMachine Command Set (1)
    • Version (1)
    • ClassesBySignature (2)
    • AllClasses (3)
    • AllThreads (4)
    • TopLevelThreadGroups (5)
    • Dispose (6)
    • IDSizes (7)
    • Suspend (8)
    • Resume (9)
    • Exit (10)
    • CreateString (11)
    • Capabilities (12)
    • ClassPaths (13)
    • DisposeObjects (14)
    • HoldEvents (15)
    • ReleaseEvents (16)
    • CapabilitiesNew (17)
    • RedefineClasses (18)
    • SetDefaultStratum (19)
    • AllClassesWithGeneric (20)
    • InstanceCounts (21)
  • ReferenceType Command Set (2)
    • Signature (1)
    • ClassLoader (2)
    • Modifiers (3)
    • Fields (4)
    • Methods (5)
    • GetValues (6)
    • SourceFile (7)
    • NestedTypes (8)
    • Status (9)
    • Interfaces (10)
    • ClassObject (11)
    • SourceDebugExtension (12)
    • SignatureWithGeneric (13)
    • FieldsWithGeneric (14)
    • MethodsWithGeneric (15)
    • Instances (16)
    • ClassFileVersion (17)
    • ConstantPool (18)
  • ClassType Command Set (3)
    • Superclass (1)
    • SetValues (2)
    • InvokeMethod (3)
    • NewInstance (4)
  • ArrayType Command Set (4)
    • NewInstance (1)
  • InterfaceType Command Set (5)
  • Method Command Set (6)
    • LineTable (1)
    • VariableTable (2)
    • Bytecodes (3)
    • IsObsolete (4)
    • VariableTableWithGeneric (5)
  • Field Command Set (8)
  • ObjectReference Command Set (9)
    • ReferenceType (1)
    • GetValues (2)
    • SetValues (3)
    • MonitorInfo (5)
    • InvokeMethod (6)
    • DisableCollection (7)
    • EnableCollection (8)
    • IsCollected (9)
    • ReferringObjects (10)
  • StringReference Command Set (10)
    • Value (1)
  • ThreadReference Command Set (11)
    • Name (1)
    • Suspend (2)
    • Resume (3)
    • Status (4)
    • ThreadGroup (5)
    • Frames (6)
    • FrameCount (7)
    • OwnedMonitors (8)
    • CurrentContendedMonitor (9)
    • Stop (10)
    • Interrupt (11)
    • SuspendCount (12)
    • OwnedMonitorsStackDepthInfo (13)
    • ForceEarlyReturn (14)
  • ThreadGroupReference Command Set (12)
    • Name (1)
    • Parent (2)
    • Children (3)
  • ArrayReference Command Set (13)
    • Length (1)
    • GetValues (2)
    • SetValues (3)
  • ClassLoaderReference Command Set (14)
    • VisibleClasses (1)
  • EventRequest Command Set (15)
    • Set (1)
    • Clear (2)
    • ClearAllBreakpoints (3)
  • StackFrame Command Set (16)
    • GetValues (1)
    • SetValues (2)
    • ThisObject (3)
    • PopFrames (4)
  • ClassObjectReference Command Set (17)
    • ReflectedType (1)
  • Event Command Set (64)
    • Composite (100)
  • Error Constants
  • EventKind Constants
  • ThreadStatus Constants
  • SuspendStatus Constants
  • ClassStatus Constants
  • TypeTag Constants
  • Tag Constants
  • StepDepth Constants
  • StepSize Constants
  • SuspendPolicy Constants
  • InvokeOptions Constants

    VirtualMachine Command Set (1)

    Version Command (1)
    Returns the JDWP version implemented by the target VM. The version string format is implementation dependent.
    Out Data
    (None)
    Reply Data
    string | description | Text information on the VM version
    int | jdwpMajor | Major JDWP Version number
    int | jdwpMinor | Minor JDWP Version number
    string | vmVersion | Target VM JRE version, as in the java.version property
    string | vmName | Target VM name, as in the java.vm.name property
    Error Data
    VM_DEAD The virtual machine is not running.
    ClassesBySignature Command (2)
    Returns reference types for all the classes loaded by the target VM which match the given signature. Multple reference types will be returned if two or more class loaders have loaded a class of the same name. The search is confined to loaded classes only; no attempt is made to load a class of the given signature.
    Out Data
    string signature JNI signature of the class to find (for example, "Ljava/lang/String;").
    Reply Data
    int | classes | Number of reference types that follow.
    Repeated classes times:
    byte | refTypeTag | Kind of following reference type.
    referenceTypeID | typeID | Matching loaded reference type
    int | status | The current class status.
    Error Data
    VM_DEAD The virtual machine is not running.
    AllClasses Command (3)
    Returns reference types for all classes currently loaded by the target VM.
    Out Data
    (None)
    Reply Data
    int | classes | Number of reference types that follow.
    Repeated classes times:
    byte | refTypeTag | Kind of following reference type.
    referenceTypeID | typeID | Loaded reference type
    string | signature | The JNI signature of the loaded reference type
    int | status | The current class status.
    Error Data
    VM_DEAD The virtual machine is not running.
    AllThreads Command (4)
    Returns all threads currently running in the target VM . The returned list contains threads created through java.lang.Thread, all native threads attached to the target VM through JNI, and system threads created by the target VM. Threads that have not yet been started and threads that have completed their execution are not included in the returned list.
    Out Data
    (None)
    Reply Data
    int | threads | Number of threads that follow.
    Repeated threads times:
    threadID | thread | A running thread
    Error Data
    VM_DEAD The virtual machine is not running.
    TopLevelThreadGroups Command (5)
    Returns all thread groups that do not have a parent. This command may be used as the first step in building a tree (or trees) of the existing thread groups.
    Out Data
    (None)
    Reply Data
    int | groups | Number of thread groups that follow.
    Repeated groups times:
    threadGroupID | group | A top level thread group
    Error Data
    VM_DEAD The virtual machine is not running.
    Dispose Command (6)
    Invalidates this virtual machine mirror. The communication channel to the target VM is closed, and the target VM prepares to accept another subsequent connection from this debugger or another debugger, including the following tasks:
    • All event requests are cancelled.
    • All threads suspended by the thread-level resume command or the VM-level resume command are resumed as many times as necessary for them to run.
    • Garbage collection is re-enabled in all cases where it was disabled
    Any current method invocations executing in the target VM are continued after the disconnection. Upon completion of any such method invocation, the invoking thread continues from the location where it was originally stopped.

    Resources originating in this VirtualMachine (ObjectReferences, ReferenceTypes, etc.) will become invalid.

    Out Data
    (None)
    Reply Data
    (None)
    Error Data
    (None)
    IDSizes Command (7)
    Returns the sizes of variably-sized data types in the target VM.The returned values indicate the number of bytes used by the identifiers in command and reply packets.
    Out Data
    (None)
    Reply Data
    int | fieldIDSize | fieldID size in bytes
    int | methodIDSize | methodID size in bytes
    int | objectIDSize | objectID size in bytes
    int | referenceTypeIDSize | referenceTypeID size in bytes
    int | frameIDSize | frameID size in bytes
    Error Data
    VM_DEAD The virtual machine is not running.
    Suspend Command (8)
    Suspends the execution of the application running in the target VM. All Java threads currently running will be suspended.

    Unlike java.lang.Thread.suspend, suspends of both the virtual machine and individual threads are counted. Before a thread will run again, it must be resumed through the VM-level resume command or the thread-level resume command the same number of times it has been suspended.

    Out Data
    (None)
    Reply Data
    (None)
    Error Data
    VM_DEAD The virtual machine is not running.
    Resume Command (9)
    Resumes execution of the application after the suspend command or an event has stopped it. Suspensions of the Virtual Machine and individual threads are counted. If a particular thread is suspended n times, it must resumed n times before it will continue.
    Out Data
    (None)
    Reply Data
    (None)
    Error Data
    (None)
    Exit Command (10)
    Terminates the target VM with the given exit code. On some platforms, the exit code might be truncated, for example, to the low order 8 bits. All ids previously returned from the target VM become invalid. Threads running in the VM are abruptly terminated. A thread death exception is not thrown and finally blocks are not run.
    Out Data
    int exitCode the exit code
    Reply Data
    (None)
    Error Data
    (None)
    CreateString Command (11)
    Creates a new string object in the target VM and returns its id.
    Out Data
    string utf UTF-8 characters to use in the created string.
    Reply Data
    stringID stringObject Created string (instance of java.lang.String)
    Error Data
    VM_DEAD The virtual machine is not running.
    Capabilities Command (12)
    Retrieve this VM's capabilities. The capabilities are returned as booleans, each indicating the presence or absence of a capability. The commands associated with each capability will return the NOT_IMPLEMENTED error if the cabability is not available.
    Out Data
    (None)
    Reply Data
    boolean | canWatchFieldModification | Can the VM watch field modification, and therefore can it send the Modification Watchpoint Event?
    boolean | canWatchFieldAccess | Can the VM watch field access, and therefore can it send the Access Watchpoint Event?
    boolean | canGetBytecodes | Can the VM get the bytecodes of a given method?
    boolean | canGetSyntheticAttribute | Can the VM determine whether a field or method is synthetic? (that is, can the VM determine if the method or the field was invented by the compiler?)
    boolean | canGetOwnedMonitorInfo | Can the VM get the owned monitors infornation for a thread?
    boolean | canGetCurrentContendedMonitor | Can the VM get the current contended monitor of a thread?
    boolean | canGetMonitorInfo | Can the VM get the monitor information for a given object?
    Error Data
    VM_DEAD The virtual machine is not running.
    ClassPaths Command (13)
    Retrieve the classpath and bootclasspath of the target VM. If the classpath is not defined, returns an empty list. If the bootclasspath is not defined returns an empty list.
    Out Data
    (None)
    Reply Data
    string | baseDir | Base directory used to resolve relative paths in either of the following lists.
    int | classpaths | Number of paths in classpath.
    Repeated classpaths times:
    string | path | One component of classpath
    int | bootclasspaths | Number of paths in bootclasspath.
    Repeated bootclasspaths times:
    string | path | One component of bootclasspath
    Error Data
    VM_DEAD The virtual machine is not running.
    DisposeObjects Command (14)
    Releases a list of object IDs. For each object in the list, the following applies. The count of references held by the back-end (the reference count) will be decremented by refCnt. If thereafter the reference count is less than or equal to zero, the ID is freed. Any back-end resources associated with the freed ID may be freed, and if garbage collection was disabled for the object, it will be re-enabled. The sender of this command promises that no further commands will be sent referencing a freed ID.

    Use of this command is not required. If it is not sent, resources associated with each ID will be freed by the back-end at some time after the corresponding object is garbage collected. It is most useful to use this command to reduce the load on the back-end if a very large number of objects has been retrieved from the back-end (a large array, for example) but may not be garbage collected any time soon.

    IDs may be re-used by the back-end after they have been freed with this command.This description assumes reference counting, a back-end may use any implementation which operates equivalently.

    Out Data
    int | requests | Number of object dispose requests that follow
    Repeated requests times:
    objectID | object | The object ID
    int | refCnt | The number of times this object ID has been part of a packet received from the back-end. An accurate count prevents the object ID from being freed on the back-end if it is part of an incoming packet, not yet handled by the front-end.
    Reply Data
    (None)
    Error Data
    (None)
    HoldEvents Command (15)
    Tells the target VM to stop sending events. Events are not discarded; they are held until a subsequent ReleaseEvents command is sent. This command is useful to control the number of events sent to the debugger VM in situations where very large numbers of events are generated. While events are held by the debugger back-end, application execution may be frozen by the debugger back-end to prevent buffer overflows on the back end. Responses to commands are never held and are not affected by this command. If events are already being held, this command is ignored.
    Out Data
    (None)
    Reply Data
    (None)
    Error Data
    (None)
    ReleaseEvents Command (16)
    Tells the target VM to continue sending events. This command is used to restore normal activity after a HoldEvents command. If there is no current HoldEvents command in effect, this command is ignored.
    Out Data
    (None)
    Reply Data
    (None)
    Error Data
    (None)
    CapabilitiesNew Command (17)
    Retrieve all of this VM's capabilities. The capabilities are returned as booleans, each indicating the presence or absence of a capability. The commands associated with each capability will return the NOT_IMPLEMENTED error if the cabability is not available.Since JDWP version 1.4.
    Out Data
    (None)
    Reply Data
    boolean | canWatchFieldModification | Can the VM watch field modification, and therefore can it send the Modification Watchpoint Event?
    boolean | canWatchFieldAccess | Can the VM watch field access, and therefore can it send the Access Watchpoint Event?
    boolean | canGetBytecodes | Can the VM get the bytecodes of a given method?
    boolean | canGetSyntheticAttribute | Can the VM determine whether a field or method is synthetic? (that is, can the VM determine if the method or the field was invented by the compiler?)
    boolean | canGetOwnedMonitorInfo | Can the VM get the owned monitors infornation for a thread?
    boolean | canGetCurrentContendedMonitor | Can the VM get the current contended monitor of a thread?
    boolean | canGetMonitorInfo | Can the VM get the monitor information for a given object?
    boolean | canRedefineClasses | Can the VM redefine classes?
    boolean | canAddMethod | Can the VM add methods when redefining classes?
    boolean | canUnrestrictedlyRedefineClasses | Can the VM redefine classesin arbitrary ways?
    boolean | canPopFrames | Can the VM pop stack frames?
    boolean | canUseInstanceFilters | Can the VM filter events by specific object?
    boolean | canGetSourceDebugExtension | Can the VM get the source debug extension?
    boolean | canRequestVMDeathEvent | Can the VM request VM death events?
    boolean | canSetDefaultStratum | Can the VM set a default stratum?
    boolean | canGetInstanceInfo | Can the VM return instances, counts of instances of classes and referring objects?
    boolean | canRequestMonitorEvents | Can the VM request monitor events?
    boolean | canGetMonitorFrameInfo | Can the VM get monitors with frame depth info?
    boolean | canUseSourceNameFilters | Can the VM filter class prepare events by source name?
    boolean | canGetConstantPool | Can the VM return the constant pool information?
    boolean | canForceEarlyReturn | Can the VM force early return from a method?
    boolean | reserved22 | Reserved for future capability
    boolean | reserved23 | Reserved for future capability
    boolean | reserved24 | Reserved for future capability
    boolean | reserved25 | Reserved for future capability
    boolean | reserved26 | Reserved for future capability
    boolean | reserved27 | Reserved for future capability
    boolean | reserved28 | Reserved for future capability
    boolean | reserved29 | Reserved for future capability
    boolean | reserved30 | Reserved for future capability
    boolean | reserved31 | Reserved for future capability
    boolean | reserved32 | Reserved for future capability
    Error Data
    VM_DEAD The virtual machine is not running.
    RedefineClasses Command (18)
    Installs new class definitions. If there are active stack frames in methods of the redefined classes in the target VM then those active frames continue to run the bytecodes of the original method. These methods are considered obsolete - see IsObsolete. The methods in the redefined classes will be used for new invokes in the target VM. The original method ID refers to the redefined method. All breakpoints in the redefined classes are cleared.If resetting of stack frames is desired, the PopFrames command can be used to pop frames with obsolete methods.

    Requires canRedefineClasses capability - see CapabilitiesNew. In addition to the canRedefineClasses capability, the target VM must have the canAddMethod capability to add methods when redefining classes, or the canUnrestrictedlyRedefineClasses to redefine classes in arbitrary ways.

    Out Data
    int | classes | Number of reference types that follow.
    Repeated classes times:
    referenceTypeID | refType | The reference type.
    int | classfile | Number of bytes defining class (below)
    Repeated classfile times:
    byte | classbyte | byte in JVM class file format.
    Reply Data
    (None)
    Error Data
    INVALID_CLASS | One of the refTypes is not the ID of a reference type.
    INVALID_OBJECT | One of the refTypes is not a known ID.
    UNSUPPORTED_VERSION | A class file has a version number not supported by this VM.
    INVALID_CLASS_FORMAT | The virtual machine attempted to read a class file and determined that the file is malformed or otherwise cannot be interpreted as a class file.
    CIRCULAR_CLASS_DEFINITION | A circularity has been detected while initializing a class.
    FAILS_VERIFICATION | The verifier detected that a class file, though well formed, contained some sort of internal inconsistency or security problem.
    NAMES_DONT_MATCH | The class name defined in the new class file is different from the name in the old class object.
    NOT_IMPLEMENTED | No aspect of this functionality is implemented (CapabilitiesNew.canRedefineClasses is false)
    ADD_METHOD_NOT_IMPLEMENTED | Adding methods has not been implemented.
    SCHEMA_CHANGE_NOT_IMPLEMENTED | Schema change has not been implemented.
    HIERARCHY_CHANGE_NOT_IMPLEMENTED | A direct superclass is different for the new class version, or the set of directly implemented interfaces is different and canUnrestrictedlyRedefineClasses is false.
    DELETE_METHOD_NOT_IMPLEMENTED | The new class version does not declare a method declared in the old class version and canUnrestrictedlyRedefineClasses is false.
    CLASS_MODIFIERS_CHANGE_NOT_IMPLEMENTED | The new class version has different modifiers and and canUnrestrictedlyRedefineClasses is false.
    METHOD_MODIFIERS_CHANGE_NOT_IMPLEMENTED | A method in the new class version has different modifiers than its counterpart in the old class version and and canUnrestrictedlyRedefineClasses is false.
    VM_DEAD | The virtual machine is not running.
    SetDefaultStratum Command (19)
    Set the default stratum. Requires canSetDefaultStratum capability - see CapabilitiesNew.
    Out Data
    string stratumID default stratum, or empty string to use reference type default.
    Reply Data
    (None)
    Error Data
    NOT_IMPLEMENTED | The functionality is not implemented in this virtual machine.
    VM_DEAD | The virtual machine is not running.
    AllClassesWithGeneric Command (20)
    Returns reference types for all classes currently loaded by the target VM. Both the JNI signature and the generic signature are returned for each class. Generic signatures are described in the signature attribute section in the Java Virtual Machine Specification, 3rd Edition. Since JDWP version 1.5.
    Out Data
    (None)
    Reply Data
    int | classes | Number of reference types that follow.
    Repeated classes times:
    byte | refTypeTag | Kind of following reference type.
    referenceTypeID | typeID | Loaded reference type
    string | signature | The JNI signature of the loaded reference type.
    string | genericSignature | The generic signature of the loaded reference type or an empty string if there is none.
    int | status | The current class status.
    Error Data
    VM_DEAD The virtual machine is not running.
    InstanceCounts Command (21)
    Returns the number of instances of each reference type in the input list. Only instances that are reachable for the purposes of garbage collection are counted. If a reference type is invalid, eg. it has been unloaded, zero is returned for its instance count.

    Since JDWP version 1.6. Requires canGetInstanceInfo capability - see CapabilitiesNew.

    Out Data
    int | refTypesCount | Number of reference types that follow. Must be non-negative.
    Repeated refTypesCount times:
    referenceTypeID | refType | A reference type ID.
    Reply Data
    int | counts | The number of counts that follow.
    Repeated counts times:
    long | instanceCount | The number of instances for the corresponding reference type in 'Out Data'.
    Error Data
    ILLEGAL_ARGUMENT | refTypesCount is less than zero.
    NOT_IMPLEMENTED | The functionality is not implemented in this virtual machine.
    VM_DEAD | The virtual machine is not running.

    ReferenceType Command Set (2)

    Signature Command (1)
    Returns the JNI signature of a reference type. JNI signature formats are described in the Java Native Inteface Specification

    For primitive classes the returned signature is the signature of the corresponding primitive type; for example, "I" is returned as the signature of the class represented by java.lang.Integer.TYPE.

    Out Data
    referenceTypeID refType The reference type ID.
    Reply Data
    string signature The JNI signature for the reference type.
    Error Data
    INVALID_CLASS | refType is not the ID of a reference type.
    INVALID_OBJECT | refType is not a known ID.
    VM_DEAD | The virtual machine is not running.
    ClassLoader Command (2)
    Returns the instance of java.lang.ClassLoader which loaded a given reference type. If the reference type was loaded by the system class loader, the returned object ID is null.
    Out Data
    referenceTypeID refType The reference type ID.
    Reply Data
    classLoaderID classLoader The class loader for the reference type.
    Error Data
    INVALID_CLASS | refType is not the ID of a reference type.
    INVALID_OBJECT | refType is not a known ID.
    VM_DEAD | The virtual machine is not running.
    Modifiers Command (3)
    Returns the modifiers (also known as access flags) for a reference type. The returned bit mask contains information on the declaration of the reference type. If the reference type is an array or a primitive class (for example, java.lang.Integer.TYPE), the value of the returned bit mask is undefined.
    Out Data
    referenceTypeID refType The reference type ID.
    Reply Data
    int modBits Modifier bits as defined in the VM Specification
    Error Data
    INVALID_CLASS | refType is not the ID of a reference type.
    INVALID_OBJECT | refType is not a known ID.
    VM_DEAD | The virtual machine is not running.
    Fields Command (4)
    Returns information for each field in a reference type. Inherited fields are not included. The field list will include any synthetic fields created by the compiler. Fields are returned in the order they occur in the class file.
    Out Data
    referenceTypeID refType The reference type ID.
    Reply Data
    int | declared | Number of declared fields.
    Repeated declared times:
    fieldID | fieldID | Field ID.
    string | name | Name of field.
    string | signature | JNI Signature of field.
    int | modBits | The modifier bit flags (also known as access flags) which provide additional information on the field declaration. Individual flag values are defined in the VM Specification.In addition, The 0xf0000000 bit identifies the field as synthetic, if the synthetic attribute capability is available.
    Error Data
    CLASS_NOT_PREPARED | Class has been loaded but not yet prepared.
    INVALID_CLASS | refType is not the ID of a reference type.
    INVALID_OBJECT | refType is not a known ID.
    VM_DEAD | The virtual machine is not running.
    Methods Command (5)
    Returns information for each method in a reference type. Inherited methods are not included. The list of methods will include constructors (identified with the name "<init>"), the initialization method (identified with the name "<clinit>") if present, and any synthetic methods created by the compiler. Methods are returned in the order they occur in the class file.
    Out Data
    referenceTypeID refType The reference type ID.
    Reply Data
    int | declared | Number of declared methods.
    Repeated declared times:
    methodID | methodID | Method ID.
    string | name | Name of method.
    string | signature | JNI signature of method.
    int | modBits | The modifier bit flags (also known as access flags) which provide additional information on the method declaration. Individual flag values are defined in the VM Specification.In addition, The 0xf0000000 bit identifies the method as synthetic, if the synthetic attribute capability is available.
    Error Data
    CLASS_NOT_PREPARED | Class has been loaded but not yet prepared.
    INVALID_CLASS | refType is not the ID of a reference type.
    INVALID_OBJECT | refType is not a known ID.
    VM_DEAD | The virtual machine is not running.
    GetValues Command (6)
    Returns the value of one or more static fields of the reference type. Each field must be member of the reference type or one of its superclasses, superinterfaces, or implemented interfaces. Access control is not enforced; for example, the values of private fields can be obtained.
    Out Data
    referenceTypeID | refType | The reference type ID.
    int | fields | The number of values to get
    Repeated fields times:
    fieldID | fieldID | A field to get
    Reply Data
    int | values | The number of values returned, always equal to fields, the number of values to get.
    Repeated values times:
    value | value | The field value
    Error Data
    INVALID_CLASS | refType is not the ID of a reference type.
    INVALID_OBJECT | refType is not a known ID.
    INVALID_FIELDID | Invalid field.
    VM_DEAD | The virtual machine is not running.
    SourceFile Command (7)
    Returns the name of source file in which a reference type was declared.
    Out Data
    referenceTypeID refType The reference type ID.
    Reply Data
    string sourceFile The source file name. No path information for the file is included
    Error Data
    INVALID_CLASS | refType is not the ID of a reference type.
    INVALID_OBJECT | refType is not a known ID.
    ABSENT_INFORMATION | The source file attribute is absent.
    VM_DEAD | The virtual machine is not running.
    NestedTypes Command (8)
    Returns the classes and interfaces directly nested within this type.Types further nested within those types are not included.
    Out Data
    referenceTypeID refType The reference type ID.
    Reply Data
    int | classes | The number of nested classes and interfaces
    Repeated classes times:
    byte | refTypeTag | Kind of following reference type.
    referenceTypeID | typeID | The nested class or interface ID.
    Error Data
    INVALID_CLASS | refType is not the ID of a reference type.
    INVALID_OBJECT | refType is not a known ID.
    VM_DEAD | The virtual machine is not running.
    Status Command (9)
    Returns the current status of the reference type. The status indicates the extent to which the reference type has been initialized, as described in the VM specification. If the class is linked the PREPARED and VERIFIED bits in the returned status bits will be set. If the class is initialized the INITIALIZED bit in the returned status bits will be set. If an error occured during initialization then the ERROR bit in the returned status bits will be set. The returned status bits are undefined for array types and for primitive classes (such as java.lang.Integer.TYPE).
    Out Data
    referenceTypeID refType The reference type ID.
    Reply Data
    int status Status bits:See JDWP.ClassStatus
    Error Data
    INVALID_CLASS | refType is not the ID of a reference type.
    INVALID_OBJECT | refType is not a known ID.
    VM_DEAD | The virtual machine is not running.
    Interfaces Command (10)
    Returns the interfaces declared as implemented by this class. Interfaces indirectly implemented (extended by the implemented interface or implemented by a superclass) are not included.
    Out Data
    referenceTypeID refType The reference type ID.
    Reply Data
    int | interfaces | The number of implemented interfaces
    Repeated interfaces times:
    interfaceID | interfaceType | implemented interface.
    Error Data
    INVALID_CLASS | refType is not the ID of a reference type.
    INVALID_OBJECT | refType is not a known ID.
    VM_DEAD | The virtual machine is not running.
    ClassObject Command (11)
    Returns the class object corresponding to this type.
    Out Data
    referenceTypeID refType The reference type ID.
    Reply Data
    classObjectID classObject class object.
    Error Data
    INVALID_CLASS | refType is not the ID of a reference type.
    INVALID_OBJECT | refType is not a known ID.
    VM_DEAD | The virtual machine is not running.
    SourceDebugExtension Command (12)
    Returns the value of the SourceDebugExtension attribute. Since JDWP version 1.4. Requires canGetSourceDebugExtension capability - see CapabilitiesNew.
    Out Data
    referenceTypeID refType The reference type ID.
    Reply Data
    string extension extension attribute
    Error Data
    INVALID_CLASS | refType is not the ID of a reference type.
    INVALID_OBJECT | refType is not a known ID.
    ABSENT_INFORMATION | If the extension is not specified.
    NOT_IMPLEMENTED | The functionality is not implemented in this virtual machine.
    VM_DEAD | The virtual machine is not running.
    SignatureWithGeneric Command (13)
    Returns the JNI signature of a reference type along with the generic signature if there is one. Generic signatures are described in the signature attribute section in the Java Virtual Machine Specification, 3rd Edition. Since JDWP version 1.5.

    Out Data
    referenceTypeID refType The reference type ID.
    Reply Data
    string | signature | The JNI signature for the reference type.
    string | genericSignature | The generic signature for the reference type or an empty string if there is none.
    Error Data
    INVALID_CLASS | refType is not the ID of a reference type.
    INVALID_OBJECT | refType is not a known ID.
    VM_DEAD | The virtual machine is not running.
    FieldsWithGeneric Command (14)
    Returns information, including the generic signature if any, for each field in a reference type. Inherited fields are not included. The field list will include any synthetic fields created by the compiler. Fields are returned in the order they occur in the class file. Generic signatures are described in the signature attribute section in the Java Virtual Machine Specification, 3rd Edition. Since JDWP version 1.5.
    Out Data
    referenceTypeID refType The reference type ID.
    Reply Data
    int | declared | Number of declared fields.
    Repeated declared times:
    fieldID | fieldID | Field ID.
    string | name | The name of the field.
    string | signature | The JNI signature of the field.
    string | genericSignature | The generic signature of the field, or an empty string if there is none.
    int | modBits | The modifier bit flags (also known as access flags) which provide additional information on the field declaration. Individual flag values are defined in the VM Specification.In addition, The 0xf0000000 bit identifies the field as synthetic, if the synthetic attribute capability is available.
    Error Data
    CLASS_NOT_PREPARED | Class has been loaded but not yet prepared.
    INVALID_CLASS | refType is not the ID of a reference type.
    INVALID_OBJECT | refType is not a known ID.
    VM_DEAD | The virtual machine is not running.
    MethodsWithGeneric Command (15)
    Returns information, including the generic signature if any, for each method in a reference type. Inherited methodss are not included. The list of methods will include constructors (identified with the name "<init>"), the initialization method (identified with the name "<clinit>") if present, and any synthetic methods created by the compiler. Methods are returned in the order they occur in the class file. Generic signatures are described in the signature attribute section in the Java Virtual Machine Specification, 3rd Edition. Since JDWP version 1.5.
    Out Data
    referenceTypeID refType The reference type ID.
    Reply Data
    int | declared | Number of declared methods.
    Repeated declared times:
    methodID | methodID | Method ID.
    string | name | The name of the method.
    string | signature | The JNI signature of the method.
    string | genericSignature | The generic signature of the method, or an empty string if there is none.
    int | modBits | The modifier bit flags (also known as access flags) which provide additional information on the method declaration. Individual flag values are defined in the VM Specification.In addition, The 0xf0000000 bit identifies the method as synthetic, if the synthetic attribute capability is available.
    Error Data
    CLASS_NOT_PREPARED | Class has been loaded but not yet prepared.
    INVALID_CLASS | refType is not the ID of a reference type.
    INVALID_OBJECT | refType is not a known ID.
    VM_DEAD | The virtual machine is not running.
    Instances Command (16)
    Returns instances of this reference type. Only instances that are reachable for the purposes of garbage collection are returned.

    Since JDWP version 1.6. Requires canGetInstanceInfo capability - see CapabilitiesNew.

    Out Data
    referenceTypeID | refType | The reference type ID.
    int | maxInstances | Maximum number of instances to return. Must be non-negative. If zero, all instances are returned.
    Reply Data
    int | instances | The number of instances that follow.
    Repeated instances times:
    tagged-objectID | instance | An instance of this reference type.
    Error Data
    INVALID_CLASS | refType is not the ID of a reference type.
    INVALID_OBJECT | refType is not a known ID.
    ILLEGAL_ARGUMENT | maxInstances is less than zero.
    NOT_IMPLEMENTED | The functionality is not implemented in this virtual machine.
    VM_DEAD | The virtual machine is not running.
    ClassFileVersion Command (17)
    Returns the class file major and minor version numbers, as defined in the class file format of the Java Virtual Machine specification.

    Since JDWP version 1.6.

    Out Data
    referenceTypeID refType The class.
    Reply Data
    int | majorVersion | Major version number
    int | minorVersion | Minor version number
    Error Data
    INVALID_CLASS | refType is not the ID of a reference type.
    INVALID_OBJECT | refType is not a known ID.
    ABSENT_INFORMATION | The class file version information is absent for primitive and array types.
    VM_DEAD | The virtual machine is not running.
    ConstantPool Command (18)
    Return the raw bytes of the constant pool in the format of the constant_pool item of the Class File Format in the Java Virtual Machine Specification.

    Since JDWP version 1.6. Requires canGetConstantPool capability - see CapabilitiesNew.

    Out Data
    referenceTypeID refType The class.
    Reply Data
    int | count | Total number of constant pool entries plus one. This corresponds to the constant_pool_count item of the Class File Format in the Java Virtual Machine Specification.
    int | bytes
    Repeated bytes times:
    byte | cpbytes | Raw bytes of constant pool
    Error Data
    INVALID_CLASS | refType is not the ID of a reference type.
    INVALID_OBJECT | refType is not a known ID.
    NOT_IMPLEMENTED | If the target virtual machine does not support the retrieval of constant pool information.
    ABSENT_INFORMATION | The Constant Pool information is absent for primitive and array types.
    VM_DEAD | The virtual machine is not running.

    ClassType Command Set (3)

    Superclass Command (1)
    Returns the immediate superclass of a class.
    Out Data
    classID clazz The class type ID.
    Reply Data
    classID superclass The superclass (null if the class ID for java.lang.Object is specified).
    Error Data
    INVALID_CLASS | clazz is not the ID of a class.
    INVALID_OBJECT | clazz is not a known ID.
    VM_DEAD | The virtual machine is not running.
    SetValues Command (2)
    Sets the value of one or more static fields. Each field must be member of the class type or one of its superclasses, superinterfaces, or implemented interfaces. Access control is not enforced; for example, the values of private fields can be set. Final fields cannot be set.For primitive values, the value's type must match the field's type exactly. For object values, there must exist a widening reference conversion from the value's type to the field's type and the field's type must be loaded.
    Out Data
    classID | clazz | The class type ID.
    int | values | The number of fields to set.
    Repeated values times:
    fieldID | fieldID | Field to set.
    untagged-value | value | Value to put in the field.
    Reply Data
    (None)
    Error Data
    INVALID_CLASS | clazz is not the ID of a class.
    CLASS_NOT_PREPARED | Class has been loaded but not yet prepared.
    INVALID_OBJECT | clazz is not a known ID or a value of an object field is not a known ID.
    INVALID_FIELDID | Invalid field.
    VM_DEAD | The virtual machine is not running.
    InvokeMethod Command (3)
    Invokes a static method. The method must be member of the class type or one of its superclasses, superinterfaces, or implemented interfaces. Access control is not enforced; for example, private methods can be invoked.

    The method invocation will occur in the specified thread. Method invocation can occur only if the specified thread has been suspended by an event. Method invocation is not supported when the target VM has been suspended by the front-end.

    The specified method is invoked with the arguments in the specified argument list. The method invocation is synchronous; the reply packet is not sent until the invoked method returns in the target VM. The return value (possibly the void value) is included in the reply packet. If the invoked method throws an exception, the exception object ID is set in the reply packet; otherwise, the exception object ID is null.

    For primitive arguments, the argument value's type must match the argument's type exactly. For object arguments, there must exist a widening reference conversion from the argument value's type to the argument's type and the argument's type must be loaded.

    By default, all threads in the target VM are resumed while the method is being invoked if they were previously suspended by an event or by command. This is done to prevent the deadlocks that will occur if any of the threads own monitors that will be needed by the invoked method. It is possible that breakpoints or other events might occur during the invocation. Note, however, that this implicit resume acts exactly like the ThreadReference resume command, so if the thread's suspend count is greater than 1, it will remain in a suspended state during the invocation. By default, when the invocation completes, all threads in the target VM are suspended, regardless their state before the invocation.

    The resumption of other threads during the invoke can be prevented by specifying the INVOKE_SINGLE_THREADED bit flag in the options field; however, there is no protection against or recovery from the deadlocks described above, so this option should be used with great caution. Only the specified thread will be resumed (as described for all threads above). Upon completion of a single threaded invoke, the invoking thread will be suspended once again. Note that any threads started during the single threaded invocation will not be suspended when the invocation completes.

    If the target VM is disconnected during the invoke (for example, through the VirtualMachine dispose command) the method invocation continues.

    Out Data
    classID | clazz | The class type ID.
    threadID | thread | The thread in which to invoke.
    methodID | methodID | The method to invoke.
    int | arguments
    Repeated arguments times:
    value | arg | The argument value.
    int | options | Invocation options
    Reply Data
    value | returnValue | The returned value.
    tagged-objectID | exception | The thrown exception.
    Error Data
    INVALID_CLASS | clazz is not the ID of a class.
    INVALID_OBJECT | clazz is not a known ID.
    INVALID_METHODID | methodID is not the ID of a method.
    INVALID_THREAD | Passed thread is null, is not a valid thread or has exited.
    THREAD_NOT_SUSPENDED | If the specified thread has not been suspended by an event.
    VM_DEAD | The virtual machine is not running.
    NewInstance Command (4)
    Creates a new object of this type, invoking the specified constructor. The constructor method ID must be a member of the class type.

    Instance creation will occur in the specified thread. Instance creation can occur only if the specified thread has been suspended by an event. Method invocation is not supported when the target VM has been suspended by the front-end.

    The specified constructor is invoked with the arguments in the specified argument list. The constructor invocation is synchronous; the reply packet is not sent until the invoked method returns in the target VM. The return value (possibly the void value) is included in the reply packet. If the constructor throws an exception, the exception object ID is set in the reply packet; otherwise, the exception object ID is null.

    For primitive arguments, the argument value's type must match the argument's type exactly. For object arguments, there must exist a widening reference conversion from the argument value's type to the argument's type and the argument's type must be loaded.

    By default, all threads in the target VM are resumed while the method is being invoked if they were previously suspended by an event or by command. This is done to prevent the deadlocks that will occur if any of the threads own monitors that will be needed by the invoked method. It is possible that breakpoints or other events might occur during the invocation. Note, however, that this implicit resume acts exactly like the ThreadReference resume command, so if the thread's suspend count is greater than 1, it will remain in a suspended state during the invocation. By default, when the invocation completes, all threads in the target VM are suspended, regardless their state before the invocation.

    The resumption of other threads during the invoke can be prevented by specifying the INVOKE_SINGLE_THREADED bit flag in the options field; however, there is no protection against or recovery from the deadlocks described above, so this option should be used with great caution. Only the specified thread will be resumed (as described for all threads above). Upon completion of a single threaded invoke, the invoking thread will be suspended once again. Note that any threads started during the single threaded invocation will not be suspended when the invocation completes.

    If the target VM is disconnected during the invoke (for example, through the VirtualMachine dispose command) the method invocation continues.

    Out Data
    classID | clazz | The class type ID.
    threadID | thread | The thread in which to invoke the constructor.
    methodID | methodID | The constructor to invoke.
    int | arguments
    Repeated arguments times:
    value | arg | The argument value.
    int | options | Constructor invocation options
    Reply Data
    tagged-objectID | newObject | The newly created object, or null if the constructor threw an exception.
    tagged-objectID | exception | The thrown exception, if any; otherwise, null.
    Error Data
    INVALID_CLASS | clazz is not the ID of a class.
    INVALID_OBJECT | clazz is not a known ID or a value of an object parameter is not a known ID..
    INVALID_METHODID | methodID is not the ID of a method.
    INVALID_OBJECT | If this reference type has been unloaded and garbage collected.
    INVALID_THREAD | Passed thread is null, is not a valid thread or has exited.
    THREAD_NOT_SUSPENDED | If the specified thread has not been suspended by an event.
    VM_DEAD | The virtual machine is not running.

    ArrayType Command Set (4)

    NewInstance Command (1)
    Creates a new array object of this type with a given length.
    Out Data
    arrayTypeID | arrType | The array type of the new instance.
    int | length | The length of the array.
    Reply Data
    tagged-objectID newArray The newly created array object.
    Error Data
    INVALID_ARRAY | The array is invalid.
    INVALID_OBJECT | If this reference type has been unloaded and garbage collected.
    VM_DEAD | The virtual machine is not running.

    InterfaceType Command Set (5)

    Method Command Set (6)

    LineTable Command (1)
    Returns line number information for the method, if present. The line table maps source line numbers to the initial code index of the line. The line table is ordered by code index (from lowest to highest). The line number information is constant unless a new class definition is installed using RedefineClasses.
    Out Data
    referenceTypeID | refType | The class.
    methodID | methodID | The method.
    Reply Data
    long | start | Lowest valid code index for the method, >=0, or -1 if the method is native
    long | end | Highest valid code index for the method, >=0, or -1 if the method is native
    int | lines | The number of entries in the line table for this method.
    Repeated lines times:
    long | lineCodeIndex | Initial code index of the line, start <= lineCodeIndex < end
    int | lineNumber | Line number.
    Error Data
    INVALID_CLASS | refType is not the ID of a reference type.
    INVALID_OBJECT | refType is not a known ID.
    INVALID_METHODID | methodID is not the ID of a method.
    VM_DEAD | The virtual machine is not running.
    VariableTable Command (2)
    Returns variable information for the method. The variable table includes arguments and locals declared within the method. For instance methods, the "this" reference is included in the table. Also, synthetic variables may be present.
    Out Data
    referenceTypeID | refType | The class.
    methodID | methodID | The method.
    Reply Data
    int | argCnt | The number of words in the frame used by arguments. Eight-byte arguments use two words; all others use one.
    int | slots | The number of variables.
    Repeated slots times:
    long | codeIndex | First code index at which the variable is visible (unsigned). Used in conjunction with length. The variable can be get or set only when the current codeIndex <= current frame code index < codeIndex + length
    string | name | The variable's name.
    string | signature | The variable type's JNI signature.
    int | length | Unsigned value used in conjunction with codeIndex. The variable can be get or set only when the current codeIndex <= current frame code index < code index + length
    int | slot | The local variable's index in its frame
    Error Data
    INVALID_CLASS | refType is not the ID of a reference type.
    INVALID_OBJECT | refType is not a known ID.
    INVALID_METHODID | methodID is not the ID of a method.
    ABSENT_INFORMATION | there is no variable information for the method.
    VM_DEAD | The virtual machine is not running.
    Bytecodes Command (3)
    Retrieve the method's bytecodes as defined in the JVM Specification.Requires canGetBytecodes capability - see CapabilitiesNew.
    Out Data
    referenceTypeID | refType | The class.
    methodID | methodID | The method.
    Reply Data
    int | bytes
    Repeated bytes times:
    byte | bytecode | A Java bytecode.
    Error Data
    INVALID_CLASS | refType is not the ID of a reference type.
    INVALID_OBJECT | refType is not a known ID.
    INVALID_METHODID | methodID is not the ID of a method.
    NOT_IMPLEMENTED | If the target virtual machine does not support the retrieval of bytecodes.
    VM_DEAD | The virtual machine is not running.
    IsObsolete Command (4)
    Determine if this method is obsolete. A method is obsolete if it has been replaced by a non-equivalent method using the RedefineClasses command. The original and redefined methods are considered equivalent if their bytecodes are the same except for indices into the constant pool and the referenced constants are equal.
    Out Data
    referenceTypeID | refType | The class.
    methodID | methodID | The method.
    Reply Data
    boolean isObsolete true if this method has been replacedby a non-equivalent method usingthe RedefineClasses command.
    Error Data
    INVALID_CLASS | refType is not the ID of a reference type.
    INVALID_OBJECT | refType is not a known ID.
    INVALID_METHODID | methodID is not the ID of a method.
    NOT_IMPLEMENTED | If the target virtual machine does not support this query.
    VM_DEAD | The virtual machine is not running.
    VariableTableWithGeneric Command (5)
    Returns variable information for the method, including generic signatures for the variables. The variable table includes arguments and locals declared within the method. For instance methods, the "this" reference is included in the table. Also, synthetic variables may be present. Generic signatures are described in the signature attribute section in the Java Virtual Machine Specification, 3rd Edition. Since JDWP version 1.5.
    Out Data
    referenceTypeID | refType | The class.
    methodID | methodID | The method.
    Reply Data
    int | argCnt | The number of words in the frame used by arguments. Eight-byte arguments use two words; all others use one.
    int | slots | The number of variables.
    Repeated slots times:
    long | codeIndex | First code index at which the variable is visible (unsigned). Used in conjunction with length. The variable can be get or set only when the current codeIndex <= current frame code index < codeIndex + length
    string | name | The variable's name.
    string | signature | The variable type's JNI signature.
    string | genericSignature | The variable type's generic signature or an empty string if there is none.
    int | length | Unsigned value used in conjunction with codeIndex. The variable can be get or set only when the current codeIndex <= current frame code index < code index + length
    int | slot | The local variable's index in its frame
    Error Data
    INVALID_CLASS | refType is not the ID of a reference type.
    INVALID_OBJECT | refType is not a known ID.
    INVALID_METHODID | methodID is not the ID of a method.
    ABSENT_INFORMATION | there is no variable information for the method.
    VM_DEAD | The virtual machine is not running.

    Field Command Set (8)

    ObjectReference Command Set (9)

    ReferenceType Command (1)
    Returns the runtime type of the object. The runtime type will be a class or an array.
    Out Data
    objectID object The object ID
    Reply Data
    byte | refTypeTag | Kind of following reference type.
    referenceTypeID | typeID | The runtime reference type.
    Error Data
    INVALID_OBJECT | If this reference type has been unloaded and garbage collected.
    VM_DEAD | The virtual machine is not running.
    GetValues Command (2)
    Returns the value of one or more instance fields. Each field must be member of the object's type or one of its superclasses, superinterfaces, or implemented interfaces. Access control is not enforced; for example, the values of private fields can be obtained.
    Out Data
    objectID | object | The object ID
    int | fields | The number of values to get
    Repeated fields times:
    fieldID | fieldID | Field to get.
    Reply Data
    int | values | The number of values returned, always equal to 'fields', the number of values to get. Field values are ordered in the reply in the same order as corresponding fieldIDs in the command.
    Repeated values times:
    value | value | The field value
    Error Data
    INVALID_OBJECT | If this reference type has been unloaded and garbage collected.
    INVALID_FIELDID | Invalid field.
    VM_DEAD | The virtual machine is not running.
    SetValues Command (3)
    Sets the value of one or more instance fields. Each field must be member of the object's type or one of its superclasses, superinterfaces, or implemented interfaces. Access control is not enforced; for example, the values of private fields can be set. For primitive values, the value's type must match the field's type exactly. For object values, there must be a widening reference conversion from the value's type to the field's type and the field's type must be loaded.
    Out Data
    objectID | object | The object ID
    int | values | The number of fields to set.
    Repeated values times:
    fieldID | fieldID | Field to set.
    untagged-value | value | Value to put in the field.
    Reply Data
    (None)
    Error Data
    INVALID_OBJECT | If this reference type has been unloaded and garbage collected.
    INVALID_FIELDID | Invalid field.
    VM_DEAD | The virtual machine is not running.
    MonitorInfo Command (5)
    Returns monitor information for an object. All threads int the VM must be suspended.Requires canGetMonitorInfo capability - see CapabilitiesNew.
    Out Data
    objectID object The object ID
    Reply Data
    threadID | owner | The monitor owner, or null if it is not currently owned.
    int | entryCount | The number of times the monitor has been entered.
    int | waiters | The number of threads that are waiting for the monitor 0 if there is no current owner
    Repeated waiters times:
    threadID | thread | A thread waiting for this monitor.
    Error Data
    INVALID_OBJECT | If this reference type has been unloaded and garbage collected.
    NOT_IMPLEMENTED | The functionality is not implemented in this virtual machine.
    VM_DEAD | The virtual machine is not running.
    InvokeMethod Command (6)
    Invokes a instance method. The method must be member of the object's type or one of its superclasses, superinterfaces, or implemented interfaces. Access control is not enforced; for example, private methods can be invoked.

    The method invocation will occur in the specified thread. Method invocation can occur only if the specified thread has been suspended by an event. Method invocation is not supported when the target VM has been suspended by the front-end.

    The specified method is invoked with the arguments in the specified argument list. The method invocation is synchronous; the reply packet is not sent until the invoked method returns in the target VM. The return value (possibly the void value) is included in the reply packet. If the invoked method throws an exception, the exception object ID is set in the reply packet; otherwise, the exception object ID is null.

    For primitive arguments, the argument value's type must match the argument's type exactly. For object arguments, there must be a widening reference conversion from the argument value's type to the argument's type and the argument's type must be loaded.

    By default, all threads in the target VM are resumed while the method is being invoked if they were previously suspended by an event or by command. This is done to prevent the deadlocks that will occur if any of the threads own monitors that will be needed by the invoked method. It is possible that breakpoints or other events might occur during the invocation. Note, however, that this implicit resume acts exactly like the ThreadReference resume command, so if the thread's suspend count is greater than 1, it will remain in a suspended state during the invocation. By default, when the invocation completes, all threads in the target VM are suspended, regardless their state before the invocation.

    The resumption of other threads during the invoke can be prevented by specifying the INVOKE_SINGLE_THREADED bit flag in the options field; however, there is no protection against or recovery from the deadlocks described above, so this option should be used with great caution. Only the specified thread will be resumed (as described for all threads above). Upon completion of a single threaded invoke, the invoking thread will be suspended once again. Note that any threads started during the single threaded invocation will not be suspended when the invocation completes.

    If the target VM is disconnected during the invoke (for example, through the VirtualMachine dispose command) the method invocation continues.

    Out Data
    objectID | object | The object ID
    threadID | thread | The thread in which to invoke.
    classID | clazz | The class type.
    methodID | methodID | The method to invoke.
    int | arguments | The number of arguments.
    Repeated arguments times:
    value | arg | The argument value.
    int | options | Invocation options
    Reply Data
    value | returnValue | The returned value, or null if an exception is thrown.
    tagged-objectID | exception | The thrown exception, if any.
    Error Data
    INVALID_OBJECT | If this reference type has been unloaded and garbage collected.
    INVALID_CLASS | clazz is not the ID of a reference type.
    INVALID_METHODID | methodID is not the ID of a method.
    INVALID_THREAD | Passed thread is null, is not a valid thread or has exited.
    THREAD_NOT_SUSPENDED | If the specified thread has not been suspended by an event.
    VM_DEAD | The virtual machine is not running.
    DisableCollection Command (7)
    Prevents garbage collection for the given object. By default all objects in back-end replies may be collected at any time the target VM is running. A call to this command guarantees that the object will not be collected. The EnableCollection command can be used to allow collection once again.

    Note that while the target VM is suspended, no garbage collection will occur because all threads are suspended. The typical examination of variables, fields, and arrays during the suspension is safe without explicitly disabling garbage collection.

    This method should be used sparingly, as it alters the pattern of garbage collection in the target VM and, consequently, may result in application behavior under the debugger that differs from its non-debugged behavior.

    Out Data
    objectID object The object ID
    Reply Data
    (None)
    Error Data
    INVALID_OBJECT | If this reference type has been unloaded and garbage collected.
    VM_DEAD | The virtual machine is not running.
    EnableCollection Command (8)
    Permits garbage collection for this object. By default all objects returned by JDWP may become unreachable in the target VM, and hence may be garbage collected. A call to this command is necessary only if garbage collection was previously disabled with the DisableCollection command.
    Out Data
    objectID object The object ID
    Reply Data
    (None)
    Error Data
    VM_DEAD The virtual machine is not running.
    IsCollected Command (9)
    Determines whether an object has been garbage collected in the target VM.
    Out Data
    objectID object The object ID
    Reply Data
    boolean isCollected true if the object has been collected; false otherwise
    Error Data
    INVALID_OBJECT | If this reference type has been unloaded and garbage collected.
    VM_DEAD | The virtual machine is not running.
    ReferringObjects Command (10)
    Returns objects that directly reference this object. Only objects that are reachable for the purposes of garbage collection are returned. Note that an object can also be referenced in other ways, such as from a local variable in a stack frame, or from a JNI global reference. Such non-object referrers are not returned by this command.

    Since JDWP version 1.6. Requires canGetInstanceInfo capability - see CapabilitiesNew.

    Out Data
    objectID | object | The object ID
    int | maxReferrers | Maximum number of referring objects to return. Must be non-negative. If zero, all referring objects are returned.
    Reply Data
    int | referringObjects | The number of objects that follow.
    Repeated referringObjects times:
    tagged-objectID | instance | An object that references this object.
    Error Data
    INVALID_OBJECT | object is not a known ID.
    ILLEGAL_ARGUMENT | maxReferrers is less than zero.
    NOT_IMPLEMENTED | The functionality is not implemented in this virtual machine.
    VM_DEAD | The virtual machine is not running.

    StringReference Command Set (10)

    Value Command (1)
    Returns the characters contained in the string.
    Out Data
    objectID stringObject The String object ID.
    Reply Data
    string stringValue UTF-8 representation of the string value.
    Error Data
    INVALID_STRING | The string is invalid.
    INVALID_OBJECT | If this reference type has been unloaded and garbage collected.
    VM_DEAD | The virtual machine is not running.

    ThreadReference Command Set (11)

    Name Command (1)
    Returns the thread name.
    Out Data
    threadID thread The thread object ID.
    Reply Data
    string threadName The thread name.
    Error Data
    INVALID_THREAD | Passed thread is null, is not a valid thread or has exited.
    INVALID_OBJECT | thread is not a known ID.
    VM_DEAD | The virtual machine is not running.
    Suspend Command (2)
    Suspends the thread.

    Unlike java.lang.Thread.suspend(), suspends of both the virtual machine and individual threads are counted. Before a thread will run again, it must be resumed the same number of times it has been suspended.

    Suspending single threads with command has the same dangers java.lang.Thread.suspend(). If the suspended thread holds a monitor needed by another running thread, deadlock is possible in the target VM (at least until the suspended thread is resumed again).

    The suspended thread is guaranteed to remain suspended until resumed through one of the JDI resume methods mentioned above; the application in the target VM cannot resume the suspended thread through {@link java.lang.Thread#resume}.

    Note that this doesn't change the status of the thread (see the ThreadStatus command.) For example, if it was Running, it will still appear running to other threads.

    Out Data
    threadID thread The thread object ID.
    Reply Data
    (None)
    Error Data
    INVALID_THREAD | Passed thread is null, is not a valid thread or has exited.
    INVALID_OBJECT | thread is not a known ID.
    VM_DEAD | The virtual machine is not running.
    Resume Command (3)
    Resumes the execution of a given thread. If this thread was not previously suspended by the front-end, calling this command has no effect. Otherwise, the count of pending suspends on this thread is decremented. If it is decremented to 0, the thread will continue to execute.
    Out Data
    threadID thread The thread object ID.
    Reply Data
    (None)
    Error Data
    INVALID_THREAD | Passed thread is null, is not a valid thread or has exited.
    INVALID_OBJECT | thread is not a known ID.
    VM_DEAD | The virtual machine is not running.
    Status Command (4)
    Returns the current status of a thread. The thread status reply indicates the thread status the last time it was running. the suspend status provides information on the thread's suspension, if any.
    Out Data
    threadID thread The thread object ID.
    Reply Data
    int | threadStatus | One of the thread status codes See JDWP.ThreadStatus
    int | suspendStatus | One of the suspend status codes See JDWP.SuspendStatus
    Error Data
    INVALID_THREAD | Passed thread is null, is not a valid thread or has exited.
    INVALID_OBJECT | thread is not a known ID.
    VM_DEAD | The virtual machine is not running.
    ThreadGroup Command (5)
    Returns the thread group that contains a given thread.
    Out Data
    threadID thread The thread object ID.
    Reply Data
    threadGroupID group The thread group of this thread.
    Error Data
    INVALID_THREAD | Passed thread is null, is not a valid thread or has exited.
    INVALID_OBJECT | thread is not a known ID.
    VM_DEAD | The virtual machine is not running.
    Frames Command (6)
    Returns the current call stack of a suspended thread. The sequence of frames starts with the currently executing frame, followed by its caller, and so on. The thread must be suspended, and the returned frameID is valid only while the thread is suspended.
    Out Data
    threadID | thread | The thread object ID.
    int | startFrame | The index of the first frame to retrieve.
    int | length | The count of frames to retrieve (-1 means all remaining).
    Reply Data
    int | frames | The number of frames retreived
    Repeated frames times:
    frameID | frameID | The ID of this frame.
    location | location | The current location of this frame
    Error Data
    INVALID_THREAD | Passed thread is null, is not a valid thread or has exited.
    INVALID_OBJECT | thread is not a known ID.
    VM_DEAD | The virtual machine is not running.
    FrameCount Command (7)
    Returns the count of frames on this thread's stack. The thread must be suspended, and the returned count is valid only while the thread is suspended. Returns JDWP.Error.errorThreadNotSuspended if not suspended.
    Out Data
    threadID thread The thread object ID.
    Reply Data
    int frameCount The count of frames on this thread's stack.
    Error Data
    INVALID_THREAD | Passed thread is null, is not a valid thread or has exited.
    INVALID_OBJECT | thread is not a known ID.
    VM_DEAD | The virtual machine is not running.
    OwnedMonitors Command (8)
    Returns the objects whose monitors have been entered by this thread. The thread must be suspended, and the returned information is relevant only while the thread is suspended. Requires canGetOwnedMonitorInfo capability - see CapabilitiesNew.
    Out Data
    threadID thread The thread object ID.
    Reply Data
    int | owned | The number of owned monitors
    Repeated owned times:
    tagged-objectID | monitor | An owned monitor
    Error Data
    INVALID_THREAD | Passed thread is null, is not a valid thread or has exited.
    INVALID_OBJECT | thread is not a known ID.
    NOT_IMPLEMENTED | The functionality is not implemented in this virtual machine.
    VM_DEAD | The virtual machine is not running.
    CurrentContendedMonitor Command (9)
    Returns the object, if any, for which this thread is waiting. The thread may be waiting to enter a monitor, or it may be waiting, via the java.lang.Object.wait method, for another thread to invoke the notify method. The thread must be suspended, and the returned information is relevant only while the thread is suspended. Requires canGetCurrentContendedMonitor capability - see CapabilitiesNew.
    Out Data
    threadID thread The thread object ID.
    Reply Data
    tagged-objectID monitor The contended monitor, or null if there is no current contended monitor.
    Error Data
    INVALID_THREAD | Passed thread is null, is not a valid thread or has exited.
    INVALID_OBJECT | thread is not a known ID.
    NOT_IMPLEMENTED | The functionality is not implemented in this virtual machine.
    VM_DEAD | The virtual machine is not running.
    Stop Command (10)
    Stops the thread with an asynchronous exception, as if done by java.lang.Thread.stop
    Out Data
    threadID | thread | The thread object ID.
    objectID | throwable | Asynchronous exception. This object must be an instance of java.lang.Throwable or a subclass
    Reply Data
    (None)
    Error Data
    INVALID_THREAD | Passed thread is null, is not a valid thread or has exited.
    INVALID_OBJECT | If thread is not a known ID or the asynchronous exception has been garbage collected.
    VM_DEAD | The virtual machine is not running.
    Interrupt Command (11)
    Interrupt the thread, as if done by java.lang.Thread.interrupt
    Out Data
    threadID thread The thread object ID.
    Reply Data
    (None)
    Error Data
    INVALID_THREAD | Passed thread is null, is not a valid thread or has exited.
    INVALID_OBJECT | thread is not a known ID.
    VM_DEAD | The virtual machine is not running.
    SuspendCount Command (12)
    Get the suspend count for this thread. The suspend count is the number of times the thread has been suspended through the thread-level or VM-level suspend commands without a corresponding resume
    Out Data
    threadID thread The thread object ID.
    Reply Data
    int suspendCount The number of outstanding suspends of this thread.
    Error Data
    INVALID_THREAD | Passed thread is null, is not a valid thread or has exited.
    INVALID_OBJECT | thread is not a known ID.
    VM_DEAD | The virtual machine is not running.
    OwnedMonitorsStackDepthInfo Command (13)
    Returns monitor objects owned by the thread, along with stack depth at which the monitor was acquired. Returns stack depth of -1 if the implementation cannot determine the stack depth (e.g., for monitors acquired by JNI MonitorEnter).The thread must be suspended, and the returned information is relevant only while the thread is suspended. Requires canGetMonitorFrameInfo capability - see CapabilitiesNew.

    Since JDWP version 1.6.

    Out Data
    threadID thread The thread object ID.
    Reply Data
    int | owned | The number of owned monitors
    Repeated owned times:
    tagged-objectID | monitor | An owned monitor
    int | stack_depth | Stack depth location where monitor was acquired
    Error Data
    INVALID_THREAD | Passed thread is null, is not a valid thread or has exited.
    INVALID_OBJECT | thread is not a known ID.
    NOT_IMPLEMENTED | The functionality is not implemented in this virtual machine.
    VM_DEAD | The virtual machine is not running.
    ForceEarlyReturn Command (14)
    Force a method to return before it reaches a return statement.

    The method which will return early is referred to as the called method. The called method is the current method (as defined by the Frames section in the Java Virtual Machine Specification) for the specified thread at the time this command is received.

    The specified thread must be suspended. The return occurs when execution of Java programming language code is resumed on this thread. Between sending this command and resumption of thread execution, the state of the stack is undefined.

    No further instructions are executed in the called method. Specifically, finally blocks are not executed. Note: this can cause inconsistent states in the application.

    A lock acquired by calling the called method (if it is a synchronized method) and locks acquired by entering synchronized blocks within the called method are released. Note: this does not apply to JNI locks or java.util.concurrent.locks locks.

    Events, such as MethodExit, are generated as they would be in a normal return.

    The called method must be a non-native Java programming language method. Forcing return on a thread with only one frame on the stack causes the thread to exit when resumed.

    For void methods, the value must be a void value. For methods that return primitive values, the value's type must match the return type exactly. For object values, there must be a widening reference conversion from the value's type to the return type type and the return type must be loaded.

    Since JDWP version 1.6. Requires canForceEarlyReturn capability - see CapabilitiesNew.

    Out Data
    threadID | thread | The thread object ID.
    value | value | The value to return.
    Reply Data
    (None)
    Error Data
    INVALID_THREAD | Passed thread is null, is not a valid thread or has exited.
    INVALID_OBJECT | Thread or value is not a known ID.
    THREAD_NOT_SUSPENDED | If the specified thread has not been suspended by an event.
    THREAD_NOT_ALIVE | Thread has not been started or is now dead.
    OPAQUE_FRAME | Attempted to return early from a frame corresponding to a native method. Or the implementation is unable to provide this functionality on this frame.
    NO_MORE_FRAMES | There are no more Java or JNI frames on the call stack.
    NOT_IMPLEMENTED | The functionality is not implemented in this virtual machine.
    TYPE_MISMATCH | Value is not an appropriate type for the return value of the method.
    VM_DEAD | The virtual machine is not running.

    ThreadGroupReference Command Set (12)

    Name Command (1)
    Returns the thread group name.
    Out Data
    threadGroupID group The thread group object ID.
    Reply Data
    string groupName The thread group's name.
    Error Data
    INVALID_THREAD_GROUP | Thread group invalid.
    INVALID_OBJECT | group is not a known ID.
    VM_DEAD | The virtual machine is not running.
    Parent Command (2)
    Returns the thread group, if any, which contains a given thread group.
    Out Data
    threadGroupID group The thread group object ID.
    Reply Data
    threadGroupID parentGroup The parent thread group object, or null if the given thread group is a top-level thread group
    Error Data
    INVALID_THREAD_GROUP | Thread group invalid.
    INVALID_OBJECT | group is not a known ID.
    VM_DEAD | The virtual machine is not running.
    Children Command (3)
    Returns the live threads and active thread groups directly contained in this thread group. Threads and thread groups in child thread groups are not included. A thread is alive if it has been started and has not yet been stopped. See java.lang.ThreadGroup for information about active ThreadGroups.
    Out Data
    threadGroupID group The thread group object ID.
    Reply Data
    int | childThreads | The number of live child threads.
    Repeated childThreads times:
    threadID | childThread | A direct child thread ID.
    int | childGroups | The number of active child thread groups.
    Repeated childGroups times:
    threadGroupID | childGroup | A direct child thread group ID.
    Error Data
    INVALID_THREAD_GROUP | Thread group invalid.
    INVALID_OBJECT | group is not a known ID.
    VM_DEAD | The virtual machine is not running.

    ArrayReference Command Set (13)

    Length Command (1)
    Returns the number of components in a given array.
    Out Data
    arrayID arrayObject The array object ID.
    Reply Data
    int arrayLength The length of the array.
    Error Data
    INVALID_OBJECT | arrayObject is not a known ID.
    INVALID_ARRAY | The array is invalid.
    VM_DEAD | The virtual machine is not running.
    GetValues Command (2)
    Returns a range of array components. The specified range must be within the bounds of the array.
    Out Data
    arrayID | arrayObject | The array object ID.
    int | firstIndex | The first index to retrieve.
    int | length | The number of components to retrieve.
    Reply Data
    arrayregion values The retrieved values. If the values are objects, they are tagged-values; otherwise, they are untagged-values
    Error Data
    INVALID_LENGTH | If index is beyond the end of this array.
    INVALID_OBJECT | arrayObject is not a known ID.
    INVALID_ARRAY | The array is invalid.
    VM_DEAD | The virtual machine is not running.
    SetValues Command (3)
    Sets a range of array components. The specified range must be within the bounds of the array. For primitive values, each value's type must match the array component type exactly. For object values, there must be a widening reference conversion from the value's type to the array component type and the array component type must be loaded.
    Out Data
    arrayID | arrayObject | The array object ID.
    int | firstIndex | The first index to set.
    int | values | The number of values to set.
    Repeated values times:
    untagged-value | value | A value to set.
    Reply Data
    (None)
    Error Data
    INVALID_LENGTH | If index is beyond the end of this array.
    INVALID_OBJECT | arrayObject is not a known ID.
    INVALID_ARRAY | The array is invalid.
    VM_DEAD | The virtual machine is not running.

    ClassLoaderReference Command Set (14)

    VisibleClasses Command (1)
    Returns a list of all classes which this class loader has been requested to load. This class loader is considered to be an initiating class loader for each class in the returned list. The list contains each reference type defined by this loader and any types for which loading was delegated by this class loader to another class loader.

    The visible class list has useful properties with respect to the type namespace. A particular type name will occur at most once in the list. Each field or variable declared with that type name in a class defined by this class loader must be resolved to that single type.

    No ordering of the returned list is guaranteed.

    Out Data
    classLoaderID classLoaderObject The class loader object ID.
    Reply Data
    int | classes | The number of visible classes.
    Repeated classes times:
    byte | refTypeTag | Kind of following reference type.
    referenceTypeID | typeID | A class visible to this class loader.
    Error Data
    INVALID_OBJECT | If this reference type has been unloaded and garbage collected.
    INVALID_CLASS_LOADER | The class loader is invalid.
    VM_DEAD | The virtual machine is not running.

    EventRequest Command Set (15)

    Set Command (1)
    Set an event request. When the event described by this request occurs, an event is sent from the target VM. If an event occurs that has not been requested then it is not sent from the target VM. The two exceptions to this are the VM Start Event and the VM Death Event which are automatically generated events - see Composite Command for further details.
    Out Data
    byte | eventKind | Event kind to request. See JDWP.EventKind for a complete list of events that can be requested.
    byte | suspendPolicy | What threads are suspended when this event occurs? Note that the order of events and command replies accurately reflects the order in which threads are suspended and resumed. For example, if a VM-wide resume is processed before an event occurs which suspends the VM, the reply to the resume command will be written to the transport before the suspending event.
    intmodifiersConstraints used to control the number of generated events.Modifiers specify additional tests that an event must satisfy before it is placed in the event queue. Events are filtered by applying each modifier to an event in the order they are specified in this collection Only events that satisfy all modifiers are reported. A value of 0 means there are no modifiers in the request.

    Filtering can improve debugger performance dramatically by reducing the amount of event traffic sent from the target VM to the debugger VM.

    Repeated modifiers times:
    byte | modKind | Modifier kind
    Case Count - if modKind is 1: Limit the requested event to be reported at most once after a given number of occurrences. The event is not reported the first count - 1 times this filter is reached. To request a one-off event, call this method with a count of 1.

    Once the count reaches 0, any subsequent filters in this request are applied. If none of those filters cause the event to be suppressed, the event is reported. Otherwise, the event is not reported. In either case subsequent events are never reported for this request. This modifier can be used with any event kind.

    int | count | Count before event. One for one-off.
    Case Conditional - if modKind is 2: Conditional on expression
    int | exprID | For the future
    Case ThreadOnly - if modKind is 3: Restricts reported events to those in the given thread. This modifier can be used with any event kind except for class unload.
    threadID | thread | Required thread
    Case ClassOnly - if modKind is 4: For class prepare events, restricts the events generated by this request to be the preparation of the given reference type and any subtypes. For monitor wait and waited events, restricts the events generated by this request to those whose monitor object is of the given reference type or any of its subtypes. For other events, restricts the events generated by this request to those whose location is in the given reference type or any of its subtypes. An event will be generated for any location in a reference type that can be safely cast to the given reference type. This modifier can be used with any event kind except class unload, thread start, and thread end.
    referenceTypeID | clazz | Required class
    Case ClassMatch - if modKind is 5: Restricts reported events to those for classes whose name matches the given restricted regular expression. For class prepare events, the prepared class name is matched. For class unload events, the unloaded class name is matched. For monitor wait and waited events, the name of the class of the monitor object is matched. For other events, the class name of the event's location is matched. This modifier can be used with any event kind except thread start and thread end.
    string | classPattern | Required class pattern. Matches are limited to exact matches of the given class pattern and matches of patterns that begin or end with '*'; for example, "*.Foo" or "java.*".
    Case ClassExclude - if modKind is 6: Restricts reported events to those for classes whose name does not match the given restricted regular expression. For class prepare events, the prepared class name is matched. For class unload events, the unloaded class name is matched. For monitor wait and waited events, the name of the class of the monitor object is matched. For other events, the class name of the event's location is matched. This modifier can be used with any event kind except thread start and thread end.
    string | classPattern | Disallowed class pattern. Matches are limited to exact matches of the given class pattern and matches of patterns that begin or end with '*'; for example, "*.Foo" or "java.*".
    Case LocationOnly - if modKind is 7: Restricts reported events to those that occur at the given location. This modifier can be used with breakpoint, field access, field modification, step, and exception event kinds.
    location | loc | Required location
    Case ExceptionOnly - if modKind is 8: Restricts reported exceptions by their class and whether they are caught or uncaught. This modifier can be used with exception event kinds only.
    referenceTypeID | exceptionOrNull | Exception to report. Null (0) means report exceptions of all types. A non-null type restricts the reported exception events to exceptions of the given type or any of its subtypes.
    boolean | caught | Report caught exceptions
    boolean | uncaught | Report uncaught exceptions. Note that it is not always possible to determine whether an exception is caught or uncaught at the time it is thrown. See the exception event catch location under composite events for more information.
    Case FieldOnly - if modKind is 9: Restricts reported events to those that occur for a given field. This modifier can be used with field access and field modification event kinds only.
    referenceTypeID | declaring | Type in which field is declared.
    fieldID | fieldID | Required field
    Case Step - if modKind is 10: Restricts reported step events to those which satisfy depth and size constraints. This modifier can be used with step event kinds only.
    threadID | thread | Thread in which to step
    int | size | size of each step. See JDWP.StepSize
    int | depth | relative call stack limit. See JDWP.StepDepth
    Case InstanceOnly - if modKind is 11: Restricts reported events to those whose active 'this' object is the given object. Match value is the null object for static methods. This modifier can be used with any event kind except class prepare, class unload, thread start, and thread end. Introduced in JDWP version 1.4.
    objectID | instance | Required 'this' object
    Case SourceNameMatch - if modKind is 12: Restricts reported class prepare events to those for reference types which have a source name which matches the given restricted regular expression. The source names are determined by the reference type's SourceDebugExtension. This modifier can only be used with class prepare events. Since JDWP version 1.6. Requires the canUseSourceNameFilters capability - see CapabilitiesNew.
    string | sourceNamePattern | Required source name pattern. Matches are limited to exact matches of the given pattern and matches of patterns that begin or end with '*'; for example, "*.Foo" or "java.*".
    Reply Data
    int requestID ID of created request
    Error Data
    INVALID_THREAD | Passed thread is null, is not a valid thread or has exited.
    INVALID_CLASS | Invalid class.
    INVALID_STRING | The string is invalid.
    INVALID_OBJECT | If this reference type has been unloaded and garbage collected.
    INVALID_COUNT | The count is invalid.
    INVALID_FIELDID | Invalid field.
    INVALID_METHODID | Invalid method.
    INVALID_LOCATION | Invalid location.
    INVALID_EVENT_TYPE | The specified event type id is not recognized.
    NOT_IMPLEMENTED | The functionality is not implemented in this virtual machine.
    VM_DEAD | The virtual machine is not running.
    Clear Command (2)
    Clear an event request. See JDWP.EventKind for a complete list of events that can be cleared. Only the event request matching the specified event kind and requestID is cleared. If there isn't a matching event request the command is a no-op and does not result in an error. Automatically generated events do not have a corresponding event request and may not be cleared using this command.
    Out Data
    byte | eventKind | Event kind to clear
    int | requestID | ID of request to clear
    Reply Data
    (None)
    Error Data
    VM_DEAD | The virtual machine is not running.
    INVALID_EVENT_TYPE | The specified event type id is not recognized.
    ClearAllBreakpoints Command (3)
    Removes all set breakpoints, a no-op if there are no breakpoints set.
    Out Data
    (None)
    Reply Data
    (None)
    Error Data
    VM_DEAD The virtual machine is not running.

    StackFrame Command Set (16)

    GetValues Command (1)
    Returns the value of one or more local variables in a given frame. Each variable must be visible at the frame's code index. Even if local variable information is not available, values can be retrieved if the front-end is able to determine the correct local variable index. (Typically, this index can be determined for method arguments from the method signature without access to the local variable table information.)
    Out Data
    threadID | thread | The frame's thread.
    frameID | frame | The frame ID.
    int | slots | The number of values to get.
    Repeated slots times:
    int | slot | The local variable's index in the frame.
    byte | sigbyte | A tag identifying the type of the variable
    Reply Data
    int | values | The number of values retrieved, always equal to slots, the number of values to get.
    Repeated values times:
    value | slotValue | The value of the local variable.
    Error Data
    INVALID_THREAD | Passed thread is null, is not a valid thread or has exited.
    INVALID_OBJECT | If this reference type has been unloaded and garbage collected.
    INVALID_FRAMEID | Invalid jframeID.
    INVALID_SLOT | Invalid slot.
    VM_DEAD | The virtual machine is not running.
    SetValues Command (2)
    Sets the value of one or more local variables. Each variable must be visible at the current frame code index. For primitive values, the value's type must match the variable's type exactly. For object values, there must be a widening reference conversion from the value's type to the variable's type and the variable's type must be loaded.

    Even if local variable information is not available, values can be set, if the front-end is able to determine the correct local variable index. (Typically, this index can be determined for method arguments from the method signature without access to the local variable table information.)

    Out Data
    threadID | thread | The frame's thread.
    frameID | frame | The frame ID.
    int | slotValues | The number of values to set.
    Repeated slotValues times:
    int | slot | The slot ID.
    value | slotValue | The value to set.
    Reply Data
    (None)
    Error Data
    INVALID_THREAD | Passed thread is null, is not a valid thread or has exited.
    INVALID_OBJECT | If this reference type has been unloaded and garbage collected.
    INVALID_FRAMEID | Invalid jframeID.
    VM_DEAD | The virtual machine is not running.
    ThisObject Command (3)
    Returns the value of the 'this' reference for this frame. If the frame's method is static or native, the reply will contain the null object reference.
    Out Data
    threadID | thread | The frame's thread.
    frameID | frame | The frame ID.
    Reply Data
    tagged-objectID objectThis The 'this' object for this frame.
    Error Data
    INVALID_THREAD | Passed thread is null, is not a valid thread or has exited.
    INVALID_OBJECT | If this reference type has been unloaded and garbage collected.
    INVALID_FRAMEID | Invalid jframeID.
    VM_DEAD | The virtual machine is not running.
    PopFrames Command (4)
    Pop the top-most stack frames of the thread stack, up to, and including 'frame'. The thread must be suspended to perform this command. The top-most stack frames are discarded and the stack frame previous to 'frame' becomes the current frame. The operand stack is restored -- the argument values are added back and if the invoke was not invokestatic, objectref is added back as well. The Java virtual machine program counter is restored to the opcode of the invoke instruction.

    Since JDWP version 1.4. Requires canPopFrames capability - see CapabilitiesNew.

    Out Data
    threadID | thread | The thread object ID.
    frameID | frame | The frame ID.
    Reply Data
    (None)
    Error Data
    INVALID_THREAD | Passed thread is null, is not a valid thread or has exited.
    INVALID_OBJECT | thread is not a known ID.
    INVALID_FRAMEID | Invalid jframeID.
    THREAD_NOT_SUSPENDED | If the specified thread has not been suspended by an event.
    NO_MORE_FRAMES | There are no more Java or JNI frames on the call stack.
    INVALID_FRAMEID | Invalid jframeID.
    NOT_IMPLEMENTED | The functionality is not implemented in this virtual machine.
    VM_DEAD | The virtual machine is not running.

    ClassObjectReference Command Set (17)

    ReflectedType Command (1)
    Returns the reference type reflected by this class object.
    Out Data
    classObjectID classObject The class object.
    Reply Data
    byte | refTypeTag | Kind of following reference type.
    referenceTypeID | typeID | reflected reference type
    Error Data
    INVALID_OBJECT | If this reference type has been unloaded and garbage collected.
    VM_DEAD | The virtual machine is not running.

    Event Command Set (64)

    Composite Command (100)
    Several events may occur at a given time in the target VM. For example, there may be more than one breakpoint request for a given location or you might single step to the same location as a breakpoint request. These events are delivered together as a composite event. For uniformity, a composite event is always used to deliver events, even if there is only one event to report.

    The events that are grouped in a composite event are restricted in the following ways:

    • Only with other thread start events for the same thread:
      • Thread Start Event
    • Only with other thread death events for the same thread:
      • Thread Death Event
    • Only with other class prepare events for the same class:
      • Class Prepare Event
    • Only with other class unload events for the same class:
      • Class Unload Event
    • Only with other access watchpoint events for the same field access:
      • Access Watchpoint Event
    • Only with other modification watchpoint events for the same field modification:
      • Modification Watchpoint Event
    • Only with other Monitor contended enter events for the same monitor object:
      • Monitor Contended Enter Event
    • Only with other Monitor contended entered events for the same monitor object:
      • Monitor Contended Entered Event
    • Only with other Monitor wait events for the same monitor object:
      • Monitor Wait Event
    • Only with other Monitor waited events for the same monitor object:
      • Monitor Waited Event
    • Only with other ExceptionEvents for the same exception occurrance:
      • ExceptionEvent
    • Only with other members of this group, at the same location and in the same thread:
      • Breakpoint Event
      • Step Event
      • Method Entry Event
      • Method Exit Event

    The VM Start Event and VM Death Event are automatically generated events. This means they do not need to be requested using the EventRequest.Set command. The VM Start event signals the completion of VM initialization. The VM Death event signals the termination of the VM.If there is a debugger connected at the time when an automatically generated event occurs it is sent from the target VM. Automatically generated events may also be requested using the EventRequest.Set command and thus multiple events of the same event kind will be sent from the target VM when an event occurs.Automatically generated events are sent with the requestID field in the Event Data set to 0. The value of the suspendPolicy field in the Event Data depends on the event. For the automatically generated VM Start Event the value of suspendPolicy is not defined and is therefore implementation or configuration specific. In the Sun implementation, for example, the suspendPolicy is specified as an option to the JDWP agent at launch-time.The automatically generated VM Death Event will have the suspendPolicy set to NONE.

    Event Data
    byte | suspendPolicy | Which threads where suspended by this composite event?
    int | events | Events in set.
    Repeated events times:
    byte | eventKind | Event kind selector
    Case VMStart - if eventKind is JDWP.EventKind.VM_START: Notification of initialization of a target VM. This event is received before the main thread is started and before any application code has been executed. Before this event occurs a significant amount of system code has executed and a number of system classes have been loaded. This event is always generated by the target VM, even if not explicitly requested.
    int | requestID | Request that generated event (or 0 if this event is automatically generated.
    threadID | thread | Initial thread
    Case SingleStep - if eventKind is JDWP.EventKind.SINGLE_STEP: Notification of step completion in the target VM. The step event is generated before the code at its location is executed.
    int | requestID | Request that generated event
    threadID | thread | Stepped thread
    location | location | Location stepped to
    Case Breakpoint - if eventKind is JDWP.EventKind.BREAKPOINT: Notification of a breakpoint in the target VM. The breakpoint event is generated before the code at its location is executed.
    int | requestID | Request that generated event
    threadID | thread | Thread which hit breakpoint
    location | location | Location hit
    Case MethodEntry - if eventKind is JDWP.EventKind.METHOD_ENTRY: Notification of a method invocation in the target VM. This event is generated before any code in the invoked method has executed. Method entry events are generated for both native and non-native methods.

    In some VMs method entry events can occur for a particular thread before its thread start event occurs if methods are called as part of the thread's initialization.

    int | requestID | Request that generated event
    threadID | thread | Thread which entered method
    location | location | The initial executable location in the method.
    Case MethodExit - if eventKind is JDWP.EventKind.METHOD_EXIT: Notification of a method return in the target VM. This event is generated after all code in the method has executed, but the location of this event is the last executed location in the method. Method exit events are generated for both native and non-native methods. Method exit events are not generated if the method terminates with a thrown exception.
    int | requestID | Request that generated event
    threadID | thread | Thread which exited method
    location | location | Location of exit
    Case MethodExitWithReturnValue - if eventKind is JDWP.EventKind.METHOD_EXIT_WITH_RETURN_VALUE: Notification of a method return in the target VM. This event is generated after all code in the method has executed, but the location of this event is the last executed location in the method. Method exit events are generated for both native and non-native methods. Method exit events are not generated if the method terminates with a thrown exception.

    Since JDWP version 1.6.

    int | requestID | Request that generated event
    threadID | thread | Thread which exited method
    location | location | Location of exit
    value | value | Value that will be returned by the method
    Case MonitorContendedEnter - if eventKind is JDWP.EventKind.MONITOR_CONTENDED_ENTER: Notification that a thread in the target VM is attempting to enter a monitor that is already acquired by another thread.

    Since JDWP version 1.6.

    int | requestID | Request that generated event
    threadID | thread | Thread which is trying to enter the monitor
    tagged-objectID | object | Monitor object reference
    location | location | Location of contended monitor enter
    Case MonitorContendedEntered - if eventKind is JDWP.EventKind.MONITOR_CONTENDED_ENTERED: Notification of a thread in the target VM is entering a monitor after waiting for it to be released by another thread.

    Since JDWP version 1.6.

    int | requestID | Request that generated event
    threadID | thread | Thread which entered monitor
    tagged-objectID | object | Monitor object reference
    location | location | Location of contended monitor enter
    Case MonitorWait - if eventKind is JDWP.EventKind.MONITOR_WAIT: Notification of a thread about to wait on a monitor object.

    Since JDWP version 1.6.

    int | requestID | Request that generated event
    threadID | thread | Thread which is about to wait
    tagged-objectID | object | Monitor object reference
    location | location | Location at which the wait will occur
    long | timeout | Thread wait time in milliseconds
    Case MonitorWaited - if eventKind is JDWP.EventKind.MONITOR_WAITED: Notification that a thread in the target VM has finished waiting on a monitor object.

    Since JDWP version 1.6.

    int | requestID | Request that generated event
    threadID | thread | Thread which waited
    tagged-objectID | object | Monitor object reference
    location | location | Location at which the wait occured
    boolean | timed_out | True if timed out
    Case Exception - if eventKind is JDWP.EventKind.EXCEPTION: Notification of an exception in the target VM. If the exception is thrown from a non-native method, the exception event is generated at the location where the exception is thrown. If the exception is thrown from a native method, the exception event is generated at the first non-native location reached after the exception is thrown.
    int | requestID | Request that generated event
    threadID | thread | Thread with exception
    location | location | Location of exception throw (or first non-native location after throw if thrown from a native method)
    tagged-objectID | exception | Thrown exception
    locationcatchLocationLocation of catch, or 0 if not caught. An exception is considered to be caught if, at the point of the throw, the current location is dynamically enclosed in a try statement that handles the exception. (See the JVM specification for details). If there is such a try statement, the catch location is the first location in the appropriate catch clause.

    If there are native methods in the call stack at the time of the exception, there are important restrictions to note about the returned catch location. In such cases, it is not possible to predict whether an exception will be handled by some native method on the call stack. Thus, it is possible that exceptions considered uncaught here will, in fact, be handled by a native method and not cause termination of the target VM. Furthermore, it cannot be assumed that the catch location returned here will ever be reached by the throwing thread. If there is a native frame between the current location and the catch location, the exception might be handled and cleared in that native method instead.

    Note that compilers can generate try-catch blocks in some cases where they are not explicit in the source code; for example, the code generated for synchronized and finally blocks can contain implicit try-catch blocks. If such an implicitly generated try-catch is present on the call stack at the time of the throw, the exception will be considered caught even though it appears to be uncaught from examination of the source code.

    Case ThreadStart - if eventKind is JDWP.EventKind.THREAD_START: Notification of a new running thread in the target VM. The new thread can be the result of a call to java.lang.Thread.start or the result of attaching a new thread to the VM though JNI. The notification is generated by the new thread some time before its execution starts. Because of this timing, it is possible to receive other events for the thread before this event is received. (Notably, Method Entry Events and Method Exit Events might occur during thread initialization. It is also possible for the VirtualMachine AllThreads command to return a thread before its thread start event is received.

    Note that this event gives no information about the creation of the thread object which may have happened much earlier, depending on the VM being debugged.

    int | requestID | Request that generated event
    threadID | thread | Started thread
    Case ThreadDeath - if eventKind is JDWP.EventKind.THREAD_DEATH: Notification of a completed thread in the target VM. The notification is generated by the dying thread before it terminates. Because of this timing, it is possible for {@link VirtualMachine#allThreads} to return this thread after this event is received.

    Note that this event gives no information about the lifetime of the thread object. It may or may not be collected soon depending on what references exist in the target VM.

    int | requestID | Request that generated event
    threadID | thread | Ending thread
    Case ClassPrepare - if eventKind is JDWP.EventKind.CLASS_PREPARE: Notification of a class prepare in the target VM. See the JVM specification for a definition of class preparation. Class prepare events are not generated for primtiive classes (for example, java.lang.Integer.TYPE).
    int | requestID | Request that generated event
    threadIDthreadPreparing thread. In rare cases, this event may occur in a debugger system thread within the target VM. Debugger threads take precautions to prevent these events, but they cannot be avoided under some conditions, especially for some subclasses of java.lang.Error. If the event was generated by a debugger system thread, the value returned by this method is null, and if the requested suspend policy for the event was EVENT_THREAD all threads will be suspended instead, and the composite event's suspend policy will reflect this change.

    Note that the discussion above does not apply to system threads created by the target VM during its normal (non-debug) operation.

    byte | refTypeTag | Kind of reference type. See JDWP.TypeTag
    referenceTypeID | typeID | Type being prepared
    string | signature | Type signature
    int | status | Status of type. See JDWP.ClassStatus
    Case ClassUnload - if eventKind is JDWP.EventKind.CLASS_UNLOAD: Notification of a class unload in the target VM.

    There are severe constraints on the debugger back-end during garbage collection, so unload information is greatly limited.

    int | requestID | Request that generated event
    string | signature | Type signature
    Case FieldAccess - if eventKind is JDWP.EventKind.FIELD_ACCESS: Notification of a field access in the target VM. Field modifications are not considered field accesses. Requires canWatchFieldAccess capability - see CapabilitiesNew.
    int | requestID | Request that generated event
    threadID | thread | Accessing thread
    location | location | Location of access
    byte | refTypeTag | Kind of reference type. See JDWP.TypeTag
    referenceTypeID | typeID | Type of field
    fieldID | fieldID | Field being accessed
    tagged-objectID | object | Object being accessed (null=0 for statics
    Case FieldModification - if eventKind is JDWP.EventKind.FIELD_MODIFICATION: Notification of a field modification in the target VM. Requires canWatchFieldModification capability - see CapabilitiesNew.
    int | requestID | Request that generated event
    threadID | thread | Modifying thread
    location | location | Location of modify
    byte | refTypeTag | Kind of reference type. See JDWP.TypeTag
    referenceTypeID | typeID | Type of field
    fieldID | fieldID | Field being modified
    tagged-objectID | object | Object being modified (null=0 for statics
    value | valueToBe | Value to be assigned
    Case VMDeath - if eventKind is JDWP.EventKind.VM_DEATH:
    int | requestID | Request that generated event

    Error Constants

    NONE | 0 | No error has occurred.
    INVALID_THREAD | 10 | Passed thread is null, is not a valid thread or has exited.
    INVALID_THREAD_GROUP | 11 | Thread group invalid.
    INVALID_PRIORITY | 12 | Invalid priority.
    THREAD_NOT_SUSPENDED | 13 | If the specified thread has not been suspended by an event.
    THREAD_SUSPENDED | 14 | Thread already suspended.
    THREAD_NOT_ALIVE | 15 | Thread has not been started or is now dead.
    INVALID_OBJECT | 20 | If this reference type has been unloaded and garbage collected.
    INVALID_CLASS | 21 | Invalid class.
    CLASS_NOT_PREPARED | 22 | Class has been loaded but not yet prepared.
    INVALID_METHODID | 23 | Invalid method.
    INVALID_LOCATION | 24 | Invalid location.
    INVALID_FIELDID | 25 | Invalid field.
    INVALID_FRAMEID | 30 | Invalid jframeID.
    NO_MORE_FRAMES | 31 | There are no more Java or JNI frames on the call stack.
    OPAQUE_FRAME | 32 | Information about the frame is not available.
    NOT_CURRENT_FRAME | 33 | Operation can only be performed on current frame.
    TYPE_MISMATCH | 34 | The variable is not an appropriate type for the function used.
    INVALID_SLOT | 35 | Invalid slot.
    DUPLICATE | 40 | Item already set.
    NOT_FOUND | 41 | Desired element not found.
    INVALID_MONITOR | 50 | Invalid monitor.
    NOT_MONITOR_OWNER | 51 | This thread doesn't own the monitor.
    INTERRUPT | 52 | The call has been interrupted before completion.
    INVALID_CLASS_FORMAT | 60 | The virtual machine attempted to read a class file and determined that the file is malformed or otherwise cannot be interpreted as a class file.
    CIRCULAR_CLASS_DEFINITION | 61 | A circularity has been detected while initializing a class.
    FAILS_VERIFICATION | 62 | The verifier detected that a class file, though well formed, contained some sort of internal inconsistency or security problem.
    ADD_METHOD_NOT_IMPLEMENTED | 63 | Adding methods has not been implemented.
    SCHEMA_CHANGE_NOT_IMPLEMENTED | 64 | Schema change has not been implemented.
    INVALID_TYPESTATE | 65 | The state of the thread has been modified, and is now inconsistent.
    HIERARCHY_CHANGE_NOT_IMPLEMENTED | 66 | A direct superclass is different for the new class version, or the set of directly implemented interfaces is different and canUnrestrictedlyRedefineClasses is false.
    DELETE_METHOD_NOT_IMPLEMENTED | 67 | The new class version does not declare a method declared in the old class version and canUnrestrictedlyRedefineClasses is false.
    UNSUPPORTED_VERSION | 68 | A class file has a version number not supported by this VM.
    NAMES_DONT_MATCH | 69 | The class name defined in the new class file is different from the name in the old class object.
    CLASS_MODIFIERS_CHANGE_NOT_IMPLEMENTED | 70 | The new class version has different modifiers and and canUnrestrictedlyRedefineClasses is false.
    METHOD_MODIFIERS_CHANGE_NOT_IMPLEMENTED | 71 | A method in the new class version has different modifiers than its counterpart in the old class version and and canUnrestrictedlyRedefineClasses is false.
    NOT_IMPLEMENTED | 99 | The functionality is not implemented in this virtual machine.
    NULL_POINTER | 100 | Invalid pointer.
    ABSENT_INFORMATION | 101 | Desired information is not available.
    INVALID_EVENT_TYPE | 102 | The specified event type id is not recognized.
    ILLEGAL_ARGUMENT | 103 | Illegal argument.
    OUT_OF_MEMORY | 110 | The function needed to allocate memory and no more memory was available for allocation.
    ACCESS_DENIED | 111 | Debugging has not been enabled in this virtual machine. JVMTI cannot be used.
    VM_DEAD | 112 | The virtual machine is not running.
    INTERNAL | 113 | An unexpected internal error has occurred.
    UNATTACHED_THREAD | 115 | The thread being used to call this function is not attached to the virtual machine. Calls must be made from attached threads.
    INVALID_TAG | 500 | object type id or class tag.
    ALREADY_INVOKING | 502 | Previous invoke not complete.
    INVALID_INDEX | 503 | Index is invalid.
    INVALID_LENGTH | 504 | The length is invalid.
    INVALID_STRING | 506 | The string is invalid.
    INVALID_CLASS_LOADER | 507 | The class loader is invalid.
    INVALID_ARRAY | 508 | The array is invalid.
    TRANSPORT_LOAD | 509 | Unable to load the transport.
    TRANSPORT_INIT | 510 | Unable to initialize the transport.
    NATIVE_METHOD | 511
    INVALID_COUNT | 512 | The count is invalid.

    EventKind Constants

    SINGLE_STEP | 1
    BREAKPOINT | 2
    FRAME_POP | 3
    EXCEPTION | 4
    USER_DEFINED | 5
    THREAD_START | 6
    THREAD_DEATH | 7
    THREAD_END | 7 | obsolete - was used in jvmdi
    CLASS_PREPARE | 8
    CLASS_UNLOAD | 9
    CLASS_LOAD | 10
    FIELD_ACCESS | 20
    FIELD_MODIFICATION | 21
    EXCEPTION_CATCH | 30
    METHOD_ENTRY | 40
    METHOD_EXIT | 41
    METHOD_EXIT_WITH_RETURN_VALUE | 42
    MONITOR_CONTENDED_ENTER | 43
    MONITOR_CONTENDED_ENTERED | 44
    MONITOR_WAIT | 45
    MONITOR_WAITED | 46
    VM_START | 90
    VM_INIT | 90 | obsolete - was used in jvmdi
    VM_DEATH | 99
    VM_DISCONNECTED | 100 | Never sent across JDWP

    ThreadStatus Constants

    ZOMBIE | 0
    RUNNING | 1
    SLEEPING | 2
    MONITOR | 3
    WAIT | 4

    SuspendStatus Constants

    SUSPEND_STATUS_SUSPENDED 0x1

    ClassStatus Constants

    VERIFIED | 1
    PREPARED | 2
    INITIALIZED | 4
    ERROR | 8

    TypeTag Constants

    CLASS | 1 | ReferenceType is a class.
    INTERFACE | 2 | ReferenceType is an interface.
    ARRAY | 3 | ReferenceType is an array.

    Tag Constants

    ARRAY | 91 | '[' - an array object (objectID size).
    BYTE | 66 | 'B' - a byte value (1 byte).
    CHAR | 67 | 'C' - a character value (2 bytes).
    OBJECT | 76 | 'L' - an object (objectID size).
    FLOAT | 70 | 'F' - a float value (4 bytes).
    DOUBLE | 68 | 'D' - a double value (8 bytes).
    INT | 73 | 'I' - an int value (4 bytes).
    LONG | 74 | 'J' - a long value (8 bytes).
    SHORT | 83 | 'S' - a short value (2 bytes).
    VOID | 86 | 'V' - a void value (no bytes).
    BOOLEAN | 90 | 'Z' - a boolean value (1 byte).
    STRING | 115 | 's' - a String object (objectID size).
    THREAD | 116 | 't' - a Thread object (objectID size).
    THREAD_GROUP | 103 | 'g' - a ThreadGroup object (objectID size).
    CLASS_LOADER | 108 | 'l' - a ClassLoader object (objectID size).
    CLASS_OBJECT | 99 | 'c' - a class object object (objectID size).

    StepDepth Constants

    INTO | 0 | Step into any method calls that occur before the end of the step.
    OVER | 1 | Step over any method calls that occur before the end of the step.
    OUT | 2 | Step out of the current method.

    StepSize Constants

    MIN | 0 | Step by the minimum possible amount (often a bytecode instruction).
    LINE | 1 | Step to the next source line unless there is no line number information in which case a MIN step is done instead.

    SuspendPolicy Constants

    NONE | 0 | Suspend no threads when this event is encountered.
    EVENT_THREAD | 1 | Suspend the event thread when this event is encountered.
    ALL | 2 | Suspend all threads when this event is encountered.

    InvokeOptions Constants

    The invoke options are a combination of zero or more of the following bit flags:
    INVOKE_SINGLE_THREADED | 0x01 | otherwise, all threads started.
    INVOKE_NONVIRTUAL | 0x02 | otherwise, normal virtual invoke (instance methods only)


Java(tm) Debug Wire Protocol

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

JavaTM Debug Wire Protocol

Protocol details

Overview

The JavaTM Debug Wire Protocol (JDWP) is the protocol used for communication between a debugger and the Java virtual machine (VM) which it debugs (hereafter called the target VM). JDWP is optional; it might not be available in some implementations of the Java(TM) 2 SDK. The existence of JDWP can allow the same debugger to work

  • in a different process on the same computer, or
  • on a remote computer,

The JDWP differs from many protocol specifications in that it only details format and layout, not transport. A JDWP implementation can be designed to accept different transport mechanisms through a simple API. A particular transport does not necessarily support each of the debugger/target VM combinations listed above.

The JDWP is designed to be simple enough for easy implementation, yet it is flexible enough for future growth.

Currently, the JDWP does not specify any mechanism for transport rendezvous or any directory services. This may be changed in the future, but it may be addressed in a separate document.

JDWP is one layer within the Java Platform Debugger Architecture (JPDA). This architecture also contains the higher-level Java Debug Interface (JDI). The JDWP is designed to facilitate efficient use by the JDI; many of its abilities are tailored to that end. The JDI is more appropriate than JDWP for many debugger tools, particularly those written in the Java programming language. For more information on the Java Platform Debugger Architecture, see the Java Platform Debugger Architecture documentation for this release.

JDWP Start Up

After the transport connection is established and before any packets are sent, a handshake occurs between the two sides of the connection:

The handshake process has the following steps:

  • The debugger side sends 14 bytes to the VM side, consisting of the 14 ASCII characters of the string "JDWP-Handshake".
  • The VM side replies with the same 14 bytes: JDWP-Handshake

JDWP Packets

The JDWP is packet based and is not stateful. There are two basic packet types: command packets and reply packets.

Command packets may be sent by either the debugger or the target VM. They are used by the debugger to request information from the target VM, or to control program execution. Command packets are sent by the target VM to notify the debugger of some event in the target VM such as a breakpoint or exception.

A reply packet is sent only in response to a command packet and always provides information success or failure of the command. Reply packets may also carry data requested in the command (for example, the value of a field or variable). Currently, events sent from the target VM do not require a response packet from the debugger.

The JDWP is asynchronous; multiple command packets may be sent before the first reply packet is received.

Command and reply packet headers are equal in size; this is to make transports easier to implement and abstract. The layout of each packet looks like this:

Command Packet
  • Header
    • length (4 bytes)
    • id (4 bytes)
    • flags (1 byte)
    • command set (1 byte)
    • command (1 byte)
  • data (Variable)
Reply Packet
  • Header
    • length (4 bytes)
    • id (4 bytes)
    • flags (1 byte)
    • error code (2 bytes)
  • data (Variable)

All fields and data sent via JDWP should be in big-endian format. (See the Java Virtual Machine Specification for the definition of big-endian.) The first three fields are identical in both packet types.

Command and Reply Packet Fields

Shared Header Fields

length
The length field is the size, in bytes, of the entire packet, including the length field. The header size is 11 bytes, so a packet with no data would set this field to 11.
id
The id field is used to uniquely identify each packet command/reply pair. A reply packet has the same id as the command packet to which it replies. This allows asynchronous commands and replies to be matched. The id field must be unique among all outstanding commands sent from one source. (Outstanding commands originating from the debugger may use the same id as outstanding commands originating from the target VM.) Other than that, there are no requirements on the allocation of id's.

A simple monotonic counter should be adequate for most implementations. It will allow 2^32 unique outstanding packets and is the simplest implementation alternative.

flags
Flags are used to alter how any command is queued and processed and to tag command packets that originate from the target VM. There is currently one flag bits defined; future versions of the protocol may define additional flags.
0x80
Reply packet

The reply bit, when set, indicates that this packet is a reply.

Command Packet Header Fields

command set
This field is useful as a means for grouping commands in a meaningful way. The Sun defined command sets are used to group commands by the interfaces they support in the JDI. For example, all commands that support the JDI VirtualMachine interface are grouped in a VirtualMachine command set.

The command set space is roughly divided as follows:

0 - 63
Sets of commands sent to the target VM
64 - 127
Sets of commands sent to the debugger
128 - 256
Vendor-defined commands and extensions.
command
This field identifies a particular command in a command set. This field, together with the command set field, is used to indicate how the command packet should be processed. More succinctly, they tell the receiver what to do. Specific commands are presented later in this document.

Reply Packet Header Fields

error code
This field is used to indicate if the command packet that is being replied too was successfully processed. A value of zero indicates success, a non-zero value indicates an error. The error code returned may be specific to each command set/command, but it is often mapped to a JVM TI error code.

Data

The data field is unique to each command set/command. It is also different between command and reply packet pairs. For example, a command packet that requests a field value will contain references to the object and field id's for the desired value in its data field. The reply packet's data field will contain the value of the field.

Detailed Command Information

In general, the data field of a command or reply packet is an abstraction of a group of multiple fields that define the command or reply data. Each subfield of a data field is encoded in big endian (Java) format. The detailed composition of data fields for each command and its reply are described in this section.

There is a small set of common data types that are common to many of the different JDWP commands and replies. They are described below.

Name | Size | Description
byte | 1 byte | A byte value.
boolean | 1 byte | A boolean value, encoded as 0 for false and non-zero for true.
int | 4 bytes | An four-byte integer value. The integer is signed unless explicitly stated to be unsigned.
long | 8 bytes | An eight-byte integer value. The value is signed unless explicitly stated to be unsigned.
objectID Target VM-specific, up to 8 bytes (see below) Uniquely identifies an object in the target VM. A particular object will be identified by exactly one objectID in JDWP commands and replies throughout its lifetime (or until the objectID is explicitly disposed). An ObjectID is not reused to identify a different object unless it has been explicitly disposed, regardless of whether the referenced object has been garbage collected. An objectID of 0 represents a null object.

Note that the existence of an object ID does not prevent the garbage collection of the object. Any attempt to access a a garbage collected object with its object ID will result in the INVALID_OBJECT error code. Garbage collection can be disabled with the DisableCollection command, but it is not usually necessary to do so.
tagged-objectID | size of objectID plus one byte | The first byte is a signature byte which is used to identify the object's type. See JDWP.Tag for the possible values of this byte (note that only object tags, not primitive tags, may be used). It is followed immediately by the objectID itself.
threadID | same as objectID | Uniquely identifies an object in the target VM that is known to be a thread
threadGroupID | same as objectID | Uniquely identifies an object in the target VM that is known to be a thread group
stringID | same as objectID | Uniquely identifies an object in the target VM that is known to be a string object. Note: this is very different from string, which is a value.
classLoaderID | same as objectID | Uniquely identifies an object in the target VM that is known to be a class loader object
classObjectID | same as objectID | Uniquely identifies an object in the target VM that is known to be a class object.
arrayID | same as objectID | Uniquely identifies an object in the target VM that is known to be an array.
referenceTypeID | same as objectID | Uniquely identifies a reference type in the target VM. It should not be assumed that for a particular class, the classObjectID and the referenceTypeID are the same. A particular reference type will be identified by exactly one ID in JDWP commands and replies throughout its lifetime A referenceTypeID is not reused to identify a different reference type, regardless of whether the referenced class has been unloaded.
classID | same as referenceTypeID | Uniquely identifies a reference type in the target VM that is known to be a class type.
interfaceID | same as referenceTypeID | Uniquely identifies a reference type in the target VM that is known to be an interface type.
arrayTypeID | same as referenceTypeID | Uniquely identifies a reference type in the target VM that is known to be an array type.
methodID | Target VM-specific, up to 8 bytes (see below) | Uniquely identifies a method in some class in the target VM. The methodID must uniquely identify the method within its class/interface or any of its subclasses/subinterfaces/implementors. A methodID is not necessarily unique on its own; it is always paired with a referenceTypeID to uniquely identify one method. The referenceTypeID can identify either the declaring type of the method or a subtype.
fieldID | Target VM-specific, up to 8 bytes (see below) | Uniquely identifies a field in some class in the target VM. The fieldID must uniquely identify the field within its class/interface or any of its subclasses/subinterfaces/implementors. A fieldID is not necessarily unique on its own; it is always paired with a referenceTypeID to uniquely identify one field. The referenceTypeID can identify either the declaring type of the field or a subtype.
frameID | Target VM-specific, up to 8 bytes (see below) | Uniquely identifies a frame in the target VM. The frameID must uniquely identify the frame within the entire VM (not only within a given thread). The frameID need only be valid during the time its thread is suspended.
location Target VM specific An executable location. The location is identified by one byte type tag followed by a a classID followed by a methodID followed by an unsigned eight-byte index, which identifies the location within the method. Index values are restricted as follows:
  • The index of the start location for the method is less than all other locations in the method.
  • The index of the end location for the method is greater than all other locations in the method.
  • If a line number table exists for a method, locations that belong to a particular line must fall between the line's location index and the location index of the next line in the table.
Index values within a method are monotonically increasing from the first executable point in the method to the last. For many implementations, each byte-code instruction in the method has its own index, but this is not required.

The type tag is necessary to identify whether location's classID identifies a class or an interface. Almost all locations are within classes, but it is possible to have executable code in the static initializer of an interface.
string | Variable | A UTF-8 encoded string, not zero terminated, preceded by a four-byte integer length.
value | Variable | A value retrieved from the target VM. The first byte is a signature byte which is used to identify the type. See JDWP.Tag for the possible values of this byte. It is followed immediately by the value itself. This value can be an objectID (see Get ID Sizes) or a primitive value (1 to 8 bytes). More details about each value type can be found in the next table.
untagged-value | Variable | A value as described above without the signature byte. This form is used when the signature information can be determined from context.
arrayregion | Variable | A compact representation of values used with some array operations. The first byte is a signature byte which is used to identify the type. See JDWP.Tag for the possible values of this byte. Next is a four-byte integer indicating the number of values in the sequence. This is followed by the values themselves: Primitive values are encoded as a sequence of untagged-values; Object values are encoded as a sequence of values.

Object ids, reference type ids, field ids, method ids, and frame ids may be sized differently in different target VM implementations. Typically, their sizes correspond to size of the native identifiers used for these items in JNI and JVMDI calls. The maximum size of any of these types is 8 bytes. The "idSizes" command in the VirtualMachine command set is used by the debugger to determine the size of each of these types.

If a debuggee receives a Command Packet with a non-implemented or non-recognized command set or command then it returns a Reply Packet with the error code field set to NOT_IMPLEMENTED (see Error Constants).

Protocol details

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java(tm) Debug Wire Protocol Transport Interface (jdwpTransport)

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java ™ Debug Wire Protocol Transport Interface (jdwpTransport)

A transport is implemented as a series of functions in a dynamic library (sometimes called a DLL, or shared library). The library exports an onload function that is invoked by the JDWP (or other) agent at startup-time.

Like JVMTI, jdwpTransport functions are accessed through an interface pointer called the environment pointer. An environment pointer is a pointer to an environment and has type jdwpTransportEnv*. The environment pointer is returned to the JDWP (or other) agent from the onload function.

A transport may support a single environment or it may support multiple environments. In other words, a transport may be used by only one, or multiple agents at the same time. If a transport supports multiple environments then each call to the onload function will return a new environment pointer. If a transport only supports a single environment then second, and subsequent calls to the onload function will return an error.

A transport is thread-safe and jdwpTransport functions can be used by multiple concurrent threads. For example, one thread may be blocked in the jdwpTransport ReadPacket function waiting for a packet while another thread invokes WritePacket function to write a packet.

In most cases jdwpTransport functions return a jdwpTransportError value indicating return status. Some functions return additional values through pointers provided by the calling function. In cases where the return values are allocated by a jdwpTransport function then the function will use the memory allocation routine specified by the agent. The memory allocation routines are specified to the transport, at start-up, via the onload function.

In the event of an error (that is, one of the jdwpTransport functions returns a value other than JDWPTRANSPORT_ERROR_NONE) then a string representing the error can be subsequently obtained through a call to the jdwpTransport function GetLastError. Errors are recorded on a per-thread basis. The GetLastError function will return a string represetning the last error that was encountered by the current thread only.

Developing a Transport implementation

A transport library can be developed in any native language that supports C language calling conventions and C or C++ definitions.

The function, data type, and constant definitions needed for using the jdwpTransport interface are defined in the include file jdwpTransport.h. To use these definitions add the Java SE include directory to your include path :-

#include "jdwpTransport.h"

Transport Start-Up

The transport library must export an onload function with the following prototype :-

JNIEXPORT jint JNICALL
jdwpTransport_OnLoad(JavaVM *jvm,
                     jdwpTransportCallback *callback,
                     jint version,
                     jdwpTransportEnv** env);

This function will be called by the JDWP (or other agent) when the library is loaded.

The jvm argument is the JNI invocation interface obtained by agent by invoking JNI's GetJavaVM function.

The callback argument is a pointer to a function table of memory management routines that the transport must use to allocate the memory for return values that are allocated by the transport implementation :-

typedef struct jdwpTransportCallback {
    void* (*alloc)(jint numBytes);
    void (*free)(void *buffer);
} jdwpTransportCallback;

The lifespan of the callback argument is the onload function and therefore the transport must take a copy of the function table in the jdwpTransport_OnLoad function.

The function table has two entries. The alloc function allocates an area of memory. It has a single argument to specify the number of bytes to allocate. It returns a pointer to the begining of the allocated memory, or NULL if the memory request cannot be honored. If the number of bytes requested is zero then NULL is returned. The free function deallocates an area of memory that was previously allocated using the alloc function.

The memory management functions provided by the agent are thread safe and the transport implementation is not required to synchronize calls to the these functions. The implementation of the memory management functions are guaranteed not to call any jdwpTransport function.

version is the version of the transport interface that the agent expects. This must be specified as JDWPTRANSPORT_VERSION_1_0.

env is a pointer to the environment pointer returned by the function.

The jdwpTransport_OnLoad function returns JNI_OK if the transport initializes successfully. If initialization fails then one of the following errors is returned :

JNI_ENOMEM
JNI_EVERSION
JNI_EEXIST

JNI_ENOMEM is returned if there is insufficient memory to complete initialization.

JNI_EVERSION is returned if the version in the version argument is not JDWPTRANSPORT_VERSION_1_0.

JNI_EEXIST is returned if the transport only supports a single environment, and the environment pointer was previously returned by the first call to the onload function.

Functions

The jdwpTransport functions fall into these categories:

  • Connection Management
    • Attach
    • StartListening
    • StopListening
    • Accept
    • IsOpen
    • Close
  • I/O Functions
    • ReadPacket
    • WritePacket
  • Miscellaneous Functions
    • GetLastError
    • Get Capabilities

Connection Management

The connection management functions are used to establish and close the connection to the debugger. A connection provides a reliable flow of JDWP packets to and from the debugger. Packets written to a connection are read, by the debugger, in exactly the order in which they were written. Similarly, any packets written to the connection by the debugger are read in the order in which they were written.

Connections are established either actively or passively. Establishing the connection actively means that the jdwpTransport's Attach function is called to initiate the connection the debugger. Establishing the connection passively means that the jdwpTransport's StartListening function is used to put the transport into listen mode so that it listens for a connection from a debugger. Once in listen mode the Accept function is used to accept the connection. Irrespective of how the connection is established the Close function is used to close the connection, and IsOpen is used to test if a connection is open to the debugger.

Attach

jdwpTransportError
Attach(jdwpTransportEnv* env, const char* address,
       jlong attachTimeout, jlong handshakeTimeout)

Attaches to the debugger. Attaching to the debugger involves two steps. First, a connection is established to the specified address. Once a connection is established a handshake is performed to ensure that the connection is indeed established to a debugger. Handshaking involves the exchange of ASCII string JDWP-Handshake as specified in the Java Debug Wire Protocol specification.

The address argument is a pointer to a string representing the address of the debugger. The exact format is specific to the transport (In the case of a TCP/IP based transport the address may include the hostname and port number of the debugger. In the case of a transport that supports connections through a serial port it might be the device name of the serial port).

The attachTimeout argument specifies a timeout to use when attaching. If the transport supports an attach timeout (see GetCapabilities) and if the attachTimeout is positive then it specifies the timeout, in milliseconds (more or less), to use when attaching to the debugger. If the transport does not support an attach timeout, or if attachTimeout is specified as zero then a timeout is not used when attaching.

The handshakeTimeout argument specifies a timeout to use when handshaking with the debugger. If the transport supports a handshake timeout (see GetCapabilities) and if the handshakeTimeout is positive then it specifies the timeout, in milliseconds (more or less), to use when handshaking with the debugger. The exact usage of the handshake timeout is specific to the transport - for example one implementation may use the timeout as an inter-character timeout while waiting for the JDWP-Handshake message from the debugger. Another implementation may use the timeout to indicate the total duration allowed for the handshake exchange. In general the purpose of the handshake timeout is to allow for error handling in the event that the transport connects to something other than a valid debugger. If the transport does not support a handshake timeout, or if the handshakeTimeout is specified as zero then a timeout is not used when handshaking.

This function returns a universal error or one of the following errors:

JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT
JDWPTRANSPORT_ERROR_ILLEGAL_STATE
JDWPTRANSPORT_ERROR_IO_ERROR
JDWPTRANSPORT_ERROR_TIMEOUT

JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT is returned if address is invalid or timeout is negative.

JDWPTRANSPORT_ERROR_ILLEGAL_STATE is returned if the transport is currently in listen mode (see StartListening), or there is already an open connection to the debugger (see IsOpen).

JDWPTRANSPORT_ERROR_IO_ERROR is returned if there is an error (other than an attach timeout) attaching to the debugger. Note that errors during the start-up handshake (including a handshake timeout) are considered I/O errors. I/O errors are specific to the transport. GetLastError can be used to obtain a string representation of the error.

JDWPTRANSPORT_ERROR_TIMEOUT is returned if the transport supports an attach timeout, and if the attachTimeout value is positive, and if the connection to the debugger cannot be established within that attachTimeout period.

StartListening

jdwpTransportError
StartListening(jdwpTransportEnv* env, const char* address, char** actualAddress);

Puts the transport into listen mode to listen for a connection from a debugger.

The address argument is a pointer to a string representing the local address that the transport should listen on. The exact format is specific to the transport (In the case of a TCP/IP based transport the address might a local TCP port number. In the case of a transport that supports connections through a serial port it might be the device name of a serial port). The address argument can be specified as NULL or as an empty string (first character is \0). In that case the transport listens on a default address that is specific to the transport.

If actualAddress is not NULL then it is set to the address of a string returned by the StartListening function. The returned string will contain the string representation of the address that the transport is listening on. This may, or may not, differ from the address provided in the address argument. The string is allocated using the allocation callback provided to the transport when the jdwpTransport_OnLoad function was called. The caller is responsible for freeing the returned string.

This function returns a universal error or one of the following errors:

JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT
JDWPTRANSPORT_ERROR_ILLEGAL_STATE
JDWPTRANSPORT_ERROR_IO_ERROR

JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT is returned if address is invalid.

JDWPTRANSPORT_ERROR_ILLEGAL_STATE is returned if there is already an open connection to a debugger (see IsOpen), or the transport is already in listen mode.

JDWPTRANSPORT_ERROR_IO_ERROR is returned if there is an error putting the transport into listen mode. The nature of the error is specific to the transport. GetLastError can be used to obtain a string representing the error.

StopListening

jdwpTransportError
StopListening(jdwpTransportEnv* env)

Takes the transport out of listen mode so that it's no longer listening for connections from a debugger.

If the transport is in listen mode then it will be taken out of this mode. If there is an open (see IsOpen) connection to a debugger then it is unaffected by this function. In other words, StopListening does not close a connection to the debugger. If the transport is not in listen mode then this function does nothing and no error is returned.

This function returns a universal error or one of the following errors:

JDWPTRANSPORT_ERROR_IO_ERROR

JDWPTRANSPORT_ERROR_IO_ERROR is returned if there is an error taking the transport out of listen mode. The nature of the error is specific to the transport. GetLastError can be used to obtain a string representing the error.

Accept

jdwpTransportError
Accept(jdwpTransportEnv* env, jlong acceptTimeout, jlong handshakeTimeout)

Accepts a connection from a debugger. Accepting a connection from a debugger involves two steps. Firstly, a connection is established by the debugger. Once a connection is established a handshake is performed to ensure that the connection was indeed established by a debugger. Handshaking involves the exchange of ASCII string JDWP-Handshake as specified in the Java Debug Wire Protocol specification.

The acceptTimeout argument specifies the timeout to use while waiting for the debugger to connect. If the transport supports an accept timeout (see GetCapabilities) and if the acceptTimeout is positive then it specifies the timeout, in milliseconds (more or less), to use when waiting for a connection from a debugger. If the transport does not support an accept timeout, or if timeout is specified as zero then block indefinitely waiting for a connection.

The handshakeTimeout argument specifies a timeout to use when handshaking with the debugger. If the transport supports a handshake timeout (see GetCapabilities) and if the handshakeTimeout is positive then it specifies the timeout, in milliseconds (more or less), to use when handshaking with the debugger. The exact usage of the handshake timeout is specific to the transport - for example one implementation may use the timeout as an inter-character timeout while waiting for the JDWP-Handshake message from the debugger. Another implementation may use the timeout to indicate the total duration allowed for the handshake exchange. In general the purpose of the handshake timeout is to allow for error handling in the event that something other than a debugger establishes a connection to the debuggee. If the transport does not support a handshake timeout, or if the handshakeTimeout is specified as zero then a timeout is not used when handshaking.

This function returns a universal error or one of the following errors:

JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT
JDWPTRANSPORT_ERROR_ILLEGAL_STATE
JDWPTRANSPORT_ERROR_IO_ERROR
JDWPTRANSPORT_ERROR_TIMEOUT

JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT is returned if attachTimeout or handshakeTimeout is negative.

JDWPTRANSPORT_ERROR_ILLEGAL_STATE is returned if there is already an open connection to a debugger (see IsOpen), or if the transport is not in listen mode (see StartListening).

JDWPTRANSPORT_ERROR_IO_ERROR is returned if there is an error (other than an accept timeout) while accepting a connection from a debugger. Note that errors during the start-up handshake (including a handshake timeout) are considered I/O errors. The nature of the error is specific to the transport. GetLastError can be used to obtain a string representing the error.

JDWPTRANSPORT_ERROR_TIMEOUT is returned if the transport supports an accept timeout, and if the acceptTimeout value is positive, and if the connection to the debugger cannot be established within that timeout period.

Note: A thread that is blocked in Accept waiting for a connection from a debugger can be interrupted by another thread calling StopListening. In that case the thread that called Accept will return JDWPTRANSPORT_ERROR_IO_ERROR indicating an I/O error has occurred. If a thread blocked in Accept has accepted a connection and is in the process of handshaking with the debugger then StopListening will not interrupt the connection.

IsOpen

jboolean
isOpen(jdwpTransportEnv* env)

Tells whether or not there is a connection open to a debugger.

Returns JNI_TRUE if, and only if, there is an open connection to a debugger. Otherwise it returns JNI_FALSE.

Close

jdwpTransportError
Close(jdwpTransportEnv* env)

Closes an open connection to a debugger.

If there isn't an open connection to a debugger (see IsOpen) then this function does nothing and no error is returned.

If there are threads blocked in any I/O functions (namely, ReadPacket and WritePacket), then these I/O functions will be interrupted by the close and will return an JDWPTRANSPORT_ERROR_IO_ERROR indicating an I/O error has occurred.

This function returns a universal error or one of the following errors:

JDWPTRANSPORT_ERROR_IO_ERROR

JDWPTRANSPORT_ERROR_IO_ERROR is returned if there is an error closing the connection. The nature of the error is specific to the transport. GetLastError can be used to obtain a string representing the error.

I/O Functions

The I/O functions are used for reading and writing JDWP packets from and to the debugger.

ReadPacket

typedef struct {
    jint len;
    jint id;
    jbyte flags;
    jbyte cmdSet;
    jbyte cmd;
    jbyte *data;
} jdwpCmdPacket;

typedef struct {
    jint len;
    jint id;
    jbyte flags;
    jshort errorCode;
    jbyte *data;
} jdwpReplyPacket;

typedef struct jdwpPacket {
    union {
        jdwpCmdPacket cmd;
        jdwpReplyPacket reply;
    } type;
} jdwpPacket;

jdwpTransportError
ReadPacket(jdwpTransportEnv* env, jdwpPacket* packet)

Reads a JDWP packet from an open connection to a debugger.

This function does a blocking read on an open connection. It blocks indefinitely until a complete JDWP packet can be returned, or in the case of a transport based on a stream-oriented protocol, end-of-stream is encountered.

The packet argument is the address of a jdwpPacket structure that is populated by this function. The packet.type.cmd.len or packet.type.reply.len field (depending on if the packet is a command or reply packet) is populated with the length of the packet. If end of stream is encountered the length field will be set to 0 and all other fields in the packet will be undefined. If end of stream is encountered after reading some, but not all, bytes of a packet it is considered an I/O error and JDWPTRANSPORT_ERROR_IO_ERROR will be returned. In that case the length field will not be populated. When an entire packet is read then all fields in the packet are populated with values in host order. This may, or may not, differ from the big endian order require when transmitting JDWP packets.

The packet.type.cmd.data or packet.type.reply.data field (depending on if the packet is a command or reply packet) will be populated with NULL or a pointer to the packet data allocated by this function. Packet data is allocated using the allocation callback provided to the transport when the jdwpTransport_OnLoad function was called. The caller is responsible to free it. The layout of the packet data (that is the data following the header, if any) is returned to the caller in the byte ordering in which it was received.

The ReadPacket function does not do any integrity checking on the returned packet except checking that the length of the packet (as indicated by the first 4 bytes) is >= 11 bytes. If the length field is less than 11 bytes then JDWPTRANSPORT_ERROR_IO_ERROR is returned.

This function returns a universal error or one of the following errors:

JDWPTRANSPORT_ERROR_IO_ERROR
JDWPTRANSPORT_ERROR_ILLEGAL_STATE
JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT

JDWPTRANSPORT_ERROR_IO_ERROR is returned if an I/O error occurs when reading, the connection is closed asynchronously by another thread calling the Close function, or a badly formed packet (length field less than 11 bytes) is received. I/O errors are specific to the transport. GetLastError can be used to obtain a string representing the error.

JDWPTRANSPORT_ERROR_ILLEGAL_STATE is returned if there isn't an open connection to a debugger (see IsOpen).

JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT is returned if packet is NULL

WritePacket

jdwpTransportError
WritePacket(jdwpTransportEnv* env, const jdwpPacket* packet)

Writes a JDWP packet to an open connection.

The packet argument is a pointer to a jdwpPacket structure. All fields in the packet header must be stored in host order. The packet data field (packet.type.cmd.data or packet.type.reply.data) must be NULL, or a pointer to a location containing packet data that immediately follows the header. The packet data is must be in network order (big endian) ready for transmission.

This function returns a universal error or one of the following errors:

JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT
JDWPTRANSPORT_ERROR_IO_ERROR
JDWPTRANSPORT_ERROR_ILLEGAL_STATE

JDWPTRANSPORT_ERROR_ILLEGAL_ARGUMENT if packet is NULL, or if the packet length field (packet.type.cmd.len or packet.type.reply.len) is less than 11, or it is greater than 11 but the packet data field (packet.type.cmd.data or packet.type.reply.data) is NULL.

JDWPTRANSPORT_ERROR_IO_ERROR is returned if an I/O error occurs when writing, or the connection is closed asynchronously by another thread calling the Close function. I/O errors are specific to the transport. GetLastError can be used to obtain a string representing the error.

JDWPTRANSPORT_ERROR_ILLEGAL_STATE is returned if there isn't an open connection to a debugger (see IsOpen).

Miscellaneous Functions

GetLastError

jdwpTransportError
GetLastError(jdwpTransportEnv* env, char** msg);

Returns the string representation of the last error.

When an error occurs it is recorded on a per-thread basis. A subsequent call to GetLastError returns the string representation of the last I/O error.

The msg argument is a pointer to a null-terminated string returned by this function. The string is allocated using the allocation callback provided to the transport when the jdwpTransport_OnLoad function was called. The caller is responsible to free the returned string.

This function returns a universal error or one of the following errors:

JDWPTRANSPORT_ERROR_MSG_NOT_AVAILABLE

JDWPTRANSPORT_ERROR_MSG_NOT_AVAILABLE is returned if this thread has not encountered an I/O error or there isn't a string representation of the last error available.

GetCapabilities

typedef struct {
    unsigned int can_timeout_attach     :1;
    unsigned int can_timeout_accept     :1;
    unsigned int can_timeout_handshake  :1;
    unsigned int reserved3              :1;
    unsigned int reserved4              :1;
    unsigned int reserved5              :1;
    unsigned int reserved6              :1;
    unsigned int reserved7              :1;
    unsigned int reserved8              :1;
    unsigned int reserved9              :1;
    unsigned int reserved10             :1;
    unsigned int reserved11             :1;
    unsigned int reserved12             :1;
    unsigned int reserved13             :1;
    unsigned int reserved14             :1;
    unsigned int reserved15             :1;
} JDWPTransportCapabilities;

jdwpTransportError
GetCapabilities(jdwpTransportEnv* env, JDWPTransportCapabilities* capabilitiesPtr)

Returns via capabilitiesPtr the optional jdwpTransport features supported by this transport. The capabilities structure contains a number of boolean flags indicating whether the named feature is supported. The current set of flags is:

Boolean Flag | Meaning
can_timeout_attach | Indicates if the transport supports attaching with a timeout
can_timeout_accept | Indicates if the transport supports an accept timeout
can_timeout_handshake | Indicates if the transport supports a timeout when performing the initial handshake with the debugger when the connection is established

This function does not return any errors.

Universal Errors

Error | Meaning
JDWPTRANSPORT_ERROR_NONE | No error has occurred. This is the error code that is returned on successful completion of the function.
JDWPTRANSPORT_ERROR_OUT_OF_MEMORY | The function needed to allocate memory and no more memory was available for allocation.
JDWPTRANSPORT_ERROR_INTERNAL | An unexpected internal error has occurred.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JGSS Security Enhancement List

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java Generic Security Services: (Java GSS) and Kerberos

Feature Enhancements added to Java

Security Contents

This page describes and lists security features and enhancements added to Java by major version number, from v1.4 through v6.

NOTE: The APIs and features described in this document are subject to change.

Java Generic Security Services (Java GSS) and Kerberos Enhancements for Java SE 6

The following enhancements were added to the Java GSS/Kerberos implementation in Java SE 6.

  • Support for AES encryption type

    J2SE 5.0 supports DES and Triple DES encryption type, with following aliases:

    des-cbc-md5
    des-cbc-crc
    des3-cbc-sha1

     Starting from Java SE 6, support for AES encryption type (AES128 and AES256) in Java GSS/Kerberos is available. This improves interoperability of the Java SE Kerberos implementation with other Kerberos implementations, such as Solaris 10 and MIT Kerberos.

    AES encryption type is specified in the Kerberos configuration file under the libdefaults section. It is specified as follows, with following tags: default_tkt_enctypes, default_tgs_enctypes, permitted_enctypes.

    (AES128 encryption type)

    aes128-cts
    aes128-cts-hmac-sha1-96

     (AES256 encryption type)

    aes256-cts
    aes256-cts-hmac-sha1-96

     NOTE: The JCE framework within JDK includes an ability to enforce restrictions regarding the cryptographic algorithms and maximum cryptographic strengths available to applications. Such restrictions are specified in "jurisdiction policy files". The jurisdiction policy files bundled in Java SE limits the maximum key length. Hence, in order to use AES256 encryption type, you will need to install the JCE crypto policy with the unlimited version to allow AES with 256-bit key.

    For example, the libdefaults section in the configuration file might include the following.

    default_tkt_enctypes = aes128-cts des3-cbc-sha1 des-cbc-md5 des-cbc-crc
    default_tgs_enctypes = aes128-cts des3-cbc-sha1 des-cbc-md5 des-cbc-crc
    permitted_enctypes = aes128-cts des3-cbc-sha1 des-cbc-md5 des-cbc-crc

     default_tkt_enctypes is used to specify the encryption types to use for the session key in the ticket-granting-ticket. It is used by the client to restrict the encryption types of session keys that will be used to communicate with the KDC. The default value is des-cbc-md5 des-cbc-crc des3-cbc-sha1 aes128-cts .

    default_tgs_enctypes is used to specify the encryption types to use for the session key in service tickets. It is used by the client to restrict the encryption types of session keys that are shared by the client and server. The default value is des-cbc-md5 des-cbc-crc des3-cbc-sha1 aes128-cts.

    permitted_enctypes is used to specify the encryption types permitted to be used by a service. It is used by the server to restrict the encryption types of session keys that it will accept. The default value is des-cbc-md5 des-cbc-crc des3-cbc-sha1 aes128-cts.
  • Support for RC4-HMAC encryption type

    J2SE 5.0 already supports DES and Triple DES encryption type, with following aliases:
    des-cbc-md5
    des-cbc-crc
    des3-cbc-sha1

     Starting from Java SE 6, support for RC4-HMAC encryption type in Java GSS/Kerberos is available. This improves interoperability of the Java SE Kerberos implementation with other Kerberos implementations, such as Windows, Solaris 10 and MIT Kerberos. Windows Active Directoiory supports RC4-HMAC as the default Kerberos encryption type.

    RC4-HMAC encryption type is specified in the Kerberos configuration file under the libdefaults section. It is specified as follows, with following tags: default_tkt_enctypes, default_tgs_enctypes, permitted_enctypes.

    rc4-hmac
    arcfour-hmac
    arcfour-hmac-md5

     For example, the libdefaults section in the configuration file might include the following.

    default_tkt_enctypes = aes128-cts des3-cbc-sha1 rc4-hmac des-cbc-md5 des-cbc-crc
    default_tgs_enctypes = aes128-cts des3-cbc-sha1 rc4-hmac des-cbc-md5 des-cbc-crc
    permitted_enctypes = aes128-cts des3-cbc-sha1 rc4-hmac des-cbc-md5 des-cbc-crc

     default_tkt_enctypes is used to specify the encryption types to use for the session key in the ticket-granting-ticket. It is used by the client to restrict the encryption types of session keys that will be used to communicate with the KDC. The default value is des-cbc-md5 des-cbc-crc rc4-hmac des3-cbc-sha1 aes128-cts

    default_tgs_enctypes is used to specify the encryption types to use for the session key in service tickets. It is used by the client to restrict the encryption types of session keys that are shared by the client and server. The default value is des-cbc-md5 des-cbc-crc rc4-hmac des3-cbc-sha1 aes128-cts.

    permitted_enctypes is used to specify the encryption types permitted to be used by a service. It is used by the server to restrict the encryption types of session keys that it will accept. The default value is des-cbc-md5 des-cbc-crc rc4-hmac des3-cbc-sha1 aes128-cts.

  • Support for SPNEGO in Java GSS

    Java SE now supports SPNEGO mechanism in Java GSS.

    Java GSS is a framework that can support multiple security mechanisms; however GSS-API does not prescribe the method by which GSS-API peers can establish whether they have a common security mechanism. The Simple and Protected GSS-API Negotiation (SPNEGO) mechanism is a pseudo security mechanism that enables GSS-API peers to securely negotiate a common security mechanism to be used. The SPNEGO protocol is used to negotiate which security mechanism should be adopted.

    Currently Java GSS applications specify a unique object identifier (OID) to select the underlying security mechanism. For e.g. Java GSS applications specify Kerberos mechanism OID "1.2.840.113554.1.2.2 to use Kerberos mechanism. Oid mechOid = new Oid("1.2.840.113554.1.2.2");

    To select SPNEGO security mechanism, Java GSS applications would need to specify the SPNEGO mechanism OID "1.3.6.1.5.5.2". Oid mechOid = new Oid("1.3.6.1.5.5.2);

    Support for SPNEGO improves interoperability with Microsoft products. SPNEGO protocol is heavily used to interoperate with Microsoft server over HTTP, to support HTTP-Based Cross-Platform Authentication via the Negotiate Protocol. Java SE now supports SPNEGO authentication scheme in HTTP as well. Please check list of new networking features for Java SE 6.

  • Support for new Pre-Authentication mechanisms

    Java SE now includes support for the new pre-authentication mechanisms.

    Kerberos is a protocol for verifying the identity of principals. The Kerberos protocol provides a mechanism called pre-authentication for proving the identity of a principal and for better protecting the long-term secret of the principal.

    Kerberos specification defines a framework for Kerberos pre-authentication mechanisms. Lastest Kerberos specification defines new pre-authentication mechanisms to notify the client which key to use, salt updates, and other additional parameters. The new pre-authentication mechanisms indicate a requirement for additional pre-authentication.

    With the support of new pre-authentication mechanisms, Java GSS/Kerberos client can now handle the salt value updates when required.

  • Native platform GSS integration

    This feature allows Java applications to take advantage of features in native GSS implementation available on the platform. To enable Java GSS to delegate to the native GSS library and its list of native mechanisms, set the system property "sun.security.jgss.native" to true. When enabled, Java GSS would look for native GSS library using the operating system specific name, e.g. Solaris: libgss.so vs Linux: libgssapi.so. If the desired GSS library has a different name or is not located under a directory for system libraries, then its full path should be specified using the system property "sun.security.jgss.lib".

    For Java SE 6, the native GSS support is limited to Solaris and Linux. Setting these system properties on platforms which native GSS integration is not supported will be ignored.

    Unlike the default Java GSS implementation which relies on JAAS KerberosLoginModule for initial credential acquisition, when using native GSS, the initial credential should be acquired beforehand, e.g. kinit, prior to calling JGSS APIs.

    In addition, when performing operations as a particular Subject, e.g. Subject.doAs(...) or Subject.doAsPrivileged(...), the to-be-used GSSCredential should be added to Subject's private credential set. Otherwise, the GSS operations will fail since no credential is found.

  • JAAS Login Entry Names Changes

    The JAAS login entry names for both SunJSSE and JGSS are unified, and can be specified separately for different mechanisms. For Kerberos 5, the names are
    com.sun.security.jgss.krb5.initiate
com.sun.security.jgss.krb5.accept

Java Generic Security Services (Java GSS) and Kerberos Enhancements for J2SE 5.0

The following enhancements were added to the Java GSS/Kerberos implementation in J2SE 5.0.

  • Support for Triple DES encryption type.
    Prior to J2SE 5.0, only the DES encryption type was supported. J2SE 5.0 supports both DES and Triple DES encryption type. This improves interoperability of the Java SE Kerberos implementation with other Kerberos implementations, such as Solaris 10 and MIT Kerberos.

    Triple DES encryption type is specified in the Kerberos configuration file under the "libdefaults" section. It is specified as "des3-cbc-sha1" with following tags: default_tkt_enctypes, default_tgs_enctypes, permitted_enctypes. "dec3-cbc-sha1" has the following aliases:

    des3-hmac-sha1
des3-cbc-sha1-kd
des3-cbc-hmac-sha1-kd
    For example, the libdefaults section in the configuration file might include the following.
    default_tkt_enctypes = des3-cbc-sha1 des-cbc-md5 des-cbc-crc
default_tgs_enctypes = des3-cbc-sha1 des-cbc-md5 des-cbc-crc
permitted_enctypes   = des3-cbc-sha1 des-cbc-md5 des-cbc-crc
    default_tkt_enctypes is used to specify the encryption types to use for the session key in the ticket-granting-ticket. It is used by the client to restrict the encryption types of session keys that will be used to communicate with the KDC. The default value is "des-cbc-md5 des-cbc-crc des3-cbc-sha1"

    default_tgs_enctypes is used to specify the encryption types to use for the session key in service tickets. It is used by the client to restrict the encryption types of session keys that are shared by the client and server. The default value is "des-cbc-md5 des-cbc-crc des3-cbc-sha1".

    permitted_enctypes is used to specify the encryption types permitted to be used by a service. It is used by the server to restrict the encryption types of session keys that it will accept. The default value is "des-cbc-md5 des-cbc-crc des3-cbc-sha1".

  • TCP vs. UDP Preference Configuration
    Java SE now supports the use of the "udp_preference_limit" property in the Kerberos configuration file (krb5.conf).

    When sending a message to the KDC, the Java SE Kerberos library will use TCP if the size of the message is above udp_preference_list. If the message is smaller than udp_preference_list, then UDP will be tried at most three times. If the KDC indicates that the request is too big, the Java SE Kerberos library will use TCP.

  • IPv6 Support in Kerberos
    Java SE now supports IPv6 addresses in Kerberos tickets. Prior to J2SE 5, only IPv4 addresses were supported in tickets.
  • TGT Renewals
    The Java Authentication and Authorizaton Server (JAAS) Kerberos login module in JDK 5.0, Krb5LoginModule, now supports Ticket Granting Ticket (TGT) renewal. This allows long-running services to renew their TGT automatically without user interaction or requiring the services to restart.

    With this feature, if Krb5LoginModule obtains an expired ticket from the ticket cache, the TGT will be automatically renewed and be added to Subject of the caller who requested the ticket. If the ticket cannot be renewed for any reason, then Krb5LoginModule will use its configured callback handler to retrieve a username and password to acquire a new TGT.

    To use this feature, configure Krb5LoginModule to use the ticket cache and set the newly introduced renewTGT option to true. Here is an example of a JAAS login configuration file that requests TGT renewal.

    server {
  com.sun.security.auth.module.Krb5LoginModule required
        principal=principal@your_realm
        useTicketCache=true
        renewTGT=true;
};
    Note that if renewTGT is set to true, then useTicketCache must also be set to true; otherwise, it results in a configuration error.
  • Login Entry Names for SunJSSE
    In JDK 5.0, the SunJSSE provider has added support for the Kerberos cipher suites, as described in RFC 2712 and the What's New in JSSE in J2SE 5.0 in the JSSE Reference Guide. The following JAAS login configuration index names are reserved for this feature.
    com.sun.net.ssl.server
com.sun.net.ssl.client
    When a JSSE application uses the Kerberos cipher suites without explicit JAAS program, the SunJSSE provider will use these index names to find and configure the JAAS login module to acquire the necessary Kerberos credentials. For example, such an application might have the following JAAS configuration file.
     com.sun.net.ssl.server {
  com.sun.security.auth.module.Krb5LoginModule required
        principal=service_principal@your_realm
        useKeyTab=true
        keyTab=keytab_name
        storeKey=true;
};
    If the entry is not found, the default "other" index name will be used. The service name for TLS is "host". For example, a TLS service running on a machine named "raven.abc.com" in the realm named "KRBNT-OPERATIONS.ABC.COM" would have the service principal name
    host/raven.abc.com@KRBNT-OPERATIONS.ABC.COM
    There are no restrictions on the TLS client; it may use any valid Kerberos principal name.

    When a JSSE application uses the Kerberos cipher suites with explicit JAAS program, it can use any index name, including the ones listed above.

New Features in Java GSS for Java 2 SDK, Standard Edition, v 1.4.2

  • Configurable Kerberos Settings
    The Kerberos Key Distribution Center (KDC) name and realm settings are provided in the Kerberos configuration file or via the system properties java.security.krb5.kdc and java.security.krb5.realm. In previous releases, changes to the Kerberos configuration values would only take effect when an application was restarted.

    In the 1.4.2 release of the Java platform, a new boolean option refreshKrb5Config can be specified in the entry for Krb5LoginModule in the JAAS configuration file. If this option is set to true, the configuration values will be refreshed before the login method of the Krb5LoginModule is called.

  • Support for Slave Kerberos Key Distribution Center
    Kerberos allows the use of slave KDCs so that if the master KDC is unavailable, the slave KDCs will respond to user requests. In earlier releases of the Java SE, Sun's implementation of Kerberos tried only the master KDC and would give up if there was no response within the default KDC timeout specified in the Kerberos configuration file, or 30 seconds if no timeout had been specified.

    With this 1.4.2 release, Sun's implementation of Kerberos will retry with the slave KDC(s), if they are specified. The slave KDCs can be specified in the Kerberos configuration file or via a list of KDCs separated by a colon (:) in the system property java.security.krb5.kdc.

  • Support TCP for Kerberos Key Distribution Center Transport
    Sun's implementation of Kerberos implements Kerberos version 5 according to RFC 1510 and uses UDP transport for ticket requests. A new Internet draft updates this RFC. One of the added features is required support for TCP as a transport in addition to UDP. As a result, in cases where Kerberos tickets exceed the UDP packet size limit, the KDC would return an error code indicating that the request should be resent over TCP.

    In the current 1.4.2 release, Sun's implementation of Kerberos now supports automatic fallback to TCP. Therefore, if the Kerberos ticket request using UDP fails and the KDC returns the error code KRB_ERR_RESPONSE_TOO_BIG, TCP is automatically the default transport.

  • Kerberos Service Ticket in the Subject's Private Credentials
    The Kerberos service ticket is now stored in the Subject's private credentials. This change allows application developers access to the service ticket so that it can be used outside the JGSS (for example, in native applications or for proprietary uses). In addition, the service ticket can now be reused if the application tries to establish a security context to the same service again. The service ticket should be valid for it to be reusable.

    Previously, when using Java Generic Security Services (JGSS) over Kerberos V5, if the useSubjectCredsOnly property was set to true, the Ticket Granting Ticket (TGT) was retrieved from the Subject and used to establish a GSS Security context. The service ticket obtained was not stored in the Subject. Now the service ticket is also stored in the Subject if useSubjectCredsOnly is true.

    If a client application searches through the Subject's private credentials, in previous releases it would find only the TGT. As of this release, it also will find any Service ticket(s) obtained.

    The bug report associated with this change is 4688866.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


When to use Java GSS-API vs. JSSE

Java GSS-API and JSSE provide you with the same basic set of security features:

  1. Client-server authentication
  2. Encryption and integrity protection of transmitted data

However, there are some key difference between the two. This document lists some of them to help you decide which might be more appropriate in your environment:

  1. Kerberos Single Sign-On Support

    In the Java 2 Standard Edition, GSS-API contains support for Kerberos as a mandatory security mechanism. This means that if your desktop has Kerberos support, you can write Java GSS-API based applications that never prompt the user for a password.

    At present JSSE does not support cipher suites to use Kerberos-based authentication. Support for such a cipher suite is dependent on its standarization in the TLS protocol at the Internet Engineering Task Force (IETF).

  2. Communications API

    JSSE supports a socket-based API. JSSE sockets extend the socket classes found in java.net and JSSE socket factories extend the socket factories found in javax.net. Thus, if your application is written such that its security needs to be configured via a socket factory, then JSSE might be more appropriate for you. JSSE sockets need to use some reliable transport. Typically, implementations use TCP.

    Java GSS-API, on the other hand, is a token-based API that relies on the application to do the communication. This means that the application can use TCP sockets, UDP datagrams, or any other channel that will allow it to transport Java GSS-API generated tokens. If your application has varying communication protocol needs, then Java GSS-API might be more appropriate for you. Java GSS-API can read and write its tokens using input and output streams. However, you will need to set up the streams yourself.

  3. Credential Delegation

    Java GSS-API allows the client to delegate its credentials to the server when using Kerberos. If your application will be deployed in a multi-tier environment where intermediaries need to impersonate clients when talking to backend layers, Java GSS-API might be more appropriate for you.

  4. Selective Encryption

    Because Java GSS-API is token-based, you can choose to selectively encrypt certain messages but not all. If your application needs to intersperse plaintext and ciphertext messages, Java GSS-API might be more appropriate for you.

  5. Protocol Requirements

    JSSE provides an implementation of the TLS protocol defined in RFC 2246. Java GSS-API provides an implementation of the GSS-API framework defined in RFC 2853, as well as an implementation of the Kerberos Version 5 mechanism defined in RFC 1964. (On Microsoft Windows platforms, this may be known as SSPI with Kerberos.) Some servers such as HTTPS servers will require you to use TLS, in which case JSSE will be appropriate for you. Other servers such as LDAP servers using SASL might need GSS-API with Kerberos, in which case Java GSS-API will be appropriate for you.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


jhat - Java Heap Analysis Tool

  • Synopsis
  • Parameters
  • Description
  • Options
  • See Also

SYNOPSIS

jhat [ options ] <heap-dump-file>

PARAMETERS

options
Options, if used, should follow immediately after the command name.
heap-dump-file
Java binary heap dump file to be browsed. For a dump file that contains multiple heap dumps, you may specify which dump in the file by appending "#<number> to the file name, i.e. "foo.hprof#3".

DESCRIPTION

The jhat command parses a java heap dump file and launches a webserver. jhat enables you to browse heap dumps using your favorite webbrowser. jhat supports pre-designed queries (such as 'show all instances of a known class "Foo"') as well as OQL (Object Query Language) - a SQL-like query language to query heap dumps. Help on OQL is available from the OQL help page shown by jhat. With the default port, OQL help is available at http://localhost:7000/oqlhelp/

There are several ways to generate a java heap dump:

  • Use jmap -dump option to obtain a heap dump at runtime;
  • Use jconsole option to obtain a heap dump via HotSpotDiagnosticMXBean at runtime;
  • Heap dump will be generated when OutOfMemoryError is thrown by specifying -XX:+HeapDumpOnOutOfMemoryError VM option;
  • Use hprof.

NOTE: This tool is experimental and may not be available in future versions of the JDK.

OPTIONS

-stack false/true
Turn off tracking object allocation call stack. Note that if allocation site information is not available in the heap dump, you have to set this flag to false. Default is true.
-refs false/true
Turn off tracking of references to objects. Default is true. By default, back pointers (objects pointing to a given object a.k.a referrers or in-coming references) are calculated for all objects in the heap.
-port port-number
Set the port for the jhat's HTTP server. Default is 7000.
-exclude exclude-file
Specify a file that lists data members that should be excluded from the "reachable objects" query. For example, if the file lists java.lang.String.value, then, whenever list of objects reachable from a specific object "o" are calculated, reference paths involving java.lang.String.value field will not considered.
-baseline baseline-dump-file
Specify a baseline heap dump. Objects in both heap dumps with the same object ID will be marked as not being "new". Other objects will be marked as "new". This is useful while comparing two different heap dumps.
-debug int
Set debug level for this tool. 0 means no debug output. Set higher values for more verbose modes.
-version
Report version number and exit.
-h
Output help message and exit.
-help
Output help message and exit.
-J<flag>
Pass <flag> to the Java virtual machine on which jhat is run. For example, -J-Xmx512m to use a maximum heap size of 512MB.

SEE ALSO

  • jmap - Java Memory Map
  • jconsole - Java Monitoring and Management Console
  • hprof - Heap and CPU profiling tool
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL: Running The "Hello World" Example on Two Machines

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java IDL: The "Hello World" Example on Two Machines

To enable the Hello World Tutorial to run on two machines, follow the steps as directed in the tutorial, with the following changes. This tutorial was written for the Java (tm) 2 Platform, Standard Edition (J2Se(tm)), version 1.4. In this example, the client, stubs, and skeletons are located on the client machine, and the server and name server are located on the server machine. This scenario can be changed to meet your needs and is provided simply as an introduction to one way to distribute an application across two machines.

  1. Create (as shown in the tutorial) and compile the Hello.idl file on the client machine:

   idlj -fall Hello.idl
  2. Create HelloClient.java on the client machine. Compile the *.java files, including the stubs and skeletons (which are in the directory HelloApp):
       javac *.java HelloApp/*.java
  3. Create HelloServer.java on the server machine. Compile the .java files:
       javac *.java
  4. Start the Java Object Request Broker Daemon, orbd, which includes a Naming Service, on the server machine. To do this on Unix:
       orbd -ORBInitialPort 1050 -ORBInitialHost servermachinename&

    To do this on Windows:

       start orbd -ORBInitialPort 1050 -ORBInitialHost servermachinename

    Both -ORBInitialPort and -ORBInitialHost are required arguments on the orbd command line. This example starts the name server on port 1050, because on Solaris you must become root to start a process on a port under 1024. If you want to use a different nameserverport, replace 1050 with the correct port number throughout this example.

    When using orbd, the ORBD must be run on the same machine as the machine on which the servers will be activated. Another Naming Service, tnameserv, could be used if you prefer to run the Naming Service on a machine other than the machine on which the servers will be activated.

  5. On the server machine, start the Hello server, as follows:
       java HelloServer -ORBInitialPort 1050

    If you used a different nameserverport, replace 1050 with the correct port number. You do not need to specify the -ORBInitialHost argument because the Hello server will be running on the same host as the name server in this example. If the Name Server were running on a different machine, you would specify which machine using the -ORBInitialHost nameserverhost argument.

  6. On the client machine, run the Hello application client. From a DOS prompt or shell, type:
       java HelloClient -ORBInitialHost nameserverhost -ORBInitialPort 1050

    Note that nameserverhost is the host on which the IDL name server is running. In this case, it is the server machine.

    If you used a different nameserverport, replace 1050 with the correct port number.

  7. Kill or stop orbd when finished. The name server will continue to wait for invocations until it is explicitly stopped.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Changes in CORBA Features Between J2SE 1.4.x and 5.0

This release of the Java™ 2 Platform Standard Edition (J2SE), contains the following enhancements to CORBA, Java IDL, and Java RMI-IIOP technology:

  • Enhancement 4674929. Additional serviceability features for the Java SE ORB provide a logging framework based on J2SE 1.4 logging APIs. When an error is encountered and an OMG minor code is generated, this minor code will now be translated to a Java error code for error logging. The ORB will also include the standard minor codes as specified by the OMG specifications.
  • Enhancement 4607440. Better performance of the default ORB in Java SE in high volume deployments, including better scalability and performance.
  • Enhancement 4629589. Added Object Reference Template (ORT) to ORB. An Object Reference Template is an extension to portable interceptors that supports portable server activation frameworks, load balancing, fault tolerance, dynamic bridging, and other advanced features.
  • Enhancement 4674944. Added on-the-wire interoperability. This includes identifying and incorporating any resolutions and/or updates from the OMG of any interoperability issues since CORBA 2.3.1 that affect on-the-wire interoperability for the J2EE Application Servers, and incorporating those resolutions into the Java SE ORB.
  • When the J2SE 5.0 ORB marshals an org.omg.CORBA.SystemException response, it adds an ExceptionDetailMessage (i.e., a ServiceContext with ServiceId 14) as defined in:
    /**
 * CORBA formal/02-06-01: 13.7.1:
 * ExceptionDetailMessage identifies a CDR encapsulation of a wstring,
 * encoded using GIOP 1.2 with a TCS-W of UTF-16.  This service context
 * may be sent on Reply messages with a reply_status of SYSTEM_EXCEPTION
 * or USER_EXCEPTION. The usage of this service context is defined
 * by language mappings.
 *
 * IDL/Java: ptc/02-01-22: 1.15.2:
 * When a System Exception is marshaled, its GIOP Reply message shall
 * include an associated ExceptionDetailMessage service context. The
 * callee's stack trace is often very valuable debugging information but
 * may contain sensitive or unwanted information. The wstring within the
 * service context will therefore contain additional information relating
 * to the exception, for example the result of calling either
 * printStackTrace(PrintWriter) or getMessage() on the exception. When
 * unmarshaling a System Exception on the client side, the wstring from
 * any ExceptionDetailMessage service context shall become the Java error
 * message in the unmarshaled exception object.
 */

    When the J2SE 5.0 ORB unmarshals an org.omg.CORBA.SystemException response it constructs the SystemException with the contents of the ExceptionDetailMessage as the message argument to the SystemException constructor.

    NOTE: The content of the message may change. In J2SE 5.0, the message contains the server side stack trace. The following code example (note: all details may change) of a stack trace on the client side for an exception generated on the server-side (note the server-side stack trace in the exception's message):

    org.omg.CORBA.FREE_MEM: ----------BEGIN server-side stack trace----------
org.omg.CORBA.FREE_MEM: idlIConnect  vmcid: 0x0  minor code: 0  completed: No
        at corba.exceptiondetailsc.idlIServantConnect.raise_system_exception(idlIServantConnect.java:23)
        at corba.exceptiondetailsc._idlIImplBase._invoke(_idlIImplBase.java:42)
        at com.sun.corba.ee.impl.protocol.CorbaServerRequestDispatcherImpl.dispatchToServant(CorbaServerRequestDispatcherImpl.java:647)
        at com.sun.corba.ee.impl.protocol.CorbaServerRequestDispatcherImpl.dispatch(CorbaServerRequestDispatcherImpl.java:190)
        at com.sun.corba.ee.impl.protocol.CorbaMessageMediatorImpl.handleRequestRequest(CorbaMessageMediatorImpl.java:1653)
        at com.sun.corba.ee.impl.protocol.CorbaMessageMediatorImpl.handleRequest(CorbaMessageMediatorImpl.java:1513)
        at com.sun.corba.ee.impl.protocol.CorbaMessageMediatorImpl.handleInput(CorbaMessageMediatorImpl.java:895)
        at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:172)
        at com.sun.corba.ee.impl.protocol.CorbaMessageMediatorImpl.handleRequest(CorbaMessageMediatorImpl.java:668)
        at com.sun.corba.ee.impl.transport.SocketOrChannelConnectionImpl.dispatch(SocketOrChannelConnectionImpl.java:375)
        at com.sun.corba.ee.impl.transport.SocketOrChannelConnectionImpl.read(SocketOrChannelConnectionImpl.java:284)
        at com.sun.corba.ee.impl.transport.ReaderThreadImpl.doWork(ReaderThreadImpl.java:73)
        at com.sun.corba.ee.impl.orbutil.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:382)
----------END server-side stack trace----------  vmcid: 0x0  minor code: 0  completed: No
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:274)
        at com.sun.corba.ee.impl.protocol.giopmsgheaders.MessageBase.getSystemException(MessageBase.java:791)
        at com.sun.corba.ee.impl.protocol.giopmsgheaders.ReplyMessage_1_2.getSystemException(ReplyMessage_1_2.java:97)
        at com.sun.corba.ee.impl.protocol.CorbaMessageMediatorImpl.getSystemExceptionReply(CorbaMessageMediatorImpl.java:546)
        at com.sun.corba.ee.impl.protocol.CorbaClientRequestDispatcherImpl.processResponse(CorbaClientRequestDispatcherImpl.java:407)
        at com.sun.corba.ee.impl.protocol.CorbaClientRequestDispatcherImpl.marshalingComplete(CorbaClientRequestDispatcherImpl.java:303)
        at com.sun.corba.ee.impl.protocol.CorbaClientDelegateImpl.invoke(CorbaClientDelegateImpl.java:132)
        at org.omg.CORBA.portable.ObjectImpl._invoke(ObjectImpl.java:457)
        at corba.exceptiondetailsc._idlIStub.raise_system_exception(_idlIStub.java:20)
        at corba.exceptiondetailsc.Client.main(Client.java:87)

------------------------------------------------------------------------------

See Official Specifications for CORBA support in J2SE 5.0 for information on how Java IDL and Java RMI-IIOP comply with the CORBA Specifications.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL: Developing Clients

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Developing Clients

This document was not updated for this release.

When updated, topics in this section will include:

  • ORBs and Invocations
  • Static Invocation
  • Dynamic Invocation

ORBs and Invocations

For a client to invoke a CORBA object operation, both the client and the server (the object implementation) must use a CORBA software component called an ORB (object request broker). ORBs are the common denominators that bridge the differences in location, platform, and programming language that can separate a client and a server. ORBs can contact each other across the network, can create and interpret object references (CORBA object handles), and can marshal parameters into and out of the format used by IIOP. In addition to enabling client/server communication, ORBs provide other services, but they are not described here.

The two ways to invoke an operation on a CORBA object are:

  • Static invocation, which is used most often and most resembles conventional Java programming, is type-checked by the compiler. But it can only be used for objects whose interface definitions exist when the invoking client is compiled.
  • Dynamic invocation is more flexible because clients can invoke objects they discover at runtime. However, compile-time type-checking is impossible with dynamic invocation. Although it's possible to type-check parameters at runtime, doing so requires a CORBA Interface Repository, which the current release of Java IDL does not provide.

Static Invocation

To make a static invocation on a CORBA object, a Java client needs an object reference to the servant that performs the operation. The object reference has two important functions:

  • It uniquely identifies the servant, wherever it is located.
  • It implements the client stub interface, making the reference a local proxy for the servant object.
Clients don't create object references but obtain them, typically from other objects such as factories or naming contexts.

OMG IDL is the language in which CORBA object interfaces are defined. For each OMG IDL module, the idlj compiler generates a Java package. For each interface Foo defined in an OMG IDL module, the generated package contains the following items of interest to the client programmer:

  • A Java signature interface Foo, which extends org.omg.portable.IDLEntity, org.omg.CORBA.Object, and the operations interface. The signature interface is used as the signature type in method declarations when interfaces of the specified type are used in other interfaces. From the client's point of view, an object reference for a CORBA Foo object implements this interface.

    Note: The Stub implements the Foo interface, where it generates code for each method to marshall the arguments, invoke the method, and then unmarshall the arguments.

  • A Java operations interface FooOperations, which is used in the server-side mapping and as a mechanism for providing optimized calls for co-located clients and server. The server developer provides implementation for the methods indicated by the operations interface.

    Note: The server writer usually extends FooPOA and provides implementation for the methods provided by the operations interface.

  • A Java class FooHelper, that defines auxiliary methods, notably narrow(), which is the CORBA counterpart of Java casting.
  • A Java class called FooHolder, that holds a public Foo member. Holders are required for CORBA operations that take out or inout arguments, which, unlike CORBA in arguments, don't map directly to Java's pass-by-value semantics.

Dynamic Invocation

CORBA dynamic invocation uses an object called a request to hold everything pertinent to an invocation: the object reference, the name of the operation, its parameters, and space for the result. The client builds a request object describing an operation, then calls the request's invoke method, which dispatches the request just as a stub would. When the invoke method returns, the result is available in the request object.

The key to dynamic invocation is the ability of requests to hold self-describing data. This facility enables a request object to represent any invocation of any operation, regardless of its parameters. Each self-describing data element has a special type known in OMG IDL as Any. An Any consists of a typecode (whose values are defined by OMG IDL) and a value; the typecode specifies the type of the value.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL: Distributed Application Concepts

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Distributed Application Concepts

Topics discussed in this section include:

  • Multi-Tiered Applications
  • User-Interface Tier
  • Service (Server) Tier
  • Data Store (Database) Tier

Multi-Tiered Applications

Traditional enterprise applications are, for the most part, self-contained monolithic programs which have limited access to one another's procedures and data. They are usually cumbersome to build and expensive to maintain because even simple changes require the entire program to be recompiled and retested.

By contrast, applications built using distributed objects such as CORBA naturally lend themselves to a multitiered architecture, fostering a neat separation of concerns. A three-tiered application has a user interface code layer, a computation code (or business logic) layer, and a database access layer. All interaction between the layers occurs via the interfaces that all CORBA objects must publish. The diagram below illustrates the transition from monolithic applications to multi-tiered, modular applications.

User-Interface Tier

The user-interface tier is the layer of user interaction. Its focus is on efficient user interface design and accessibility throughout your organization. The user interface tier can reside on the user's desktop, on your organization's intranet, or on the World Wide Web (Internet). Several user interface implementations may be deployed which access the same server. The UI tier usually invokes methods on the business logic tier and thus acts as a client of the business logic servers.

Service (Server) Tier

The service, or business logic layer, is server-based code with which the client code interacts. The business logic layer is made up of business objects - CORBA objects that perform logical business functions such as inventory control, budget, sales orders, and billing. These objects invoke methods on Data Store tier objects.

Data Store (Database) Tier

The data store layer is made up of objects that encapsulate database routines and interact directly with the DBMS product(s). For example, a hypothetical get_Sales_Sum method might be implemented to obtain data from a relational database via the appropriate SQL SELECT statements.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL: DSI Programming

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Advanced Topic: The Dynamic Skeleton Interface (DSI)

The Dynamic Skeleton Interface (DSI) allows servers to serve a servant object without prior (compile time) knowledge of the object's interface. Insead of using skeleton code compiled from the IDL interface definition, the server constructs an operation invocation dynamically.

Why Use DSI?

DSI can be used to bridge CORBA with non-CORBA environments. Such a bridge would allow CORBA clients to invoke methods on CORBA objects that are implemented as, for example, COM services.

why use DSI

The dynamic servant is implemented to convert the CORBA client request to a format understood by the COM server. You must write all the code to perform this work. Contrast this with a typical static object invocation. The server has access to the compiled skeletons for the interface being invoked. These skeletons are generated by compiling the IDL interface definitions with the idlj compiler. When the ORB receives a request, it uses the skeleton code to build operation arguments on the server side and to send back any result.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL: The "Hello World" Example

POA model, transient server

This document is a high-level overview of how to create a complete CORBA (Common Object Request Broker Architecture) application using IDL (Interface Definiton Language) to define interfaces and the Java IDL compiler to generate stubs and skeletons. For more information on the development process, and a more detailed tutorial on creating a CORBA application using IDL, see Getting Started with Java IDL: The Hello World Tutorial. You can also create CORBA application by defining the interfaces in the Java programming language. For more information and a tutorial on this development process, see the Java RMI-IIOP documentation.

In this release of Java SE, the server-side implementation generated by the idlj compiler is the Portable Servant Inheritance Model, also known as the POA model. The POA, or Portable Object Adapter, is discussed in more detail in Portable Object Adapter. This document presents a sample application created using the default behavior of the idlj compiler, which uses a POA server-side model.

CORBA supports at least two different server-side mappings for implementing an IDL interface:

  • The Inheritance Model

    Using the Inheritance Model, you implement the IDL interface using an implementation class that also extends the compiler-generated skeleton.

    Inheritance models include:

    • The OMG-standard, POA. Given an interface My defined in My.idl, the file MyPOA.java is generated by the idlj compiler. You must provide the implementation for My and it must inherit from MyPOA, a stream-based skeleton that extends org.omg.PortableServer.Servant , which serves as the base class for all POA servant implementations.
    • ImplBase. Given an interface My defined in My.idl, the file _MyImplBase.java is generated. You must provide the implementation for My and it must inherit from _MyImplBase.

      NOTE: ImplBase is deprecated in favor of the POA model, but is provided to allow compatibility with servers written in J2SE 1.3 and prior. We do not recommend creating new servers using this nonstandard model.

  • The Delegation Model

    Using the Delegation Model, you implement the IDL interface using two classes:

    • An IDL-generated Tie class that inherits from the compiler-generated skeleton, but delegates all calls to an implementation class.
    • A class that implements the IDL-generated operations interface (such as HelloOperations), which defines the IDL function.

    The Delegation model is also known as the Tie model, or the Tie Delegation model. It inherits from either the POA or ImplBase compiler-generated skeleton, so the models will be described as POA/Tie or ImplBase/Tie models in this document.

This tutorial presents the POA Inheritance model for server-side implementation. For tutorials using the other server-side implementations, see the following documents:

  • Java IDL: The "Hello World" Example with the POA/Tie Server-Side Model

    The Tie Model is a delegation model. Use the idlj compiler to first generate server-side bindings. Then, run the idlj compiler a second time with the with the -fallTie option to generate Tie model server-side bindings. For the interface Hello, HelloPOATie.java is one of the generated files. The constructor to HelloPOATie takes a delegate or a delegate and a poa. You must provide the implementation for delegate and/or the poa, but the delegate does not have to inherit from any other class, only the interface HelloOperations. For more information, refer to the IDL to Java Language Mapping Specification.

    You might want to use the Tie model instead of the typical Inheritance model if your implementation must inherit from some other implementation. Java allows any number of interface inheritance, but there is only one slot for class inheritance. If you use the inheritance model, that slot is used up . By using the Tie Model, that slot is freed up for your own use. The drawback is that it introduces a level of indirection: one extra method call occurs when invoking a method.

  • Java IDL: The "Hello World" Example with the ImplBase Server-Side Model

    The ImplBase server-side model is an Inheritance Model, as is the POA model. Use the idlj compiler with the -oldImplBase flag to generate server-side bindings that are compatible with versions of Java IDL prior to J2SE 1.4. Given an interface Hello defined in Hello.idl, the file _HelloImplBase.java is generated. You must provide the implementation for Hello and it must inherit from _HelloImplBase.

    Note that using the -oldImplBase flag is non-standard: these APIs are being deprecated. You would use this flag ONLY for compatibility with existing servers written in J2SE 1.3 or earlier. In that case, you would need to modify an existing MAKEFILE to add the -oldImplBase flag to the idlj compiler, otherwise POA-based server-side mappings will be generated.

This document contains:

  • The example code for this application
  • The IDL for a simple "Hello World" program
  • A server that creates an object and publishes it with the naming service using the default server-side implementation (POA)
  • An application client that knows the object's name, retrieves a reference for it from the naming service, and invokes the object
  • Instructions for compiling and running the example

To create this example, create a directory named hello/ where you develop sample applications and create the files in this directory, or download the example code and unzip it into your sample applications directory.

Defining the Interface (Hello.idl)

The first step to creating a CORBA application is to specify all of your objects and their interfaces using the OMG's Interface Definition Language (IDL). IDL has a syntax similar to C++ and can be used to define modules, interfaces, data structures, and more. The IDL can be mapped to a variety of programming languages. The IDL mapping for Java is summarized in IDL to Java Language Mapping Summary.

The following code is written in the OMG IDL, and describes a CORBA object whose sayHello() operation returns a string and whose shutdown() method shuts down the ORB. To learn more about OMG IDL Syntax and Semantics, read Chapter 3 of the CORBA 2.3.1 Specification.

Hello.idl

module HelloApp
{
  interface Hello
  {
  string sayHello();
  oneway void shutdown();
  };
};
NOTE: When writing code in OMG IDL, do not use an interface name as the name of a module. Doing so runs the risk of getting inconsistent results when compiling with tools from different vendors, thereby jeopardizing the code's portability. For example, code containing the same names could be compiled with the IDL to Java compiler from Sun Microsystems and get one result. The same code compiled with another vendor's IDL to Java compiler could produce a different result.

To complete the application, you simply provide the server (HelloServer.java) and client (HelloClient.java) implementations.

Implementing the Server (HelloServer.java)

The example server consists of two classes, the servant and the server. The servant, HelloImpl, is the implementation of the Hello IDL interface; each Hello instance is implemented by a HelloImpl instance. The servant is a subclass of HelloPOA, which is generated by the idlj compiler from the example IDL. The servant contains one method for each IDL operation, in this example, the sayHello() and shutdown() methods. Servant methods are just like ordinary Java methods; the extra code to deal with the ORB, with marshaling arguments and results, and so on, is provided by the skeleton.

The HelloServer class has the server's main() method, which:

  • Creates and initializes an ORB instance
  • Gets a reference to the root POA and activates the POAManager
  • Creates a servant instance (the implementation of one CORBA Hello object) and tells the ORB about it
  • Gets a CORBA object reference for a naming context in which to register the new CORBA object
  • Gets the root naming context
  • Registers the new object in the naming context under the name "Hello"
  • Waits for invocations of the new object from the client

This example provides an example of a transient object server. For an example of the "Hello World" program with a persistent object server, see Example 2: Hello World with Persistent State. For more discussion of CORBA servers, see Developing Servers.

For more discussion of the code, see the detailed tutorial topic Getting Started with Java IDL: Developing a Hello World Server.

HelloServer.java

// HelloServer.java
// Copyright and License
import HelloApp.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;
import org.omg.PortableServer.*;
import org.omg.PortableServer.POA;

import java.util.Properties;

class HelloImpl extends HelloPOA {
  private ORB orb;

  public void setORB(ORB orb_val) {
    orb = orb_val;
  }

  // implement sayHello() method
  public String sayHello() {
    return "\nHello world !!\n";
  }

  // implement shutdown() method
  public void shutdown() {
    orb.shutdown(false);
  }
}

public class HelloServer {

  public static void main(String args[]) {
    try{
      // create and initialize the ORB
      ORB orb = ORB.init(args, null);

      // get reference to rootpoa & activate the POAManager
      POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
      rootpoa.the_POAManager().activate();

      // create servant and register it with the ORB
      HelloImpl helloImpl = new HelloImpl();
      helloImpl.setORB(orb);

      // get object reference from the servant
      org.omg.CORBA.Object ref = rootpoa.servant_to_reference(helloImpl);
      Hello href = HelloHelper.narrow(ref);

      // get the root naming context
      // NameService invokes the name service
      org.omg.CORBA.Object objRef =
          orb.resolve_initial_references("NameService");
      // Use NamingContextExt which is part of the Interoperable
      // Naming Service (INS) specification.
      NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

      // bind the Object Reference in Naming
      String name = "Hello";
      NameComponent path[] = ncRef.to_name( name );
      ncRef.rebind(path, href);

      System.out.println("HelloServer ready and waiting ...");

      // wait for invocations from clients
      orb.run();
    }

      catch (Exception e) {
        System.err.println("ERROR: " + e);
        e.printStackTrace(System.out);
      }

      System.out.println("HelloServer Exiting ...");

  }
}

Implementing the Client Application (HelloClient.java)

The example application client that follows:

  • Creates and initializes an ORB
  • Obtains a reference to the root naming context
  • Looks up "Hello" in the naming context and receives a reference to that CORBA object
  • Invokes the object's sayHello() and shutdown() operations and prints the result

For more discussion of the details of the code, see Getting Started with Java IDL: Developing a Client Application.

HelloClient.java

// Copyright and License

import HelloApp.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;

public class HelloClient
{
  static Hello helloImpl;

  public static void main(String args[])
    {
      try{
        // create and initialize the ORB
        ORB orb = ORB.init(args, null);

        // get the root naming context
        org.omg.CORBA.Object objRef =
            orb.resolve_initial_references("NameService");
        // Use NamingContextExt instead of NamingContext. This is
        // part of the Interoperable naming Service.
        NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

        // resolve the Object Reference in Naming
        String name = "Hello";
        helloImpl = HelloHelper.narrow(ncRef.resolve_str(name));

        System.out.println("Obtained a handle on server object: " + helloImpl);
        System.out.println(helloImpl.sayHello());
        helloImpl.shutdown();

        } catch (Exception e) {
          System.out.println("ERROR : " + e) ;
          e.printStackTrace(System.out);
          }
    }

}

Building and Running Hello World

Despite its simple design, the Hello World program lets you learn and experiment with all the tasks required to develop almost any CORBA program that uses static invocation. Static invocation, which uses a client stub for the invocation and a server skeleton for the service being invoked, is used when the interface of the object is known at compile time. If the interface is not known at compile time, dynamic invocation must be used.

This example requires a naming service, which is a CORBA service that allows CORBA objects to be named by means of binding a name to an object reference. The name binding may be stored in the naming service, and a client may supply the name to obtain the desired object reference. The two options for Naming Services shipped with this release of Java SE include orbd, a daemon process containing a Bootstrap Service, a Transient Naming Service, a Persistent Naming Service, and a Server Manager, and tnameserv, a transient naming service that is provided for backward compatibility. This example uses orbd.

When running this example, remember that, when using Solaris software, you must become root to start a process on a port under 1024. For this reason, we recommend that you use a port number greater than or equal to 1024. The -ORBInitialPort option is used to override the default port number in this example. The following instructions assume you can use port 1050 for the Java IDL Object Request Broker Daemon, orbd. You can substitute a different port if necessary. When running these examples on a Windows machine, subtitute a backslash (\) in path names.

To run this client-server application on your development machine:

  1. Change to the directory that contains the file Hello.idl.
  2. Run the IDL-to-Java compiler, idlj, on the IDL file to create stubs and skeletons. This step assumes that you have included the path to the java/bin directory in your path.
      idlj -fall  Hello.idl

    You must use the -fall option with the idlj compiler to generate both client and server-side bindings. This command line will generate the default server-side bindings, which assumes the POA Inheritance server-side model. For more information on the idlj options, see IDL-to-Java compiler options.

    The idlj compiler generates a number of files. The actual number of files generated depends on the options selected when the IDL file is compiled. The generated files provide standard functionality, so you can ignore them until it is time to deploy and run your program. The files generated by the idlj compiler for Hello.idl, with the -fall command line option, are:

    • HelloPOA.java

      This abstract class is the stream-based server skeleton, providing basic CORBA functionality for the server. It extends org.omg.PortableServer.Serva nt , and implements the InvokeHandler interface and the HelloOperations interface. The server class HelloImpl extends HelloPOA.

    • _HelloStub.java

      This class is the client stub, providing CORBA functionality for the client. It extends org.omg.CORBA.portable.ObjectImpl and implements the Hello.java interface.

    • Hello.java

      This interface contains the Java version of our IDL interface. The Hello.java interface extends org.omg.CORBA.Object, providing standard CORBA object functionality. It also extends the HelloOperations interface and org.omg.CORBA.portable.IDLEntity.

    • HelloHelper.java

      This class provides auxiliary functionality, notably the narrow() method required to cast CORBA object references to their proper types.The Helper class is responsible for reading and writing the data type to CORBA streams, and inserting and extracting the data type from Anys. The Holder class delegates to the methods in the Helper class for reading and writing.

    • HelloHolder.java

      This final class holds a public instance member of type Hello. Whenever the IDL type is an out or an inout parameter, the Holder class is used. It provides operations for org.omg.CORBA.portable.OutputStream and org.omg.CORBA.portable.InputStream arguments, which CORBA allows, but which do not map easily to Java's semantics. The Holder class delegates to the methods in the Helper class for reading and writing. It implements org.omg.CORBA.portable.Streamable.

    • HelloOperations.java

      This interface contains the methods sayHello() and shutdown(). The IDL-to-Java mapping puts all of the operations defined on the IDL interface into this file, which is shared by both the stubs and skeletons.

  3. Compile the .java files, including the stubs and skeletons (which are in the directory HelloApp). This step assumes the java/bin directory is included in your path.
       javac *.java HelloApp/*.java
  4. Start orbd.

    To start orbd from a UNIX command shell, enter:

      orbd -ORBInitialPort 1050&

    From an MS-DOS system prompt (Windows), enter:

      start orbd -ORBInitialPort 1050

    Note that 1050 is the port on which you want the name server to run. The -ORBInitialPort argument is a required command-line argument. Note that when using Solaris software, you must become root to start a process on a port under 1024. For this reason, we recommend that you use a port number greater than or equal to 1024.

    For an example of how to run this program on two machines, see Running the Hello World Program on 2 machines.

  5. Start the Hello server:

    To start the Hello server from a UNIX command shell, enter:

      java HelloServer -ORBInitialPort 1050 -ORBInitialHost localhost&

    From an MS-DOS system prompt (Windows), enter:

      start java HelloServer -ORBInitialPort 1050 -ORBInitialHost localhost

    You will see HelloServer ready and waiting... when the server is started.

    For this example, you can omit -ORBInitialHost localhost since the name server is running on the same host as the Hello server. If the name server is running on a different host, use -ORBInitialHost nameserverhost to specify the host on which the IDL name server is running.

    Specify the name server (orbd) port as done in the previous step, for example, -ORBInitialPort 1050.

  6. Run the client application:
      java HelloClient -ORBInitialPort 1050 -ORBInitialHost localhost

    When the client is running, you will see a response such as the following on your terminal: Obtained a handle on server object: IOR: (binary code) Hello World! HelloServer exiting...

    For this example, you can omit -ORBInitialHost localhost since the name server is running on the same host as the Hello client. If the name server is running on a different host, use -ORBInitialHost nameserverhost to specify the host on which the IDL name server is running.

    Specify the name server (orbd) port as done in the previous step, for example, -ORBInitialPort 1050.

When you have finished this tutorial, be sure to shut down or kill the name server (orbd). To do this from a DOS prompt, select the window that is running the server and enter Ctrl+C to shut it down. To do this from a Unix shell, find the process, and kill it. The server will continue to wait for invocations until it is explicitly stopped.

Running the Hello World Application on Two Machines describes one way of distributing the simple application across two machines - a client and a server.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL: The "Hello World" Example

Using the POA, a persistent server, and a persistent naming service

This document is a high-level overview of how to create a complete CORBA (Common Object Request Broker Architecture) application using IDL (Interface Definiton Language) to define interfaces and the Java IDL compiler to generate stubs and skeletons. For more information on the development process, and a more detailed tutorial on creating a CORBA application using IDL, see Getting Started with Java IDL: The Hello World Tutorial. You can also create CORBA applications by defining the interfaces in the Java programming language. For more information and a tutorial on this development process, see Java RMI-IIOP documentation.

For more information on transient vs. persistent servers, refer to the document Developing Servers.

This document contains:

  • The IDL for a simple "Hello World" program
  • A persistent server that creates an object and publishes it with the naming service using the default server-side implementation (POA)
  • A servant that implements each of the IDL interfaces
  • An application client that knows the object's name, retrieves a reference for it from the naming service, and invokes the object
  • Instructions for compiling and running the example

Defining the Interface (PersistentHello.idl)

The first step to creating a CORBA application is to specify all of your objects and their interfaces using the OMG's Interface Definition Language (IDL). IDL has a syntax similar to C++ and can be used to define modules, interfaces, data structures, and more. The IDL can be mapped to a variety of programming languages. The IDL mapping for Java is summarized in IDL to Java Language Mapping Summary.

The following code is written in the OMG IDL, and describes a CORBA object whose sayHello() operation returns a string and whose shutdown() method shuts down the ORB. To learn more about OMG IDL Syntax and Semantics, read Chapter 3 of the CORBA 2.3.1 Specification.

PersistentHello.idl

module Persistent {
    interface Hello {
        string sayHello( );
        oneway void shutdown();
    };
};
NOTE: When writing code in OMG IDL, do not use an interface name as the name of a module. Doing so runs the risk of getting inconsistent results when compiling with tools from different vendors, thereby jeopardizing the code's portability. For example, code containing the same names could be compiled with the IDL to Java compiler from Sun Microsystems and get one result. The same code compiled with another vendor's IDL to Java compiler could produce a different result.

To complete the application, you simply provide the server (PersistentServer.java), servant (PersistentHelloServant.java), and client (PersistentClient.java) implementations.

Implementing the Server (PersistentServer.java)

The example server, PersistentServer, has the server's main() method, which:

  • Creates and initializes an ORB instance
  • Creates a servant
  • Gets a reference to the root POA
  • Creates the policy that makes the server persistent
  • Creates a persistent POA by passing in the persistent policy
  • Activates the persistent POA's POAManager
  • Associates the servant with the persistent POA
  • Gets a CORBA object reference for the root naming context in which to register the new CORBA object
  • Narrows the object reference to a naming context
  • Registers the new object in the naming context under the name "PersistentServerTutorial"
  • Waits for invocations of the new object from the client

This example provides an example of a persistent object server. For an example of the "Hello World" program with a transient object server, see Hello World with a Transient Server. For more discussion of CORBA servers, see Developing Servers.

PersistentServer.java

// PersistentServer.java
// Copyright and License
import java.util.Properties;
import org.omg.CORBA.Object;
import org.omg.CORBA.ORB;
import org.omg.CosNaming.NameComponent;
import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextExtHelper;
import org.omg.CORBA.Policy;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.*;
import org.omg.PortableServer.Servant;

public class PersistentServer {

    public static void main( String args[] ) {
        Properties properties = System.getProperties();
        properties.put( "org.omg.CORBA.ORBInitialHost",
            "localhost" );
        properties.put( "org.omg.CORBA.ORBInitialPort",
            "1050" );

        try {
            // Step 1: Instantiate the ORB
            ORB orb = ORB.init(args, properties);

            // Step 2: Instantiate the servant
            PersistentHelloServant servant = new PersistentHelloServant(orb);

            // Step 3 : Create a POA with Persistent Policy
            // *******************
            // Step 3-1: Get the rootPOA
            POA rootPOA = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
            // Step 3-2: Create the Persistent Policy
            Policy[] persistentPolicy = new Policy[1];
            persistentPolicy[0] = rootPOA.create_lifespan_policy(
                LifespanPolicyValue.PERSISTENT);
            // Step 3-3: Create a POA by passing the Persistent Policy
            POA persistentPOA = rootPOA.create_POA("childPOA", null,
                persistentPolicy );
            // Step 3-4: Activate PersistentPOA's POAManager, Without this
            // All calls to Persistent Server will hang because POAManager
            // will be in the 'HOLD' state.
            persistentPOA.the_POAManager().activate( );
            // ***********************

            // Step 4: Associate the servant with PersistentPOA
            persistentPOA.activate_object( servant );

            // Step 5: Resolve RootNaming context and bind a name for the
            // servant.
            // NOTE: If the Server is persistent in nature then using Persistent
            // Name Service is a good choice. Even if ORBD is restarted the Name
            // Bindings will be intact. To use Persistent Name Service use
            // 'NameService' as the key for resolve_initial_references() when
            // ORBD is running.
            org.omg.CORBA.Object obj = orb.resolve_initial_references(
                "NameService" );
            NamingContextExt rootContext = NamingContextExtHelper.narrow( obj );

            NameComponent[] nc = rootContext.to_name(
                "PersistentServerTutorial" );
            rootContext.rebind( nc, persistentPOA.servant_to_reference(
                servant ) );

            // Step 6: We are ready to receive client requests
            orb.run();
        } catch ( Exception e ) {
            System.err.println( "Exception in Persistent Server Startup " + e );
        }
    }
}

Implementing the Servant (PersistentHelloServant.java)

The example servant, PersistentHelloServant, is the implementation of the Hello IDL interface; each Hello instance is implemented by a PersistentHelloServant instance. The servant is a subclass of HelloPOA, which is generated by the idlj compiler from the example IDL. The servant contains one method for each IDL operation, in this example, the sayHello() and shutdown() methods. Servant methods are just like ordinary Java methods; the extra code to deal with the ORB, with marshaling arguments and results, and so on, is provided by the skeleton.

PersistentHelloServant.java

// PersistentHelloServant.java
// Copyright and License
import org.omg.CORBA.ORB;

public class PersistentHelloServant extends Persistent.HelloPOA {
    private ORB orb;

    public PersistentHelloServant( ORB orb ) {
        this.orb = orb;
    }

    /**
     *  sayHello() method implementation returns a simple message.
     */
    public String sayHello( ) {
        return "Hello From Persistent Server...";
    }

    /**
     *  shutdown() method shuts down the Persistent Server.
     *  See NOTE below.
     */
    public void shutdown( ) {
        orb.shutdown( false );
    }
}

Note: For convenience of presentation in this example, the shutdown() method is included as part of the servant. This has been done in order to demonstrate the persistence of the server in this example. This is not a recommended programming convention for the following reasons:

  • If the orb.shutdown() method is called with parameter true (meaning "wait for completion") within the implementation of a remote method, the ORB will hang in a deadlock. Other threads can invoke orb.shutdown() without deadlock.
  • If you have multiple servants associated with the ORB, using the shutdown(false) method by one of them will make all of them unavailable.
  • The orb.shutdown(false) method should be called as part of the SERVER code under more controlled circumstances.

Implementing the Client Application (PersistentClient.java)

The example application client that follows:

  • Creates and initializes an ORB.
  • Resolves the PersistentHelloServant by using the Interoperable Naming Service's (INS) corbaname url. The URL locates the Naming Service running on host localhost and listening on port 1050. When located, it resolves "PersistentServerTutorial" from that Naming Service.
  • Invokes the object's sayHello() and shutdown() operations and prints the result. In this example, the client calls the sayHello() method every 3 seconds, then shuts down the server. The next call from the client will restart the server (because of the persistent lifespan of the server).

PersistentClient.java

// Copyright and License

import java.util.Properties;
import org.omg.CORBA.ORB;
import org.omg.CORBA.OBJ_ADAPTER;
import org.omg.CosNaming.NamingContext;
import org.omg.CosNaming.NamingContextHelper;
import org.omg.CosNaming.NameComponent;
import org.omg.PortableServer.POA;

import Persistent.HelloHelper;
import Persistent.Hello;

public class PersistentClient {

    public static void main(String args[]) {

        try {
            // Step 1: Instantiate the ORB
            ORB orb = ORB.init(args, null);

            // Step 2: Resolve the PersistentHelloServant by using INS's
            // corbaname url. The URL locates the NameService running on
            // localhost and listening on 1050 and resolve
            // 'PersistentServerTutorial' from that NameService
            org.omg.CORBA.Object obj = orb.string_to_object(
                "corbaname::localhost:1050#PersistentServerTutorial");

            Hello hello = HelloHelper.narrow( obj );

            // Step 3: Call the sayHello() method every 60 seconds and shutdown
            // the server. Next call from the client will restart the server,
            // because it is persistent in nature.
            while( true ) {
                System.out.println( "Calling Persistent Server.." );
                String helloFromServer = hello.sayHello();
                System.out.println("Message From Persistent Server: " +
                    helloFromServer );
                System.out.println( "Shutting down Persistent Server.." );
                hello.shutdown( );
                Thread.sleep( 60000 );
            }
        } catch ( Exception e ) {
            System.err.println( "Exception in PersistentClient.java..." + e );
            e.printStackTrace( );
        }
    }
}

Building and Running Hello World

Despite its simple design, the Hello World program lets you learn and experiment with all the tasks required to develop almost any CORBA program that uses static invocation.

This example requires a naming service, which is a CORBA service that allows CORBA objects to be named by means of binding a name to an object reference. The name binding may be stored in the naming service, and a client may supply the name to obtain the desired object reference. This example uses orbd, which contains a Persistent Naming Service and a Server Manager.

When running this example, remember that, when using Solaris software, you must become root to start a process on a port under 1024. For this reason, we recommend that you use a port number greater than or equal to 1024. The following instructions assume you can set the -ORBInitialPort option to use port 1050 for the Java IDL Object Request Broker Daemon, orbd. You can substitute a different port if necessary.

To run this client-server application on your development machine:

  1. Create or download the IDL and Java files for this example.
  2. Change to the directory that contains the file PersistentHello.idl.
  3. Run the IDL-to-Java compiler, idlj, on the IDL file to create stubs and skeletons. This step assumes that you have included the path to the java/bin directory in your path.
      idlj  -fall -td . -verbose  PersistentHello.idl

    You must use the -fall option with the idlj compiler to generate both client and server-side bindings. This command line will generate the default server-side bindings, which assumes the POA Inheritance server-side model. For more information on the idlj options, see IDL-to-Java compiler options.

    The idlj compiler generates a number of files. The actual number of files generated depends on the options selected when the IDL file is compiled. The generated files provide standard functionality, so you can ignore them until it is time to deploy and run your program. The files generated by the idlj compiler for PersistentHello.idl, with the -fall command line option, are:

    • HelloPOA.java

      This abstract class is the stream-based server skeleton, providing basic CORBA functionality for the server. It extends org.omg.PortableServer.Servant , and implements the InvokeHandler interface and the HelloOperations interface. The server class PersistentHelloServant extends HelloPOA.

    • _HelloStub.java

      This class is the client stub, providing CORBA functionality for the client. It extends org.omg.CORBA.portable.ObjectImpl and implements the Hello interface.

    • Hello.java

      This interface contains the Java version of our IDL interface. The Hello.java interface extends org.omg.CORBA.Object, providing standard CORBA object functionality. It also extends the HelloOperations interface and org.omg.CORBA.portable.IDLEntity.

    • HelloHelper.java

      This class provides auxiliary functionality, notably the narrow() method required to cast CORBA object references to their proper types.The Helper class is responsible for reading and writing the data type to CORBA streams, and inserting and extracting the data type from Anys. The Holder class delegates to the methods in the Helper class for reading and writing.

    • HelloHolder.java

      This final class holds a public instance member of type Hello. Whenever the IDL type is an out or an inout parameter, the Holder class is used. It provides operations for org.omg.CORBA.portable.OutputStream and org.omg.CORBA.portable.InputStream arguments, which CORBA allows, but which do not map easily to Java's semantics. The Holder class delegates to the methods in the Helper class for reading and writing. It implements org.omg.CORBA.portable.Streamable.

    • HelloOperations.java

      This interface contains the methods sayHello() and shutdown(). The IDL-to-Java mapping puts all of the operations defined on the IDL interface into this file, which is shared by both the stubs and skeletons.

  4. Compile the .java files, including the stubs and skeletons (which are in the directory Persistent). This step assumes the java/bin directory is included in your path.
       javac *.java Persistent/*.java
  5. Start orbd.

    To start orbd, enter one of the following:

    • Unix operating system:

      orbd -ORBInitialPort 1050 -serverPollingTime 200&

    • Windows operating system:

      start orbd  -ORBInitialPort 1050 -serverPollingTime 200&

    Note that 1050 is the port on which you want the name server to run. The -ORBInitialPort argument is a required command-line argument. Note that when using Solaris software, you must become root to start a process on a port under 1024. For this reason, we recommend that you use a port number greater than or equal to 1024.

    The -serverPollingTime 200 argument specifies how often ORBD checks for the health of persistent servers registered via servertool. The default value is 1,000 ms. We are setting this parameter to 200 ms in this example to enable more frequent monitoring of failures. In the event that a server failure is detected, the server will be restarted to its proper state.

  6. Start the Hello server:

    To register a persistent server with the ORBD, the server must be started using servertool, which is a command-line interface for application programmers to register, unregister, startup, and shutdown a persistent server. When the servertool is started, you must specify the port and the host (if different) on which orbd is executing.

    To start the Hello server,

    • Start the servertool from the command line of another terminal window or command prompt as follows:
        servertool -ORBInitialPort 1050        (Unix operating system)

  start servertool -ORBInitialPort 1050  (Windows operating system)

      Make sure the name server (orbd) port is the same as in the previous step, for example, -ORBInitialPort 1050. The servertool must be started on the same port as the name server.

      The servertool command line interface appears:

      Server Tool
    • Register the PersistentServer from the servertool prompt, as shown below. Type the information in one long string without returns.
        servertool  > register -server PersistentServer -applicationName s1
                -classpath path_to_server_class_files

      The servertool registers the server, assigns it the name of "s1", and displays its server id.

  7. Run the client application from the command line of another terminal window or command prompt:
      java -classpath . PersistentClient

    The terminal window or DOS prompt displays the following messages:

    Calling Persistent Server..
Message From Persistent Server: Hello From Persistent Server...
Shutting down Persistent Server..
Calling Persistent Server..
Message From Persistent Server: Hello From Persistent Server...
Shutting down Persistent Server..

In this example, the client invokes the sayHello() method every minute and then kills the persistent server, which will be automatically restarted the next time the client invokes the sayHello() method.

When you have finished this tutorial, be sure to shut down or kill the name server (orbd). To do this from a DOS prompt, select the window that is running the server and enter Ctrl+C to shut it down. To do this from a Unix shell, type pkill ordb from a terminal window. The server will continue to wait for invocations until it is explicitly stopped.

Running the Hello World Application on Two Machines describes one way of distributing the simple application across two machines - a client and a server.

Running the Example on Unix Using a Makefile

The following code provides an example of a Makefile that can be used to run this example. Change the location of JAVA_HOME to the location where you installed J2SE 5.0. Change the CLASSPATH variable to the directory where you have created the sample application. This example is for the Unix operating system, modify accordingly if using the Windows operating system.

#Change to location of your Java SE installation.
JAVA_HOME=/home/user_name/j2sdk1.5.0/

CLASSPATH=.

JAVAC=$(JAVA_HOME)/bin/javac
JAVA=$(JAVA_HOME)/bin/java

ORB_INITIAL_PORT=1050
ORB_INITIAL_HOST=localhost
ORB_ACTIVATION_PORT=1049

#Change ClassPath based on where your PersistentServer is located.
export CLASSPATH=<path to server class files>
IDLJ :=$(JAVA_HOME)/bin/idlj

ORB_PROPS=-Dorg.omg.CORBA.ORBInitialHost=$(ORB_INITIAL_HOST)
-Dorg.omg.CORBA.ORBInitialPort=$(ORB_INITIAL_PORT)

IDLJ_FLAGS=-fall -td . -verbose

ORBD=${JAVA_HOME}/bin/orbd -ORBInitialPort ${ORB_INITIAL_PORT}
-port ${ORB_ACTIVATION_PORT} -serverPollingTime 200
-serverStartupDelay 1000

SERVERTOOL=${JAVA_HOME}/bin/servertool

all: clean build run

build: stubs

stubs:
        $(IDLJ) $(IDLJ_FLAGS) PersistentHello.idl
        $(JAVAC) *.java
        $(JAVAC) Persistent/*.java

runc:
        $(JAVA) -classpath . PersistentClient

runorbd:
        $(ORBD)

# Enter the following command in servertool to register server:
# (without the # sign)
# register -server PersistentServer -applicationName s1
-classpath path_to_server_class_files

servertool:
        $(SERVERTOOL) -ORBInitialPort $(ORB_INITIAL_PORT)

clean:
        rm -rf Persistent
        rm -rf *.class

To run the application using the Makefile, enter the following commands:

  1. gnumake build
  2. gnumake runorbd
  3. gnumake runservertool
  4. In servertool, enter the commands as shown above
  5. gnumake runc
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL: Example with Callback Object

Client programs often react to changes or updates that occur in a server. For example, a client graph or spreadsheet program might need to be updated with each stock price update on a stock market server. The client has two options in this scenario:

  • Periodically ask for the stock price via a method request on the stock server. This is known as the "polling" or "pull" model.
  • Ask to be notified by the server whenever a price change occurs. This option is referred to as a "callback" or the "push" model.

The example in this document illustrates how a client program can pass a callback object to a server, and the server can then callback to notify changes to the client. At this time, we have provided the code for an extension of a simple application. Notes about simplifying the application are contained within the code.

This document provides the code for:

  • The IDL for an example program with a callback.
  • A server implementation that callsback to a client.
  • A client that sends a callback object reference to a server.
  • An implementation of the Listener.
  • An implementation of the MessageServer.

Instructions for compiling and running the example are also provided.

Callback Example: Intermediate Level

Writing the IDL file

For the example application, the file callback.idl looks like this:

interface Listener {
        void message(in string msg);
};

interface MessageServer {
        void register(in Listener lt);
};

Writing the Server Code

For the example application, the Server.java file looks like as follows.

import org.omg.CORBA.ORB;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;
import org.omg.CosNaming.NameComponent;
import org.omg.CosNaming.NamingContext;
import org.omg.CosNaming.NamingContextHelper;

public class Server {

    public static void main(String[] args) {
        try {
            //create and initialize the ORB
            Properties props = System.getProperties();
            props.put("org.omg.CORBA.ORBInitialPort", "1050");
            //Replace MyHost with the name of the host on which you are running the server
            props.put("org.omg.CORBA.ORBInitialHost", "<MyHost>");
            ORB orb = ORB.init(args, props);
            System.out.println("Initialized ORB");

            //Instantiate Servant and create reference
            POA rootPOA = POAHelper.narrow(
                orb.resolve_initial_references("RootPOA"));
            MessageServerImpl msImpl = new MessageServerImpl();
            rootPOA.activate_object(msImpl);
            MessageServer msRef = MessageServerHelper.narrow(
                rootPOA.servant_to_reference(msImpl));

            //Bind reference with NameService
            NamingContext namingContext = NamingContextHelper.narrow(
                orb.resolve_initial_references("NameService"));
            System.out.println("Resolved NameService");
            NameComponent[] nc = { new NameComponent("MessageServer", "") };
            namingContext.rebind(nc, msRef);

            //Activate rootpoa
            rootPOA.the_POAManager().activate();

            //Start readthread and wait for incoming requests
            System.out.println("Server ready and running ....");

            //REMOVE THE NEXT LINE FOR THE SIMPLER EXAMPLE
            msImpl.startReadThread();

            orb.run();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Writing the MessageServer Implementation

The file registers new clients, accepts messages, then relays the messages to the registered clients. For the example application, the file MessageServerImpl.java looks like the following example.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Vector;
import java.util.Iterator;

public class MessageServerImpl extends MessageServerPOA {

    private Vector clients = new Vector();
    private ReadThread rt = null;

    public MessageServerImpl() {
        rt = new ReadThread(this);
    }

    public void register(Listener lt) {
        clients.add(lt);
    }

    public void startReadThread() {
        rt.start();
    }

    public void message(String msg) {
        Iterator it = clients.iterator();
        while (it.hasNext()) {
            Listener lt = (Listener) it.next();
            lt.message(msg);
            //FOR THE SIMPLER EXAMPLE, ADD A SIMPLE
            //MESSAGE TO BE CALLED BACK, FOR EXAMPLE,
            //SLEEP FOR 30 SECONDS, THEN SEND THE TIME
        }
    }
}

//EXCLUDE THIS CLASS FOR THE SIMPLER EXAMPLE
class ReadThread extends Thread {

    MessageServerImpl msImpl = null;

    public ReadThread(MessageServerImpl msImpl) {
        this.msImpl = msImpl;
    }

    public void run() {
        BufferedReader br = new BufferedReader(
            new InputStreamReader(System.in));

        try {
            for (;;) {
                System.out.print("message > ");
                String msg = br.readLine();
                msImpl.message(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Writing the Client Code

For the example application, the file Client.java file looks like the following example.

import java.util.Properties;
import org.omg.CORBA.ORB;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;
import org.omg.CosNaming.NameComponent;
import org.omg.CosNaming.NamingContext;
import org.omg.CosNaming.NamingContextHelper;

public class Client {

    public static void main(String[] args) {
        try {

            //initialize orb
            Properties props = System.getProperties();
            props.put("org.omg.CORBA.ORBInitialPort", "1050");
            //Replace MyHost with the name of the host on which you are running the server
            props.put("org.omg.CORBA.ORBInitialHost", "<MyHost>");
            ORB orb = ORB.init(args, props);
            System.out.println("Initialized ORB");

            //Instantiate Servant and create reference
            POA rootPOA = POAHelper.narrow(
                orb.resolve_initial_references("RootPOA"));
            ListenerImpl listener  = new ListenerImpl();
            rootPOA.activate_object(listener);
            Listener ref = ListenerHelper.narrow(
                rootPOA.servant_to_reference(listener));

            //Resolve MessageServer
            MessageServer msgServer = MessageServerHelper.narrow(
                orb.string_to_object("corbaname:iiop:1.2@localhost:1050#MessageServer"));

            //Register listener reference (callback object) with MessageServer
            msgServer.register(ref);
            System.out.println("Listener registered with MessageServer");

            //Activate rootpoa
            rootPOA.the_POAManager().activate();

            //Wait for messages
            System.out.println("Wait for incoming messages");
            orb.run();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Writing the Listener Implementation

When the Listener identifies that a message has been received from the server, it displays the message on the client. For the example application, the ListenerImpl.java file looks like the following example.

public class ListenerImpl extends ListenerPOA {

    public void message(String msg) {
        System.out.println("Message from server : " + msg);
    }
}

Instructions for compiling and running the example

To run the example application, you would follow these instructions on the SERVER machine:
  1. If you've run the example previously, remove any existing generated files. In the Unix operating environment, this command would be as follows:
    rm -rf ./classes ./orb.db
  2. Generate the stubs and skeletons. First, you need to create the directory where the stubs and skeletons will reside, then run the idlj compiler to generate the stubs and skeletons. This command would look like this:
    mkdir -p ./classes
<path_to_java>/bin/idlj -fall -td ./classes callback.idl
  3. Compile the .java files, as follows:
    <path_to_java>/bin/javac -classpath ./classes -d ./classes *.java
  4. Start the orbd naming service, as follows:
    <path_to_java>/bin/orbd -ORBInitialPort 1050 -ORBInitialHost <host_name> &
  5. Run the server, as follows:
    <path_to_java>/bin/java -classpath ./classes Server -ORBInitialPort 1050

After you have started the server, you will see output such as the following in the terminal window:

Initialized ORB
Resolved NameService
Server ready and running ....
message >

At this prompt, you will send messages to the client, but first you need to start the client application. From the CLIENT terminal, follow these steps to run the client. Make sure that you used the host name on which the server is running in the properties section of the client code.

<path_to_java>/bin/java -classpath ./classes Client -ORBInitialPort 1050

The output from the client will display in a format similar to this:

Initialized ORB
Listener registered with MessageServer
Wait for incoming messages

To display the functionality of using a callback, you would enter a data on the server terminal, at the prompt, and it will display on all client terminals. This could be anything where clients are interested in some notifications.

One example is a football game score where clients are notified whenever the score changes.

message > Niners TD. Niners 7 - Giants 0
message > Giants TD. Niners 7 - Giants 7
message > Niners TD. Niners 14 - Giants 7

When messages such as those shown above are sent, the client display looks similar to the following:

Wait for incoming messages
Message from server : Niners TD. Niners 7 - Giants 0
Message from server : Giants TD. Niners 7 - Giants 7
Message from server : Niners TD. Niners 14 - Giants 7
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL: Exceptions

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Exceptions

CORBA has two types of exceptions: standard system exceptions which are fully specified by the OMG and user exceptions which are defined by the individual application programmer. CORBA exceptions are a little different from Java exception objects, but those differences are largely handled in the mapping from IDL to Java.

Topics in this section include:

  • Differences Between CORBA and Java Exceptions
  • System Exceptions
    • System Exception Structure
    • Minor Codes
    • Completion Status
  • User Exceptions
  • Minor Code Meanings

Differences Between CORBA and Java Exceptions

To specify an exception in IDL, the interface designer uses the raises keyword. This is similar to the throws specification in Java. When you use the exception keyword in IDL you create a user-defined exception. The standard system exceptions need not (and cannot) be specified this way.

System Exceptions

CORBA defines a set of standard system exceptions, which are generally raised by the ORB libraries to signal systemic error conditions like:
  • Server-side system exceptions, such as resource exhaustion or activation failure.
  • Communication system exceptions, for example, losing contact with the object, host down, or cannot talk to ORB daemon (orbd).
  • Client-side system exceptions, such as invalid operand type or anything that occurs before a request is sent or after the result comes back.

All IDL operations can throw system exceptions when invoked. The interface designer need not specify anything to enable operations in the interface to throw system exceptions -- the capability is automatic.

This makes sense because no matter how trivial an operation's implementation is, the potential of an operation invocation coming from a client that is in another process, and perhaps (likely) on another machine, means that a whole range of errors is possible.

Therefore, a CORBA client should always catch CORBA system exceptions. Moreover, developers cannot rely on the Java compiler to notify them of a system exception they should catch, because CORBA system exceptions are descendants of java.lang.RuntimeException.

System Exception Structure

All CORBA system exceptions have the same structure:

exception <SystemExceptionName> { // descriptive of error
    unsigned long minor;          // more detail about error
    CompletionStatus completed;   // yes, no, maybe
}

System exceptions are subtypes of java.lang.RuntimeException through org.omg.CORBA.SystemException:

  • java.lang.Exception
    • java.lang.RuntimeException
      • org.omg.CORBA.SystemException
        • BAD_PARAM
        • //etc.

Minor Codes

All CORBA system exceptions have a minor code field, a number that provides additional information about the nature of the failure that caused the exception. Minor code meanings are not specified by the OMG; each ORB vendor specifies appropriate minor codes for that implementation. For the meaning of minor codes thrown by the Java ORB, see Minor code meanings .

Completion Status

All CORBA system exceptions have a completion status field, indicating the status of the operation that threw the exception. The completion codes are:

COMPLETED_YES
The object implementation has completed processing prior to the exception being raised.
COMPLETED_NO
The object implementation was not invoked prior to the exception being raised.
COMPLETED_MAYBE
The status of the invocation is unknown.

User Exceptions

CORBA user exceptions are subtypes of java.lang.Exception through org.omg.CORBA.UserException:

  • java.lang.Exception
    • org.omg.CORBA.UserException
      • Stocks.BadSymbol
      • //etc.

Each user-defined exception specified in IDL results in a generated Java exception class. These exceptions are entirely defined and implemented by the programmer

Minor Code Meanings

System exceptions all have a field minor that allows CORBA vendors to provide additional information about the cause of the exception. For a list of standard OMG minor code exceptions (OMGVMCID), see the Object Management Group website.

Some of the most common Sun minor code exceptions are the following:

  • COMM_FAILURE/201. vmcid: SUN minor code: 201 literally means "CONNECT_FAILURE". This may be caused by a java.net.SocketException, usually one of BindException, ConnectException, or NoRouteToHostException.

    Some things to verify are:

    • Is a naming service running? If not, start the ORBD naming service as described in the document Starting and Stopping ORBD.
    • Are the -ORBInitialHost and -ORBInitialPort values being set correctly for the naming service? If you are uncertain about what the settings should be, read the document Starting and Stopping ORBD.
    • Are the client and server applications aware of the port number (and machine name, if applicable) where the Naming Service is running? Read Starting and Stopping ORBD for more information on how to do this.
  • COMM_FAILURE/208. vmcid: SUN minor code: 208 literally means "CONNECTION ABORT", which generally means the connection has been dropped.
  • COMM_FAILURE/209. vmcid: SUN minor code: 209 literally means "CREATE_LISTENER_FAILED": Unable to create the listener thread on the specific port. Either the post is taken or there was an error creating the daemon thread. This generally indicates that the port on which you are trying to run the naming service is in use by another process. If you are running on Solaris, you could discover whether or not something is running on this port using the following terminal prompt command:
    netstat | grep port_number
  • OBJECT_NOT_EXIST/204. vmcid: SUN minor code: 204 literally means "SERVANT_NOT_FOUND". It is only thrown in one place: corba.INSSubcontract.getINSReference.
  • MARSHAL/217. vmcid: SUN minor code: 217 means that your client tried to send either a wchar or wstring in GIOP 1.0, which is not legal in the spec.
  • MARSHAL/202. vmcid: SUN minor code: 202 means that the code is attempting to marshal an object that derives from org.omg.CORBA.Object, but that particular instance has never been connected to an ORB. When using the POA, you need to register the object with the POA first. If you need more information on how to register an object with the POA, refer to the POA document or the tutorial.
  • BAD_PARAM/201. vmcid: SUN minor code: 201 literally means "NULL_PARAM". This exception often occurs because a Java null was given to a write method such as write_string, write_octet_array, etc. You cannot return a Java null as the result of a Java method.
  • org.omg.CORBA.INTERNAL. vmcid: SUN minor code: 208 means Unable to determine local hostname using InetAddress.getLocalHost().getHostName().

    The ORB uses InetAddress.getLocalHost().getHostName() to create a reference to the name service for looking for and/or binding references. It also uses InetAddress.getLocalHost().getHostName() on the server side to create remote object references (i.e., IORs) that contain the name/port of the server (rather than a dotted-decimal/port pair).

    To avoid the call to getHostName, you can set the following properties (refer to Starting and Stopping ORBD if you are not sure how to do this):

    • Set com.sun.CORBA.ORBServerHost to the DNS name or dotted-decimal address of the server if the ORB is acting as a server.
    • Set com.sun.CORBA.ORBInitialHost to the DNS name or dotted-decimal address of the name server.

    NOTE: These properties are proprietary and are subject to deletion or change.

If none of these suggestions work for you, or if you encounter a different Sun minor code exception, post a message to the developer forum at http://forum.java.sun.com.

When requesting the meaning of a minor code, include the following information:

  • The platform on which the client and server are running (e.g., Solaris, Linux, Win32)
  • The version of Java SE you are using (e.g., 1.5.0_01)
  • A complete stack trace
  • If you are using a naming service or an ORB from a different vendor, provide the information on the vendor and version of the product.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL FAQ

This is a document that attempts to answer many of the questions you may have about using Java IDL technology.

Errors

  • Why do I get this message when I try to run HelloServer: Exception in thread "main" java.lang.NoClassDefFoundError: HelloServer/java
  • My existing programs aren't running using this release. Are there any compatibility issues that could affect this?
  • Why can't I connect using IOR's from a Linux server when the IOR contains 127.0.0.0 as the host address?
  • What does this minor code mean?
  • Can I add multiple classpaths when starting a server using servertool?
  • What do I do when the naming service (tnameserv, orbd) fails to run on the Linux platform??

Features

  • What is the thread model supported by the CORBA implementation in this release?
  • Does Java IDL contain notification/event services? an Interface Repository?
  • How can I run the Hello World example on two machines?
  • Is Java IDL compliant with OMG CORBA specifications?

Compatibility/Interoperability

  • With which CORBA specifications does J2SE 5.0 comply?
  • How can I specify a different ORB?
  • How can I test whether my JDK ORB Client can communicate with another vendor's ORB implementation?
  • Do you have any examples that use a CORBA client and a Java server application?
  • How do I connect to a 3rd-party Naming Service from Sun's ORB?
  • Can I use the Java IDL ORB with a C++ CORBA server? (interoperability)

General

  • Should I use Java IDL or Java RMI-IIOP technology?
  • Where can I download the idltojava compiler?
  • What are my options for developing CORBA applications using Java technology?
  • What is the difference between Java IDL and Java RMI-IIOP?
  • What are the limitations of Java IDL and Java RMI-IIOP in this release?
  • What are the standard tags for ...?

Errors

Why do I get this message when I try to run HelloServer: "Exception in thread "main" java.lang.NoClassDefFoundError: HelloServer/java"

The most common reason for this error when running HelloServer (and also HelloClient) from the Java IDL tutorial is that HelloServer is not in the classpath. For more information on setting the classpath variable, see Setting the class path.

The second most common reason occurs when a space is added between quotation marks in the following line of code:

NameComponent nc = new NameComponent("Hello", "");

There should be no spaces between the quotation marks. Without spaces, this value is passed as a null. With a space between the quotations, a space character is passed.

My existing programs aren't running using this release. Are there any compatibility issues that could affect this?

Information on compatibility between J2SE 1.4.x and J2SE 5.0 can be found in CORBA Compatibility Information - J2SE 5.0.

Why can't I connect using IOR's from a Linux server when the IOR contains 127.0.0.0 as the host address?

On Red Hat Linux installations InetAddress.getLocalHost() may return an InetAddress corresponding to the loopback address (127.0.0.1). This arises because the default installation creates an association in /etc/hosts between the hostname of the machine and the loopback address. To ensure that InetAddress.getLocalHost() returns the actual host address, update the /etc/hosts file or the name service configuration file (/etc/nsswitch.conf) to query dns or nis before searching hosts.

What does this minor code mean?

The most recent versions of the standard (OMG) minor code exceptions can be found on the OMG Web site at http://www.omg.org/.

Some of the most common Sun minor code exceptions are the following:

  • COMM_FAILURE/201. vmcid: SUN minor code: 201 literally means "CONNECT_FAILURE". This may be caused by a java.net.SocketException, usually one of BindException, ConnectException, or NoRouteToHostException.

    Some things to verify are:

    • Is a naming service running? If not, start the ORBD naming service as described in the document Starting and Stopping ORBD.

    • Are the -ORBInitialHost and -ORBInitialPort values being set correctly for the naming service? If you are uncertain about what the settings should be, read the document Starting and Stopping ORBD.

    • Are the client and server applications aware of the port number (and machine name, if applicable) where the Naming Service is running? Read Starting and Stopping ORBD for more information on how to do this.

  • COMM_FAILURE/208. vmcid: SUN minor code: 208 literally means "CONNECTION ABORT", which generally means the connection has been dropped.

  • COMM_FAILURE/209. vmcid: SUN minor code: 209 literally means "CREATE_LISTENER_FAILED": Unable to create the listener thread on the specific port. Either the post is taken or there was an error creating the daemon thread. This generally indicates that the port on which you are trying to run the naming service is in use by another process. If you are running on Solaris, you could discover whether or not something is running on this port using the following terminal prompt command:

    netstat | grep port_number

  • OBJECT_NOT_EXIST/204. vmcid: SUN minor code: 204 literally means "SERVANT_NOT_FOUND". It is only thrown in one place: corba.INSSubcontract.getINSReference.

  • MARSHAL/217. vmcid: SUN minor code: 217 means that your client tried to send either a wchar or wstring in GIOP 1.0, which is not legal in the spec.

  • MARSHAL/202. vmcid: SUN minor code: 202 means that the code is attempting to marshal an object that derives from org.omg.CORBA.Object, but that particular instance has never been connected to an ORB. When using the POA, you need to register the object with the POA first. If you need more information on how to register an object with the POA, refer to Portable Object Adapter (POA) or the Getting Started with Java™ IDL tutorial.

  • BAD_PARAM/201. vmcid: SUN minor code: 201 literally means "NULL_PARAM". This exception often occurs because a Java null was given to a write method such as write_string, write_octet_array, etc. You cannot return a Java null as the result of a Java method.

  • org.omg.CORBA.INTERNAL. vmcid: SUN minor code: 208 means Unable to determine local hostname using InetAddress.getLocalHost().getHostName().

    The ORB uses InetAddress.getLocalHost().getHostName() to create a reference to the name service for looking for and/or binding references. It also uses InetAddress.getLocalHost().getHostName() on the server side to create remote object references (i.e., IORs) that contain the name/port of the server (rather than a dotted-decimal/port pair).

    To avoid the call to getHostName, you can set the following properties (refer to Starting and Stopping ORBD if you are not sure how to do this):

    • Set com.sun.CORBA.ORBServerHost to the DNS name or dotted-decimal address of the server if the ORB is acting as a server.

    • Set com.sun.CORBA.ORBInitialHost to the DNS name or dotted-decimal address of the name server.

    NOTE: These properties are proprietary and are subject to deletion or change.

Can I add multiple classpaths when starting a server using servertool?

The longer version of this question was as follows: My server code needs multiple JAR files in the classpath. When I register my server using the servertool, and try to specify the classpath, I get the syntax of the register command. I assume my command line is exceeding the limit.

How do I specify a really long classpath while registering the server in the servertool?

The servertool does accept multiple JAR files, however, there is currently a bug with the length of the command line buffer in servertool. Read more about the servertool wrapper bug, 4482166.

The workaround is to call the ServerTool class to start the server, rather than starting the server from within servertool, such as:

${JAVA_HOME}/bin/java com.sun.corba.se.internal.Activation.ServerTool
-ORBInitialPort ${ORB_INITIAL_PORT} -cmd register -server
sample.MyServer -classpath jar1:jar2:jar3 -applicationName sample

Please note that the name of the servertool class may change in future releases.

What do I do when the naming service (tnameserv, orbd) fails to run on the Linux platform?

If the naming service fails to startup on Linux, include the following lines in the /etc/hosts file:
<Local Host IP Address>   localhost
<Local Host IP Address>   <HostName>

where <Local Host IP Address> is the IP address where the naming service (tnameserv, orbd) is started.

Features

What is the thread model supported by the CORBA implementation in this release?

The Java CORBA ORB shipped in Java SE is multi-threaded. On the server side, we have a thread pool such that each incoming request is handled by a separate thread. If all the pool's threads are in use when a new request comes in, a new thread is created and added to the pool. The thread is returned to the pool after the request is finished. The Java CORBA ORB is threaded to allow scalability and concurrent request processing. The SINGLE_THREAD option for the POA threading policy is not supported. The threading model for the Java CORBA ORB is implicit: the user does not set the thread policy for the ORB. There are no external, user-level APIs exposed for controlling the threading model or the number of threads.

Does Java IDL contain notification/event services? an Interface Repository?

No, it does not. If you need one of these services, you can implement one, you can purchase one off the shelf, or you can search for one freely available to start things off with. You can plug-in 3rd party services such as these to the ORB using INS technology.

How can I run the Hello World example on two machines?

You need to use the -ORBInitialHost <Host Name where Name Service is Launched> option when starting the client and/or server (whichever is not running on the same machine as the name server). This way the client and server know where to find the Name Service. An example can be found at Java IDL: The "Hello World" Example on Two Machines.

Is Java IDL technology compliant with CORBA specifications?

For compliance information for CORBA technology shipped with J2SE 5.0, read the CORBA compliance statement at Official Specifications for CORBA support in J2SE 5.0.

Compatibility/Interoperability

With which CORBA specifications does J2SE 5.0 comply?

See Official Specifications for CORBA support in J2SE 5.0.

How can I specify a different ORB?

To use an ORB other than the Java CORBA ORB in your application, you can set the org.omg.CORBA.ORBClass property to the ORB of your choice. For example, use code as shown in the example to explicitly set the ORB to the ORB-implementation you would prefer to use:
public class MyApp {

    public static void main( String args[] ) {
        Properties properties = System.getProperties();
        properties.put( "org.omg.CORBA.ORBClass",
            "<com.other_company.package.ORB>" );

        try {
             ORB orb = ORB.init( args, properties);

             ...

Check the vendor's documentation for information on setting properties specific to their ORB implementation.

How can I test whether my JDK ORB Client can communicate with another company's ORB implementation?

This ORB has been tested as part of the J2EE certification process, however, it has not been tested with all vendor's standalone CORBA ORBs.

If INS is supported in the other vendor's service, then, try this. Convert the Interoperable Object References (see Java ID: Interoperable Naming Service Example) on the other vendor's ORB server to a string using the ORB.object_to_string() method using INS. Write that string to a file.

Do you have any examples that use a CORBA client and an EJB server application?

A developer guide that includes an example application with a C++ client and an Enterprise JavaBeans component can be found on the Web site at: Enterprise JavaBeans™ Components and CORBA Clients: A Developer's Guide.

How do I connect to a 3rd-party Naming Service from Sun's ORB?

The recommended way is to use the Java IDL: Interoperable Naming Service (INS) Example, if this option is supported by the 3rd-party Naming Service.

To use the Sun ORB with another vendor's Naming Service,

  1. Start the 3rd-party name server on Host <H> and Port. <P>
  2. Pass the following argument to ORB.init():
            -ORBInitRef NameService=corbaloc:iiop:1.2@:/NameService

When you do orb.resolve_initial_references( "NameService" ), you should be able to connect to 3rd-party Name Service. If you are still not able to connect, try these troubleshooting hints:

  • Verify that the 3rd-party Name Service supports INS.
  • Verify that the host and port information is accurate.
  • Verify that the 3rd-party Name Service has been started successfully.
  • Verify that the 3rd-party Name Service supports GIOP 1.2. If not, refer to the Name Server's documentation for the correct the GIOP version, and modify the corbaloc: URL accordingly.
  • Determine if the 3rd-party Name Service has a different object key it uses to contact NameService. If so, refer to the Name Server's documentation.

Can I use the Java IDL ORB with a C++ CORBA server? (interoperability)

The Java IDL ORB is an ORB completely written using Java technology. The idlj compiler generates code that follows the conventions defined in the IDL to Java Language Mapping Specification. The Java ORB does not provide a compiler that generates code in any languages other than the Java platform. If you want to test interoperability between the Java ORB and an ORB written in another language (such as C++), you will need to find an ORB written in that language and a compiler that conforms to the specific language mapping. Language mapping specifications are available from the Object Management Group Web site at http://www.omg.org/. A user who wants to use the Java platform on one side and C++ on the other will only share the IDL. You will have to use your C++ ORB's tools to generate the stubs and skeletons for use with the C++ ORB, but you don't have to change the IDL at all. To find a vendor that provides a CORBA ORB and a language mapping compiler in the language you are working with, search the Web for "C++ CORBA ORB", or equivalent.

A developer guide that includes an example application with a C++ client and an Enterprise JavaBeans component can be found on the Web site at: Enterprise JavaBeans™ Components and CORBA Clients: A Developer's Guide.

Although it is true that ORBs written in different languages should be able to talk to each other, we haven't tested the interoperability of the Java ORB with other vendor's ORBs.

General

Should I use Java IDL or Java RMI-IIOP technology?

This is a fundamental question and it's important to understand the distinction between these two ways of integrating the Java programming language with CORBA.

Java IDL technology is for CORBA programmers who want to program in the Java programming language based on interfaces defined in CORBA Interface Definition Language (IDL). This is "business as usual" CORBA programming, supporting Java in exactly the same way as other languages like C++ or COBOL.

Java Remote Method Invocation over Internet Inter-ORB Protocol ("RMI-IIOP") technology is for Java programmers who want to program to the Java Remote Method Invocation ("Java RMI") interfaces, but use IIOP as the underlying transport. RMI-IIOP provides interoperability with other CORBA objects implemented in various languages - but only if all the remote interfaces are originally defined as Java RMI interfaces. It is of particular interest to programmers using Enterprise JavaBeans™ (EJB™) technology, since the EJB remote object model is based on Java RMI technology.

Where can I download the idltojava compiler?

The idltojava compiler is no longer available for download. We highly recommend that you use the latest version of the IDL-to-Java compiler, idlj.

To get the latest version of the IDL-to-Java compiler, download the latest version of the Java™ Platform, Standard Edition (Java SE). When Java SE is installed, idlj will be located in the bin directory.

Other troubleshooting information related to idltojava is located in the Java IDL FAQ for J2SE v.1.3.

What are my options for developing CORBA applications using Java technology?

CORBA technology as part of the Java 2 platform consists of an Object Request Broker (ORB) written in the Java language (with a small bit of native code), the RMI programming model, and the IDL programming model. The "magic" that gives us the cross-language, cross-vendor interoperability is the Internet InterORB Protocol, or IIOP. IIOP can be a transport protocol for distributed applications written in either IDL or Java RMI. IIOP allows distributed objects to conform to OMG's CORBA specification. When using the IDL programming model, the interface is everything! It defines the points of entry that can be called from a remote process, such as the types of arguments the called procedure will accept, or the value/output parameter of information returned. Using IDL, the programmer can make the entry points and datatypes that pass between communicating processes act like a standard language. CORBA is a language-neutral system in which the argument values or return values are limited to what can be represented in the involved implementation languages. In CORBA, object orientation is limited only to objects that can be passed by reference (the object code itself cannot be passed from machine-to-machine) or are predefined in the overall framework. Passed and returned types must be those declared in the interface. With RMI, the IDL and the implementation language are the same thing, so you don't have to worry about mapping from one to the other. Language-level objects (the code itself) can be passed from one process to the next. Values can be returned by their actual type, not the declared type. Or, you can compile the interfaces to generate IIOP-compliant stubs and skeletons to talk to objects written on other machines in other CORBA-compliant languages.

What is the difference between Java IDL and Java RMI-IIOP?

This is a fundamental question and it's important to understand the distinction between these two ways of integrating the Java programming language with CORBA. Java IDL is for CORBA programmers who want to program in the Java programming language based on interfaces defined in CORBA Interface Definition Language (IDL). This is "business as usual" CORBA programming, supporting the Java language in exactly the same way as other languages like C++ or COBOL. Java RMI-IIOP (Remote Method Invocation over Internet Inter-ORB Protocol) is for developers who want to use the Java programming language to program to the Java RMI interfaces, but use IIOP as the underlying transport. Java RMI-IIOP provides interoperability with other CORBA objects implemented in various languages - but only if all the remote interfaces are originally defined as Java RMI interfaces. It is of particular interest to programmers using Enterprise JavaBeans (EJB), since the remote object model for EJB's is RMI-based. There are several scenarios that will define how you will want to create distributed CORBA applications. Here are some of them:
  • Java IDL - If you have been developing CORBA applications using IDL for some time, you will probably want to stay in this environment. Create the interfaces using IDL, and define the client and server applications using the Java programming language to take advantage of its portability, its highly productive implementation environment, and its very robust platform.
  • RMI-JRMP - If all of your applications are written in the Java programming language, you will probably want to use Java RMI technology to enable communication between Java objects on different virtual machines and different physical machines. Using Java RMI without its IIOP option leverages its strengths of code portability, security, and garbage collection.
  • Java RMI-IIOP - If you are writing most of your new applications using the Java programming language, but need to maintain legacy applications written in other programming languages as well, you will probably want to use Java RMI with its IIOP compiler option.

What are the limitations when using Java IDL and/or Java RMI-IIOP?

For more information on product limitations, read Limitations.

What are the standard tags for ...?

The most recent versions of standard tag allocation files can be found at the OMG Web site: http://www.omg.org/.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL: Glossary

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Glossary of Java IDL Terms

adapter activator
An adapter activator is an object that the application developer can associate with a POA. The ORB will invoke an operation on an adapter activator when a request is received for a child POA that does not currently exist. The adapter activator can then create the required POA on demand.

attribute (IDL)
An identifiable association between an object and a value. An attribute A is made visible to clients as a pair of operations: get_A and set_A. Readonly attributes only generate a get operation.

Also, that part of an IDL interface that is similar to a public class field or C++ data member. The idlj compiler maps an OMG IDL attribute to accessor and modifier methods in the Java programming language. For example, an interface ball might include the attribute color. The idlj compiler would generate a Java programming language method to get the color, and unless the attribute is readonly, a method to set the color.

client
Any code which invokes an operation on a distributed object. A client might itself be a CORBA object, or it might be a non-object-oriented program, but while invoking a method on a CORBA object, it is said to be acting as client.

client stub
A Java programming language class generated by idlj and used transparently by the client ORB during object invocation. The remote object reference held by the client points to the client stub. This stub is specific to the IDL interface from which it was generated, and it contains the information needed for the client to invoke a method on the CORBA object that was defined in the IDL interface.

client tier
The portion of a distributed application that requests services from the server tier. Typically, the client tier is characterized by a small local footprint, a graphical user interface, and simplified development and maintenance efforts.

Common Object Request Broker Architecture (CORBA)
An OMG-specified architecture that is the basis for the CORBA object model. The CORBA specification includes an interface definition language (IDL), which is a language-independent way of creating contracts between objects for implementation as distributed applications.

The Java 2 Platform Standard Edition (J2SE) provides a CORBA Object Request Broker (ORB) and two CORBA programming models that utilize the Java CORBA ORB and Internet InterORB Protocol (IIOP). The two programming models are the RMI programming model, or RMI-IIOP, and the IDL programming model, or Java IDL. For more information on these programming models, read CORBA Technology and the Java Platform.
See also: client tier, service tier, data store tier

CORBA object
An entity which (1) is defined by an OMG IDL interface, and (2) for which an object reference is available. Object is also the implicit common base type for object references of IDL interfaces.

data store tier
The portion of a distributed application that manages access to persistent data and its storage mechanisms, such as relational databases.

distributed application
A program designed to run on more than one computer, typically with functionality separated into tiers such as client, service, and data store.

distributed environment
A network of one or more computers that use CORBA objects. Objects are installed on the various machines and can communicate with each other.

Dynamic Invocation Interface (DII)
An API that allows a client to make dynamic invocations on remote CORBA objects. It is used when at compile time a client does not have knowledge about an object it wants to invoke. Once an object is discovered, the client program can obtain a definition of it, issue a parameterized call to it, and receive a reply from it, all without having a type-specific client stub for the remote object.

Dynamic Skeleton Interface (DSI)
An API that provides a way to deliver requests from an ORB to an object implementation when the type of the object implementation is not known at compile time. DSI, which is the server side analog to the client side DII, makes it possible for the application programmer to inspect the parameters of an incoming request to determine a target object and method.

exception (IDL)
An IDL construct that represents an exceptional condition that could be returned in response to an invocation. There are two categories of exceptions: (1) system exceptions, which inherit from org.omg.CORBA.SystemException (which is a java.lang.RuntimeException), and (2) user-defined exceptions, which inherit from org.omg.CORBA.UserException (which is a java.lang.Exception).

factory object
A CORBA object that is used to create new CORBA objects. Factory objects are themselves usually created at server installation time.

idlj compiler
A tool that takes an interface written in OMG IDL and produces Java programming language interfaces and classes that represent the mapping from the IDL interface to the Java programming language. The resulting files are .java files. Prior to JDK 1.3, the idlj compiler was known as the idltojava compiler. The idlj compiler supports new CORBA-standard features required for RMI-IIOP. The idlj compiler is placed in the SDK's .bin directory by the installer.

idltojava compiler
A tool that takes an interface written in OMG IDL and produces Java programming language interfaces and classes that represent the mapping from the IDL interface to the Java programming language. The resulting files are .java files. Beginning with JDK 1.3, the IDL-to-Java language mapping is handled by the idlj compiler, which supports new CORBA-standard features required for RMI-IIOP. The idltojava compiler can be downloaded from the Java Developer Connection (JDC) web site.

implementation
A concrete class that defines the behavior for all of the operations and attributes of the IDL interface it supports. A servant object is an instance of an implementation. There may be many implementations of a single interface.

initial naming context
The NamingContext object returned by a call to the method orb.resolve_initial_references("NameService"). It is an object reference to the COS Naming Service registered with the ORB and can be used to create other NamingContext objects.
See also: naming context

Interface Definition Language (IDL)
The OMG-standard language for defining the interfaces for all CORBA objects. An IDL interface declares a set of operations, exceptions, and attributes. Each operation has a signature, which defines its name, parameters, result and exceptions. OMG IDL does not include implementations for operations; rather, as its name indicates, it is simply a language for defining interfaces. The complete syntax and semantics for IDL are available in the OMG specification at the OMG web site.

Interface Repository (IFR)
A service that contains all the registered component interfaces, the methods they support, and the parameters they require. The IFR stores, updates, and manages object interface definitions. Programs may use the IFR APIs to access and update this information. An IFR is not necessary for normal client/server interactions.

Internet InterORB Protocol (IIOP)
The OMG-specified network protocol for communicating between ORBs. Java IDL conforms to CORBA/IIOP specification 2.3.1.

invocation
The process of performing a method call on a CORBA object, which can be done without knowledge of the object's location on the network. Static invocation, which uses a client stub for the invocation and a server skeleton for the service being invoked, is used when the interface of the object is known at compile time. If the interface is not known at compile time, dynamic invocation must be used.

Java IDL
The classes, libraries, and tools that make it possible to use CORBA objects from the Java programming language. The main components of Java IDL are an ORB, a naming service, and the idlj compiler. All are part of this release of J2SE.

name binding
The association of a name with an object reference. Name bindings are stored in a naming context.

namespace
A collection of naming contexts that are grouped together.

naming context
A CORBA object that supports the NamingContext interface and functions as a sort of directory which contains (points to) other naming contexts and/or simple names. Similar to a directory structure, where the last item is a file and preceding items are directories, in a naming context, the last item is an object reference name, and the preceding items are naming contexts.

naming service
A CORBA service that allows CORBA objects to be named by means of binding a name to an object reference. The name binding may be stored in the naming service, and a client may supply the name to obtain the desired object reference. The two options for Naming Services shipped with this version of Java SE are orbd, which is a daemon process containing a Bootstrap Service, a Transient Naming Service, a Persistent Naming Service, and a Server Manager, and tnameserv, a transient naming service.

object
A computational grouping of operations and data into a modular unit. An object is defined by the interface it presents to others, its behavior when operations on its interface are invoked, and its state.

object adapter
The ORB component which provides object reference, activation, and state related services to an object implementation. There may be different adapters provided for different kinds of implementations. The POA is a particular type of object adapter specified by OMG that can be used with multiple ORB implementations with a minimum of rewriting needed to deal with different vendors' implementations.

object id
An object id is a value that is used by the POA and by the user-supplied implementation to identify a particular abstract CORBA object. Object Id values may be assigned and managed by the POA, or they may be assigned and managed by the implementation. Object Id values are hidden from clients, encapsulated by references. Object Ids have no standard form; they are managed by the POA as uninterpreted octet sequences.

object implementation
See implementation.

Object Management Group (OMG)
An international organization with over 700 members that establishes industry guidelines and object management specifications in order to provide a common framework for object-oriented application development. Its members include platform vendors, object-oriented database vendors, software tool developers, corporate developers, and software application vendors. The OMG Common Object Request Broker Architecture specifies the CORBA object model. See www.omg.org for more information.

object reference
A construct containing the information needed to specify an object within an ORB. An object reference is used in method invocations to locate a CORBA object. Object references are the CORBA object equivalent to programming language-specific object pointers. They may be obtained from a factory object or from the Naming Service. An object reference, which is opaque (its internal structure is irrelevant to application developers), identifies the same CORBA object each time it is used. It is possible, however, for multiple object references to refer to the same CORBA object.

Object Request Broker (ORB)
The libraries, processes, and other infrastructure in a distributed environment that enable CORBA objects to communicate with each other. The ORB connects objects requesting services to the objects providing them.

operation (IDL)
The construct in an IDL interface that maps to a Java programming language method. For example, an interface ball might support the operation bounce. Operations may take parameters, return a result, or raise exceptions. IDL operations can be oneway, in which case they cannot return results (return values or out arguments) or raise exceptions.

operations interface
A non abstract IDL interface is mapped to two public Java interfaces: a signature interface and an operations interface. The operations interface has the same name as the IDL interface with the suffix Operations appended to the end and is used in the server-side mapping and as a mechanism for providing optimized calls for collocated clients and servers.

ORBD (Object Request Broker Daemon)
The orbd tool is a daemon process containing a Bootstrap Service, a Transient Naming Service, a Persistent Naming Service, and a Server Manager.

parameter (IDL)
One or more objects the client passes to an IDL operation when it invokes the operation. Parameters may be declared as "in" (passed from client to server), "out" (passed from server to client), or "inout" (passed from client to server and then back from server to client).

persistent object
An object that can survive the process or thread that created it. A persistent object exists until it is explicitly deleted.

PIDL (Pseudo-IDL)
The interface definition language for describing a CORBA pseudo-object. Each language mapping, including the mapping from IDL to the Java programming language, describes how pseudo objects are mapped to language-specific constructs. PIDL mappings may or may not follow the rules that apply to mapping regular CORBA objects.

POA (Portable Object Adapter)
An object adapter is the mechanism that connects a request using an object reference with the proper code to service that request. The POA is a particular type of object adapter specified by OMG that can be used with multiple ORB implementations with a minimum of rewriting needed to deal with different vendors' implementations.

The POA is also intended to allow persistent objects -- at least, from the client's perspective. That is, as far as the client is concerned, these objects are always alive, and maintain data values stored in them, even though physically, the server may have been restarted many times, or the implementation may be provided by many different object implementations.

POA Manager
A POA manager is an object that encapsulates the processing state of one or more POAs. Using operations on a POA manager, the developer can cause requests for the associated POAs to be queued or discarded. The developer can also use the POA manager to deactivate the POAs.

policy
A policy is an object associated with a POA by an application in order to specify a characteristic shared by the objects implemented in that POA. This specification defines policies controlling the POA's threading model as well as a variety of other options related to the management of objects. Other specifications may define other policies that affect how an ORB processes requests on objects implemented in the POA.

Portable Interceptors
Portable Interceptors are hooks into the ORB through which ORB services can intercept the normal flow of execution of the ORB. For more information, see PortableInterceptor Package.

pragma
In J2SE v.1.2, a directive to the idltojava compiler to perform certain operations while compiling an IDL file. For example, the pragma "javaPackage" directs the idltojava compiler to put the Java programming language interfaces and classes it generates from the IDL interface into the Java programming language package specified. In J2SE v.1.3 and higher, this functionality is supported via the -pkgPrefix command line option to idlj.

pseudo-object
An object similar to a CORBA object in that it is described in IDL, but unlike a CORBA object, it cannot be passed around using its object reference, nor can it be narrowed or stringified. Examples of pseudo-objects include the Interface Repository and DII which, although implemented as libraries, are more clearly described in OMG specifications as pseudo-objects with IDL interfaces. The IDL for pseudo-objects is called "PIDL" to indicate that a pseudo-object is being defined.

RMI-IIOP
Java RMI-IIOP is an Object Request Broker and a compiler, rmic -iiop, that generates IIOP stub and tie classes. With RMI-IIOP, developers can write remote interfaces in the Java programming language and implement them simply using Java technology and the Java RMI APIs. These interfaces can be implemented in any other language that is supported by an OMG mapping and a vendor supplied ORB for that language. Similarly, clients can be written in other languages using IDL derived from the remote Java technology-based interfaces. Using RMI-IIOP, objects can be passed both by reference and by value over IIOP.

servant
A servant is a programming language object or entity that implements requests on one or more objects. Servants generally exist within the context of a server process. Requests made on an object's references are mediated by the ORB and transformed into invocations on a particular servant. In the course of an object's lifetime it may be associated with (that is, requests on its references will be targeted at) multiple servants.

servant manager
A servant manager is an object that the application developer can associate with a POA. The ORB will invoke operations on servant managers to activate servants on demand, and to deactivate servants. Servant managers are responsible for managing the association of an object (as characterized by its Object Id value) with a particular servant, and for determining whether an object exists or not. There are two kinds of servant managers, called ServantActivator and ServantLocator; the type used in a particular situation depends on policies in the POA.

servant object
An instance of an object implementation for an IDL interface. The servant object is registered with the ORB so that the ORB knows where to send invocations. It is the servant that performs the services requested when a CORBA object's method is invoked.

server
A program that contains the implementations of one or more IDL interfaces. For example, a desktop publishing server might implement a Document object type, a ParagraphTag object type, and other related object types. The server is required to register each implementation (servant object) with the ORB so that the ORB knows about the servant. Servers are sometimes referred to as object servers.

server skeleton
A public abstract class generated by the idlj compiler that provides the ORB with information it needs in dispatching method invocations to the servant object(s). A server skeleton, like a client stub, is specific to the IDL interface from which it is generated. A server skeleton is the server side analog to a client stub, and these two classes are used by ORBs in static invocation.

servertool
The Java IDL Server Tool, servertool provides the ease-of-use interface for the application programmers to register, unregister, startup, and shutdown a server.

service tier
The portion of a distributed application that contains the business logic and performs most of the computation. The service tier is typically located on a shared machine for optimum resource use.

signature interface
A non-abstract IDL interface is mapped to two public Java interfaces: a signature interface and an operations interface. The signature interface, which extends IDLEntity, has the same name as the IDL interface name and is used as the signature type in method declarations when interfaces of the specified type are used in other interfaces.

skeleton
The object-interface-specific ORB component which assists an object adapter in passing requests to particular methods.

static invocation
See invocation.

stringified object reference
An object reference that has been converted to a string so that it may be stored on disk in a text file (or stored in some other manner). Such strings should be treated as opaque because they are ORB-implementation independent. Standard object_to_string and string_to_object methods on org.omg.CORBA.Object make stringified references available to all CORBA Objects.

stub
A local procedure corresponding to a single operation that invokes that operation when called.

tnameserv
The CORBA COS (Common Object Services) Naming Service provides a tree-like directory for object references much like a filesystem provides a directory structure for files. The Transient Naming Service provided with Java IDL, tnameserv, is a simple implementation of the COS Naming Service specification. Object references are stored in the namespace by name and each object reference-name pair is called a name binding. Name bindings may be organized under naming contexts. Naming contexts are themselves name bindings and serve the same organizational function as a file system subdirectory. All bindings are stored under the initial naming context. The initial naming context is the only persistent binding in the namespace; the rest of the namespace is lost if the transient naming service process halts and restarts.

transient object
An object whose existence is limited by the lifetime of the process or thread that created it.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL: The "Hello World" Example With The ImplBase Server-Side Model

This document is a high-level overview of how to create a complete CORBA (Common Object Request Broker Architecture) application using IDL (Interface Definiton Language) to define interfaces and the Java IDL compiler to generate stubs and skeletons. This document describes using the ImplBase Inheritance Server-Side Model.

The idlj compiler now generates server-side mappings based on the POA Inheritance Model as the default. For compatibility with existing applications, a new flag has been added to the idlj compiler to allow it to generate server-side mappings based on the ImplBase Inheritance Model, -oldImplBase. Existing applications that need to talk to servers created in J2SE 1.3 or prior may need to update their MAKEFILE so that this flag is used, however, new applications that have no such requirements should not generate these deprecated mappings.

NOTE: ImplBase is deprecated in favor of the POA model, but is provided to allow compatibility with servers written in J2SE 1.3 and prior. We do not recommend creating new servers using this nonstandard model.

This document contains:

  • The IDL for a simple "Hello World" program
  • A server that creates an object and publishes it with a naming service using the ImplBase server-side implementation
  • An application client that knows the object's name, retrieves a reference for it from the naming service, and invokes the object
  • Instructions for compiling and running the example

Defining the Interface (Hello.idl)

The first step to creating a CORBA application is to specify all of your objects and their interfaces using the OMG's Interface Definition Language (IDL). IDL has a syntax similar to C++ and can be used to define modules, interfaces, data structures, and more. The IDL can be mapped to a variety of programming languages. The IDL mapping for Java is summarized in IDL to Java Language Mapping Summary.

The following code is written in the OMG IDL, and describes a CORBA object whose sayHello() operation returns a string and whose shutdown() operation shuts down the ORB. To learn more about OMG IDL Syntax and Semantics, link to the OMG Web site, and read Chapter 3 of the CORBA Specification.

Hello.idl

module HelloApp
{
  interface Hello
  {
  string sayHello();
  oneway void shutdown();
  };
};
NOTE: When writing code in OMG IDL, do not use an interface name as the name of a module. Doing so runs the risk of getting inconsistent results when compiling with tools from different vendors, thereby jeopardizing the code's portability. For example, code containing the same names could be compiled with the IDL to Java compiler from Sun Microsystems and get one result. The same code compiled with another vendor's IDL to Java compiler could produce a different result.

To complete the application, you simply provide the server (HelloServer.java) and client (HelloClient.java) implementations.

Implementing the Server (HelloServer.java)

The example server consists of two classes, the servant and the server. The servant, HelloImpl, is the implementation of the Hello IDL interface; each Hello instance is implemented by a HelloImpl instance. The servant is a subclass of _HelloImplBase, which is generated by the idlj compiler from the example IDL. The servant contains one method for each IDL operation, in this example, the sayHello() and shutdown() methods. Servant methods are just like ordinary Java methods; the extra code to deal with the ORB, with marshaling arguments and results, and so on, is provided by the skeleton.

The HelloServer class has the server's main() method, which:

  • Creates and initializes an ORB instance
  • Creates a servant instance (the implementation of one CORBA Hello object) and tells the ORB about it
  • Gets a CORBA object reference for a naming context in which to register the new CORBA object
  • Gets the root naming context
  • Registers the new object in the naming context under the name "Hello"
  • Waits for invocations of the new object from the client

NOTE: ImplBase is deprecated in favor of the POA model, but is provided to allow compatibility with servers written in J2SE 1.3 and prior. We do not recommend creating new servers using this nonstandard model.

The HelloServer for the ImplBase server-side implementation differs only slightly from its POA counterpart. The sections of the POA-based server that get a reference to the root POA and activate the POAManager are not necessary for this implementation, which follows:

HelloServer.java

// Copyright and License
import HelloApp.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;

import java.util.Properties;

class HelloImpl extends _HelloImplBase{

  private ORB orb;

  public void setORB(ORB orb_val){
    orb = orb_val;
  }

  public String sayHello(){
    return "\nHello world !!\n";
  }

  public void shutdown(){
    orb.shutdown(false);
  }
}

public class HelloServer {

  public static void main(String args[]) {
    try{
      // create and initialize the ORB
      ORB orb = ORB.init(args, null);

      // create servant and register it with the ORB
      HelloImpl helloImpl = new HelloImpl();
      helloImpl.setORB(orb);

      // get the root naming context
      org.omg.CORBA.Object objRef =
          orb.resolve_initial_references("NameService");
      NamingContext ncRef = NamingContextHelper.narrow(objRef);

      Hello href = HelloHelper.narrow(helloImpl);

      // bind the Object Reference in Naming
      NameComponent nc = new NameComponent("Hello", "");
      NameComponent path[] = {nc};
      ncRef.rebind(path, href);

      System.out.println("HelloServer ready and waiting ...");

      // wait for invocations from clients
      orb.run();
    }

    catch (Exception e) {
      System.err.println("ERROR: " + e);
      e.printStackTrace(System.out);
    }

    System.out.println("HelloServer Exiting ...");

  }
}

Implementing the Client Application (HelloClient.java)

The example application client that follows is similar to the one presented in the default tutorial, however, the new Interoperable Naming Service features are not used in this example to preserve backward compatibility. The example client application:

  • Creates and initiliazes an ORB
  • Obtains a reference to the naming context
  • Looks up "Hello" in the naming context and receives a reference to that CORBA object
  • Invokes the object's sayHello() and shutdown() operations and prints the result

HelloClient.java

// Copyright and License

import HelloApp.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;

public class HelloClient{

  static Hello helloImpl;

  public static void main(String args[]){

    try{
      // create and initialize the ORB
      ORB orb = ORB.init(args, null);

      // get the root naming context
      org.omg.CORBA.Object objRef =
          orb.resolve_initial_references("NameService");
      NamingContext ncRef = NamingContextHelper.narrow(objRef);

      // resolve the Object Reference in Naming
      NameComponent nc = new NameComponent("Hello", "");
      NameComponent path[] = {nc};
      Hello helloImpl = HelloHelper.narrow(ncRef.resolve(path));

      System.out.println("Obtained a handle on server object: " + helloImpl);
      System.out.println(helloImpl.sayHello());
      helloImpl.shutdown();
      }

    catch (Exception e) {
      System.out.println("ERROR : " + e) ;
      e.printStackTrace(System.out);
    }
  }
}

Building and Running Hello World

Despite its simple design, the Hello World program lets you learn and experiment with all the tasks required to develop almost any CORBA program that uses static invocation.

This example requires a naming service, which is a CORBA service that allows CORBA objects to be named by means of binding a name to an object reference. The name binding may be stored in the naming service, and a client may supply the name to obtain the desired object reference. The two options for Naming Services shipped with this version of Java SE are tnameserv, a transient naming service, and orbd, which is a daemon process containing a Bootstrap Service, a Transient Naming Service, a Persistent Naming Service, and a Server Manager. This example uses orbd.

When running this example, remember that, when using Solaris software, you must become root to start a process on a port under 1024. For this reason, we recommend that you use a port number greater than or equal to 1024. The -ORBInitialPort option is used to override the default port number in this example. The following instructions assume you can use port 1050 for the Java IDL Object Request Broker Daemon, orbd. You can substitute a different port if necessary. When running these examples on a Windows machine, subtitute a backslash (\) in path names.

To run this client-server application on your development machine:

  1. Create the program files or download and unzip HelloImplBase.zip.
  2. Change to the directory that contains the file Hello.idl.
  3. Run the IDL-to-Java compiler, idlj, on the IDL file to create stubs and skeletons. This step assumes that you have included the path to the java/bin directory in your path.

    NOTE: ImplBase is deprecated in favor of the POA model, but is provided to allow compatibility with servers written in J2SE 1.3 and prior. We do not recommend creating new servers using this nonstandard model.

      idlj -fall -oldImplBase Hello.idl

    You must use the -fall option with the idlj compiler to generate both client and server-side bindings. This command line will generate the default server-side bindings, which assumes the POA programming model. The -oldImplBase option tells the compiler to generate the ImplBase Inheritance Model server-side bindings, instead of the default POA Inheritance Model server-side bindings. For more information on the idlj options, link to IDL-to-Java compiler options.

    The idlj compiler generates a number of files. The actual number of files generated depends on the options selected when the IDL file is compiled. The generated files provide standard functionality, so you can ignore them until it is time to deploy and run your program. The files generated by the idlj compiler for Hello.idl, with the -fall command line option, are:

    • _HelloImplBase.java

      This abstract class is the server skeleton, providing basic CORBA functionality for the server. It implements the InvokeHandler and the Hello interface. It inherits from org.omg.CORBA.portable.ObjectImpl. The server class HelloImpl inherits from _HelloImplBase.

    • _HelloStub.java

      This class is the client stub, providing CORBA functionality for the client. It inherits from org.omg.CORBA.portable.ObjectImpl and implements the Hello interface.

    • Hello.java

      This interface contains the Java version of our IDL interface. The Hello.java interface inherits from org.omg.CORBA.Object, providing standard CORBA object functionality. It also inherits from HelloOperations and org.omg.CORBA.portable.IDLEntity.

    • HelloHelper.java

      This class provides auxiliary functionality, notably the narrow() method required to cast CORBA object references to their proper types.The Helper class is responsible for reading and writing the data type to CORBA streams, and inserting and extracting the data type from Anys. The Holder class delegates to the methods in the Helper class for reading and writing.

    • HelloHolder.java

      This final class holds a public instance member of type Hello. Whenever the IDL type is an out or an inout parameter, the Holder class is used. It provides operations for org.omg.CORBA.portable.OutputStream and org.omg.CORBA.portable.InputStream arguments, which CORBA allows, but which do not map easily to Java's semantics. The Holder class delegates to the methods in the Helper class for reading and writing. It implements org.omg.CORBA.portable.Streamable.

    • HelloOperations.java

      This interface contains the methods sayHello() and shutdown(). The IDL-to-Java mapping puts all of the operations defined on the IDL interface into this file, which is shared by both the stubs and skeletons.

  4. Compile the .java files, including the stubs and skeletons (which are in the directory HelloApp). This step assumes the java/bin directory is included in your path.
       javac *.java HelloApp/*.java
  5. Start orbd.

    To start orbd from a UNIX command shell, enter:

      orbd -ORBInitialPort 1050 -ORBInitialHost localhost&

    From an MS-DOS system prompt (Windows), enter:

      start orbd -ORBInitialPort 1050 -ORBInitialHost localhost

    Note that 1050 is the port on which you want the name server to run. -ORBInitialPort is a required command-line argument. Note that when using Solaris software, you must become root to start a process on a port under 1024. For this reason, we recommend that you use a port number greater than or equal to 1024.

    -ORBInitialHost is an optional command-line argument. For this example, since both client and server on running on the development machine, we have set the host to localhost. When developing on more than one machine, you will replace this with the name of the host. For an example of how to run this program on two machines, see Running the Hello World Program on 2 machines.

  6. Start the Hello server:

    To start the Hello server from a UNIX command shell, enter:

      java HelloServer -ORBInitialPort 1050 -ORBInitialHost localhost&

    From an MS-DOS system prompt (Windows), enter:

      start java HelloServer -ORBInitialPort 1050 -ORBInitialHost localhost

    For this example, you can omit -ORBInitialHost localhost since the name server is running on the same host as the Hello server. If the name server is running on a different host, use -ORBInitialHost nameserverhost to specify the host on which the IDL name server is running.

    Specify the name server (orbd) port as done in the previous step, for example, -ORBInitialPort 1050.

    When the server is running, it will echo the following message back to the terminal:

    HelloServer ready and waiting ...
  7. Run the client application:
      java HelloClient -ORBInitialPort 1050 -ORBInitialHost localhost

    For this example, you can omit -ORBInitialHost localhost since the name server is running on the same host as the Hello client. If the name server is running on a different host, use -ORBInitialHost nameserverhost to specify the host on which the IDL name server is running.

    Specify the name server (orbd) port as done in the previous step, for example, -ORBInitialPort 1050.

    When the client is running, the following message will echo to the terminal:

       Obtained a handle on server object: IOR: ...
   Hello World !!
   HelloServer Exiting ...

When you have finished this tutorial, be sure to shut down or kill the name server (orbd). To do this from a DOS prompt, select the window that is running the server and enter Ctrl+C to shut it down. To do this from a Unix shell, find the process, and kill it. The server will continue to wait for invocations until it is explicitly stopped.

Running the Hello World Application on Two Machines describes one way of distributing the simple application across two machines - a client and a server.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL: Initialization

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Initialization

This document was not updated for this release.

Before a Java program can use CORBA objects, it must initialize itself as follows:

  • Create an ORB object.
  • Obtain one or more initial object references, typically at least a naming context.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL: Mapping IDL to Java

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java IDL: IDL to Java Language Mapping

This release of the Java™ 2 Platform Standard Edition 5.0, includes idlj, a compiler that reads an Object Management Group (OMG) Interface Definition Language (IDL) file and translates it, or maps it, to a Java interface. Depending on the command-line options used, the idlj compiler creates stub, skeleton, helper, holder, and other files as necessary. These .java files are generated from the IDL file according to the mapping specified in the OMG document (pdf format) OMG IDL to Java Language Mapping Specification, ptc, 00-01-08, with the revisions indicated in ptc/00-11-03, The new IDL to Java Mapping Chapter. Version 00-01-08 of the IDL to Java language mapping is aligned with CORBA version 2.3.2. For a basic summary of the IDL to Java mapping, see IDL to Java Language Mapping Overview below.

  • The CORBA technology shipped in J2SE 5.0 conforms to the mappings specified by the following document: Official Specifications for CORBA support in J2SE 5.0.

Some topics from the OMG IDL to Java Language Mapping specification that are not easily summarized are:

  • Section 1.13, Mapping for Value Type
  • Section 1.14, Value Box Types
  • Section 1.20, Server-Side Mapping
  • Section 1.21, Java ORB Portability Interfaces

IDL to Java Language Mapping Overview

CORBA objects are defined in OMG IDL (Object Management Group Interface Definition Language). The syntax and semantics of OMG IDL are defined in Chapter 3 of the CORBA/IIOP 2.3.1 Specification. The IDL-to-Java compiler, idlj, maps the IDL-defined interfaces to Java classes and interfaces as defined in OMG IDL to Java Language Mapping Specification, ptc, 00-01-08, and as supported in this version of the Java platform, as described in Official Specifications for CORBA support in J2SE 5.0.

This overview shows the correspondence between OMG IDL types and Java types. Note that OMG IDL, as its name implies, defines interfaces. Like Java interfaces, IDL interfaces contain no implementations for their operations (methods in Java). In other words, IDL interfaces define only the signature for an operation (the name of the operation, the data type of its return value, the data types of the parameters that it takes, and any exceptions that it raises). The implementations for these operations need to be supplied in Java classes written by a Java programmer.

The following table lists the main constructs of IDL and the corresponding constructs in Java.

IDL Type | Java Type
module | package
boolean | boolean
char, wchar | char
octet | byte
string, wstring | java.lang.String
short, unsigned short | short
long, unsigned long | int
long long, unsigned long long | long
float | float
double | double
fixed | java.math.BigDecimal
enum, struct, union | class
sequence, array | array
interface (non-abstract) | signature interface and an operations interface, helper class, holder class
interface (abstract) | signature interface, helper class, holder class
constant (not within an interface) | public interface
constant (within an interface) | fields in the Java signature interface for non-abstract, or the sole Java interface for abstract
exception | class
Any | org.omg.CORBA.Any
type declarations nested within interfaces | "scoped" package
typedef | helper classes
pseudo objects | pseudo interface
readonly attribute | accessor method
readwrite attribute | accessor and modifer methods
operation | method
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL and RMI-IIOP: Naming Services

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Naming Service

Topics in this section include:

  • COS Naming Service: an Overview
  • Using the Naming Service

COS Naming Service: an Overview

The CORBA COS (Common Object Services) Naming Service provides a tree-like directory for object references much like a filesystem provides a directory structure for files. The Naming Service provided with Java IDL is an implementation of the COS Naming Service specification. The following overview is taken from that document.

A name-to-object association is called a name binding. A name binding is always defined relative to a naming context. A naming context is an object that contains a set of name bindings in which each name is unique. Different names can be bound to an object in the same or different contexts at the same time.

To resolve a name is to determine the object associated with the name in a given context. To bind a name is to create a name binding in a given context. A name is always resolved relative to a context - there are no absolute names.

Because a context is like any other object, it can also be bound to a name in a naming context. Binding contexts in other contexts creates a naming graph - a directed graph with nodes and labeled edges where the nodes are contexts. A naming graph allows more complex names to reference an object. Given a context in a naming graph, a sequence of names can reference an object. This sequence of names (called a compound name) defines a path in the naming graph to navigate the resolution process.

The following figure shows an example of a naming graph. A sample program that illustrates how to add names to the namespace uses this same model.

Example of naming graph

For an application to use the COS Naming Service, its ORB must know the port of a host running a naming service or have access to a stringified initial naming context for that naming service. The naming service can either be the Java IDL naming service or another COS-compliant naming service.

Prior to running a client or a server, you will start ORBD. ORBD includes a persistent Naming Service and a transient Naming Service, both of which are an implementation of the COS Naming Service.

  • The Persistent Naming Service provides persistence for naming contexts. This means that this information is persistent across service shutdowns and startups, and is recoverable in the event of a service failure. If ORBD is restarted, the Persistent Naming Service will restore the naming context graph, so that the binding of all clients' and servers' names remains intact (persistent).
  • For backward compatibility, tnameserv, a Transient Naming Service shipped with older versions of the JDK, is also included in this release of J2SE. A transient naming service retains naming contexts as long as it is running. If there is a service interruption, the naming context graph is lost.

Both client and server should agree on which root naming context to use. The orb.resolve_initial_references(String name_of_service) method is used to obtain the root naming context. If you get a handle on a Naming Service by providing "NameService" as the name_of_service, you will get a persistent naming service, meaning that the naming context graph will be restored after a service failure. If you get the handle using "TNameService", you will get a transient naming service, meaning that you will need to re-obtain the root naming context using orb.resolve_initial_references(String name_of_service) if there is a service interruption.

For example,

      // get the root naming context
      org.omg.CORBA.Object objRef =
          orb.resolve_initial_references("NameService");
      NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

The string "NameService" is defined for all CORBA ORBs. When you pass in this string, the ORB returns a naming context object that is an object reference for:

  • The persistent name service if you are using the Naming Service that is part of ORBD.
  • The transient name service if you are using tnameserv.

To specify that you want to use the transient naming service with ORBD, pass in the string "TNameService". The string "TNameService" is a proprietary name. When you pass in this string, the ORB returns a naming context object that is an object reference for ORBD's transient name service.

As with all CORBA object references, objRef is a generic CORBA object. To use it as a NamingContextExt object, you must narrow it to its proper type.

NamingContextExtHelper is an idlj-generated helper class, similar in function to HelloHelper. The ncRef object is now an org.omg.CosNaming.NamingContextExt and you can use it to access the naming service and register the server.

NamingContextExt and NamingContextExtHelper are new to this release of J2SE. NamingContextExt is the extension of NamingContext. It contains a set of name bindings in which each name is unique and is part of the Interoperable Naming Service. Different names can be bound to an object in the same or different contexts at the same time. Using NamingContextExt, you can use URL-based names to bind and resolve. NamingContextExtHelper provides additional helper methods like narrow() that are type-specific but don't deal with business logic.

Interoperable Naming Service

The Interoperable Naming Service (INS) is a URL-based naming system on top of the CORBA Naming Service, as well as a common bootstrap mechanism that lets applications share a common initial naming context.

The Interoperable Naming Service (INS) provides the following features:

  • Capability to resolve using stringified names (e.g., a/b.c/d)
  • URLs for CORBA object references (corbaloc: and corbaname: formats)
  • Standard APIs in NamingContextExt for converting between CosNames, URLs, and Strings
  • ORB arguments for bootstrapping (ORBInitRef and ORBDefaultInitRef)

An example application that demonstrates how to use the INS can be found at Interoperable Naming Service Example.

The following diagram shows how INS fits into ORBD:

ORBD

An object reference contains at least three pieces of information: an address, the name of the POA that created an object reference, and an Object ID.

Using INS, you can provide a URL to access the CORBA object, which is more readable than a stringified IOR. The following stringified object reference formats are allowed:

  • Interoperable Object References (IOR)

    An IOR is an object reference that is understood by ORBs that can interoperate using the OMG-defined protocols GIOP and IIOP. A client can obtain an object reference using orb.object_to_string(objRef), as shown in the Browsing the Namespace example, or as a result of an invocation on another object reference.

    Note: If an IOR contains multiple profiles, the J2SE v.1.4 and higher ORB always uses the first one.

  • Human-Readable URL Formats for CORBA Object References
    • corbaloc:

      The corbaloc: format is useful for CORBA client programs, and is typically used to resolve the reference using the GIOP LocateRequest or Request message. For example, a corbaloc: object reference might look like this:

              corbaloc:iiop:1.2@MyBank.com:2050/TraderService

      This example show how to get an object reference for TraderService from host myBank.com on port 2050.

    • corbaname:

      The corbaname: format provides a mechanism for a client to bootstrap directly, and is typically used to resolve the stringified name from the root naming context. For example, a corbaname: object reference might look like this:

              corbaname::myBank.com:2050#Personal/schedule

      where myBank.com is the host, 2050 is the port. The portion of the reference up to the hash mark (corbaname::myBank.com:2050 ) is the URL that returns the root naming context. This example provides the URL to use to: a) locate the Naming Service, and, b) resolve the name Personal/schedule from the Naming Service.

Bootstrap Options for the ORB

INS provides ORB options for bootstrapping. To bootstrap a CORBA system, you must give it an object reference. The ORB can be configured to return the handle of a customized CORBA service from resolve_initial_references() using either ORBInitRef and/or ORBDefaultInitRef. For example,

-ORBInitRef TraderService=corbaloc::myBank.com:2050/TraderService
-ORBDefaultInitRef corbaloc:iiop:1.2:myBank.com:2050

The order of resolution when these options are used is as follows:

  1. Objects registered with register_initial_references
  2. -ORBInitRef
  3. -ORBDefaultInitRef
  4. Proprietary Bootstrap (Sun ORBs only)

For more information about INS, refer to the INS Naming Specification.

Using the Naming Service

To use the Naming Service, you must first write the server and client code that finds and/or creates the namespace and/or the objects in the namespace. Before running the client and server, you must start the Naming Service and tell the client and server where to find it. The following steps loosely suggest what happens when the client and server attempt to access the Naming Service:

  • The server invokes the bind or rebind method to associate a logical name with an object reference.
  • The Naming Service adds this object reference/name binding to its namespace database.
  • A client application invokes the resolve method to obtain an object reference with this name.
  • The client uses an object reference to invoke methods on the target object.

The following topics are covered in this section:

  • Sample Client: Adding Objects to the Namespace
  • Sample Client: Resolving Objects from the Namespace
  • Sample Client: Browsing the Namespace
  • Starting the Naming Service
  • Stopping the Naming Service

Sample Client: Adding Objects to the Namespace

The following sample program illustrates how to add names to the namespace. It is a self-contained Naming Service client that creates the following simple tree. Naming contexts are in italics and object references are in normal font.

adding names to the namespace

In this example, plans is an object reference and Personal is a naming context that contains two object references: calendar and schedule.

  1. Create the NameClient.java file and import the proper libraries:
    import java.util.Properties;
import org.omg.CORBA.*;
import org.omg.CosNaming.*;

public class NameClient
{
   public static void main(String args[])
   {
      try {
  2. Set Port and Host properties.

    In the section, Starting the Naming Service, the name server is started on port 1050 and host localhost. The following code ensures that the client program is aware of this port number and host name.

            Properties props = new Properties();
        props.put("org.omg.CORBA.ORBInitialPort", "1050");
        props.put("org.omg.CORBA.ORBInitialHost", "localhost");
        ORB orb = ORB.init(args, props);
  3. Obtain the initial naming context.

    The following code obtains the initial naming context and assigns it to ctx. The second line copies ctx into a dummy object reference objref that we'll attach to various names and add into the namespace.

        NamingContextExt ctx =
          NamingContextExtHelper.narrow(orb.resolve_initial_references(
            "NameService"));
        org.omg.CORBA.Object objref = ctx;
  4. Bind the name "plans" to the object reference.

    This code binds the name "plans" to our dummy object reference. The object reference, "plans", is then added under the initial naming context using rebind. The rebind method allows us to run this program over and over again without getting the exceptions we'd get from using bind.

            NameComponent name1[] = ctx.to_name("plans");
        ctx.rebind(name1, objref);
        System.out.println("plans rebind successful!");
  5. Create a new naming context named "Personal".

    This code creates a new naming context called "Personal". The resulting object reference, ctx2, is bound to the name and added under the initial naming context.

            NameComponent name2[] = ctx.to_name("Personal");
        NamingContextExt ctx2 = (NamingContextExt)ctx.bind_new_context(name2);
        System.out.println("New naming context, Personal, added!");
  6. Bind "schedule" and "calendar" to a dummy object reference. To bind a name is to create a name binding in a given context. A name is always resolved relative to a context - there are no absolute names.

    This code binds the dummy object reference using the names "schedule" and "calendar" under the "Personal" naming context (ctx2).

            NameComponent name3[] = ctx.to_name("schedule");
        ctx2.rebind(name3, objref);
        System.out.println("schedule rebind successful!");

        NameComponent name4[] = ctx.to_name("calendar");
        ctx2.rebind(name4, objref);
        System.out.println("calendar rebind successful!");

    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
  }
}
  7. Save NameClient.java, and compile the file as follows:
         javac NameClient.java

    Correct any syntax errors before proceeding.

  8. Run the Object Request Broker Daemon as shown in Starting the Naming Service.
  9. Run NameClient, as follows:
         java NameClient -ORBInitialPort 1050

The output in the terminal window looks like this:

output in the terminal window

We now have a namespace that to the Naming Service looks like the above diagram.

Sample Client: Resolving Objects from the Namespace

The following sample program illustrates how to resolve names from the namespace. To resolve a name is to determine the object associated with the name in a given context. When using the persistent Naming Service, you do not need to re-resolve if the Naming Service goes down. If you use a transient Naming Service, you do need to re-resolve in the Naming Service goes down.

In this example, plans is an object reference and Personal is a naming context that contains two object references: calendar and schedule.

  1. Create the NameClientResolve.java file and import the proper libraries:
    import java.util.Properties;
import org.omg.CORBA.*;
import org.omg.CosNaming.*;

public class NameClientResolve
{
   public static void main(String args[])
   {
      try {
  2. Set Port and Host properties.

    In the section, Starting the Naming Service, the name server is started on port 1050 and host localhost. The following code ensures that the client program is aware of this port number and host name.

            Properties props = new Properties();
        props.put("org.omg.CORBA.ORBInitialPort", "1050");
        props.put("org.omg.CORBA.ORBInitialHost", "localhost");
        ORB orb = ORB.init(args, props);
  3. Obtain the initial naming context.

    The following code obtains the initial naming context and assigns it to nc.

        NamingContextExt nc =
          NamingContextExtHelper.narrow(orb.resolve_initial_references(
            "NameService"));
  4. Resolve each namespace.

    The following code resolves each namespace.

       org.omg.CORBA.Object sched = nc.resolve_str("Personal/schedule");
        org.omg.CORBA.Object cal = nc.resolve_str("Personal/calendar");
        org.omg.CORBA.Object plan = nc.resolve_str("plans");

      //finish the try-catch block
      } catch (Exception e) {
        e.printStackTrace(System.err);
        }
}
  5. Save NameClientResolve.java, and compile the file as follows:
         javac NameClientResolve.java

    Correct any syntax errors before proceeding.

  6. Make sure the Object Request Broker Daemon is running and the client application illustrated in Sample Client: Adding Objects to the Namespace has been run.
  7. Run NameClientResolve, as follows:
         java NameClientResolve -ORBInitialPort 1050

There is no output to the terminal window when you run this client application. If you want verification that the object references have been resolved, you could add code such as the following for testing purposes:

        if (sched == null){
          System.out.println("Schedule is null");
        }

        if (cal == null){
          System.out.println("Calendar is null");
        }

        if (plan == null){
          System.out.println("Plans is null");
        }

Sample Client: Browsing the Namespace

The following sample program illustrates how to browse the namespace.

  1. Create the NameClientList.java file and import the proper libraries:
    import java.util.Properties;
import org.omg.CORBA.*;
import org.omg.CosNaming.*;

public class NameClientList
{
   public static void main(String args[])
   {
      try {

  2. In the section, Starting the Naming Service, the nameserver is started on port 1050 and host localhost. The following code ensures that the client program is aware of this port number and host name.

        Properties props = new Properties();
        props.put("org.omg.CORBA.ORBInitialPort", "1050");
        props.put("org.omg.CORBA.ORBInitialHost", "localhost");
        ORB orb = ORB.init(args, props);
  3. Obtain the initial naming context.
            NamingContextExt nc =
          NamingContextExtHelper.narrow(orb.resolve_initial_references(
            "NameService"));
  4. List all bindings in the naming context.

    The list method lists the bindings in the naming context. In this case, up to 1000 bindings from the initial naming context will be returned in the BindingListHolder; any remaining bindings are returned in the BindingIteratorHolder.

        BindingListHolder bl = new BindingListHolder();
        BindingIteratorHolder blIt= new BindingIteratorHolder();
        nc.list(1000, bl, blIt);
  5. Get the array of bindings.

    This code gets the array of bindings out of the returned BindingListHolder.

            Binding bindings[] = bl.value;
  6. This code loops through the bindings and prints the names out.
            for (int i=0; i < bindings.length; i++) {

            int lastIx = bindings[i].binding_name.length-1;

            // check to see if this is a naming context
            if (bindings[i].binding_type == BindingType.ncontext) {
              System.out.println( "Context: " +
                bindings[i].binding_name[lastIx].id);
            } else {
                System.out.println("Object: " +
                  bindings[i].binding_name[lastIx].id);
            }
        }

       } catch (Exception e) {
        e.printStackTrace(System.err);
       }
   }
}
  7. Save NameClientList.java, and compile the file as follows:
         javac NameClientList.java

    Correct any syntax errors before proceeding.

  8. Make sure the Object Request Broker Daemon is running, the client application illustrated in Sample Client: Adding Objects to the Namespace has been run, and the client application illustrated in Sample Client: Resolving Objects from the Namespace has been run.
  9. Run NameClientList, as follows:
         java NameClientList -ORBInitialPort 1050

The output in the terminal window looks like this:

output in the terminal window

Starting the Naming Service

In all of the tutorials we use the Object Request Broker Daemon, orbd, which includes both a Persistent and a Transient Naming Service, and is available with every download of J2SE 1.4 and higher.

For a caller (client, peer, or client application) to be able to invoke a method on a remote object, that caller must first obtain a reference to the remote object.

Once a remote object is registered on the server, callers can look up the object by name, obtain a remote object reference, and then remotely invoke methods on the object.

To learn how to start the Naming Service, see the topic Starting the Naming Service in the ORBD documentation.

Stopping the Naming Service

To stop the naming service, use the relevant operating system command, such as kill on Solaris, or Ctrl+C in the DOS window in which orbd is running. Note that names registered with the naming service may disappear when the service is terminated if the naming service is transient. The Java IDL naming service will run until it is explicitly stopped.

Naming Service FAQ

How do I connect to a 3rd-party Naming Service from Sun's ORB?

The recommended way is to use the Inter-Operable Naming Service (INS), if this option is supported by the 3rd-party Naming Service.

To use the Sun ORB with another vendor's Naming Service,

  1. Start the 3rd-party name server on Host <H> and Port. <P>
  2. Pass the following argument to ORB.init():
            -ORBInitRef NameService=corbaloc:iiop:1.2@<H>:<P>/NameService

When you do orb.resolve_initial_references( "NameService" ), you should be able to connect to 3rd-party Name Service. If you are still not able to connect, try these troubleshooting hints:

  • Verify that the 3rd-party Name Service supports INS.
  • Verify that the host and port information is accurate.
  • Verify that the 3rd-party Name Service has been started successfully.
  • Verify that the 3rd-party Name Service supports GIOP 1.2. If not, refer to the Name Server's documentation for the correct the GIOP version, and modify the corbaloc: URL accordingly.
  • Determine if the 3rd-party Name Service has a different object key it uses to contact NameService. If so, refer to the Name Server's documentation.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Sample code

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Sample Code for Hello.idl

This document shows the code generated by the IDL-to-Java compiler in accordance with the IDL to Java Language Mapping Specification (for compliance details refer to the compliance document), as well as sample client and server applications.

For a detailed description of the code listed here, consult the introductory tutorial, Getting Started with Java IDL.

Hello.idl, the interface definition

The following file, Hello.idl, is written in the OMG Interface Definition Language, and describes a CORBA object whose sayHello() operation returns a string and whose shutdown() method shuts down the ORB. OMG IDL is a purely declarative language designed for specifying programming-language-independent operational interfaces for distributed applications. The IDL can be mapped to a variety of programming languages. The IDL mapping for Java is summarized in IDL to Java Language Mapping Summary.

To learn more about OMG IDL Syntax and Semantics, read Chapter 3 of the CORBA Specification.

Hello.idl

module HelloApp
{
  interface Hello
  {
  string sayHello();
  oneway void shutdown();
  };
};

Generated Files

The idlj compiler uses the IDL-to-Java mapping to convert IDL interface definitions to corresponding Java interfaces, classes, and methods, which you can then use to implement your client and server code. The following files are generated when Hello.idl is compiled with the IDL-to-Java compiler, using the following command:

   idlj -fall Hello.idl

Hello.java, the signature interface

The signature interface file, Hello.java extends org.omg.portable.IDLEntity, org.omg.CORBA.Object, and the operations interface, HelloOperations. The signature interface is used as the signature type in method declarations when interfaces of the specified type are used in other interfaces. From the client's point of view, an object reference for a CORBA Hello object implements this interface.

Note: The Stub implements the Hello interface, where it generates code for each method to marshall the arguments, invoke the method, and then unmarshall the arguments.

HelloApp/Hello.java
package HelloApp;

/**
* HelloApp/Hello.java
* Generated by the IDL-to-Java compiler (portable), version "3.0"
* from Hello.idl
* Thursday, March 22, 2001 2:17:15 PM PST
*/

public interface Hello extends HelloOperations, org.omg.CORBA.Object,
org.omg.CORBA.portable.IDLEntity
{
} // interface Hello

HelloOperations.java, the operations interface

The Java operations interface, HelloOperations.java, is used in the server-side mapping and as a mechanism for providing optimized calls for co-located clients and server. The server developer provides implementation for the methods indicated by the operations interface.

This interface contains the methods sayHello() and shutdown(). The IDL-to-Java mapping puts all of the operations defined on the IDL interface into this file, which is shared by both the stubs and skeletons.

Note: The server writer usually extends HelloPOA and provides implementation for the methods provided by the operations interface.

HelloApp/HelloOperations.java
package HelloApp;

/**
* HelloApp/HelloOperations.java
* Generated by the IDL-to-Java compiler (portable), version "3.0"
* from Hello.idl
* Thursday, March 22, 2001 2:17:15 PM PST
*/

public interface HelloOperations
{
  String sayHello ();
  void Shutdown ();
} // interface HelloOperations

HelloHelper.java, the Helper class

The Java class HelloHelper provides auxiliary functionality, notably the narrow() method required to cast CORBA object references to their proper types. The Helper class is responsible for reading and writing the data type to CORBA streams, and inserting and extracting the data type from Anys. The Holder class delegates to the methods in the Helper class for reading and writing.

HelloApp/HelloHelper.java
package HelloApp;

/**
* HelloApp/HelloHelper.java
* Generated by the IDL-to-Java compiler (portable), version "3.0"
* from Hello.idl
* Thursday, March 22, 2001 2:17:15 PM PST
*/

abstract public class HelloHelper
{
  private static String  _id = "IDL:HelloApp/Hello:1.0";

  public static void insert (org.omg.CORBA.Any a, HelloApp.Hello that)
  {
    org.omg.CORBA.portable.OutputStream out = a.create_output_stream ();
    a.type (type ());
    write (out, that);
    a.read_value (out.create_input_stream (), type ());
  }

  public static HelloApp.Hello extract (org.omg.CORBA.Any a)
  {
    return read (a.create_input_stream ());
  }

  private static org.omg.CORBA.TypeCode __typeCode = null;
  synchronized public static org.omg.CORBA.TypeCode type ()
  {
    if (__typeCode == null)
    {
      __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc
(HelloApp.HelloHelper.id (), "Hello");
    }
    return __typeCode;
  }

  public static String id ()
  {
    return _id;
  }

  public static HelloApp.Hello read (org.omg.CORBA.portable.InputStream istream)
  {
    return narrow (istream.read_Object (_HelloStub.class));
  }

  public static void write (org.omg.CORBA.portable.OutputStream ostream,
HelloApp.Hello value)
  {
    ostream.write_Object ((org.omg.CORBA.Object) value);
  }

  public static HelloApp.Hello narrow (org.omg.CORBA.Object obj)
  {
    if (obj == null)
      return null;
    else if (obj instanceof HelloApp.Hello)
      return (HelloApp.Hello)obj;
    else if (!obj._is_a (id ()))
      throw new org.omg.CORBA.BAD_PARAM ();
    else
    {
      org.omg.CORBA.portable.Delegate delegate =
((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate ();
      HelloApp._HelloStub stub = new HelloApp._HelloStub ();
      stub._set_delegate(delegate);
      return stub;
    }
  }

}

HelloHolder.java, the Holder class

The Java class called HelloHolder holds a public instance member of type Hello. Whenever the IDL type is an out or an inout parameter, the Holder class is used. It provides operations for org.omg.CORBA.portable.OutputStream and org.omg.CORBA.portable.InputStream arguments, which CORBA allows, but which do not map easily to Java's semantics. The Holder class delegates to the methods in the Helper class for reading and writing. It implements org.omg.CORBA.portable.Streamable.

HelloApp/HelloHolder.java
package HelloApp;

/**
* HelloApp/HelloHolder.java
* Generated by the IDL-to-Java compiler (portable), version "3.0"
* from Hello.idl
* Thursday, March 22, 2001 2:17:15 PM PST
*/

public final class HelloHolder implements org.omg.CORBA.portable.Streamable
{
  public HelloApp.Hello value = null;

  public HelloHolder ()
  {
  }

  public HelloHolder (HelloApp.Hello initialValue)
  {
    value = initialValue;
  }

  public void _read (org.omg.CORBA.portable.InputStream i)
  {
    value = HelloApp.HelloHelper.read (i);
  }

  public void _write (org.omg.CORBA.portable.OutputStream o)
  {
    HelloApp.HelloHelper.write (o, value);
  }

  public org.omg.CORBA.TypeCode _type ()
  {
    return HelloApp.HelloHelper.type ();
  }

}

_HelloStub.java, the client stub

The Java class _HelloStub is the stub file for the client-side mapping. It extends org.omg.CORBA.portable.ObjectImpl and implements the Hello.java interface.

HelloApp/_HelloStub.java
package HelloApp;

/**
* HelloApp/_HelloStub.java
* Generated by the IDL-to-Java compiler (portable), version "3.0"
* from Hello.idl
* Thursday, March 22, 2001 2:17:15 PM PST
*/

public class _HelloStub extends org.omg.CORBA.portable.ObjectImpl implements
HelloApp.Hello
{

  public String sayHello ()
  {
    org.omg.CORBA.portable.InputStream _in = null;
    try {
       org.omg.CORBA.portable.OutputStream _out = _request ("sayHello", true);
       _in = _invoke (_out);
       String __result = _in.read_string ();
       return __result;
    } catch (org.omg.CORBA.portable.ApplicationException _ex) {
       _in = _ex.getInputStream ();
       String _id = _ex.getId ();
       throw new org.omg.CORBA.MARSHAL (_id);
    } catch (org.omg.CORBA.portable.RemarshalException _rm) {
       return sayHello ();
    } finally {
        _releaseReply (_in);
    }
  } // sayHello

  public void Shutdown ()
  {
    org.omg.CORBA.portable.InputStream _in = null;
    try {
       org.omg.CORBA.portable.OutputStream _out = _request ("Shutdown", false);
       _in = _invoke (_out);
    } catch (org.omg.CORBA.portable.ApplicationException _ex) {
       _in = _ex.getInputStream ();
       String _id = _ex.getId ();
       throw new org.omg.CORBA.MARSHAL (_id);
    } catch (org.omg.CORBA.portable.RemarshalException _rm) {
       Shutdown ();
    } finally {
        _releaseReply (_in);
    }
  } // Shutdown

  // Type-specific CORBA::Object operations
  private static String[] __ids = {
    "IDL:HelloApp/Hello:1.0"};

  public String[] _ids ()
  {
    return (String[])__ids.clone ();
  }

  private void readObject (java.io.ObjectInputStream s) throws java.io.IOException
  {
     String str = s.readUTF ();
     String[] args = null;
     java.util.Properties props = null;
     org.omg.CORBA.Object obj = org.omg.CORBA.ORB.init (args,
props).string_to_object
(str);
     org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)
obj)._get_delegate ();
     _set_delegate (delegate);
  }

  private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException
  {
     String[] args = null;
     java.util.Properties props = null;
     String str = org.omg.CORBA.ORB.init (args, props).object_to_string (this);
     s.writeUTF (str);
  }
} // class _HelloStub

HelloPOA.java, the server skeleton

The Java class HelloImplPOA is the skeleton file for the server-side mapping, providing basic CORBA functionality for the server. It extends org.omg.PortableServer.Servant, and implements the InvokeHandler interface and the HelloOperations interface. The server class, HelloServant, extends HelloPOA.

HelloApp/HelloPOA.java
package HelloApp;

/**
* HelloApp/HelloPOA.java
* Generated by the IDL-to-Java compiler (portable), version "3.0"
* from Hello.idl
* Thursday, March 22, 2001 2:17:15 PM PST
*/

public abstract class HelloPOA extends org.omg.PortableServer.Servant
 implements HelloApp.HelloOperations, org.omg.CORBA.portable.InvokeHandler
{

  // Constructors

  private static java.util.Hashtable _methods = new java.util.Hashtable ();
  static
  {
    _methods.put ("sayHello", new java.lang.Integer (0));
    _methods.put ("Shutdown", new java.lang.Integer (1));
  }

  public org.omg.CORBA.portable.OutputStream _invoke (String method,
                                org.omg.CORBA.portable.InputStream in,
                                org.omg.CORBA.portable.ResponseHandler rh)
  {
    org.omg.CORBA.portable.OutputStream out = null;
    java.lang.Integer __method = (java.lang.Integer)_methods.get (method);
    if (__method == null)
      throw new org.omg.CORBA.BAD_OPERATION (0,
org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);

    switch (__method.intValue ())
    {
       case 0:  // HelloApp/Hello/sayHello
       {
         String __result = null;
         __result = this.sayHello ();
         out = rh.createReply();
         out.write_string (__result);
         break;
       }

       case 1:  // HelloApp/Hello/Shutdown
       {
         this.Shutdown ();
         out = rh.createReply();
         break;
       }

       default:
         throw new org.omg.CORBA.BAD_OPERATION (0,
org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE);
    }

    return out;
  } // _invoke

  // Type-specific CORBA::Object operations
  private static String[] __ids = {
    "IDL:HelloApp/Hello:1.0"};

  public String[] _all_interfaces (org.omg.PortableServer.POA poa, byte[] objectId)
  {
    return (String[])__ids.clone ();
  }

  public Hello _this()
  {
    return HelloHelper.narrow(
    super._this_object());
  }

  public Hello _this(org.omg.CORBA.ORB orb)
  {
    return HelloHelper.narrow(
    super._this_object(orb));
  }

} // class HelloPOA

Completing the application

To complete the application, the developer must write the client and server code.

HelloServer.java, a transient server

The example server consists of two classes, the servant and the server. The servant, HelloImpl, is the implementation of the Hello IDL interface; each Hello instance is implemented by a HelloImpl instance. The servant is a subclass of HelloPOA, which is generated by the idlj compiler from the example IDL.

The servant contains one method for each IDL operation, in this example, the sayHello() and shutdown() methods. Servant methods are just like ordinary Java methods; the extra code to deal with the ORB, with marshaling arguments and results, and so on, is provided by the skeleton.

This example shows the code for a transient server. For a "Hello World" application with a persistent server, see Hello World with a Persistent Server.

The following code is written by the developer.

HelloServer.java
// HelloServer.java
// Copyright and License
import HelloApp.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;
import org.omg.PortableServer.*;
import org.omg.PortableServer.POA;

import java.util.Properties;

class HelloImpl extends HelloPOA {
  private ORB orb;

  public void setORB(ORB orb_val) {
    orb = orb_val;
  }

  // implement sayHello() method
  public String sayHello() {
    return "\nHello world !!\n";
  }

  // implement shutdown() method
  public void shutdown() {
    orb.shutdown(false);
  }
}

public class HelloServer {

  public static void main(String args[]) {
    try{
      // create and initialize the ORB
      ORB orb = ORB.init(args, null);

      // get reference to rootpoa & activate the POAManager
      POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
      rootpoa.the_POAManager().activate();

      // create servant and register it with the ORB
      HelloImpl helloImpl = new HelloImpl();
      helloImpl.setORB(orb);

      // get object reference from the servant
      org.omg.CORBA.Object ref = rootpoa.servant_to_reference(helloImpl);
      Hello href = HelloHelper.narrow(ref);

      // get the root naming context
      // NameService invokes the name service
      org.omg.CORBA.Object objRef =
          orb.resolve_initial_references("NameService");
      // Use NamingContextExt which is part of the Interoperable
      // Naming Service (INS) specification.
      NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

      // bind the Object Reference in Naming
      String name = "Hello";
      NameComponent path[] = ncRef.to_name( name );
      ncRef.rebind(path, href);

      System.out.println("HelloServer ready and waiting ...");

      // wait for invocations from clients
      orb.run();
    }

      catch (Exception e) {
        System.err.println("ERROR: " + e);
        e.printStackTrace(System.out);
      }

      System.out.println("HelloServer Exiting ...");

  }
}

HelloClient.java, the client application

This example shows a Java client application. You could write a CORBA client as a servlet, a JSP, an applet, etc.

HelloClient.java
// Copyright and License

import HelloApp.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;

public class HelloClient
{
  static Hello helloImpl;

  public static void main(String args[])
    {
      try{
        // create and initialize the ORB
        ORB orb = ORB.init(args, null);

        // get the root naming context
        org.omg.CORBA.Object objRef =
            orb.resolve_initial_references("NameService");
        // Use NamingContextExt instead of NamingContext. This is
        // part of the Interoperable naming Service.
        NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

        // resolve the Object Reference in Naming
        String name = "Hello";
        helloImpl = HelloHelper.narrow(ncRef.resolve_str(name));

        System.out.println("Obtained a handle on server object: " + helloImpl);
        System.out.println(helloImpl.sayHello());
        helloImpl.shutdown();

        } catch (Exception e) {
          System.out.println("ERROR : " + e) ;
          e.printStackTrace(System.out);
          }
    }

}

Compiling and Running a Java CORBA application

For the details of compiling and running a Java CORBA application, refer to Building and Running the Hello World Application.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL: Developing Servers

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Developing Servers

This document was not updated for this release

This topic introduces Java IDL support for servers of both persistent and transient CORBA objects.

Transient and Persistent Objects

A persistent CORBA object lives until it is explicitly destroyed. If a client has a reference to a persistent CORBA object, that reference can be used even if the object's server is not running -- an ORB daemon, ORBD, will start the server when the ORB receives an invocation on the object.

Starting with J2SE 1.4, Java IDL includes a Portable Object Adapter (POA), Object Request Broker Daemon (ORBD), and the servertool. These features enable persistent object servers to be written using Java IDL!

By contrast, a transient CORBA object has the same lifetime as the execution of the server process that creates it. When a server terminates, its transient objects disappear with it and any object references held by the client become invalid. Transient objects are often used to effect asynchronous, or callback communication between applications and objects. For example, suppose a timing service notifies a client application when an interval expires; it could do so as follows:

  • The timing service defines an interface for a notifier object that includes an interval_expired() operation.
  • The timing service requires that a client pass a notifier object to the timing service's set_interval() operation.
  • The timing service client application implements a transient object that implements the notifier interface.
  • The client application creates and passes a notifier object to the timing service.
  • When the interval expires, the timing service invokes the notifier object's interval_expired() operation.

The arrangement, in other words, is much like a callback in procedural programming.

Persistent Object Servers

Starting with J2SE 1.4, Java IDL includes a Portable Object Adapter (POA), Object Request Broker Daemon (ORBD), and the servertool. These features enable persistent object servers to be written using Java IDL! The tutorial Hello World with persistent server provides a version of the "Hello World" application that utilizes a persistent object server.

Transient Object Servers

The Hello World example includes a transient object server.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL: The "Hello World" Example With The POA-Tie Server-Side Model

This document is a high-level overview of how to create a complete CORBA (Common Object Request Broker Architecture) application using IDL (Interface Definiton Language) to define interfaces and the Java IDL compiler to generate stubs and skeletons. This document describes using the POA-Tie Server-Side Model. You might want to use the Tie model instead of the typical Inheritance model if your implementation must inherit from some other implementation. Java allows any number of interface inheritance, but there is only one slot for class inheritance. If you use the inheritance model, that slot is used up. By using the Tie Model, that slot is freed up for your own use. The drawback is that it introduces a level of indirection: one extra method call occurs when invoking a method.

The other part of this programming model is the Portable Object Adapter, or POA, which is designed to meet the following goals:

  • Allow programmers to construct object implementations that are portable between different ORB products.
  • Provide support for objects with persistent identities.
  • Provide support for transparent activation of objects.
  • Allow a single servant to support multiple object identities simultaneously.

This document contains:

  • The IDL for a simple "Hello World" program
  • A server that creates an object and publishes it with a naming service using the POA-Tie server-side implementation
  • An application client that knows the object's name, retrieves a reference for it from the naming service, and invokes the object
  • Instructions for compiling and running the example

Defining the Interface (Hello.idl)

The first step to creating a CORBA application is to specify all of your objects and their interfaces using the OMG's Interface Definition Language (IDL). IDL has a syntax similar to C++ and can be used to define modules, interfaces, data structures, and more. The IDL can be mapped to a variety of programming languages. The IDL mapping for Java is summarized in IDL to Java Language Mapping Summary.

The following code is written in the OMG IDL, and describes a CORBA object whose sayHello() operation returns a string and whose shutdown() method shuts down the ORB. To learn more about OMG IDL Syntax and Semantics, read Chapter 3 of the CORBA 2.3.1 Specification.

Hello.idl

module HelloApp
{
  interface Hello
  {
  string sayHello();
  oneway void shutdown();
  };
};
NOTE: When writing code in OMG IDL, do not use an interface name as the name of a module. Doing so runs the risk of getting inconsistent results when compiling with tools from different vendors, thereby jeopardizing the code's portability. For example, code containing the same names could be compiled with the IDL to Java compiler from Sun Microsystems and get one result. The same code compiled with another vendor's IDL to Java compiler could produce a different result.

To complete the application, you simply provide the server (HelloServer.java) and client (HelloClient.java) implementations.

Implementing the Server (HelloServer.java)

The example server consists of two classes, the servant and the server. The servant, HelloImpl, is the implementation of the Hello IDL interface; each Hello instance is implemented by a HelloImpl instance. The servant is a subclass of HelloPOA, which is generated by the idlj compiler from the example IDL. The servant contains one method for each IDL operation, in this example, the sayHello() and shutdown() methods. Servant methods are just like ordinary Java methods; the extra code to deal with the ORB, with marshaling arguments and results, and so on, is provided by the skeleton.

The HelloServer class has the server's main() method, which:

  • Creates and initializes an ORB instance
  • Gets a reference to the root POA and activates the POAManager
  • Creates a servant instance (the implementation of one CORBA Hello object) and tells the ORB about it
  • Creates a tie with the servant being the delegate
  • Gets a CORBA object reference for a naming context in which to register the tie. This step also implicitly activates the object. See the POA topic for more information on POA policies and activations.
  • Gets the root naming context
  • Registers the new object in the naming context under the name "Hello"
  • Waits for invocations of the new object from the client

The code that is different from that in the default tutorial is highlighted in bold.

HelloServer.java

// Copyright and License
import HelloApp.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;
import org.omg.PortableServer.*;
import org.omg.PortableServer.POA;

import java.util.Properties;

class HelloImpl extends HelloPOA{
  private ORB orb;

  public void setORB(ORB orb_val){
    orb = orb_val;
  }

  public String sayHello(){
    return "\nHello world !!\n";
  }

  public void shutdown(){
    orb.shutdown(false);
  }
}

public class HelloServer{

  public static void main(String args[]){
    try{
      // create and initialize the ORB
      ORB orb = ORB.init(args, null);

      // Get reference to rootpoa & activate the POAManager
      POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
      rootpoa.the_POAManager().activate();

      // create servant and register it with the ORB
      HelloImpl helloImpl = new HelloImpl();
      helloImpl.setORB(orb);

      // create a tie, with servant being the delegate.
      HelloPOATie tie = new HelloPOATie(helloImpl, rootpoa);

      // obtain the objectRef for the tie
      // this step also implicitly activates the object
      Hello href = tie._this(orb);

      // get the root naming context
      org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService");

      // Use NamingContextExt which is part of the Interoperable
      // Naming Service specification.
      NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

      // bind the Object Reference in Naming
      String name = "Hello";
      NameComponent path[] = ncRef.to_name( name );
      ncRef.rebind(path, href);

      System.out.println("HelloServer ready and waiting ...");

      // wait for invocations from clients
      orb.run();
      }

    catch (Exception e){
      System.err.println("ERROR: " + e);
      e.printStackTrace(System.out);
    }

    System.out.println("HelloServer Exiting ...");

  }
}

Implementing the Client Application (HelloClient.java)

The example application client that follows is the same as the one presented in the default tutorial. The server implementation is the only file that is changed from that example. The example client application:

  • Creates and initializes an ORB
  • Obtains a reference to the root naming context
  • Looks up "Hello" in the naming context and receives a reference to that CORBA object
  • Invokes the object's sayHello() and shutdown() operations and prints the result

HelloClient.java

// Copyright and License

import HelloApp.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;

public class HelloClient{

  public static void main(String args[]){

    try{
      // create and initialize the ORB
      ORB orb = ORB.init(args, null);

      // get the root naming context
      org.omg.CORBA.Object objRef =
          orb.resolve_initial_references("NameService");

      // Use NamingContextExt instead of NamingContext. This is
      // part of the Interoperable naming Service.
      NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

      // resolve the Object Reference in Naming
      String name = "Hello";
      Hello helloImpl = HelloHelper.narrow(ncRef.resolve_str(name));

      System.out.println("Obtained a handle on server object: " + helloImpl);
      System.out.println(helloImpl.sayHello());
      helloImpl.shutdown();
      }

    catch (Exception e) {
      System.out.println("ERROR : " + e) ;
      e.printStackTrace(System.out);
    }
  }
}

Building and Running Hello World

Despite its simple design, the Hello World program lets you learn and experiment with all the tasks required to develop almost any CORBA program that uses static invocation.

This example requires a naming service, which is a CORBA service that allows CORBA objects to be named by means of binding a name to an object reference. The name binding may be stored in the naming service, and a client may supply the name to obtain the desired object reference. The two options for Naming Services shipped with this version of Java SE are tnameserv, a transient naming service, and orbd, which contain a Naming Service. This example uses orbd.

When running this example, remember that, when using Solaris software, you must become root to start a process on a port under 1024. For this reason, we recommend that you use a port number greater than or equal to 1024. The -ORBInitialPort option is used to override the default port number in this example. The following instructions assume you can use port 1050 for the Java IDL Object Request Broker Daemon, orbd. You can substitute a different port if necessary. When running these examples on a Windows machine, subtitute a backslash (\) in path names.

To run this client-server application on your development machine:

  1. Create the program files or download and unzip the file HelloTie.zip.
  2. Change to the directory that contains the program files.
  3. Run the IDL-to-Java compiler, idlj, twice on the IDL file to create stubs and skeletons. This step assumes that you have included the path to the java/bin directory in your path.
      idlj -fall  Hello.idl
  idlj -fallTie Hello.idl

    You must use the -fall option with the idlj compiler to generate both client and server-side bindings. This command line will generate the default server-side bindings, which assumes the POA programming model. The -fallTie option generates another file, HelloPOATie, which is used to create a Tie. For more information on the idlj options, link to IDL-to-Java compiler options.

    The idlj compiler generates a number of files. The actual number of files generated depends on the options selected when the IDL file is compiled. The generated files provide standard functionality, so you can ignore them until it is time to deploy and run your program. The files generated by the idlj compiler for Hello.idl, with the -fall command line option, are:

    • HelloPOA.java

      This abstract class is the stream-based server skeleton, providing basic CORBA functionality for the server. It extends org.omg.PortableServer.Servant, and implements the InvokeHandler interface and the HelloOperations interface. The server class HelloImpl extends HelloPOA.

    • _HelloStub.java

      This class is the client stub, providing CORBA functionality for the client. It extends org.omg.CORBA.portable.ObjectImpl and implements the Hello interface.

    • Hello.java

      This interface contains the Java version of our IDL interface. The Hello interface extends org.omg.CORBA.Object, providing standard CORBA object functionality. It also extends the HelloOperations interface and org.omg.CORBA.portable.IDLEntity.

    • HelloHelper.java

      This class provides auxiliary functionality, notably the narrow() method required to cast CORBA object references to their proper types.The Helper class is responsible for reading and writing the data type to CORBA streams, and inserting and extracting the data type from Anys. The Holder class delegates to the methods in the Helper class for reading and writing.

    • HelloHolder.java

      This final class holds a public instance member of type Hello. Whenever the IDL type is an out or an inout parameter, the Holder class is used. It provides operations for org.omg.CORBA.portable.OutputStream and org.omg.CORBA.portable.InputStream arguments, which CORBA allows, but which do not map easily to Java's semantics. The Holder class delegates to the methods in the Helper class for reading and writing. It implements org.omg.CORBA.portable.Streamable.

    • HelloOperations.java

      This interface contains the methods sayHello() and shutdown(). The IDL-to-Java mapping puts all of the operations defined on the IDL interface into this file, which is shared by both the stubs and skeletons.

    The files generated by the idlj compiler for Hello.idl, with the -fallTie command line option, are:

    • HelloPOATie.java

      The constructor to MyPOATie takes a delegate and/or a poa. You must provide the implementations for delegate and/or poa, but the delegate does not have to inherit from any other class, only the interface HelloOperations. For more information, refer to the IDL to Java Language Mapping Specification.

  4. Compile the .java files, including the stubs and skeletons (which are in the directory HelloApp). This step assumes the java/bin directory is included in your path.
       javac *.java HelloApp/*.java
  5. Start orbd.

    To start orbd from a UNIX command shell, enter:

      orbd -ORBInitialPort 1050 -ORBInitialHost localhost&

    From an MS-DOS system prompt (Windows), enter:

      start orbd -ORBInitialPort 1050 -ORBInitialHost localhost

    Note that 1050 is the port on which you want the name server to run. -ORBInitialPort is a required command-line argument. Note that when using Solaris software, you must become root to start a process on a port under 1024. For this reason, we recommend that you use a port number greater than or equal to 1024.

    -ORBInitialHost is an optional command-line argument. For this example, since both client and server on running on the development machine, we have set the host to localhost. When developing on more than one machine, you will replace this with the name of the host. For an example of how to run this program on two machines, see Running the Hello World Program on 2 machines.

  6. Start the Hello server.

    To start the Hello server from a UNIX command shell, enter:

      java HelloServer -ORBInitialPort 1050 -ORBInitialHost localhost&

    From an MS-DOS system prompt (Windows), enter:

      start java HelloServer -ORBInitialPort 1050 -ORBInitialHost localhost

    For this example, you can omit -ORBInitialHost localhost since the name server is running on the same host as the Hello server. If the name server is running on a different host, use -ORBInitialHost nameserverhost to specify the host on which the IDL name server is running.

    Specify the name server (orbd) port as done in the previous step, for example, -ORBInitialPort 1050.

    The server starts and echos the following message back to the terminal:

    HelloServer ready and waiting ...
  7. Run the client application:
      java HelloClient -ORBInitialPort 1050 -ORBInitialHost localhost

    For this example, you can omit -ORBInitialHost localhost since the name server is running on the same host as the Hello client. If the name server is running on a different host, use -ORBInitialHost nameserverhost to specify the host on which the IDL name server is running.

    Specify the name server (orbd) port as done in the previous step, for example, -ORBInitialPort 1050.

    The client runs and echos the following information back to the terminal:

    Obtained a handle on server object: IOR:
...
Hello World!
Hello Server Exiting ...

When you have finished this tutorial, be sure to shut down or kill the name server (orbd). To do this from a DOS prompt, select the window that is running orbd and enter Ctrl+C to shut it down. To do this from a Unix shell, find the process, and kill it. The name server will continue to wait for invocations until it is explicitly stopped.

Running the Hello World Application on Two Machines describes one way of distributing the simple application across two machines - a client and a server.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

jinfo - Configuration Info

  • Synopsis
  • Parameters
  • Description
  • Options
  • See Also

SYNOPSIS

jinfo [ option ] pid
jinfo [ option ] executable core
jinfo [ option ] [server-id@]remote-hostname-or-IP

PARAMETERS

option
Options are mutually exclusive. Option, if used, should follow immediately after the command name.

pid
process id for which the configuration info is to be printed. The process must be a Java process. To get a list of Java processes running on a machine, jps may be used.
executable
Java executable from which the core dump was produced.
core
core file for which the configuration info is to be printed.
remote-hostname-or-IP
remote debug server's (see jsadebugd) hostname or IP address.
server-id
optional unique id, if multiple debug servers are running on the same remote host.

DESCRIPTION

jinfo prints Java configuration information for a given Java process or core file or a remote debug server. Configuration information includes Java System properties and Java virtual machine command line flags. If the given process is running on a 64-bit VM, you may need to specify the -J-d64 option, e.g.:
jinfo -J-d64 -sysprops pid

NOTE - This utility is unsupported and may or may not be available in future versions of the JDK. In Windows Systems where dbgeng.dll is not present, 'Debugging Tools For Windows' need to be installed to have these tools working. Also, PATH environment variable should contain the location of jvm.dll used by the target process or the location from which the Crash Dump file was produced.

For example, set PATH=<jdk>\jre\bin\client;%PATH%

OPTIONS

<no option>
prints both command line flags as well as System properties name, value pairs.
-flag name
prints the name and value of the given command line flag.
-flag [+|-]name
enables or disables the given boolean command line flag.
-flag name=value
sets the given command line flag to the specified value.
-flags
prints command line flags passed to the JVM. pairs.
-sysprops
prints Java System properties as name, value pairs.
-h
prints a help message
-help
prints a help message

SEE ALSO

  • jps
  • jsadebugd
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


jlist

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Overview File Class Tree Index Help
PREV CLASS NEXT CLASS
SUMMARY: FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

Class jlist

Object
   |
   +--jlist
class jlist

Defined in init.js

Constructor Summary
jlist (list)
Creates a convenient script object to deal with java.util.List instances.

Constructor Detail

jlist

jlist(list)
    Creates a convenient script object to deal with java.util.List instances. The result script object behaves like an array. For example, scriptObj[index] syntax can be used to access values in the List instance. 'length' field gives size of the List.
    Example:

    var x = new java.util.ArrayList(4);
    x.add('Java');
    x.add('JavaScript');
    x.add('SQL');
    x.add('XML');

    var y = jlist(x);
    print(y[2]); // prints third element of list
    print(y.length); // prints size of the list
    Parameters:
      map - java.util.List instance that will be wrapped
Overview  File   Class  Tree  Index  Help
 PREV CLASS  NEXT CLASS
SUMMARY: FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


jmap

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Overview File Class Tree Index Help
PREV CLASS NEXT CLASS
SUMMARY: FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

Class jmap

Object
   |
   +--jmap
class jmap

Defined in init.js

Constructor Summary
jmap (map)
Creates a convenient script object to deal with java.util.Map instances.

Constructor Detail

jmap

jmap(map)
    Creates a convenient script object to deal with java.util.Map instances. The result script object's field names are keys of the Map. For example, scriptObj.keyName can be used to access value associated with given key.
    Example:

     var x = java.lang.SystemProperties();
     var y = jmap(x);
     print(y['java.class.path']); // prints java.class.path System property
     delete y['java.class.path']; // remove java.class.path System property
    Parameters:
      map - java.util.Map instance that will be wrapped
Overview File Class Tree Index Help
PREV CLASS NEXT CLASS
SUMMARY: FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


--                    LDAP Schema for JSR 160 Lookup
--                    ------------------------------

-- AttributeTypes:
-----------------

-- jmxServiceURL attribute is an IA5 String

( 1.3.6.1.4.1.42.2.27.11.1.1 NAME 'jmxServiceURL'
  DESC 'String representation of a JMX Service URL'
  SYNTAX 1.3.6.1.4.1.1466.115.121.1.26
  SINGLE-VALUE )

-- jmxAgentName attribute is an IA5 String

( 1.3.6.1.4.1.42.2.27.11.1.2 NAME 'jmxAgentName'
  DESC 'Name of the JMX Agent'
  SYNTAX 1.3.6.1.4.1.1466.115.121.1.26
  SINGLE-VALUE )

-- jmxProtocolType attribute is an IA5 String

( 1.3.6.1.4.1.42.2.27.11.1.3 NAME 'jmxProtocolType'
  DESC 'Protocol used by the registered connector'
  SYNTAX 1.3.6.1.4.1.1466.115.121.1.26
  SINGLE-VALUE )

-- jmxAgentHost attribute is an IA5 String

( 1.3.6.1.4.1.42.2.27.11.1.4 NAME 'jmxAgentHost'
  DESC 'Names or IP Addresses of the host on which the agent is running.
        When multiple values are given, they should be aliases to the
        same host.'
  SYNTAX 1.3.6.1.4.1.1466.115.121.1.26  )

-- jmxProperty attribute is an IA5 String

( 1.3.6.1.4.1.42.2.27.11.1.5 NAME 'jmxProperty'
  DESC 'Java-like property characterizing the registered object.
        The form of each value should be: "<property-name>=<value>".
        For instance: "com.sun.jmx.remote.tcp.timeout=200"'
  SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 )

-- jmxExpirationDate attribute is a Generalized Time
-- see [RFC 2252] - or X.208 for a description of
-- Generalized Time

( 1.3.6.1.4.1.42.2.27.11.1.6 NAME 'jmxExpirationDate'
  DESC 'Date at which the JMX Service URL will be considered obsolete
        and may be removed from the directory tree'
  SYNTAX 1.3.6.1.4.1.1466.115.121.1.24
  SINGLE-VALUE )

-- ObjectClasses:
-----------------

-- jmxConnector class - represents a JMX Connector.
-- must contain the JMX Service URL
-- and the JMX Agent Name

( 1.3.6.1.4.1.42.2.27.11.2.1 NAME 'jmxConnector'
  DESC  'A class representing a JMX Connector, and containing a
         JMX Service URL. The jmxServiceURL is not present if the server
         is not accepting connections'
  AUXILIARY
  MUST  ( jmxAgentName  )
  MAY   ( jmxServiceURL $ jmxAgentHost $ jmxProtocolType $ jmxProperty $
          jmxExpirationDate $ description ) )


Java VisualVM

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java VisualVM - Connecting to JMX Agents Explicitly

Java Management Extensions (JMX) technology can be used to monitor and manage any Java technology-based applications (Java applications) that are running in either a local or a remote Java Virtual Machine (JVM). Java applications are automatically exposed for monitoring and management by JMX agents if they are run on the Java platform, Standard Edition (Java SE platform) version 6. If the Java applications are running on the Java 2 platform, Standard Edition (J2SE platform) 5.0, you can expose them manually for monitoring and management by setting the com.sun.management.jmxremote.* system properties when the applications are launched. Setting these system properties, or running your applications on version 6 of the Java SE platform, enables the platform's out-of-the-box monitoring and management capability, automatically enabling the platform MBean server in the JVM software, and registering MBeans in it that expose the application for management by any appropriately configured JMX client application. VisualVM is one such JMX client application.

NOTE: For a very brief introduction to JMX technology, MBeans, the platform MBean server, and how to monitor and manage MBeans using Java VisualVM, see the Java VisualVM MBeans Tab page. For an introduction to the Java SE platform's out-of-the-box monitoring and management capability, see Monitoring and Management Using JMX Technology in the Java SE Platform Monitoring and Management Guide.

When Are Explicit JMX Connections Necessary?

As stated above, Java VisualVM will automatically detect and connect to Java applications that are running on version 6 of the Java SE platform or that have been started with the correct system properties on version 5.0. However, because there are cases in which Java VisualVM cannot automatically discover and connect to JMX agents that are running in a target Java application, a means of creating explicit JMX connections has also been added to Java VisualVM.

The circumstances in which Java VisualVM will not automatically discover JMX agents, and thus the Java applications they expose, are the following:

  • The target application is running on the J2SE 5.0 platform and the -Dcom.sun.management.jmxremote* properties have not been specified.
  • The target application is running on the same host as Java VisualVM but was started by a different user than the one who started Java VisualVM. Java VisualVM discovers running applications using the jps tool, which can only discover Java applications started by the same user as the one who starts the Java VisualVM tool.
  • The target application is running on a remote host where jstatd is not running or is running but was started by a different user. The jstatd daemon provides an interface that allows remote monitoring applications to connect to Java applications on the host where it is running.

Making an Explicit JMX Connection

Before you can make an explicit JMX connection from Java VisualVM to a running application, this application must be started with the correct system properties. The system properties in question are the following:

  • com.sun.management.jmxremote.port, to specify the port number through which the application will be exposed
  • com.sun.management.jmxremote.ssl, to specify whether secure sockets layer (SSL) encryption will be activated to secure the connection to the application
  • com.sun.management.jmxremote.authenticate, to specify whether the connection will be password protected

Local JMX Connections

This section shows an example of how to connect Java VisualVM to a local application via an explicit JMX connection.

  1. Start a Java application on the J2SE platform version 5.0, setting the system properties to enable the Java SE platform's out-of-the-box monitoring and management capability, using the command shown below:
    java -Dcom.sun.management.jmxremote.port=3333 \
     -Dcom.sun.management.jmxremote.ssl=false \
     -Dcom.sun.management.jmxremote.authenticate=false \
     YourJavaApp
    In the command above, YourJavaApp is launched with the Java SE platform's out-of-the-box monitoring and management capability configured as follows:
    • The application is exposed for monitoring and management via port 3333.
    • SSL encryption is deactivated.
    • Password authentication is deactivated.
  2. Start Java VisualVM on the same machine.
  3. In Java VisualVM's Applications window, right click on the Local machine and select 'Add JMX Connection'.

    Adding a JMX connection to the local host.

  4. The Add JMX Connection dialog box opens.

    The Add JMX Connection dialog.

    The host name localhost is already filled in. You only need to add the port number on which the application is exposed for monitoring and management.

  5. Click OK. The JMX connection will appear in the application tree, with a special JMX connection icon.

    A JMX connection to the local host machine.

  6. Right click on the JMX connection, and select Open. The JVM software exposed via the JMX connection can now be monitored and managed via Java VisualVM.

    Monitoring an application via a JMX connection.

Remote JMX Connections

You can also make explicit JMX connections to applications running on remote hosts, as explained below:

  1. Right click anywhere in the blank area under the application tree and select Add JMX Connection.

    Adding a JMX connection to a remote application.

  2. Provide the machine name and port number for a running JMX agent, that has been started with the appropriate system properties to allow remote management. Here the JMX agent has been exposed on port 2222 of the machine curcuma.

    Adding a remote JMX connection.

    If you know that the JMX agent has been protected with a username and password, enter them in the Add JMX Connection dialog and specify whether you want the credentials to be saved so
    that when Java VisualVM restarts it will silently reconnect to the JMX agent without prompting the user for the security credentials again.

  3. If the JMX connection is secured and you did not provide a username and password in the Add JMX Connection dialog, you will be prompted to provide a username and password.

    JMX connector security credentials.

  4. If you know the correct username and password, the JMX connection will be established, and the JMX connection will appear in the application tree, with a special JMX connection icon.

    Remote JMX connection shown in application tree.

  5. Right click on the remote JMX connection and select Open. You can now monitor and manage remote applications via the JMX connection, and manipulate any MBeans that are registered in the MBean server exposed by this connection (note that the Java VisualVM-MBeans plugin must be installed if you want to access to the MBeans tab.)

    MBeans in a remote MBean server.

Further Reading About JMX Technology

For more information about JMX technology and monitoring and management of the Java SE platform, see the following documents.

  • JMX technology trail in the Java Tutorials
  • JMX technology documentation for the Java SE platform
  • Monitoring and Management documentation for the Java SE Platform

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Contents

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java Management Extensions (JMX) Technology Overview

Java Management Extensions (JMX)
Java Platform, Standard Edition version 7

August, 2008
Contents | Previous | Next

Contents

Preface

1. Introduction to JMX Technology

What Is JMX Technology?

Why Use JMX Technology?

2. JMX Architecture

Architecture Outline

Instrumenting Resources Using MBeans

Creating a JMX Agent

Managing Resources Remotely

3. Instrumenting Your Resources for JMX Technology

Manageable Resources

Managed Beans (MBeans)

Java Virtual Machine Instrumentation

4. Using JMX Agents

MBean Server

Agent Services

Protocol Adaptors and Connectors

Protocol Adaptors

Connectors

5. Using JMX Connectors to Manage Resources Remotely

RMI Connector

Generic Connector

User-Defined Protocols

6. Discovery and Lookup Services

Getting Started With Lookup Services

Using the Service Location Protocol (SLP)

Using the Jini Network Technology

Using the Java Naming and Directory Interface (JNDI) API With an LDAP Backend

A. JMX Technology Versions

Java Management Extensions (JMX) Instrumentation and Agent Specification (JSR 3)

JMX Remote API Specification (JSR 160)

Contents | Previous | Next
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JNDI/COS Naming Service Provider

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

COS Naming Service Provider for the
Java Naming and Directory Interface (JNDI)

Table of Contents

  • Introduction
  • Conformance
  • Environment Properties
  • ORB Initialization
  • Root Naming Context Initialization
  • Names and URLs
  • API Mapping
  • Converting CORBA Programs to use JNDI
  • Security Considerations

Introduction

The Common Object Services (COS) Name Server is the name server for storing Common Object Request Broker Architecture (CORBA) object references. It can be accessed from CORBA applications by using the COS Naming package (org.omg.CORBA.CosNaming).

The JNDI/COS naming service provider implements the javax.naming.Context interface on top of the COS Naming package in order to allow applications to use JNDI to access the COS Name Server. JNDI can also be used to access other naming and directory services, in addition to the COS Name Server, thereby offering the CORBA application one interface for accessing different naming and directory services.

This document describes the features of the COS naming service provider and contains details of how JNDI is mapped to the COS naming package.

Conformance

The COS naming service provider for JNDI uses JavaTM IDL, the Java programming language mapping to the industry standard Object Management Group Interface Definition Language (OMG IDL). In particular, it uses the COS Naming Service.

The complete specification for COS Naming can be obtained from OMG.

The syntax of names conforms to the Interoperable Naming Service (INS) specification (99-12-03), with backward compatibility support for the previous version of INS, OMG TC Document orbos/98-10-11. This is described in Names and URLs.

Environment Properties

The following JNDI environment properties are relevant for the COS naming service provider. See the JNDI documentation for a description of how properties are initialized using the environment properties, system properties, applet parameters, and resource files.

java.naming.factory.initial

This property is used to select the COS naming service provider; it's not actually used by the provider itself. It specifies the class name of the initial context factory for the provider.

For example:

env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.cosnaming.CNCtxFactory");

This property must be set if you are using the COS naming service as the initial context. The only exception is if you supply only URLs to the initial context, in which case, you don't need to specify this property. See Names and URLs for details.

java.naming.provider.url

This property is used to configure the root naming context and/or the Object Request Broker (ORB). Its value is the string representation of a URL.

If this property is not specified, then the ORB is initialized using the java.naming.corba.orb property, the java.naming.applet property, or other ORB initialization properties. The root naming context is obtained by invoking

orb.resolve_initial_references("NameService");

If the URL scheme is one of "IOR", "corbaname", or "corbaloc", as specified in the INS specification (99-12-03), then the root naming context is that named by the URL. The ORB is initialized using the java.naming.corba.orb property, the java.naming.applet property, or other ORB initialization properties.

If the URL scheme is either "iiop" or "iiopname", then the host and port fields of the URL are used to initialize the ORB. An "iiopname" URL must conform to the now obsolete INS specification (98-10-11). It has the form:

iiopname://[<addr_list>][/<cosnaming_name>]

The "iiop" URL scheme is supported for backward compatibility with an older version of the INS specification. It has the form:

iiop://[<host>[:<port>]][/<cosnaming_name>]

For both "iiop" and "iiopname" URLs, if <host> is not specified, then it defaults to "localhost" for an application and the applet's host for an applet. If <port> is not specified, then it defaults to 9999 for "iiopname", and 900 for "iiop". The root naming context is obtained by invoking the following method on the ORB:

orb.resolve_initial_references("NameService");

If <cosnaming_name> is nonempty, then the root naming context is the naming context named by cosnaming_name.

If the URL scheme is not one of "iiop", "iiopname", "IOR", "corbaname", or "corbaloc", then the URL must name a location that contains the stringified IOR of the root naming context. For example, if the property contains "file:/nsdir/ior", then the file /nsdir/ior must contain a stringified IOR. The URL scheme can be any for which there is a corresponding URL protocol handler ( java.net.URLStreamHandler). See the java.net.URL class for details. The stringified IOR is read from the data stream corresponding to the URL by using a character encoding of ISO Latin-1. The stringified IOR is the first line in the stream that contains the prefix "IOR:". For example, if the URL scheme is "http", then the headers in the stream are skipped and the first line that contains the prefix "IOR:" is returned as the IOR.

When the property specifies a stringified IOR or the location of one, the root naming context is that named by the stringified IOR. The ORB is initialized using the java.naming.corba.orb property, the java.naming.applet property, or other ORB initialization properties.

java.naming.corba.orb

This property specifies the ORB that the program is using. When the JNDI COS naming service provider needs to use an ORB, for example, to look up the "NameService" initial reference or to turn a stringified IOR into an object reference, it will use this ORB.

In an application you can set this property as follows:

ORB orb = ORB.init(args, null);
Hashtable env = new Hashtable(5, 0.75f);
env.put("java.naming.corba.orb", orb);
...
In an applet, you can set it as follows:
public class MyApplet extends Applet {

    public someInitMethod() {
        ORB orb = ORB.init(this, null);
        Hashtable env = new Hashtable(5, 0.75f);
        env.put("java.naming.corba.orb", orb);
        ...
    }
...
}

If this property is not set, then the java.naming.provider.url property, the java.naming.applet property, or the ORB initialization properties are used to initialize the ORB.

java.naming.applet

This property specifies the applet that the program is using. It is used to initialize the ORB to be used by the COS naming service provider. Its parameters are used for setting JNDI-related properties; see the JNDI documentation for details.

public class MyApplet extends Applet {

    public someInitMethod() {
        Hashtable env = new Hashtable(5, 0.75f);
        env.put("java.naming.applet", this);
        ...
    }
...
}

java.naming.factory.state

A colon-separated list of the fully qualified class names of state factory classes used to get an object's state for storing given the object itself. You can use this mechanism to transform an object into forms that can be stored into a COS name server. The COS name server supports storing CORBA objects.

A state factory that transforms a java.rmi.Remote into a CORBA object is supplied by default. This factory is useful for applications that use RMI-IIOP. You can supply other factories to affect the transformation of other objects into CORBA objects for storing. See javax.naming.spi.NamingManager.getStateToBind() for details.

java.naming.factory.object

A colon-separated list of the fully qualified class names of object factory classes for transforming a CORBA object. You can use this mechanism to transform an object into forms expected by the application. For example, a specialized object factory could do the appropriate narrowing to return an object of the expected type. See javax.naming.spi.NamingManager.getObjectInstance() for details.

java.naming.batchsize

Specifies the batch size to use in CosNaming::BindingIterator.next_n when getting the results of a list()/listBindings(). The default is "100." For example, the following sets the batch size to be 24.

env.put(Context.BATCHSIZE, "24");
ORB initialization properties

You can specify CORBA related properties such as those with the "org.omg.CORBA." prefix as properties. Properties of type String are used to initialize the ORB.

ORB Initialization

The properties that affect which ORB is used and how the ORB is initialized are:

  • java.naming.corba.orb

  • java.naming.applet

  • java.naming.provider.url
  • org.omg.CORBA.* and other ORB-specific properties of type String
The following algorithm is used to determine which ORB is used:
  1. If java.naming.corba.orb has been set, then its value (an ORB) is used.
  2. Otherwise, the provider will internally initialize and use an ORB as follows:
    a) Any org.omg.CORBA.* properties and properties of type String are extracted and used as part of the Properties argument to the ORB.init() method. You can use this mechanism to specify, for example, the ORB implementation or host to use.
    b) If java.naming.provider.url has been set and it contains a URL of scheme "iiop" or "iiopname", then the host and port number specified in the URL are used as part of the Properties argument to the ORB.init() method, overriding any org.omg.CORBA.ORBInitialHost and org.omg.CORBA.ORBInitialPort properties set up in (a).
    c) The Properties instance constructed in (a) and (b) are passed to ORB.init() along with the Applet instance in java.naming.applet property, or an empty String[] if java.naming.applet was not supplied.

If the properties employed in steps (a), (b) and (c) contain no relevant information for initializing the ORB, then the Java IDL implementation's defaults are used. Typically that means port 900 on the local host for an application, and port 900 on the applet host for an applet are used. Note that when the ORB is initialized using ORB.init(), its arguments are checked in the following order: (from org.omg.CORBA.ORB javadoc)

  1. Check in Applet parameter or application string array, if any
  2. Check in properties parameter, if any
  3. Check in the System properties (currently applications only)
  4. Fall back on a hardcoded default behavior (use the Java IDL implementation)

Root Naming Context Initialization

The root naming context is initialized either using the java.naming.provider.url property or by a resolve_initial_references() call on the ORB. If the java.naming.provider.url property is set but contains neither an "iiop" or "iiopname" URL, then it is assumed to contain a stringified IOR, a "corbaname" or "corbaloc" URL of an IOR, or a URL containing the location of a stringified IOR. The IOR is used to obtain the root naming context and must be that of a CORBA object of type CosNaming::NamingContext.

If the java.naming.provider.url has not been set, then the root naming context is obtained by invoking the following method on the ORB:

        orb.resolve_initial_references("NameService");

Names and URLs

String Names

String names accepted by the java.naming.Context methods are JNDI composite names in which each component is the stringified form of a CosNaming::NameComponent.

A CosNaming::Name contains a sequence of CosNaming::NameComponent. The stringified form of a component is the concatenation of the component's id, the kind separator character ('.'), and the component's kind. The occurrence of any meta characters ('.', '/', or '\') in either the id or kind is escaped using the escape character ('\'). The stringified form of a CosNaming::Name is defined in Section 3.5 of the INS specification (99-12-03).

The JNDI composite name syntax is very similar to, but not identical to, the INS syntax. There are minor differences with respect to the treatment of escape and quote characters. If you want to use names with the precise INS syntax, then you should use the overloads that accept a Name argument instead of a String argument. The Name argument should be a value returned by nameParser.parse(), where nameParser is a value obtained from the COS naming service provider. See the Name Parsing section.

URL String Names

The URL form of a CosNaming::Name is defined in the INS specification.

corbaname:<corbaloc_obj>["#" <cosnaming_name>]

where <corbaloc_obj> is

<corbaloc_obj> = <obj_addr_list> ["/" <key_string>]

and <obj_addr_list> is a list of addresses as defined in a "corbaloc" URL and <key_string> is a key string as defined in a "corbaloc" URL. <cosnaming_name> is the stringified form of an INS name (see Name Parsing).

For backward compatibility with older versions of the INS, the following URL schemes are also supported.

iiopname://[<addr_list>][/<cosnaming_name>]

where <addr_list> specifies a list of host/port pairs. If <port> is not specified, then it defaults to 9999. <cosnaming_name> is the stringified form of an INS name.

iiop://<host>[:<port>][/<cosnaming_name>]

If <port> is not supplied, then it defaults to 900. <cosnaming_name> is the stringified form of an INS name.

When you supply an "iiop" or "iiopname" URL to the initial context in this way, the ORB supplied to the initial context is used if its string_to_object() method supports the 99-12-03 INS specification. Otherwise, the ORB is ignored and the server and port designations in the URL are used to create an ORB. The value of the java.naming.factory.initial property is ignored for the purposes of resolving the URL.

Note that this rule is not used when you supply a "corbaname" URL to the initial context. For a "corbaname" URL, the ORB supplied to the initial context is used because the ORB is needed to resolve the "corbaname" URL. Name Objects

The Name argument to a Context method is treated as a sequence of strings, each representing a stringified CosNaming::NameComponent.

Name Parsing

The COS naming service provider supports names in the syntax specified in the INS specification. In short, the syntax is that components are left-to-right slash ('/') separated and case-sensitive. The id and kind of each component are separated by the period character ('.').

Here is a code fragment that uses the name parser from the COS naming service provider to eventually do a lookup using an INS name.

String insName = ...;
InitialContext ctx = new InitialContext(env);   // env contains init properties
NameParser parser = ctx.getNameParser("");      // parser for INS names
Name name = parser.parse(insName);              // get parsed INS name
Object obj = ctx.lookup(name);                  // do lookup

API Mapping

The COS name server supports only naming operations. The COS naming service provider maps the javax.naming.Context methods to use the appropriate COS Naming calls.

addToEnvironment()

Records change to environment property but does not reinitialize ORB.

bind()

Binds an object to the specified name.

If the object being bound is an org.omg.CosNaming.NamingContext, then CosNaming::NamingContext.bind_context is used. If it is an org.omg.CORBA.Object, then CosNaming::NamingContext.bind is used. The binding of any other type of object is not supported unless the object can be converted into an org.omg.CORBA.Object using the state factory mechanism described next.

Before the bind is performed on the naming server, the COS naming service provider uses javax.naming.spi.NamingManager.getStateToBind() to allow the object to be transformed into a org.omg.CORBA.Object. The getStateToBind() method uses the state factories available to the COS naming service provider. If the state factory accepts a java.rmi.Remote object, then it is responsible for obtaining the object's RMI-IIOP stub and connecting it to the ORB associated with the context. The connected stub is the object that will be bound in the naming server.

By default, the COS naming service provider supplies and uses a state factory that transforms an object implementing the java.rmi.Remote interface to an org.omg.CORBA.Object following the requirements described above. This factory uses the utilities in the javax.rmi.CORBA package. You can supply additional state factories to transform objects into CORBA objects.

close()

Releases any internal data structures used.

composeName()

Concatenates the supplied name to the prefix.

createSubcontext()

Uses CosNaming::NamingContext.bind_new_context to create and bind a new context.

destroySubcontext()

Uses CosNaming::NamingContext.destroy to destroy the named context. Then uses CosNaming::NamingContext.unbind to remove the binding.

getEnvironment()

Returns the environment of this context.

getNameInNamespace()

Returns the INS name of this context relative to the root of the Cos Naming namespace.

getNameParser()

Returns a name parser for parsing INS names.

lookup()
lookupLink()

Uses CosNaming::NamingContext.resolve to lookup the name. It returns a CORBA object reference except when the reference is that of a CosNaming::NamingContext, in which case a Context object is returned instead. NamingManager.getObjectInstance() is called before the object is returned in case the application or user has supplied object factories.

list()
listBindings()

Uses CosNaming::NamingContext.resolve to get the object reference for the context, and then uses CosNaming::BindingIterator and helper classes to iterate through the context. The objects bound to the names are obtained by calling CosNaming::NamingContext.resolve on them. NamingManager.getObjectInstance() is called before the object is returned in case the application or user has supplied object factories.

removeFromEnvironment()

Removes the specified property from the environment but does not otherwise update the context.

rebind()

If the object being bound is an org.omg.CosNaming.NamingContext, then CosNaming::NamingContext.rebind_context is used. If it is an org.omg.CORBA.Object, then CosNaming::NamingContext.rebind is used. See bind() for details on the use of state factories to transform the argument into an org.omg.CORBA.Object.

rename()

This method is implemented using bind() followed by unbind(). It is not atomic.

unbind()

Uses CosNaming::NamingContext.unbind to unbind the object.

Converting CORBA Programs to use JNDI

This section explains how to modify your Java IDL program to use JNDI. The explanation uses the Java IDL sample programs helloClient.java and helloServer.java.

  1. Generate the stubs from the IDL file.
    # idltojava -fclient -fserver hello.idl

    This creates the client (helloClient.java) and server (helloServer.java) skeletons, and a directory containing common code (e.g. HelloApp/*.java).

  2. Fill in the code for the client and server programs.
  3. Modify (or copy the client and server files) to use JNDI instead of COS Naming directly.
    • Replace the import to use javax.naming.*;

      Delete:

      import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
      Add:
      import javax.naming.*;
    • Replace how you get the initial reference to "NameService" with InitialContext, supplying the initial context the ORB being used by the current application.

      Delete:

      org.omg.CORBA.Object objRef =
   orb.resolve_initial_references("NameService");
NamingContext ncRef = NamingContextHelper.narrow(objRef);

      Add:

      Hashtable env = new Hashtable(5, 0.75f);
env.put("java.naming.corba.orb", orb);
Context ic = new InitialContext(env);
    • Replace the call to resolve() to use lookup().

      Delete:

      // resolve the Object Reference in Naming
NameComponent nc = new NameComponent("Hello", "");
NameComponent path[] = {nc};
hello helloRef = helloHelper.narrow(ncRef.resolve(path));
      Add:
      // resolve the Object Reference using JNDI
hello helloRef =
helloHelper.narrow((org.omg.CORBA.Object)ic.lookup("Hello"));

Security Considerations

When a security manager has been installed, you must grant to the application using JNDI and the COS naming service provider the following permissions:

permission java.net.SocketPermission "host[:port]", "connect";

For each host/port identified in the java.naming.factory.initial property, in URL string names supplied to context methods, in ORB initialization parameters and properties, and in object references.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JNDI/DNS Service Provider

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

DNS Service Provider for the
Java Naming Directory Interface™ (JNDI)

Table of Contents

  • Introduction
  • Conformance
  • Environment Properties
  • Mapping DNS Content to JNDI
  • DNS Pseudo-URLs
  • API Mapping
  • Usage Examples
  • Security Considerations
  • Federation

Introduction

The DNS service provider allows JNDI applications to access information stored in the internet Domain Name System. The provider presents the DNS namespace as a tree of JNDI directory contexts, and DNS resource records as JNDI attributes.

This document describes the features of the DNS service provider, and contains details of how DNS is mapped onto JNDI.

Conformance

The DNS service provider supports the Domain Name System as described in RFC 1034 and RFC 1035, and as updated and clarified by RFC 1123 and RFC 2181. It currently supports the following resource record types and classes:

Type Where Specified
A | RFC 1035
NS | RFC 1035
CNAME | RFC 1035
SOA | RFC 1035
PTR | RFC 1035
MX | RFC 1035
TXT | RFC 1035
HINFO | RFC 1035
AAAA | RFC 1886
NAPTR | RFC 2915
SRV | RFC 2782
Each lookup is initially performed using UDP. If the response is too long to be returned in a UDP packet without being truncated, the lookup is repeated using TCP.

Environment Properties

The following JNDI environment properties are relevant to the DNS service provider. See the JNDI documentation for a description of how properties are initialized using the initial context constructor, system properties, applet parameters, and resource files.

java.naming.authoritative

This property is used to specify whether all responses must be authoritative. If its value is "true", only authoritative responses are accepted from DNS servers; otherwise, all responses are accepted. If this property has not been set, the default is "false". Here is an example that specifies that all responses must be authoritative.

env.put(Context.AUTHORITATIVE, "true");

Note that some information might be made unavailable when you request that only authoritative responses be returned because the DNS protocol does not provide a way to request authoritative information. For example, the DNS service provider might have retrieved nonauthoritative data as the result of a query and is subsequently forced to discard it because only authoritative data may be returned.

java.naming.factory.initial

This property is used to select the DNS service provider as the initial context. It is not used by the provider itself. It specifies the class name of the initial context factory for the provider, and may be set as in the following example:

env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");

java.naming.factory.object

This property contains a colon-separated list of the fully-qualified class names of object factories for transforming objects read from DNS. This mechanism is used to transform objects into forms more useful to the application. See DirectoryManager.getObjectInstance() for details.

java.naming.provider.url

This property specifies the host name and port of the DNS server used by the initial DNS context, as well the initial context's domain name. For details on the URL format see DNS Pseudo-URLs below. For example:

env.put(Context.PROVIDER_URL, "dns://server1.sun.com/java.sun.com");

will cause the provider to use the DNS server at server1.sun.com, and set the initial context's domain name to java.sun.com. If this property is not set, it defaults to "dns:" (all defaults as described in the DNS Pseudo-URLs section are used).

Multiple DNS servers may be specified by setting this property to a space-separated list of URLs. Each of the servers is contacted in turn until one of them responds. Since the initial context has only a single domain name, if multiple URLs are listed then each must contain the same domain part. For example:

env.put(Context.PROVIDER_URL,
    "dns://server1.sun.com/java.sun.com dns://server2.sun.com/java.sun.com");

com.sun.jndi.dns.lookup.attr

Before JNDI invokes an object factory on a DNS context, it by default reads and passes to the factory any internet TXT attributes of the context. This property, if set, names an alternate attribute identifier to use. See Mapping DNS Content to JNDI below for information on the format of attribute identifiers.

com.sun.jndi.dns.recursion

This property is used to specify that recursion is disallowed on DNS queries. If this property has not been set or if it has been set to "true", recursion is allowed; otherwise, recursion is disallowed. Here is an example that specifies that recursion on DNS queries is to be disallowed.

env.put("com.sun.jndi.dns.recursion", "false");

com.sun.jndi.dns.timeout.initial
com.sun.jndi.dns.timeout.retries

These properties are used to alter the timeout-related defaults that the DNS provider uses when submitting UDP queries. The DNS provider submits UDP queries using the following exponential backoff algorithm. The provider submits a query to a DNS server and waits for a response to arrive within a timeout period (1 second by default). If it receives no response within the timeout period, it queries the next server, and so on. If the provider receives no response from any server, it doubles the timeout period and repeats the process of submitting the query to each server, up to a maximum number of retries (4 by default).

The "com.sun.jndi.dns.timeout.initial" property, if set, specifies the number of milliseconds to use as the initial timeout period (i.e., before any doubling). If this property has not been set, the default initial timeout is 1000 milliseconds.

The "com.sun.jndi.dns.timeout.retries" property, if set, specifies the number of times to retry each server using the exponential backoff algorithm described previously. If this property has not been set, the default number of retries is 4.

Here is an example that doubles the initial timeout period while keeping total length of all timeouts roughly unchanged.

env.put("com.sun.jndi.dns.timeout.initial", "2000");
env.put("com.sun.jndi.dns.timeout.retries", "3");

NOTE: On systems earlier than the Java 2 SDK, v 1.4.1, these two properties are ignored and the defaults always apply.

Mapping DNS Content to JNDI

The DNS service provider maps DNS names, nodes, and resource records onto JNDI data types as follows.

Names

DNS domain names are represented by JNDI compound Nameobjects with right-to-left, dot-separated syntax, and with backslash (\) as the escape character. Escape sequences of the form \DDDmay also be used, where DDDis a three-digit decimal value. Names are case-insensitive. A fully-qualified name ending with an explicit root domain label (".") is represented by a compound Nameobject with an empty component in the most-significant position.

Host names are a subset of domain names. Their labels contain only US-ASCII letters, digits, and hyphens, and none may begin or end with a hyphen. While names not conforming to these rules may be valid domain names, they will not be usable by a number of DNS applications, and should in most cases be avoided.

DNS does not specify an encoding (such as UTF-8) to use for characters other than those of US-ASCII. As a consequence, no character in a DNS name will ever have a non-zero high-order byte. When work on internationalizing domain names is finalized, the DNS service provider may be updated to conform to that work.

Nodes and Resource Records

A DNS node is represented by a DirContextobject. The resource records of the node are represented by attributes of the context. For example, if the DNS node sun.com contains an A record with the address 192.9.49.33 and an MX record with the data "10 sun.com", the corresponding JNDI context will have an attribute with identifier "A" and string value "192.9.49.33" and an attribute with identifier "MX" and string value "10 sun.com".

Multiple records of the same type are represented as multi-valued attributes. Records of unsupported types are represented by attributes with numeric identifiers and with byte arrays as values.

Attribute Identifiers

DNS resource record class and type names are mapped onto JNDI attribute identifiers. If a record is in the internet class, the corresponding attribute ID is simply the record's type name. If the type is an unsupported one, its integer value is used instead. If the record is not in the internet class, the class name (or integer class value) is prepended to the attribute ID, separated by a space. For example, the attribute identifier "AAAA" represents an IPv6 address record, and the attribute identifier "HS 97" represents a resource record of type 97 in the Hesiod class.

Superclass attribute identifiers are also defined. These may be useful when querying records using the DirContext.getAttributes() method. If an attribute name has "*" in place of a type name (or class name), it represents records of any type (or class). For example, the attribute identifier "IN *" may be passed to the getAttributes() method to find all internet class records. The attribute identifier "* *" represents records of any class or type.

Attribute identifiers are case-insensitive.

DNS Pseudo-URLs

A URL-like notation is used to represent a DNS server, port, and domain in the java.naming.provider.urlproperty and in URL names passed to the initial context. The format of this pseudo-URL is:
   dns:[//host[:port]][/domain]
The host and port indicate the DNS server to use. If only a host is given, the port defaults to 53; if only a port is given, the host defaults to "localhost". If neither is given, the provider will attempt to determine and use the server(s) configured for the underlying platform, and if successful, will set the java.naming.provider.urlproperty to a space-separated list of URLs constructed using the server(s). (For example, on Solaris or Linux, the provider will read the /etc/resolv.conffile.) If DNS has not been configured on the underlying platform, the host and port default to "localhost" and 53.

NOTE: On systems earlier than the Java 2 SDK, v 1.4.1, the provider does not attempt to use the underlying platform's DNS configuration. If neither host nor port is specified, they default to "localhost" and 53, respectively.

The domain is the DNS domain name of the context, and is not necessarily related to the domain of the server. It defaults to "." (the root domain).

API Mapping

The DNS service provider implements the DirContextinterface. Methods are mapped onto DNS operations as described below. Methods not listed are not supported.
addToEnvironment()

Adds a new property to the environment, or changes an existing property.

close()

Releases internal data structures.

composeName()

Composes two names.

getAttributes()

Returns attributes representing DNS resource records.

getEnvironment()

Returns the environment properties associated with this context.

getNameInNamespace()

Returns the fully-qualified domain name of this node.

getNameParser()

Returns a name parser for DNS domain names.

lookup()
lookupLink()

Returns a DirContext that represents the named node. The DirectoryManager.getObjectInstance() method is invoked on the object before it is returned, in case the application or user has supplied object factories.

list()
listBindings()

The listing of the DNS namespace is implemented using zone transfers, so these operations are potentially compute- and network-intensive, and they may not be supported by all DNS installations. The DirectoryManager.getObjectInstance() method is invoked on an object before it is returned, in case the application or user has supplied object factories; no attributes are passed in.

removeFromEnvironment()

Removes a property from the environment.

Usage Examples

Example 1

In this example we create an initial context representing the sun.com domain, then read the IP addresses (the A records) of two hosts in that domain.
Hashtable env = new Hashtable();
env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
env.put("java.naming.provider.url",    "dns://server1.sun.com/sun.com");

DirContext ictx = new InitialDirContext(env);
Attributes attrs1 = ictx.getAttributes("host1", new String[] {"A"});
Attributes attrs2 = ictx.getAttributes("host2", new String[] {"A"});

Example 2

Instead of using the properties as above, we may pass a DNS pseudo-URL to the methods of the default initial context. In this example we read the MX record of a host in the sun.com domain.

DirContext ictx = new InitialDirContext();
Attributes attrs3 = ictx.getAttributes("dns://server1.sun.com/host3.sun.com",
                                       new String[] {"MX"});

Security Considerations

When a security manager has been installed, the DNS service provider and the application using it must both be granted the following permissions:

permission java.net.SocketPermission "host[:port]", "connect,accept";

for each host/port identified in the java.naming.provider.urlproperty, in URL string names supplied to context methods, and in object references.

Federation

The DNS service provider treats composite names as strongly separated. That is, it processes the first component of the composite name as a DNS domain name and the rest of the components as names in the next naming system(s)(nns). The implicit next naming system is determined dynamically.

For example, here is an example that lists the root of the next naming system federated beyond a DNS context, and one that looks up a name using a multi-component composite name:

// List the root of the nns.
// Note the use of a trailing slash to indicate traversal into the nns.
NamingEnumeration enum = ctx.list("java.sun.com/");

// A composite name lookup.
Object obj = ctx.lookup("sun.com/some/x/y/z");

Class | Where Specified
IN | RFC 1035
HS | RFC 1035
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JNDI/LDAP Service Provider

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

LDAP Naming Service Provider for the
Java Naming and Directory Interface™ (JNDI)

Table of Contents

  1. Introduction
  2. Conformance
  3. Environment Properties
  4. Names
  5. Attributes
  6. URLs
  7. Java Objects
  8. Schema
  9. Exceptions
  10. API Mapping
  11. Federation
  12. Event Notification
  13. SASL Authentication
  14. SSL and Start TLS
  15. Connection Pooling
  16. Security Considerations

1. Introduction

The Lightweight Directory Access Protocol (LDAP) is an Internet standard for accessing directory services. The JNDI/LDAP service provider provides access to servers implementing the LDAP protocols.

This document describes the features of the LDAP service provider. A major portion of the description is couched in terms of how the LDAP service provider behaves with respect to the descriptions in Guidelines for LDAP Service Providers. For examples and descriptions of how to use this provider, please see the JNDI Tutorial.

The LDAP service provider implements the basic features for LDAP access. Additional functionality, such as support for a number of popular LDAP controls, and for storing and reading RMI and CORBA objects, can be added to the basic provider by installing a booster pack, available for download at the JNDI Web site.

2. Conformance

The LDAP service provider conforms to the following standards:
Standard | Supported | Comments
LDAPv3 (RFC 2251) | Yes |
LDAPv3 Attributes (RFC 2252) | Yes |
LDAPv3 Distinguished Names (RFC 2253) | Yes |
LDAP Search Filters (RFC 2254) | Yes |
LDAP URL Format (RFC 2255) | Yes |
LDAPv3 Schema (RFC 2256) | Yes |
LDAPv2 (RFC 1777) | Yes |
LDAP Authentication (RFC 2829) | Yes |
Start TLS Extension (RFC 2830) | Yes |
DIGEST-MD5 (RFC 2831) | Yes |
Manage Referral Control (RFC 3296) | Yes |
Paged Results Control (RFC 2696) | Yes |
Sort Control (RFC 2891) | Yes |

3. Environment Properties

Descriptions of JNDI, LDAP-specific, and SASL-specific properties are found in Guidelines for LDAP Service Providers.

3.1 JNDI Properties

The LDAP service provider supports the following JNDI environment properties:
Property | Supported | Comments
java.naming.batchsize | Yes | Default value is 1.
java.naming.factory.control | Yes |
java.naming.factory.initial | Yes | Specify com.sun.jndi.ldap.LdapCtxFactory to use the LDAP service provider as the initial context.
java.naming.factory.object | Yes |
java.naming.factory.state | Yes |
java.naming.language | No | Ignored by the provider.
java.naming.provider.url | Yes | On systems earlier than the Java 2 SDK, v 1.4.1, can contain only a single URL. On systems earlier than the Java 2 SDK, v 1.4.2, cannot contain LDAPS URLs.
java.naming.referral | Yes |
java.naming.security.authentication | Yes | simple, none, list of SASL mechanisms
java.naming.security.credentials | Yes |
java.naming.security.principal | Yes |
java.naming.security.protocol | Yes | ssl

3.2 LDAP-specific Properties

The provider supports the following LDAP-specific environment properties:
Property | Supported | Comments
java.naming.ldap.attributes.binary | Yes |
java.naming.ldap.control.connect | Yes |
java.naming.ldap.deleteRDN | Yes |
java.naming.ldap.derefAliases | Yes |
java.naming.ldap.factory.socket | Yes | Default value is javax.net.ssl.SSLSocketFactory when the java.naming.security.protocol property is set to ssl. See the SSL Section for details.
java.naming.ldap.ref.separator | Yes |
java.naming.ldap.referral.limit | Yes |
java.naming.ldap.typesOnly | Yes |
java.naming.ldap.version | Yes |

3.3 SASL-specific Properties

The provider supports the following SASL-specific environment properties:
Property | Supported | Comments
java.naming.security.sasl.authorizationId | Yes |
java.naming.security.sasl.callback | Yes |
java.naming.security.sasl.realm | Yes |
javax.security.sasl.qop | Yes |
javax.security.sasl.strength | Yes | Cipher selected depends on the ciphers available from the Java Cryptography Extension (JCE) service providers in the Java platform.
javax.security.sasl.maxbuffer | Yes |
javax.security.sasl.server.authentication | Yes |
javax.security.sasl.policy.forward | Yes |
javax.security.sasl.policy.credentials | Yes |
javax.security.sasl.policy.noplaintext | Yes |
javax.security.sasl.policy.noactive | Yes |
javax.security.sasl.policy.nodictionary | Yes |
javax.security.sasl.policy.noanonymous | Yes |

3.4 Provider-specific Properties

The LDAP service provider defines the following provider-specific environment properties:
com.sun.jndi.ldap.connect.pool

This property is used to specify that a pooled connection should be used when creating the initial context instance. If its value is "true", the provider will use a pooled connection if the parameters for creating a connection (referred to as the connection request) meet the criteria set forth by the connection pool configuration. If this property has not been set, or if it has been set to any other value, or if the connection request does not meet the criteria, the provider will not use a pooled connection. See the Connection Pooling section for more information on connection pooling.

For example, the following code

env.put("com.sun.jndi.ldap.connect.pool",
"true");
directs the LDAP provider to use a pooled connection when creating an initial context.

NOTE: On systems earlier than the Java 2 SDK, v 1.4.1, connection pooling is not supported and therefore, this property is ignored.

com.sun.jndi.ldap.connect.timeout

The value of this property is the string representation of an integer representing the connection timeout in milliseconds. If the LDAP provider cannot establish a connection within that period, it aborts the connection attempt. The integer should be greater than zero. An integer less than or equal to zero means to use the network protocol's (i.e., TCP's) timeout value.

If this property is not specified, the default is to wait for the connection to be established or until the underlying network times out.

For example,

env.put("com.sun.jndi.ldap.connect.timeout", "500"); causes the LDAP service provider to abort the connection attempt if a connection cannot be established in half a second.

When connection pooling has been requested for a connection, this property also determines the maximum wait time for a connection when all connections in the pool are in use and the maximum pool size has been reached. If the value of this property is less than or equal to zero under such circumstances, the provider will wait indefinitely for a connection to become available; otherwise, the provider will abort the wait when the maximum wait time has been exceeded. See the Connection Pooling section for details.

NOTE: On systems earlier than the Java 2 SDK, v 1.4, this property is ignored because there is no support in the SDK for connection timeouts.

com.sun.jndi.ldap.read.timeout

The value of this property is the string representation of an integer representing the read timeout in milliseconds for LDAP operations. If the LDAP provider cannot get a LDAP response within that period, it aborts the read attempt. The integer should be greater than zero. An integer less than or equal to zero means no read timeout is specified which is equivalent to waiting for the response infinitely until it is received.

If this property is not specified, the default is to wait for the response until it is received.

For example,

env.put("com.sun.jndi.ldap.read.timeout", "5000"); causes the LDAP service provider to abort the read attempt if the server does not respond with a reply within 5 seconds.

NOTE: On systems earlier than the Java SDK, v 6.0, this property is ignored because there is no support in the SDK for read timeouts.

com.sun.jndi.ldap.netscape.schemaBugs

The Netscape Directory Server 4.0 and earlier releases do not support schema entries that comply with RFC 2252. Specifically, contrary to RFC 2252, the Netscape server requires OIDs (such as those for SUP and SYNTAX) be delimited by single quotes and MUST/MAY lists be enclosed by parentheses. When you update the schema of the Netscape Directory Server 4.0, you need to use this property to get around these problems.

The following values are defined for this property:

true
activate the workaround.
false
do not activate the workaround.

If this property is not set then its default value is false.

For example,

env.put("com.sun.jndi.ldap.netscape.schemaBugs", "true");
activates the workaround.

NOTE 1: This property may only be passed to the initial context and becomes fixed for the provider. It is unaffected by the addToEnvironment or removeFromEnvironment methods.

NOTE 2: If you are using Netscape Directory Server 4.1, do not use this property. The 4.1 server has problems parsing object class definitions that contain MUST/MAY clauses without parentheses. If you are creating or modifying an object class definition that contains a single MUST/MAY item, work around the bug by adding a superfluous value (such as 'objectClass') to the MUST/MAY list.

com.sun.jndi.ldap.trace.ber

The value of this property is a java.io.OutputStream object into which a hexadecimal dump of the incoming and outgoing LDAP ASN.1 BER packets is written. No default is defined for this property.

For example,

env.put("com.sun.jndi.ldap.trace.ber",
System.out);
directs the LDAP protocol trace to the standard output stream.

NOTE: This property may only be passed to the initial context and becomes fixed for the provider. It is unaffected by the addToEnvironment or removeFromEnvironment methods.

4. Names

The LDAP service provider supports names in accordance with the description in Guidelines for LDAP Service Providers. It supports LDAP distinguished names in the following formats:
Distinguished Name format | Comments
String | Treat as composite name. Process the first component of the composite name as a distinguished name. Use rest of the components for federation.
Name | If instance of CompositeName, treat as composite name, which means process the first component of the composite name as a distinguished name and use the rest for federation. Otherwise, treat as parsed LDAP name, where each component of Name is a component of the LDAP name as defined in RFC 2253.
LDAP URL String | When passed to the initial context, the LDAP URL string is interpreted according to RFC 2255, and its distinguished name component interpreted according to RFC 2253.
LDAPS URL String | When passed to the initial context, the LDAPS URL string is interpreted like an LDAP URL, except that an SSL connection is used to communicate with the server. NOTE: On systems earlier than the Java 2 SDK, v 1.4.2, the LDAP service provider does not recognize LDAPS URLs.

The name parser returned by an invocation of getNameParser() returns a parser that, when given a string name, parses it into components in accordance with RFC 2253.

5. Attributes

The LDAP service provider supports attributes in accordance with the description in Guidelines for LDAP Service Providers. It supports the following formats for specifying LDAP attribute values:
Attribute value format | Supported | Comments
String values | Yes |
byte[] values | Yes |

Some LDAP servers support attribute subtyping, attribute name synonyms, and language codes for specifying language preferences for attribute values. In such cases, the attribute name returned by an LDAP server may be different from the one which was requested.

In LDAP, attribute names are case-insensitive. Therefore, when creating a collection of attributes to be passed as a parameter to JNDI operations, it is recommended to use a case-insensitive attributes class. For example,

Attributes attrs = new BasicAttributes(true); // ignoreCase=true

For all attribute values, regardless of whether they are String or byte[], you need to know the syntax and format of the attribute value. You can typically find this out by reading the schema document in which the attribute and its syntax is defined.

When attributes are supplied as arguments to JNDI calls then they must satisfy whatever schema is enforced at the LDAP directory. In particular, the objectClass attribute is normally required when creating a new LDAP entry (for example, when using Context.bind, Context.rebind or DirContext.createSubcontext).

6. URLs

6.1 Uses

The LDAP service provider supports URLs in accordance with the description in Guidelines for LDAP Service Providers. It supports both LDAP and LDAPS URLs.

It supports the following use of URLs:

URL usage | Supported | Comments
LDAP and LDAPS URLs to configure the LDAP service provider. | Yes |
URLs passed as names to the InitialDirContext methods. | Yes |
URLs in LDAP referrals | Yes | The scope component of LDAP/LDAPS URLs is supported. The attributes, filter and extensions components are ignored.
URLs returned as names in list, listBindings, and search enumerations. | Yes |
URLs linking federated namespaces. | Yes |

NOTE: On systems earlier than the Java 2 SDK, v 1.4.2, the LDAP service provider does not recognize or return LDAPS URLs.

6.2 Automatic Discovery of LDAP Service

The LDAP service provider supports the use of DNS configuration for automatically discovering the LDAP service. When an LDAP/LDAPS URL in the above usage cases is missing the hostname and port but has a non-empty distinguished name, the LDAP service provider will attempt to locate the LDAP servers to use as described in the Guidelines for LDAP Service Providers.

For example, given a URL of ldap:///dc=example,dc=com, the service provider will try to locate the DNS SRV records for _ldap._tcp.example.com. If the provider finds such records, it will then extract and use the hostnames and ports of the LDAP servers from the records. The order in which it uses these records follows the algorithm described in the Internet draft draft-ietf-ldapext-locate-08.txt.

For locating the DNS SRV records of the LDAP service, the LDAP service provider uses the DNS service configured for the underlying platform (on Solaris or Linux, for example, the DNS client configuration is read from the /etc/resolv.conf file). If DNS has not been configured for the underlying platform, the LDAP service provider will use localhost and 53 as the hostname and port of the DNS server. If no DNS service is available, or if the DNS service does not have the LDAP service's SRV records, the LDAP service provider will use localhost as the hostname, and 389 as the port for a plain connection and 636 as the port for an SSL connection.

NOTE 1: On systems earlier than the Java 2 SDK, v 1.4.1, unspecified hostname and port always default to localhost and 389, respectively; no attempt is made to use DNS.

NOTE 2: On systems earlier than the Java 2 SDK, v 1.4.2, the default port is always 389 regardless of whether SSL is being used.

7. Java Objects

The LDAP service provider supports storing and reading the following types of objects, as specified in Guidelines for LDAP Service Providers.
Storable/Readable Objects | Supported | Comments
Reference objects | Yes |
Referenceable objects | Yes |
Serializable objects | Yes |
DirContext objects | Yes |

See the JNDI Tutorial for examples.

8. Schema

The LDAP service provider supports the following schema bindings, as specified in Guidelines for LDAP Service Providers.
Schema Tree | Supported | Comments
AttributeDefinition | Yes |
ClassDefinition | Yes |
SyntaxDefinition | Yes |
MatchingRule | Yes |
ExtensionDefinition | No |
ControlDefinition | No |
SASLMechanism | No |

9. Exceptions

The LDAP service provider maps LDAP error codes to JNDI exceptions according to Guidelines for LDAP Service Providers.

10. API Mapping

The LDAP service provider maps the following JNDI API methods to LDAP according to Guidelines for LDAP Service Providers:
Mapping for Context methods | Supported | Comments
addToEnvironment | Yes |
bind | Yes |
close | Yes |
composeName | Yes |
destroySubcontext | Yes |
getEnvironment | Yes |
getNameInNamespace | Yes |
getNameParser | Yes |
list | Yes |
listBindings | Yes |
lookup | Yes | Does not process LinkRef specially.
lookupLink | Yes |
rebind | Yes |
removeFromEnvironment | Yes |
rename | Yes |
unbind | Yes |
Mapping for DirContext methods | Supported | Comments
bind | Yes |
createSubcontext | Yes |
destroySubcontext | Yes |
getAttributes | Yes |
getSchema | Yes |
getSchemaClassDefinition | Yes |
modifyAttributes | Yes |
rebind | Yes |
search | Yes |
Mapping for LdapContext methods | Supported | Comments
extendedOperation | Yes |
getRequestControls | Yes |
getResponseControls | Yes |
newInstance | Yes |
reconnect | Yes |
setRequestControls | Yes |
Mapping for EventDirContext methods | Supported | Comments
addNamingListener | Yes |
removeNamingListener | Yes |
targetMustExist | Yes |

11. Federation

The LDAP service provider supports federation in accordance with the description in Guidelines for LDAP Service Providers. It supports the following federation techniques:
Federation Technique | Supported | Comments
Junction | Yes | Except when subordinate naming system is another LDAP system
Implicit Next Naming System Pointer | Yes |

The LDAP service provider treats composite names as strongly separated. That is, it processes the first component of the composite name as a distinguished name and the rest of the components as names in the next naming system(s). For example, here are examples that lists the root of the next naming system federated beyond an LDAP context and looks up a name using a multicomponent composite name:

// List the root of the nns,
// Note use of the trailing slash to indicate traversal into the nns
NamingEnumeration enum = ctx.list("cn=objects,ou=Sales/");

// A composite name lookup
Object obj = ctx.lookup("cn=objects,ou=Sales/some/x/y/z");

12. Event Notification

The LDAP service provider supports event notification in accordance with the description in Guidelines for LDAP Service Providers. It supports the following events:
Event | Supported | Comments
Namespace change notification | Yes | Uses the persistent search control*
Object change notification | Yes | Uses the persistent search control*
Unsolicited notification | Yes |

* The persistent search control is defined in the IETF Internet-Draft draft-ietf-ldapext-psearch-03.txt.

13. SASL Authentication

The LDAP service provider supports SASL authentication in accordance with the description in Guidelines for LDAP Service Providers.

The LDAP service provider supports the following SASL mechanisms.

  • EXTERNAL (RFC 2222). This mechanism obtains authentication information from an external source (such as SSL/TLS or IPsec).
  • DIGEST-MD5 (RFC 2831) is for Digest Authentication.
  • GSSAPI (RFC 2222) is for Kerberos V5 authentication.
In addition to these mechanisms, the provider supports additional SASL mechanisms made available via the framework defined in the Java SASL API (JSR 28 Public Review Draft), with the exception that the package is named com.sun.security.sasl.preview instead of javax.security.sasl.

14. SSL and Start TLS

14.1 SSL

The LDAP service provider supports SSL in accordance with the description in Guidelines for LDAP Service Providers. It uses the default socket factory javax.net.ssl.SSLSocketFactory unless the java.naming.ldap.factory.socket property has been set to the class name of some other socket factory.

When SSL is being used and no port has been specified, 636 is used as the default port.

NOTE: On Java 2 SDK, v 1.4.1 and earlier systems, the default port is always 389, regardless of whether SSL is being used.

14.2 Start TLS

The LDAP provider supports the the "Start TLS" extension ("1.3.6.1.4.1.1466.20037") by supplying a concrete implementation of the StartTlsResponse abstract class. Hostname verification is performed as per the Guidelines for LDAP Service Providers.

15. Connection Pooling

NOTE: Connection pooling is supported only on the Java 2 SDK, v 1.4.1 and later releases.

15.1 Overview

The LDAP service provider supports connection pooling by maintaining pools of previously used connections. Whenever the LDAP provider needs a connection (and the application has requested pooling), it gets a connection from the pool. If an existing connection is available, it will be used. If no existing connection is available, a new connection is created and used. When the provider is done with the connection, the connection is marked idle and can be reused.

An application requests connection pooling by adding the property, com.sun.jndi.ldap.connect.pool, to the environment properties passed to the initial context constructor. An application can decide whether to use pooling on a per-context basis by using environment properties with and without this property. This same mechanism is used to control whether pooled connections are used for referral handling and processing of LDAP/LDAPS URLs passed to the initial context. For example, when this property is present in the environment when the provider is processing a referral, the provider will use a pooled connection for the referral.

Here is sample code that requests that connection pooling be used for a new initial context and all contexts derived from it.

Hashtable env = new Hashtable();
env.put("com.sun.jndi.ldap.connect.pool", "true");
env.put(Context.PROVIDER_URL, url);
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
DirContext ctx = new InitialDirContext(env);
...

Only the addition of the single property, com.sun.jndi.ldap.connect.pool, is required; no other changes are required to the application.

The LDAP provider keeps track of whether a connection is being used through indications from the application. It assumes that an application that is maintaining an open context handle is using the connection. Therefore, in order for the LDAP provider to properly manage the pooled connections, the application must be diligent about invoking Context.close() on contexts that it no longer needs.

Bad connections are automatically detected and removed from the pool. The probability of a context ending up with a bad connection is the same regardless of whether connection pooling is used.

15.2 When Not to Use Pooling

Pooled connections are intended to be reused. Therefore, an application that plans on performing operations on a context that might alter the underlying connection's state should not use connection pooling for the context. Specifically, if an application is planning to use the Start TLS extended operation on a context, or is planning to change security-related properties (such as java.naming.security.principal or java.naming.security.protocol) after the initial context has been created, it should not use connection pooling for that context. Using connection pooling under such circumstances might compromise the security of the application and/or create unexpected behavior.

15.3 Global Configuration

Connection pooling is configured and maintained per Java runtime. Connections are not shared across different runtimes. To use connection pooling, no configuration is required. Configuration is necessary only if you want to customize how pooling is done, such as controlling the size of the pools and which connections are pooled.

Connection pooling is configured by a number of System properties at runtime startup time. Note that these are System properties, not environment properties and that they affect all connection pooling requests.

Here is a summary of the system properties. They are described in more detail in the rest of this section.

System Property Name | Description | Default
com.sun.jndi.ldap.connect.pool.authentication | A list of space-separated authentication types of connections that may be pooled. Valid types are "none", "simple", and "DIGEST-MD5". | "none simple"
com.sun.jndi.ldap.connect.pool.debug | A string that indicates the level of debug output to produce. Valid values are "fine" (trace connection creation and removal) and "all" (all debugging information). |
com.sun.jndi.ldap.connect.pool.initsize | The string representation of an integer that represents the number of connections per connection identity to create when initially creating a connection for the identity. | 1
com.sun.jndi.ldap.connect.pool.maxsize | The string representation of an integer that represents the maximum number of connections per connection identity that can be maintained concurrently. | no maximum size
com.sun.jndi.ldap.connect.pool.prefsize | The string representation of an integer that represents the preferred number of connections per connection identity that should be maintained concurrently. | no preferred size
com.sun.jndi.ldap.connect.pool.protocol | A list of space-separated protocol types of connections that may be pooled. Valid types are "plain" and "ssl". | "plain"
com.sun.jndi.ldap.connect.pool.timeout | The string representation of an integer that represents the number of milliseconds that an idle connection may remain in the pool without being closed and removed from the pool. | no timeout

Here is an example that sets the maximum pool size to 20, the preferred pool size to 10, and the idle timeout to 5 minutes for pooled connections.

# java -Dcom.sun.jndi.ldap.connect.pool.maxsize=20 \
       -Dcom.sun.jndi.ldap.connect.pool.prefsize=10 \
       -Dcom.sun.jndi.ldap.connect.pool.timeout=300000 \
    YourProgram

15.3.1 What Gets Pooled

The LDAP provider will use a pooled connection only if the application has requested it and the request for the connection meets the pooling criteria. The application requests that a connection be pooled by using the com.sun.jndi.ldap.connect.pool environment property. The default pooling criteria is that plain (non-SSL) connections that use simple or no authentication are allowed to be pooled. The pooling criteria can be adjusted to include SSL connections and the DIGEST-MD5 authentication type by using System properties. A connection that has enabled protocol tracing (via the com.sun.jndi.ldap.trace.ber environment property) cannot be pooled. For pooling connections from a custom socket factory see Pooling Custom Socket Factory Connections

To allow SSL connections to be pooled, include the string "ssl" in the com.sun.jndi.ldap.connect.pool.protocol System property. For example, to allow both plain and SSL connections to be pooled, set this System property to the string "plain ssl".

To allow DIGEST-MD5 connections to be pooled, include the string "DIGEST-MD5" in the com.sun.jndi.ldap.connect.pool.authentication System property. For example, to allow connections of anonymous, simple and DIGEST-MD5 authentication types to be pooled, set this System property to the string "none simple DIGEST-MD5".

15.3.2 How Connections are Pooled

The LDAP provider maintains pooled connections so that they can be reused. When an application requests to use a pooled connection, the LDAP provider needs to determine whether the request can be satisfied by an existing pooled connection. It does this by assigning a connection identity to each pooled connection and checking whether the incoming request has the same connection identity as that of one of its pooled connections.

A connection identity is the set of the parameters required to create a possibly authenticated LDAP connection. Its composition depends on the authentication type of the request, as shown in the following table.

Authentication type Connection identity contents
none
  • connection controls
  • hostname, port number and scheme as specified in the java.naming.provider.url property, referral, or URL supplied to the initial context
  • the contents of the following properties:
    java.naming.security.protocol
java.naming.ldap.version
simple
  • all of the information listed for anonymous
  • the contents of following properties:
    java.naming.security.principal
java.naming.security.credentials
DIGEST-MD5
  • all of the information listed for simple
  • the contents of following properties:
    java.naming.security.sasl.authorizationId
java.naming.security.sasl.realm
javax.security.sasl.qop
javax.security.sasl.strength
javax.security.sasl.server.authentication
javax.security.sasl.maxbuffer
javax.security.sasl.policy.noplaintext
javax.security.sasl.policy.noactive
javax.security.sasl.policy.nodictionary
javax.security.sasl.policy.noanonymous
javax.security.sasl.policy.forward
javax.security.sasl.policy.credentials

15.3.3 Pooling Custom Socket Factory Connections

Pooling of connections from a custom socket factory is allowed when java.naming.ldap.factory.socket environment property is set. For the custom socket factory to be pooled the socket factory class must implement the Comparator interface. The LDAP Service Provider calls Comparator.compare() method for equality comparison of the socket factories whose connections are being checked for equality by the pooling mechanism. The socket factory comparison should ensure that the socket factory parameters that influence the connection equality are being compared. This comparison is made in addition to the connection identity comparison described in How Connections are Pooled. A custom socket factory class should have the following structure if its connections were to be pooled:
    public class CustomSocketFactory extends SocketFactory
                implements Comparator<SocketFactory> {
       :
       :
       public int compare(SocketFactory sf1, SocketFactory sf2) {
           :
           :
           // do whatever comparison that's required
       }
    }

If the socket factory class does not implement Comparator interface, the connections from that socket factory class do not get pooled. This requirement for implementing the Comparator interface is to ensure that the LDAP Service Provider does the necessary checks when comparing connections from different socket factories whose implementation is not known to the provider.

15.3.4 Pool Sizes

The LDAP provider maintains pools of connections; each pool holds connections (either in-use or idle) that have the same connection identity. There are three sizes that affect the management of each pool. These sizes are global and affect all pools.

The initial pool size is the number of connections per connection identity that the LDAP service provider creates when first creating the pool (which corresponds to when the application first requests a pooled connection for that connection identity). Authentication of each connection in the pool is performed on demand, as the connection gets used. By default, the initial pool size is 1 and can be changed by using the System property com.sun.jndi.ldap.connect.pool.initsize. It is typically used at application start-up time to prime the pool with a certain number of connections to a server.

The maximum pool size is the maximum number of connections per connection identity that can be maintained concurrently by the LDAP service provider. Both in-use and idle connections contribute to this number. When the pool size reaches this number, no new connection for the corresponding connection identity may be created until a connection in the pool has been removed (i.e., the physical connection is closed). When the pool size reaches the maximum and all of the connections in the pool are in use, the application's request for a connection from that pool is blocked until a connection in the pool either becomes idle or is removed. A maximum pool size of 0 means that there is no maximum size: A request for a pooled connection will use an existing pooled idle connection or a newly created pooled connection.

The preferred pool size is the preferred number of connections per connection identity that the LDAP service provider should maintain. Both in-use and idle connections contribute to this number. When an application requests the use of a pooled connection and the pool size is less than the preferred size, the LDAP provider will create and use a new pooled connection regardless of whether an idle connection is availble. When an application is finished with a pooled connection (by invoking Context.close() on all contexts that share the connection) and the pool size is greater than the preferred size, the LDAP provider will close and remove the pooled connection from the pool. A preferred pool size of 0 means that there is no preferred size: A request for a pooled connection will result in a newly created connection only if no idle ones are available.

Note that the maximum pool size overrides both the initial and preferred pool sizes. For example, setting the preferred pool size greater than the maximum pool size is effectively setting it to the maximum pool size.

15.3.5 Idle Connections

When the application is finished with a pooled connection (by invoking Context.close() on all contexts that share the connection), the underlying pooled connection is marked as idle, waiting to be reused. By default, idle connections remain in the pool indefinitely until they are garbage-collected. If the "com.sun.jndi.ldap.connect.pool.timeout" System property has been set, the LDAP provider will automatically close and remove pooled connections that have been idle for more than the specified period.

15.4 Per-Context Configuration

15.4.1 Enabling Pooling

To use pooling, set the com.sun.jndi.ldap.connect.pool property to "true" in the environment properties passed to the initial context constructor. The provider will apply the pooling criteria to the supplied environment properties and decide whether to use pooling for that context. If the provider determines that a connection cannot be pooled, it creates and uses an unpooled connection for the context.

If this property is omitted, the context will not use connection pooling.

15.4.2 Connection Timeout

The com.sun.jndi.ldap.connect.timeout environment property is used to specify a timeout period for establishment of the LDAP connection. This property affects the TCP timeout when opening a connection to an LDAP server. When connection pooling has been requested, this property also specifies the maximum wait time for a connection when all connections in pool are in use and the maximum pool size has been reached.

If this property has not been specified, the LDAP provider will wait indefinitely for a pooled connection to become available, and to wait for the default TCP timeout to take effect when creating a new connection.

Note that this property is different from the System property com.sun.jndi.ldap.connect.pool.timeout, which is related to the removal of idle pooled connections.

16. Security Considerations

When a security manager has been installed, you must grant to the application using JNDI and the LDAP service provider the following permissions:
permission java.net.SocketPermission "host[:port]", "connect";

For each host/port identified in the java.naming.factory.initial property and in URL string names supplied to context methods.

permission java.net.SocketPermission "host[:port]", "connect,accept";

For each host/port named in the URL strings in References and javaCodebase attributes stored with Serializable objects.

If you are using SASL authentication and will be setting the SASL client factory programmatically, grant your application the following permission.
permission java.lang.RuntimePermission "setFactory"
If you use the "GSSAPI" SASL mechanism, you need the following additional permissions.
permission javax.security.auth.AuthPermission "createLoginContext.appClassName";
permission javax.security.auth.AuthPermission "doAsPrivileged";

For the application class that's going to be logging in and invoking the doAsPrivileged method.

permission java.net.SocketPermission "host[:port]", "connect";

For the host/port of the Kerberos Key Distribution Center (KDC).

permission javax.security.auth.kerberos.ServicePermission "krbtgt/realm@realm", "initiate";
permission javax.security.auth.kerberos.ServicePermission "ldap/fully-qualified-hostname@realm", "initiate";

For the realm and host of the LDAP service and KDC.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JNDI/LDAP Supplement: Guidelines for LDAP Service Providers

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
JNDI Implementor Guidelines for LDAP Service Providers

Draft 0.4.2

Table of Contents
1. Introduction
2. Conformance
3. Environment Properties
4. Names
5. Attributes
6. URLs
7. Java Objects
8. Schema
9. Exceptions
10. API Mapping
11. Federation
12. SASL
13. Extensions and Controls
14. Event Notification
15. SSL

1. Introduction

This document specifies guidelines that developers creating LDAP service providers and service providers that support LDAP-like features should follow. By following these guidelines, developers can produce implementations that JNDI API users can configure and use with minimal differences.

Not all of the features described in this document must be supported by an LDAP service provider. However, if a feature is supported, it should be supported in the way described by this document.

2. Conformance

An LDAP service provider that supports LDAP version 3 (LDAPv3) conforms to:
  • RFC 2251 and related specifications.
An LDAP service provider that supports LDAP version 2 (LDAPv2) conforms to:
  • RFC 1777 and related specifications.

3. Environment Properties

Environment properties are the means by which JNDI application users configure and affect the behavior of JNDI service providers. Consequently, service providers must interpret and handle environment properties in the same way.

There are four types of environment properties that affect LDAP service providers:

  • Standard JNDI environment properties
  • LDAP-specific environment properties
  • Provider-specific environment properties
  • Feature-specific environment properties

3.1 Overview

3.1.1 Initialization

When creating an initial context, environment properties can be passed as an argument to the constructor or may be initialized as specified in the JNDI documentation.

In particular, if any of the following properties is not supplied in the environment properties then it is sought from the system properties, applet parameters, and both provider and application resource files (in that order):

  • java.naming.factory.control
  • java.naming.factory.initial
  • java.naming.factory.object
  • java.naming.factory.state
  • java.naming.provider.url
In the case of the control, object and state factory properties, if more than one occurrence of the property is located, then its values are concatenated into a single list. In the case of the url property and all other properties, only the first occurrence is used.

A context's environment properties can be examined using the Context.getEnvironment method.

3.1.2 Modification

A context's environment properties may be changed using the Context.addToEnvironment and Context.removeFromEnvironment methods.

3.1.3 Scope

With the exception of the java.naming.provider.url and java.naming.factory.initial properties, changing a property using the Context.addToEnvironment or Context.removeFromEnvironment methods affects the context instance on which the method is invoked. For example, if you specify new credentials for a context to use, subsequent methods invoked on that context that require communication with the server will use those new credentials (perhaps internally by first creating a new connection to the server). These updated environment properties are inherited by context instances that are subsequently derived from the affected context instance, but do not otherwise affect other context instances that were in existence prior to the update.

3.1.4 Timeliness

When a change is made to the environment properties, there is no requirement that the change be verified and acted upon at the time the Context.addToEnvironment or Context.removeFromEnvironment method is invoked. The only requirement is that the change (or changes) be effective the next time an operation that uses that property is invoked.

3.1.5 Defaults

This specification defines defaults for the environment properties. In a few cases, the default is determined by the service provider. If a context does not have a particular environment property, it behaves as if it has that environment property with its default value.

When a property is removed from the environment properties of a context, the context assumes the default behavior specified for that property. This does not necessarily mean that the default value must be recorded as the property's value. The removal may also be indicated by the absence of the property from the context's environment properties.

3.1.6 Acceptable Values

This specification defines acceptable values for the environment properties. Some environment properties have a fixed set of acceptable values while others have values that must follow a particular syntax. If an unacceptable value is presented, a property-specific exception will be thrown (for example, ConfigurationException, IllegalArgumentException, or AuthenticationNotSupportedException). In some cases, it might be reasonable for the service provider to accept additional values than those specified, in which case, those values should be documented.

3.2 JNDI Properties

LDAP service providers should process the JNDI environment properties according to the following specifications. In the examples given, env is an instance of Hashtable that holds the environment properties used to create an initial context.

java.naming.batchsize

The value of this property is a string of decimal digits that specifies the batch size of search results returned by the server.

This property affects the blocking behaviour of the Context.list, Context.listBindings, and DirContext.search methods and the NamingEnumeration objects that they return. It does not affect how many items are returned in the enumeration; it only affects how the items are batched or read at the LDAP protocol level.

A setting of zero means that the provider should block until all results have been received. A setting of an integer n greater than zero means that the provider should block until n results have been received from the server or until the enumeration terminates, whichever produces the fewer number of results. After the application has read n results (using NamingEnumeration.next or NamingEnumeration.nextElement), the provider should read n more results from the server or until the enumeration terminates, whichever produces the fewer number of results.

If this property is not set then its default value is implementation-specific.

For example, the following code specifies that the provider should block until 24 entries have been read from the server or until the enumeration terminates, whichever produces the fewer number of results:

env.put(Context.BATCHSIZE, "24");
java.naming.factory.control

The value of this property is a colon-separated list of fully qualified class names of control factory classes.

The factories are responsible for narrowing the class of response controls. They create specific response controls from the generic response controls generated by the provider.

No default value is defined for this property.

For example, the following code sets the ResponseControlFactory class as the control factory to try:

env.put(LdapContext.CONTROL_FACTORIES,
        "com.sun.jndi.ldap.ctl.ResponseControlFactory");
java.naming.factory.initial

The value of this property is the fully qualified class name of the factory class which creates the initial context for the LDAP service provider.

It is used to select a particular LDAP service provider; it's not actually used by the provider itself. This property need not be set when the name argument to initial context methods is a URL.

No default value is defined for this property.

For example, the following code selects Sun's LDAP provider:

env.put(Context.INITIAL_CONTEXT_FACTORY,
        "com.sun.jndi.ldap.LdapCtxFactory");
java.naming.factory.object

The value of this property is a colon-separated list of fully qualified class names of object factory classes.

The factories are responsible for creating specific objects from the LDAP entries returned by the provider. For example, a Person object factory might generate a Person object from an LDAP entry of object class person. Object factories behave in the opposite way to state factories in that they generate objects from LDAP attributes.

No default value is defined for this property.

For example,

env.put(Context.OBJECT_FACTORIES,
        "com.sun.jndi.ldap.obj.PersonFromLDAP");
sets the PersonFromLDAP class as the object factory to try.
java.naming.factory.state

The value of this property is a colon-separated list of fully qualified class names of state factory classes.

The factories are responsible for creating an object's state (for storing) from the object itself. For example, a Person state factory might generate an LDAP entry of object class person from a Person object. State factories behave in the opposite way to object factories in that they generate LDAP attributes from objects.

No default value is defined for this property.

For example,

env.put(Context.STATE_FACTORIES,
        "com.sun.jndi.ldap.obj.PersonToLDAP");

sets the PersonToLDAP class as the state factory to try.

java.naming.language

The value of this property is a string language tag according to RFC 1766.

This property indicates a preference for a particular natural language. A provider may adjust its LDAP requests and responses according to the value of this property.
The affect of this property is implementation-specific. No default value is defined.
For example:
env.put(Context.LANGUAGE, "ja-JP");
indicates a preference for Japanese.
java.naming.provider.url

The value of this property is a list of space-separated LDAP or LDAPS URL strings, each of which specifies the hostname and port number of the LDAP server, and the root distinguished name of the naming context to use. An LDAP URL specifies the use of a plain (i.e., unprotected) connection; an LDAPS URL specifies the use of an SSL connection. If the list contains more than one URL, the provider should attempt to use each URL in turn until it is able to create a successful connection, and after creation, set the property to the successful URL.

The default hostname is localhost; the default port is 389 for plain connections and 636 for SSL connections. The default root distinguished name is the empty string. If this property is not set, or if either the hostname or port number is omitted, then the default values are used in place of the missing information. If both the hostname and port are missing but a non-empty distinguished name is present in the URL, then the provider should use the distinguished name to determine the hostname and port of the LDAP server(s) as described in the URLs section and when a connection has been established successfully, set the java.naming.provider.url property to a URL constructed using the successful hostname, port and distinguished name. See also the URLs section for information on how the provider should treat other information found in the URL.

For example:

env.put(Context.PROVIDER_URL, "ldap://secserver:636");
specifies that the LDAP server is running on a host named secserver at port 636.

NOTE: Changing this property using the Context.addToEnvironment or Context.removeFromEnvironment methods does not affect the context. It is only used by the initial context constructors.

java.naming.referral

The value of this property is a string that specifies how referrals shall be handled by the provider. The following values are defined for this property:

follow
automatically follow any referrals.
throw
throw a ReferralException for each referral.
ignore
ignore referrals if they appear in results. A PartialResultException is thrown to indicate an incomplete result. In addition, for LDAPv3 servers, the provider shall request that referrals be treated as ordinary attributes when they appear in entries. This is achieved by sending a non-critical ManageDsaIT (RFC 3296) LDAP control with each LDAP request. LDAP servers which do not support this LDAP control will simply ignore it and process the request as normal.

See the URLs section for information on how to treat multiple URLs found in a single referral entry.

If this property is not set then its default value is ignore.

For example:

env.put(Context.REFERRAL, "throw");
specifies that referrals encountered during an LDAP operation should throw a ReferralException to the application.
java.naming.security.authentication

The value of this property is a string that specifies the authentication mechanism(s) for the provider to use. The following values are defined for this property:

none
use no authentication (anonymous bind).
simple
use simple authentication (a cleartext password).
A space-separated list of one or more SASL mechanism names:
use the first available SASL mechanism in the list that conforms to the specified policy requirements

See the SASL section for information on how this property is used for SASL authentication. See RFC 2829 for information on LDAP authentication mechanisms.

If this property is not set then its default value is none, unless the java.naming.security.credentials property is set, in which case the default value is simple. If this property is set to a value that the provider does not recognize or support, it should throw AuthenticationNotSupportedException.

For example:

env.put(Context.SECURITY_AUTHENTICATION, "simple");
specifies that simple authentication be used to authenticate to the LDAP server. Or,
env.put(Context.SECURITY_AUTHENTICATION, "DIGEST-MD5 CRAM-MD5");
specifies that DIGEST-MD5 authentication be used and, if that SASL mechanism is unavailable, that CRAM-MD5 authentication be used. If neither is available then throw AuthenticationNotSupportedException.
java.naming.security.credentials
The value of this property is an object that specifies the credentials of the principal to be authenticated. Its format and handling depends on the value of the java.naming.security.authentication property.
For anonymous binds, this property is ignored - an empty string is always used for the credentials. For simple authentication and SASL authentication that requires a password, the value of this property may be supplied as a java.lang.String, a char[] or a byte[]. If it is a String or a char[] then it is encoded into a byte array using UTF-8 in the case of LDAPv3 and encoded using ISO-Latin-1 in the case of LDAPv2. If it is a byte[] then it is used as is.
See the SASL section for information on how this property is used for SASL authentication.
No default value is defined for this property.
For example:
env.put(Context.SECURITY_CREDENTIALS, "secret");
sets the credentials to be the string "secret".
java.naming.security.principal

The value of this property is a string that specifies the identity of the principal to be authenticated. Its format depends on the authentication type; see RFC 2829 for more information. The value is used as the name component in an LDAP ASN.1 BindRequest for non-SASL authentication. For SASL authentication, the value of this property is used as the authentication ID for SASL mechanisms that need an authentication ID.

The provider is not required to verify the validity of the principal name. It may, for example, just pass the string to be verified by the server. If the principal identified is not a valid principal then the provider shall throw an AuthenticationException.

No default value is defined for this property.

For example:

env.put(Context.SECURITY_PRINCIPAL, "cn=admin,o=sun,c=us");

sets the principal name to be the distinguished name "cn=admin, o=sun, c=us".

java.naming.security.protocol
The value of this property is a string that specifies the security protocol for the provider to use. The following value is defined for this property:
ssl
use Secure Sockets Layer version 3.0.

If this property is set to ssl, the provider must use SSL sockets, or throw ConfigurationException if it is unable to do so. In addition to the value listed above, a provider may support other security protocols. However, such provider-specific protocols might not be supported by all providers. If this property is set to a security protocol that the provider does not recognize or support, it should throw ConfigurationException.

If the java.naming.ldap.factory.socket property is set, then the socket factory identified by that property must create sockets that are appropriate for this protocol setting. For example, if the security protocol is set to ssl, then the socket factory must create SSL-compliant sockets.

If this property is not set then the default is to use no security protocol.

As a developer of the LDAP provider, you should be aware that using SSL to connect to a server on a port that is not listening for SSL connections causes the socket to hang. Similarly, using a plain socket to connect to a server that is listening for SSL connections also leads to hanging. This is a characteristic of the protocol that some implementations may choose to correct but is not otherwise required to do so. The provider's documentation, however, should describe this behavior to its users. See SSL for information on how to use SSL.

For example:

env.put(Context.SECURITY_PROTOCOL, "ssl");
specifies that SSL-compliant sockets be used to communicate with the server.

3.3 LDAP-specific Properties

LDAP-specific properties are environment properties that apply to LDAP service providers in general. These properties' names have the prefix "java.naming.ldap.". The following table lists LDAP-specific properties that have been defined so far.

java.naming.ldap.attributes.binary
The value of this property is a string of space-separated attribute names. It specifies attributes which have non-string syntax. It extends the provider's built-in list of non-string attributes (below). The value of an attribute that has non-string syntax is returned as a byte array (byte[]) instead of a String.
No default is defined. If this property is not set then only the following attributes are considered to have non-string syntax:
Attribute ID | OID | Reference
Any attribute ID with the ";binary" option.
photo | 0.9.2342.19200300.100.1.7 | RFC 1274
personalSignature | 0.9.2342.19200300.100.1.53 | RFC 1274
audio | 0.9.2342.19200300.100.1.55 | RFC 1274
jpegPhoto | 0.9.2342.19200300.100.1.60 | RFC 2798
javaSerializedData | 1.3.6.1.4.1.42.2.27.4.1.7 | RFC 2713
thumbnailPhoto | 2.16.128.113533.1.1400.1 | NAC LIP Schema
thumbnailLogo | 2.16.128.113533.1.1400.2 | NAC LIP Schema
userPassword | 2.5.4.35 | RFC 2256
userCertificate | 2.5.4.36 | RFC 2256
cACertificate | 2.5.4.37 | RFC 2256
authorityRevocationList | 2.5.4.38 | RFC 2256
certificateRevocationList | 2.5.4.39 | RFC 2256
crossCertificatePair | 2.5.4.40 | RFC 2256
x500UniqueIdentifier | 2.5.4.45 | RFC 2256
For example:
env.put("java.naming.ldap.attributes.binary",
        "mpegVideo myspecialkey");
informs the provider to return values of the mpegVideo and myspecialkey attributes as byte[].
java.naming.ldap.control.connect
The value of this property is a Control[] object. It sets the connection request controls that are active on a connection. See LdapContext.
No default value is defined for this property.
For example:
env.put("java.naming.ldap.control.connect",
        new Control[]{ new ManageReferralControl(true) });
sets a critical ManageDsaIT LDAP control as the connection request control.

java.naming.ldap.deleteRDN
The value of this property is a string that specifies whether the old RDN is removed by the Context.rename method. The following values are defined for this property:
true
delete the old RDN from the entry during the rename operation.
false
retain the old RDN as an attribute value of the entry.

If this property is not set then its default value is true.

For example:

env.put("java.naming.ldap.deleteRDN", "false");
causes the old RDN to be retained as an attribute of the renamed entry.

java.naming.ldap.derefAliases

The value of this property is a string that specifies how aliases are dereferenced during search operations. The following values are defined for this property:

always
always dereference aliases.
never
never dereference aliases.
finding
dereference aliases only during name resolution (that is, while locating the target entry).
searching
dereference aliases once name resolution has completed (that is, after locating the target entry).
If this property is not set then its default value is always.
For example:
env.put("java.naming.ldap.derefAliases", "searching");
causes the provider to dereference aliases only once the target entry has been located.

NOTE: this property is unrelated to the dereference-links flag in the SearchControls object.

java.naming.ldap.factory.socket
The value of this property is a string identifying the class name of a socket factory.
This property is used to override the default socket factory. The class specified in this property must implement the javax.net.SocketFactory interface. See http://java.sun.com/j2se/1.4/docs/guide/security/jsse/JSSERefGuide.html for more information. See SSL for information on how to use SSL.
In addition, if the java.naming.security.protocol property is set, then the socket factory identified by this property must create sockets which are appropriate for that protocol setting. For example, if the security protocol is set to ssl then the socket factory must create SSL-compliant sockets.
No default is defined for this property.
For example:
env.put("java.naming.ldap.factory.socket",
        "javax.net.ssl.SSLSocketFactory");
sets the socket factory of the provider to be javax.net.ssl.SSLSocketFactory.

java.naming.ldap.ref.separator
The value of this property is a string containing the character to use when encoding a RefAddr object in the javaReferenceAddress attribute (see Java Objects).
This property is used to avoid a conflict in the case where the default separator character appears in the components of a RefAddr object.
If this property is not set then its default value is '#' (the hash character).
For example:
env.put("java.naming.ldap.ref.separator", ":");
specifies that the separator ':' (the colon character) be used when storing RefAddr instances.

java.naming.ldap.referral.limit
The value of this property is a string of decimal digits specifying the maximum number of referrals to follow in a chain of referrals. A setting of zero indicates that there is no limit.
If this property is not set then the default value is 10.
For example:
env.put("java.naming.ldap.referral.limit", "5");
specifies that the referral limit is 5.

java.naming.ldap.typesOnly
The value of this property is a string that specifies whether only attribute IDs are returned in results - attribute values are omitted. Affects the SearchResult.getAttributes and DirContext.getAttributes methods. The following values are defined for this property:
true
return only attribute IDs.
false
return both attribute IDs and attribute values.

If this property is not set then its default value is false.

For example:

env.put("java.naming.ldap.typesOnly", "true");
causes the server to return attribute IDs but not attribute values.
java.naming.ldap.version
The value of this property is a string that specifies the protocol version for the provider. The following values are defined for this property:
2
selects LDAP version 2 (LDAPv2).
3
selects LDAP version 3 (LDAPv3).

If this property is not set then the provider first attempts to bind using LDAP v3 and fails over to using LDAP v2 if a protocol error is received from the server. This failover mechanism is only used when the java.naming.security.authentication property indicates anonymous bind or simple authentication.

For example:

env.put("java.naming.ldap.version", "2");
requests the LDAP provider to communicate with the server using LDAPv2.

3.4 Feature-specific Properties

Feature-specific properties are environment properties which apply to a particular feature which is supported by a provider.

3.4.1 SASL Properties

There are two groups of SASL properties. The first group comprises those that relate to how the JNDI service provider interacts with the Java SASL API (JSR 28). These properties have the prefix "java.naming.security.sasl." The second group comprises those that affect the SASL mechanisms. These properties are specified in the Java SASL API and have the prefix "javax.security.sasl." See the SASL section and the Java SASL API for details about this second group of properties.

java.naming.security.sasl.authorizationId

The value of this property is a string that specifies the authorization ID for the SASL mechanisms.

If this property is not set, then the authorization ID passed to the SASL mechanisms is the empty string. According to SASL (RFC 2222), using an authorization ID of the empty string directs the server to derive an authorization ID from the client's authentication credentials.

For example:

env.put("java.naming.security.sasl.authorizationId",
        "dn:cn=administrators,ou=groups,o=sun,c=us");

specifies the identity to use for authorization (access control) upon successful authentication.

java.naming.security.sasl.realm

The value of this property is a string that specifies the realm information required by some SASL mechanisms such as DIGEST-MD5.

If this property is not set, then a mechanism-specific default such as that negotiated between the client and server during the authentication exchange is used.

For example:

env.put("java.naming.security.sasl.realm", "webusers");

specifies that the client wants to use the "webusers" realm for authentication.

java.naming.security.sasl.callback

The value of this property is an instance of javax.security.auth.callback.CallbackHandler. When the provider uses a SASL mechanism that requires callbacks, the SASL mechanism uses the object supplied in the property. The callback handler should satisfy a NameCallback by supplying the authentication ID.

If this property is not set, then the provider should use a default callback handler that satisfies the NameCallback using the value of the java.naming.security.principal property, satisfies the PasswordCallback using the value of the java.naming.security.credentials property, and satisfies the RealmCallback and RealmChoiceCallback (described in the Java SASL API) using the value of the java.naming.security.sasl.realm property.

For example:

env.put("java.naming.security.sasl.callback",
        new MyCallbackHandler());

supplies an instance of the callback handler for SASL mechanisms to use.

javax.security.sasl.qop

The value of this property is a ','-separated list of quality-of-protection (qop) values used to specify the client's qop preference. A qop value is one of

  • "auth" - authentication only
  • "auth-int" - authentication plus integrity protection
  • "auth-conf" - authentication plus integrity and confidentiality protection
The order of the list specifies the preference order. If this property is absent, the default qop is "auth".
javax.security.sasl.strength

The value of this property is a ','-separated list of cipher strength values used to specify the client's preference. A strength value is one of

  • "low"
  • "medium"
  • "high"
The order of the list specifies the preference order. If this property is absent, the default strength is "high,medium,low".

For privacy in DIGEST-MD5, "high" maps to "3des", "medium" to "rc4" or "des", and "low" to "rc4-56" or "rc4-40".

javax.security.sasl.maxbuffer

The value of this property is the string representation of an integer that specifies the maximum size of the receive buffer in bytes that the client is willing to receive. If this property is absent, the default size is defined by the SASL mechanism.

javax.security.sasl.server.authentication

The value of this property is either "true" or "false", specifying whether the server must authenticate to the client or not, respectively. If this property is absent, the default is "false".

javax.security.sasl.policy.forward

The value of this property is either "true" or "false", specifying whether the selected SASL mechanism must support forward secrecy between sessions or not, respectively. If this property is absent, the default is "false".

javax.security.sasl.policy.credentials

The value of this property is either "true" or "false", specifying whether the selected SASL mechanism must require client credentials or not, respectively. If this property is absent, the default is "false".

javax.security.sasl.policy.noplaintext

The value of this property is either "true" or "false", specifying whether the selected SASL mechanism must not be susceptible to simple plain passive attacks or not, respectively. If this property is absent, the default is "false".

javax.security.sasl.policy.noactive

The value of this property is either "true" or "false", specifying whether the selected SASL mechanism must not be susceptible to active (non-dictionary) attacks or not, respectively. If this property is absent, the default is "false".

javax.security.sasl.policy.nodictionary

The value of this property is either "true" or "false", specifying whether the selected SASL mechanism must not be susceptible to dictionary attacks or not, respectively. If this property is absent, the default is "false".

javax.security.sasl.policy.noanonymous

The value of this property is either "true" or "false", specifying whether the selected SASL mechanism must not accept anonymous logins or not, respectively. If this property is absent, the default is "false".

3.5 Provider-specific Properties

Provider-specific properties are environment properties which apply only to particular provider implementations. The names of these properties are chosen by the provider's implementor. The recommended policy for naming these properties is to use the implementor's reversed DNS domain name to prefix the provider's package name and to use that package name to prefix the property name. For example, Sun prefixes its provider-specific LDAP properties with "com.sun.jndi.ldap".

4. Names

Names are handled by the provider's context methods according to the following rules:
  1. String names supplied as parameters to the context methods are in the composite name syntax.The first component of the composite name is an LDAP distinguished name while the rest of the components are used for federation.
  2. If a Name argument is a CompositeName object then its first component is assumed to be an LDAP distinguished name and the remaining components (if any) are used for federation.
  3. If a Name argument is not a CompositeName object then all of its components are assumed to be the parsed form of an LDAP distinguished name. That is, each Name component is an LDAP relative distinguished name (RDN).
  4. Names are parsed using the name parser returned by the Context.getNameParser method. The parser accepts LDAP distinguished names as String objects and produces LDAP distinguished names as Name objects.
  5. Names returned by context operations are string composite names or string URLs.
The syntax of string LDAP distinguished names follows RFC 2253. For example:
  • CN=Steve Kille, O=Isode Limited, C=GB
  • OU=Sales+CN=J. Smith, O=Widget Inc., C=US
  • CN=L. Eagle, O=Sue\, Grabbit and Runn, C=GB

The name supplied to an LDAP context is always relative to that context. For example, given an LDAP context (lctx) for "dc=widget,dc=com", in order to name LDAP entries in that subtree, a name relative to "dc=widget,dc=com" must be supplied. For example, the following call obtains the attributes for the "cn=John Smith,dc=widget,dc=com" entry.

Attributes attrs = lctx.getAttributes("cn=John Smith");

Similarly, when a context is enumerated using any of the enumeration methods (Context.list, Context.listBindings, DirContext.search), the names returned are relative to the target context--the context being enumerated. When referrals are invoked, instead of a relative name, an LDAP or LDAPS URL string containing the fully qualified name is returned. (If the enumeration was performed using a plain connection, an LDAP URL string is returned; if it was done using an SSL connection, an LDAPS URL string is returned.) The format of LDAP URLs is defined in RFC 2255.

LDAP URLs that follow RFC 2255 and LDAPS URLs may be supplied to any of the context methods. The hostname and port number are extracted from the URL and used to contact the LDAP server; the URL's scheme ("ldap" or "ldaps") is used to determine whether a plain or SSL connection is used. The java.naming.factory.initial and java.naming.provider.url properties are ignored. For example,

    DirContext ictx = new InitialDirContext();
    Attributes attrs = ictx.getAttributes(
        "ldap://wserver:389/cn=John Smith,dc=widget,dc=com");

This code fragment contacts the LDAP server at machine wserver at port 389 using a plain connection.

5. Attributes

The LDAP provider expects as input and returns as output all attribute values as either String or byte[] objects. See the java.naming.ldap.attributes.binary environment property for which ones are treated as byte[] and how to extend the list.

6. URLs

RFC 2255 describes the syntactic format of LDAP URLs. The format contains all the elements necessary to specify an LDAP search operation, with provisions for supporting extensions:
ldap://host:port/dn?attributes?scope?filter?extensions

Authentication information may be specified in the extensions portion of the URL. See the RFC for a complete description of the format.

In addition to LDAP URLs, the provider may also support the non-standard but widely used LDAPS URLs. LDAPS URLs use SSL connections instead of plain (i.e., unprotected) connections. They have a syntax similar to LDAP URLs except the schemes are different and the default port for LDAPS URLs is 636 instead of 389.

ldaps://host:port/dn?attributes?scope?filter?extensions

URLs play a role in several places in JNDI:

  1. Configuration of service providers.
    To configure an LDAP service provider, you typically supply one or more space-separated LDAP or LDAPS URLs in the java.naming.provider.url property. This is used by the LDAP service provider to configure its connection to the directory server. Only the host, port, and dn parts of the URL are relevant in this setting. Supplying other parts of the URL results in a ConfigurationException.
  2. Argument to initial context methods.
    If a URL string (with syntax scheme_id:rest_of_name) is passed to the methods in InitialContext, either as a String argument or as the first component of Name, the URL's scheme id is used to locate the context factory for handling that scheme. If none is found, the URL string is treated as an ordinary name and passed to the initial context specified by the java.naming.factory.initial property is used. See the java.naming.spi.NamingManager.getURLContext method for details on how URL context factories are located. Note that this support for URLs as names is only available in the initial context.

    With the exception of the search methods, when an LDAP or LDAPS URL is passed as a name to the initial context, the URL should not contain any query ('?') components. Otherwise, an InvalidNameException is thrown by the service provider. For the search methods, the query components of the URL override any corresponding components supplied as arguments. For example, if an LDAP URL containing a scope component is supplied, then that scope overrides any scope setting that may be passed in a SearchControls argument.

  3. Referrals.
    An LDAP referral contains a list of one or more URLs. To process an LDAP referral (either explicitly or implicitly by setting the java.naming.referral property), the service provider needs to use the information in the these URLs to create connections to LDAP servers to which they refer. When multiple URLs are present in a single referral they are treated as alternatives and each is followed until one succeeds. The complete URL (that is, including any query components) is used.
  4. Returned as a name in list and search enumerations.
    When the name of the entry being returned has a name that is not relative to the target context (i.e., the starting context for the list or search), the name is returned as a URL. See the NameClassPair.isRelative method for details.
  5. Argument to the getObjectInstance method of NamingManager or DirectoryManager.
    When an LDAP namespace is federated underneath another namespace (for example, such as DNS), the information that is stored in the superior namespace might be an LDAP or LDAPS URL. In such a scenario, a lookup/list/search operation in the superior namespace would return a Reference containing an LDAP or LDAPS URL for the LDAP namespace. The service provider for the superior namespace would pass the Reference to the getObjectInstance method to create an instance of an LDAP context.
For items (1), (2), (3), and (5), if the URL is missing the hostname and port but has a non-empty distinguished name, the provider should use the algorithm for discovering LDAP services with DNS as described in the Internet draft draft-ietf-ldapext-locate-08.txt. If the provider does not use this algorithm, or if the DNS configuration is not available, then the provider should use localhost as the hostname, and 389 as the port for plain connections, 636 as the port for SSL connections.

7. Java Objects

7.1 Storing

The LDAP provider should support the storing of Java objects into the directory. This is implemented in the following methods:
  • Context.bind()
  • Context.rebind()
  • DirContext.bind()
  • DirContext.rebind()
The provider should support at a minimum the storage of the following types of Java objects:
  1. Instances of Reference
  2. Objects that implement the Referenceable interface
  3. Objects that implement the Serializable interface
  4. Objects that implement the DirContext interface
It should check whether an object is in these four categories in the order listed because that is most likely to capture the intent of the client. For example, a Reference is Serializable, so if you performed the Serializable check first, no References would ever be stored in the reference format (that is, they would all be serialized).

References, referenceable and serializable objects should be stored according to RFC 2713. DirContext objects should be stored by storing their attributes.

When storing a reference's list of RefAddr into the javaReferenceAddress attribute, the separator to use for delimiting the address's position, type and content are controlled using the environment property java.naming.ldap.ref.separator. If this environment property is not specified, the hash character '#' should be used as the separator.

The provider uses the DirectoryManager.getStateToBind method when storing objects in the directory. This allows objects of any type to be transformed into one of the four categories listed above so that they can be stored into the directory.

7.2 Reading

Objects are read from the directory using the following operations:
  • Context.lookup()
  • Context.lookupLink()
  • Binding.getObject()
When the provider reads an entry from the directory, it will get LDAP attributes, and attributes defined in RFC 2713 if the entry has an associated Java object. If the entry contains Java object-related attributes, the provider should recreate the object using those attributes. Otherwise, the provider should return an instance of DirContext containing the attributes of the entry. For both DirContext and Java objects, the provider should then invoke DirectoryManager.getObjectInstance() on it and return the result to the caller.

8.0 Schema

JNDI does not specify schema-related details such as structure and contents of the schema tree, permission to modify to the contents of the schema tree, and the effect of such modifications on the directory are dependent on the underlying directory. JNDI specifies only that the root schema context--that returned by DirContext.getSchema()--contain the following bindings:
  • AttributeDefinition
  • ClassDefinition
  • SyntaxDefinition
This document specifies the structure and content of schema trees that are derived from LDAP-based schemas. It describes how the schema tree is laid out, and the mandatory and optional attributes that you can expect to find associated with entries in different parts of this schema tree.

Permission to modify the contents of the schema tree is determined by the directory administrator. When the schema tree is modified, the changes are made to schema stored on the directory server.

8.1 Schema Tree Structure

In addition to the three bindings in the root schema context listed previously, the root schema context may also contain the following four bindings:
  • MatchingRule
  • ExtensionDefinition
  • ControlDefinition
  • SASLDefinition

Name of Binding | Description of Binding
AttributeDefinition | Root of the attribute definition tree: a flat namespace with attributes identified by their name or OID.
ClassDefinition | Root of the "objectclass" definition tree: a flat namespace with object classes identified by their name or OID.
SyntaxDefinition | Root of the syntax definition tree: a flat namespace with syntaxes identified by their OID.
MatchingRule | Root of matching rule tree: a flat namespace with matching rules identified by their name or OID.
ExtensionDefinition | Root of the extensions tree: a flat namespace with extensions identified by their OID.
ControlDefinition | Root of the controls tree: a flat namespace with controls identified by their OID.
SASLMechanism | Root of the SASL tree: a flat namespace with SASL authentication mechanisms identified by their string name.

Any or all of these bindings may be absent if the underlying directory does not publish such schema information, or the service provider does not support retrieving them. If these names are present in the root schema context, however, they must have the binding specified in the above table.

The attribute names and values of these entries' attributes are case-insensitive.

8.2 Attribute Definitions

The name "AttributeDefinition" is bound to a context containing DirContext objects representing attribute definitions in the schema. For example, if a directory supports a "commonName" attribute, the "AttributeDefinition" context would have a binding with name "commonName" that is bound to a DirContext object.

Each object in the "AttributeDefinition" context has the following mandatory and optional attributes:

Attribute Identifier | Attribute Value Description
NUMERICOID (mandatory) | unique identifier (OID)
NAME | attribute's name
DESC | attribute's description
OBSOLETE | "true" if obsolete, "false" or absent otherwise
SUP | name of superior attribute type from which this attribute's type is derived
EQUALITY | name or OID of matching rule if equality matching allowed, absent otherwise
ORDERING | name or OID of matching rule if ordering matching allowed, absent otherwise
SUBSTRING | name or OID of matching rule if substring matching allowed, absent otherwise
SYNTAX | numeric OID of syntax of values of this type
SINGLE-VALUE | "true" if attribute not multi-valued, "false" or absent otherwise.
COLLECTIVE | "true" if attribute is collective, "false" or absent otherwise.
NO-USER-MODIFICATION | "true" if not user-modifiable, "false" or absent otherwise.
USAGE | description of attribute usage

These attributes have a 1-to-1 correspondence with the names defined in RFC 2252 for "AttributeTypeDescription." All the attribute values are represented by the java.lang.String class.

You can, for example, obtain the object representing the "cn" attribute using the following code:

DirContext schema = ctx.getSchema(""); // get schema tree
DirContext cnSchema = schema.lookup("AttributeDefinition/cn");

If you then get the attributes of the "cnSchema" DirContext object, you would see:

NUMERICOID      2.5.4.3
NAME            cn
SYNTAX          1.3.6.1.4.1.1466.115.121.1.15
DESC            Standard Attribute, alias for commonName

An equivalent way of getting "cnSchema" is if you already have a "cn" attribute. The following code illustrates this alternative:

Attributes attrs = ctx.getAttributes("cn=John", new String[]{"cn"});
Attribute cnAttr = attrs.get("cn");
DirContext cnSchema = cnAttr.getAttributeDefinition();

8.3 Object Class Definitions

The name "ClassDefinition" is bound to a context containing DirContext objects representing object class definitions in the schema. For example, if a directory supports a "country" object class, the "ClassDefinition" context would have a binding with name "country" that is bound to a DirContext object.

Each object in the "ClassDefinition" context has the following mandatory and optional attributes:

Attribute Identifier | Attribute Value Description
NUMERICOID (mandatory) | unique identifier (OID)
NAME | object class's name
DESC | object class's description
OBSOLETE | "true" if obsolete, "false" or absent otherwise
SUP | name of superior object class from which this object class is derived
ABSTRACT | "true" if object class is abstract, "false" or absent otherwise
STRUCTURAL | "true" if object class is structural, "false" or absent otherwise
AUXILIARY | "true" if object class is auxiliary, "false" or absent otherwise
MUST | a list of type names of attributes that must be present
MAY | a list of type names of attributes that may be present

These attributes have a 1-to-1 correspondence with the names defined in RFC 2252 for "ObjectClassDescription." All the attribute values are represented by the java.lang.String class.

You can, for example, obtain the object representing the "country" object class using the following code:

DirContext schema = ctx.getSchema(""); // get schema tree
DirContext countrySchema = schema.lookup("ClassDefinition/country");

If you then get the attributes of the "countrySchema" DirContext object, you would see:

NUMERICOID      2.5.6.2
NAME            country
MAY             aci, searchguide, description
MUST            objectclass, c
DESC            Standard ObjectClass
SUP             top

An equivalent way of getting "countrySchema" is if you already have a "country" object. The following code illustrates this alternative:

// Read object from directory
DirContext countryObj = (DirContext)ctx.lookup("c=us", new String[]{"country"});

// Get all of object's object class definitions
DirContext objClasses = countryAttr.getSchemaClassDefinition();

// Pick out "country" object class in particular
DirContext countryClass = (DirContext)objClasses.lookup("country");

NOTE: JNDI 1.1's specification of getSchemaClassDefinition() implies that the service provider should return any one of an object's object class definitions. This specification is inadequate because an object usually has multiple object classes and the application might require knowledge about any of those object classes depending on what it is doing. The proposal as illustrated by the example above is to return a context containing all of the object class definitions.

8.4 Syntax Definitions

The name "SyntaxDefinition" is bound to a context containing DirContext objects representing syntax definitions in the schema. For example, if a directory supports the "1.3.6.1.4.1.1466.115.121.1.15" syntax (Directory String) syntax, the "SyntaxDefinition" context would have a binding with name "1.3.6.1.4.1.1466.115.121.1.15" that is bound to a DirContext object.

Each object in "SyntaxDefinition" context has the following mandatory and optional attributes:

Attribute Identifier | Attribute Value Description
NUMERICOID (mandatory) | unique identifier (OID)
DESC | syntax's description

These attributes have a 1-to-1 correspondence with the names defined in RFC 2252 for "SyntaxDescription." All the attribute values are represented by the java.lang.String class.

You can, for example, obtain the object representing the "1.3.6.1.4.1.1466.115.121.1.15" syntax using the following code:

DirContext schema = ctx.getSchema(""); // get schema tree
DirContext dirStringSchema =
    schema.lookup("SyntaxDefinition/1.3.6.1.4.1.1466.115.121.1.15");

If you then get the attributes of the "dirStringSchema" DirContext object, you would see:

NUMERICOID      1.3.6.1.4.1.1466.115.121.1.15
DESC            Directory String

An equivalent way of getting "dirStringSchema" is if you already have an attribute that has that syntax (such as, the "country" attribute). The following code illustrates this alternative:

Attributes attrs = ctx.getAttributes("c=us", new String[]{"country"});
Attribute countryAttr = attrs.get("country");
DirContext dirStringSchema = countryAttr.getSyntaxAttributeDefinition();

8.5 Matching Rules

The name "MatchingRule" is bound to a context containing DirContext objects representing matching rules in the schema. A "matching rule" uniquely identifies the algorithm to use when comparing attribute values. For example, a directory might support a matching rule that is based on how a string sounds and define it as the "soundAlikeMatch" matching rule. Then, the "MatchingRule" context would have a binding with name "soundAlikeMatch" that is bound to a DirContext object.

When a matching rule is an extensible matching rule, it must also contain an "APPLIES" attribute listing the attributes to which this extensible matching rule can be applied.

Each object in "MatchingRule" context has the following mandatory and optional attributes:

Attribute Identifier | Attribute Value Description
NUMERICOID (mandatory) | unique identifier (OID)
NAME | name of matching rule
DESC | matching rule's description
OBSOLETE | "true" if obsolete, "false" or absent otherwise
SYNTAX | numeric oid of syntax to which this rule applies
APPLIES | a list type names of attributes to which this extensible matching rule applies

These attributes have a 1-to-1 correspondence with the names defined in RFC 2252 for "MatchingRuleDescription" and "MatchingRuleUseDescription." All the attribute values are represented by the java.lang.String class.

You can, for example, obtain the object representing the "soundAlikeMatch" syntax using the following code:

DirContext schema = ctx.getSchema(""); // get schema tree
DirContext soundMatchSchema =
    schema.lookup("MatchingRule/soundAlikeMatch");

If you then get the attributes of the "soundMatchSchema" DirContext object, you would see:

NUMERICOID      1.2.3.4.5
NAME            soundAlikeMatch
SYNTAX          1.3.6.1.4.1.1466.115.121.1.15 (for directory string)
APPLIES         2.5.4.41, 2.5.4.15
DESC            Home-grown Phonetic match

8.6 Extension Definitions

The name "ExtensionDefinition" is bound to a context containing DirContext objects representing extensions supported by the server. For example, a directory might support the "Start TLS" extension ("1.3.6.1.4.1.1466.20037"). Then, the "ExtensionDefinition" context would have a binding with name "1.3.6.1.4.1.1466.20037" that is bound to a DirContext object.

Each object in "ExtensionDefinition" context has the following mandatory and optional attributes:

Attribute Identifier | Attribute Value Description
NUMERICOID (mandatory) | unique identifier (OID)
DESC | extension's description

All the attribute values are represented by the java.lang.String class.

You can, for example, obtain the object representing the Start TLS extension ("1.3.6.1.4.1.1466.20037") using the following code:

DirContext schema = ctx.getSchema(""); // get schema tree
DirContext startTLSSchema =
    schema.lookup("ExtensionDefinition/1.3.6.1.4.1.1466.20037");

If you then get the attributes of the "startTLSSchema" DirContext object, you would see:

NUMERICOID      1.3.6.1.4.1.1466.20037
DESC            Start TLS (see RFC 2830)

8.7 Control Definitions

The name "ControlDefinition" is bound to a context containing DirContext objects representing controls supported by the server. For example, a directory might support the control for asking the server to sort the search results it returns.

Each object in "ControlDefinition" context has the following mandatory and optional attributes:

Attribute Identifier | Attribute Value Description
NUMERICOID (mandatory) | unique identifier (string)
DESC | control's description

All the attribute values are represented by the java.lang.String class.

You can, for example, obtain the object representing the server-side sorting control ("1.2.840.113556.1.4.473") using the following code:

DirContext schema = ctx.getSchema(""); // get schema tree
DirContext svrSortSchema =
    schema.lookup("ControlDefinition/1.2.840.113556.1.4.473");

If you then get the attributes of the "svrSortSchema" DirContext object, you would see:

NUMERICOID      1.2.840.113556.1.4.473
DESC            server-side sorting of search results

8.8 SASL Mechanisms

The name "SASLMechanism" is bound to a context containing DirContext objects representing SASL authentication mechanisms supported by the server. For example, a directory might support the EXTERNAL SASL mechanism (RFC 2222) which requests that the server make use of security credentials exchanged by a lower layer.

Each object in "SASLMechanism" context has the following mandatory and optional attributes:

Attribute Identifier | Attribute Value Description
NAME (mandatory) | SASL mechanism's name
DESC | SASL mechanism's description

All the attribute values are represented by the java.lang.String class.

You can, for example, obtain the object representing the EXTERNAL SASL mechanism using the following code:

DirContext schema = ctx.getSchema(""); // get schema tree
DirContext saslExternalSchema =
    schema.lookup("SASLMechanism/EXTERNAL");
If you then get the attributes of the "saslExternalSchema" DirContext object, you would see:
NAME
EXTERNAL
DESC      EXTERNAL SASL mechanism (RFC
2222)

9. Exceptions

When building an LDAP provider, you need to translate LDAP error codes (see RFC 2251) into JNDI exceptions. You should use the following table when performing the translation. Furthermore, you should encode as much information as possible about the error into the exception's detailed message, "root cause" exception, resolved and remaining names. Note that resolved name and resolved object should correspond to each other's setting.
LDAP error code | Exception or Action
success (0) | Report success.
operationsError (1) | NamingException
protocolError (2) | CommunicationException
timeLimitExceeded (3) | TimeLimitExceededException
sizeLimitExceeded (4) | SizeLimitExceededException
compareFalse (5) | Used by DirContext.search() and does not generate an exception.
compareTrue (6) | Used by DirContext.search() and does not generate an exception.
authMethodNotSupported (7) | AuthenticationNotSupportedException
strongAuthRequired (8) | AuthenticationNotSupportedException
partialResults (9) | If java.naming.referral is set to ignore, or contents of error does not contain a referral, throw PartialResultException. Otherwise, use the contents to build a referral.
referral (10) | If java.naming.referral is set to ignore then throw PartialResultException. If it is set to throw then throw ReferralException. If it is set to follow then the provider shall follow the referral. If the value for java.naming.ldap.referral.limit is exceeded while following the referral then throw LimitExceededException.
adminLimitExceeded (11) | LimitExceededException
unavailableCriticalExtension (12) | OperationNotSupportedException
confidentialityRequired (13) | AuthenticationNotSupportedException
saslBindInProgress (14) | Used internally by LDAP provider during multi-stage SASL authentication.
noSuchAttribute (16) | NoSuchAttributeException
undefinedAttributeType (17) | InvalidAttributeIdentifierException
inappropriateMatching (18) | InvalidSearchFilterException
constraintViolation (19) | InvalidAttributeValueException
attributeOrValueExists (20) | AttributeInUseException
invalidAttributeSyntax (21) | InvalidAttributeValueException
noSuchObject (32) | NameNotFoundException
aliasProblem (33) | NamingException
invalidDNSyntax (34) | InvalidNameException
isLeaf (35) | Used by provider; usually doesn't generate exception.
aliasDereferencingProblem (36) | NamingException
inappropriateAuthentication (48) | AuthenticationNotSupportedException
invalidCredentials (49) | AuthenticationException
insufficientAccessRights (50) | NoPermissionException
busy (51) | ServiceUnavailableException
unavailable (52) | ServiceUnavailableException
unwillingToPerform (53) | OperationNotSupportedException
loopDetect (54) | NamingException
namingViolation (64) | InvalidNameException
objectClassViolation (65) | SchemaViolationException
notAllowedOnNonLeaf (66) | ContextNotEmptyException
notAllowedOnRDN (67) | SchemaViolationException
entryAlreadyExists (68) | NameAlreadyBoundException
objectClassModsProhibited (69) | SchemaViolationException
affectsMultipleDSAs (71) | NamingException
other (80) | NamingException

10. API Mapping

The methods of the JNDI API context interfaces are mapped onto LDAP operations as follows.
EventContext.addNamingListener
EventDirContext.addNamingListener
Register a listener for receiving naming events that take place in the specified subtree of LDAP entries. LDAP servers notify clients of events by means of LDAP controls attached to LDAP operation responses or by means of an LDAP unsolicited notifications. Such responses are then processed by the LDAP provider and indicated to the application in the form of NamingEvent or UnsolicitedNotificationEvent.
Context.addToEnvironment

Update context's environment properties. If multiple contexts share the same set of environment properties, the provider should take care to only modify the intended context's environment. Changing an environment property might require changes to the existing connection the context is using.

Supplying null for the property value has the same effect as removing the property.
For all environment properties, the new property is recorded even if it does not affect the context. See the Environment Properties section.
Context.bind

DirContext.bind
Perform an LDAP add operation to create a new entry in the directory. The DirContext.bind method can accept null as the object to bind if it is also supplied a non-null set of attributes. Otherwise, if the method is given insufficient information (i.e., no object or attributes), no entry can be added. If an object is provided in the arguments, then it is converted into attributes and stored in the entry along with any supplied attributes, as described in the Java Objects section. The provider should use the DirectoryManager.getStateToBind method to transform the input object into a form that it can store.
If the provider does not support binding any objects in the directory then it should throw OperationNotSupportedException. Otherwise, if it does support binding objects but does not support the supplied object then it should throw IllegalArgumentException.
Context.close
Release resources associated with context. For example, if the connection being used by this context is not shared with another context, the provider may abandon any outstanding requests and close the network connection to the server. Precisely which resources are released is implementation-dependent.
Context.composeName
If the parent context is from the same LDAP namespace, then concatenate the names according to the LDAP name syntax described in Context.getNameParser(). Otherwise, concatenate the names as composite names.
Context.createSubcontext

DirContext.createSubcontext
Perform an LDAP add operation to create the named entry and its associated attributes. If no attributes are supplied then the objectClass attribute is generated with the values top and javaContainer (javaContainer is a structural class that is necessary to avoid a schema violation error).
Context.destroySubcontext
Perform an LDAP delete operation to remove the named entry and its associated attributes. The named entry must be a leaf entry; subtrees are not removed. If the leaf entry does not exist (but its parent exists), the operation still succeeds.
LdapContext.extendedOperation
Perform an LDAP extended operation.
DirContext.getAttributes
Perform an LDAP base-object search operation to retrieve the LDAP entry's attributes. Use "(objectclass=*)" as the filter.
If the list of requested attributes is null or contains the special attribute identifier '*' then all the user attributes at the LDAP entry are returned. If operational attributes are required then those attribute identifiers must be present in the list of requested attributes.
LdapContext.getConnectControls
Retrieve the connection request controls in effect for LDAP bind operations invoked on this context.
Context.getEnvironment
Return the environment properties recorded at the context.
Context.getNameInNamespace
Return the LDAP distinguished name of the context.
Context.getNameParser
Return a name parser that parses LDAP names according to RFC 2253.
LdapContext.getRequestControls
Retrieve the request controls in effect for LDAP operations subsequently invoked on this context.
LdapContext.getResponseControls
Retrieve the response controls returned by the last LDAP operation invoked on this context.
DirContext.getSchema
See the Schema Section.
DirContext.getSchemaClassDefinition
See the Schema Section.
Context.list
Perform an LDAP one-level search operation of the named entry using the filter "(objectclass=*)" to retrieve the names of the entries immediately below the named entry.
Ask for, at a minimum, the javaClassName attributes so that the class name of each entry can be determined. If the class name cannot be determined, return javax.naming.directory.DirContext as the class name.
The names which are returned are either relative to the named context or they are LDAP or LDAPS URLs.
Context.listBindings
Perform an LDAP one-level search operation of the named entry using the filter "(objectclass=*)" to retrieve the attributes representing objects (or object references). Request the attributes for reconstructing the Java object and possibly other attributes as well. See Java Objects on how to reconstruct the object. If the object cannot be reconstructed according to RFC 2713 then return a DirContext object representing the LDAP entry. The provider should use the DirectoryManager.getObjectInstance method to satisfy calls to the Binding.getObject method.
The names which are returned are either relative to the named context or they are LDAP or LDAPS URLs.
Context.lookup

Context.lookupLink
Perform an LDAP base-object search operation of the named entry using the filter "(objectclass=*)". Request (possibly all) the attributes for reconstructing the Java object. See Java Objects on how to reconstruct the object. The provider should use the DirectoryManager.getObjectInstance method to satisfy calls to the Binding.getObject method.
DirContext.modifyAttributes
Perform an LDAP modify operation at the named entry using the supplied modifications. For the overloaded method that accepts an Attributes, first convert the Attributes argument into an ordered list of modifications by enumerating its contents using Attributes.getAll() and reusing the modification operation argument (mod_op).
LdapContext.newInstance
Initialize an new instance of this context with the specified request controls.
Context.rebind

DirContext.rebind
This method may involve several different LDAP operations. First get the existing entry's attributes. If the existing entry does not exist, this method behaves the same as bind(). Otherwise, if no attributes have been supplied and the object being bound is DirContext, invoke DirContext.getAttributes() and use the result as the attributes argument (attrs). If there are still no attributes, use the original entry's attributes as attrs. Remove the existing entry using the LDAP delete operation. Convert the object provided in the arguments into attributes (as described in the Java Objects section) and store in the entry along with attrs using the LDAP add operation. The provider should use the DirectoryManager.getStateToBind method to transform the input object into a form that it can store.
LdapContext.reconnect
Reconnect to the LDAP server using the supplied connection request controls and the current environment properties.
Context.removeFromEnvironment

Remove context's environment properties. If multiple contexts share the same set of environment properties, the provider should take care to only modify the intended context's environment. Changing an environment property might require changes to the existing connection the context is using.

For all environment properties, the new property is recorded even if it does not affect the context. Removing a property should cause the context to assume the property's default.
EventContext.removeNamingListener
Deregister a naming event listener so that subsequent events destined for that listener are not delivered.
Context.rename
Perform an LDAP modify DN operation to rename the entry. If LDAPv2 is being used then the new name and the old name must share the same immediate parent name. If the parents are not equal then throw InvalidNameException.
Note the effect of the java.naming.ldap.deleteRDN property on the behavior of this method.
DirContext.search
Perform an LDAP search operation according to the specified search controls.
If the list of requested attributes is null or contains the special attribute identifier '*' then all the user attributes at the LDAP entry are returned. If operational attributes are required then those attribute identifiers must be present in the list of requested attributes.
If objects are requested to be returned, then the Java object-related attributes (RFC 2713) are requested in addition to any requested by the API user. If these attributes are present then they are used to assemble the original objects (see Java Objects). If the object cannot be reconstructed according to RFC 2713 then return a DirContext object representing the LDAP entry. The provider should use the DirectoryManager.getObjectInstance method to satisfy calls to the Binding.getObject method.
The names which are returned are either relative to the named context or they are LDAP or LDAPS URLs.
The provider may use an LDAP compare operation instead of an LDAP search when the search filter supplied is suitably constrained:
  • The filter must be of the form "(<attributeID>=<value>)"
  • The scope must be object scope
  • Zero attributes must be requested (empty returning-attributes list)

In the forms of search that accept a string filter as argument, the syntax of the filter follows RFC 2254 with the exception that Unicode characters are also allowed. The use of Unicode characters is preferable to the use of encoded UTF-8 octets. The service provider is responsible for translating the Unicode characters into their corresponding UTF-8 representation for transmission to the server. For example, the Greek letter alpha can be specified in the string filter either as "\u03B1" or as "\\CE\\B1".

In the form search(Name, Attributes) and related methods, the Attributes argument is converted into a string filter by creating a conjunctive expression out of its elements. Each attribute value is treated as a literal; therefore '*' and other special characters defined in RFC 2254 that appear in the values of an attribute should be escaped according to the rules in RFC 2254. For example, an attribute value of '*' should be encoded as the string "\\2a".

In the form search(Name, String filterExpr, Object[] filterArgs) and its String overloaded method, "{num}" expansion is done in the filter by putting in values from filterArgs. Each "{num}" component may appear in the place of "attr" or "value" in Section 4 from RFC 2254.

The objects in filterArgs should be encoded in the following way:

  • byte arrays (byte[]) are encoded by encoding each byte as a string according to RFC 2254. For example, the array {0, 1, 10, 100} is encoded as the string "\\00\\01\\0a\\64".
  • Strings are treated as literals. In other words, '*' and other special characters defined in RFC 2254 that appear in the string are escaped according to the rules in RFC 2254. For example, a string of "*" is encoded as the string "\\2a".
  • Objects that are neither String nor byte[] are converted to their string form using Object.toString() and then the rules for String applied.
LdapContext.setRequestControls
Set the request controls for LDAP operations subsequently invoked on this context.
EventContext.targetMustExist
Determine whether a listener can register interest in an LDAP entry that doesn't exist.
Context.unbind
Perform an LDAP delete operation to remove the named entry. The named entry must be a leaf entry; subtrees are not removed. If the leaf entry does not exist (but its parents exist), the operation still succeeds.

11. Federation

The LDAP service provider should support federation using strong separation and either or both of junctions or implicit next naming system pointer.

12. SASL

The provider supports SASL mechanisms by means of the Java SASL API (JSR 28). This allows SASL mechanism drivers from different vendors to be used with the LDAP provider, and also allows a SASL mechanism driver to be used with different LDAP providers and even non-LDAP protocol libraries.

The Java SASL API depends on the Java Authentication and Authorization Service (JAAS), which provides callback support for SASL mechanisms that need to obtain or supply user/application information directly.

12.1 SASL Configuration

To specify that SASL authentication be used, you specify the official IANA-registered names of the SASL mechanisms in the java.naming.security.authentication property. The first SASL mechanism on the list that is both available and satisfies the optionally specified policies is used. That is, properties with the prefix "javax.security.sasl.policy." can be used to control the security characteristics of the selected SASL mechanism.

Some SASL mechanisms require the identity of the entity being authenticated. This is known as the authentication ID. Some SASL mechanisms, like DIGEST-MD5, require the use of a password and/or a realm. By default, the provider supplies the value of java.naming.security.principal property as the authentication ID to any SASL mechanism that requires the authentication ID, the value of the java.naming.security.credentials property as the password, and the value of the java.naming.security.sasl.realm property as the realm. To override these defaults, use the java.naming.security.sasl.callback property.

SASL mechanisms support the notion of authorization identity or authorization ID, which is the entity to which the server should grant access if the authentication succeeds. If the java.naming.security.sasl.authorizationId property has been set, then its value is used as the authorization ID. Otherwise, the empty string is used as the authorization ID, which directs the server to derive an authorization ID from the client's authentication credentials.

See SASL properties for a description of the properties used by an LDAP service provider for supporting SASL.

In addition to these properties, there might be properties required for specific SASL mechanisms. For example, a SASL mechanism that supports privacy and integrity needs to know the quality of protection that the client requires. Properties such as these are passed to the SASL mechanism via the environment properties. See the JNDI documentation for how to set environment properties.

For example, if the application needs privacy, it can do so by using a call such as:

env.put("javax.security.sasl.qop", "auth-conf");

before passing env to the initial context constructor. See the Java SASL API for details about these properties.

12.2 SASL Mechanism Drivers

The Java SASL API provides a framework for dynamically plugging in SASL mechanism drivers. The LDAP provider might provide a few default drivers. See the Java SASL API for details.

13. Extensions and Controls

The provider supports LDAP extensions and controls using the javax.naming.ldap package. In addition, the provider supports LDAP unsolicited notifications (which are transmitted in LDAP extended operation responses) using the services of the javax.naming.event package.

Several LDAP extensions and controls are defined by the IETF LDAPEXT working group.

The "Start TLS" extension ("1.3.6.1.4.1.1466.20037") is supported by the StartTlsRequest and StartTlsResponse classes. The LDAP provider must provide a concrete implementation of the abstract StartTlsResponse class and make its implementation available to the LDAP provider. See the description in StartTlsRequest.createExtendedResponse. Typically, the StartTlsResponse implementation would need access to the LDAP provider's data structures.

The LDAP service provider should perform hostname verification after Start TLS negotiation as specified in RFC 2830. If the LDAP server was discovered automatically by using information in DNS (as described in the URLs section), the provider should use the domain name derived from the distinguished name as the hostname to verify, as recommended by draft-ietf-ldapext-locate-08.txt.

14. Event Notification

The provider supports event notification using the javax.naming.event package.

A JNDI application can register for events that occur in the directory, such as the addition or removal of an entry, or the modification of an entry. Applications can also register for unsolicited notifications.

15. SSL

The provider supports SSL according to the Java Secure Socket Extension (JSSE) specification. SSL is activated by setting the java.naming.security.protocol environment property as follows:

env.put(Context.SECURITY_PROTOCOL,
"ssl");
and by selecting the hostname and port number of an LDAP server that supports SSL. Once an SSL connection has been established subsequent LDAP protocol exchanges take place over that secure connection.

If, in addition, LDAP authentication is also required then the java.naming.security.authentication, java.naming.security.principal, and java.naming.security.credentials environment properties should be set, as appropriate. If LDAP authentication is required and the SSL credentials should be reused for LDAP authentication then set the java.naming.security.authentication environment property to select the SASL EXTERNAL mechanism, as follows:

env.put(Context.SECURITY_AUTHENTICATION, "EXTERNAL");

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JNDI/RMI Registry Service Provider

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

RMI Registry Service Provider for the
Java Naming and Directory Interface™ (JNDI)

Table of Contents

  • Introduction
  • Environment Properties
  • Names
  • RMI URLs
  • RMI URL Format
  • API Mapping
  • Bindings
  • Usage Examples
  • Security Considerations

Introduction

The RMI registry service provider allows JNDI applications to access remote objects registered with the RMI registry. Given the location of a registry, the provider will create a naming context with bindings for the objects registered there. Such a context may be bound into another JNDI-accessible namespace (such as LDAP, for example). References to individual remote objects may likewise be bound into another namespace.

A key benefit of binding registry contexts into other namespaces is location-independent access to remote objects: the RMI clients do not need to know the registry's host name or port number. RMI servers can take advantage of this to advertise their services to potential clients. In addition, remote objects can be linked into the same enterprise directory that is used to access information about people, organizations, and network resources.

With this service provider installed, JNDI subsumes the functionality of the java.rmi.Naming class.

This document describes the features of the RMI registry service provider.

Environment Properties

The following JNDI environment properties are used by the RMI registry service provider. See the JNDI documentation for a description of how properties are initialized using the environment properties, system properties, applet parameters, and resource files.

java.naming.factory.initial

This property is used to select the registry service provider as the initial context. It is not used by the provider itself. It specifies the class name of the initial context factory for the provider. For example:

env.put(Context.INITIAL_CONTEXT_FACTORY,
    "com.sun.jndi.rmi.registry.RegistryContextFactory");

This property is used in conjunction with the java.naming.provider.url property. This property must be set if you are using the registry as the initial context. The only exception is if you supply only URLs to the initial context, in which case, you don't need to specify this property. See RMI URLs for details.

java.naming.provider.url

This property specifies the location of the registry when the registry is being used as the initial context. It's value is an RMI URL with no object name component (see RMI URL Format below). For example:

env.put(Context.PROVIDER_URL, "rmi://server:1099");

The default value of this property is "rmi:", signifying a registry running on port 1099 of the local host.

This property is used in conjunction with the java.naming.factory.initial property.

java.naming.factory.state

A colon-separated list of the fully qualified class names of state factory classes used to get an object's state for storing given the object itself. You can use this mechanism to transform an object into forms that can be stored into the registry. The RMI registry service provider supports storing java.rmi.Remote, javax.naming.Reference, and javax.naming.Referenceable objects. See javax.naming.spi.NamingManager.getStateToBind() for details.

java.naming.factory.object

A colon-separated list of the fully qualified class names of object factory classes for transforming objects read from the registry. You can use this mechanism to transform an object into forms expected by the application. See javax.naming.spi.NamingManager.getObjectInstance() for details.

com.sun.jndi.rmi.factory.socket

This property specifies the socket factory for use by the RMI runtime in order to obtain the client sockets to make RMI calls. The value specified for the socket factory must be of the type java.rmi.server.RMIClientSocketFactory. If this property is not set, the default socket factory is used by the registry.

java.naming.rmi.security.manager

This property, when set to any value, indicates that the provider should attempt to install the RMISecurityManager. See the Security Considerations section below.

Names

The RMI registry supports a flat namespace. Since there is no hierarchy, every name is atomic. Each name may be composed of any characters, and case is significant.

Names are passed as arguments to the methods of a registry context, and are returned as the results of those methods, either as Name objects or as strings. When a Name object is used, it should have a single component whose value is the atomic name that will be passed on to the registry. When a string is used as a name, it is interpreted as the string representation of a composite name. So if ctx is a registry context, for example, then the following two unbind operations are equivalent:

String name = ...
ctx.unbind(name);
ctx.unbind(new CompositeName(name));

Care must be taken with names containing any of the four meta-characters that are treated specially during the parsing of composite names: '/', '\\', '"', and '\''. These characters must be properly escaped or quoted. The atomic name X/Y, for example, may be represented as the composite name X\/Y so as not to be mistaken for a two-component name with X and Y as its components. See CompositeName for more information.

RMI URLs

JNDI provides support for resolving URLs that name objects. The registry service provider allows RMI URLs to be used as names in this manner. This provides a generalization of the java.rmi.Naming functionality, only using the more general JNDI interface.

The class com.sun.jndi.url.rmi.rmiURLContextFactory implements a URL context factory for RMI URLs. This allows an RMI URL to be passed as a name to the default JNDI initial context.

RMI URL Format

The format of an RMI URL is one of the following:

   rmi://[host][:port][/[object]]

   rmi:[/][object]
If the object name is absent, then the URL names the registry at the given host and port. Otherwise, it names the remote object registered at that registry under the name provided.

If the host is omitted, the local host is assumed. If the port is omitted, the default registry port 1099 is assumed.

API Mapping

The registry service provider implements the java.naming.Context and java.naming.Referenceable interfaces. Context and Referenceable methods are mapped onto registry operations as described below.

lookup()
lookupLink()

The java.rmi.Registry.lookup() method is called. If the returned object is a wrapper around a javax.naming.Reference, the referenced object is created using javax.naming.spi.NamingManager.getObjectInstance(). JNDI links are not currently supported.

bind()

The java.rmi.Registry.bind() method is called. State factories are first consulted through javax.naming.spi.NamingManager.getStateToBind(). The object being bound must be of type java.rmi.Remote, javax.naming.Reference, or javax.naming.Referenceable. If the object is a javax.naming.Reference or javax.naming.Referenceable, its reference is wrapped in a Remote wrapper and then bound (see Binding Objects into the Registry below).

rebind()

The java.rmi.Registry.rebind() method is called. Objects are otherwise treated as for the JNDI bind() operation.

unbind()

The java.rmi.Registry.unbind() method is called.

rename()

This method is implemented as a sequence of JNDI operations: lookup(), bind(), unbind(). The sequence is not performed atomically.

list()

The java.rmi.Registry.list() method is called. As this provides no information about the types of the bound objects, each javax.naming.NameClassPair returned has the generic java.lang.Object as its class name.

listBindings()

The java.rmi.Registry.list() method is called. As each javax.naming.Binding is read from the resulting enumeration, java.rmi.Registry.lookup() is called and passed through javax.naming.spi.NamingManager.getObjectInstance().

createSubcontext()
destroySubcontext()

These operations are not supported.

getNameParser()

Returns a name parser for case-sensitive atomic names.

getNameInNamespace()

Returns the empty string (the name of the registry).

composeName()

Returns the composition of the two names.

addToEnvironment()

The specified property is added to the context's environment. If the java.naming.rmi.security.manager property is added, the provider will attempt to install the default RMI security manager (see Security Considerations). Other properties may be added or changed in the environment, but have no additional effect on the context.

removeFromEnvironment()

The specified property is removed from the context's environment. The context is otherwise unaffected.

close()

Clears internal state used by the provider, but otherwise has no immediate effect.

getReference()

If this context was constructed from a reference, a clone of that reference is returned. Otherwise a new reference for the context is returned, providing that the host name can be determined and is not "localhost" (see Binding Registry Contexts and Remote Objects below).

Bindings

Binding Objects into the Registry

An object may be bound into a registry context if it implements the java.rmi.Remote interface. An object may also be bound if it is a JNDI Reference object, or if it implements the Referenceable interface (in which case the corresponding reference will be bound in place of the object itself).

Binding Registry Contexts and Remote Objects

Each RMI registry context implements the Referenceable interface. It may therefore be bound into any JNDI-accessible namespace that can store Referenceable objects. A reference to an individual remote object that is registered with a registry may also be constructed, allowing that object to be bound into another namespace.

The class com.sun.jndi.rmi.registry.RegistryContextFactory implements the object factory that converts registry references into the corresponding registry contexts or remote objects.

For a registry context to be constructed, the registry's URL must be determined. This URL may come from the java.naming.provider.url property, or may be passed as a name to the initial context, or may be embedded in a registry reference. If the URL contains no host name or uses the host name "localhost", then the registry context's getReference() method is unable to return a reference for the context. Such a registry context, therefore, cannot be bound into another namespace.

Registry Reference Format

A JNDI reference for an RMI registry contains a list of string addresses (class StringRefAddr), each tagged with the type "URL". Each address contains an RMI URL locating either a registry, or a remote object registered with a registry (see RMI URL Format above).

When multiple URLs appear within a single reference, each represents an alternative address for the same logical resource. The order of the addresses is not significant. Addresses not of class StringRefAddr, or not of address type "URL", are ignored.

Usage Examples

Example 1

To create an initial context that accesses a registry, set the properties java.naming.factory.initial and java.naming.provider.url as described in Environment Properties above. Then the names stored in the registry, for example, may be listed as follows:

Context ictx = new InitialContext(env);
NamingEnumeration enum = ictx.list("");

Example 2

Instead of using the properties as above, you may pass an RMI URL as a name to resolve in the default initial context:

Context registryCtx = (Context)ictx.lookup("rmi://host");

Example 3

A registry context may be bound into another JNDI-accessible namespace. To bind registryCtx (from the preceding example) into an LDAP directory, for example:

Context ldapCtx = (Context)ictx.lookup("ldap://server/o=sun,c=us");
ldapCtx.bind("cn=rmi", registryCtx);
If the names R1 and R2 are bound in this registry, then a JNDI client browsing the LDAP namespace will see R1 and R2 beneath the cn=rmi entry.

Example 4

A remote object that is registered with an RMI registry may be bound into another JNDI-accessible namespace by constructing a reference for that object. If the variable obj holds the object named R1 from the preceding examples, it may be bound into an LDAP directory as follows:

RefAddr addr = new StringRefAddr("URL", "rmi://host/R1");
Reference ref = new Reference(obj.getClass().getName(), addr);
ldapCtx.bind("cn=R1", ref);

Security Considerations

Security Manager

The usual security considerations of RMI apply. For RMI to dynamically load classes from a remote server, a security manager must first be installed. This can be done in the same way as it would for any other RMI application. See the JavaTM Remote Method Invocation Specification. Or, if the environment property java.naming.rmi.security.manager is passed to the provider, then the provider will attempt to install the RMISecurityManager itself.

Permissions

The application using JNDI and the RMI registry provider must be granted the following permissions:

permission java.net.SocketPermission "host[:port]", "connect";

For each host/port identified in the java.naming.provider.url property and in URL string names supplied to context methods.

permission java.net.SocketPermission "host[:port]", "connect,accept";

For each host/port identified in the URL strings in javax.naming.References.

permission java.lang.RuntimePermission "setSecurityManager";

If using the java.naming.rmi.security.manager environment property, which asks the RMI registry provider to install the RMISecurityManager.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


1 Introduction

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

1. Introduction

Directory services play a vital role in Intranets and Internets by providing access to a variety of information about users, machines, networks, services, and applications. By its very nature, a directory service incorporates a naming facility for providing human understandable namespaces that characterize the arrangement and identification of the various entities.

The computing environment of an enterprise typically consists of several naming facilities often representing different parts of a composite namespace. For example, the Internet Domain Name System (DNS) might be used as the top-level naming facility for different organizations within an enterprise. The organizations themselves might use a directory service such as LDAP or NDS or NIS. From a user's perspective, there is one namespace consisting of composite names. URLs are examples of composite names because they span namespaces of multiple naming facilities. Applications which use directory services must support this user perspective.

Many JavaTM application developers can benefit from a directory service API that is not only independent of the particular directory or naming service implementation, but also enables seamless access to directory objects through multiple naming facilities. In fact, any application can attach its own objects to the namespace. Such a facility enables any Java application to discover and retrieve objects of any type.

End users can benefit from logical namespaces that allow easier discovery and identification of the objects in the network.

Directory service developers can benefit from a service-provider capability that enables them to incorporate their respective implementations without requiring changes to the client.

Java Naming and Directory InterfaceTM (JNDI) is an API that provides directory and naming functionality to Java applications. It is defined to be independent of any specific directory service implementation. Thus, a variety of directories can be accessed in a common way.

Here are two examples to briefly illustrate some of the more commonly used features of JNDI.

An application that wants to access a printer needs the corresponding printer object. This is simply done as follows:

prt = (Printer) building7.lookup("puffin");
prt.print(document);

JNDI does all the work of locating the information needed to construct the printer object.

An application that wants to find a person's phone numbers, which are stored in the organization's directory, can simply do:

String[] attrs = {"workPhone", "cellPhone", "faxNumber"};
bobsPhones = directory.getAttributes("cn=Bob, o=Widget, c=US", attrs);

If there may be several Bobs in the Widget organization, the application can search the organization's directory to find the right Bob as follows:

bob = directory.search("o=Widget, c=US", "(cn=Bob)", searchctls);

This document describes the architecture and interfaces of JNDI.

CONTENTS | PREV | NEXT

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


2 Goals and Design Principles

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

2. Goals and Design Principles

We followed several principles and maxims in designing the API.

2.1 Keep it consistent and intuitive

Wherever possible, we have used existing components from the rest of the Java development environment. Adhering to this principle not only makes JNDI consistent with existing core classes in the Java platform but also reduces needless proliferation of classes.

The object-oriented nature of the Java programming language allows for an intuitive and simple API design, in which the directory service functionality is expressed as a natural extension to the more fundamental naming service functionality.

2.2 Pay for what you use

The API is structured in a tiered manner so that the application programmer interested in a certain directory service capability need not necessarily know about a more advanced capability. We have strived to keep the lower tiers simple and also make them represent the common case capability, relegating the more complex ones to the upper tiers.

2.3 Implementable over common directory and naming services and protocols

This goal is important for two reasons. First, it enables Java applications to take advantage of information in a variety of existing naming and directory services such as DNS, NDS, NIS (YP), X.500, and LDAP. Second, it helps limit the appearance of any implementation specific artifacts in the API.

Providing a unified interface to multiple naming and directory services does not imply that access of unique features of a particular service is precluded. The unified API which is designed to cover the common case is still beneficial to applications that have explicit knowledge of the underlying naming or directory service. Such applications still benefit from sharing the common portions that use the API. This is analogous to applications sharing commonly used classes and yet adding needed specificity via subclassing.

2.4 Seamless integration

This is important not only because of the diversity of directory service and naming services in the installed base that need to be supported, but also because new Java application and service programmers can export their own namespaces and directory objects in a uniform way.

We also wanted to make a variety of implementation choices possible without having the application pay for this freedom. For example, a "thin-client" might be better served by a proxy-style protocol in which the access to specific naming and directory services is relegated to a server. Whereas, a performance sensitive, resource rich client, might choose to use an implementation which directly allows it to access the various servers. However, the application should be insulated from these implementation choices. It should be possible to defer such choices even until runtime.

2.5 Support for leading industry standards

The Lightweight Directory Access Protocol (Internet RFC 2251) has emerged as the standard for directory access at the protocol level. All major directory vendors have products that support this protocol. An application that uses JNDI should be able to access all of the features offered by this standard. Where possible, JNDI should support conventions (such as those for specifying search queries/filters) already defined by the standard.

CONTENTS | PREV | NEXT

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


3 Overview of the Architecture

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

3. Overview of the Architecture

The JNDI architecture consists of the JNDI API and the JNDI SPI. The JNDI API allows Java applications to access a variety of naming and directory services. The JNDI SPI is designed to be used by arbitrary service providers including directory service providers. This enables a variety of directory and naming services to be plugged in transparently to the Java application (which uses only the JNDI API). The JNDI Architecture figure shows the JNDI architecture and includes a few service providers of directory and naming contexts as examples.

JNDI Architecture

Graphic with the following from top to bottom: Java application, JNDI API, JNDI Naming Manager, JNDI SPI, and RMI, CORBA, LDAP and NDS on the bottom row.

CONTENTS | PREV | NEXT

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


4 Fundamentals

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

4. Fundamentals

A directory service provides access to diverse kinds of information about users and resources in a network environment. It uses a naming system for the purpose of identifying and organizing directory objects to represent this information. A directory object provides an association between attributes and values. Thus, a directory service enables information to be organized in a hierarchical manner to provide a mapping between human understandable names and directory objects.

4.1 Naming -- The Foundation

A fundamental facility in any computing system is the naming service - the means by which names are associated with objects, and by which objects are found given their names. In traditional systems, the naming service is seldom a separate service. It is usually integrated with another service, such as a file system, directory service, database, desktop, mail system, spreadsheet, or calendar. For example, a file system includes a naming service for files and directories; a spreadsheet has a naming service for cells and macros.

The computing environment of an enterprise typically consists of several naming services. There are naming services that provide contexts for naming common entities in an enterprise such as organizations, physical sites, human users and computers. Naming services are also incorporated in applications offering services such as file service, mail service, printer service, and so on. From a user's perspective, there exist several natural and logical relationships between these naming services. For example, it is natural to think of naming a variety of services such as files, mail, appointment calendar, and so on, in the context of a user. It is also natural to think of a user in the context of a department, within a division of an enterprise. Meaningful names can be composed using useful arrangements of naming services reflecting these relationships.

Every name is generated by a set of syntactic rules called a naming convention. An atomic name is an indivisible component of a name, as defined by the naming convention.

A compound name represents a sequence of zero or more atomic names composed according to the naming convention.

For example, in UNIX pathnames, atomic names are ordered from left to right, and are delimited by slash (`/') characters. The UNIX pathname usr/local/bin is a compound name representing the sequence of atomic names, usr , local , and bin . In names from the Internet Domain Name System (DNS), atomic names are ordered from right to left, and are delimited by dot (`.') characters. Thus, the DNS name sales.Wiz.COM is a compound name representing the sequence of atomic names, COM , Wiz , sales .

The association of an atomic name with an object is called a binding.

A context is an object whose state is a set of bindings with distinct atomic names. Every context has an associated naming convention. A context provides a lookup (resolution) operation that returns an object, and may provide operations such as for binding names, unbinding names, listing bound names. An atomic name in one context object can be bound to another context object of the same type, called a subcontext, giving rise to compound names.

Resolution of compound names proceeds by looking up each successive atomic component in each successive context. The reader will find a familiar model in UNIX file naming, where directories serve as contexts, and pathnames may be compound names.

A naming system is a connected set of contexts of the same type (having the same naming convention) and providing the same set of operations with identical semantics.

A namespace is the set of all names in a naming system.

A composite name is a name that spans multiple naming systems. It consists of an ordered list of zero or more components. Each component is a name from the namespace of a single naming system.

For example, the name jurassic.eng:/export/home/jdoe/.signature is a composite name representation made up of a host name jurassic.eng from a host namespace, and the file name /export/home/jdoe/.signature from a UNIX file namespace. Another example is the Internet URL http://www.moon.org/public/index.html , which is a composite name representation made up of the scheme-id http from the "URL scheme-id" namespace, www.moon.org which is the DNS name of the machine on which the web server is running, and public/index.html which is a file name from a file namespace.

Every name is interpreted relative to some context, and every naming operation is performed on a context object. A client can obtain an initial context object that provides a starting point for resolution of names.

4.2 Directory Objects

The primary function of a naming system is to map names to objects. The objects can be of any type. A directory object is a particular type of object that is used to represent the variety of information in a computing environment. A directory object can have associated with it attributes. An attribute has an identifier and a set of values.

A directory object provides operations for creating attributes, adding, removing, and modifying attributes associated with the directory object. If we make a directory object also be a naming context, we can represent trees of directory information where the interior nodes not only behave like naming contexts but also contain attributes.

The Example of a Composite Namespace figure is an example used for illustrating several things.

Example of a Composite Namespace

The following context describes this graphic
  • There can be multiple naming systems that can be represented by a composite namespace. In this case, DNS is used as the global naming system; one division uses NDS, while a second division uses LDAP.
  • Each namespace has interior nodes that represent naming contexts, which may be directory objects as well. Leaf nodes can be objects of any type.
  • The InitialContext is configured to have bindings to useful starting contexts in different naming and directory systems.
  • Applications just see a composite namespace. They can access any type of object bound in any naming system in this arrangement.
  • Services can incorporate their own namespaces which appear as first-class citizens in JNDI.
  • Arbitrary directory services can be added and accessed without requiring client applications to be changed.

4.3 URLs and Composite Names

Uniform Resource Locators (URLs) are special composite names whose syntax are determined by the URL's definition. Clients of JNDI can use URLs to refer to arbitrary types of objects. For example, a client can use nfs://nfs.sun.com/export/jndi/src/README to refer to a file object that is being accessed using the Network File System (NFS) protocol. Similarly, a client can perform directory operations on a directory object in an LDAP server using the URL ldap://ldap.widget.com/cn=Jonathan,ou=marketing .

To support composite names in general, JNDI defines a composite name syntax and utilities for processing composite names. This allows clients of JNDI to refer to objects using names that span multiple namespaces.

4.4 Events

As the naming/directory service plays an increasingly important role in the computing environment, the need to provide administration and monitoring tools to help manage changes in the service also increases. For such tools and other applications, the traditional request/response style of interaction needs to be augmented with an asynchronous notification model that allows applications to register interest in changes in the service.

CONTENTS | PREV | NEXT

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


5 Overview of the Interface

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

5. Overview of the Interface

The JNDI API is contained in four packages:

  • javax.naming contains classes and interfaces for accessing naming services
  • javax.naming.directory extends the core javax.naming package to provide access to directories
  • javax.naming.event contains classes and interfaces for supporting event notification in naming and directory services
  • javax.naming.ldap contains classes and interfaces for supporting LDAP v3 extensions and controls

The JNDI service provider interface is contained one package:

  • javax.naming.spi contains classes and interfaces that allow various naming and directory service providers to be dynamically plugged in beneath the JNDI API (see the JNDI SPI document for details)

The following sections provide an overview of the JNDI API. For more details on the API, see the corresponding javadoc.

5.1 The Naming Package -- javax.naming 1

The javax.naming package. The information in this graphic is available in the API documentation.

(exception classes are not shown)

5.1.1 Contexts

Context is the core interface that specifies a naming context. It defines basic operations such as adding a name-to-object binding, looking up the object bound to a specified name, listing the bindings, removing a name-to-object binding, creating and destroying subcontexts of the same type, etc.

public interface Context {
    public Object lookup(Name name) throws NamingException;
    public void bind(Name name, Object obj) throws NamingException;
    public void rebind(Name name, Object obj) throws NamingException;
    public void unbind(Name name) throws NamingException;
    public void rename(Name old, Name new) throws NamingException;
    public NamingEnumeration listBindings(Name name) throws NamingException;
    ...
    public Context createSubcontext(Name name) throws NamingException;
    public void destroySubcontext(Name name) throws NamingException;
    ...
};

Every naming method in Context takes a name as an argument. The operation defined by the method is performed on the Context object that is obtained by implicitly resolving the name. If the name is empty ("") the operation is performed directly on the context itself. The name of an object can be a composite name reflecting the arrangement of the namespaces used to refer to the object. Of course, the client is not exposed to any naming service implementation. In fact, a new type of naming service can be introduced without requiring the application to be modified or even disrupted if it is running.

5.1.2 The Initial Context

In JNDI, every name is relative to a context. There is no notion of "absolute names." An application can bootstrap by obtaining its first context of class InitialContext :

public class InitialContext implements Context {
    public InitialContext()...;
    ...
}

The initial context contains a variety of bindings that hook up the client to useful and shared contexts from one or more naming systems, such as the namespace of URLs or the root of DNS.

5.1.3 Names

The Name interface represents a generic name--an ordered sequence of components. Each Context method that takes a Name argument has a counterpart that takes the name as a String instead. The versions using Name are useful for applications that need to manipulate names: composing them, comparing components, and so on. The versions using String are likely to be more useful for simple applications, such as those that simply read in a name and look up the corresponding object. The String name parameter represents a composite name. The Name parameter can represent a composite name or a compound name .

The CompositeName class represents a sequence of names (atomic or compound) from multiple namespaces. If the Name parameter supplied to a method of the Context class is an instance of CompositeName , the name represents a composite name.

If the Name parameter supplied to a method of the Context class is not an instance of CompositeName , the name represents a compound name, which can be represented by the CompoundName class or some other implementation class. The CompoundName class represents hierarchical names from a single namespace. A context's name parser can be used to manipulate compound names in the syntax associated with that particular context:

public interface Context {
    ...
    public NameParser getNameParser(Name name) throws NamingException;
    ...
}

A namespace browser is an example of the kind of application that might need to manipulate names syntactically at this level. Most other applications will work with strings or composite names.

5.1.4 Bindings

Context.lookup() is the most commonly used operation. The context implementation can return an object of whatever class is required by the Java application. For example, a client might use the name of a printer to look up the corresponding Printer object, and then print to it directly:

Printer printer = (Printer) ctx.lookup("treekiller");
printer.print(report);

Context.listBindings() returns an enumeration of name-to-object bindings, each binding represented by an object of class Binding . A binding is a tuple containing the name of the bound object, the name of the object's class, and the object itself.

The Context.list() method is similar to listBindings() , except that it returns an enumeration of NameClassPair objects. Each NameClassPair contains an object's name and the name of the object's class. The list() method is useful for applications such as browsers that wish to discover information about the objects bound within a context, but don't need all of the actual objects. Although listBindings() provides all of the same information, it is potentially a much more expensive operation.

public class NameClassPair ... {
    public String getName() ...;
    public String getClassName() ...;
    ...
}
public class Binding extends NameClassPair {
    public Object getObject() ...;
    ...
}

5.1.5 References

Different Context implementations are able to bind different kinds of objects natively. A particularly useful object that should be supported by any general-purpose context implementation is the Reference class. A reference represents an object that exists outside of the directory. References are used to give JNDI clients the illusion that objects of arbitrary classes are able to be bound in naming or directory services--such as X.500--that do not have native support for objects in the Java programming language.

When the result of an operation such as Context.lookup() or Binding.getObject() is a Reference object, JNDI attempts to convert the reference into the object that it represents before returning it to the client. A particularly significant instance of this occurs when a reference representing a Context of one naming system is bound to a name in a different naming system. This is how multiple independent naming systems are joined together into the JNDI composite namespace. Details of how this mechanism operates are provided in the JNDI SPI document.

Objects that are able to be represented by a reference should implement the Referenceable interface. Its single method -- getReference() -- returns the object's reference. When such an object is bound to a name in any context, the context implementation might store the reference in the underlying system if the object itself cannot be stored natively.

Each reference may contain the name of the class of the object that it represents, and may also contain the location (typically a URL) where the class file for that object can be found. In addition, a reference contains a sequence of objects of class RefAddr . Each RefAddr in turn contains a "type" string and some addressing data, generally a string or a byte array.

A specialization of Reference called a LinkRef is used to add "symbolic" links into the JNDI namespace. It contains the name of a JNDI object. By default, these links are followed whenever JNDI names are resolved.

5.1.6 Referrals

Some naming/directory services support the notion of referrals for redirecting a client's request to another server. The JNDI client can request that referrals be automatically followed, be ignored, or be processed manually.

The abstract class ReferralException is used to represent a referral:

public abstract class ReferralException extends NamingException {
    public abstract Context getReferralContext() throws NamingException;
    ...
    public abstract Object getReferralInfo();
    public abstract void retryReferral();
    public abstract boolean skipReferral();
}

When a referral is encountered and the client has requested that referrals not be ignored or automatically followed, a ReferralException is thrown. The getReferralInfo() method provides information--in a format appropriate to the service provider--about where the referral leads. The application is not required to examine this information; however, it might choose to present it to a human user to help him determine whether to follow the referral or not. skipReferral() allows the application to discard a referral and continue to the next referral (if any).

To continue the operation, the application re-invokes the method on the referral context using the same arguments it supplied to the original method.

5.2 The Directory Package -- javax.naming.directory 2

The javax.naming.directory package.

(exception classes are not shown)

5.2.1 Directory Objects

The DirContext interface enables the directory capability by defining methods for examining and updating attributes associated with a directory object.

public interface DirContext extends Context {
    public Attributes getAttributes(Name name)
                 throws NamingException;
    public Attributes getAttributes(Name name, String[] attrIds)
                 throws NamingException;
    ...
    public void modifyAttributes(Name name, int modOp, Attributes attrs)
                 throws NamingException;
    public void modifyAttributes(Name name, ModificationItem[] mods)
                 throws NamingException;
    ...
}

The getAttributes() operations on a directory return some or all of its attributes. Attributes are modified using two forms of modifyAttributes() . Both forms make use of a "modification operation," one of:

ADD_ATTRIBUTE
REPLACE_ATTRIBUTE
REMOVE_ATTRIBUTE

The ADD_ATTRIBUTE operation adds values to an attribute if that attribute already exists, while the REPLACE_ATTRIBUTE operation discards any pre-existing values. The first form of modifyAttributes() performs the specified operation on each element of a set of attributes. The second form takes an array of objects of class ModificationItem :

public class ModificationItem {
    public ModificationItem(int modOp, Attribute attr) ...;
    ...
}

Each operation is performed on its corresponding attribute in the order specified. When possible, a context implementation should perform each call to modifyAttributes() as an atomic operation.

5.2.2 Attributes

A directory object contains a set of zero or more Attribute objects. Each attribute is denoted by a string identifier and can have zero or more values of any type.

public interface Attribute ... {
    ...
    public String getID();
    public Object get(int n) throws NamingException;
    public boolean isOrdered();
    public NamingEnumeration getAll()
           throws NamingException;
    ...
}

An attribute's values can be ordered or unordered. If the values are unordered, no duplicates are allowed. If the values are ordered, duplicates are allowed.

Attributes are grouped into a collection by using the Attributes interface.

public interface Attributes ... {
    ...
    public Attribute get(String attrID);
    public NamingEnumeration getIDs();
    public NamingEnumeration getAll();
    public Attribute put(Attribute attr);
    public Attribute remove(String attrID);
    ...
}

JNDI provides implementations for these two interfaces, BasicAttribute and BasicAttributes , for convenience. Service providers and applications are free to use their own implementations.

Note that updates to Attributes and Attribute , such as adding or removing an attribute or its value, do not affect the corresponding representation in the directory. Updates to the directory can only be effected by using DirContext.modifyAttributes() .

5.2.3 Directory Objects as Naming Contexts

The DirContext interface also behaves as a naming context by extending the Context interface. This means that any directory object can also provide a naming context. In addition to a directory object keeping a variety of information about a person, for example, it is also a natural naming context for resources associated with that person: a person's printers, file system, calendar, etc.

Hybrid operations perform certain naming and directory operations in a single atomic operation:

public interface DirContext extends Context {
    ...
    public void bind(Name name, Object obj, Attributes attrs)
           throws NamingException;
    ...
}

Other hybrid operations that are provided are rebind() and createSubcontext() that accept an additional Attributes argument.

5.2.4 The Initial Context

An application that is performing directory operations can use InitialDirContext instead of javax.naming.InitialContext to create its initial context:

public class InitialDirContext
       extends InitialContext implements DirContext {
    public InitialDirContext() ...;
    ...
}

It can then invoke any method in the Context or DirContext interface on the initial context.

5.2.5 Searches

The DirContext interface supports content-based searching of directories. In the simplest and most common form of usage, the application specifies a set of attributes -- possibly with specific values -- to match. It then invokes the DirContext.search() method on the directory object, which returns the matching directory objects along with the requested attributes.

public interface DirContext extends Context {
    ...
    public NamingEnumeration search(Name name, Attributes matchingAttributes)
                 throws NamingException;
    public NamingEnumeration search(Name name,
                                    Attributes matchingAttributes,
                                    String[] attributesToReturn)
                 throws NamingException;
    ...
}

The results of the search are returned as a NamingEnumeration containing an enumeration of objects of class SearchResult :

public class SearchResult extends Binding {
    ...
    public Attributes getAttributes() ...;
}

In the more sophisticated case, it is possible to specify a search filter and to provide controlling information such as the scope of the search and the maximum size of the results. The search filter specifies a syntax that follows Internet RFC 2254 for LDAP. The SearchControls argument specifies such things as the scope of the search: this can include a single directory object, all of its children, or all of its descendants in the directory hierarchy.

public interface DirContext extends Context {
    ...
    public NamingEnumeration search(Name name,
                                    String filter,
                                    SearchControls ctls)
           throws NamingException;

    public NamingEnumeration search(Name name,
                                    String filter,
                                    Object[] filterArgs,
                                    SearchControls ctls)
                throws NamingException;
        ...
}

5.2.6 Schema

A schema describes the rules that define the structure of a namespace and the attributes stored within it. The granularity of the schema can range from a single schema that is associated with the entire namespace, to a per-attribute, fine-grained schema description.

Because schemas can be expressed as an information tree, it is natural to use for this purpose the naming and directory interfaces already defined in JNDI. This is powerful because the schema part of a namespace is accessible to applications in a uniform way. A browser, for example, can access information in the schema tree just as though it were accessing any other directory objects.

Applications can retrieve the schema associated with a directory object when the underlying context implementation provides the appropriate support.

DirContext.getSchema() is used to retrieve the root of the schema tree associated with a directory object. The root has children such as "ClassDefinition", "AttributeDefinition", and "SyntaxDefinition", each denoting the kind of definition being described. The schema root and its descendents are objects of type DirContext . The DirContext.getSchemaClassDefinition() method returns a DirContext that contains class descriptions about a particular directory object.

public interface DirContext extends Context {
        ...
        public DirContext getSchema(Name name)
                throws NamingException;

        public DirContext getSchemaClassDefinition(Name name)
                throws NamingException;
        ...
}

In addition, the schema associated with any attribute can be accessed using the Attribute.getAttributeDefinition() and getAttributeSyntaxDefinition() methods.

public interface Attribute ... {
    ...
    public DirContext getAttributeDefinition() throws NamingException;
    public DirContext getAttributeSyntaxDefinition()
    throws NamingException;
    ...
}

Example mapping Directory to Schema is an example showing the different associations for accessing schema information.

Example mapping Directory to Schema

Example mapping Directory to Schema

5.3 The Event Package -- javax.naming.event 3

The javax.naming.event package. The information in this graphic is available in the <a href= API documentation." WIDTH="769" HEIGHT="258" ALIGN="BOTTOM" BORDER="0" >

The javax.naming.event package contains classes and interfaces for supporting event notification in naming and directory services.

5.3.1 Naming Events

A NamingEvent represents an event that is generated by a naming/directory service.

public class NamingEvent extends java.util.EventObject {
    ...
    public int getType();
    public Binding getOldBinding();
    public Binding getNewBinding();
    ...
}

The event's type identifies the type of event. The NamingEvent class defines four types of events:

  1. OBJECT_ADDED
  2. OBJECT_REMOVED
  3. OBJECT_RENAMED
  4. OBJECT_CHANGED

These types can be placed into two categories:

  • Those that affect the namespace (add/remove/rename an object)
  • Those that affect an object's contents

In addition to the event's type, a NamingEvent contains other information about the change, such as information about the object before and after the change.

5.3.2 Naming Listeners

A naming listener is an object that registers for NamingEvent s. It is represented by the interface NamingListener . Each category of NamingEvent is handled by a corresponding subtype of NamingListener . The NamespaceChangeListener interface represents a listener interested in namespace changes, while the ObjectChangeListener represents a listener interested in changes to an object's contents. A listener implementation might implement one or both of these interfaces, depending on the types of events it is interested in.

5.3.3 Event Registration and Deregistration

The EventContext and EventDirContext interfaces extend the Context and DirContext interfaces, respectively, to support event registration and deregistration.

public interface EventContext extends Context {
    ...
    public void addNamingListener(Name target,
                                  int scope,
                                  NamingListener l)
           throws NamingException;
    public void removeNamingListener(NamingListener l)
           throws NamingException;
    public boolean targetMustExist()
           throws NamingException;
}

Like methods in the corresponding Context interface, addNamingListener() has an overload that accepts a String name argument. The name parameter is referred to as the target . The scope parameter specifies whether the registration is for the object named by the target, the immediate children of the context named by the target, or the entire subtree rooted at the object named by the target.

It is possible to register interest in a target that does not exist, but there might be limitations in the extent to which this can be supported by the service provider and underlying protocol/service. An application can use the method targetMustExist() to check whether an EventContext supports registration of nonexistent targets.

public interface EventDirContext extends EventContext, DirContext {
    public void addNamingListener(Name target,
                                  String filter,
                                  SearchControls ctls,
                                  NamingListener l)
                throws NamingException;
    public void addNamingListener(Name target,
                                  String filter,
                                  Object[] filterArgs,
                                  SearchControls ctls,
                                  NamingListener l)
                throws NamingException;
    ...
}

The EventDirContext interface extends the EventContext and DirContext interfaces to allow a listener to register interest in objects identified using search filters (Internet RFC 2254).

Like methods in the corresponding DirContext interface, addNamingListener() methods have overloads that accept a String name argument.

The EventContext/EventDirContext instance on which the addNamingListener() method is invoked is the event source of the events that are (potentially) generated. When the registered listener invokes getSource() or getEventContext() on a NamingEvent , the result will be this EventContext / EventDirContext instance.

For example, suppose a listener makes the following registration:

NamespaceChangeListener listener = ...;
src.addNamingListener("x", SUBTREE_SCOPE, listener);

When an object named "x/y" is subsequently deleted, the corresponding NamingEvent ( evt ) delivered to listener must contain src as its event source. The following will both be true:

evt.getEventContext() == src
evt.getOldBinding().getName().equals("x/y")

5.3.4 Exception Handling

When a listener registers for events with a context, the context might need to do some internal processing in order to collect information required to generate the events. The context, for example, might need to make a request to the server to register interest in changes on the server that will eventually be translated into events. If an error occurs that prevents information about the events from being collected, the listener will never be notified of the events. When such an error occurs, a NamingExceptionEvent is fired to notify the listener, and the listener is automatically deregistered.

The base NamingListener interface defines a namingExceptionThrown() method so that a listener can be notified of such an error.

public interface NamingListener extends java.util.EventListener {
    public void namingExceptionThrown(NamingExceptionEvent evt);
}

5.4 The LDAP Package -- javax.naming.ldap 4

The javax.naming.ldap package. The information in the graphic is available in the <a href= API documentation." WIDTH="826" HEIGHT="429" ALIGN="BOTTOM" BORDER="0" >

The javax.naming.ldap package contains classes and interfaces for using LDAP v3-specific features that are not already covered by the more generic javax.naming.directory package. In fact, the majority of JNDI applications that use LDAP will find the javax.naming.directory package sufficient, and will not need to use this package at all. This package is primarily for those applications that need to use extended operations, controls, or unsolicited notifications.

5.4.1 Extended Operations

In addition to specifying well-defined operations such as search and modify, the LDAP v3 protocol (Internet RFC 2251) specifies a way of transmitting yet-to-be defined operations between the LDAP client and server. These operations are referred to as extended operations . An extended operation may be defined by a standards organization such as the IETF or by a vendor.

The LdapContext interface defines a method for executing an extended operation:

public interface LdapContext extends DirContext {
    public ExtendedResponse extendedOperation(ExtendedRequest request)
           throws NamingException;
    ...
}

The ExtendedRequest interface represents the argument to an extended operation, while the ExtendedResponse interface represents the result of the extended operation. An ExtendedRequest or ExtendedResponse consists of an identifier that identifies the extended operation and a byte array containing the ASN.1 BER encoded contents of the request/response.

An application typically does not deal directly with the ExtendedRequest / ExtendedResponse interfaces. Instead, it deals with classes that implement these interfaces. The application gets these classes either as part of a repertoire of extended operations standardized through the IETF, or from directory vendors for vendor-specific extended operations. The request classes should have constructors that accept arguments in a type-safe and user-friendly manner, while the response classes should have access methods for getting the data of the response in a type-safe and user-friendly manner. Internally, the request/response classes deal with encoding and decoding BER values.

For example, suppose an LDAP server supports a "get time" extended operation. It would supply classes such as GetTimeRequest and GetTimeResponse , so that applications can use this feature. An application would use these classes as follows:

GetTimeResponse resp =
   (GetTimeResponse)lctx.extendedOperation(new GetTimeRequest());
long time = resp.getTime();

5.4.2 Controls

The LDAP v3 protocol (Internet RFC 2251) allows any request or response to be augmented by yet-to-be defined modifiers. These modifiers are referred to as controls . Controls that are sent with requests are called request controls and those that are sent with responses are called response controls . A control may be defined by a standards organization such as the IETF or by a vendor. There is not necessarily a pairing between request controls and response controls.

JNDI classifies request controls into two categories:

  • connection request controls: those that affect how a connection is created
  • context request controls: those that affect context methods

Connection request controls are used whenever a connection needs to be established or re-established with an LDAP server. Context request controls are used when all other LDAP operations are sent to the LDAP server. The reason for this distinction is because JNDI is a high-level API that does not deal directly with connections. It is the job of service providers to do any necessary connection management. Hence, a single connection might be shared by multiple context instances, and a service provider is free to use its own algorithms to conserve connection and network usage. Thus, when a method is invoked on the context instance, the service provider might need to do some connection management in addition to performing the corresponding LDAP operations. For connection management, it uses the connection request controls, while for the normal LDAP operations, it uses the context request controls.

The LdapContext interface defines methods for dealing with controls:

public interface LdapContext extends DirContext {
    public void reconnect(Control[] connCtls) throws NamingException;
    public Control[] getConnectControls() throws NamingException;
    ...
    public LdapContext newInstance(Control[] reqCtls)
           throws NamingException;
    public void setRequestControls(Control[] reqCtls)
           throws NamingException;
    public Control[] getRequestControls() throws NamingException;
    ...
    public Control[] getResponseControls() throws NamingException;
}

The Control interface represents a control. It consists of an identifier that identifies the control and a byte array containing the ASN.1 BER encoded contents of the control.

Connection request controls are initialized using the initial context constructor and are inherited by contexts that are derived from a context. reconnect() is used to change the connection request controls of a context. A context's connection request controls are retrieved using getConnectControls() .

Context request controls are initialized using newInstance() and changed using setRequestControls() . newInstance() is a convenience method for creating a new instance of a context for the purposes of multithreaded access. For example, if multiple threads want to use different context request controls, each thread may use this method to get its own copy of this context and set/get context request controls without having to synchronize with other threads.

Unlike connection request controls, context request controls are not inherited by context instances that are derived from a context. Derived context instances are initialized with no context request controls. You must set the request controls of a derived context instance explicitly using setRequestControls() . A context's context request controls are retrieved using getRequestControls() .

5.4.3 The Initial Context

An application that is performing LDAP extended operations or controls can use InitialLdapContext instead of javax.naming.InitialContext or javax.naming.directory.InitialDirContext to create its initial context:

public class InitialLdapContext extends InitialDirContext implements LdapContext {
    public InitialDirContext() ...;
    public InitialDirContext(Hashtable env, Control[] connCtls) ...;
}

It can then invoke any method in the Context , DirContext , or LdapContext interfaces on the initial context. By using the constructor that accepts a connCtls argument, the application can specify controls to be used when establishing a connection with the LDAP server.

5.4.4 Unsolicited Notifications

In addition to the normal request/response style of interaction between the client and server, the LDAP v3 protocol also specifies unsolicited notifications --messages that are sent from the server to the client asynchronously, not in response to any client request.

JNDI supports unsolicited notifications using the event model embodied in the javax.naming.event package. It defines an UnsolicitedNotificationEvent class and a corresponding UnsolicitedNotificationListener interface. An application registers to receive UnsolicitedNotificationEvent s by supplying an UnsolicitedNotificationListener to EventContext.addNamingListener() .

1. See Appendix C for legend of class diagram.

2. See Appendix C for legend of class diagram.

3. See Appendix C for legend of class diagram.

4. See Appendix C for legend of class diagram.

CONTENTS | PREV | NEXT

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


6 Configuration

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

6. Configuration

6.1 Environment Properties

Some JNDI applications need a way to communicate various preferences and information that define the environment in which naming and directory services are accessed. For example, an application might need to specify the level of security for accessing a directory service. Or, when directory and naming services are distributed, the source of information is in more than one place--replicas, master, caches, etc. An application might want to access information from the authoritative source and needs to indicate this information to the JNDI system.

To address these requirements, JNDI defines a number of properties that developers and users can use to provide configuration information to the JNDI system. These are called environment properties .

There are different types of environment properties:

  • Standard JNDI environment properties. These properties are defined by JNDI and are common across all service providers. They are defined in relatively generic terms. For example, the property "java.naming.security.principal" is used to specify the security principal for authentication to the naming service. Individual service providers map these environment properties to an interpretation appropriate for their service. These properties have the prefix "java.naming.". contains a list of standard JNDI environment properties. The Context interface defines constants for most of these environment property names.
  • Service-specific environment properties. These properties are common across all service providers that implement a particular service or protocol. They have the prefix "java.naming. service. ", where service is the name of the service. For example, the prefix "java.naming.ldap." is used for LDAP-specific environment properties.
  • Feature-specific environment properties. These properties are common across all service providers that support a particular feature. They have the prefix "java.naming. feature .", where feature is the name of the feature. For example, the prefix "java.naming.security.sasl." is used for SASL-specific environment properties.
  • Provider-specific environment properties. These properties only apply to a particular service provider. They should have a prefix that reflects this uniqueness. A common practice is to use the package name of the service provider as the prefix. For example, since Sun's LDAP provider is primarily contained in the package com.sun.jndi.ldap , properties specific to Sun's LDAP provider have the prefix "com.sun.jndi.ldap.".

See Context Environment for security-related considerations when using environment properties.

Although the support for environment properties is rather extensive, it is important to note that an application typically does not need to deal with them, or only needs to set one or two properties. Most properties have reasonable defaults and only need to be adjusted when the application has special requirements.

6.2 Context Environment

A context's environment is represented as a java.util.Hashtable or any of its subclasses (e.g., java.util.Properties 1 ). It is typically specified using an argument to the InitialContext , InitialDirContext , or InitialLdapContext constructors, and augmented with data from other sources (as discussed in the rest of this section). They are inherited from the parent context as context methods proceed from one context to the next. For example, the following code creates an environment consisting of two security-related properties and creates an initial context using that environment.

Hashtable env = new Hashtable();
env.put(Context.SECURITY_PRINCIPAL, "jsmith");
env.put(Context.SECURITY_CREDENTIALS, "xxxxxxx");
Context ctx = new InitialContext(env);

Contexts that are looked up or otherwise derived from this initial context will have these two properties in their environment.

A context's environment can be examined using Context.getEnvironment() .

Not all environment properties are meaningful to all contexts. Those that are not meaningful are ignored by the context but inherited by derived contexts (because they might be meaningful, for instance, to federated contexts).

6.3 Resource Files

A JNDI resource file is a file in the properties file format (see java.util.Properties ). The file contains a list of key/value pairs. The key is the name of the property (e.g., "java.naming.factory.object") and the value is a string in the format defined for that property. Here is an example of a JNDI resource file:

java.naming.factory.object=com.wiz.jndi.AttrsToCorba:com.wiz.jndi.ToPerson
java.naming.factory.state=com.wiz.jndi.CorbaToAttrs:com.wiz.jndi.FromPerson
java.naming.factory.control=com.wiz.jndi.MyResponseControlFactory

There are two kinds of JNDI resource files: application and provider.

Application Resource Files

When an application is deployed, it will generally have several codebase directories and JARs in its classpath. Similarly, when an applet is deployed, it will have a codebase and archives specifying where to find the applet's classes. JNDI locates all application resource files named jndi.properties in the classpath. In addition, if the file $JAVA_HOME/lib/jndi.properties exists and is readable, JNDI treats it as an additional application resource file. ( $JAVA_HOME is the directory named by the java.home system property.) All of the properties contained in these files are placed into the environment of the initial context. This environment is then inherited by other contexts.

For each property found in more than one application resource file, JNDI uses the first value found or, in a few cases where it makes sense to do so, it concatenates all of the values. For example, if the java.naming.factory.object property is found in three jndi.properties resource files, the list of object factories is a concatenation of the property values from all three files. Using this scheme, each deployable component is responsible for listing the factories that it exports. JNDI automatically collects and uses all of these export lists when searching for factory classes.

Application resource files are available beginning with the Java 2 Platform, except that the file in $JAVA_HOME/lib can be used on all Java platforms.

Provider Resource Files

Each service provider has an optional resource file that contains properties specific to that provider. The name of this resource is:

[prefix/]jndiprovider.properties

where prefix is the package name of the provider's context implementation(s), with each period (".") converted to a slash ("/").

The JNDI library will consult the provider resource file when determining the values of certain properties. Properties other than these can be set in the provider resource file at the discretion of the service provider. The service provider's documentation should clearly state which properties are allowed.

6.4 Application/Applet-scope Standard JNDI Properties

Certain standard JNDI properties can alternately be set in the Java runtime's system properties, or in an applet's parameter list. These properties are:

java.naming.factory.initial
java.naming.factory.object
java.naming.factory.state
java.naming.factory.control
java.naming.factory.url.pkgs
java.naming.provider.url
java.naming.dns.url

For JNDI to access an applet's parameters, the applet code must set the java.naming.applet environment property to an instance of the applet ( java.applet.Applet ).

When these properties are set as system properties or applet parameters, they affect all of the application's/applet's contexts.

6.5 How the Environment Properties are Set

When JNDI constructs an initial context, the context's environment is initialized with properties defined in the environment parameter passed to the constructor and all application resource files. For the application/applet-scope properties, their values from the system properties and the applet parameters are also used.

JNDI passes the resulting environment to the initial context implementation. The environment is then inherited by contexts that are derived from the initial context. Since JNDI performs any necessary merging of the properties and their values, there is no need for the application or context implementation to directly consult the system properties or applet parameters.

6.6 Modifications to the Environment

A context's environment can be changed using the addToEnvironment() and removeFromEnvironment() methods:

public interface Context {
        public Object addToEnvironment(String propName, Object val)
                throws NamingException;
        public Object removeFromEnvironment(String propName)
                throws NamingException;
        ...
}

Not all environment properties are meaningful to all contexts. Changes to those that are not meaningful are still recorded and passed onto derived contexts.

Scope

Changing a property using the addToEnvironment() or removeFromEnvironment() methods affects the context instance on which the method is invoked. For example, if you specify new credentials for a context to use, subsequent methods invoked on that context that require communication with the server will use those new credentials (perhaps internally by first creating a new connection to the server). These updated environment properties are inherited by context instances that are subsequently derived from the affected context instance, but do not otherwise affect other context instances that were in existence prior to the update.

Timeliness

When a change is made to the environment properties, there is no requirement that the change be verified and acted upon at the time addToEnvironment() or removeFromEnvironment() is invoked. The only requirement is that the change (or changes) be effective the next time an operation that uses that property is invoked.

Defaults

For some environment properties, JNDI defines defaults (see Appendix A). For others, the default might be determined by the service provider or a group of service providers. If a context's environment does not have a particular property, the context behaves as if its environment has that property with its default value.

When a property is removed from a context's environment, the context assumes the default behavior specified for that property. This does not necessarily mean that the default value must be recorded as the property's value. The removal may also be indicated by the absence of the property from the context's environment.

Acceptable Values

Some environment properties have a fixed set of acceptable values while others have values that must follow a particular syntax. If an unacceptable value is presented, a property-specific exception will be thrown (for example, ConfigurationException , IllegalArgumentException , or AuthenticationNotSupportedException ). In some cases, it might be reasonable for the service provider to accept additional values than those specified, in which case, those values should be documented.

1. Note that if you use Properties, only the top-level properties are consulted--its defaults are not consulted--because Hashtable.get() is used when retrieving entries from the environment. See java.util.Properties for details.

CONTENTS | PREV | NEXT

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


7 Scenarios

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

7. Scenarios

This section outlines a few application scenarios to help illustrate the capabilities enabled by JNDI.

The examples below are not meant to be prescriptive. There are often several ways to solve a problem, and JNDI is designed with flexibility in mind.

7.1 User authentication

In secure systems, a user must authenticate himself to the computer, network, or service that he wishes to access. For example, logging into Unix requires the user to supply a password. Similarly, use of SSL requires that the user supply his X.509 certificate. Such authentication information can be stored as attributes associated with each user in the directory. The system performing the authentication would look up the attribute (for example, "password") of the user and verify the authenticity using the information supplied by the user.

DirContext ctx = new InitialDirContext();
Attribute attr = ctx.getAttributes(userName).get("password");
String password = (String)attr.get();

7.2 Electronic Mail

A useful feature of an electronic mail system is a directory service that provides a mapping between users and email addresses. This allows mail users to search for the email address of a particular user. This is analogous to searching for an individual's telephone number in the phone book in order to dial his phone number. For example, when I want to send mail to John Smith in my department, I search for "John Smith" in the directory using a "search" widget in the mail application. The widget returns to me five entries of John Smith, from which I select the one that is in a building on my site and use the email address attribute associated with that entry.

NamingEnumeration matches = deptCtx.search("user", new BasicAttributes("name", "John Smith"));
// use matches to construct a selectable list for end-user
while (matches.hasMore()) {
    SearchResult item = (SearchResult) matches.next();
    Attributes info = item.getAttributes();
    /* display attributes */
    ...
}

The directory could also be used by users to set up personalized address books. For example, once I have located John Smith's email address, I might not want to search the directory again each time I send him mail. Instead, I can create a personal subtree in the directory in which I maintain entries that I frequently use, possibly by creating links to the existing entries.

7.3 Databases

Database applications can use the directory to locate database servers. For example, a financial application needs to get the stock quotes from a stock quote server using JDBC. This application can enable the user to select the stock quote server based on specification of some attributes (such as coverage of which markets and frequency of quote updates). The application searches the directory for quote servers that meet these attributes, and then retrieves the "location" attribute (a JDBC URL) of the selected quote server and connects to it.

NamingEnumeration matches =     ctx.search("service/stockQuotes",
                                        "(&(market=NASDAQ)(updateFreqency<=300))", searchctls);
while (matches.hasMore()) {
           SearchResult item = (SearchResult)matches.next();
           Attribute location = item.getAttributes().get("location");
   ...
}

7.4 Browsing

When using almost any kind of interactive application that asks a user to input names, the user's job is made easier if a namespace browser is available to him. The browser can either be built into the application and tailored to suit that application in particular, or it can be more general-purpose such as a typical web browser.

A very simple example of a JNDI browser allows a user to "walk" through a namespace, viewing the atomic names at each step along the way. The browser prints a "*" to highlight the name of each Context , thus telling the user where he can go next. 1

// Start at the top -- the initial context.
Context ctx = new InitialContext();
while (ctx != null) {           // display one level
    NamingEnumeration   items = ctx.list();
    while (items.hasMoreElements()) {
        NameClassPair item = (NameClassPair)items.next();
        if (isContext(item.getClassName())) {
            System.out.print("*");
        } else {
            System.out.print(" ");
        }
        System.out.println(" " + item.getName());
    }
    // Take the next step down into the namespace.
    String target = input.readLine();
    try {
        ctx = (Context)ctx.lookup(target);
    } catch (NamingException e) {
        // handle error
    } catch (ClassCastException e) {
        // not a context; cannot traverse
    }
}

7.5 Network Printing

An important function of a printing service is to provide a means for its human users to easily discover and select printers in the network. An application that needs to print, or the machine on which it runs, should not have to be configured each time a new printer is added to the network. The scope of network access to printers may range from a workgroup to global. The printing service can use the directory to provide this capability.

Assume that printers are represented by a Printer interface. One of the methods in it could be print() which, when given an InputStream , will read data from InputStream and print it on the printer represented by this instance of Printer.

interface Printer {
        void print(InputStream data) throws PrinterException;
        ...
}

A user selects a printer using a logical printer name, either explicitly or through default settings. For example, the user might have specified a default printer to use for all his applications, which is overridden only when he explicitly specifies another printer to use. The application that is accepting the print request takes the printer name and looks it up in the directory service. The application expects to receive as the result an object that implements the Printer interface.

void myAppPrint(String printerName, String fileName) throws IOException {
    try {
        DirContext ctx = new InitialDirContext();
        Printer prt = (Printer) ctx.lookup(printerName);
        prt.print(new FileInputStream(fileName));
    } catch (NamingException e){
        System.err.println("Could not locate printer: " + e);
    } catch (ClassCastException e) {
        System.err.println(printerName + "does not name a printer");
    }
}

7.5.1 Browsing and searching for printers

Selecting a printer by explicitly giving its name is but one way of identifying a printer. The user can also use the directory to see the different printers available (browsing), or to search for printers with particular attributes. For example the user can ask the directory to list all the printers on the second floor of building 5 in the Mountain View campus, or search for all color laser printers with 600dpi resolution. From the application's perspective, just as lookup() returned a Printer object, the list and search operations also provide the same capability of returning Printer objects that the application could use to submit print requests.

1. The isContext() method used in the example is not part of JNDI. It is a method that must be provided by the application.

CONTENTS | PREV | NEXT

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


8 Security Considerations

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

8. Security Considerations

There are two main settings in which JNDI is used: with and without a security manager installed.

In the case of Java applications running with no security manager installed, the code is trusted and the application can access service providers from the local classpath. Furthermore, there is no restriction if the service providers access local files, or make network connections to naming or directory servers anywhere on the network.

In the case of an applet or application running with a security manager installed, there can be trusted code and untrusted code within the same applet or application. The Sharing Context Handles and Context Environment sections below are especially applicable in such a scenario. The ability of an applet or an application running with a security manager installed to access service providers, especially service providers that require the use of restricted resources (like the file system or network connections) may be severely limited.

8.1 JNDI Classes

The classes in the JNDI packages contain no native methods. They do not require any special installation in order to run inside an applet or an application.

JNDI uses several system properties (see Application/Applet-scope Standard JNDI Properties ). This allows applets and applications to be configured easily without much programming. However, an applet or application might have restricted access to some or all system properties as a result of the security manager installed on the platform on which it is running. Consequently, JNDI also allows these same properties to be specified as applet parameters, in resource files, or as environment properties passed to a context.

In the Java 2 Platform, the JNDI classes use doPrivileged blocks when accessing the system properties listed in Application/Applet-scope Standard JNDI Properties .

8.2 Security Model

JNDI does not define a security model or a common security interface for accessing naming and directory servers. Security-related operations, such as those required for authentication or access control to the directory service, are dealt with by individual service providers. JNDI provides the means by which an application or applet can pass such security-related information to service providers in order to establish a connection with the service, but does not itself take part in such security-related activities.

JNDI also provides the means by which security-related problems can be indicated to the client in the form of security-related exceptions.

JNDI service providers are controlled by the security manager in place when they try to gain access to protected resources such as the file system or network. Some service providers may control directory access by making use of the Java 2 Platform security architecture (for example, allowing access to special ports for administration-related applets).

8.3 Access To Servers

Naming and directory services typically have their own security system in place to protect information stored therein. For example, one directory might require that its users first "login" to the directory before reading or updating information in the directory. Some services might allow anonymous access to part of its namespace/directory.

Once a user has logged into a service, it is imperative for security reasons not to share that privilege with untrusted code.

8.4 Sharing Context Handles

In the following discussion, we refer to a context handle as a reference to a Context instance. This is analogous to how a reference to a Reader / Writer / InputStream / OutputStream instance is often referred to as a file handle .

A context handle should be treated like any other protected resource. If a piece of trusted code obtains a context handle (possibly by authenticating its access with the directory server), it should protect the use of that context against unauthorized or untrusted code. This is analogous to how application and/or applet code should protect file handles. For example, if a piece of trusted code opens a file for writing (and it was granted such privilege because of its trusted nature), it should be careful about passing that file handle to any other pieces of code, trusted or otherwise.

Similarly, giving access of a context handle to untrusted code may lead to its misuse in accessing or updating information in the directory, or accessing security-sensitive environment properties associated with the context.

8.5 Context Environment

JNDI allows the application/applet to pass preferences and information to a context in the form of an environment. The application/applet can also get the current environment from a context. See See Configuration and Appendix A for more information on a context's environment.

The nature of the information contained in a context's environment might be sensitive and need protection from untrusted access. Specifically, the environment properties java.naming.security.principal and java.naming.security.credentials contain information that should not be given out to untrusted code. Service providers might take precaution to protect against accessing these properties (see Responsibilities of Service Providers below). Client applications and applets should take care not to pass context handles with such sensitive environment properties to untrusted code.

8.6 Class Loading

JNDI allows the class files to be loaded dynamically.

When JNDI is run on the JDK 1.1.x platform, it uses the RMI class loader. The classes can only be loaded if there is a security manager installed, and if that security manager permits the class to be loaded. When such classes are loaded, they run in the security context dictated by the security manager.

When JNDI is run on the Java 2 platform, it will attempt to load such classes from the locations specified in the codebase using the java.net.URLClassLoader . In order for the class loading to succeed, you must grant the application and the JNDI and service provider classes the permissions appropriate for the URLs named in the codebase. For example, if the URL scheme is "http" or "ftp", you must grant the application the appropriate java.net.SocketPermission ; if the URL scheme is "file", you must grant the application the appropriate java.io.FilePermission .

8.7 Serializable Objects

Several of the JNDI classes are serializable. This allows the objects to be accessed in the form of a byte stream, possibly outside of the environment in which they were created. See the document at the following URL regarding security issues related to serialized objects.

http://java.sun.com/products/jdk/1.2/docs/guide/serialization/spec/security.doc.html

8.8 Responsibilities of Service Providers

8.8.1 Context Environment

When a context handle is created (either by getting the initial context or by looking it up or by creating it from the directory), some environment properties may be specified for it. Sometimes security-related properties are required for the creation of the context handle (such as user information that "logs" the user in with the directory). The service provider should take care to protect this security-sensitive information from untrusted code.

The service provider needs to protect the context's environment from being tampered or otherwise modified by untrusted code. The service provider needs to protect the security-sensitive environment properties from being read by untrusted code. It might do this by disallowing any thread whose execution context and/or trust level is different than that originally held by the thread that created the context handle to use the context handle. Or it might disallow certain operations (such as accessing security-sensitive environment properties). Or it might simply not return security-sensitive environment properties, or only return them to trusted code.

8.8.2 Network Security

Untrusted code (such as those found in untrusted applets) have limited access to the network. Untrusted applets, for example, can only create a network connection to the host from which they were downloaded. With finer-grain security models, it will be possible for the service provider itself to be trusted code, and hence be allowed to connect to hosts not allowed for untrusted applets. In such a scenario, the service provider should be careful not to compromise the security intended by the security manager. If the service provider is sure that access by an untrusted applet to the directory will cause no security problems, then it may proceed to offer such a service to untrusted code. For example, allowing untrusted code to access a directory "anonymously" would post no security problems because the directory already allows any anonymous client (written in the Java programming language or otherwise) to access the same data.

Most naming and directory services are accessed over the network. Although the data requested is protected by the server's authentication and access control mechanisms, some protocols do not protect (encrypt) the data being sent as replies. Again, this is not a problem particular to a client using JNDI but a problem for any client accessing the directory. The service provider should document the security implications associated with using the associated directory over a network.

8.8.3 Accessing Local Files

Similar to network access, untrusted code has limited access to the local file system. If the service provider has special privileges for accessing local files, it should do so with utmost precaution so as not to compromise the security policies intended by the runtime/platform.

8.8.4 Privileged Code, Native Methods

A service provider that is written completely in the Java programming language with no privileged sections is controlled by the same security policies afforded other code written in the Java programming language. All protected resources that it attempts to access go through the same security manager and access controller.

If a service provider contains privileged code sections, or if it contains native methods, then it needs to be especially careful to preserve the security policies intended by the runtime/platform.

CONTENTS | PREV | NEXT

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


9 Design Choices

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

9. Design Choices

9.1 Separation of Interfaces into Context and DirContext

There are two core interfaces in JNDI: Context , and DirContext , with DirContext extending the base naming operations in Context with directory service operations. They have been separated into separate interfaces both for modularity and also in keeping with the "pay for what you use" goal of JNDI.

Naming is a basic component found in many computing services such as file systems, spreadsheets, calendar services, and directory services. By having a base Context interface for the naming operations, we enable its use by all these other services, not just for directory services.

DirContext extends Context to provide basic directory service operations, which include manipulation of attributes associated with named objects, attribute-based searches, and schema-related operations of those attributes and named objects.

9.2 Separation of JNDI into Different Functional Packages

JNDI is separated into four client packages ( javax.naming , javax.naming.directory , javax.naming.event , javax.naming.ldap ) and a service provider package ( javax.naming.spi ). The idea is that each package contains the interfaces and classes required for a particular category of applications, again in keeping with the "pay for what you use" goal. For example, an application that just wants to perform name-lookups only needs to use the javax.naming package. An application that wants to examine/modify attributes associated with an object uses the javax.naming and javax.naming.directory packages. An application that needs to use LDAP-specific controls or extended operations uses the javax.naming.ldap package. There is a step-by-step progression of what classes and interfaces each category of application writer needs to learn and use.

9.3 Separation of Client APIs and Service Provider Interfaces

JNDI separates interfaces and classes that a client application needs to use from those that are only of interest to service providers into different packages. For example, a client would use interfaces and classes from javax.naming , while a service provider that is hooking up a naming service would use both javax.naming and javax.naming.spi . The package delineation minimizes confusion for the application developer and makes clear which packages he needs to examine when writing his program.

9.4 Multiple methods for listing Context

There are two common types of applications that list contexts: browser-style applications, and applications that need to perform operations on the objects in a context en-masse. Browser-style applications typically want to display the names of the contents of a context. In addition to the names, many browsers often require type information of the objects bound to the names, so that it can display appropriate pictorial representations of the objects. The browser is usually interactive. Once a user has used a browser to display the contents of a context, he would then select one or a few of the entries displayed and request more information on it.

Some applications need to perform operations on objects within a context en-masse. For example, a backup program might want to perform "file stats" operations on all the objects in a file directory. A printer administration program might want to restart all the printers in a building. To perform such operations, these programs need to obtain all the objects bound in a context.

With these two common styles of usage in mind, the Context interface has two types of list methods: list() and listBindings() . list() returns a list of name/class-name pairs while listBindings() returns a list of name/class-name/object tuples. list() is designed for browser-style applications that want mostly just the names and types of objects bound in a context. listBindings() is for applications that want to potentially get all the objects in the context, as well as their names and types. listBindings() returns an enumeration of Binding . Both the listBindings() operation itself and invocation of methods in the Binding class (e.g. getObject() ) could be implemented lazily or eagerly. Using listBindings() simply indicates the potential that the caller might want all or many of the objects in the context so that implementations that are able can optimize for it. Using list() indicates that the caller is unlikely to want all, if any, objects in the context so implementations can optimize for that if possible.

An alternative is to have a single list operation and have the lazy or eager behavior as part of the implementation of Binding . The advantage of this is that there is a single list operation to learn. The disadvantage is that the caller has no way of indicating which piece of information he wants back from list, and subsequently, implementations cannot optimize for the eventual behavior of the program.

9.5 Support for Federation

Federation is a first-class concept in JNDI. In the client interfaces, it is supported by the use of the Name interface for specifying names that can span one or more namespaces. The caller of the methods in the client interface need not know anything else regarding federation. Resolution of names across multiple systems is handled by the SPI and does not involve any intervention on the part of the caller.

Although federation is a first-class concept, that does not mean that all callers and service providers must make use of it. If an application or service does not want to take advantage of federation, there is no requirement that Name always span multiple namespaces. Name can just name objects within a single namespace, and the SPI can handle name resolution within a single namespace as well (as a degenerate case of multiple namespace support).

9.6 DirContext versus DirObject

Instead of having DirContext extend Context , an alternative would be to not extend Context at all but to have a separate interface called DirObject that encapsulates all the directory-related methods. In that case, an object can implement both Context and DirObject if it supports both the naming and directory operations; another object might implement just DirObject .

The problem with eliminating DirContext is that DirContext contains some hybrid operations that involve both naming and directories ( bind() , createSubcontext() methods that accept attributes as arguments). To keep these operations and have DirObject at the same time would produce the need for a third interface (perhaps called DirContext ) to contain just these hybrids.

Furthermore, having DirContext instead of DirObject is somewhat more convenient in that you can perform some operations in one step instead of two. For example DirContext.getAttributes() could be used to get the attributes associated with a named object, whereas with DirObject , you would need first to resolve to the object ( Context.lookup() ) and then use DirObject.getAttributes() to get the attributes from it.

9.7 Support for Schemas

The DirContext interface contains support for schemas. For example, from a DirContext object you can obtain its schema object, which points to the directory space where the schema for this particular DirContext instance is defined. From a DirContext object, you can also obtain its schema class definition (i.e. information about what type of object this represents in the directory). There is further support for schemas in the Attribute class, which contains methods for obtaining an attribute's syntax information (i.e. what is the type of the attribute's value) and the attribute's definition (e.g. is it multivalued, syntax, constraints on its syntax). There is no requirement that any of this schema information be dynamically accessible (i.e. points to live directory spaces). Support for such schema information could be generated statically by the service provider. For example, a particular directory service might only support string attribute values, so it can hard-wire the syntax of the attributes that it returns. Another directory might support only static schemas (where information in the schema are not modifiable). Yet another directory might support fully dynamic schemas. The interfaces and classes in DirContext are flexible enough that these different levels of support for schemas can be accommodated.

9.8 Overloaded Methods in Context and DirContext

For each method in the Context and DirContext interfaces that accepts a Name argument, there is a corresponding overloaded form that accepts a String argument for specifying a name.

The motivation for having the String -based methods is that there are many applications that simply accept a string name from the end-user and perform context methods on the object named by that string name. For those applications, it is useful to have the context methods accept a string for the name directly, instead of requiring the applications to first construct a Name object using the string name.

The motivation for having the Name -based methods is that there are also many applications that manipulate names and do not want to worry about syntactic details of the names' string forms when composing and modifying names. These applications deal with the parsed form of names and hence would prefer to deal with Name objects rather than string names. For these applications, we provide the Name -based methods in the context interfaces. Not providing these methods would probably cause proliferation of Name -like interfaces/classes to support manipulation of names in their structural form in applications developed on top of JNDI.

9.9 Reference and Referenceable

There are different ways in which applications and services can use the directory to locate objects. JNDI is general enough that it accommodates several different models. For some applications, the object bound in the directory is the object itself. An application may build up a dynamic directory while the application is active, and delete the directory when the application exits. Another application might store URLs as attributes for locating objects in its namespace. Other systems might bind some reference information in the directory, which can subsequently be used to locate or access the actual object. This last case is quite common, especially for making Java applications take advantage of services in the installed base. The reference in the directory acts as a "pointer" to the real object.

JNDI defines a Reference class to provide a uniform way of representing reference information. A Reference contains information on how to access an object. It consists of a list of addresses and class information about the object to which this reference refers. When binding a name to an object that is to be represented in the directory as a reference, the desired effect is that the object's reference be extracted and bound. To allow for this behavior, the object's class must implement the Referenceable interface, which contains the method getReference() .

There is some similarity between the interfaces Serializable and Referenceable and a natural question is "why not just use Serializable instead?" The answer is that a serialized object is really a frozen version of the object, whereas the reference contains just the information needed to construct it. The serialized version may have a lot more state which may not be appropriate for storage in the directory.

9.10 Automatically Turning References into Objects

For an object that is bound as a Reference in the directory, JNDI SPI framework automatically creates and instantiates the object identified by the reference. In this way, the program can simply narrow the result of lookup() to the expected class, instead of calling a separate operation to transform the result of lookup() into an object of the expected class.

For example, if you are looking up a printer object, a successful lookup would return to you a printer object that you can directly use.

Printer prt = (Printer) ctx.lookup(somePrinterName);
prt.print(someFileName);

JNDI does this automatically, instead of requiring an explicit conversion step, because this is expected to be the common usage pattern. By having the Reference class, and a common mechanism for converting a Reference into the object identified by the Reference , JNDI encourages different applications and system providers to utilize this mechanism, rather than inventing separate mechanisms on their own.

CONTENTS | PREV | NEXT

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.security.auth.module.JndiLoginModule (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.module.JndiLoginModule

No usage of com.sun.security.auth.module.JndiLoginModule
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


JNDI SPI

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
[Top] [Prev] [Next] [Bottom]

1 Introduction

The JNDI SPI provides the means by which developers can write different naming and directory service providers and make them available so that the corresponding services are accessible from applications that use the JNDI API. A service provider is a set of modules that together satisfy JNDI API requests. In addition, because JNDI allows the use of names that span multiple namespaces, one service provider implementation may need to interact with another in order to complete an operation. The SPI provides methods that allow different provider implementations to cooperate to complete client JNDI operations.

This document describes the components of the SPI and explains how developers can build service providers for JNDI. It is assumed that the reader is familiar with the contents of the JNDI API document.

All service provider developers should read the "Security Considerations" section of the JNDI API document. It contains important issues that all developers using JNDI, especially those writing service providers, should consider.

1.1 Document Overview

There are several types of implementations that sit beneath the JNDI API. A service provider contains at a minimum a context implementation. A context implementation implements the Context interface or any of its subinterfaces, such as DirContext, EventContext, or LdapContext. The complexity of the implementation depends primarily on the complexity of the underlying service, and secondarily on the number of JNDI features that the implementation supports. Chapter 2 describes the details of building a context implementation.

A context implementation can be accessed in different ways. The most common way is to access it from the initial context. Chapter 3 describes two ways that a context implementation can be accessed from the initial context: via an initial context factory and a URL context factory.

The JNDI architecture defines components/implementations that can be used to augment the behavior of context implementations. This allows users and applications to customize the implementation. These components are supported through factories. JNDI defines three types of factories and provides SPI methods that make use of them. These factories are described in Chapter 4.

  • Object factories-For transforming data stored in naming/directory services into Java types more natural to the Java application.
  • State factories-For transforming objects of Java types natural to the program into formats suitable for storage into naming/directory services.
  • Response control factories-For narrowing LDAP v3 response controls received from LDAP servers into more user-friendly types.

1.2 Interface1 Overview

The JNDI SPI is contained in the javax.naming.spi package. The following sections provide an overview of the SPI. For more details on the SPI, see the corresponding javadoc.

The javax.naming.spi package

The information in this graphic is available in the API documentation.

1.2.1 NamingManager and DirectoryManager

The NamingManager class contains static methods that perform provider-related operations. For example, it contains methods to create instances of objects using Reference, to obtain an instance of the initial context using the java.naming.factory.initial property, and to install ObjectFactoryBuilder and InitialContextFactoryBuilder. The DirectoryManager class provides similar static methods for DirContext related operations.

1.2.2 Initial Contexts

InitialContextFactory is the interface for creating an initial context instance. See Section 3.1 for more details.

InitialContextFactoryBuilder is the interface for creating InitialContextFactory instances. See Section 3.3 for more details.

1.2.3 Object Factories

ObjectFactory is the interface for supporting creation of objects using information stored in the namespace. DirObjectFactory is a subinterface of ObjectFactory for use by context implementations that implement the DirContext interface. See Section 4.1 for more details.

ObjectFactoryBuilder is the interface for creating object factories. See Section 4.1.4 for more details.

1.2.4 State Factories

StateFactory is the interface for supporting converting objects into storable formats supported by the naming/directory service. DirStateFactory is a subinterface of StateFactory for use by context implementations that implement the DirContext interface. DirStateFactory.Result is a class for holding a pair of java.lang.Object and Attributes that is returned by DirStateFactory.getStateToBind(). See Section 4.2 for more details.

1.2.5 Federation Support

The Resolver interface defines a method for providers to implement that allows them to participate in a federation for supporting extended interfaces to Context. See "Resolving Through to Subinterfaces of Context" on page 10 for more details.

ResolveResult is the return value of calling Resolver.resolveToClass(). It contains the object to which resolution succeeded, and the remaining name yet to be resolved.

2 Building a Context Implementation

One of the basic tasks in building a service provider is to define a class that implements the Context interface or any of its subinterfaces. This class is called a context implementation. The following guidelines should be used for developing a context implementation.

2.1 Ownership of Parameters

In general, any object passed as a parameter to methods in the Context interface (or subinterfaces) and NamingManager/DirectoryManager utility methods is owned by the caller. In many cases, the parameter eventually reaches a context implementation. Because the caller owns the object, the context implementation is prohibited from modifying the object. Furthermore, the context implementation is allowed to maintain a pointer to the object only for the duration of the operation and not beyond. If a context implementation needs to save the information contained in a parameter beyond the duration of the operation, it should maintain its own copy.

For purposes of parameter ownership, an operation on a context instance is not considered to have completed while any referrals generated by that operation are still being followed, or if the operation returns a NamingEnumeration, while the enumeration is still in use.

2.2 Reentrancy

A context instance need not be reentrant. Two threads that need to access the same context instance concurrently should synchronize amongst themselves and provide the necessary locking.

However, different context instances must be safe for concurrent multithreaded access. That is, two threads each operating concurrently on their respective context instance should not need to synchronize their access. For example, even though two contexts might share the same resources (such as the same connection), it must be possible (and safe) for two separate threads to operate on each of those contexts without the threads having to do any explicit synchronization.

For purposes of concurrency control, an operation on a context instance is not considered to have completed while any referrals generated by that operation are still being followed, or if the operation returns a NamingEnumeration, while the enumeration is still in use.

2.3 Basic Support-Implementing the Context Interface(s)

The context implementation defines implementations for each of the methods in the Context interface or subinterfaces that the implementation supports.

If a method is not supported, it should throw OperationNotSupportedException.

For methods in the Context interface or subinterfaces that accept a name argument (either as a String or a Name), an empty name denotes the current context. For example, if an empty name is supplied to lookup(), that means to return a new instance of the current context. If an empty name is supplied to list(), that means to enumerate the names in the current context. If an empty name is supplied to getAttributes(), that means to retrieve the attributes associated with this context.

Appendix A contains an example context implementation that implements a flat, in-memory namespace.

2.4 Object Support

JNDI encourages providers to supply implementations of the Context and its subinterfaces that are natural and intuitive for the Java application programmer. For example, when looking up a printer name in the namespace, it is natural for the programmer to expect to get back a printer object on which to operate.

Context ctx = new InitialContext();
Printer prt = (Printer)ctx.lookup(somePrinterName);
prt.print(someStreamOfData);

Similarly, when storing an application's object into the underlying service, it is most portable and convenient if the application does not have to know about the underlying data representation.

However, what is bound in the underlying directory or naming services typically are not objects in the Java programming language but merely reference information which can be used to locate or access the actual object. This case is quite common, especially for Java applications accessing and sharing services in an existing installed base. The reference in effect acts as a "pointer" to the real object. In the printer example, what is actually bound might be information on how to access the printer (e.g., its protocol type, its server address). To enable this easy-to-use model for the application developer, the context implementation must do the transformation of the data to/from the underlying service into the appropriate objects in the Java programming language.

There are different ways to achieve this goal. One context implementation might have access to all the implementation classes of objects that a directory can return; another context implementation might have a special class loader for locating implementation classes for its objects. JNDI provides the Reference class as a standard way of representing references. Applications and context implementations are encouraged to use this class, rather than invent separate mechanisms on their own. However, this does not preclude context implementations from using their own mechanisms for achieving the same goal.

JNDI provides utilities for context implementations to use when reading/storing objects in the Java programming language in a format-independent way to the underlying service. This section describes these utilities. These utilities interact with components called object and state factories that do the actual transformations. These factories are described in Chapter 4.

2.4.1 Reading an Object

JNDI provides the following methods that context implementations should use to transform data read from the underlying service into objects in the Java programming language:

Object NamingManager.getObjectInstance(Object refInfo,
                                       Name name,
                                       Context nameCtx,
                                       Hashtable env)
        throws Exception;
Object DirectoryManager.getObjectInstance(Object refInfo,
                                          Name name,
                                          Context nameCtx,
                                          Hashtable env,
                                          Attributes attrs)
        throws Exception;
refInfo is the data (representing the object) read from the underlying service. name is the name of the object while nameCtx is the context in which to resolve name. The name/nameCtx pair can be used to obtain more information about the object than is available from refInfo. env is the environment of the context from which getObjectInstance() is being invoked. attrs is the collection of attributes read from the directory about the object, usually in the same request that was used to get refInfo. It might not be the complete collection of attributes if such was not requested.

The method in the NamingManager class should be used by context implementations that implement the Context interface, while the method in the DirectoryManager class should be used by context implementations that implement the DirContext interface.

When constructing objects to be returned for the following methods, the context implementation should call getObjectInstance(), or its own mechanism for generating objects from the bound information, if it wants this feature to be enabled in their contexts. (String overloads not shown.)

        javax.naming.Context.lookup(Name name)
        javax.naming.Context.lookupLink(Name name)
        javax.naming.Binding.getObject()
        javax.naming.directory.SearchResult.getObject()

For Binding and SearchResult, the context implementation should either pass an object that is the result of calling getObjectInstance() or its equivalent to the constructor, or override the default implementation of Binding and SearchResult so that their getObject() implementations call getObjectInstance() or its equivalent before returning.

Here is an example. Suppose printers are represented in the namespace using References. To turn a printer Reference into a live Printer object, the context implementation would use the NamingManager.getObjectInstance() method. In this way, the underlying service need not know anything specific about printers.

Object lookup(Name name) {
        ...
        Reference ref = <some printer reference looked up from naming service>;
        return NamingManager.getObjectInstance(ref, name, this, env);
}

In another example, suppose printers are represented in the directory as a collection of attributes. To turn a printer's directory entry into a live Printer object, the context implementation would use DirectoryManager.getObjectInstance().

Object lookup(Name name) {
        ...
        Attributes attrs = <read attributes from directory>;
        Reference ref = <construct reference from attributes>;
        return DirectoryManager.getObjectInstance(ref, name, this,
                env, attrs);
}

2.4.2 Storing an Object

JNDI provides the following methods that context implementations should use to transform an object before storing it in the underlying service:

Object NamingManager.getStateToBind(
                                    Object obj,
                                    Name name,
                                    Context nameCtx,
                                    Hashtable env)
        throws NamingException;
DirStateFactory.Result DirectoryManager.getStateToBind(
                                    Object obj,
                                    Name name,
                                    Context nameCtx,
                                    Hashtable env,
                                    Attributes attrs)
        throws NamingException;

obj is the object to be stored in the underlying service. name is the name of the object while nameCtx is the context in which to resolve name. The name/nameCtx pair can be used to obtain more information about the object than is available from obj. env is the environment of the context from which getStateToBind() is being invoked. attrs is the collection of attributes that is to be bound with the object. DirStateFactory.Result is a class that contains an object and a collection of attributes.

The method in the NamingManager class should be used by context implementations that implement the Context interface, while the method in the DirectoryManager class should be used by context implementations that implement the DirContext interface.

Before storing an object supplied by the application, the context implementation should call getStateToBind(), or its own mechanism for generating information to be bound, if it wants this feature to be enabled in their contexts. (String overloads not shown.)

javax.naming.Context.bind(Name name, Object o)
javax.naming.Context.rebind(Name name, Object o)
javax.naming.DirContext.bind(Name name, Object o, Attributes attrs)
javax.naming.DirContext.rebind(Name name, Object o, Attributes attrs)

Here's an example of how a Context implementation supports Context.bind:

// First do transformation
obj = NamingManager.getStateToBind(obj, name, ctx, env);

// Check for Referenceable
if (obj instanceof Referenceable) {
    obj = ((Referenceable)obj).getReference();
}

if (obj instanceof Reference) {
        // store as ref
} else if (obj instanceof Serializable) {
        // serialize
} else {
        ...
}

Here's an example of how a DirContext implementation supports DirContext.bind:

// First do transformation
DirStateFactory.Result res = DirectoryManager.getStateToBind(
        obj, name, ctx, env, inAttrs);

obj = res.getObject();
Attributes outAttrs = res.getAttributes();

// Check for Referenceable
if (obj instanceof Referenceable) {
        obj = ((Referenceable)obj).getReference();
}
if (obj instanceof Reference) {
        // store as ref and add outAttrs
} else if (obj instanceof Serializable) {
        // serialize and add outAttrs
} else if (obj instanceof DirContext) {
        // grab attributes and merge with outAttrs
} else {
        ...
}

As shown in these examples, a context implementation might be able to store different types of objects (Reference, Serializable, and DirContext). If the context implementation cannot store Referenceable objects directly and getStateToBind() returns such an object, the context implementation should subsequently call Referenceable.getReference() and store the resulting Reference instead.

If a context implementation can store different types of objects, it should follow this order for the following common types:

  • Reference
  • Serializable
  • DirContext

This order is recommended because it is most likely to capture the intent of the caller of the bind()/rebind() method. For example, a Reference is Serializable, so if you performed the Serializable check first, no Reference objects would ever be stored in the reference format (that is, they would all be serialized).

2.5 Federation Support

2.5.1 Names

When a context is given a string name argument, the name represents a composite name that may span multiple namespaces, or it may have only a single compound name component (which in turn may be made up of one or several atomic names) that belongs to a single namespace. The context implementation must determine which part of the name is to be resolved/processed in its context and pass the rest onto the next context. This may be done syntactically by examining the name, or dynamically by resolving the name.

When a context is given a Name argument, if it is an instance of CompositeName, then it will be treated as a composite name. Otherwise, it will be treated as a compound name that is implemented by the CompoundName class or some other compound name implementation.

2.5.2 Resolving Through a Context

A context participates in a federation by performing the resolution phase of all of the context operations. The lookup() method must always be supported. Support for other methods is optional, but if the context is to participate in a federation, then the resolution implicit in all operations must be supported.

Figure 1: Example of Resolving through Intermediate Contexts to Perform a bind().

Example of resolving through intermediate contexts to perform a bind()

For example, suppose a context does not support the bind() operation. When that context is being used as an intermediate context for bind(), it must perform the resolution part of that operation to enable the operation to continue to the next context. It should only throw OperationNotSupportedException if it is being asked to create a binding in its own context. Figure 1 shows an example of how the bind() operation is passed through intermediate contexts to be performed in the target context.

2.5.3 Resolving Through to Subinterfaces of Context

To invoke a DirContext method (such as getAttributes()), the application first obtains an initial DirContext, and then perform the operation on the DirContext.

DirContext ctx = new InitialDirContext();
Attributes attrs = ctx.getAttributes(someName);
From the context implementation's perspective, in order to retrieve the attributes, getAttributes() might need to traverse multiple naming systems. Some of these naming systems only support the Context interface, not the DirContext interface. These naming systems are being used as intermediaries for resolving towards the target context. The target context must support the DirContext interface. Figure 2 shows an example of this.

Figure 2: Example of Resolving Through Intermediate non-DirContexts

Example of resolving through intermediate non-DirContexts

In order for intermediate naming systems to participate in the federation for extensions of Context, they must implement the Resolver interface. The Resolver interface is used by the JNDI framework to resolve through intermediate contexts that do not support a particular subinterface of Context. It consists of two overloaded forms of the method resolveToClass(). This method is used to partially resolve a name, stopping at the first context that is an instance of the required subinterface. By providing support for this method and the resolution phase of all methods in the Context interface, a context implementation can act as an intermediate context for extensions (subinterfaces) of Context.

public interface Resolver {
        public ResolveResult resolveToClass(Name name, Class contextType)
                throws NamingException;
        public ResolveResult resolveToClass(String name,
                                           Class contextType)
                throws NamingException;
}

2.5.4 Naming System Boundaries

The resolution of a (multicomponent) composite name proceeds from one naming system to the next, with the resolution of the components that span each naming system typically handled by a corresponding context implementation. From a context implementation's point of view, it passes the components for which it is not responsible to the (context implementation of the) next naming system.

There are several ways in which the context implementation for the next naming system may be located. It may be done explicitly through the use of a junction, where a name in one naming system is bound to a context (or a Reference to a context) in the next naming system. For example, with the composite name "cn=fs,ou=eng/lib/xyz.zip", the LDAP name "cn=fs,ou=eng" might resolve to a file system context in which the name "lib/xyz.zip" could then be resolved.

Alternately, the next naming system may be located implicitly. For example, a context implementation may choose the next naming system based upon service-specific knowledge of the object that it has resolved. For example, with the composite name "ldap.wiz.com/cn=fs,ou=eng", the DNS name ldap.wiz.com might name a DNS entry. To get the next naming system beyond DNS, the DNS context implementation might construct a context using SRV resource records found in that entry, which in this case, happens to name an LDAP context. When the next naming system is located in this fashion, JNDI composite name separator is used to denote the boundary from one naming system to the next, and is referred to as the implicit next naming system pointer.

However the next naming system is located, the context implementation must hand the next naming system the remaining portion of the composite name to resolve.

2.5.5 Continuing an Operation in a Federation

In performing an operation on a name that spans multiple namespaces, a context in an intermediate naming system needs to pass the operation onto the next naming system. The context does this by first constructing a CannotProceedException containing information pinpointing how far it has proceeded. In so doing it sets the resolved object, resolved name, remaining name, and environment parts of the exception.2 (In the case of the Context.rename() method, it also sets the "resolved newname" part.)

It then obtains a continuation context from JNDI by passing the CannotProceedException to static method NamingManager.getContinuationContext()

public class NamingManager {
        public static Context getContinuationContext(
                CannotProceedException e) throws NamingException;
        ...
}

The information in the exception is used by getContinuationContext() to create the context instance in which to continue the operation.

To obtain a continuation context for the DirContext operations, use Directory-Manager.getContinuationDirContext().

public class DirectoryManager {
        public static getContinuationDirContext(
                CannotProceedException e) throws NamingException;
        ...
}

Upon receiving the continuation context, the operation should be continued using the remainder of the name that has not been resolved.

For example, when attempting to continue a bind() operation, the code in the context implementation might look as follows:

public void bind(Name name, Object obj) throws NamingException {
        ...
        try {
                internal_bind(name, obj);
                ...
        } catch (CannotProceedException e) {
                Context cctx =                  NamingManager.getContinuationContext(e);
                cctx.bind(e.getRemainingName(), obj);
        }
}

In this example, bind() depends on an internal method, internal_bind(), to carry out the actual work of the bind and to throw a CannotProceedException when it discovers that it is going beyond this naming system. The exception is then passed to getContinuationContext() in order to continue the operation. If the operation cannot be continued, the continuation context will throw the CannotProceedException to the caller of the original bind() operation.

2.5.6 "Dynamic" Location of Next Naming System

In some federation configurations, the result of resolution in one naming system does not indicate which is the next naming system. The only conclusion that the context implementation can draw is that resolution has terminated in the current naming system and should proceed to the next naming system.

For example, suppose the composite name "lib/xyz.zip/part1/abc" consists of two parts: "lib/xyz.zip", which names a file in ZIP format, and "part1/abc", which names an entry within the ZIP file. Although the resolution of "lib/xyz.zip" results in a file object, the desired result is a context in which to resolve names of ZIP entries. Similarly, another composite name could name an entry within a file in "tar" format, and the desired result of the resolution of the file component of the composite name would be a context in which to resolve tar entries.

In effect, any type of context might be federated beneath the file system namespace depending on the format of the files. Such relationships should be symmetric: it should be possible for the ZIP file context and other similar contexts to federate beneath other, non-file system namespaces. Furthermore, developers writing the file system context implementation and those writing the context implementations for the ZIP file context, the tar file context, or a context for some yet-to-be defined format, should be able to work independently.

To support this type of federation, JNDI defines a special form of Reference called an nns reference ("nns" stands for "next naming system"). This Reference has an address with type nns. The address contents is the resolved object (in the above example, the ZIP file). Continuing with the file system example, the file system context implementation might create the nns reference as follows:

 RefAddr addr = new RefAddr("nns") {
        public Object getContent() {
                return theFile;
        }
};
Reference ref = new Reference("java.io.File", addr);

Next, the context implementation constructs a CannotProceedException (as with the junction case) by using the nns reference as the resolved object, and a resolved name consisting of the resolved file name and an empty component. The empty component is being used as an implicit next naming system pointer and indicates that the resolution has succeeded to the point of resolving the next naming system. (Notice how the values of the resolved object and resolved name are matched.) The context impementation then passes the CannotProceedException to getContinuationContext().

As with any resolved object in a CannotProceedException, getContinuationContext() searches for a context implementation that accepts this nns reference. The ZIP file context implementation, for instance, might accept an nns reference and other information provided, such as the name of the file (relative to a given context). If the context implementation determines that the file is a ZIP file, it would then construct a context for resolving names within that file.

2.5.7 More about CannotProceedException

Central to the JNDI SPI's framework for federation is the CannotProceedException. A Cannot-ProceedException contains information such as the resolved name/object and remaining name, inherited from the NamingException superclass. In addition, a CannotProceedException also contains fields for the "alt" name and "alt" name context. While the resolved name from NamingException is the full composite name (relative to the starting context of the operation), alt name is the resolved name relative to the alt name context. That is, alt name might not necessarily be the same as the resolved name. Alt name and alt name context are used as arguments to NamingManager/DirectoryManager.getObjectInstance(). They allow the factories that are called by this method to obtain more information about the resolved object (for example, it could be used to get a special attribute about the object). These factories are described in Chapter 4.

2.5.8 Contextual Information

While the emphasis of the JNDI SPI framework is on "looking forward" and trying to find the next naming system, some context implementations, once located, need to "look back" the resolution chain to obtain contextual information. For example, a particular context implementation that is federated off of a host naming system might be designed such that the only means by which it can find out host information is to ask its (possibly not immediate) superior naming system. To do that, it needs contextual information-information about how the resolution proceeded to its current point.

Summarizing earlier discussions on federation, when performing an operation on a name that spans multiple namespaces, the context implementation first constructs a CannotProceed-Exception containing information pinpointing how far it has proceeded. It then obtains a continuation context from JNDI by calling getContinuationContext(). To support the retrieval of contextual information, getContinuationContext() automatically adds the environment property java.naming.spi.CannotProceedException, with the value of the Cannot-ProceedException argument, to the continuation context's environment. This property is inherited by the continuation context and may be used by that context's implementation to inspect the fields of the exception.

2.6 Referral Support

LDAP-style directory services support the notion of referrals for redirecting a client's request to another server. A referral differs from the federation continuation mechanism described earlier in that a referral may be presented to the JNDI client, who then decides whether to follow it, whereas a CannotProceedException should be returned to the client only when no further progress is possible. Another difference is that an individual context implementation offers the capability of continuing the operation using the referral (and itself determines the mechanism for doing so). In a federation, the mechanism of continuation is beyond the scope of individual context implementations: individual context implementations benefit from the common federation mechanism provided by the JNDI SPI framework.

A context implementation that supports referrals defines a subclass of ReferralException and provides implementations for its abstract methods. getReferralContext() returns a context at which to carry on the operation, and getReferralInfo() returns information on where the referral leads to, in a format appropriate to the context implementation.

The environment property java.naming.referral specifies how the context implementation should treat referrals. If the context implementation is asked to throw an exception when a referral is encountered, or if the context implementation encounters problems following a referral, it throws a ReferralException to the application. To continue the operation, the application re-invokes the method on the referral context using the same arguments it supplied to the original method. The following code sample shows how ReferralException may be used by an application:3

while (true) {
        try {
                bindings = ctx.listBindings(name);
                while (bindings.hasMore()) {
                        b = (Binding) bindings.next();
                        ...
                }
                break;
        } catch (ReferralException e) {
                ctx = e.getReferralContext();
        }
}

This convention of re-invoking the method using the original arguments is a simple one for applications to follow. This places the burden on the implementation of the ReferralException to supply enough information to the implementation of the referral context for the operation to be continued. Note that this will likely render some of the arguments passed to the re-invoked operation superfluous. The referral context implementation is free to ignore any redundant or unneeded information.

It is possible for an operation to return results in addition to a referral. For example, when searching a context, the server might return several results in addition to a few referrals as to where to obtain further results. These results and referrals might be interleaved at the protocol level. If referrals require user interaction (i.e., not followed automatically), the context implementation should return the results through the search enumeration first. When the results have been returned, the referral exception can then be thrown. This allows a simple programming model to be used when presenting the user with a clear relationship between a referral and its set of results.

2.7 Schema Support

JNDI defines the Attribute interface for representing an attribute in a directory. An attribute consists of an attribute identifier (a string) and a set of attribute values, which can be any object in the Java programming language. There are also methods defined in Attribute for obtaining the attribute's definition and syntax definition from the directory's schema.

public class Attribute {
        public DirContext getAttributeDefinition() throws NamingException;
        public DirContext getAttributeSyntaxDefinition()
                throws NamingException;
        ...
}

The utility class, BasicAttribute, does not provide useful implementations for these methods. A directory context implementation that has support for such schema information should provide implementations of Attribute that implement these two methods based on its schema mechanisms, perhaps by subclassing BasicAttribute and overriding these two methods. The context implementation should then return instances of these subclasses when asked to return instances of Attribute. The context implementation, when it receives an Attribute instance that do not have meaningful implementations of these two methods, should use reasonable defaults to determine the attribute's definition and syntax, using information such as the attribute values' class names or conventions used for the attribute identifier.

The DirContext interface contains schema-related methods:

public class DirContext {
        ...
        public DirContext getSchema(Name name) throws NamingException;
        public DirContext getSchema(String name) throws NamingException;

        public DirContext getSchemaClassDefinition(Name name)
                throws NamingException;
        public DirContext getSchemaClassDefinition(String name)
                throws NamingException;

}

getSchema() returns the schema tree for the named object, while getSchemaClassDefinition() returns a context containing schema class definitions for the named object. Some systems have just one global schema and, regardless of the value of the name argument, will return the same schema tree. Others support finer grained schema definitions, and may return different schema trees depending on which context is being examined.

2.8 Event Support

A context implementation supports event notification by providing implementation for the methods in the EventContext/EventDirContext interfaces. The event model advocated by these interfaces can be readily supported using a multithreaded model. When an application uses addNamingListener() to register a listener with a context, the context records the requests and takes action to collect information required to generate the events. When the context eventually receives information to generate the events, it fires the events to the listener. The thread that does the registration is typically different from the thread that runs the listener. The context implementation typically uses a thread that it has created and manages to run the listener method. When one event is dispatched to multiple listeners, the context implementation may choose to (and is generally encouraged) to execute the listener methods concurrently in separate threads.

The addNamingListener() methods accept an instance of NamingListener. The instance might implement one or more subinterfaces of NamingListener. If the listener implements more than one subinterface, the context implementation should try to conserve resources required to satisfy the registration. For example, an implementation might be able to submit a single request to the server that captures all of the requests of the subinterfaces.

Where possible, the context implementation should fire a NamingExceptionEvent to a listener if the context will be unable to fire further events and then automatically deregister the listener. For example, if the connection to the server is broken subsequent to the registration of the listener and no information will be available to fire events, the context should fire a NamingExceptionEvent to the listener.

2.9 Context Environment Support

Each instance of Context (or its subinterfaces) can have associated with it an environment which contains preferences expressed by the application of how it would like to access the services offered by the context. Examples of information found in an environment are security-related information that specify the user's credentials and desired level of security (none, simple, strong), and configuration information, such as the server to use. See Chapter 6 and Appendix A of the JNDI API document for more details about environment properties.

Environment properties are defined generically in order to ensure maximum portability. Individual service providers should map these generic properties to characteristics appropriate for their service. Properties that are not relevant to a provider should be recorded and silently ignored. The environment may also be used for storing service provider-specific properties or preferences, in which case their applicability across different providers is limited.

2.9.1 Property Naming Convention

See Section 6.1 in the JNDI API document for a description of how environment properties are named. Service provider-specific properties should have a prefix that reflects their uniqueness to the provider. A common practice is to use the package name of the service provider as the prefix. For example, since Sun's LDAP provider is primarily contained in the package com.sun.jndi.ldap, properties specific to Sun's LDAP provider have the prefix "com.sun.jndi.ldap.".

2.9.2 Initializing a Context's Environment

When creating an initial context (either using the constructors from InitialContext or its subclasses), the application can supply an environment as a parameter. The parameter is represented as a Hashtable or any of its subclasses (e.g., Properties). The JNDI class library augments the data from this parameter with data from other sources (see Chapter 6 in the JNDI API document) and passes this to the context implementation.

Like all other parameters, the environment parameter received by a context implementation is owned by the caller. The context implementation should make a copy of the environment parameter it gets or otherwise take steps to ensure that changes by the caller to the parameter would not affect what the context implementation sees and vice versa. Note also that if the environment parameter is a Properties instance, enumeration and Hashtable.get() on the parameter only examine the top-level properties (not any nested defaults). This is the expected behavior. The context implementation is not expected to retrieve or enumerate values in the Properties instance's nested defaults.

The JNDI library is responsible for merging properties from different sources, such as the environment parameter to the initial context, resource files, and, where appropriate, system properties and applet parameters (see the JNDI API document, Chapter 6). The context implementation typically just reads the property it needs from the environment which it was supplied. There is seldom a need for a context implementation to consult other sources.

2.9.3 Inheritance

The environment is inherited from parent to child as the context methods proceed from one context to the next. The entire environment of a context instance is inherited by the child context instances, regardless of whether certain properties within the environment are ignored by a particular context.

A context implementation must pass on the environment from one context instance to the next in order to implement this "inheritance" trait of environments. Within one context implementation it can do so by passing the environment as an argument to the Context constructor, or to the NamingManager/DirectoryManager.getObjectInstance() method for creating Context instances.

Across context implementations in a federation, this is supported by passing the environment as part of the CannotProceedException parameter of NamingManager.getContinuationContext()/DirectoryManager.getContinuationDirContext(), which in turn will use this environment when creating an instance of the context in which to continue the operation.

Inheritance can be implemented in any way as long as it preserves the semantics that each context has its own view of its environment. For example, a copy-on-write implementation could be used to defer copying of the environment until it is absolutely necessary.

2.9.4 Updates to the Environment

The environment of a context can be updated via the use of the addToEnvironment() and removeFromEnvironment() methods in the Context interface.

public interface Context {
        ...
        public Object addToEnvironment(String propName, Object propVal)
                throws NamingException;

        public Object removeFromEnvironment(String propName)
                throws NamingException;
}

These methods update the environment of this instance of Context. An environment property that is not relevant to the context implementation is silently ignored but maintained as part of the environment. The updated environment affects this instance of Context, and will be inherited by any new child Context instances, but does not affect any Context instances already in existence. A lookup of the empty name on a Context will return a new Context instance with an environment inherited as with any other child.

See Section 6.6 in the JNDI API document for details.

2.9.5 Provider Resource Files

Each service provider has an optional resource file that contains properties specific to that provider. The name of this resource is:

[prefix/]jndiprovider.properties
where prefix is the package name of the provider's context implementation(s), with each period (".") converted to a slash ("/"). For example, suppose a service provider defines a context implementation with class name com.sun.jndi.ldap.LdapCtx. The provider resource for this provider is named com/sun/jndi/ldap/jndiprovider.properties.

The JNDI class library will consult this file when it needs to determine the value of a property, as described in Section 6.5.2 in the JNDI API document.

When the service provider needs to determine the value of a property, it will generally take that value directly from the environment. The service provider may define provider-specific properties to be placed in its own provider resource file. In that case it needs to read them from its property resource file and merge them in a way consistent with the algorithm described in Section 6.5.2 in the JNDI API document.

2.10 Connection Management

For a context implementation that uses a client/server protocol, there is not necessarily a one-to-one mapping between a context and a connection between the client and the server. JNDI is a high-level API that does not deal directly with connections. It is the job of the context implementation to do any necessary connection management. Hence, a single connection may be shared by multiple context instances, and a context implementation is free to use its own algorithms to conserve connection and network usage. Thus, when a method is invoked on the context instance, the context implementation might need to do some connection management in addition to performing the requested operation.

The Context.close() and NamingEnumeration.close() methods can be used by applications to provide hints to the context implementation as to when to free connection-related resources. A context implementation may choose to (and is generally encouraged to) take other measures to garbage-collect and conserve its connection-related resources.

Some environment properties affect a context's connection. For example, if the application changes the security-related properties, the context implementation might need to modify or create a new connection using those updated properties. If the connection was being shared by other contexts prior to the change, the connection change should not affect contexts whose properties have not been updated.

3 The Initial Context

Since all naming methods are performed relative to a context, an application needs a starting context in order to invoke them. This starting context is referred to as the initial context. The bindings in the initial context are determined by policies set forth by the initial context implementation, perhaps using standard policies for naming global and enterprise-wide namespaces. For example, the initial context might contain a binding to the Internet DNS namespace, a binding to the enterprise-wide namespace, and a binding to a personal directory belonging to the user who is running the application.

An application obtains an initial context by making the following call:

Context ctx = new InitialContext();
An alternate constructor allows an environment to be passed as an argument. This allows the application to pass in preferences or security information to be used in the construction of the initial context.
Hashtable env = new Hashtable();4
env.put(Context.SECURITY_PRINCIPAL, "jsmith");
env.put(Context.SECURITY_CREDENTIALS, "xxxxxxx");
Context ctx = new InitialContext(env);

Subsequent to getting an initial context, the application can invoke Context methods.

Object obj = ctx.lookup("this/is/a/test");

The InitialContext class (and subclasses) selects an implementation using a default algorithm that can be overridden by installing an initial context factory builder (described below).

The InitialDirContext is an extension of InitialContext. It is used for performing directory operations using the initial context. The InitialLdapContext class is an extension of InitialDirContext. It is used for performing special LDAP v3 operations using the initial context. The algorithms and policies described in this section also apply to InitialDirContext and InitialLdapContext. Places where DirContext/LdapContext is required instead of Context have been noted.

3.1 The Initial Context Factory

An initial context factory is a class that creates an instance of a context that has been implemented following the guidelines outlined in Chapter 2. The factory is used by the InitialContext class (or subclass) constructor.

Given an environment, the factory returns an instance of Context (or its subinterfaces).

public interface InitialContextFactory {
        public Context getInitialContext(Hashtable env)
                throws NamingException;
}

Appendix A contains an example of an InitialContextFactory.

Once the context instance has been created, when a method is invoked on InitialContext by using a non-URL name (see below), the method is forwarded and invoked on that context instance.

JNDI selects the initial context implementation to use by using the property java.naming.factory.initial. This property contains the fully-qualified class name of an initial context factory. The class must implement the InitialContextFactory interface and have a public constructor that does not take any arguments. JNDI will load the initial context factory class and then invoke getInitialContext() on it to obtain a Context instance to be used as the initial context.

An application that wants to use a particular initial context must supply the java.naming.factory.initial property in the environment passed to the InitialContext (or subclass) constructors, or via resource files, system properties, or applet parameters.

3.1.1 Exceptions

When the property java.naming.factory.initial is set to a non-null value, the InitialContext (and subclass) constructors will try to load and instantiate an initial context factory, which will then create a context instance. If the factory or context cannot be created, for example as a result of an authentication problem, the initial context factory can throw an exception to indicate this problem. Note however that it is up to the context implementation when it verifies and indicates to users of the initial context any environment property- or connection- related problems. It can do so lazily-delaying until an operation is performed on the context, or eagerly, at the time the context is created.

If the property java.naming.factory.initial is not set, no attempt will be made to create an underlying context for the initial context. The initial context is still useful, for instance, for processing URL names, as described next.

3.2 URL Support

If a URL5 string is passed to the initial context, it will be resolved using the corresponding URL context implementation. This feature is supported by the InitialContext class (and subclasses) and is independent of the setting of the java.naming.factory.initial environment property.

This feature allows applications to use the initial context to reach any namespace for which a URL context implementation has been made available. For example, the following code lists an LDAP namespace from the initial context:

new InitialContext().list("ldap://lserver/ou=eng,o=wiz,c=us");

3.2.1 URL Context

A URL string has the following format:

scheme_id:opaque_string

For example, an LDAP URL string has the scheme id "ldap"; a file URL has the scheme id "file".

A URL context implementation is a class that implements the Context interface (and possibly some subinterfaces) and accepts name arguments that are URL strings of the scheme that it supports. For example, an LDAP URL context accepts "ldap" URL strings.

When a URL string name is passed to a URL context, the context methods that accept String treat the name as a URL with the syntax defined by the URL scheme. When a Name object in which the first component is a URL string name is passed to a URL context, the first component is treated as a URL string, and the rest is used for federation (that is, resolution of the first component will indicate which naming system to use to resolve the rest). The Name instance should be a CompositeName; otherwise, an InvalidNameException should be thrown.

Name arguments that are not URL strings, and URL strings with an inappropriate scheme id should be rejected with an InvalidNameException.

3.2.2 URL Context Factory

A URL context factory is a class (actually a special type object factory (see Section 4.1)) that creates an instance of a URL context for URLs of one or more schemes.

When the InitialContext class receives a URL string as a name argument, it will look for a URL context factory by using the following algorithm. The environment property java.naming.factory.url.pkgs contains a colon-separated list of package prefixes. The factory's class name is constructed by using the following rule:

package_prefix + "." + scheme_id + "." + scheme_id URLContextFactory

for each package prefix listed in the property. The default package prefix com.sun.jndi.url is appended to the end of the list.

For example, if the URL is "ldap://somehost:389" and java.naming.factory.url.pkgs contains "com.widget:com.wiz.jndi", the InitialContext class will attempt to locate the corresponding factory class by loading the following classes until one is successfully instantiated:

com.widget.ldap.ldapURLContextFactory
com.wiz.jndi.ldap.ldapURLContextFactory
com.sun.jndi.url.ldap.ldapURLContextFactory
The factory class implements the ObjectFactory interface (see "URL Context Factory" on page 31) and has a public constructor that takes no arguments. The InitialContext class passes the scheme id as the resolved object to the factory's getObjectInstance() method, which in turn creates a URL context for the URL scheme. The URL context will then be used to carry out the originally intended Context or DirContext operation on the URL supplied to InitialContext.

3.2.3 Service Provider's Responsibility

There is no requirement that a service provider supply a URL context factory and URL context implementation. It only does so if it wants to allow URL string names with its URL scheme to be accepted by the InitialContext class. A service provider, for instance, might just provide an initial context factory and a context implementation that is accessed through that factory.

3.3 Overriding the Default Behavior

The policy of creating an initial context factory using the java.naming.factory.initial environment property and URL support is built into the InitialContext class. There are two ways an application can override some or all of this policy.

3.3.1 Removing URL Support

If an application does not want URL strings to be treated specially, it can use the method NamingManager.getInitialContext(), which creates a context instance using the factory named in the java.naming.factory.initial environment property.

This method is also useful if the application needs to access interfaces implemented by the context created by the initial context factory, but which are not one of Context, DirContext, or LdapContext. Here is a code fragment that gets a context using NamingManager.getInitialContext() and then casts it to a subclass:

FooContext ctx = (FooContext) NamingManager.getInitialContext(env);
...
Object obj = ctx.lookup(name);
ctx.fooMethod1(...);
Note that installing an initial context factory builder (discussed next) affects the result of NamingManager.getInitialContext().

3.3.2 Removing All Policy

An initial context factory builder is a class that creates instances of initial context factories.

An application can install an initial context factory builder to define its own policy of how to locate and construct initial context implementations. When a builder has been installed, it is solely responsible for creating the initial context factories. None of the default policies (java.naming.factory.initial property or URL support) normally used by JNDI are employed.

An implementation of an initial context factory builder must implement the InitialContext-FactoryBuilder interface. Its createInitialContextFactory() method creates instances of InitialContextFactory.

After a builder has been installed. the application can get the initial context by either using the InitialContext/InitialDirContext/InitialLdapContext constructors, or by using NamingManager.getInitialContext(). When one of the constructors is used, its class is basically a wrapper around the underlying context implementation returned by NamingManager.getInitialContext().

3.4 Implementing a Subclass of InitialContext

When there is a need to provide an initial context that supports an interface that extends from Context, DirContext, or LdapContext, the service provider should supply a subclass of InitialContext (or InitialDirContext/InitialLdapContext).

3.4.1 URL Support

To add support for URLs in the same way InitialContext and InitialDirContext do, the subclass should use the protected methods available in InitialContext as follows. This only makes sense for interfaces that have methods that accept name argument.

For example, suppose FooContext is a subinterface of DirContext. Its initial context implementation would define getURLOrDefaultInitFooCtx() methods (for both Name and String parameters) that retrieve the real initial context to use.

public class InitialFooContext extends InitialDirContext {
        ...
        protected FooContext getURLOrDefaultInitFooCtx(Name name)
                throws NamingException {
                Context answer = getURLOrDefaultInitCtx(name);
                if (!(answer instanceof FooContext)) {
                        throw new NoInitialContextException("Not a FooContext");
                }
                return (FooContext)answer;
        }
        // similar code for getURLOrDefaultInitFooCtx(String name)
}
When providing implementations for the new methods in the FooContext interface that accept a name argument, getURLOrDefaultInitFooCtx() is used in the following way.
        public Object FooMethod1(Name name, ...) throws NamingException {
                return getURLOrDefaultInitFooCtx(name).FooMethod1(name, ...);
        }

3.4.2 New Method Support

When providing implementations for the new methods in the FooContext interface that do not have a name argument, or for which URL support is not required, use InitialContext.getDefaultInitCtx().

protected FooContext getDefaultInitFooCtx() throws NamingException {
        Context answer = getDefaultInitCtx();
        if (!(answer instanceof FooContext)) {
                throw new NoInitialContextException("Not an FooContext");
        }
        return (FooContext)answer;
}
public Object FooMethod2(Args args) throws NamingException {
        return getDefaultInitFooCtx().FooMethod2(args);
}

3.4.3 Constructors

The implementation should provide appropriate constructors for the class. The constructor should call the appropriate constructor of the superclass. If the environment needs to be modified or examined prior to the superclass's constructor being called, it should use the protected constructor that accepts a boolean flag to control the initialization of the initial context, and then use the init() method to initialize the context. Here is an example:

public InitialFooContext(Hashtable environment, Object otherArg)
            throws NamingException {
        super(true); // don't initialize yet

        // Clone environment and adjust
        Hashtable env = (environment == null) ? new Hashtable(11) :
                (Hashtable)environment.clone();
        ...
        init(env);
}
Client programs that use this new initial context would look as follows.

import com.widget.jndi.InitialFooContext;
...
FooContext ctx = new InitialFooContext(env);
Object obj = ctx.lookup(name);
ctx.FooMethod1(name, ...);

4 Customizing A Context Implementation

JNDI allows a context implementation to be customized-by the application, the application's deployer or user, or the service provider-in how it reads and stores objects in the naming/directory service. A similar facility is also available for narrowing LDAP v3 control classes.

You can think of these facilities as modules that plug into a context implementation.

4.1 Reading Objects: Object Factories

JNDI provides a generic way of creating objects (including instances of Context) using information stored in the namespace. That information may be of arbitrary type (java.lang.Object). For example, it may be a Reference, or a URL, or any other data required to create the object. Turning such information stored in the namespace into an object is supported through the use of object factories. An object factory is a class that implements the ObjectFactory interface (or the DirObjectFactory subinterface):

        public interface ObjectFactory {
                public Object getObjectInstance(Object refObj,
                                                Name name,
                                                Context nameCtx,
                                                Hashtable env)
                        throws Exception;
        }
        public interface DirObjectFactory extends ObjectFactory {
                public Object getObjectInstance(Object refObj,
                                                Name name,
                                                Context nameCtx,
                                                Hashtable env,
                                                Attributes attrs)
                        throws Exception;
        }

Given some reference information (refObj) about an object, optional information about the name of the object and where it is bound, and optionally some additional environment information (for example, some identity or authentication information about the user creating the object), the factory attempts to create an object represented by the reference information. For example, given reference information about a printer, a printer object factory might return an instance of Printer. In the case of an object factory that is to be used with a DirContext implementation, the factory is also given some attributes about the object. If the factory requires more attributes or information, it can obtain them directly from the naming/directory service by using the name/nameCtx arguments.

If the factory cannot created an object using the arguments supplied, it should return null. For example, when a printer object factory is given data about a disk drive, it should return null. The factory should only thrown an exception if no other object factories should be tried. Therefore, the factory should be careful about runtime exceptions that might be thrown from its implementation. For example, if a printer object factory is given data about a printer but the data is malformed in some way, it should throw an exception.

Object factories are used in several places in JNDI, basically to turn any reference information into an object. They are used in federation, URL processing in the initial context, and, as illustrated by the printer example, turning data into a form expected by the application.

4.1.1 Handling Structured References

A Reference contains methods for returning the class name and location of the object factory. The following methods are found in Reference.

public class Reference {
        ...
        public String   getClassName();
        public String getFactoryClassName();
        public String getFactoryClassLocation();
}
If the object read from the directory/naming service is an instance of Reference or Referenceable, its corresponding object factory can be located using information in Reference. The getFactoryClassName() method retrieves the name of the factory class that implements the ObjectFactory interface. This factory must implement the ObjectFactory interface and have a public constructor that takes no arguments. getFactoryClassLocation() retrieves the codebase of the class implementation for the factory, which is a list of space-separated URLs.

JNDI creates the object by invoking getObjectInstance() on the ObjectFactory instance, by using the Reference and environment as arguments. The result is an instance of a class identified by getClassName().

Note that all the classes necessary to instantiate the object returned to the application are made available using mechanisms provided by JNDI. The application doesn't have to install the classes locally.

Figure 3: Example Using Reference to Get Back an Object From the Namespace

Example Using Reference to Get Back an Object From the Namespace

Returning to the printer example, suppose Printer is an interface for representing a printer and the BSDPrinter class is an implementation of that interface. BSDPrinter implements the Referenceable interface and uses the Reference class to store information on how to construct instances of BSDPrinter and address information for communicating with the print server. The Reference contains the class name of the object ("Printer"), the class name of the printer object factory ("PrinterFactory") and a URL for loading the factory's class implementation. Using the factory class name and implementation location, JNDI first loads the implementation of PrinterFactory and creates an instance of PrinterFactory. It then invokes getObjectInstance() on the factory to create an instance of Printer using the reference. For example, one address in the reference may have an address of type "bsd", and contains the print server's host name ("lobby-printserver"). The PrinterFactory instance uses the address type ("bsd") to decide to create a BSDPrinter instance and passes the address contents ("lobby-printserver") to its constructor. The resulting BSDPrinter object is returned as the result of lookup().

From the context implementation's point of view, all of this is done automatically by its invocation of NamingManager/DirectoryManager.getObjectInstance().

When the application invokes print() on the BSDPrinter instance returned by lookup(), the data is sent to the print server on the machine "lobby-printserver" for printing. The application need not know the details of the Reference stored in the namespace, the protocol used to perform the job, or whether the BSDPrinter class was defined locally or loaded over the network. The transformation of the information stored in the underlying service into an object that implements the Printer interface is done transparently through the cooperation of the service provider (which stores bindings of printer names to printer address information), the printer service provider (which provides the PrinterFactory and BSDPrinter classes), and the JNDI SPI framework (which ties the two together to return an object that the application can use directly).

A service provider for such an object must do the following:

  2. Define the class for the object (e.g., BSDPrinter) that implements Referenceable or is a subclass of Reference.
  3. Define the Reference and its reference addresses for the object.
  4. Define a factory class that implements ObjectFactory (e.g., PrinterFactory). This class's getObjectInstance() method will create an instance of the class from step 1 (e.g., BSDPrinter) when given the Reference from step 2.

4.1.2 Handling URL References

If a Reference contains an address of type "URL" but not the factory class name and location, or if the reference is an array of strings containing URLs, JNDI will use the URL context factory support described in Section 3.2 to locate the factory, and then pass the URL string in the address to the factory's getObjectInstance() method. See Section 4.1.6 for a description of how JNDI expects a URL context factory implementation to behave.

A service provider for such an object must do the following:

  2. Define the class for the object (e.g., BSDPrinter).
  3. Define the URL scheme for the object.
  4. Define a URL context factory class that implements ObjectFactory. This class's getObjectInstance() method will create an instance of the class from step 1 (e.g., BSDPrinter) when given the URL from step 2.

4.1.3 Handling Arbitrary References: The java.naming.factory.object Property

In addition to extracting factory information from References, or using URLs, JNDI also looks for object factories specified in the java.naming.factory.object property, which can be in the environment or the provider resource file (see Section 2.9.5). The property contains a colon-separated list of fully-qualified class names of object factories. Each class must implement the ObjectFactory interface and have a public constructor that takes no arguments. For each class in the list, JNDI attempts to load and instantiate the factory class, and to invoke the ObjectFactory/DirObjectFactory.getObjectInstance() method on it using the object and environment arguments supplied. If the creation is successful, the resulting object is returned; otherwise, JNDI uses the same procedure on the next class in the list until the list is exhausted or a factory returns a non-null result.

Figure 4: Example using java.naming.factory.object to Get Back an Object from the Namespace

Example using java.naming.factory.object to Get Back an Object from the Namespace

For the printer example, instead of using a Reference to represent a printer in the namespace, some other information is stored. When that information is later retrieved, the object factories specified java.naming.factory.object are tried in turn to attempt to turn that information into a Printer instance.

A service provider for such an object must do the following:

  2. Define the class for the object (e.g., BSDPrinter).
  3. Define the class for reference information for the object. This is the object that will be bound in the namespace. This need not be Reference. It can be anything that will be understood by its corresponding object factory (e.g., some string containing the server name "printer type=bsd; host=lobby-printserver").
  4. Define a factory class that implements ObjectFactory (e.g., PrinterFactory). This class's getObjectInstance() method will create an instance of the class from step 1 (e.g., BSDPrinter) when given an instance of the class from step 2 (e.g., "printer type=bsd; host=lobby-printserver").

The service provider should automatically convert between the actual object (e.g., BSDPrinter) and the reference information (step 2, e.g., "printer type=bsd; host=lobby-printserver") when binding or looking up the object.

An application that wants to use a particular factory for generating objects must include the factory's class name in its java.naming.factory.object environment property and make the factory's classes and object classes available.

4.1.4 Overriding the Default Behavior

An object factory builder is a class that creates instances of object factories.

An application can install an object factory builder to defining its own policy of how to locate and construct object factory implementations. When a builder has been installed, it is solely responsible for creating the object factories. None of the default policies (Reference, URL string, or java.naming.factory.object property) normally used by JNDI are employed.

Figure 5: Example using an Object Factory Builder to Get Back an Object from the Namespece

Example using an Object Factory Builder to Get Back an Object from the Namespece

A service provider for an object factory builder must do the following:

  2. Define object factories that implement ObjectFactory.
  3. Define a class that implements ObjectFactoryBuilder. This class's createObjectFactory() method will use the constructors for the ObjectFactory classes in step 1.

An application that wants to use this factory builder must first install it.

       NamingManager.setObjectFactoryBuilder(builder);

4.1.5 Context Factory

A context factory is an object factory that creates instances of Context. The implementation of these contexts for a particular naming or directory service is referred to as a context implementation. Context implementations are described in Chapter 2. Like any other object factory, a context factory can be obtained by using any of the three mechanisms described above: from a Reference, a URL scheme id, or listed in the java.naming.factory.object property.

4.1.6 URL Context Factory

A URL context factory is a special kind of context factory. It follows these rules when implementing ObjectFactory.getObjectInstance().

  • If refObj is null, create a context for resolving URLs of the scheme associated with this factory. The resulting context is not tied to a specific URL. For example, invoking
getObjectInstance(null, null, null, env)
  • on an "ldap" URL context factory returns a context that can resolve LDAP URLs (e.g., "ldap://ldap.wiz.com/o=wiz,c=us" or "ldap://ldap.umich.edu/", ...).
  • If refObj is a URL string, create the object identified by the URL. For example, invoking
getObjectInstance("ldap://ldap.wiz.com/o=wiz,c=us", null, null, env);
  • on an "ldap" URL context factory would return the object named by "o=wiz,c=us" on the LDAP server ldap.wiz.com. If this happens to name a context, it can then be used for resolving (relative) LDAP names (e.g., "cn=Jane Smith").
  • If refObj is an array of URL strings, the assumption is that the URLs are equivalent in terms of the context to which they refer. Verification of whether the URLs are, or need to be, equivalent is up to the context factory. The order of the URLs in the array is not significant. The object returned by getObjectInstance() is the same as that for the single URL case-it is an object (perhaps a context) named by the URLs.
  • If refObj is any other type, the behavior of getObjectInstance() is determined by the implementation.

    URL context factories are used by the InitialContext class when it is passed a URL to resolve. URL context factories are also used for creating objects in the Java programming language from URLs stored in the namespace (see Section 4.1.2).

4.2 Storing Objects: State Factories

JNDI provides a mechanism to transform an object into a form storable by the underlying context implementation. That form may be any arbitrary type acceptable to the underlying context implementation. For example, it may be a Reference, a URL, a Serializable object, or a set of attributes, or any other data acceptable by the underlying context implementation. Turning an arbitrary object into data that can be stored in the namespace is supported through the use of state factories. A state factory is a class that implements the StateFactory interface (or the DirStateFactory subinterface):

        public interface StateFactory {
                public Object getStateToBind(Object obj,
                                             Name name,
                                             Context nameCtx,
                                             Hashtable env)
                        throws NamingException;
        }

        public interface DirStateFactory {
                public DirStateFactory.Result getStateToBind(Object obj,
                                                             Name name,
                                                             Context nameCtx,
                                                             Hashtable env,
                                                             Attributes attrs)
                        throws NamingException;
        }

Given an object (obj), optional information about the name of the object and where it is bound, and optionally some additional environment information (for example, some identity or authentication information about the user accessing the namespace), the factory attempts to create an object suitable for binding. Typically, the state factory is knowledgeable about the target naming/directory service and/or context implementation, and knows which data formats are acceptable. In the case of a state factory that is to be used with a DirContext implementation, the factory is also given some attributes that are to be stored with the object. If the factory require more information about the object, it can obtain them directly from the naming/directory service by using the name/nameCtx arguments. For example, a printer state factory for an LDAP directory might return a set of attributes that represent the printer.

If the factory cannot return any data using the arguments supplied, it should return null. For example, when a printer state factory is given a disk object, it should return null. The factory should only thrown an exception if no other state factories should be tried. Therefore, the factory should be careful about exceptions that might be thrown from its implementation. For example, if a printer state factory is given a printer object but perhaps contradictory attributes, it might throw an exception.

4.2.1 Input/Output Options

Ultimately, a factory's output formats are determined by the underlying naming/directory service. A context implementation for the CORBA Object Services (COS) naming service, for example, can only store CORBA object references into the service; a context implementation for LDAP can only store attributes, although there is a lot of flexibility in how to encode information within those attributes.

A service provider typically supplies a factory for each (common) type of input that it expects, and the application can augment that set with state factories of its own. For example, a service provider for COS naming might have a state factory for converting a Java Remote Method Invocation (RMI) object into a CORBA object reference. A user of that provider might add a state factory for converting a Microsoft COM object reference into a CORBA object reference.

4.2.2 Locating State Factories: The java.naming.factory.state Property

JNDI looks for state factories specified in the java.naming.factory.state property, which can be in the environment or the provider resource file (see Section 2.9.5). The property contains a colon-separated list of fully-qualified class names of state factories. Each class must implement the StateFactory interface and have a public constructor that takes no arguments. For each class in the list, JNDI attempts to load and instantiate the factory class, and to invoke the StateFactory/DirStateFactory.getStateToBind() method on it using the object, name, context, environment, and attributes arguments supplied. If the factory produces a non-null result, the result is returned; otherwise, JNDI uses the same procedure on the next class in the list until the list is exhausted or a factory returns a non-null result.

4.3 Narrowing LDAP v3 Controls: Response Control Factories

The LDAP v3 protocol allows response controls to accompany any response sent by the server. The control consists of an OID string identifier and a sequence of ASN.1 BER encoded bytes. In the absence of any external information or assistance, the context implementation can only return a plain implementation of the Control interface that returns the OID and bytes.

JNDI provides the following abstract class for dealing with response controls:

        public abstract javax.naming.ldap.ControlFactory {
        ...
        public static Control getControlInstance(Control ctl,
                                                Context ctx,
                                                Hashtable env)
                throws NamingException;
        public abstract Control getControlInstance(Control ctl)
                throws NamingException;
}
When a context implementation receives a response control, it invokes the static getControl-Instance() method to find a control factory that can narrow the control to one that has more user-friendly access methods. Such a control, for instance, can decode the ASN.1 BER bytes and provide access methods that return the information as Java types. If no such control factory can be found, the original response control is returned. Here is an example of a hypothetical Time-ResponseControl which decodes the time of day.
public class TimeResponseControl implements Control {
        long time;
        // Constructor used by ControlFactory
        public TimeResponseControl(String OID, byte[] berVal)
                throws NamingException {
                // check validity of OID
                time = // extract time from berVal
        };

        // Type-safe and User-friendly method
        public long getTime() {
                return time;
        }
        // Low-level methods
        public String getID() {
                return TIME_OID;
        }
        public byte[] getEncodedValue() {
                return // original berVal
        }
         ...
}
A control factory may be responsible for one or more controls. If the factory cannot return a control using the arguments supplied, it should return null. Typically, this involves just matching the control's OID against the list of OIDs supported by the factory. The factory should only thrown an exception if no other control factories should be tried. Therefore, the factory should be careful about exceptions that might be thrown from its implementation. For example, if a control factory is given a control with an OID that it supports, but the byte array has an encoding error, it should throw an exception.

Here is an example of a control factory:

public class VendorXControlFactory extends ControlFactory {
        public VendorXControlFactory () {
        }
        public Control getControlInstance(Control orig)
                throws NamingException {
                if (isOneOfMyControls(orig.getID())) {
                         ...
                        // determine which of ours it is and call its constructor
                        return new TimeResponseControl(orig.getID(),
                                                                orig.getEncodedValue());
                }
                return null;  // not one of ours
        }
}

4.3.1 Locating Response Control Factories: The java.naming.factory.control Property

JNDI looks for response control factories specified in the java.naming.factory.control property, which can be in the environment or the provider resource file (see Section 2.9.5). The property contains a colon-separated list of fully-qualified class names of control factories. Each class must implement the ControlFactory interface and have a public constructor that takes no arguments. For each class in the list, JNDI attempts to load and instantiate the factory class, and to invoke the ControlFactory.getControlInstance() instance method on it using the control, context, and environment arguments supplied. If the factory produces a non-null result, the result is returned; otherwise, JNDI uses the same procedure on the next class in the list until the list is exhausted or a factory returns a non-null result.

4.4 Ownership of Parameters

Any object passed as a parameter to a method in a factory is owned by the caller. Therefore, the factory is prohibited from maintaining a pointer to the object beyond the duration of the operation or modifying the object. If the factory needs to save the information contained in a parameter beyond the duration of the operation, it should maintain its own copy.

4.5 Reentrancy

A factory instance should be reentrant. That is, it should be possible for multiple threads to invoke methods on a single instance of a factory concurrently.

[Top] [Prev] [Next] [Bottom]

1 See Appendix B for legend of class diagram. 2 The CannotProceedException may well have been thrown by one of the context's internal methods when it discovered that the name being processed is beyond the scope of its naming system. The process by which the exception is produced is dependent on the implementation of the context. 3 Note that this is code in the application. In "Continuing an Operation in a Federation", the code sample presented is code in the context implementation. 4 You can also use a subclass of Hashtable (e.g. Properties) for this. 5 The mention of "URL" in this document refers to a URL string as defined by RFC 1738 and its related RFCs. It is any string that conforms to the syntax described therein, and may not always have corresponding support in the java.net.URL class or Web browsers. The URL string is either passed as the String name parameter, or as the first component of the Name parameter.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
[Top] [Prev] [Next] [Bottom]
1 Introduction
1.1 Document Overview
1.2 Interface Overview
1.2.1 NamingManager and DirectoryManager
1.2.2 Initial Contexts
1.2.3 Object Factories
1.2.4 State Factories
1.2.5 Federation Support
2 Building a Context Implementation
2.1 Ownership of Parameters
2.2 Reentrancy
2.3 Basic Support-Implementing the Context Interface(s)
2.4 Object Support
2.4.1 Reading an Object
2.4.2 Storing an Object
2.5 Federation Support
2.5.1 Names
2.5.2 Resolving Through a Context
2.5.3 Resolving Through to Subinterfaces of Context
2.5.4 Naming System Boundaries
2.5.5 Continuing an Operation in a Federation
2.5.6 "Dynamic" Location of Next Naming System
2.5.7 More about CannotProceedException
2.5.8 Contextual Information
2.6 Referral Support
2.7 Schema Support
2.8 Event Support
2.9 Context Environment Support
2.9.1 Property Naming Convention
2.9.2 Initializing a Context's Environment
2.9.3 Inheritance
2.9.4 Updates to the Environment
2.9.5 Provider Resource Files
2.10 Connection Management
3 The Initial Context
3.1 The Initial Context Factory
3.1.1 Exceptions
3.2 URL Support
3.2.1 URL Context
3.2.2 URL Context Factory
3.2.3 Service Provider's Responsibility
3.3 Overriding the Default Behavior
3.3.1 Removing URL Support
3.3.2 Removing All Policy
3.4 Implementing a Subclass of InitialContext
3.4.1 URL Support
3.4.2 New Method Support
3.4.3 Constructors
4 Customizing A Context Implementation
4.1 Reading Objects: Object Factories
4.1.1 Handling Structured References
4.1.2 Handling URL References
4.1.3 Handling Arbitrary References: The java.naming.factory.object Property
4.1.4 Overriding the Default Behavior
4.1.5 Context Factory
4.1.6 URL Context Factory
4.2 Storing Objects: State Factories
4.2.1 Input/Output Options
4.2.2 Locating State Factories: The java.naming.factory.state Property
4.3 Narrowing LDAP v3 Controls: Response Control Factories
4.3.1 Locating Response Control Factories: The java.naming.factory.control Property
4.4 Ownership of Parameters
4.5 Reentrancy
Appendix A: Service Provider Example
Appendix B: Legend for Class Diagram
Appendix C: JNDI Change History

[Top] [Prev] [Next] [Bottom]
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

Contents

1. Introduction

2. Goals and Design Principles

3. Overview of the Architecture

4. Fundamentals
4.1 Naming -- The Foundation
4.2 Directory Objects
4.3 URLs and Composite Names
4.4 Events
5. Overview of the Interface
5.1 The Naming Package -- javax.naming
5.1.1 Contexts
5.1.2 The Initial Context
5.1.3 Names
5.1.4 Bindings
5.1.5 References
5.1.6 Referrals
5.2 The Directory Package -- javax.naming.directory
5.2.1 Directory Objects
5.2.2 Attributes
5.2.3 Directory Objects as Naming Contexts
5.2.4 The Initial Context
5.2.5 Searches
5.2.6 Schema
5.3 The Event Package -- javax.naming.event
5.3.1 Naming Events
5.3.2 Naming Listeners
5.3.3 Event Registration and Deregistration
5.3.4 Exception Handling
5.4 The LDAP Package -- javax.naming.ldap
5.4.1 Extended Operations
5.4.2 Controls
5.4.3 The Initial Context
5.4.4 Unsolicited Notifications
6. Configuration
6.1 Environment Properties
6.2 Context Environment
6.3 Resource Files
6.4 Application/Applet-scope Standard JNDI Properties
6.5 How the Environment Properties are Set
6.6 Modifications to the Environment
7. Scenarios
7.1 User authentication
7.2 Electronic Mail
7.3 Databases
7.4 Browsing
7.5 Network Printing
8. Security Considerations
8.1 JNDI Classes
8.2 Security Model
8.3 Access To Servers
8.4 Sharing Context Handles
8.5 Context Environment
8.6 Class Loading
8.7 Serializable Objects
8.8 Responsibilities of Service Providers
9. Design Choices
9.1 Separation of Interfaces into Context and DirContext
9.2 Separation of JNDI into Different Functional Packages
9.3 Separation of Client APIs and Service Provider Interfaces
9.4 Multiple methods for listing Context
9.5 Support for Federation
9.6 DirContext versus DirObject
9.7 Support for Schemas
9.8 Overloaded Methods in Context and DirContext
9.9 Reference and Referenceable
9.10 Automatically Turning References into Objects

Appendix A: JNDI Standard Environment Properties

Appendix B: Examples for LDAP Programmers

Appendix C: Legend for Class Diagram

Appendix D: JNDI Change History

CONTENTS | PREV | NEXT

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JNI Enhancements in the Java 2 SDK

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

JNI Enhancements
Introduced in Version 1.4
of the JavaTM 2 SDK

JNI has been enhanced in v 1.4 with support for the java.nio package as well as a new entry point in the JNI Invocation Interface. Also, the JNI version number has been incremented and the description of JNI_OnLoad updated accordingly.

The new Invocation Interface routine allows native code to attach a daemon thread to the Java virtual machine (JVM); this is useful when the JVM should not wait for this thread to exit upon shutdown.

  • AttachCurrentThreadAsDaemon

The NIO-related entry points allow native code to access java.nio direct buffers. The contents of a direct buffer can, potentially, reside in native memory outside of the ordinary garbage-collected heap. For information about direct buffers, please see New I/O APIs and the specification of the java.nio.ByteBuffer class.

Three new functions allow JNI code to create, examine, and manipulate direct buffers:
  • NewDirectByteBuffer
  • GetDirectBufferAddress
  • GetDirectBufferCapacity

Every implementation of the Java virtual machine must support these functions, but not every implementation is required to support JNI access to direct buffers. If a JVM does not support such access then the NewDirectByteBuffer and GetDirectBufferAddress functions must always return NULL, and the GetDirectBufferCapacity function must always return -1. If a JVM does support such access then these three functions must be implemented to return the appropriate values.

Incremented Version Number

The JNI version number has been incremented. The include file jni.h defines the new constant:

    #define JNI_VERSION_1_4 0x00010004

The GetVersion procedure now returns this value, and the specification of the JNI_OnLoad procedure has been revised:

    jint JNI_OnLoad(JavaVM *vm, void *reserved);

      The VM calls JNI_OnLoad when the native library is loaded (for example,
      through System.loadLibrary).  JNI_OnLoad must return the JNI version
      needed by the native library.

      In order to use the JNI functions introduced in J2SE release 1.2 in
      addition to those that were available in JDK 1.1, a native library must
      export a JNI_OnLoad function that returns JNI_VERSION_1_2.

      In order to use the JNI functions introduced in J2SE release 1.4 in
      addition to those that were available in release 1.2, a native library
      must export a JNI_OnLoad function that returns JNI_VERSION_1_4.

      If the native library does not export a JNI_OnLoad function, the VM
      assumes that the library only requires JNI version JNI_VERSION_1_1.  If
      the VM does not recognize the version number returned by JNI_OnLoad, the
      native library cannot be loaded.

Additions to the JNI Invocation Interface

AttachCurrentThreadAsDaemon

jint AttachCurrentThreadAsDaemon(JavaVM* vm, void** penv, void* args);

Same semantics as AttachCurrentThread, but the newly-created java.lang.Thread instance is a daemon.

If the thread has already been attached via either AttachCurrentThread or AttachCurrentThreadAsDaemon, this routine simply sets the value pointed to by penv to the JNIEnv of the current thread. In this case neither AttachCurrentThread nor this routine have any effect on the daemon status of the thread.

LINKAGE

Index 7 in the JavaVM interface function table.

PARAMETERS

vm: the virtual machine instance to which the current thread will be attached.

penv: a pointer to the location in which the JNIEnv interface pointer for the current thread will be placed.

args: a pointer to a JavaVMAttachArgs structure.

RETURNS

Returns zero on success; otherwise, returns a negative number.

EXCEPTIONS

None.

Additions to the JNI Interface

NewDirectByteBuffer

jobject NewDirectByteBuffer(JNIEnv* env, void* address, jlong capacity);

Allocates and returns a direct java.nio.ByteBuffer referring to the block of memory starting at the memory address address and extending capacity bytes.

Native code that calls this function and returns the resulting byte-buffer object to Java-level code should ensure that the buffer refers to a valid region of memory that is accessible for reading and, if appropriate, writing. An attempt to access an invalid memory location from Java code will either return an arbitrary value, have no visible effect, or cause an unspecified exception to be thrown.

LINKAGE

Index 229 in the JNIEnv interface function table.

PARAMETERS

env: the JNIEnv interface pointer

address: the starting address of the memory region (must not be NULL)

capacity: the size in bytes of the memory region (must be positive)

RETURNS

Returns a local reference to the newly-instantiated java.nio.ByteBuffer object. Returns NULL if an exception occurs, or if JNI access to direct buffers is not supported by this virtual machine.

EXCEPTIONS

OutOfMemoryError: if allocation of the ByteBuffer object fails

GetDirectBufferAddress

void* GetDirectBufferAddress(JNIEnv* env, jobject buf);

Fetches and returns the starting address of the memory region referenced by the given direct java.nio.Buffer.

This function allows native code to access the same memory region that is accessible to Java code via the buffer object.

LINKAGE

Index 230 in the JNIEnv interface function table.

PARAMETERS

env: the JNIEnv interface pointer

buf: a direct java.nio.Buffer object (must not be NULL)

RETURNS

Returns the starting address of the memory region referenced by the buffer. Returns NULL if the memory region is undefined, if the given object is not a direct java.nio.Buffer, or if JNI access to direct buffers is not supported by this virtual machine.

GetDirectBufferCapacity

jlong GetDirectBufferCapacity(JNIEnv* env, jobject buf);

Fetches and returns the capacity in bytes of the memory region referenced by the given direct java.nio.Buffer.

LINKAGE

Index 231 in the JNIEnv interface function table.

PARAMETERS

env: the JNIEnv interface pointer

buf: a direct java.nio.Buffer object (must not be NULL)

RETURNS

Returns the capacity in bytes of the memory region associated with the buffer. Returns -1 if the given object is not a direct java.nio.Buffer, or if JNI access to direct buffers is not supported by this virtual machine.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Contents

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java Native Interface Specification—Contents

Contents | Previous | Next

1. Introduction

Java Native Interface Overview
 Background

JDK 1.0 Native Method Interface
 Java Runtime Interface
Raw Native Interface and Java/COM Interface

Objectives
 Java Native Interface Approach
Programming to the JNI
 Changes in JDK 1.1.2

2. Design Overview

JNI Interface Functions and Pointers
 Compiling, Loading and Linking Native Methods

Resolving Native Method Names
 Native Method Arguments

Referencing Java Objects

Global and Local References
 Implementing Local References

Accessing Java Objects

Accessing Primitive Arrays
 Accessing Fields and Methods

Reporting Programming Errors
 Java Exceptions

Exceptions and Error Codes
 Asynchronous Exceptions
 Exception Handling

3. JNI Types and Data Structures

Primitive Types
Reference Types
Field and Method IDs
The Value Type
Type Signatures
Modified UTF-8 Strings

4. JNI Functions

Interface Function Table
Version Information

GetVersion

Class Operations

DefineClass
 FindClass
 GetSuperclass
 IsAssignableFrom

Exceptions

Throw
 ThrowNew
ExceptionOccurred
 ExceptionDescribe
ExceptionClear
 FatalError
 ExceptionCheck

Global and Local References

NewGlobalRef
 DeleteGlobalRef
DeleteLocalRef
 EnsureLocalCapacity
 PushLocalFrame
 PopLocalFrame
 NewLocalRef

Weak Global References

NewWeakGlobalRef
 DeleteWeakGlobalRef

Object Operations

AllocObject
 NewObject, NewObjectA, and NewObjectV
GetObjectClass
GetObjectRefType
IsInstanceOf
IsSameObj ect

Accessing Fields of Objects

GetFieldID
 Get<type>Field Routines
Set<type>Field Routines

Calling Instance Methods

GetMethodID
 Call<type>Method Routines, Call<type>MethodA Routines, and Call<type>MethodV Routines
CallNonvirtual<type>Method Routines, CallNonvirtual<type>MethodA Routines, and CallNonvirtual<type>MethodV Routines

Accessing Static Fields

GetStaticFieldID
 GetStatic<type>Field Routines
SetStatic<type>Field Routines

Calling Static Methods

GetStaticMethodID
 CallStatic<type>Method Routines, CallStatic<type>MethodA Routines, and CallStatic<type>MethodV Routines

String Operations

NewString
 GetStringLength
GetStringChars
 ReleaseStringChars
NewStringUTF
 GetStringUTFLength
GetStringUTFChars
 ReleaseStringUTFChars
 GetStringRegion
 GetStringUTFRegion
 GetStringCritical
 Release StringCritical

Array Operations

GetArrayLength
 NewObjectArray
GetObjectArrayElement
 SetObjectArrayElement
New<PrimitiveType>Array Routines
 Get<PrimitiveType>ArrayElements Routines
Release<PrimitiveType>ArrayElements Routines
 Get<PrimitiveType>ArrayRegion Routines
Set<PrimitiveType>ArrayRegion Routines
 GetPrimitiveArrayCritical
 ReleasePrimitiveArrayCritical

Registering Native Methods

RegisterNatives
 UnregisterNatives

Monitor Operations

MonitorEnter
 MonitorExit

NIO Support

NewDirectByteBuffer
 GetDirectBufferAddress
 GetDirectBufferCapacity

Reflection Support

FromReflectedMethod
 FromReflectedField
 ToReflectedMethod
 ToReflectedField

Java VM Interface

GetJavaVM

5. The Invocation API

Overview

Creating the VM
 Attaching to the VM
Unloading the VM

Library and Version Management

JNI_OnLoad
 JNI_OnUnload

Invocation API Functions

JNI_GetDefaultJavaVMInitArgs
 JNI_GetCreatedJavaVMs
JNI_CreateJavaVM
 DestroyJavaVM
AttachCurrentThread
 AttachCurrentThreadAsDaemon
 DetachCurrentThread
 GetEnv

Contents | Previous | Next
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JNLPRandomAccessFile (JNLP API Reference 1.7.0)

  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method
javax.jnlp

Interface JNLPRandomAccessFile

  • All Superinterfaces:
    java.io.DataInput, java.io.DataOutput

    public interface JNLPRandomAccessFile
extends java.io.DataInput, java.io.DataOutput
    Instances of this class support both reading and writing to a random access file. A random access file behaves like a large array of bytes stored in the file system. There is a kind of cursor, or index into the implied array, called the file pointer; input operations read bytes starting at the file pointer and advance the file pointer past the bytes read. If the random access file is created in read/write mode, then output operations are also available; output operations write bytes starting at the file pointer and advance the file pointer past the bytes written. Output operations that write past the current end of the implied array cause the array to be extended. The file pointer can be read by the getFilePointer method and set by the seek method.

    It is generally true of all the reading routines in this class that if end-of-file is reached before the desired number of bytes has been read, an EOFException (which is a kind of IOException) is thrown. If any byte cannot be read for any reason other than end-of-file, an IOException other than EOFException is thrown. In particular, an IOException may be thrown if the stream has been closed.

    Implementations are encouraged to enforce a maximum amount of data that may be written to a file.

    Since:
    1.0

    • Method Summary

      Methods
      Modifier and Type Method and Description
      void close()
      Closes this random access file stream and releases any system resources associated with the stream.
      long getFilePointer()
      Returns the current offset in this file.
      long length()
      Returns the length of this file.
      int read()
      Reads a byte of data from this file.
      int read(byte[] b)
      Reads up to b.length bytes of data from this file into an array of bytes.
      int read(byte[] b, int off, int len)
      Reads up to len bytes of data from this file into an array of bytes.
      boolean readBoolean()
      Reads a boolean from this file.
      byte readByte()
      Reads a signed eight-bit value from this file.
      char readChar()
      Reads a Unicode character from this file.
      double readDouble()
      Reads a double from this file.
      float readFloat()
      Reads a float from this file.
      void readFully(byte[] b)
      Reads b.length bytes from this file into the byte array, starting at the current file pointer.
      void readFully(byte[] b, int off, int len)
      Reads exactly len bytes from this file into the byte array, starting at the current file pointer.
      int readInt()
      Reads a signed 32-bit integer from this file.
      java.lang.String readLine()
      Reads the next line of text from this file.
      long readLong()
      Reads a signed 64-bit integer from this file.
      short readShort()
      Reads a signed 16-bit number from this file.
      int readUnsignedByte()
      Reads an unsigned eight-bit number from this file.
      int readUnsignedShort()
      Reads an unsigned 16-bit number from this file.
      java.lang.String readUTF()
      Reads in a string from this file.
      void seek(long pos)
      Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.
      void setLength(long newLength)
      Sets the length of this file.
      int skipBytes(int n)
      Attempts to skip over n bytes of input discarding the skipped bytes.
      void write(byte[] b)
      Writes b.length bytes from the specified byte array to this file, starting at the current file pointer.
      void write(byte[] b, int off, int len)
      Writes len bytes from the specified byte array starting at offset off to this file.
      void write(int b)
      Writes the specified byte to this file.
      void writeBoolean(boolean v)
      Writes a boolean to the file as a one-byte value.
      void writeByte(int v)
      Writes a byte to the file as a one-byte value.
      void writeBytes(java.lang.String s)
      Writes the string to the file as a sequence of bytes.
      void writeChar(int v)
      Writes a char to the file as a two-byte value, high byte first.
      void writeChars(java.lang.String s)
      Writes a string to the file as a sequence of characters.
      void writeDouble(double v)
      Converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the file as an eight-byte quantity, high byte first.
      void writeFloat(float v)
      Converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the file as a four-byte quantity, high byte first.
      void writeInt(int v)
      Writes an int to the file as four bytes, high byte first.
      void writeLong(long v)
      Writes a long to the file as eight bytes, high byte first.
      void writeShort(int v)
      Writes a short to the file as two bytes, high byte first.
      void writeUTF(java.lang.String str)
      Writes a string to the file using UTF-8 encoding in a machine-independent manner.

    • Method Detail

      • close

        void close()
           throws java.io.IOException
        Closes this random access file stream and releases any system resources associated with the stream. A closed random access file cannot perform input or output operations and cannot be reopened.
        Throws:
        java.io.IOException - if an I/O error occurs.

      • length

        long length()
            throws java.io.IOException
        Returns the length of this file.
        Returns:
        the length of this file, measured in bytes.
        Throws:
        java.io.IOException - if an I/O error occurs.

      • getFilePointer

        long getFilePointer()
                    throws java.io.IOException
        Returns the current offset in this file.
        Returns:
        the offset from the beginning of the file, in bytes, at which the next read or write occurs.
        Throws:
        java.io.IOException - if an I/O error occurs.

      • read

        int read()
         throws java.io.IOException
        Reads a byte of data from this file. The byte is returned as an integer in the range 0 to 255 (0x00-0x0ff). This method blocks if no input is yet available.

        Although JNLPRandomAccessFile is not a subclass of InputStream, this method behaves in exactly the same way as the read method of InputStream.

        Returns:
        the next byte of data, or -1 if the end of the file has been reached.
        Throws:
        java.io.IOException - if an I/O error occurs. Not thrown if end-of-file has been reached.

      • read

        int read(byte[] b,
       int off,
       int len)
         throws java.io.IOException
        Reads up to len bytes of data from this file into an array of bytes. This method blocks until at least one byte of input is available.

        Although JNLPRandomAccessFile is not a subclass of InputStream, this method behaves in the exactly the same way as the read(byte[], int, int) method of InputStream.

        Parameters:
        b - the buffer into which the data is read.
        off - the start offset of the data.
        len - the maximum number of bytes read.
        Returns:
        the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.
        Throws:
        java.io.IOException - if an I/O error occurs.

      • read

        int read(byte[] b)
         throws java.io.IOException
        Reads up to b.length bytes of data from this file into an array of bytes. This method blocks until at least one byte of input is available.

        Although JNLPRandomAccessFile is not a subclass of InputStream, this method behaves in the exactly the same way as the read(byte[]) method of InputStream.

        Parameters:
        b - the buffer into which the data is read.
        Returns:
        the total number of bytes read into the buffer, or -1 if there is no more data because the end of this file has been reached.
        Throws:
        java.io.IOException - if an I/O error occurs.

      • readFully

        void readFully(byte[] b)
               throws java.io.IOException
        Reads b.length bytes from this file into the byte array, starting at the current file pointer. This method reads repeatedly from the file until the requested number of bytes are read. This method blocks until the requested number of bytes are read, the end of the stream is detected, or an exception is thrown.
        Specified by:
        readFully in interface java.io.DataInput
        Parameters:
        b - the buffer into which the data is read.
        Throws:
        EOFException - if this file reaches the end before reading all the bytes.
        java.io.IOException - if an I/O error occurs.

      • readFully

        void readFully(byte[] b,
             int off,
             int len)
               throws java.io.IOException
        Reads exactly len bytes from this file into the byte array, starting at the current file pointer. This method reads repeatedly from the file until the requested number of bytes are read. This method blocks until the requested number of bytes are read, the end of the stream is detected, or an exception is thrown.
        Specified by:
        readFully in interface java.io.DataInput
        Parameters:
        b - the buffer into which the data is read.
        off - the start offset of the data.
        len - the number of bytes to read.
        Throws:
        EOFException - if this file reaches the end before reading all the bytes.
        java.io.IOException - if an I/O error occurs.

      • skipBytes

        int skipBytes(int n)
              throws java.io.IOException
        Attempts to skip over n bytes of input discarding the skipped bytes.

        This method may skip over some smaller number of bytes, possibly zero. This may result from any of a number of conditions; reaching end of file before n bytes have been skipped is only one possibility. This method never throws an EOFException. The actual number of bytes skipped is returned. If n is negative, no bytes are skipped.

        Specified by:
        skipBytes in interface java.io.DataInput
        Parameters:
        n - the number of bytes to be skipped.
        Returns:
        the actual number of bytes skipped.
        Throws:
        java.io.IOException - if an I/O error occurs.

      • readBoolean

        boolean readBoolean()
                    throws java.io.IOException
        Reads a boolean from this file. This method reads a single byte from the file, starting at the current file pointer. A value of 0 represents false. Any other value represents true. This method blocks until the byte is read, the end of the stream is detected, or an exception is thrown.
        Specified by:
        readBoolean in interface java.io.DataInput
        Returns:
        the boolean value read.
        Throws:
        EOFException - if this file has reached the end.
        java.io.IOException - if an I/O error occurs.

      • readByte

        byte readByte()
              throws java.io.IOException
        Reads a signed eight-bit value from this file. This method reads a byte from the file, starting from the current file pointer. If the byte read is b, where 0 <= b <= 255, then the result is:
             (byte)(b)

        This method blocks until the byte is read, the end of the stream is detected, or an exception is thrown.

        Specified by:
        readByte in interface java.io.DataInput
        Returns:
        the next byte of this file as a signed eight-bit byte.
        Throws:
        EOFException - if this file has reached the end.
        java.io.IOException - if an I/O error occurs.

      • readUnsignedByte

        int readUnsignedByte()
                     throws java.io.IOException
        Reads an unsigned eight-bit number from this file. This method reads a byte from this file, starting at the current file pointer, and returns that byte.

        This method blocks until the byte is read, the end of the stream is detected, or an exception is thrown.

        Specified by:
        readUnsignedByte in interface java.io.DataInput
        Returns:
        the next byte of this file, interpreted as an unsigned eight-bit number.
        Throws:
        EOFException - if this file has reached the end.
        java.io.IOException - if an I/O error occurs.

      • readShort

        short readShort()
                throws java.io.IOException
        Reads a signed 16-bit number from this file. The method reads two bytes from this file, starting at the current file pointer. If the two bytes read, in order, are b1 and b2, where each of the two values is between 0 and 255, inclusive, then the result is equal to:
             (short)((b1 << 8) | b2)

        This method blocks until the two bytes are read, the end of the stream is detected, or an exception is thrown.

        Specified by:
        readShort in interface java.io.DataInput
        Returns:
        the next two bytes of this file, interpreted as a signed 16-bit number.
        Throws:
        EOFException - if this file reaches the end before reading two bytes.
        java.io.IOException - if an I/O error occurs.

      • readUnsignedShort

        int readUnsignedShort()
                      throws java.io.IOException
        Reads an unsigned 16-bit number from this file. This method reads two bytes from the file, starting at the current file pointer. If the bytes read, in order, are b1 and b2, where 0 <= b1, b2 <= 255, then the result is equal to:
             (b1 << 8) | b2

        This method blocks until the two bytes are read, the end of the stream is detected, or an exception is thrown.

        Specified by:
        readUnsignedShort in interface java.io.DataInput
        Returns:
        the next two bytes of this file, interpreted as an unsigned 16-bit integer.
        Throws:
        EOFException - if this file reaches the end before reading two bytes.
        java.io.IOException - if an I/O error occurs.

      • readChar

        char readChar()
              throws java.io.IOException
        Reads a Unicode character from this file. This method reads two bytes from the file, starting at the current file pointer. If the bytes read, in order, are b1 and b2, where 0 <= b1, b2 <= 255, then the result is equal to:
             (char)((b1 << 8) | b2)

        This method blocks until the two bytes are read, the end of the stream is detected, or an exception is thrown.

        Specified by:
        readChar in interface java.io.DataInput
        Returns:
        the next two bytes of this file as a Unicode character.
        Throws:
        EOFException - if this file reaches the end before reading two bytes.
        java.io.IOException - if an I/O error occurs.

      • readInt

        int readInt()
            throws java.io.IOException
        Reads a signed 32-bit integer from this file. This method reads 4 bytes from the file, starting at the current file pointer. If the bytes read, in order, are b1, b2, b3, and b4, where 0 <= b1, b2, b3, b4 <= 255, then the result is equal to:
             (b1 << 24) | (b2 << 16) + (b3 << 8) + b4

        This method blocks until the four bytes are read, the end of the stream is detected, or an exception is thrown.

        Specified by:
        readInt in interface java.io.DataInput
        Returns:
        the next four bytes of this file, interpreted as an int.
        Throws:
        EOFException - if this file reaches the end before reading four bytes.
        java.io.IOException - if an I/O error occurs.

      • readLong

        long readLong()
              throws java.io.IOException
        Reads a signed 64-bit integer from this file. This method reads eight bytes from the file, starting at the current file pointer. If the bytes read, in order, are b1, b2, b3, b4, b5, b6, b7, and b8, where:
             0 <= b1, b2, b3, b4, b5, b6, b7, b8 <=255,

        then the result is equal to:

             ((long)b1 << 56) + ((long)b2 << 48)
     + ((long)b3 << 40) + ((long)b4 << 32)
     + ((long)b5 << 24) + ((long)b6 << 16)
     + ((long)b7 << 8) + b8

        This method blocks until the eight bytes are read, the end of the stream is detected, or an exception is thrown.

        Specified by:
        readLong in interface java.io.DataInput
        Returns:
        the next eight bytes of this file, interpreted as a long.
        Throws:
        EOFException - if this file reaches the end before reading eight bytes.
        java.io.IOException - if an I/O error occurs.

      • readFloat

        float readFloat()
                throws java.io.IOException
        Reads a float from this file. This method reads an int value, starting at the current file pointer, as if by the readInt method and then converts that int to a float using the intBitsToFloat method in class Float.

        This method blocks until the four bytes are read, the end of the stream is detected, or an exception is thrown.

        Specified by:
        readFloat in interface java.io.DataInput
        Returns:
        the next four bytes of this file, interpreted as a float.
        Throws:
        EOFException - if this file reaches the end before reading four bytes.
        java.io.IOException - if an I/O error occurs.
        See Also:
        readInt()

      • readDouble

        double readDouble()
                  throws java.io.IOException
        Reads a double from this file. This method reads a long value, starting at the current file pointer, as if by the readLong method and then converts that long to a double using the longBitsToDouble method in class Double.

        This method blocks until the eight bytes are read, the end of the stream is detected, or an exception is thrown.

        Specified by:
        readDouble in interface java.io.DataInput
        Returns:
        the next eight bytes of this file, interpreted as a double.
        Throws:
        EOFException - if this file reaches the end before reading eight bytes.
        java.io.IOException - if an I/O error occurs.
        See Also:
        readLong()

      • readLine

        java.lang.String readLine()
                          throws java.io.IOException
        Reads the next line of text from this file. This method successively reads bytes from the file, starting at the current file pointer, until it reaches a line terminator or the end of the file. Each byte is converted into a character by taking the byte's value for the lower eight bits of the character and setting the high eight bits of the character to zero. This method does not, therefore, support the full Unicode character set.

        A line of text is terminated by a carriage-return character ('\r'), a newline character ('\n'), a carriage-return character immediately followed by a newline character, or the end of the file. Line-terminating characters are discarded and are not included as part of the string returned.

        This method blocks until a newline character is read, a carriage return and the byte following it are read (to see if it is a newline), the end of the file is reached, or an exception is thrown.

        Specified by:
        readLine in interface java.io.DataInput
        Returns:
        the next line of text from this file, or null if end of file is encountered before even one byte is read.
        Throws:
        java.io.IOException - if an I/O error occurs.

      • readUTF

        java.lang.String readUTF()
                         throws java.io.IOException
        Reads in a string from this file. The string has been encoded using a modified UTF-8 format.

        The first two bytes are read, starting from the current file pointer, as if by readUnsignedShort. This value gives the number of following bytes that are in the encoded string, not the length of the resulting string. The following bytes are then interpreted as bytes encoding characters in the UTF-8 format and are converted into characters.

        This method blocks until all the bytes are read, the end of the stream is detected, or an exception is thrown.

        Specified by:
        readUTF in interface java.io.DataInput
        Returns:
        a Unicode string.
        Throws:
        EOFException - if this file reaches the end before reading all the bytes.
        java.io.IOException - if an I/O error occurs.
        UTFDataFormatException - if the bytes do not represent valid UTF-8 encoding of a Unicode string.
        See Also:
        readUnsignedShort()

      • seek

        void seek(long pos)
          throws java.io.IOException
        Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs. The offset may be set beyond the end of the file. Setting the offset beyond the end of the file does not change the file length. The file length will change only by writing after the offset has been set beyond the end of the file.
        Parameters:
        pos - the offset position, measured in bytes from the beginning of the file, at which to set the file pointer.
        Throws:
        java.io.IOException - if pos is less than 0 or if an I/O error occurs.

      • setLength

        void setLength(long newLength)
               throws java.io.IOException
        Sets the length of this file.

        If the present length of the file as returned by the length method is greater than the newLength argument then the file will be truncated. In this case, if the file offset as returned by the getFilePointer method is greater then newLength then after this method returns the offset will be equal to newLength.

        If the present length of the file as returned by the length method is smaller than the newLength argument then the file will be extended. In this case, the contents of the extended portion of the file are not defined.

        Parameters:
        newLength - The desired length of the file
        Throws:
        java.io.IOException - If an I/O error occurs

      • write

        void write(int b)
           throws java.io.IOException
        Writes the specified byte to this file. The write starts at the current file pointer.
        Specified by:
        write in interface java.io.DataOutput
        Parameters:
        b - the byte to be written.
        Throws:
        java.io.IOException - if an I/O error occurs.

      • write

        void write(byte[] b)
           throws java.io.IOException
        Writes b.length bytes from the specified byte array to this file, starting at the current file pointer.
        Specified by:
        write in interface java.io.DataOutput
        Parameters:
        b - the data.
        Throws:
        java.io.IOException - if an I/O error occurs.

      • write

        void write(byte[] b,
         int off,
         int len)
           throws java.io.IOException
        Writes len bytes from the specified byte array starting at offset off to this file.
        Specified by:
        write in interface java.io.DataOutput
        Parameters:
        b - the data.
        off - the start offset in the data.
        len - the number of bytes to write.
        Throws:
        java.io.IOException - if an I/O error occurs.

      • writeBoolean

        void writeBoolean(boolean v)
                  throws java.io.IOException
        Writes a boolean to the file as a one-byte value. The value true is written out as the value (byte)1; the value false is written out as the value (byte)0. The write starts at the current position of the file pointer.
        Specified by:
        writeBoolean in interface java.io.DataOutput
        Parameters:
        v - a boolean value to be written.
        Throws:
        java.io.IOException - if an I/O error occurs.

      • writeByte

        void writeByte(int v)
               throws java.io.IOException
        Writes a byte to the file as a one-byte value. The write starts at the current position of the file pointer.
        Specified by:
        writeByte in interface java.io.DataOutput
        Parameters:
        v - a byte value to be written.
        Throws:
        java.io.IOException - if an I/O error occurs.

      • writeShort

        void writeShort(int v)
                throws java.io.IOException
        Writes a short to the file as two bytes, high byte first. The write starts at the current position of the file pointer.
        Specified by:
        writeShort in interface java.io.DataOutput
        Parameters:
        v - a short to be written.
        Throws:
        java.io.IOException - if an I/O error occurs.

      • writeChar

        void writeChar(int v)
               throws java.io.IOException
        Writes a char to the file as a two-byte value, high byte first. The write starts at the current position of the file pointer.
        Specified by:
        writeChar in interface java.io.DataOutput
        Parameters:
        v - a char value to be written.
        Throws:
        java.io.IOException - if an I/O error occurs.

      • writeInt

        void writeInt(int v)
              throws java.io.IOException
        Writes an int to the file as four bytes, high byte first. The write starts at the current position of the file pointer.
        Specified by:
        writeInt in interface java.io.DataOutput
        Parameters:
        v - an int to be written.
        Throws:
        java.io.IOException - if an I/O error occurs.

      • writeLong

        void writeLong(long v)
               throws java.io.IOException
        Writes a long to the file as eight bytes, high byte first. The write starts at the current position of the file pointer.
        Specified by:
        writeLong in interface java.io.DataOutput
        Parameters:
        v - a long to be written.
        Throws:
        java.io.IOException - if an I/O error occurs.

      • writeFloat

        void writeFloat(float v)
                throws java.io.IOException
        Converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the file as a four-byte quantity, high byte first. The write starts at the current position of the file pointer.
        Specified by:
        writeFloat in interface java.io.DataOutput
        Parameters:
        v - a float value to be written.
        Throws:
        java.io.IOException - if an I/O error occurs.

      • writeDouble

        void writeDouble(double v)
                 throws java.io.IOException
        Converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the file as an eight-byte quantity, high byte first. The write starts at the current position of the file pointer.
        Specified by:
        writeDouble in interface java.io.DataOutput
        Parameters:
        v - a double value to be written.
        Throws:
        java.io.IOException - if an I/O error occurs.

      • writeBytes

        void writeBytes(java.lang.String s)
                throws java.io.IOException
        Writes the string to the file as a sequence of bytes. Each character in the string is written out, in sequence, by discarding its high eight bits. The write starts at the current position of the file pointer.
        Specified by:
        writeBytes in interface java.io.DataOutput
        Parameters:
        s - a string of bytes to be written.
        Throws:
        java.io.IOException - if an I/O error occurs.

      • writeChars

        void writeChars(java.lang.String s)
                throws java.io.IOException
        Writes a string to the file as a sequence of characters. Each character is written to the data output stream as if by the writeChar method. The write starts at the current position of the file pointer.
        Specified by:
        writeChars in interface java.io.DataOutput
        Parameters:
        s - a String value to be written.
        Throws:
        java.io.IOException - if an I/O error occurs.
        See Also:
        writeChar(int)

      • writeUTF

        void writeUTF(java.lang.String str)
              throws java.io.IOException
        Writes a string to the file using UTF-8 encoding in a machine-independent manner.

        First, two bytes are written to the file, starting at the current file pointer, as if by the writeShort method giving the number of bytes to follow. This value is the number of bytes actually written out, not the length of the string. Following the length, each character of the string is output, in sequence, using the UTF-8 encoding for each character.

        Specified by:
        writeUTF in interface java.io.DataOutput
        Parameters:
        str - a string to be written.
        Throws:
        java.io.IOException - if an I/O error occurs.
  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.


JPDA Overview

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java Platform Debugger Architecture

Overview

The Java Platform Debugger Architecture (JPDA) consists of two interfaces (JVM TI and JDI), a protocol (JDWP) and two software components which tie them together (back-end and front-end). JVM TI is a new interface introduced in J2SE 5.0 which replaces JVMDI. The intent is multi-fold:
  • To provide standard interfaces (for the sake of simplicity we will refer to JDWP as an interface) which allow Java programming language debugging tools to be easily written without regard to platform specifics such hardware, operating system and virtual machine implementation.
  • To describe a complete architecture for implementing these interfaces, including remote and cross-platform debugging.
  • To provide a reference implementation of this architecture.
  • To provide a highly modular architecture where the implementation and/or client of an interface can be different than the reference implementation or different from the JPDA component.

Background

See Java Platform Debugger Architecture.

Modularity

Details of the modular structure of JPDA are discussed below. In each case the standard JPDA usage is described. The reference implementation is described and alternative implementations and clients of the interface are discussed.

JVM TI Modularity

The Java Virtual Machine Tool Interface (JVM TI) describes the functionality provided by a virtual machine (VM) in order to allow debugging of Java programming language applications running under this VM. In JPDA, JVM TI is implemented by a VM and the client is the JPDA back-end. In the reference implementation of JPDA, JVM TI is implemented by the Java HotSpot VM and the client is the reference implementation of the back-end, supplied as a native shared library (jdwp.so, jdwp.dll, ...), which is shipped with the JDK.

Many VMs other than the Java HotSpot VM implement JVM TI. The reference implementation of the back-end has been ported to other platforms. And there are JVM TI clients other than the back-end, most notably agents for applications that allow debugging of both native and Java programming language code, and thus need native level control and information. We are aware of no clean-room implementations of the back-end, although this is possible - and a lot of work.

JDWP Modularity

The Java Debug Wire Protocol (JDWP) describes the format of debugging information and requests between a debuggee and a debugger. In JPDA, there is a communication channel between the front-end (in the debugger process) and the back-end (in the debuggee process) - the format of data flowing on this channel is described by JDWP. In the reference implementation of JPDA, the reference implementation of the back-end (above) provides the debuggee side of this channel, and the reference implementation of the front-end (a Java programming language component of the JDK, located in tools.jar) provides the debugger side.

JVM TI is problematic to implement in some VMs. JDWP is implemented directly in such VMs. On the client side, an application written in a language other than the Java programming language may not be an optimal candidate for using JDI. Some have chosen to be clients of JDWP.

JDI Modularity

The Java Debug Interface (JDI) provides a pure Java programming language interface for debugging Java programming language applications. In JPDA, the JDI is a remote view in the debugger process of a virtual machine in the debuggee process. It is implemented by the front-end (above) while a debugger-like application (IDE, debugger, tracer, monitoring tool, ...) is the client.

The JDI could be implemented by a system with a static view of an application. It could be implemented by a system with a mechanism utterly different than JDWP/front-end for collecting information or controlling a VM.

Walk-through

The various ways that the interfaces can be used is discussed above. This section will examine how the standard full JPDA works. The examples go into detail about specific calls and codes. It is not important to understand these -- they are present only to make the examples more concrete.

Across each interface there are two classes of activity: requests and events. Requests originate on the debugger side and include queries for information, setting of state changes in the remote VM/application, and setting of debugging state. Events originate on the debuggee side and denote changes of state in the remote VM/application.

Let's walk through an example. A user clicks on a local variable in a stack view in an IDE, requesting its value. The IDE uses the JDI to get the value, in particular it calls the getValue method, for example:

    theStackFrame.getValue(theLocalVariable)
Where theStackFrame is a com.sun.jdi.StackFrame and theLocalVariable is a com.sun.jdi.LocalVariable.

The front-end then sends this query over a communications channel (let's say a socket) to the back-end running in the debuggee process. It sends it by formatting it into a byte stream in accordance with the JDWP. In particular, it sends a GetValues command (byte value: 1) in the StackFrame command set (byte value: 16), followed by the thread ID, frame ID, etc.

The back-end deciphers the byte-stream and sends the query off to the VM through the JVM TI. In particular, let's say the requested value is an integer, the following JVM TI function call is made:

    error = jvmti->GetLocalInt(frame, slot, &intValue);
The back-end sends back across the socket, a response packet, which will include the value of intValue, and which will be formatted according to JDWP. The front-end deciphers the response packet and returns the value as the value of the getValue method call. The IDE then displays the value.

Requests to change debugging state are processed in a similar manner. For example, a request to set a breakpoint goes through the same steps -- although, of course, the JDI methods called, the JDWP commands sent, and the JVM TI functions called are different. Additionally, the front-end and back-end do more than shove data back and forth, they track and schedule activity and convert, filter, and cache information, so a breakpoint request will be processed quite differently than a get value query - but the communication sequence will be the same.

What happens when the application being debugged finally hits this breakpoint? This is where events come into play. The virtual machine sends an event across the JVM TI interface. In particular, it calls the event handling function passing the breakpoint:

The back-end has set the event handling function to be:

static void Breakpoint(jvmtiEnv *jvmti_env,
                       JNIEnv* jni_env, jthread thread,
                       jmethodID method, jlocation location)
{ ...
This back-end function starts a chain of activity which filters the event to see if it is interesting, queues it, and sends it across the socket in the JDWP format defined for breakpoint events. The front-end decodes and processes the event, eventually generating a JDI event. In particular, the JDI event is exposing it as a com.sun.tools.jdi.event.BreakpointEvent. The IDE then gets the event by removing it from the event queue:
    theEventQueue.remove()
where theEventQueue is a com.sun.jdi.event.EventQueue. The IDE will probably update its displays by making many query calls across the JDI.

Porting

Each virtual machine implementation needs its own JVM TI implementation -- a JVM TI implementation must dig deeply into VM data structures and must set hooks into the VM implementation in order to get events. Adding JVMDT to a VM without JVM TI support is a significant undertaking. Depending on the complexity of the VM and the amount of optional JVM TI implemented, it might be a three to twelve month project. Porting a VM which has JVM TI support to a new platform is primarily the work of porting the non-JVM TI portions of the VM -- JVM TI adds a comparatively small amount of work.

The reference implementation of the back-end can usually be moved to a new platform with little (a few lines) or no change to the source and then recompiled. To use a new VM on the same platform, the binary of the back-end should generally work -- although, it's not Java programming language code so you never know. Note that licensing issues are not covered by this document.

The front-end implementation is written in the Java programming language and will run on any platform or VM. However, the connector code has functionality that may need to be extended for some systems. For example, the reference implementation of the front-end includes a launcher which assumes virtual machines are launched using Java SE conventions. A user of the JDI can configure any launcher syntax he or she wants, but generally a debugger application would prefer to leave this to the JDI implementation. If a different type of communication channel is desired (serial, for example) this too would need to be added using the Service Provider Interface introduced in JDK 5.0.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java(tm) Platform Debugger Architecture - Service provider interfaces

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java™ Platform Debugger Architecture -
Service Provider Interfaces

J2SE 5.0 adds new service provider interfaces to the Java Debug Interface (JDI) so that Connector and TransportService implementations can be developed and deployed. TransportService is a new class in 5.0. It represents the underlying transport service used by a Connector and is used to establish connections and transport Java Debug Wire Protocol (JDWP) packets between a debugger and a target VM.

In addition to new service provider interfaces in JDI, J2SE 5.0 also includes a new transport library interface called the Java™ Debug Wire Protocol Transport Interface (jdwpTransport). This is a native (C/C++) interface to allow the development and deployment of transport libraries. A transport library is loaded by the debuggee-side JDWP agent and is used to establish a connection to the debugger and to transport JDWP packets between the debugger and the VM.

This page describes a number of scenarios where the new interfaces may be used. It also provides an overview of the tasks involved in developing and deploying new Connectors and transport implementations.

  • Example Scenarios
  • Developing a Connector
  • Deploying a Connector
  • Developing a TransportService
  • Deploying a TransportService

Example Scenarios

The service provider interfaces and the native transport interface are expected to be used by the following classes of users:

  • Debugger and tool vendors that need to develop new LaunchingConnector implementations or wish to provide additional transport options for remote debugging over-and-beyond the TCP/IP and shared memory transports provided by Sun.
  • Embedded device, operating system, or virtual machine vendors that require remote debugging using transports that than TCP/IP.

Given the above class of user the following describes a number of scenarios where the new interfaces might be used.

  • In many environments, particularly embedded devices, the debugger may be required to connect to a target VM using a transport other than TCP/IP. In this type of environment the new service provider interfaces can be used to develop and support debugging over an alternative transport.

    On the debuggee-side a transport library for the new transport can be developed by implementing the jdwpTransport interface. For the debugger, a TransportService implementation can be developed. When the TransportService implementation is deployed, the JDI VirtualMachineManager implementation will automatically create an AttachingConnector and a ListeningConnector to allow remote debugging to the target VM.

  • In some environments the debugger may be required to connect to a target VM using a mechanism other than a transport. For example, the debugger may be used to attach, in a read-only manner, to a crash dump or to a hung process.

    For these examples, an AttachingConnector implementation can be developed. The AttachingConnector implementation extends com.sun.jdi.connect.AttachingConnectors and when deployed it will appear on the list of attaching connectors returned by the VirtualMachineManager's attachingConnectors() method.

  • In many environments the target VM will be launched in a very proprietary way. In such environments the Connector arguments or launch mechanism used by the Sun-provided com.sun.jdi.CommandLineLaunch LaunchingConnector may not be sufficient. In such cases the operating system or virtual machine vendor may decide to develop their own LaunchingConnector that is capable of launching the target VM. This new LaunchingConnector would have appropriate Connector arguments which would be used to configure the target VM for debugging. Once deployed it will appear on the list of Connectors returned by the VirtualMachineManager's launchingConnectors() method.
  • Another example arises in enterprise environments where an Integrated Development Environment (IDE) implementer wishes to support debugging over a non-Sun provided transport. For example an IDE may wish to provide the option of debugging over a secure connection using TLS/SSL.

    In this example the IDE implementer develops a transport library using the jdwpTransport interface. This allows the debuggee to use the new transport. On the debugger-side the IDE implementer has a choice. One option is to develop and deploy a TransportService implementation. This option would allow the new transport to be used for remote debugging.

    Alternatively, the IDE implementer may decide to create a Connector implementation that encapsulates the transport. This option is appropriate when the IDE implementer wishes to add new Connector arguments. For example, with a secure transport the IDE implementer may wish to have a Connector that has Connector arguments to specify keystore, pass phrase, or other options needed to configure the secure connection. If a new Connector is appropriate then the IDE implementer develops a transport library for the debuggee-side and a Connector for the debugger-side. The type of Connector is the choice of the implementer - one example is a LaunchingConnector that launches the debuggee and establishes a secure connection between the debugger and debuggee.

Developing a Connector

Developing a Connector involves creating a concrete implementation of a LaunchingConnector, AttachingConnector, or ListeningConnector.

Every Connector implementation must have a public no-arg constructor in addition to implementing all the Connector methods. The constructor will be called by the VirtualMachineManager during initialization. The constructor may be a no-op or it may perform initialization tasks such as loading a transport service. The constructor does not throw any checked exceptions so any problems during initialization should be thrown as Errors or other unchecked exceptions.

Connectors are not required to use a TransportService. Some Connectors may connect to the target VM using a mechanism other than a transport (in the Example Scenarios section we list the examples of AttachingConnectors that attach to crash dumps or hung processes). For Connectors that use a TransportService implementation the Connector can either reference the TransportService implementation directly or it can load the implementation at runtime. Connectors that wish to make use of Sun provided transports should load the transport service using code such as following:

try {
    Class c = Class.forName("com.sun.tools.jdi.SocketTransportService");
    ts = (TransportService)c.newInstance();
} catch (Exception x) {
    throw new Error(x);
}

Java SE implementations are not required to include Sun's socket or shared memory transport service implementations so in the above example an Error will be thrown if the transport service does not exist.

Assuming that the type of Connector is known then the following items should be noted when developing the implementation:

  • The list of Connector.Arguments should be carefully considered. For some Connector implementations the default argument construction and parsing may be the bulk of the code in the implementation.
  • A Connector is required to name the transport that it uses. If an implementation uses an existing TransportService then the recommended transport name is the name of the underlying TransportService. That is, the Connector's transport() implementation returns a Transport for which the name() method returns a java.lang.String representing the name of the transport.
  • Most Connector implementations will establish a Connection to a target VM. Once established the Connector's launch, attach, or accept method will return a VirtualMachine instance to the debugger. To facilitate the creation of a VirtualMachine mirror the VirtualMachineManager has a new method in 5.0 to create a VirtualMachine. The following code fragment shows an example usage of this method:
    VirtualMachine vm = Bootstrap.virtualMachineManager().createVirtualMachine(conn);

    VirtualMachineManager also involves another form of the createVirtualMachine for use by LaunchingConnectors. The other form allows the LaunchingConnector to specify the java.lang.Process that represents the debuggee. See the specification for com.sun.jdi.VirtualMachineManager for further details.

The source code for an example LaunchingConnector can be found here. The Connector has a single Connector.Argument called class which specifies the class name of class to run in the target VM. The example demonstrates all of the above points including Connector.Argument, transport naming, and the use of the createVirtualMachine method.

Deploying a Connector

To deploy a Connector requires packaging the classes for the Connector implementation into a jar file along with a service configuration file that lists the fully-qualified class name of the Connector. The jar file is then deployed in a location that is visible to the system class loader.

The service configuration file that must be included in the jar file is named META-INF/services/com.sun.jdi.connect.Connector. The file simply lists the full-qualified class names of the Connector included in the jar file. Multiple Connector implementations may be included in the same jar file and in that case the class name for each Connector is listed on a separate line.

Suppose we wish to deploy a launching connector named SimpleLaunchingConnector. In order to deploy this we create a file META-INF/services/com.sun.jdi.connect.Connector similar to the following:

# Our very simple launching connector
SimpleLaunchingConnector

This service configuration file is then packaged into a jar file along with the classes that comprise the implementation of the Connector:

jar cf SimpleLaunchingConnector.jar \
    META-INF/services/com.sun.jdi.connect.Connector \
    SimpleLaunchingConnector.class

The jar file is then copied into a location that is visible to the system class loader.

Once deployed the Connector will be located by the debugger when the debugger is restarted. That is, SimpleLaunchingConnector will be included in the list of Connectors returned by VirtualMachineManager's allConnectors() method. In addition, as this is a launching connector, it will also appear on the list of launching connectors returned by the launchingConnectors() method.

Developing a TransportService

Developing a transport service requires developing two components :-

  • A concrete implementation of com.sun.jdi.connect.spi.TransportService.
  • A debuggee-side shared library that implements the jdwpTransport interface.

The development of a transport service requires a high degree of familiarity with the transport and the underlying communication protocol. A transport service essentially binds JDWP to an underlying communication protocol. The service that it provides is reliable and JDWP packets are exchanged between the debugger and debuggee without duplication or data loss. Given that packets must be exchanged in a reliable manner might mean that additional protocol support be included in the transport service over and beyond that provided by the underlying communication protocol. For example, if debugging over a raw and unreliable serial connection is required, then the transport service implementer may be required to build in error detection and recovery in the implementation to ensure that JDWP packets can be reliably transported between the debugger and the debuggee.

Assuming the details of the transport and underlying communication protocol are understood then the next step is to consider the following:

  • The TransportService's capabilities() method returns a TransportService.Capabilities to indicate the transport service's capabilities. The transport service implementer thus needs to consider:
    • Can the transport can support multiple concurrent connections to a single listener address?
    • Can timeouts be feasibly implemented when connecting, handshaking, or waiting for a connection to be established?
  • The native transport library may be used by only one, or multiple JDWP (or other) agents at the same time. If a transport supports multiple environments then each call to the jdwpTransport_OnLoad function will return a new environment pointer. If a transport only supports a single environment then second and subsequent calls to jdwpTransport_OnLoad will return an error. The transport library implementer must therefore decide if the library implementation will support one or multiple environments.
  • Addresses, or connection-endpoints, are represented by Strings. The implementer must therefore design an address scheme so that all the components of an address can be encoded into a String. For example the address and configuration of a serial port might be encoded as something like:
    /dev/ttya;9600,1
  • Design an appropriate ListenKey implementation. As a TransportService may be used to listen on multiple, yet different, addresses at the same time the listen key is used to uniquely identify each "listener".
  • Decide on an appropriate name and description for the TransportService. At start-up the VirtualMachineManager will create an Attaching and Listening Connector to encapsulate the transport service. The name and description of these Connectors will be based on the name and description of the transport service - for example, if the TransportService's name() method returns "Serial" then the Connectors created by the VirtualMachineManager will be named "SerialAttach" and "SerialListen".

Once the above have been resolved then creating a TransportService involves extending com.sun.jdi.connect.spi.TransportService and providing an implementation. The attach and accept methods return an instance of com.sun.jdi.connect.spi.Connection so an implementation of Connection is required so that the debugger can exchange JDWP packets with the debuggee.

As an example of a TransportService implementation the source code for Sun's socket transport can be found here. This is provided for reference purposes only.

To develop a native transport library requires implementing each of the functions listed in the jdwpTransport specification. The function prototypes and definitions are defined in ${java_home}/include/jdwpTransport.h.

The transport library implementer compiles and links the function implementations into a dynamic library (or equivalent). The library exports a function jdwpTransport_OnLoad function which the JDWP agent will call when the transport library is loaded. Some embedded environments don't support dynamic linking and in such environments the transport library may need to be statically linked. In that case there isn't any library loading but the jdwpTransport_OnLoad function will still be called to initialize the transport library and obtain the environment pointer.

As an example of a jdwpTransport implementation the source code for Sun's socket transport library (dt_socket) can be found here. This is provided for references purposes only.

Deploying a TransportService

A TransportService is deployed in a similar manner to a Connector. To deploy a TransportService requires packaging the classes for the TransportService implementation into a jar file along with a service configuration file that lists the fully-qualified class name of the TransportService. The jar file is then deployed in a location that is visible to the system class loader.

The service configuration file that must be included in the jar file is named META-INF/services/com.sun.jdi.connect.spi.TransportService. As per Connector deployment the configuration file may list the classes names of multiple transport service implementations in the event that the jar file includes multiple implementations.

In the case of a transport service com.sun.SerialTransportService then the service configuration file will be similar to the following :-

# Serial line transport
com.foo.SerialTransportService

This service configuration file is then packaged into a jar file along with the classes that comprise the implementation. For this example we will assume that the implementation involves a number of classes :-

jar cf SerialTransportService.jar \
    META-INF/services/com.sun.jdi.connect.spi.TransportService \
    com/foo/SerialTransportService.class \
    com/foo/SerialConnection.class \
    com/foo/SerialCapabilities.clas \
    com/foo/SerialIO.class \
    com/foo/SerialProtocol.class

As per the deployment of Connectors, the jar file is then copied into a location that is visible to the system class loader.

A TransportService may have native methods or rely on other APIs that require a native library. In that case the native library must be location that allows it be loaded using System.loadLibrary.

A native transport library is loaded by the JDWP agent. In must be located on the normal runtime library search path for the operating systems. For example, on Solaris or Linux systems it must be on search path specified by the LD_LIBRARY_PATH environment variable.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


jps - Java Virtual Machine Process Status Tool

  • Synopsis
  • Parameters
  • Description
  • Options
  • Host Identifier
  • Output Format
  • Examples
  • See Also

SYNOPSIS

jps [ options ] [ hostid ]

PARAMETERS

options
Command-line options.
hostid
The host identifier of the host for which the process report should be generated. The hostid may include optional components that indicate the communications protocol, port number, and other implementation specific data.

DESCRIPTION

The jps tool lists the instrumented HotSpot Java Virtual Machines (JVMs) on the target system. The tool is limited to reporting information on JVMs for which it has the access permissions.

If jps is run without specifying a hostid, it will look for instrumented JVMs on the local host. If started with a hostid, it will look for JVMs on the indicated host, using the specified protocol and port. A jstatd process is assumed to be running on the target host.

The jps command will report the local VM identifier, or lvmid, for each instrumented JVM found on the target system. The lvmid is typically, but not necessarily, the operating system's process identifier for the JVM process. With no options, jps will list each Java application's lvmid followed by the short form of the application's class name or jar file name. The short form of the class name or JAR file name omits the class's package information or the JAR files path information.

The jps command uses the java launcher to find the class name and arguments passed to the main method. If the target JVM is started with a custom launcher, the class name (or JAR file name) and the arguments to the main method will not be available. In this case, the jps command will output the string Unknown for the class name or JAR file name and for the arguments to the main method.

The list of JVMs produced by the jps command may be limited by the permissions granted to the principal running the command. The command will only list the JVMs for which the principle has access rights as determined by operating system specific access control mechanisms.

NOTE: This utility is unsupported and may not be available in future versions of the JDK. It is not currently available on Windows 98 and Windows ME platforms.

OPTIONS

The jps command supports a number of options that modify the output of the command. These options are subject to change or removal in the future.

-q
Suppress the output of the class name, JAR file name, and arguments passed to the main method, producing only a list of local VM identifiers.
-m
Output the arguments passed to the main method. The output may be null for embedded JVMs.
-l
Output the full package name for the application's main class or the full path name to the application's JAR file.
-v
Output the arguments passed to the JVM.
-V
Output the arguments passed to the JVM through the flags file (the .hotspotrc file or the file specified by the -XX:Flags=<filename> argument).
-J option
Pass option to the java launcher called by jps. For example, -J-Xms48m sets the startup memory to 48 megabytes. It is a common convention for -J to pass options to the underlying VM executing applications written in Java.

HOST IDENTIFIER

The host identifier, or hostid is a string that indicates the target system. The syntax of the hostid string largely corresponds to the syntax of a URI:

[protocol:][[//]hostname][:port][/servername]
protocol
The communications protocol. If the protocol is omitted and a hostname is not specified, the default protocol is a platform specific, optimized, local protocol. If the protocol is omitted and a hostname is specified, then the default protocol is rmi.
hostname
A hostname or IP address indicating the target host. If hostname is omitted, then the target host is the local host.
port
The default port for communicating with the remote server. If the hostname is omitted or the protocol specifies an optimized, local protocol, then port is ignored. Otherwise, treatment of the port parameter is implementation specific. For the default rmi protocol the port indicates the port number for the rmiregistry on the remote host. If port is omitted, and protocol indicates rmi, then the default rmiregistry port (1099) is used.
servername
The treatment of this parameter depends on the implementation. For the optimized, local protocol, this field is ignored. For the rmi protocol, this parameter is a string representing the name of the RMI remote object on the remote host. See the -n option for the jstatd command.

OUTPUT FORMAT

The output of the jps command follows the following pattern:

lvmid [ [ classname | JARfilename | "Unknown"] [ arg* ] [ jvmarg* ] ]

Where all output tokens are separated by white space. An arg that includes embedded white space will introduce ambiguity when attempting to map arguments to their actual positional parameters.

NOTE: You are advised not to write scripts to parse jps output since the format may change in future releases. If you choose to write scripts that parse jps output, expect to modify them for future releases of this tool.

EXAMPLES

This section provides examples of the jps command.

Listing the instrumented JVMs on the local host:

jps
18027 Java2Demo.JAR
18032 jps
18005 jstat

Listing the instrumented JVMs on a remote host:

This example assumes that the jstat server and either the its internal RMI registry or a separate external rmiregistry process are running on the remote host on the default port (port 1099). It also assumes that the local host has appropriate permissions to access the remote host. This example also includes the -l option to output the long form of the class names or JAR file names.

jps -l remote.domain
3002 /opt/jdk1.7.0/demo/jfc/Java2D/Java2Demo.JAR
2857 sun.tools.jstatd.jstatd

Listing the instrumented JVMs on a remote host with a non-default port for the RMI registry

This example assumes that the jstatd server, with an internal RMI registry bound to port 2002, is running on the remote host. This example also uses the -m option to include the arguments passed to the main method of each of the listed Java applications.

jps -m remote.domain:2002
3002 /opt/jdk1.7.0/demo/jfc/Java2D/Java2Demo.JAR
3102 sun.tools.jstatd.jstatd -p 2002

SEE ALSO

  • java - the Java Application Launcher
  • jstat - the Java virtual machine Statistics Monitoring Tool
  • jstatd - the jstat daemon
  • rmiregistry - the Java Remote Object Registry
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: - JavaTM Print Service Glossary

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

APPENDIX G

Java Print Service Glossary

attribute
a description of: a capability of a print service, a charactaristic of a doc, an instruction for processing a doc or an entire print job, or the state of a print job or printer.
attribute category
the name of the attribute without its range of values. The Java Print Service represents the attribute category with a class, such as the OrientationRequested class. An instance of an attribute class, such as an OrientationRequested object, is an attribute value.
attribute set
an attribute collection that usually is restricted to contain only a certain kind of attribute. The Java Print Service defines a superinterface for all attribute sets called AttributeSet and an interface for each kind of attribute set. The kinds of attribute sets are: doc attribute set, print request attribute set, print job attribute set, and print service attribute set.
attribute value
one of the range of values that an attribute supports. The Java Print Service represents each supported attribute with one of the attribute classes, such as the OrientationRequested class. The class itself is the attribute category. An instance of the class, such as an OrientationRequested object, is the attribute value. The term attribute often refers to the attribute value because the value of an attribute implies the attribute itself.
doc
a piece of print data. the Java Print Service uses the Doc interface to represent a piece of print data.
doc attribute
an attribute that specifies a characteristic of an individual document and the print job settings to be applied to an individual document.
doc attribute set
a collection of attributes that is restricted to only contain doc attributes.
doc flavor
a document type. The Java Print Service uses the DocFlavor class to represent a document type. A DocFlavor object encapsulates a String representing a MIME type, which indicates the format of the document, and a String representing a Java class, such as "java.io.InputStream", that indicates how the document is sent to the printer.
hash attribute set
an attribute set that can contain different kinds of attributes. The Java Print Service represents this attribute set with the HashAttributeSet class, which implements AttributeSet.
print job
a submitted print request, which includes one or more pieces of print data and a set of processing instructions. The Java Print Service represents a print job with the DocPrintJob object, which is obtained from a print service.
print job attribute
an attribute that reports the status of a print job. A client usually does not specify these attributes since these attributes describe the print job after the client has submitted it. To specify settings for a whole print job, the client instead uses the print request attributes.
print job attribute set
a collection of attributes that is restricted to only contain print job attributes.
print request
an unsubmitted print job.
print request attribute
an attribute that specifies a setting applied to a whole print job and to all the documents in the print job.
print request attribute set
a collection of attributes that is restricted to only contain print request attributes.
print service
an interface that represents a particular printer and is a factory for print jobs.
print service attribute
an attribute that describes a printer. An example of such an attribute is one that describes the printer's location.
print service attribute set
a collection of attributes that is restricted to only contain print service attributes.
print-service lookup
the action of attempting to locate a set of print services representing printers that can print a given set of print data according to a given set of processing instructions. A client uses the PrintServiceLookup class to perform this action.
stream print service
a print service that prints data to a client-provided output stream.

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 1 - Introduction

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT
CHAPTER 1

Introduction

The Java™ Print Service (JPS) is a new Java Print API that is designed to support printing on all Java platforms, including platforms requiring a small footprint, but also supports the current Java™ 2 Print API. This unified Java Print API includes extensible print attributes based on the standard attributes specified in the Internet Printing Protocol (IPP) 1.1 from the IETF Specification, RFC 2911. With the attributes, client and server applications can discover and select printers that have the capabilities specified by the attributes. In addition to the included StreamPrintService, which allows applications to transcode print data to different formats, a third party can dynamically install their own print services through the Service Provider Interface.
CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 1 - Introduction

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

History of Printing on the Java Platform

Basic printing support for the Java platform was first introduced in the Java Development Kit, version 1.1 in 1997. The JDK 1.1 printing API provided developers with a basic framework for printing the user-interface content from client applications. JDK 1.1 printing, also called the AWT Printing API, was designed around the java.awt.PrintJob class, which encapsulates a printing request. The PrintJob class creates a subclass of Graphics, which implements the rendering calls to image the page.

In 1998, the JDK 1.2 advanced printing on the Java platform with the java.awt.print package by allowing applications to print all Java 2D graphics, which includes 2D graphics, text, and images.

For the JDK version 1.3, the JobAttributes and PageAttributes classes were introduced to AWT printing so that client applications could specify the properties of a print job and the attributes of a page.

The two APIs primarily support page imaging, which is the rendering and formatting of a page and is one component of a printing subsystem. Although a client can choose a printer from a print dialog and can specify printing attributes using JobAttributes and PageAttributes, neither the AWT nor Java 2D printing APIs support discovery of printers based on their capabilities, which is another key component of any printing subsystem. For more details on the history of printing on the Java platform refer to Printing on the Java Platform.

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 1 - Introduction

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

What the Java Print Service API Offers

The Java Print Service API unifies and extends printing on the Java platform by addressing many of the common printing needs of both client and server applications that are not met by the current Java printing APIs.

In addition to supporting the current Java 2D printing features, the Java Print Service offers many improvements, including:

  • Both client and server applications can discover and select printers based on their capabilities and specify the properties of a print job. Thus, the JPS provides the missing component in a printing subsystem: programmatic printer discovery.
  • Implementations of standard IPP attributes are included in the JPS API as first-class objects.
  • Applications can extend the attributes included with the JPS API.
  • Third parties can plug in their own print services with the Service Provider Interface.

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 1 - Introduction

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

Java Print Service Architecture

The Java Print Service API consists of four packages: javax.print, javax.print.attribute, javax.print.attribute.standard, and javax.print.event.

The javax.print Package

The javax.print package is the main package of the API. It contains classes and interfaces that you use to:
  • Discover Print Services
  • Specify the print data format
  • Create print jobs from a print service
  • Send the print data to a printer or a stream

Discover Print Services

An application invokes the static methods of the abstract class PrintServiceLookup to locate print services that have the capabilities to satisfy the application's print request. For example, to print a double-sided document, the application first needs to find printers that have the double-sided printing capability.

An implementation of the PrintService interface represents an actual printer that might be returned from an implementation of PrintServiceLookup. The PrintService can be queried to determine its capabilities by invoking one of the many methods that return the print service's supported attributes. The Locating Services section of the Printing and Streaming Documents chapter discusses using PrintService and PrintServiceLookup.

The JDK includes PrintServiceLookup implementations that can locate the standard platform printers. To locate other types of printers, such as IPP printers or JINI printers, a print-service provider can write implementations of PrintServiceLookup. The print-service provider can dynamically install these PrintServiceLookup implementations using the SPI JAR file specification.

Rather than sending data to a printer, an application can also print the data to an output stream using a StreamPrintService, which allows the application to convert the data to different formats. To obtain a StreamPrintService, an application uses the lookup methods of the StreamPrintServiceFactory abstract class. This class is similar to that of the PrintServiceLookup class in that it also discovers print services. The chapter Printing and Streaming Documents describes using StreamPrintServiceFactory and StreamPrintService. A StreamPrintService can also be used to send 2D graphics to an output stream. See Printing and Streaming 2D Graphics for more details.

Specify the Print Data Format

The DocFlavor class represents the print data format, such as JPEG or PostScript. A DocFlavor object consists of a MIME type describing the format, and a representation class name, such as java.io.InputStream, that indicates how the document will be delivered to the service. As a convenience, the JPS API also includes pre-defined DocFlavor objects representing common data formats. The Specifying Document Types chapter describes in more detail how to use DocFlavor objects.

Create Print Jobs

When an appropriate print service is found, an application creates a print job from it. The print job is represented by the DocPrintJob class, which provides the actual print method. Before calling print, the application creates a Doc object to encapsulate the print data and the print request attributes, which are defined in the javax.print.attribute and javax.print.attribute.standard packages. The chapter Printing and Streaming Documents discusses using Doc and DocPrintJob. An application that is using the Java Print Service to print 2D Graphics can use either the PrinterJob class or the DocPrintJob class. The chapter Printing and Streaming 2D Graphics discusses using the Java Print Service to print 2D Graphics.

The Attribute Packages

The javax.print.attribute and javax.print.attribute.standard packages define print attributes, which describe a capability of a print service, a charactaristic of a document, an instruction for processing a document or an entire print job, or the state of a print job or printer.

The javax.print.attribute package describes the types of attributes and how they can be collected into sets. The Attribute interface is the superinterface for all attributes. The javax.print.attribute package includes classes and interfaces defining the five different kinds of attributes, each of which describes the capabilities of one piece of the printing process. For example, the PrintRequestAttribute interface defines attributes that clients use to describe the characteristics of a print job, which might include the number of copies to print.

The javax.print.attribute.standard package enumerates all of the standard attributes supported by the API, most of which are implementations of attributes specified in the IPP specification. The Attributes chapter discusses the attribute API in more detail.

The javax.print.event Package

The javax.print.event package contains classes that allow applications to register for events on print jobs and print services. Read the Registering for Events section for more information on registering for print job events.
CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 1 - Introduction

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

How Applications Use the Java Print Service

A typical application using the Java Print Service API performs these steps to process a print request:
  1. Obtain a suitable DocFlavor, which is a class that defines the format of the print data.
  2. Create and populate an AttributeSet, which encapsulates a set of attributes that describe the desired print service capabilities, such as the ability to print five copies, stapled, and double-sided.
  3. Lookup a print service that can handle the print request as specified by the DocFlavor and the attribute set.
  4. Create a print job from the print service.
  5. Call the print job's print method.
The application performs these steps differently depending on what and how it intends to print. The application can either send print data to a printer or to an output stream. The print data can either be a document in the form of text or images, or a Jav a object encapsulating 2D Graphics. If the print data is 2D graphics , the print job can be represented by either a DocPrintJob or a PrinterJob. If the print data is a document then a DocPrintJob must be used.

The combinations of printing methods and print data formats yield a choice of six printing mechanisms:

  • Print a document to a printer by using a DocPrintJob and an implementation of PrintService
  • Stream a document to an output stream by using a DocPrintJob and a StreamPrintService
  • Print 2D graphics to a printer by using a DocPrintJob and an implementation of PrintService
  • Stream 2D graphics to an output stream by using a DocPrintJob and a StreamPrintService
  • Print 2D graphics to a PrintService using java.awt.print.PrinterJob
  • Stream 2D graphics to a StreamPrintService using java.awt.print.PrinterJob
The Attributes chapter and the Specifying Document Types chapter describe how to create an attribute set and specify document types for use with any of the print mechanisms. The Printing and Streaming Documents</ a> chapter discusses printing and streaming documents using DocPrintJob. The Printing and Streaming 2D Graphics chapter explains printing and streaming 2D graphics using both DocPrintJob and PrinterJob.

A Basic Example

Most applications using the Java Print Service API will probably send a document directly to a printer, which the following code sample demonstrates:

// Input the file
FileInputStream textStream;
try {
        textstream = new FileInputStream("file.TXT");
} catch (FileNotFoundException ffne) {
}
if (textstream == null) {
        return;
}
// Set the document type
DocFlavor myFormat = DocFlavor.INPUT_STREAM.TEXT_PLAIN_ASCII;
// Create a Doc
Doc myDoc = new SimpleDoc(texttream, myFormat, null);
// Build a set of attributes
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new Copies(5));
aset.add(MediaSize.ISO_A4);
aset.add(Sides.DUPLEX);
// discover the printers that can print the format according to the
// instructions in the attribute set
PrintService[] services =
        PrintServiceLookup.lookupPrintServices(myFormat, aset);
// Create a print job from one of the print services
if (services.length > 0) {
        DocPrintJob job = services[0].createPrintJob();
        try {
                job.print(myDoc, aset);
        } catch (PrintException pe) {}
}
Although this sample only demonstrates one of the six ways to print, the other printing mechanisms work in a similar way. The rest of this guide discusses each piece of the printing process and all the printing mechanisms in more detail

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: Contents

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

Java™ Print Service API User Guide

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: -

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

1. Introduction

History of Printing on the Java Platform
What the Java Print Service API Offers
Java Print Service Architecture
The javax.print Package
Discover Print Services
Specify the Print Data Format
Create Print Jobs
The javax.print.event Package
How Applications Use the Java Print Service
A Basic Example

2. Attributes

Attribute Categories and Values
Attribute Roles
Attribute Sets
How to Specify Attributes
Standard Attributes
OrientationRequested
Copies
Media
MediaSize
MediaPrintableArea
Destination
SheetCollate
Sides
Fidelity
Uses of JPS Attributes

3. Specifying Document Types

Client-Formatted Print Data
MIME Types for Preformatted Data
Text Data
Page Description Language Documents
Image Data
Autosense Print Data
Representation Classes
Importance of Character Encoding
Service-Formatted Print Data
How to Use DocFlavor

4. Printing and Streaming Documents

StreamPrintService Versus PrintService
Locating Services
Discovering Print Services
Discovering Stream Print Services
Obtaining a Print Job
Creating a Doc
Registering for Events
Print Service Events
Print Job Events
PrintJobAttributeListener
PrintJobListener
Submitting the Print Job
Submitting the Print Job to the Printer
Submitting the Print Job to the Stream
Print Service Providers

5. Printing and Streaming 2D Graphics

Using PrinterJob to Print or Stream Graphics
Printing 2D Graphics
Streaming 2D Graphics
Using Service-Formatted Data
Printing the Service-Formatted Data
Streaming Service-Formatted Print Data

A. Example: PrintPS.java

B. Example: PrintGIFtoStream.java

C. Example: Print2DPrinterJob.java

D. Example: Print2DGraphics.java

E. Example: Print2DtoStream.java

F. Example: PrintGIF.java

G. JavaTM Print Service Glossary

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


jrunscript - command line script shell

  • Synopsis
  • Parameters
  • Description
  • Options
  • Arguments
  • Examples
  • See Also

SYNOPSIS

jrunscript [ options ] [ arguments... ]

PARAMETERS

options
Options, if used, should follow immediately after the command name.
arguments
Arguments, if used, should follow immediately after options or command name.

DESCRIPTION

jrunscript is a command line script shell. jrunscript supports both an interactive (read-eval-print) mode and a batch (-f option) mode of script execution. This is a scripting language independent shell. By default, JavaScript is the language used, but the -l option can be used to specify a different language. Through Java to scripting language communication, jrunscript supports "exploratory programming" style.

NOTE: This tool is experimental and may not be available in future versions of the JDK.

OPTIONS

-classpath path
Specify where to find the user's .class files that are accessed by the script.
-cp path
This is a synonym for -classpath path
-D name=value
Set a Java system property.
-J<flag>
Pass <flag> directly to the Java virtual machine on which jrunscript is run.
-l language
Use the specified scripting language. By default, JavaScript is used. Note that to use other scripting languages, you also need to specify the corresponding script engine's jar file using -cp or -classpath option.
-e script
Evaluate the given script. This option can be used to run "one liner" scripts specified completely on the command line.
-encoding encoding
Specify the character encoding used while reading script files.
-f script-file
Evaluate the given script file (batch mode).
-f -
Read and evaluate a script from standard input (interactive mode).
-help
Output help message and exit.
-?
Output help message and exit.
-q
List all script engines available and exit.

ARGUMENTS

If [arguments...] are present and if no -e or -f option is used, then the first argument is the script file and the rest of the arguments, if any, are passed as script arguments. If [arguments..] and -e or -f option are used, then all [arguments..] are passed as script arguments. If [arguments..], -e and -f are missing, interactive mode is used. Script arguments are available to a script in an engine variable named "arguments" of type String array.

EXAMPLES

Executing inline scripts

jrunscript -e "print('hello world')"
jrunscript -e "cat('http://java.sun.com')"

Use specified language and evaluate given script file

jrunscript -l js -f test.js

Interactive mode

jrunscript
js> print('Hello World\n');
Hello World
js> 34 + 55
89.0
js> t = new java.lang.Thread(function() { print('Hello World\n'); })
Thread[Thread-0,5,main]
js> t.start()
js> Hello World

js>

Run script file with script arguments

jrunscript test.js arg1 arg2 arg3
test.js is script file to execute and arg1, arg2 and arg3 are passed to script as script arguments. Script can access these using "arguments" array.

SEE ALSO

If JavaScript is used, then before evaluating any user defined script, jrunscript initializes certain built-in functions and objects. These JavaScript built-ins are documented in jsdocs.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JavaScript to Java

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

< Contents

JavaScript to Java Communication (Scripting)

This section includes the following topics:

  • How to Script Applets
  • Using Scripts to Invoke a Method

How to Script Applets

This chapter requires understanding the specific HTML tags required for Java Plug-in. For information about these tags, refer to Using OBJECT, EMBED, and APPLET Tags in Java Plug-in. You also should be familiar with JavaScript.

With scripting you have the capability to call applet methods from within an HTML page. In addition to invoking methods, you can use scripts to:

  • Get and set properties in applets
  • Run Java objects that have been built for scripting

Using Scripts to Invoke a Method

You often want to use scripts to invoke methods on an applet. For example, you might have an HTML button that, when clicked, starts an animation sequence. You do this through a combination of HTML tags and scripting in the HTML file, plus the actual code in the applet itself.

You need to include the following in your applet's HTML page:

  • Within the OBJECT tag, an ID parameter that specifies the name of the applet
  • Tags specifying a scripting language and scripting method associated with a particular action
  • A SCRIPT tag for the scripting method that the action will invoke

These tags are explained in the following sections.

Specify the Applet

You must designate an ID parameter within the OBJECT tag for your HTML page. Recall that the OBJECT tag includes such parameters as classid, width, height, and so on.

The ID parameter is the symbolic name of the applet. Once you establish a symbolic name for an applet through the ID parameter, you can reuse this name later in the scripts to refer to this applet.

For example, suppose you have an applet called Fractal. You add the ID parameter to the OBJECT tag and set ID to the symbolic name of the applet. You might set the tag as follows:

ID="Fractal"

Now, you can use the name Fractal within scripts to refer to the Fractal applet.

Using the same Fractal applet example, your HTML page would begin with a FORM tag, followed by an OBJECT tag, that together might look as follows:

<form name="Form1">
<OBJECT ID="Fractal" WIDTH=500 HEIGHT=120
CLASSID="CLSID:8AD9C840-044E-11d1-B3E9-00805F499D93"
<PARAM NAME="code" value="CLSFractal.class">
<PARAM NAME="codebase" value="1.0.2">
<PARAM NAME="level" value="5">
...
</OBJECT>

Associate the Action to the Script

The HTML page defines components that are intended to invoke actions triggered by the user. You use the INPUT tag to define these components. You specify the TYPE of the component, such as button, its NAME, and VALUE. To have the button or other component actually invoke the intended action, you need to add tags that specify:

  • What the user does to trigger the action, such as onClick for when the user clicks on the button
  • The name of the script method that the HTML page will invoke when the specified trigger action occurs
  • The language in which the script method is written

For example, suppose your HTML page creates a button that, when clicked, starts a particular animation sequence. Your HTML tag creates the button and gives that button a name and a value (label).

To do this you want to add two tags. One tag indicates that on a certain action, such as onclick, a corresponding script method should be called. You might have the tag onClick="method name". The method name is a script method within the same HTML page.

Thus, you might have the following in your HTML page:

<input type="button" name="Button1" value="Start"
onClick="startJSFractal" language="JavaScript">

This INPUT tag creates a button, names the button "Button1", and gives it the value "Start" (the label that appears on the button). It also specifies the scripting method that will be called when a user clicks the button, and the scripting method's language. In this example, the scripting method is startJSFractal, and the scripting language is JavaScript. When the user clicks this button, the HTML page branches to the script method startJSFractal, which is written in JavaScriptscript.

The Script Tag and Method

You must include a SCRIPT tag for the method (function) that the onClick tag specifies. The SCRIPT tag must have the same name as the name used in the onClick tag. It also has a parameter that specifies the script language. More importantly, the script method calls the Java applet method. It identifies the method by using the name of the applet as specified by the ID tag, followed by the actual method name as implemented in the applet code.

For example, the same HTML page might have the following SCRIPT tag:

<SCRIPT language="JavaScript">
function startJSFractal() {
        document.Form1.Fractal.startFractal()
}
</SCRIPT>

In this example, the SCRIPT tag begins by specifying that the scripting language is JavaScript. This is followed by the JavaScript function statement, which starts the definition of a scripting method. The function statement supplies a label or name for the scripting method, calling it startJSFractal. This name must match the method name given for the input component's action parameter.

For this example, both the onClick parameter and the function statement specify the identical scripting method. The scripting method startJSFractal merely calls the actual method, startFractal(), implemented in the applet code. It qualifies the method name by using the document form name , then the applet name (OBJECT ID), then the method name itself, as follows:

document.Form1.Fractal.startFractal()

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


jsadebugd - Serviceability Agent Debug Daemon

  • Synopsis
  • Parameters
  • Description
  • See Also

SYNOPSIS

jsadebugd pid [ server-id ]
jsadebugd executable core [ server-id ]

PARAMETERS

pid
process id of the process to which the debug server should attach. The process must be a Java process. To get a list of Java processes running on a machine, jps may be used. At most one instance of the debug server may be attached to a single process.
executable
Java executable from which the core dump was produced
core
Core file to which the debug server should attach.
server-id
Optional unique id, needed if multiple debug servers are started on the same machine. This ID must be used by remote clients to identify the particular debug server to attach. Within a single machine, this ID must be unique.

DESCRIPTION

jsadebugd attaches to a Java process or core file and acts as a debug server. Remote clients such as jstack, jmap, and jinfo can attach to the server using Java Remote Method Invocation (RMI). Before starting jsadebugd, rmiregistry must be started with:

rmiregistry -J-Xbootclasspath/p:$JAVA_HOME/lib/sajdi.jar

where $JAVA_HOME is the JDK installation directory. If rmiregistry was not started, jsadebugd will start an rmiregistry in a standard (1099) port internally. Debug server may be stopped by sending SIGINT (pressing Ctrl-C) to it.

NOTE - This utility is unsupported and may or may not be available in future versions of the JDK. In Windows Systems where dbgeng.dll is not present, 'Debugging Tools For Windows' needs to be installed to have these tools working. Also, PATH environment variable should contain the location of jvm.dll used by the target process or the location from which the Crash Dump file was produced.

For example, set PATH=<jdk>\jre\bin\client;%PATH%

SEE ALSO

  • jinfo
  • jmap
  • jps
  • jstack
  • rmiregistry
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JSInvoker

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Overview File Class Tree Index Help
PREV CLASS NEXT CLASS
SUMMARY: FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

Class JSInvoker

Object
   |
   +--JSInvoker
class JSInvoker

Defined in init.js

Constructor Summary
JSInvoker (obj)
Creates an object that delegates all method calls on it to the 'invoke' method on the given delegate object.

Constructor Detail

JSInvoker

JSInvoker(obj)
    Creates an object that delegates all method calls on it to the 'invoke' method on the given delegate object.
    Example:

     var x  = { invoke: function(name, args) { //code...}
     var y = new JSInvoker(x);
     y.func(3, 3); // calls x.invoke('func', args); where args is array of arguments
    Parameters:
      obj - object to be wrapped by JSInvoker
Overview File Class Tree Index Help
PREV CLASS NEXT CLASS
SUMMARY: FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Overview of Java SE Security

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java™ Security Overview

1 Introduction

The Java™ platform was designed with a strong emphasis on security. At its core, the Java language itself is type-safe and provides automatic garbage collection, enhancing the robustness of application code. A secure class loading and verification mechanism ensures that only legitimate Java code is executed.

The initial version of the Java platform created a safe environment for running potentially untrusted code, such as Java applets downloaded from a public network. As the platform has grown and widened its range of deployment, the Java security architecture has correspondingly evolved to support an increasing set of services. Today the architecture includes a large set of application programming interfaces (APIs), tools, and implementations of commonly-used security algorithms, mechanisms, and protocols. This provides the developer a comprehensive security framework for writing applications, and also provides the user or administrator a set of tools to securely manage applications.

The Java security APIs span a wide range of areas. Cryptographic and public key infrastructure (PKI) interfaces provide the underlying basis for developing secure applications. Interfaces for performing authentication and access control enable applications to guard against unauthorized access to protected resources.

The APIs allow for multiple interoperable implementations of algorithms and other security services. Services are implemented in providers, which are plugged into the Java platform via a standard interface that makes it easy for applications to obtain security services without having to know anything about their implementations. This allows developers to focus on how to integrate security into their applications, rather than on how to actually implement complex security mechanisms.

The Java platform includes a number of providers that implement a core set of security services. It also allows for additional custom providers to be installed. This enables developers to extend the platform with new security mechanisms.

This paper gives a broad overview of security in the Java platform, from secure language features to the security APIs, tools, and built-in provider services, highlighting key packages and classes where applicable. Note that this paper is based on Java™ SE version 6.

2 Java Language Security and Bytecode Verification

The Java language is designed to be type-safe and easy to use. It provides automatic memory management, garbage collection, and range-checking on arrays. This reduces the overall programming burden placed on developers, leading to fewer subtle programming errors and to safer, more robust code.

In addition, the Java language defines different access modifiers that can be assigned to Java classes, methods, and fields, enabling developers to restrict access to their class implementations as appropriate. Specifically, the language defines four distinct access levels: private, protected, public, and, if unspecified, package. The most open access specifier is public access is allowed to anyone. The most restrictive modifier is private access is not allowed outside the particular class in which the private member (a method, for example) is defined. The protected modifier allows access to any subclass, or to other classes within the same package. Package-level access only allows access to classes within the same package.

A compiler translates Java programs into a machine-independent bytecode representation. A bytecode verifier is invoked to ensure that only legitimate bytecodes are executed in the Java runtime. It checks that the bytecodes conform to the Java Language Specification and do not violate Java language rules or namespace restrictions. The verifier also checks for memory management violations, stack underflows or overflows, and illegal data typecasts. Once bytecodes have been verified, the Java runtime prepares them for execution.

3 Basic Security Architecture

The Java platform defines a set of APIs spanning major security areas, including cryptography, public key infrastructure, authentication, secure communication, and access control. These APIs allow developers to easily integrate security into their application code. They were designed around the following principles:

  1. Implementation independence Applications do not need to implement security themselves. Rather, they can request security services from the Java platform. Security services are implemented in providers (see below), which are plugged into the Java platform via a standard interface. An application may rely on multiple independent providers for security functionality.
  2. Implementation interoperability Providers are interoperable across applications. Specifically, an application is not bound to a specific provider, and a provider is not bound to a specific application.
  3. Algorithm extensibility The Java platform includes a number of built-in providers that implement a basic set of security services that are widely used today. However, some applications may rely on emerging standards not yet implemented, or on proprietary services. The Java platform supports the installation of custom providers that implement such services.

Security Providers

The java.security.Provider class encapsulates the notion of a security provider in the Java platform. It specifies the provider's name and lists the security services it implements. Multiple providers may be configured at the same time, and are listed in order of preference. When a security service is requested, the highest priority provider that implements that service is selected.

Applications rely on the relevant getInstance method to obtain a security service from an underlying provider. For example, message digest creation represents one type of service available from providers. (Section 4 discusses message digests and other cryptographic services.) An application invokes the getInstance method in the java.security.MessageDigest class to obtain an implementation of a specific message digest algorithm, such as MD5.

MessageDigest md = MessageDigest.getInstance("MD5");

The program may optionally request an implementation from a specific provider, by indicating the provider name, as in the following:

MessageDigest md =
    MessageDigest.getInstance("MD5", "ProviderC");

Figures 1 and 2 illustrate these options for requesting an MD5 message digest implementation. Both figures show three providers that implement message digest algorithms. The providers are ordered by preference from left to right (1-3). In Figure 1, an application requests an MD5 algorithm implementation without specifying a provider name. The providers are searched in preference order and the implementation from the first provider supplying that particular algorithm, ProviderB, is returned. In Figure 2, the application requests the MD5 algorithm implementation from a specific provider, ProviderC. This time the implementation from that provider is returned, even though a provider with a higher preference order, ProviderB, also supplies an MD5 implementation.

diagram showing an application requesting an MD5 algorithem without specifying a provider name | diagram showing an application requesting an MD5 algorithem from a specific provider
Figure 1 Provider searching | Figure 2 Specific provider requested

The Java platform implementation from Sun Microsystems includes a number of pre-configured default providers that implement a basic set of security services that can be used by applications. Note that other vendor implementations of the Java platform may include different sets of providers that encapsulate vendor-specific sets of security services. When this paper mentions built-in default providers, it is referencing those available in Sun's implementation.

The sections below on the various security areas (cryptography, authentication, etc.) each include descriptions of the relevant services supplied by the default providers. A table in Appendix C summarizes all of the default providers.

File Locations

Certain aspects of Java security mentioned in this paper, including the configuration of providers, may be customized by setting security properties. You may set security properties statically in the security properties file, which by default is the java.security file in the lib/security directory of the directory where the Java™ Runtime Environment (JRE) is installed. Security properties may also be set dynamically by calling appropriate methods of the Security class (in the java.security package).

The tools and commands mentioned in this paper are all in the ~jre/bin directory, where ~jre stands for the directory in which the JRE is installed. The cacerts file mentioned in Section 5 is in ~jre/lib/security.

4 Cryptography

The Java cryptography architecture is a framework for accessing and developing cryptographic functionality for the Java platform. It includes APIs for a large variety of cryptographic services, including

  • Message digest algorithms
  • Digital signature algorithms
  • Symmetric bulk encryption
  • Symmetric stream encryption
  • Asymmetric encryption
  • Password-based encryption (PBE)
  • Elliptic Curve Cryptography (ECC)
  • Key agreement algorithms
  • Key generators
  • Message Authentication Codes (MACs)
  • (Pseudo-)random number generators

For historical (export control) reasons, the cryptography APIs are organized into two distinct packages. The java.security package contains classes that are not subject to export controls (like Signature and MessageDigest). The javax.crypto package contains classes that are subject to export controls (like Cipher and KeyAgreement).

The cryptographic interfaces are provider-based, allowing for multiple and interoperable cryptography implementations. Some providers may perform cryptographic operations in software; others may perform the operations on a hardware token (for example, on a smartcard device or on a hardware cryptographic accelerator). Providers that implement export-controlled services must be digitally signed.

The Java platform includes built-in providers for many of the most commonly used cryptographic algorithms, including the RSA and DSA signature algorithms, the DES, AES, and ARCFOUR encryption algorithms, the MD5 and SHA-1 message digest algorithms, and the Diffie-Hellman key agreement algorithm. These default providers implement cryptographic algorithms in Java code.

The Java platform also includes a built-in provider that acts as a bridge to a native PKCS#11 (v2.x) token. This provider, named SunPKCS11, allows Java applications to seamlessly access cryptographic services located on PKCS#11-compliant tokens.

5 Public Key Infrastructure

Public Key Infrastructure (PKI) is a term used for a framework that enables secure exchange of information based on public key cryptography. It allows identities (of people, organizations, etc.) to be bound to digital certificates and provides a means of verifying the authenticity of certificates. PKI encompasses keys, certificates, public key encryption, and trusted Certification Authorities (CAs) who generate and digitally sign certificates.

The Java platform includes API and provider support for X.509 digital certificates and certificate revocation lists (CRLs), as well as PKIX-compliant certification path building and validation. The classes related to PKI are located in the java.security and java.security.cert packages.

Key and Certificate Storage

The Java platform provides for long-term persistent storage of cryptographic keys and certificates via key and certificate stores. Specifically, the java.security.KeyStore class represents a key store, a secure repository of cryptographic keys and/or trusted certificates (to be used, for example, during certification path validation), and the java.security.cert.CertStore class represents a certificate store, a public and potentially vast repository of unrelated and typically untrusted certificates. A CertStore may also store CRLs.

KeyStore and CertStore implementations are distinguished by types. The Java platform includes the standard PKCS11 and PKCS12 key store types (whose implementations are compliant with the corresponding PKCS specifications from RSA Security), as well as a proprietary file-based key store type called JKS (which stands for "Java Key Store").

The Java platform includes a special built-in JKS key store, cacerts, that contains a number of certificates for well-known, trusted CAs. The keytool documentation (see the security features documentation link in Section 9) lists the certificates included in cacerts.

The SunPKCS11 provider mentioned in the "Cryptography" section (Section 4) includes a PKCS11 KeyStore implementation. This means that keys and certificates residing in secure hardware (such as a smartcard) can be accessed and used by Java applications via the KeyStore API. Note that smartcard keys may not be permitted to leave the device. In such cases, the java.security.Key object reference returned by the KeyStore API may simply be a reference to the key (that is, it would not contain the actual key material). Such a Key object can only be used to perform cryptographic operations on the device where the actual key resides.

The Java platform also includes an LDAP certificate store type (for accessing certificates stored in an LDAP directory), as well as an in-memory Collection certificate store type (for accessing certificates managed in a java.util.Collection object).

PKI Tools

There are two built-in tools for working with keys, certificates, and key stores:

keytool is used to create and manage key stores. It can

  • Create public/private key pairs
  • Display, import, and export X.509 v1, v2, and v3 certificates stored as files
  • Create self-signed certificates
  • Issue certificate (PKCS#10) requests to be sent to CAs
  • Import certificate replies (obtained from the CAs sent certificate requests)
  • Designate public key certificates as trusted

The jarsigner tool is used to sign JAR files, or to verify signatures on signed JAR files. The Java ARchive (JAR) file format enables the bundling of multiple files into a single file. Typically a JAR file contains the class files and auxiliary resources associated with applets and applications. When you want to digitally sign code, you first use keytool to generate or import appropriate keys and certificates into your key store (if they are not there already), then use the jar tool to place the code in a JAR file, and finally use the jarsigner tool to sign the JAR file. The jarsigner tool accesses a key store to find any keys and certificates needed to sign a JAR file or to verify the signature of a signed JAR file. Note: jarsigner can optionally generate signatures that include a timestamp. Systems (such as Java Plug-in) that verify JAR file signatures can check the timestamp and accept a JAR file that was signed while the signing certificate was valid rather than requiring the certificate to be current. (Certificates typically expire annually, and it is not reasonable to expect JAR file creators to re-sign deployed JAR files annually.)

6 Authentication

Authentication is the process of determining the identity of a user. In the context of the Java runtime environment, it is the process of identifying the user of an executing Java program. In certain cases, this process may rely on the services described in the "Cryptography" section (Section 4).

The Java platform provides APIs that enable an application to perform user authentication via pluggable login modules. Applications call into the LoginContext class (in the javax.security.auth.login package), which in turn references a configuration. The configuration specifies which login module (an implementation of the javax.security.auth.spi.LoginModule interface) is to be used to perform the actual authentication.

Since applications solely talk to the standard LoginContext API, they can remain independent from the underlying plug-in modules. New or updated modules can be plugged in for an application without having to modify the application itself. Figure 3 illustrates the independence between applications and underlying login modules:

diagram illustrating the independence between applications and login modules

Figure 3 Authentication login modules plugging into the authentication framework

It is important to note that although login modules are pluggable components that can be configured into the Java platform, they are not plugged in via security Providers. Therefore, they do not follow the Provider searching model described in Section 3. Instead, as is shown in the above diagram, login modules are administered by their own unique configuration.

The Java platform provides the following built-in LoginModules, all in the com.sun.security.auth.module package:

  • Krb5LoginModule for authentication using Kerberos protocols
  • JndiLoginModule for username/password authentication using LDAP or NIS databases
  • KeyStoreLoginModule for logging into any type of key store, including a PKCS#11 token key store

Authentication can also be achieved during the process of establishing a secure communication channel between two peers. The Java platform provides implementations of a number of standard communication protocols, which are discussed in the following section.

7 Secure Communication

The data that travels across a network can be accessed by someone who is not the intended recipient. When the data includes private information, such as passwords and credit card numbers, steps must be taken to make the data unintelligible to unauthorized parties. It is also important to ensure that you are sending the data to the appropriate party, and that the data has not been modified, either intentionally or unintentionally, during transport.

Cryptography forms the basis required for secure communication, and that is described in Section 4. The Java platform also provides API support and provider implementations for a number of standard secure communication protocols.

SSL/TLS

The Java platform provides APIs and an implementation of the SSL and TLS protocols that includes functionality for data encryption, message integrity, server authentication, and optional client authentication. Applications can use SSL/TLS to provide for the secure passage of data between two peers over any application protocol, such as HTTP on top of TCP/IP.

The javax.net.ssl.SSLSocket class represents a network socket that encapsulates SSL/TLS support on top of a normal stream socket (java.net.Socket). Some applications might want to use alternate data transport abstractions (e.g., New-I/O); the javax.net.ssl.SSLEngine class is available to produce and consume SSL/TLS packets.

The Java platform also includes APIs that support the notion of pluggable (provider-based) key managers and trust managers. A key manager is encapsulated by the javax.net.ssl.KeyManager class, and manages the keys used to perform authentication. A trust manager is encapsulated by the TrustManager class (in the same package), and makes decisions about who to trust based on certificates in the key store it manages.

SASL

Simple Authentication and Security Layer (SASL) is an Internet standard that specifies a protocol for authentication and optional establishment of a security layer between client and server applications. SASL defines how authentication data is to be exchanged, but does not itself specify the contents of that data. It is a framework into which specific authentication mechanisms that specify the contents and semantics of the authentication data can fit. There are a number of standard SASL mechanisms defined by the Internet community for various security levels and deployment scenarios.

The Java SASL API defines classes and interfaces for applications that use SASL mechanisms. It is defined to be mechanism-neutral; an application that uses the API need not be hardwired into using any particular SASL mechanism. Applications can select the mechanism to use based on desired security features. The API supports both client and server applications. The javax.security.sasl.Sasl class is used to create SaslClient and SaslServer objects.

SASL mechanism implementations are supplied in provider packages. Each provider may support one or more SASL mechanisms and is registered and invoked via the standard provider architecture.

The Java platform includes a built-in provider that implements the following SASL mechanisms:

  • CRAM-MD5, DIGEST-MD5, EXTERNAL, GSSAPI, and PLAIN client mechanisms
  • CRAM-MD5, DIGEST-MD5, and GSSAPI server mechanisms

GSS-API and Kerberos

The Java platform contains an API with the Java language bindings for the Generic Security Service Application Programming Interface (GSS-API). GSS-API offers application programmers uniform access to security services atop a variety of underlying security mechanisms. The Java GSS-API currently requires use of a Kerberos v5 mechanism, and the Java platform includes a built-in implementation of this mechanism. At this time, it is not possible to plug in additional mechanisms. Note: The Krb5LoginModule mentioned in Section 6 can be used in conjunction with the GSS Kerberos mechanism.

Before two applications can use the Java GSS-API to securely exchange messages between them, they must establish a joint security context. The context encapsulates shared state information that might include, for example, cryptographic keys. Both applications create and use an org.ietf.jgss.GSSContext object to establish and maintain the shared information that makes up the security context. Once a security context has been established, it can be used to prepare secure messages for exchange.

The Java GSS APIs are in the org.ietf.jgss package. The Java platform also defines basic Kerberos classes, like KerberosPrincipal and KerberosTicket, which are located in the javax.security.auth.kerberos package.

8 Access Control

The access control architecture in the Java platform protects access to sensitive resources (for example, local files) or sensitive application code (for example, methods in a class). All access control decisions are mediated by a security manager, represented by the java.lang.SecurityManager class. A SecurityManager must be installed into the Java runtime in order to activate the access control checks.

Java applets and Java™ Web Start applications are automatically run with a SecurityManager installed. However, local applications executed via the java command are by default not run with a SecurityManager installed. In order to run local applications with a SecurityManager, either the application itself must programmatically set one via the setSecurityManager method (in the java.lang.System class), or java must be invoked with a -Djava.security.manager argument on the commandline.

Permissions

When Java code is loaded by a class loader into the Java runtime, the class loader automatically associates the following information with that code:

  • Where the code was loaded from
  • Who signed the code (if anyone)
  • Default permissions granted to the code

This information is associated with the code regardless of whether the code is downloaded over an untrusted network (e.g., an applet) or loaded from the filesystem (e.g., a local application). The location from which the code was loaded is represented by a URL, the code signer is represented by the signer's certificate chain, and default permissions are represented by java.security.Permission objects.

The default permissions automatically granted to downloaded code include the ability to make network connections back to the host from which it originated. The default permissions automatically granted to code loaded from the local filesystem include the ability to read files from the directory it came from, and also from subdirectories of that directory.

Note that the identity of the user executing the code is not available at class loading time. It is the responsibility of application code to authenticate the end user if necessary (for example, as described in Section 6). Once the user has been authenticated, the application can dynamically associate that user with executing code by invoking the doAs method in the javax.security.auth.Subject class.

Policy

As mentioned earlier, a limited set of default permissions are granted to code by class loaders. Administrators have the ability to flexibly manage additional code permissions via a security policy.

The Java platform encapsulates the notion of a security policy in the java.security.Policy class. There is only one Policy object installed into the Java runtime at any given time. The basic responsibility of the Policy object is to determine whether access to a protected resource is permitted to code (characterized by where it was loaded from, who signed it, and who is executing it). How a Policy object makes this determination is implementation-dependent. For example, it may consult a database containing authorization data, or it may contact another service.

The Java platform includes a default Policy implementation that reads its authorization data from one or more ASCII (UTF-8) files configured in the security properties file. These policy files contain the exact sets of permissions granted to code: specifically, the exact sets of permissions granted to code loaded from particular locations, signed by particular entities, and executing as particular users. The policy entries in each file must conform to a documented proprietary syntax, and may be composed via a simple text editor or the graphical policytool utility.

Access Control Enforcement

The Java runtime keeps track of the sequence of Java calls that are made as a program executes. When access to a protected resource is requested, the entire call stack, by default, is evaluated to determine whether the requested access is permitted.

As mentioned earlier, resources are protected by the SecurityManager. Security-sensitive code in the Java platform and in applications protects access to resources via code like the following:

SecurityManager sm = System.getSecurityManager();
if (sm != null) {
   sm.checkPermission(perm);
}

where perm is the Permission object that corresponds to the requested access. For example, if an attempt is made to read the file /tmp/abc, the permission may be constructed as follows:

Permission perm =
    new java.io.FilePermission("/tmp/abc", "read");

The default implementation of SecurityManager delegates its decision to the java.security.AccessController implementation. The AccessController traverses the call stack, passing to the installed security Policy each code element in the stack, along with the requested permission (for example, the FilePermission in the above example). The Policy determines whether the requested access is granted, based on the permissions configured by the administrator. If access is not granted, the AccessController throws a java.lang.SecurityException.

Figure 4 illustrates access control enforcement. In this particular example, there are initially two elements on the call stack, ClassA and ClassB. ClassA invokes a method in ClassB, which then attempts to access the file /tmp/abc by creating an instance of java.io.FileInputStream. The FileInputStream constructor creates a FilePermission, perm, as shown above, and then passes perm to the SecurityManager's checkPermission method. In this particular case, only the permissions for ClassA and ClassB need to be checked, because all system code, including FileInputStream, SecurityManager, and AccessController, automatically receives all permissions.

In this example, ClassA and ClassB have different code characteristics – they come from different locations and have different signers. Each may have been granted a different set of permissions. The AccessController only grants access to the requested file if the Policy indicates that both classes have been granted the required FilePermission.

diagram showing how access is controlled to resources

Figure 4 Controlling access to resources

9 For More Information

Detailed documentation for all the Java SE 6 security features mentioned in this paper can be found at

http://java.sun.com/javase/6/docs/technotes/guides/security/index.html

Additional Java security documentation can be found online at

http://java.sun.com/security/

and in the book Inside Java 2 Platform Security, Second Edition (Addison-Wesley). See

http://java.sun.com/docs/books/security/index.html

Note: Historically, as new types of security services were added to the Java platform (sometimes initially as extensions), various acronymns were used to refer to them. Since these acronyms are still in use in the Java security documentation, here is an explanation of what they represent: JSSE (Java™ Secure Socket Extension) refers to the SSL-related services described in Section 7, JCE (Java™ Cryptography Extension) refers to cryptographic services (Section 4), and JAAS (Java™ Authentication and Authorization Service) refers to the authentication and user-based access control services described in Sections 6 and 8, respectively.

Appendix A Classes Summary

Table 1 summarizes the names, packages, and usage of the Java security classes and interfaces mentioned in this paper.

Table 1 Key Java security packages and classes

Package | Class/Interface Name | Usage
com.sun.security.auth.module | JndiLoginModule | Performs username/password authentication using LDAP or NIS
com.sun.security.auth.module | KeyStoreLoginModule | Performs authentication based on key store login
com.sun.security.auth.module | Krb5LoginModule | Performs authentication using Kerberos protocols
java.lang | SecurityException | Indicates a security violation
java.lang | SecurityManager | Mediates all access control decisions
java.lang | System | Installs the SecurityManager
java.security | AccessController | Called by default implementation of SecurityManager to make access control decisions
java.security | Key | Represents a cryptographic key
java.security | KeyStore | Represents a repository of keys and trusted certificates
java.security | MessageDigest | Represents a message digest
java.security | Permission | Represents access to a particular resource
java.security | Policy | Encapsulates the security policy
java.security | Provider | Encapsulates security service implementations
java.security | Security | Manages security providers and security properties
java.security | Signature | Creates and verifies digital signatures
java.security.cert | Certificate | Represents a public key certificate
java.security.cert | CertStore | Represents a repository of unrelated and typically untrusted certificates
javax.crypto | Cipher | Performs encryption and decryption
javax.crypto | KeyAgreement | Performs a key exchange
javax.net.ssl | KeyManager | Manages keys used to perform SSL/TLS authentication
javax.net.ssl | SSLEngine | Produces/consumes SSL/TLS packets, allowing the application freedom to choose a transport mechanism
javax.net.ssl | SSLSocket | Represents a network socket that encapsulates SSL/TLS support on top of a normal stream socket
javax.net.ssl | TrustManager | Makes decisions about who to trust in SSL/TLS interactions (for example, based on trusted certificates in key stores)
javax.security.auth | Subject | Represents a user
javax.security.auth.kerberos | KerberosPrincipal | Represents a Kerberos principal
javax.security.auth.kerberos | KerberosTicket | Represents a Kerberos ticket
javax.security.auth.login | LoginContext | Supports pluggable authentication
javax.security.auth.spi | LoginModule | Implements a specific authentication mechanism
javax.security.sasl | Sasl | Creates SaslClient and SaslServer objects
javax.security.sasl | SaslClient | Performs SASL authentication as a client
javax.security.sasl | SaslServer | Performs SASL authentication as a server
org.ietf.jgss | GSSContext | Encapsulates a GSS-API security context and provides the security services available via the context

Appendix B Tools Summary

Table 2 summarizes the tools mentioned in this paper.

Table 2 Java security tools

Tool | Usage
jar | Creates Java Archive (JAR) files
jarsigner | Signs and verifies signatures on JAR files
keytool | Creates and manages key stores
policytool | Creates and edits policy files for use with default Policy implementation

There are also three Kerberos-related tools that are shipped with the Java platform for Windows. Equivalent functionality is provided in tools of the same name that are automatically part of the Solaris and Linux operating environments. Table 3 summarizes the Kerberos tools.

Table 3 Kerberos-related tools

Tool | Usage
kinit | Obtains and caches Kerberos ticket-granting tickets
klist | Lists entries in the local Kerberos credentials cache and key table
ktab | Manages the names and service keys stored in the local Kerberos key table

Appendix C Built-in Providers

The Java platform implementation from Sun Microsystems includes a number of built-in provider packages. For details, see the Java™ Cryptography Architecture Sun Providers Documentation.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JavaServer Pages

This chapter includes the following topics:

  • JSP Java Plug-in Action Element: <jsp:plugin>
  • Deploying Java Plug-in through JSP

JavaServer Pages (JSP) is a technology for generating dynamic web-page content from a web/application server. JSP provides support for Java Plug-in HTML elements. This document tells how to use the JSP Plug-in action element for deploying applets with Java Plug-in.

JSP Java Plug-in Action Element: <jsp:plugin>

The <jsp:plugin> action element enables a JSP page author to generate HTML for downloading the Java Plug-in, if it is not installed, and executing an applet. Specifically the action generates the OBJECT element for Internet Explorer or the EMBED element for Netscape Navigator.

When the JSP is executed, the <jsp:plugin> action element is replaced by either an <OBJECT> or <EMBED> HTML tag, depending on the browser.

For example, an applet may be specified as follows in JSP:

<jsp:plugin type=applet code="Molecule" codebase="/html" >
<jsp:params>
    <jsp:param name="molecule" value="molecules/benzene.mol"/>
</jsp:params>
<jsp:fallback>
       <p> Unable to start Plug-in. </p>
</jsp:fallback>
</jsp:plugin>

In the above example, the attributes of the <jsp:plugin> element provide configuration data for the applet itself. The <jsp:param> elements specify the parameters to the applet. The <jsp:fallback> element specifies content for the browser if Java Plug-in fails to start.

Depending on the User Agent requesting the JSP page, the web server will generate either an EMBED or OBJECT tag.

For example, if Netscape Navigator is the User Agent requesting the JSP page, the following EMBED tag will be produced by the server:

<EMBED type="application/x-java-applet"
        code="Molecule" codebase="/html" molecule="molecules/benzene.mol">
<NOEMBED>
<p> Unable to start plug-in </p>
</NOEMBED>

Note

The above works for Netscape 4, as it supports the EMBED tag, but it does not work for Netscape 6.x, as it currently does not support the EMBED tag.

For more information about the <jsp:plugin> element, see Java Server Pages Specification.

Deploying Java Plug-in through JSP

JSP provides an alternative way to deploy applets through Java Plug-in. Because of the dynamic nature of JSP, developers will be able to generate HTML pages on-the-fly that take advantage of Java Plug-in much more easily than before.

Although <jsp:plugin> tag support is part of the JSP specification, various web or application server vendors may provide different implementations and different levels of controls over this feature. For more information, contact your server vendor.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JSSE Reference Guide for Java SE

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java™ Secure Socket Extension (JSSE)
Reference Guide

for Java Platform Standard Edition 7

Introduction
Features and Benefits
JSSE Standard API
SunJSSE Provider
Related Documentation
Terms and Definitions
Secure Sockets Layer (SSL) Protocol Overview
Why Use SSL?
How SSL Works
Key Classes
Relationship Between Classes
Core Classes and Interfaces
SocketFactory and ServerSocketFactory Classes
SSLSocketFactory and SSLServerSocketFactory Classes
SSLSocket and SSLServerSocket Classes
Nonblocking I/O with SSLEngine
SSLSession and ExtendedSSLSession Interfaces
HttpsURLConnection Class
Support Classes and Interfaces
SSLContext Class
TrustManager Interface
TrustManagerFactory Class
X509TrustManager Interface
X509ExtendedTrustManager Class
KeyManager Interface
KeyManagerFactory Class
X509KeyManager Interface
X509ExtendedKeyManager Class
Relationships between TrustManagers and KeyManagers
Secondary Support Classes and Interfaces
SSLParameters Class
SSLSessionContext Interface
SSLSessionBindingListener Interface
SSLSessionBindingEvent Class
HandShakeCompletedListener Interface
HandShakeCompletedEvent Class
HostnameVerifier Interface
X509Certificate Class
AlgorithmConstraints Interface
Previous (JSSE 1.0.x) Implementation Classes and Interfaces
Customizing JSSE
The Installation Directory <java-home>
Customization
Transport Layer Security (TLS) Renegotiation Issue
Introduction
Phased Approach to Fixing This Issue
Description of Phase 2 Fix
Workarounds/Alternatives to SSL/TLS Renegotiation
Implementation Details
Description of the Phase 1 Fix
JCE and Hardware Acceleration/Smartcard Support
Use of JCE
Hardware Accelerators
Configure JSSE to use Smartcards as Keystore and Trust Stores
Multiple and Dynamic Keystores
Kerberos Cipher Suites
Kerberos Requirements
Peer Identity Information
Security Manager

Additional Keystore Formats (PKCS12)

Troubleshooting
Configuration Problems
Debugging Utilities
Code Examples
Converting an Unsecure Socket to a Secure Socket
Running the JSSE Sample Code
Creating a Keystore to Use with JSSE
Appendix A: Standard Names

Appendix B: Provider Pluggability

Introduction

Data that travels across a network can easily be accessed by someone who is not the intended recipient. When the data includes private information, such as passwords and credit card numbers, steps must be taken to make the data unintelligible to unauthorized parties. It is also important to ensure the data has not been modified, either intentionally or unintentionally, during transport. The Secure Sockets Layer (SSL) and Transport Layer Security (TLS) protocols were designed to help protect the privacy and integrity of data while it is transferred across a network.

The Java Secure Socket Extension (JSSE) enables secure Internet communications. It provides a framework and an implementation for a Java version of the SSL and TLS protocols and includes functionality for data encryption, server authentication, message integrity, and optional client authentication. Using JSSE, developers can provide for the secure passage of data between a client and a server running any application protocol, such as Hypertext Transfer Protocol (HTTP), Telnet, or FTP, over TCP/IP. (For an introduction to SSL, see Secure Sockets Layer (SSL) Protocol Overview.)

By abstracting the complex underlying security algorithms and "handshaking" mechanisms, JSSE minimizes the risk of creating subtle, but dangerous security vulnerabilities. Furthermore, it simplifies application development by serving as a building block which developers can integrate directly into their applications.

JSSE was previously an optional package to the Java 2 SDK, Standard Edition (J2SDK), v 1.3. JSSE was integrated into the Java Standard Edition Development Kit starting with J2SDK 1.4.

JSSE provides both an application programming interface (API) framework and an implementation of that API. The JSSE API supplements the "core" network and cryptographic services defined by the java.security and java.net packages by providing extended networking socket classes, trust managers, key managers, SSLContexts, and a socket factory framework for encapsulating socket creation behavior. Because the socket APIs were based on a blocking I/O model, in JDK 5.0, a nonblocking SSLEngineAPI was introduced to allow implementations to choose their own I/O methods.

The JSSE API is capable of supporting SSL versions 2.0 and 3.0 and Transport Layer Security (TLS) 1.0. These security protocols encapsulate a normal bidirectional stream socket and the JSSE API adds transparent support for authentication, encryption, and integrity protection. The JSSE implementation shipped with Oracle's JRE supports SSL 3.0 and TLS 1.0. It does not implement SSL 2.0.

As mentioned above, JSSE is a security component of the Java SE 6 platform, and is based on the same design principles found elsewhere in the Java Cryptography Architecture (JCA) framework. This framework for cryptography-related security components allows them to have implementation independence and, whenever possible, algorithm independence. JSSE uses the same "provider" architecture defined in the JCA.

Other security components in the Java SE 6 platform include the Java Authentication and Authorization Service (JAAS), and the Java Security Tools. JSSE encompasses many of the same concepts and algorithms as those in JCE but automatically applies them underneath a simple stream socket API.

The JSSE APIs were designed to allow other SSL/TLS protocol and Public Key Infrastructure (PKI) implementations to be plugged in seamlessly. Developers can also provide alternate logic for determining if remote hosts should be trusted or what authentication key material should be sent to a remote host.

Features and Benefits

JSSE includes the following important features:

  • Included as a standard component of JRE 1.4 and later
  • Extensible, provider based architecture
  • Implemented in 100% Pure Java
  • Provides API support for SSL versions 2.0 and 3.0, TLS 1.0 and later; and an implementation of SSL 3.0 and TLS 1.0
  • Includes classes that can be instantiated to create secure channels (SSLSocket, SSLServerSocket, and SSLEngine)
  • Provides support for cipher suite negotiation, which is part of the SSL handshaking used to initiate or verify secure communications
  • Provides support for client and server authentication, which is part of the normal SSL handshaking
  • Provides support for Hypertext Transfer Protocol (HTTP) encapsulated in the SSL protocol (HTTPS), which allows access to data such as web pages using HTTPS
  • Provides server session management APIs to manage memory-resident SSL sessions
  • Provides support for several cryptographic algorithms commonly used in cipher suites, including those listed in the following table:
Cryptographic Functionality Available With JSSE
Cryptographic Algorithm1 | Cryptographic Process | Key Lengths (Bits)
RSA | Authentication and key exchange | 512 and larger
RC4 | Bulk encryption | 128 128 (40 effective)
DES | Bulk encryption | 64 (56 effective) 64 (40 effective)
Triple DES | Bulk encryption | 192 (112 effective)
AES | Bulk encryption | 2562 128
Diffie-Hellman | Key agreement | 1024 512
DSA | Authentication | 1024

1 Note: The SunJSSE implementation uses the Java Cryptography Extension (JCE) for all its cryptographic algorithms.

2 Cipher suites that use AES_256 require installation of the JCE Unlimited Strength Jurisdiction Policy Files. See Java SE Download Page.

JSSE Standard API

The JSSE standard API, available in the javax.net and javax.net.ssl packages, covers:

  • Secure (SSL) sockets and server sockets.
  • A nonblocking engine for producing and consuming streams of SSL/TLS data (SSLEngine).
  • Factories for creating sockets, server sockets, SSL sockets, and SSL server sockets. Using socket factories you can encapsulate socket creation and configuration behavior.
  • A class representing a secure socket context that acts as a factory for secure socket factories and engines.
  • Key and trust manager interfaces (including X.509-specific key and trust managers), and factories that can be used for creating them.
  • A class for secure HTTP URL connections (HTTPS).

SunJSSE Provider

Oracle's implementation of Java SE includes a JSSE provider named "SunJSSE", which comes pre-installed and pre-registered with the JCA. This provider supplies the following cryptographic services:

  • An implementation of the SSL 3.0 and TLS 1.0 security protocols.

  • An implementation of the most common SSL and TLS cipher suites which encompass a combination of authentication, key agreement, encryption and integrity protection.

  • An implementation of an X.509-based key manager which chooses appropriate authentication keys from a standard JCA KeyStore.

  • An implementation of an X.509-based trust manager which implements rules for certificate chain path validation.

  • An implementation of PKCS12 as JCA keystore type "pkcs12". Storing trusted anchors in PKCS12 is not supported. Users should store trust anchors in JKS format and save private keys in PKCS12 format.

More information about this provider is available in the SunJSSE section.

Related Documentation

Java Secure Socket Extension Documentation

  • Archive of API-related questions and answers posted to Sun's Java Security team through java-security@sun.com:
    http://archives.java.sun.com/archives/java-security.html

    Note: The above mailing list is not a subscription list or a support mechanism. It is simply a one-way channel that you can use to send comments to the Java SE 6 Standard Edition security team.

  • JSSE API documentation:
    • javax.net package
    • javax.net.ssl package
    • javax.security.cert package

Java Platform Security Documentation

  • The Java Security home page has links to White Papers, Books, Secure Coding guidelines, etc:
    Java SE Security

  • The Java Certification Path API Programmer's Guide:
    CertPath Programmer's Guide

  • Links to more Java SE 6 platform security documents:
    Security Guides page

  • Tutorial for Java platform security:
    Security Features in Java SE

  • Book on Java SE platform security:
    Inside Java 2 Platform Security: Architecture, API Design, and Implementation by Li Gong. Addison Wesley Longman, Inc., 1999. ISBN: 0201310007.

Export Issues Related to Cryptography

For information on U.S. encryption policies, refer to these Web sites:

  • U.S. Department of Commerce:
    http://www.commerce.gov

  • Export Policy Resource Page:
    http://www.crypto.com/

  • Computer Systems Public Policy:
    http://www.cspp.org/

  • Federal Information Processing Standards Publications (FIPS PUBS) homepage, which has links to the Data Encryption Standard (DES):
    http://www.itl.nist.gov/fipspubs/

  • Revised U.S. Encryption Export Control Regulations:
    http://www.epic.org/crypto/export_controls/regs_1_00.html

Cryptography Documentation

Online resources:

  • Dr. Rivest's Cryptography and Security page:
    http://theory.lcs.mit.edu/~rivest/crypto-security.html

Books:

  • Applied Cryptography, Second Edition by Bruce Schneier. John Wiley and Sons, Inc., 1996.

  • Cryptography Theory and Practice by Doug Stinson. CRC Press, Inc., 1995.

  • Cryptography & Network Security: Principles & Practice by William Stallings. Prentice Hall, 1998.

Secure Sockets Layer Documentation

Online resources:

  • Introduction to SSL from Sun ONE Software:
    http://docs.sun.com/source/816-6156-10/contents.htm

  • The SSL Protocol version 3.0 Internet Draft:
    http://wp.netscape.com/eng/ssl3/ssl-toc.html

  • The TLS Protocol version 1.0 RFC:
    http://www.ietf.org/rfc/rfc2246.txt

  • "HTTP Over TLS" Information RFC:
    http://www.ietf.org/rfc/rfc2818.txt

Books:

  • SSL and TLS: Designing and Building Secure Systems by Eric Rescorla. Addison Wesley Professional, 2000.

  • SSL and TLS Essentials: Securing the Web by Stephen Thomas. John Wiley and Sons, Inc., 2000.

  • Java 2 Network Security, Second Edition, by Marco Pistoia, Duane F Reller, Deepak Gupta, Milind Nagnur, and Ashok K Ramani. Prentice Hall, 1999. Copyright 1999 International Business Machines.

Terms and Definitions

There are several terms relating to cryptography that are used within this document. This section defines some of these terms.

Authentication

Authentication is the process of confirming the identity of a party with whom one is communicating.

Cipher Suite

A cipher suite is a combination of cryptographic parameters that define the security algorithms and key sizes used for authentication, key agreement, encryption, and integrity protection.

Certificate

A certificate is a digitally signed statement vouching for the identity and public key of an entity (person, company, etc.). Certificates can either be self-signed or issued by a Certification Authority (CA). Certification Authorities are entities that are trusted to issue valid certificates for other entities. Well-known CAs include VeriSign, Entrust, and GTE CyberTrust. X509 is a common certificate format, and they can be managed by the JDK's keytool.

Cryptographic Hash Function

A cryptographic hash function is similar to a checksum. Data is processed with an algorithm that produces a relatively small string of bits called a hash. A cryptographic hash function has three primary characteristics: it is a one-way function, meaning that it is not possible to produce the original data from the hash; a small change in the original data produces a large change in the resulting hash; and it does not require a cryptographic key.

Cryptographic Service Provider

In the JCA, implementations for various cryptographic algorithms are provided by cryptographic service providers, or "providers" for short. Providers are essentially packages that implement one or more engine classes for specific algorithms. An engine class defines a cryptographic service in an abstract fashion without a concrete implementation.

Digital Signature

A digital signature is the digital equivalent of a handwritten signature. It is used to ensure that data transmitted over a network was sent by whoever claims to have sent it and that the data has not been modified in transit. For example, an RSA-based digital signature is calculated by first computing a cryptographic hash of the data and then encrypting the hash with the sender's private key.

Encryption and Decryption

Encryption is the process of using a complex algorithm to convert an original message, or cleartext, to an encoded message, called ciphertext, that is unintelligible unless it is decrypted. Decryption is the inverse process of producing cleartext from ciphertext. The algorithms used to encrypt and decrypt data typically come in two categories: secret key (symmetric) cryptography and public key (asymmetric) cryptography.

Handshake Protocol

The negotiation phase during which the two socket peers agree to use a new or existing session. The handshake protocol is a series of messages exchanged over the record protocol. At the end of the handshake new connection-specific encryption and integrity protection keys are generated based on the key agreement secrets in the session.

Key Agreement

Key agreement is a method by which two parties cooperate to establish a common key. Each side generates some data which is exchanged. These two pieces of data are then combined to generate a key. Only those holding the proper private initialization data will be able to obtain the final key. Diffie-Hellman (DH) is the most common example of a key agreement algorithm.

Key Exchange

One side generates a symmetric key and encrypts it using the peer's public key (typically RSA). The data is then transmitted to the peer, who then decrypts the key using its corresponding private key.

Key Managers and Trust Managers

Key managers and trust managers use keystores for their key material. A key manager manages a keystore and supplies public keys to others as needed, e.g., for use in authenticating the user to others. A trust manager makes decisions about who to trust based on information in the truststore it manages.

Keystores and Truststores

A keystore is a database of key material. Key material is used for a variety of purposes, including authentication and data integrity. There are various types of keystores available, including "PKCS12" and Oracle's "JKS."

Generally speaking, keystore information can be grouped into two different categories: key entries and trusted certificate entries. A key entry consists of an entity's identity and its private key, and can be used for a variety of cryptographic purposes. In contrast, a trusted certificate entry only contains a public key in addition to the entity's identity. Thus, a trusted certificate entry can not be used where a private key is required, such as in a javax.net.ssl.KeyManager. In the JDK implementation of "JKS", a keystore may contain both key entries and trusted certificate entries.

A truststore is a keystore which is used when making decisions about what to trust. If you receive some data from an entity that you already trust, and if you can verify that the entity is the one it claims to be, then you can assume that the data really came from that entity.

An entry should only be added to a truststore if the user makes a decision to trust that entity. By either generating a keypair or by importing a certificate, the user has given trust to that entry, and thus any entry in the keystore is considered a trusted entry.

It may be useful to have two different keystore files: one containing just your key entries, and the other containing your trusted certificate entries, including Certification Authority (CA) certificates. The former contains private information, while the latter does not. Using two different files instead of a single keystore file provides for a cleaner separation of the logical distinction between your own certificates (and corresponding private keys) and others' certificates. You could provide more protection for your private keys if you store them in a keystore with restricted access, while providing the trusted certificates in a more publicly accessible keystore if needed.

Message Authentication Code

A Message Authentication Code (MAC) provides a way to check the integrity of information transmitted over or stored in an unreliable medium, based on a secret key. Typically, MACs are used between two parties that share a secret key in order to validate information transmitted between these parties.

A MAC mechanism that is based on cryptographic hash functions is referred to as HMAC. HMAC can be used with any cryptographic hash function, such as Message Digest 5 (MD5) and Secure Hash Algorithm (SHA), in combination with a secret shared key. HMAC is specified in RFC 2104.

Public Key Cryptography

Public key cryptography uses an encryption algorithm in which two keys are produced. One key is made public while the other is kept private. The public key and the private key are cryptographic inverses; what one key encrypts only the other key can decrypt. Public key cryptography is also called asymmetric cryptography.

Record Protocol

The record protocol packages all data whether application-level or as part of the handshake process into discrete records of data much like a TCP stream socket converts an application byte stream into network packets. The individual records are then protected by the current encryption and integrity protection keys.

Secret Key Cryptography

Secret key cryptography uses an encryption algorithm in which the same key is used both to encrypt and decrypt the data. Secret key cryptography is also called symmetric cryptography.

Session

A session is a named collection of state information including authenticated peer identity, cipher suite, and key agreement secrets which are negotiated through a secure socket handshake and which can be shared among multiple secure socket instances.

Trust Managers

See Key Managers and Trust Managers.

Truststore

See Keystores and Truststores.

Secure Sockets Layer (SSL) Protocol Overview

Secure Sockets Layer (SSL) is the most widely used protocol for implementing cryptography on the Web. SSL uses a combination of cryptographic processes to provide secure communication over a network. This section provides an introduction to SSL and the cryptographic processes it uses.

SSL provides a secure enhancement to the standard TCP/IP sockets protocol used for Internet communications. As shown in the following table, "TCP/IP Protocol Stack with SSL," the secure sockets layer is added between the transport layer and the application layer in the standard TCP/IP protocol stack. The application most commonly used with SSL is Hypertext Transfer Protocol (HTTP), the protocol for Internet Web pages. Other applications, such as Net News Transfer Protocol (NNTP), Telnet, Lightweight Directory Access Protocol (LDAP), Interactive Message Access Protocol (IMAP), and File Transfer Protocol (FTP), can be used with SSL as well.

Note: There is currently no standard for secure FTP.

TCP/IP Protocol Stack with SSL
TCP/IP Layer | Protocol
Application Layer | HTTP, NNTP, Telnet, FTP, etc.
Secure Sockets Layer | SSL
Transport Layer | TCP
Internet Layer | IP

SSL was developed by Netscape in 1994, and with input from the Internet community, has evolved to become a standard. It is now under the control of the international standards organization, the Internet Engineering Task Force (IETF). The IETF has renamed SSL to Transport Layer Security (TLS), and released the first specification, version 1.0, in January 1999. TLS 1.0 is a modest upgrade to the most recent version of SSL, version 3.0. The differences between SSL 3.0 and TLS 1.0 are minor.

Why Use SSL?

Transferring sensitive information over a network can be risky due to the following three issues:
  • You cannot always be sure that the entity with whom you are communicating is really who you think it is.
  • Network data can be intercepted, so it is possible that it can be read by an unauthorized third party, sometimes known as an attacker.
  • If an attacker can intercept the data, the attacker may be able to modify the data before sending it on to the receiver.

SSL addresses each of these issues. It addresses the first issue by optionally allowing each of two communicating parties to ensure the identity of the other party in a process called authentication. Once the parties are authenticated, SSL provides an encrypted connection between the two parties for secure message transmission. Encrypting the communication between the two parties provides privacy and therefore addresses the second issue. The encryption algorithms used with SSL include a secure hash function, which is similar to a checksum. This ensures that data is not modified in transit. The secure hash function addresses the third issue of data integrity.

Note, both authentication and encryption are optional, and depend on the the negotiated cipher suites between the two entities.

The most obvious example of when you would use SSL is in an e-commerce transaction. In an e-commerce transaction, it would be foolish to assume that you can guarantee the identity of the server with whom you are communicating. It would be easy enough for someone to create a phony Web site promising great services if only you enter your credit card number. SSL allows you, the client, to authenticate the identity of the server. It also allows the server to authenticate the identity of the client, although in Internet transactions, this is seldom done.

Once the client and the server are comfortable with each other's identity, SSL provides privacy and data integrity through the encryption algorithms it uses. This allows sensitive information, such as credit card numbers, to be transmitted securely over the Internet.

While SSL provides authentication, privacy, and data integrity, it does not provide non-repudiation services. Non-repudiation means that an entity that sends a message cannot later deny that they sent it. When the digital equivalent of a signature is associated with a message, the communication can later be proved. SSL alone does not provide non-repudiation.

How SSL Works

One of the reasons SSL is effective is that it uses several different cryptographic processes. SSL uses public key cryptography to provide authentication, and secret key cryptography and digital signatures to provide for privacy and data integrity. Before you can understand SSL, it is helpful to understand these cryptographic processes.

Cryptographic Processes

The primary purpose of cryptography is to make it difficult for an unauthorized third party to access and understand private communication between two parties. It is not always possible to restrict all unauthorized access to data, but private data can be made unintelligible to unauthorized parties through the process of encryption. Encryption uses complex algorithms to convert the original message, or cleartext, to an encoded message, called ciphertext. The algorithms used to encrypt and decrypt data that is transferred over a network typically come in two categories: secret key cryptography and public key cryptography. These forms of cryptography are explained in the following subsections.

Both secret key cryptography and public key cryptography depend on the use of an agreed-upon cryptographic key or pair of keys. A key is a string of bits that is used by the cryptographic algorithm or algorithms during the process of encrypting and decrypting the data. A cryptographic key is like a key for a lock: only with the right key can you open the lock.

Safely transmitting a key between two communicating parties is not a trivial matter. A public key certificate allows a party to safely transmit its public key, while ensuring the receiver of the authenticity of the public key. Public key certificates are described in a later section.

In the descriptions of the cryptographic processes that follow, we use the conventions used by the security community: we label the two communicating parties with the names Alice and Bob. We call the unauthorized third party, also known as the attacker, Charlie.

Secret Key Cryptography

With secret key cryptography, both communicating parties, Alice and Bob, use the same key to encrypt and decrypt the messages. Before any encrypted data can be sent over the network, both Alice and Bob must have the key and must agree on the cryptographic algorithm that they will use for encryption and decryption.

One of the major problems with secret key cryptography is the logistical issue of how to get the key from one party to the other without allowing access to an attacker. If Alice and Bob are securing their data with secret key cryptography, and if Charlie gains access to their key, Charlie can understand any secret messages he intercepts between Alice and Bob. Not only can Charlie decrypt Alice's and Bob's messages, but he can also pretend that he is Alice and send encrypted data to Bob. Bob will not know that the message came from Charlie, not Alice.

Once the problem of secret key distribution is solved, secret key cryptography can be a valuable tool. The algorithms provide excellent security and encrypt data relatively quickly. The majority of the sensitive data sent in an SSL session is sent using secret key cryptography.

Secret key cryptography is also called symmetric cryptography because the same key is used to both encrypt and decrypt the data. Well-known secret key cryptographic algorithms include the Data Encryption Standard (DES), triple-strength DES (3DES), Rivest Cipher 2 (RC2), and Rivest Cipher 4 (RC4).

Public Key Cryptography

Public key cryptography solves the logistical problem of key distribution by using both a public key and a private key. The public key can be sent openly through the network while the private key is kept private by one of the communicating parties. The public and the private keys are cryptographic inverses of each other; what one key encrypts, the other key will decrypt.

Assume that Bob wants to send a secret message to Alice using public key cryptography. Alice has both a public key and a private key, so she keeps her private key in a safe place and sends her public key to Bob. Bob encrypts the secret message to Alice using Alice's public key. Alice can later decrypt the message with her private key.

If Alice encrypts a message using her private key and sends the encrypted message to Bob, Bob can be sure that the data he receives comes from Alice; if Bob can decrypt the data with Alice's public key, the message must have been encrypted by Alice with her private key, and only Alice has Alice's private key. The problem is that anybody else can read the message as well because Alice's public key is public. While this scenario does not allow for secure data communication, it does provide the basis for digital signatures. A digital signature is one of the components of a public key certificate, and is used in SSL to authenticate a client or a server. Public key certificates and digital signatures are described in later sections.

Public key cryptography is also called asymmetric cryptography because different keys are used to encrypt and decrypt the data. A well known public key cryptographic algorithm often used with SSL is the Rivest Shamir Adleman (RSA) algorithm. Another public key algorithm used with SSL that is designed specifically for secret key exchange is the Diffie-Hellman (DH) algorithm. Public key cryptography requires extensive computations, making it very slow. It is therefore typically used only for encrypting small pieces of data, such as secret keys, rather than for the bulk of encrypted data communications.

A Comparison Between Secret Key and Public Key Cryptography

Both secret key cryptography and public key cryptography have strengths and weaknesses. With secret key cryptography, data can be encrypted and decrypted quickly, but because both communicating parties must share the same secret key information, the logistics of exchanging the key can be a problem. With public key cryptography, key exchange is not a problem because the public key does not need to be kept secret, but the algorithms used to encrypt and decrypt data require extensive computations, and are therefore very slow.

Public Key Certificates

A public key certificate provides a safe way for an entity to pass on its public key to be used in asymmetric cryptography. The public key certificate avoids the following situation: if Charlie creates his own public key and private key, he can claim that he is Alice and send his public key to Bob. Bob will be able to communicate with Charlie, but Bob will think that he is sending his data to Alice.

A public key certificate can be thought of as the digital equivalent of a passport. It is issued by a trusted organization and provides identification for the bearer. A trusted organization that issues public key certificates is known as a certificate authority (CA). The CA can be likened to a notary public. To obtain a certificate from a CA, one must provide proof of identity. Once the CA is confident that the applicant represents the organization it says it represents, the CA signs the certificate attesting to the validity of the information contained within the certificate.

A public key certificate contains several fields, including:

  • Issuer - The issuer is the CA that issued the certificate. If a user trusts the CA that issues a certificate, and if the certificate is valid, the user can trust the certificate.
  • Period of validity - A certificate has an expiration date, and this date is one piece of information that should be checked when verifying the validity of a certificate.
  • Subject - The subject field includes information about the entity that the certificate represents.
  • Subject's public key - The primary piece of information that the certificate provides is the subject's public key. All the other fields are provided to ensure the validity of this key.
  • Signature - The certificate is digitally signed by the CA that issued the certificate. The signature is created using the CA's private key and ensures the validity of the certificate. Because only the certificate is signed, not the data sent in the SSL transaction, SSL does not provide for non-repudiation.

If Bob only accepts Alice's public key as valid when she sends it in a public key certificate, Bob will not be fooled into sending secret information to Charlie when Charlie masquerades as Alice.

Multiple certificates may be linked in a certificate chain. When a certificate chain is used, the first certificate is always that of the sender. The next is the certificate of the entity that issued the sender's certificate. If there are more certificates in the chain, each is that of the authority that issued the previous certificate. The final certificate in the chain is the certificate for a root CA. A root CA is a public certificate authority that is widely trusted. Information for several root CAs is typically stored in the client's Internet browser. This information includes the CA's public key. Well-known CAs include VeriSign, Entrust, and GTE CyberTrust.

Cryptographic Hash Functions

When sending encrypted data, SSL typically uses a cryptographic hash function to ensure data integrity. The hash function prevents Charlie from tampering with data that Alice sends to Bob.

A cryptographic hash function is similar to a checksum. The main difference is that while a checksum is designed to detect accidental alterations in data, a cryptographic hash function is designed to detect deliberate alterations. When data is processed by a cryptographic hash function, a small string of bits, known as a hash, is generated. The slightest change to the message typically makes a large change in the resulting hash. A cryptographic hash function does not require a cryptographic key. Two hash functions often used with SSL are Message Digest 5 (MD5) and Secure Hash Algorithm (SHA). SHA was proposed by the U.S. National Institute of Science and Technology (NIST).

Message Authentication Code

A message authentication code (MAC) is similar to a cryptographic hash, except that it is based on a secret key. When secret key information is included with the data that is processed by a cryptographic hash function, the resulting hash is known as an HMAC.

If Alice wants to be sure that Charlie does not tamper with her message to Bob, she can calculate an HMAC for her message and append the HMAC to her original message. She can then encrypt the message plus the HMAC using a secret key she shares with Bob. When Bob decrypts the message and calculates the HMAC, he will be able to tell if the message was modified in transit. With SSL, an HMAC is used with the transmission of secure data.

Digital Signatures

Once a cryptographic hash is created for a message, the hash is encrypted with the sender's private key. This encrypted hash is called a digital signature.

The SSL Process

Communication using SSL begins with an exchange of information between the client and the server. This exchange of information is called the SSL handshake.

The three main purposes of the SSL handshake are:

  • Negotiate the cipher suite
  • Authenticate identity (optional)
  • Establish information security by agreeing on encryption mechanisms

Negotiating the Cipher Suite

The SSL session begins with a negotiation between the client and the server as to which cipher suite they will use. A cipher suite is a set of cryptographic algorithms and key sizes that a computer can use to encrypt data. The cipher suite includes information about the public key exchange algorithms or key agreement algorithms, and cryptographic hash functions. The client tells the server which cipher suites it has available, and the server chooses the best mutually acceptable cipher suite.

Authenticating the Server

In SSL, the authentication step is optional, but in the example of an e-commerce transaction over the Web, the client will generally want to authenticate the server. Authenticating the server allows the client to be sure that the server represents the entity that the client believes the server represents.

To prove that a server belongs to the organization that it claims to represent, the server presents its public key certificate to the client. If this certificate is valid, the client can be sure of the identity of the server.

The client and server exchange information that allows them to agree on the same secret key. For example, with RSA, the client uses the server's public key, obtained from the public key certificate, to encrypt the secret key information. The client sends the encrypted secret key information to the server. Only the server can decrypt this message because the server's private key is required for this decryption.

Sending the Encrypted Data

Both the client and the server now have access to the same secret key. With each message, they use the cryptographic hash function, chosen in the first step of this process, and shared secret information, to compute an HMAC that they append to the message. They then use the secret key and the secret key algorithm negotiated in the first step of this process to encrypt the secure data and the HMAC. The client and server can now communicate securely using their encrypted and hashed data.

The SSL Protocol

The previous section provides a high-level description of the SSL handshake, which is the exchange of information between the client and the server prior to sending the encrypted message. This section provides more detail.

The "SSL Messages" figure that follows shows the sequence of messages that are exchanged in the SSL handshake. Messages that are sent only in certain situations are noted as optional. Each of the SSL messages is described in the following figure:

Sequence of messages exchanged in SSL handshake.

The SSL messages are sent in the following order:

  1. Client hello - The client sends the server information including the highest version of SSL it supports and a list of the cipher suites it supports. (TLS 1.0 is indicated as SSL 3.1.) The cipher suite information includes cryptographic algorithms and key sizes.
  2. Server hello - The server chooses the highest version of SSL and the best cipher suite that both the client and server support and sends this information to the client.
  3. Certificate - The server sends the client a certificate or a certificate chain. A certificate chain typically begins with the server's public key certificate and ends with the certificate authority's root certificate. This message is optional, but is used whenever server authentication is required.
  4. Certificate request - If the server needs to authenticate the client, it sends the client a certificate request. In Internet applications, this message is rarely sent.
  5. Server key exchange - The server sends the client a server key exchange message when the public key information sent in message 3 above is not sufficient for key exchange. For example, in ciphersuites based on Diffie-Hellman, this message contains the server's DH public key.
  6. Server hello done - The server tells the client that it is finished with its initial negotiation messages.
  7. Certificate - If the server requests a certificate from the client in message 4, the client sends its certificate chain, just as the server did in message 3.

    Note: Only a few Internet server applications ask for a certificate from the client.

  8. Client key exchange - The client generates information used to create a key to use for symmetric encryption. For RSA, the client then encrypts this key information with the server's public key and sends it to the server. For ciphersuites based on Diffie-Hellman, this message contains the client's DH public key.
  9. Certificate verify - This message is sent when a client presents a certificate as previously explained. Its purpose is to allow the server to complete the process of authenticating the client. When this message is used, the client sends information that it digitally signs using a cryptographic hash function. When the server decrypts this information with the client's public key, the server is able to authenticate the client.
  10. Change cipher spec - The client sends a message telling the server to change to encrypted mode.
  11. Finished - The client tells the server that it is ready for secure data communication to begin.
  12. Change cipher spec - The server sends a message telling the client to change to encrypted mode.
  13. Finished - The server tells the client that it is ready for secure data communication to begin. This is the end of the SSL handshake.
  14. Encrypted data - The client and the server communicate using the symmetric encryption algorithm and the cryptographic hash function negotiated in messages 1 and 2, and using the secret key that the client sent to the server in Message 8. The handshake can be renegotiated at this time. See the next section for details.
  15. Close Messages - At the end of the connection, each side will send a close_notify message to inform the peer that the connection is closed.

If the parameters generated during an SSL session are saved, these parameters can sometimes be reused for future SSL sessions. Saving SSL session parameters allows encrypted communication to begin much more quickly.

Handshaking Again (Renegotiation)

Once the initial handshake has been finished and application data is flowing, either side is free to initiate a new handshake at any time. An application might like to use a stronger cipher suite for especially critical operations, or a server application might want to require client authentication.

Regardless of the reason, the new handshake takes place over the existing encrypted session, and application data and handshake messages are interleaved until a new session is established.

Your application can initiate a new handshake using one of the following methods:

  • SSLSocket.startHandshake()
  • SSLEngine.beginHandshake()

Note that a protocol flaw related to renegotiation was found in 2009. The protocol and the Java SE implementation have both been fixed. For more information, see Transport Layer Security (TLS) Renegotiation Issue.

Cipher Suite Choice and Remote Entity Verification

The SSL/TLS protocols define a specific series of steps to ensure a "protected" connection. However, the choice of cipher suite will directly impact the type of security the connection enjoys. For example, if an anonymous cipher suite is selected, the application will have no way to verify the remote peer's identity. If a suite with no encryption is selected, then the privacy of the data can not be protected. Additionally, the SSL/TLS protocols do not specify that the credentials received must match those that peer might be expected to send. If the connection were somehow redirected to a rogue peer, but the rogue's credentials presented were acceptable based on the current trust material, the connection would be considered valid.

When using raw SSLSockets/SSLEngines you should always check the peer's credentials before sending any data. The SSLSocket and SSLEngine classes do not automatically verify that the hostname in a URL matches the hostname in the peer's credentials. An application could be exploited with URL spoofing if the hostname is not verified.

Protocols such as https do require hostname verification. Applications can use HostnameVerifier to override the default HTTPS hostname rules. See HttpsURLConnection for more information.

SSL and TLS References

For a list of resources containing more information about SSL, see Secure Sockets Layer Documentation .

Key Classes

Relationship Between Classes

To communicate securely, both sides of the connection must be SSL-enabled. In the JSSE API, the endpoint classes of the connection is the SSLSocket and SSLEngine. In the diagram below, the major classes used to create SSLSocket/SSLEngines are laid out in a logical ordering.

diagram of classes used to create SSLSockets/SSLEngines

An SSLSocket is created either by an SSLSocketFactory or by an SSLServerSocket accepting an in-bound connection. (In turn, an SSLServerSocket is created by an SSLServerSocketFactory.) Both SSLSocketFactory and SSLServerSocketFactory objects are created by an SSLContext. An SSLEngine is created directly by the SSLContext, and relies on the application to handle all I/O.

IMPORTANT NOTE: When using raw SSLSockets/SSLEngines you should always check the peer's credentials before sending any data. The SSLSocket/SSLEngine classes do not automatically verify, for example, that the hostname in a URL matches the hostname in the peer's credentials. An application could be exploited with URL spoofing if the hostname is not verified.

There are two ways to obtain and initialize an SSLContext:

  • The simplest is to call the static getDefault method on either the SSLSocketFactory or SSLServerSocketFactory class. These methods create a default SSLContext with a default KeyManager, TrustManager, and a secure random number generator. (A default KeyManagerFactory and TrustManagerFactory are used to create the KeyManager and TrustManager, respectively.) The key material used is found in the default keystore/truststore, as determined by system properties described in Customizing the Default Key and Trust Stores, Store Types, and Store Passwords.
  • The approach that gives the caller the most control over the behavior of the created context is to call the static method getInstance on the SSLContext class, then initialize the context by calling the instance's proper init method. One variant of the init method takes three arguments: an array of KeyManager objects, an array of TrustManager objects, and a SecureRandom random number generator. The KeyManager and TrustManager objects are created by either implementing the appropriate interface(s) or using the KeyManagerFactory and TrustManagerFactory classes to generate implementations. The KeyManagerFactory and TrustManagerFactory can then each be initialized with key material contained in the KeyStore passed as an argument to the TrustManagerFactory/KeyManagerFactory init method. Finally, the getTrustManagers method (in TrustManagerFactory) and getKeyManagers method (in KeyManagerFactory) can be called to obtain the array of trust or key managers, one for each type of trust or key material.

Once an SSL connection is established, an SSLSession is created which contains various information, such as identities established, cipher suite used, etc. The SSLSession is then used to describe an ongoing relationship and state information between two entities. Each SSL connection involves one session at a time, but that session may be used on many connections between those entities, simultaneously or sequentially.

Core Classes and Interfaces

The core JSSE classes are part of the javax.net and javax.net.ssl packages.

SocketFactory and ServerSocketFactory Classes

The abstract javax.net.SocketFactory class is used to create sockets. It must be subclassed by other factories, which create particular subclasses of sockets and thus provide a general framework for the addition of public socket-level functionality. (See, for example, SSLSocketFactory.)

The javax.net.ServerSocketFactory class is analogous to the SocketFactory class, but is used specifically for creating server sockets.

Socket factories are a simple way to capture a variety of policies related to the sockets being constructed, producing such sockets in a way which does not require special configuration of the code which asks for the sockets:

  • Due to polymorphism of both factories and sockets, different kinds of sockets can be used by the same application code just by passing different kinds of factories.
  • Factories can themselves be customized with parameters used in socket construction. So for example, factories could be customized to return sockets with different networking timeouts or security parameters already configured.
  • The sockets returned to the application can be subclasses of java.net.Socket (or javax.net.ssl.SSLSocket), so that they can directly expose new APIs for features such as compression, security, record marking, statistics collection, or firewall tunneling.

SSLSocketFactory and SSLServerSocketFactory Classes

A javax.net.ssl.SSLSocketFactory acts as a factory for creating secure sockets. This class is an abstract subclass of javax.net.SocketFactory.

Secure socket factories encapsulate the details of creating and initially configuring secure sockets. This includes authentication keys, peer certificate validation, enabled cipher suites and the like.

The javax.net.ssl.SSLServerSocketFactory class is analogous to the SSLSocketFactory class, but is used specifically for creating server sockets.

Obtaining an SSLSocketFactory

There are three primary ways of obtaining an SSLSocketFactory:

  • Get the default factory by calling the SSLSocketFactory.getDefault static method.
  • Receive a factory as an API parameter. That is, code which needs to create sockets but which doesn't care about the details of how the sockets are configured can include a method with an SSLSocketFactory parameter that can be called by clients to specify which SSLSocketFactory to use when creating sockets. (For example, javax.net.ssl.HttpsURLConnection.)
  • Construct a new factory with specifically configured behavior.

The default factory is typically configured to support server authentication only so that sockets created by the default factory do not leak any more information about the client than a normal TCP socket would.

Many classes which create and use sockets do not need to know the details of socket creation behavior. Creating sockets through a socket factory passed in as a parameter is a good way of isolating the details of socket configuration, and increases the reusability of classes which create and use sockets.

You can create new socket factory instances either by implementing your own socket factory subclass or by using another class which acts as a factory for socket factories. One example of such a class is SSLContext, which is provided with the JSSE implementation as a provider-based configuration class.

SSLSocket and SSLServerSocket Classes

The javax.net.ssl.SSLSocket class is a subclass of the standard Java java.net.Socket class. It supports all of the standard socket methods and adds additional methods specific to secure sockets. Instances of this class encapsulate the SSLContext under which they were created. There are APIs to control the creation of secure socket sessions for a socket instance but trust and key management are not directly exposed.

The javax.net.ssl.SSLServerSocket class is analogous to the SSLSocket class, but is used specifically for creating server sockets.

To prevent peer spoofing, you should always verify the credentials presented to a SSLSocket.

Implementation note: Due to the complexity of the SSL and TLS protocols, it is difficult to predict whether incoming bytes on a connection are handshake or application data, and how that data might affect the current connection state (even causing the process to block). In the Oracle JSSE implementation, the available() method on the object obtained by SSLSocket.getInputStream() returns a count of the number of application data bytes successfully decrypted from the SSL connection but not yet read by the application.

Obtaining an SSLSocket

Instances of SSLSocket can be obtained in two ways. First, an SSLSocket can be created by an instance of SSLSocketFactory via one of the several createSocket methods on that class. The second way to obtain SSLSockets is through the accept method on the SSLServerSocket class.

Nonblocking I/O with SSLEngine

SSL/TLS is becoming increasingly popular. It is being used in a wide variety of applications across a wide range of computing platforms and devices. Along with this popularity comes demands to use it with different I/O and threading models in order to satisfy the applications' performance, scalability, footprint, and other requirements. There are demands to use it with blocking and nonblocking I/O channels, asynchronous I/O, arbitrary input and output streams, and byte buffers. There are demands to use it in highly scalable, performance-critical environments, requiring management of thousands of network connections.

Prior to Java SE 5, the JSSE API supported only a single transport abstraction: stream-based sockets via SSLSocket. While this was adequate for many applications, it did not meet the needs of applications that need to use different I/O or threading models. In 1.6.0, a new abstraction was introduced to allow applications to use the SSL/TLS protocols in a transport independent way, and thus freeing applications to choose transport and computing models that best meet their needs. Not only does this new abstraction allow applications to use nonblocking I/O channels and other I/O models, it also accommodates different threading models. This effectively leaves the I/O and threading decisions up to the application. Because of this flexibility, the application must now manage I/O and threading (complex topics in and of themselves), as well as have some understanding of the SSL/TLS protocols. The new abstraction is therefore an advanced API: beginners should continue to use SSLSocket.

Newcomers to the API may wonder "Why not just have an SSLSocketChannel which extends java.nio.channels.SocketChannel?" There are two main reasons:

  • There were a lot of very difficult questions about what a SSLSocketChannel should be, including its class hierarchy and how it should interoperate with Selectors and other types of SocketChannels. Each proposal brought up more questions than answers. It was noted that any new API abstraction extended to work with SSL/TLS would require the same significant analysis and could result in large and complex APIs.
  • Any JSSE implementation of a new API would be free to choose the "best" I/O & compute strategy, but hiding any of these details is inappropriate for those applications needing full control. Any specific implementation would be inappropriate for some application segment.
By abstracting the I/O and treating data as streams of bytes, these issues are resolved and the new API could be used with any existing or future I/O model. While this solution makes I/O and CPU handling the developers' responsibility, JSSE implementations are prevented from being unusable due to some unconfigurable and/or unchangeable internal detail.

Users of other Java programming language APIs such as JGSS and SASL will notice similarities in that the application is also responsible for transporting data.

SSLEngine

The core class in this new abstraction is javax.net.ssl.SSLEngine. It encapsulates an SSL/TLS state machine and operates on inbound and outbound byte buffers supplied by the user of the SSLEngine. The following diagram illustrates the flow of data from the application, to the SSLEngine, to the transport mechanism, and back.

The application, shown on the left, supplies application (plaintext) data in an application buffer and passes it to the SSLEngine. The SSLEngine processes the data contained in the buffer, or any handshaking data, to produce SSL/TLS encoded data and places it the network buffer supplied by the application. The application is then responsible for using an appropriate transport (shown on the right) to send the contents of the network buffer to its peer. Upon receiving SSL/TLS encoded data from its peer (via the transport), the application places the data into a network buffer and passes it to SSLEngine. The SSLEngine processes the network buffer's contents to produce handshaking data or application data.

In all, SSLEngine can be in one of five states.

  1. Creation - ready to be configured.
  2. Initial handshaking - perform authentication and negotiate communication parameters.
  3. Application data - ready for application exchange.
  4. Rehandshaking - renegotiate communications parameters/authentication; handshaking data may be mixed with application data.
  5. Closure - ready to shut down connection.
These five states are decribed in more detail in the SSLEngine class documentation.

Getting Started

To create an SSLEngine, you use the SSLContext.createSSLEngine() methods. You must then configure the engine to act as a client or a server, as well as set other configuration parameters such as which cipher suites to use and whether to require client authentication.

Here is an example that creates an SSLEngine. Note that the server name and port number are not used for communicating with the server--all transport is the responsibility of the application. They are hints to the JSSE provider to use for SSL session caching, and for Kerberos-based cipher suite implementations to determine which server credentials should be obtained.

import javax.net.ssl.*;
import java.security.*;

// Create/initialize the SSLContext with key material

char[] passphrase = "passphrase".toCharArray();

// First initialize the key and trust material.
KeyStore ksKeys = KeyStore.getInstance("JKS");
ksKeys.load(new FileInputStream("testKeys"), passphrase);
KeyStore ksTrust = KeyStore.getInstance("JKS");
ksTrust.load(new FileInputStream("testTrust"), passphrase);

// KeyManager's decide which key material to use.
KeyManagerFactory kmf =
    KeyManagerFactory.getInstance("SunX509");
kmf.init(ksKeys, passphrase);

// TrustManager's decide whether to allow connections.
TrustManagerFactory tmf =
    TrustManagerFactory.getInstance("SunX509");
tmf.init(ksTrust);

sslContext = SSLContext.getInstance("TLS");
sslContext.init(
    kmf.getKeyManagers(), tmf.getTrustManagers(), null);

// We're ready for the engine.
SSLEngine engine = sslContext.createSSLengine(hostname, port);

// Use as client
engine.setUseClientMode(true);

Generating and Processing SSL/TLS data

The two main SSLEngine methods wrap() and unwrap() are responsible for generating and consuming network data respectively. Depending on the state of the SSLEngine, this data might be handshake or application data.

Each SSLEngine has several phases during its lifetime. Before application data can be sent/received, the SSL/TLS protocol requires a handshake to establish cryptographic parameters. This handshake requires a series of back-and-forth steps by the SSLEngine. The SSL Process can provide more details about the handshake itself.

During the initial handshaking, wrap() and unwrap() generate and consume handshake data, and the application is responsible for transporting the data. The wrap()/unwrap() sequence is repeated until the handshake is finished. Each SSLEngine operation generates a SSLEngineResult, of which the SSLEngineResult.HandshakeStatus field is used to determine what operation needs to occur next to move the handshake along.

A typical handshake might look like this:

client | SSL/TLS message | HSStatus
wrap() | ClientHello | NEED_UNWRAP
unwrap() | ServerHello/Cert/ServerHelloDone | NEED_WRAP
wrap() | ClientKeyExchange | NEED_WRAP
wrap() | ChangeCipherSpec | NEED_WRAP
wrap() | Finished | NEED_UNWRAP
unwrap() | ChangeCipherSpec | NEED_UNWRAP
unwrap() | Finished | FINISHED
Now that handshaking is complete, further calls to wrap() will attempt to consume application data and packages it for transport. unwrap() attempts the opposite.

To send data to the peer, the application first supplies the data that it wants to send to SSLEngine via SSLEngine.wrap() to obtain the corresponding SSL/TLS encoded data. The application then sends the encoded data to the peer using its chosen transport mechanism. When the application receives the SSL/TLS encoded data from the peer via the transport mechanism, it supplies this data to the SSLEngine via SSLEngine.unwrap() to obtain the plaintext data sent by the peer.

Here is an example of an SSL application that is using a nonblocking SocketChannel to communicate with its peer. (It can be made more robust and scalable by using a Selector with the nonblocking SocketChannel.) The following sample code sends the string "hello" to its peer, by encoding it using the SSLEngine created in the previous example. It uses information from the SSLSession to determine how large to make the byte buffers.

// Create a nonblocking socket channel
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress(hostname, port));

// Complete connection
while (!socketChannel.finishedConnect()) {
    // do something until connect completed
}

// Create byte buffers to use for holding application and encoded data
SSLSession session = engine.getSession();
ByteBuffer myAppData = ByteBuffer.allocate(session.getApplicationBufferSize());
ByteBuffer myNetData = ByteBuffer.allocate(session.getPacketBufferSize());
ByteBuffer peerAppData = ByteBuffer.allocate(session.getApplicationBufferSize());
ByteBuffer peerNetData = ByteBuffer.allocate(session.getPacketBufferSize());

// Do initial handshake
doHandshake(socketChannel, engine, myNetData, peerNetData);

myAppData.put("hello".getBytes());
myAppData.flip();

while (myAppData.hasRemaining()) {
    // Generate SSL/TLS encoded data (handshake or application data)
    SSLEngineResult res = engine.wrap(myAppData, myNetData);

    // Process status of call
    if (res.getStatus() == SSLEngineResult.Status.OK) {
        myAppData.compact();

        // Send SSL/TLS encoded data to peer
        while(myNetData.hasRemaining()) {
            int num = socketChannel.write(myNetData);
            if (num == -1) {
                // handle closed channel
            } else if (num == 0) {
                // no bytes written; try again later
            }
        }
    }

    // Handle other status:  BUFFER_OVERFLOW, CLOSED
    ...
}
The following code reads data from the same nonblocking SocketChannel and extracts the plaintext data from it by using the SSLEngine created previously. Each iteration of this code may or may not produce any plaintext data, depending on whether handshaking is in progress.
// Read SSL/TLS encoded data from peer
int num = socketChannel.read(peerNetData);
if (num == -1) {
    // Handle closed channel
} else if (num == 0) {
    // No bytes read; try again ...
} else {
    // Process incoming data
    peerNetData.flip();
    res = engine.unwrap(peerNetData, peerAppData);

    if (res.getStatus() == SSLEngineResult.Status.OK) {
        peerNetData.compact();

        if (peerAppData.hasRemaining()) {
            // Use peerAppData
        }
    }
    // Handle other status:  BUFFER_OVERFLOW, BUFFER_UNDERFLOW, CLOSED
    ...
}

Status of Operations

To indicate the status of the engine and what action(s) the application should take, the SSLEngine.wrap() and SSLEngine.unwrap() methods return an SSLEngineResult instance, as shown in the previous examples. The SSLEngineResult contains two pieces of status information: the overall status of the engine and the handshaking status.

The possible overall statuses are represented by the SSLEngineResult.Status enum. Some examples of this status include OK, which means that there was no error, and BUFFER_UNDERFLOW, which means that the input buffer had insufficient data, indicating that the application needs to obtain more data from the peer (for example, by reading more data from the network), and BUFFER_OVERFLOW, which means that the output buffer had insufficient space to hold the result, indicating that the application needs to clear or enlarge the destination buffer.

Here is an example of how to handle BUFFER_UNDERFLOW and BUFFER_OVERFLOW statuses of SSLEngine.unwrap(). It uses SSLSession.getApplicationBufferSize() and SSLSession.getPacketBufferSize() to determine how large to make the byte buffers.

SSLEngineResult res = engine.unwrap(peerNetData, peerAppData);
switch (res.getStatus()) {

case BUFFER_OVERFLOW:
  // Maybe need to enlarge the peer application data buffer.
  if (engine.getSession().getApplicationBufferSize() >
          peerAppData.capacity()) {
      // enlarge the peer application data buffer
  } else {
        // compact or clear the buffer
  }
  // retry the operation
  break;

case BUFFER_UNDERFLOW:
  // Maybe need to enlarge the peer network packet buffer
  if (engine.getSession().getPacketBufferSize() >
          peerNetData.capacity()) {
      // enlarge the peer network packet buffer
  } else {
        // compact or clear the buffer
  }
  // obtain more inbound network data and then retry the operation
  break;

// Handle other status: CLOSED, OK
...
}

The possible handshaking statuses are represented by the SSLEngineResult.HandshakeStatus enum. They represent whether handshaking has completed, whether the caller needs to obtain more handshaking data from the peer, send more handshaking data to the peer, and so on.

Having two statuses per result allows the engine to indicate that the application must take two actions: one in response to the handshaking and one representing the overall status of the wrap()/unwrap() method. For example, the engine might, as the result of a single SSLEngine.unwrap() call, return SSLEngineResult.Status.OK to indicate that the input data was processed successfully and SSLEngineResult.HandshakeStatus.NEED_UNWRAP to indicate that the application should obtain more SSL/TLS encoded data from the peer and supply it to SSLEngine.unwrap() again so that handshaking can continue. As you can see, the previous examples were greatly simplified; they would need to be expanded significantly to properly handle all of these statuses.

Here is an example of how to process handshaking data by checking handshaking status and the overall status of the wrap()/unwrap() method.

void doHandshake(SocketChannel socketChannel, SSLEngine engine,
        ByteBuffer myNetData, ByteBuffer peerNetData) throws Exception {

    // Create byte buffers to use for holding application data
    int appBufferSize = engine.getSession().getApplicationBufferSize();
    ByteBuffer myAppData = ByteBuffer.allocate(appBufferSize);
    ByteBuffer peerAppData = ByteBuffer.allocate(appBufferSize);

    // Begin handshake
    engine.beginHandshake();
    SSLEngineResult.HandshakeStatus hs = engine.getHandshakeStatus();

    // Process handshaking message
    while (hs != SSLEngineResult.HandshakeStatus.FINISHED &&
        hs != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {

        switch (hs) {

        case NEED_UNWRAP:
            // Receive handshaking data from peer
            if (socketChannel.read(peerNetData) < 0) {
                // Handle closed channel
            }

            // Process incoming handshaking data
            peerNetData.flip();
            SSLEngineResult res = engine.unwrap(peerNetData, peerAppData);
            peerNetData.compact();
            hs = res.getHandshakeStatus();

            // Check status
            switch (res.getStatus()) {
            case OK :
                // Handle OK status
                break;

            // Handle other status: BUFFER_UNDERFLOW, BUFFER_OVERFLOW, CLOSED
            ...
            }
            break;

        case NEED_WRAP :
            // Empty the local network packet buffer.
            myNetData.clear();

            // Generate handshaking data
            res = engine.wrap(myAppData, myNetData);
            hs = res.getHandshakeStatus();

            // Check status
            switch (res.getStatus()) {
            case OK :
                myNetData.flip();

                // Send the handshaking data to peer
                while (myNetData.hasRemaining()) {
                    if (socketChannel.write(myNetData) < 0) {
                        // Handle closed channel
                    }
                }
                break;

            // Handle other status:  BUFFER_OVERFLOW, BUFFER_UNDERFLOW, CLOSED
            ...
            }
            break;

        case NEED_TASK :
            // Handle blocking tasks
            break;

        // Handle other status:  // FINISHED or NOT_HANDSHAKING
        ...
        }
    }

    // Processes after handshaking
    ...
}

Blocking Tasks

During handshaking, the SSLEngine might encounter tasks that might block or take a long time. For example, a TrustManager may need to connect to a remote certificate validation service, or a KeyManager might need to prompt a user to determine which certificate to use as part of client authentication. To preserve the nonblocking nature of SSLEngine, when the engine encounters such a task, it will return SSLEngineResult.HandshakeStatus.NEED_TASK. Upon receiving this status, the application should invoke SSLEngine.getDelegatedTask() to get the task, and then, using the threading model appropriate for its requirements, process the task. The application might, for example, obtain thread(s) from a thread pool to process the task(s), while the main thread goes about handling other I/O.

Here is an example that executes each task in a newly created thread.

if (res.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_TASK) {
    Runnable task;
    while ((task=engine.getDelegatedTask()) != null) {
        new Thread(task).start();
    }
}
The engine will block future wrap/unwrap calls until all of the outstanding tasks are completed.

Shutting Down

For an orderly shutdown of an SSL/TLS connection, the SSL/TLS protocols require transmission of close messages. Therefore, when an application is done with the SSL/TLS connection, it should first obtain the close messages from the SSLEngine, then transmit them to the peer using its transport mechanism, and finally shut down the transport mechanism. Here is an example.
// Indicate that application is done with engine
engine.closeOutbound();

while (!engine.isOutboundDone()) {
    // Get close message
    SSLEngineResult res = engine.wrap(empty, myNetData);

    // Check res statuses

    // Send close message to peer
    while(myNetData().hasRemaining()) {
        int num = socketChannel.write(myNetData);
        if (num == -1) {
            // handle closed channel
        } else if (num == 0) {
            // no bytes written; try again later
        }
        myNetData().compact();
    }
}

// Close transport
socketChannel.close();
In addition to an application explicitly closing the SSLEngine, the SSLEngine might be closed by the peer (via receipt of a close message while it is processing handshake data), or by the SSLEngine encountering an error while processing application or handshake data, indicated by throwing an SSLException. In such cases, the application should invoke SSLEngine.wrap() to get the close message and send it to the peer until SSLEngine.isOutboundDone() returns true, as shown in the previous example, or the SSLEngineResult.getStatus() returns CLOSED.

In addition to orderly shutdowns, there can also be unorderly shutdowns in which the transport link is severed before close messages are exchanged. In the previous examples, the application might get -1 when trying to read or write to the nonblocking SocketChannel. When you get to the end of your input data, you should call engine.closeInbound(), which will verify with the SSLEngine that the remote peer has closed cleanly from the SSL/TLS perspective, and then the application should still try to shutdown cleanly by using the procedure above. Obviously, unlike SSLSocket, the application using SSLEngine must deal with more state transitions, statuses and programming than when using SSLEngine. Please see the NIO-based HTTPS server for more information on writing a SSLEngine-based application.

SSLSession and ExtendedSSLSession Interfaces

A javax.net.ssl.SSLSession represents a security context negotiated between the two peers of an SSLSocket or SSLEngine connection. After a session has been arranged, it can be shared by future SSLSocket or SSLEngine objects connected between the same two peers.

In some cases, parameters negotiated during the handshake are needed later in the handshake to make decisions about trust. For example, the list of valid signature algorithms might restrict the certificate types that can be used for authentication. In the Java SE 7 release, the SSLSession can be retrieved during the handshake by calling getHandshakeSession() on an SSLSocket or SSLEngine. Implementations of TrustManager or KeyManager can use getHandshakeSession() to get information about session parameters to help them make decisions.

A fully initialized SSLSession contains the cipher suite which will be used for communications over a secure socket as well as a non-authoritative hint as to the network address of the remote peer, and management information such as the time of creation and last use. A session also contains a shared master secret negotiated between the peers that is used to create cryptographic keys for encrypting and guaranteeing the integrity of the communications over an SSLSocket or SSLEngine connection. The value of this master secret is known only to the underlying secure socket implementation and is not exposed through the SSLSession API.

In the Java SE 7 release, a TLS 1.2 session is represented by ExtendedSSLSession, an implementation of SSLSession. ExtendedSSLSession adds methods that describe the signature algorithms that are supported by the local implementation and the peer.

Calls to SSLSession.getPacketBufferSize() and SSLSession.getApplicationBufferSize() also are used to determine the appropriate buffer sizes used by SSLEngine.

Note: The SSL/TLS protocols specify that implementations are to produce packets containing at most 16 KB of plaintext. However, some implementations violate the specification and generate large records up to 32 KB. If the SSLEngine.unwrap() code detects large inbound packets, the buffer sizes returned by SSLSession will be updated dynamically. Applications should always check the BUFFER_OVERFLOW/BUFFER_UNDERFLOW statuses and enlarge the corresponding buffers if necessary. SunJSSE will always send standard compliant 16 KB records and allow incoming 32 KB records. (Also see the System property jsse.SSLEngine.acceptLargeFragments in Customization for a workaround.)

HttpsURLConnection Class

The https protocol is similar to http, but https first establishes a secure channel via SSL/TLS sockets and then verifies the identity of the peer before requesting/receiving data. javax.net.ssl.HttpsURLConnection extends the java.net.HttpsURLConnection class, and adds support for https-specific features. See the java.net.URL, java.net.URLConnection, java.net.HttpURLConnection, and javax.net.ssl.HttpURLConnection classes for more information about how https URLs are constructed and used.

Upon obtaining a HttpsURLConnection, you can configure a number of http/https parameters before actually initiating the network connection via the method URLConnection.connect. Of particular interest are:

  • Setting the Assigned SSLSocketFactory
  • Setting the Assigned HostnameVerifier

Setting the Assigned SSLSocketFactory

In some situations, it is desirable to specify the SSLSocketFactory that an HttpsURLConnection instance uses. For example, you may wish to tunnel through a proxy type that isn't supported by the default implementation. The new SSLSocketFactory could return sockets that have already performed all necessary tunneling, thus allowing HttpsURLConnection to use additional proxies.

The HttpsURLConnection class has a default SSLSocketFactory which is assigned when the class is loaded. (In particular it is the factory returned by the method SSLSocketFactory.getDefault.) Future instances of HttpsURLConnection will inherit the current default SSLSocketFactory until a new default SSLSocketFactory is assigned to the class via the static method HttpsURLConnection.setDefaultSSLSocketFactory. Once an instance of HttpsURLConnection has been created, the inherited SSLSocketFactory on this instance can be overriden with a call to the setSSLSocketFactory method.

Note that changing the default static SSLSocketFactory has no effect on existing instances of HttpsURLConnections, a call to the setSSLSocketFactory method is necessary to change the existing instance.

One can obtain the per-instance or per-class SSLSocketFactory by making a call to the getSSLSocketFactory/getDefaultSSLSocketFactory methods, respectively.

Setting the Assigned HostnameVerifier

If the host name of the URL does not match the host name in the credentials received as part of the SSL/TLS handshake, it is possible that URL spoofing has occurred. If the implementation cannot determine a host name match with reasonable certainty, the SSL implementation will perform a callback to the instance's assigned HostnameVerifier for futher checking. The host name verifier can perform whatever steps are necessary to make the determination, such as performing alternate host name pattern matching or perhaps popping up an interactive dialog box. An unsuccessful verification by the host name verifier will close the connection. (See RFC 2818 for more information regarding host name verification.)

The setHostnameVerifier/setDefaultHostnameVerifier methods operate in a similar manner to the setSSLSocketFactory/setDefaultSSLSocketFactory methods, in that there are HostnameVerifiers assigned on a per-instance and per-class basis, and the current values can be obtained by a call to the getHostnameVerifier/getDefaultHostnameVerifier methods.

Support Classes and Interfaces

The classes and interfaces in this section are provided to support the creation and initialization of SSLContext objects, which are used to create SSLSocketFactory, SSLServerSocketFactory, and SSLEngine objects. The support classes and interfaces are part of the javax.net.ssl package.

Three of the classes described in this section ( SSLContext, KeyManagerFactory, and TrustManagerFactory) are engine classes. An engine class is an API class for specific algorithms (or protocols, in the case of SSLContext), for which implementations may be provided in one or more Cryptographic Service Provider (provider) packages. For more information on providers and engine classes, see the "Design Principles" and "Concepts" sections of the Java Cryptography Architecture Reference Guide.

The SunJSSE provider that comes standard with JSSE provides SSLContext, KeyManagerFactory, and TrustManagerFactory implementations, as well as implementations for engine classes in the standard Java security (java.security) API. The implementations supplied by SunJSSE are:

Engine Class Implemented | Algorithm or Protocol
KeyStore | PKCS12
KeyManagerFactory | PKIX, SunX509
TrustManagerFactory | PKIX (a.k.a. X509 or SunPKIX), SunX509
SSLContext | SSLv3 (a.k.a. SSL), TLSv1 (a.k.a. TLS), TLSv1.1, TLSv1.2

SSLContext Class

javax.net.ssl.SSLContext is an engine class for an implementation of a secure socket protocol. An instance of this class acts as a factory for SSL socket factories and SSL engines. An SSLContext holds all of the state information shared across all objects created under that context. For example, session state is associated with the SSLContext when it is negotiated through the handshake protocol by sockets created by socket factories provided by the context. These cached sessions can be reused and shared by other sockets created under the same context.

Each instance is configured through its init method with the keys, certificate chains, and trusted root CA certificates that it needs to perform authentication. This configuration is provided in the form of key and trust managers. These managers provide support for the authentication and key agreement aspects of the cipher suites supported by the context.

Currently, only X.509-based managers are supported.

Creating an SSLContext Object

Like other JCA provider-based "engine" classes, SSLContext objects are created using the getInstance factory methods of the SSLContext class. These static methods each return an instance that implements at least the requested secure socket protocol. The returned instance may implement other protocols too. For example, getInstance("TLSv1") may return a instance which implements "TLSv1", "TLSv1.1" and "TLSv1.2". The getSupportedProtocols method returns a list of supported protocols when an SSLSocket, SSLServerSocket or SSLEngine is created from this context. You can control which protocols are actually enabled for an SSL connection by using the method setEnabledProtocols(String[] protocols).

Note: An SSLContext object is automatically created, initialized, and statically assigned to the SSLSocketFactory class when you call SSLSocketFactory.getDefault. Therefore, you don't have to directly create and initialize an SSLContext object (unless you want to override the default behavior).

To create an SSLContext object by calling a getInstance factory method, you must specify the protocol name. You may also specify which provider you want to supply the implementation of the requested protocol:

public static SSLContext getInstance(String protocol);

public static SSLContext getInstance(String protocol,
                                     String provider);

public static SSLContext getInstance(String protocol,
                                     Provider provider);

If just a protocol name is specified, the system will determine if there is an implementation of the requested protocol available in the environment, and if there is more than one, if there is a preferred one.

If both a protocol name and a provider are specified, the system will determine if there is an implementation of the requested protocol in the provider requested, and throw an exception if there is not.

A protocol is a string (such as "SSL") that describes the secure socket protocol desired. Common protocol names for SSLContext objects are defined in Appendix A.

Here is an example of obtaining an SSLContext:

SSLContext sc = SSLContext.getInstance("SSL");

A newly-created SSLContext should be initialized by calling the init method:

public void init(KeyManager[] km, TrustManager[] tm,
                   SecureRandom random);

If the KeyManager[] paramater is null, then an empty KeyManager will be defined for this context. If the TrustManager[] parameter is null, the installed security providers will be searched for the highest-priority implementation of the TrustManagerFactory, from which an appropriate TrustManager will be obtained. Likewise, the SecureRandom parameter may be null, in which case a default implementation will be used.

If the internal default context is used, (e.g. a SSLContext is created by SSLSocketFactory.getDefault() or SSLServerSocketFactory.getDefault()), a default KeyManager and a TrustManager are created. The default SecureRandom implementation is also chosen.

TrustManager Interface

The primary responsibility of the TrustManager is to determine whether the presented authentication credentials should be trusted. If the credentials are not trusted, the connection will be terminated. To authenticate the remote identity of a secure socket peer, you need to initialize an SSLContext object with one or more TrustManagers. You need to pass one TrustManager for each authentication mechanism that is supported. If null is passed into the SSLContext initialization, a trust manager will be created for you. Typically, there is a single trust manager that supports authentication based on X.509 public key certificates (e.g. X509TrustManager). Some secure socket implementations may also support authentication based on shared secret keys, Kerberos, or other mechanisms.

TrustManagers are created either by a TrustManagerFactory, or by providing a concrete implementation of the interface.

TrustManagerFactory Class

The javax.net.ssl.TrustManagerFactory is an engine class for a provider-based service that acts as a factory for one or more types of TrustManager objects. Because it is provider-based, additional factories can be implemented and configured that provide additional or alternate trust managers that provide more sophisticated services or that implement installation-specific authentication policies.

Creating a TrustManagerFactory

You create an instance of this class in a similar manner to SSLContext, except for passing an algorithm name string instead of a protocol name to the getInstance method:
public static TrustManagerFactory
                  getInstance(String algorithm);

public static TrustManagerFactory
                  getInstance(String algorithm,
                              String provider);

public static TrustManagerFactory
                  getInstance(String algorithm,
                              Provider provider);

A sample algorithm name string is:

"PKIX"

A sample call is the following:

TrustManagerFactory tmf =
    TrustManagerFactory.getInstance("PKIX", "SunJSSE");

The above call will create an instance of the SunJSSE provider's PKIX trust manager factory. This factory can then be used to create trust managers which provide X.509 PKIX-based certification path validity checking.

When initializing a SSLContext, you can use trust managers created from a trust manager factory, or you can write your own trust manager, perhaps using the CertPath API. (See the Java Certification Path API Programmer's Guide for details.) You don't need to use a trust manager factory at all if you implement a trust manager using the X509TrustManager interface.

A newly-created factory should be initialized by calling one of the init methods:

public void init(KeyStore ks);
public void init(ManagerFactoryParameters spec);

You should call whichever init method is appropriate for the TrustManagerFactory you are using. (Ask the provider vendor.)

For many factories, such as the "SunX509" TrustManagerFactory from the SunJSSE provider, the KeyStore is the only information required in order to initialize the TrustManagerFactory and thus the first init method is the appropriate one to call. The TrustManagerFactory will query the KeyStore for information on which remote certificates should be trusted during authorization checks.

In some cases, initialization parameters other than a KeyStore may be needed by a provider. Users of that particular provider are expected to pass an implementation of the appropriate ManagerFactoryParameters as defined by the provider. The provider can then call the specified methods in the ManagerFactoryParameters implementation to obtain the needed information.

For example, suppose the TrustManagerFactory provider requires initialization parameters B, R, and S from any application that wishes to use that provider. Like all providers that require initialization parameters other than a KeyStore, the provider will require that the application provide an instance of a class that implements a particular ManagerFactoryParameters sub-interface. In our example, suppose the provider requires that the calling application implement and create an instance of MyTrustManagerFactoryParams and pass it to the second init. Here is what MyTrustManagerFactoryParams may look like:

public interface MyTrustManagerFactoryParams extends
       ManagerFactoryParameters {
    public boolean getBValue();
    public float getRValue();
    public String getSValue():
}

Some trustmanagers are capable of making trust decisions without having to be explicitly initialized with a KeyStore object or any other parameters. For example, they may access trust material from a local directory service via LDAP, may use a remote online certificate status checking server, or may access default trust material from a standard local location.

PKIX TrustManager Support

The default trust manager algorithm is "PKIX". The default can be changed by editing the ssl.TrustManagerFactory.algorithm property in the java.security file.

The PKIX trust manager factory uses the CertPath PKIX implementation from an installed security provider; a "SUN" CertPath provider is supplied with the Java SE Development Kit 6. The trust manager factory can be initialized using the normal init(KeyStore ks) method, or by passing CertPath parameters to the the PKIX trust manager using the newly introduced class javax.net.ssl.CertPathTrustManagerParameters.

Here is an example of how to get the trust manager to use a particular LDAP certificate store and enable revocation checking.

import javax.net.ssl.*;
import java.security.cert.*;
import java.security.KeyStore;
...

// Create PKIX parameters
KeyStore anchors = KeyStore.getInstance("JKS");
anchors.load(new FileInputStream(anchorsFile));
CertPathParameters pkixParams = new PKIXBuilderParameters(anchors,
    new X509CertSelector());

// Specify LDAP certificate store to use
LDAPCertStoreParameters lcsp = new LDAPCertStoreParameters("ldap.imc.org", 389);
pkixParams.addCertStore(CertStore.getInstance("LDAP", lcsp));

// Specify that revocation checking is to be enabled
pkixParams.setRevocationEnabled(true);

// Wrap them as trust manager parameters
ManagerFactoryParameters trustParams =
    new CertPathTrustManagerParameters(pkixParams);

// Create TrustManagerFactory for PKIX-compliant trust managers
TrustManagerFactory factory = TrustManagerFactory.getInstance("PKIX");

// Pass parameters to factory to be passed to CertPath implementation
factory.init(trustParams);

// Use factory
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, factory.getTrustManagers(), null);

If the init(KeyStore ks) method is used, default PKIXParameters are used with the exception that revocation checking is disabled. It can be enabled by setting the system property com.sun.net.ssl.checkRevocation to true. Note that this setting requires that the CertPath implementation can locate revocation information by itself. The PKIX implementation in the SUN provider can do this in many cases but requires that the system property com.sun.security.enableCRLDP be set to true.

More information about PKIX and the CertPath API can be found in the Java Certificate Path API Programming Guide.

X509TrustManager Interface

The javax.net.ssl.X509TrustManager interface extends the general TrustManager interface. This interface must be implemented by a trust manager when using X.509-based authentication.

In order to support X.509 authentication of remote socket peers through JSSE, an instance of this interface must be passed to the init method of an SSLContext object.

Creating an X509TrustManager

You can either implement this interface directly yourself or obtain one from a provider-based TrustManagerFactory (such as that supplied by the SunJSSE provider). You could also implement your own that delegates to a factory-generated trust manager. For example, you might do this in order to filter the resulting trust decisions and query an end-user through a graphical user interface.

Note: If a null KeyStore parameter is passed to the SunJSSE "PKIX" or "SunX509" TrustManagerFactory, the factory uses the following steps to try to find trust material:

  1. If the system property:
    javax.net.ssl.trustStore
    is defined, then the TrustManagerFactory attempts to find a file using the filename specified by that system property, and uses that file for the KeyStore. If the javax.net.ssl.trustStorePassword system property is also defined, its value is used to check the integrity of the data in the truststore before opening it.

    If javax.net.ssl.trustStore is defined but the specified file does not exist, then a default TrustManager using an empty keystore is created.

  2. If the javax.net.ssl.trustStore system property was not specified, then if the file
    <java-home>/lib/security/jssecacerts
    exists, that file is used. (See The Installation Directory <java-home> for information about what <java-home> refers to.) Otherwise,
  3. If the file
    <java-home>/lib/security/cacerts
    exists, that file is used.

(If none of these files exists, that may be okay because there are SSL cipher suites which are anonymous, that is, which don't do any authentication and thus don't need a truststore.)

The factory looks for a file specified via the security property javax.net.ssl.trustStore or for the jssecacerts file before checking for a cacerts file so that you can provide a JSSE-specific set of trusted root certificates separate from ones that might be present in cacerts for code-signing purposes.

Creating Your Own X509TrustManager

If the supplied X509TrustManager behavior isn't suitable for your situation, you can create your own X509TrustManager by either creating and registering your own TrustManagerFactory or by implementing the X509TrustManager interface directly.

The following MyX509TrustManager class enhances the default SunJSSE X509 TrustManager behavior by providing alternative authentication logic when the default SunJSSE X509 TrustManager fails.

class MyX509TrustManager implements X509TrustManager {

     /*
      * The default PKIX X509TrustManager9.  We'll delegate
      * decisions to it, and fall back to the logic in this class if the
      * default X509TrustManager doesn't trust it.
      */
     X509TrustManager pkixTrustManager;

     MyX509TrustManager() throws Exception {
         // create a "default" JSSE X509TrustManager.

         KeyStore ks = KeyStore.getInstance("JKS");
         ks.load(new FileInputStream("trustedCerts"),
             "passphrase".toCharArray());

         TrustManagerFactory tmf =
                TrustManagerFactory.getInstance("PKIX");
         tmf.init(ks);

         TrustManager tms [] = tmf.getTrustManagers();

         /*
          * Iterate over the returned trustmanagers, look
          * for an instance of X509TrustManager.  If found,
          * use that as our "default" trust manager.
          */
         for (int i = 0; i < tms.length; i++) {
             if (tms[i] instanceof X509TrustManager) {
                 pkixTrustManager = (X509TrustManager) tms[i];
                 return;
             }
         }

         /*
          * Find some other way to initialize, or else we have to fail the
          * constructor.
          */
         throw new Exception("Couldn't initialize");
     }

     /*
      * Delegate to the default trust manager.
      */
     public void checkClientTrusted(X509Certificate[] chain, String authType)
                 throws CertificateException {
         try {
             pkixTrustManager.checkClientTrusted(chain, authType);
         } catch (CertificateException excep) {
             // do any special handling here, or rethrow exception.
         }
     }

     /*
      * Delegate to the default trust manager.
      */
     public void checkServerTrusted(X509Certificate[] chain, String authType)
                 throws CertificateException {
         try {
             pkixTrustManager.checkServerTrusted(chain, authType);
         } catch (CertificateException excep) {
             /*
              * Possibly pop up a dialog box asking whether to trust the
              * cert chain.
              */
         }
     }

     /*
      * Merely pass this through.
      */
     public X509Certificate[] getAcceptedIssuers() {
         return pkixTrustManager.getAcceptedIssuers();
     }
}

Once you have created such a trust manager, assign it to an SSLContext via the init method. Future SocketFactories created from this SSLContext will use your new TrustManager when making trust decisions.

TrustManager[] myTMs = new TrustManager [] {
                          new MyX509TrustManager() };
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, myTMs, null);

Updating the keyStore Dynamically

You can enhance MyX509TrustManager to handle dynamic keystore updates. When a checkClientTrusted or checkServerTrusted test fails and does not establish a trusted certificate chain, you can add the required trusted certificate to the keystore. You need to create a new pkixTrustManager from the TrustManagerFactory initialized with the updated keystore. When you establish a new connection (using the previously initialized SSLContext), the newly added certificate will be used when making trust decisions.

X509ExtendedTrustManager Class

In the Java SE 7 release, the X509ExtendedTrustManager class is an abstract implementation of the X509TrustManager interface. It adds methods for connection-sensitive trust management. In addition, it enables endpoint verification at the TLS layer.

In TLS 1.2 and later, both client and server are able to specify which hash and signature algorithms they will accept. In order to authenticate the remote side, authentication decisions must be based on both X509 certificates and the local accepted hash and signature algorithms. The local accepted hash and signature algorithms can be got from the ExtendedSSLSession.getLocalSupportedSignatureAlgorithms() method.

The ExtendedSSLSession object can be retrieved by calling the SSLSocket.getHandshakeSession() method or the SSLEngine.getHandshakeSession() method.

The X509TrustManager interface is not connection-sensitive. It provides no way to access SSLSocket or SSLEngine session properties.

Besides TLS 1.2 support, the X509ExtendedTrustManager class also support algorithm constraints and SSL layer hostname verification. For JSSE providers and trust manager implementations, the X509ExtendedTrustManager class is highly recommended rather than the legacy X509TrustManager interface.

Creating an X509ExtendedTrustManager

You can either create an X509ExtendedTrustManager sublcass yourself (which is outlined in the following section) or obtain one from a provider-based TrustManagerFactory (such as that supplied by the SunJSSE provider). In the Java SE 7 release, the PKIX or SunX509 TrustManagerFactory returns an X509ExtendedTrustManager instance.

Creating Your Own X509ExtendedTrustManager

This section outlines how to subclass X509ExtendedTrustManager in nearly the same way as described for X509TrustManager.

The following class uses the "PKIX" TrustManagerFactory to locate a default X509ExtendedTrustManager that will be used to make decisions about trust. If the default trust manager fails for any reason, the subclass is able to add other behavior. In the example, these locations are indicated by comments in the catch clauses.

import java.io.*;
import java.net.*;

import java.security.*;
import java.security.cert.*;
import javax.net.ssl.*;

public class MyX509ExtendedTrustManager extends X509ExtendedTrustManager {

     /*
      * The default PKIX X509ExtendedTrustManager.  We'll delegate
      * decisions to it, and fall back to the logic in this class if the
      * default X509ExtendedTrustManager doesn't trust it.
      */
     X509ExtendedTrustManager pkixTrustManager;

     MyX509ExtendedTrustManager() throws Exception {
         // create a "default" JSSE X509ExtendedTrustManager.

         KeyStore ks = KeyStore.getInstance("JKS");
         ks.load(new FileInputStream("trustedCerts"),
             "passphrase".toCharArray());

         TrustManagerFactory tmf =
                TrustManagerFactory.getInstance("PKIX");
         tmf.init(ks);

         TrustManager tms [] = tmf.getTrustManagers();

         /*
          * Iterate over the returned trustmanagers, look
          * for an instance of X509TrustManager.  If found,
          * use that as our "default" trust manager.
          */
         for (int i = 0; i < tms.length; i++) {
             if (tms[i] instanceof X509ExtendedTrustManager) {
                 pkixTrustManager = (X509ExtendedTrustManager) tms[i];
                 return;
             }
         }

         /*
          * Find some other way to initialize, or else we have to fail the
          * constructor.
          */
         throw new Exception("Couldn't initialize");
     }

     /*
      * Delegate to the default trust manager.
      */
     public void checkClientTrusted(X509Certificate[] chain, String authType)
                 throws CertificateException {
         try {
             pkixTrustManager.checkClientTrusted(chain, authType);
         } catch (CertificateException excep) {
             // do any special handling here, or rethrow exception.
         }
     }

     /*
      * Delegate to the default trust manager.
      */
     public void checkServerTrusted(X509Certificate[] chain, String authType)
                 throws CertificateException {
         try {
             pkixTrustManager.checkServerTrusted(chain, authType);
         } catch (CertificateException excep) {
             /*
              * Possibly pop up a dialog box asking whether to trust the
              * cert chain.
              */
         }
     }

     /*
      * Connection-sensitive verification.
      */
     public void checkClientTrusted(X509Certificate[] chain, String authType,
                  Socket socket)
                 throws CertificateException {
       try {
           pkixTrustManager.checkClientTrusted(chain, authType, socket);
       } catch (CertificateException excep) {
           // do any special handling here, or rethrow exception.
       }
     }

     public void checkClientTrusted(X509Certificate[] chain, String authType,
                  SSLEngine engine)
                 throws CertificateException {
       try {
           pkixTrustManager.checkClientTrusted(chain, authType, engine);
       } catch (CertificateException excep) {
           // do any special handling here, or rethrow exception.
       }
     }

     public void checkServerTrusted(X509Certificate[] chain, String authType,
                  Socket socket)
                 throws CertificateException {
       try {
           pkixTrustManager.checkServerTrusted(chain, authType, socket);
       } catch (CertificateException excep) {
           // do any special handling here, or rethrow exception.
       }
     }

     public void checkServerTrusted(X509Certificate[] chain, String authType,
                  SSLEngine engine)
                 throws CertificateException {
       try {
           pkixTrustManager.checkServerTrusted(chain, authType, engine);
       } catch (CertificateException excep) {
           // do any special handling here, or rethrow exception.
       }
     }

     /*
      * Merely pass this through.
      */
     public X509Certificate[] getAcceptedIssuers() {
         return pkixTrustManager.getAcceptedIssuers();
     }
}

KeyManager Interface

The primary responsibility of the KeyManager is to select the authentication credentials that will eventually be sent to the remote host. To authenticate yourself (a local secure socket peer) to a remote peer, you need to initialize an SSLContext object with one or more KeyManagers. You need to pass one KeyManager for each different authentication mechanism that will be supported. If null is passed into the SSLContext initialization, an empty KeyManager will be created. If the internal default context is used (e.g. a SSLContext created by SSLSocketFactory.getDefault() or SSLServerSocketFactory.getDefault()), a default KeyManager is created. Typically, there is a single key manager that supports authentication based on X.509 public key certificates. Some secure socket implementations may also support authentication based on shared secret keys, Kerberos, or other mechanisms.

KeyManagers are created either by a KeyManagerFactory, or by providing a concrete implementation of the interface.

KeyManagerFactory Class

javax.net.ssl.KeyManagerFactory is an engine class for a provider-based service that acts as a factory for one or more types of KeyManager objects. The SunJSSE provider implements a factory which can return a basic X.509 key manager. Because it is provider-based, additional factories can be implemented and configured to provide additional or alternate key managers.

Creating a KeyManagerFactory

You create an instance of this class in a similar manner to SSLContext, except for passing an algorithm name string instead of a protocol name to the getInstance method:
public static KeyManagerFactory
                  getInstance(String algorithm);

public static KeyManagerFactory
                  getInstance(String algorithm,
                              String provider);

public static KeyManagerFactory
                  getInstance(String algorithm,
                              Provider provider);

A sample algorithm name string is:

"SunX509"

A sample call is the following:

KeyManagerFactory kmf =
    KeyManagerFactory.getInstance("SunX509", "SunJSSE");

The above call will create an instance of the SunJSSE provider's default key manager factory, which provides basic X.509-based authentication keys.

A newly-created factory should be initialized by calling one of the init methods:

public void init(KeyStore ks, char[] password);
public void init(ManagerFactoryParameters spec);

You should call whichever init method is appropriate for the KeyManagerFactory you are using. (Ask the provider vendor.)

For many factories, such as the default "SunX509" KeyManagerFactory from the SunJSSE provider, the KeyStore and password are the only information required in order to initialize the KeyManagerFactory and thus the first init method is the appropriate one to call. The KeyManagerFactory will query the KeyStore for information on which private key and matching public key certificates should be used for authenticating to a remote socket peer. The password parameter specifies the password that will be used with the methods for accessing keys from the KeyStore. All keys in the KeyStore must be protected by the same password.

In some cases, initialization parameters other than a KeyStore and password may be needed by a provider. Users of that particular provider are expected to pass an implementation of the appropriate ManagerFactoryParameters as defined by the provider. The provider can then call the specified methods in the ManagerFactoryParameters implementation to obtain the needed information.

Some factories are capable of providing access to authentication material without having to be initialized with a KeyStore object or any other parameters. For example, they may access key material as part of a login mechanism such as one based on JAAS, the Java Authentication and Authorization Service.

As indicated above, the SunJSSE provider supports a "SunX509" factory that must be initialized with a KeyStore parameter.

X509KeyManager Interface

The javax.net.ssl.X509KeyManager interface extends the general KeyManager interface. It must be implemented by a key manager for X.509-based authentication. In order to support X.509 authentication to remote socket peers through JSSE, an instance of this interface must be passed to the init method of an SSLContext object.

Creating an X509KeyManager

You can either implement this interface directly yourself or obtain one from a provider-based KeyManagerFactory (such as those supplied by the SunJSSE provider). You could also implement your own that delegates to a factory-generated key manager. For example, you might do this in order to filter the resulting keys and query an end-user through a graphical user interface.

Creating Your Own X509KeyManager

If the default X509KeyManager behavior isn't suitable for your situation, you can create your own X509KeyManager in a way similiar to that shown in Creating Your Own X509TrustManager.

X509ExtendedKeyManager Class

The X509ExtendedKeyManager abstract class is an implementation of the X509KeyManager interface which allows for connection-specific key selection. It adds two methods that select a key alias for client or server based on the key type, allowed issuers, and current SSLEngine.

public String chooseEngineClientAlias(String[] keyType,
                                      Principal[] issuers,
                                      SSLEngine engine)

public String chooseEngineServerAlias(String keyType,
                                      Principal[] issuers,
                                      SSLEngine engine)

If a key manager is not a instance of the X509ExtendedKeyManager class, it will not work with the SSLEngine class.

For JSSE providers and key manager implementations, the X509ExtendedKeyManager class is highly recommended rather than the legacy X509KeyManager interface.

In TLS 1.2 and later, both client and server are able to specify which hash and signature algorithms they will accept. In order to pass the authentication required by the remote side, local key selection decisions must be based on both X509 certificate and the remote accepted hash and signature algorithms. The remote accepted hash and signature algorithms can be retrieved from the method ExtendedSSLSession.getPeerSupportedSignatureAlgorithms().

You can create your own X509ExtendedKeyManager subclass in a way similar to that shown in Creating Your Own X509ExtendedTrustManager.

Relationships Between TrustManagers and KeyManagers

Historically, there has been confusion regarding the jobs of TrustManagers and KeyManagers. In summary, here are the primary responsibilities of each manager type:
Type | Function
TrustManager | Determines whether the remote authentication credentials (and thus the connection) should be trusted.
KeyManager | Determines which authentication credentials to send to the remote host.

Secondary Support Classes and Interfaces

These classes are provided as part of the JSSE API to support the creation, use, and management of secure sockets. They are less likely to be used by secure socket applications than are the core and support classes. The secondary support classes and interfaces are part of the javax.net.ssl and javax.security.cert packages.

SSLParameters Class

SSLParameters encapsulates things that affect a TLS connection:

  • The list of ciphersuites to be accepted in an SSL/TLS handshake
  • The list of protocols to be allowed
  • The endpoint identification algorithm during SSL/TLS handshaking
  • The algorithm constraints
  • Whether SSL/TLS servers should request or require client authentication

You can retrieve the current SSLParameters for an SSLSocket or SSLEngine using the following methods:

  • getSSLParameters() in SSLSocket, SSLServerSocket and SSLEngine
  • getDefaultSSLParameters() and getSupportedSSLParamters() in SSLContext

Assign SSLParameters with the setSSLParameters() method in SSLSocket, SSLServerSocket, or SSLEngine.

SSLSessionContext Interface

A javax.net.ssl.SSLSessionContext is a grouping of SSLSessions associated with a single entity. For example, it could be associated with a server or client that participates in many sessions concurrently. The methods on this interface enable the enumeration of all sessions in a context and allow lookup of specific sessions via their session ids.

An SSLSessionContext may optionally be obtained from an SSLSession by calling the SSLSession getSessionContext method. The context may be unavailable in some environments, in which case the getSessionContext method returns null.

SSLSessionBindingListener Interface

javax.net.ssl.SSLSessionBindingListener is an interface implemented by objects which want to be notified when they are being bound or unbound from an SSLSession.

SSLSessionBindingEvent Class

A javax.net.ssl.SSLSessionBindingEvent is the event communicated to an SSLSessionBindingListener when it is bound or unbound from an SSLSession.

HandShakeCompletedListener Interface

javax.net.ssl.HandShakeCompletedListener is an interface implemented by any class which wants to receive notification of the completion of an SSL protocol handshake on a given SSLSocket connection.

HandShakeCompletedEvent Class

A javax.net.ssl.HandShakeCompletedEvent is the event communicated to a HandShakeCompletedListener upon completion of an SSL protocol handshake on a given SSLSocket connection.

HostnameVerifier Interface

If the SSL/TLS implementation's standard hostname verification logic fails, the implementation will call the verify method of the class which implements this interface and is assigned to this HttpsURLConnection instance. If the callback class can determine that the hostname is acceptable given the parameters, it should report that the connection should be allowed. An unacceptable response will cause the connection to be terminated.

For example:

public class MyHostnameVerifier implements HostnameVerifier {

    public boolean verify(String hostname, SSLSession session) {
        // pop up an interactive dialog box
        // or insert additional matching logic
        if (good_address) {
            return true;
        } else {
            return false;
        }
    }
}

//...deleted...

HttpsURLConnection urlc = (HttpsURLConnection)
  (new URL("https://www.sun.com/")).openConnection();
urlc.setHostnameVerifier(new MyHostnameVerifier());
See HttpsURLConnection Class for more information on how to assign the HostnameVerifier to the HttpsURLConnection.

X509Certificate Class

Many secure socket protocols perform authentication using public key certificates, also called X.509 certificates. This is the default authentication mechanism for the SSL and TLS protocols.

The java.security.cert.X509Certificate abstract class provides a standard way to access the attributes of X.509 certificates.

Note: The javax.security.cert.X509Certificate class is supported only for backward compatibility with previous (1.0.x and 1.1.x) versions of JSSE. New applications should use java.security.cert.X509Certificate, not javax.security.cert.X509Certificate.

AlgorithmConstraints Interface

The Java SE 7 release includes an interface, java.security.AlgorithmConstraints, for controlling allowed cryptographic algorithms. AlgorithmConstraints defines three permits() methods. These methods tell whether an algorithm name or a key is permitted for certain cryptographic functions. Cryptographic functions are represented by a set of CryptoPrimitive, which is an enumeration containing fields like STREAM_CIPHER, MESSAGE_DIGEST, SIGNATURE, and more.

Thus, an AlgorithmConstraints implementation can answer questions like "Can I use this key with this algorithm for the purpose of a cryptographic operation?"

An AlgorithmConstraints object can be associated with an SSLParameters object using a new method, setAlgorithmConstraints(). The current AlgorithmConstraints object for an SSLParameters object is retrieved with getAlgorithmConstraints().

Previous (JSSE 1.0.x) Implementation Classes and Interfaces

In previous (1.0.x) versions of JSSE, there was a reference implementation whose classes and interfaces were provided in the com.sun.net.ssl package.

As of v1.4, JSSE has been integrated into the J2SDK. The classes formerly in com.sun.net.ssl have been promoted to the javax.net.ssl package and are now a part of the standard JSSE API.

For compatibility purposes the com.sun.net.ssl classes and interfaces still exist, but have been deprecated. Applications written using them can run in the J2SDK v1.4 and later without being recompiled. This may change in a future release; these classes/interfaces may be removed. Thus, all new applications should be written using the javax classes/interfaces.

For now, applications written using the com.sun.net.ssl API can utilize either JSSE 1.0.2 providers (ones using com.sun.net.ssl) or JSSE providers written for the J2SDK v1.4 and later (ones using the javax API). However, applications written using the JSSE API in the J2SDK 1.4 and later can only utilize JSSE providers written for the J2SDK 1.4 and later. There more recent releases contain some new functionality and attempting to access such functionality on a provider that doesn't supply it wouldn't work. SunJSSE, provided with the JDK from Oracle, is a provider written using the javax API.

You can still obtain a com.sun.net.ssl.HttpsURLConnection if you update the URL search path by setting the java.protocol.handler.pkgs System property as you did when using JSSE 1.0.2. For more information, see Code Using HttpsURLConnection Class... in the Troubleshooting section.

Customizing JSSE

The Installation Directory <java-home>

The term <java-home> is used throughout this document to refer to the directory where the Java SE 6 Runtime Environment (JRE) is installed. It is determined based on whether you are running JSSE on a JRE with or without the Java SDK installed. Java SE 6 SDK includes the JRE, but it is located in a different level in the file hierarchy.

The following are some examples of which directories <java-home> refers to:

  • On Solaris, if the Java SE 6 SDK is installed in /home/user1/jdk1.6.0, then <java-home> is
    /home/user1/jdk1.6.0/jre
  • On Solaris, if JRE is installed in /home/user1/jre1.6.0 and the Java 2 SDK is not installed, then <java-home> is
    /home/user1/jre1.6.0
  • On Microsoft Windows platforms, if the Java SE 6 SDK is installed in C:\jdk1.6.0, then <java-home> is
    C:\j2k1.6.0\jre
  • On Microsoft Windows platforms, if the JRE is installed in C:\jre1.6.0 and the Java SE 6 SDK is not installed, then <java-home> is
    C:\jre1.6.0

Customization

JSSE includes an implementation that all users can utilize. If desired, it is also possible to customize a number of aspects of JSSE, plugging in different implementations or specifying the default keystore, and so on. The table that follows summarizes which aspects can be customized, what the defaults are, and which mechanisms are used to provide customization. The first column of the table provides links to more detailed descriptions of each designated aspect and how to customize it.

Some of the customizations are done by setting system property or security property values. Sections following the table explain how to set such property values.

IMPORTANT NOTE: Many of the properties shown in this table are currently utilized by the JSSE implementation, but there is no guarantee that they will continue to have the same names and types (system or security) or even that they will exist at all in future releases. All such properties are flagged with an "*". They are documented here for your convenience for use with the JSSE implementation.
JSSE Customization

Customizable Item | Default | How To Customize
X509Certificate implementation | X509Certificate implementation from Oracle | cert.provider.x509v1 security property
HTTPS protocol implementation | Implementation from Oracle | java.protocol.handler.pkgs system property
provider implementation | SunJSSE | A security.provider.n= line in security properties file. See description.
default SSLSocketFactory implementation | SSLSocketFactory implementation from Sun Microsystems. | ** ssl.SocketFactory.provider security property
default SSLServerSocketFactory implementation | SSLServerSocketFactory implementation from Sun Microsystems. | ** ssl.ServerSocketFactory.provider security property
default keystore | No default. | * javax.net.ssl.keyStore system property Note that the value NONE may be specified. This setting is appropriate if the keystore is not file-based (for example, it resides in a hardware token).
default keystore password | No default. | * javax.net.ssl.keyStorePassword system property
default keystore provider | No default. | * javax.net.ssl.keyStoreProvider system property
default keystore type | KeyStore.getDefaultType() | * javax.net.ssl.keyStoreType system property
default truststore | jssecacerts, if it exists. Otherwise, cacerts | * javax.net.ssl.trustStore system property
default truststore password | No default. | * javax.net.ssl.trustStorePassword system property
default truststore provider | No default. | * javax.net.ssl.trustStoreProvider system property
default truststore type | KeyStore.getDefaultType() | * javax.net.ssl.trustStoreType system property Note that the value NONE may be specified. This setting is appropriate if the truststore is not file-based (for example, it resides in a hardware token.)
default key manager factory algorithm name | SunX509 | ssl.KeyManagerFactory.algorithm security property
default trust manager factory algorithm name | PKIX | ssl.TrustManagerFactory.algorithm security property
disabled certificate verification cryptographic algorithms | MD2 | jdk.certpath.disabledAlgorithms security property
disabled cipher suite cryptographic algorithms | No default. | jdk.tls.disabledAlgorithms security property
default proxy host | No default. | * https.proxyHost system property
default proxy port | 80 | * https.proxyPort system property
Server Name Indication option | true | * jsse.enableSNIExtension system property. Server Name Indication (SNI) is a TLS extension, defined in RFC 4366. It enables TLS connections to virtual servers, in which multiple servers for different network names are hosted at a single underlying network address. Some very old SSL/TLS vendors may not be able handle SSL/TLS extensions. In this case, set this property to false to disable the SNI extension.
default ciphersuites | Determined by the socket factory. | * https.cipherSuites system property. This contains a comma-separated list of cipher suite names specifying which cipher suites to enable for use on this HttpsURLConnection. See the SSLSocket setEnabledCipherSuites(String[]) method.
default handshaking protocols | Determined by the socket factory | * https.protocols system property. This contains a comma-separated list of protocol suite names specifying which protocol suites to enable on this HttpsURLConnection. See the SSLSocket setEnabledProtocols(String[]) method.
default https port | 443 | * Customize via port field in the https URL.
JCE encryption algorithms used by SunJSSE provider | SunJCE implementations | Give alternate JCE algorithm provider(s) a higher preference order than the SunJCE provider
defaultly sizing buffers for large SSL/TLS packets | No default. | * jsse.SSLEngine.acceptLargeFragments system property By setting this system property to true, SSLSession will size buffers to handle large data packets by default. This may cause applications to allocate unnecessarily large SSLEngine buffers. Instead, applications should dynamically check for buffer overflow conditions and resize buffers as appropriate.
Allow Unsafe SSL/TLS Renegotiations | false | * sun.security.ssl.allowUnsafeRenegotiation system property. Setting this system property to true permits full (unsafe) legacy renegotiation.
Allow Legacy Hello Messages (Renegotiations) | true | * sun.security.ssl.allowLegacyHelloMessages system property. Setting this system property to true allows the peer to handshake without requiring the proper RFC 5746 messages.

* This property is currently used by the JSSE implementation. It is not guaranteed to be examined and used by other implementations. If it is examined by another implementation, that implementation should handle it in the same manner as the JSSE implementation does. There is no guarantee the property will continue to exist or be of the same type (system or security) in future releases.

Note that some items are customized by setting java.lang.System properties while others are customized by setting java.security.Security properties. The following sections explain how to set values for both types of properties.

How to Specify a java.lang.System Property

Some aspects of JSSE may be customized by setting system properties. There are several ways to set these properties:

  • To set a system property statically, use the -D option of the java command. For example, to run an application named MyApp and set the javax.net.ssl.trustStore system property to specify a truststore named "MyCacertsFile", type the following:

    java -Djavax.net.ssl.trustStore=MyCacertsFile MyApp

  • To set a system property dynamically, call the java.lang.System.setProperty method in your code:

    System.setProperty(propertyName, "propertyValue");

    substituting the appropriate property name and value. For example, a setProperty call corresponding to the previous example for setting the javax.net.ssl.trustStore system property to specify a truststore named "MyCacertsFile" would be:

    System.setProperty("javax.net.ssl.trustStore", "MyCacertsFile");

  • In the Java Deployment environment (Plug-In/Web Start), there are several ways to set the system properties. (See Java Rich Internet Applications Development and Deployment for more information.)

    • Use the Java Control Panel to set the Runtime Environment Property on a local/per-VM basis. This creates a local deployment.properties file. Deployers can also distribute a enterprise-wide deployment.properties file by using the deployment.config mechanism. (See Deployment Configuration File and Properties.)

    • To set a property for a specific applet, use the HTML subtag <PARAM> "java_arguments" within the <APPLET> tag. (See java arguments.)

    • To set the property in a specific Java Web Start application or applet using the new Plugin2 (6u10+), use the JNLP "property" sub-element of the "resources" element. (See resources Element.)

How to Specify a java.security.Security Property

Some aspects of JSSE may be customized by setting security properties. You can set a security property either statically or dynamically:

  • To set a security property statically, add a line to the security properties file. The security properties file is located at:
    <java-home>/lib/security/java.security
    where <java-home> refers to the directory where the JRE runtime software is installed, as described in The Installation Directory <java-home>.

    To specify a security property value in the security properties file, you add a line of the following form:

    propertyName=propertyValue

    For example, suppose you want to specify a different key manager factory algorithm name than the "SunX509" default. You do this by specifying the algorithm name as the value of a security property named ssl.KeyManagerFactory.algorithm. Suppose you want to set the value to "MyX509". To do so, place the following in the security properties file:

    ssl.KeyManagerFactory.algorithm=MyX509
  • To set a security property dynamically, call the java.security.Security.setProperty method in your code:
    Security.setProperty(propertyName,
    "propertyValue");
    substituting the appropriate property name and value. For example, a setProperty call corresponding to the previous example for specifying the key manager factory algorithm name would be:
    Security.setProperty("ssl.KeyManagerFactory.algorithm",
    "MyX509");

Customizing the X509Certificate Implementation

The X509Certificate implementation returned by the X509Certificate.getInstance method is by default the implementation from the JSSE implementation.

You can optionally cause a different implementation to be returned. To do so, specify the name (and package) of the alternate implementation's class as the value of a security property named cert.provider.x509v1. For example, if the class is called MyX509CertificateImpl and it appears in the com.cryptox package, you should place the following in the security properties file:

cert.provider.x509v1=com.cryptox.MyX509CertificateImpl

Specifying an Alternate HTTPS Protocol Implementation

You can communicate securely with an SSL-enabled web server by using the "https" URL scheme for the java.net.URL class. The JDK provides a default https URL implementation.

If you want an alternate https protocol implementation to be used, set the java.protocol.handler.pkgs system property to include the new class name. This action causes the specified classes to be found and loaded before the JDK default classes. See the java.net.URL class documentation for details.

Note to previous JSSE users: In past Sun JSSE releases, you had to set the java.protocol.handler.pkgs system property during JSSE installation. This step is no longer required unless you wish to obtain an instance of com.sun.net.ssl.HttpsURLConnection. For more information, see Code Using HttpsURLConnection Class... in the Troubleshooting section.

Customizing the Provider Implementation

The J2SDK 1.4 and later releases come standard with a JSSE Cryptographic Service Provider, or provider for short, named "SunJSSE". Providers are essentially packages that implement one or more engine classes for specific cryptographic algorithms. The JSSE engine classes are SSLContext, KeyManagerFactory, and TrustManagerFactory. For more information on providers and engine classes, see the "Design Principles" and "Concepts" sections of the Java Cryptography Architecture Reference Guide.

In order to be used, a provider must be registered, either statically or dynamically. You do not need to register the "SunJSSE" provider because it is pre-registered. If you want to use other providers, read the following sections to see how to register them.

Registering the Cryptographic Service Provider Statically

You register a provider statically by adding a line of the following form to the security properties file:
security.provider.n=providerClassName

This declares a provider, and specifies its preference order "n". The preference order is the order in which providers are searched for requested algorithms (when no specific provider is requested). The order is 1-based; 1 is the most preferred, followed by 2, and so on.

The providerClassName is the fully qualified name of the provider class. You get this name from the provider vendor.

To register a provider, add the above line to the security properties file, replacing providerClassName with the fully qualified name of the provider class and substituting n with the priority that you would like to assign to the provider.

The standard security provider and the SunJSSE provider shipped with the Java SE 6 platform are automatically registered for you; the following lines appear in the java.security security properties file to register the SunJCE security provider with preference order 5 and the SunJSSE provider with preference order 4:

          security.provider.1=sun.security.pkcs11.SunPKCS11 \
              ${java.home}/lib/security/sunpkcs11-solaris.cfg
          security.provider.2=sun.security.provider.Sun
          security.provider.3=sun.security.rsa.SunRsaSign
          security.provider.4=com.sun.net.ssl.internal.ssl.Provider
          security.provider.5=com.sun.crypto.provider.SunJCE
          security.provider.6=sun.security.jgss.SunProvider
          security.provider.7=com.sun.security.sasl.Provider

To utilize another JSSE provider, add a line registering the alternate provider, giving it whatever preference order you prefer.

You can have more than one JSSE provider registered at the same time. They may include different implementations for different algorithms for different engine classes, or they may have support for some or all of the same types of algorithms and engine classes. When a particular engine class implementation for a particular algorithm is searched for, if no specific provider is specified for the search, the providers are searched in preference order and the implementation from the first provider that supplies an implementation for the specified algorithm is used.

Registering the Cryptographic Service Provider Dynamically

Instead of registering a provider statically, you can add the provider dynamically at runtime by calling the Security.addProvider method at the beginning of your program. For example, to dynamically add a provider whose Provider class name is MyProvider and whose MyProvider class resides in the com.ABC package, you would call:

Security.addProvider(
  new com.ABC.MyProvider());

The Security.addProvider method adds the specified provider to the next available preference position.

This type of registration is not persistent and can only be done by a program with sufficient permissions.

Customizing the Default Key and Trust Stores, Store Types, and Store Passwords

Whenever a default SSLSocketFactory or SSLServerSocketFactory is created (via a call to SSLSocketFactory.getDefault or SSLServerSocketFactory.getDefault), and this default SSLSocketFactory (or SSLServerSocketFactory) comes from the JSSE reference implementation, a default SSLContext is associated with the socket factory. (The default socket factory will come from the JSSE implementation.)

This default SSLContext is initialized with a default KeyManager and a TrustManager. If a keystore is specified by the javax.net.ssl.keyStore system property and an appropriate javax.net.ssl.keyStorePassword system property, then the KeyManager created by the default SSLContext will be a KeyManager implementation for managing the specified keystore. (The actual implementation will be as specified in Customizing the Default Key and Trust Managers.) If no such system property is specified, then the keystore managed by the KeyManager will be a new empty keystore.

Generally, the peer acting as the server in the handshake will need a keystore for its KeyManager in order to obtain credentials for authentication to the client. However, if one of the anonymous cipher suites is selected, the server's KeyManager keystore is not necessary. And, unless the server requires client authentication, the peer acting as the client will not need a KeyManager keystore. Thus, in these situations it may be okay if there is no javax.net.ssl.keyStore system property value defined.

Similarly, if a truststore is specified by the javax.net.ssl.trustStore system property, then the TrustManager created by the default SSLContext will be a TrustManager implementation for managing the specified truststore. In this case, if such a property exists but the file it specifies doesn't, then no truststore is utilized. If no javax.net.ssl.trustStore property exists, then a default truststore is searched for. If a truststore named <java-home>/lib/security/jssecacerts is found, it is used. If not, then a truststore named <java-home>/lib/security/cacerts is searched for and used (if it exists). See The Installation Directory <java-home> for information as to what <java-home> refers to. Finally, if a truststore is still not found, then the truststore managed by the TrustManager will be a new empty truststore.

IMPORTANT NOTE: The JDK ships with a limited number of trusted root certificates in the <java-home>/lib/security/cacerts file. As documented in keytool, it is your responsibility to maintain (that is, add/remove) the certificates contained in this file if you use this file as a truststore.

Depending on the certificate configuration of the servers you contact, you may need to add additional root certificate(s). Obtain the needed specific root certificate(s) from the appropriate vendor.

If system properties javax.net.ssl.keyStoreType and/or javax.net.ssl.keyStorePassword are also specified, they are treated as the default KeyManager keystore type and password, respectively. If there is no type specified, the default type is that returned by KeyStore.getDefaultType(), which is the value of the keystore.type security property, or "jks" if no such security property is specified. If there is no keystore password specified, it is assumed to be "".

Similarly, if system properties javax.net.ssl.trustStoreType and/or javax.net.ssl.trustStorePassword are also specified, they are treated as the default truststore type and password, respectively. If there is no type specified, the default type is that returned by KeyStore.getDefaultType(). If there is no truststore password specified, it is assumed to be "".

Important Note: This section describes the current JSSE reference implementation behavior. The system properties described in this section are not guaranteed to continue to have the same names and types (system or security) or even to exist at all in future releases. They are also not guaranteed to be examined and used by any other JSSE implementations. If they are examined by an implementation, that implementation should handle them in the same manner as the JSSE reference implementation does, as described herein.

Customizing the Default Key and Trust Managers

As noted in Customizing the Default Key and Trust Stores, Store Types, and Store Passwords, whenever a default SSLSocketFactory or SSLServerSocketFactory is created, and this default SSLSocketFactory (or SSLServerSocketFactory) comes from the JSSE reference implementation, a default SSLContext is associated with the socket factory.

This default SSLContext is initialized with a KeyManager and a TrustManager. The KeyManager and/or TrustManager supplied to the default SSLContext will be a KeyManager/TrustManager implementation for managing the specified keystore/truststore, as described in the aforementioned section.

The KeyManager implementation chosen is determined by first examining the

ssl.KeyManagerFactory.algorithm
security property. If such a property value is specified, a KeyManagerFactory implementation for the specified algorithm is searched for. The implementation from the first provider that supplies an implementation is used. Its getKeyManagers method is called to determine the KeyManager to supply to the default SSLContext. (Technically, getKeyManagers returns an array of KeyManagers, one KeyManager for each type of key material.) If there is no such security property value specified, the default value of "SunX509" is used to perform the search. Note: A KeyManagerFactory implementation for the "SunX509" algorithm is supplied by the SunJSSE provider. The KeyManager it specifies is a javax.net.ssl.X509KeyManager implementation.

Similarly, the TrustManager implementation chosen is determined by first examining the

ssl.TrustManagerFactory.algorithm
security property. If such a property value is specified, a TrustManagerFactory implementation for the specified algorithm is searched for. The implementation from the first provider that supplies an implementation is used. Its getTrustManagers method is called to determine the TrustManager to supply to the default SSLContext. (Technically, getTrustManagers returns an array of TrustManagers, one TrustManager for each type of trust material.) If there is no such security property value specified, the default value of "PKIX" is used to perform the search. Note: A TrustManagerFactory implementation for the "PKIX" algorithm is supplied by the SunJSSE provider. The TrustManager it specifies is a javax.net.ssl.X509TrustManager implementation.

Important Note: This section describes the current JSSE reference implementation behavior. The system properties described in this section are not guaranteed to continue to have the same names and types (system or security) or even to exist at all in future releases. They are also not guaranteed to be examined and used by any other JSSE implementations. If they are examined by an implementation, that implementation should handle them in the same manner as the JSSE reference implementation does, as described herein.

Disabled Cryptographic Algorithms

The cryptographic hash algorithm MD2 is no longer considered secure. The Java SE 7 release includes two new security properties and a new API that support disabling specific cryptographic algorithms.

The jdk.tls.disabledAlgorithms property applies to TLS handshaking, while the jdk.certpath.disabledAlgorithms property applies to certification path processing.

For example, the default value of jdk.certpath.disabledAlgorithms is MD2. This means that any certificate signed with MD2 is not acceptable.

Each security property contains a list of cryptographic algorithms that will not be used during certification path processing. The exact syntax of the properties is described in the jre/lib/security/java.security file, but is briefly summarized here.

The security property contains a list of cryptographic algorithms that must not be used. The algorithm names are separated by commas. Furthermore, you can also specify certain key sizes that cannot be used.

For example, the following line in java.security specifies that the MD2 and DSA algorithms must not be used for certification path processing. Furthermore, RSA is disabled for key sizes less than 2048 bits.

jdk.certpath.disabledAlgorithms=MD2, DSA, RSA keySize < 2048

Customizing the Encryption Algorithm Providers

As of the Java SE 5 release, the SunJSSE provider uses the SunJCE implementation for all its cryptographic needs. While it is recommended that you leave the Sun provider at its regular position, you can use implementations from other JCA/JCE providers by registering them before the SunJCE provider. The standard JCA mechanism can be used to configure providers, either statically via the security properties file

<java-home>/lib/security/java.security
or dynamically via the addProvider or insertProviderAt method in the java.security.Security class. (See The Installation Directory <java-home> for information about what <java-home> refers to.)

Note for People Implementing Providers

The transformation strings used when SunJSSE calls Cipher.getInstance() are "RSA/ECB/PKCS1Padding", "RC4", "DES/CBC/NoPadding", and "DESede/CBC/NoPadding". For further information on the Cipher class and transformation strings see the Cryptography Specification.

Transport Layer Security (TLS) Renegotiation Issue

Introduction

In the Fall of 2009, a flaw was discovered in the SSL/TLS protocols. A fix to the protocol was developed by the IETF TLS Working Group, and current versions of the JDK contain this fix. This section describes the situation in much more detail, along with interoperability issues when communicating with the older implementations which to not contain this protocol fix.

The vulnerability allowed for Man-In-The-Middle (MITM) type attacks where chosen plain text could be injected as a prefix to a TLS connection. This vulnerability does not allow an attacker to decrypt or modify the intercepted network communication once the client and server have successfully negotiated a session between themselves. This vulnerability has been disclosed at:

  • Authentication Gap in TLS Renegotiation - posted on Marsh Ray's blog, Extended Subset, November 5th, 2009.

and additional information is available at:

  • CVE-2009-3555 - posted on Mitre's Common Vulnerabilities and Exposures List, 2009.
  • Understanding the TLS Renegotiation Attack - posted on Eric Rescorla's blog, Educated Guesswork, November 5th, 2009.

Phased Approach To Fixing This Issue

The fix for this issue was handled in two phases:

  • Phase 1: Until a protocol fix could be developed, an interim fix which disabled SSL/TLS renegotiations by default, was made available in the March 30, 2010 Java SE and Java for Business Critical Patch Update.

  • Phase 2: The IETF issued RFC 5746 which addresses the renegotiation protocol flaw. A fix which implements RFC 5746 and supports secure renegotiation is included in the following releases:

JDK Family | Vulnerable Releases | Phase 1 Fix (Disable Reneg.) | Phase 2 Fix (RFC 5746)
JDK and JRE 6 | Update 18 and earlier | Updates 19-21 | Update 22
JDK and JRE 5.0 | Update 23 and earlier | Updates 24-25 | Update 26
SDK and JRE 1.4.2 | Update 25 and earlier | Updates 26-27 | Update 28

NOTE: In the Phase 2 default configuration, there is no impact to applications that do not require renegotiations. Applications that require a renegotiation (e.g. web servers that initially allow for anonymous client browsing, but later require SSL/TLS authenticated clients):

  • will not be impacted if the peer is also RFC 5746-compliant.
  • will be impacted if the peer has not been upgraded to RFC 5746 (see next section for details).

Description of Phase 2 Fix

The SunJSSE implementation reenables renegotiations by default for connections to RFC 5746 compliant peers. That is, both the client and server must support RFC 5746 in order to securely renegotiate. SunJSSE provides some interoperability modes for connections with peers that have not been upgraded, but users are strongly encouraged to update both their client and server implementations as soon as possible.

With the Phase 2 fix, SunJSSE now has three "renegotiation interoperability modes." Each mode fully supports RFC 5746's secure renegotiation, but has these added semantics when communicating with an unupgraded peer:

  1. Strict mode: Requires both client and server be upgraded to RFC 5746 and send the proper RFC 5746 messages. If not, the initial (or subsequent) handshaking will fail and the connection will be terminated.

  2. Interoperable mode (default) : Use of the proper RFC 5746 messages is optional, however legacy (original SSL/TLS specifications) renegotiations are disabled if the proper messages are not used. Initial legacy connections are still allowed, but legacy renegotiations are disabled. This is the best mix of security and interoperability, and is the default setting.

  3. Insecure mode: Permits full legacy renegotiation. Most interoperable with legacy peers but vulnerable to the original MITM attack.

The mode distinctions above only affect a connection with an unupgraded peer. Ideally, strict (full RFC 5746) mode should be used for all clients/servers, however it will take some time for all deployed SSL/TLS implementations to support RFC 5746, thus the interoperable mode will be the default for now.

Here is some additional interoperability information:

Client | Server | Mode
Updated | Updated | Secure Renegotiation in all modes.
Legacy[1] Updated
  • Strict: If clients do not send the proper RFC 5746 messages, initial connections will immediately be terminated by the server (SSLHandshakeException/handshake_failure).
  • Interoperable: Initial connections from legacy clients allowed (missing RFC 5746 messages), but renegotiations will not be allowed by the server. [2][3]
  • Insecure: Connections and renegotiations with legacy clients are allowed, but are vulnerable to the original MITM attack.
Updated Legacy[1]
  • Strict: If the server does not respond with the proper RFC 5746 messages, the client will immediately terminate the connection (SSLHandshakeException/handshake_failure).
  • Interoperable: The client will not require the proper initial RFC 5746 message from the server, but renegotiations will not be allowed by the client. [2][3]
  • Insecure: Connections and renegotiations with legacy clients are allowed, but are vulnerable to the original MITM attack.
Legacy[1] | Legacy[1] | Existing SSL/TLS behavior, vulnerable to the MITM attack.

[1] Legacy means the original SSL/TLS specifications (i.e. non-RFC 5746).

[2] SunJSSE Phase 1 implementations (see above) reject renegotiations unless specifically reenabled. If renegotiations are reenabled, they will be treated as Legacy by the RFC 5746-compliant peer since they do not send the proper RFC 5746 messages.

[3] In SSL/TLS, renegotiations can be initiated by either side. Like the Phase 1 fix, applications communicating with an unupgraded peer in Interoperable mode and that attempt to initiate renegotiation (via SSLSocket.startHandshake() or SSLEngine.beginHandshake()) will receive a SSLHandshakeException (IOException) and the connection will be shutdown (handshake_failure). Applications that receive a renegotiation request from a non-upgraded peer will respond according to the type of connection in place:

  • TLSv1: A warning Alert message of type "no_renegotiation(100)" will be sent to the peer and the connection will remain open. Older versions of SunJSSE will shutdown the connection when a "no_renegotiation" Alert is received.
  • SSLv3: The application will receive a SSLHandshakeException, and the connection will be closed (handshake_failure). ("no_renegotiation" is not defined in the SSLv3 spec.)

To set these modes, two system properties are used:

  • sun.security.ssl.allowUnsafeRenegotiation Introduced in Phase 1, this controls whether legacy (unsafe) renegotiations are permitted.
  • sun.security.ssl.allowLegacyHelloMessages Introduced in Phase 2, this allows the peer to handshake without requiring the proper RFC 5746 messages.
mode | allowLegacyHelloMessages | allowUnsafeRenegotiation
Strict | false | false
Interoperable (default) | true | false
Insecure | true | true

WARNING: It is not recommended to re-enable the insecure SSL/TLS renegotiation, as the vulnerability is once again present.

For information on how to configure a specific mode by setting a system property, see How to Specify a java.lang.System Property.

Workarounds/Alternatives to SSL/TLS Renegotiation

All peers should be updated to RFC 5746-compliant implementation as soon as possible. Even with this RFC 5746 fix, communications with unupgraded peers will be impacted if a renegotiation is necessary. Here are a few suggested options:

  • Restructure the peer to not require renegotiation.

    Renegotiations are typically used by web servers that initially allow for anonymous client browsing but later require SSL/TLS authenticated clients, or which may initially allow weak ciphersuites but later need stronger ones. The alternative is to require client authentication/strong ciphersuites during the initial negotiation. There are a couple of options for doing so:

    • If an application has a "browse mode" until a certain point is reached and a renegotiation is required, one can restructure the server to eliminate the "browse mode" and require all initial connections be strong.

    • Another alternative is to break the server into two entities, with the "browse mode" occuring on server, and a second for the more secure mode. When the point is reached, transfer any relevent information between the servers and.

    Both of these options couple require a fair amount of work, but will not reopen the original hole.

  • Set renegotiation interoperability mode to "insecure" using the system properties (see above for information and warnings).

\

Implementation Details

RFC 5746 defines two new data structures which are mentioned here for advanced users:

  • a new pseudo-ciphersuite called the Signaling Cipher Suite Value (SCSV), "TLS_EMPTY_RENEGOTIATION_INFO_SCSV", and
  • a new TLS extension called the "Renegotiation Info" (RI).

Either of these can be used to signal that an implementation is RFC 5746-compliant and can perform secure renegotiations. Please see the IETF email discussion from November 2009 to February 2010 for the relevant technical discussions.

RFC 5746 allows for clients to send either a SCSV or RI in the first ClientHello. For maximum interoperability, SunJSSE will use the SCSV by default, as a few TLS and SSL servers do not handle unknown extensions correctly. The presence of the SCSV in the enabled Cipher Suites (i.e. SSLSocket.setEnabledCipherSuites()/SSLEngine.setEnabledCipherSuites() will determine whether the SCSV is sent in the initial ClientHello, or if an RI should be sent instead.

SSLv2 does not support SSL/TLS extensions. If the SSLv2Hello protocol is enabled, SCSV will be sent in the initial ClientHello.

Description of the Phase 1 Fix

As mentioned above, the Phase 1 Fix was to disable renegotiations by default until a RFC 5746-compliant fix could be developed. Renegotiations could be reenabled by setting the sun.security.ssl.allowUnsafeRenegotiation system property. The Phase 2 fix uses the same system property, with the addition of the sun.security.ssl.allowUnsafeRenegotiation system property to require the use of RFC 5746 messages.

All applications should upgrade to the Phase 2 RFC 5746 fix as soon as possible.

JCE and Hardware Acceleration/Smartcard Support

Use of JCE

The Java Cryptography Extension (JCE) is a set of packages that provides a framework and implementations for encryption, key generation and key agreement, and Message Authentication Code (MAC) algorithms. Prior to Java SE 5, the SunJSSE provider could make use of JCE providers when configured to do so, but it still contained internal cryptographic code that did not use JCE. In Java SE 6, the SunJSSE provider uses JCE exclusively for all of its cryptographic operations and hence, is able to automatically take advantage of JCE features and enhancements, including JCE's newly added support for PKCS#11. This allows the SunJSSE provider in Java SE 6 to be able to use hardware cryptographic accelerators for significant performance improvements and to use Smartcards as keystores for greater flexibility in key and trust management.

Hardware Accelerators

Use of hardware cryptographic accelerators is automatic if JCE has been configured to use the Oracle PKCS#11 provider, which in turn has been configured to use the underlying accelerator hardware. The provider must be configured before any other JCE/JCA providers in the provider list. See the PKCS#11 Guide for details on how to configure the Oracle PKCS#11 provider.

Configuring JSSE to use Smartcards as Keystores and Trust Stores

Support in JCE for PKCS#11 also enables access to Smartcards as a keystore. See the Customization section for details on how to configure the type and location of the keystores to be used by JSSE. To use a Smartcard as a keystore or trust store, set the javax.net.ssl.keyStoreType and javax.net.ssl.trustStoreType system properties, respectively, to "pkcs11", and set the javax.net.ssl.keyStore and javax.net.ssl.trustStore system properties, respectively, to NONE. To specify the use of a specific provider, use the javax.net.ssl.keyStoreProvider and javax.net.ssl.trustStoreProvider system properties (e.g., "SunPKCS11-joe"). By using these properties, you can configure an application that previously depended on these properties to access a file-based keystore to use a Smartcard keystore with no changes to the application.

Some applications request the use of keystores programmatically. These applications can continue to use the existing APIs to instantiate a Keystore and pass it to its key manager and trust manager. If the Keystore instance refers to a PKCS#11 keystore backed by a Smartcard, then the JSSE application will have access to the keys on the Smartcard.

Multiple and Dynamic Keystores

Smartcards (and other removable tokens) have additional requirements for an X509KeyManager. Different Smartcards may be present in a Smartcard reader during the lifetime of a Java application and they may protected using different passwords. The pre-J2SE 5 APIs and the SunX509 key manager do not accomodate these requirements well. As a result, in Java SE 5, new APIs were introduced and a new X509KeyManager implementation was added to the SunJSSE provider.

The java.security.KeyStore.Builder class abstracts the construction and initialization of a KeyStore object. It supports the use of CallbackHandlers for password prompting and can be subclassed to support additional features as desired by an application. For example, it is possible to implement a Builder that allows individual KeyStore entries to be protected with different passwords. The javax.net.ssl.KeyStoreBuilderParameters class then can be used to initialize a KeyManagerFactory using one or more of these Builder objects.

A new X509KeyManager implementation in the SunJSSE provider called "NewSunX509" supports these parameters. If multiple certificates are available, it also makes the effort to pick a certificate with the appropriate key usage and prefers valid to expired certificates

Here is an example of how to tell JSSE to use both a PKCS#11 keystore (which might in turn use a Smartcard) and a PKCS#12 file-based keystore.

import javax.net.ssl.*;
import java.security.KeyStore.*;
...

// Specify keystore builder parameters for PKCS#11 keystores
Builder scBuilder = Builder.newInstance("PKCS11", null,
    new CallbackHandlerProtection(myGuiCallbackHandler));

// Specify keystore builder parameters for a specific PKCS#12 keystore
Builder fsBuilder = Builder.newInstance("PKCS12", null,
    new File(pkcsFileName), new PasswordProtection(pkcsKsPassword));

// Wrap them as key manager parameters
ManagerFactoryParameters ksParams =
    new KeyStoreBuilderParameters(
        Arrays.asList(new Builder[] { scBuilder, fsBuilder }));

// Create KeyManagerFactory
KeyManagerFactory factory = KeyManagerFactory.getInstance("NewSunX509");

// Pass builder parameters to factory
factory.init(ksParams);

// Use factory
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(factory.getKeyManagers(), null, null);

Kerberos Cipher Suites

In Java SE 6, the SunJSSE provider has support for Kerberos cipher suites, as described in RFC 2712. The following cipher suites are supported but not enabled by default.
TLS_KRB5_WITH_RC4_128_SHA
TLS_KRB5_WITH_RC4_128_MD5
TLS_KRB5_WITH_3DES_EDE_CBC_SHA
TLS_KRB5_WITH_3DES_EDE_CBC_MD5
TLS_KRB5_WITH_DES_CBC_SHA
TLS_KRB5_WITH_DES_CBC_MD5
TLS_KRB5_EXPORT_WITH_RC4_40_SHA
TLS_KRB5_EXPORT_WITH_RC4_40_MD5
TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA
TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5
To enable use of these cipher suites, you must do so explicitly. See SSLEngine.setEnabledCipherSuites() and SSLSocket.setEnabledCipherSuites() for more information. As with all other SSL/TLS cipher suites, if a cipher suite is not supported by the peer, then it won't be selected during cipher negotiation. Furthermore, if the application and/or server cannot acquire the necessary Kerberos credentials, then the Kerberos cipher suites also will not be selected.

Here is an example of a TLS client that wants to use only the TLS_KRB5_WITH_DES_CBC_SHA cipher suite.

// Create socket
SSLSocketFactory sslsf = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslSocket = (SSLSocket) sslsf.createSocket(tlsServer, serverPort);

// Enable only one cipher suite
String enabledSuites[] = { "TLS_KRB5_WITH_DES_CBC_SHA" };
sslSocket.setEnabledCipherSuites(enabledSuites);

Kerberos Requirements

You must have the Kerberos infrastructure set up in your deployment environment before you can use the Kerberos cipher suites with JSSE. In particular, both the TLS client and server must have accounts set up with the Kerberos Key Distribution Center (KDC). At runtime, if one or more of the Kerberos cipher suites have been enabled, the TLS client and server will acquire their Kerberos credentials associated with their respective account from the KDC. For example, a TLS server running on the machine mach1.imc.org in the Kerberos realm IMC.ORG must have an account with the name host/mach1.imc.org@IMC.ORG and be configured to use the KDC for IMC.ORG. See the Kerberos Requirements document for information about using Kerberos with Java SE .

An application can acquire its Kerberos credentials by using the Java Authentication and Authorization Service (JAAS) and a Kerberos login module. Java SE Development Kit 6 comes with a Kerberos login module. You can use the Kerberos cipher suites with JSSE with, or without JAAS programming, similar to how you can use the Java Generic Security Services (Java GSS) with, or without JAAS programming.

To use it without JAAS programming, you must use the index names "com.sun.net.ssl.server" or "other" for the TLS server JAAS configuration entry and "com.sun.net.ssl.client" or "other" for the TLS client, and set the system property javax.security.auth.useSubjectCredsOnly to false. For example, a TLS server that is not using JAAS programming might have the following JAAS configuration file.

com.sun.net.ssl.server {
  com.sun.security.auth.module.Krb5LoginModule required
        principal="host/mach1.imc.org@IMC.ORG"
        useKeyTab=true
        keyTab=mach1.keytab
        storeKey=true;
};
An example of how to Java GSS and Kerberos without JAAS programming is described in the Java GSS Tutorial. You can adapt it to use JSSE by replacing Java GSS calls with JSSE calls.

To use the Kerberos cipher suites with JAAS programming, you can use any index name because your application is responsible for creating the JAAS LoginContext using the index name, and then wrapping the JSSE calls inside of a Subject.doAs() or Subject.doAsPrivileged() call. An example of how to use JAAS with Java GSS and Kerberos is described in the Java GSS Tutorial. You can adapt it to use JSSE by replacing Java GSS calls with JSSE calls.

If you have trouble using or configuring the JSSE application to use Kerberos, see the Troubleshooting section of the Java GSS Tutorial.

Peer Identity Information

To determine the identity of the peer of an SSL connection, use the getPeerPrincipal() method in the following classes: javax.net.ssl.SSLSession, javax.net.ssl.HttpsURLConnection, and javax.net.HandshakeCompletedEvent. Similarly, to get the identity that was sent to the peer (to identify the local entity), use getLocalPrincipal() in these classes. For X509-based cipher suites, these methods will return an instance of javax.security.auth.x500.X500Principal; for Kerberos cipher suites, these methods will return an instance of javax.security.auth.kerberos.KerberosPrincipal.

Prior to Java SE 5, JSSE applications used getPeerCertificates() and similar methods in javax.net.ssl.SSLSession, javax.net.ssl.HttpsURLConnection, and javax.net.HandshakeCompletedEvent to obtain information about the peer. When the peer does not have any certificates, SSLPeerUnverifiedException is thrown. The behavior of these methods remain unchanged in Java SE 6, which means that if the connection was secured using a Kerberos cipher suite, these methods will throw SSLPeerUnverifiedException.

If the application needs to determine only the identity of the peer or identity sent to the peer, it should use the getPeerPrincipal() and getLocalPrincipal() methods, respectively. It should use getPeerCertificates() and getLocalCertificates() only if it needs to examine the contents of those certificates. Furthermore, it must be prepared to handle the case where an authenticated peer might not have any certificate.

Security Manager

When the security manager has been enabled, in addition to the SocketPermissions needed to communicate with the peer, a TLS client application that uses the Kerberos cipher suites also needs the following permission.
javax.security.auth.kerberos.ServicePermission(serverPrincipal, "initiate");
where serverPrincipal is the Kerberos principal name of the TLS server that the TLS client will be communicating with, such as host/mach1.imc.org@IMC.ORG. A TLS server application needs the following permission.
javax.security.auth.kerberos.ServicePermission(serverPrincipal, "accept");
where serverPrincipal is the Kerberos principal name of the TLS server, such as host/mach1.imc.org@IMC.ORG. If the server or client needs to contact the KDC (for example, if its credentials are not cached locally), it also needs the following permission.
javax.security.auth.kerberos.ServicePermission(tgtPrincipal, "initiate");
where tgtPrincipal is principal name of the KDC, such as krbtgt/IMC.ORG@IMC.ORG.

Additional Keystore Formats (PKCS12)

The PKCS#12 (Personal Information Exchange Syntax Standard) specifies a portable format for storage and/or transport of a user's private keys, certificates, miscellaneous secrets, and other items. The SunJSSE provider supplies a complete implementation of the PKCS12 java.security.KeyStore format for reading and write pkcs12 files. This format is also supported by other toolkits and applications for importing and exporting keys and certificates, such as Netscape/Mozilla, Microsoft's Internet Explorer, and OpenSSL. For example, these implementations can export client certificates and keys into a file using the ".p12" filename extension.

With the SunJSSE provider, you can access PKCS12 keys through the KeyStore API with a keystore type of "pkcs12" (or "PKCS12", the name is case-insensitive). In addition, you can list the installed keys and associated certificates using the keytool command with the -storetype option set to pkcs12. (See Security Tools for information about keytool.)

Troubleshooting

Configuration Problems

CertificateException: (while handshaking)

Problem: When negotiating an SSL connection, the client or server throws a CertificateException.

Cause 1: This is generally caused by the remote side sending a certificate that is unknown to the local side.

Solution 1: The best way to debug this type of problem is to turn on debugging (see Debugging Utilities) and watch as certificates are loaded and when certificates are received via the network connection. Most likely, the received certificate is unknown to the trust mechanism because the wrong trust file was loaded. Refer the following sections for more information:

  • Relationship Between Classes
  • TrustManager Interface
  • KeyManager Interface

Cause 2: The system clock is not set correctly.

Solution 2: If the clock is not set correctly, the perceived time may be outside the validity period on one of the certificates, and unless the certificate can be replaced with a valid one from a truststore, the system must assume that the certificate is invalid, and therefore throw the exception.

java.security.KeyStoreException: TrustedCertEntry not supported

Problem: Attempt to store trusted certificates in PKCS12 keystore throws java.security.KeyStoreException: TrustedCertEntry not supported.

Cause 1: We do not support storing trusted certificates in pkcs12 keystore. PKCS12 is mainly used to deliver private keys with the associated cert chains. It does not have any notion of "trusted" certificates. Note that in terms of interoperability, other pkcs12 vendors have the same restriction. Browsers such as Mozilla and Internet Explorer do not accept a pkcs12 file with only trusted certs.

Solution 1: Use JKS (or JCEKS) keystore for storing trusted certificates.

Runtime Exception: SSL Service Not Available

Problem: When running a program that uses JSSE, an exception occurs indicating that an SSL service is not available. For example, an exception similar to one of the following occurs:

    Exception in thread "main"
        java.net.SocketException: no SSL Server Sockets

    Exception in thread "main":
        SSL implementation not available

Cause: There was a problem with SSLContext initialization, for example due to an incorrect password on a keystore or a corrupted keystore. (Note: A JDK vendor once shipped a keystore in an unknown format, and that caused this type of error.)

Solution: Check initialization parameters. Ensure any keystores specified are valid and that the passwords specified are correct. (One way you can check these things is by trying to use the keytool to examine the keystore(s) and the relevant contents.)

Exception, "No available certificate corresponding to the SSL cipher suites which are enabled"

Problem: When I try to run a simple SSL Server program, the following exception is thrown:

Exception in thread "main" javax.net.ssl.SSLException:
No available certificate corresponding to the SSL
cipher suites which are enabled...

Cause: Various cipher suites require certain types of key material. For example, if an RSA cipher suite is enabled, an RSA keyEntry must be available in the keystore. If no such key is available, this cipher suite cannot be used. If there are no available key entries for all of the cipher suites enabled, this exception is thrown.

Solution: Create key entries for the various cipher suite types, or use an anonymous suite. (Be aware that anonymous ciphersuites are inherently dangerous because they are vulnerable to "man-in-the-middle" attacks, see RFC 2246.) Refer to the following sections to learn how to pass the correct keystore and certificates:

  • Relationship Between Classes
  • Customizing the Default Key and Trust Stores, Store Types, and Store Passwords
  • Additional Keystore Formats

Runtime Exception: No Cipher Suites in Common

Problem 1: When handshaking, the client and/or server throw this exception.

Cause 1: Both sides of an SSL connection must agree on a common ciphersuite. If the intersection of the client's ciphersuite set with the server's ciphersuite set is empty, then you will see this exception.

Solution 1: Configure the enabled cipher suites to include common ciphersuites, and be sure to provide an appropriate keyEntry for asymmetric ciphersuites. (See Exception, "No available certificate..." in this section.)

Problem 2: When using Netscape Navigator or Microsoft Internet Explorer (IE) to access files on a server that only has DSA-based certificates, a runtime exception occurs indicating that there are no cipher suites in common.

Cause 2: By default, keyEntries created with keytool use DSA public keys. If only DSA keyEntries exist in the keystore, only DSA-based ciphersuites can be used. By default, Navigator and IE send only RSA-based ciphersuites. Since the intersection of client and server ciphersuite sets is empty, this exception is thrown.

Solution 2: To interact with Navigator or IE, you should create certificates that use RSA-based keys. To do this, you need to specify the -keyalg RSA option when using keytool. For example:

    keytool -genkeypair -alias duke \
        -keystore testkeys -keyalg rsa

Slowness of the First JSSE Access

Problem: JSSE seems to stall on the first access.

Cause: JSSE must have a secure source of random numbers. The initialization takes a while.

Solution: Provide an alternate generator of random numbers, or initialize ahead of time when the overhead won't be noticed:

SecureRandom sr = new SecureRandom();
sr.nextInt();
SSLContext.init(..., ..., sr);
The <java-home>/lib/security/java.security file also provides a way to specify the source of seed data for SecureRandom: see the file for more information.

Code Using HttpsURLConnection Class Throws ClassCastException in JSSE 1.0.x

Problem: The following code snippet was written using JSSE 1.0.x's com.sun.net.ssl.HttpsURLConnection.

import com.sun.net.ssl.*;
...deleted...
HttpsURLConnection urlc = new URL("https://foo.com/").openConnection();
When running under this release, this code returns a javax.net.ssl.HttpsURLConnection and throws a ClassCastException.

Cause: By default, opening an "https" URL will create a javax.net.ssl.HttpsURLConnection.

Solution: Previous releases of the JDK (now known as the Java SE 6 SDK) did not ship with an "https" URL implemention. The JSSE 1.0.x implementation did provide such an "https" URL handler, and the installation guide described how to set the URL handler search path to obtain a JSSE 1.0.x com.sun.net.ssl.HttpsURLConnection implementation.

In this release, there is now an "https" handler in the default URL handler search path. It returns an instance of javax.net.ssl.HttpsURLConnection. By prepending the old JSSE 1.0.x implementation path to the URL search path via the java.protocol.handler.pkgs variable, you can still obtain a com.sun.net.ssl.HttpsURLConnection, and the code will no longer throw cast exceptions.

% java -Djava.protocol.handler.pkgs=\
  com.sun.net.ssl.internal.www.protocol YourClass
or
System.setProperty("java.protocol.handler.pkgs",
                   "com.sun.net.ssl.internal.www.protocol");

Socket Disconnected after Sending ClientHello Message

Problem: A socket attempts to connect, sends a ClientHello message, and is immediately disconnected.

Cause: Some SSL/TLS servers will disconnect if a ClientHello message is received in a format it doesn't understand or with a protocol version number that it doesn't support.

Solution: Try adjusting the protocols in SSLSocket.setEnabledProtocols. For example, some older server implementations speak only SSLv3 and do not understand TLS. Ideally, these implementations should negotiate to SSLv3, but some simply hangup. For backwards compatibility, some server implementations (such as SunJSSE) can send SSLv3/TLS ClientHellos encapsulated in a SSLv2 ClientHello packet. The SunJSSE provider supports this feature, but it is not enabled by default. If you wish to use this feature, call setEnabledProtocols to enable SSLv2Hello, which is the sending of encapsulated SSLv2 ClientHellos.

SunJSSE can not find a JCA/JCE provider which supports a required algorithm and causes NoSuchAlgorithmException

Problem: A handshake is attempted, and fails when it can not find a required algorithm. Examples might include:

Exception in thread ...deleted...
     ...deleted...
     Caused by java.security.NoSuchAlgorithmException: Cannot find any
provider supporting RSA/ECB/PKCS1Padding
or
     Caused by java.security.NoSuchAlgorithmException: Cannot find any
provider supporting AES/CBC/NoPadding

Cause: SunJSSE uses JCE for all its cryptographic algorithms. By default, the Oracle JDK will use the Standard Extension ClassLoader to load the SunJCE provider located in <java-home>/lib/ext/sunjce_provider.jar. If the file can't be found or loaded, or if the SunJCE provider has been deregistered from the Provider mechanism and an alternate implementation from JCE isn't available, this exception will be seen.

Solution: Ensure the SunJCE is available by checking the file is loadable and that the provider is registered with the Provider interface. Try to run the following code in the context of your SSL connection.

    import javax.crypto.*;

    System.out.println("=====Where did you get AES=====");
    Cipher c = Cipher.getInstance("AES/CBC/NoPadding");
    System.out.println(c.getProvider());

Debugging Utilities

JSSE provides dynamic debug tracing support. This is similar to the support used for debugging access control failures in the Java SE 6 platform. The generic Java dynamic debug tracing support is accessed with the system property java.security.debug, while the JSSE-specific dynamic debug tracing support is accessed with the system property javax.net.debug.

Note: The debug utility is not an officially supported feature of JSSE.

To view the options of the JSSE dynamic debug utility, use the following command-line option on the java command:

    -Djavax.net.debug=help

Note: If you specify the value help with either dynamic debug utility when running a program that does not use any classes that the utility was designed to debug, you will not get the debugging options.

Here is a complete example of how to get a list of the debug options:

    java -Djavax.net.debug=help MyApp
where MyApp is an application that uses some of the JSSE classes. MyApp will not run after the debug help information is printed, as the help code causes the application to exit.

Here are the current options:

        all        turn on all debugging
        ssl        turn on ssl debugging

        The following can be used with ssl:
            record          enable per-record tracing
            handshake       print each handshake message
            keygen          print key generation data
            session         print session activity
            defaultctx      print default SSL initialization
            sslctx          print SSLContext tracing
            sessioncache    print session cache tracing
            keymanager      print key manager tracing
            trustmanager    print trust manager tracing

        handshake debugging can be widened with:
            data            hex dump of each handshake message
            verbose         verbose handshake message printing

        record debugging can be widened with:
            plaintext       hex dump of record plaintext
            packet          print raw SSL/TLS packets
The javax.net.debug property value must specify either all or ssl, optionally followed by debug specifiers. You can use one or more options. You do not have to have a separator between options, although a separator such as ":" or "," helps readability. It doesn't matter what separators you use, and the ordering of the option keywords is also not important.

For an introduction on reading this debug information, please refer to the guide, Debugging SSL/TLS Connections.

Examples

  • To view all debugging messages:
    java -Djavax.net.debug=all MyApp
  • To view the hexadecimal dumps of each handshake message, you can type the following, where the colons are optional:
    java -Djavax.net.debug=ssl:handshake:data MyApp
  • To view the hexadecimal dumps of each handshake message, and to print trust manager tracing, you can type the following, where the commas are optional:
    java -Djavax.net.debug=SSL,handshake,data,trustmanager MyApp

Code Examples

The sections below describe the following code examples:

  • Converting an Unsecure Socket to a Secure Socket
    • Socket Example Without SSL
    • Socket Example With SSL
  • Running the JSSE Sample Code
    • Sample Code Illustrating a Secure Socket Connection Between a Client and a Server
      • Configuration Requirements
      • Running SSLSocketClient
      • Running SSLSocketClientWithTunneling
      • Running SSLSocketClientWithClientAuth
      • Running ClassFileServer
      • Running SSLSocketClientWithClientAuth With ClassFileServer
    • Sample Code Illustrating HTTPS Connections
      • Running URLReader
      • Running URLReaderWithOptions
    • Sample Code Illustrating a Secure RMI Connection
    • Sample Code Illustrating the Use of an SSLEngine
      • Running SSLEngineSimpleDemo
      • Running the NIO-based server

  • Creating a Keystore to Use with JSSE
    • Creating a Simple Keystore and Truststore

Converting an Unsecure Socket to a Secure Socket

This section provides examples of source code that illustrate how to use JSSE to convert an unsecure socket connection to a secure socket connection. The code in this section is excerpted from the book Java SE 6 Network Security by Marco Pistoia, et. al.

First, "Socket Example Without SSL" shows sample code that can be used to set up communication between a client and a server using unsecure sockets. This code is then modified in "Socket Example With SSL" to use JSSE to set up secure socket communication.

Socket Example Without SSL

Server Code for Unsecure Socket Communications

When writing a Java program that acts as a server and communicates with a client using sockets, the socket communication is set up with code similar to the following:

import java.io.*;
import java.net.*;

. . .

int port = availablePortNumber;

ServerSocket s;

try {
    s = new ServerSocket(port);
    Socket c = s.accept();

    OutputStream out = c.getOutputStream();
    InputStream in = c.getInputStream();

    // Send messages to the client through
    // the OutputStream
    // Receive messages from the client
    // through the InputStream
}

catch (IOException e) {
}

Client Code for Unsecure Socket Communications

The client code to set up communication with a server using sockets is similar to the following:

import java.io.*;
import java.net.*;

. . .

int port = availablePortNumber;
String host = "hostname";

try {
    s = new Socket(host, port);

    OutputStream out = s.getOutputStream();
    InputStream in = s.getInputStream();

    // Send messages to the server through
    // the OutputStream
    // Receive messages from the server
    // through the InputStream
}

catch (IOException e) {
}

Socket Example With SSL

Server Code for Secure Socket Communications

When writing a Java program that acts as a server and communicates with a client using secure sockets, the socket communication is set up with code similar to the following. Differences between this program and the one for communication using unsecure sockets are highlighted in bold.

import java.io.*;
import javax.net.ssl.*;

. . .

int port = availablePortNumber;

SSLServerSocket s;

try {
    SSLServerSocketFactory sslSrvFact =
        (SSLServerSocketFactory)
        SSLServerSocketFactory.getDefault();
    s =(SSLServerSocket)sslSrvFact.createServerSocket(port);

    SSLSocket c = (SSLSocket)s.accept();

    OutputStream out = c.getOutputStream();
    InputStream in = c.getInputStream();

    // Send messages to the client through
    // the OutputStream
    // Receive messages from the client
    // through the InputStream
}

catch (IOException e) {
}

Client Code for Secure Socket Communications

The client code to set up communication with a server using secure sockets is similar to the following, where differences with the unsecure version are highlighted in bold:

import java.io.*;
import javax.net.ssl.*;

. . .

int port = availablePortNumber;
String host = "hostname";

try {
    SSLSocketFactory sslFact =
      (SSLSocketFactory)SSLSocketFactory.getDefault();
    SSLSocket s =
      (SSLSocket)sslFact.createSocket(host, port);

    OutputStream out = s.getOutputStream();
    InputStream in = s.getInputStream();

    // Send messages to the server through
    // the OutputStream
    // Receive messages from the server
    // through the InputStream
}

catch (IOException e) {
}

Running the JSSE Sample Code

The JSSE sample programs illustrate how to use JSSE to:

  • Create a secure socket connection between a client and a server
  • Create a secure connection to an HTTPS Web site
  • Use secure communications with RMI
  • Illustrate SSLEngine usage

When using the sample code, be aware that the sample programs are designed to illustrate how to use JSSE. They are not designed to be robust applications.

Note: Setting up secure communications involves complex algorithms. The sample programs provide no feedback during the setup process. When running the programs, be patient: you may not see any output for a while. If you run the programs with the system property javax.net.debug set to all, you will see more feedback. For an introduction on reading this debug information, refer to the guide, Debugging SSL/TLS Connections.

Where to Find the Sample Code

Most of the sample code is located in the samples subdirectory of the same directory as that containing the document you are reading. Follow that link to see a listing of all the samples files and to link to the text files. That page also has a zip file you can download to obtain all the samples files, which is helpful if you are viewing this documentation from the web.

The sections below describe the samples. See the README for further information.

Sample Code Illustrating a Secure Socket Connection Between a Client and a Server

The sample programs in the samples/sockets directory illustrate how to set up a secure socket connection between a client and a server.

When running the sample client programs, you can communicate with an existing server, such as a commercial Web server, or you can communicate with the sample server program, ClassFileServer. You can run the sample client and the sample server programs on different machines connected to the same network, or you can run them both on one machine but from different terminal windows.

All the sample SSLSocketClient* programs in the samples/sockets/client directory (and URLReader* programs described in Sample Code Illustrating HTTPS Connections) can be run with the ClassFileServer sample server program. An example of how to do this is shown in Running SSLSocketClientWithClientAuth with ClassFileServer. You can make similar changes in order to run URLReader, SSLSocketClient or SSLSocketClientWithTunneling with ClassFileServer.

If an authentication error occurs while attempting to send messages between the client and the server (whether using a web server or ClassFileServer), it is most likely because the necessary keys are not in the truststore (trust key database). For example, the ClassFileServer uses a keystore called "testkeys" containing the private key for "localhost" as needed during the SSL handshake. ("testkeys" is included in the same samples/sockets/server directory as the ClassFileServer source.) If the client cannot find a certificate for the corresponding public key of "localhost" in the truststore it consults, an authentication error will occur. Be sure to use the samplecacerts truststore (which contains "localhost"s public key/cert), as described in the next section.

Configuration Requirements

When running the sample programs that create a secure socket connection between a client and a server, you will need to make the appropriate certificates file (truststore) available. For both the client and the server programs, you should use the certificates file samplecacerts from the samples directory. Using this certificates file will allow the client to authenticate the server. The file contains all the common Certification Authority certificates shipped with the JDK (in the cacerts file), plus a certificate for "localhost" needed by the client to authenticate "localhost" when communicating with the sample server ClassFileServer. (ClassFileServer uses a keystore containing the private key for "localhost" which corresponds to the public key in samplecacerts. )

To make the samplecacerts file available to both the client and the server, you can either copy it to the file <java-home>/lib/security/jssecacerts, rename it cacerts and use it to replace the <java-home>/lib/security/cacerts file, or add the following option to the command line when running the java command for both the client and the server:

-Djavax.net.ssl.trustStore=path_to_samplecacerts_file

(See The Installation Directory <java-home> for information about what <java-home> refers to.)

The password for the samplecacerts truststore is changeit. You can substitute your own certificates in the samples, using keytool.

If you use a browser, such as Netscape Navigator or Microsoft's Internet Explorer, to access the sample SSL server provided in the ClassFileServer example, a dialog box may pop up with the message that it does not recognize the certificate. This is normal because the certificate used with the sample programs is self-signed and is for testing only. You can accept the certificate for the current session. After testing the SSL server, you should exit the browser, which deletes the test certificate from the browser's namespace.

For client authentication, a separate "duke" certificate is available in the appropriate directories. The public key/certificate is also stored in the samplecacerts file.

Running SSLSocketClient

The SSLSocketClient.java program demonstrates how to create a client to use an SSLSocket to send an HTTP request and to get a response from an HTTPS server. The output of this program is the HTML source for https://www.verisign.com/index.html.

You must not be behind a firewall to run this program as shipped. If you run it from behind a firewall, you will get an UnknownHostException because JSSE can't find a path through your firewall to www.verisign.com. To create an equivalent client that can run from behind a firewall, set up proxy tunneling as illustrated in the sample program SSLSocketClientWithTunneling.

Running SSLSocketClientWithTunneling

The SSLSocketClientWithTunneling.java program illustrates how to do proxy tunneling to access a secure web server from behind a firewall. To run this program, you must set the following Java system properties to the appropriate values:

java -Dhttps.proxyHost=webproxy
-Dhttps.proxyPort=ProxyPortNumber
SSLSocketClientWithTunneling

Note: Proxy specifications with the -D options (shown in blue) are optional. Also, be sure to replace webproxy with the name of your proxy host and ProxyPortNumber with the appropriate port number.

The program will return the HTML source file from https://www.verisign.com/index.html.

Running SSLSocketClientWithClientAuth

The SSLSocketClientWithClientAuth.java program shows how to set up a key manager to do client authentication if required by a server. This program also assumes that the client is not outside a firewall. You can modify the program to connect from inside a firewall by following the example in SSLSocketClientWithTunneling.

To run this program, you must specify three parameters: host, port, and requested file path. To mirror the previous examples, you can run this program without client authentication by setting the host to www.verisign.com, the port to 443, and the requested file path to https://www.verisign.com/. The output when using these parameters is the HTML for the Web site https://www.verisign.com/.

To run SSLSocketClientWithClientAuth to do client authentication, you must access a server that requests client authentication. You can use the sample program ClassFileServer as this server. This is described in the following sections.

Running ClassFileServer

The program referred to herein as ClassFileServer is made up of two files, ClassFileServer.java and ClassServer.java.

To execute them, run ClassFileServer.class, which requires the following parameters:

  • port - The port parameter can be any available unused port number, for example, you can use the number 2001.
  • docroot - This parameter indicates the directory on the server that contains the file you wish to retrieve. For example, on Solaris, you can use /home/userid/ (where userid refers to your particular user id), while on Microsoft Windows systems, you can use c:\.
  • TLS - This is an optional parameter. When used, it indicates that the server is to use SSL or TLS.
  • true - This is an optional parameter. When used, client authentication is required. This parameter is only consulted if the TLS parameter is set.

Note 1: The TLS and true parameters are optional. If you leave them off, indicating that just an ordinary (not TLS) file server should be used, without authentication, nothing happens. This is because one side (the client) is trying to negotiate with TLS, while the other (the server) isn't, so they can't communicate.

Note 2: The server expects GET requests in the form "GET /...", where "..." is the path to the file.

Running SSLSocketClientWithClientAuth With ClassFileServer

You can use the sample programs SSLSocketClientWithClientAuth and ClassFileServer to set up authenticated communication, where the client and server are authenticated to each other. You can run both sample programs on different machines connected to the same network, or you can run them both on one machine but from different terminal windows or command prompt windows. To set up both the client and the server, do the following:

  1. Run the program ClassFileServer from one machine or terminal window, as described in Running ClassFileServer.
  2. Run the program SSLSocketClientWithClientAuth on another machine or terminal window. SSLSocketClientWithClientAuth requires the following parameters:
    • host - This is the hostname of the machine you are using to run ClassFileServer.
    • port - This is the same port you specified for ClassFileServer.
    • requestedfilepath - This parameter indicates the path to the file you want to retrieve from the server. You must give this parameter as /filepath. Forward slashes are required in the file path because it is used as part of a GET statement, which requires forward slashes regardless of what type of operating system you are running. The statement is formed as
      "GET " + requestedfilepath + " HTTP/1.0"
NOTE: you can modify the other SSLClient* application's "GET" commands to connect to a local machine running ClassFileServer.

Sample Code Illustrating HTTPS Connections

There are two primary APIs for accessing secure communications through JSSE. One way is through a socket-level API which can be used for arbitrary secure communications, as illustrated by the SSLSocketClient, SSLSocketClientWithTunneling, and SSLSocketClientWithClientAuth (with and without ClassFileServer) sample programs.

A second, and often simpler way, is through the standard Java URL API. You can communicate securely with an SSL-enabled web server by using the "https" URL protocol or scheme using the java.net.URL class.

Support for "https" URL schemes is implemented in many of the common browsers, which allows access to secured communications without requiring the socket-level API provided with JSSE.

An example URL might be:

"https://www.verisign.com"

The trust and key management for the "https" URL implementation is environment-specific. The JSSE implementation provides an "https" URL implementation. If you want a different https protocol implementation to be used, you can set the java.protocol.handler.pkgs system property to the package name. See the java.net.URL class documentation for details.

The samples that you can download with JSSE include two sample programs that illustrate how to create an HTTPS connection. Both of these sample programs, URLReader.java and URLReaderWithOptions.java are in the urls directory.

Running URLReader

The URLReader.java program illustrates using the URL class to access a secure site. The output of this program is the HTML source for https://www.verisign.com/. By default, the HTTPS protocol implementation included with JSSE will be utilized. If you want to use a different implementation, you must set the system property java.protocol.handler.pkgs value to be the name of the package containing the implementation.

If you are running the sample code behind a firewall, you must set the system properties https.proxyHost and https.proxyPort. For example, to use the proxy host "webproxy" on port 8080, you can use the following options to the java command:

-Dhttps.proxyHost=webproxy
-Dhttps.proxyPort=8080

Alternatively, you can set the system properties within the source code with the java.lang.System method setProperty. For example, instead of using the command line options, you can include the following lines in your program:

System.setProperty("java.protocol.handler.pkgs",
    "com.ABC.myhttpsprotocol");

System.setProperty("https.proxyHost",
    "webproxy");

System.setProperty("https.proxyPort",
    "8080");

Note: When running on Windows 95 or Windows 98, the maximum number of characters allowed in an MS-DOS prompt may not be enough to include all the command-line options. If you encounter this problem, either create a .bat file with the entire command or add the system properties to the source code and recompile the source code.

Running URLReaderWithOptions

The URLReaderWithOptions.java program is essentially the same as URLReader, except that it allows you to optionally input any or all of the following system properties as arguments to the program when you run it:

  • java.protocol.handler.pkgs
  • https.proxyHost
  • https.proxyPort
  • https.cipherSuites

To run URLReaderWithOptions, type the following command (all on one line):

java URLReaderWithOptions
     [-h proxyhost -p proxyport]
     [-k protocolhandlerpkgs]
     [-c ciphersarray]
     myApp

Note: Multiple protocol handlers can be included in the protocolhandlerpkgs in a list with items separated by vertical bars. Multiple SSL cipher suite names can be included in the ciphersarray in a list with items separated by commas. The possible cipher suite names are the same as those returned by the call SSLSocket.getSupportedCipherSuites(). The suite names are taken from the SSL and TLS protocol specifications.

You only need a protocolhandlerpkgs argument if you want to use an HTTPS protocol handler implementation other than the default one provided by Oracle.

If you are running behind a firewall, you must include arguments for the proxy host and the proxy port. Additionally, you can include a list of cipher suites to enable.

Here is an example of running URLReaderWithOptions and specifying the proxy host "webproxy" on port 8080:

java URLReaderWithOptions
    -h webproxy -p 8080

Sample Code Illustrating a Secure RMI Connection

The sample code in the samples/rmi directory illustrates how to create a secure RMI connection. The sample code is based on an RMI example that is basically a "Hello World" example modified to install and use a custom RMI socket factory.

For more information about RMI, see the Java RMI documentation. This Web page points to RMI tutorials and other information about RMI.

Sample Code Illustrating the Use of an SSLEngine

SSLEngine was introduced in the Java SE 5 release of the Java 2 Platform to give application developers flexibility when choosing I/O and compute strategies. Rather than tie the SSL/TLS implementation to a specific I/O abstraction (such as single-threaded SSLSockets), SSLEngine removes the I/O and compute constraints from the SSL/TLS implementation.

As mentioned earlier, SSLEngine is an advanced API, and is not appropriate for casual use. Some introductary sample code is provided here that helps illustrate its use. The first demo removes most of the I/O and threading issues, and focuses on many of the SSLEngine methods. The second demo is a more realistic example showing how SSLEngine might be combined with Java NIO to create a rudimentary HTTP/HTTPS server.

Running SSLEngineSimpleDemo

The SSLEngineSimpleDemo is a very simple application that focuses on the operation of the SSLEngine while simplifying the I/O and threading issues. This application creates two SSLEngines which exchange SSL/TLS messages via common ByteBuffers. A single loop serially performs all of the engine operations and demonstrates how a secure connection is established (handshaking), how application data is transferred, and how the engine is closed.

The SSLEngineResult provides a great deal of information about the SSLEngine's current state. This example doesn't examine all of the states. It simplifies the I/O and threading issues to the point that this is not a good example for a production environment; nonetheless, it is useful to demonstrate the overall function of the SSLEngine.

Running the NIO-based Server

Note: The server example discussed in this section is included in the Java SE Development Kit 6. You can find the code bundled in the <jdk-home>/samples/nio/server directory.
To fully exploit the flexibility provided by SSLEngine, one must first understand complementary API's such as I/O and threading models.

An I/O model that large-scale application developers find of use is NIO SocketChannels. NIO was introduced in part to solve some of the scaling problem inherent in the java.net.Socket API. SocketChannels have many different modes of operation including:

  • blocking
  • nonblocking
  • nonblocking with Selectors
Sample code for a bare-bones HTTP server is provided that not only demonstrates many of the new NIO APIs, and also shows how SSLEngine can be employed to create a secure HTTPS server. The server is not production quality, but does show many of these new APIs in action.

Inside the sample directory is a README.txt file which introduces the server, explains how to build and configure, and provides a brief overview of the code layout. The files of most interest for SSLEngine users are ChannelIO.java and ChannelIOSecure.java.

Creating a Keystore to Use with JSSE

Creating a Simple Keystore and Truststore

In this section, we'll use keytool to create a simple JKS keystore suitable for use with JSSE. We'll make a keyEntry (with public/private keys) in the keystore, then make a corresponding trustedCertEntry (public keys only) in a truststore. (For client authentication, you'll need to do a similar process for the client's certificates.) Note: Storing trust anchors in PKCS12 is not supported. Users should use JKS for storing trust anchors and PKCS12 for private keys. Note: It is beyond the scope of this example to explain each step in detail. If you need more information, please see the keytool documentation for Solaris or Microsoft Windows. User input is shown in boldface font.
  1. Create a new keystore and self-signed certificate with corresponding public/private keys.
    % keytool -genkeypair -alias duke -keyalg RSA \
  -validity 7 -keystore keystore

 Enter keystore password:  password
 What is your first and last name?
 [Unknown]:  Duke
 What is the name of your organizational unit?
 [Unknown]:  Java Software
 What is the name of your organization?
 [Unknown]:  Oracle, Inc.
 What is the name of your City or Locality?
 [Unknown]:  Palo Alto
 What is the name of your State or Province?
 [Unknown]:  CA
 What is the two-letter country code for this unit?
 [Unknown]:  US
 Is CN=Duke, OU=Java Software, O="Oracle, Inc.",
 L=Palo Alto, ST=CA, C=US correct?
 [no]:  yes

 Enter key password for <duke>
  (RETURN if same as keystore password):  <CR>
    This is the keystore that the server will use.
  2. Examine the keystore. Notice the entry type is keyEntry which means that this entry has a private key associated with it (shown in red).
    % keytool -list -v -keystore keystore
Enter keystore password:  password

Keystore type: jks
Keystore provider: SUN

Your keystore contains 1 entry

Alias name: duke
Creation date: Dec 20, 2001
Entry type: keyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Duke, OU=Java Software, O="Oracle, Inc.",
L=Palo Alto, ST=CA, C=US
Issuer: CN=Duke, OU=Java Software, O="Oracle, Inc.", L=Palo Alto, ST=CA, C=US
Serial number: 3c22adc1
Valid from: Thu Dec 20 19:34:25 PST 2001 until: Thu Dec 27 19:34:25 PST 2001
Certificate fingerprints:
    MD5: F1:5B:9B:A1:F7:16:CF:25:CF:F4:FF:35:3F:4C:9C:F0
    SHA1: B2:00:50:DD:B6:CC:35:66:21:45:0F:96:AA:AF:6A:3D:E4:03:7C:74
  3. Export and examine the self-signed certificate.
    % keytool -export -alias duke -keystore keystore -rfc \
  -file duke.cer
Enter keystore password:  password
Certificate stored in file <duke.cer>
% cat duke.cer
-----BEGIN CERTIFICATE-----
MIICXjCCAccCBDwircEwDQYJKoZIhvcNAQEEBQAwdjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNB
MRIwEAYDVQQHEwlQYWxvIEFsdG8xHzAdBgNVBAoTFlN1biBNaWNyb3N5c3RlbXMsIEluYy4xFjAU
BgNVBAsTDUphdmEgU29mdHdhcmUxDTALBgNVBAMTBER1a2UwHhcNMDExMjIxMDMzNDI1WhcNMDEx
MjI4MDMzNDI1WjB2MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVBhbG8gQWx0
bzEfMB0GA1UEChMWU3VuIE1pY3Jvc3lzdGVtcywgSW5jLjEWMBQGA1UECxMNSmF2YSBTb2Z0d2Fy
ZTENMAsGA1UEAxMERHVrZTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1loObJzNXsi5aSr8
N4XzDksD6GjTHFeqG9DUFXKEOQetfYXvA8F9uWtz8WInrqskLTNzwXgmNeWkoM7mrPpK6Rf5M3G1
NXtYzvxyi473Gh1h9k7tjJvqSVKO7E1oFkQYeUPYifxmjbSMVirWZgvo2UmA1c76oNK+NhoHJ4qj
eCUCAwEAATANBgkqhkiG9w0BAQQFAAOBgQCRPoQYw9rWWvfLPQuPXowvFmuebsTc28qI7iFWm6BJ
TT/qdmzti7B5MHOt9BeVEft3mMeBU0CS2guaBjDpGlf+zsK/UUi1w9C4mnwGDZzqY/NKKWtLxabZ
5M+4MAKLZ92ePPKGpobM2CPLfM8ap4IgAzCbBKd8+CMp8yFmifze9Q==
-----END CERTIFICATE-----
    Alternatively, you could generate Certificate Signing Request (CSR) with -certreq and send that to a Certificate Authority (CA) for signing, but again, that's beyond the scope of this example.
  4. Import the certificate into a new truststore.
    % keytool -import -alias dukecert -file duke.cer \
  -keystore truststore
Enter keystore password:  trustword
Owner: CN=Duke, OU=Java Software, O="Oracle, Inc.", L=Palo Alto, ST=CA, C=US
Issuer: CN=Duke, OU=Java Software, O="Oracle, Inc.", L=Palo Alto, ST=CA, C=US
Serial number: 3c22adc1
Valid from: Thu Dec 20 19:34:25 PST 2001 until: Thu Dec 27 19:34:25 PST 2001
Certificate fingerprints:
    MD5: F1:5B:9B:A1:F7:16:CF:25:CF:F4:FF:35:3F:4C:9C:F0
    SHA1: B2:00:50:DD:B6:CC:35:66:21:45:0F:96:AA:AF:6A:3D:E4:03:7C:74
Trust this certificate? [no]:  yes
Certificate was added to keystore
  5. Examine the truststore. Note that the entry type is trustedCertEntry, which means that a private key is not available for this entry (shown in red). It also means that this file is not suitable as a KeyManager's keystore.
    % keytool -list -v -keystore truststore
Enter keystore password:  trustword

Keystore type: jks
Keystore provider: SUN

Your keystore contains 1 entry

Alias name: dukecert
Creation date: Dec 20, 2001
Entry type: trustedCertEntry

Owner: CN=Duke, OU=Java Software, O="Oracle, Inc.", L=Palo Alto, ST=CA, C=US
Issuer: CN=Duke, OU=Java Software, O="Oracle, Inc.", L=Palo Alto, ST=CA, C=US
Serial number: 3c22adc1
Valid from: Thu Dec 20 19:34:25 PST 2001 until: Thu Dec 27 19:34:25 PST 2001
Certificate fingerprints:
    MD5: F1:5B:9B:A1:F7:16:CF:25:CF:F4:FF:35:3F:4C:9C:F0
    SHA1: B2:00:50:DD:B6:CC:35:66:21:45:0F:96:AA:AF:6A:3D:E4:03:7C:74
    Now run your applications with the appropriate key stores. This example assumes the default X509KeyManager and X509TrustManager are used, thus we will select the keystores using the system properties described in Customization.
    % java -Djavax.net.ssl.keyStore=keystore \
  -Djavax.net.ssl.keyStorePassword=password Server

% java -Djavax.net.ssl.trustStore=truststore \
  -Djavax.net.ssl.trustStorePassword=trustword Client

Note: In this example, we authenticated the server only. If client authentication is desired, you will need to provide a similar keystore for the client's keys, and an appropriate truststore for the server.

Appendix A: Standard Names

The JDK Security API requires and uses a set of standard names for algorithms, certificate and keystore types. The specification names previously found here in Appendix A and in the other security specifications (JCA/CertPath/etc.) have been combined in the Standard Names document. Specific provider information can be found in the Oracle Provider Documentation.

Appendix B: Provider Pluggability

JSSE in Java SE 6 is fully pluggable and does not restrict the use of third party JSSE providers in any way.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


jstack - Stack Trace

  • Synopsis
  • Parameters
  • Description
  • Options
  • See Also
  • Known Bugs

SYNOPSIS

jstack [ option ] pid
jstack [ option ] executable core
jstack [ option ] [server-id@]remote-hostname-or-IP

PARAMETERS

Options are mutually exclusive. Option, if used, should follow immediately after the command name. See OPTIONS.

pid
process id for which the stack trace is to be printed. The process must be a Java process. To get a list of Java processes running on a machine, jps may be used.
executable
Java executable from which the core dump was produced.

core
core file for which the stack trace is to be printed.

remote-hostname-or-IP
remote debug server's (see jsadebugd) hostname or IP address.

server-id
optional unique id, if multiple debug servers are running on the same remote host.

DESCRIPTION

jstack prints Java stack traces of Java threads for a given Java process or core file or a remote debug server. For each Java frame, the full class name, method name, 'bci' (byte code index) and line number, if available, are printed. With the -m option, jstack prints both Java and native frames of all threads along with the 'pc' (program counter). For each native frame, the closest native symbol to 'pc', if available, is printed. C++ mangled names are not demangled. To demangle C++ names, the output of this command may be piped to c++filt. If the given process is running on a 64-bit VM, you may need to specify the -J-d64 option, e.g.:

jstack -J-d64 -m pid

NOTE - This utility is unsupported and may or may not be available in future versions of the JDK. In Windows Systems where dbgeng.dll is not present, 'Debugging Tools For Windows' needs to be installed to have these tools working. Also, PATH environment variable should contain the location of jvm.dll used by the target process or the location from which the Crash Dump file was produced.

For example, set PATH=<jdk>\jre\bin\client;%PATH%

OPTIONS

-F
Force a stack dump when 'jstack [-l] pid' does not respond.
-l
Long listing. Prints additional information about locks such as list of owned java.util.concurrent ownable synchronizers.
-m
prints mixed mode (both Java and native C/C++ frames) stack trace.
-h
prints a help message.

-help
prints a help message

SEE ALSO

  • pstack(1)
  • c++filt(1)
  • jps
  • jsadebugd

KNOWN BUGS

Mixed mode stack trace, the -m option, does not work with the remote debug server.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


jstat - Java Virtual Machine Statistics Monitoring Tool

  • Synopsis
  • Parameters
  • Description
  • Virtual Machine Identifier
  • Options
    • General Options
    • Output Options
  • Examples
  • See Also

SYNOPSIS

jstat [ generalOption | outputOptions vmid [interval[s|ms] [count]] ]

PARAMETERS

generalOption
A single general command-line option (-help, -options, or -version)
outputOptions
One or more output options, consisting of a single statOption, plus any of the -t, -h, and -J options.
vmid
Virtual machine identifier, a string indicating the target Java virtual machine (JVM). The general syntax is
[protocol:][//]lvmid[@hostname[:port]/servername]
The syntax of the vmid string largely corresponds to the syntax of a URI. The vmid can vary from a simple integer representing a local JVM to a more complex construction specifying a communications protocol, port number, and other implementation-specific values. See Virtual Machine Identifier for details.
interval[s|ms]
Sampling interval in the specified units, seconds (s) or milliseconds (ms). Default units are milliseconds. Must be a positive integer. If specified, jstat will produce its output at each interval.
count
Number of samples to display. Default value is infinity; that is, jstat displays statistics until the target JVM terminates or the jstat command is terminated. Must be a positive integer.

DESCRIPTION

The jstat tool displays performance statistics for an instrumented HotSpot Java virtual machine (JVM). The target JVM is identified by its virtual machine identifier, or vmid option described below.

NOTE: This utility is unsupported and may not be available in future versions of the JDK. It is not currently available on Windows 98 and Windows ME. platforms.

VIRTUAL MACHINE IDENTIFIER

The syntax of the vmid string largely corresponds to the syntax of a URI:

[protocol:][//]lvmid[@hostname][:port][/servername]
protocol
The communications protocol. If the protocol is omitted and a hostname is not specified, the default protocol is a platform specific optimized local protocol. If the protocol is omitted and a hostname is specified, then the default protocol is rmi.
lvmid
The local virtual machine identifier for the target JVM. The lvmid is a platform-specific value that uniquely identifies a JVM on a system. The lvmid is the only required component of a virtual machine identifier. The lvmid is typically, but not necessarily, the operating system's process identifier for the target JVM process. You can use the jps command to determine the lvmid. Also, you can determine lvmid on Unix platforms with the ps command, and on Windows with the Windows Task Manager.
hostname
A hostname or IP address indicating the target host. If hostname is omitted, then the target host is the local host.
port
The default port for communicating with the remote server. If the hostname is omitted or the protocol specifies an optimized, local protocol, then port is ignored. Otherwise, treatment of the port parameter is implementation specific. For the default rmi protocol, the port indicates the port number for the rmiregistry on the remote host. If port is omitted, and protocol indicates rmi, then the default rmiregistry port (1099) is used.
servername
The treatment of this parameter depends on implementation. For the optimized local protocol, this field is ignored. For the rmi protocol, it represents the name of the RMI remote object on the remote host.

OPTIONS

The jstat command supports two types of options, general options and output options. General options cause jstat to display simple usage and version information. Output options determine the content and format of the statistical output.

NOTE: All options, and their functionality are subject to change or removal in future releases.

GENERAL OPTIONS

If you specify one of the general options, you cannot specify any other option or parameter.

-help
Display help message.
-version
Display version information.
-options
Display list of statistics options. See the Output Options section below.

OUTPUT OPTIONS

If you do not specify a general option, then you can specify output options. Output options determine the content and format of jstat's output, and consist of a single statOption, plus any of the other output options (-h, -t, and -J). The statOption must come first.

Output is formatted as a table, with columns are separated by spaces. A header row with titles describes the columns. Use the -h option to set the frequency at which the header is displayed. Column header names are generally consistent between the different options. In general, if two options provide a column with the same name, then the data source for the two columns are the same.

Use the -t option to display a time stamp column, labeled Timestamp as the first column of output. The Timestamp column contains the elapsed time, in seconds, since startup of the target JVM. The resolution of the time stamp is dependent on various factors and is subject to variation due to delayed thread scheduling on heavily loaded systems.

Use the interval and count parameters to determine how frequently and how many times, respectively, jstat displays its output.

NOTE: You are advised not to write scripts to parse jstat's output since the format may change in future releases. If you choose to write scripts that parse jstat output, expect to modify them for future releases of this tool.

-statOption
Determines the statistics information that jstat displays. The following table lists the available options. Use the -options general option to display the list of options for a particular platform installation.

Option | Displays...
class | Statistics on the behavior of the class loader.
compiler | Statistics of the behavior of the HotSpot Just-in-Time compiler.
gc | Statistics of the behavior of the garbage collected heap.
gccapacity | Statistics of the capacities of the generations and their corresponding spaces.
gccause | Summary of garbage collection statistics (same as -gcutil), with the cause of the last and current (if applicable) garbage collection events.
gcnew | Statistics of the behavior of the new generation.
gcnewcapacity | Statistics of the sizes of the new generations and its corresponding spaces.
gcold | Statistics of the behavior of the old and permanent generations.
gcoldcapacity | Statistics of the sizes of the old generation.
gcpermcapacity | Statistics of the sizes of the permanent generation.
gcutil | Summary of garbage collection statistics.
printcompilation | HotSpot compilation method statistics.
-h n
Display a column header every n samples (output rows), where n is a positive integer. Default value is 0, which displays the column header above the first row of data.
-t n
Display a timestamp column as the first column of output. The timestamp is the time since the start time of the target JVM.
-J javaOption
Pass javaOption to the java application launcher. For example, -J-Xms48m sets the startup memory to 48 megabytes. For a complete list of options, see java - the Java application launcher

STATOPTIONS AND OUTPUT

The following tables summarize the columns that jstat outputs for each statOption.

-class Option

Class Loader Statistics
Column | Description
Loaded | Number of classes loaded.
Bytes | Number of Kbytes loaded.
Unloaded | Number of classes unloaded.
Bytes | Number of Kbytes unloaded.
Time | Time spent performing class load and unload operations.

-compiler Option

HotSpot Just-In-Time Compiler Statistics
Column | Description
Compiled | Number of compilation tasks performed.
Failed | Number of compilation tasks that failed.
Invalid | Number of compilation tasks that were invalidated.
Time | Time spent performing compilation tasks.
FailedType | Compile type of the last failed compilation.
FailedMethod | Class name and method for the last failed compilation.

-gc Option

Garbage-collected heap statistics
Column | Description
S0C | Current survivor space 0 capacity (KB).
S1C | Current survivor space 1 capacity (KB).
S0U | Survivor space 0 utilization (KB).
S1U | Survivor space 1 utilization (KB).
EC | Current eden space capacity (KB).
EU | Eden space utilization (KB).
OC | Current old space capacity (KB).
OU | Old space utilization (KB).
PC | Current permanent space capacity (KB).
PU | Permanent space utilization (KB).
YGC | Number of young generation GC Events.
YGCT | Young generation garbage collection time.
FGC | Number of full GC events.
FGCT | Full garbage collection time.
GCT | Total garbage collection time.

-gccapacity Option

Memory Pool Generation and Space Capacities
Column | Description
NGCMN | Minimum new generation capacity (KB).
NGCMX | Maximum new generation capacity (KB).
NGC | Current new generation capacity (KB).
S0C | Current survivor space 0 capacity (KB).
S1C | Current survivor space 1 capacity (KB).
EC | Current eden space capacity (KB).
OGCMN | Minimum old generation capacity (KB).
OGCMX | Maximum old generation capacity (KB).
OGC | Current old generation capacity (KB).
OC | Current old space capacity (KB).
PGCMN | Minimum permanent generation capacity (KB).
PGCMX | Maximum Permanent generation capacity (KB).
PGC | Current Permanent generation capacity (KB).
PC | Current Permanent space capacity (KB).
YGC | Number of Young generation GC Events.
FGC | Number of Full GC Events.

-gccause Option

This option displays the same summary of garbage collection statistics as the -gcutil option, but includes the causes of the last garbage collection event and (if applicable) the current garbage collection event. In addition to the columns listed for -gcutil, this option adds the following columns:

Garbage Collection Statistics, Including GC Events
Column | Description
LGCC | Cause of last Garbage Collection.
GCC | Cause of current Garbage Collection.

-gcnew Option

New Generation Statistics
Column | Description
S0C | Current survivor space 0 capacity (KB).
S1C | Current survivor space 1 capacity (KB).
S0U | Survivor space 0 utilization (KB).
S1U | Survivor space 1 utilization (KB).
TT | Tenuring threshold.
MTT | Maximum tenuring threshold.
DSS | Desired survivor size (KB).
EC | Current eden space capacity (KB).
EU | Eden space utilization (KB).
YGC | Number of young generation GC events.
YGCT | Young generation garbage collection time.

-gcnewcapacity Option

New Generation Space Size Statistics
Column | Description
NGCMN | Minimum new generation capacity (KB).
NGCMX | Maximum new generation capacity (KB).
NGC | Current new generation capacity (KB).
S0CMX | Maximum survivor space 0 capacity (KB).
S0C | Current survivor space 0 capacity (KB).
S1CMX | Maximum survivor space 1 capacity (KB).
S1C | Current survivor space 1 capacity (KB).
ECMX | Maximum eden space capacity (KB).
EC | Current eden space capacity (KB).
YGC | Number of young generation GC events.
FGC | Number of Full GC Events.

-gcold Option

Old and Permanent Generation Statistics
Column | Description
PC | Current permanent space capacity (KB).
PU | Permanent space utilization (KB).
OC | Current old space capacity (KB).
OU | old space utilization (KB).
YGC | Number of young generation GC events.
FGC | Number of full GC events.
FGCT | Full garbage collection time.
GCT | Total garbage collection time.

-gcoldcapacity Option

Old Generation Statistics
Column | Description
OGCMN | Minimum old generation capacity (KB).
OGCMX | Maximum old generation capacity (KB).
OGC | Current old generation capacity (KB).
OC | Current old space capacity (KB).
YGC | Number of young generation GC events.
FGC | Number of full GC events.
FGCT | Full garbage collection time.
GCT | Total garbage collection time.

-gcpermcapacity Option

Permanent Generation Statistics
Column | Description
PGCMN | Minimum permanent generation capacity (KB).
PGCMX | Maximum permanent generation capacity (KB).
PGC | Current permanent generation capacity (KB).
PC | Current permanent space capacity (KB).
YGC | Number of young generation GC events.
FGC | Number of full GC events.
FGCT | Full garbage collection time.
GCT | Total garbage collection time.

-gcutil Option

Summary of Garbage Collection Statistics
Column | Description
S0 | Survivor space 0 utilization as a percentage of the space's current capacity.
S1 | Survivor space 1 utilization as a percentage of the space's current capacity.
E | Eden space utilization as a percentage of the space's current capacity.
O | Old space utilization as a percentage of the space's current capacity.
P | Permanent space utilization as a percentage of the space's current capacity.
YGC | Number of young generation GC events.
YGCT | Young generation garbage collection time.
FGC | Number of full GC events.
FGCT | Full garbage collection time.
GCT | Total garbage collection time.

-printcompilation Option

HotSpot Compiler Method Statistics
Column | Description
Compiled | Number of compilation tasks performed.
Size | Number of bytes of bytecode for the method.
Type | Compilation type.
Method | Class name and method name identifying the compiled method. Class name uses "/" instead of "." as namespace separator. Method name is the method within the given class. The format for these two fields is consistent with the HotSpot - XX:+PrintComplation option.

EXAMPLES

This section presents some examples of monitoring a local JVM with a lvmid of 21891.

Using the gcutil option

This example attaches to lvmid 21891 and takes 7 samples at 250 millisecond intervals and displays the output as specified by the -gcutil option.

jstat -gcutil 21891 250 7

  S0     S1     E      O      P     YGC    YGCT    FGC    FGCT     GCT

 12.44   0.00  27.20   9.49  96.70    78    0.176     5    0.495    0.672

 12.44   0.00  62.16   9.49  96.70    78    0.176     5    0.495    0.672

 12.44   0.00  83.97   9.49  96.70    78    0.176     5    0.495    0.672

  0.00   7.74   0.00   9.51  96.70    79    0.177     5    0.495    0.673

  0.00   7.74  23.37   9.51  96.70    79    0.177     5    0.495    0.673

  0.00   7.74  43.82   9.51  96.70    79    0.177     5    0.495    0.673

  0.00   7.74  58.11   9.51  96.71    79    0.177     5    0.495    0.673

The output of this example shows that a young generation collection occurred between the 3rd and 4th sample. The collection took 0.001 seconds and promoted objects from the eden space (E) to the old space (O), resulting in an increase of old space utilization from 9.49% to 9.51%. Before the collection, the survivor space was 12.44% utilized, but after this collection it is only 7.74% utilized.

Repeating the column header string

This example attaches to lvmid 21891 and takes samples at 250 millisecond intervals and displays the output as specified by -gcutil option. In addition, it uses the -h3 option to output the column header after every 3 lines of data.

jstat -gcnew -h3 21891 250

 S0C    S1C    S0U    S1U   TT MTT  DSS      EC       EU     YGC     YGCT

  64.0   64.0    0.0   31.7 31  31   32.0    512.0    178.6    249    0.203

  64.0   64.0    0.0   31.7 31  31   32.0    512.0    355.5    249    0.203

  64.0   64.0   35.4    0.0  2  31   32.0    512.0     21.9    250    0.204

 S0C    S1C    S0U    S1U   TT MTT  DSS      EC       EU     YGC     YGCT

  64.0   64.0   35.4    0.0  2  31   32.0    512.0    245.9    250    0.204

  64.0   64.0   35.4    0.0  2  31   32.0    512.0    421.1    250    0.204

  64.0   64.0    0.0   19.0 31  31   32.0    512.0     84.4    251    0.204

 S0C    S1C    S0U    S1U   TT MTT  DSS      EC       EU     YGC     YGCT

  64.0   64.0    0.0   19.0 31  31   32.0    512.0    306.7    251    0.204

In addition to showing the repeating header string, this example shows that between the 2nd and 3rd samples, a young GC occurred. Its duration was 0.001 seconds. The collection found enough live data that the survivor space 0 utilization (S0U) would would have exceeded the desired survivor Size (DSS). As a result, objects were promoted to the old generation (not visible in this output), and the tenuring threshold (TT) was lowered from 31 to 2.

Another collection occurs between the 5th and 6th samples. This collection found very few survivors and returned the tenuring threshold to 31.

Including a time stamp for each sample

This example attaches to lvmid 21891 and takes 3 samples at 250 millisecond intervals. The -t option is used to generate a time stamp for each sample in the first column.

jstat -gcoldcapacity -t 21891 250 3

Timestamp          OGCMN        OGCMX         OGC           OC       YGC   FGC    FGCT    GCT

          150.1       1408.0      60544.0      11696.0      11696.0   194    80    2.874   3.799

          150.4       1408.0      60544.0      13820.0      13820.0   194    81    2.938   3.863

          150.7       1408.0      60544.0      13820.0      13820.0   194    81    2.938   3.863

The Timestamp column reports the elapsed time in seconds since the start of the target JVM. In addition, the -gcoldcapacity output shows the old generation capacity (OGC) and the old space capacity (OC) increasing as the heap expands to meet allocation and/or promotion demands. The old generation capacity (OGC) has grown to from 11696 KB to 13820 KB after the 81st Full GC (FGC). The maximum capacity of the generation (and space) is 60544 KB (OGCMX), so it still has room to expand.

Monitor instrumentation for a remote JVM

This example attaches to lvmid 40496 on the system named remote.domain using the -gcutil option, with samples taken every second indefinitely.

jstat -gcutil 40496@remote.domain 1000

... output omitted

The lvmid is combined with the name of the remote host to construct a vmid of 40496@remote.domain. This vmid results in the use of the rmi protocol to communicate to the default jstatd server on the remote host. The jstatd server is located using the rmiregistry on remote.domain that is bound to the default rmiregistry port (port 1099).

SEE ALSO

  • java - the Java Application Launcher
  • jps - the Java Process Status Application
  • jstatd - the jvmstat daemon
  • rmiregistry - the Java Remote Object Registry
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


jstatd - Virtual Machine jstat Daemon

  • Synopsis
  • Parameters
  • Description
  • Options
  • Security
  • Remote Interface
  • Examples
  • See Also

SYNOPSIS

jstatd [ options ]

PARAMETERS

options
Command-line options. The options may be in any order. If there are redundant or contradictory options, the last option specified will take precedence.

DESCRIPTION

The jstatd tool is an RMI server application that monitors for the creation and termination of instrumented HotSpot Java virtual machines (JVMs) and provides a interface to allow remote monitoring tools to attach to JVMs running on the local host.

The jstatd server requires the presence of an RMI registry on the local host. The jstatd server will attempt to attach to the RMI registry on the default port, or on the port indicated by the -p port option. If an RMI registry is not found, one will be created within the jstatd application bound to the port indicated by the -p port option or to the default RMI registry port if -p port is omitted. Creation of an internal RMI registry can be inhibited by specifying the -nr option.

NOTE: This utility is unsupported and may or may not be available in future versions of the JDK. It is not currently available on the Windows 98 and Windows ME platforms.

OPTIONS

The jstatd command supports the following options:

-nr
Do not attempt to create an internal RMI registry within the jstatd process when an existing RMI registry is not found.
-p port
Port number where the RMI registry is expected to be found, or, if not found, created if -nr is not specified.
-n rminame
Name to which the remote RMI object is bound in the RMI registry. The default name is JStatRemoteHost. If multiple jstatd servers are started on the same host, the name of the exported RMI object for each server can be made unique by specifying this option. However, doing so will require that the unique server name be included in the monitoring client's hostid and vmid strings.
-J option
Pass option to the java launcher called by javac. For example, -J-Xms48m sets the startup memory to 48 megabytes. It is a common convention for -J to pass options to the underlying VM executing applications written in Java.

SECURITY

The jstatd server can only monitor JVMs for which it has the appropriate native access permissions. Therefor the jstatd process must be running with the same user credentials as the target JVMs. Some user credentials, such as the root user in UNIX™ based systems, have permission to access the instrumentation exported by any JVM on the system. A jstatd process running with such credentials can monitor any JVM on the system, but introduces additional security concerns.

The jstatd server does not provide any authentication of remote clients. Therefore, running a jstatd server process exposes the instrumentation export by all JVMs for which the jstatd process has access permissions to any user on the network. This exposure may be undesireable in your environment and local security policies should be considered before starting the jstatd process, particularly in production environments or on unsecure networks.

The jstatd server installs an instance of RMISecurityPolicy if no other security manager has been installed and therefore requires a security policy file to be specified. The policy file must conform to the default policy implementation's Policy File Syntax.

The following policy file will allow the jstatd server to run without any security exceptions. This policy is less liberal then granting all permissions to all codebases, but is more liberal than a policy that grants the minimal permissions to run the jstatd server.

grant codebase "file:${java.home}/../lib/tools.jar" {
   permission java.security.AllPermission;
};

To use this policy, copy the text into a file called jstatd.all.policy and run the jstatd server as follows:

jstatd -J-Djava.security.policy=jstatd.all.policy

For sites with more restrictive security practices, it is possible to use a custom policy file to limit access to specific trusted hosts or networks, though such techniques are subject to IP addreess spoofing attacks. If your security concerns cannot be addressed with a customized policy file, then the safest action is to not run the jstatd server and use the jstat and jps tools locally.

REMOTE INTERFACE

The interface exported by the jstatd process is proprietary and is guaranteed to change. Users and developers are discouraged from writing to this interface.

EXAMPLES

Here are some examples of starting jstatd. Note that the jstatd scripts automatically start the server in the background.

Using Internal RMI Registry

This example demonstrates starting jstatd with an internal RMI registry. This example assumes that no other server is bound to the default RMI Registry port (port 1099).

jstatd -J-Djava.security.policy=all.policy

Using External RMI Registry

This example demonstrates starting jstatd with a external RMI registry.

rmiregistry&
jstatd -J-Djava.security.policy=all.policy

This example demonstrates starting jstatd with an external RMI registry server on port 2020.

rmiregistry 2020&
jstatd -J-Djava.security.policy=all.policy -p 2020

This example demonstrates starting jstatd with an external RMI registry on port 2020, bound to name AlternateJstatdServerName.

rmiregistry 2020&
jstatd -J-Djava.security.policy=all.policy -p 2020 -n AlternateJstatdServerName

Inhibiting creation of an in-process RMI registry

This example demonstrates starting jstatd such that it will not create a RMI registry if one is not found. This example assumes an RMI registry is already running. If it is not, an appropriate error message is emitted.

jstatd -J-Djava.security.policy=all.policy -nr

Enabling RMI logging capabilities.

This example demonstrates starting jstatd with RMI logging capabilities enabled. This technique is useful as a troubleshooting aid or for monitoring server activities.

jstatd -J-Djava.security.policy=all.policy -J-Djava.rmi.server.logCalls=true

SEE ALSO

  • java - the Java Application Launcher
  • jps - the Java Process Status Application
  • jstat - the Java Virtual Machine Statistics Monitoring Tool
  • rmiregistry - the Java Remote Object Registry
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


jvisualvm - Java Virtual Machine Monitoring, Troubleshooting, and Profiling Tool

  • Synopsis
  • Parameters
  • Description
  • Options
  • Usage
  • See Also

SYNOPSIS

        jvisualvm [ options ]

PARAMETERS

Options, if used, should follow immediately after the command name. Options may be in any order. For a discussion of parameters that apply to a specific option, see OPTIONS below.

DESCRIPTION

Java VisualVM is an intuitive graphical user interface that provides detailed information about Java technology-based applications (Java applications) while they are running on a given Java Virtual Machine (JVM*). The name Java VisualVM comes from the fact that Java VisualVM provides information about the JVM software visually.

Java VisualVM combines several monitoring, troubleshooting, and profiling utilities into a single tool. For example, most of the functionality offered by the standalone tools jmap, jinfo, jstat and jstack have been integrated into Java VisualVM. Other functionalities, such as some of those offered by the JConsole tool, can be added as optional plug-ins.

OPTIONS

The following option is possible when you launch Java VisualVM.

-J<jvm_option>
Pass this <jvm_option> to the JVM software.

USAGE

Java VisualVM is useful to Java application developers to troubleshoot applications and to monitor and improve the applications' performance. Java VisualVM can allow developers to generate and analyse heap dumps, track down memory leaks, perform and monitor garbage collection, and perform lightweight memory and CPU profiling. Plug-ins also exist that expand the functionality of Java VisualVM. For example, most of the functionality of the JConsole tool is available via the MBeans Tab and JConsole Plug-in Wrapper plug-ins. You can choose from a catalog of standard Java VisualVM plug-ins by selecting 'Tools' | 'Plugins' in the Java VisualVM menus.

Start Java VisualVM with the following command:

%  jvisualvm <options>

SEE ALSO

For more details about Java VisualVM see the following pages.

  • Java VisualVM developers' site
  • Java VisualVM in Java SE platform documentation

(* The terms "Java Virtual Machine" and "JVM" mean a Virtual Machine for the Java platform.)

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JVM(TM) Tool Interface 1.2.1

JVMTM Tool Interface

Version 1.2
  • Introduction
    • What is the JVM Tool Interface?
    • Architecture
    • Writing Agents
    • Deploying Agents
    • Agent Command Line Options
    • Agent Start-Up
    • Agent Start-Up (OnLoad phase)
    • Agent Start-Up (Live phase)
    • Agent Shutdown
    • JAVA_TOOL_OPTIONS
    • Environments
    • Bytecode Instrumentation
    • Modified UTF-8 String Encoding
    • Specification Context
  • Functions
    • Accessing Functions
    • Function Return Values
    • Managing JNI Object References
    • Prerequisite State for Calling Functions
    • Exceptions and Functions
    • Function Index
      • Memory Management
      • Thread
      • Thread Group
      • Stack Frame
      • Force Early Return
      • Heap
      • Heap (1.0)
      • Local Variable
      • Breakpoint
      • Watched Field
      • Class
      • Object
      • Field
      • Method
      • Raw Monitor
      • JNI Function Interception
      • Event Management
      • Extension Mechanism
      • Capability
      • Timers
      • Class Loader Search
      • System Properties
      • General
    • Error Codes
  • Events
    • Event Index
  • Data Types
    • JNI Types Used in the JVM Tool Interface
    • JVM Tool Interface Base Types
    • Structure Type Definitions
    • Function Type Definitions
    • Enumeration Definitions
    • Function Table
  • Constant Index
  • Change History

What is the JVM Tool Interface?

The JVMTM Tool Interface (JVM TI) is a programming interface used by development and monitoring tools. It provides both a way to inspect the state and to control the execution of applications running in the JavaTM virtual machine (VM).

JVM TI is intended to provide a VM interface for the full breadth of tools that need access to VM state, including but not limited to: profiling, debugging, monitoring, thread analysis, and coverage analysis tools.

JVM TI may not be available in all implementations of the JavaTM virtual machine.

JVM TI is a two-way interface. A client of JVM TI, hereafter called an agent, can be notified of interesting occurrences through events. JVM TI can query and control the application through many functions, either in response to events or independent of them.

Agents run in the same process with and communicate directly with the virtual machine executing the application being examined. This communication is through a native interface (JVM TI). The native in-process interface allows maximal control with minimal intrusion on the part of a tool. Typically, agents are relatively compact. They can be controlled by a separate process which implements the bulk of a tool's function without interfering with the target application's normal execution.

Architecture

Tools can be written directly to JVM TI or indirectly through higher level interfaces. The Java Platform Debugger Architecture includes JVM TI, but also contains higher-level, out-of-process debugger interfaces. The higher-level interfaces are more appropriate than JVM TI for many tools. For more information on the Java Platform Debugger Architecture, see the Java Platform Debugger Architecture website.

Writing Agents

Agents can be written in any native language that supports C language calling conventions and C or C++ definitions.

The function, event, data type, and constant definitions needed for using JVM TI are defined in the include file jvmti.h. To use these definitions add the J2SETM include directory to your include path and add
#include <jvmti.h>
to your source code.

Deploying Agents

An agent is deployed in a platform specific manner but is typically the platform equivalent of a dynamic library. On the WindowsTM operating system, for example, an agent library is a "Dynamic Linked Library" (DLL). On the SolarisTM Operating Environment, an agent library is a shared object (.so file).

An agent may be started at VM startup by specifying the agent library name using a command line option. Some implementations may support a mechanism to start agents in the live phase. The details of how this is initiated are implementation specific.

Agent Command Line Options

The term "command-line option" is used below to mean options supplied in the JavaVMInitArgs argument to the JNI_CreateJavaVM function of the JNI Invocation API.

One of the two following command-line options is used on VM startup to properly load and run agents. These arguments identify the library containing the agent as well as an options string to be passed in at startup.
-agentlib:<agent-lib-name>=<options>
The name following -agentlib: is the name of the library to load. Lookup of the library, both its full name and location, proceeds in a platform-specific manner. Typically, the <agent-lib-name> is expanded to an operating system specific file name. The <options> will be passed to the agent on start-up. For example, if the option -agentlib:foo=opt1,opt2 is specified, the VM will attempt to load the shared library foo.dll from the system PATH under WindowsTM or libfoo.so from the LD_LIBRARY_PATH under the SolarisTM operating environment.
-agentpath:<path-to-agent>=<options>
The path following -agentpath: is the absolute path from which to load the library. No library name expansion will occur. The <options> will be passed to the agent on start-up. For example, if the option -agentpath:c:\myLibs\foo.dll=opt1,opt2 is specified, the VM will attempt to load the shared library c:\myLibs\foo.dll.
The start-up routine Agent_OnLoad in the library will be invoked.

Libraries loaded with -agentlib: or -agentpath: will be searched for JNI native method implementations to facilitate the use of Java programming language code in tools, as is needed for bytecode instrumentation.

The agent libraries will be searched after all other libraries have been searched (agents wishing to override or intercept the native method implementations of non-agent methods can use the NativeMethodBind event).

These switches do the above and nothing more - they do not change the state of the VM or JVM TI. No command line options are needed to enable JVM TI or aspects of JVM TI, this is handled programmatically by the use of capabilities.

Agent Start-Up

The VM starts each agent by invoking a start-up function. If the agent is started in the OnLoad phase the function Agent_OnLoad will be invoked. If the agent is started in the live phase the function Agent_OnAttach will be invoked. Exactly one call to a start-up function is made per agent.

Agent Start-Up (OnLoad phase)

If an agent is started during the OnLoad phase then its agent library must export a start-up function with the following prototype:
JNIEXPORT jint JNICALL
Agent_OnLoad(JavaVM *vm, char *options, void *reserved)
The VM will start the agent by calling this function. It will be called early enough in VM initialization that:
  • system properties may be set before they have been used in the start-up of the VM
  • the full set of capabilities is still available (note that capabilities that configure the VM may only be available at this time--see the Capability function section)
  • no bytecodes have executed
  • no classes have been loaded
  • no objects have been created

The VM will call the Agent_OnLoad function with <options> as the second argument - that is, using the command-line option examples, "opt1,opt2" will be passed to the char *options argument of Agent_OnLoad. The options argument is encoded as a modified UTF-8 string. If =<options> is not specified, a zero length string is passed to options. The lifespan of the options string is the Agent_OnLoad call. If needed beyond this time the string or parts of the string must be copied. The period between when Agent_OnLoad is called and when it returns is called the OnLoad phase. Since the VM is not initialized during the OnLoad phase, the set of allowed operations inside Agent_OnLoad is restricted (see the function descriptions for the functionality available at this time). The agent can safely process the options and set event callbacks with SetEventCallbacks. Once the VM initialization event is received (that is, the VMInit callback is invoked), the agent can complete its initialization.

Rationale: Early startup is required so that agents can set the desired capabilities, many of which must be set before the VM is initialized. In JVMDI, the -Xdebug command-line option provided very coarse-grain control of capabilities. JVMPI implementations use various tricks to provide a single "JVMPI on" switch. No reasonable command-line option could provide the fine-grain of control required to balance needed capabilities vs performance impact. Early startup is also needed so that agents can control the execution environment - modifying the file system and system properties to install their functionality.

The return value from Agent_OnLoad is used to indicate an error. Any value other than zero indicates an error and causes termination of the VM.

Agent Start-Up (Live phase)

A VM may support a mechanism that allows agents to be started in the VM during the live phase. The details of how this is supported, are implementation specific. For example, a tool may use some platform specific mechanism, or implementation specific API, to attach to the running VM, and request it start a given agent.

If an agent is started during the live phase then its agent library must export a start-up function with the following prototype:
JNIEXPORT jint JNICALL
Agent_OnAttach(JavaVM* vm, char *options, void *reserved)

The VM will start the agent by calling this function. It will be called in the context of a thread that is attached to the VM. The first argument <vm> is the Java VM. The <options> argument is the startup options provided to the agent. <options> is encoded as a modified UTF-8 string. If startup options were not provided, a zero length string is passed to options. The lifespan of the options string is the Agent_OnAttach call. If needed beyond this time the string or parts of the string must be copied.

Note that some capabilities may not be available in the live phase.

The Agent_OnAttach function initializes the agent and returns a value to the VM to indicate if an error occurred. Any value other than zero indicates an error. An error does not cause the VM to terminate. Instead the VM ignores the error, or takes some implementation specific action -- for example it might print an error to standard error, or record the error in a system log.

Agent Shutdown

The library may optionally export a shutdown function with the following prototype:
JNIEXPORT void JNICALL
Agent_OnUnload(JavaVM *vm)
This function will be called by the VM when the library is about to be unloaded. The library will be unloaded and this function will be called if some platform specific mechanism causes the unload (an unload mechanism is not specified in this document) or the library is (in effect) unloaded by the termination of the VM whether through normal termination or VM failure, including start-up failure. Uncontrolled shutdown is, of couse, an exception to this rule. Note the distinction between this function and the VM Death event: for the VM Death event to be sent, the VM must have run at least to the point of initialization and a valid JVM TI environment must exist which has set a callback for VMDeath and enabled the event None of these are required for Agent_OnUnload and this function is also called if the library is unloaded for other reasons. In the case that a VM Death event is sent, it will be sent before this function is called (assuming this function is called due to VM termination). This function can be used to clean-up resources allocated by the agent.

JAVA_TOOL_OPTIONS

Since the command-line cannot always be accessed or modified, for example in embedded VMs or simply VMs launched deep within scripts, a JAVA_TOOL_OPTIONS variable is provided so that agents may be launched in these cases.

Platforms which support environment variables or other named strings, may support the JAVA_TOOL_OPTIONS variable. This variable will be broken into options at white-space boundaries. White-space characters include space, tab, carriage-return, new-line, vertical-tab, and form-feed. Sequences of white-space characters are considered equivalent to a single white-space character. No white-space is included in the options unless quoted. Quoting is as follows:
  • All characters enclosed between a pair of single quote marks (''), except a single quote, are quoted.
  • Double quote characters have no special meaning inside a pair of single quote marks.
  • All characters enclosed between a pair of double quote marks (""), except a double quote, are quoted.
  • Single quote characters have no special meaning inside a pair of double quote marks.
  • A quoted part can start or end anywhere in the variable.
  • White-space characters have no special meaning when quoted -- they are included in the option like any other character and do not mark white-space boundaries.
  • The pair of quote marks is not included in the option.
JNI_CreateJavaVM (in the JNI Invocation API) will prepend these options to the options supplied in its JavaVMInitArgs argument. Platforms may disable this feature in cases where security is a concern; for example, the Reference Implementation disables this feature on Unix systems when the effective user or group ID differs from the real ID. This feature is intended to support the initialization of tools -- specifically including the launching of native or Java programming language agents. Multiple tools may wish to use this feature, so the variable should not be overwritten, instead, options should be appended to the variable. Note that since the variable is processed at the time of the JNI Invocation API create VM call, options processed by a launcher (e.g., VM selection options) will not be handled.

Environments

The JVM TI specification supports the use of multiple simultaneous JVM TI agents. Each agent has its own JVM TI environment. That is, the JVM TI state is separate for each agent - changes to one environment do not affect the others. The state of a JVM TI environment includes:
  • the event callbacks
  • the set of events which are enabled
  • the capabilities
  • the memory allocation/deallocation hooks
Although their JVM TI state is separate, agents inspect and modify the shared state of the VM, they also share the native environment in which they execute. As such, an agent can perturb the results of other agents or cause them to fail. It is the responsibility of the agent writer to specify the level of compatibility with other agents. JVM TI implementations are not capable of preventing destructive interactions between agents. Techniques to reduce the likelihood of these occurrences are beyond the scope of this document.

An agent creates a JVM TI environment by passing a JVM TI version as the interface ID to the JNI Invocation API function GetEnv. See Accessing JVM TI Functions for more details on the creation and use of JVM TI environments. Typically, JVM TI environments are created by calling GetEnv from Agent_OnLoad.

Bytecode Instrumentation

This interface does not include some events that one might expect in an interface with profiling support. Some examples include object allocation events and full speed method enter and exit events. The interface instead provides support for bytecode instrumentation, the ability to alter the Java virtual machine bytecode instructions which comprise the target program. Typically, these alterations are to add "events" to the code of a method - for example, to add, at the beginning of a method, a call to MyProfiler.methodEntered(). Since the changes are purely additive, they do not modify application state or behavior. Because the inserted agent code is standard bytecodes, the VM can run at full speed, optimizing not only the target program but also the instrumentation. If the instrumentation does not involve switching from bytecode execution, no expensive state transitions are needed. The result is high performance events. This approach also provides complete control to the agent: instrumentation can be restricted to "interesting" portions of the code (e.g., the end user's code) and can be conditional. Instrumentation can run entirely in Java programming language code or can call into the native agent. Instrumentation can simply maintain counters or can statistically sample events.

Instrumentation can be inserted in one of three ways:
  • Static Instrumentation: The class file is instrumented before it is loaded into the VM - for example, by creating a duplicate directory of *.class files which have been modified to add the instrumentation. This method is extremely awkward and, in general, an agent cannot know the origin of the class files which will be loaded.
  • Load-Time Instrumentation: When a class file is loaded by the VM, the raw bytes of the class file are sent for instrumentation to the agent. The ClassFileLoadHook event, triggered by the class load, provides this functionality. This mechanism provides efficient and complete access to one-time instrumentation.
  • Dynamic Instrumentation: A class which is already loaded (and possibly even running) is modified. This optional feature is provided by the ClassFileLoadHook event, triggered by calling the RetransformClasses function. Classes can be modified multiple times and can be returned to their original state. The mechanism allows instrumentation which changes during the course of execution.

The class modification functionality provided in this interface is intended to provide a mechanism for instrumentation (the ClassFileLoadHook event and the RetransformClasses function) and, during development, for fix-and-continue debugging (the RedefineClasses function).

Care must be taken to avoid perturbing dependencies, especially when instrumenting core classes. For example, an approach to getting notification of every object allocation is to instrument the constructor on Object. Assuming that the constructor is initially empty, the constructor could be changed to:
      public Object() {
        MyProfiler.allocationTracker(this);
      }
However, if this change was made using the ClassFileLoadHook event then this might impact a typical VM as follows: the first created object will call the constructor causing a class load of MyProfiler; which will then cause object creation, and since MyProfiler isn't loaded yet, infinite recursion; resulting in a stack overflow. A refinement of this would be to delay invoking the tracking method until a safe time. For example, trackAllocations could be set in the handler for the VMInit event.
      static boolean trackAllocations = false;

      public Object() {
        if (trackAllocations) {
          MyProfiler.allocationTracker(this);
        }
      }

The SetNativeMethodPrefix allows native methods to be instrumented by the use of wrapper methods.

Modified UTF-8 String Encoding

JVM TI uses modified UTF-8 to encode character strings. This is the same encoding used by JNI. Modified UTF-8 differs from standard UTF-8 in the representation of supplementary characters and of the null character. See the Modified UTF-8 Strings section of the JNI specification for details.

Specification Context

Since this interface provides access to the state of applications running in the Java virtual machine; terminology refers to the Java platform and not the native platform (unless stated otherwise). For example:
  • "thread" means Java programming language thread.
  • "stack frame" means Java virtual machine stack frame.
  • "class" means Java programming language class.
  • "heap" means Java virtual machine heap.
  • "monitor" means Java programming language object monitor.

Sun, Sun Microsystems, the Sun logo, Java, and JVM are trademarks or registered trademarks of Oracle and/or its affiliates, in the U.S. and other countries.

Functions

Accessing Functions

Native code accesses JVM TI features by calling JVM TI functions. Access to JVM TI functions is by use of an interface pointer in the same manner as Java Native Interface (JNI) functions are accessed. The JVM TI interface pointer is called the environment pointer.

An environment pointer is a pointer to an environment and has the type jvmtiEnv*. An environment has information about its JVM TI connection. The first value in the environment is a pointer to the function table. The function table is an array of pointers to JVM TI functions. Every function pointer is at a predefined offset inside the array.

When used from the C language: double indirection is used to access the functions; the environment pointer provides context and is the first parameter of each function call; for example:
jvmtiEnv *jvmti;
...
jvmtiError err = (*jvmti)->GetLoadedClasses(jvmti, &class_count, &classes);

When used from the C++ language: functions are accessed as member functions of jvmtiEnv; the environment pointer is not passed to the function call; for example:
jvmtiEnv *jvmti;
...
jvmtiError err = jvmti->GetLoadedClasses(&class_count, &classes);
Unless otherwise stated, all examples and declarations in this specification use the C language.

A JVM TI environment can be obtained through the JNI Invocation API GetEnv function:
jvmtiEnv *jvmti;
...
(*jvm)->GetEnv(jvm, &jvmti, JVMTI_VERSION_1_0);
Each call to GetEnv creates a new JVM TI connection and thus a new JVM TI environment. The version argument of GetEnv must be a JVM TI version. The returned environment may have a different version than the requested version but the returned environment must be compatible. GetEnv will return JNI_EVERSION if a compatible version is not available, if JVM TI is not supported or JVM TI is not supported in the current VM configuration. Other interfaces may be added for creating JVM TI environments in specific contexts. Each environment has its own state (for example, desired events, event handling functions, and capabilities). An environment is released with DisposeEnvironment. Thus, unlike JNI which has one environment per thread, JVM TI environments work across threads and are created dynamically.

Function Return Values

JVM TI functions always return an error code via the jvmtiError function return value. Some functions can return additional values through pointers provided by the calling function. In some cases, JVM TI functions allocate memory that your program must explicitly deallocate. This is indicated in the individual JVM TI function descriptions. Empty lists, arrays, sequences, etc are returned as NULL.

In the event that the JVM TI function encounters an error (any return value other than JVMTI_ERROR_NONE) the values of memory referenced by argument pointers is undefined, but no memory will have been allocated and no global references will have been allocated. If the error occurs because of invalid input, no action will have occurred.

Managing JNI Object References

JVM TI functions identify objects with JNI references (jobject and jclass) and their derivatives (jthread and jthreadGroup). References passed to JVM TI functions can be either global or local, but they must be strong references. All references returned by JVM TI functions are local references--these local references are created during the JVM TI call. Local references are a resource that must be managed (see the JNI Documentation). When threads return from native code all local references are freed. Note that some threads, including typical agent threads, will never return from native code. A thread is ensured the ability to create sixteen local references without the need for any explicit management. For threads executing a limited number of JVM TI calls before returning from native code (for example, threads processing events), it may be determined that no explicit management is needed. However, long running agent threads will need explicit local reference management--usually with the JNI functions PushLocalFrame and PopLocalFrame. Conversely, to preserve references beyond the return from native code, they must be converted to global references. These rules do not apply to jmethodID and jfieldID as they are not jobjects.

Prerequisite State for Calling Functions

Unless the function explicitly states that the agent must bring a thread or the VM to a particular state (for example, suspended), the JVM TI implementation is responsible for bringing the VM to a safe and consistent state for performing the function.

Exceptions and Functions

JVM TI functions never throw exceptions; error conditions are communicated via the function return value. Any existing exception state is preserved across a call to a JVM TI function. See the Java Exceptions section of the JNI specification for information on handling exceptions.

Function Index

  • Memory Management
    • Allocate
    • Deallocate
  • Thread
    • Get Thread State
    • Get Current Thread
    • Get All Threads
    • Suspend Thread
    • Suspend Thread List
    • Resume Thread
    • Resume Thread List
    • Stop Thread
    • Interrupt Thread
    • Get Thread Info
    • Get Owned Monitor Info
    • Get Owned Monitor Stack Depth Info
    • Get Current Contended Monitor
    • Run Agent Thread
    • Set Thread Local Storage
    • Get Thread Local Storage
  • Thread Group
    • Get Top Thread Groups
    • Get Thread Group Info
    • Get Thread Group Children
  • Stack Frame
    • Get Stack Trace
    • Get All Stack Traces
    • Get Thread List Stack Traces
    • Get Frame Count
    • Pop Frame
    • Get Frame Location
    • Notify Frame Pop
  • Force Early Return
    • Force Early Return - Object
    • Force Early Return - Int
    • Force Early Return - Long
    • Force Early Return - Float
    • Force Early Return - Double
    • Force Early Return - Void
  • Heap
    • Follow References
    • Iterate Through Heap
    • Get Tag
    • Set Tag
    • Get Objects With Tags
    • Force Garbage Collection
  • Heap (1.0)
    • Iterate Over Objects Reachable From Object
    • Iterate Over Reachable Objects
    • Iterate Over Heap
    • Iterate Over Instances Of Class
  • Local Variable
    • Get Local Variable - Object
    • Get Local Instance
    • Get Local Variable - Int
    • Get Local Variable - Long
    • Get Local Variable - Float
    • Get Local Variable - Double
    • Set Local Variable - Object
    • Set Local Variable - Int
    • Set Local Variable - Long
    • Set Local Variable - Float
    • Set Local Variable - Double
  • Breakpoint
    • Set Breakpoint
    • Clear Breakpoint
  • Watched Field
    • Set Field Access Watch
    • Clear Field Access Watch
    • Set Field Modification Watch
    • Clear Field Modification Watch
  • Class
    • Get Loaded Classes
    • Get Classloader Classes
    • Get Class Signature
    • Get Class Status
    • Get Source File Name
    • Get Class Modifiers
    • Get Class Methods
    • Get Class Fields
    • Get Implemented Interfaces
    • Get Class Version Numbers
    • Get Constant Pool
    • Is Interface
    • Is Array Class
    • Is Modifiable Class
    • Get Class Loader
    • Get Source Debug Extension
    • Retransform Classes
    • Redefine Classes
  • Object
    • Get Object Size
    • Get Object Hash Code
    • Get Object Monitor Usage
  • Field
    • Get Field Name (and Signature)
    • Get Field Declaring Class
    • Get Field Modifiers
    • Is Field Synthetic
  • Method
    • Get Method Name (and Signature)
    • Get Method Declaring Class
    • Get Method Modifiers
    • Get Max Locals
    • Get Arguments Size
    • Get Line Number Table
    • Get Method Location
    • Get Local Variable Table
    • Get Bytecodes
    • Is Method Native
    • Is Method Synthetic
    • Is Method Obsolete
    • Set Native Method Prefix
    • Set Native Method Prefixes
  • Raw Monitor
    • Create Raw Monitor
    • Destroy Raw Monitor
    • Raw Monitor Enter
    • Raw Monitor Exit
    • Raw Monitor Wait
    • Raw Monitor Notify
    • Raw Monitor Notify All
  • JNI Function Interception
    • Set JNI Function Table
    • Get JNI Function Table
  • Event Management
    • Set Event Callbacks
    • Set Event Notification Mode
    • Generate Events
  • Extension Mechanism
    • Get Extension Functions
    • Get Extension Events
    • Set Extension Event Callback
  • Capability
    • Get Potential Capabilities
    • Add Capabilities
    • Relinquish Capabilities
    • Get Capabilities
  • Timers
    • Get Current Thread CPU Timer Information
    • Get Current Thread CPU Time
    • Get Thread CPU Timer Information
    • Get Thread CPU Time
    • Get Timer Information
    • Get Time
    • Get Available Processors
  • Class Loader Search
    • Add To Bootstrap Class Loader Search
    • Add To System Class Loader Search
  • System Properties
    • Get System Properties
    • Get System Property
    • Set System Property
  • General
    • Get Phase
    • Dispose Environment
    • Set Environment Local Storage
    • Get Environment Local Storage
    • Get Version Number
    • Get Error Name
    • Set Verbose Flag
    • Get JLocation Format

Memory Management

Memory Management functions:
  • Allocate
  • Deallocate
These functions provide for the allocation and deallocation of memory used by JVM TI functionality and can be used to provide working memory for agents. Memory managed by JVM TI is not compatible with other memory allocation libraries and mechanisms.

Allocate

jvmtiError
Allocate(jvmtiEnv* env,
            jlong size,
            unsigned char** mem_ptr)
Allocate an area of memory through the JVM TI allocator. The allocated memory should be freed with Deallocate.

Phase | Callback Safe | Position | Since
may be called during any phase | This function may be called from the callbacks to the Heap iteration functions, or from the event handlers for the GarbageCollectionStart, GarbageCollectionFinish, and ObjectFree events. | 46 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
size | jlong | The number of bytes to allocate. Rationale: jlong is used for compatibility with JVMDI.
mem_ptr | unsigned char** | On return, a pointer to the beginning of the allocated memory. If size is zero, NULL is returned. Agent passes a pointer to a unsigned char*. On return, the unsigned char* points to a newly allocated array of size size. The array should be freed with Deallocate.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_OUT_OF_MEMORY | Memory request cannot be honored.
JVMTI_ERROR_ILLEGAL_ARGUMENT | size is less than zero.
JVMTI_ERROR_NULL_POINTER | mem_ptr is NULL.

Deallocate

jvmtiError
Deallocate(jvmtiEnv* env,
            unsigned char* mem)
Deallocate mem using the JVM TI allocator. This function should be used to deallocate any memory allocated and returned by a JVM TI function (including memory allocated with Allocate). All allocated memory must be deallocated or the memory cannot be reclaimed.

Phase | Callback Safe | Position | Since
may be called during any phase | This function may be called from the callbacks to the Heap iteration functions, or from the event handlers for the GarbageCollectionStart, GarbageCollectionFinish, and ObjectFree events. | 47 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
mem | unsigned char * | A pointer to the beginning of the allocated memory. Please ignore "On return, the elements are set." Agent passes an array of unsigned char. The incoming values of the elements of the array are ignored. On return, the elements are set. If mem is NULL, the call is ignored.

Errors
This function returns a universal error

Thread

Thread functions:
  • Get Thread State
  • Get Current Thread
  • Get All Threads
  • Suspend Thread
  • Suspend Thread List
  • Resume Thread
  • Resume Thread List
  • Stop Thread
  • Interrupt Thread
  • Get Thread Info
  • Get Owned Monitor Info
  • Get Owned Monitor Stack Depth Info
  • Get Current Contended Monitor
  • Run Agent Thread
  • Set Thread Local Storage
  • Get Thread Local Storage
Thread function types:
  • Agent Start Function
Thread types:
  • jvmtiThreadInfo - Thread information structure
  • jvmtiMonitorStackDepthInfo - Monitor stack depth information structure
Thread flags and constants:
  • Thread State Flags
  • java.lang.Thread.State Conversion Masks
  • Thread Priority Constants

Get Thread State

jvmtiError
GetThreadState(jvmtiEnv* env,
            jthread thread,
            jint* thread_state_ptr)
Get the state of a thread. The state of the thread is represented by the answers to the hierarchical set of questions below:
  • Alive?
    • Not alive.
      • Why not alive?
        • New.
        • Terminated (JVMTI_THREAD_STATE_TERMINATED)
    • Alive (JVMTI_THREAD_STATE_ALIVE)
      • Suspended?
        • Suspended (JVMTI_THREAD_STATE_SUSPENDED)
        • Not suspended
      • Interrupted?
        • Interrupted (JVMTI_THREAD_STATE_INTERRUPTED)
        • Not interrupted.
      • In native?
        • In native code (JVMTI_THREAD_STATE_IN_NATIVE)
        • In Java programming language code
      • What alive state?
        • Runnable (JVMTI_THREAD_STATE_RUNNABLE)
        • Blocked (JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER)
        • Waiting (JVMTI_THREAD_STATE_WAITING)
          • Timed wait?
            • Indefinite (JVMTI_THREAD_STATE_WAITING_INDEFINITELY
            • Timed (JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT)
          • Why waiting?
            • Object.wait (JVMTI_THREAD_STATE_IN_OBJECT_WAIT)
            • LockSupport.park (JVMTI_THREAD_STATE_PARKED)
            • Sleeping (JVMTI_THREAD_STATE_SLEEPING)

The answers are represented by the following bit vector.
Thread State Flags
Constant | Value | Description
JVMTI_THREAD_STATE_ALIVE | 0x0001 | Thread is alive. Zero if thread is new (not started) or terminated.
JVMTI_THREAD_STATE_TERMINATED | 0x0002 | Thread has completed execution.
JVMTI_THREAD_STATE_RUNNABLE | 0x0004 | Thread is runnable.
JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER | 0x0400 | Thread is waiting to enter a synchronization block/method or, after an Object.wait(), waiting to re-enter a synchronization block/method.
JVMTI_THREAD_STATE_WAITING | 0x0080 | Thread is waiting.
JVMTI_THREAD_STATE_WAITING_INDEFINITELY | 0x0010 | Thread is waiting without a timeout. For example, Object.wait().
JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT | 0x0020 | Thread is waiting with a maximum time to wait specified. For example, Object.wait(long).
JVMTI_THREAD_STATE_SLEEPING | 0x0040 | Thread is sleeping -- Thread.sleep(long).
JVMTI_THREAD_STATE_IN_OBJECT_WAIT | 0x0100 | Thread is waiting on an object monitor -- Object.wait.
JVMTI_THREAD_STATE_PARKED | 0x0200 | Thread is parked, for example: LockSupport.park, LockSupport.parkUtil and LockSupport.parkNanos.
JVMTI_THREAD_STATE_SUSPENDED | 0x100000 | Thread suspended. java.lang.Thread.suspend() or a JVM TI suspend function (such as SuspendThread) has been called on the thread. If this bit is set, the other bits refer to the thread state before suspension.
JVMTI_THREAD_STATE_INTERRUPTED | 0x200000 | Thread has been interrupted.
JVMTI_THREAD_STATE_IN_NATIVE 0x400000 Thread is in native code--that is, a native method is running which has not called back into the VM or Java programming language code.

This flag is not set when running VM compiled Java programming language code nor is it set when running VM code or VM support code. Native VM interface functions, such as JNI and JVM TI functions, may be implemented as VM code.
JVMTI_THREAD_STATE_VENDOR_1 | 0x10000000 | Defined by VM vendor.
JVMTI_THREAD_STATE_VENDOR_2 | 0x20000000 | Defined by VM vendor.
JVMTI_THREAD_STATE_VENDOR_3 | 0x40000000 | Defined by VM vendor.
The following definitions are used to convert JVM TI thread state to java.lang.Thread.State style states.
java.lang.Thread.State Conversion Masks
Constant | Value | Description
JVMTI_JAVA_LANG_THREAD_STATE_MASK | JVMTI_THREAD_STATE_TERMINATED | JVMTI_THREAD_STATE_ALIVE | JVMTI_THREAD_STATE_RUNNABLE | JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER | JVMTI_THREAD_STATE_WAITING | JVMTI_THREAD_STATE_WAITING_INDEFINITELY | JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT | Mask the state with this before comparison
JVMTI_JAVA_LANG_THREAD_STATE_NEW | 0 | java.lang.Thread.State.NEW
JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED | JVMTI_THREAD_STATE_TERMINATED | java.lang.Thread.State.TERMINATED
JVMTI_JAVA_LANG_THREAD_STATE_RUNNABLE | JVMTI_THREAD_STATE_ALIVE | JVMTI_THREAD_STATE_RUNNABLE | java.lang.Thread.State.RUNNABLE
JVMTI_JAVA_LANG_THREAD_STATE_BLOCKED | JVMTI_THREAD_STATE_ALIVE | JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER | java.lang.Thread.State.BLOCKED
JVMTI_JAVA_LANG_THREAD_STATE_WAITING | JVMTI_THREAD_STATE_ALIVE | JVMTI_THREAD_STATE_WAITING | JVMTI_THREAD_STATE_WAITING_INDEFINITELY | java.lang.Thread.State.WAITING
JVMTI_JAVA_LANG_THREAD_STATE_TIMED_WAITING | JVMTI_THREAD_STATE_ALIVE | JVMTI_THREAD_STATE_WAITING | JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT | java.lang.Thread.State.TIMED_WAITING
Rules

There can be no more than one answer to a question, although there can be no answer (because the answer is unknown, does not apply, or none of the answers is correct). An answer is set only when the enclosing answers match. That is, no more than one of
  • JVMTI_THREAD_STATE_RUNNABLE
  • JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER
  • JVMTI_THREAD_STATE_WAITING
can be set (a J2SETM compliant implementation will always set one of these if JVMTI_THREAD_STATE_ALIVE is set). And if any of these are set, the enclosing answer JVMTI_THREAD_STATE_ALIVE is set. No more than one of
  • JVMTI_THREAD_STATE_WAITING_INDEFINITELY
  • JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT
can be set (a J2SETM compliant implementation will always set one of these if JVMTI_THREAD_STATE_WAITING is set). And if either is set, the enclosing answers JVMTI_THREAD_STATE_ALIVE and JVMTI_THREAD_STATE_WAITING are set. No more than one of
  • JVMTI_THREAD_STATE_IN_OBJECT_WAIT
  • JVMTI_THREAD_STATE_PARKED
  • JVMTI_THREAD_STATE_SLEEPING
can be set. And if any of these is set, the enclosing answers JVMTI_THREAD_STATE_ALIVE and JVMTI_THREAD_STATE_WAITING are set. Also, if JVMTI_THREAD_STATE_SLEEPING is set, then JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT is set. If a state A is implemented using the mechanism of state B then it is state A which is returned by this function. For example, if Thread.sleep(long) is implemented using Object.wait(long) then it is still JVMTI_THREAD_STATE_SLEEPING which is returned. More than one of
  • JVMTI_THREAD_STATE_SUSPENDED
  • JVMTI_THREAD_STATE_INTERRUPTED
  • JVMTI_THREAD_STATE_IN_NATIVE
can be set, but if any is set, JVMTI_THREAD_STATE_ALIVE is set.

And finally, JVMTI_THREAD_STATE_TERMINATED cannot be set unless JVMTI_THREAD_STATE_ALIVE is not set.

The thread state representation is designed for extension in future versions of the specification; thread state values should be used accordingly, that is they should not be used as ordinals. Most queries can be made by testing a single bit, if use in a switch statement is desired, the state bits should be masked with the interesting bits. All bits not defined above are reserved for future use. A VM, compliant to the current specification, must set reserved bits to zero. An agent should ignore reserved bits -- they should not be assumed to be zero and thus should not be included in comparisons.

Examples

Note that the values below exclude reserved and vendor bits.

The state of a thread blocked at a synchronized-statement would be:
            JVMTI_THREAD_STATE_ALIVE + JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER
The state of a thread which hasn't started yet would be:
            0
The state of a thread at a Object.wait(3000) would be:
            JVMTI_THREAD_STATE_ALIVE + JVMTI_THREAD_STATE_WAITING +
                JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT +
                JVMTI_THREAD_STATE_MONITOR_WAITING
The state of a thread suspended while runnable would be:
            JVMTI_THREAD_STATE_ALIVE + JVMTI_THREAD_STATE_RUNNABLE + JVMTI_THREAD_STATE_SUSPENDED

Testing the State

In most cases, the thread state can be determined by testing the one bit corresponding to that question. For example, the code to test if a thread is sleeping:
    jint state;
    jvmtiError err;

    err = (*jvmti)->GetThreadState(jvmti, thread, &state);
    if (err == JVMTI_ERROR_NONE) {
       if (state & JVMTI_THREAD_STATE_SLEEPING) {  ...

For waiting (that is, in Object.wait, parked, or sleeping) it would be:
       if (state & JVMTI_THREAD_STATE_WAITING) {  ...
For some states, more than one bit will need to be tested as is the case when testing if a thread has not yet been started:
       if ((state & (JVMTI_THREAD_STATE_ALIVE | JVMTI_THREAD_STATE_TERMINATED)) == 0)  {  ...
To distinguish timed from untimed Object.wait:
       if (state & JVMTI_THREAD_STATE_IN_OBJECT_WAIT)  {
             if (state & JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT)  {
               printf("in Object.wait(long timeout)\n");
             } else {
               printf("in Object.wait()\n");
             }
           }

Relationship to java.lang.Thread.State

The thread state represented by java.lang.Thread.State returned from java.lang.Thread.getState() is a subset of the information returned from this function. The corresponding java.lang.Thread.State can be determined by using the provided conversion masks. For example, this returns the name of the java.lang.Thread.State thread state:
        err = (*jvmti)->GetThreadState(jvmti, thread, &state);
        abortOnError(err);
            switch (state & JVMTI_JAVA_LANG_THREAD_STATE_MASK) {
            case JVMTI_JAVA_LANG_THREAD_STATE_NEW:
              return "NEW";
            case JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED:
              return "TERMINATED";
            case JVMTI_JAVA_LANG_THREAD_STATE_RUNNABLE:
              return "RUNNABLE";
            case JVMTI_JAVA_LANG_THREAD_STATE_BLOCKED:
              return "BLOCKED";
            case JVMTI_JAVA_LANG_THREAD_STATE_WAITING:
              return "WAITING";
            case JVMTI_JAVA_LANG_THREAD_STATE_TIMED_WAITING:
              return "TIMED_WAITING";
            }

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 17 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
thread | jthread | The thread to query. If thread is NULL, the current thread is used.
thread_state_ptr | jint* | On return, points to state flags, as defined by the Thread State Flags. Agent passes a pointer to a jint. On return, the jint has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_NULL_POINTER | thread_state_ptr is NULL.

Get Current Thread

jvmtiError
GetCurrentThread(jvmtiEnv* env,
            jthread* thread_ptr)
Get the current thread. The current thread is the Java programming language thread which has called the function.

Note that most JVM TI functions that take a thread as an argument will accept NULL to mean the current thread.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 18 | 1.1

Capabilities
Required Functionality

Parameters
Name | Type | Description
thread_ptr | jthread* | On return, points to the current thread. Agent passes a pointer to a jthread. On return, the jthread has been set. The object returned by thread_ptr is a JNI local reference and must be managed.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NULL_POINTER | thread_ptr is NULL.

Get All Threads

jvmtiError
GetAllThreads(jvmtiEnv* env,
            jint* threads_count_ptr,
            jthread** threads_ptr)
Get all live threads. The threads are Java programming language threads; that is, threads that are attached to the VM. A thread is live if java.lang.Thread.isAlive() would return true, that is, the thread has been started and has not yet died. The universe of threads is determined by the context of the JVM TI environment, which typically is all threads attached to the VM. Note that this includes JVM TI agent threads (see RunAgentThread).

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 4 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
threads_count_ptr | jint* | On return, points to the number of running threads. Agent passes a pointer to a jint. On return, the jint has been set.
threads_ptr | jthread** | On return, points to an array of references, one for each running thread. Agent passes a pointer to a jthread*. On return, the jthread* points to a newly allocated array of size *threads_count_ptr. The array should be freed with Deallocate. The objects returned by threads_ptr are JNI local references and must be managed.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NULL_POINTER | threads_count_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | threads_ptr is NULL.

Suspend Thread

jvmtiError
SuspendThread(jvmtiEnv* env,
            jthread thread)
Suspend the specified thread. If the calling thread is specified, this function will not return until some other thread calls ResumeThread. If the thread is currently suspended, this function does nothing and returns an error.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 5 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_suspend | Can suspend and resume threads

Parameters
Name | Type | Description
thread | jthread | The thread to suspend. If thread is NULL, the current thread is used.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_suspend. Use AddCapabilities.
JVMTI_ERROR_THREAD_SUSPENDED | Thread already suspended.
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).

Suspend Thread List

jvmtiError
SuspendThreadList(jvmtiEnv* env,
            jint request_count,
            const jthread* request_list,
            jvmtiError* results)
Suspend the request_count threads specified in the request_list array. Threads may be resumed with ResumeThreadList or ResumeThread. If the calling thread is specified in the request_list array, this function will not return until some other thread resumes it. Errors encountered in the suspension of a thread are returned in the results array, not in the return value of this function. Threads that are currently suspended do not change state.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 92 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_suspend | Can suspend and resume threads

Parameters
Name | Type | Description
request_count | jint | The number of threads to suspend.
request_list | const jthread* | The list of threads to suspend. Agent passes in an array of request_count elements of jthread.
results | jvmtiError* | An agent supplied array of request_count elements. On return, filled with the error code for the suspend of the corresponding thread. The error code will be JVMTI_ERROR_NONE if the thread was suspended by this call. Possible error codes are those specified for SuspendThread. Agent passes an array large enough to hold request_count elements of jvmtiError. The incoming values of the elements of the array are ignored. On return, the elements are set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_suspend. Use AddCapabilities.
JVMTI_ERROR_ILLEGAL_ARGUMENT | request_count is less than 0.
JVMTI_ERROR_NULL_POINTER | request_list is NULL.
JVMTI_ERROR_NULL_POINTER | results is NULL.

Resume Thread

jvmtiError
ResumeThread(jvmtiEnv* env,
            jthread thread)
Resume a suspended thread. Any threads currently suspended through a JVM TI suspend function (eg. SuspendThread) or java.lang.Thread.suspend() will resume execution; all other threads are unaffected.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 6 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_suspend | Can suspend and resume threads

Parameters
Name | Type | Description
thread | jthread | The thread to resume.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_suspend. Use AddCapabilities.
JVMTI_ERROR_THREAD_NOT_SUSPENDED | Thread was not suspended.
JVMTI_ERROR_INVALID_TYPESTATE | The state of the thread has been modified, and is now inconsistent.
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).

Resume Thread List

jvmtiError
ResumeThreadList(jvmtiEnv* env,
            jint request_count,
            const jthread* request_list,
            jvmtiError* results)
Resume the request_count threads specified in the request_list array. Any thread suspended through a JVM TI suspend function (eg. SuspendThreadList) or java.lang.Thread.suspend() will resume execution.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 93 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_suspend | Can suspend and resume threads

Parameters
Name | Type | Description
request_count | jint | The number of threads to resume.
request_list | const jthread* | The threads to resume. Agent passes in an array of request_count elements of jthread.
results | jvmtiError* | An agent supplied array of request_count elements. On return, filled with the error code for the resume of the corresponding thread. The error code will be JVMTI_ERROR_NONE if the thread was suspended by this call. Possible error codes are those specified for ResumeThread. Agent passes an array large enough to hold request_count elements of jvmtiError. The incoming values of the elements of the array are ignored. On return, the elements are set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_suspend. Use AddCapabilities.
JVMTI_ERROR_ILLEGAL_ARGUMENT | request_count is less than 0.
JVMTI_ERROR_NULL_POINTER | request_list is NULL.
JVMTI_ERROR_NULL_POINTER | results is NULL.

Stop Thread

jvmtiError
StopThread(jvmtiEnv* env,
            jthread thread,
            jobject exception)
Send the specified asynchronous exception to the specified thread (similar to java.lang.Thread.stop). Normally, this function is used to kill the specified thread with an instance of the exception ThreadDeath.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 7 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_signal_thread | Can send stop or interrupt to threads

Parameters
Name | Type | Description
thread | jthread | The thread to stop.
exception | jobject | The asynchronous exception object.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_signal_thread. Use AddCapabilities.
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).
JVMTI_ERROR_INVALID_OBJECT | exception is not an object.

Interrupt Thread

jvmtiError
InterruptThread(jvmtiEnv* env,
            jthread thread)
Interrupt the specified thread (similar to java.lang.Thread.interrupt).

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 8 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_signal_thread | Can send stop or interrupt to threads

Parameters
Name | Type | Description
thread | jthread | The thread to interrupt.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_signal_thread. Use AddCapabilities.
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).

Get Thread Info

typedef struct {
    char* name;
    jint priority;
    jboolean is_daemon;
    jthreadGroup thread_group;
    jobject context_class_loader;
} jvmtiThreadInfo;
jvmtiError
GetThreadInfo(jvmtiEnv* env,
            jthread thread,
            jvmtiThreadInfo* info_ptr)
Get thread information. The fields of the jvmtiThreadInfo structure are filled in with details of the specified thread.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 9 | 1.0

Capabilities
Required Functionality

jvmtiThreadInfo - Thread information structure
Field | Type | Description
name | char* | The thread name, encoded as a modified UTF-8 string.
priority | jint | The thread priority. See the thread priority constants: jvmtiThreadPriority.
is_daemon | jboolean | Is this a daemon thread?
thread_group | jthreadGroup | The thread group to which this thread belongs. NULL if the thread has died.
context_class_loader | jobject | The context class loader associated with this thread.

Parameters
Name | Type | Description
thread | jthread | The thread to query. If thread is NULL, the current thread is used.
info_ptr | jvmtiThreadInfo* | On return, filled with information describing the specified thread. For JDK 1.1 implementations that don't recognize context class loaders, the context_class_loader field will be NULL. Agent passes a pointer to a jvmtiThreadInfo. On return, the jvmtiThreadInfo has been set. The pointer returned in the field name of jvmtiThreadInfo is a newly allocated array. The array should be freed with Deallocate. The object returned in the field thread_group of jvmtiThreadInfo is a JNI local reference and must be managed. The object returned in the field context_class_loader of jvmtiThreadInfo is a JNI local reference and must be managed.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_NULL_POINTER | info_ptr is NULL.

Get Owned Monitor Info

jvmtiError
GetOwnedMonitorInfo(jvmtiEnv* env,
            jthread thread,
            jint* owned_monitor_count_ptr,
            jobject** owned_monitors_ptr)
Get information about the monitors owned by the specified thread.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 10 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_get_owned_monitor_info | Can get information about ownership of monitors - GetOwnedMonitorInfo

Parameters
Name | Type | Description
thread | jthread | The thread to query. If thread is NULL, the current thread is used.
owned_monitor_count_ptr | jint* | The number of monitors returned. Agent passes a pointer to a jint. On return, the jint has been set.
owned_monitors_ptr | jobject** | The array of owned monitors. Agent passes a pointer to a jobject*. On return, the jobject* points to a newly allocated array of size *owned_monitor_count_ptr. The array should be freed with Deallocate. The objects returned by owned_monitors_ptr are JNI local references and must be managed.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_get_owned_monitor_info. Use AddCapabilities.
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).
JVMTI_ERROR_NULL_POINTER | owned_monitor_count_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | owned_monitors_ptr is NULL.

Get Owned Monitor Stack Depth Info

typedef struct {
    jobject monitor;
    jint stack_depth;
} jvmtiMonitorStackDepthInfo;
jvmtiError
GetOwnedMonitorStackDepthInfo(jvmtiEnv* env,
            jthread thread,
            jint* monitor_info_count_ptr,
            jvmtiMonitorStackDepthInfo** monitor_info_ptr)
Get information about the monitors owned by the specified thread and the depth of the stack frame which locked them.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 153 | 1.1

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_get_owned_monitor_stack_depth_info | Can get information about owned monitors with stack depth - GetOwnedMonitorStackDepthInfo

jvmtiMonitorStackDepthInfo - Monitor stack depth information structure
Field | Type | Description
monitor | jobject | The owned monitor.
stack_depth | jint | The stack depth. Corresponds to the stack depth used in the Stack Frame functions. That is, zero is the current frame, one is the frame which called the current frame. And it is negative one if the implementation cannot determine the stack depth (e.g., for monitors acquired by JNI MonitorEnter).

Parameters
Name | Type | Description
thread | jthread | The thread to query. If thread is NULL, the current thread is used.
monitor_info_count_ptr | jint* | The number of monitors returned. Agent passes a pointer to a jint. On return, the jint has been set.
monitor_info_ptr | jvmtiMonitorStackDepthInfo ** | The array of owned monitor depth information. Agent passes a pointer to a jvmtiMonitorStackDepthInfo*. On return, the jvmtiMonitorStackDepthInfo* points to a newly allocated array of size *owned_monitor_depth_count_ptr. The array should be freed with Deallocate. The objects returned in the field monitor of jvmtiMonitorStackDepthInfo are JNI local references and must be managed.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_get_owned_monitor_stack_depth_info. Use AddCapabilities.
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).
JVMTI_ERROR_NULL_POINTER | monitor_info_count_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | monitor_info_ptr is NULL.

Get Current Contended Monitor

jvmtiError
GetCurrentContendedMonitor(jvmtiEnv* env,
            jthread thread,
            jobject* monitor_ptr)
Get the object, if any, whose monitor the specified thread is waiting to enter or waiting to regain through java.lang.Object.wait.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 11 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_get_current_contended_monitor | Can GetCurrentContendedMonitor

Parameters
Name | Type | Description
thread | jthread | The thread to query. If thread is NULL, the current thread is used.
monitor_ptr | jobject* | On return, filled with the current contended monitor, or NULL if there is none. Agent passes a pointer to a jobject. On return, the jobject has been set. The object returned by monitor_ptr is a JNI local reference and must be managed.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_get_current_contended_monitor. Use AddCapabilities.
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).
JVMTI_ERROR_NULL_POINTER | monitor_ptr is NULL.

Agent Start Function

typedef void (JNICALL *jvmtiStartFunction)
    (jvmtiEnv* jvmti_env,
     JNIEnv* jni_env,
     void* arg);
Agent supplied callback function. This function is the entry point for an agent thread started with RunAgentThread.

Parameters
Name | Type | Description
jvmti_env | jvmtiEnv * | The JVM TI environment.
jni_env | JNIEnv * | The JNI environment.
arg | void * | The arg parameter passed to RunAgentThread.

Run Agent Thread

jvmtiError
RunAgentThread(jvmtiEnv* env,
            jthread thread,
            jvmtiStartFunction proc,
            const void* arg,
            jint priority)
Starts the execution of an agent thread. with the specified native function. The parameter arg is forwarded on to the start function (specified with proc) as its single argument. This function allows the creation of agent threads for handling communication with another process or for handling events without the need to load a special subclass of java.lang.Thread or implementer of java.lang.Runnable. Instead, the created thread can run entirely in native code. However, the created thread does require a newly created instance of java.lang.Thread (referenced by the argument thread) to which it will be associated. The thread object can be created with JNI calls.

The following common thread priorities are provided for your convenience:
Thread Priority Constants
Constant | Value | Description
JVMTI_THREAD_MIN_PRIORITY | 1 | Minimum possible thread priority
JVMTI_THREAD_NORM_PRIORITY | 5 | Normal thread priority
JVMTI_THREAD_MAX_PRIORITY | 10 | Maximum possible thread priority

The new thread is started as a daemon thread with the specified priority. If enabled, a ThreadStart event will be sent.

Since the thread has been started, the thread will be live when this function returns, unless the thread has died immediately.

The thread group of the thread is ignored -- specifically, the thread is not added to the thread group and the thread is not seen on queries of the thread group at either the Java programming language or JVM TI levels.

The thread is not visible to Java programming language queries but is included in JVM TI queries (for example, GetAllThreads and GetAllStackTraces).

Upon execution of proc, the new thread will be attached to the VM--see the JNI documentation on Attaching to the VM.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 12 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
thread | jthread | The thread to run.
proc | jvmtiStartFunction | The start function.
arg | const void * | The argument to the start function. Agent passes in a pointer. If arg is NULL, NULL is passed to the start function.
priority | jint | The priority of the started thread. Any thread priority allowed by java.lang.Thread.setPriority can be used including those in jvmtiThreadPriority.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_PRIORITY | priority is less than JVMTI_THREAD_MIN_PRIORITY or greater than JVMTI_THREAD_MAX_PRIORITY
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_NULL_POINTER | proc is NULL.

Set Thread Local Storage

jvmtiError
SetThreadLocalStorage(jvmtiEnv* env,
            jthread thread,
            const void* data)
The VM stores a pointer value associated with each environment-thread pair. This pointer value is called thread-local storage. This value is NULL unless set with this function. Agents can allocate memory in which they store thread specific information. By setting thread-local storage it can then be accessed with GetThreadLocalStorage.

This function is called by the agent to set the value of the JVM TI thread-local storage. JVM TI supplies to the agent a pointer-size thread-local storage that can be used to record per-thread information.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 103 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
thread | jthread | Store to this thread. If thread is NULL, the current thread is used.
data | const void * | The value to be entered into the thread-local storage. Agent passes in a pointer. If data is NULL, value is set to NULL.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).

Get Thread Local Storage

jvmtiError
GetThreadLocalStorage(jvmtiEnv* env,
            jthread thread,
            void** data_ptr)
Called by the agent to get the value of the JVM TI thread-local storage.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 102 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
thread | jthread | Retrieve from this thread. If thread is NULL, the current thread is used.
data_ptr | void** | Pointer through which the value of the thread local storage is returned. If thread-local storage has not been set with SetThreadLocalStorage the returned pointer is NULL.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).
JVMTI_ERROR_NULL_POINTER | data_ptr is NULL.

Thread Group

Thread Group functions:
  • Get Top Thread Groups
  • Get Thread Group Info
  • Get Thread Group Children
Thread Group types:
  • jvmtiThreadGroupInfo - Thread group information structure

Get Top Thread Groups

jvmtiError
GetTopThreadGroups(jvmtiEnv* env,
            jint* group_count_ptr,
            jthreadGroup** groups_ptr)
Return all top-level (parentless) thread groups in the VM.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 13 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
group_count_ptr | jint* | On return, points to the number of top-level thread groups. Agent passes a pointer to a jint. On return, the jint has been set.
groups_ptr | jthreadGroup** | On return, refers to a pointer to the top-level thread group array. Agent passes a pointer to a jthreadGroup*. On return, the jthreadGroup* points to a newly allocated array of size *group_count_ptr. The array should be freed with Deallocate. The objects returned by groups_ptr are JNI local references and must be managed.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NULL_POINTER | group_count_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | groups_ptr is NULL.

Get Thread Group Info

typedef struct {
    jthreadGroup parent;
    char* name;
    jint max_priority;
    jboolean is_daemon;
} jvmtiThreadGroupInfo;
jvmtiError
GetThreadGroupInfo(jvmtiEnv* env,
            jthreadGroup group,
            jvmtiThreadGroupInfo* info_ptr)
Get information about the thread group. The fields of the jvmtiThreadGroupInfo structure are filled in with details of the specified thread group.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 14 | 1.0

Capabilities
Required Functionality

jvmtiThreadGroupInfo - Thread group information structure
Field | Type | Description
parent | jthreadGroup | The parent thread group.
name | char* | The thread group's name, encoded as a modified UTF-8 string.
max_priority | jint | The maximum priority for this thread group.
is_daemon | jboolean | Is this a daemon thread group?

Parameters
Name | Type | Description
group | jthreadGroup | The thread group to query.
info_ptr | jvmtiThreadGroupInfo* | On return, filled with information describing the specified thread group. Agent passes a pointer to a jvmtiThreadGroupInfo. On return, the jvmtiThreadGroupInfo has been set. The object returned in the field parent of jvmtiThreadGroupInfo is a JNI local reference and must be managed. The pointer returned in the field name of jvmtiThreadGroupInfo is a newly allocated array. The array should be freed with Deallocate.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_THREAD_GROUP | group is not a thread group object.
JVMTI_ERROR_NULL_POINTER | info_ptr is NULL.

Get Thread Group Children

jvmtiError
GetThreadGroupChildren(jvmtiEnv* env,
            jthreadGroup group,
            jint* thread_count_ptr,
            jthread** threads_ptr,
            jint* group_count_ptr,
            jthreadGroup** groups_ptr)
Get the live threads and active subgroups in this thread group.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 15 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
group | jthreadGroup | The group to query.
thread_count_ptr | jint* | On return, points to the number of live threads in this thread group. Agent passes a pointer to a jint. On return, the jint has been set.
threads_ptr | jthread** | On return, points to an array of the live threads in this thread group. Agent passes a pointer to a jthread*. On return, the jthread* points to a newly allocated array of size *thread_count_ptr. The array should be freed with Deallocate. The objects returned by threads_ptr are JNI local references and must be managed.
group_count_ptr | jint* | On return, points to the number of active child thread groups Agent passes a pointer to a jint. On return, the jint has been set.
groups_ptr | jthreadGroup** | On return, points to an array of the active child thread groups. Agent passes a pointer to a jthreadGroup*. On return, the jthreadGroup* points to a newly allocated array of size *group_count_ptr. The array should be freed with Deallocate. The objects returned by groups_ptr are JNI local references and must be managed.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_THREAD_GROUP | group is not a thread group object.
JVMTI_ERROR_NULL_POINTER | thread_count_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | threads_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | group_count_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | groups_ptr is NULL.

Stack Frame

Stack Frame functions:
  • Get Stack Trace
  • Get All Stack Traces
  • Get Thread List Stack Traces
  • Get Frame Count
  • Pop Frame
  • Get Frame Location
  • Notify Frame Pop
Stack Frame types:
  • jvmtiFrameInfo - Stack frame information structure
  • jvmtiStackInfo - Stack information structure
These functions provide information about the stack of a thread. Stack frames are referenced by depth. The frame at depth zero is the current frame.

Stack frames are as described in the Frames section of the Java Virtual Machine Specification. That is, they correspond to method invocations (including native methods) but do not correspond to platform native or VM internal frames.

A JVM TI implementation may use method invocations to launch a thread and the corresponding frames may be included in the stack as presented by these functions -- that is, there may be frames shown deeper than main() and run(). However this presentation must be consistent across all JVM TI functionality which uses stack frames or stack depth.

Stack frame information structure

Information about a stack frame is returned in this structure.

typedef struct {
    jmethodID method;
    jlocation location;
} jvmtiFrameInfo;
jvmtiFrameInfo - Stack frame information structure
Field | Type | Description
method | jmethodID | The method executing in this frame.
location | jlocation | The index of the instruction executing in this frame. -1 if the frame is executing a native method.

Stack information structure

Information about a set of stack frames is returned in this structure.

typedef struct {
    jthread thread;
    jint state;
    jvmtiFrameInfo* frame_buffer;
    jint frame_count;
} jvmtiStackInfo;
jvmtiStackInfo - Stack information structure
Field | Type | Description
thread | jthread | On return, the thread traced.
state | jint | On return, the thread state. See GetThreadState.
frame_buffer | jvmtiFrameInfo * | On return, this agent allocated buffer is filled with stack frame information.
frame_count | jint | On return, the number of records filled into frame_buffer. This will be min(max_frame_count, stackDepth).

Get Stack Trace

jvmtiError
GetStackTrace(jvmtiEnv* env,
            jthread thread,
            jint start_depth,
            jint max_frame_count,
            jvmtiFrameInfo* frame_buffer,
            jint* count_ptr)
Get information about the stack of a thread. If max_frame_count is less than the depth of the stack, the max_frame_count topmost frames are returned, otherwise the entire stack is returned. The topmost frames, those most recently invoked, are at the beginning of the returned buffer.

The following example causes up to five of the topmost frames to be returned and (if there are any frames) the currently executing method name to be printed.
jvmtiFrameInfo frames[5];
jint count;
jvmtiError err;

err = (*jvmti)->GetStackTrace(jvmti, aThread, 0, 5,
                               &frames, &count);
if (err == JVMTI_ERROR_NONE && count >= 1) {
   char *methodName;
   err = (*jvmti)->GetMethodName(jvmti, frames[0].method,
                       &methodName, NULL);
   if (err == JVMTI_ERROR_NONE) {
      printf("Executing method: %s", methodName);
   }
}

The thread need not be suspended to call this function.

The GetLineNumberTable function can be used to map locations to line numbers. Note that this mapping can be done lazily.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 104 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
thread | jthread | Fetch the stack trace of this thread. If thread is NULL, the current thread is used.
start_depth | jint | Begin retrieving frames at this depth. If non-negative, count from the current frame, the first frame retrieved is at depth start_depth. For example, if zero, start from the current frame; if one, start from the caller of the current frame; if two, start from the caller of the caller of the current frame; and so on. If negative, count from below the oldest frame, the first frame retrieved is at depth stackDepth + start_depth, where stackDepth is the count of frames on the stack. For example, if negative one, only the oldest frame is retrieved; if negative two, start from the frame called by the oldest frame.
max_frame_count | jint | The maximum number of jvmtiFrameInfo records to retrieve.
frame_buffer | jvmtiFrameInfo * | On return, this agent allocated buffer is filled with stack frame information. Agent passes an array large enough to hold max_frame_count elements of jvmtiFrameInfo. The incoming values of the elements of the array are ignored. On return, *count_ptr of the elements are set.
count_ptr | jint* | On return, points to the number of records filled in. For non-negative start_depth, this will be min(max_frame_count, stackDepth - start_depth). For negative start_depth, this will be min(max_frame_count, -start_depth). Agent passes a pointer to a jint. On return, the jint has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_ILLEGAL_ARGUMENT | start_depth is positive and greater than or equal to stackDepth. Or start_depth is negative and less than -stackDepth.
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).
JVMTI_ERROR_ILLEGAL_ARGUMENT | max_frame_count is less than 0.
JVMTI_ERROR_NULL_POINTER | frame_buffer is NULL.
JVMTI_ERROR_NULL_POINTER | count_ptr is NULL.

Get All Stack Traces

jvmtiError
GetAllStackTraces(jvmtiEnv* env,
            jint max_frame_count,
            jvmtiStackInfo** stack_info_ptr,
            jint* thread_count_ptr)
Get information about the stacks of all live threads (including agent threads). If max_frame_count is less than the depth of a stack, the max_frame_count topmost frames are returned for that thread, otherwise the entire stack is returned. The topmost frames, those most recently invoked, are at the beginning of the returned buffer.

All stacks are collected simultaneously, that is, no changes will occur to the thread state or stacks between the sampling of one thread and the next. The threads need not be suspended.
jvmtiStackInfo *stack_info;
jint thread_count;
int ti;
jvmtiError err;

err = (*jvmti)->GetAllStackTraces(jvmti, MAX_FRAMES, &stack_info, &thread_count);
if (err != JVMTI_ERROR_NONE) {
   ...
}
for (ti = 0; ti < thread_count; ++ti) {
   jvmtiStackInfo *infop = &stack_info[ti];
   jthread thread = infop->thread;
   jint state = infop->state;
   jvmtiFrameInfo *frames = infop->frame_buffer;
   int fi;

   myThreadAndStatePrinter(thread, state);
   for (fi = 0; fi < infop->frame_count; fi++) {
      myFramePrinter(frames[fi].method, frames[fi].location);
   }
}
/* this one Deallocate call frees all data allocated by GetAllStackTraces */
err = (*jvmti)->Deallocate(jvmti, stack_info);

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 100 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
max_frame_count | jint | The maximum number of jvmtiFrameInfo records to retrieve per thread.
stack_info_ptr | jvmtiStackInfo ** | On return, this buffer is filled with stack information for each thread. The number of jvmtiStackInfo records is determined by thread_count_ptr. Note that this buffer is allocated to include the jvmtiFrameInfo buffers pointed to by jvmtiStackInfo.frame_buffer. These buffers must not be separately deallocated. Agent passes a pointer to a jvmtiStackInfo*. On return, the jvmtiStackInfo* points to a newly allocated array. The array should be freed with Deallocate. The objects returned in the field thread of jvmtiStackInfo are JNI local references and must be managed.
thread_count_ptr | jint* | The number of threads traced. Agent passes a pointer to a jint. On return, the jint has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_ILLEGAL_ARGUMENT | max_frame_count is less than 0.
JVMTI_ERROR_NULL_POINTER | stack_info_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | thread_count_ptr is NULL.

Get Thread List Stack Traces

jvmtiError
GetThreadListStackTraces(jvmtiEnv* env,
            jint thread_count,
            const jthread* thread_list,
            jint max_frame_count,
            jvmtiStackInfo** stack_info_ptr)
Get information about the stacks of the supplied threads. If max_frame_count is less than the depth of a stack, the max_frame_count topmost frames are returned for that thread, otherwise the entire stack is returned. The topmost frames, those most recently invoked, are at the beginning of the returned buffer.

All stacks are collected simultaneously, that is, no changes will occur to the thread state or stacks between the sampling one thread and the next. The threads need not be suspended.

If a thread has not yet started or terminates before the stack information is collected, a zero length stack (jvmtiStackInfo.frame_count will be zero) will be returned and the thread jvmtiStackInfo.state can be checked.

See the example for the similar function GetAllStackTraces.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 101 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
thread_count | jint | The number of threads to trace.
thread_list | const jthread* | The list of threads to trace. Agent passes in an array of thread_count elements of jthread.
max_frame_count | jint | The maximum number of jvmtiFrameInfo records to retrieve per thread.
stack_info_ptr | jvmtiStackInfo ** | On return, this buffer is filled with stack information for each thread. The number of jvmtiStackInfo records is determined by thread_count. Note that this buffer is allocated to include the jvmtiFrameInfo buffers pointed to by jvmtiStackInfo.frame_buffer. These buffers must not be separately deallocated. Agent passes a pointer to a jvmtiStackInfo*. On return, the jvmtiStackInfo* points to a newly allocated array of size *thread_count. The array should be freed with Deallocate. The objects returned in the field thread of jvmtiStackInfo are JNI local references and must be managed.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_THREAD | An element in thread_list is not a thread object.
JVMTI_ERROR_ILLEGAL_ARGUMENT | thread_count is less than 0.
JVMTI_ERROR_NULL_POINTER | thread_list is NULL.
JVMTI_ERROR_ILLEGAL_ARGUMENT | max_frame_count is less than 0.
JVMTI_ERROR_NULL_POINTER | stack_info_ptr is NULL.

Get Frame Count

jvmtiError
GetFrameCount(jvmtiEnv* env,
            jthread thread,
            jint* count_ptr)
Get the number of frames currently in the specified thread's call stack.

If this function is called for a thread actively executing bytecodes (for example, not the current thread and not suspended), the information returned is transient.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 16 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
thread | jthread | The thread to query. If thread is NULL, the current thread is used.
count_ptr | jint* | On return, points to the number of frames in the call stack. Agent passes a pointer to a jint. On return, the jint has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).
JVMTI_ERROR_NULL_POINTER | count_ptr is NULL.

Pop Frame

jvmtiError
PopFrame(jvmtiEnv* env,
            jthread thread)
Pop the current frame of thread's stack. Popping a frame takes you to the previous frame. When the thread is resumed, the execution state of the thread is reset to the state immediately before the called method was invoked. That is (using the Java Virtual Machine Specification terminology):
  • the current frame is discarded as the previous frame becomes the current one
  • the operand stack is restored--the argument values are added back and if the invoke was not invokestatic, objectref is added back as well
  • the Java virtual machine PC is restored to the opcode of the invoke instruction
Note however, that any changes to the arguments, which occurred in the called method, remain; when execution continues, the first instruction to execute will be the invoke.

Between calling PopFrame and resuming the thread the state of the stack is undefined. To pop frames beyond the first, these three steps must be repeated:
  • suspend the thread via an event (step, breakpoint, ...)
  • call PopFrame
  • resume the thread

A lock acquired by calling the called method (if it is a synchronized method) and locks acquired by entering synchronized blocks within the called method are released. Note: this does not apply to native locks or java.util.concurrent.locks locks.

Finally blocks are not executed.

Changes to global state are not addressed and thus remain changed.

The specified thread must be suspended (which implies it cannot be the current thread).

Both the called method and calling method must be non-native Java programming language methods.

No JVM TI events are generated by this function.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 80 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_pop_frame | Can pop frames off the stack - PopFrame

Parameters
Name | Type | Description
thread | jthread | The thread whose current frame is to be popped.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_pop_frame. Use AddCapabilities.
JVMTI_ERROR_OPAQUE_FRAME | Called or calling method is a native method. The implementation is unable to pop this frame.
JVMTI_ERROR_THREAD_NOT_SUSPENDED | Thread was not suspended.
JVMTI_ERROR_NO_MORE_FRAMES | There are less than two stack frames on the call stack.
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).

Get Frame Location

jvmtiError
GetFrameLocation(jvmtiEnv* env,
            jthread thread,
            jint depth,
            jmethodID* method_ptr,
            jlocation* location_ptr)

For a Java programming language frame, return the location of the instruction currently executing.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 19 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
thread | jthread | The thread of the frame to query. If thread is NULL, the current thread is used.
depth | jint | The depth of the frame to query.
method_ptr | jmethodID* | On return, points to the method for the current location. Agent passes a pointer to a jmethodID. On return, the jmethodID has been set.
location_ptr | jlocation* | On return, points to the index of the currently executing instruction. Is set to -1 if the frame is executing a native method. Agent passes a pointer to a jlocation. On return, the jlocation has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).
JVMTI_ERROR_ILLEGAL_ARGUMENT | depth is less than zero.
JVMTI_ERROR_NO_MORE_FRAMES | There are no stack frames at the specified depth.
JVMTI_ERROR_NULL_POINTER | method_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | location_ptr is NULL.

Notify Frame Pop

jvmtiError
NotifyFramePop(jvmtiEnv* env,
            jthread thread,
            jint depth)
When the frame that is currently at depth is popped from the stack, generate a FramePop event. See the FramePop event for details. Only frames corresponding to non-native Java programming language methods can receive notification.

The specified thread must either be the current thread or the thread must be suspended.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 20 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_generate_frame_pop_events | Can set and thus get FramePop events

Parameters
Name | Type | Description
thread | jthread | The thread of the frame for which the frame pop event will be generated. If thread is NULL, the current thread is used.
depth | jint | The depth of the frame for which the frame pop event will be generated.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_generate_frame_pop_events. Use AddCapabilities.
JVMTI_ERROR_OPAQUE_FRAME | The frame at depth is executing a native method.
JVMTI_ERROR_THREAD_NOT_SUSPENDED | Thread was not suspended and was not the current thread.
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).
JVMTI_ERROR_ILLEGAL_ARGUMENT | depth is less than zero.
JVMTI_ERROR_NO_MORE_FRAMES | There are no stack frames at the specified depth.

Force Early Return

Force Early Return functions:
  • Force Early Return - Object
  • Force Early Return - Int
  • Force Early Return - Long
  • Force Early Return - Float
  • Force Early Return - Double
  • Force Early Return - Void
These functions allow an agent to force a method to return at any point during its execution. The method which will return early is referred to as the called method. The called method is the current method (as defined by the Frames section of the Java Virtual Machine Specification) for the specified thread at the time the function is called.

The specified thread must be suspended or must be the current thread. The return occurs when execution of Java programming language code is resumed on this thread. Between calling one of these functions and resumption of thread execution, the state of the stack is undefined.

No further instructions are executed in the called method. Specifically, finally blocks are not executed. Note: this can cause inconsistent states in the application.

A lock acquired by calling the called method (if it is a synchronized method) and locks acquired by entering synchronized blocks within the called method are released. Note: this does not apply to native locks or java.util.concurrent.locks locks.

Events, such as MethodExit, are generated as they would be in a normal return.

The called method must be a non-native Java programming language method. Forcing return on a thread with only one frame on the stack causes the thread to exit when resumed.

Force Early Return - Object

jvmtiError
ForceEarlyReturnObject(jvmtiEnv* env,
            jthread thread,
            jobject value)
This function can be used to return from a method whose result type is Object or a subclass of Object.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 81 | 1.1

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_force_early_return | Can return early from a method, as described in the Force Early Return category.

Parameters
Name | Type | Description
thread | jthread | The thread whose current frame is to return early. If thread is NULL, the current thread is used.
value | jobject | The return value for the called frame. An object or NULL.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_force_early_return. Use AddCapabilities.
JVMTI_ERROR_OPAQUE_FRAME | Attempted to return early from a frame corresponding to a native method. Or the implementation is unable to provide this functionality on this frame.
JVMTI_ERROR_TYPE_MISMATCH | The result type of the called method is not Object or a subclass of Object.
JVMTI_ERROR_TYPE_MISMATCH | The supplied value is not compatible with the result type of the called method.
JVMTI_ERROR_THREAD_NOT_SUSPENDED | Thread was not the current thread and was not suspended.
JVMTI_ERROR_NO_MORE_FRAMES | There are no more frames on the call stack.
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).
JVMTI_ERROR_INVALID_OBJECT | value is not an object.

Force Early Return - Int

jvmtiError
ForceEarlyReturnInt(jvmtiEnv* env,
            jthread thread,
            jint value)
This function can be used to return from a method whose result type is int, short, char, byte, or boolean.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 82 | 1.1

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_force_early_return | Can return early from a method, as described in the Force Early Return category.

Parameters
Name | Type | Description
thread | jthread | The thread whose current frame is to return early. If thread is NULL, the current thread is used.
value | jint | The return value for the called frame.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_force_early_return. Use AddCapabilities.
JVMTI_ERROR_OPAQUE_FRAME | Attempted to return early from a frame corresponding to a native method. Or the implementation is unable to provide this functionality on this frame.
JVMTI_ERROR_TYPE_MISMATCH | The result type of the called method is not int, short, char, byte, or boolean.
JVMTI_ERROR_THREAD_NOT_SUSPENDED | Thread was not the current thread and was not suspended.
JVMTI_ERROR_NO_MORE_FRAMES | There are no frames on the call stack.
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).

Force Early Return - Long

jvmtiError
ForceEarlyReturnLong(jvmtiEnv* env,
            jthread thread,
            jlong value)
This function can be used to return from a method whose result type is long.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 83 | 1.1

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_force_early_return | Can return early from a method, as described in the Force Early Return category.

Parameters
Name | Type | Description
thread | jthread | The thread whose current frame is to return early. If thread is NULL, the current thread is used.
value | jlong | The return value for the called frame.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_force_early_return. Use AddCapabilities.
JVMTI_ERROR_OPAQUE_FRAME | Attempted to return early from a frame corresponding to a native method. Or the implementation is unable to provide this functionality on this frame.
JVMTI_ERROR_TYPE_MISMATCH | The result type of the called method is not long.
JVMTI_ERROR_THREAD_NOT_SUSPENDED | Thread was not the current thread and was not suspended.
JVMTI_ERROR_NO_MORE_FRAMES | There are no frames on the call stack.
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).

Force Early Return - Float

jvmtiError
ForceEarlyReturnFloat(jvmtiEnv* env,
            jthread thread,
            jfloat value)
This function can be used to return from a method whose result type is float.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 84 | 1.1

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_force_early_return | Can return early from a method, as described in the Force Early Return category.

Parameters
Name | Type | Description
thread | jthread | The thread whose current frame is to return early. If thread is NULL, the current thread is used.
value | jfloat | The return value for the called frame.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_force_early_return. Use AddCapabilities.
JVMTI_ERROR_OPAQUE_FRAME | Attempted to return early from a frame corresponding to a native method. Or the implementation is unable to provide this functionality on this frame.
JVMTI_ERROR_TYPE_MISMATCH | The result type of the called method is not float.
JVMTI_ERROR_THREAD_NOT_SUSPENDED | Thread was not the current thread and was not suspended.
JVMTI_ERROR_NO_MORE_FRAMES | There are no frames on the call stack.
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).

Force Early Return - Double

jvmtiError
ForceEarlyReturnDouble(jvmtiEnv* env,
            jthread thread,
            jdouble value)
This function can be used to return from a method whose result type is double.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 85 | 1.1

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_force_early_return | Can return early from a method, as described in the Force Early Return category.

Parameters
Name | Type | Description
thread | jthread | The thread whose current frame is to return early. If thread is NULL, the current thread is used.
value | jdouble | The return value for the called frame.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_force_early_return. Use AddCapabilities.
JVMTI_ERROR_OPAQUE_FRAME | Attempted to return early from a frame corresponding to a native method. Or the implementation is unable to provide this functionality on this frame.
JVMTI_ERROR_TYPE_MISMATCH | The result type of the called method is not double.
JVMTI_ERROR_THREAD_NOT_SUSPENDED | Thread was not the current thread and was not suspended.
JVMTI_ERROR_NO_MORE_FRAMES | There are no frames on the call stack.
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).

Force Early Return - Void

jvmtiError
ForceEarlyReturnVoid(jvmtiEnv* env,
            jthread thread)
This function can be used to return from a method with no result type. That is, the called method must be declared void.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 86 | 1.1

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_force_early_return | Can return early from a method, as described in the Force Early Return category.

Parameters
Name | Type | Description
thread | jthread | The thread whose current frame is to return early. If thread is NULL, the current thread is used.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_force_early_return. Use AddCapabilities.
JVMTI_ERROR_OPAQUE_FRAME | Attempted to return early from a frame corresponding to a native method. Or the implementation is unable to provide this functionality on this frame.
JVMTI_ERROR_TYPE_MISMATCH | The called method has a result type.
JVMTI_ERROR_THREAD_NOT_SUSPENDED | Thread was not the current thread and was not suspended.
JVMTI_ERROR_NO_MORE_FRAMES | There are no frames on the call stack.
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).

Heap

Heap functions:
  • Follow References
  • Iterate Through Heap
  • Get Tag
  • Set Tag
  • Get Objects With Tags
  • Force Garbage Collection
Heap function types:
  • Heap Iteration Callback
  • Heap Reference Callback
  • Primitive Field Callback
  • Array Primitive Value Callback
  • String Primitive Value Callback
  • reserved for future use Callback
Heap types:
  • jvmtiHeapReferenceKind - Heap Reference Enumeration
  • jvmtiPrimitiveType - Primitive Type Enumeration
  • jvmtiHeapReferenceInfoField - Reference information structure for Field references
  • jvmtiHeapReferenceInfoArray - Reference information structure for Array references
  • jvmtiHeapReferenceInfoConstantPool - Reference information structure for Constant Pool references
  • jvmtiHeapReferenceInfoStackLocal - Reference information structure for Local Variable references
  • jvmtiHeapReferenceInfoJniLocal - Reference information structure for JNI local references
  • jvmtiHeapReferenceInfoReserved - Reference information structure for Other references
  • jvmtiHeapReferenceInfo - Reference information structure
  • jvmtiHeapCallbacks - Heap callback function structure
Heap flags and constants:
  • Heap Filter Flags
  • Heap Visit Control Flags
These functions are used to analyze the heap. Functionality includes the ability to view the objects in the heap and to tag these objects.

Object Tags

A tag is a value associated with an object. Tags are explicitly set by the agent using the SetTag function or by callback functions such as jvmtiHeapIterationCallback.

Tags are local to the environment; that is, the tags of one environment are not visible in another.

Tags are jlong values which can be used simply to mark an object or to store a pointer to more detailed information. Objects which have not been tagged have a tag of zero. Setting a tag to zero makes the object untagged.

Heap Callback Functions

Heap functions which iterate through the heap and recursively follow object references use agent supplied callback functions to deliver the information.

These heap callback functions must adhere to the following restrictions -- These callbacks must not use JNI functions. These callbacks must not use JVM TI functions except callback safe functions which specifically allow such use (see the raw monitor, memory management, and environment local storage functions).

An implementation may invoke a callback on an internal thread or the thread which called the iteration function. Heap callbacks are single threaded -- no more than one callback will be invoked at a time.

The Heap Filter Flags can be used to prevent reporting based on the tag status of an object or its class. If no flags are set (the jint is zero), objects will not be filtered out.
Heap Filter Flags
Constant | Value | Description
JVMTI_HEAP_FILTER_TAGGED | 0x4 | Filter out tagged objects. Objects which are tagged are not included.
JVMTI_HEAP_FILTER_UNTAGGED | 0x8 | Filter out untagged objects. Objects which are not tagged are not included.
JVMTI_HEAP_FILTER_CLASS_TAGGED | 0x10 | Filter out objects with tagged classes. Objects whose class is tagged are not included.
JVMTI_HEAP_FILTER_CLASS_UNTAGGED | 0x20 | Filter out objects with untagged classes. Objects whose class is not tagged are not included.

The Heap Visit Control Flags are returned by the heap callbacks and can be used to abort the iteration. For the Heap Reference Callback, it can also be used to prune the graph of traversed references (JVMTI_VISIT_OBJECTS is not set).
Heap Visit Control Flags
Constant | Value | Description
JVMTI_VISIT_OBJECTS | 0x100 | If we are visiting an object and if this callback was initiated by FollowReferences, traverse the references of this object. Otherwise ignored.
JVMTI_VISIT_ABORT | 0x8000 | Abort the iteration. Ignore all other bits.

The Heap Reference Enumeration is provided by the Heap Reference Callback and Primitive Field Callback to describe the kind of reference being reported.
Heap Reference Enumeration (jvmtiHeapReferenceKind)
Constant | Value | Description
JVMTI_HEAP_REFERENCE_CLASS | 1 | Reference from an object to its class.
JVMTI_HEAP_REFERENCE_FIELD | 2 | Reference from an object to the value of one of its instance fields.
JVMTI_HEAP_REFERENCE_ARRAY_ELEMENT | 3 | Reference from an array to one of its elements.
JVMTI_HEAP_REFERENCE_CLASS_LOADER | 4 | Reference from a class to its class loader.
JVMTI_HEAP_REFERENCE_SIGNERS | 5 | Reference from a class to its signers array.
JVMTI_HEAP_REFERENCE_PROTECTION_DOMAIN | 6 | Reference from a class to its protection domain.
JVMTI_HEAP_REFERENCE_INTERFACE | 7 | Reference from a class to one of its interfaces. Note: interfaces are defined via a constant pool reference, so the referenced interfaces may also be reported with a JVMTI_HEAP_REFERENCE_CONSTANT_POOL reference kind.
JVMTI_HEAP_REFERENCE_STATIC_FIELD | 8 | Reference from a class to the value of one of its static fields.
JVMTI_HEAP_REFERENCE_CONSTANT_POOL | 9 | Reference from a class to a resolved entry in the constant pool.
JVMTI_HEAP_REFERENCE_SUPERCLASS | 10 | Reference from a class to its superclass. A callback is bot sent if the superclass is java.lang.Object. Note: loaded classes define superclasses via a constant pool reference, so the referenced superclass may also be reported with a JVMTI_HEAP_REFERENCE_CONSTANT_POOL reference kind.
JVMTI_HEAP_REFERENCE_JNI_GLOBAL | 21 | Heap root reference: JNI global reference.
JVMTI_HEAP_REFERENCE_SYSTEM_CLASS | 22 | Heap root reference: System class.
JVMTI_HEAP_REFERENCE_MONITOR | 23 | Heap root reference: monitor.
JVMTI_HEAP_REFERENCE_STACK_LOCAL | 24 | Heap root reference: local variable on the stack.
JVMTI_HEAP_REFERENCE_JNI_LOCAL | 25 | Heap root reference: JNI local reference.
JVMTI_HEAP_REFERENCE_THREAD | 26 | Heap root reference: Thread.
JVMTI_HEAP_REFERENCE_OTHER | 27 | Heap root reference: other heap root reference.

Definitions for the single character type descriptors of primitive types.
Primitive Type Enumeration (jvmtiPrimitiveType)
Constant | Value | Description
JVMTI_PRIMITIVE_TYPE_BOOLEAN | 90 | 'Z' - Java programming language boolean - JNI jboolean
JVMTI_PRIMITIVE_TYPE_BYTE | 66 | 'B' - Java programming language byte - JNI jbyte
JVMTI_PRIMITIVE_TYPE_CHAR | 67 | 'C' - Java programming language char - JNI jchar
JVMTI_PRIMITIVE_TYPE_SHORT | 83 | 'S' - Java programming language short - JNI jshort
JVMTI_PRIMITIVE_TYPE_INT | 73 | 'I' - Java programming language int - JNI jint
JVMTI_PRIMITIVE_TYPE_LONG | 74 | 'J' - Java programming language long - JNI jlong
JVMTI_PRIMITIVE_TYPE_FLOAT | 70 | 'F' - Java programming language float - JNI jfloat
JVMTI_PRIMITIVE_TYPE_DOUBLE | 68 | 'D' - Java programming language double - JNI jdouble

Reference information structure for Field references

Reference information returned for JVMTI_HEAP_REFERENCE_FIELD and JVMTI_HEAP_REFERENCE_STATIC_FIELD references.

typedef struct {
    jint index;
} jvmtiHeapReferenceInfoField;
jvmtiHeapReferenceInfoField - Reference information structure for Field references
Field Type Description
index jint For JVMTI_HEAP_REFERENCE_FIELD, the referrer object is not a class or an inteface. In this case, index is the index of the field in the class of the referrer object. This class is referred to below as C.

For JVMTI_HEAP_REFERENCE_STATIC_FIELD, the referrer object is a class (referred to below as C) or an interface (referred to below as I). In this case, index is the index of the field in that class or interface.

If the referrer object is not an interface, then the field indices are determined as follows:
  • make a list of all the fields in C and its superclasses, starting with all the fields in java.lang.Object and ending with all the fields in C.
  • Within this list, put the fields for a given class in the order returned by GetClassFields.
  • Assign the fields in this list indices n, n+1, ..., in order, where n is the count of the fields in all the interfaces implemented by C. Note that C implements all interfaces directly implemented by its superclasses; as well as all superinterfaces of these interfaces.
If the referrer object is an interface, then the field indices are determined as follows:
  • make a list of the fields directly declared in I.
  • Within this list, put the fields in the order returned by GetClassFields.
  • Assign the fields in this list indices n, n+1, ..., in order, where n is the count of the fields in all the superinterfaces of I.
All fields are included in this computation, regardless of field modifier (static, public, private, etc).

For example, given the following classes and interfaces:
interface I0 {
    int p = 0;
}

interface I1 extends I0 {
    int x = 1;
}

interface I2 extends I0 {
    int y = 2;
}

class C1 implements I1 {
    public static int a = 3;
    private int b = 4;
}

class C2 extends C1 implements I2 {
    static int q = 5;
    final int r = 6;
}
Assume that GetClassFields called on C1 returns the fields of C1 in the order: a, b; and that the fields of C2 are returned in the order: q, r. An instance of class C1 will have the following field indices:
a | 2 | The count of the fields in the interfaces implemented by C1 is two (n=2): p of I0 and x of I1.
b | 3 | the subsequent index.
The class C1 will have the same field indices.

An instance of class C2 will have the following field indices:
a | 3 | The count of the fields in the interfaces implemented by C2 is three (n=3): p of I0, x of I1 and y of I2 (an interface of C2). Note that the field p of I0 is only included once.
b | 4 | the subsequent index to "a".
q | 5 | the subsequent index to "b".
r | 6 | the subsequent index to "q".
The class C2 will have the same field indices. Note that a field may have a different index depending on the object that is viewing it -- for example field "a" above. Note also: not all field indices may be visible from the callbacks, but all indices are shown for illustrative purposes.

The interface I1 will have the following field indices:
x 1 The count of the fields in the superinterfaces of I1 is one (n=1): p of I0.

Reference information structure for Array references

Reference information returned for JVMTI_HEAP_REFERENCE_ARRAY_ELEMENT references.

typedef struct {
    jint index;
} jvmtiHeapReferenceInfoArray;
jvmtiHeapReferenceInfoArray - Reference information structure for Array references
Field | Type | Description
index | jint | The array index.

Reference information structure for Constant Pool references

Reference information returned for JVMTI_HEAP_REFERENCE_CONSTANT_POOL references.

typedef struct {
    jint index;
} jvmtiHeapReferenceInfoConstantPool;
jvmtiHeapReferenceInfoConstantPool - Reference information structure for Constant Pool references
Field | Type | Description
index | jint | The index into the constant pool of the class. See the Constant Pool section of the Java Virtual Machine Specification description.

Reference information structure for Local Variable references

Reference information returned for JVMTI_HEAP_REFERENCE_STACK_LOCAL references.

typedef struct {
    jlong thread_tag;
    jlong thread_id;
    jint depth;
    jmethodID method;
    jlocation location;
    jint slot;
} jvmtiHeapReferenceInfoStackLocal;
jvmtiHeapReferenceInfoStackLocal - Reference information structure for Local Variable references
Field | Type | Description
thread_tag | jlong | The tag of the thread corresponding to this stack, zero if not tagged.
thread_id | jlong | The unique thread ID of the thread corresponding to this stack.
depth | jint | The depth of the frame.
method | jmethodID | The method executing in this frame.
location | jlocation | The currently executing location in this frame.
slot | jint | The slot number of the local variable.

Reference information structure for JNI local references

Reference information returned for JVMTI_HEAP_REFERENCE_JNI_LOCAL references.

typedef struct {
    jlong thread_tag;
    jlong thread_id;
    jint depth;
    jmethodID method;
} jvmtiHeapReferenceInfoJniLocal;
jvmtiHeapReferenceInfoJniLocal - Reference information structure for JNI local references
Field | Type | Description
thread_tag | jlong | The tag of the thread corresponding to this stack, zero if not tagged.
thread_id | jlong | The unique thread ID of the thread corresponding to this stack.
depth | jint | The depth of the frame.
method | jmethodID | The method executing in this frame.

Reference information structure for Other references

Reference information returned for other references.

typedef struct {
    jlong reserved1;
    jlong reserved2;
    jlong reserved3;
    jlong reserved4;
    jlong reserved5;
    jlong reserved6;
    jlong reserved7;
    jlong reserved8;
} jvmtiHeapReferenceInfoReserved;
jvmtiHeapReferenceInfoReserved - Reference information structure for Other references
Field | Type | Description
reserved1 | jlong | reserved for future use.
reserved2 | jlong | reserved for future use.
reserved3 | jlong | reserved for future use.
reserved4 | jlong | reserved for future use.
reserved5 | jlong | reserved for future use.
reserved6 | jlong | reserved for future use.
reserved7 | jlong | reserved for future use.
reserved8 | jlong | reserved for future use.

Reference information structure

The information returned about referrers. Represented as a union of the various kinds of reference information.

typedef union {
    jvmtiHeapReferenceInfoField field;
    jvmtiHeapReferenceInfoArray array;
    jvmtiHeapReferenceInfoConstantPool constant_pool;
    jvmtiHeapReferenceInfoStackLocal stack_local;
    jvmtiHeapReferenceInfoJniLocal jni_local;
    jvmtiHeapReferenceInfoReserved other;
} jvmtiHeapReferenceInfo;
jvmtiHeapReferenceInfo - Reference information structure
Field | Type | Description
field | jvmtiHeapReferenceInfoField | The referrer information for JVMTI_HEAP_REFERENCE_FIELD and JVMTI_HEAP_REFERENCE_STATIC_FIELD references.
array | jvmtiHeapReferenceInfoArray | The referrer information for For JVMTI_HEAP_REFERENCE_ARRAY_ELEMENT references.
constant_pool | jvmtiHeapReferenceInfoConstantPool | The referrer information for For JVMTI_HEAP_REFERENCE_CONSTANT_POOL references.
stack_local | jvmtiHeapReferenceInfoStackLocal | The referrer information for For JVMTI_HEAP_REFERENCE_STACK_LOCAL references.
jni_local | jvmtiHeapReferenceInfoJniLocal | The referrer information for For JVMTI_HEAP_REFERENCE_JNI_LOCAL references.
other | jvmtiHeapReferenceInfoReserved | reserved for future use.

Heap callback function structure

typedef struct {
    jvmtiHeapIterationCallback heap_iteration_callback;
    jvmtiHeapReferenceCallback heap_reference_callback;
    jvmtiPrimitiveFieldCallback primitive_field_callback;
    jvmtiArrayPrimitiveValueCallback array_primitive_value_callback;
    jvmtiStringPrimitiveValueCallback string_primitive_value_callback;
    jvmtiReservedCallback reserved5;
    jvmtiReservedCallback reserved6;
    jvmtiReservedCallback reserved7;
    jvmtiReservedCallback reserved8;
    jvmtiReservedCallback reserved9;
    jvmtiReservedCallback reserved10;
    jvmtiReservedCallback reserved11;
    jvmtiReservedCallback reserved12;
    jvmtiReservedCallback reserved13;
    jvmtiReservedCallback reserved14;
    jvmtiReservedCallback reserved15;
} jvmtiHeapCallbacks;
jvmtiHeapCallbacks - Heap callback function structure
Field | Type | Description
heap_iteration_callback | jvmtiHeapIterationCallback | The callback to be called to describe an object in the heap. Used by the IterateThroughHeap function, ignored by the FollowReferences function.
heap_reference_callback | jvmtiHeapReferenceCallback | The callback to be called to describe an object reference. Used by the FollowReferences function, ignored by the IterateThroughHeap function.
primitive_field_callback | jvmtiPrimitiveFieldCallback | The callback to be called to describe a primitive field.
array_primitive_value_callback | jvmtiArrayPrimitiveValueCallback | The callback to be called to describe an array of primitive values.
string_primitive_value_callback | jvmtiStringPrimitiveValueCallback | The callback to be called to describe a String value.
reserved5 | jvmtiReservedCallback | Reserved for future use..
reserved6 | jvmtiReservedCallback | Reserved for future use..
reserved7 | jvmtiReservedCallback | Reserved for future use..
reserved8 | jvmtiReservedCallback | Reserved for future use..
reserved9 | jvmtiReservedCallback | Reserved for future use..
reserved10 | jvmtiReservedCallback | Reserved for future use..
reserved11 | jvmtiReservedCallback | Reserved for future use..
reserved12 | jvmtiReservedCallback | Reserved for future use..
reserved13 | jvmtiReservedCallback | Reserved for future use..
reserved14 | jvmtiReservedCallback | Reserved for future use..
reserved15 | jvmtiReservedCallback | Reserved for future use..

Rationale: The heap dumping functionality (below) uses a callback for each object. While it would seem that a buffered approach would provide better throughput, tests do not show this to be the case--possibly due to locality of memory reference or array access overhead.

Heap Iteration Callback

typedef jint (JNICALL *jvmtiHeapIterationCallback)
    (jlong class_tag,
     jlong size,
     jlong* tag_ptr,
     jint length,
     void* user_data);
Agent supplied callback function. Describes (but does not pass in) an object in the heap.

This function should return a bit vector of the desired visit control flags. This will determine if the entire iteration should be aborted (the JVMTI_VISIT_OBJECTS flag is ignored).

See the heap callback function restrictions.

Parameters
Name | Type | Description
class_tag | jlong | The tag of the class of object (zero if the class is not tagged). If the object represents a runtime class, the class_tag is the tag associated with java.lang.Class (zero if java.lang.Class is not tagged).
size | jlong | Size of the object (in bytes). See GetObjectSize.
tag_ptr | jlong* | The object tag value, or zero if the object is not tagged. To set the tag value to be associated with the object the agent sets the jlong pointed to by the parameter.
length | jint | If this object is an array, the length of the array. Otherwise negative one (-1).
user_data | void* | The user supplied data that was passed into the iteration function.

Heap Reference Callback

typedef jint (JNICALL *jvmtiHeapReferenceCallback)
    (jvmtiHeapReferenceKind reference_kind,
     const jvmtiHeapReferenceInfo* reference_info,
     jlong class_tag,
     jlong referrer_class_tag,
     jlong size,
     jlong* tag_ptr,
     jlong* referrer_tag_ptr,
     jint length,
     void* user_data);
Agent supplied callback function. Describes a reference from an object or the VM (the referrer) to another object (the referree) or a heap root to a referree.

This function should return a bit vector of the desired visit control flags. This will determine if the objects referenced by the referree should be visited or if the entire iteration should be aborted.

See the heap callback function restrictions.

Parameters
Name | Type | Description
reference_kind | jvmtiHeapReferenceKind | The kind of reference.
reference_info | const jvmtiHeapReferenceInfo * | Details about the reference. Set when the reference_kind is JVMTI_HEAP_REFERENCE_FIELD, JVMTI_HEAP_REFERENCE_STATIC_FIELD, JVMTI_HEAP_REFERENCE_ARRAY_ELEMENT, JVMTI_HEAP_REFERENCE_CONSTANT_POOL, JVMTI_HEAP_REFERENCE_STACK_LOCAL, or JVMTI_HEAP_REFERENCE_JNI_LOCAL. Otherwise NULL.
class_tag | jlong | The tag of the class of referree object (zero if the class is not tagged). If the referree object represents a runtime class, the class_tag is the tag associated with java.lang.Class (zero if java.lang.Class is not tagged).
referrer_class_tag | jlong | The tag of the class of the referrer object (zero if the class is not tagged or the referree is a heap root). If the referrer object represents a runtime class, the referrer_class_tag is the tag associated with the java.lang.Class (zero if java.lang.Class is not tagged).
size | jlong | Size of the referree object (in bytes). See GetObjectSize.
tag_ptr | jlong* | Points to the referree object tag value, or zero if the object is not tagged. To set the tag value to be associated with the object the agent sets the jlong pointed to by the parameter.
referrer_tag_ptr | jlong* | Points to the tag of the referrer object, or points to the zero if the referrer object is not tagged. NULL if the referrer in not an object (that is, this callback is reporting a heap root). To set the tag value to be associated with the referrer object the agent sets the jlong pointed to by the parameter. If this callback is reporting a reference from an object to itself, referrer_tag_ptr == tag_ptr.
length | jint | If this object is an array, the length of the array. Otherwise negative one (-1).
user_data | void* | The user supplied data that was passed into the iteration function.

Primitive Field Callback

typedef jint (JNICALL *jvmtiPrimitiveFieldCallback)
    (jvmtiHeapReferenceKind kind,
     const jvmtiHeapReferenceInfo* info,
     jlong object_class_tag,
     jlong* object_tag_ptr,
     jvalue value,
     jvmtiPrimitiveType value_type,
     void* user_data);
Agent supplied callback function which describes a primitive field of an object (the object). A primitive field is a field whose type is a primitive type. This callback will describe a static field if the object is a class, and otherwise will describe an instance field.

This function should return a bit vector of the desired visit control flags. This will determine if the entire iteration should be aborted (the JVMTI_VISIT_OBJECTS flag is ignored).

See the heap callback function restrictions.

Parameters
Name | Type | Description
kind | jvmtiHeapReferenceKind | The kind of field -- instance or static (JVMTI_HEAP_REFERENCE_FIELD or JVMTI_HEAP_REFERENCE_STATIC_FIELD).
info | const jvmtiHeapReferenceInfo * | Which field (the field index).
object_class_tag | jlong | The tag of the class of the object (zero if the class is not tagged). If the object represents a runtime class, the object_class_tag is the tag associated with java.lang.Class (zero if java.lang.Class is not tagged).
object_tag_ptr | jlong* | Points to the tag of the object, or zero if the object is not tagged. To set the tag value to be associated with the object the agent sets the jlong pointed to by the parameter.
value | jvalue | The value of the field.
value_type | jvmtiPrimitiveType | The type of the field.
user_data | void* | The user supplied data that was passed into the iteration function.

Array Primitive Value Callback

typedef jint (JNICALL *jvmtiArrayPrimitiveValueCallback)
    (jlong class_tag,
     jlong size,
     jlong* tag_ptr,
     jint element_count,
     jvmtiPrimitiveType element_type,
     const void* elements,
     void* user_data);
Agent supplied callback function. Describes the values in an array of a primitive type.

This function should return a bit vector of the desired visit control flags. This will determine if the entire iteration should be aborted (the JVMTI_VISIT_OBJECTS flag is ignored).

See the heap callback function restrictions.

Parameters
Name | Type | Description
class_tag | jlong | The tag of the class of the array object (zero if the class is not tagged).
size | jlong | Size of the array (in bytes). See GetObjectSize.
tag_ptr | jlong* | Points to the tag of the array object, or zero if the object is not tagged. To set the tag value to be associated with the object the agent sets the jlong pointed to by the parameter.
element_count | jint | The length of the primitive array.
element_type | jvmtiPrimitiveType | The type of the elements of the array.
elements | const void* | The elements of the array in a packed array of element_count items of element_type size each.
user_data | void* | The user supplied data that was passed into the iteration function.

String Primitive Value Callback

typedef jint (JNICALL *jvmtiStringPrimitiveValueCallback)
    (jlong class_tag,
     jlong size,
     jlong* tag_ptr,
     const jchar* value,
     jint value_length,
     void* user_data);
Agent supplied callback function. Describes the value of a java.lang.String.

This function should return a bit vector of the desired visit control flags. This will determine if the entire iteration should be aborted (the JVMTI_VISIT_OBJECTS flag is ignored).

See the heap callback function restrictions.

Parameters
Name | Type | Description
class_tag | jlong | The tag of the class of the String class (zero if the class is not tagged).
size | jlong | Size of the string (in bytes). See GetObjectSize.
tag_ptr | jlong* | Points to the tag of the String object, or zero if the object is not tagged. To set the tag value to be associated with the object the agent sets the jlong pointed to by the parameter.
value | const jchar* | The value of the String, encoded as a Unicode string.
value_length | jint | The length of the string. The length is equal to the number of 16-bit Unicode characters in the string.
user_data | void* | The user supplied data that was passed into the iteration function.

reserved for future use Callback

typedef jint (JNICALL *jvmtiReservedCallback)
    ();
Placeholder -- reserved for future use.

Parameters
Name Type Description

Follow References

jvmtiError
FollowReferences(jvmtiEnv* env,
            jint heap_filter,
            jclass klass,
            jobject initial_object,
            const jvmtiHeapCallbacks* callbacks,
            const void* user_data)
This function initiates a traversal over the objects that are directly and indirectly reachable from the specified object or, if initial_object is not specified, all objects reachable from the heap roots. The heap root are the set of system classes, JNI globals, references from thread stacks, and other objects used as roots for the purposes of garbage collection.

This function operates by traversing the reference graph. Let A, B, ... represent objects. When a reference from A to B is traversed, when a reference from a heap root to B is traversed, or when B is specified as the initial_object, then B is said to be visited. A reference from A to B is not traversed until A is visited. References are reported in the same order that the references are traversed. Object references are reported by invoking the agent supplied callback function jvmtiHeapReferenceCallback. In a reference from A to B, A is known as the referrer and B as the referree. The callback is invoked exactly once for each reference from a referrer; this is true even if there are reference cycles or multiple paths to the referrer. There may be more than one reference between a referrer and a referree, each reference is reported. These references may be distinguished by examining the reference_kind and reference_info parameters of the jvmtiHeapReferenceCallback callback.

This function reports a Java programming language view of object references, not a virtual machine implementation view. The following object references are reported when they are non-null:
  • Instance objects report references to each non-primitive instance fields (including inherited fields).
  • Instance objects report a reference to the object type (class).
  • Classes report a reference to the superclass and directly implemented/extended interfaces.
  • Classes report a reference to the class loader, protection domain, signers, and resolved entries in the constant pool.
  • Classes report a reference to each directly declared non-primitive static field.
  • Arrays report a reference to the array type (class) and each array element.
  • Primitive arrays report a reference to the array type.

This function can also be used to examine primitive (non-object) values. The primitive value of an array or String is reported after the object has been visited; it is reported by invoking the agent supplied callback function jvmtiArrayPrimitiveValueCallback or jvmtiStringPrimitiveValueCallback. A primitive field is reported after the object with that field is visited; it is reported by invoking the agent supplied callback function jvmtiPrimitiveFieldCallback.

Whether a callback is provided or is NULL only determines whether the callback will be invoked, it does not influence which objects are visited nor does it influence whether other callbacks will be invoked. However, the visit control flags returned by jvmtiHeapReferenceCallback do determine if the objects referenced by the current object as visited. The heap filter flags and klass provided as parameters to this function do not control which objects are visited but they do control which objects and primitive values are reported by the callbacks. For example, if the only callback that was set is array_primitive_value_callback and klass is set to the array of bytes class, then only arrays of byte will be reported. The table below summarizes this:

 | Controls objects visited | Controls objects reported | Controls primitives reported
the Heap Visit Control Flags returned by jvmtiHeapReferenceCallback | Yes | Yes, since visits are controlled | Yes, since visits are controlled
object_reference_callback in callbacks set | No | Yes | No
heap_filter | No | Yes | Yes
klass | No | Yes | Yes

During the execution of this function the state of the heap does not change: no objects are allocated, no objects are garbage collected, and the state of objects (including held values) does not change. As a result, threads executing Java programming language code, threads attempting to resume the execution of Java programming language code, and threads attempting to execute JNI functions are typically stalled.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 115 | 1.1

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_tag_objects | Can set and get tags, as described in the Heap category.

Parameters
Name | Type | Description
heap_filter | jint | This bit vector of heap filter flags. restricts the objects for which the callback function is called. This applies to both the object and primitive callbacks.
klass | jclass | Callbacks are only reported when the object is an instance of this class. Objects which are instances of a subclass of klass are not reported. If klass is an interface, no objects are reported. This applies to both the object and primitive callbacks. If klass is NULL, callbacks are not limited to instances of a particular class.
initial_object | jobject | The object to follow If initial_object is NULL, references are followed from the heap roots.
callbacks | const jvmtiHeapCallbacks * | Structure defining the set of callback functions. Agent passes in a pointer to jvmtiHeapCallbacks.
user_data | const void * | User supplied data to be passed to the callback. Agent passes in a pointer. If user_data is NULL, NULL is passed as the user supplied data.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_tag_objects. Use AddCapabilities.
JVMTI_ERROR_INVALID_CLASS | klass is not a valid class.
JVMTI_ERROR_INVALID_OBJECT | initial_object is not a valid object.
JVMTI_ERROR_NULL_POINTER | callbacks is NULL.

Iterate Through Heap

jvmtiError
IterateThroughHeap(jvmtiEnv* env,
            jint heap_filter,
            jclass klass,
            const jvmtiHeapCallbacks* callbacks,
            const void* user_data)
Initiate an iteration over all objects in the heap. This includes both reachable and unreachable objects. Objects are visited in no particular order.

Heap objects are reported by invoking the agent supplied callback function jvmtiHeapIterationCallback. References between objects are not reported. If only reachable objects are desired, or if object reference information is needed, use FollowReferences.

This function can also be used to examine primitive (non-object) values. The primitive value of an array or String is reported after the object has been visited; it is reported by invoking the agent supplied callback function jvmtiArrayPrimitiveValueCallback or jvmtiStringPrimitiveValueCallback. A primitive field is reported after the object with that field is visited; it is reported by invoking the agent supplied callback function jvmtiPrimitiveFieldCallback.

Unless the iteration is aborted by the Heap Visit Control Flags returned by a callback, all objects in the heap are visited. Whether a callback is provided or is NULL only determines whether the callback will be invoked, it does not influence which objects are visited nor does it influence whether other callbacks will be invoked. The heap filter flags and klass provided as parameters to this function do not control which objects are visited but they do control which objects and primitive values are reported by the callbacks. For example, if the only callback that was set is array_primitive_value_callback and klass is set to the array of bytes class, then only arrays of byte will be reported. The table below summarizes this (contrast this with FollowReferences):

 | Controls objects visited | Controls objects reported | Controls primitives reported
the Heap Visit Control Flags returned by jvmtiHeapIterationCallback | No (unless they abort the iteration) | No (unless they abort the iteration) | No (unless they abort the iteration)
object_callback in callbacks set | No | Yes | No
heap_filter | No | Yes | Yes
klass | No | Yes | Yes

During the execution of this function the state of the heap does not change: no objects are allocated, no objects are garbage collected, and the state of objects (including held values) does not change. As a result, threads executing Java programming language code, threads attempting to resume the execution of Java programming language code, and threads attempting to execute JNI functions are typically stalled.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 116 | 1.1

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_tag_objects | Can set and get tags, as described in the Heap category.

Parameters
Name | Type | Description
heap_filter | jint | This bit vector of heap filter flags. restricts the objects for which the callback function is called. This applies to both the object and primitive callbacks.
klass | jclass | Callbacks are only reported when the object is an instance of this class. Objects which are instances of a subclass of klass are not reported. If klass is an interface, no objects are reported. This applies to both the object and primitive callbacks. If klass is NULL, callbacks are not limited to instances of a particular class.
callbacks | const jvmtiHeapCallbacks * | Structure defining the set callback functions. Agent passes in a pointer to jvmtiHeapCallbacks.
user_data | const void * | User supplied data to be passed to the callback. Agent passes in a pointer. If user_data is NULL, NULL is passed as the user supplied data.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_tag_objects. Use AddCapabilities.
JVMTI_ERROR_INVALID_CLASS | klass is not a valid class.
JVMTI_ERROR_NULL_POINTER | callbacks is NULL.

Get Tag

jvmtiError
GetTag(jvmtiEnv* env,
            jobject object,
            jlong* tag_ptr)
Retrieve the tag associated with an object. The tag is a long value typically used to store a unique identifier or pointer to object information. The tag is set with SetTag. Objects for which no tags have been set return a tag value of zero.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 106 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_tag_objects | Can set and get tags, as described in the Heap category.

Parameters
Name | Type | Description
object | jobject | The object whose tag is to be retrieved.
tag_ptr | jlong* | On return, the referenced long is set to the value of the tag. Agent passes a pointer to a jlong. On return, the jlong has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_tag_objects. Use AddCapabilities.
JVMTI_ERROR_INVALID_OBJECT | object is not an object.
JVMTI_ERROR_NULL_POINTER | tag_ptr is NULL.

Set Tag

jvmtiError
SetTag(jvmtiEnv* env,
            jobject object,
            jlong tag)
Set the tag associated with an object. The tag is a long value typically used to store a unique identifier or pointer to object information. The tag is visible with GetTag.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 107 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_tag_objects | Can set and get tags, as described in the Heap category.

Parameters
Name | Type | Description
object | jobject | The object whose tag is to be set.
tag | jlong | The new value of the tag.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_tag_objects. Use AddCapabilities.
JVMTI_ERROR_INVALID_OBJECT | object is not an object.

Get Objects With Tags

jvmtiError
GetObjectsWithTags(jvmtiEnv* env,
            jint tag_count,
            const jlong* tags,
            jint* count_ptr,
            jobject** object_result_ptr,
            jlong** tag_result_ptr)
Return objects in the heap with the specified tags. The format is parallel arrays of objects and tags.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 114 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_tag_objects | Can set and get tags, as described in the Heap category.

Parameters
Name | Type | Description
tag_count | jint | Number of tags to scan for.
tags | const jlong * | Scan for objects with these tags. Zero is not permitted in this array. Agent passes in an array of tag_count elements of jlong.
count_ptr | jint * | Return the number of objects with any of the tags in tags. Agent passes a pointer to a jint. On return, the jint has been set.
object_result_ptr | jobject ** | Returns the array of objects with any of the tags in tags. Agent passes a pointer to a jobject*. On return, the jobject* points to a newly allocated array of size *count_ptr. The array should be freed with Deallocate. If object_result_ptr is NULL, this information is not returned. The objects returned by object_result_ptr are JNI local references and must be managed.
tag_result_ptr | jlong ** | For each object in object_result_ptr, return the tag at the corresponding index. Agent passes a pointer to a jlong*. On return, the jlong* points to a newly allocated array of size *count_ptr. The array should be freed with Deallocate. If tag_result_ptr is NULL, this information is not returned.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_tag_objects. Use AddCapabilities.
JVMTI_ERROR_ILLEGAL_ARGUMENT | Zero is present in tags.
JVMTI_ERROR_ILLEGAL_ARGUMENT | tag_count is less than 0.
JVMTI_ERROR_NULL_POINTER | tags is NULL.
JVMTI_ERROR_NULL_POINTER | count_ptr is NULL.

Force Garbage Collection

jvmtiError
ForceGarbageCollection(jvmtiEnv* env)
Force the VM to perform a garbage collection. The garbage collection is as complete as possible. This function does not cause finalizers to be run. This function does not return until the garbage collection is finished.

Although garbage collection is as complete as possible there is no guarantee that all ObjectFree events will have been sent by the time that this function returns. In particular, an object may be prevented from being freed because it is awaiting finalization.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 108 | 1.0

Capabilities
Required Functionality

Parameters
Name Type Description

Errors
This function returns a universal error

Heap (1.0)

Heap (1.0) functions:
  • Iterate Over Objects Reachable From Object
  • Iterate Over Reachable Objects
  • Iterate Over Heap
  • Iterate Over Instances Of Class
Heap (1.0) function types:
  • Heap Object Callback
  • Heap Root Object Callback
  • Stack Reference Object Callback
  • Object Reference Callback
Heap (1.0) types:
  • jvmtiHeapObjectFilter - Heap Object Filter Enumeration
  • jvmtiHeapRootKind - Heap Root Kind Enumeration
  • jvmtiObjectReferenceKind - Object Reference Enumeration
  • jvmtiIterationControl - Iteration Control Enumeration
These functions and data types were introduced in the original JVM TI version 1.0 and have been superseded by more powerful and flexible versions which:
  • Allow access to primitive values (the value of Strings, arrays, and primitive fields)
  • Allow the tag of the referrer to be set, thus enabling more efficient localized reference graph building
  • Provide more extensive filtering abilities
  • Are extensible, allowing their abilities to grow in future versions of JVM TI

Please use the current Heap functions.

Heap Object Filter Enumeration (jvmtiHeapObjectFilter)
Constant | Value | Description
JVMTI_HEAP_OBJECT_TAGGED | 1 | Tagged objects only.
JVMTI_HEAP_OBJECT_UNTAGGED | 2 | Untagged objects only.
JVMTI_HEAP_OBJECT_EITHER | 3 | Either tagged or untagged objects.
Heap Root Kind Enumeration (jvmtiHeapRootKind)
Constant | Value | Description
JVMTI_HEAP_ROOT_JNI_GLOBAL | 1 | JNI global reference.
JVMTI_HEAP_ROOT_SYSTEM_CLASS | 2 | System class.
JVMTI_HEAP_ROOT_MONITOR | 3 | Monitor.
JVMTI_HEAP_ROOT_STACK_LOCAL | 4 | Stack local.
JVMTI_HEAP_ROOT_JNI_LOCAL | 5 | JNI local reference.
JVMTI_HEAP_ROOT_THREAD | 6 | Thread.
JVMTI_HEAP_ROOT_OTHER | 7 | Other.
Object Reference Enumeration (jvmtiObjectReferenceKind)
Constant | Value | Description
JVMTI_REFERENCE_CLASS | 1 | Reference from an object to its class.
JVMTI_REFERENCE_FIELD | 2 | Reference from an object to the value of one of its instance fields. For references of this kind the referrer_index parameter to the jvmtiObjectReferenceCallback is the index of the the instance field. The index is based on the order of all the object's fields. This includes all fields of the directly declared static and instance fields in the class, and includes all fields (both public and private) fields declared in superclasses and superinterfaces. The index is thus calculated by summing the index of the field in the directly declared class (see GetClassFields), with the total number of fields (both public and private) declared in all superclasses and superinterfaces. The index starts at zero.
JVMTI_REFERENCE_ARRAY_ELEMENT | 3 | Reference from an array to one of its elements. For references of this kind the referrer_index parameter to the jvmtiObjectReferenceCallback is the array index.
JVMTI_REFERENCE_CLASS_LOADER | 4 | Reference from a class to its class loader.
JVMTI_REFERENCE_SIGNERS | 5 | Reference from a class to its signers array.
JVMTI_REFERENCE_PROTECTION_DOMAIN | 6 | Reference from a class to its protection domain.
JVMTI_REFERENCE_INTERFACE | 7 | Reference from a class to one of its interfaces.
JVMTI_REFERENCE_STATIC_FIELD 8 Reference from a class to the value of one of its static fields. For references of this kind the referrer_index parameter to the jvmtiObjectReferenceCallback is the index of the the static field. The index is based on the order of all the object's fields. This includes all fields of the directly declared static and instance fields in the class, and includes all fields (both public and private) fields declared in superclasses and superinterfaces. The index is thus calculated by summing the index of the field in the directly declared class (see GetClassFields), with the total number of fields (both public and private) declared in all superclasses and superinterfaces. The index starts at zero. Note: this definition differs from that in the JVM TI 1.0 Specification.

Rationale: No known implementations used the 1.0 definition.
JVMTI_REFERENCE_CONSTANT_POOL | 9 | Reference from a class to a resolved entry in the constant pool. For references of this kind the referrer_index parameter to the jvmtiObjectReferenceCallback is the index into constant pool table of the class, starting at 1. See the Constant Pool section of the Java Virtual Machine Specification
Iteration Control Enumeration (jvmtiIterationControl)
Constant | Value | Description
JVMTI_ITERATION_CONTINUE | 1 | Continue the iteration. If this is a reference iteration, follow the references of this object.
JVMTI_ITERATION_IGNORE | 2 | Continue the iteration. If this is a reference iteration, ignore the references of this object.
JVMTI_ITERATION_ABORT | 0 | Abort the iteration.

Heap Object Callback

typedef jvmtiIterationControl (JNICALL *jvmtiHeapObjectCallback)
    (jlong class_tag,
     jlong size,
     jlong* tag_ptr,
     void* user_data);
Agent supplied callback function. Describes (but does not pass in) an object in the heap.

Return value should be JVMTI_ITERATION_CONTINUE to continue iteration, or JVMTI_ITERATION_ABORT to stop iteration.

See the heap callback function restrictions.

Parameters
Name | Type | Description
class_tag | jlong | The tag of the class of object (zero if the class is not tagged). If the object represents a runtime class, the class_tag is the tag associated with java.lang.Class (zero if java.lang.Class is not tagged).
size | jlong | Size of the object (in bytes). See GetObjectSize.
tag_ptr | jlong* | The object tag value, or zero if the object is not tagged. To set the tag value to be associated with the object the agent sets the jlong pointed to by the parameter.
user_data | void* | The user supplied data that was passed into the iteration function.

Heap Root Object Callback

typedef jvmtiIterationControl (JNICALL *jvmtiHeapRootCallback)
    (jvmtiHeapRootKind root_kind,
     jlong class_tag,
     jlong size,
     jlong* tag_ptr,
     void* user_data);
Agent supplied callback function. Describes (but does not pass in) an object that is a root for the purposes of garbage collection.

Return value should be JVMTI_ITERATION_CONTINUE to continue iteration, JVMTI_ITERATION_IGNORE to continue iteration without pursuing references from referree object or JVMTI_ITERATION_ABORT to stop iteration.

See the heap callback function restrictions.

Parameters
Name | Type | Description
root_kind | jvmtiHeapRootKind | The kind of heap root.
class_tag | jlong | The tag of the class of object (zero if the class is not tagged). If the object represents a runtime class, the class_tag is the tag associated with java.lang.Class (zero if java.lang.Class is not tagged).
size | jlong | Size of the object (in bytes). See GetObjectSize.
tag_ptr | jlong* | The object tag value, or zero if the object is not tagged. To set the tag value to be associated with the object the agent sets the jlong pointed to by the parameter.
user_data | void* | The user supplied data that was passed into the iteration function.

Stack Reference Object Callback

typedef jvmtiIterationControl (JNICALL *jvmtiStackReferenceCallback)
    (jvmtiHeapRootKind root_kind,
     jlong class_tag,
     jlong size,
     jlong* tag_ptr,
     jlong thread_tag,
     jint depth,
     jmethodID method,
     jint slot,
     void* user_data);
Agent supplied callback function. Describes (but does not pass in) an object on the stack that is a root for the purposes of garbage collection.

Return value should be JVMTI_ITERATION_CONTINUE to continue iteration, JVMTI_ITERATION_IGNORE to continue iteration without pursuing references from referree object or JVMTI_ITERATION_ABORT to stop iteration.

See the heap callback function restrictions.

Parameters
Name | Type | Description
root_kind | jvmtiHeapRootKind | The kind of root (either JVMTI_HEAP_ROOT_STACK_LOCAL or JVMTI_HEAP_ROOT_JNI_LOCAL).
class_tag | jlong | The tag of the class of object (zero if the class is not tagged). If the object represents a runtime class, the class_tag is the tag associated with java.lang.Class (zero if java.lang.Class is not tagged).
size | jlong | Size of the object (in bytes). See GetObjectSize.
tag_ptr | jlong* | The object tag value, or zero if the object is not tagged. To set the tag value to be associated with the object the agent sets the jlong pointed to by the parameter.
thread_tag | jlong | The tag of the thread corresponding to this stack, zero if not tagged.
depth | jint | The depth of the frame.
method | jmethodID | The method executing in this frame.
slot | jint | The slot number.
user_data | void* | The user supplied data that was passed into the iteration function.

Object Reference Callback

typedef jvmtiIterationControl (JNICALL *jvmtiObjectReferenceCallback)
    (jvmtiObjectReferenceKind reference_kind,
     jlong class_tag,
     jlong size,
     jlong* tag_ptr,
     jlong referrer_tag,
     jint referrer_index,
     void* user_data);
Agent supplied callback function. Describes a reference from an object (the referrer) to another object (the referree).

Return value should be JVMTI_ITERATION_CONTINUE to continue iteration, JVMTI_ITERATION_IGNORE to continue iteration without pursuing references from referree object or JVMTI_ITERATION_ABORT to stop iteration.

See the heap callback function restrictions.

Parameters
Name | Type | Description
reference_kind | jvmtiObjectReferenceKind | The type of reference.
class_tag | jlong | The tag of the class of referree object (zero if the class is not tagged). If the referree object represents a runtime class, the class_tag is the tag associated with java.lang.Class (zero if java.lang.Class is not tagged).
size | jlong | Size of the referree object (in bytes). See GetObjectSize.
tag_ptr | jlong* | The referree object tag value, or zero if the object is not tagged. To set the tag value to be associated with the object the agent sets the jlong pointed to by the parameter.
referrer_tag | jlong | The tag of the referrer object, or zero if the referrer object is not tagged.
referrer_index | jint | For references of type JVMTI_REFERENCE_FIELD or JVMTI_REFERENCE_STATIC_FIELD the index of the field in the referrer object. The index is based on the order of all the object's fields - see JVMTI_REFERENCE_FIELD or JVMTI_REFERENCE_STATIC_FIELD for further description. For references of type JVMTI_REFERENCE_ARRAY_ELEMENT the array index - see JVMTI_REFERENCE_ARRAY_ELEMENT for further description. For references of type JVMTI_REFERENCE_CONSTANT_POOL the index into the constant pool of the class - see JVMTI_REFERENCE_CONSTANT_POOL for further description. For references of other kinds the referrer_index is -1.
user_data | void* | The user supplied data that was passed into the iteration function.

Iterate Over Objects Reachable From Object

jvmtiError
IterateOverObjectsReachableFromObject(jvmtiEnv* env,
            jobject object,
            jvmtiObjectReferenceCallback object_reference_callback,
            const void* user_data)
This function iterates over all objects that are directly and indirectly reachable from the specified object. For each object A (known as the referrer) with a reference to object B the specified callback function is called to describe the object reference. The callback is called exactly once for each reference from a referrer; this is true even if there are reference cycles or multiple paths to the referrer. There may be more than one reference between a referrer and a referree, These may be distinguished by the jvmtiObjectReferenceCallback.reference_kind and jvmtiObjectReferenceCallback.referrer_index. The callback for an object will always occur after the callback for its referrer.

See FollowReferences for the object references which are reported.

During the execution of this function the state of the heap does not change: no objects are allocated, no objects are garbage collected, and the state of objects (including held values) does not change. As a result, threads executing Java programming language code, threads attempting to resume the execution of Java programming language code, and threads attempting to execute JNI functions are typically stalled.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 109 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_tag_objects | Can set and get tags, as described in the Heap category.

Parameters
Name | Type | Description
object | jobject | The object
object_reference_callback | jvmtiObjectReferenceCallback | The callback to be called to describe each object reference.
user_data | const void * | User supplied data to be passed to the callback. Agent passes in a pointer. If user_data is NULL, NULL is passed as the user supplied data.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_tag_objects. Use AddCapabilities.
JVMTI_ERROR_INVALID_OBJECT | object is not an object.
JVMTI_ERROR_NULL_POINTER | object_reference_callback is NULL.

Iterate Over Reachable Objects

jvmtiError
IterateOverReachableObjects(jvmtiEnv* env,
            jvmtiHeapRootCallback heap_root_callback,
            jvmtiStackReferenceCallback stack_ref_callback,
            jvmtiObjectReferenceCallback object_ref_callback,
            const void* user_data)
This function iterates over the root objects and all objects that are directly and indirectly reachable from the root objects. The root objects comprise the set of system classes, JNI globals, references from thread stacks, and other objects used as roots for the purposes of garbage collection.

For each root the heap_root_callback or stack_ref_callback callback is called. An object can be a root object for more than one reason and in that case the appropriate callback is called for each reason.

For each object reference the object_ref_callback callback function is called to describe the object reference. The callback is called exactly once for each reference from a referrer; this is true even if there are reference cycles or multiple paths to the referrer. There may be more than one reference between a referrer and a referree, These may be distinguished by the jvmtiObjectReferenceCallback.reference_kind and jvmtiObjectReferenceCallback.referrer_index. The callback for an object will always occur after the callback for its referrer.

See FollowReferences for the object references which are reported.

Roots are always reported to the profiler before any object references are reported. In other words, the object_ref_callback callback will not be called until the appropriate callback has been called for all roots. If the object_ref_callback callback is specified as NULL then this function returns after reporting the root objects to the profiler.

During the execution of this function the state of the heap does not change: no objects are allocated, no objects are garbage collected, and the state of objects (including held values) does not change. As a result, threads executing Java programming language code, threads attempting to resume the execution of Java programming language code, and threads attempting to execute JNI functions are typically stalled.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 110 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_tag_objects | Can set and get tags, as described in the Heap category.

Parameters
Name | Type | Description
heap_root_callback | jvmtiHeapRootCallback | The callback function to be called for each heap root of type JVMTI_HEAP_ROOT_JNI_GLOBAL, JVMTI_HEAP_ROOT_SYSTEM_CLASS, JVMTI_HEAP_ROOT_MONITOR, JVMTI_HEAP_ROOT_THREAD, or JVMTI_HEAP_ROOT_OTHER. If heap_root_callback is NULL, do not report heap roots.
stack_ref_callback | jvmtiStackReferenceCallback | The callback function to be called for each heap root of JVMTI_HEAP_ROOT_STACK_LOCAL or JVMTI_HEAP_ROOT_JNI_LOCAL. If stack_ref_callback is NULL, do not report stack references.
object_ref_callback | jvmtiObjectReferenceCallback | The callback function to be called for each object reference. If object_ref_callback is NULL, do not follow references from the root objects.
user_data | const void * | User supplied data to be passed to the callback. Agent passes in a pointer. If user_data is NULL, NULL is passed as the user supplied data.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_tag_objects. Use AddCapabilities.

Iterate Over Heap

jvmtiError
IterateOverHeap(jvmtiEnv* env,
            jvmtiHeapObjectFilter object_filter,
            jvmtiHeapObjectCallback heap_object_callback,
            const void* user_data)
Iterate over all objects in the heap. This includes both reachable and unreachable objects.

The object_filter parameter indicates the objects for which the callback function is called. If this parameter is JVMTI_HEAP_OBJECT_TAGGED then the callback will only be called for every object that is tagged. If the parameter is JVMTI_HEAP_OBJECT_UNTAGGED then the callback will only be for objects that are not tagged. If the parameter is JVMTI_HEAP_OBJECT_EITHER then the callback will be called for every object in the heap, irrespective of whether it is tagged or not.

During the execution of this function the state of the heap does not change: no objects are allocated, no objects are garbage collected, and the state of objects (including held values) does not change. As a result, threads executing Java programming language code, threads attempting to resume the execution of Java programming language code, and threads attempting to execute JNI functions are typically stalled.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 111 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_tag_objects | Can set and get tags, as described in the Heap category.

Parameters
Name | Type | Description
object_filter | jvmtiHeapObjectFilter | Indicates the objects for which the callback function is called.
heap_object_callback | jvmtiHeapObjectCallback | The iterator function to be called for each object matching the object_filter.
user_data | const void * | User supplied data to be passed to the callback. Agent passes in a pointer. If user_data is NULL, NULL is passed as the user supplied data.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_tag_objects. Use AddCapabilities.
JVMTI_ERROR_ILLEGAL_ARGUMENT | object_filter is not a jvmtiHeapObjectFilter.
JVMTI_ERROR_NULL_POINTER | heap_object_callback is NULL.

Iterate Over Instances Of Class

jvmtiError
IterateOverInstancesOfClass(jvmtiEnv* env,
            jclass klass,
            jvmtiHeapObjectFilter object_filter,
            jvmtiHeapObjectCallback heap_object_callback,
            const void* user_data)
Iterate over all objects in the heap that are instances of the specified class. This includes direct instances of the specified class and instances of all subclasses of the specified class. This includes both reachable and unreachable objects.

The object_filter parameter indicates the objects for which the callback function is called. If this parameter is JVMTI_HEAP_OBJECT_TAGGED then the callback will only be called for every object that is tagged. If the parameter is JVMTI_HEAP_OBJECT_UNTAGGED then the callback will only be called for objects that are not tagged. If the parameter is JVMTI_HEAP_OBJECT_EITHER then the callback will be called for every object in the heap, irrespective of whether it is tagged or not.

During the execution of this function the state of the heap does not change: no objects are allocated, no objects are garbage collected, and the state of objects (including held values) does not change. As a result, threads executing Java programming language code, threads attempting to resume the execution of Java programming language code, and threads attempting to execute JNI functions are typically stalled.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 112 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_tag_objects | Can set and get tags, as described in the Heap category.

Parameters
Name | Type | Description
klass | jclass | Iterate over objects of this class only.
object_filter | jvmtiHeapObjectFilter | Indicates the objects for which the callback function is called.
heap_object_callback | jvmtiHeapObjectCallback | The iterator function to be called for each klass instance matching the object_filter.
user_data | const void * | User supplied data to be passed to the callback. Agent passes in a pointer. If user_data is NULL, NULL is passed as the user supplied data.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_tag_objects. Use AddCapabilities.
JVMTI_ERROR_INVALID_CLASS | klass is not a class object or the class has been unloaded.
JVMTI_ERROR_ILLEGAL_ARGUMENT | object_filter is not a jvmtiHeapObjectFilter.
JVMTI_ERROR_NULL_POINTER | heap_object_callback is NULL.

Local Variable

Local Variable functions:
  • Get Local Variable - Object
  • Get Local Instance
  • Get Local Variable - Int
  • Get Local Variable - Long
  • Get Local Variable - Float
  • Get Local Variable - Double
  • Set Local Variable - Object
  • Set Local Variable - Int
  • Set Local Variable - Long
  • Set Local Variable - Float
  • Set Local Variable - Double
These functions are used to retrieve or set the value of a local variable. The variable is identified by the depth of the frame containing its value and the variable's slot number within that frame. The mapping of variables to slot numbers can be obtained with the function GetLocalVariableTable.

Get Local Variable - Object

jvmtiError
GetLocalObject(jvmtiEnv* env,
            jthread thread,
            jint depth,
            jint slot,
            jobject* value_ptr)
This function can be used to retrieve the value of a local variable whose type is Object or a subclass of Object.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 21 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_access_local_variables | Can set and get local variables

Parameters
Name | Type | Description
thread | jthread | The thread of the frame containing the variable's value. If thread is NULL, the current thread is used.
depth | jint | The depth of the frame containing the variable's value.
slot | jint | The variable's slot number.
value_ptr | jobject* | On return, points to the variable's value. Agent passes a pointer to a jobject. On return, the jobject has been set. The object returned by value_ptr is a JNI local reference and must be managed.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_access_local_variables. Use AddCapabilities.
JVMTI_ERROR_INVALID_SLOT | Invalid slot.
JVMTI_ERROR_TYPE_MISMATCH | The variable type is not Object or a subclass of Object.
JVMTI_ERROR_OPAQUE_FRAME | Not a visible frame
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).
JVMTI_ERROR_ILLEGAL_ARGUMENT | depth is less than zero.
JVMTI_ERROR_NO_MORE_FRAMES | There are no stack frames at the specified depth.
JVMTI_ERROR_NULL_POINTER | value_ptr is NULL.

Get Local Instance

jvmtiError
GetLocalInstance(jvmtiEnv* env,
            jthread thread,
            jint depth,
            jobject* value_ptr)
This function can be used to retrieve the value of the local object variable at slot 0 (the "this" object) from non-static frames. This function can retrieve the "this" object from native method frames, whereas GetLocalObject() would return JVMTI_ERROR_OPAQUE_FRAME in those cases.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 155 | 1.2

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_access_local_variables | Can set and get local variables

Parameters
Name | Type | Description
thread | jthread | The thread of the frame containing the variable's value. If thread is NULL, the current thread is used.
depth | jint | The depth of the frame containing the variable's value.
value_ptr | jobject* | On return, points to the variable's value. Agent passes a pointer to a jobject. On return, the jobject has been set. The object returned by value_ptr is a JNI local reference and must be managed.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_access_local_variables. Use AddCapabilities.
JVMTI_ERROR_INVALID_SLOT | If the specified frame is a static method frame.
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).
JVMTI_ERROR_ILLEGAL_ARGUMENT | depth is less than zero.
JVMTI_ERROR_NO_MORE_FRAMES | There are no stack frames at the specified depth.
JVMTI_ERROR_NULL_POINTER | value_ptr is NULL.

Get Local Variable - Int

jvmtiError
GetLocalInt(jvmtiEnv* env,
            jthread thread,
            jint depth,
            jint slot,
            jint* value_ptr)
This function can be used to retrieve the value of a local variable whose type is int, short, char, byte, or boolean.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 22 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_access_local_variables | Can set and get local variables

Parameters
Name | Type | Description
thread | jthread | The thread of the frame containing the variable's value. If thread is NULL, the current thread is used.
depth | jint | The depth of the frame containing the variable's value.
slot | jint | The variable's slot number.
value_ptr | jint* | On return, points to the variable's value. Agent passes a pointer to a jint. On return, the jint has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_access_local_variables. Use AddCapabilities.
JVMTI_ERROR_INVALID_SLOT | Invalid slot.
JVMTI_ERROR_TYPE_MISMATCH | The variable type is not int, short, char, byte, or boolean.
JVMTI_ERROR_OPAQUE_FRAME | Not a visible frame
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).
JVMTI_ERROR_ILLEGAL_ARGUMENT | depth is less than zero.
JVMTI_ERROR_NO_MORE_FRAMES | There are no stack frames at the specified depth.
JVMTI_ERROR_NULL_POINTER | value_ptr is NULL.

Get Local Variable - Long

jvmtiError
GetLocalLong(jvmtiEnv* env,
            jthread thread,
            jint depth,
            jint slot,
            jlong* value_ptr)
This function can be used to retrieve the value of a local variable whose type is long.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 23 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_access_local_variables | Can set and get local variables

Parameters
Name | Type | Description
thread | jthread | The thread of the frame containing the variable's value. If thread is NULL, the current thread is used.
depth | jint | The depth of the frame containing the variable's value.
slot | jint | The variable's slot number.
value_ptr | jlong* | On return, points to the variable's value. Agent passes a pointer to a jlong. On return, the jlong has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_access_local_variables. Use AddCapabilities.
JVMTI_ERROR_INVALID_SLOT | Invalid slot.
JVMTI_ERROR_TYPE_MISMATCH | The variable type is not long.
JVMTI_ERROR_OPAQUE_FRAME | Not a visible frame
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).
JVMTI_ERROR_ILLEGAL_ARGUMENT | depth is less than zero.
JVMTI_ERROR_NO_MORE_FRAMES | There are no stack frames at the specified depth.
JVMTI_ERROR_NULL_POINTER | value_ptr is NULL.

Get Local Variable - Float

jvmtiError
GetLocalFloat(jvmtiEnv* env,
            jthread thread,
            jint depth,
            jint slot,
            jfloat* value_ptr)
This function can be used to retrieve the value of a local variable whose type is float.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 24 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_access_local_variables | Can set and get local variables

Parameters
Name | Type | Description
thread | jthread | The thread of the frame containing the variable's value. If thread is NULL, the current thread is used.
depth | jint | The depth of the frame containing the variable's value.
slot | jint | The variable's slot number.
value_ptr | jfloat* | On return, points to the variable's value. Agent passes a pointer to a jfloat. On return, the jfloat has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_access_local_variables. Use AddCapabilities.
JVMTI_ERROR_INVALID_SLOT | Invalid slot.
JVMTI_ERROR_TYPE_MISMATCH | The variable type is not float.
JVMTI_ERROR_OPAQUE_FRAME | Not a visible frame
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).
JVMTI_ERROR_ILLEGAL_ARGUMENT | depth is less than zero.
JVMTI_ERROR_NO_MORE_FRAMES | There are no stack frames at the specified depth.
JVMTI_ERROR_NULL_POINTER | value_ptr is NULL.

Get Local Variable - Double

jvmtiError
GetLocalDouble(jvmtiEnv* env,
            jthread thread,
            jint depth,
            jint slot,
            jdouble* value_ptr)
This function can be used to retrieve the value of a local variable whose type is long.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 25 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_access_local_variables | Can set and get local variables

Parameters
Name | Type | Description
thread | jthread | The thread of the frame containing the variable's value. If thread is NULL, the current thread is used.
depth | jint | The depth of the frame containing the variable's value.
slot | jint | The variable's slot number.
value_ptr | jdouble* | On return, points to the variable's value. Agent passes a pointer to a jdouble. On return, the jdouble has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_access_local_variables. Use AddCapabilities.
JVMTI_ERROR_INVALID_SLOT | Invalid slot.
JVMTI_ERROR_TYPE_MISMATCH | The variable type is not double.
JVMTI_ERROR_OPAQUE_FRAME | Not a visible frame
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).
JVMTI_ERROR_ILLEGAL_ARGUMENT | depth is less than zero.
JVMTI_ERROR_NO_MORE_FRAMES | There are no stack frames at the specified depth.
JVMTI_ERROR_NULL_POINTER | value_ptr is NULL.

Set Local Variable - Object

jvmtiError
SetLocalObject(jvmtiEnv* env,
            jthread thread,
            jint depth,
            jint slot,
            jobject value)
This function can be used to set the value of a local variable whose type is Object or a subclass of Object.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 26 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_access_local_variables | Can set and get local variables

Parameters
Name | Type | Description
thread | jthread | The thread of the frame containing the variable's value. If thread is NULL, the current thread is used.
depth | jint | The depth of the frame containing the variable's value.
slot | jint | The variable's slot number.
value | jobject | The new value for the variable.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_access_local_variables. Use AddCapabilities.
JVMTI_ERROR_INVALID_SLOT | Invalid slot.
JVMTI_ERROR_TYPE_MISMATCH | The variable type is not Object or a subclass of Object.
JVMTI_ERROR_TYPE_MISMATCH | The supplied value is not compatible with the variable type.
JVMTI_ERROR_OPAQUE_FRAME | Not a visible frame
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).
JVMTI_ERROR_ILLEGAL_ARGUMENT | depth is less than zero.
JVMTI_ERROR_NO_MORE_FRAMES | There are no stack frames at the specified depth.
JVMTI_ERROR_INVALID_OBJECT | value is not an object.

Set Local Variable - Int

jvmtiError
SetLocalInt(jvmtiEnv* env,
            jthread thread,
            jint depth,
            jint slot,
            jint value)
This function can be used to set the value of a local variable whose type is int, short, char, byte, or boolean.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 27 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_access_local_variables | Can set and get local variables

Parameters
Name | Type | Description
thread | jthread | The thread of the frame containing the variable's value. If thread is NULL, the current thread is used.
depth | jint | The depth of the frame containing the variable's value.
slot | jint | The variable's slot number.
value | jint | The new value for the variable.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_access_local_variables. Use AddCapabilities.
JVMTI_ERROR_INVALID_SLOT | Invalid slot.
JVMTI_ERROR_TYPE_MISMATCH | The variable type is not int, short, char, byte, or boolean.
JVMTI_ERROR_OPAQUE_FRAME | Not a visible frame
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).
JVMTI_ERROR_ILLEGAL_ARGUMENT | depth is less than zero.
JVMTI_ERROR_NO_MORE_FRAMES | There are no stack frames at the specified depth.

Set Local Variable - Long

jvmtiError
SetLocalLong(jvmtiEnv* env,
            jthread thread,
            jint depth,
            jint slot,
            jlong value)
This function can be used to set the value of a local variable whose type is long.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 28 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_access_local_variables | Can set and get local variables

Parameters
Name | Type | Description
thread | jthread | The thread of the frame containing the variable's value. If thread is NULL, the current thread is used.
depth | jint | The depth of the frame containing the variable's value.
slot | jint | The variable's slot number.
value | jlong | The new value for the variable.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_access_local_variables. Use AddCapabilities.
JVMTI_ERROR_INVALID_SLOT | Invalid slot.
JVMTI_ERROR_TYPE_MISMATCH | The variable type is not long.
JVMTI_ERROR_OPAQUE_FRAME | Not a visible frame
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).
JVMTI_ERROR_ILLEGAL_ARGUMENT | depth is less than zero.
JVMTI_ERROR_NO_MORE_FRAMES | There are no stack frames at the specified depth.

Set Local Variable - Float

jvmtiError
SetLocalFloat(jvmtiEnv* env,
            jthread thread,
            jint depth,
            jint slot,
            jfloat value)
This function can be used to set the value of a local variable whose type is float.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 29 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_access_local_variables | Can set and get local variables

Parameters
Name | Type | Description
thread | jthread | The thread of the frame containing the variable's value. If thread is NULL, the current thread is used.
depth | jint | The depth of the frame containing the variable's value.
slot | jint | The variable's slot number.
value | jfloat | The new value for the variable.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_access_local_variables. Use AddCapabilities.
JVMTI_ERROR_INVALID_SLOT | Invalid slot.
JVMTI_ERROR_TYPE_MISMATCH | The variable type is not float.
JVMTI_ERROR_OPAQUE_FRAME | Not a visible frame
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).
JVMTI_ERROR_ILLEGAL_ARGUMENT | depth is less than zero.
JVMTI_ERROR_NO_MORE_FRAMES | There are no stack frames at the specified depth.

Set Local Variable - Double

jvmtiError
SetLocalDouble(jvmtiEnv* env,
            jthread thread,
            jint depth,
            jint slot,
            jdouble value)
This function can be used to set the value of a local variable whose type is double.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 30 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_access_local_variables | Can set and get local variables

Parameters
Name | Type | Description
thread | jthread | The thread of the frame containing the variable's value. If thread is NULL, the current thread is used.
depth | jint | The depth of the frame containing the variable's value.
slot | jint | The variable's slot number.
value | jdouble | The new value for the variable.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_access_local_variables. Use AddCapabilities.
JVMTI_ERROR_INVALID_SLOT | Invalid slot.
JVMTI_ERROR_TYPE_MISMATCH | The variable type is not double.
JVMTI_ERROR_OPAQUE_FRAME | Not a visible frame
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).
JVMTI_ERROR_ILLEGAL_ARGUMENT | depth is less than zero.
JVMTI_ERROR_NO_MORE_FRAMES | There are no stack frames at the specified depth.

Breakpoint

Breakpoint functions:
  • Set Breakpoint
  • Clear Breakpoint

Set Breakpoint

jvmtiError
SetBreakpoint(jvmtiEnv* env,
            jmethodID method,
            jlocation location)
Set a breakpoint at the instruction indicated by method and location. An instruction can only have one breakpoint.

Whenever the designated instruction is about to be executed, a Breakpoint event is generated.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 38 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_generate_breakpoint_events | Can set and thus get Breakpoint events

Parameters
Name | Type | Description
method | jmethodID | The method in which to set the breakpoint
location | jlocation | the index of the instruction at which to set the breakpoint

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_generate_breakpoint_events. Use AddCapabilities.
JVMTI_ERROR_DUPLICATE | The designated bytecode already has a breakpoint.
JVMTI_ERROR_INVALID_METHODID | method is not a jmethodID.
JVMTI_ERROR_INVALID_LOCATION | location is not a valid location.

Clear Breakpoint

jvmtiError
ClearBreakpoint(jvmtiEnv* env,
            jmethodID method,
            jlocation location)
Clear the breakpoint at the bytecode indicated by method and location.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 39 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_generate_breakpoint_events | Can set and thus get Breakpoint events

Parameters
Name | Type | Description
method | jmethodID | The method in which to clear the breakpoint
location | jlocation | the index of the instruction at which to clear the breakpoint

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_generate_breakpoint_events. Use AddCapabilities.
JVMTI_ERROR_NOT_FOUND | There's no breakpoint at the designated bytecode.
JVMTI_ERROR_INVALID_METHODID | method is not a jmethodID.
JVMTI_ERROR_INVALID_LOCATION | location is not a valid location.

Watched Field

Watched Field functions:
  • Set Field Access Watch
  • Clear Field Access Watch
  • Set Field Modification Watch
  • Clear Field Modification Watch

Set Field Access Watch

jvmtiError
SetFieldAccessWatch(jvmtiEnv* env,
            jclass klass,
            jfieldID field)
Generate a FieldAccess event when the field specified by klass and field is about to be accessed. An event will be generated for each access of the field until it is canceled with ClearFieldAccessWatch. Field accesses from Java programming language code or from JNI code are watched, fields modified by other means are not watched. Note that JVM TI users should be aware that their own field accesses will trigger the watch. A field can only have one field access watch set. Modification of a field is not considered an access--use SetFieldModificationWatch to monitor modifications.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 41 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_generate_field_access_events | Can set watchpoints on field access - SetFieldAccessWatch

Parameters
Name | Type | Description
klass | jclass | The class containing the field to watch
field | jfieldID | The field to watch

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_generate_field_access_events. Use AddCapabilities.
JVMTI_ERROR_DUPLICATE | The designated field is already being watched for accesses.
JVMTI_ERROR_INVALID_CLASS | klass is not a class object or the class has been unloaded.
JVMTI_ERROR_INVALID_FIELDID | field is not a jfieldID.

Clear Field Access Watch

jvmtiError
ClearFieldAccessWatch(jvmtiEnv* env,
            jclass klass,
            jfieldID field)
Cancel a field access watch previously set by SetFieldAccessWatch, on the field specified by klass and field.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 42 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_generate_field_access_events | Can set watchpoints on field access - SetFieldAccessWatch

Parameters
Name | Type | Description
klass | jclass | The class containing the field to watch
field | jfieldID | The field to watch

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_generate_field_access_events. Use AddCapabilities.
JVMTI_ERROR_NOT_FOUND | The designated field is not being watched for accesses.
JVMTI_ERROR_INVALID_CLASS | klass is not a class object or the class has been unloaded.
JVMTI_ERROR_INVALID_FIELDID | field is not a jfieldID.

Set Field Modification Watch

jvmtiError
SetFieldModificationWatch(jvmtiEnv* env,
            jclass klass,
            jfieldID field)
Generate a FieldModification event when the field specified by klass and field is about to be modified. An event will be generated for each modification of the field until it is canceled with ClearFieldModificationWatch. Field modifications from Java programming language code or from JNI code are watched, fields modified by other means are not watched. Note that JVM TI users should be aware that their own field modifications will trigger the watch. A field can only have one field modification watch set.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 43 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_generate_field_modification_events | Can set watchpoints on field modification - SetFieldModificationWatch

Parameters
Name | Type | Description
klass | jclass | The class containing the field to watch
field | jfieldID | The field to watch

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_generate_field_modification_events. Use AddCapabilities.
JVMTI_ERROR_DUPLICATE | The designated field is already being watched for modifications.
JVMTI_ERROR_INVALID_CLASS | klass is not a class object or the class has been unloaded.
JVMTI_ERROR_INVALID_FIELDID | field is not a jfieldID.

Clear Field Modification Watch

jvmtiError
ClearFieldModificationWatch(jvmtiEnv* env,
            jclass klass,
            jfieldID field)
Cancel a field modification watch previously set by SetFieldModificationWatch, on the field specified by klass and field.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 44 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_generate_field_modification_events | Can set watchpoints on field modification - SetFieldModificationWatch

Parameters
Name | Type | Description
klass | jclass | The class containing the field to watch
field | jfieldID | The field to watch

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_generate_field_modification_events. Use AddCapabilities.
JVMTI_ERROR_NOT_FOUND | The designated field is not being watched for modifications.
JVMTI_ERROR_INVALID_CLASS | klass is not a class object or the class has been unloaded.
JVMTI_ERROR_INVALID_FIELDID | field is not a jfieldID.

Class

Class functions:
  • Get Loaded Classes
  • Get Classloader Classes
  • Get Class Signature
  • Get Class Status
  • Get Source File Name
  • Get Class Modifiers
  • Get Class Methods
  • Get Class Fields
  • Get Implemented Interfaces
  • Get Class Version Numbers
  • Get Constant Pool
  • Is Interface
  • Is Array Class
  • Is Modifiable Class
  • Get Class Loader
  • Get Source Debug Extension
  • Retransform Classes
  • Redefine Classes
Class types:
  • jvmtiClassDefinition - Class redefinition description
Class flags and constants:
  • Class Status Flags

Get Loaded Classes

jvmtiError
GetLoadedClasses(jvmtiEnv* env,
            jint* class_count_ptr,
            jclass** classes_ptr)
Return an array of all classes loaded in the virtual machine. The number of classes in the array is returned via class_count_ptr, and the array itself via classes_ptr.

Array classes of all types (including arrays of primitive types) are included in the returned list. Primitive classes (for example, java.lang.Integer.TYPE) are not included in this list.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 78 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
class_count_ptr | jint* | On return, points to the number of classes. Agent passes a pointer to a jint. On return, the jint has been set.
classes_ptr | jclass** | On return, points to an array of references, one for each class. Agent passes a pointer to a jclass*. On return, the jclass* points to a newly allocated array of size *class_count_ptr. The array should be freed with Deallocate. The objects returned by classes_ptr are JNI local references and must be managed.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NULL_POINTER | class_count_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | classes_ptr is NULL.

Get Classloader Classes

jvmtiError
GetClassLoaderClasses(jvmtiEnv* env,
            jobject initiating_loader,
            jint* class_count_ptr,
            jclass** classes_ptr)
Returns an array of those classes for which this class loader has been recorded as an initiating loader. Each class in the returned array was created by this class loader, either by defining it directly or by delegation to another class loader. See the Creation and Loading section of the Java Virtual Machine Specification.

For JDK version 1.1 implementations that don't recognize the distinction between initiating and defining class loaders, this function should return all classes loaded in the virtual machine. The number of classes in the array is returned via class_count_ptr, and the array itself via classes_ptr.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 79 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
initiating_loader | jobject | An initiating class loader. If initiating_loader is NULL, the classes initiated by the bootstrap loader will be returned.
class_count_ptr | jint* | On return, points to the number of classes. Agent passes a pointer to a jint. On return, the jint has been set.
classes_ptr | jclass** | On return, points to an array of references, one for each class. Agent passes a pointer to a jclass*. On return, the jclass* points to a newly allocated array of size *class_count_ptr. The array should be freed with Deallocate. The objects returned by classes_ptr are JNI local references and must be managed.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NULL_POINTER | class_count_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | classes_ptr is NULL.

Get Class Signature

jvmtiError
GetClassSignature(jvmtiEnv* env,
            jclass klass,
            char** signature_ptr,
            char** generic_ptr)
For the class indicated by klass, return the JNI type signature and the generic signature of the class. For example, java.util.List is "Ljava/util/List;" and int[] is "[I" The returned name for primitive classes is the type signature character of the corresponding primitive type. For example, java.lang.Integer.TYPE is "I".

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 48 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
klass | jclass | The class to query.
signature_ptr | char ** | On return, points to the JNI type signature of the class, encoded as a modified UTF-8 string. Agent passes a pointer to a char*. On return, the char* points to a newly allocated array. The array should be freed with Deallocate. If signature_ptr is NULL, the signature is not returned.
generic_ptr | char ** | On return, points to the generic signature of the class, encoded as a modified UTF-8 string. If there is no generic signature attribute for the class, then, on return, points to NULL. Agent passes a pointer to a char*. On return, the char* points to a newly allocated array. The array should be freed with Deallocate. If generic_ptr is NULL, the generic signature is not returned.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_CLASS | klass is not a class object or the class has been unloaded.

Get Class Status

jvmtiError
GetClassStatus(jvmtiEnv* env,
            jclass klass,
            jint* status_ptr)
Get the status of the class. Zero or more of the following bits can be set.
Class Status Flags
Constant | Value | Description
JVMTI_CLASS_STATUS_VERIFIED | 1 | Class bytecodes have been verified
JVMTI_CLASS_STATUS_PREPARED | 2 | Class preparation is complete
JVMTI_CLASS_STATUS_INITIALIZED | 4 | Class initialization is complete. Static initializer has been run.
JVMTI_CLASS_STATUS_ERROR | 8 | Error during initialization makes class unusable
JVMTI_CLASS_STATUS_ARRAY | 16 | Class is an array. If set, all other bits are zero.
JVMTI_CLASS_STATUS_PRIMITIVE | 32 | Class is a primitive class (for example, java.lang.Integer.TYPE). If set, all other bits are zero.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 49 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
klass | jclass | The class to query.
status_ptr | jint* | On return, points to the current state of this class as one or more of the class status flags. Agent passes a pointer to a jint. On return, the jint has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_CLASS | klass is not a class object or the class has been unloaded.
JVMTI_ERROR_NULL_POINTER | status_ptr is NULL.

Get Source File Name

jvmtiError
GetSourceFileName(jvmtiEnv* env,
            jclass klass,
            char** source_name_ptr)
For the class indicated by klass, return the source file name via source_name_ptr. The returned string is a file name only and never contains a directory name.

For primitive classes (for example, java.lang.Integer.TYPE) and for arrays this function returns JVMTI_ERROR_ABSENT_INFORMATION.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 50 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_get_source_file_name | Can get the source file name of a class

Parameters
Name | Type | Description
klass | jclass | The class to query.
source_name_ptr | char** | On return, points to the class's source file name, encoded as a modified UTF-8 string. Agent passes a pointer to a char*. On return, the char* points to a newly allocated array. The array should be freed with Deallocate.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_get_source_file_name. Use AddCapabilities.
JVMTI_ERROR_ABSENT_INFORMATION | Class information does not include a source file name. This includes cases where the class is an array class or primitive class.
JVMTI_ERROR_INVALID_CLASS | klass is not a class object or the class has been unloaded.
JVMTI_ERROR_NULL_POINTER | source_name_ptr is NULL.

Get Class Modifiers

jvmtiError
GetClassModifiers(jvmtiEnv* env,
            jclass klass,
            jint* modifiers_ptr)
For the class indicated by klass, return the access flags via modifiers_ptr. Access flags are defined in the Class File Format chapter of the Java Virtual Machine Specification.

If the class is an array class, then its public, private, and protected modifiers are the same as those of its component type. For arrays of primitives, this component type is represented by one of the primitive classes (for example, java.lang.Integer.TYPE).

If the class is a primitive class, its public modifier is always true, and its protected and private modifiers are always false.

If the class is an array class or a primitive class then its final modifier is always true and its interface modifier is always false. The values of its other modifiers are not determined by this specification.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 51 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
klass | jclass | The class to query.
modifiers_ptr | jint* | On return, points to the current access flags of this class. Agent passes a pointer to a jint. On return, the jint has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_CLASS | klass is not a class object or the class has been unloaded.
JVMTI_ERROR_NULL_POINTER | modifiers_ptr is NULL.

Get Class Methods

jvmtiError
GetClassMethods(jvmtiEnv* env,
            jclass klass,
            jint* method_count_ptr,
            jmethodID** methods_ptr)
For the class indicated by klass, return a count of methods via method_count_ptr and a list of method IDs via methods_ptr. The method list contains constructors and static initializers as well as true methods. Only directly declared methods are returned (not inherited methods). An empty method list is returned for array classes and primitive classes (for example, java.lang.Integer.TYPE).

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 52 | 1.0

Capabilities
Required Functionality
Optional Features
Capability | Effect
can_maintain_original_method_order | Can return methods in the order they occur in the class file

Parameters
Name | Type | Description
klass | jclass | The class to query.
method_count_ptr | jint* | On return, points to the number of methods declared in this class. Agent passes a pointer to a jint. On return, the jint has been set.
methods_ptr | jmethodID** | On return, points to the method ID array. Agent passes a pointer to a jmethodID*. On return, the jmethodID* points to a newly allocated array of size *method_count_ptr. The array should be freed with Deallocate.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_CLASS_NOT_PREPARED | klass is not prepared.
JVMTI_ERROR_INVALID_CLASS | klass is not a class object or the class has been unloaded.
JVMTI_ERROR_NULL_POINTER | method_count_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | methods_ptr is NULL.

Get Class Fields

jvmtiError
GetClassFields(jvmtiEnv* env,
            jclass klass,
            jint* field_count_ptr,
            jfieldID** fields_ptr)
For the class indicated by klass, return a count of fields via field_count_ptr and a list of field IDs via fields_ptr. Only directly declared fields are returned (not inherited fields). Fields are returned in the order they occur in the class file. An empty field list is returned for array classes and primitive classes (for example, java.lang.Integer.TYPE). Use JNI to determine the length of an array.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 53 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
klass | jclass | The class to query.
field_count_ptr | jint* | On return, points to the number of fields declared in this class. Agent passes a pointer to a jint. On return, the jint has been set.
fields_ptr | jfieldID** | On return, points to the field ID array. Agent passes a pointer to a jfieldID*. On return, the jfieldID* points to a newly allocated array of size *field_count_ptr. The array should be freed with Deallocate.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_CLASS_NOT_PREPARED | klass is not prepared.
JVMTI_ERROR_INVALID_CLASS | klass is not a class object or the class has been unloaded.
JVMTI_ERROR_NULL_POINTER | field_count_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | fields_ptr is NULL.

Get Implemented Interfaces

jvmtiError
GetImplementedInterfaces(jvmtiEnv* env,
            jclass klass,
            jint* interface_count_ptr,
            jclass** interfaces_ptr)
Return the direct super-interfaces of this class. For a class, this function returns the interfaces declared in its implements clause. For an interface, this function returns the interfaces declared in its extends clause. An empty interface list is returned for array classes and primitive classes (for example, java.lang.Integer.TYPE).

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 54 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
klass | jclass | The class to query.
interface_count_ptr | jint* | On return, points to the number of interfaces. Agent passes a pointer to a jint. On return, the jint has been set.
interfaces_ptr | jclass** | On return, points to the interface array. Agent passes a pointer to a jclass*. On return, the jclass* points to a newly allocated array of size *interface_count_ptr. The array should be freed with Deallocate. The objects returned by interfaces_ptr are JNI local references and must be managed.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_CLASS_NOT_PREPARED | klass is not prepared.
JVMTI_ERROR_INVALID_CLASS | klass is not a class object or the class has been unloaded.
JVMTI_ERROR_NULL_POINTER | interface_count_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | interfaces_ptr is NULL.

Get Class Version Numbers

jvmtiError
GetClassVersionNumbers(jvmtiEnv* env,
            jclass klass,
            jint* minor_version_ptr,
            jint* major_version_ptr)
For the class indicated by klass, return the minor and major version numbers, as defined in the Class File Format chapter of the Java Virtual Machine Specification.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 145 | 1.1

Capabilities
Required Functionality

Parameters
Name | Type | Description
klass | jclass | The class to query.
minor_version_ptr | jint* | On return, points to the value of the minor_version item of the Class File Format. Note: to be consistent with the Class File Format, the minor version number is the first parameter. Agent passes a pointer to a jint. On return, the jint has been set.
major_version_ptr | jint* | On return, points to the value of the major_version item of the Class File Format. Agent passes a pointer to a jint. On return, the jint has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_ABSENT_INFORMATION | The class is a primitive or array class.
JVMTI_ERROR_INVALID_CLASS | klass is not a class object or the class has been unloaded.
JVMTI_ERROR_NULL_POINTER | minor_version_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | major_version_ptr is NULL.

Get Constant Pool

jvmtiError
GetConstantPool(jvmtiEnv* env,
            jclass klass,
            jint* constant_pool_count_ptr,
            jint* constant_pool_byte_count_ptr,
            unsigned char** constant_pool_bytes_ptr)
For the class indicated by klass, return the raw bytes of the constant pool in the format of the constant_pool item of the Class File Format in the Java Virtual Machine Specification. The format of the constant pool may differ between versions of the Class File Format, so, the minor and major class version numbers should be checked for compatibility.

The returned constant pool might not have the same layout or contents as the constant pool in the defining class file. The constant pool returned by GetConstantPool() may have more or fewer entries than the defining constant pool. Entries may be in a different order. The constant pool returned by GetConstantPool() will match the constant pool used by GetBytecodes(). That is, the bytecodes returned by GetBytecodes() will have constant pool indices which refer to constant pool entries returned by GetConstantPool(). Note that since RetransformClasses and RedefineClasses can change the constant pool, the constant pool returned by this function can change accordingly. Thus, the correspondence between GetConstantPool() and GetBytecodes() does not hold if there is an intervening class retransformation or redefinition. The value of a constant pool entry used by a given bytecode will match that of the defining class file (even if the indices don't match). Constant pool entries which are not used directly or indirectly by bytecodes (for example, UTF-8 strings associated with annotations) are not required to exist in the returned constant pool.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 146 | 1.1

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_get_constant_pool | Can get the constant pool of a class - GetConstantPool

Parameters
Name | Type | Description
klass | jclass | The class to query.
constant_pool_count_ptr | jint* | On return, points to the number of entries in the constant pool table plus one. This corresponds to the constant_pool_count item of the Class File Format. Agent passes a pointer to a jint. On return, the jint has been set.
constant_pool_byte_count_ptr | jint* | On return, points to the number of bytes in the returned raw constant pool. Agent passes a pointer to a jint. On return, the jint has been set.
constant_pool_bytes_ptr | unsigned char** | On return, points to the raw constant pool, that is the bytes defined by the constant_pool item of the Class File Format Agent passes a pointer to a unsigned char*. On return, the unsigned char* points to a newly allocated array of size *constant_pool_byte_count_ptr. The array should be freed with Deallocate.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_get_constant_pool. Use AddCapabilities.
JVMTI_ERROR_ABSENT_INFORMATION | The class is a primitive or array class.
JVMTI_ERROR_INVALID_CLASS | klass is not a class object or the class has been unloaded.
JVMTI_ERROR_NULL_POINTER | constant_pool_count_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | constant_pool_byte_count_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | constant_pool_bytes_ptr is NULL.

Is Interface

jvmtiError
IsInterface(jvmtiEnv* env,
            jclass klass,
            jboolean* is_interface_ptr)
Determines whether a class object reference represents an interface. The jboolean result is JNI_TRUE if the "class" is actually an interface, JNI_FALSE otherwise.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 55 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
klass | jclass | The class to query.
is_interface_ptr | jboolean* | On return, points to the boolean result of this function. Agent passes a pointer to a jboolean. On return, the jboolean has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_CLASS | klass is not a class object or the class has been unloaded.
JVMTI_ERROR_NULL_POINTER | is_interface_ptr is NULL.

Is Array Class

jvmtiError
IsArrayClass(jvmtiEnv* env,
            jclass klass,
            jboolean* is_array_class_ptr)
Determines whether a class object reference represents an array. The jboolean result is JNI_TRUE if the class is an array, JNI_FALSE otherwise.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 56 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
klass | jclass | The class to query.
is_array_class_ptr | jboolean* | On return, points to the boolean result of this function. Agent passes a pointer to a jboolean. On return, the jboolean has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_CLASS | klass is not a class object or the class has been unloaded.
JVMTI_ERROR_NULL_POINTER | is_array_class_ptr is NULL.

Is Modifiable Class

jvmtiError
IsModifiableClass(jvmtiEnv* env,
            jclass klass,
            jboolean* is_modifiable_class_ptr)
Determines whether a class is modifiable. If a class is modifiable (is_modifiable_class_ptr returns JNI_TRUE) the class can be redefined with RedefineClasses (assuming the agent possesses the can_redefine_classes capability) or retransformed with RetransformClasses (assuming the agent possesses the can_retransform_classes capability). If a class is not modifiable (is_modifiable_class_ptr returns JNI_FALSE) the class can be neither redefined nor retransformed.

Primitive classes (for example, java.lang.Integer.TYPE) and array classes are never modifiable.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 45 | 1.1

Capabilities
Required Functionality
Optional Features
Capability | Effect
can_redefine_any_class | If possessed then all classes (except primitive and array classes) are modifiable.
can_redefine_classes | No effect on the result of the function. But must additionally be possessed to modify the class with RedefineClasses.
can_retransform_classes | No effect on the result of the function. But must additionally be possessed to modify the class with RetransformClasses.

Parameters
Name | Type | Description
klass | jclass | The class to query.
is_modifiable_class_ptr | jboolean* | On return, points to the boolean result of this function. Agent passes a pointer to a jboolean. On return, the jboolean has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_CLASS | klass is not a class object or the class has been unloaded.
JVMTI_ERROR_NULL_POINTER | is_modifiable_class_ptr is NULL.

Get Class Loader

jvmtiError
GetClassLoader(jvmtiEnv* env,
            jclass klass,
            jobject* classloader_ptr)
For the class indicated by klass, return via classloader_ptr a reference to the class loader for the class.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 57 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
klass | jclass | The class to query.
classloader_ptr | jobject* | On return, points to the class loader that loaded this class. If the class was not created by a class loader or if the class loader is the bootstrap class loader, points to NULL. Agent passes a pointer to a jobject. On return, the jobject has been set. The object returned by classloader_ptr is a JNI local reference and must be managed.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_CLASS | klass is not a class object or the class has been unloaded.
JVMTI_ERROR_NULL_POINTER | classloader_ptr is NULL.

Get Source Debug Extension

jvmtiError
GetSourceDebugExtension(jvmtiEnv* env,
            jclass klass,
            char** source_debug_extension_ptr)
For the class indicated by klass, return the debug extension via source_debug_extension_ptr. The returned string contains exactly the debug extension information present in the class file of klass.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 90 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_get_source_debug_extension | Can get the source debug extension of a class

Parameters
Name | Type | Description
klass | jclass | The class to query.
source_debug_extension_ptr | char** | On return, points to the class's debug extension, encoded as a modified UTF-8 string. Agent passes a pointer to a char*. On return, the char* points to a newly allocated array. The array should be freed with Deallocate.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_get_source_debug_extension. Use AddCapabilities.
JVMTI_ERROR_ABSENT_INFORMATION | Class information does not include a debug extension.
JVMTI_ERROR_INVALID_CLASS | klass is not a class object or the class has been unloaded.
JVMTI_ERROR_NULL_POINTER | source_debug_extension_ptr is NULL.

Retransform Classes

jvmtiError
RetransformClasses(jvmtiEnv* env,
            jint class_count,
            const jclass* classes)
This function facilitates the bytecode instrumentation of already loaded classes. To replace the class definition without reference to the existing bytecodes, as one might do when recompiling from source for fix-and-continue debugging, RedefineClasses function should be used instead.

When classes are initially loaded or when they are redefined, the initial class file bytes can be transformed with the ClassFileLoadHook event. This function reruns the transformation process (whether or not a transformation has previously occurred). This retransformation follows these steps:
  • starting from the initial class file bytes
  • for each retransformation incapable agent which received a ClassFileLoadHook event during the previous load or redefine, the bytes it returned (via the new_class_data parameter) are reused as the output of the transformation; note that this is equivalent to reapplying the previous transformation, unaltered. except that the ClassFileLoadHook event is not sent to these agents
  • for each retransformation capable agent, the ClassFileLoadHook event is sent, allowing a new transformation to be applied
  • the transformed class file bytes are installed as the new definition of the class
See the ClassFileLoadHook event for more details.

The initial class file bytes represent the bytes passed to ClassLoader.defineClass or RedefineClasses (before any transformations were applied), however they may not exactly match them. The constant pool may differ in ways described in GetConstantPool. Constant pool indices in the bytecodes of methods will correspond. Some attributes may not be present. Where order is not meaningful, for example the order of methods, order may not be preserved.

Retransformation can cause new versions of methods to be installed. Old method versions may become obsolete The new method version will be used on new invokes. If a method has active stack frames, those active frames continue to run the bytecodes of the original method version.

This function does not cause any initialization except that which would occur under the customary JVM semantics. In other words, retransforming a class does not cause its initializers to be run. The values of static fields will remain as they were prior to the call.

Threads need not be suspended.

All breakpoints in the class are cleared.

All attributes are updated.

Instances of the retransformed class are not affected -- fields retain their previous values. Tags on the instances are also unaffected.

In response to this call, no events other than the ClassFileLoadHook event will be sent.

The retransformation may change method bodies, the constant pool and attributes. The retransformation must not add, remove or rename fields or methods, change the signatures of methods, change modifiers, or change inheritance. These restrictions may be lifted in future versions. See the error return description below for information on error codes returned if an unsupported retransformation is attempted. The class file bytes are not verified or installed until they have passed through the chain of ClassFileLoadHook events, thus the returned error code reflects the result of the transformations. If any error code is returned other than JVMTI_ERROR_NONE, none of the classes to be retransformed will have a new definition installed. When this function returns (with the error code of JVMTI_ERROR_NONE) all of the classes to be retransformed will have their new definitions installed.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 152 | 1.1

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_retransform_classes | Can retransform classes with RetransformClasses. In addition to the restrictions imposed by the specific implementation on this capability (see the Capability section), this capability must be set before the ClassFileLoadHook event is enabled for the first time in this environment. An environment that possesses this capability at the time that ClassFileLoadHook is enabled for the first time is said to be retransformation capable. An environment that does not possess this capability at the time that ClassFileLoadHook is enabled for the first time is said to be retransformation incapable.
Optional Features
can_retransform_any_class | RetransformClasses can be called on any class (can_retransform_classes must also be set)

Parameters
Name | Type | Description
class_count | jint | The number of classes to be retransformed.
classes | const jclass* | The array of classes to be retransformed. Agent passes in an array of class_count elements of jclass.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_retransform_classes. Use AddCapabilities.
JVMTI_ERROR_UNMODIFIABLE_CLASS | One of the classes cannot be modified. See IsModifiableClass.
JVMTI_ERROR_INVALID_CLASS | One of the classes is not a valid class.
JVMTI_ERROR_UNSUPPORTED_VERSION | A retransformed class file has a version number not supported by this VM.
JVMTI_ERROR_INVALID_CLASS_FORMAT | A retransformed class file is malformed (The VM would return a ClassFormatError).
JVMTI_ERROR_CIRCULAR_CLASS_DEFINITION | The retransformed class file definitions would lead to a circular definition (the VM would return a ClassCircularityError).
JVMTI_ERROR_FAILS_VERIFICATION | The retransformed class file bytes fail verification.
JVMTI_ERROR_NAMES_DONT_MATCH | The class name defined in a retransformed class file is different from the name in the old class object.
JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_ADDED | A retransformed class file would require adding a method.
JVMTI_ERROR_UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED | A retransformed class file changes a field.
JVMTI_ERROR_UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED | A direct superclass is different for a retransformed class file, or the set of directly implemented interfaces is different.
JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_DELETED | A retransformed class file does not declare a method declared in the old class version.
JVMTI_ERROR_UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED | A retransformed class file has different class modifiers.
JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED | A method in the retransformed class file has different modifiers than its counterpart in the old class version.
JVMTI_ERROR_ILLEGAL_ARGUMENT | class_count is less than 0.
JVMTI_ERROR_NULL_POINTER | classes is NULL.

Redefine Classes

typedef struct {
    jclass klass;
    jint class_byte_count;
    const unsigned char* class_bytes;
} jvmtiClassDefinition;
jvmtiError
RedefineClasses(jvmtiEnv* env,
            jint class_count,
            const jvmtiClassDefinition* class_definitions)
All classes given are redefined according to the definitions supplied. This function is used to replace the definition of a class with a new definition, as might be needed in fix-and-continue debugging. Where the existing class file bytes are to be transformed, for example in bytecode instrumentation, RetransformClasses should be used.

Redefinition can cause new versions of methods to be installed. Old method versions may become obsolete The new method version will be used on new invokes. If a method has active stack frames, those active frames continue to run the bytecodes of the original method version. If resetting of stack frames is desired, use PopFrame to pop frames with obsolete method versions.

This function does not cause any initialization except that which would occur under the customary JVM semantics. In other words, redefining a class does not cause its initializers to be run. The values of static fields will remain as they were prior to the call.

Threads need not be suspended.

All breakpoints in the class are cleared.

All attributes are updated.

Instances of the redefined class are not affected -- fields retain their previous values. Tags on the instances are also unaffected.

In response to this call, the JVM TI event Class File Load Hook will be sent (if enabled), but no other JVM TI events will be sent.

The redefinition may change method bodies, the constant pool and attributes. The redefinition must not add, remove or rename fields or methods, change the signatures of methods, change modifiers, or change inheritance. These restrictions may be lifted in future versions. See the error return description below for information on error codes returned if an unsupported redefinition is attempted. The class file bytes are not verified or installed until they have passed through the chain of ClassFileLoadHook events, thus the returned error code reflects the result of the transformations applied to the bytes passed into class_definitions. If any error code is returned other than JVMTI_ERROR_NONE, none of the classes to be redefined will have a new definition installed. When this function returns (with the error code of JVMTI_ERROR_NONE) all of the classes to be redefined will have their new definitions installed.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 87 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_redefine_classes | Can redefine classes with RedefineClasses.
Optional Features
can_redefine_any_class | Can modify (retransform or redefine) any non-primitive non-array class. See IsModifiableClass.

jvmtiClassDefinition - Class redefinition description
Field | Type | Description
klass | jclass | Class object for this class
class_byte_count | jint | Number of bytes defining class (below)
class_bytes | const unsigned char* | Bytes defining class (in the Class File Format of the Java Virtual Machine Specification)

Parameters
Name | Type | Description
class_count | jint | The number of classes specified in class_definitions
class_definitions | const jvmtiClassDefinition* | The array of new class definitions Agent passes in an array of class_count elements of jvmtiClassDefinition.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_redefine_classes. Use AddCapabilities.
JVMTI_ERROR_NULL_POINTER | One of class_bytes is NULL.
JVMTI_ERROR_UNMODIFIABLE_CLASS | An element of class_definitions cannot be modified. See IsModifiableClass.
JVMTI_ERROR_INVALID_CLASS | An element of class_definitions is not a valid class.
JVMTI_ERROR_UNSUPPORTED_VERSION | A new class file has a version number not supported by this VM.
JVMTI_ERROR_INVALID_CLASS_FORMAT | A new class file is malformed (The VM would return a ClassFormatError).
JVMTI_ERROR_CIRCULAR_CLASS_DEFINITION | The new class file definitions would lead to a circular definition (the VM would return a ClassCircularityError).
JVMTI_ERROR_FAILS_VERIFICATION | The class bytes fail verification.
JVMTI_ERROR_NAMES_DONT_MATCH | The class name defined in a new class file is different from the name in the old class object.
JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_ADDED | A new class file would require adding a method.
JVMTI_ERROR_UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED | A new class version changes a field.
JVMTI_ERROR_UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED | A direct superclass is different for a new class version, or the set of directly implemented interfaces is different.
JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_DELETED | A new class version does not declare a method declared in the old class version.
JVMTI_ERROR_UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED | A new class version has different modifiers.
JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED | A method in the new class version has different modifiers than its counterpart in the old class version.
JVMTI_ERROR_ILLEGAL_ARGUMENT | class_count is less than 0.
JVMTI_ERROR_NULL_POINTER | class_definitions is NULL.

Object

Object functions:
  • Get Object Size
  • Get Object Hash Code
  • Get Object Monitor Usage
Object types:
  • jvmtiMonitorUsage - Object monitor usage information

Get Object Size

jvmtiError
GetObjectSize(jvmtiEnv* env,
            jobject object,
            jlong* size_ptr)
For the object indicated by object, return via size_ptr the size of the object. This size is an implementation-specific approximation of the amount of storage consumed by this object. It may include some or all of the object's overhead, and thus is useful for comparison within an implementation but not between implementations. The estimate may change during a single invocation of the JVM.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 154 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
object | jobject | The object to query.
size_ptr | jlong* | On return, points to the object's size in bytes. Agent passes a pointer to a jlong. On return, the jlong has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_OBJECT | object is not an object.
JVMTI_ERROR_NULL_POINTER | size_ptr is NULL.

Get Object Hash Code

jvmtiError
GetObjectHashCode(jvmtiEnv* env,
            jobject object,
            jint* hash_code_ptr)
For the object indicated by object, return via hash_code_ptr a hash code. This hash code could be used to maintain a hash table of object references, however, on some implementations this can cause significant performance impacts--in most cases tags will be a more efficient means of associating information with objects. This function guarantees the same hash code value for a particular object throughout its life

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 58 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
object | jobject | The object to query.
hash_code_ptr | jint* | On return, points to the object's hash code. Agent passes a pointer to a jint. On return, the jint has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_OBJECT | object is not an object.
JVMTI_ERROR_NULL_POINTER | hash_code_ptr is NULL.

Get Object Monitor Usage

typedef struct {
    jthread owner;
    jint entry_count;
    jint waiter_count;
    jthread* waiters;
    jint notify_waiter_count;
    jthread* notify_waiters;
} jvmtiMonitorUsage;
jvmtiError
GetObjectMonitorUsage(jvmtiEnv* env,
            jobject object,
            jvmtiMonitorUsage* info_ptr)
Get information about the object's monitor. The fields of the jvmtiMonitorUsage structure are filled in with information about usage of the monitor.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 59 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_get_monitor_info | Can GetObjectMonitorUsage

jvmtiMonitorUsage - Object monitor usage information
Field | Type | Description
owner | jthread | The thread owning this monitor, or NULL if unused
entry_count | jint | The number of times the owning thread has entered the monitor
waiter_count | jint | The number of threads waiting to own this monitor
waiters | jthread* | The waiter_count waiting threads
notify_waiter_count | jint | The number of threads waiting to be notified by this monitor
notify_waiters | jthread* | The notify_waiter_count threads waiting to be notified

Parameters
Name | Type | Description
object | jobject | The object to query.
info_ptr | jvmtiMonitorUsage* | On return, filled with monitor information for the specified object. Agent passes a pointer to a jvmtiMonitorUsage. On return, the jvmtiMonitorUsage has been set. The object returned in the field owner of jvmtiMonitorUsage is a JNI local reference and must be managed. The pointer returned in the field waiters of jvmtiMonitorUsage is a newly allocated array. The array should be freed with Deallocate. The objects returned in the field waiters of jvmtiMonitorUsage are JNI local references and must be managed. The pointer returned in the field notify_waiters of jvmtiMonitorUsage is a newly allocated array. The array should be freed with Deallocate. The objects returned in the field notify_waiters of jvmtiMonitorUsage are JNI local references and must be managed.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_get_monitor_info. Use AddCapabilities.
JVMTI_ERROR_INVALID_OBJECT | object is not an object.
JVMTI_ERROR_NULL_POINTER | info_ptr is NULL.

Field

Field functions:
  • Get Field Name (and Signature)
  • Get Field Declaring Class
  • Get Field Modifiers
  • Is Field Synthetic

Get Field Name (and Signature)

jvmtiError
GetFieldName(jvmtiEnv* env,
            jclass klass,
            jfieldID field,
            char** name_ptr,
            char** signature_ptr,
            char** generic_ptr)
For the field indicated by klass and field, return the field name via name_ptr and field signature via signature_ptr.

Field signatures are defined in the JNI Specification and are referred to as field descriptors in the Java Virtual Machine Specification.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 60 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
klass | jclass | The class of the field to query.
field | jfieldID | The field to query.
name_ptr | char ** | On return, points to the field name, encoded as a modified UTF-8 string. Agent passes a pointer to a char*. On return, the char* points to a newly allocated array. The array should be freed with Deallocate. If name_ptr is NULL, the name is not returned.
signature_ptr | char ** | On return, points to the field signature, encoded as a modified UTF-8 string. Agent passes a pointer to a char*. On return, the char* points to a newly allocated array. The array should be freed with Deallocate. If signature_ptr is NULL, the signature is not returned.
generic_ptr | char ** | On return, points to the generic signature of the field, encoded as a modified UTF-8 string. If there is no generic signature attribute for the field, then, on return, points to NULL. Agent passes a pointer to a char*. On return, the char* points to a newly allocated array. The array should be freed with Deallocate. If generic_ptr is NULL, the generic signature is not returned.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_CLASS | klass is not a class object or the class has been unloaded.
JVMTI_ERROR_INVALID_FIELDID | field is not a jfieldID.

Get Field Declaring Class

jvmtiError
GetFieldDeclaringClass(jvmtiEnv* env,
            jclass klass,
            jfieldID field,
            jclass* declaring_class_ptr)
For the field indicated by klass and field return the class that defined it via declaring_class_ptr. The declaring class will either be klass, a superclass, or an implemented interface.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 61 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
klass | jclass | The class to query.
field | jfieldID | The field to query.
declaring_class_ptr | jclass* | On return, points to the declaring class Agent passes a pointer to a jclass. On return, the jclass has been set. The object returned by declaring_class_ptr is a JNI local reference and must be managed.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_CLASS | klass is not a class object or the class has been unloaded.
JVMTI_ERROR_INVALID_FIELDID | field is not a jfieldID.
JVMTI_ERROR_NULL_POINTER | declaring_class_ptr is NULL.

Get Field Modifiers

jvmtiError
GetFieldModifiers(jvmtiEnv* env,
            jclass klass,
            jfieldID field,
            jint* modifiers_ptr)
For the field indicated by klass and field return the access flags via modifiers_ptr. Access flags are defined in the Class File Format chapter of the Java Virtual Machine Specification.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 62 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
klass | jclass | The class to query.
field | jfieldID | The field to query.
modifiers_ptr | jint* | On return, points to the access flags. Agent passes a pointer to a jint. On return, the jint has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_CLASS | klass is not a class object or the class has been unloaded.
JVMTI_ERROR_INVALID_FIELDID | field is not a jfieldID.
JVMTI_ERROR_NULL_POINTER | modifiers_ptr is NULL.

Is Field Synthetic

jvmtiError
IsFieldSynthetic(jvmtiEnv* env,
            jclass klass,
            jfieldID field,
            jboolean* is_synthetic_ptr)
For the field indicated by klass and field, return a value indicating whether the field is synthetic via is_synthetic_ptr. Synthetic fields are generated by the compiler but not present in the original source code.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 63 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_get_synthetic_attribute | Can test if a field or method is synthetic - IsFieldSynthetic and IsMethodSynthetic

Parameters
Name | Type | Description
klass | jclass | The class of the field to query.
field | jfieldID | The field to query.
is_synthetic_ptr | jboolean* | On return, points to the boolean result of this function. Agent passes a pointer to a jboolean. On return, the jboolean has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_get_synthetic_attribute. Use AddCapabilities.
JVMTI_ERROR_INVALID_CLASS | klass is not a class object or the class has been unloaded.
JVMTI_ERROR_INVALID_FIELDID | field is not a jfieldID.
JVMTI_ERROR_NULL_POINTER | is_synthetic_ptr is NULL.

Method

Method functions:
  • Get Method Name (and Signature)
  • Get Method Declaring Class
  • Get Method Modifiers
  • Get Max Locals
  • Get Arguments Size
  • Get Line Number Table
  • Get Method Location
  • Get Local Variable Table
  • Get Bytecodes
  • Is Method Native
  • Is Method Synthetic
  • Is Method Obsolete
  • Set Native Method Prefix
  • Set Native Method Prefixes
Method types:
  • jvmtiLineNumberEntry - Line number table entry
  • jvmtiLocalVariableEntry - Local variable table entry
These functions provide information about a method (represented as a jmethodID) and set how methods are processed.

Obsolete Methods

The functions RetransformClasses and RedefineClasses can cause new versions of methods to be installed. An original version of a method is considered equivalent to the new version if:
  • their bytecodes are the same except for indices into the constant pool and
  • the referenced constants are equal.
An original method version which is not equivalent to the new method version is called obsolete and is assigned a new method ID; the original method ID now refers to the new method version. A method ID can be tested for obsolescence with IsMethodObsolete.

Get Method Name (and Signature)

jvmtiError
GetMethodName(jvmtiEnv* env,
            jmethodID method,
            char** name_ptr,
            char** signature_ptr,
            char** generic_ptr)
For the method indicated by method, return the method name via name_ptr and method signature via signature_ptr.

Method signatures are defined in the JNI Specification and are referred to as method descriptors in the Java Virtual Machine Specification. Note this is different than method signatures as defined in the Java Language Specification.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 64 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
method | jmethodID | The method to query.
name_ptr | char ** | On return, points to the method name, encoded as a modified UTF-8 string. Agent passes a pointer to a char*. On return, the char* points to a newly allocated array. The array should be freed with Deallocate. If name_ptr is NULL, the name is not returned.
signature_ptr | char ** | On return, points to the method signature, encoded as a modified UTF-8 string. Agent passes a pointer to a char*. On return, the char* points to a newly allocated array. The array should be freed with Deallocate. If signature_ptr is NULL, the signature is not returned.
generic_ptr | char ** | On return, points to the generic signature of the method, encoded as a modified UTF-8 string. If there is no generic signature attribute for the method, then, on return, points to NULL. Agent passes a pointer to a char*. On return, the char* points to a newly allocated array. The array should be freed with Deallocate. If generic_ptr is NULL, the generic signature is not returned.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_METHODID | method is not a jmethodID.

Get Method Declaring Class

jvmtiError
GetMethodDeclaringClass(jvmtiEnv* env,
            jmethodID method,
            jclass* declaring_class_ptr)
For the method indicated by method, return the class that defined it via declaring_class_ptr.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 65 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
method | jmethodID | The method to query.
declaring_class_ptr | jclass* | On return, points to the declaring class Agent passes a pointer to a jclass. On return, the jclass has been set. The object returned by declaring_class_ptr is a JNI local reference and must be managed.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_METHODID | method is not a jmethodID.
JVMTI_ERROR_NULL_POINTER | declaring_class_ptr is NULL.

Get Method Modifiers

jvmtiError
GetMethodModifiers(jvmtiEnv* env,
            jmethodID method,
            jint* modifiers_ptr)
For the method indicated by method, return the access flags via modifiers_ptr. Access flags are defined in the Class File Format chapter of the Java Virtual Machine Specification.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 66 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
method | jmethodID | The method to query.
modifiers_ptr | jint* | On return, points to the access flags. Agent passes a pointer to a jint. On return, the jint has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_METHODID | method is not a jmethodID.
JVMTI_ERROR_NULL_POINTER | modifiers_ptr is NULL.

Get Max Locals

jvmtiError
GetMaxLocals(jvmtiEnv* env,
            jmethodID method,
            jint* max_ptr)
For the method indicated by method, return the number of local variable slots used by the method, including the local variables used to pass parameters to the method on its invocation.

See max_locals in the Code Attribute section of the Java Virtual Machine Specification.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 68 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
method | jmethodID | The method to query.
max_ptr | jint* | On return, points to the maximum number of local slots Agent passes a pointer to a jint. On return, the jint has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_METHODID | method is not a jmethodID.
JVMTI_ERROR_NATIVE_METHOD | method is a native method.
JVMTI_ERROR_NULL_POINTER | max_ptr is NULL.

Get Arguments Size

jvmtiError
GetArgumentsSize(jvmtiEnv* env,
            jmethodID method,
            jint* size_ptr)
For the method indicated by method, return via max_ptr the number of local variable slots used by the method's arguments. Note that two-word arguments use two slots.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 69 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
method | jmethodID | The method to query.
size_ptr | jint* | On return, points to the number of argument slots Agent passes a pointer to a jint. On return, the jint has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_METHODID | method is not a jmethodID.
JVMTI_ERROR_NATIVE_METHOD | method is a native method.
JVMTI_ERROR_NULL_POINTER | size_ptr is NULL.

Get Line Number Table

typedef struct {
    jlocation start_location;
    jint line_number;
} jvmtiLineNumberEntry;
jvmtiError
GetLineNumberTable(jvmtiEnv* env,
            jmethodID method,
            jint* entry_count_ptr,
            jvmtiLineNumberEntry** table_ptr)
For the method indicated by method, return a table of source line number entries. The size of the table is returned via entry_count_ptr and the table itself is returned via table_ptr.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 70 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_get_line_numbers | Can get the line number table of a method

jvmtiLineNumberEntry - Line number table entry
Field | Type | Description
start_location | jlocation | the jlocation where the line begins
line_number | jint | the line number

Parameters
Name | Type | Description
method | jmethodID | The method to query.
entry_count_ptr | jint* | On return, points to the number of entries in the table Agent passes a pointer to a jint. On return, the jint has been set.
table_ptr | jvmtiLineNumberEntry** | On return, points to the line number table pointer. Agent passes a pointer to a jvmtiLineNumberEntry*. On return, the jvmtiLineNumberEntry* points to a newly allocated array of size *entry_count_ptr. The array should be freed with Deallocate.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_get_line_numbers. Use AddCapabilities.
JVMTI_ERROR_ABSENT_INFORMATION | Class information does not include line numbers.
JVMTI_ERROR_INVALID_METHODID | method is not a jmethodID.
JVMTI_ERROR_NATIVE_METHOD | method is a native method.
JVMTI_ERROR_NULL_POINTER | entry_count_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | table_ptr is NULL.

Get Method Location

jvmtiError
GetMethodLocation(jvmtiEnv* env,
            jmethodID method,
            jlocation* start_location_ptr,
            jlocation* end_location_ptr)
For the method indicated by method, return the beginning and ending addresses through start_location_ptr and end_location_ptr. In a conventional byte code indexing scheme, start_location_ptr will always point to zero and end_location_ptr will always point to the byte code count minus one.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 71 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
method | jmethodID | The method to query.
start_location_ptr | jlocation* | On return, points to the first location, or -1 if location information is not available. If the information is available and GetJLocationFormat returns JVMTI_JLOCATION_JVMBCI then this will always be zero. Agent passes a pointer to a jlocation. On return, the jlocation has been set.
end_location_ptr | jlocation* | On return, points to the last location, or -1 if location information is not available. Agent passes a pointer to a jlocation. On return, the jlocation has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_ABSENT_INFORMATION | Class information does not include method sizes.
JVMTI_ERROR_INVALID_METHODID | method is not a jmethodID.
JVMTI_ERROR_NATIVE_METHOD | method is a native method.
JVMTI_ERROR_NULL_POINTER | start_location_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | end_location_ptr is NULL.

Get Local Variable Table

typedef struct {
    jlocation start_location;
    jint length;
    char* name;
    char* signature;
    char* generic_signature;
    jint slot;
} jvmtiLocalVariableEntry;
jvmtiError
GetLocalVariableTable(jvmtiEnv* env,
            jmethodID method,
            jint* entry_count_ptr,
            jvmtiLocalVariableEntry** table_ptr)
Return local variable information.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 72 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_access_local_variables | Can set and get local variables

jvmtiLocalVariableEntry - Local variable table entry
Field | Type | Description
start_location | jlocation | The code array index where the local variable is first valid (that is, where it must have a value).
length | jint | The length of the valid section for this local variable. The last code array index where the local variable is valid is start_location + length.
name | char* | The local variable name, encoded as a modified UTF-8 string.
signature | char* | The local variable's type signature, encoded as a modified UTF-8 string. The signature format is the same as that defined in Field Descriptors section of the Java Virtual Machine Specification
generic_signature | char* | The local variable's generic signature, encoded as a modified UTF-8 string. The value of this field will be NULL for any local variable which does not have a generic type.
slot | jint | The local variable's slot. See Local Variables.

Parameters
Name | Type | Description
method | jmethodID | The method to query.
entry_count_ptr | jint* | On return, points to the number of entries in the table Agent passes a pointer to a jint. On return, the jint has been set.
table_ptr | jvmtiLocalVariableEntry** | On return, points to an array of local variable table entries. Agent passes a pointer to a jvmtiLocalVariableEntry*. On return, the jvmtiLocalVariableEntry* points to a newly allocated array of size *entry_count_ptr. The array should be freed with Deallocate. The pointers returned in the field name of jvmtiLocalVariableEntry are newly allocated arrays. The arrays should be freed with Deallocate. The pointers returned in the field signature of jvmtiLocalVariableEntry are newly allocated arrays. The arrays should be freed with Deallocate. The pointers returned in the field generic_signature of jvmtiLocalVariableEntry are newly allocated arrays. The arrays should be freed with Deallocate.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_access_local_variables. Use AddCapabilities.
JVMTI_ERROR_ABSENT_INFORMATION | Class information does not include local variable information.
JVMTI_ERROR_INVALID_METHODID | method is not a jmethodID.
JVMTI_ERROR_NATIVE_METHOD | method is a native method.
JVMTI_ERROR_NULL_POINTER | entry_count_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | table_ptr is NULL.

Get Bytecodes

jvmtiError
GetBytecodes(jvmtiEnv* env,
            jmethodID method,
            jint* bytecode_count_ptr,
            unsigned char** bytecodes_ptr)
For the method indicated by method, return the byte codes that implement the method. The number of bytecodes is returned via bytecode_count_ptr. The byte codes themselves are returned via bytecodes_ptr.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 75 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_get_bytecodes | Can get bytecodes of a method GetBytecodes

Parameters
Name | Type | Description
method | jmethodID | The method to query.
bytecode_count_ptr | jint* | On return, points to the length of the byte code array Agent passes a pointer to a jint. On return, the jint has been set.
bytecodes_ptr | unsigned char** | On return, points to the pointer to the byte code array Agent passes a pointer to a unsigned char*. On return, the unsigned char* points to a newly allocated array of size *bytecode_count_ptr. The array should be freed with Deallocate.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_get_bytecodes. Use AddCapabilities.
JVMTI_ERROR_INVALID_METHODID | method is not a jmethodID.
JVMTI_ERROR_NATIVE_METHOD | method is a native method.
JVMTI_ERROR_NULL_POINTER | bytecode_count_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | bytecodes_ptr is NULL.

Is Method Native

jvmtiError
IsMethodNative(jvmtiEnv* env,
            jmethodID method,
            jboolean* is_native_ptr)
For the method indicated by method, return a value indicating whether the method is native via is_native_ptr

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 76 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
method | jmethodID | The method to query.
is_native_ptr | jboolean* | On return, points to the boolean result of this function. Agent passes a pointer to a jboolean. On return, the jboolean has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_METHODID | method is not a jmethodID.
JVMTI_ERROR_NULL_POINTER | is_native_ptr is NULL.

Is Method Synthetic

jvmtiError
IsMethodSynthetic(jvmtiEnv* env,
            jmethodID method,
            jboolean* is_synthetic_ptr)
For the method indicated by method, return a value indicating whether the method is synthetic via is_synthetic_ptr. Synthetic methods are generated by the compiler but not present in the original source code.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 77 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_get_synthetic_attribute | Can test if a field or method is synthetic - IsFieldSynthetic and IsMethodSynthetic

Parameters
Name | Type | Description
method | jmethodID | The method to query.
is_synthetic_ptr | jboolean* | On return, points to the boolean result of this function. Agent passes a pointer to a jboolean. On return, the jboolean has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_get_synthetic_attribute. Use AddCapabilities.
JVMTI_ERROR_INVALID_METHODID | method is not a jmethodID.
JVMTI_ERROR_NULL_POINTER | is_synthetic_ptr is NULL.

Is Method Obsolete

jvmtiError
IsMethodObsolete(jvmtiEnv* env,
            jmethodID method,
            jboolean* is_obsolete_ptr)
Determine if a method ID refers to an obsolete method version.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 91 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
method | jmethodID | The method ID to query.
is_obsolete_ptr | jboolean* | On return, points to the boolean result of this function. Agent passes a pointer to a jboolean. On return, the jboolean has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_METHODID | method is not a jmethodID.
JVMTI_ERROR_NULL_POINTER | is_obsolete_ptr is NULL.

Set Native Method Prefix

jvmtiError
SetNativeMethodPrefix(jvmtiEnv* env,
            const char* prefix)
This function modifies the failure handling of native method resolution by allowing retry with a prefix applied to the name. When used with the ClassFileLoadHook event, it enables native methods to be instrumented.

Since native methods cannot be directly instrumented (they have no bytecodes), they must be wrapped with a non-native method which can be instrumented. For example, if we had:
native boolean foo(int x);

We could transform the class file (with the ClassFileLoadHook event) so that this becomes:
boolean foo(int x) {
  ... record entry to foo ...
  return wrapped_foo(x);
}

native boolean wrapped_foo(int x);

Where foo becomes a wrapper for the actual native method with the appended prefix "wrapped_". Note that "wrapped_" would be a poor choice of prefix since it might conceivably form the name of an existing method thus something like "$$$MyAgentWrapped$$$_" would be better but would make these examples less readable.

The wrapper will allow data to be collected on the native method call, but now the problem becomes linking up the wrapped method with the native implementation. That is, the method wrapped_foo needs to be resolved to the native implementation of foo, which might be:
Java_somePackage_someClass_foo(JNIEnv* env, jint x)

This function allows the prefix to be specified and the proper resolution to occur. Specifically, when the standard resolution fails, the resolution is retried taking the prefix into consideration. There are two ways that resolution occurs, explicit resolution with the JNI function RegisterNatives and the normal automatic resolution. For RegisterNatives, the VM will attempt this association:
method(foo) -> nativeImplementation(foo)

When this fails, the resolution will be retried with the specified prefix prepended to the method name, yielding the correct resolution:
method(wrapped_foo) -> nativeImplementation(foo)

For automatic resolution, the VM will attempt:
method(wrapped_foo) -> nativeImplementation(wrapped_foo)

When this fails, the resolution will be retried with the specified prefix deleted from the implementation name, yielding the correct resolution:
method(wrapped_foo) -> nativeImplementation(foo)

Note that since the prefix is only used when standard resolution fails, native methods can be wrapped selectively.

Since each JVM TI environment is independent and can do its own transformation of the bytecodes, more than one layer of wrappers may be applied. Thus each environment needs its own prefix. Since transformations are applied in order, the prefixes, if applied, will be applied in the same order. The order of transformation application is described in the ClassFileLoadHook event. Thus if three environments applied wrappers, foo might become $env3_$env2_$env1_foo. But if, say, the second environment did not apply a wrapper to foo it would be just $env3_$env1_foo. To be able to efficiently determine the sequence of prefixes, an intermediate prefix is only applied if its non-native wrapper exists. Thus, in the last example, even though $env1_foo is not a native method, the $env1_ prefix is applied since $env1_foo exists.

Since the prefixes are used at resolution time and since resolution may be arbitrarily delayed, a native method prefix must remain set as long as there are corresponding prefixed native methods.

Phase | Callback Safe | Position | Since
may be called during any phase | No | 73 | 1.1

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_set_native_method_prefix | Can set prefix to be applied when native method cannot be resolved - SetNativeMethodPrefix and SetNativeMethodPrefixes

Parameters
Name | Type | Description
prefix | const char * | The prefix to apply, encoded as a modified UTF-8 string. Agent passes in an array of char. If prefix is NULL, any existing prefix in this environment is cancelled .

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_set_native_method_prefix. Use AddCapabilities.

Set Native Method Prefixes

jvmtiError
SetNativeMethodPrefixes(jvmtiEnv* env,
            jint prefix_count,
            char** prefixes)
For a normal agent, SetNativeMethodPrefix will provide all needed native method prefixing. For a meta-agent that performs multiple independent class file transformations (for example as a proxy for another layer of agents) this function allows each transformation to have its own prefix. The prefixes are applied in the order supplied and are processed in the same manor as described for the application of prefixes from multiple JVM TI environments in SetNativeMethodPrefix.

Any previous prefixes are replaced. Thus, calling this function with a prefix_count of 0 disables prefixing in this environment.

SetNativeMethodPrefix and this function are the two ways to set the prefixes. Calling SetNativeMethodPrefix with a prefix is the same as calling this function with prefix_count of 1. Calling SetNativeMethodPrefix with NULL is the same as calling this function with prefix_count of 0.

Phase | Callback Safe | Position | Since
may be called during any phase | No | 74 | 1.1

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_set_native_method_prefix | Can set prefix to be applied when native method cannot be resolved - SetNativeMethodPrefix and SetNativeMethodPrefixes

Parameters
Name | Type | Description
prefix_count | jint | The number of prefixes to apply.
prefixes | char ** | The prefixes to apply for this environment, each encoded as a modified UTF-8 string.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_set_native_method_prefix. Use AddCapabilities.
JVMTI_ERROR_ILLEGAL_ARGUMENT | prefix_count is less than 0.
JVMTI_ERROR_NULL_POINTER | prefixes is NULL.

Raw Monitor

Raw Monitor functions:
  • Create Raw Monitor
  • Destroy Raw Monitor
  • Raw Monitor Enter
  • Raw Monitor Exit
  • Raw Monitor Wait
  • Raw Monitor Notify
  • Raw Monitor Notify All

Create Raw Monitor

jvmtiError
CreateRawMonitor(jvmtiEnv* env,
            const char* name,
            jrawMonitorID* monitor_ptr)
Create a raw monitor.

Phase | Callback Safe | Position | Since
may only be called during the OnLoad or the live phase | This function may be called from the callbacks to the Heap iteration functions, or from the event handlers for the GarbageCollectionStart, GarbageCollectionFinish, and ObjectFree events. | 31 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
name | const char* | A name to identify the monitor, encoded as a modified UTF-8 string. Agent passes in an array of char.
monitor_ptr | jrawMonitorID* | On return, points to the created monitor. Agent passes a pointer to a jrawMonitorID. On return, the jrawMonitorID has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NULL_POINTER | name is NULL.
JVMTI_ERROR_NULL_POINTER | monitor_ptr is NULL.

Destroy Raw Monitor

jvmtiError
DestroyRawMonitor(jvmtiEnv* env,
            jrawMonitorID monitor)
Destroy the raw monitor. If the monitor being destroyed has been entered by this thread, it will be exited before it is destroyed. If the monitor being destroyed has been entered by another thread, an error will be returned and the monitor will not be destroyed.

Phase | Callback Safe | Position | Since
may only be called during the OnLoad or the live phase | This function may be called from the callbacks to the Heap iteration functions, or from the event handlers for the GarbageCollectionStart, GarbageCollectionFinish, and ObjectFree events. | 32 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
monitor | jrawMonitorID | The monitor

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NOT_MONITOR_OWNER | Not monitor owner
JVMTI_ERROR_INVALID_MONITOR | monitor is not a jrawMonitorID.

Raw Monitor Enter

jvmtiError
RawMonitorEnter(jvmtiEnv* env,
            jrawMonitorID monitor)
Gain exclusive ownership of a raw monitor. The same thread may enter a monitor more then once. The thread must exit the monitor the same number of times as it is entered. If a monitor is entered during OnLoad (before attached threads exist) and has not exited when attached threads come into existence, the enter is considered to have occurred on the main thread.

Phase | Callback Safe | Position | Since
may be called during any phase | This function may be called from the callbacks to the Heap iteration functions, or from the event handlers for the GarbageCollectionStart, GarbageCollectionFinish, and ObjectFree events. | 33 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
monitor | jrawMonitorID | The monitor

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_MONITOR | monitor is not a jrawMonitorID.

Raw Monitor Exit

jvmtiError
RawMonitorExit(jvmtiEnv* env,
            jrawMonitorID monitor)
Release exclusive ownership of a raw monitor.

Phase | Callback Safe | Position | Since
may be called during any phase | This function may be called from the callbacks to the Heap iteration functions, or from the event handlers for the GarbageCollectionStart, GarbageCollectionFinish, and ObjectFree events. | 34 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
monitor | jrawMonitorID | The monitor

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NOT_MONITOR_OWNER | Not monitor owner
JVMTI_ERROR_INVALID_MONITOR | monitor is not a jrawMonitorID.

Raw Monitor Wait

jvmtiError
RawMonitorWait(jvmtiEnv* env,
            jrawMonitorID monitor,
            jlong millis)
Wait for notification of the raw monitor.

Causes the current thread to wait until either another thread calls RawMonitorNotify or RawMonitorNotifyAll for the specified raw monitor, or the specified timeout has elapsed.

Phase | Callback Safe | Position | Since
may be called during any phase | This function may be called from the callbacks to the Heap iteration functions, or from the event handlers for the GarbageCollectionStart, GarbageCollectionFinish, and ObjectFree events. | 35 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
monitor | jrawMonitorID | The monitor
millis | jlong | The timeout, in milliseconds. If the timeout is zero, then real time is not taken into consideration and the thread simply waits until notified.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NOT_MONITOR_OWNER | Not monitor owner
JVMTI_ERROR_INTERRUPT | Wait was interrupted, try again
JVMTI_ERROR_INVALID_MONITOR | monitor is not a jrawMonitorID.

Raw Monitor Notify

jvmtiError
RawMonitorNotify(jvmtiEnv* env,
            jrawMonitorID monitor)
Notify a single thread waiting on the raw monitor.

Phase | Callback Safe | Position | Since
may be called during any phase | This function may be called from the callbacks to the Heap iteration functions, or from the event handlers for the GarbageCollectionStart, GarbageCollectionFinish, and ObjectFree events. | 36 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
monitor | jrawMonitorID | The monitor

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NOT_MONITOR_OWNER | Not monitor owner
JVMTI_ERROR_INVALID_MONITOR | monitor is not a jrawMonitorID.

Raw Monitor Notify All

jvmtiError
RawMonitorNotifyAll(jvmtiEnv* env,
            jrawMonitorID monitor)
Notify all threads waiting on the raw monitor.

Phase | Callback Safe | Position | Since
may be called during any phase | This function may be called from the callbacks to the Heap iteration functions, or from the event handlers for the GarbageCollectionStart, GarbageCollectionFinish, and ObjectFree events. | 37 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
monitor | jrawMonitorID | The monitor

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NOT_MONITOR_OWNER | Not monitor owner
JVMTI_ERROR_INVALID_MONITOR | monitor is not a jrawMonitorID.

JNI Function Interception

JNI Function Interception functions:
  • Set JNI Function Table
  • Get JNI Function Table
Provides the ability to intercept and resend Java Native Interface (JNI) function calls by manipulating the JNI function table. See JNI Functions in the Java Native Interface Specification.

The following example illustrates intercepting the NewGlobalRef JNI call in order to count reference creation.
JNIEnv original_jni_Functions;
JNIEnv redirected_jni_Functions;
int my_global_ref_count = 0;

jobject
MyNewGlobalRef(JNIEnv *jni_env, jobject lobj) {
   ++my_global_ref_count;
   return originalJNIFunctions->NewGlobalRef(env, lobj);
}

void
myInit() {
   jvmtiError err;

   err = (*jvmti_env)->GetJNIFunctionTable(jvmti_env, &original_jni_Functions);
   if (err != JVMTI_ERROR_NONE) {
      die();
   }
   err = (*jvmti_env)->GetJNIFunctionTable(jvmti_env, &redirected_jni_Functions);
   if (err != JVMTI_ERROR_NONE) {
      die();
   }
   redirectedJNIFunctions->NewGlobalRef = MyNewGlobalRef;
      err = (*jvmti_env)->SetJNIFunctionTable(jvmti_env, redirected_jni_Functions);
   if (err != JVMTI_ERROR_NONE) {
      die();
   }
}
Sometime after myInit is called the user's JNI code is executed which makes the call to create a new global reference. Instead of going to the normal JNI implementation the call goes to myNewGlobalRef. Note that a copy of the original function table is kept so that the normal JNI function can be called after the data is collected. Note also that any JNI functions which are not overwritten will behave normally.

Set JNI Function Table

jvmtiError
SetJNIFunctionTable(jvmtiEnv* env,
            const jniNativeInterface* function_table)
Set the JNI function table in all current and future JNI environments. As a result, all future JNI calls are directed to the specified functions. Use GetJNIFunctionTable to get the function table to pass to this function. For this function to take effect the the updated table entries must be used by the JNI clients. Since the table is defined const some compilers may optimize away the access to the table, thus preventing this function from taking effect. The table is copied--changes to the local copy of the table have no effect. This function affects only the function table, all other aspects of the environment are unaffected. See the examples above.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 120 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
function_table | const jniNativeInterface * | Points to the new JNI function table. Agent passes in a pointer to jniNativeInterface.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NULL_POINTER | function_table is NULL.

Get JNI Function Table

jvmtiError
GetJNIFunctionTable(jvmtiEnv* env,
            jniNativeInterface** function_table)
Get the JNI function table. The JNI function table is copied into allocated memory. If SetJNIFunctionTable has been called, the modified (not the original) function table is returned. Only the function table is copied, no other aspects of the environment are copied. See the examples above.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | No | 121 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
function_table | jniNativeInterface ** | On return, *function_table points a newly allocated copy of the JNI function table. Agent passes a pointer to a jniNativeInterface*. On return, the jniNativeInterface* points to a newly allocated array. The array should be freed with Deallocate.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NULL_POINTER | function_table is NULL.

Event Management

Event Management functions:
  • Set Event Callbacks
  • Set Event Notification Mode
  • Generate Events
Event Management types:
  • jvmtiEventMode - Event Enable/Disable

Set Event Callbacks

jvmtiError
SetEventCallbacks(jvmtiEnv* env,
            const jvmtiEventCallbacks* callbacks,
            jint size_of_callbacks)
Set the functions to be called for each event. The callbacks are specified by supplying a replacement function table. The function table is copied--changes to the local copy of the table have no effect. This is an atomic action, all callbacks are set at once. No events are sent before this function is called. When an entry is NULL or when the event is beyond size_of_callbacks no event is sent. Details on events are described later in this document. An event must be enabled and have a callback in order to be sent--the order in which this function and SetEventNotificationMode are called does not affect the result.

Phase | Callback Safe | Position | Since
may only be called during the OnLoad or the live phase | No | 122 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
callbacks | const jvmtiEventCallbacks * | The new event callbacks. Agent passes in a pointer to jvmtiEventCallbacks. If callbacks is NULL, remove the existing callbacks.
size_of_callbacks | jint | sizeof(jvmtiEventCallbacks)--for version compatibility.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_ILLEGAL_ARGUMENT | size_of_callbacks is less than 0.

Set Event Notification Mode

typedef enum {
    JVMTI_ENABLE = 1,
    JVMTI_DISABLE = 0
} jvmtiEventMode;
jvmtiError
SetEventNotificationMode(jvmtiEnv* env,
            jvmtiEventMode mode,
            jvmtiEvent event_type,
            jthread event_thread,
             ...)
Control the generation of events.
Event Enable/Disable (jvmtiEventMode)
Constant | Value | Description
JVMTI_ENABLE | 1 | If mode is JVMTI_ENABLE, the event event_type will be enabled
JVMTI_DISABLE | 0 | If mode is JVMTI_DISABLE, the event event_type will be disabled
If thread is NULL, the event is enabled or disabled globally; otherwise, it is enabled or disabled for a particular thread. An event is generated for a particular thread if it is enabled either at the thread or global levels.

See below for information on specific events.

The following events cannot be controlled at the thread level through this function.
  • VMInit
  • VMStart
  • VMDeath
  • ThreadStart
  • CompiledMethodLoad
  • CompiledMethodUnload
  • DynamicCodeGenerated
  • DataDumpRequest

Initially, no events are enabled at either the thread level or the global level.

Any needed capabilities (see Event Enabling Capabilities below) must be possessed before calling this function.

Details on events are described below.

Phase | Callback Safe | Position | Since
may only be called during the OnLoad or the live phase | No | 2 | 1.0

Capabilities
Required Functionality
Event Enabling Capabilities
Capability | Events
can_generate_field_modification_events | FieldModification
can_generate_field_access_events | FieldAccess
can_generate_single_step_events | SingleStep
can_generate_exception_events | Exception ExceptionCatch
can_generate_frame_pop_events | FramePop
can_generate_breakpoint_events | Breakpoint
can_generate_method_entry_events | MethodEntry
can_generate_method_exit_events | MethodExit
can_generate_compiled_method_load_events | CompiledMethodLoad CompiledMethodUnload
can_generate_monitor_events | MonitorContendedEnter MonitorContendedEntered MonitorWait MonitorWaited
can_generate_vm_object_alloc_events | VMObjectAlloc
can_generate_native_method_bind_events | NativeMethodBind
can_generate_garbage_collection_events | GarbageCollectionStart GarbageCollectionFinish
can_generate_object_free_events | ObjectFree

Parameters
Name | Type | Description
mode | jvmtiEventMode | JVMTI_ENABLE or JVMTI_DISABLE
event_type | jvmtiEvent | the event to control
event_thread | jthread | The thread to control If event_thread is NULL, event is controlled at the global level.
... | ... | for future expansion

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_INVALID_THREAD | event_thread is non-NULL and is not a valid thread.
JVMTI_ERROR_THREAD_NOT_ALIVE | event_thread is non-NULL and is not live (has not been started or is now dead).
JVMTI_ERROR_ILLEGAL_ARGUMENT | thread level control was attempted on events which do not permit thread level control.
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The Required Event Enabling Capability is not possessed.
JVMTI_ERROR_ILLEGAL_ARGUMENT | mode is not a jvmtiEventMode.
JVMTI_ERROR_INVALID_EVENT_TYPE | event_type is not a jvmtiEvent.

Generate Events

jvmtiError
GenerateEvents(jvmtiEnv* env,
            jvmtiEvent event_type)
Generate events to represent the current state of the VM. For example, if event_type is JVMTI_EVENT_COMPILED_METHOD_LOAD, a CompiledMethodLoad event will be sent for each currently compiled method. Methods that were loaded and now have been unloaded are not sent. The history of what events have previously been sent does not effect what events are sent by this function--for example, all currently compiled methods will be sent each time this function is called.

This function is useful when events may have been missed due to the agent attaching after program execution begins; this function generates the missed events.

Attempts to execute Java programming language code or JNI functions may be paused until this function returns - so neither should be called from the thread sending the event. This function returns only after the missed events have been sent, processed and have returned. The event may be sent on a different thread than the thread on which the event occurred. The callback for the event must be set with SetEventCallbacks and the event must be enabled with SetEventNotificationMode or the events will not occur. If the VM no longer has the information to generate some or all of the requested events, the events are simply not sent - no error is returned.

Only the following events are supported:
  • CompiledMethodLoad
  • DynamicCodeGenerated

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 123 | 1.0

Capabilities
Required Functionality
Optional Features
Capability | Effect
can_generate_compiled_method_load_events | Can generate events when a method is compiled or unloaded

Parameters
Name Type Description
event_type jvmtiEvent The type of event to generate. Must be one of these:
  • JVMTI_EVENT_COMPILED_METHOD_LOAD
  • JVMTI_EVENT_DYNAMIC_CODE_GENERATED

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | event_type is JVMTI_EVENT_COMPILED_METHOD_LOAD and can_generate_compiled_method_load_events is false.
JVMTI_ERROR_ILLEGAL_ARGUMENT | event_type is other than JVMTI_EVENT_COMPILED_METHOD_LOAD or JVMTI_EVENT_DYNAMIC_CODE_GENERATED.
JVMTI_ERROR_INVALID_EVENT_TYPE | event_type is not a jvmtiEvent.

Extension Mechanism

Extension Mechanism functions:
  • Get Extension Functions
  • Get Extension Events
  • Set Extension Event Callback
Extension Mechanism function types:
  • Extension Function
  • Extension Event
Extension Mechanism types:
  • jvmtiParamTypes - Extension Function/Event Parameter Types
  • jvmtiParamKind - Extension Function/Event Parameter Kinds
  • jvmtiParamInfo - Extension Function/Event Parameter Info
  • jvmtiExtensionFunctionInfo - Extension Function Info
  • jvmtiExtensionEventInfo - Extension Event Info
These functions allow a JVM TI implementation to provide functions and events beyond those defined in this specification.

Both extension functions and extension events have parameters each of which has a 'type' and 'kind' chosen from the following tables:
Extension Function/Event Parameter Types (jvmtiParamTypes)
Constant | Value | Description
JVMTI_TYPE_JBYTE | 101 | Java programming language primitive type - byte. JNI type jbyte.
JVMTI_TYPE_JCHAR | 102 | Java programming language primitive type - char. JNI type jchar.
JVMTI_TYPE_JSHORT | 103 | Java programming language primitive type - short. JNI type jshort.
JVMTI_TYPE_JINT | 104 | Java programming language primitive type - int. JNI type jint.
JVMTI_TYPE_JLONG | 105 | Java programming language primitive type - long. JNI type jlong.
JVMTI_TYPE_JFLOAT | 106 | Java programming language primitive type - float. JNI type jfloat.
JVMTI_TYPE_JDOUBLE | 107 | Java programming language primitive type - double. JNI type jdouble.
JVMTI_TYPE_JBOOLEAN | 108 | Java programming language primitive type - boolean. JNI type jboolean.
JVMTI_TYPE_JOBJECT | 109 | Java programming language object type - java.lang.Object. JNI type jobject. Returned values are JNI local references and must be managed.
JVMTI_TYPE_JTHREAD | 110 | Java programming language object type - java.lang.Thread. JVM TI type jthread. Returned values are JNI local references and must be managed.
JVMTI_TYPE_JCLASS | 111 | Java programming language object type - java.lang.Class. JNI type jclass. Returned values are JNI local references and must be managed.
JVMTI_TYPE_JVALUE | 112 | Union of all Java programming language primitive and object types - JNI type jvalue. Returned values which represent object types are JNI local references and must be managed.
JVMTI_TYPE_JFIELDID | 113 | Java programming language field identifier - JNI type jfieldID.
JVMTI_TYPE_JMETHODID | 114 | Java programming language method identifier - JNI type jmethodID.
JVMTI_TYPE_CCHAR | 115 | C programming language type - char.
JVMTI_TYPE_CVOID | 116 | C programming language type - void.
JVMTI_TYPE_JNIENV | 117 | JNI environment - JNIEnv. Should be used with the correct jvmtiParamKind to make it a pointer type.
Extension Function/Event Parameter Kinds (jvmtiParamKind)
Constant | Value | Description
JVMTI_KIND_IN | 91 | Ingoing argument - foo.
JVMTI_KIND_IN_PTR | 92 | Ingoing pointer argument - const foo*.
JVMTI_KIND_IN_BUF | 93 | Ingoing array argument - const foo*.
JVMTI_KIND_ALLOC_BUF | 94 | Outgoing allocated array argument - foo**. Free with Deallocate.
JVMTI_KIND_ALLOC_ALLOC_BUF | 95 | Outgoing allocated array of allocated arrays argument - foo***. Free with Deallocate.
JVMTI_KIND_OUT | 96 | Outgoing argument - foo*.
JVMTI_KIND_OUT_BUF | 97 | Outgoing array argument (pre-allocated by agent) - foo*. Do not Deallocate.

Extension Function/Event Parameter Info

typedef struct {
    char* name;
    jvmtiParamKind kind;
    jvmtiParamTypes base_type;
    jboolean null_ok;
} jvmtiParamInfo;
jvmtiParamInfo - Extension Function/Event Parameter Info
Field | Type | Description
name | char* | The parameter name, encoded as a modified UTF-8 string
kind | jvmtiParamKind | The kind of the parameter - type modifiers
base_type | jvmtiParamTypes | The base type of the parameter - modified by kind
null_ok | jboolean | Is a NULL argument permitted? Applies only to pointer and object types.

Extension Function

typedef jvmtiError (JNICALL *jvmtiExtensionFunction)
    (jvmtiEnv* jvmti_env,
      ...);
This is the implementation-specific extension function.

Parameters
Name | Type | Description
jvmti_env | jvmtiEnv * | The JVM TI environment is the only fixed parameter for extension functions.
... | ... | The extension function-specific parameters

Get Extension Functions

typedef struct {
    jvmtiExtensionFunction func;
    char* id;
    char* short_description;
    jint param_count;
    jvmtiParamInfo* params;
    jint error_count;
    jvmtiError* errors;
} jvmtiExtensionFunctionInfo;
jvmtiError
GetExtensionFunctions(jvmtiEnv* env,
            jint* extension_count_ptr,
            jvmtiExtensionFunctionInfo** extensions)
Returns the set of extension functions.

Phase | Callback Safe | Position | Since
may only be called during the OnLoad or the live phase | No | 124 | 1.0

Capabilities
Required Functionality

jvmtiExtensionFunctionInfo - Extension Function Info
Field | Type | Description
func | jvmtiExtensionFunction | The actual function to call
id | char* | The identifier for the extension function, encoded as a modified UTF-8 string. Uses package name conventions. For example, com.sun.hotspot.bar
short_description | char* | A one sentence description of the function, encoded as a modified UTF-8 string.
param_count | jint | The number of parameters excluding jvmtiEnv *jvmti_env
params | jvmtiParamInfo * | Array of param_count parameters (jvmtiEnv *jvmti_env excluded)
error_count | jint | The number of possible error returns (excluding universal errors)
errors | jvmtiError * | Array of error_count possible errors

Parameters
Name | Type | Description
extension_count_ptr | jint* | On return, points to the number of extension functions Agent passes a pointer to a jint. On return, the jint has been set.
extensions | jvmtiExtensionFunctionInfo** | Returns an array of extension function info, one per function Agent passes a pointer to a jvmtiExtensionFunctionInfo*. On return, the jvmtiExtensionFunctionInfo* points to a newly allocated array of size *extension_count_ptr. The array should be freed with Deallocate. The pointers returned in the field id of jvmtiExtensionFunctionInfo are newly allocated arrays. The arrays should be freed with Deallocate. The pointers returned in the field short_description of jvmtiExtensionFunctionInfo are newly allocated arrays. The arrays should be freed with Deallocate. The pointers returned in the field params of jvmtiExtensionFunctionInfo are newly allocated arrays. The arrays should be freed with Deallocate. The pointers returned in the field name of jvmtiParamInfo are newly allocated arrays. The arrays should be freed with Deallocate. The pointers returned in the field errors of jvmtiExtensionFunctionInfo are newly allocated arrays. The arrays should be freed with Deallocate.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NULL_POINTER | extension_count_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | extensions is NULL.

Get Extension Events

typedef struct {
    jint extension_event_index;
    char* id;
    char* short_description;
    jint param_count;
    jvmtiParamInfo* params;
} jvmtiExtensionEventInfo;
jvmtiError
GetExtensionEvents(jvmtiEnv* env,
            jint* extension_count_ptr,
            jvmtiExtensionEventInfo** extensions)
Returns the set of extension events.

Phase | Callback Safe | Position | Since
may only be called during the OnLoad or the live phase | No | 125 | 1.0

Capabilities
Required Functionality

jvmtiExtensionEventInfo - Extension Event Info
Field | Type | Description
extension_event_index | jint | The identifying index of the event
id | char* | The identifier for the extension event, encoded as a modified UTF-8 string. Uses package name conventions. For example, com.sun.hotspot.bar
short_description | char* | A one sentence description of the event, encoded as a modified UTF-8 string.
param_count | jint | The number of parameters excluding jvmtiEnv *jvmti_env
params | jvmtiParamInfo * | Array of param_count parameters (jvmtiEnv *jvmti_env excluded)

Parameters
Name | Type | Description
extension_count_ptr | jint* | On return, points to the number of extension events Agent passes a pointer to a jint. On return, the jint has been set.
extensions | jvmtiExtensionEventInfo** | Returns an array of extension event info, one per event Agent passes a pointer to a jvmtiExtensionEventInfo*. On return, the jvmtiExtensionEventInfo* points to a newly allocated array of size *extension_count_ptr. The array should be freed with Deallocate. The pointers returned in the field id of jvmtiExtensionEventInfo are newly allocated arrays. The arrays should be freed with Deallocate. The pointers returned in the field short_description of jvmtiExtensionEventInfo are newly allocated arrays. The arrays should be freed with Deallocate. The pointers returned in the field params of jvmtiExtensionEventInfo are newly allocated arrays. The arrays should be freed with Deallocate. The pointers returned in the field name of jvmtiParamInfo are newly allocated arrays. The arrays should be freed with Deallocate.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NULL_POINTER | extension_count_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | extensions is NULL.

Extension Event

typedef void (JNICALL *jvmtiExtensionEvent)
    (jvmtiEnv* jvmti_env,
      ...);
This is the implementation-specific event. The event handler is set with SetExtensionEventCallback.

Event handlers for extension events must be declared varargs to match this definition. Failure to do so could result in calling convention mismatch and undefined behavior on some platforms.

For example, if the jvmtiParamInfo returned by GetExtensionEvents indicates that there is a jint parameter, the event handler should be declared:
    void JNICALL myHandler(jvmtiEnv* jvmti_env, jint myInt, ...)
Note the terminal "..." which indicates varargs.

Parameters
Name | Type | Description
jvmti_env | jvmtiEnv * | The JVM TI environment is the only fixed parameter for extension events.
... | ... | The extension event-specific parameters

Set Extension Event Callback

jvmtiError
SetExtensionEventCallback(jvmtiEnv* env,
            jint extension_event_index,
            jvmtiExtensionEvent callback)
Sets the callback function for an extension event and enables the event. Or, if the callback is NULL, disables the event. Note that unlike standard events, setting the callback and enabling the event are a single operation.

Phase | Callback Safe | Position | Since
may only be called during the OnLoad or the live phase | No | 126 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
extension_event_index | jint | Identifies which callback to set. This index is the extension_event_index field of jvmtiExtensionEventInfo.
callback | jvmtiExtensionEvent | If callback is non-NULL, set callback to be the event callback function and enable the event. If callback is NULL, disable the event.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_ILLEGAL_ARGUMENT | extension_event_index is not an extension_event_index returned by GetExtensionEvents

Capability

Capability functions:
  • Get Potential Capabilities
  • Add Capabilities
  • Relinquish Capabilities
  • Get Capabilities
Capability types:
  • jvmtiCapabilities - The Capabilities Structure
The capabilities functions allow you to change the functionality available to JVM TI--that is, which JVM TI functions can be called, what events can be generated, and what functionality these events and functions can provide.

The "Capabilities" section of each function and event describe which capabilities, if any, they are associated with. "Required Functionality" means it is available for use and no capabilities must be added to use it. "Optional Functionality" means the agent must possess the capability before it can be used. To possess a capability, the agent must add the capability. "Optional Features" describe capabilities which, if added, extend the feature set.

The potentially available capabilities of each JVM TI implementation are different. Depending on the implementation, a capability:
  • may never be added
  • may be added in either the OnLoad or live phase in any environment
  • may be added only during the OnLoad phase
  • may be possessed by only one environment at a time
  • may be possessed by only one environment at a time, and only during the OnLoad phase
  • and so on ...
Frequently, the addition of a capability may incur a cost in execution speed, start up time, and/or memory footprint. Note that the overhead of using a capability is completely different than the overhead of possessing a capability. Take single stepping as an example. When single stepping is on (that is, when the event is enabled and thus actively sending events) the overhead of sending and processing an event on each instruction is huge in any implementation. However, the overhead of possessing the capability may be small or large, depending on the implementation. Also, when and if a capability is potentially available depends on the implementation. Some examples:
  • One VM might perform all execution by compiling bytecodes into native code and be unable to generate single step instructions. In this implementation the capability can not be added.
  • Another VM may be able to switch execution to a single stepping interpreter at any time. In this implementation, having the capability has no overhead and could be added at any time.
  • Yet another VM might be able to choose a bytecode compiling or single stepping capable interpreted execution engine at start up, but be unable to switch between them. In this implementation the capability would need to be added during the OnLoad phase (before bytecode execution begins) and would have a large impact on execution speed even if single stepping was never used.
  • Still another VM might be able to add an "is single stepping on" check into compiled bytecodes or a generated interpreter. Again in this implementation the capability would need to be added during the OnLoad phase but the overhead (a test and branch on each instruction) would be considerably less.

Each JVM TI environment has its own set of capabilities. Initially, that set is empty. Any desired capability must be added. If possible, capabilities should be added during the OnLoad phase. For most virtual machines certain capabilities require special set up for the virtual machine and this set up must happen during the OnLoad phase, before the virtual machine begins execution. Once a capability is added, it can only be removed if explicitly relinquished by the environment.

The agent can, determine what capabilities this VM can potentially provide, add the capabilities to be used, release capabilities which are no longer needed, and examine the currently available capabilities.

Capability Examples

For example, a freshly started agent (in the OnLoad function) wants to enable all possible capabilities. Note that, in general, this is not advisable as the agent may suffer a performance penalty for functionality it is not using. The code might look like this in C:
    jvmtiCapabilities capa;
    jvmtiError err;

    err = (*jvmti)->GetPotentialCapabilities(jvmti, &capa);
    if (err == JVMTI_ERROR_NONE) {
       err = (*jvmti)->AddCapabilities(jvmti, &capa);
For example, if an agent wants to check if it can get the bytecodes of a method (that is, it wants to check if it previously added this capability and has not relinquished it), the code might look like this in C:
    jvmtiCapabilities capa;
    jvmtiError err;

    err = (*jvmti)->GetCapabilities(jvmti, &capa);
    if (err == JVMTI_ERROR_NONE) {
          if (capa.can_get_bytecodes) { ... } }

The Capabilities Structure

The functions in this category use this capabilities structure which contains boolean flags corresponding to each capability:

typedef struct {
    unsigned int can_tag_objects : 1;
    unsigned int can_generate_field_modification_events : 1;
    unsigned int can_generate_field_access_events : 1;
    unsigned int can_get_bytecodes : 1;
    unsigned int can_get_synthetic_attribute : 1;
    unsigned int can_get_owned_monitor_info : 1;
    unsigned int can_get_current_contended_monitor : 1;
    unsigned int can_get_monitor_info : 1;
    unsigned int can_pop_frame : 1;
    unsigned int can_redefine_classes : 1;
    unsigned int can_signal_thread : 1;
    unsigned int can_get_source_file_name : 1;
    unsigned int can_get_line_numbers : 1;
    unsigned int can_get_source_debug_extension : 1;
    unsigned int can_access_local_variables : 1;
    unsigned int can_maintain_original_method_order : 1;
    unsigned int can_generate_single_step_events : 1;
    unsigned int can_generate_exception_events : 1;
    unsigned int can_generate_frame_pop_events : 1;
    unsigned int can_generate_breakpoint_events : 1;
    unsigned int can_suspend : 1;
    unsigned int can_redefine_any_class : 1;
    unsigned int can_get_current_thread_cpu_time : 1;
    unsigned int can_get_thread_cpu_time : 1;
    unsigned int can_generate_method_entry_events : 1;
    unsigned int can_generate_method_exit_events : 1;
    unsigned int can_generate_all_class_hook_events : 1;
    unsigned int can_generate_compiled_method_load_events : 1;
    unsigned int can_generate_monitor_events : 1;
    unsigned int can_generate_vm_object_alloc_events : 1;
    unsigned int can_generate_native_method_bind_events : 1;
    unsigned int can_generate_garbage_collection_events : 1;
    unsigned int can_generate_object_free_events : 1;
    unsigned int can_force_early_return : 1;
    unsigned int can_get_owned_monitor_stack_depth_info : 1;
    unsigned int can_get_constant_pool : 1;
    unsigned int can_set_native_method_prefix : 1;
    unsigned int can_retransform_classes : 1;
    unsigned int can_retransform_any_class : 1;
    unsigned int can_generate_resource_exhaustion_heap_events : 1;
    unsigned int can_generate_resource_exhaustion_threads_events : 1;
    unsigned int : 7;
    unsigned int : 16;
    unsigned int : 16;
    unsigned int : 16;
    unsigned int : 16;
    unsigned int : 16;
} jvmtiCapabilities;
jvmtiCapabilities - The Capabilities Structure
All types are unsigned int : 1
Field | Description | Since
can_tag_objects | Can set and get tags, as described in the Heap category. | 1.0
can_generate_field_modification_events | Can set watchpoints on field modification - SetFieldModificationWatch | 1.0
can_generate_field_access_events | Can set watchpoints on field access - SetFieldAccessWatch | 1.0
can_get_bytecodes | Can get bytecodes of a method GetBytecodes | 1.0
can_get_synthetic_attribute | Can test if a field or method is synthetic - IsFieldSynthetic and IsMethodSynthetic | 1.0
can_get_owned_monitor_info | Can get information about ownership of monitors - GetOwnedMonitorInfo | 1.0
can_get_current_contended_monitor | Can GetCurrentContendedMonitor | 1.0
can_get_monitor_info | Can GetObjectMonitorUsage | 1.0
can_pop_frame | Can pop frames off the stack - PopFrame | 1.0
can_redefine_classes | Can redefine classes with RedefineClasses. | 1.0
can_signal_thread | Can send stop or interrupt to threads | 1.0
can_get_source_file_name | Can get the source file name of a class | 1.0
can_get_line_numbers | Can get the line number table of a method | 1.0
can_get_source_debug_extension | Can get the source debug extension of a class | 1.0
can_access_local_variables | Can set and get local variables | 1.0
can_maintain_original_method_order | Can return methods in the order they occur in the class file | 1.0
can_generate_single_step_events | Can get single step events | 1.0
can_generate_exception_events | Can get exception thrown and exception catch events | 1.0
can_generate_frame_pop_events | Can set and thus get FramePop events | 1.0
can_generate_breakpoint_events | Can set and thus get Breakpoint events | 1.0
can_suspend | Can suspend and resume threads | 1.0
can_redefine_any_class | Can modify (retransform or redefine) any non-primitive non-array class. See IsModifiableClass. | 1.0
can_get_current_thread_cpu_time | Can get current thread CPU time | 1.0
can_get_thread_cpu_time | Can get thread CPU time | 1.0
can_generate
_method_entry_events 		Can generate method entry events on entering a method 1.0
can_generate
_method_exit_events 		Can generate method exit events on leaving a method 1.0
can_generate
_all_class_hook_events 		Can generate ClassFileLoadHook events for every loaded class. 1.0
can_generate
_compiled_method_load_events 		Can generate events when a method is compiled or unloaded 1.0
can_generate
_monitor_events 		Can generate events on monitor activity 1.0
can_generate
_vm_object_alloc_events 		Can generate events on VM allocation of an object 1.0
can_generate
_native_method_bind_events 		Can generate events when a native method is bound to its implementation 1.0
can_generate
_garbage_collection_events 		Can generate events when garbage collection begins or ends 1.0
can_generate
_object_free_events 		Can generate events when the garbage collector frees an object 1.0
can_force_early_return | Can return early from a method, as described in the Force Early Return category. | 1.1
can_get_owned_monitor_stack_depth_info | Can get information about owned monitors with stack depth - GetOwnedMonitorStackDepthInfo | 1.1
can_get_constant_pool | Can get the constant pool of a class - GetConstantPool | 1.1
can_set_native_method_prefix | Can set prefix to be applied when native method cannot be resolved - SetNativeMethodPrefix and SetNativeMethodPrefixes | 1.1
can_retransform_classes | Can retransform classes with RetransformClasses. In addition to the restrictions imposed by the specific implementation on this capability (see the Capability section), this capability must be set before the ClassFileLoadHook event is enabled for the first time in this environment. An environment that possesses this capability at the time that ClassFileLoadHook is enabled for the first time is said to be retransformation capable. An environment that does not possess this capability at the time that ClassFileLoadHook is enabled for the first time is said to be retransformation incapable. | 1.1
can_retransform_any_class | RetransformClasses can be called on any class (can_retransform_classes must also be set) | 1.1
can_generate_resource_exhaustion_heap_events | Can generate events when the VM is unable to allocate memory from the JavaTM platform heap. See ResourceExhausted. | 1.1
can_generate_resource_exhaustion_threads_events | Can generate events when the VM is unable to create a thread. See ResourceExhausted. | 1.1

Get Potential Capabilities

jvmtiError
GetPotentialCapabilities(jvmtiEnv* env,
            jvmtiCapabilities* capabilities_ptr)
Returns via capabilities_ptr the JVM TI features that can potentially be possessed by this environment at this time. The returned capabilities differ from the complete set of capabilities implemented by the VM in two cases: another environment possesses capabilities that can only be possessed by one environment, or the current phase is live, and certain capabilities can only be added during the OnLoad phase. The AddCapabilities function may be used to set any or all or these capabilities. Currently possessed capabilities are included.

Typically this function is used in the OnLoad function. Some virtual machines may allow a limited set of capabilities to be added in the live phase. In this case, the set of potentially available capabilities will likely differ from the OnLoad phase set.

See the Capability Examples.

Phase | Callback Safe | Position | Since
may only be called during the OnLoad or the live phase | No | 140 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
capabilities_ptr | jvmtiCapabilities* | On return, points to the JVM TI capabilities that may be added. Agent passes a pointer to a jvmtiCapabilities. On return, the jvmtiCapabilities has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NULL_POINTER | capabilities_ptr is NULL.

Add Capabilities

jvmtiError
AddCapabilities(jvmtiEnv* env,
            const jvmtiCapabilities* capabilities_ptr)
Set new capabilities by adding the capabilities whose values are set to one (1) in * capabilities_ptr. All previous capabilities are retained. Typically this function is used in the OnLoad function. Some virtual machines may allow a limited set of capabilities to be added in the live phase.

See the Capability Examples.

Phase | Callback Safe | Position | Since
may only be called during the OnLoad or the live phase | No | 142 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
capabilities_ptr | const jvmtiCapabilities* | Points to the JVM TI capabilities to add. Agent passes in a pointer to jvmtiCapabilities.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NOT_AVAILABLE | The desired capabilities are not even potentially available.
JVMTI_ERROR_NULL_POINTER | capabilities_ptr is NULL.

Relinquish Capabilities

jvmtiError
RelinquishCapabilities(jvmtiEnv* env,
            const jvmtiCapabilities* capabilities_ptr)
Relinquish the capabilities whose values are set to one (1) in * capabilities_ptr. Some implementations may allow only one environment to have a capability (see the capability introduction). This function releases capabilities so that they may be used by other agents. All other capabilities are retained. The capability will no longer be present in GetCapabilities. Attempting to relinquish a capability that the agent does not possess is not an error.

Phase | Callback Safe | Position | Since
may only be called during the OnLoad or the live phase | No | 143 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
capabilities_ptr | const jvmtiCapabilities* | Points to the JVM TI capabilities to relinquish. Agent passes in a pointer to jvmtiCapabilities.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NULL_POINTER | capabilities_ptr is NULL.

Get Capabilities

jvmtiError
GetCapabilities(jvmtiEnv* env,
            jvmtiCapabilities* capabilities_ptr)
Returns via capabilities_ptr the optional JVM TI features which this environment currently possesses. Each possessed capability is indicated by a one (1) in the corresponding field of the capabilities structure. An environment does not possess a capability unless it has been successfully added with AddCapabilities. An environment only loses possession of a capability if it has been relinquished with RelinquishCapabilities. Thus, this function returns the net result of the AddCapabilities and RelinquishCapabilities calls which have been made.

See the Capability Examples.

Phase | Callback Safe | Position | Since
may be called during any phase | No | 89 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
capabilities_ptr | jvmtiCapabilities* | On return, points to the JVM TI capabilities. Agent passes a pointer to a jvmtiCapabilities. On return, the jvmtiCapabilities has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NULL_POINTER | capabilities_ptr is NULL.

Timers

Timers functions:
  • Get Current Thread CPU Timer Information
  • Get Current Thread CPU Time
  • Get Thread CPU Timer Information
  • Get Thread CPU Time
  • Get Timer Information
  • Get Time
  • Get Available Processors
Timers types:
  • jvmtiTimerInfo - Timer Info
  • jvmtiTimerKind - Timer Kinds
These functions provide timing information. The resolution at which the time is updated is not specified. They provides nanosecond precision, but not necessarily nanosecond accuracy. Details about the timers, such as their maximum values, can be accessed with the timer information functions.

Timer Info

The information function for each timer returns this data structure.

typedef struct {
    jlong max_value;
    jboolean may_skip_forward;
    jboolean may_skip_backward;
    jvmtiTimerKind kind;
    jlong reserved1;
    jlong reserved2;
} jvmtiTimerInfo;
jvmtiTimerInfo - Timer Info
Field | Type | Description
max_value | jlong | The maximum value the timer can reach. After this value is reached the timer wraps back to zero. This is an unsigned value. If tested or printed as a jlong (signed value) it may appear to be a negative number.
may_skip_forward | jboolean | If true, the timer can be externally adjusted and as a result skip forward. If false, the timer value will never increase faster than real time.
may_skip_backward | jboolean | If true, the timer can be externally adjusted and as a result skip backward. If false, the timer value will be monotonically increasing.
kind | jvmtiTimerKind | The kind of timer. On a platform that does not distinguish between user and system time, JVMTI_TIMER_TOTAL_CPU is returned.
reserved1 | jlong | Reserved for future use.
reserved2 | jlong | Reserved for future use.
Where the timer kind is --
Timer Kinds (jvmtiTimerKind)
Constant | Value | Description
JVMTI_TIMER_USER_CPU | 30 | CPU time that a thread is in user mode.
JVMTI_TIMER_TOTAL_CPU | 31 | CPU time that a thread is in user or system mode.
JVMTI_TIMER_ELAPSED | 32 | Elapsed time.

Get Current Thread CPU Timer Information

jvmtiError
GetCurrentThreadCpuTimerInfo(jvmtiEnv* env,
            jvmtiTimerInfo* info_ptr)
Get information about the GetCurrentThreadCpuTime timer. The fields of the jvmtiTimerInfo structure are filled in with details about the timer. This information is specific to the platform and the implementation of GetCurrentThreadCpuTime and thus does not vary by thread nor does it vary during a particular invocation of the VM.

Note that the implementations of GetCurrentThreadCpuTime and GetThreadCpuTime may differ, and thus the values returned by GetCurrentThreadCpuTimerInfo and GetThreadCpuTimerInfo may differ -- see GetCurrentThreadCpuTime for more information.

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | This function may be called from the callbacks to the Heap iteration functions, or from the event handlers for the GarbageCollectionStart, GarbageCollectionFinish, and ObjectFree events. | 134 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_get_current_thread_cpu_time | Can get current thread CPU time.

Parameters
Name | Type | Description
info_ptr | jvmtiTimerInfo* | On return, filled with information describing the time returned by GetCurrentThreadCpuTime. Agent passes a pointer to a jvmtiTimerInfo. On return, the jvmtiTimerInfo has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_get_current_thread_cpu_time. Use AddCapabilities.
JVMTI_ERROR_NULL_POINTER | info_ptr is NULL.

Get Current Thread CPU Time

jvmtiError
GetCurrentThreadCpuTime(jvmtiEnv* env,
            jlong* nanos_ptr)
Return the CPU time utilized by the current thread.

Note that the GetThreadCpuTime function provides CPU time for any thread, including the current thread. GetCurrentThreadCpuTime exists to support platforms which cannot supply CPU time for threads other than the current thread or which have more accurate information for the current thread (see GetCurrentThreadCpuTimerInfo vs GetThreadCpuTimerInfo). On many platforms this call will be equivalent to:
  GetThreadCpuTime(env, NULL, nanos_ptr)

Phase | Callback Safe | Position | Since
may only be called during the start or the live phase | This function may be called from the callbacks to the Heap iteration functions, or from the event handlers for the GarbageCollectionStart, GarbageCollectionFinish, and ObjectFree events. | 135 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_get_current_thread_cpu_time | Can get current thread CPU time. If this capability is enabled after threads have started, the implementation may choose any time up to and including the time that the capability is enabled as the point where CPU time collection starts. This capability must be potentially available on any platform where can_get_thread_cpu_time is potentially available.

Parameters
Name | Type | Description
nanos_ptr | jlong* | On return, points to the CPU time used by this thread in nanoseconds. This is an unsigned value. If tested or printed as a jlong (signed value) it may appear to be a negative number. Agent passes a pointer to a jlong. On return, the jlong has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_get_current_thread_cpu_time. Use AddCapabilities.
JVMTI_ERROR_NULL_POINTER | nanos_ptr is NULL.

Get Thread CPU Timer Information

jvmtiError
GetThreadCpuTimerInfo(jvmtiEnv* env,
            jvmtiTimerInfo* info_ptr)
Get information about the GetThreadCpuTime timer. The fields of the jvmtiTimerInfo structure are filled in with details about the timer. This information is specific to the platform and the implementation of GetThreadCpuTime and thus does not vary by thread nor does it vary during a particular invocation of the VM.

Note that the implementations of GetCurrentThreadCpuTime and GetThreadCpuTime may differ, and thus the values returned by GetCurrentThreadCpuTimerInfo and GetThreadCpuTimerInfo may differ -- see GetCurrentThreadCpuTime for more information.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 136 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_get_thread_cpu_time | Can get thread CPU time.

Parameters
Name | Type | Description
info_ptr | jvmtiTimerInfo* | On return, filled with information describing the time returned by GetThreadCpuTime. Agent passes a pointer to a jvmtiTimerInfo. On return, the jvmtiTimerInfo has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_get_thread_cpu_time. Use AddCapabilities.
JVMTI_ERROR_NULL_POINTER | info_ptr is NULL.

Get Thread CPU Time

jvmtiError
GetThreadCpuTime(jvmtiEnv* env,
            jthread thread,
            jlong* nanos_ptr)
Return the CPU time utilized by the specified thread.

Get information about this timer with GetThreadCpuTimerInfo.

Phase | Callback Safe | Position | Since
may only be called during the live phase | No | 137 | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this function.
Capability | Effect
can_get_thread_cpu_time | Can get thread CPU time. If this capability is enabled after threads have started, the implementation may choose any time up to and including the time that the capability is enabled as the point where CPU time collection starts.

Parameters
Name | Type | Description
thread | jthread | The thread to query. If thread is NULL, the current thread is used.
nanos_ptr | jlong* | On return, points to the CPU time used by the specified thread in nanoseconds. This is an unsigned value. If tested or printed as a jlong (signed value) it may appear to be a negative number. Agent passes a pointer to a jlong. On return, the jlong has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_MUST_POSSESS_CAPABILITY | The environment does not possess the capability can_get_thread_cpu_time. Use AddCapabilities.
JVMTI_ERROR_INVALID_THREAD | thread is not a thread object.
JVMTI_ERROR_THREAD_NOT_ALIVE | thread is not live (has not been started or is now dead).
JVMTI_ERROR_NULL_POINTER | nanos_ptr is NULL.

Get Timer Information

jvmtiError
GetTimerInfo(jvmtiEnv* env,
            jvmtiTimerInfo* info_ptr)
Get information about the GetTime timer. The fields of the jvmtiTimerInfo structure are filled in with details about the timer. This information will not change during a particular invocation of the VM.

Phase | Callback Safe | Position | Since
may be called during any phase | This function may be called from the callbacks to the Heap iteration functions, or from the event handlers for the GarbageCollectionStart, GarbageCollectionFinish, and ObjectFree events. | 138 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
info_ptr | jvmtiTimerInfo* | On return, filled with information describing the time returned by GetTime. Agent passes a pointer to a jvmtiTimerInfo. On return, the jvmtiTimerInfo has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NULL_POINTER | info_ptr is NULL.

Get Time

jvmtiError
GetTime(jvmtiEnv* env,
            jlong* nanos_ptr)
Return the current value of the system timer, in nanoseconds.

The value returned represents nanoseconds since some fixed but arbitrary time (perhaps in the future, so values may be negative). This function provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change.

Get information about this timer with GetTimerInfo.

Phase | Callback Safe | Position | Since
may be called during any phase | This function may be called from the callbacks to the Heap iteration functions, or from the event handlers for the GarbageCollectionStart, GarbageCollectionFinish, and ObjectFree events. | 139 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
nanos_ptr | jlong* | On return, points to the time in nanoseconds. This is an unsigned value. If tested or printed as a jlong (signed value) it may appear to be a negative number. Agent passes a pointer to a jlong. On return, the jlong has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NULL_POINTER | nanos_ptr is NULL.

Get Available Processors

jvmtiError
GetAvailableProcessors(jvmtiEnv* env,
            jint* processor_count_ptr)
Returns the number of processors available to the Java virtual machine.

This value may change during a particular invocation of the virtual machine. Applications that are sensitive to the number of available processors should therefore occasionally poll this property.

Phase | Callback Safe | Position | Since
may be called during any phase | No | 144 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
processor_count_ptr | jint* | On return, points to the maximum number of processors available to the virtual machine; never smaller than one. Agent passes a pointer to a jint. On return, the jint has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NULL_POINTER | processor_count_ptr is NULL.

Class Loader Search

Class Loader Search functions:
  • Add To Bootstrap Class Loader Search
  • Add To System Class Loader Search
These functions allow the agent to add to the locations that a class loader searches for a class. This is useful for installing instrumentation under the correct class loader.

Add To Bootstrap Class Loader Search

jvmtiError
AddToBootstrapClassLoaderSearch(jvmtiEnv* env,
            const char* segment)
This function can be used to cause instrumentation classes to be defined by the bootstrap class loader. See Loading Using the Bootstrap Class Loader in the Java Virtual Machine Specification. After the bootstrap class loader unsuccessfully searches for a class, the specified platform-dependent search path segment will be searched as well. Only one segment may be specified in the segment. This function may be called multiple times to add multiple segments, the segments will be searched in the order that this function was called.

In the OnLoad phase the function may be used to specify any platform-dependent search path segment to be searched after the bootstrap class loader unsuccessfully searches for a class. The segment is typically a directory or JAR file.

In the live phase the segment may be used to specify any platform-dependent path to a JAR file. The agent should take care that the JAR file does not contain any classes or resources other than those to be defined by the bootstrap class loader for the purposes of instrumentation.

The Java Virtual Machine Specification specifies that a subsequent attempt to resolve a symbolic reference that the Java virtual machine has previously unsuccessfully attempted to resolve always fails with the same error that was thrown as a result of the initial resolution attempt. Consequently, if the JAR file contains an entry that corresponds to a class for which the Java virtual machine has unsuccessfully attempted to resolve a reference, then subsequent attempts to resolve that reference will fail with the same error as the initial attempt.

Phase | Callback Safe | Position | Since
may only be called during the OnLoad or the live phase | No | 149 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
segment | const char* | The platform-dependent search path segment, encoded as a modified UTF-8 string. Agent passes in an array of char.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_ILLEGAL_ARGUMENT | segment is an invalid path. In the live phase, anything other than an existing JAR file is an invalid path.
JVMTI_ERROR_NULL_POINTER | segment is NULL.

Add To System Class Loader Search

jvmtiError
AddToSystemClassLoaderSearch(jvmtiEnv* env,
            const char* segment)
This function can be used to cause instrumentation classes to be defined by the system class loader. See Loading Using a User-defined Class Loader in the Java Virtual Machine Specification. After the class loader unsuccessfully searches for a class, the specified platform-dependent search path segment will be searched as well. Only one segment may be specified in the segment. This function may be called multiple times to add multiple segments, the segments will be searched in the order that this function was called.

In the OnLoad phase the function may be used to specify any platform-dependent search path segment to be searched after the system class loader unsuccessfully searches for a class. The segment is typically a directory or JAR file.

In the live phase the segment is a platform-dependent path to a JAR file to be searched after the system class loader unsuccessfully searches for a class. The agent should take care that the JAR file does not contain any classes or resources other than those to be defined by the system class loader for the purposes of instrumentation.

In the live phase the system class loader supports adding a JAR file to be searched if the system class loader implements a method name appendToClassPathForInstrumentation which takes a single parameter of type java.lang.String. The method is not required to have public access.

The Java Virtual Machine Specification specifies that a subsequent attempt to resolve a symbolic reference that the Java virtual machine has previously unsuccessfully attempted to resolve always fails with the same error that was thrown as a result of the initial resolution attempt. Consequently, if the JAR file contains an entry that corresponds to a class for which the Java virtual machine has unsuccessfully attempted to resolve a reference, then subsequent attempts to resolve that reference will fail with the same error as the initial attempt.

Phase | Callback Safe | Position | Since
may only be called during the OnLoad or the live phase | No | 151 | 1.1

Capabilities
Required Functionality

Parameters
Name | Type | Description
segment | const char* | The platform-dependent search path segment, encoded as a modified UTF-8 string. Agent passes in an array of char.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_ILLEGAL_ARGUMENT | segment is an invalid path. In the live phase, anything other than an existing JAR file is an invalid path.
JVMTI_ERROR_CLASS_LOADER_UNSUPPORTED | Operation not supported by the system class loader.
JVMTI_ERROR_NULL_POINTER | segment is NULL.

System Properties

System Properties functions:
  • Get System Properties
  • Get System Property
  • Set System Property
These functions get and set system properties.

Get System Properties

jvmtiError
GetSystemProperties(jvmtiEnv* env,
            jint* count_ptr,
            char*** property_ptr)
The list of VM system property keys which may be used with GetSystemProperty is returned. It is strongly recommended that virtual machines provide the following property keys:
  • java.vm.vendor
  • java.vm.version
  • java.vm.name
  • java.vm.info
  • java.library.path
  • java.class.path
Provides access to system properties defined by and used by the VM. Properties set on the command-line are included. This allows getting and setting of these properties before the VM even begins executing bytecodes. Since this is a VM view of system properties, the set of available properties will usually be different than that in java.lang.System.getProperties. JNI method invocation may be used to access java.lang.System.getProperties.

The set of properties may grow during execution.

Phase | Callback Safe | Position | Since
may only be called during the OnLoad or the live phase | No | 130 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
count_ptr | jint* | On return, points to the number of property keys returned. Agent passes a pointer to a jint. On return, the jint has been set.
property_ptr | char*** | On return, points to an array of property keys, encoded as modified UTF-8 strings. Agent passes a pointer to a char**. On return, the char** points to a newly allocated array of size *count_ptr, each element of which is also newly allocated. The array should be freed with Deallocate. Each of the elements should be freed with Deallocate.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NULL_POINTER | count_ptr is NULL.
JVMTI_ERROR_NULL_POINTER | property_ptr is NULL.

Get System Property

jvmtiError
GetSystemProperty(jvmtiEnv* env,
            const char* property,
            char** value_ptr)
Return a VM system property value given the property key.

The function GetSystemProperties returns the set of property keys which may be used. The properties which can be retrieved may grow during execution.

Since this is a VM view of system properties, the values of properties may differ from that returned by java.lang.System.getProperty(String). A typical VM might copy the values of the VM system properties into the Properties held by java.lang.System during the initialization of that class. Thereafter any changes to the VM system properties (with SetSystemProperty) or the java.lang.System system properties (with java.lang.System.setProperty(String,String)) would cause the values to diverge. JNI method invocation may be used to access java.lang.System.getProperty(String).

Phase | Callback Safe | Position | Since
may only be called during the OnLoad or the live phase | No | 131 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
property | const char* | The key of the property to retrieve, encoded as a modified UTF-8 string. Agent passes in an array of char.
value_ptr | char** | On return, points to the property value, encoded as a modified UTF-8 string. Agent passes a pointer to a char*. On return, the char* points to a newly allocated array. The array should be freed with Deallocate.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NOT_AVAILABLE | This property is not available. Use GetSystemProperties to find available properties.
JVMTI_ERROR_NULL_POINTER | property is NULL.
JVMTI_ERROR_NULL_POINTER | value_ptr is NULL.

Set System Property

jvmtiError
SetSystemProperty(jvmtiEnv* env,
            const char* property,
            const char* value_ptr)
Set a VM system property value.

The function GetSystemProperties returns the set of property keys, some of these may be settable. See GetSystemProperty.

Phase | Callback Safe | Position | Since
may only be called during the OnLoad phase | No | 132 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
property | const char* | The key of the property, encoded as a modified UTF-8 string. Agent passes in an array of char.
value_ptr | const char * | The property value to set, encoded as a modified UTF-8 string. Agent passes in an array of char. If value_ptr is NULL, do not set the value, but return JVMTI_ERROR_NOT_AVAILABLE if the property is not writeable .

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NOT_AVAILABLE | This property is not available or is not writeable.
JVMTI_ERROR_NULL_POINTER | property is NULL.

General

General functions:
  • Get Phase
  • Dispose Environment
  • Set Environment Local Storage
  • Get Environment Local Storage
  • Get Version Number
  • Get Error Name
  • Set Verbose Flag
  • Get JLocation Format
General types:
  • jvmtiPhase - Phases of execution
  • jvmtiVerboseFlag - Verbose Flag Enumeration
  • jvmtiJlocationFormat - JLocation Format Enumeration
General flags and constants:
  • Version Interface Types
  • Version Masks
  • Version Shifts

Get Phase

typedef enum {
    JVMTI_PHASE_ONLOAD = 1,
    JVMTI_PHASE_PRIMORDIAL = 2,
    JVMTI_PHASE_START = 6,
    JVMTI_PHASE_LIVE = 4,
    JVMTI_PHASE_DEAD = 8
} jvmtiPhase;
jvmtiError
GetPhase(jvmtiEnv* env,
            jvmtiPhase* phase_ptr)
Return the current phase of VM execution. The phases proceed in sequence:
Phases of execution (jvmtiPhase)
Constant | Value | Description
JVMTI_PHASE_ONLOAD | 1 | OnLoad phase: while in the Agent_OnLoad function.
JVMTI_PHASE_PRIMORDIAL | 2 | Primordial phase: between return from Agent_OnLoad and the VMStart event.
JVMTI_PHASE_START | 6 | Start phase: when the VMStart event is sent and until the VMInit event is sent.
JVMTI_PHASE_LIVE | 4 | Live phase: when the VMInit event is sent and until the VMDeath event returns.
JVMTI_PHASE_DEAD | 8 | Dead phase: after the VMDeath event returns or after start-up failure.
In the case of start-up failure the VM will proceed directly to the dead phase skipping intermediate phases and neither a VMInit nor VMDeath event will be sent.

Most JVM TI functions operate only in the live phase. The following functions operate in either the OnLoad or live phases:
  • CreateRawMonitor
  • DestroyRawMonitor
  • SetEventCallbacks
  • SetEventNotificationMode
  • GetExtensionFunctions
  • GetExtensionEvents
  • SetExtensionEventCallback
  • GetPotentialCapabilities
  • AddCapabilities
  • RelinquishCapabilities
  • AddToBootstrapClassLoaderSearch
  • AddToSystemClassLoaderSearch
  • GetSystemProperties
  • GetSystemProperty
The following functions operate in only the OnLoad phase:
  • SetSystemProperty
The following functions operate in the start or live phases:
  • GetCurrentThread
  • SetThreadLocalStorage
  • GetThreadLocalStorage
  • GetTag
  • SetTag
  • GetClassSignature
  • GetClassStatus
  • GetSourceFileName
  • GetClassModifiers
  • GetClassMethods
  • GetClassFields
  • GetImplementedInterfaces
  • GetClassVersionNumbers
  • GetConstantPool
  • IsInterface
  • IsArrayClass
  • IsModifiableClass
  • GetClassLoader
  • GetSourceDebugExtension
  • GetObjectSize
  • GetObjectHashCode
  • GetFieldName
  • GetFieldDeclaringClass
  • GetFieldModifiers
  • IsFieldSynthetic
  • GetMethodName
  • GetMethodDeclaringClass
  • GetMethodModifiers
  • GetMaxLocals
  • GetArgumentsSize
  • GetLineNumberTable
  • GetMethodLocation
  • GetBytecodes
  • IsMethodNative
  • IsMethodSynthetic
  • IsMethodObsolete
  • SetJNIFunctionTable
  • GetJNIFunctionTable
  • GetCurrentThreadCpuTimerInfo
  • GetCurrentThreadCpuTime
The following functions operate in any phase:
  • Allocate
  • Deallocate
  • SetNativeMethodPrefix
  • SetNativeMethodPrefixes
  • RawMonitorEnter
  • RawMonitorExit
  • RawMonitorWait
  • RawMonitorNotify
  • RawMonitorNotifyAll
  • GetCapabilities
  • GetTimerInfo
  • GetTime
  • GetAvailableProcessors
  • GetPhase
  • DisposeEnvironment
  • SetEnvironmentLocalStorage
  • GetEnvironmentLocalStorage
  • GetVersionNumber
  • GetErrorName
  • SetVerboseFlag
  • GetJLocationFormat
JNI functions (except the Invocation API) must only be used in the start or live phases.

Most JVM TI events are sent only in the live phase. The following events operate in others phases:
  • ThreadStart
  • ThreadEnd
  • ClassLoad
  • ClassPrepare
  • VMStart
  • NativeMethodBind
  • ClassFileLoadHook
  • DynamicCodeGenerated

Phase | Callback Safe | Position | Since
may be called during any phase | No | 133 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
phase_ptr | jvmtiPhase* | On return, points to the phase. Agent passes a pointer to a jvmtiPhase. On return, the jvmtiPhase has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NULL_POINTER | phase_ptr is NULL.

Dispose Environment

jvmtiError
DisposeEnvironment(jvmtiEnv* env)
Shutdown a JVM TI connection created with JNI GetEnv (see JVM TI Environments). Dispose of any resources held by the environment. Threads suspended by this environment are not resumed by this call, this must be done explicitly by the agent. Memory allocated by this environment via calls to JVM TI functions is not released, this can be done explicitly by the agent by calling Deallocate. Raw monitors created by this environment are not destroyed, this can be done explicitly by the agent by calling DestroyRawMonitor. The state of threads waiting on raw monitors created by this environment are not affected.

Any native method prefixes for this environment will be unset; the agent must remove any prefixed native methods before dispose is called.

Any capabilities held by this environment are relinquished.

Events enabled by this environment will no longer be sent, however event handlers currently running will continue to run. Caution must be exercised in the design of event handlers whose environment may be disposed and thus become invalid during their execution.

This environment may not be used after this call. This call returns to the caller.

Phase | Callback Safe | Position | Since
may be called during any phase | No | 127 | 1.0

Capabilities
Required Functionality

Parameters
Name Type Description

Errors
This function returns a universal error

Set Environment Local Storage

jvmtiError
SetEnvironmentLocalStorage(jvmtiEnv* env,
            const void* data)
The VM stores a pointer value associated with each environment. This pointer value is called environment-local storage. This value is NULL unless set with this function. Agents can allocate memory in which they store environment specific information. By setting environment-local storage it can then be accessed with GetEnvironmentLocalStorage.

Called by the agent to set the value of the JVM TI environment-local storage. JVM TI supplies to the agent a pointer-size environment-local storage that can be used to record per-environment information.

Phase | Callback Safe | Position | Since
may be called during any phase | This function may be called from the callbacks to the Heap iteration functions, or from the event handlers for the GarbageCollectionStart, GarbageCollectionFinish, and ObjectFree events. | 148 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
data | const void * | The value to be entered into the environment-local storage. Agent passes in a pointer. If data is NULL, value is set to NULL.

Errors
This function returns a universal error

Get Environment Local Storage

jvmtiError
GetEnvironmentLocalStorage(jvmtiEnv* env,
            void** data_ptr)
Called by the agent to get the value of the JVM TI environment-local storage.

Phase | Callback Safe | Position | Since
may be called during any phase | This function may be called from the callbacks to the Heap iteration functions, or from the event handlers for the GarbageCollectionStart, GarbageCollectionFinish, and ObjectFree events. | 147 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
data_ptr | void** | Pointer through which the value of the environment local storage is returned. If environment-local storage has not been set with SetEnvironmentLocalStorage returned pointer is NULL.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NULL_POINTER | data_ptr is NULL.

Get Version Number

jvmtiError
GetVersionNumber(jvmtiEnv* env,
            jint* version_ptr)
Return the JVM TI version via version_ptr. The return value is the version identifier. The version identifier includes major, minor and micro version as well as the interface type.
Version Interface Types
Constant | Value | Description
JVMTI_VERSION_INTERFACE_JNI | 0x00000000 | Value of JVMTI_VERSION_MASK_INTERFACE_TYPE for JNI.
JVMTI_VERSION_INTERFACE_JVMTI | 0x30000000 | Value of JVMTI_VERSION_MASK_INTERFACE_TYPE for JVM TI.
Version Masks
Constant | Value | Description
JVMTI_VERSION_MASK_INTERFACE_TYPE | 0x70000000 | Mask to extract interface type. The value of the version returned by this function masked with JVMTI_VERSION_MASK_INTERFACE_TYPE is always JVMTI_VERSION_INTERFACE_JVMTI since this is a JVM TI function.
JVMTI_VERSION_MASK_MAJOR | 0x0FFF0000 | Mask to extract major version number.
JVMTI_VERSION_MASK_MINOR | 0x0000FF00 | Mask to extract minor version number.
JVMTI_VERSION_MASK_MICRO | 0x000000FF | Mask to extract micro version number.
Version Shifts
Constant | Value | Description
JVMTI_VERSION_SHIFT_MAJOR | 16 | Shift to extract major version number.
JVMTI_VERSION_SHIFT_MINOR | 8 | Shift to extract minor version number.
JVMTI_VERSION_SHIFT_MICRO | 0 | Shift to extract micro version number.

Phase | Callback Safe | Position | Since
may be called during any phase | No | 88 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
version_ptr | jint* | On return, points to the JVM TI version. Agent passes a pointer to a jint. On return, the jint has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NULL_POINTER | version_ptr is NULL.

Get Error Name

jvmtiError
GetErrorName(jvmtiEnv* env,
            jvmtiError error,
            char** name_ptr)
Return the symbolic name for an error code.

For example GetErrorName(env, JVMTI_ERROR_NONE, &err_name) would return in err_name the string "JVMTI_ERROR_NONE".

Phase | Callback Safe | Position | Since
may be called during any phase | No | 128 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
error | jvmtiError | The error code.
name_ptr | char** | On return, points to the error name. The name is encoded as a modified UTF-8 string, but is restricted to the ASCII subset. Agent passes a pointer to a char*. On return, the char* points to a newly allocated array. The array should be freed with Deallocate.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_ILLEGAL_ARGUMENT | error is not a jvmtiError.
JVMTI_ERROR_NULL_POINTER | name_ptr is NULL.

Set Verbose Flag

typedef enum {
    JVMTI_VERBOSE_OTHER = 0,
    JVMTI_VERBOSE_GC = 1,
    JVMTI_VERBOSE_CLASS = 2,
    JVMTI_VERBOSE_JNI = 4
} jvmtiVerboseFlag;
jvmtiError
SetVerboseFlag(jvmtiEnv* env,
            jvmtiVerboseFlag flag,
            jboolean value)
Verbose Flag Enumeration (jvmtiVerboseFlag)
Constant | Value | Description
JVMTI_VERBOSE_OTHER | 0 | Verbose output other than the below.
JVMTI_VERBOSE_GC | 1 | Verbose garbage collector output, like that specified with -verbose:gc.
JVMTI_VERBOSE_CLASS | 2 | Verbose class loading output, like that specified with -verbose:class.
JVMTI_VERBOSE_JNI | 4 | Verbose JNI output, like that specified with -verbose:jni.
Control verbose output. This is the output which typically is sent to stderr.

Phase | Callback Safe | Position | Since
may be called during any phase | No | 150 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
flag | jvmtiVerboseFlag | Which verbose flag to set.
value | jboolean | New value of the flag.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_ILLEGAL_ARGUMENT | flag is not a jvmtiVerboseFlag.

Get JLocation Format

typedef enum {
    JVMTI_JLOCATION_JVMBCI = 1,
    JVMTI_JLOCATION_MACHINEPC = 2,
    JVMTI_JLOCATION_OTHER = 0
} jvmtiJlocationFormat;
jvmtiError
GetJLocationFormat(jvmtiEnv* env,
            jvmtiJlocationFormat* format_ptr)
Although the greatest functionality is achieved with location information referencing the virtual machine bytecode index, the definition of jlocation has intentionally been left unconstrained to allow VM implementations that do not have this information.

This function describes the representation of jlocation used in this VM. If the returned format is JVMTI_JLOCATION_JVMBCI, jlocations can be used as in indices into the array returned by GetBytecodes.
JLocation Format Enumeration (jvmtiJlocationFormat)
Constant | Value | Description
JVMTI_JLOCATION_JVMBCI | 1 | jlocation values represent virtual machine bytecode indices--that is, offsets into the virtual machine code for a method.
JVMTI_JLOCATION_MACHINEPC | 2 | jlocation values represent native machine program counter values.
JVMTI_JLOCATION_OTHER | 0 | jlocation values have some other representation.

Phase | Callback Safe | Position | Since
may be called during any phase | No | 129 | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
format_ptr | jvmtiJlocationFormat* | On return, points to the format identifier for jlocation values. Agent passes a pointer to a jvmtiJlocationFormat. On return, the jvmtiJlocationFormat has been set.

Errors
This function returns either a universal error or one of the following errors
Error | Description
JVMTI_ERROR_NULL_POINTER | format_ptr is NULL.

Errors

Every JVM TI function returns a jvmtiError error code.

It is the responsibility of the agent to call JVM TI functions with valid parameters and in the proper context (calling thread is attached, phase is correct, etc.). Detecting some error conditions may be difficult, inefficient, or impossible for an implementation. The errors listed in Function Specific Required Errors must be detected by the implementation. All other errors represent the recommended response to the error condition.

Universal Errors

The following errors may be returned by any function

JVMTI_ERROR_NONE (0)
No error has occurred. This is the error code that is returned on successful completion of the function.

JVMTI_ERROR_NULL_POINTER (100)
Pointer is unexpectedly NULL.

JVMTI_ERROR_OUT_OF_MEMORY (110)
The function attempted to allocate memory and no more memory was available for allocation.

JVMTI_ERROR_ACCESS_DENIED (111)
The desired functionality has not been enabled in this virtual machine.

JVMTI_ERROR_UNATTACHED_THREAD (115)
The thread being used to call this function is not attached to the virtual machine. Calls must be made from attached threads. See AttachCurrentThread in the JNI invocation API.

JVMTI_ERROR_INVALID_ENVIRONMENT (116)
The JVM TI environment provided is no longer connected or is not an environment.

JVMTI_ERROR_WRONG_PHASE (112)
The desired functionality is not available in the current phase. Always returned if the virtual machine has completed running.

JVMTI_ERROR_INTERNAL (113)
An unexpected internal error has occurred.

Function Specific Required Errors

The following errors are returned by some JVM TI functions and must be returned by the implementation when the condition occurs.

JVMTI_ERROR_INVALID_PRIORITY (12)
Invalid priority.

JVMTI_ERROR_THREAD_NOT_SUSPENDED (13)
Thread was not suspended.

JVMTI_ERROR_THREAD_SUSPENDED (14)
Thread already suspended.

JVMTI_ERROR_THREAD_NOT_ALIVE (15)
This operation requires the thread to be alive--that is, it must be started and not yet have died.

JVMTI_ERROR_CLASS_NOT_PREPARED (22)
The class has been loaded but not yet prepared.

JVMTI_ERROR_NO_MORE_FRAMES (31)
There are no Java programming language or JNI stack frames at the specified depth.

JVMTI_ERROR_OPAQUE_FRAME (32)
Information about the frame is not available (e.g. for native frames).

JVMTI_ERROR_DUPLICATE (40)
Item already set.

JVMTI_ERROR_NOT_FOUND (41)
Desired element (e.g. field or breakpoint) not found

JVMTI_ERROR_NOT_MONITOR_OWNER (51)
This thread doesn't own the raw monitor.

JVMTI_ERROR_INTERRUPT (52)
The call has been interrupted before completion.

JVMTI_ERROR_UNMODIFIABLE_CLASS (79)
The class cannot be modified.

JVMTI_ERROR_NOT_AVAILABLE (98)
The functionality is not available in this virtual machine.

JVMTI_ERROR_ABSENT_INFORMATION (101)
The requested information is not available.

JVMTI_ERROR_INVALID_EVENT_TYPE (102)
The specified event type ID is not recognized.

JVMTI_ERROR_NATIVE_METHOD (104)
The requested information is not available for native method.

JVMTI_ERROR_CLASS_LOADER_UNSUPPORTED (106)
The class loader does not support this operation.

Function Specific Agent Errors

The following errors are returned by some JVM TI functions. They are returned in the event of invalid parameters passed by the agent or usage in an invalid context. An implementation is not required to detect these errors.

JVMTI_ERROR_INVALID_THREAD (10)
The passed thread is not a valid thread.

JVMTI_ERROR_INVALID_FIELDID (25)
Invalid field.

JVMTI_ERROR_INVALID_METHODID (23)
Invalid method.

JVMTI_ERROR_INVALID_LOCATION (24)
Invalid location.

JVMTI_ERROR_INVALID_OBJECT (20)
Invalid object.

JVMTI_ERROR_INVALID_CLASS (21)
Invalid class.

JVMTI_ERROR_TYPE_MISMATCH (34)
The variable is not an appropriate type for the function used.

JVMTI_ERROR_INVALID_SLOT (35)
Invalid slot.

JVMTI_ERROR_MUST_POSSESS_CAPABILITY (99)
The capability being used is false in this environment.

JVMTI_ERROR_INVALID_THREAD_GROUP (11)
Thread group invalid.

JVMTI_ERROR_INVALID_MONITOR (50)
Invalid raw monitor.

JVMTI_ERROR_ILLEGAL_ARGUMENT (103)
Illegal argument.

JVMTI_ERROR_INVALID_TYPESTATE (65)
The state of the thread has been modified, and is now inconsistent.

JVMTI_ERROR_UNSUPPORTED_VERSION (68)
A new class file has a version number not supported by this VM.

JVMTI_ERROR_INVALID_CLASS_FORMAT (60)
A new class file is malformed (the VM would return a ClassFormatError).

JVMTI_ERROR_CIRCULAR_CLASS_DEFINITION (61)
The new class file definitions would lead to a circular definition (the VM would return a ClassCircularityError).

JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_ADDED (63)
A new class file would require adding a method.

JVMTI_ERROR_UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED (64)
A new class version changes a field.

JVMTI_ERROR_FAILS_VERIFICATION (62)
The class bytes fail verification.

JVMTI_ERROR_UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED (66)
A direct superclass is different for the new class version, or the set of directly implemented interfaces is different.

JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_DELETED (67)
A new class version does not declare a method declared in the old class version.

JVMTI_ERROR_NAMES_DONT_MATCH (69)
The class name defined in the new class file is different from the name in the old class object.

JVMTI_ERROR_UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED (70)
A new class version has different modifiers.

JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED (71)
A method in the new class version has different modifiers than its counterpart in the old class version.

Data Types

JVM TI extends the data types defined by JNI.

JNI Types Used in the JVM Tool Interface
Type | Description
jboolean | Holds a Java programming language boolean. Unsigned 8 bits.
jint | Holds a Java programming language int. Signed 32 bits.
jlong | Holds a Java programming language long. Signed 64 bits.
jfloat | Holds a Java programming language float. 32 bits.
jdouble | Holds a Java programming language double. 64 bits.
jobject | Holds a Java programming language object.
jclass | Holds a Java programming language class.
jvalue | Is a union of all primitive types and jobject. Thus, holds any Java programming language value.
jfieldID | Identifies a Java programming language field. jfieldIDs returned by JVM TI functions and events may be safely stored.
jmethodID | Identifies a Java programming language method, initializer, or constructor. jmethodIDs returned by JVM TI functions and events may be safely stored. However, if the class is unloaded, they become invalid and must not be used.
JNIEnv | Pointer to the JNI function table. Pointer to this (JNIEnv *) is a JNI environment.

JVM Tool Interface Base Types
Type | Description
jvmtiEnv | The JVM TI environment pointer. See the Function Section. jvmtiEnv points to the function table pointer.
jthread | Subtype of jobject that holds a thread.
typedef jobject jthread;
jthreadGroup | Subtype of jobject that holds a thread group.
typedef jobject jthreadGroup;
jlocation | A 64 bit value, representing a monotonically increasing executable position within a method. -1 indicates a native method. See GetJLocationFormat for the format on a given VM.
typedef jlong jlocation;
jrawMonitorID | A raw monitor.
struct _jrawMonitorID;
typedef struct _jrawMonitorID *jrawMonitorID;
jvmtiError Holds an error return code. See the Error section for possible values.
typedef enum {
    JVMTI_ERROR_NONE = 0,
    JVMTI_ERROR_INVALID_THREAD = 10,
      ...
} jvmtiError;
jvmtiEvent An identifier for an event type. See the Event section for possible values. It is guaranteed that future versions of this specification will never assign zero as an event type identifier.
typedef enum {
    JVMTI_EVENT_SINGLE_STEP = 1,
    JVMTI_EVENT_BREAKPOINT = 2,
      ...
} jvmtiEvent;
jvmtiEventCallbacks The callbacks used for events.
typedef struct {
    jvmtiEventVMInit VMInit;
    jvmtiEventVMDeath VMDeath;
      ...
} jvmtiEventCallbacks;
See event callbacks for the complete structure.

Where, for example, the VM initialization callback is defined:
typedef void (JNICALL *jvmtiEventVMInit)
    (jvmtiEnv *jvmti_env,
     JNIEnv* jni_env,
     jthread thread);
See the individual events for the callback function definition.
jniNativeInterface | Typedef for the JNI function table JNINativeInterface defined in the JNI Specification. The JNI reference implementation defines this with an underscore.
typedef struct JNINativeInterface_ jniNativeInterface;

Structure Type Definitions
Type | Description
jvmtiAddrLocationMap | Native address to location entry
jvmtiCapabilities | The Capabilities Structure
jvmtiClassDefinition | Class redefinition description
jvmtiExtensionEventInfo | Extension Event Info
jvmtiExtensionFunctionInfo | Extension Function Info
jvmtiFrameInfo | Stack frame information structure
jvmtiHeapCallbacks | Heap callback function structure
jvmtiHeapReferenceInfo | Reference information structure
jvmtiHeapReferenceInfoArray | Reference information structure for Array references
jvmtiHeapReferenceInfoConstantPool | Reference information structure for Constant Pool references
jvmtiHeapReferenceInfoField | Reference information structure for Field references
jvmtiHeapReferenceInfoJniLocal | Reference information structure for JNI local references
jvmtiHeapReferenceInfoReserved | Reference information structure for Other references
jvmtiHeapReferenceInfoStackLocal | Reference information structure for Local Variable references
jvmtiLineNumberEntry | Line number table entry
jvmtiLocalVariableEntry | Local variable table entry
jvmtiMonitorStackDepthInfo | Monitor stack depth information structure
jvmtiMonitorUsage | Object monitor usage information
jvmtiParamInfo | Extension Function/Event Parameter Info
jvmtiStackInfo | Stack information structure
jvmtiThreadGroupInfo | Thread group information structure
jvmtiThreadInfo | Thread information structure
jvmtiTimerInfo | Timer Info

Function Type Definitions
Type | Description
jvmtiArrayPrimitiveValueCallback | Array Primitive Value Callback
jvmtiExtensionEvent | Extension Event
jvmtiExtensionFunction | Extension Function
jvmtiHeapIterationCallback | Heap Iteration Callback
jvmtiHeapObjectCallback | Heap Object Callback
jvmtiHeapReferenceCallback | Heap Reference Callback
jvmtiHeapRootCallback | Heap Root Object Callback
jvmtiObjectReferenceCallback | Object Reference Callback
jvmtiPrimitiveFieldCallback | Primitive Field Callback
jvmtiReservedCallback | reserved for future use Callback
jvmtiStackReferenceCallback | Stack Reference Object Callback
jvmtiStartFunction | Agent Start Function
jvmtiStringPrimitiveValueCallback | String Primitive Value Callback

Enumeration Definitions
Type | Description
jvmtiEventMode | Event Enable/Disable
jvmtiHeapObjectFilter | Heap Object Filter Enumeration
jvmtiHeapReferenceKind | Heap Reference Enumeration
jvmtiHeapRootKind | Heap Root Kind Enumeration
jvmtiIterationControl | Iteration Control Enumeration
jvmtiJlocationFormat | JLocation Format Enumeration
jvmtiObjectReferenceKind | Object Reference Enumeration
jvmtiParamKind | Extension Function/Event Parameter Kinds
jvmtiParamTypes | Extension Function/Event Parameter Types
jvmtiPhase | Phases of execution
jvmtiPrimitiveType | Primitive Type Enumeration
jvmtiTimerKind | Timer Kinds
jvmtiVerboseFlag | Verbose Flag Enumeration

Function Table Layout
Position Function Declaration
1 reserved
void *reserved1;
2 Set Event Notification Mode
jvmtiError (JNICALL *SetEventNotificationMode) (jvmtiEnv* env,
                       jvmtiEventMode mode,
                       jvmtiEvent event_type,
                       jthread event_thread,
                        ...);
3 reserved
void *reserved3;
4 Get All Threads
jvmtiError (JNICALL *GetAllThreads) (jvmtiEnv* env,
                       jint* threads_count_ptr,
                       jthread** threads_ptr);
5 Suspend Thread
jvmtiError (JNICALL *SuspendThread) (jvmtiEnv* env,
                       jthread thread);
6 Resume Thread
jvmtiError (JNICALL *ResumeThread) (jvmtiEnv* env,
                       jthread thread);
7 Stop Thread
jvmtiError (JNICALL *StopThread) (jvmtiEnv* env,
                       jthread thread,
                       jobject exception);
8 Interrupt Thread
jvmtiError (JNICALL *InterruptThread) (jvmtiEnv* env,
                       jthread thread);
9 Get Thread Info
jvmtiError (JNICALL *GetThreadInfo) (jvmtiEnv* env,
                       jthread thread,
                       jvmtiThreadInfo* info_ptr);
10 Get Owned Monitor Info
jvmtiError (JNICALL *GetOwnedMonitorInfo) (jvmtiEnv* env,
                       jthread thread,
                       jint* owned_monitor_count_ptr,
                       jobject** owned_monitors_ptr);
11 Get Current Contended Monitor
jvmtiError (JNICALL *GetCurrentContendedMonitor) (jvmtiEnv* env,
                       jthread thread,
                       jobject* monitor_ptr);
12 Run Agent Thread
jvmtiError (JNICALL *RunAgentThread) (jvmtiEnv* env,
                       jthread thread,
                       jvmtiStartFunction proc,
                       const void* arg,
                       jint priority);
13 Get Top Thread Groups
jvmtiError (JNICALL *GetTopThreadGroups) (jvmtiEnv* env,
                       jint* group_count_ptr,
                       jthreadGroup** groups_ptr);
14 Get Thread Group Info
jvmtiError (JNICALL *GetThreadGroupInfo) (jvmtiEnv* env,
                       jthreadGroup group,
                       jvmtiThreadGroupInfo* info_ptr);
15 Get Thread Group Children
jvmtiError (JNICALL *GetThreadGroupChildren) (jvmtiEnv* env,
                       jthreadGroup group,
                       jint* thread_count_ptr,
                       jthread** threads_ptr,
                       jint* group_count_ptr,
                       jthreadGroup** groups_ptr);
16 Get Frame Count
jvmtiError (JNICALL *GetFrameCount) (jvmtiEnv* env,
                       jthread thread,
                       jint* count_ptr);
17 Get Thread State
jvmtiError (JNICALL *GetThreadState) (jvmtiEnv* env,
                       jthread thread,
                       jint* thread_state_ptr);
18 Get Current Thread
jvmtiError (JNICALL *GetCurrentThread) (jvmtiEnv* env,
                       jthread* thread_ptr);
19 Get Frame Location
jvmtiError (JNICALL *GetFrameLocation) (jvmtiEnv* env,
                       jthread thread,
                       jint depth,
                       jmethodID* method_ptr,
                       jlocation* location_ptr);
20 Notify Frame Pop
jvmtiError (JNICALL *NotifyFramePop) (jvmtiEnv* env,
                       jthread thread,
                       jint depth);
21 Get Local Variable - Object
jvmtiError (JNICALL *GetLocalObject) (jvmtiEnv* env,
                       jthread thread,
                       jint depth,
                       jint slot,
                       jobject* value_ptr);
22 Get Local Variable - Int
jvmtiError (JNICALL *GetLocalInt) (jvmtiEnv* env,
                       jthread thread,
                       jint depth,
                       jint slot,
                       jint* value_ptr);
23 Get Local Variable - Long
jvmtiError (JNICALL *GetLocalLong) (jvmtiEnv* env,
                       jthread thread,
                       jint depth,
                       jint slot,
                       jlong* value_ptr);
24 Get Local Variable - Float
jvmtiError (JNICALL *GetLocalFloat) (jvmtiEnv* env,
                       jthread thread,
                       jint depth,
                       jint slot,
                       jfloat* value_ptr);
25 Get Local Variable - Double
jvmtiError (JNICALL *GetLocalDouble) (jvmtiEnv* env,
                       jthread thread,
                       jint depth,
                       jint slot,
                       jdouble* value_ptr);
26 Set Local Variable - Object
jvmtiError (JNICALL *SetLocalObject) (jvmtiEnv* env,
                       jthread thread,
                       jint depth,
                       jint slot,
                       jobject value);
27 Set Local Variable - Int
jvmtiError (JNICALL *SetLocalInt) (jvmtiEnv* env,
                       jthread thread,
                       jint depth,
                       jint slot,
                       jint value);
28 Set Local Variable - Long
jvmtiError (JNICALL *SetLocalLong) (jvmtiEnv* env,
                       jthread thread,
                       jint depth,
                       jint slot,
                       jlong value);
29 Set Local Variable - Float
jvmtiError (JNICALL *SetLocalFloat) (jvmtiEnv* env,
                       jthread thread,
                       jint depth,
                       jint slot,
                       jfloat value);
30 Set Local Variable - Double
jvmtiError (JNICALL *SetLocalDouble) (jvmtiEnv* env,
                       jthread thread,
                       jint depth,
                       jint slot,
                       jdouble value);
31 Create Raw Monitor
jvmtiError (JNICALL *CreateRawMonitor) (jvmtiEnv* env,
                       const char* name,
                       jrawMonitorID* monitor_ptr);
32 Destroy Raw Monitor
jvmtiError (JNICALL *DestroyRawMonitor) (jvmtiEnv* env,
                       jrawMonitorID monitor);
33 Raw Monitor Enter
jvmtiError (JNICALL *RawMonitorEnter) (jvmtiEnv* env,
                       jrawMonitorID monitor);
34 Raw Monitor Exit
jvmtiError (JNICALL *RawMonitorExit) (jvmtiEnv* env,
                       jrawMonitorID monitor);
35 Raw Monitor Wait
jvmtiError (JNICALL *RawMonitorWait) (jvmtiEnv* env,
                       jrawMonitorID monitor,
                       jlong millis);
36 Raw Monitor Notify
jvmtiError (JNICALL *RawMonitorNotify) (jvmtiEnv* env,
                       jrawMonitorID monitor);
37 Raw Monitor Notify All
jvmtiError (JNICALL *RawMonitorNotifyAll) (jvmtiEnv* env,
                       jrawMonitorID monitor);
38 Set Breakpoint
jvmtiError (JNICALL *SetBreakpoint) (jvmtiEnv* env,
                       jmethodID method,
                       jlocation location);
39 Clear Breakpoint
jvmtiError (JNICALL *ClearBreakpoint) (jvmtiEnv* env,
                       jmethodID method,
                       jlocation location);
40 reserved
void *reserved40;
41 Set Field Access Watch
jvmtiError (JNICALL *SetFieldAccessWatch) (jvmtiEnv* env,
                       jclass klass,
                       jfieldID field);
42 Clear Field Access Watch
jvmtiError (JNICALL *ClearFieldAccessWatch) (jvmtiEnv* env,
                       jclass klass,
                       jfieldID field);
43 Set Field Modification Watch
jvmtiError (JNICALL *SetFieldModificationWatch) (jvmtiEnv* env,
                       jclass klass,
                       jfieldID field);
44 Clear Field Modification Watch
jvmtiError (JNICALL *ClearFieldModificationWatch) (jvmtiEnv* env,
                       jclass klass,
                       jfieldID field);
45 Is Modifiable Class
jvmtiError (JNICALL *IsModifiableClass) (jvmtiEnv* env,
                       jclass klass,
                       jboolean* is_modifiable_class_ptr);
46 Allocate
jvmtiError (JNICALL *Allocate) (jvmtiEnv* env,
                       jlong size,
                       unsigned char** mem_ptr);
47 Deallocate
jvmtiError (JNICALL *Deallocate) (jvmtiEnv* env,
                       unsigned char* mem);
48 Get Class Signature
jvmtiError (JNICALL *GetClassSignature) (jvmtiEnv* env,
                       jclass klass,
                       char** signature_ptr,
                       char** generic_ptr);
49 Get Class Status
jvmtiError (JNICALL *GetClassStatus) (jvmtiEnv* env,
                       jclass klass,
                       jint* status_ptr);
50 Get Source File Name
jvmtiError (JNICALL *GetSourceFileName) (jvmtiEnv* env,
                       jclass klass,
                       char** source_name_ptr);
51 Get Class Modifiers
jvmtiError (JNICALL *GetClassModifiers) (jvmtiEnv* env,
                       jclass klass,
                       jint* modifiers_ptr);
52 Get Class Methods
jvmtiError (JNICALL *GetClassMethods) (jvmtiEnv* env,
                       jclass klass,
                       jint* method_count_ptr,
                       jmethodID** methods_ptr);
53 Get Class Fields
jvmtiError (JNICALL *GetClassFields) (jvmtiEnv* env,
                       jclass klass,
                       jint* field_count_ptr,
                       jfieldID** fields_ptr);
54 Get Implemented Interfaces
jvmtiError (JNICALL *GetImplementedInterfaces) (jvmtiEnv* env,
                       jclass klass,
                       jint* interface_count_ptr,
                       jclass** interfaces_ptr);
55 Is Interface
jvmtiError (JNICALL *IsInterface) (jvmtiEnv* env,
                       jclass klass,
                       jboolean* is_interface_ptr);
56 Is Array Class
jvmtiError (JNICALL *IsArrayClass) (jvmtiEnv* env,
                       jclass klass,
                       jboolean* is_array_class_ptr);
57 Get Class Loader
jvmtiError (JNICALL *GetClassLoader) (jvmtiEnv* env,
                       jclass klass,
                       jobject* classloader_ptr);
58 Get Object Hash Code
jvmtiError (JNICALL *GetObjectHashCode) (jvmtiEnv* env,
                       jobject object,
                       jint* hash_code_ptr);
59 Get Object Monitor Usage
jvmtiError (JNICALL *GetObjectMonitorUsage) (jvmtiEnv* env,
                       jobject object,
                       jvmtiMonitorUsage* info_ptr);
60 Get Field Name (and Signature)
jvmtiError (JNICALL *GetFieldName) (jvmtiEnv* env,
                       jclass klass,
                       jfieldID field,
                       char** name_ptr,
                       char** signature_ptr,
                       char** generic_ptr);
61 Get Field Declaring Class
jvmtiError (JNICALL *GetFieldDeclaringClass) (jvmtiEnv* env,
                       jclass klass,
                       jfieldID field,
                       jclass* declaring_class_ptr);
62 Get Field Modifiers
jvmtiError (JNICALL *GetFieldModifiers) (jvmtiEnv* env,
                       jclass klass,
                       jfieldID field,
                       jint* modifiers_ptr);
63 Is Field Synthetic
jvmtiError (JNICALL *IsFieldSynthetic) (jvmtiEnv* env,
                       jclass klass,
                       jfieldID field,
                       jboolean* is_synthetic_ptr);
64 Get Method Name (and Signature)
jvmtiError (JNICALL *GetMethodName) (jvmtiEnv* env,
                       jmethodID method,
                       char** name_ptr,
                       char** signature_ptr,
                       char** generic_ptr);
65 Get Method Declaring Class
jvmtiError (JNICALL *GetMethodDeclaringClass) (jvmtiEnv* env,
                       jmethodID method,
                       jclass* declaring_class_ptr);
66 Get Method Modifiers
jvmtiError (JNICALL *GetMethodModifiers) (jvmtiEnv* env,
                       jmethodID method,
                       jint* modifiers_ptr);
67 reserved
void *reserved67;
68 Get Max Locals
jvmtiError (JNICALL *GetMaxLocals) (jvmtiEnv* env,
                       jmethodID method,
                       jint* max_ptr);
69 Get Arguments Size
jvmtiError (JNICALL *GetArgumentsSize) (jvmtiEnv* env,
                       jmethodID method,
                       jint* size_ptr);
70 Get Line Number Table
jvmtiError (JNICALL *GetLineNumberTable) (jvmtiEnv* env,
                       jmethodID method,
                       jint* entry_count_ptr,
                       jvmtiLineNumberEntry** table_ptr);
71 Get Method Location
jvmtiError (JNICALL *GetMethodLocation) (jvmtiEnv* env,
                       jmethodID method,
                       jlocation* start_location_ptr,
                       jlocation* end_location_ptr);
72 Get Local Variable Table
jvmtiError (JNICALL *GetLocalVariableTable) (jvmtiEnv* env,
                       jmethodID method,
                       jint* entry_count_ptr,
                       jvmtiLocalVariableEntry** table_ptr);
73 Set Native Method Prefix
jvmtiError (JNICALL *SetNativeMethodPrefix) (jvmtiEnv* env,
                       const char* prefix);
74 Set Native Method Prefixes
jvmtiError (JNICALL *SetNativeMethodPrefixes) (jvmtiEnv* env,
                       jint prefix_count,
                       char** prefixes);
75 Get Bytecodes
jvmtiError (JNICALL *GetBytecodes) (jvmtiEnv* env,
                       jmethodID method,
                       jint* bytecode_count_ptr,
                       unsigned char** bytecodes_ptr);
76 Is Method Native
jvmtiError (JNICALL *IsMethodNative) (jvmtiEnv* env,
                       jmethodID method,
                       jboolean* is_native_ptr);
77 Is Method Synthetic
jvmtiError (JNICALL *IsMethodSynthetic) (jvmtiEnv* env,
                       jmethodID method,
                       jboolean* is_synthetic_ptr);
78 Get Loaded Classes
jvmtiError (JNICALL *GetLoadedClasses) (jvmtiEnv* env,
                       jint* class_count_ptr,
                       jclass** classes_ptr);
79 Get Classloader Classes
jvmtiError (JNICALL *GetClassLoaderClasses) (jvmtiEnv* env,
                       jobject initiating_loader,
                       jint* class_count_ptr,
                       jclass** classes_ptr);
80 Pop Frame
jvmtiError (JNICALL *PopFrame) (jvmtiEnv* env,
                       jthread thread);
81 Force Early Return - Object
jvmtiError (JNICALL *ForceEarlyReturnObject) (jvmtiEnv* env,
                       jthread thread,
                       jobject value);
82 Force Early Return - Int
jvmtiError (JNICALL *ForceEarlyReturnInt) (jvmtiEnv* env,
                       jthread thread,
                       jint value);
83 Force Early Return - Long
jvmtiError (JNICALL *ForceEarlyReturnLong) (jvmtiEnv* env,
                       jthread thread,
                       jlong value);
84 Force Early Return - Float
jvmtiError (JNICALL *ForceEarlyReturnFloat) (jvmtiEnv* env,
                       jthread thread,
                       jfloat value);
85 Force Early Return - Double
jvmtiError (JNICALL *ForceEarlyReturnDouble) (jvmtiEnv* env,
                       jthread thread,
                       jdouble value);
86 Force Early Return - Void
jvmtiError (JNICALL *ForceEarlyReturnVoid) (jvmtiEnv* env,
                       jthread thread);
87 Redefine Classes
jvmtiError (JNICALL *RedefineClasses) (jvmtiEnv* env,
                       jint class_count,
                       const jvmtiClassDefinition* class_definitions);
88 Get Version Number
jvmtiError (JNICALL *GetVersionNumber) (jvmtiEnv* env,
                       jint* version_ptr);
89 Get Capabilities
jvmtiError (JNICALL *GetCapabilities) (jvmtiEnv* env,
                       jvmtiCapabilities* capabilities_ptr);
90 Get Source Debug Extension
jvmtiError (JNICALL *GetSourceDebugExtension) (jvmtiEnv* env,
                       jclass klass,
                       char** source_debug_extension_ptr);
91 Is Method Obsolete
jvmtiError (JNICALL *IsMethodObsolete) (jvmtiEnv* env,
                       jmethodID method,
                       jboolean* is_obsolete_ptr);
92 Suspend Thread List
jvmtiError (JNICALL *SuspendThreadList) (jvmtiEnv* env,
                       jint request_count,
                       const jthread* request_list,
                       jvmtiError* results);
93 Resume Thread List
jvmtiError (JNICALL *ResumeThreadList) (jvmtiEnv* env,
                       jint request_count,
                       const jthread* request_list,
                       jvmtiError* results);
94 reserved
void *reserved94;
95 reserved
void *reserved95;
96 reserved
void *reserved96;
97 reserved
void *reserved97;
98 reserved
void *reserved98;
99 reserved
void *reserved99;
100 Get All Stack Traces
jvmtiError (JNICALL *GetAllStackTraces) (jvmtiEnv* env,
                       jint max_frame_count,
                       jvmtiStackInfo** stack_info_ptr,
                       jint* thread_count_ptr);
101 Get Thread List Stack Traces
jvmtiError (JNICALL *GetThreadListStackTraces) (jvmtiEnv* env,
                       jint thread_count,
                       const jthread* thread_list,
                       jint max_frame_count,
                       jvmtiStackInfo** stack_info_ptr);
102 Get Thread Local Storage
jvmtiError (JNICALL *GetThreadLocalStorage) (jvmtiEnv* env,
                       jthread thread,
                       void** data_ptr);
103 Set Thread Local Storage
jvmtiError (JNICALL *SetThreadLocalStorage) (jvmtiEnv* env,
                       jthread thread,
                       const void* data);
104 Get Stack Trace
jvmtiError (JNICALL *GetStackTrace) (jvmtiEnv* env,
                       jthread thread,
                       jint start_depth,
                       jint max_frame_count,
                       jvmtiFrameInfo* frame_buffer,
                       jint* count_ptr);
105 reserved
void *reserved105;
106 Get Tag
jvmtiError (JNICALL *GetTag) (jvmtiEnv* env,
                       jobject object,
                       jlong* tag_ptr);
107 Set Tag
jvmtiError (JNICALL *SetTag) (jvmtiEnv* env,
                       jobject object,
                       jlong tag);
108 Force Garbage Collection
jvmtiError (JNICALL *ForceGarbageCollection) (jvmtiEnv* env);
109 Iterate Over Objects Reachable From Object
jvmtiError (JNICALL *IterateOverObjectsReachableFromObject) (jvmtiEnv* env,
                       jobject object,
                       jvmtiObjectReferenceCallback object_reference_callback,
                       const void* user_data);
110 Iterate Over Reachable Objects
jvmtiError (JNICALL *IterateOverReachableObjects) (jvmtiEnv* env,
                       jvmtiHeapRootCallback heap_root_callback,
                       jvmtiStackReferenceCallback stack_ref_callback,
                       jvmtiObjectReferenceCallback object_ref_callback,
                       const void* user_data);
111 Iterate Over Heap
jvmtiError (JNICALL *IterateOverHeap) (jvmtiEnv* env,
                       jvmtiHeapObjectFilter object_filter,
                       jvmtiHeapObjectCallback heap_object_callback,
                       const void* user_data);
112 Iterate Over Instances Of Class
jvmtiError (JNICALL *IterateOverInstancesOfClass) (jvmtiEnv* env,
                       jclass klass,
                       jvmtiHeapObjectFilter object_filter,
                       jvmtiHeapObjectCallback heap_object_callback,
                       const void* user_data);
113 reserved
void *reserved113;
114 Get Objects With Tags
jvmtiError (JNICALL *GetObjectsWithTags) (jvmtiEnv* env,
                       jint tag_count,
                       const jlong* tags,
                       jint* count_ptr,
                       jobject** object_result_ptr,
                       jlong** tag_result_ptr);
115 Follow References
jvmtiError (JNICALL *FollowReferences) (jvmtiEnv* env,
                       jint heap_filter,
                       jclass klass,
                       jobject initial_object,
                       const jvmtiHeapCallbacks* callbacks,
                       const void* user_data);
116 Iterate Through Heap
jvmtiError (JNICALL *IterateThroughHeap) (jvmtiEnv* env,
                       jint heap_filter,
                       jclass klass,
                       const jvmtiHeapCallbacks* callbacks,
                       const void* user_data);
117 reserved
void *reserved117;
118 reserved
void *reserved118;
119 reserved
void *reserved119;
120 Set JNI Function Table
jvmtiError (JNICALL *SetJNIFunctionTable) (jvmtiEnv* env,
                       const jniNativeInterface* function_table);
121 Get JNI Function Table
jvmtiError (JNICALL *GetJNIFunctionTable) (jvmtiEnv* env,
                       jniNativeInterface** function_table);
122 Set Event Callbacks
jvmtiError (JNICALL *SetEventCallbacks) (jvmtiEnv* env,
                       const jvmtiEventCallbacks* callbacks,
                       jint size_of_callbacks);
123 Generate Events
jvmtiError (JNICALL *GenerateEvents) (jvmtiEnv* env,
                       jvmtiEvent event_type);
124 Get Extension Functions
jvmtiError (JNICALL *GetExtensionFunctions) (jvmtiEnv* env,
                       jint* extension_count_ptr,
                       jvmtiExtensionFunctionInfo** extensions);
125 Get Extension Events
jvmtiError (JNICALL *GetExtensionEvents) (jvmtiEnv* env,
                       jint* extension_count_ptr,
                       jvmtiExtensionEventInfo** extensions);
126 Set Extension Event Callback
jvmtiError (JNICALL *SetExtensionEventCallback) (jvmtiEnv* env,
                       jint extension_event_index,
                       jvmtiExtensionEvent callback);
127 Dispose Environment
jvmtiError (JNICALL *DisposeEnvironment) (jvmtiEnv* env);
128 Get Error Name
jvmtiError (JNICALL *GetErrorName) (jvmtiEnv* env,
                       jvmtiError error,
                       char** name_ptr);
129 Get JLocation Format
jvmtiError (JNICALL *GetJLocationFormat) (jvmtiEnv* env,
                       jvmtiJlocationFormat* format_ptr);
130 Get System Properties
jvmtiError (JNICALL *GetSystemProperties) (jvmtiEnv* env,
                       jint* count_ptr,
                       char*** property_ptr);
131 Get System Property
jvmtiError (JNICALL *GetSystemProperty) (jvmtiEnv* env,
                       const char* property,
                       char** value_ptr);
132 Set System Property
jvmtiError (JNICALL *SetSystemProperty) (jvmtiEnv* env,
                       const char* property,
                       const char* value_ptr);
133 Get Phase
jvmtiError (JNICALL *GetPhase) (jvmtiEnv* env,
                       jvmtiPhase* phase_ptr);
134 Get Current Thread CPU Timer Information
jvmtiError (JNICALL *GetCurrentThreadCpuTimerInfo) (jvmtiEnv* env,
                       jvmtiTimerInfo* info_ptr);
135 Get Current Thread CPU Time
jvmtiError (JNICALL *GetCurrentThreadCpuTime) (jvmtiEnv* env,
                       jlong* nanos_ptr);
136 Get Thread CPU Timer Information
jvmtiError (JNICALL *GetThreadCpuTimerInfo) (jvmtiEnv* env,
                       jvmtiTimerInfo* info_ptr);
137 Get Thread CPU Time
jvmtiError (JNICALL *GetThreadCpuTime) (jvmtiEnv* env,
                       jthread thread,
                       jlong* nanos_ptr);
138 Get Timer Information
jvmtiError (JNICALL *GetTimerInfo) (jvmtiEnv* env,
                       jvmtiTimerInfo* info_ptr);
139 Get Time
jvmtiError (JNICALL *GetTime) (jvmtiEnv* env,
                       jlong* nanos_ptr);
140 Get Potential Capabilities
jvmtiError (JNICALL *GetPotentialCapabilities) (jvmtiEnv* env,
                       jvmtiCapabilities* capabilities_ptr);
141 reserved
void *reserved141;
142 Add Capabilities
jvmtiError (JNICALL *AddCapabilities) (jvmtiEnv* env,
                       const jvmtiCapabilities* capabilities_ptr);
143 Relinquish Capabilities
jvmtiError (JNICALL *RelinquishCapabilities) (jvmtiEnv* env,
                       const jvmtiCapabilities* capabilities_ptr);
144 Get Available Processors
jvmtiError (JNICALL *GetAvailableProcessors) (jvmtiEnv* env,
                       jint* processor_count_ptr);
145 Get Class Version Numbers
jvmtiError (JNICALL *GetClassVersionNumbers) (jvmtiEnv* env,
                       jclass klass,
                       jint* minor_version_ptr,
                       jint* major_version_ptr);
146 Get Constant Pool
jvmtiError (JNICALL *GetConstantPool) (jvmtiEnv* env,
                       jclass klass,
                       jint* constant_pool_count_ptr,
                       jint* constant_pool_byte_count_ptr,
                       unsigned char** constant_pool_bytes_ptr);
147 Get Environment Local Storage
jvmtiError (JNICALL *GetEnvironmentLocalStorage) (jvmtiEnv* env,
                       void** data_ptr);
148 Set Environment Local Storage
jvmtiError (JNICALL *SetEnvironmentLocalStorage) (jvmtiEnv* env,
                       const void* data);
149 Add To Bootstrap Class Loader Search
jvmtiError (JNICALL *AddToBootstrapClassLoaderSearch) (jvmtiEnv* env,
                       const char* segment);
150 Set Verbose Flag
jvmtiError (JNICALL *SetVerboseFlag) (jvmtiEnv* env,
                       jvmtiVerboseFlag flag,
                       jboolean value);
151 Add To System Class Loader Search
jvmtiError (JNICALL *AddToSystemClassLoaderSearch) (jvmtiEnv* env,
                       const char* segment);
152 Retransform Classes
jvmtiError (JNICALL *RetransformClasses) (jvmtiEnv* env,
                       jint class_count,
                       const jclass* classes);
153 Get Owned Monitor Stack Depth Info
jvmtiError (JNICALL *GetOwnedMonitorStackDepthInfo) (jvmtiEnv* env,
                       jthread thread,
                       jint* monitor_info_count_ptr,
                       jvmtiMonitorStackDepthInfo** monitor_info_ptr);
154 Get Object Size
jvmtiError (JNICALL *GetObjectSize) (jvmtiEnv* env,
                       jobject object,
                       jlong* size_ptr);
155 Get Local Instance
jvmtiError (JNICALL *GetLocalInstance) (jvmtiEnv* env,
                       jthread thread,
                       jint depth,
                       jobject* value_ptr);

Events

Handling Events

Agents can be informed of many events that occur in application programs.

To handle events, designate a set of callback functions with SetEventCallbacks. For each event the corresponding callback function will be called. Arguments to the callback function provide additional information about the event.

The callback function is usually called from within an application thread. The JVM TI implementation does not queue events in any way. This means that event callback functions must be written carefully. Here are some general guidelines. See the individual event descriptions for further suggestions.

  • Any exception thrown during the execution of an event callback can overwrite any current pending exception in the current application thread. Care must be taken to preserve a pending exception when an event callback makes a JNI call that might generate an exception.
  • Event callback functions must be re-entrant. The JVM TI implementation does not queue events. If an agent needs to process events one at a time, it can use a raw monitor inside the event callback functions to serialize event processing.
  • Event callback functions that execute JNI's FindClass function to load classes need to note that FindClass locates the class loader associated with the current native method. For the purposes of class loading, an event callback that includes a JNI environment as a parameter to the callback will treated as if it is a native call, where the native method is in the class of the event thread's current frame.

Some JVM TI events identify objects with JNI references. All references in JVM TI events are JNI local references and will become invalid after the event callback returns. Unless stated otherwise, memory referenced by pointers sent in event callbacks may not be referenced after the event callback returns.

Except where stated otherwise, events are delivered on the thread that caused the event. Events are sent at the time they occur. The specification for each event includes the set of phases in which it can be sent; if an event triggering activity occurs during another phase, no event is sent.

A thread that generates an event does not change its execution status (for example, the event does not cause the thread to be suspended). If an agent wishes the event to result in suspension, then the agent is responsible for explicitly suspending the thread with SuspendThread.

If an event is enabled in multiple environments, the event will be sent to each agent in the order that the environments were created.

Enabling Events

All events are initially disabled. In order to receive any event:
  • If the event requires a capability, that capability must be added with AddCapabilities.
  • A callback for the event must be set with SetEventCallbacks.
  • The event must be enabled with SetEventNotificationMode.

Multiple Co-located Events

In many situations it is possible for multiple events to occur at the same location in one thread. When this happens, all the events are reported through the event callbacks in the order specified in this section.

If the current location is at the entry point of a method, the MethodEntry event is reported before any other event at the current location in the same thread.

If an exception catch has been detected at the current location, either because it is the beginning of a catch clause or a native method that cleared a pending exception has returned, the exceptionCatch event is reported before any other event at the current location in the same thread.

If a singleStep event or breakpoint event is triggered at the current location, the event is defined to occur immediately before the code at the current location is executed. These events are reported before any events which are triggered by the execution of code at the current location in the same thread (specifically: exception, fieldAccess, and fieldModification). If both a step and breakpoint event are triggered for the same thread and location, the step event is reported before the breakpoint event.

If the current location is the exit point of a method (that is, the last location before returning to the caller), the MethodExit event and the FramePop event (if requested) are reported after all other events at the current location in the same thread. There is no specified ordering of these two events with respect to each other.

Co-located events can be triggered during the processing of some other event by the agent at the same location in the same thread. If such an event, of type y, is triggered during the processing of an event of type x, and if x precedes y in the ordering specified above, the co-located event y is reported for the current thread and location. If x does not precede y, y is not reported for the current thread and location. For example, if a breakpoint is set at the current location during the processing of SingleStep, that breakpoint will be reported before the thread moves off the current location.

The following events are never considered to be co-located with other events.
  • VMStart
  • VMInit
  • VMDeath
  • ThreadStart
  • ThreadEnd
  • ClassLoad
  • ClassPrepare

Event Callbacks

The event callback structure below is used to specify the handler function for events. It is set with the SetEventCallbacks function.
typedef struct {
    jvmtiEventVMInit VMInit;
    jvmtiEventVMDeath VMDeath;
    jvmtiEventThreadStart ThreadStart;
    jvmtiEventThreadEnd ThreadEnd;
    jvmtiEventClassFileLoadHook ClassFileLoadHook;
    jvmtiEventClassLoad ClassLoad;
    jvmtiEventClassPrepare ClassPrepare;
    jvmtiEventVMStart VMStart;
    jvmtiEventException Exception;
    jvmtiEventExceptionCatch ExceptionCatch;
    jvmtiEventSingleStep SingleStep;
    jvmtiEventFramePop FramePop;
    jvmtiEventBreakpoint Breakpoint;
    jvmtiEventFieldAccess FieldAccess;
    jvmtiEventFieldModification FieldModification;
    jvmtiEventMethodEntry MethodEntry;
    jvmtiEventMethodExit MethodExit;
    jvmtiEventNativeMethodBind NativeMethodBind;
    jvmtiEventCompiledMethodLoad CompiledMethodLoad;
    jvmtiEventCompiledMethodUnload CompiledMethodUnload;
    jvmtiEventDynamicCodeGenerated DynamicCodeGenerated;
    jvmtiEventDataDumpRequest DataDumpRequest;
    jvmtiEventReserved reserved72;
    jvmtiEventMonitorWait MonitorWait;
    jvmtiEventMonitorWaited MonitorWaited;
    jvmtiEventMonitorContendedEnter MonitorContendedEnter;
    jvmtiEventMonitorContendedEntered MonitorContendedEntered;
    jvmtiEventReserved reserved77;
    jvmtiEventReserved reserved78;
    jvmtiEventReserved reserved79;
    jvmtiEventResourceExhausted ResourceExhausted;
    jvmtiEventGarbageCollectionStart GarbageCollectionStart;
    jvmtiEventGarbageCollectionFinish GarbageCollectionFinish;
    jvmtiEventObjectFree ObjectFree;
    jvmtiEventVMObjectAlloc VMObjectAlloc;
} jvmtiEventCallbacks;

Event Index

  • Breakpoint
  • Class File Load Hook
  • Class Load
  • Class Prepare
  • Compiled Method Load
  • Compiled Method Unload
  • Data Dump Request
  • Dynamic Code Generated
  • Exception
  • Exception Catch
  • Field Access
  • Field Modification
  • Frame Pop
  • Garbage Collection Finish
  • Garbage Collection Start
  • Method Entry
  • Method Exit
  • Monitor Contended Enter
  • Monitor Contended Entered
  • Monitor Wait
  • Monitor Waited
  • Native Method Bind
  • Object Free
  • Resource Exhausted
  • Single Step
  • Thread End
  • Thread Start
  • VM Death Event
  • VM Initialization Event
  • VM Object Allocation
  • VM Start Event

Single Step

void JNICALL
SingleStep(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env,
            jthread thread,
            jmethodID method,
            jlocation location)
Single step events allow the agent to trace thread execution at the finest granularity allowed by the VM. A single step event is generated whenever a thread reaches a new location. Typically, single step events represent the completion of one VM instruction as defined in the Java Virtual Machine Specification. However, some implementations may define locations differently. In any case the method and location parameters uniquely identify the current location and allow the mapping to source file and line number when that information is available.

No single step events are generated from within native methods.

Phase | Event Type | Number | Enabling | Since
sent only during the live phase | JVMTI_EVENT_SINGLE_STEP | 60 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_SINGLE_STEP, NULL) | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this event.
Capability | Effect
can_generate_single_step_events | Can get single step events

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread
thread | jthread | Thread about to execution a new instruction
method | jmethodID | Method about to execute a new instruction
location | jlocation | Location of the new instruction

Breakpoint

void JNICALL
Breakpoint(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env,
            jthread thread,
            jmethodID method,
            jlocation location)
Breakpoint events are generated whenever a thread reaches a location designated as a breakpoint with SetBreakpoint. The method and location parameters uniquely identify the current location and allow the mapping to source file and line number when that information is available.

Phase | Event Type | Number | Enabling | Since
sent only during the live phase | JVMTI_EVENT_BREAKPOINT | 62 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_BREAKPOINT, NULL) | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this event.
Capability | Effect
can_generate_breakpoint_events | Can set and thus get Breakpoint events

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread.
thread | jthread | Thread that hit the breakpoint
method | jmethodID | Method that hit the breakpoint
location | jlocation | location of the breakpoint

Field Access

void JNICALL
FieldAccess(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env,
            jthread thread,
            jmethodID method,
            jlocation location,
            jclass field_klass,
            jobject object,
            jfieldID field)
Field access events are generated whenever a thread accesses a field that was designated as a watchpoint with SetFieldAccessWatch. The method and location parameters uniquely identify the current location and allow the mapping to source file and line number when that information is available.

Phase | Event Type | Number | Enabling | Since
sent only during the live phase | JVMTI_EVENT_FIELD_ACCESS | 63 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_FIELD_ACCESS, NULL) | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this event.
Capability | Effect
can_generate_field_access_events | Can set watchpoints on field access - SetFieldAccessWatch

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread
thread | jthread | Thread accessing the field
method | jmethodID | Method where the access is occurring
location | jlocation | Location where the access is occurring
field_klass | jclass | Class of the field being accessed
object | jobject | Object with the field being accessed if the field is an instance field; NULL otherwise
field | jfieldID | Field being accessed

Field Modification

void JNICALL
FieldModification(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env,
            jthread thread,
            jmethodID method,
            jlocation location,
            jclass field_klass,
            jobject object,
            jfieldID field,
            char signature_type,
            jvalue new_value)
Field modification events are generated whenever a thread modifies a field that was designated as a watchpoint with SetFieldModificationWatch. The method and location parameters uniquely identify the current location and allow the mapping to source file and line number when that information is available.

Phase | Event Type | Number | Enabling | Since
sent only during the live phase | JVMTI_EVENT_FIELD_MODIFICATION | 64 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_FIELD_MODIFICATION, NULL) | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this event.
Capability | Effect
can_generate_field_modification_events | Can set watchpoints on field modification - SetFieldModificationWatch

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread
thread | jthread | Thread modifying the field
method | jmethodID | Method where the modification is occurring
location | jlocation | Location where the modification is occurring
field_klass | jclass | Class of the field being modified
object | jobject | Object with the field being modified if the field is an instance field; NULL otherwise
field | jfieldID | Field being modified
signature_type | char | Signature type of the new value
new_value | jvalue | The new value

Frame Pop

void JNICALL
FramePop(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env,
            jthread thread,
            jmethodID method,
            jboolean was_popped_by_exception)
Frame pop events are generated upon exit from a single method in a single frame as specified in a call to NotifyFramePop. This is true whether termination is caused by executing its return instruction or by throwing an exception to its caller (see was_popped_by_exception). However, frame pops caused by the PopFrame function are not reported.

The location reported by GetFrameLocation identifies the executable location in the returning method, immediately prior to the return.

Phase | Event Type | Number | Enabling | Since
sent only during the live phase | JVMTI_EVENT_FRAME_POP | 61 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_FRAME_POP, NULL) | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this event.
Capability | Effect
can_generate_frame_pop_events | Can set and thus get FramePop events

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread
thread | jthread | Thread that is popping the frame
method | jmethodID | Method being popped
was_popped_by_exception | jboolean | True if frame was popped by a thrown exception. False if method exited through its return instruction.

Method Entry

void JNICALL
MethodEntry(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env,
            jthread thread,
            jmethodID method)
Method entry events are generated upon entry of Java programming language methods (including native methods).

The location reported by GetFrameLocation identifies the initial executable location in the method.

Enabling method entry or exit events will significantly degrade performance on many platforms and is thus not advised for performance critical usage (such as profiling). Bytecode instrumentation should be used in these cases.

Phase | Event Type | Number | Enabling | Since
sent only during the live phase | JVMTI_EVENT_METHOD_ENTRY | 65 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_METHOD_ENTRY, NULL) | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this event.
Capability | Effect
can_generate_method_entry_events | Can generate method entry events on entering a method

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread
thread | jthread | Thread entering the method
method | jmethodID | Method being entered

Method Exit

void JNICALL
MethodExit(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env,
            jthread thread,
            jmethodID method,
            jboolean was_popped_by_exception,
            jvalue return_value)
Method exit events are generated upon exit from Java programming language methods (including native methods). This is true whether termination is caused by executing its return instruction or by throwing an exception to its caller (see was_popped_by_exception).

The method field uniquely identifies the method being entered or exited. The frame field provides access to the stack frame for the method.

The location reported by GetFrameLocation identifies the executable location in the returning method immediately prior to the return.

Enabling method entry or exit events will significantly degrade performance on many platforms and is thus not advised for performance critical usage (such as profiling). Bytecode instrumentation should be used in these cases.

Phase | Event Type | Number | Enabling | Since
sent only during the live phase | JVMTI_EVENT_METHOD_EXIT | 66 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_METHOD_EXIT, NULL) | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this event.
Capability | Effect
can_generate_method_exit_events | Can generate method exit events on leaving a method

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread
thread | jthread | Thread exiting the method
method | jmethodID | Method being exited
was_popped_by_exception | jboolean | True if frame was popped by a thrown exception. False if method exited through its return instruction.
return_value | jvalue | The return value of the method being exited. Undefined and should not be used if was_popped_by_exception is true.

Native Method Bind

void JNICALL
NativeMethodBind(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env,
            jthread thread,
            jmethodID method,
            void* address,
            void** new_address_ptr)
A Native Method Bind event is sent when a VM binds a Java programming language native method to the address of a function that implements the native method. This will occur when the native method is called for the first time and also occurs when the JNI function RegisterNatives is called. This event allows the bind to be redirected to an agent-specified proxy function. This event is not sent when the native method is unbound. Typically, this proxy function will need to be specific to a particular method or, to handle the general case, automatically generated assembly code, since after instrumentation code is executed the function at the original binding address will usually be invoked. The original binding can be restored or the redirection changed by use of the JNI function RegisterNatives. Some events may be sent during the primordial phase, JNI and most of JVM TI cannot be used at this time but the method and address can be saved for use later.

Phase | Event Type | Number | Enabling | Since
sent during the primordial, start or live phase | JVMTI_EVENT_NATIVE_METHOD_BIND | 67 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_NATIVE_METHOD_BIND, NULL) | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this event.
Capability | Effect
can_generate_native_method_bind_events | Can generate events when a native method is bound to its implementation

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread Will be NULL if sent during the primordial phase.
thread | jthread | Thread requesting the bind
method | jmethodID | Native method being bound
address | void* | The address the VM is about to bind to--that is, the address of the implementation of the native method
new_address_ptr | void** | if the referenced address is changed (that is, if *new_address_ptr is set), the binding will instead be made to the supplied address.

Exception

void JNICALL
Exception(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env,
            jthread thread,
            jmethodID method,
            jlocation location,
            jobject exception,
            jmethodID catch_method,
            jlocation catch_location)
Exception events are generated whenever an exception is first detected in a Java programming language method. Where "exception" means any java.lang.Throwable. The exception may have been thrown by a Java programming language or native method, but in the case of native methods, the event is not generated until the exception is first seen by a Java programming language method. If an exception is set and cleared in a native method (and thus is never visible to Java programming language code), no exception event is generated.

The method and location parameters uniquely identify the current location (where the exception was detected) and allow the mapping to source file and line number when that information is available. The exception field identifies the thrown exception object. The catch_method and catch_location identify the location of the catch clause, if any, that handles the thrown exception. If there is no such catch clause, each field is set to 0. There is no guarantee that the thread will ever reach this catch clause. If there are native methods on the call stack between the throw location and the catch clause, the exception may be reset by one of those native methods. Similarly, exceptions that are reported as uncaught (catch_klass et al. set to 0) may in fact be caught by native code. Agents can check for these occurrences by monitoring ExceptionCatch events. Note that finally clauses are implemented as catch and re-throw. Therefore they will be reported in the catch location.

Phase | Event Type | Number | Enabling | Since
sent only during the live phase | JVMTI_EVENT_EXCEPTION | 58 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_EXCEPTION, NULL) | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this event.
Capability | Effect
can_generate_exception_events | Can get exception thrown and exception catch events

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread
thread | jthread | Thread generating the exception
method | jmethodID | Method generating the exception
location | jlocation | Location where exception occurred
exception | jobject | The exception being thrown
catch_method | jmethodID | Method that will catch the exception, or NULL if no known catch
catch_location | jlocation | location which will catch the exception or zero if no known catch

Exception Catch

void JNICALL
ExceptionCatch(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env,
            jthread thread,
            jmethodID method,
            jlocation location,
            jobject exception)
Exception catch events are generated whenever a thrown exception is caught. Where "exception" means any java.lang.Throwable. If the exception is caught in a Java programming language method, the event is generated when the catch clause is reached. If the exception is caught in a native method, the event is generated as soon as control is returned to a Java programming language method. Exception catch events are generated for any exception for which a throw was detected in a Java programming language method. Note that finally clauses are implemented as catch and re-throw. Therefore they will generate exception catch events.

The method and location parameters uniquely identify the current location and allow the mapping to source file and line number when that information is available. For exceptions caught in a Java programming language method, the exception object identifies the exception object. Exceptions caught in native methods are not necessarily available by the time the exception catch is reported, so the exception field is set to NULL.

Phase | Event Type | Number | Enabling | Since
sent only during the live phase | JVMTI_EVENT_EXCEPTION_CATCH | 59 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_EXCEPTION_CATCH, NULL) | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this event.
Capability | Effect
can_generate_exception_events | Can get exception thrown and exception catch events

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread
thread | jthread | Thread catching the exception
method | jmethodID | Method catching the exception
location | jlocation | Location where exception is being caught
exception | jobject | Exception being caught

Thread Start

void JNICALL
ThreadStart(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env,
            jthread thread)
Thread start events are generated by a new thread before its initial method executes.

A thread may be listed in the array returned by GetAllThreads before its thread start event is generated. It is possible for other events to be generated on a thread before its thread start event.

The event is sent on the newly started thread.

Phase | Event Type | Number | Enabling | Since
sent during the start or live phase | JVMTI_EVENT_THREAD_START | 52 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_THREAD_START, NULL) | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread.
thread | jthread | Thread starting

Thread End

void JNICALL
ThreadEnd(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env,
            jthread thread)
Thread end events are generated by a terminating thread after its initial method has finished execution.

A thread may be listed in the array returned by GetAllThreads after its thread end event is generated. No events are generated on a thread after its thread end event.

The event is sent on the dying thread.

Phase | Event Type | Number | Enabling | Since
sent during the start or live phase | JVMTI_EVENT_THREAD_END | 53 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_THREAD_END, NULL) | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread.
thread | jthread | Thread ending

Class Load

void JNICALL
ClassLoad(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env,
            jthread thread,
            jclass klass)
A class load event is generated when a class is first loaded. The order of class load events generated by a particular thread are guaranteed to match the order of class loading within that thread. Array class creation does not generate a class load event. The creation of a primitive class (for example, java.lang.Integer.TYPE) does not generate a class load event.

This event is sent at an early stage in loading the class. As a result the class should be used carefully. Note, for example, that methods and fields are not yet loaded, so queries for methods, fields, subclasses, and so on will not give correct results. See "Loading of Classes and Interfaces" in the Java Language Specification. For most purposes the ClassPrepare event will be more useful.

Phase | Event Type | Number | Enabling | Since
sent during the start or live phase | JVMTI_EVENT_CLASS_LOAD | 55 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_LOAD, NULL) | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread
thread | jthread | Thread loading the class
klass | jclass | Class being loaded

Class Prepare

void JNICALL
ClassPrepare(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env,
            jthread thread,
            jclass klass)
A class prepare event is generated when class preparation is complete. At this point, class fields, methods, and implemented interfaces are available, and no code from the class has been executed. Since array classes never have fields or methods, class prepare events are not generated for them. Class prepare events are not generated for primitive classes (for example, java.lang.Integer.TYPE).

Phase | Event Type | Number | Enabling | Since
sent during the start or live phase | JVMTI_EVENT_CLASS_PREPARE | 56 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_PREPARE, NULL) | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread
thread | jthread | Thread generating the class prepare
klass | jclass | Class being prepared

Class File Load Hook

void JNICALL
ClassFileLoadHook(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env,
            jclass class_being_redefined,
            jobject loader,
            const char* name,
            jobject protection_domain,
            jint class_data_len,
            const unsigned char* class_data,
            jint* new_class_data_len,
            unsigned char** new_class_data)
This event is sent when the VM obtains class file data, but before it constructs the in-memory representation for that class. This event is also sent when the class is being modified by the RetransformClasses function or the RedefineClasses function, called in any JVM TI environment. The agent can instrument the existing class file data sent by the VM to include profiling/debugging hooks. See the description of bytecode instrumentation for usage information.

This event may be sent before the VM is initialized (the primordial phase). During this time no VM resources should be created. Some classes might not be compatible with the function (eg. ROMized classes) and this event will not be generated for these classes.

The agent must allocate the space for the modified class file data buffer using the memory allocation function Allocate because the VM is responsible for freeing the new class file data buffer using Deallocate. Note that Allocate is permitted during the primordial phase.

If the agent wishes to modify the class file, it must set new_class_data to point to the newly instrumented class file data buffer and set new_class_data_len to the length of that buffer before returning from this call. If no modification is desired, the agent simply does not set new_class_data. If multiple agents have enabled this event the results are chained. That is, if new_class_data has been set, it becomes the class_data for the next agent.

The order that this event is sent to each environment differs from other events. This event is sent to environments in the following order:
  • retransformation incapable environments, in the order in which they were created
  • retransformation capable environments, in the order in which they were created
When triggered by RetransformClasses, this event is sent only to retransformation capable environments.

Phase | Event Type | Number | Enabling | Since
sent during the primordial, start or live phase | JVMTI_EVENT_CLASS_FILE_LOAD_HOOK | 54 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, NULL) | 1.0

Capabilities
Required Functionality
Optional Features
Capability | Effect
can_generate_all_class_hook_events | Can generate ClassFileLoadHook events for every loaded class.

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread. Will be NULL if sent during the primordial phase.
class_being_redefined | jclass | The class being redefined or retransformed. NULL if sent by class load.
loader | jobject | The class loader loading the class. NULL if the bootstrap class loader.
name | const char* | Name of class being loaded as a VM internal qualified name (for example, "java/util/List"), encoded as a modified UTF-8 string. Note: if the class is defined with a NULL name or without a name specified, name will be NULL.
protection_domain | jobject | The ProtectionDomain of the class.
class_data_len | jint | Length of current class file data buffer.
class_data | const unsigned char* | Pointer to the current class file data buffer.
new_class_data_len | jint* | Pointer to the length of the new class file data buffer.
new_class_data | unsigned char** | Pointer to the pointer to the instrumented class file data buffer.

VM Start Event

void JNICALL
VMStart(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env)
The VM initialization event signals the start of the VM. At this time JNI is live but the VM is not yet fully initialized. Once this event is generated, the agent is free to call any JNI function. This event signals the beginning of the start phase, JVM TI functions permitted in the start phase may be called.

In the case of VM start-up failure, this event will not be sent.

Phase | Event Type | Number | Enabling | Since
sent during the start or live phase | JVMTI_EVENT_VM_START | 57 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_START, NULL) | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread.

VM Initialization Event

void JNICALL
VMInit(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env,
            jthread thread)
The VM initialization event signals the completion of VM initialization. Once this event is generated, the agent is free to call any JNI or JVM TI function. The VM initialization event can be preceded by or can be concurrent with other events, but the preceding events should be handled carefully, if at all, because the VM has not completed its initialization. The thread start event for the main application thread is guaranteed not to occur until after the handler for the VM initialization event returns.

In the case of VM start-up failure, this event will not be sent.

Phase | Event Type | Number | Enabling | Since
sent only during the live phase | JVMTI_EVENT_VM_INIT | 50 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, NULL) | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread.
thread | jthread | The initial thread

VM Death Event

void JNICALL
VMDeath(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env)
The VM death event notifies the agent of the termination of the VM. No events will occur after the VMDeath event.

In the case of VM start-up failure, this event will not be sent. Note that Agent_OnUnload will still be called in these cases.

Phase | Event Type | Number | Enabling | Since
sent only during the live phase | JVMTI_EVENT_VM_DEATH | 51 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_DEATH, NULL) | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread

Compiled Method Load

typedef struct {
    const void* start_address;
    jlocation location;
} jvmtiAddrLocationMap;
void JNICALL
CompiledMethodLoad(jvmtiEnv *jvmti_env,
            jmethodID method,
            jint code_size,
            const void* code_addr,
            jint map_length,
            const jvmtiAddrLocationMap* map,
            const void* compile_info)
Sent when a method is compiled and loaded into memory by the VM. If it is unloaded, the CompiledMethodUnload event is sent. If it is moved, the CompiledMethodUnload event is sent, followed by a new CompiledMethodLoad event. Note that a single method may have multiple compiled forms, and that this event will be sent for each form. Note also that several methods may be inlined into a single address range, and that this event will be sent for each method.

These events can be sent after their initial occurrence with GenerateEvents.

Phase | Event Type | Number | Enabling | Since
sent only during the live phase | JVMTI_EVENT_COMPILED_METHOD_LOAD | 68 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_COMPILED_METHOD_LOAD, NULL) | 1.0

jvmtiAddrLocationMap - Native address to location entry
Field | Type | Description
start_address | const void* | Starting native address of code corresponding to a location
location | jlocation | Corresponding location. See GetJLocationFormat for the meaning of location.

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this event.
Capability | Effect
can_generate_compiled_method_load_events | Can generate events when a method is compiled or unloaded

Parameters
Name | Type | Description
method | jmethodID | Method being compiled and loaded
code_size | jint | Size of compiled code
code_addr | const void* | Address where compiled method code is loaded
map_length | jint | Number of jvmtiAddrLocationMap entries in the address map. Zero if mapping information cannot be supplied.
map | const jvmtiAddrLocationMap* | Map from native addresses to location. The native address range of each entry is from start_address to start_address-1 of the next entry. NULL if mapping information cannot be supplied.
compile_info | const void* | VM-specific compilation information. The referenced compile information is managed by the VM and must not depend on the agent for collection. A VM implementation defines the content and lifetime of the information.

Compiled Method Unload

void JNICALL
CompiledMethodUnload(jvmtiEnv *jvmti_env,
            jmethodID method,
            const void* code_addr)
Sent when a compiled method is unloaded from memory. This event might not be sent on the thread which performed the unload. This event may be sent sometime after the unload occurs, but will be sent before the memory is reused by a newly generated compiled method. This event may be sent after the class is unloaded.

Phase | Event Type | Number | Enabling | Since
sent only during the live phase | JVMTI_EVENT_COMPILED_METHOD_UNLOAD | 69 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_COMPILED_METHOD_UNLOAD, NULL) | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this event.
Capability | Effect
can_generate_compiled_method_load_events | Can generate events when a method is compiled or unloaded

Parameters
Name | Type | Description
method | jmethodID | Compiled method being unloaded. For identification of the compiled method only -- the class may be unloaded and therefore the method should not be used as an argument to further JNI or JVM TI functions.
code_addr | const void* | Address where compiled method code was loaded. For identification of the compiled method only -- the space may have been reclaimed.

Dynamic Code Generated

void JNICALL
DynamicCodeGenerated(jvmtiEnv *jvmti_env,
            const char* name,
            const void* address,
            jint length)
Sent when a component of the virtual machine is generated dynamically. This does not correspond to Java programming language code that is compiled--see CompiledMethodLoad. This is for native code--for example, an interpreter that is generated differently depending on command-line options.

Note that this event has no controlling capability. If a VM cannot generate these events, it simply does not send any.

These events can be sent after their initial occurrence with GenerateEvents.

Phase | Event Type | Number | Enabling | Since
sent during the primordial, start or live phase | JVMTI_EVENT_DYNAMIC_CODE_GENERATED | 70 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_DYNAMIC_CODE_GENERATED, NULL) | 1.0

Capabilities
Required Functionality

Parameters
Name | Type | Description
name | const char* | Name of the code, encoded as a modified UTF-8 string. Intended for display to an end-user. The name might not be unique.
address | const void* | Native address of the code
length | jint | Length in bytes of the code

Data Dump Request

void JNICALL
DataDumpRequest(jvmtiEnv *jvmti_env)
Sent by the VM to request the agent to dump its data. This is just a hint and the agent need not react to this event. This is useful for processing command-line signals from users. For example, in the Java 2 SDK a CTRL-Break on Win32 and a CTRL-\ on Solaris causes the VM to send this event to the agent.

Phase | Event Type | Number | Enabling | Since
sent only during the live phase | JVMTI_EVENT_DATA_DUMP_REQUEST | 71 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_DATA_DUMP_REQUEST, NULL) | 1.0

Capabilities
Required Functionality

Parameters
Name Type Description

Monitor Contended Enter

void JNICALL
MonitorContendedEnter(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env,
            jthread thread,
            jobject object)
Sent when a thread is attempting to enter a Java programming language monitor already acquired by another thread.

Phase | Event Type | Number | Enabling | Since
sent only during the live phase | JVMTI_EVENT_MONITOR_CONTENDED_ENTER | 75 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_MONITOR_CONTENDED_ENTER, NULL) | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this event.
Capability | Effect
can_generate_monitor_events | Can generate events on monitor activity

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread
thread | jthread | JNI local reference to the thread attempting to enter the monitor
object | jobject | JNI local reference to the monitor

Monitor Contended Entered

void JNICALL
MonitorContendedEntered(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env,
            jthread thread,
            jobject object)
Sent when a thread enters a Java programming language monitor after waiting for it to be released by another thread.

Phase | Event Type | Number | Enabling | Since
sent only during the live phase | JVMTI_EVENT_MONITOR_CONTENDED_ENTERED | 76 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_MONITOR_CONTENDED_ENTERED, NULL) | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this event.
Capability | Effect
can_generate_monitor_events | Can generate events on monitor activity

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread
thread | jthread | JNI local reference to the thread entering the monitor
object | jobject | JNI local reference to the monitor

Monitor Wait

void JNICALL
MonitorWait(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env,
            jthread thread,
            jobject object,
            jlong timeout)
Sent when a thread is about to wait on an object.

Phase | Event Type | Number | Enabling | Since
sent only during the live phase | JVMTI_EVENT_MONITOR_WAIT | 73 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_MONITOR_WAIT, NULL) | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this event.
Capability | Effect
can_generate_monitor_events | Can generate events on monitor activity

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread
thread | jthread | JNI local reference to the thread about to wait
object | jobject | JNI local reference to the monitor
timeout | jlong | The number of milliseconds the thread will wait

Monitor Waited

void JNICALL
MonitorWaited(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env,
            jthread thread,
            jobject object,
            jboolean timed_out)
Sent when a thread finishes waiting on an object.

Phase | Event Type | Number | Enabling | Since
sent only during the live phase | JVMTI_EVENT_MONITOR_WAITED | 74 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_MONITOR_WAITED, NULL) | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this event.
Capability | Effect
can_generate_monitor_events | Can generate events on monitor activity

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread
thread | jthread | JNI local reference to the thread that was finished waiting
object | jobject | JNI local reference to the monitor.
timed_out | jboolean | True if the monitor timed out

Resource Exhausted

void JNICALL
ResourceExhausted(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env,
            jint flags,
            const void* reserved,
            const char* description)
Sent when a VM resource needed by a running application has been exhausted. Except as required by the optional capabilities, the set of resources which report exhaustion is implementation dependent.

The following bit flags define the properties of the resource exhaustion:
Resource Exhaustion Flags
Constant | Value | Description
JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | 0x0001 | After this event returns, the VM will throw a java.lang.OutOfMemoryError.
JVMTI_RESOURCE_EXHAUSTED_JAVA_HEAP | 0x0002 | The VM was unable to allocate memory from the JavaTM platform heap. The heap is the runtime data area from which memory for all class instances and arrays are allocated.
JVMTI_RESOURCE_EXHAUSTED_THREADS | 0x0004 | The VM was unable to create a thread.

Phase | Event Type | Number | Enabling | Since
sent only during the live phase | JVMTI_EVENT_RESOURCE_EXHAUSTED | 80 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_RESOURCE_EXHAUSTED, NULL) | 1.1

Capabilities
Required Functionality
Optional Features
Capability | Effect
can_generate_resource_exhaustion_heap_events | Can generate events when the VM is unable to allocate memory from the heap.
can_generate_resource_exhaustion_threads_events | Can generate events when the VM is unable to create a thread.

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread
flags | jint | Flags defining the properties of the of resource exhaustion as specified by the Resource Exhaustion Flags.
reserved | const void* | Reserved.
description | const char* | Description of the resource exhaustion, encoded as a modified UTF-8 string.

VM Object Allocation

void JNICALL
VMObjectAlloc(jvmtiEnv *jvmti_env,
            JNIEnv* jni_env,
            jthread thread,
            jobject object,
            jclass object_klass,
            jlong size)
Sent when a method causes the virtual machine to allocate an Object visible to Java programming language code and the allocation is not detectable by other intrumentation mechanisms. Generally object allocation should be detected by instrumenting the bytecodes of allocating methods. Object allocation generated in native code by JNI function calls should be detected using JNI function interception. Some methods might not have associated bytecodes and are not native methods, they instead are executed directly by the VM. These methods should send this event. Virtual machines which are incapable of bytecode instrumentation for some or all of their methods can send this event.

Typical examples where this event might be sent:
  • Reflection -- for example, java.lang.Class.newInstance()
  • Methods not represented by bytecodes -- for example, VM intrinsics and J2ME preloaded classes
Cases where this event would not be generated:
  • Allocation due to bytecodes -- for example, the new and newarray VM instructions
  • Allocation due to JNI function calls -- for example, AllocObject
  • Allocations during VM initialization
  • VM internal objects

Phase | Event Type | Number | Enabling | Since
sent only during the live phase | JVMTI_EVENT_VM_OBJECT_ALLOC | 84 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_OBJECT_ALLOC, NULL) | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this event.
Capability | Effect
can_generate_vm_object_alloc_events | Can generate events on VM allocation of an object

Parameters
Name | Type | Description
jni_env | JNIEnv * | The JNI environment of the event (current) thread
thread | jthread | Thread allocating the object.
object | jobject | JNI local reference to the object that was allocated
object_klass | jclass | JNI local reference to the class of the object
size | jlong | Size of the object (in bytes). See GetObjectSize.

Object Free

void JNICALL
ObjectFree(jvmtiEnv *jvmti_env,
            jlong tag)
An Object Free event is sent when the garbage collector frees an object. Events are only sent for tagged objects--see heap functions.

The event handler must not use JNI functions and must not use JVM TI functions except those which specifically allow such use (see the raw monitor, memory management, and environment local storage functions).

Phase | Event Type | Number | Enabling | Since
sent only during the live phase | JVMTI_EVENT_OBJECT_FREE | 83 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_OBJECT_FREE, NULL) | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this event.
Capability | Effect
can_generate_object_free_events | Can generate events when the garbage collector frees an object

Parameters
Name | Type | Description
tag | jlong | The freed object's tag

Garbage Collection Start

void JNICALL
GarbageCollectionStart(jvmtiEnv *jvmti_env)
A Garbage Collection Start event is sent when a garbage collection pause begins. Only stop-the-world collections are reported--that is, collections during which all threads cease to modify the state of the Java virtual machine. This means that some collectors will never generate these events. This event is sent while the VM is still stopped, thus the event handler must not use JNI functions and must not use JVM TI functions except those which specifically allow such use (see the raw monitor, memory management, and environment local storage functions).

This event is always sent as a matched pair with GarbageCollectionFinish (assuming both events are enabled) and no garbage collection events will occur between them.

Phase | Event Type | Number | Enabling | Since
sent only during the live phase | JVMTI_EVENT_GARBAGE_COLLECTION_START | 81 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_GARBAGE_COLLECTION_START, NULL) | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this event.
Capability | Effect
can_generate_garbage_collection_events | Can generate events when garbage collection begins or ends

Parameters
Name Type Description

Garbage Collection Finish

void JNICALL
GarbageCollectionFinish(jvmtiEnv *jvmti_env)
A Garbage Collection Finish event is sent when a garbage collection pause ends. This event is sent while the VM is still stopped, thus the event handler must not use JNI functions and must not use JVM TI functions except those which specifically allow such use (see the raw monitor, memory management, and environment local storage functions).

Some agents may need to do post garbage collection operations that require the use of the disallowed JVM TI or JNI functions. For these cases an agent thread can be created which waits on a raw monitor, and the handler for the Garbage Collection Finish event simply notifies the raw monitor

This event is always sent as a matched pair with GarbageCollectionStart (assuming both events are enabled).

Phase | Event Type | Number | Enabling | Since
sent only during the live phase | JVMTI_EVENT_GARBAGE_COLLECTION_FINISH | 82 | SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_GARBAGE_COLLECTION_FINISH, NULL) | 1.0

Capabilities
Optional Functionality: might not be implemented for all virtual machines. The following capability (as returned by GetCapabilities) must be true to use this event.
Capability | Effect
can_generate_garbage_collection_events | Can generate events when garbage collection begins or ends

Parameters
Name Type Description

Constant Index

JVMTI_CLASS_STATUS_ARRAY
JVMTI_CLASS_STATUS_ERROR
JVMTI_CLASS_STATUS_INITIALIZED
JVMTI_CLASS_STATUS_PREPARED
JVMTI_CLASS_STATUS_PRIMITIVE
JVMTI_CLASS_STATUS_VERIFIED
JVMTI_DISABLE
JVMTI_ENABLE
JVMTI_HEAP_FILTER_CLASS_TAGGED
JVMTI_HEAP_FILTER_CLASS_UNTAGGED
JVMTI_HEAP_FILTER_TAGGED
JVMTI_HEAP_FILTER_UNTAGGED
JVMTI_HEAP_OBJECT_EITHER
JVMTI_HEAP_OBJECT_TAGGED
JVMTI_HEAP_OBJECT_UNTAGGED
JVMTI_HEAP_REFERENCE_ARRAY_ELEMENT
JVMTI_HEAP_REFERENCE_CLASS
JVMTI_HEAP_REFERENCE_CLASS_LOADER
JVMTI_HEAP_REFERENCE_CONSTANT_POOL
JVMTI_HEAP_REFERENCE_FIELD
JVMTI_HEAP_REFERENCE_INTERFACE
JVMTI_HEAP_REFERENCE_JNI_GLOBAL
JVMTI_HEAP_REFERENCE_JNI_LOCAL
JVMTI_HEAP_REFERENCE_MONITOR
JVMTI_HEAP_REFERENCE_OTHER
JVMTI_HEAP_REFERENCE_PROTECTION_DOMAIN
JVMTI_HEAP_REFERENCE_SIGNERS
JVMTI_HEAP_REFERENCE_STACK_LOCAL
JVMTI_HEAP_REFERENCE_STATIC_FIELD
JVMTI_HEAP_REFERENCE_SUPERCLASS
JVMTI_HEAP_REFERENCE_SYSTEM_CLASS
JVMTI_HEAP_REFERENCE_THREAD
JVMTI_HEAP_ROOT_JNI_GLOBAL
JVMTI_HEAP_ROOT_JNI_LOCAL
JVMTI_HEAP_ROOT_MONITOR
JVMTI_HEAP_ROOT_OTHER
JVMTI_HEAP_ROOT_STACK_LOCAL
JVMTI_HEAP_ROOT_SYSTEM_CLASS
JVMTI_HEAP_ROOT_THREAD
JVMTI_ITERATION_ABORT
JVMTI_ITERATION_CONTINUE
JVMTI_ITERATION_IGNORE
JVMTI_JAVA_LANG_THREAD_STATE_BLOCKED
JVMTI_JAVA_LANG_THREAD_STATE_MASK
JVMTI_JAVA_LANG_THREAD_STATE_NEW
JVMTI_JAVA_LANG_THREAD_STATE_RUNNABLE
JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED
JVMTI_JAVA_LANG_THREAD_STATE_TIMED_WAITING
JVMTI_JAVA_LANG_THREAD_STATE_WAITING
JVMTI_JLOCATION_JVMBCI
JVMTI_JLOCATION_MACHINEPC
JVMTI_JLOCATION_OTHER
JVMTI_KIND_ALLOC_ALLOC_BUF
JVMTI_KIND_ALLOC_BUF
JVMTI_KIND_IN
JVMTI_KIND_IN_BUF
JVMTI_KIND_IN_PTR
JVMTI_KIND_OUT
JVMTI_KIND_OUT_BUF
JVMTI_PHASE_DEAD
JVMTI_PHASE_LIVE
JVMTI_PHASE_ONLOAD
JVMTI_PHASE_PRIMORDIAL
JVMTI_PHASE_START
JVMTI_PRIMITIVE_TYPE_BOOLEAN
JVMTI_PRIMITIVE_TYPE_BYTE
JVMTI_PRIMITIVE_TYPE_CHAR
JVMTI_PRIMITIVE_TYPE_DOUBLE
JVMTI_PRIMITIVE_TYPE_FLOAT
JVMTI_PRIMITIVE_TYPE_INT
JVMTI_PRIMITIVE_TYPE_LONG
JVMTI_PRIMITIVE_TYPE_SHORT
JVMTI_REFERENCE_ARRAY_ELEMENT
JVMTI_REFERENCE_CLASS
JVMTI_REFERENCE_CLASS_LOADER
JVMTI_REFERENCE_CONSTANT_POOL
JVMTI_REFERENCE_FIELD
JVMTI_REFERENCE_INTERFACE
JVMTI_REFERENCE_PROTECTION_DOMAIN
JVMTI_REFERENCE_SIGNERS
JVMTI_REFERENCE_STATIC_FIELD
JVMTI_RESOURCE_EXHAUSTED_JAVA_HEAP
JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR
JVMTI_RESOURCE_EXHAUSTED_THREADS
JVMTI_THREAD_MAX_PRIORITY
JVMTI_THREAD_MIN_PRIORITY
JVMTI_THREAD_NORM_PRIORITY
JVMTI_THREAD_STATE_ALIVE
JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER
JVMTI_THREAD_STATE_IN_NATIVE
JVMTI_THREAD_STATE_IN_OBJECT_WAIT
JVMTI_THREAD_STATE_INTERRUPTED
JVMTI_THREAD_STATE_PARKED
JVMTI_THREAD_STATE_RUNNABLE
JVMTI_THREAD_STATE_SLEEPING
JVMTI_THREAD_STATE_SUSPENDED
JVMTI_THREAD_STATE_TERMINATED
JVMTI_THREAD_STATE_VENDOR_1
JVMTI_THREAD_STATE_VENDOR_2
JVMTI_THREAD_STATE_VENDOR_3
JVMTI_THREAD_STATE_WAITING
JVMTI_THREAD_STATE_WAITING_INDEFINITELY
JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT
JVMTI_TIMER_ELAPSED
JVMTI_TIMER_TOTAL_CPU
JVMTI_TIMER_USER_CPU
JVMTI_TYPE_CCHAR
JVMTI_TYPE_CVOID
JVMTI_TYPE_JBOOLEAN
JVMTI_TYPE_JBYTE
JVMTI_TYPE_JCHAR
JVMTI_TYPE_JCLASS
JVMTI_TYPE_JDOUBLE
JVMTI_TYPE_JFIELDID
JVMTI_TYPE_JFLOAT
JVMTI_TYPE_JINT
JVMTI_TYPE_JLONG
JVMTI_TYPE_JMETHODID
JVMTI_TYPE_JNIENV
JVMTI_TYPE_JOBJECT
JVMTI_TYPE_JSHORT
JVMTI_TYPE_JTHREAD
JVMTI_TYPE_JVALUE
JVMTI_VERBOSE_CLASS
JVMTI_VERBOSE_GC
JVMTI_VERBOSE_JNI
JVMTI_VERBOSE_OTHER
JVMTI_VERSION_INTERFACE_JNI
JVMTI_VERSION_INTERFACE_JVMTI
JVMTI_VERSION_MASK_INTERFACE_TYPE
JVMTI_VERSION_MASK_MAJOR
JVMTI_VERSION_MASK_MICRO
JVMTI_VERSION_MASK_MINOR
JVMTI_VERSION_SHIFT_MAJOR
JVMTI_VERSION_SHIFT_MICRO
JVMTI_VERSION_SHIFT_MINOR
JVMTI_VISIT_ABORT
JVMTI_VISIT_OBJECTS

Change History

Last update: 09/05/07
Version: 1.2.1

The JVM TI specification is an evolving document with major, minor, and micro version numbers. A released version of the specification is uniquely identified by its major and minor version. The functions, events, and capabilities in this specification indicate a "Since" value which is the major and minor version in which it was introduced. The version of the specification implemented by the VM can be retrieved at runtime with the GetVersionNumber function.

Version
Date 		Changes
14 Nov 2002 | Converted to XML document.
14 Nov 2002 | Elided heap dump functions (for now) since what was there was wrong.
18 Nov 2002 | Added detail throughout.
18 Nov 2002 | Changed JVMTI_THREAD_STATUS_RUNNING to JVMTI_THREAD_STATUS_RUNNABLE.
19 Nov 2002 | Added AsyncGetStackTrace.
19 Nov 2002 | Added jframeID return to GetStackTrace.
19 Nov 2002 | Elided GetCurrentFrame and GetCallingFrame functions (for now) since what was there since they are redundant with GetStackTrace.
19 Nov 2002 | Elided ClearAllBreakpoints since it has always been redundant.
19 Nov 2002 | Added GetSystemProperties.
19 Nov 2002 | Changed the thread local storage functions to use jthread.
20 Nov 2002 | Added GetJLocationFormat.
22 Nov 2002 | Added events and introductory text.
22 Nov 2002 | Cross reference type and constant definitions.
24 Nov 2002 | Added DTD.
24 Nov 2002 | Added capabilities function section.
29 Nov 2002 | Assign capabilities to each function and event.
29 Nov 2002 | Add JNI interception functions.
30 Nov 2002 | Auto generate SetEventNotificationMode capabilities.
30 Nov 2002 | Add VMObjectAlloc event.
30 Nov 2002 | Add DynamicCodeGenerated event.
30 Nov 2002 | Add const to declarations.
30 Nov 2002 | Change method exit and frame pop to send on exception.
1 Dec 2002 | Add ForceGarbageCollection.
2 Dec 2002 | Redo Xrun section; clarify GetStackTrace and add example; Fix width problems; use "agent" consistently.
8 Dec 2002 | Remove previous start-up intro. Add JVM TI Environments section.
8 Dec 2002 | Add DisposeEnvironment.
9 Dec 2002 | Numerous minor updates.
15 Dec 2002 | Add heap profiling functions added: get/set annotation, iterate live objects/heap. Add heap profiling functions place holder added: heap roots. Heap profiling event added: object free. Heap profiling event redesigned: vm object allocation. Heap profiling event placeholders added: garbage collection start/finish. Native method bind event added.
19 Dec 2002 | Revamp suspend/resume functions. Add origin information with jvmdi tag. Misc fixes.
24 Dec 2002 | Add semantics to types.
27 Dec 2002 | Add local reference section. Autogenerate parameter descriptions from types.
28 Dec 2002 | Document that RunAgentThread sends threadStart.
29 Dec 2002 | Remove redundant local ref and dealloc warning. Convert GetRawMonitorName to allocated buffer. Add GenerateEvents.
30 Dec 2002 | Make raw monitors a type and rename to "jrawMonitorID".
1 Jan 2003 | Include origin information. Clean-up JVMDI issue references. Remove Deallocate warnings which are now automatically generated.
2 Jan 2003 | Fix representation issues for jthread.
3 Jan 2003 | Make capabilities buffered out to 64 bits - and do it automatically.
4 Jan 2003 | Make constants which are enumeration into enum types. Parameters now of enum type. Clean-up and index type section. Replace remaining datadef entities with callback.
7 Jan 2003 | Correct GenerateEvents description. More internal semantics work.
9 Jan 2003 | Replace previous GetSystemProperties with two functions which use allocated information instead fixed. Add SetSystemProperty. More internal semantics work.
12 Jan 2003 | Add varargs to end of SetEventNotificationMode.
20 Jan 2003 | Finish fixing spec to reflect that alloc sizes are jlong.
22 Jan 2003 | Allow NULL as RunAgentThread arg.
22 Jan 2003 | Fixed names to standardized naming convention Removed AsyncGetStackTrace.
29 Jan 2003 | Since we are using jthread, removed GetThread.
31 Jan 2003 | Change GetFieldName to allow NULLs like GetMethodName.
v40
29 Feb 2003 		Rewrite the introductory text, adding sections on start-up, environments and bytecode instrumentation. Change the command line arguments per EG discussions. Add an introduction to the capabilities section. Add the extension mechanism category and functions. Mark for deletion, but clarified anyhow, SuspendAllThreads. Rename IterateOverLiveObjects to IterateOverReachableObjects and change the text accordingly. Clarify IterateOverHeap. Clarify CompiledMethodLoad. Discuss prerequisite state for Calling Functions. Clarify SetAllocationHooks. Added issues ("To be resolved:") through-out. And so on...
v41
6 Mar 2003 		Remove struct from the call to GetOwnedMonitorInfo. Automatically generate most error documentation, remove (rather broken) hand written error doc. Better describe capability use (empty initial set). Add min value to jint params. Remove the capability can_access_thread_local_storage. Rename error JVMTI_ERROR_NOT_IMPLEMENTED to JVMTI_ERROR_MUST_POSSESS_CAPABILITY; same for *NOT_IMPLEMENTED. Description fixes.
v42
8 Mar 2003 		Rename GetClassSignature to GetClassName. Rename IterateOverClassObjects to IterateOverInstancesOfClass. Remove GetMaxStack (operand stack isn't used in JVM TI). Description fixes: define launch-time, remove native frame pop from PopFrame, and assorted clarifications.
v43
8 Mar 2003 		Fix minor editing problem.
v44
10 Mar 2003 		Add phase information. Remap (compact) event numbers.
v45
11 Mar 2003 		More phase information - allow "any". Elide raw monitor queries and events. Minor description fixes.
v46
12 Mar 2003 		Add GetPhase. Use "phase" through document. Elide GetRawMonitorName. Elide GetObjectMonitors.
v47
12 Mar 2003 		Fixes from link, XML, and spell checking. Auto-generate the callback structure.
v48
13 Mar 2003 		One character XML fix.
v49
13 Mar 2003 		Change function parameter names to be consistent with event parameters (fooBarBaz becomes foo_bar_baz).
v50
14 Mar 2003 		Fix broken link. Fix thread markers.
v51
14 Mar 2003 		Change constants so they are under 128 to workaround compiler problems.
v52
23 Mar 2003 		Overhaul capabilities. Separate GetStackTrace into GetStackTrace and GetStackFrames.
v54
8 Apr 2003 		Use depth instead of jframeID to reference frames. Remove the now irrelevant GetCurrentFrame, GetCallerFrame and GetStackFrames. Remove frame arg from events.
v55
9 Apr 2003 		Remove GetObjectWithAnnotation since tests show bufferred approach more efficient. Add missing annotation_count to GetObjectsWithAnnotations
v56
10 Apr 2003 		Remove confusing parenthetical statement in GetObjectsWithAnnotations
v58
13 Apr 2003 		Replace jclass/jmethodID representation of method with simply jmethodID; Pass JvmtiEnv* as first arg of every event; remove JNIEnv* where inappropriate. Replace can_access_frames with can_access_local_variables; remove from purely stack access. Use can_get_synthetic_attribute; fix description. Clarify that zero length arrays must be deallocated. Clarify RelinquishCapabilities. Generalize JVMTI_ERROR_VM_DEAD to JVMTI_ERROR_WRONG_PHASE.
v59
27 Apr 2003 		Remove lingering indirect references to OBSOLETE_METHOD_ID.
v60
4 May 2003 		Allow DestroyRawMonitor during OnLoad.
v61
7 May 2003 		Added not monitor owner error return to DestroyRawMonitor.
v62
13 May 2003 		Clarify semantics of raw monitors. Change flags on GetThreadStatus. GetClassLoader return NULL for the bootstrap class loader. Add GetClassName issue. Define local variable signature. Disallow zero in annotations array of GetObjectsWithAnnotations. Remove over specification in GetObjectsWithAnnotations. Elide SetAllocationHooks. Elide SuspendAllThreads.
v63
14 May 2003 		Define the data type jvmtiEventCallbacks. Zero length allocations return NULL. Keep SetAllocationHooks in JVMDI, but remove from JVM TI. Add JVMTI_THREAD_STATUS_FLAG_INTERRUPTED.
v64
15 May 2003 		Better wording, per review.
v65
15 May 2003 		First Alpha. Make jmethodID and jfieldID unique, jclass not used.
v66
27 May 2003 		Fix minor XSLT errors.
v67
13 June 2003 		Undo making jfieldID unique (jmethodID still is).
v68
17 June 2003 		Changes per June 11th Expert Group meeting -- Overhaul Heap functionality: single callback, remove GetHeapRoots, add reachable iterators, and rename "annotation" to "tag". NULL thread parameter on most functions is current thread. Add timers. Remove ForceExit. Add GetEnvironmentLocalStorage. Add verbose flag and event. Add AddToBootstrapClassLoaderSearch. Update ClassFileLoadHook.
v69
18 June 2003 		Clean up issues sections. Rename GetClassName back to GetClassSignature and fix description. Add generic signature to GetClassSignature, GetFieldSignature, GetMethodSignature, and GetLocalVariableTable. Elide EstimateCostOfCapabilities. Clarify that the system property functions operate on the VM view of system properties. Clarify Agent_OnLoad. Remove "const" from JNIEnv* in events. Add metadata accessors.
v70
18 June 2003 		Add start_depth to GetStackTrace. Move system properties to a new category. Add GetObjectSize. Remove "X" from command line flags. XML, HTML, and spell check corrections.
v71
19 June 2003 		Fix JVMTI_HEAP_ROOT_THREAD to be 6. Make each synopsis match the function name. Fix unclear wording.
v72
26 June 2003 		SetThreadLocalStorage and SetEnvironmentLocalStorage should allow value to be set to NULL. NotifyFramePop, GetFrameLocationm and all the local variable operations needed to have their wording about frames fixed. Grammar and clarity need to be fixed throughout. Capitalization and puntuation need to be consistent. Need micro version number and masks for accessing major, minor, and micro. The error code lists should indicate which must be returned by an implementation. The command line properties should be visible in the properties functions. Disallow popping from the current thread. Allow implementations to return opaque frame error when they cannot pop. The NativeMethodBind event should be sent during any phase. The DynamicCodeGenerated event should be sent during any phase. The following functions should be allowed to operate before VMInit: Set/GetEnvironmentLocalStorage GetMethodDeclaringClass GetClassSignature GetClassModifiers IsInterface IsArrayClass GetMethodName GetMethodModifiers GetMaxLocals GetArgumentsSize GetLineNumberTable GetMethodLocation IsMethodNative IsMethodSynthetic. Other changes (to XSL): Argument description should show asterisk after not before pointers. NotifyFramePop, GetFrameLocationm and all the local variable operations should hsve the NO_MORE_FRAMES error added. Not alive threads should have a different error return than invalid thread.
v73
7 July 2003 		VerboseOutput event was missing message parameter. Minor fix-ups.
v74
14 July 2003 		Technical Publications Department corrections. Allow thread and environment local storage to be set to NULL.
v75
23 July 2003 		Use new Agent_OnLoad rather than overloaded JVM_OnLoad. Add JNICALL to callbacks (XSL). Document JNICALL requirement for both events and callbacks (XSL). Restrict RedefineClasses to methods and attributes. Elide the VerboseOutput event. VMObjectAlloc: restrict when event is sent and remove method parameter. Finish loose ends from Tech Pubs edit.
v76
24 July 2003 		Change ClassFileLoadHook event to send the class instead of a boolean of redefine.
v77
24 July 2003 		XML fixes. Minor text clarifications and corrections.
v78
24 July 2003 		Remove GetExceptionHandlerTable and GetThrownExceptions from JVM TI. Clarify that stack frames are JVM Spec frames. Split can_get_source_info into can_get_source_file_name, can_get_line_numbers, and can_get_source_debug_extension. PopFrame cannot have a native calling method. Removed incorrect statement in GetClassloaderClasses (see http://java.sun.com/docs/books/vmspec/2nd-edition/html/ConstantPool.doc.html#79383).
v79
24 July 2003 		XML and text fixes. Move stack frame description into Stack Frame category.
v80
26 July 2003 		Allow NULL (means bootstrap loader) for GetClassloaderClasses. Add new heap reference kinds for references from classes. Add timer information struct and query functions. Add AvailableProcessors. Rename GetOtherThreadCpuTime to GetThreadCpuTime. Explicitly add JVMTI_ERROR_INVALID_THREAD and JVMTI_ERROR_THREAD_NOT_ALIVE to SetEventNotification mode. Add initial thread to the VM_INIT event. Remove platform assumptions from AddToBootstrapClassLoaderSearch.
v81
26 July 2003 		Grammar and clarity changes per review.
v82
27 July 2003 		More grammar and clarity changes per review. Add Agent_OnUnload.
v83
28 July 2003 		Change return type of Agent_OnUnload to void.
v84
28 July 2003 		Rename JVMTI_REFERENCE_ARRAY to JVMTI_REFERENCE_ARRAY_ELEMENT.
v85
28 July 2003 		Steal java.lang.Runtime.availableProcessors() wording for AvailableProcessors(). Guarantee that zero will never be an event ID. Remove some issues which are no longer issues. Per review, rename and more completely document the timer information functions.
v86
29 July 2003 		Non-spec visible change to XML controlled implementation: SetThreadLocalStorage must run in VM mode.
0.1.87
5 August 2003 		Add GetErrorName. Add varargs warning to jvmtiExtensionEvent. Remove "const" on the jvmtiEnv* of jvmtiExtensionEvent. Remove unused can_get_exception_info capability. Pass jvmtiEnv* and JNIEnv* to the jvmtiStartFunction. Fix jvmtiExtensionFunctionInfo.func declared type. Extension function returns error code. Use new version numbering.
0.2.88
5 August 2003 		Remove the ClassUnload event.
0.2.89
8 August 2003 		Heap reference iterator callbacks return an enum that allows outgoing object references to be ignored. Allow JNIEnv as a param type to extension events/functions.
0.2.90
15 August 2003 		Fix a typo.
0.2.91
2 September 2003 		Remove all metadata functions: GetClassMetadata, GetFieldMetadata, and GetMethodMetadata.
0.2.92
1 October 2003 		Mark the functions Allocate. Deallocate, RawMonitor*, SetEnvironmentLocalStorage, and GetEnvironmentLocalStorage as safe for use in heap callbacks and GC events.
0.2.93
24 November 2003 		Add pass through opaque user data pointer to heap iterate functions and callbacks. In the CompiledMethodUnload event, send the code address. Add GarbageCollectionOccurred event. Add constant pool reference kind. Mark the functions CreateRawMonitor and DestroyRawMonitor as safe for use in heap callbacks and GC events. Clarify: VMDeath, GetCurrentThreadCpuTimerInfo, GetThreadCpuTimerInfo, IterateOverReachableObjects, IterateOverObjectsReachableFromObject, GetTime and JVMTI_ERROR_NULL_POINTER. Add missing errors to: GenerateEvents and AddToBootstrapClassLoaderSearch. Fix description of ClassFileLoadHook name parameter. In heap callbacks and GC/ObjectFree events, specify that only explicitly allowed functions can be called. Allow GetCurrentThreadCpuTimerInfo, GetCurrentThreadCpuTime, GetTimerInfo, and GetTime during callback. Allow calling SetTag/GetTag during the onload phase. SetEventNotificationMode, add: error attempted inappropriate thread level control. Remove jvmtiExceptionHandlerEntry. Fix handling of native methods on the stack -- location_ptr param of GetFrameLocation, remove JVMTI_ERROR_OPAQUE_FRAME from GetFrameLocation, jvmtiFrameInfo.location, and jlocation. Remove typo (from JVMPI) implying that the MonitorWaited event is sent on sleep.
0.2.94
25 November 2003 		Clarifications and typos.
0.2.95
3 December 2003 		Allow NULL user_data in heap iterators.
0.2.97
28 January 2004 		Add GetThreadState, deprecate GetThreadStatus.
0.2.98
29 January 2004 		INVALID_SLOT and TYPE_MISMATCH errors should be optional.
0.2.102
12 February 2004 		Remove MonitorContendedExit. Added JNIEnv parameter to VMObjectAlloc. Clarified definition of class_tag and referrer_index parameters to heap callbacks.
0.2.103
16 Febuary 2004 		Document JAVA_TOOL_OPTIONS.
0.2.105
17 Febuary 2004 		Divide start phase into primordial and start. Add VMStart event Change phase associations of functions and events.
0.3.6
18 Febuary 2004 		Elide deprecated GetThreadStatus. Bump minor version, subtract 100 from micro version
0.3.7
18 Febuary 2004 		Document that timer nanosecond values are unsigned. Clarify text having to do with native methods.
0.3.8
19 Febuary 2004 		Fix typos. Remove elided deprecated GetThreadStatus.
0.3.9
23 Febuary 2004 		Require NotifyFramePop to act on suspended threads.
0.3.10
24 Febuary 2004 		Add capabilities (can_redefine_any_class and can_generate_all_class_hook_events) and an error (JVMTI_ERROR_UNMODIFIABLE_CLASS) which allow some classes to be unmodifiable.
0.3.11
28 Febuary 2004 		Add JVMTI_ERROR_MUST_POSSESS_CAPABILITY to SetEventNotificationMode.
0.3.12
8 March 2004 		Clarified CompiledMethodUnload so that it is clear the event may be posted after the class has been unloaded.
0.3.13
5 March 2004 		Change the size parameter of VMObjectAlloc to jlong to match GetObjectSize.
0.3.14
13 March 2004 		Added guideline for the use of the JNI FindClass function in event callback functions.
0.3.15
15 March 2004 		Add GetAllStackTraces and GetThreadListStackTraces.
0.3.16
19 March 2004 		ClassLoad and ClassPrepare events can be posted during start phase.
0.3.17
25 March 2004 		Add JVMTI_ERROR_NATIVE_METHOD to GetLineNumberTable, GetLocalVariableTable, GetMaxLocals, GetArgumentsSize, GetMethodLocation, GetBytecodes.
0.3.18
29 March 2004 		Return the timer kind in the timer information structure.
0.3.19
31 March 2004 		Spec clarifications: JVMTI_THREAD_STATE_IN_NATIVE might not include JNI or JVM TI. ForceGarbageCollection does not run finalizers. The context of the specification is the Java platform. Warn about early instrumentation.
0.3.20
1 April 2004 		Refinements to the above clarifications and Clarify that an error returned by Agent_OnLoad terminates the VM.
0.3.21
1 April 2004 		Array class creation does not generate a class load event.
0.3.22
7 April 2004 		Align thread state hierarchy more closely with java.lang.Thread.State.
0.3.23
12 April 2004 		Clarify the documentation of thread state.
0.3.24
19 April 2004 		Remove GarbageCollectionOccurred event -- can be done by agent.
0.3.25
22 April 2004 		Define "command-line option".
0.3.26
29 April 2004 		Describe the intended use of bytecode instrumentation. Fix description of extension event first parameter.
0.3.27
30 April 2004 		Clarification and typos.
0.3.28
18 May 2004 		Remove DataDumpRequest event.
0.3.29
18 May 2004 		Clarify RawMonitorWait with zero timeout. Clarify thread state after RunAgentThread.
0.3.30
24 May 2004 		Clean-up: fix bad/old links, etc.
0.3.31
30 May 2004 		Clarifications including: All character strings are modified UTF-8. Agent thread visibiity. Meaning of obsolete method version. Thread invoking heap callbacks,
1.0.32
1 June 2004 		Bump major.minor version numbers to "1.0".
1.0.33
2 June 2004 		Clarify interaction between ForceGarbageCollection and ObjectFree.
1.0.34
6 June 2004 		Restrict AddToBootstrapClassLoaderSearch and SetSystemProperty to the OnLoad phase only.
1.0.35
11 June 2004 		Fix typo in SetTag.
1.0.36
18 June 2004 		Fix trademarks. Add missing parameter in example GetThreadState usage.
1.0.37
4 August 2004 		Copyright updates.
1.0.38
5 November 2004 		Add missing function table layout. Add missing description of C++ member function format of functions. Clarify that name in CFLH can be NULL. Released as part of J2SETM 5.0.
1.1.47
24 April 2005 		Bump major.minor version numbers to "1.1". Add ForceEarlyReturn* functions. Add GetOwnedMonitorStackDepthInfo function. Add GetCurrentThread function. Add "since" version marker. Add AddToSystemClassLoaderSearch. Allow AddToBootstrapClassLoaderSearch be used in live phase. Fix historic rubbish in the descriptions of the heap_object_callback parameter of IterateOverHeap and IterateOverInstancesOfClass functions; disallow NULL for this parameter. Clarify, correct and make consistent: wording about current thread, opaque frames and insufficient number of frames in PopFrame. Consistently use "current frame" rather than "topmost". Clarify the JVMTI_ERROR_TYPE_MISMATCH errors in GetLocal* and SetLocal* by making them compatible with those in ForceEarlyReturn*. Many other clarifications and wording clean ups.
1.1.48
25 April 2005 		Add GetConstantPool. Switch references to the first edition of the VM Spec, to the seconds edition.
1.1.49
26 April 2005 		Clarify minor/major version order in GetConstantPool.
1.1.50
26 April 2005 		Add SetNativeMethodPrefix and SetNativeMethodPrefixes. Reassign GetOwnedMonitorStackDepthInfo to position 153. Break out Class Loader Search in its own documentation category. Deal with overly long lines in XML source.
1.1.51
29 April 2005 		Allow agents be started in the live phase. Added paragraph about deploying agents.
1.1.52
30 April 2005 		Add specification description to SetNativeMethodPrefix(es). Better define the conditions on GetConstantPool.
1.1.53
30 April 2005 		Break out the GetClassVersionNumber function from GetConstantPool. Clean-up the references to the VM Spec.
1.1.54
1 May 2005 		Allow SetNativeMethodPrefix(es) in any phase. Add clarifications about the impact of redefinition on GetConstantPool.
1.1.56
2 May 2005 		Various clarifications to SetNativeMethodPrefix(es).
1.1.57
2 May 2005 		Add missing performance warning to the method entry event.
1.1.58
5 May 2005 		Remove internal JVMDI support.
1.1.59
8 May 2005 		Add RetransformClasses. Revamp the bytecode instrumentation documentation. Change IsMethodObsolete to no longer require the can_redefine_classes capability.
1.1.63
11 May 2005 		Clarifications for retransformation.
1.1.64
11 May 2005 		Clarifications for retransformation, per review. Lock "retransformation (in)capable" at class load enable time.
1.1.67
4 June 2005 		Add new heap functionity which supports reporting primitive values, allows setting the referrer tag, and has more powerful filtering: FollowReferences, IterateThroughHeap, and their associated callbacks, structs, enums, and constants.
1.1.68
4 June 2005 		Clarification.
1.1.69
6 June 2005 		FollowReferences, IterateThroughHeap: Put callbacks in a struct; Add missing error codes; reduce bits in the visit control flags.
1.1.70
14 June 2005 		More on new heap functionity: spec clean-up per review.
1.1.71
15 June 2005 		More on new heap functionity: Rename old heap section to Heap (1.0).
1.1.72
21 June 2005 		Fix typos.
1.1.73
27 June 2005 		Make referrer info structure a union.
1.1.74
9 September 2005 		In new heap functions: Add missing superclass reference kind. Use a single scheme for computing field indexes. Remove outdated references to struct based referrer info.
1.1.75
12 September 2005 		Don't callback during FollowReferences on frivolous java.lang.Object superclass.
1.1.76
13 September 2005 		In string primitive callback, length now Unicode length. In array and string primitive callbacks, value now "const". Note possible compiler impacts on setting JNI function table.
1.1.77
13 September 2005 		GetClassVersionNumbers() and GetConstantPool() should return error on array or primitive class.
1.1.78
14 September 2005 		Grammar fixes.
1.1.79
26 September 2005 		Add IsModifiableClass query.
1.1.81
9 February 2006 		Add referrer_class_tag parameter to jvmtiHeapReferenceCallback.
1.1.82
13 February 2006 		Doc fixes: update can_redefine_any_class to include retransform. Clarify that exception events cover all Throwables. In GetStackTrace, no test is done for start_depth too big if start_depth is zero, Clarify fields reported in Primitive Field Callback -- static vs instance. Repair confusing names of heap types, including callback names. Require consistent usage of stack depth in the face of thread launch methods. Note incompatibility of JVM TI memory management with other systems.
1.1.85
14 February 2006 		Fix typos and missing renames.
1.1.86
13 March 2006 		Clarify that jmethodIDs and jfieldIDs can be saved. Clarify that Iterate Over Instances Of Class includes subclasses.
1.1.87
14 March 2006 		Better phrasing.
1.1.88
16 March 2006 		Match the referrer_index for static fields in Object Reference Callback with the Reference Implementation (and all other known implementations); that is, make it match the definition for instance fields. In GetThreadListStackTraces, add JVMTI_ERROR_INVALID_THREAD to cover an invalid thread in the list; and specify that not started threads return empty stacks.
1.1.89
17 March 2006 		Typo.
1.1.90
25 March 2006 		Typo.
1.1.91
6 April 2006 		Remove restrictions on AddToBootstrapClassLoaderSearch and AddToSystemClassLoaderSearch.
1.1.93
1 May 2006 		Changed spec to return -1 for monitor stack depth for the implementation which can not determine stack depth.
1.1.94
3 May 2006 		Corrections for readability and accuracy courtesy of Alan Pratt of IBM. List the object relationships reported in FollowReferences.
1.1.95
5 May 2006 		Clarify the object relationships reported in FollowReferences.
1.1.98
28 June 2006 		Clarify DisposeEnvironment; add warning. Fix typos in SetLocalXXX "retrieve" => "set". Clarify that native method prefixes must remain set while used. Clarify that exactly one Agent_OnXXX is called per agent. Clarify that library loading is independent from start-up. Remove ambiguous reference to Agent_OnLoad in the Agent_OnUnload spec.
1.1.99
31 July 2006 		Clarify the interaction between functions and exceptions. Clarify and give examples of field indices. Remove confusing "That is" sentence from MonitorWait and MonitorWaited events. Update links to point to Java 6.
1.1.102
6 August 2006 		Add ResourceExhaustedEvent.


Kerberos Requirements

Kerberos Version 5 is used for both the authentication and secure communication aspects of the client and server applications developed in this tutorial. The reader is assumed to already be familiar with Kerberos. See the Kerberos reference documentation.

The JAAS framework, and the Kerberos mechanism required by the Java GSS-API methods, are built into the version 1.4 and later JREs from all vendors. (JAAS was available as a separately-downloadable optional package starting in version 1.3.) The Kerberos LoginModule required for the JAAS authentication in this tutorial may not be available in all vendors' JREs. We will be using the LoginModule for Kerberos provided in the JRE from Sun Microsystems (versions 1.4 and later).

In order to run the sample programs, you will need access to a Kerberos installation. As described in the following sections, you may also need a krb5.conf Kerberos configuration file and an indication as to where that file is located.

As with all Kerberos installations, a Kerberos Key Distribution Center (KDC) is required. It needs to contain the user name and password you will use to be authenticated to Kerberos. Note: A KDC implementation is part of a Kerberos installation and not a part of the JRE v 1.4 and later.

As with most Kerberos installations, a Kerberos configuration file krb5.conf is consulted to determine such things as the default realm and KDC. If you are using a Kerberos implementation such as that from Microsoft for Windows 2000, which does not include a krb5.conf file, you will either need to create one or use system properties as described in Setting Properties to Indicate the Default Realm and KDC.

Setting Properties to Indicate the Default Realm and KDC

Typically, the default realm and the KDC for that realm are indicated in the Kerberos krb5.conf configuration file. However, if you like, you can instead specify these values by setting the following system properties to indicate the realm and KDC, respectively:

java.security.krb5.realm
java.security.krb5.kdc

If you set one of these properties you must set them both.

Also note that if you set these properties, then no cross-realm authentication is possible unless a krb5.conf file is also provided from which the additional information required for cross-realm authentication may be obtained.

If you set values for these properties, then they override the default realm and KDC values specified in krb5.conf (if such a file is found). The krb5.conf file is still consulted if values for items other than the default realm and KDC are needed. If no krb5.conf file is found, then the default values used for these items are implementation-specific.

Locating the krb5.conf Configuration File

The essential Kerberos configuration information is the default realm and the default KDC. As shown in Setting Properties to Indicate the Default Realm and KDC, if you set properties to indicate these values, they are not obtained from a krb5.conf configuration file.

If these properties do not have values set, or if other Kerberos configuration information is needed, an attempt is made to find the required information in a krb5.conf file. The algorithm to locate the krb5.conf file is the following:

  • If the system property java.security.krb5.conf is set, its value is assumed to specify the path and file name.

  • If that system property value is not set, then the configuration file is looked for in the directory

    • <java-home>\lib\security (Windows)
    • <java-home>/lib/security (Solaris and Linux)

    Here <java-home> refers to the directory where the JRE was installed. For example, if you have J2SE 5.0 installed on Solaris in a directory named /j2sdk1.5, the directory in which the configuration file is looked for is:

    /j2sdk1.5/jre/lib/security

  • If the file is still not found, then an attempt is made to locate it as follows:

    • /etc/krb5/krb5.conf (Solaris)
    • c:\winnt\krb5.ini (Windows)
    • /etc/krb5.conf (Linux)

  • If the file is still not found, and the configuration information being searched for is not the default realm and KDC, then implementation-specific defaults are used. If, on the other hand, the configuration information being searched for is the default realm and KDC because they weren't specified in system properties, and the krb5.conf file is not found either, then an exception is thrown.

Naming Conventions for Realm Names and Hostnames

By convention, all Kerberos realm names are uppercase and all DNS hostname and domain names are lowercase. On the Windows 2000 platform, domains are also Kerberos realms; however, the realm name is always the uppercase version of the domain name.

Hostnames are case insensitive and by convention they are all lowercase. They must resolve to the same hostname on the client and server by their respective naming services.

However, in the Kerberos database hostnames are case sensitive. In all host-based Kerberos service principals in the KDC, hostnames are case-sensitive. The hostnames used in the Kerberos service principal names must exactly match the hostnames returned by the naming service. For example, if the naming service returns a fully qualified lowercased DNS hostname, such as "raven.sun.com", then the administrator must use the same fully qualified lowercased DNS hostname when creating host-based principal names in the KDC: "host/raven.sun.com".

Cross-Realm Authentication

In cross-realm authentication, a principal in one realm can authenticate to principals in another realm.

In Kerberos, cross-realm authentication is implemented by sharing an encryption key between two realms. The KDCs in two different realms share a special cross-realm secret; this secret is used to prove identity when crossing the boundary between realms.

The key that is shared is the Ticket Granting Service principal's key. Here's a typical Ticket Granting Service principal for a single realm:

ktbtgt/ACME.COM@ACME.COM
In cross realm authentication, two principals are created on each participating realm. For two realms, ENG.EAST.ACME.COM and SALES.WEST.ACME.COM, these principals would be:
krbtgt/ENG.EAST.ACME.COM@SALES.WEST.ACME.COM
krbtgt/SALES.WEST.ACME.COM@ENG.EAST.ACME.COM
These principals, known as remote Ticket Granting Server principals, must be created on both realms.

On Windows 2000 KDC, the krbtgt account is created automatically when a Windows 2000 domain is created. This account cannot be deleted and renamed.

Types of Realms

When you set up multiple realms, you must decide if your realm configuration will be "hierarchical" (one realm is a superset of the other) or "direct" (the mapping between realms must be defined).

How to Set Up Cross-Realm Authentication

In transitive cross-realm authentication you can define a path of realms connected via cross-realm secrets and use this path to traverse realms until you get credentials in the desired realm.

The [capaths] section in the Kerberos configuration file defines a series of authentication paths used for transitive cross-realm authentication. Clients use [capaths] to determine the correct path for doing transitive cross-realm authentication. Application servers check the [capaths] section to determine if a cross-realm authentication path is valid.

For example, to set-up cross realm authentication between ENG.EAST.ACME.COM and SALES.WEST.ACME.COM, krb5.conf should include the following entry:

[capaths]
    ENG.EAST.ACME.COM = {
        SALES.WEST.ACME.COM = .
    }

    SALES.WEST.ACME.COM = {
         ENG.EAST.ACME.COM = .
    }
On Windows 2000, you must set up a trust relationship between the two realms. For configuration details, refer to Step-by-Step Guide to Kerberos 5 (krb5 1.0) Interoperability on Microsoft's Web site.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Windows Look and Feel Keyboard Navigation Hiding

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Keyboard Navigation Hiding

One of the new features that was introduced in Windows 2000 has been a display property which will hide the keyboard mnemonic for a menu item or a dialog control until the Alt key is pressed. In other words, all the underlined characters which represent an Alt key combination to invoke that menu or control will not be drawn until the user indicates the intention to invoke a command with the keyboard rather than the mouse. The result of this behavior is to provide an interface which is not visually cluttered with underlined characters for people who choose to navigate the user interface with the mouse.

The keyboard navigation hiding feature will be automatically enabled on Windows 2000 if the application uses the Windows look and feel and the "Hide keyboard navigation indicators until I use the Alt key" property is enabled in the Windows 2000 "Display Properties" control panel applet.

Implementation Details

These details will be of use to developers who are extending look and feels. The keyboard navigation hiding feature will automatically be enabled when a Windows Look and Feel Java application is run on Windows 2000.

When the WindowsLookAndFeel is instantiated, it will read the DesktopProperty "win.menu.keyboardCuesOn". This value is stored in the UIManager and can be referenced using the key: "Button.isMnemonicHidingEnabled". The static methods setMnemonicHidden and isMnemonicHidden in WindowsLookAndFeelprovide access to this value.

Hiding the mnemonics in the menus

The existing BasicMenuItemUI.paintMenuItem() method is responsible for rendering the background, text, icon and mnemonic of a menu item. A new protected method, paintText() was extracted from paintMenuItem(), which is consistent in name and signature to a similar method in the BasicButtonUI hierarchy.

The paintText() methods are overloaded in WindowsMenuItemUI and WindowsMenuUI. The body of the overloaded paintText method checks the isMnemonicEnabled flag in the WindowsLookAndFeel class to determine if the mnemonic should be hidden and then appropriately renders the text.

Hiding the mnemonic in controls

BasicButtonUI already defined a protected method paintText. The WindowsButtonUI and similar classes overloaded this method in much the same manner. A new class was introduced, WindowsGraphicsUtils, to consolidate all the paintText methods. This was done because the Windows...UI classes don't follow the same inheritance hierarchy as the Basic..UI classes.

A new RootPaneUI delegate called WindowsRootPaneUI was created for the Windows look and feel. This class had an action registered to reset the mnemonic hidden bit and repaint the ui when the Alt key was pressed.

New API

All these methods were added as result of implementing this feature. These methods will only have value to developers who wish to extend or create a Look and Feel.

New method for BasicMenuItemUI:

    /**
     * Renders the text of the current menu item.
     *
     * @param g graphics context
     * @param menuItem menu item to render
     * @param textRect bounding rectangle for rendering the text
     * @param text String to render
     * @since 1.4
     */
     protected void paintText(Graphics g, JMenuItem menuItem, Rectangle textRect, String text)

New class WindowsRootPaneUI:

    /**
     * Windows implementation of RootPaneUI. One WindowsRootPaneUI
     * object is shared between all JRootPane instances.
     *
     * @version 1.1 08/16/00
     * @author Mark Davidson
     * @since 1.4
     */
     public class WindowsRootPaneUI extends BasicRootPaneUI

New class WindowsGraphicsUtils:

    /**
     * A collection of static utility methods used for rendering the
     * Windows look and feel.
     *
     * @Version 1.1 08/16/00
     * @author Mark Davidson
     * @since 1.4
     */
     public class WindowsGraphicsUtils

New methods for WindowsLookAndFeel:

    /**
     * Sets the state of the hide mnemonic flag. This flag is used by the
     * component UI delegates to determine if the mnemonic should be rendered.
     * This method is a non operation if the underlying operating system
     * does not support the mnemonic hiding feature.
     *
     * @param hide true if mnemonics should be hidden
     * @since 1.4
     */
     public static void setMnemonicHidden(boolean hide)

    /**
     * Gets the state of the hide mnemonic flag. This only has meaning
     * if this feature is supported by the underlying OS.
     *
     * @return true if mnemonics are hidden, otherwise, false
     * @see #setMnemonicHidden
     * @since 1.4
     */
     public static Boolean isMnemonicHidden()

    /**
     * Gets the state of the flag which indicates if the old Windows
     * look and feel should be rendered. This flag is used by the
     * component UI delegates as a hint to determine which style the component
     * should be rendered.
     *
     * @return true if Windows 95 and Windows NT 4 look and feel should
     *     be rendered
     * @since 1.4
     */
     public static Boolean isClassicWindows()
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.security.auth.module.KeyStoreLoginModule (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.module.KeyStoreLoginModule

No usage of com.sun.security.auth.module.KeyStoreLoginModule
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Mozilla Browser Keystores

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Browser Keystores

Overview

Java Plug-in and Java Web Start support browser keystore in Internet Explorer and Mozilla; certificates and keys in browser keystores are used for the following purpose:

  • Signature signing verification
  • HTTPS server authentication
  • HTTPS client authentication

If the certificates and keys are on the smart cards, they are also recognized by Java Plug-in and Java Web Start if exposed in the browser keystore.

By default, browser keystore support is enabled; users may configure the support through the Advanced tab in the Java Control Panel.

Internet Explorer keystore support

On Windows, browser keystore is supported through Internet Explorer. Certificates and keys in Internet Explorer are automatically recognized by Java Plug-in and Java Web Start when Java applications and applets are deployed on Windows.

This feature is supported only with Internet Explorer 5.0 or higher.

Mozilla keystore support

On Linux and Solaris, browser keystore is supported through Mozilla. Certificates and keys in Mozilla are recognized by Java Plug-in and Java Web Start when Java applications and applets are deployed on Linux and Solaris.

Support for Mozilla keystore requires a Mozilla library called JSS (Network Security Services for Java). By default, JSS is a separate component that does not ship with Mozilla -- it is the responsibility of the deployer to install JSS with Mozilla. Java Plug-in and Java Web Start will enable the Mozilla keystore support appropriately after JSS is deployed.

This feature is supported only with Mozilla 1.4 or higher and JSS 3.2 or higher, assuming both Mozilla and JSS are compiled using the same compiler on the same platform.

Installing JSS with Mozilla

Windows

  1. Create jss directory under Mozilla's installed directory.
  2. Copy JSS JAR file into the jss directory.
  3. Copy JSS native library DLL into Mozilla's installed directory.

Linux/Solaris

  1. Create jss directory under Mozilla's installed directory.
  2. Copy JSS JAR file into the jss directory.
  3. Copy JSS native library .so into Mozilla's installed directory.
  4. Set environment variable MOZILLA_HOME to Mozilla's installed directory in Mozilla's launch script.
  5. Change environment variable LD_LIBRARY_PATH to include Mozilla's installed directory in Mozilla's launch script.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


keytool-Key and Certificate Management Tool

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

keytool - Key and Certificate Management Tool

Manages a keystore (database) of cryptographic keys, X.509 certificate chains, and trusted certificates.

SYNOPSIS

keytool [ commands ]

The keytool command interface has changed in Java SE 6. See the Changes Section for a detailed description. Note that previously defined commands are still supported.

DESCRIPTION

keytool is a key and certificate management utility. It allows users to administer their own public/private key pairs and associated certificates for use in self-authentication (where the user authenticates himself/herself to other users/services) or data integrity and authentication services, using digital signatures. It also allows users to cache the public keys (in the form of certificates) of their communicating peers.

A certificate is a digitally signed statement from one entity (person, company, etc.), saying that the public key (and some other information) of some other entity has a particular value. (See Certificates.) When data is digitally signed, the signature can be verified to check the data integrity and authenticity. Integrity means that the data has not been modified or tampered with, and authenticity means the data indeed comes from whoever claims to have created and signed it.

keytool also enables users to administer secret keys used in symmetric encryption/decryption (e.g. DES).

keytool stores the keys and certificates in a keystore.

COMMAND AND OPTION NOTES

The various commands and their options are listed and described below. Note:

  • All command and option names are preceded by a minus sign (-).
  • The options for each command may be provided in any order.
  • All items not italicized or in braces or square brackets are required to appear as is.
  • Braces surrounding an option generally signify that a default value will be used if the option is not specified on the command line. Braces are also used around the -v, -rfc, and -J options, which only have meaning if they appear on the command line (that is, they don't have any "default" values other than not existing).
  • Brackets surrounding an option signify that the user is prompted for the value(s) if the option is not specified on the command line. (For a -keypass option, if you do not specify the option on the command line, keytool will first attempt to use the keystore password to recover the private/secret key, and if this fails, will then prompt you for the private/secret key password.)
  • Items in italics (option values) represent the actual values that must be supplied. For example, here is the format of the -printcert command:
      keytool -printcert {-file cert_file} {-v}

    When specifying a -printcert command, replace cert_file with the actual file name, as in:

      keytool -printcert -file VScert.cer
  • Option values must be quoted if they contain a blank (space).
  • The -help command is the default. Thus, the command line
      keytool

    is equivalent to

      keytool -help

Option Defaults

Below are the defaults for various option values.

-alias "mykey"

-keyalg
    "DSA" (when using -genkeypair)
    "DES" (when using -genseckey)

-keysize
    2048 (when using -genkeypair and -keyalg is "RSA")
    1024 (when using -genkeypair and -keyalg is "DSA")
    256 (when using -genkeypair and -keyalg is "EC")
    56 (when using -genseckey and -keyalg is "DES")
    168 (when using -genseckey and -keyalg is "DESede")

-validity 90

-keystore the file named .keystore in the user's home directory

-storetype the value of the "keystore.type" property in the security properties file,
           which is returned by the static getDefaultType method in
           java.security.KeyStore

-file stdin if reading, stdout if writing

-protected false

In generating a public/private key pair, the signature algorithm (-sigalg option) is derived from the algorithm of the underlying private key:

  • If the underlying private key is of type "DSA", the -sigalg option defaults to "SHA1withDSA"
  • If the underlying private key is of type "RSA", the -sigalg option defaults to "SHA256withRSA".
  • If the underlying private key is of type "EC", the -sigalg option defaults to "SHA256withECDSA".

Please consult the Java Cryptography Architecture API Specification & Reference for a full list of -keyalg and -sigalg you can choose from.

Common Options

The -v option can appear for all commands except -help. If it appears, it signifies "verbose" mode; more information will be provided in the output.

There is also a -Jjavaoption option that may appear for any command. If it appears, the specified javaoption string is passed through directly to the Java interpreter. This option should not contain any spaces. It is useful for adjusting the execution environment or memory usage. For a list of possible interpreter options, type java -h or java -X at the command line.

These options may appear for all commands operating on a keystore:

-storetype storetype

This qualifier specifies the type of keystore to be instantiated.

-keystore keystore

The keystore location.

If the JKS storetype is used and a keystore file does not yet exist, then certain keytool commands may result in a new keystore file being created. For example, if keytool -genkeypair is invoked and the -keystore option is not specified, the default keystore file named .keystore in the user's home directory will be created if it does not already exist. Similarly, if the -keystore ks_file option is specified but ks_file does not exist, then it will be created

Note that the input stream from the -keystore option is passed to the KeyStore.load method. If NONE is specified as the URL, then a null stream is passed to the KeyStore.load method. NONE should be specified if the KeyStore is not file-based (for example, if it resides on a hardware token device).

-storepass[:env|:file] argument

The password which is used to protect the integrity of the keystore.

If the modifier env or file is not specified, then the password has the value argument, which must be at least 6 characters long. Otherwise, the password is retrieved as follows:

  • env: Retrieve the password from the environment variable named argument
  • file: Retrieve the password from the file named argument

Note: All other options that require passwords, such as -keypass, -srckeypass, -destkeypass -srcstorepass, and -deststorepass, accept the env and file modifiers. (Remember to separate the password option and the modifier with a colon, (:).)

The password must be provided to all commands that access the keystore contents. For such commands, if a -storepass option is not provided at the command line, the user is prompted for it.

When retrieving information from the keystore, the password is optional; if no password is given, the integrity of the retrieved information cannot be checked and a warning is displayed.

-providerName provider_name

Used to identify a cryptographic service provider's name when listed in the security properties file.

-providerClass provider_class_name

Used to specify the name of cryptographic service provider's master class file when the service provider is not listed in the security properties file.

-providerArg provider_arg

Used in conjunction with -providerClass. Represents an optional string input argument for the constructor of provider_class_name.

-protected

Either true or false. This value should be specified as true if a password must be given via a protected authentication path such as a dedicated PIN reader.

Note: Since there are two keystores involved in -importkeystore command, two options, namely, -srcprotected and -destprotected are provided for the source keystore and the destination keystore respectively.

-ext {name{:critical}{=value}}

Denotes an X.509 certificate extension. The option can be used in -genkeypair and -gencert to embed extensions into the certificate generated, or in -certreq to show what extensions are requested in the certificate request. The option can appear multiple times. name can be a supported extension name (see below) or an arbitrary OID number. value, if provided, denotes the parameter for the extension; if omitted, denotes the default value (if defined) of the extension or the extension requires no parameter. The :critical modifier, if provided, means the extension's isCritical attribute is true; otherwise, false. You may use :c in place of :critical.

Currently keytool supports these named extensions (case-insensitive):

Name | Value
BC or BasicConstraints | The full form: "ca:{true|false}[,pathlen:<len>]"; or, <len>, a shorthand for "ca:true,pathlen:<len>"; or omitted, means "ca:true"
KU or KeyUsage | usage(,usage)*, usage can be one of digitalSignature, nonRepudiation (contentCommitment), keyEncipherment, dataEncipherment, keyAgreement, keyCertSign, cRLSign, encipherOnly, decipherOnly. Usage can be abbreviated with the first few letters (say, dig for digitalSignature) or in camel-case style (say, dS for digitalSignature, cRLS for cRLSign), as long as no ambiguity is found. Usage is case-insensitive.
EKU or ExtendedkeyUsage | usage(,usage)*, usage can be one of anyExtendedKeyUsage, serverAuth, clientAuth, codeSigning, emailProtection, timeStamping, OCSPSigning, or any OID string. Named usage can be abbreviated with the first few letters or in camel-case style, as long as no ambiguity is found. Usage is case-insensitive.
SAN or SubjectAlternativeName | type:value(,type:value)*, type can be EMAIL, URI, DNS, IP, or OID, value is the string format value for the type.
IAN or IssuerAlternativeName | same as SubjectAlternativeName
SIA or SubjectInfoAccess | method:location-type:location-value (,method:location-type:location-value)*, method can be "timeStamping", "caRepository" or any OID. location-type and location-value can be any type:value supported by the SubjectAlternativeName extension.
AIA or AuthorityInfoAccess | same as SubjectInfoAccess. method can be "ocsp","caIssuers" or any OID.

For name as OID, value is the HEX dumped DER encoding of the extnValue for the extension excluding the OCTET STRING type and length bytes. Any extra character other than standard HEX numbers (0-9, a-f, A-F) are ignored in the HEX string. Therefore, both "01:02:03:04" and "01020304" are accepted as identical values. If there's no value, the extension has an empty value field then.

A special name 'honored', used in -gencert only, denotes how the extensions included in the certificate request should be honored. The value for this name is a comma separated list of "all" (all requested extensions are honored), "name{:[critical|non-critical]}" (the named extension is honored, but using a different isCritical attribute) and "-name" (used with all, denotes an exception). Requested extensions are not honored by default.

If, besides the -ext honored option, another named or OID -ext option is provided, this extension will be added to those already honored. However, if this name (or OID) also appears in the honored value, its value and criticality overrides the one in the request.

The subjectKeyIdentifier extension is always created. For non self-signed certificates, the authorityKeyIdentifier is always created.

Note: Users should be aware that some combinations of extensions (and other certificate fields) may not conform to the Internet standard. See Warning Regarding Certificate Conformance for details.

COMMANDS

Creating or Adding Data to the Keystore

-gencert {-rfc} {-infile infile} {-outfile outfile} {-alias alias} {-sigalg sigalg} {-dname dname} {-startdate startdate {-ext ext}* {-validity valDays} [-keypass keypass] {-keystore keystore} [-storepass storepass] {-storetype storetype} {-providername provider_name} {-providerClass provider_class_name {-providerArg provider_arg}} {-v} {-protected} {-Jjavaoption}

Generates a certificate as a response to a certificate request file (which can be created by the keytool -certreq command). The command reads the request from infile (if omitted, from the standard input), signs it using alias's private key, and output the X.509 certificate into outfile (if omitted, to the standard output). If -rfc is specified, output format is BASE64-encoded PEM; otherwise, a binary DER is created.

sigalg specifies the algorithm that should be used to sign the certificate. startdate is the start time/date that the certificate is valid. valDays tells the number of days for which the certificate should be considered valid.

If dname is provided, it's used as the subject of the generated certificate. Otherwise, the one from the certificate request is used.

ext shows what X.509 extensions will be embedded in the certificate. Read Common Options for the grammar of -ext.

The -gencert command enables you to create certificate chains. The following example creates a certificate, e1, that contains three certificates in its certificate chain.

The following commands creates four key pairs named ca, ca1, ca2, and e1:

keytool -alias ca -dname CN=CA -genkeypair
keytool -alias ca1 -dname CN=CA -genkeypair
keytool -alias ca2 -dname CN=CA -genkeypair
keytool -alias e1 -dname CN=E1 -genkeypair

The following two commands create a chain of signed certificates; ca signs ca1 and ca1 signs ca2, all of which are self-issued:

keytool -alias ca1 -certreq | keytool -alias ca -gencert -ext san=dns:ca1 | keytool -alias ca1 -importcert
keytool -alias ca2 -certreq | $KT -alias ca1 -gencert -ext san=dns:ca2 | $KT -alias ca2 -importcert

The following command creates the certificate e1 and stores it in the file e1.cert, which is signed by ca2. As a result, e1 should contain ca, ca1, and ca2 in its certificate chain:

keytool -alias e1 -certreq | keytool -alias ca2 -gencert > e1.cert
-genkeypair {-alias alias} {-keyalg keyalg} {-keysize keysize} {-sigalg sigalg} [-dname dname] [-keypass keypass] {-startdate value} {-ext ext}* {-validity valDays} {-storetype storetype} {-keystore keystore} [-storepass storepass] {-providerClass provider_class_name {-providerArg provider_arg}} {-v} {-protected} {-Jjavaoption}

Generates a key pair (a public key and associated private key). Wraps the public key into an X.509 v3 self-signed certificate, which is stored as a single-element certificate chain. This certificate chain and the private key are stored in a new keystore entry identified by alias.

keyalg specifies the algorithm to be used to generate the key pair, and keysize specifies the size of each key to be generated. sigalg specifies the algorithm that should be used to sign the self-signed certificate; this algorithm must be compatible with keyalg.

dname specifies the X.500 Distinguished Name to be associated with alias, and is used as the issuer and subject fields in the self-signed certificate. If no distinguished name is provided at the command line, the user will be prompted for one.

keypass is a password used to protect the private key of the generated key pair. If no password is provided, the user is prompted for it. If you press RETURN at the prompt, the key password is set to the same password as that used for the keystore. keypass must be at least 6 characters long.

startdate specifies the issue time of the certificate, also known as the "Not Before" value of the X.509 certificate's Validity field.

The option value can be set in one of these two forms:

  1. ([+-]nnn[ymdHMS])+
  2. [yyyy/mm/dd] [HH:MM:SS]

With the first form, the issue time is shifted by the specified value from the current time. The value is a concatenation of a sequence of sub values. Inside each sub value, the plus sign ("+") means shifting forward, and the minus sign ("-") means shifting backward. The time to be shifted is nnn units of years, months, days, hours, minutes, or seconds (denoted by a single character of "y", "m", "d", "H", "M", or "S" respectively). The exact value of the issue time is calculated using the java.util.GregorianCalendar.add(int field, int amount) method on each sub value, from left to right. For example, by specifying "-startdate -1y+1m-1d", the issue time will be:

   Calendar c = new GregorianCalendar();
   c.add(Calendar.YEAR, -1);
   c.add(Calendar.MONTH, 1);
   c.add(Calendar.DATE, -1);
   return c.getTime()

With the second form, the user sets the exact issue time in two parts, year/month/day and hour:minute:second (using the local time zone). The user may provide only one part, which means the other part is the same as the current date (or time). User must provide the exact number of digits as shown in the format definition (padding with 0 if shorter). When both the date and time are provided, there is one (and only one) space character between the two parts. The hour should always be provided in 24 hour format.

When the option is not provided, the start date is the current time. The option can be provided at most once.

valDays specifies the number of days (starting at the date specified by -startdate, or the current date if -startdate is not specified) for which the certificate should be considered valid.

This command was named -genkey in previous releases. This old name is still supported in this release and will be supported in future releases, but for clarity the new name, -genkeypair, is preferred going forward.

-genseckey {-alias alias} {-keyalg keyalg} {-keysize keysize} [-keypass keypass] {-storetype storetype} {-keystore keystore} [-storepass storepass] {-providerClass provider_class_name {-providerArg provider_arg}} {-v} {-protected} {-Jjavaoption}

Generates a secret key and stores it in a new KeyStore.SecretKeyEntry identified by alias.

keyalg specifies the algorithm to be used to generate the secret key, and keysize specifies the size of the key to be generated. keypass is a password used to protect the secret key. If no password is provided, the user is prompted for it. If you press RETURN at the prompt, the key password is set to the same password as that used for the keystore. keypass must be at least 6 characters long.

-importcert {-alias alias} {-file cert_file} [-keypass keypass] {-noprompt} {-trustcacerts} {-storetype storetype} {-keystore keystore} [-storepass storepass] {-providerName provider_name} {-providerClass provider_class_name {-providerArg provider_arg}} {-v} {-protected} {-Jjavaoption}

Reads the certificate or certificate chain (where the latter is supplied in a PKCS#7 formatted reply or a sequence of X.509 certificates) from the file cert_file, and stores it in the keystore entry identified by alias. If no file is given, the certificate or certificate chain is read from stdin.

keytool can import X.509 v1, v2, and v3 certificates, and PKCS#7 formatted certificate chains consisting of certificates of that type. The data to be imported must be provided either in binary encoding format, or in printable encoding format (also known as Base64 encoding) as defined by the Internet RFC 1421 standard. In the latter case, the encoding must be bounded at the beginning by a string that starts with "-----BEGIN", and bounded at the end by a string that starts with "-----END".

You import a certificate for two reasons:

  1. to add it to the list of trusted certificates, or
  2. to import a certificate reply received from a CA as the result of submitting a Certificate Signing Request (see the -certreq command) to that CA.

Which type of import is intended is indicated by the value of the -alias option:

  1. If the alias does not point to a key entry, then keytool assumes you are adding a trusted certificate entry. In this case, the alias should not already exist in the keystore. If the alias does already exist, then keytool outputs an error, since there is already a trusted certificate for that alias, and does not import the certificate.

  2. If the alias points to a key entry, then keytool assumes you are importing a certificate reply.

Importing a New Trusted Certificate

Before adding the certificate to the keystore, keytool tries to verify it by attempting to construct a chain of trust from that certificate to a self-signed certificate (belonging to a root CA), using trusted certificates that are already available in the keystore.

If the -trustcacerts option has been specified, additional certificates are considered for the chain of trust, namely the certificates in a file named "cacerts".

If keytool fails to establish a trust path from the certificate to be imported up to a self-signed certificate (either from the keystore or the "cacerts" file), the certificate information is printed out, and the user is prompted to verify it, e.g., by comparing the displayed certificate fingerprints with the fingerprints obtained from some other (trusted) source of information, which might be the certificate owner himself/herself. Be very careful to ensure the certificate is valid prior to importing it as a "trusted" certificate! -- see WARNING Regarding Importing Trusted Certificates. The user then has the option of aborting the import operation. If the -noprompt option is given, however, there will be no interaction with the user.

Importing a Certificate Reply

When importing a certificate reply, the certificate reply is validated using trusted certificates from the keystore, and optionally using the certificates configured in the "cacerts" keystore file (if the -trustcacerts option was specified).

The methods of determining whether the certificate reply is trusted are described in the following:

  • If the reply is a single X.509 certificate, keytool attempts to establish a trust chain, starting at the certificate reply and ending at a self-signed certificate (belonging to a root CA). The certificate reply and the hierarchy of certificates used to authenticate the certificate reply form the new certificate chain of alias. If a trust chain cannot be established, the certificate reply is not imported. In this case, keytool does not print out the certificate and prompt the user to verify it, because it is very hard (if not impossible) for a user to determine the authenticity of the certificate reply.
  • If the reply is a PKCS#7 formatted certificate chain or a sequence of X.509 certificates, the chain is ordered with the user certificate first followed by zero or more CA certificates. If the chain ends with a self-signed root CA certificate and -trustcacerts option was specified, keytool will attempt to match it with any of the trusted certificates in the keystore or the "cacerts" keystore file. If the chain does not end with a self-signed root CA certificate and the -trustcacerts option was specified, keytool will try to find one from the trusted certificates in the keystore or the "cacerts" keystore file and add it to the end of the chain. If the certificate is not found and -noprompt option is not specified, the information of the last certificate in the chain is printed out, and the user is prompted to verify it.

If the public key in the certificate reply matches the user's public key already stored with under alias, the old certificate chain is replaced with the new certificate chain in the reply. The old chain can only be replaced if a valid keypass, the password used to protect the private key of the entry, is supplied. If no password is provided, and the private key password is different from the keystore password, the user is prompted for it.

This command was named -import in previous releases. This old name is still supported in this release and will be supported in future releases, but for clarify the new name, -importcert, is preferred going forward.

-importkeystore -srckeystore srckeystore -destkeystore destkeystore {-srcstoretype srcstoretype} {-deststoretype deststoretype} [-srcstorepass srcstorepass] [-deststorepass deststorepass] {-srcprotected} {-destprotected} {-srcalias srcalias {-destalias destalias} [-srckeypass srckeypass] [-destkeypass destkeypass] } {-noprompt} {-srcProviderName src_provider_name} {-destProviderName dest_provider_name} {-providerClass provider_class_name {-providerArg provider_arg}} {-v} {-protected} {-Jjavaoption}

Imports a single entry or all entries from a source keystore to a destination keystore.

When the srcalias option is provided, the command imports the single entry identified by the alias to the destination keystore. If a destination alias is not provided with destalias, then srcalias is used as the destination alias. If the source entry is protected by a password, srckeypass will be used to recover the entry. If srckeypass is not provided, then keytool will attempt to use srcstorepass to recover the entry. If srcstorepass is either not provided or is incorrect, the user will be prompted for a password. The destination entry will be protected using destkeypass. If destkeypass is not provided, the destination entry will be protected with the source entry password.

If the srcalias option is not provided, then all entries in the source keystore are imported into the destination keystore. Each destination entry will be stored under the alias from the source entry. If the source entry is protected by a password, srcstorepass will be used to recover the entry. If srcstorepass is either not provided or is incorrect, the user will be prompted for a password. If a source keystore entry type is not supported in the destination keystore, or if an error occurs while storing an entry into the destination keystore, the user will be prompted whether to skip the entry and continue, or to quit. The destination entry will be protected with the source entry password.

If the destination alias already exists in the destination keystore, the user is prompted to either overwrite the entry, or to create a new entry under a different alias name.

Note that if -noprompt is provided, the user will not be prompted for a new destination alias. Existing entries will automatically be overwritten with the destination alias name. Finally, entries that can not be imported are automatically skipped and a warning is output.

-printcertreq {-file file}

Prints the content of a PKCS #10 format certificate request, which can be generated by the keytool -certreq command. The command reads the request from file; if omitted, from the standard input.

Exporting Data

-certreq {-alias alias} {-dname dname} {-sigalg sigalg} {-file certreq_file} [-keypass keypass] {-storetype storetype} {-keystore keystore} [-storepass storepass] {-providerName provider_name} {-providerClass provider_class_name {-providerArg provider_arg}} {-v} {-protected} {-Jjavaoption}

Generates a Certificate Signing Request (CSR), using the PKCS#10 format.

A CSR is intended to be sent to a certificate authority (CA). The CA will authenticate the certificate requestor (usually off-line) and will return a certificate or certificate chain, used to replace the existing certificate chain (which initially consists of a self-signed certificate) in the keystore.

The private key associated with alias is used to create the PKCS#10 certificate request. In order to access the private key, the appropriate password must be provided, since private keys are protected in the keystore with a password. If keypass is not provided at the command line, and is different from the password used to protect the integrity of the keystore, the user is prompted for it. If dname is provided, it's used as the subject in the CSR. Otherwise, the X.500 Distinguished Name associated with alias is used.

sigalg specifies the algorithm that should be used to sign the CSR.

The CSR is stored in the file certreq_file. If no file is given, the CSR is output to stdout.

Use the importcert command to import the response from the CA.

-exportcert {-alias alias} {-file cert_file} {-storetype storetype} {-keystore keystore} [-storepass storepass] {-providerName provider_name} {-providerClass provider_class_name {-providerArg provider_arg}} {-rfc} {-v} {-protected} {-Jjavaoption}

Reads (from the keystore) the certificate associated with alias, and stores it in the file cert_file.

If no file is given, the certificate is output to stdout.

The certificate is by default output in binary encoding, but will instead be output in the printable encoding format, as defined by the Internet RFC 1421 standard, if the -rfc option is specified.

If alias refers to a trusted certificate, that certificate is output. Otherwise, alias refers to a key entry with an associated certificate chain. In that case, the first certificate in the chain is returned. This certificate authenticates the public key of the entity addressed by alias.

This command was named -export in previous releases. This old name is still supported in this release and will be supported in future releases, but for clarify the new name, -exportcert, is preferred going forward.

Displaying Data

-list {-alias alias} {-storetype storetype} {-keystore keystore} [-storepass storepass] {-providerName provider_name} {-providerClass provider_class_name {-providerArg provider_arg}} {-v | -rfc} {-protected} {-Jjavaoption}

Prints (to stdout) the contents of the keystore entry identified by alias. If no alias is specified, the contents of the entire keystore are printed.

This command by default prints the SHA1 fingerprint of a certificate. If the -v option is specified, the certificate is printed in human-readable format, with additional information such as the owner, issuer, serial number, and any extensions. If the -rfc option is specified, certificate contents are printed using the printable encoding format, as defined by the Internet RFC 1421 standard

You cannot specify both -v and -rfc.

-printcert {-file cert_file | -sslserver host[:port]} {-jarfile JAR_file {-rfc} {-v} {-Jjavaoption}

Reads the certificate from the file cert_file, the SSL server located at host:port, or the signed JAR file JAR_file (with the option -jarfile and prints its contents in a human-readable format. When no port is specified, the standard HTTPS port 443 is assumed. Note that -sslserver and -file options cannot be provided at the same time. Otherwise, an error is reported. If neither option is given, the certificate is read from stdin.

If -rfc is specified, keytool prints the certificate in PEM mode as defined by the Internet RFC 1421 standard.

If the certificate is read from a file or stdin, it may be either binary encoded or in printable encoding format, as defined by the Internet RFC 1421 standard

If the SSL server is behind a firewall, -J-Dhttps.proxyHost=proxyhost and -J-Dhttps.proxyPort=proxyport can be specified on the command line for proxy tunneling. See the JSSE Reference Guide for more information.

Note: This option can be used independently of a keystore.

-printcrl -file crl_ {-v}

Reads the certificate revocation list (CRL) from the file crl_file.

A Certificate Revocation List (CRL) is a list of digital certificates which have been revoked by the Certificate Authority (CA) that issued them. The CA generates crl_file.

Note: This option can be used independently of a keystore.

Managing the Keystore

-storepasswd [-new new_storepass] {-storetype storetype} {-keystore keystore} [-storepass storepass] {-providerName provider_name} {-providerClass provider_class_name {-providerArg provider_arg}} {-v} {-Jjavaoption}

Changes the password used to protect the integrity of the keystore contents. The new password is new_storepass, which must be at least 6 characters long.

-keypasswd {-alias alias} [-keypass old_keypass] [-new new_keypass] {-storetype storetype} {-keystore keystore} [-storepass storepass] {-providerName provider_name} {-providerClass provider_class_name {-providerArg provider_arg}} {-v} {-Jjavaoption}

Changes the password under which the private/secret key identified by alias is protected, from old_keypass to new_keypass, which must be at least 6 characters long.

If the -keypass option is not provided at the command line, and the key password is different from the keystore password, the user is prompted for it.

If the -new option is not provided at the command line, the user is prompted for it.

-delete [-alias alias] {-storetype storetype} {-keystore keystore} [-storepass storepass] {-providerName provider_name} {-providerClass provider_class_name {-providerArg provider_arg}} {-v} {-protected} {-Jjavaoption}

Deletes from the keystore the entry identified by alias. The user is prompted for the alias, if no alias is provided at the command line.

-changealias {-alias alias} [-destalias destalias] [-keypass keypass] {-storetype storetype} {-keystore keystore} [-storepass storepass] {-providerName provider_name} {-providerClass provider_class_name {-providerArg provider_arg}} {-v} {-protected} {-Jjavaoption}

Move an existing keystore entry from the specified alias to a new alias, destalias. If no destination alias is provided, the command will prompt for one. If the original entry is protected with an entry password, the password can be supplied via the "-keypass" option. If no key password is provided, the storepass (if given) will be attempted first. If that attempt fails, the user will be prompted for a password.

Getting Help

-help

Lists the basic commands and their options.

For more information about a specific command, enter the following, where command_name is the name of the command:

keytool -command_name -help

EXAMPLES

Suppose you want to create a keystore for managing your public/private key pair and certificates from entities you trust.

Generating Your Key Pair

The first thing you need to do is create a keystore and generate the key pair. You could use a command such as the following:

    keytool -genkeypair -dname "cn=Mark Jones, ou=Java, o=Oracle, c=US"
      -alias business -keypass kpi135 -keystore C:\working\mykeystore
      -storepass ab987c -validity 180

(Please note: This must be typed as a single line. Multiple lines are used in the examples just for legibility purposes.)

This command creates the keystore named "mykeystore" in the "C:\working" directory (assuming it doesn't already exist), and assigns it the password "ab987c". It generates a public/private key pair for the entity whose "distinguished name" has a common name of "Mark Jones", organizational unit of "Java", organization of "Oracle" and two-letter country code of "US". It uses the default "DSA" key generation algorithm to create the keys, both 1024 bits long.

It creates a self-signed certificate (using the default "SHA1withDSA" signature algorithm) that includes the public key and the distinguished name information. This certificate will be valid for 180 days, and is associated with the private key in a keystore entry referred to by the alias "business". The private key is assigned the password "kpi135".

The command could be significantly shorter if option defaults were accepted. As a matter of fact, no options are required; defaults are used for unspecified options that have default values, and you are prompted for any required values. Thus, you could simply have the following:

    keytool -genkeypair

In this case, a keystore entry with alias "mykey" is created, with a newly-generated key pair and a certificate that is valid for 90 days. This entry is placed in the keystore named ".keystore" in your home directory. (The keystore is created if it doesn't already exist.) You will be prompted for the distinguished name information, the keystore password, and the private key password.

The rest of the examples assume you executed the -genkeypair command without options specified, and that you responded to the prompts with values equal to those given in the first -genkeypair command, above (a private key password of "kpi135", etc.)

Requesting a Signed Certificate from a Certification Authority

So far all we've got is a self-signed certificate. A certificate is more likely to be trusted by others if it is signed by a Certification Authority (CA). To get such a signature, you first generate a Certificate Signing Request (CSR), via the following:

    keytool -certreq -file MarkJ.csr

This creates a CSR (for the entity identified by the default alias "mykey") and puts the request in the file named "MarkJ.csr". Submit this file to a CA, such as VeriSign, Inc. The CA will authenticate you, the requestor (usually off-line), and then will return a certificate, signed by them, authenticating your public key. (In some cases, they will actually return a chain of certificates, each one authenticating the public key of the signer of the previous certificate in the chain.)

Importing a Certificate for the CA

You need to replace your self-signed certificate with a certificate chain, where each certificate in the chain authenticates the public key of the signer of the previous certificate in the chain, up to a "root" CA.

Before you import the certificate reply from a CA, you need one or more "trusted certificates" in your keystore or in the cacerts keystore file (which is described in importcert command):

  • If the certificate reply is a certificate chain, you just need the top certificate of the chain (that is, the "root" CA certificate authenticating that CA's public key).
  • If the certificate reply is a single certificate, you need a certificate for the issuing CA (the one that signed it), and if that certificate is not self-signed, you need a certificate for its signer, and so on, up to a self-signed "root" CA certificate.

The "cacerts" keystore file ships with several VeriSign root CA certificates, so you probably won't need to import a VeriSign certificate as a trusted certificate in your keystore. But if you request a signed certificate from a different CA, and a certificate authenticating that CA's public key hasn't been added to "cacerts", you will need to import a certificate from the CA as a "trusted certificate".

A certificate from a CA is usually either self-signed, or signed by another CA (in which case you also need a certificate authenticating that CA's public key). Suppose company ABC, Inc., is a CA, and you obtain a file named "ABCCA.cer" that is purportedly a self-signed certificate from ABC, authenticating that CA's public key.

Be very careful to ensure the certificate is valid prior to importing it as a "trusted" certificate! View it first (using the keytool -printcert command, or the keytool -importcert command without the -noprompt option), and make sure that the displayed certificate fingerprint(s) match the expected ones. You can call the person who sent the certificate, and compare the fingerprint(s) that you see with the ones that they show (or that a secure public key repository shows). Only if the fingerprints are equal is it guaranteed that the certificate has not been replaced in transit with somebody else's (for example, an attacker's) certificate. If such an attack took place, and you did not check the certificate before you imported it, you would end up trusting anything the attacker has signed.

If you trust that the certificate is valid, then you can add it to your keystore via the following:

    keytool -importcert -alias abc -file ABCCA.cer

This creates a "trusted certificate" entry in the keystore, with the data from the file "ABCCA.cer", and assigns the alias "abc" to the entry.

Importing the Certificate Reply from the CA

Once you've imported a certificate authenticating the public key of the CA you submitted your certificate signing request to (or there's already such a certificate in the "cacerts" file), you can import the certificate reply and thereby replace your self-signed certificate with a certificate chain. This chain is the one returned by the CA in response to your request (if the CA reply is a chain), or one constructed (if the CA reply is a single certificate) using the certificate reply and trusted certificates that are already available in the keystore where you import the reply or in the "cacerts" keystore file.

For example, suppose you sent your certificate signing request to VeriSign. You can then import the reply via the following, which assumes the returned certificate is named "VSMarkJ.cer":

    keytool -importcert -trustcacerts -file VSMarkJ.cer

Exporting a Certificate Authenticating Your Public Key

Suppose you have used the jarsigner tool to sign a Java ARchive (JAR) file. Clients that want to use the file will want to authenticate your signature.

One way they can do this is by first importing your public key certificate into their keystore as a "trusted" entry. You can export the certificate and supply it to your clients. As an example, you can copy your certificate to a file named MJ.cer via the following, assuming the entry is aliased by "mykey":

    keytool -exportcert -alias mykey -file MJ.cer

Given that certificate, and the signed JAR file, a client can use the jarsigner tool to authenticate your signature.

Importing Keystore

The command "importkeystore" is used to import an entire keystore into another keystore, which means all entries from the source keystore, including keys and certificates, are all imported to the destination keystore within a single command. You can use this command to import entries from a different type of keystore. During the import, all new entries in the destination keystore will have the same alias names and protection passwords (for secret keys and private keys). If keytool has difficulties recover the private keys or secret keys from the source keystore, it will prompt you for a password. If it detects alias duplication, it will ask you for a new one, you can specify a new alias or simply allow keytool to overwrite the existing one.

For example, to import entries from a normal JKS type keystore key.jks into a PKCS #11 type hardware based keystore, you can use the command:

keytool -importkeystore
    -srckeystore key.jks -destkeystore NONE
    -srcstoretype JKS -deststoretype PKCS11
    -srcstorepass changeit -deststorepass topsecret

The importkeystore command can also be used to import a single entry from a source keystore to a destination keystore. In this case, besides the options you see in the above example, you need to specify the alias you want to import. With the srcalias option given, you can also specify the destination alias name in the command line, as well as protection password for a secret/private key and the destination protection password you want. In this way, you can issue a keytool command that will never ask you a question. This makes it very convenient to include a keytool command into a script file, like this:

keytool -importkeystore
    -srckeystore key.jks -destkeystore NONE
    -srcstoretype JKS -deststoretype PKCS11
    -srcstorepass changeit -deststorepass topsecret
    -srcalias myprivatekey -destalias myoldprivatekey
    -srckeypass oldkeypass -destkeypass mynewkeypass
    -noprompt

Generating Certificates for a Typical SSL Server

The following are keytool commands to generate keypairs and certificates for three entities, namely, Root CA (root), Intermediate CA (ca), and SSL server (server). Ensure that you store all the certificates in the same keystore. In these examples, it is recommended that you specify RSA as the key algorithm.

keytool -genkeypair -keystore root.jks -alias root -ext bc:c
keytool -genkeypair -keystore ca.jks -alias ca -ext bc:c
keytool -genkeypair -keystore server.jks -alias server

keytool -keystore root.jks -alias root -exportcert -rfc > root.pem

keytool -storepass <storepass> -keystore ca.jks -certreq -alias ca | keytool -storepass <storepass> -keystore root.jks -gencert -alias root -ext BC=0 -rfc > ca.pem
keytool -keystore ca.jks -importcert -alias ca -file ca.pem

keytool -storepass <storepass> -keystore server.jks -certreq -alias server | keytool -storepass <storepass> -keystore ca.jks -gencert -alias ca -ext ku:c=dig,kE -rfc > server.pem
cat root.pem ca.pem server.pem | keytool -keystore server.jks -importcert -alias server

TERMINOLOGY and WARNINGS

KeyStore

A keystore is a storage facility for cryptographic keys and certificates.

  • KeyStore Entries

    Keystores may have different types of entries. The two most applicable entry types for keytool include:

    1. key entries - each holds very sensitive cryptographic key information, which is stored in a protected format to prevent unauthorized access. Typically, a key stored in this type of entry is a secret key, or a private key accompanied by the certificate "chain" for the corresponding public key. The keytool can handle both types of entries, while the jarsigner tool only handle the latter type of entry, that is private keys and their associated certificate chains.
    2. trusted certificate entries - each contains a single public key certificate belonging to another party. It is called a "trusted certificate" because the keystore owner trusts that the public key in the certificate indeed belongs to the identity identified by the "subject" (owner) of the certificate. The issuer of the certificate vouches for this, by signing the certificate.

  • KeyStore Aliases

    All keystore entries (key and trusted certificate entries) are accessed via unique aliases.

    An alias is specified when you add an entity to the keystore using the -genseckey command to generate a secret key, -genkeypair command to generate a key pair (public and private key) or the -importcert command to add a certificate or certificate chain to the list of trusted certificates. Subsequent keytool commands must use this same alias to refer to the entity.

    For example, suppose you use the alias duke to generate a new public/private key pair and wrap the public key into a self-signed certificate (see Certificate Chains) via the following command:

        keytool -genkeypair -alias duke -keypass dukekeypasswd

    This specifies an initial password of "dukekeypasswd" required by subsequent commands to access the private key associated with the alias duke. If you later want to change duke's private key password, you use a command like the following:

        keytool -keypasswd -alias duke -keypass dukekeypasswd -new newpass

    This changes the password from "dukekeypasswd" to "newpass".

    Please note: A password should not actually be specified on a command line or in a script unless it is for testing purposes, or you are on a secure system. If you don't specify a required password option on a command line, you will be prompted for it.

  • KeyStore Implementation

    The KeyStore class provided in the java.security package supplies well-defined interfaces to access and modify the information in a keystore. It is possible for there to be multiple different concrete implementations, where each implementation is that for a particular type of keystore.

    Currently, two command-line tools (keytool and jarsigner) and a GUI-based tool named Policy Tool make use of keystore implementations. Since KeyStore is publicly available, users can write additional security applications that use it.

    There is a built-in default implementation, provided by Oracle. It implements the keystore as a file, utilizing a proprietary keystore type (format) named "JKS". It protects each private key with its individual password, and also protects the integrity of the entire keystore with a (possibly different) password.

    Keystore implementations are provider-based. More specifically, the application interfaces supplied by KeyStore are implemented in terms of a "Service Provider Interface" (SPI). That is, there is a corresponding abstract KeystoreSpi class, also in the java.security package, which defines the Service Provider Interface methods that "providers" must implement. (The term "provider" refers to a package or a set of packages that supply a concrete implementation of a subset of services that can be accessed by the Java Security API.) Thus, to provide a keystore implementation, clients must implement a "provider" and supply a KeystoreSpi subclass implementation, as described in How to Implement a Provider for the Java Cryptography Architecture.

    Applications can choose different types of keystore implementations from different providers, using the "getInstance" factory method supplied in the KeyStore class. A keystore type defines the storage and data format of the keystore information, and the algorithms used to protect private/secret keys in the keystore and the integrity of the keystore itself. Keystore implementations of different types are not compatible.

    keytool works on any file-based keystore implementation. (It treats the keystore location that is passed to it at the command line as a filename and converts it to a FileInputStream, from which it loads the keystore information.) The jarsigner and policytool tools, on the other hand, can read a keystore from any location that can be specified using a URL.

    For keytool and jarsigner, you can specify a keystore type at the command line, via the -storetype option. For Policy Tool, you can specify a keystore type via the "Keystore" menu.

    If you don't explicitly specify a keystore type, the tools choose a keystore implementation based simply on the value of the keystore.type property specified in the security properties file. The security properties file is called java.security, and it resides in the security properties directory, java.home\lib\security, where java.home is the runtime environment's directory (the jre directory in the SDK or the top-level directory of the Java 2 Runtime Environment).

    Each tool gets the keystore.type value and then examines all the currently-installed providers until it finds one that implements keystores of that type. It then uses the keystore implementation from that provider.

    The KeyStore class defines a static method named getDefaultType that lets applications and applets retrieve the value of the keystore.type property. The following line of code creates an instance of the default keystore type (as specified in the keystore.type property):

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

    The default keystore type is "jks" (the proprietary type of the keystore implementation provided by Oracle). This is specified by the following line in the security properties file:

        keystore.type=jks

    To have the tools utilize a keystore implementation other than the default, you can change that line to specify a different keystore type.

    For example, if you have a provider package that supplies a keystore implementation for a keystore type called "pkcs12", change the line to

        keystore.type=pkcs12

    Note: case doesn't matter in keystore type designations. For example, "JKS" would be considered the same as "jks".

Certificate

A certificate (also known as a public-key certificate) is a digitally signed statement from one entity (the issuer), saying that the public key (and some other information) of another entity (the subject) has some specific value.

  • Certificate Terms

    Public Keys

    These are numbers associated with a particular entity, and are intended to be known to everyone who needs to have trusted interactions with that entity. Public keys are used to verify signatures.

    Digitally Signed

    If some data is digitally signed it has been stored with the "identity" of an entity, and a signature that proves that entity knows about the data. The data is rendered unforgeable by signing with the entity's private key.

    Identity

    A known way of addressing an entity. In some systems the identity is the public key, in others it can be anything from a Unix UID to an Email address to an X.509 Distinguished Name.

    Signature

    A signature is computed over some data using the private key of an entity (the signer, which in the case of a certificate is also known as the issuer).

    Private Keys

    These are numbers, each of which is supposed to be known only to the particular entity whose private key it is (that is, it's supposed to be kept secret). Private and public keys exist in pairs in all public key cryptography systems (also referred to as "public key crypto systems"). In a typical public key crypto system, such as DSA, a private key corresponds to exactly one public key. Private keys are used to compute signatures.

    Entity

    An entity is a person, organization, program, computer, business, bank, or something else you are trusting to some degree.

    Basically, public key cryptography requires access to users' public keys. In a large-scale networked environment it is impossible to guarantee that prior relationships between communicating entities have been established or that a trusted repository exists with all used public keys. Certificates were invented as a solution to this public key distribution problem. Now a Certification Authority (CA) can act as a trusted third party. CAs are entities (for example, businesses) that are trusted to sign (issue) certificates for other entities. It is assumed that CAs will only create valid and reliable certificates, as they are bound by legal agreements. There are many public Certification Authorities, such as VeriSign, Thawte, Entrust, and so on. You can also run your own Certification Authority using products such as Microsoft Certificate Server or the Entrust CA product for your organization.

    Using keytool, it is possible to display, import, and export certificates. It is also possible to generate self-signed certificates.

    keytool currently handles X.509 certificates.

  • X.509 Certificates

    The X.509 standard defines what information can go into a certificate, and describes how to write it down (the data format). All the data in a certificate is encoded using two related standards called ASN.1/DER. Abstract Syntax Notation 1 describes data. The Definite Encoding Rules describe a single way to store and transfer that data.

    All X.509 certificates have the following data, in addition to the signature:

    Version

    This identifies which version of the X.509 standard applies to this certificate, which affects what information can be specified in it. Thus far, three versions are defined. keytool can import and export v1, v2, and v3 certificates. It generates v3 certificates.

    X.509 Version 1 has been available since 1988, is widely deployed, and is the most generic.

    X.509 Version 2 introduced the concept of subject and issuer unique identifiers to handle the possibility of reuse of subject and/or issuer names over time. Most certificate profile documents strongly recommend that names not be reused, and that certificates should not make use of unique identifiers. Version 2 certificates are not widely used.

    X.509 Version 3 is the most recent (1996) and supports the notion of extensions, whereby anyone can define an extension and include it in the certificate. Some common extensions in use today are: KeyUsage (limits the use of the keys to particular purposes such as "signing-only") and AlternativeNames (allows other identities to also be associated with this public key, e.g. DNS names, Email addresses, IP addresses). Extensions can be marked critical to indicate that the extension should be checked and enforced/used. For example, if a certificate has the KeyUsage extension marked critical and set to "keyCertSign" then if this certificate is presented during SSL communication, it should be rejected, as the certificate extension indicates that the associated private key should only be used for signing certificates and not for SSL use.

    Serial Number

    The entity that created the certificate is responsible for assigning it a serial number to distinguish it from other certificates it issues. This information is used in numerous ways, for example when a certificate is revoked its serial number is placed in a Certificate Revocation List (CRL).

    Signature Algorithm Identifier

    This identifies the algorithm used by the CA to sign the certificate.

    Issuer Name

    The X.500 Distinguished Name of the entity that signed the certificate. This is normally a CA. Using this certificate implies trusting the entity that signed this certificate. (Note that in some cases, such as root or top-level CA certificates, the issuer signs its own certificate.)

    Validity Period

    Each certificate is valid only for a limited amount of time. This period is described by a start date and time and an end date and time, and can be as short as a few seconds or almost as long as a century. The validity period chosen depends on a number of factors, such as the strength of the private key used to sign the certificate or the amount one is willing to pay for a certificate. This is the expected period that entities can rely on the public value, if the associated private key has not been compromised.

    Subject Name

    The name of the entity whose public key the certificate identifies. This name uses the X.500 standard, so it is intended to be unique across the Internet. This is the X.500 Distinguished Name (DN) of the entity, for example,

        CN=Java Duke, OU=Java Software Division, O=Oracle Corporation, C=US

    (These refer to the subject's Common Name, Organizational Unit, Organization, and Country.)

    Subject Public Key Information

    This is the public key of the entity being named, together with an algorithm identifier which specifies which public key crypto system this key belongs to and any associated key parameters.

  • Certificate Chains

    keytool can create and manage keystore "key" entries that each contain a private key and an associated certificate "chain". The first certificate in the chain contains the public key corresponding to the private key.

    When keys are first generated (see the -genkeypair command), the chain starts off containing a single element, a self-signed certificate. A self-signed certificate is one for which the issuer (signer) is the same as the subject (the entity whose public key is being authenticated by the certificate). Whenever the -genkeypair command is called to generate a new public/private key pair, it also wraps the public key into a self-signed certificate.

    Later, after a Certificate Signing Request (CSR) has been generated (see the -certreq command) and sent to a Certification Authority (CA), the response from the CA is imported (see -importcert), and the self-signed certificate is replaced by a chain of certificates. At the bottom of the chain is the certificate (reply) issued by the CA authenticating the subject's public key. The next certificate in the chain is one that authenticates the CA's public key.

    In many cases, this is a self-signed certificate (that is, a certificate from the CA authenticating its own public key) and the last certificate in the chain. In other cases, the CA may return a chain of certificates. In this case, the bottom certificate in the chain is the same (a certificate signed by the CA, authenticating the public key of the key entry), but the second certificate in the chain is a certificate signed by a different CA, authenticating the public key of the CA you sent the CSR to. Then, the next certificate in the chain will be a certificate authenticating the second CA's key, and so on, until a self-signed "root" certificate is reached. Each certificate in the chain (after the first) thus authenticates the public key of the signer of the previous certificate in the chain.

    Many CAs only return the issued certificate, with no supporting chain, especially when there is a flat hierarchy (no intermediates CAs). In this case, the certificate chain must be established from trusted certificate information already stored in the keystore.

    A different reply format (defined by the PKCS#7 standard) also includes the supporting certificate chain, in addition to the issued certificate. Both reply formats can be handled by keytool.

    The top-level (root) CA certificate is self-signed. However, the trust into the root's public key does not come from the root certificate itself (anybody could generate a self-signed certificate with the distinguished name of say, the VeriSign root CA!), but from other sources like a newspaper. The root CA public key is widely known. The only reason it is stored in a certificate is because this is the format understood by most tools, so the certificate in this case is only used as a "vehicle" to transport the root CA's public key. Before you add the root CA certificate to your keystore, you should view it (using the -printcert option) and compare the displayed fingerprint with the well-known fingerprint (obtained from a newspaper, the root CA's Web page, etc.).

  • The cacerts Certificates File

    A certificates file named "cacerts" resides in the security properties directory, java.home\lib\security, where java.home is the runtime environment's directory (the jre directory in the SDK or the top-level directory of the Java 2 Runtime Environment).

    The "cacerts" file represents a system-wide keystore with CA certificates. System administrators can configure and manage that file using keytool, specifying "jks" as the keystore type. The "cacerts" keystore file ships with a default set of root CA certificates; list them with the following command:

    keytool -list -keystore java.home\lib\security\cacerts

    The initial password of the "cacerts" keystore file is "changeit". System administrators should change that password and the default access permission of that file upon installing the SDK.

    IMPORTANT: Verify Your cacerts File: Since you trust the CAs in the cacerts file as entities for signing and issuing certificates to other entities, you must manage the cacerts file carefully. The cacerts file should contain only certificates of the CAs you trust. It is your responsibility to verify the trusted root CA certificates bundled in the cacerts file and make your own trust decisions. To remove an untrusted CA certificate from the cacerts file, use the delete option of the keytool command. You can find the cacerts file in the JRE installation directory. Contact your system administrator if you do not have permission to edit this file.

  • The Internet RFC 1421 Certificate Encoding Standard

    Certificates are often stored using the printable encoding format defined by the Internet RFC 1421 standard, instead of their binary encoding. This certificate format, also known as "Base 64 encoding", facilitates exporting certificates to other applications by email or through some other mechanism.

    Certificates read by the -importcert and -printcert commands can be in either this format or binary encoded.

    The -exportcert command by default outputs a certificate in binary encoding, but will instead output a certificate in the printable encoding format, if the -rfc option is specified.

    The -list command by default prints the SHA1 fingerprint of a certificate. If the -v option is specified, the certificate is printed in human-readable format, while if the -rfc option is specified, the certificate is output in the printable encoding format.

    In its printable encoding format, the encoded certificate is bounded at the beginning by

    -----BEGIN CERTIFICATE-----

    and at the end by

    -----END CERTIFICATE-----

X.500 Distinguished Names

X.500 Distinguished Names are used to identify entities, such as those which are named by the subject and issuer (signer) fields of X.509 certificates. keytool supports the following subparts:

  • commonName - common name of a person, e.g., "Susan Jones"
  • organizationUnit - small organization (e.g., department or division) name, e.g., "Purchasing"
  • organizationName - large organization name, e.g., "ABCSystems, Inc."
  • localityName - locality (city) name, e.g., "Palo Alto"
  • stateName - state or province name, e.g., "California"
  • country - two-letter country code, e.g., "CH"

When supplying a distinguished name string as the value of a -dname option, as for the -genkeypair command, the string must be in the following format:

CN=cName, OU=orgUnit, O=org, L=city, S=state, C=countryCode

where all the italicized items represent actual values and the above keywords are abbreviations for the following:

        CN=commonName
        OU=organizationUnit
        O=organizationName
        L=localityName
        S=stateName
        C=country

A sample distinguished name string is

CN=Mark Smith, OU=Java, O=Oracle, L=Cupertino, S=California, C=US

and a sample command using such a string is

keytool -genkeypair -dname "CN=Mark Smith, OU=Java, O=Oracle, L=Cupertino,
S=California, C=US" -alias mark

Case does not matter for the keyword abbreviations. For example, "CN", "cn", and "Cn" are all treated the same.

Order matters; each subcomponent must appear in the designated order. However, it is not necessary to have all the subcomponents. You may use a subset, for example:

CN=Steve Meier, OU=Java, O=Oracle, C=US

If a distinguished name string value contains a comma, the comma must be escaped by a "\" character when you specify the string on a command line, as in

   cn=Peter Schuster, ou=Java\, Product Development, o=Oracle, c=US

It is never necessary to specify a distinguished name string on a command line. If it is needed for a command, but not supplied on the command line, the user is prompted for each of the subcomponents. In this case, a comma does not need to be escaped by a "\".

WARNING Regarding Importing Trusted Certificates

IMPORTANT: Be sure to check a certificate very carefully before importing it as a trusted certificate!

View it first (using the -printcert command, or the -importcert command without the -noprompt option), and make sure that the displayed certificate fingerprint(s) match the expected ones. For example, suppose someone sends or emails you a certificate, and you put it in a file named C:\temp\cert. Before you consider adding the certificate to your list of trusted certificates, you can execute a -printcert command to view its fingerprints, as in

  keytool -printcert -file C:\temp\cert
    Owner: CN=ll, OU=ll, O=ll, L=ll, S=ll, C=ll
    Issuer: CN=ll, OU=ll, O=ll, L=ll, S=ll, C=ll
    Serial Number: 59092b34
    Valid from: Thu Sep 25 18:01:13 PDT 1997 until: Wed Dec 24 17:01:13 PST 1997
    Certificate Fingerprints:
         MD5:  11:81:AD:92:C8:E5:0E:A2:01:2E:D4:7A:D7:5F:07:6F
         SHA1: 20:B6:17:FA:EF:E5:55:8A:D0:71:1F:E8:D6:9D:C0:37:13:0E:5E:FE
         SHA256: 90:7B:70:0A:EA:DC:16:79:92:99:41:FF:8A:FE:EB:90:
                 17:75:E0:90:B2:24:4D:3A:2A:16:A6:E4:11:0F:67:A4

Then call or otherwise contact the person who sent the certificate, and compare the fingerprint(s) that you see with the ones that they show. Only if the fingerprints are equal is it guaranteed that the certificate has not been replaced in transit with somebody else's (for example, an attacker's) certificate. If such an attack took place, and you did not check the certificate before you imported it, you would end up trusting anything the attacker has signed (for example, a JAR file with malicious class files inside).

Note: it is not required that you execute a -printcert command prior to importing a certificate, since before adding a certificate to the list of trusted certificates in the keystore, the -importcert command prints out the certificate information and prompts you to verify it. You then have the option of aborting the import operation. Note, however, this is only the case if you invoke the -importcert command without the -noprompt option. If the -noprompt option is given, there is no interaction with the user.

Warning Regarding Passwords

Most commands operating on a keystore require the store password. Some commands require a private/secret key password.

Passwords can be specified on the command line (in the -storepass and -keypass options, respectively). However, a password should not be specified on a command line or in a script unless it is for testing purposes, or you are on a secure system.

If you don't specify a required password option on a command line, you will be prompted for it.

Warning Regarding Certificate Conformance

The Internet standard RFC 5280 has defined a profile on conforming X.509 certificates, which includes what values and value combinations are valid for certificate fields and extensions. keytool has not enforced all these rules so it can generate certificates which do not conform to the standard, and these certificates might be rejected by JRE or other applications. Users should make sure that they provide the correct options for -dname, -ext, etc.

SEE ALSO

  • jar tool documentation
  • jarsigner tool documentation
  • the Security trail of the Java Tutorial for examples of the use of keytool

CHANGES

The command interface for keytool changed in Java SE 6.

keytool no longer displays password input when entered by users. Since password input can no longer be viewed when entered, users will be prompted to re-enter passwords any time a password is being set or changed (for example, when setting the initial keystore password, or when changing a key password).

Some commands have simply been renamed, and other commands deemed obsolete are no longer listed in this document. All previous commands (both renamed and obsolete) are still supported in this release and will continue to be supported in future releases. The following summarizes all of the changes made to the keytool command interface:

Renamed commands:

  • -export, renamed to -exportcert
  • -genkey, renamed to -genkeypair
  • -import, renamed to -importcert

Commands deemed obsolete and no longer documented:

  • -keyclone
  • -identitydb
  • -selfcert
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


kinit - Kerberos tool

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

kinit - Obtain and cache Kerberos ticket-granting ticket

kinit is used to obtain and cache Kerberos ticket-granting tickets. This tool is similar in functionality to the kinit tool that are commonly found in other Kerberos implementations, such as SEAM and MIT Reference implementations.

The user must be registered as a principal with the Key Distribution Center (KDC) prior to running kinit.

SYNOPSIS

    kinit [ commands ] <principal name> [<password>]

DESCRIPTION

By default, on the Windows platform a cache file named <USER_HOME>\krb5cc_<USER_NAME> will be generated. <uid> is the user identification number of the user logged into the system.

<USER_HOME> is obtained from the java.lang.System property user.home. <USER_NAME> is obtained from java.lang.System property user.name. If <USER_HOME> is null, the cache file would be stored in the current directory that the program is running from. <USER_NAME> is the operating system's login username. This username could be different than the user's principal name. For example on Windows NT, it could be c:\winnt\profiles\duke\krb5cc_duke, in which duke is the <USER_NAME> and c:\winnt\profiles\duke is the <USER_HOME>.

By default, the keytab name is retrieved from the Kerberos configuration file. If the keytab name is not specifed in the Kerberos configuration file, the name is assumed to be <USER_HOME>\krb5.keytab

If you do not specify the password using the password option on the command line, kinit will prompt you for the password.

Note: password is provided only for testing purposes. Do not place your password in a script or provide your password on the command line. Doing so will compromise your password.

For more information see the man pages for kinit.

COMMANDS

Usage: kinit [-fp] [-c <cache_name>] [-k] [-t <keytab_filename>] [<principal>] [<password>] [-help]

Command Option | Description
-A | Do not include addresses.
-f | Issue a forwardable ticket.
-p | Issue a proxiable ticket.
-c <cache_name> | The cache name (i.e., FILE:d:\temp\mykrb5cc).
-k | Use keytab
-t <keytab_filename> | The keytab name (i.e, d:\winnt\profiles\duke\krb5.keytab).
<principal> | The principal name (i.e., duke@java.sun.com).
<password> | The principal's Kerberos password. (DO NOT SPECIFY ON COMMAND LINE OR IN A SCRIPT.)
-help | Displays instructions.

EXAMPLES

Requesting credentials valid for authentication from the current client host, for the default services, storing the credentials cache in the default location (c:\winnt\profiles\duke\krb5cc_duke):

      kinit duke@JAVA.SUN.COM

Requesting proxiable credentials for a different principal and storing these credentials in a specified file cache:

      kinit -p -c FILE:c:\winnt\profiles\duke\credentials\krb5cc_cafebeef cafebeef@JAVA.SUN.COM

Requesting proxiable and forwardable credentials for a different principal and storing these credentials in a specified file cache:

      kinit -f -p -c FILE:c:\winnt\profiles\duke\credentials\krb5cc_cafebeef cafebeef@JAVA.SUN.COM

Displaying the help menu for kinit:

      kinit -help

SECURITY ALERT

The password flag is for testing purposes only. Do not specify your password on the command line. Doing so is a security hole since an attacker could discover your password while enumerating all running processes in the system, for example.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


klist - Kerberos tool

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

klist - Kerberos display entries in credentials cache and keytab

klist allows the user to view entries in the local credentials cache and key table.

SYNOPSIS

klist [ commands ]

DESCRIPTION

klist displays the entries in the local credentials cache and key table. After the user has modified the credentials cache with kinit or modified the keytab with ktab, the only way to verify the changes is to view the contents of the credentials cache and/or keytab using klist. klist does not change the Kerberos database.

COMMANDS

Usage: klist [ [-c] [-f] [-e] [-a [-n]] ] [-k [-t] [-K] ] [<name>] [-help]

Command Option | Description
-c | Specifies that the credential cache entries are to be listed.
-k | Specifies that the key tab entries are to be listed.
<name> | Specifies the credential cache name or the keytab name. If the name is not specified default values for cache name and the keytab are used. The default values for the cache and the keytab are specified in the man page for kinit.
-help | Displays instructions.
If the -c option is specified (options for credential cache)
Comman Option | Description
-f | Shows credentials flags.
-e | Shows the encryption type.
-a | Shows addresses.
-n | If -a is specified, do not reverse resolve addresses.
If the -k option is specified (options available for keytabs)
Command Option | Description
-t | Shows keytab entry timestamps.
-K | Shows keytab entry DES keys. | -K | Shows keytab entry key type.

EXAMPLES

List entries in the keytable specified including keytab entry timestamps and DES keys:

      klist -k -t -K FILE:\temp\mykrb5cc

List entries in the credentials cache specified including credentials flag and address list:

      klist -c -f FILE:\temp\mykrb5cc
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.security.auth.module.Krb5LoginModule (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.module.Krb5LoginModule

No usage of com.sun.security.auth.module.Krb5LoginModule
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


ktab - Kerberos tool

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

ktab - Kerberos key table manager

ktab allows the user to manage the principal names and service keys stored in a local key table. Principal and key pairs listed in the keytab allow services running on a host to authenticate themselves to the Key Distribution Center (KDC). Before a server can be setup to use Kerberos, the user must setup a keytab on the host running the server. Note that any updates made to the keytab using ktab do not affect the Kerberos database. If you change the keys in the keytab, you must also make the corresponding changes to the Kerberos database.

SYNOPSIS

ktab [ commands ]

DESCRIPTION

ktab manages principal name and key pairs in the key table. ktab allows the user to list, add, update or delete principal names and key pairs in the key table. None of these operations affect the Kerberos database.

Keytab
A keytab is a host's copy of its own keylist, which is analogous to a user's password. An application server that needs to authenticate itself to the Key Distribution Center (KDC) must have a keytab which contains its own principal and key. Just as it is important for users to protect their passwords, it is equally important for hosts to protect their keytabs. You should always store keytab files on the local disk and make them readable only by root. You should never send a keytab file over a network in the clear.

COMMANDS

Usage: The command line options are not case-sensitive.

ktab -help

ktab -l [-e -t] [-k <keytab_name>]

ktab [-a <principal_name> <password>] [-k <keytab_name>]

ktab [-d <principal_name> [<etype>]] [-k <keytab_name>]

Command Option | Description
-l [-e -t] | List the keytab name and entries. When -e is specified, the encryption type for each entry is displayed. When -t is specified, timestamp for each entry is displayed.
-a <principal_name> <password> | Add an entry to the keytab. No changes are made to the Kerberos database. (DO NOT SPECIFY YOUR PASSWORD ON COMMAND LINE OR IN A SCRIPT.)
-d <principal_name> [<etype>] | Delete one or more entries from the keytab. No changes are made to the Kerberos database. When etype is provided, only the entry matching this encryption type is deleted. Otherwise, all entries are deleted.
-k <keytab_name> | Specify keytab name and path with the prefix FILE:
-help | Displays instructions.

EXAMPLES

To list all the entries in the default keytable:
ktab -l
To add a new principal to the key table (note that you will be prompted for your password):
ktab -a duke@java.sun.com
To delete a principal from the key table:
ktab -d duke@java.sun.com

SECURITY ALERT

Do not specify your password on the command line. Doing so is a security hole. For example, an attacker could discover your password while running the Unix ps command.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.source.tree.LabeledStatementTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.LabeledStatementTree

  • Packages that use LabeledStatementTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of LabeledStatementTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type LabeledStatementTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitLabeledStatement(LabeledStatementTree node, P p)

    • Uses of LabeledStatementTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type LabeledStatementTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitLabeledStatement(LabeledStatementTree node, P p)
      R | SimpleTreeVisitor.visitLabeledStatement(LabeledStatementTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.javadoc.LanguageVersion (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.javadoc.LanguageVersion

    • Uses of LanguageVersion in com.sun.javadoc

      Methods in com.sun.javadoc that return LanguageVersion
      Modifier and Type Method and Description
      static LanguageVersion Doclet.languageVersion()
      Return the version of the Java Programming Language supported by this doclet.
      static LanguageVersion LanguageVersion.valueOf(String name)
      Returns the enum constant of this type with the specified name.
      static LanguageVersion[] LanguageVersion.values()
      Returns an array containing the constants of this enum type, in the order they are declared.
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Creating the Web Page That Lauches the Application

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

< Contents

Creating the Web Page That Launches the Application

This chapter includes the following topics:

  • Introduction

  • Detecting if Java Web Start is installed on Netscape

  • Detecting if Java Web Start is installed on IE, and if so, the version number

  • Launching the application if Java Web Start is Installed—or providing a link for auto-install or general download page

  • Creating an auto-install page

Introduction

The following information predates the introduction of the Deployment Toolkit script in the Java SE 6 update 10 release.
See Java Rich Internet Applications Deployment Advice for information about using the Deployment Toolkit script.

In order for an application to be launched from a web page via JNLP, the page must include a link to the JNLP file. E.g., to be able to launch application app.jnlp on a web site http://www.MySite.com, the page needs to include the following link:

<a href=http://www.MySite.com/app.jnlp>Launch the application</a>

It may be the case, however, that Java Web Start is not installed on the user's computer. Thus the page needs to include logic (scripts) to take account of this. In fact, the page should include logic for the following:

Detect if Java Web Start is installed

  • If so, launch the application.

  • If not, detect if user is running IE on Window.

    • If so, provide link to a page that can auto-install the JRE for Windows

    • If not, provide a link to the general download page for the JDK/JRE.

The scripts, and the HTML for the auto-install page, are discussed below.

Detecting if Java Web Start is installed on Netscape

Here is the first script that should be run on a web page for launching an application via JNLP:

<SCRIPT LANGUAGE="JavaScript">
var javawsInstalled = 0;
var javaws142Installed=0;
var javaws150Installed=0;
var javaws160Installed = 0;
isIE = "false";
if (navigator.mimeTypes && navigator.mimeTypes.length) {
   x = navigator.mimeTypes['application/x-java-jnlp-file'];
   if (x) {
      javawsInstalled = 1;
      javaws142Installed=1;
      javaws150Installed=1;
      javaws160Installed = 1;
  }
}
else {
   isIE = "true";
}
</SCRIPT>

This script looks at the navigator.mimeTypes object and the navigator.mimeTypes.length var to decide if the browser is Netscape or IE. If length is 0, it is assumed the browser is IE, as with IE the navigator.mimeTypes array is defined but always empty. If length is non-zero, then the browser is assumed to be Netscape and the JNLP MIME type is checked to see if it exists on Netscape. If so, javawsInstalled, javaws142Installed, javaws150Installed and javaws160Installed are all set to 1. With Netscape it is not possible to determine which particular version of Java Web Start is installed, so all four variables are set to 1.

Detecting if JavaWeb Start is installed on IE, and if so, the version

The above JavaScript should be followed by a VBScript that sets variables related to Internet Explorer browers:

<SCRIPT LANGUAGE="VBScript">
on error resume next
If isIE = "true" Then
  If Not(IsObject(CreateObject("JavaWebStart.isInstalled"))) Then
     javawsInstalled = 0
  Else
     javawsInstalled = 1
  End If
  If Not(IsObject(CreateObject("JavaWebStart.isInstalled.1.4.2.0"))) Then
     javaws142Installed = 0
  Else
     javaws142Installed = 1
  End If
  If Not(IsObject(CreateObject("JavaWebStart.isInstalled.1.5.0.0"))) Then
     javaws150Installed = 0
  Else
     javaws150Installed = 1
  End If
  If Not(IsObject(CreateObject("JavaWebStart.isInstalled.1.6.0.0"))) Then
     javaws160Installed = 0
  Else
     javaws160Installed = 1
  End If
End If
</SCRIPT>

This VBScript is executed if the variable isIE from the preceeding JavaScript is "true"; i.e., if the end-user's browser is Internet Explorer. This script instantiates the isInstalled COM object in JavaWebStart.dll, and this object determines four things:

  • whether the client machine has any version of Java Web Start installed;

  • whether the client machine has version 1.2 of Java Web Start installed;

  • whether the client machine has versions 1.4.2 of Java Web Start installed;

  • whether the client machine has versions 1.5.0 of Java Web Start installed.

  • whether the client machine has versions 1.6.0 of Java Web Start installed.

After the above two scripts have been executed, the variables javawsInstalled, javaws142Installed, javawsInstalled150 and javawsInstalled160 will be set to either 1 or 0, as follows:

Browser

javawsInstalled

javaws142Installed

javaws150Installed

javaws160Installed

Internet Explorer

1 if any version of Java Web Start is installed; 0 otherwise.

1 if Java Web Start 1.4.2 is installed; 0 otherwise.

1 if Java Web Start 1.5.0 is installed; 0 otherwise.

1 if Java Web Start 1.6.0 is installed; 0 otherwise.

Netscape Navigator

1 if any version of Java Web Start is installed; 0 otherwise.

1 if any version of Java Web Start is installed; 0 otherwise.

1 if any version of Java Web Start is installed; 0 otherwise.

1 if any version of Java Web Start is installed; 0 otherwise.

Launching the application if Java Web Start is Installed—or providing a link for auto-install or general download page

An additional JavaScript can be used to decide whether to:

  • provide a link to the application's jnlp file (i.e., Java Web Start is installed);

  • initiate auto-download of JRE 6.0, which includes Java Web Start (i.e., Java Web Start is not installed and the user is running IE on Windows);

  • or provide a link to the general download page for the 6.0 JDK/JRE (i.e., Java Web Start is not installed and the user is not running IE on Windows).

The following JavaScript handles these scenarios:

<script language="JavaScript">
/* Note that the logic below always launches the JNLP application
 *if the browser is Gecko based. This is because it is not possible
 *to detect MIME type application/x-java-jnlp-file on Gecko-based browsers.
 */
if (javawsInstalled || (navigator.userAgent.indexOf("Gecko") !=-1)) {
    document.write("<a href=http://www.MySite.com/app.jnlp>Launch
        the application</a>");
} else {
    document.write("Click ");
    document.write("<a href=http://java.sun.com/PluginBrowserCheck?
        pass=http://www.MySite.com/download.html&
        fail=http://java.sun.com/javase/downloads/ea.jsp>here</a> ");
    document.write("to download and install JRE 5.0 and
        the application.");
}
</SCRIPT>

Notes:

  1. The script only uses javawsInstalled—not javaws142Installed or javaws150Installed or javaws160Installed.

  2. The line breaks following '?' and '&' are for readability purposes only; in an actual script there should be no breaks in the href string.

If javawsInstalled is 1, indicating that Java Web Start is already available on the client, then the script provides a link to the application's jnlp file. If Java Web Start is not installed on the client, the script instead provides a link to the PluginBrowserCheck program on the java.sun.com web site. PluginBrowserCheck checks whether the client uses Internet Explorer on a Microsoft Windows platform. If so, PluginBrowserCheck sends the user to the auto-install page http://www.MySite.com/download.html. (See the next section, Creating an auto-install page, for how to create an auto-install page for IE running on Windows.) If PluginBrowserCheck determines the user is not using Internet Explorer on Microsoft Windows, the user is redirected to the 6.0 JRE general download page on java.sun.com.

Creating an auto-install page

The download.html file should be staged on the server side. It contains special OBJECT and PARAM tags that will download to the client an auto-installer for JRE 6.0 . Along with Java Web Start, an ActiveX control will be downloaded to the client. The ActiveX control will launch the application using the newly installed Java Web Start. Here is a sample download.html file:

<HTML>
<BODY>
<OBJECT codebase="http://java.sun.com/update/1.6.0/jinstall-6-windows-i586.cab#Version=6,0,0,0"
classid="clsid:5852F5ED-8BF4-11D4-A245-0080C6F74284" height=0 width=0>
<PARAM name="app" value="http://www.MySite.com/app.jnlp">
<PARAM name="back" value="true">
<!-- Alternate HTML for browsers which cannot instantiate the object -->
<A href="http://java.sun.com/javase/downloads/ea.jsp">
Download Java Web Start</A>
</OBJECT>
</BODY>
</HTML>

The OBJECT tag fetches a .cab file that contains an auto-installer for JRE 6.0.

The URL:

http://java.sun.com/update/1.6.0/jinstall-6-windows-i586.cab

will return the latest update release available for the Java SE 6 release.

The string: Version=6,0,0,0 will be used to compare with the wsdetect.dll version, which is registered with the CLSID above. If the local machine has the dll installed and the version is greater than or equal to the Version specified, we will just load the dll in the local machine. Otherwise it will download and install Java from the codebase specified.

The PARAM tags specify the location of the application's jnlp file so that it may be automatically launched after the JRE is installed on the client.

app: Once the Java Web Start Active-X control is installed/loaded, it will invoke Java Web Start to launch the application specified by this URL.

back: This controls the behavior of the browser after launching the application. It can remain on the current page (download.html in this case) or navigate back to the previous page.

For issues relating to application development see the next chapter, Application Development Considerations.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Designing Services to be Launched from inetd

On the Solaris Operating System (Solaris OS), the Internet services daemon inetd provides an alternative to starting up services at system boot time. This daemon, a server process for Internet standard services, can be configured to start services on demand. For details on the Internet services daemon, see the Solaris OS inetd(1M) man page.

Now, inetd can be configured to start JavaTM Remote Method Invocation (Java RMI) services on demand. An application, however, must use a specific technique to enable that application and its constituent services to be started from inetd. First, the service program should create a local registry, exported to use the I/O socket inherited from inetd. The service program should then bind the service's proxy in this specially exported registry so that clients can look up the service. Once the service program is complete, inetd can be configured to start this program when a client attempts to connect to the service's local registry in order to look up the service by name.

This tutorial first describes how to structure a service program (employing a specially exported local registry) so that the service can be started from inetd when clients connect to the service's local registry.

Next, the tutorial describes how to configure inetd to launch the service program. You will need to add an entry to each of two configuration files that inetd uses, /etc/inetd.conf and /etc/services. Editing these files requires root access to the machine that the service will run on.

After inetd has been reconfigured, you should test your configuration to make sure that it works properly.

This tutorial has the following steps:

  • Implement the service program
  • Configure /etc/inetd.conf
  • Configure /etc/services
  • Force inetd to read its new configuration
  • Test your configuration using a simple client

Implement the service program

The server-side implementation uses the following source files:

  • ServiceInterface.java: remote interface for the service
  • InitializeRegistry.java: utility to create/export a registry using an inherited channel
  • Server.java: service program
The interface ServiceInterface defines a remote interface with a single method sendMessage specified to take a single argument, message, and return an acknowledgment that the message was received.

The class InitializeRegistry defines a static utility method initializeWithInheritedChannel that creates and exports a registry (using an inherited channel, if any), and binds a remote service's proxy in that registry for clients to look up.

The service program Server implements the interface ServiceInterface and defines a static main method for running the service. The static main method does the following:

  • Redirects System.err output to a file, in order to prevent the error output from being lost in the case that the service program is started from inetd.
  • Parses the optional argument, which is the port number for the local registry.
  • Creates and exports the server on an anonymous port.
  • Invokes the InitializeRegistry.initializeWithInheritedChannel utility method with the service's proxy, the name for the service in the registry, and an optional port number to use if the program is run from the command line instead of being started from inetd.
  • Prints out the message ready.
  • Waits forever.

The most interesting part of the implementation is in the initializeWithInheritedChannel utility method. This method uses the System.inheritedChannel method which allows an application to obtain a channel (java.nio.channels.SocketChannel or java.nio.channels.ServerSocketChannel, for example) inherited from a process that launched the virtual machine. Such an inherited channel can be used to either service a single incoming connection (in the case of a SocketChannel), or accept multiple incoming connections (in the case of ServerSocketChannel). In this way, applications launched by inetd can obtain the SocketChannel or ServerSocketChannel inherited from inetd.

The initializeWithInheritedChannel utility method first invokes the System.inheritedChannel method to obtain the inherited channel. The inherited channel must either be null or a ServerSocketChannel or the method will throw an IOException.

If the inherited channel is null, there is no inherited channel; that is, the program was run from the command line. In this case, the initializeWithInheritedChannel method simply exports a registry on the specified port (which must be nonzero) and binds the specified service proxy in that registry.

If the inherited channel is a ServerSocketChannel instance, then the program was started from inetd. In this case, the initializeWithInheritedChannel method exports a registry with an RMIServerSocketFactory whose createServerSocket method returns a ServerSocket that delays accepting requests from the inherited ServerSocketChannel until the specified proxy is bound in the registry.

In the case that the program is started from inetd, it is important that the registry not accept any incoming connections on the inherited ServerSocket until the service's proxy is bound in the local registry. If a connection is accepted before the service is bound in the registry, a client might receive a java.rmi.NotBoundException from attempting to look up the service proxy.

For details on how to implement a ServerSocket that delays accepting requests until a service is bound in the registry, see the private nested class DelayedAcceptServerSocket defined in the InitializeRegistry class.

Compile the service program as follows:

% javac -d classDir ServiceInterface.java InitializeRegistry.java Server.java
where classDir is the class path for this example.

Note that if the service needs to be accessible to clients running on releases earlier than J2SE 5.0, you will need to use rmic to generate a stub for the remote service.

The next three sections describe how to set up inetd to start the service program.

Configure /etc/inetd.conf

The /etc/inetd.conf configuration file contains entries for the services to be launched when inetd receives a request over a socket. For details on the format of this configuration file see the Solaris OS inetd.conf(4) man page.

To configure inetd to launch the service program, add the following entry to the /etc/inetd.conf configuration file (requires root access to the machine):

example-server stream tcp wait nobody jreHome/bin/java  \
     java -classpath classpath example.inetd.Server
where jreHome is a path to the installed JRE, and classpath is the class path for the example.

If the program needs to be run as a user other than nobody, replace nobody above with the user ID under which the program should run.

Configure /etc/services

Next, the name chosen to refer to the service, example-server, needs to be listed as a service in the /etc/services configuration file. For details on the format of this configuration file see the Solaris OS services(4) man page.

To list example-server as a service, add the following entry to the /etc/services configuration file (requires root access to the machine):

example-server        port/tcp
where port is the port number for the service's local registry.

Force inetd to read its new configuration

Now that the configuration has been modified, inetd needs to read the new configuration so that it can listen on the appropriate ports for the services that are configured.

But first, it is important to make sure that the service program is not already running. To do this, run the following command:

% ps -ef | grep example.inetd.Server
If the above command does not print out the information for a running java process for the service program, then the program is not running. If it does, then you will need to terminate the program first before continuing.

Next, inetd needs to read its new configuration. To force inetd to reread its configuration, the running inetd process must be sent a hangup signal. First, find the process ID for the running inetd process by running the following command:

% ps -ef | grep inetd
which will print out something like this:
root   171     1  0   Sep 30 ?        0:02 /usr/sbin/inetd -s
In this example, the process ID for inetd is 171. Now, the inetd process can be sent a hangup signal by running the following command and supplying the process ID (requires root access):
% kill -HUP 171
Now, inetd is all set to launch the service program when a client attempts to connect to the port configured above.

Test your configuration using a simple client

To test that inetd is configured properly, you can run a simple client program that looks up the service in the registry on the port configured above, and then invokes a method on the service. Attempting to connect to the service's local registry will, in turn, cause inetd to launch the service program if the configuration is correct.

The following is a simple program to look up the service and invoke a method on the service to send it a message. The program takes three command-line arguments, the host and port of the service's local registry, and the message to send to the service:

package example.inetd;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Client {

    public static void main(String[] args) throws Exception {

        int port = 0;
        String host = "";
        String message = "";

        if (args.length > 2) {
            host = args[0];
            try {
                port = Integer.parseInt(args[1]);
                if (port == 0) {
                    goodbye("nonzero port argument required", null);
                }
            } catch (NumberFormatException e) {
                goodbye("malformed port argument", e);
            }
            message = args[2];
        } else {
            usage();
        }

        Registry registry = LocateRegistry.getRegistry(host, port);
        ServiceInterface proxy =
            (ServiceInterface) registry.lookup("ServiceInterface");
        System.out.println("sending message: " + message);
        System.out.println("received message from proxy: " +
                           proxy.sendMessage(message));

        System.out.println("done.");
    }

    private static void goodbye(String message, Exception e) {
        System.err.println("Client: " + message + (e != null ? ": " : ""));
        if (e != null) {
            e.printStackTrace();
        }
        System.exit(1);
    }

    private static void usage() {
        System.err.println("Client <host> <port> <message>");
        System.exit(1);
    }
}

The full source (including comments) for the client is:

  • ServiceInterface.java: remote interface for the service
  • Client.java: client program

Compile and run this program as follows:

% javac -d classDir ServiceInterface.java Client.java
% java -classpath classDir example.inetd.Client host port "message"
where classDir is the class path for this example, host is the host that the service is configured to run on, port is the port configured for the service in the /etc/services file, and message is a string to send to the service.

If the client program prints out that it sent a message to and received a message from the service, then the service program was successfully launched by inetd.

If the client program either hangs or prints an exception trace, check the output produced by the service program. The service program redirects any output written to System.err to a file located in the directory specified by the property java.io.tmpdir, typically /var/tmp on the Solaris OS. The output file is prefixed with "example-server-err" and has the suffix of ".tmp". The file name also contains other characters (typically numbers) in between to keep the file name unique.

If the service program starts up successfully from inetd, the output file should contain the text "ready" with no warning or error messages.

If the file does not exist, the "ready" message is not in the file, or additional error output is in the file, then recheck the configuration. Upon changing the inetd configuration, remember to send inetd a hangup signal so that it rereads its altered configuration, and remember to terminate any process started from the previous attempt before continuing.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.connect.LaunchingConnector (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.connect.LaunchingConnector

  • Packages that use LaunchingConnector
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of LaunchingConnector in com.sun.jdi

      Methods in com.sun.jdi that return LaunchingConnector
      Modifier and Type Method and Description
      LaunchingConnector VirtualMachineManager.defaultConnector()
      Identifies the default connector.
      Methods in com.sun.jdi that return types with arguments of type LaunchingConnector
      Modifier and Type Method and Description
      List<LaunchingConnector> VirtualMachineManager.launchingConnectors()
      Returns the list of known LaunchingConnector objects.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.auth.module.LdapLoginModule (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.module.LdapLoginModule

No usage of com.sun.security.auth.module.LdapLoginModule
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.auth.LdapPrincipal (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.LdapPrincipal

No usage of com.sun.security.auth.LdapPrincipal
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Appendix B: Legend for Class Diagram

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

Appendix 3:

Legend for Class Diagram

In a class diagram, we visually distinguish the different kinds of Java entities, as follows:

The interface: A rounded rectangle

  1. The class: A rectangle
  2. The abstract class: A rectangle with an empty dot
  3. The final class: A rectangle with a black dot
  4. Classes with subclasses: A rectangle with a small black triangle on the lower right corner

Most of these elements are shown below. The class or interface being described in the current chapter is shaded grey (this is not applicable for package class diagrams). A solid line represents extends , while a dotted line represents implements .

Example class diagram

CONTENTS | PREV | NEXT

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
[Top] [Prev] [Next] [Bottom]

Appendix B: Legend for Class Diagram

In a class diagram, we visually distinguish the different kinds of Java entities, as follows:

  2. The interface: A rounded rectangle
  3. The class: A rectangle
  4. The abstract class: A rectangle with an empty dot
  5. The final class: A rectangle with a black dot
  6. Classes with subclasses: A rectangle with a small black triangle on the lower right corner

    Most of these elements are shown below. The class or interface being described in the current chapter is shaded grey (this is not applicable for package class diagrams). A solid line represents extends, while a dotted line represents implements.

    Example class diagram

[Top] [Prev] [Next] [Bottom]
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Limitations (Java IDL/Java RMI over IIOP Technologies)

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Limitations (Java IDL/Java RMI over IIOP)

This document lists some of the limitations regarding Java IDL and Java RMI over IIOP technology in this release of the Java 2 Platform Standard Edition (J2SE). The limitations are outlined below.

The Official Specifications for CORBA Support in J2SE 5.0 document provides information outlining with which OMG Specifications this implementation of the Java IDL and Java RMI over IIOP technologies comply.

LIMITATIONS:

  • Java SDK version interoperability When a J2SE 1.3.x client talks to a server written in J2SE 1.4 or higher using RMI-IIOP and an unchecked or RemoteException is thrown by the server, the client will hang. Similarly, when the server is using J2SE 1.3.x and the client is using J2SE 1.4 or higher, the client will receive a CORBA UNKNOWN exception with minor code 0.

    This issue is currently being addressed at the OMG in the Java to IDL RTF as issue 4795: http://www.omg.org/issues/java2idl-rtf.html#Issue4795.

    In J2SE 1.4.1 and higher: If one side is using J2SE 1.3.1.05, and the other side is using J2SE 1.4.1 or higher on the other side, this type of communication will work properly.

  • Multiple Profile IOR If an IOR has multiple profiles, the first IIOP profile is used for the invocation.

  • Multiple ORBs not allowed in persistent servers This release of Java SE platform does not allow multiple ORB instantiations in persistent servers. If the persistent server is written using the Java RMI over IIOP APIs, instantiating JNDI's InitialContext() creates an ORB. To avoid creating multiple ORBs in this setting, you can set the java.naming.ORB system property to an ORB that is already initialized.

  • Locally-optimized stubs Locally-optimized stubs, those with the local optimization generated by a different IDL-to-Java compiler than idlj, may be used with the J2SE 1.4 or higher ORB. However, Portable Interceptors will not be invoked when taking the locally-optimized stub branch. This is due to an issue with the OMG IDL to Java language mapping and is being addressed under OMG issue 4701.

    The J2SE 1.4 or higher rmic compiler generates locally optimized stubs when used in conjunction with the -iiop option. However, the J2SE 1.4 and higher implementation of javax.rmi.CORBA.Util always returns false for isLocal. The result is that the stubs never use the local optimization. This is due to an issue with the OMG Java to IDL language mapping and is addressed under OMG issue 3754.

    The J2SE 1.4 and higher ORB does use a locally-optimized transport for both Java IDL and Java RMI-IIOP when it detects that the client and server are running sharing the same ORB.

  • Single thread POA policy As per the CORBA 2.3.1 specification, there can be two choices for Thread Policy for the Portable Object Adapter (POA): The ORB Controlled Model and the Single Thread Model. J2SE 5.0 does not support the Single Thread Model.

  • RMI-IIOP Stream Format version 2 If the super-type of a class has evolved to become custom-marshalled and writes optional, custom data, then that class cannot be sent between J2SE 1.3.x and J2SE 1.4 or higher. One example of this is that java.util.Calendar in J2SE 1.4 or higher cannot be sent back to J2SE 1.3.x.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.source.tree.LineMap (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.LineMap

  • Packages that use LineMap
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).

    • Uses of LineMap in com.sun.source.tree

      Methods in com.sun.source.tree that return LineMap
      Modifier and Type Method and Description
      LineMap CompilationUnitTree.getLineMap()
      Gets the line map for this compilation unit, if available.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.stylesheets.LinkStyle (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.stylesheets.LinkStyle

No usage of org.w3c.dom.stylesheets.LinkStyle
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.connect.ListeningConnector (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.connect.ListeningConnector

  • Packages that use ListeningConnector
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of ListeningConnector in com.sun.jdi

      Methods in com.sun.jdi that return types with arguments of type ListeningConnector
      Modifier and Type Method and Description
      List<ListeningConnector> VirtualMachineManager.listeningConnectors()
      Returns the list of known ListeningConnector objects.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.LiteralTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.LiteralTree

  • Packages that use LiteralTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of LiteralTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type LiteralTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitLiteral(LiteralTree node, P p)

    • Uses of LiteralTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type LiteralTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitLiteral(LiteralTree node, P p)
      R | SimpleTreeVisitor.visitLiteral(LiteralTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.LocalVariable (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.LocalVariable

  • Packages that use LocalVariable
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of LocalVariable in com.sun.jdi

      Methods in com.sun.jdi that return LocalVariable
      Modifier and Type Method and Description
      LocalVariable StackFrame.visibleVariableByName(String name)
      Finds a LocalVariable that matches the given name and is visible at the current frame location.
      Methods in com.sun.jdi that return types with arguments of type LocalVariable
      Modifier and Type Method and Description
      List<LocalVariable> Method.arguments()
      Returns a list containing each LocalVariable that is declared as an argument of this method.
      Map<LocalVariable,Value> StackFrame.getValues(List<? extends LocalVariable> variables)
      Returns the values of multiple local variables in this frame.
      List<LocalVariable> Method.variables()
      Returns a list containing each LocalVariable declared in this method.
      List<LocalVariable> Method.variablesByName(String name)
      Returns a list containing each LocalVariable of a given name in this method.
      List<LocalVariable> StackFrame.visibleVariables()
      Returns a list containing each LocalVariable that can be accessed from this frame's location.
      Methods in com.sun.jdi with parameters of type LocalVariable
      Modifier and Type Method and Description
      Value StackFrame.getValue(LocalVariable variable)
      Gets the Value of a LocalVariable in this frame.
      void StackFrame.setValue(LocalVariable variable, Value value)
      Sets the Value of a LocalVariable in this frame.
      Method parameters in com.sun.jdi with type arguments of type LocalVariable
      Modifier and Type Method and Description
      Map<LocalVariable,Value> StackFrame.getValues(List<? extends LocalVariable> variables)
      Returns the values of multiple local variables in this frame.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.Locatable (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.Locatable

  • Packages that use Locatable
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.
    com.sun.jdi.event
    This package defines JDI events and event processing.
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of Locatable in com.sun.jdi

      Subinterfaces of Locatable in com.sun.jdi
      Modifier and Type Interface and Description
      interface  Method
      A static or instance method in the target VM.
      interface  StackFrame
      The state of one method invocation on a thread's call stack.

    • Uses of Locatable in com.sun.jdi.event

      Subinterfaces of Locatable in com.sun.jdi.event
      Modifier and Type Interface and Description
      interface  AccessWatchpointEvent
      Notification of a field access in the target VM.
      interface  BreakpointEvent
      Notification of a breakpoint in the target VM.
      interface  ExceptionEvent
      Notification of an exception in the target VM.
      interface  LocatableEvent
      Abstract superinterface of events which have both location and thread.
      interface  MethodEntryEvent
      Notification of a method invocation in the target VM.
      interface  MethodExitEvent
      Notification of a method return in the target VM.
      interface  ModificationWatchpointEvent
      Notification of a field modification in the target VM.
      interface  MonitorContendedEnteredEvent
      Notification that a thread in the target VM is entering a monitor after waiting for it to be released by another thread.
      interface  MonitorContendedEnterEvent
      Notification that a thread in the target VM is attempting to enter a monitor that is already acquired by another thread.
      interface  MonitorWaitedEvent
      Notification that a thread in the target VM has finished waiting on an monitor object.
      interface  MonitorWaitEvent
      Notification that a thread in the target VM is about to wait on a monitor object.
      interface  StepEvent
      Notification of step completion in the target VM.
      interface  WatchpointEvent
      Notification of a field triggered event encountered by a thread in the target VM.

    • Uses of Locatable in com.sun.jdi.request

      Subinterfaces of Locatable in com.sun.jdi.request
      Modifier and Type Interface and Description
      interface  BreakpointRequest
      Identifies a Location in the target VM at which execution should be stopped.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.event.LocatableEvent (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.event.LocatableEvent

  • Packages that use LocatableEvent
    Package Description
    com.sun.jdi.event
    This package defines JDI events and event processing.

    • Uses of LocatableEvent in com.sun.jdi.event

      Subinterfaces of LocatableEvent in com.sun.jdi.event
      Modifier and Type Interface and Description
      interface  AccessWatchpointEvent
      Notification of a field access in the target VM.
      interface  BreakpointEvent
      Notification of a breakpoint in the target VM.
      interface  ExceptionEvent
      Notification of an exception in the target VM.
      interface  MethodEntryEvent
      Notification of a method invocation in the target VM.
      interface  MethodExitEvent
      Notification of a method return in the target VM.
      interface  ModificationWatchpointEvent
      Notification of a field modification in the target VM.
      interface  MonitorContendedEnteredEvent
      Notification that a thread in the target VM is entering a monitor after waiting for it to be released by another thread.
      interface  MonitorContendedEnterEvent
      Notification that a thread in the target VM is attempting to enter a monitor that is already acquired by another thread.
      interface  MonitorWaitedEvent
      Notification that a thread in the target VM has finished waiting on an monitor object.
      interface  MonitorWaitEvent
      Notification that a thread in the target VM is about to wait on a monitor object.
      interface  StepEvent
      Notification of step completion in the target VM.
      interface  WatchpointEvent
      Notification of a field triggered event encountered by a thread in the target VM.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.Location (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.Location

  • Packages that use Location
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.
    com.sun.jdi.event
    This package defines JDI events and event processing.
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of Location in com.sun.jdi

      Methods in com.sun.jdi that return Location
      Modifier and Type Method and Description
      Location StackFrame.location()
      Returns the Location of the current instruction in the frame.
      Location Locatable.location()
      Returns the Location of this mirror, if there is executable code associated with it.
      Location Method.location()
      Returns the Location of this method, if there is executable code associated with it.
      Location Method.locationOfCodeIndex(long codeIndex)
      Returns a Location for the given code index.
      Methods in com.sun.jdi that return types with arguments of type Location
      Modifier and Type Method and Description
      List<Location> Method.allLineLocations()
      Returns a list containing a Location object for each executable source line in this method.
      List<Location> ReferenceType.allLineLocations()
      Returns a list containing a Location object for each executable source line in this reference type.
      List<Location> Method.allLineLocations(String stratum, String sourceName)
      Returns a list containing a Location object for each executable source line in this method.
      List<Location> ReferenceType.allLineLocations(String stratum, String sourceName)
      Returns a list containing a Location object for each executable source line in this reference type.
      List<Location> Method.locationsOfLine(int lineNumber)
      Returns a List containing all Location objects that map to the given line number.
      List<Location> ReferenceType.locationsOfLine(int lineNumber)
      Returns a List containing all Location objects that map to the given line number.
      List<Location> Method.locationsOfLine(String stratum, String sourceName, int lineNumber)
      Returns a List containing all Location objects that map to the given line number and source name.
      List<Location> ReferenceType.locationsOfLine(String stratum, String sourceName, int lineNumber)
      Returns a List containing all Location objects that map to the given line number.

    • Uses of Location in com.sun.jdi.event

      Methods in com.sun.jdi.event that return Location
      Modifier and Type Method and Description
      Location ExceptionEvent.catchLocation()
      Gets the location where the exception will be caught.

    • Uses of Location in com.sun.jdi.request

      Methods in com.sun.jdi.request that return Location
      Modifier and Type Method and Description
      Location BreakpointRequest.location()
      Returns the location of the requested breakpoint.
      Methods in com.sun.jdi.request with parameters of type Location
      Modifier and Type Method and Description
      BreakpointRequest EventRequestManager.createBreakpointRequest(Location location)
      Creates a new disabled BreakpointRequest.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Java RMI Implementation Logging

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

JavaTM RMI Implementation Logging
in JDKTM 6

As of JavaTM SE Development Kit (JDK) v1.4, Sun's Java Remote Method Invocation (Java RMI) implementation uses the Logging APIs to provide implementation logging output. The logging configuration file and programmatic API (java.util.logging) can be used to configure Java RMI implementation logging.

The java.rmi.server.logCalls system property and the implementation-specific sun.rmi.* logging properties that were recognized by previous JDK versions still function to set the default levels for the Java RMI implementation Logger objects and to cause their output to be directed to System.err as with earlier versions.

The table below shows the names of the Logger objects used by the Java RMI implementation and how they correspond to the logging properties supported by previous versions.

Note that the Java RMI implementation supports a logging category, client-side call logging, which is analogous to the server-side call logging activated by the java.rmi.server.logCalls property. Client-side call logging is output to the Logger named sun.rmi.client.call.

System Property Name | Logger Name | Information Logged
java.rmi.server.logCalls | sun.rmi.server.call | server-side remote calls and exceptions
sun.rmi.server.logLevel | sun.rmi.server.ref | server-side remote reference activity
sun.rmi.client.logCalls (new in J2SE 1.4) | sun.rmi.client.call | client-side remote calls and exceptions
sun.rmi.client.logLevel | sun.rmi.client.ref | client-side remote reference activity
sun.rmi.dgc.logLevel | sun.rmi.dgc | distributed garbage collection activity
sun.rmi.loader.logLevel | sun.rmi.loader | activity of default RMIClassLoader provider
sun.rmi.transport.logLevel | sun.rmi.transport.misc | transport-layer activity
sun.rmi.transport.tcp.logLevel | sun.rmi.transport.tcp | TCP binding and connection activity
sun.rmi.transport.proxy.logLevel | sun.rmi.transport.proxy | HTTP tunnelling activity
(none) | sun.rmi.runtime | miscellaneous runtime activity

For both the sun.rmi.client.call and the sun.rmi.server.call Loggers, exceptions thrown from remote calls are logged at the level Level.FINE, and each remote call is logged at the level Level.FINER. Setting the java.rmi.server.logCalls or sun.rmi.client.logCalls system properties to the value "true" causes the corresponding Logger to be set to the level Level.FINER.

For the sun.rmi.* logging properties that have names ending in ".logLevel", a value of "BRIEF" causes the corresponding Logger to be set to the level Level.FINE, and a value of "VERBOSE" causes the corresponding Logger to be set to the level Level.FINER. Use of the logging configuration file is now preferred over the use of these sun.rmi.* system properties for logging.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JAAS Login Configuration File

JAAS authentication is performed in a pluggable fashion, so Java applications can remain independent from underlying authentication technologies. Configuration information such as the desired authentication technology is specified at runtime. The source of the configuration information (for example, a file or a database) is up to the current javax.security.auth.login.Configuration implementation. The default Configuration implementation from Sun Microsystems reads configuration information from configuration files, which are described in this document.

Login Configuration File Structure and Contents

A login configuration file consists of one or more entries, each specifying which underlying authentication technology should be used for a particular application or applications. The structure of each entry is the following:

<entry name> {
    <LoginModule> <flag> <LoginModule options>;
    <LoginModule> <flag> <LoginModule options>;
    . . .
    };

Thus, each login configuration file entry consists of a name followed by one or more LoginModule-specific items. Each LoginModule-specific item specifies a LoginModule, a flag value, and options to be passed to the LoginModule. (These are described futher below.) Each LoginModule-specific item is terminated by a semicolon and the entire group of items is enclosed in braces. Each configuration file entry is terminated by a semicolon.

As an example, the login configuration file used for the JAAS Authentication tutorial contains just one entry, which is

JaasSample {
  com.sun.security.auth.module.Krb5LoginModule required;
};

Here, the entry is named "JaasSample" and that is the name that the JAAS Authentication tutorial application (JaasAcn.java) uses to refer to this entry. The entry specifies that the LoginModule to be used to do the user authentication is the Krb5LoginModule in the com.sun.security.auth.module package and that this Krb5LoginModule is required to "succeed" in order for authentication to be considered successful. The Krb5LoginModule succeeds only if the name and password supplied by the user are successfully used to log the user into the Kerberos KDC.

The name for an entry in a login configuration file is the name that applications use to refer to the entry when they instantiate a LoginContext, as described in Instantiating a LoginContext in the JAAS authentication tutorial. The name can be whatever name the application developer wishes to use. Here, the term "application" refers to whatever code does the JAAS login, whether it is your application (as shown in the JAAS Authentication and JAAS Authorization tutorials) or a Login utility that does the JAAS operations for you (as shown in the Use of JAAS Login Utility and Use of Java GSS-API for Secure Message Exchanges Using JAAS Login Utility tutorials.)

The subparts of each LoginModule-specific item are described by the following. See the Configuration documentation for more information.

  • LoginModule

    This specifies the fully qualified class name for a class that implements a particular authentication technology. Specifically, the class must implement the javax.security.auth.spi.LoginModule interface. A typical LoginModule may prompt for and verify a user name and password. Any vendor can provide a LoginModule implementation that you can use. Some implementations are supplied with the JRE from Sun Microsystems. Throughout these tutorials we use the Krb5LoginModule in the com.sun.security.auth.module package. The Krb5LoginModule uses Kerberos as the underlying authentication technology. You can view the reference documentation for the various LoginModules, all in the com.sun.security.auth package:

    • JndiLoginModule
    • KeyStoreLoginModule
    • Krb5LoginModule
    • NTLoginModule
    • UnixLoginModule
  • flag

    The flag value indicates whether success of the LoginModule is "required", "requisite", "sufficient", or "optional".

  • LoginModule options

    If the specified LoginModule implementation has options that can be set, you specify any desired option values here. This is a space-separated list of values which are passed directly to the underlying LoginModule. Options are defined by the LoginModule itself, and control the behavior within it. For example, a LoginModule may define options to support debugging/testing capabilities. See the Krb5LoginModule documentation for information about the options defined for the Krb5LoginModule used for all the tutorials in this series.

    The correct way to specify options in the configuration file is by using a name-value pairing, for example debug=true, where the option name (in this case, "debug") and value (in this case, "true") should be separated by an "equals" symbol.

Where to Specify Which Login Configuration File Should Be Used

The configuration file to be used can be specified in one of two ways:

  1. On the command line.

    You can use a -Djava.security.auth.login.config command line argument to specify the login configuration file that should be used. We use this approach for all the tutorials. For example, we run our JaasAcn application in the JAAS Authentication tutorial using the following command, which specifies that the configuration file is the jaas.conf file in the current directory:

    java -Djava.security.auth.login.config=jaas.conf JaasAcn
  2. In the Java security properties file.

    An alternate approach to specifying the location of the login configuration file is to indicate its URL as the value of a login.config.url.n property in the security properties file. The security properties file is the java.security file located in the lib/security directory of the JRE.

    Here, n indicates a consecutively-numbered integer starting with 1. Thus, if desired, you can specify more than one login configuration file by indicating one file's URL for the login.config.url.1 property, a second file's URL for the login.config.url.2 property, and so on. If more than one login configuration file is specified (that is, if n > 1), then the files are read and concatenated into a single configuration.

    Here is an example of what would need to be added to the security properties file in order to indicate the jaas.conf login configuration file used by this tutorial. This example assumes the file is in the C:\AcnTest directory on a Microsoft Windows system:

    login.config.url.1=file:C:/AcnTest/jaas.conf
    (Note that URLs always use forward slashes, regardless of what operating system the user is running.)
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Use of JAAS Login Utility

The previous two tutorials, JAAS Authentication and JAAS Authorization, show how you can use the LoginContext and Subject classes to write a program to

  • authenticate the user to verify his or her identity and
  • associate an instance of a particular class representing the user (a Subject instance) with an access control context in such a way that subsequent security-sensitive operations will be allowed if the current policy grants the user the required permissions.

This tutorial describes a Login utility that performs the above operations and then executes any specified application as the authenticated user.

Use of the Login utility with a sample application is demonstrated in this tutorial. The next tutorial, a client/server application using the Java GSS-API, also uses the Login utility.

It is not necessary to read the previous two tutorials on JAAS authentication and authorization prior to reading this one. However, you may want to refer to some sections in those tutorials to obtain further details regarding certain topics, such as how to make user-based policy file statements. You should also read JAAS Login Configuration File for information as to what a login configuration file is, since one is needed for this and all other tutorials in this series.

As with all tutorials in this series of tutorials, the underlying technology used to support authentication is Kerberos. See Kerberos Requirements.

  • What You Need to Know About the Login Utility
  • Application and Other File Requirements
  • The Sample Application Program
  • The Login Configuration File
  • The Policy File
  • Running the Sample Program with the Login Utility

If you want to first see the tutorial code in action, you can skip directly to Running the Sample Program with the Login Utility and then go back to the other sections to learn more.

What You Need to Know About the Login Utility

You do not need to understand the code contained in Login.java; you can just use it as is. However, you need to understand some facts about what it does so that your program, policy file, and login configuration file will properly work with it. Below is a summary of these facts, followed by sections with further information and examples.

The Login class does the following:

  • Assumes it is passed, as arguments, your application's top-level class name, followed by any arguments your application may require.
  • Assumes that the class name of your top-level application class is also used as the name of the entry to be looked up in your login configuration file.
  • Specifies the TextCallbackHandler class (from the com.sun.security.auth.callback package) as the class to be used when communicating with the user. This class can prompt the user for a user name and password.
  • Uses a LoginContext to authenticate the user. The LoginContext invokes the appropriate authentication technology, or LoginModule, to perform the authentication. LoginModules use a CallbackHandler (in our case, TextCallbackHandler) as needed to communicate with the user.
  • Allows the user three attempts to successfully log in.
  • Creates an instance of the MyAction class (also in Login.java), passing it the application arguments, if any.
  • Invokes Subject.doAsPrivileged, passing it a Subject representing the user, the MyAction instance, and a null AccessControlContext. The result is that the public static main method from your application is invoked and your application code is considered to be executed on behalf of the user.

Application and Other File Requirements

To utilize the Login utility to authenticate the user and execute your application, you may need a small number of additions or modifications to your login configuration file and policy file, as described in the following.

  • Application Requirements
  • Login Configuration File Requirements
  • Policy File Requirements

Application Requirements

In order to utilize the Login utility, your application code does not need anything special. All you need is for the entry point of your application to be the main method of a class you write, as usual.

The way to invoke Login such that it will authenticate the user and then instantiate MyAction to invoke your application is the following:

java <options> Login <AppName> <app arguments>
where <AppName> is your application's top-level class name and <app arguments> are any arguments required by your application. See Running the Sample Program with the Login Utility for the full command used for this tutorial.

Login Configuration File Requirements

Whenever a LoginContext is used to authenticate the user, you need a login configuration file to specify the desired login module. See the The Login Configuration File section in the JAAS authentication tutorial for more information as to what a login configuration file is and what it contains.

When you use the Login utility, the name for the login configuration file entry must be exactly the same as your top-level application class name. See The Login Configuration File in this tutorial for an example.

Policy File Requirements

Whenever you run an application with a security manager, you need a policy indicating the permissions granted to specific code, or to specific code being executed by a specific user (or users). One way of specifying the policy is by grant statements in a policy file. See The Policy File for more information.

If you use the Login utility to invoke your application, then you will need to grant it various permissions, as described in Permissions Required by the Login and MyAction Classes.

The Sample Application Program

The Sample.java application used for this tutorial performs the same actions as the SampleAction.java application did in the previous (JAAS Authorization) tutorial. It does the following:
  • Reads and prints the value of the java.home system property,
  • Reads and prints the value of the user.home system property, and
  • Determines whether or not a file named foo.txt exists in the current directory.

Here is the code:

import java.io.File;

public class Sample {

  public static void main (String[] args) throws SecurityException {

    // If there were any arguments to read, we'd do it here.

    System.out.println("\nYour java.home property value is: "
                +System.getProperty("java.home"));

    System.out.println("\nYour user.home property value is: "
                +System.getProperty("user.home"));

    File f = new File("foo.txt");
    System.out.print("\nfoo.txt does ");
    if (!f.exists())
        System.out.print("not ");
    System.out.println("exist in the current working directory.");
  }
}

The Login Configuration File

The sample.conf login configuration file for this tutorial contains a single entry, just like the login configuration file for the previous (JAAS Authorization) tutorial. The entry contents are the same since the class implementing the desired authentication technology in both cases is the Krb5LoginModule in the com.sun.security.auth.module package.

The only difference is the name used for the entry. In the previous tutorial we used the name "JaasSample", since that is the name used by the JaasAzn class to look up the entry. When you use the Login utility with your application, it expects the name for your login configuration file entry to be the same as the name of your top-level application class. That application class for this tutorial is named "Sample" so that must also be the name of the login configuration file entry. Thus the login configuration file looks like the following:

Sample {
   com.sun.security.auth.module.Krb5LoginModule required;
};

The "required" indicates that login using the Krb5LoginModule is required to "succeed" in order for authentication to be considered successful. The Krb5LoginModule succeeds only if the name and password supplied by the user are successfully used to log the user into the Kerberos KDC.

For information about all the possible options that can be passed to Krb5LoginModule, see the Krb5LoginModule documentation.

The Policy File

The Login, MyAction, and Sample classes all perform some security-sensitive operations and thus relevant permissions are required in a policy file in order for the operations to be executed.

Permissions Required by the Login and MyAction Classes

For this tutorial, you will create a Login.jar JAR file containing the Login.class and MyAction.class files. You need to grant Login.jar various permissions, specifically the ones required for invoking the security-sensitive methods the Login.jar classes call, as well as all the permissions required by your application. Otherwise, access control checks will fail.

The simplest thing to do, and what we recommend, is to grant Login.jar AllPermission. For this tutorial, the Login.jar file is assumed to be in the current directory and the policy file includes the following:

grant codebase "file:./Login.jar" {
   permission java.security.AllPermission;
};

Permissions Required by Sample

(Note: This section is essentially a modified copy of the Permissions Required by SampleAction section from the previous (JAAS Authorization) tutorial, since Sample and SampleAction perform the same operations and thus require the same permissions.)

The Sample code does three operations for which permissions are required. It

  • reads the value of the "java.home" system property.
  • reads the value of the "user.home" system property.
  • checks to see whether or not a file named foo.txt exists in the current directory.

The permissions required for these operations are the following:

permission java.util.PropertyPermission "java.home", "read";
permission java.util.PropertyPermission "user.home", "read";
permission java.io.FilePermission "foo.txt", "read";

We need to grant these permissions to the code in Sample.class, which we will place in a JAR file named Sample.jar. However, our grant statement will grant the permissions not just to the code but to a specific authenticated user executing the code. This illustrates how you can use a Principal designation in a grant statement to restrict execution of security-sensitive operations in code to a specific user rather than allowing the permissions to all users executing the code.

Thus, as explained in How Do You Make Principal-Based Policy File Statements?, our grant statement looks like the following:

grant codebase "file:./Sample.jar",
    Principal javax.security.auth.kerberos.KerberosPrincipal
        "your_user_name@your_realm"  {

   permission java.util.PropertyPermission "java.home", "read";
   permission java.util.PropertyPermission "user.home", "read";
   permission java.io.FilePermission "foo.txt", "read";
};
Important: You must substitute your Kerberos user name (complete with "@" and realm) for "your_user_name@your_realm". For example, if your user name is "mjones" and your realm is "KRBNT-OPERATIONS.ABC.COM", you would use "mjones@KRBNT-OPERATIONS.ABC.COM" (complete with the quotes).

The Full Policy File

The full policy file is sample.policy.

Running the Sample Program with the Login Utility

To execute the Sample application with the Login utility, do the following:

  1. Place the following files into a directory:
    • The Login.java source file.
    • The Sample.java source file.
    • The sample.conf login configuration file.
    • The sample.policy policy file.
  2. Replace "your_user_name@your_realm" in sample.policy with your user name and realm.
  3. Compile Login.java and Sample.java:
    javac Login.java Sample.java

    Note that Login.java contains two classes and thus compiling Login.java creates Login.class and MyAction.class.

  4. Create a JAR file named Login.jar containing Login.class and MyAction.class:
    jar -cvf Login.jar Login.class MyAction.class
  5. Create a JAR file named Sample.jar containing Sample.class:
    jar -cvf Sample.jar Sample.class
  6. Execute the Login class, specifying
    • by an appropriate -classpath clause that classes should be searched for in the Login.jar and Sample.jar JAR files,
    • by -Djava.security.manager that a security manager should be installed,
    • by -Djava.security.krb5.realm=<your_realm> that your Kerberos realm is the one specified.
    • by -Djava.security.krb5.kdc=<your_kdc> that your Kerberos KDC is the one specified.
    • by -Djava.security.policy=sample.policy that the policy file to be used is sample.policy, and
    • by -Djava.security.auth.login.config=sample.conf that the login configuration file to be used is sample.conf.

    You pass the name of your application (in this case, "Sample") as an argument to Login. You would then add as arguments any arguments required by your application, but in our case Sample does not require any.

    Below are the full commands to use for both Microsoft Windows and Unix systems. The only difference is that on Windows systems you use semicolons to separate classpath items, while you use colons for that purpose on Unix systems. Be sure to replace <your_realm> with your Kerberos realm, and <your_kdc> with your Kerberos KDC.

    Here is the full command for Windows systems:

    java -classpath Login.jar;Sample.jar
 -Djava.security.manager
 -Djava.security.krb5.realm=<your_realm>
 -Djava.security.krb5.kdc=<your_kdc>
 -Djava.security.policy=sample.policy
 -Djava.security.auth.login.config=sample.conf Login Sample

    Here is the full command for UNIX systems:

    java -classpath Login.jar:Sample.jar
 -Djava.security.manager
 -Djava.security.krb5.realm=<your_realm>
 -Djava.security.krb5.kdc=<your_kdc>
 -Djava.security.policy=sample.policy
 -Djava.security.auth.login.config=sample.conf Login Sample

    Type the full command on one line. Multiple lines are used here for legibility. If the command is too long for your system, you may need to place it in a .bat file (for Windows) or a .sh file (for UNIX) and then run that file to execute the command.

    You will be prompted for your Kerberos user name and password, and the underlying Kerberos login module specified in the login configuration file will log you into Kerberos. Once authentication is successfully completed, the Sample code will be executed on behalf of you, the user. The sample.policy policy file grants you the required permissions, so you will see a display of the values of your java.home and user.home system properties and a statement as to whether or not you have a file named foo.txt in the current directory.

    For login troubleshooting suggestions, see Troubleshooting.

Tutorials Introduction and TOC
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.LongType (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.LongType

No usage of com.sun.jdi.LongType
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.LongValue (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.LongValue

  • Packages that use LongValue
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of LongValue in com.sun.jdi

      Methods in com.sun.jdi that return LongValue
      Modifier and Type Method and Description
      LongValue VirtualMachine.mirrorOf(long value)
      Creates a LongValue for the given value.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Contents | Previous | Next Java Management Extensions (JMX) Technology Tutorial

Chapter 4

Lookup Services

The Java Management Extensions (JMX) specification defines three bindings to lookup services, using existing lookup technologies, as described in the following sections:

  • Section "Initial Configuration" provides configuration information that applies to all three types of lookup service.
  • Section "Service Location Protocol (SLP) Lookup Service" presents the SLP lookup example.
  • Section "Jini Lookup Service" presents the Jini lookup example.
  • Section "Java Naming and Directory Interface (JNDI) / LDAP Lookup Service" presents the JNDI/LDAP lookup example.

The lookup services allow JMX technology clients to find and connect to connector servers that have registered with the lookup services.

Initial Configuration

As shown simply in Section "Accessing Standard and Dynamic MBeans via the RMI Connector", if you are using remote method invocation (RMI) connectors, you can choose to use an external directory to register the connector server stubs you want to look up. The following cases are presented in the lookup service examples relating to RMI connectors:

  • RMI connectors using one of the following external directories:
  • An RMI registry, for RMI connectors implementing the default Java Remote Method Protocol (JRMP) transport
  • CORBA Naming Service, for RMI connectors implementing the Internet Inter-ORB Protocol (IIOP) transport
  • Lightweight Directory Access Protocol (LDAP), for both the IIOP and JRMP transports
  • RMI connectors without an external directory

If you choose to register the RMI connector stubs in an external directory, some initial configuration is required, to set up your RMI registry, CORBA naming service or LDAP server. If you do not use an external directory, the RMI connector stub is encoded into the JMX service URL.

The following sections describe the external directories that you can use in conjunction with the lookup service examples that use RMI connectors. These external directories are referred to when running the three examples of lookup services that are given in the subsequent sections in this chapter.

External RMI Registry

To register the RMI connector server stubs in an external RMI registry, for use by connectors implementing the JRMP transport, perform the following actions:

  2. Start the RMI registry on port 9999 of the local host.

    As was the case in Chapter 3, "JMX Connectors", the RMI registry is used to store the RMI connector stubs for RMI connectors implementing the JRMP transport.

    $ rmiregistry 9999 &

  3. For your convenience when typing commands, create an environment variable for the address of the RMI registry.

    To shorten the commands that you will type when you run the examples, set the service URL for the RMI registry as an environment variable, jndirmi. In these examples, the service URL is given in JNDI form. See the API documentation for the javax.management.remote.rmi package for an explanation of JNDI form. If you want to run the external directories on a machine other than the local machine, you must specify that machine’s host name instead of localhost.

    $ jndirmi="rmi://localhost:9999"

External CORBA Naming Service

To register the RMI connector server stubs in an external CORBA naming service, for use by connectors implementing the IIOP transport, perform the following actions:

  2. Start an Object Request Broker (ORB) daemon on port 7777 of the local host.

    RMI connectors that implement the IIOP transport can use CORBA naming to identify the RMI connector stub.

    $ orbd -ORBInitialPort 7777 &

  3. For your convenience when typing commands, create an environment variable for the address of the CORBA naming service.

    To shorten the commands that you type when you run the examples, set the service URL for the CORBA naming service as an environment variable, jndiiiop. In these examples, the service URL is given in JNDI form. If you want to run the external directories on a machine other than the local machine, you must specify that machine’s host name instead of localhost.

    $ jndiiiop="iiop://localhost:7777"

External LDAP Registry

To register the RMI connector server stubs in an external LDAP registry, for use by connectors implementing either of the JRMP or IIOP transports, perform the following actions:

  2. Start an LDAP Server.

    The LDAP server you use is your choice, although the schema for representing Java objects in an LDAP directory must be known to the server. See the relevant Request For Comments (RFC) document for details:

    http://www.ietf.org/rfc/rfc2713.txt

  3. Create a domain component suffix.

    These examples require that you create the following domain component suffix:

    dc=Test

    See the documentation accompanying your LDAP server for details of how to configure the server and create this suffix.

  4. For your convenience, set the following LDAP parameters as environment variables.

    These variables are used to shorten the commands you type when starting the Server and Client classes in the lookup service examples that register RMI connector stubs in the external LDAP server.

    2. The name of the machine running your LDAP server (ldap_host)

      $ ldaphost=ldap_host

    3. The port the LDAP server is running on (ldap_port)

      $ ldapport=ldap_port

    4. The LDAP common name attribute, which in these examples is “Directory Manager”

      $ principal=”cn=Directory Manager”

    5. The password required by your LDAP server

      Supply the password for your LDAP server.

      $ credentials=your_ldap_password

    6. The address of the LDAP server

      In this example, the service URL for the LDAP server is given in JNDI form and is identified by the variable jndildap.

      $ jndildap="ldap://$ldaphost:$ldapport"

    • You are now ready to run the different lookup service examples.

Service Location Protocol (SLP) Lookup Service

The JMX technology specifies how to register RMI connectors with the SLP lookup service.

The purpose of this example is to demonstrate how a JMX Remote API connector client can find and connect to a connector server that has registered with the SLP lookup service. This example performs the following operations:

  • The agent:
  • Creates an MBean server
  • Gets a pointer to the SLP lookup service
  • Creates a connector server
  • Registers the connector address with the SLP lookup service
  • The client:
  • Gets a pointer to the SLP lookup service
  • Looks for any connector servers registered in the SLP lookup service
  • Creates a JMX Remote API connector
  • Retrieves information about the MBeans in the MBean server

This example assumes that you are already familiar with SLP technology. The code provided for this example conforms to Sun Microsystems’ implementation of SLP, as defined by RFC 2614 (see http://www.ietf.org/rfc/rfc2614.txt). Sun Microsystems’ implementation of SLP is available in the Solaris operating environment in the directory/usr/share/lib/slp. If you are not running the Solaris operating environment, you must obtain a version of SLP that is compliant with RFC 2614, section 5. You can download the OpenSLP Java implementation from http://www.openslp.org/.

The SLP lookup example is contained in the directory work_dir/jmx_examples/Lookup/slp.

  2. Open work_dir/jmx_examples/Lookup/slp.

    Inside this directory, you will find the following files:

    • Server.java
    • Client.java
    • README
  3. Open both the *.java files in a text editor.

    These classes will be analyzed in the following sections.

Analyzing the Example Classes

The following sections analyze each of the classes used in the SLP lookup example, and explain how they perform the operations described above.

Note – If you are using an implementation of SLP other than Sun Microsystems’ implementation, you will have to modify Server.java and Client.java to import your version of the SLP Java classes instead of the com.sun.slp package. See RFC 2614, section 5.

Server.java

Due to its size, the SLP lookup service Server.java class is shown as a series of code excerpts. For explanations of the SLP code used in this example, see RFC 2614 and the API documentation for SLP.

CODE EXAMPLE 4-1 SLP Lookup Service Example Class Server.java (Excerpt 1)

public class Server {
   public final static int JMX_DEFAULT_LEASE = 300;
   public final static String JMX_SCOPE = "DEFAULT";

   private final MBeanServer mbs;
   public Server() {
       mbs = MBeanServerFactory.createMBeanServer();
   }

[...]

CODE EXAMPLE 4-1 sets the default SLP lease JMX_DEFAULT_LEASE to a default lease of 300 seconds, corresponding to the length of time the URL will be registered, and shows the initial creation of the MBean server mbs.

In code that is not shown here, you then define an SLP advertiser slpAdvertiser, and an SLP service URL url. The slpAdvertiser is used to register the service URL in the SLP lookup service. The SCOPE and the agentName are registered in SLP as lookup attributes.

CODE EXAMPLE 4-2 SLP Lookup Service Example Class Server.java (Excerpt 2)

[...]

   public static void register(JMXServiceURL jmxUrl, String name)
     throws ServiceLocationException {
     ServiceURL serviceURL =
          new ServiceURL(jmxUrl.toString(),
                         JMX_DEFAULT_LEASE);
     debug("ServiceType is: " + serviceURL.getServiceType());
     Vector attributes = new Vector();
     Vector attrValues = new Vector();
     attrValues.add(JMX_SCOPE);
     ServiceLocationAttribute attr1 =
          new ServiceLocationAttribute("SCOPE", attrValues);
     attributes.add(attr1);
     attrValues.removeAllElements();
     attrValues.add(name);
     ServiceLocationAttribute attr2 =
          new ServiceLocationAttribute("AgentName", attrValues);
     attributes.add(attr2);
     final Advertiser slpAdvertiser =
          ServiceLocationManager.getAdvertiser(Locale.US);
     slpAdvertiser.register(serviceURL, attributes);

   }

[...]

CODE EXAMPLE 4-2 shows the registration of the JMX connector server’s URL with the SLP lookup service.

The JMX service URL jmxUrl is the address of the connector server, and is obtained by a call to the getAddress() method of JMXConnectorServer when the connector server is started.

The SLP lookup attributes, namely the scope and the agent name under which the connector server address is to be registered (name), are then specified by the SLP class ServiceLocationAttribute. The AgentName attribute is mandatory, but other optional attributes, such as ProtocolType, AgentHost, and Property can also be registered in the SLP lookup service.

Finally, the JMX connector server address is registered in the SLP service with a call to the register() method of the Advertiser interface, with the serviceURL and the attributes passed in as parameters.

CODE EXAMPLE 4-3 SLP Lookup Service Example Class Server.java (Excerpt 3)

[...]

   public JMXConnectorServer rmi(String url) throws
     IOException,
     JMException,
     NamingException,
     ClassNotFoundException,
     ServiceLocationException {
     JMXServiceURL jurl = new JMXServiceURL(url);
     final HashMap env = new HashMap();
     // Environment map attributes
     [...]

     JMXConnectorServer rmis =
        JMXConnectorServerFactory.newJMXConnectorServer(jurl, env, mbs);
     final String agentName = System.getProperty("agent.name",
                                                 "DefaultAgent");
     start(rmis, agentName);

     return rmis;
  }
[...]

CODE EXAMPLE 4-3 shows the creation of an RMI connector server. The JMX service URL jurl is constructed from the string url that is included in the command used to launch the Server at the command line. An RMI connector server named rmis is then created with the system properties defined by the environment map and the address jurl.

The connector server is then started, and the RMI connector server address is registered in the SLP lookup service under the name agentName.

CODE EXAMPLE 4-4 SLP Lookup Service Example Class Server.java (Excerpt 4)

[...]

   public void start(JMXConnectorServer server, String agentName)
      throws IOException, ServiceLocationException {
      server.start();
      final JMXServiceURL address = server.getAddress();
      register(address,agentName);
   }

[...]

CODE EXAMPLE 4-4 shows the launching of the connector server server and the registration of server in the SLP lookup service with the given address address.

Client.java

The SLP lookup service Client.java class is shown in CODE EXAMPLE 4-1, CODE EXAMPLE 4-2, and CODE EXAMPLE 4-3:

CODE EXAMPLE 4-1 SLP Lookup Service Example Class Client.java (Excerpt 1)

public class Client {

    public final static String JMX_SCOPE = "DEFAULT";

    public static Locator getLocator() throws ServiceLocationException {
      final Locator slpLocator =
          ServiceLocationManager.getLocator(Locale.US);
      return slpLocator;
    }

      public static List lookup(Locator slpLocator, String name)
          throws IOException, ServiceLocationException {

          final ArrayList list = new ArrayList();
          Vector scopes = new Vector();

          scopes.add(JMX_SCOPE);
          String query =
              "(&(AgentName=" + ((name!=null)?name:"*") + "))";

          ServiceLocationEnumeration result =
              slpLocator.findServices(new ServiceType("service:jmx"),
                                      scopes, query);

          while(result.hasMoreElements()) {
                final ServiceURL surl = (ServiceURL) result.next();

             JMXServiceURL jmxUrl = new JMXServiceURL(surl.toString());
             try {
                  JMXConnector client =
                     JMXConnectorFactory.newJMXConnector(jmxUrl,null);
                  if (client != null) list.add(client);
             } catch (IOException x ) {
             [...]
             }
          }
      }
      return list;
    }

CODE EXAMPLE 4-1 first of all obtains the SLP service Locator by calling the getLocator method of the SLP class ServiceLocationManager. Client then retrieves all the connector servers registered in the SLP service under a given agent name, or under agent names that match a certain pattern. If no agent name is specified when the Client is started, all agent names will be considered.

A JMX technology service URL, jmxUrl, is generated for each of the agents retrieved by SLP, with each agent’s SLP service URL, surl, passed as a parameter into the JMXServiceURL instance. The URL jmxUrl is then passed to the newJMXConnector() method of JMXConnectorFactory, to create a new connector client named client for each agent that is registered in the SLP service.

The connector clients retrieved are stored in an array list called list.

CODE EXAMPLE 4-2 SLP Lookup Service Example Class Client.java (Excerpt 2)

public static void listMBeans(MBeanServerConnection server)
     throws IOException {

     final Set names = server.queryNames(null,null);
     for (final Iterator i=names.iterator(); i.hasNext(); ) {
          ObjectName name = (ObjectName)i.next();
          System.out.println("Got MBean: "+name);
          try {
               MBeanInfo info =
                  server.getMBeanInfo((ObjectName)name);
               MBeanAttributeInfo[] attrs = info.getAttributes();
               if (attrs == null) continue;
               for (int j=0; j<attrs.length; j++) {
                    try {
                         Object o =
                         server.getAttribute(name,attrs[j].getName());
                         System.out.println("\t\t" + attrs[j].getName() +
                         " = "+o);
                    } catch (Exception x) {
                         System.err.println("JmxClient failed to get " +
                                             attrs[j].getName() + x);
                         x.printStackTrace(System.err);
                    }
     }
}

In CODE EXAMPLE 4-2, a reference to the MBeanServerConnection is retrieved for every connector client that is created from the connector server address stored in the SLP service. A list of all the MBeans and their attributes is retrieved.

CODE EXAMPLE 4-3 SLP Lookup Service Example Class Client.java (Excerpt 3)

public static void main(String[] args) {
      try {
           final String agentName = System.getProperty("agent.name");
           final Locator slpLocator = getLocator();
           List l = lookup(slpLocator,agentName);
           int j = 1;
           for (Iterator i=l.iterator();i.hasNext();j++) {
                JMXConnector c1 = (JMXConnector) i.next();
                if (c1 != null) {
                    try {
                         c1.connect(env);
                    } catch (IOException x) {
                         System.err.println ("Connection failed: " + x);
                         x.printStackTrace(System.err);
                         continue;
                    }

                    MBeanServerConnection conn =
                         c1.getMBeanServerConnection();

                    try {
                         listMBeans(conn);
                    } catch (IOException x) {
                         x.printStackTrace(System.err);
                    }
                    try {
                         c1.close();
                    } catch (IOException x) {
                         x.printStackTrace(System.err);
                    }
                }
           }
      } catch (Exception x) {
           x.printStackTrace(System.err);
      }
}

In CODE EXAMPLE 4-3, the agent.name property is retrieved by calling the getProperty() method of the System class, and the SLP lookup service is found by calling the getLocator() method of Locator.

All the agents named agentName are then looked up, and connections are made to the agents discovered. If no agent is specified, then all agents are lookup up. Connections are made to the MBean server created by Server, and all the MBeans in it are listed, before the connection is closed down.

Running the SLP Lookup Service Example

In addition to the actions you performed in Section "Initial Configuration", before you can run the lookup service examples that use the SLP, you must perform some further initial actions that are specific to this example. You can then start looking up connectors using SLP in conjunction with the two connectors supported by the JMX technology.

When you run the examples, to help you keep track of which agent has been created with which transport, the agent names include a letter suffix that is the same as the lettering of the corresponding section. For example, the agent from Section a. "RMI connector over JRMP, without an external directory" is called test-server-a.

Setting up the SLP Lookup Service Example

The following steps are required by all of the different transports you can run in this example.

  2. For convenience when compiling and running the classes, define an additional environment variable.

    In addition to the common environment variables that were set in Section "Initial Configuration", you need to add the path to the SLP service. If you are using the Solaris operating environment, add the following variable:

    $ SLPLIB=/usr/share/lib/slp

    If you are using another platform, set SLPLIB appropriately for the platform you are using.

  3. Define and export the classp environment variable.

    This example requires a classpath that includes the Java archive (JAR) files for SLP.

    $ classp=$SLPLIB/slp.jar

  4. Compile the example Client and Server classes.

    Type the following command:

    $ javac -d . -classpath $classp Server.java Client.java

  5. Start the SLP daemon.

    If you are using the Solaris operating environment, type the following command, which requires you to know your super user password:

    $ su root -c "java -cp $SLPLIB/slpd.jar com.sun.slp.slpd &"

    Password: [type superuser password]

    If you are not running a Solaris system, start the SLP daemon according to the implementation of SLP you are using.

Running the SLP Lookup Service Example

This example demonstrates the use of the SLP lookup service to look up RMI connector servers that use RMI’s default transport, JRMP, as well as the IIOP transport. In addition, as described in Section "Initial Configuration", different external directories are used to register the RMI connector stubs.

The combinations of transports and external directories demonstrated here are:

  • RMI connector over the JRMP transport, with:
  • No external directory
  • An RMI registry
  • An LDAP registry
  • RMI connector over the IIOP transport, with:
  • No external directory
  • A CORBA naming service
  • An LDAP registry

Perform the following steps to run the example:

  2. Start the Server.

    The command you use to start the Server varies according to which external directory you are using. You can start one or more of the following instances of Server with different transports and external registries before starting the Client.

    2. RMI connector over JRMP, without an external directory

      Start Server by typing the following command:

$ java -classpath .:$classp -Ddebug=true \
  -Dagent.name=test-server-a \
  -Durl ="service:jmx:rmi://" \
  slp.Server &

      In this command:

      • debug is set to true to provide more complete screen output when the Server runs
      • The name of the agent to be created is test-server-a
      • The service URL specifies that the chosen connector is an RMI connector, running over the RMI default transport JRMP.

      When Server is launched, you will see confirmation of the creation of the RMI connector, and the registration of its URL in the SLP service.

    3. RMI connector over JRMP, using an RMI registry as an external directory.

      Start Server by typing the following command:

$ java -classpath .:$classp -Ddebug=true \
  -Dagent.name=test-server-b \
  -Durl="service:jmx:rmi:///jndi/${jndirmi}/server" \
  slp.Server &

      In this command:

      • The name of the agent created is test-server-b
      • The service URL specifies the chosen connector as RMI over JRMP, and the external directory in which the RMI connector stub, server, is stored is the RMI registry you identified as jndirmi in Section "Initial Configuration".

      When Server is launched, you will see confirmation of the creation of the RMI connector, and the registration of its URL in the SLP service.

    4. RMI connector over JRMP, using LDAP as the external directory.

      Start Server by typing the following command:

$ java -classpath .:$classp -Ddebug=true \
  -Dagent.name=test-server-c \
  -Durl="service:jmx:rmi:///jndi/${jndildap}/cn=x,dc=Test" \
  -Djava.naming.security.principal="$principal" \
  -Djava.naming.security.credentials="$credentials" \
  slp.Server &

      In this command:

      • The name of the agent created is test-server-c
      • The service URL specifies the chosen connector as RMI over JRMP, and the external directory in which the RMI connector stub is stored is the LDAP server you identified as jndildap in Section "Initial Configuration".
      • The stub is registered in the Test domain component in the LDAP server.
      • The common name attribute principal and password credentials are given to gain access to the LDAP server.

      When Server is launched, you will see confirmation of the creation of the RMI connector, and the registration of its URL in the SLP service under the agent name test-server-c.

    5. RMI connector over IIOP, without an external directory.

      Start Server by typing the following command:

$ java -classpath .:$classp -Ddebug=true \
  -Dagent.name=test-server-d \
  -Durl="service:jmx:iiop://" \
  slp.Server &

      In this command:

      • The name of the agent created is test-server-d
      • The service URL specifies the chosen connector as RMI connector over IIOP.

      When the Server is launched, you will see confirmation of the creation of the RMI connector, and the registration of its automatically generated URL in the SLP service.

    6. RMI connector over IIOP, using CORBA naming as the external directory.

      Start Server by typing the following command:

$ java -classpath .:$classp -Ddebug=true \
  -Dagent.name=test-server-e \
  -Durl="service:jmx:iiop:///jndi/${jndiiiop}/server" \
  slp.Server &

      In this command:

      • The name of the agent created is test-server-e
      • The service URL specifies the chosen connector as RMI connector over IIOP. The external directory in which the RMI connector stub server is stored is the CORBA naming service you identified as jndiiiop in Section "Initial Configuration"

      When Server is launched, you will see confirmation of the creation of the RMI connector, and the registration of its URL in the SLP service under the name test-server-e.

    7. RMI connector over IIOP, using LDAP as the external directory.

      Start Server by typing the following command:

$ java -classpath .:$classp -Ddebug=true \
  -Dagent.name=test-server-f \
  -Durl="service:jmx:iiop:///jndi/${jndildap}/cn=x,dc=Test" \
  -Djava.naming.security.principal="$principal" \
  -Djava.naming.security.credentials="$credentials" \
  slp.Server &

      In this command:

      • The name of the agent created is test-server-f
      • The service URL specifies the chosen connector as RMI over IIOP, and the external directory in which the RMI connector stub is stored is the LDAP server you identified as jndildap in Section "Initial Configuration".
      • The stub is registered in the Test domain component in the LDAP server.
      • The common name attribute principal and password credentials are given to gain access to the LDAP server.

      When Server is launched, you will see confirmation of the creation of the RMI connector, and the registration of its URL in the SLP service under the agent name test-server-f.

    • Start the Client.

    • After starting the Server using the transport and external directory of your choice, start the Client:

$ java -classpath .:$classp -Ddebug=true \
     -Djava.naming.security.principal="$principal" \
     -Djava.naming.security.credentials="$credentials" \
     slp.Client

      You will see output confirming the detection of the agents created by the Server and registered in the lookup service. You will also see the identification and confirmation of the connection made to the agents.

      To look up a specific agent, type the following command:

$ java -classpath .:$classp -Ddebug=true \
     -Djava.naming.security.principal="$principal" \
     -Djava.naming.security.credentials="$credentials" \
     -Dagent.name="agentName" \
    slp.Client

      In the command shown above, agentName is the name of the agent you want to look up. You can also specify a partial agent name by using *; for example, x* for all agent names beginning with the letter x.

Jini Lookup Service

The purpose of this example is to demonstrate how a JMX technology connector client can find and connect to a connector server that has registered with the Jini lookup service. This example performs the following operations:

  • The agent:
  • Creates an MBean server
  • Creates a connector server
  • Registers the connector address with the Jini lookup service
  • The client:
  • Gets a pointer to the Jini lookup service
  • Looks for any connector servers registered in the Jini lookup service
  • Creates a JMX Remote API connector
  • Retrieves information about the MBeans in the MBean server

The Jini lookup service example is contained in the directory work_dir/jmx_examples/Lookup/jini.

Note – These examples assume that you are already familiar with the Jini network technology. The documentation for the Jini network technology is available at http://www.jini.org/ and http://java.net/projects/jini. You can download the Jini network technology from http://java.net/projects/jini. This example has been implemented using the Jini Technology Starter Kit Version 1.2.1_002.
  2. Open the work_dir/jmx_examples/Lookup/jini directory.

    Inside this directory, you will find the following files:

    • Server.java
    • Client.java
    • java.policy
    • jini.properties.template
    • README
  3. Open each of the files in a text editor.

    These classes will be analyzed in the following sections.

Analyzing the Example Classes

The following sections analyze each of the classes used in the Jini lookup service example, and explain how they perform the operations described above.

Server.java

Due to its size, the Jini lookup service Server.java class is shown as a series of code excerpts.

CODE EXAMPLE 4-1 Jini Lookup Service Example Class Server.java (Excerpt 1)

public class Server {
   private final MBeanServer mbs;
   private static boolean debug = false;
   public Server() {
     mbs = MBeanServerFactory.createMBeanServer();
   }

[...]

CODE EXAMPLE 4-1 shows the creation of an MBean server mbs. As was the case for the SLP examples, the JMX service URL and the agent name are passed to Server when it is launched at the command line.

CODE EXAMPLE 4-2 Jini Lookup Service Example Class Server.java (Excerpt 2)

[...]

   public JMXConnectorServer rmi(String url)
      throws IOException, JMException, ClassNotFoundException {
      JMXServiceURL jurl = new JMXServiceURL(url);
      final HashMap env = new HashMap();
      // Environment map attributes
     [...]
     JMXConnectorServer rmis =
        JMXConnectorServerFactory.newJMXConnectorServer(jurl, env, mbs);

     final String agentName = System.getProperty("agent.name",
                                                 "DefaultAgent");

     start(rmis,env,agentName);

     return rmis;
   }

[...]

CODE EXAMPLE 4-2 shows the creation of an RMI connector server named rmis, using the system properties defined by the environment map env and the address jurl.

The RMI connector server rmis is started. The RMI connector server address is registered in the Jini lookup service under the name agentName.

CODE EXAMPLE 4-3 Jini Lookup Service Example Class Server.java (Excerpt 3)

[...]

   public void start(JMXConnectorServer server, Map env, String agentName)
      throws IOException, ClassNotFoundException {
      server.start();
      final ServiceRegistrar registrar=getRegistrar();
      final JMXConnector proxy = server.toJMXConnector(env);
      register(registrar,proxy,agentName);
   }

   public static ServiceRegistrar getRegistrar()
      throws IOException, ClassNotFoundException,
         MalformedURLException {
      final String jurl =
         System.getProperty("jini.lookup.url","jini://localhost");
      final LookupLocator lookup = new LookupLocator(jurl);
      final ServiceRegistrar registrar = lookup.getRegistrar();
      if (registrar instanceof Administrable)
          debug("Registry is administrable.");
      return registrar;
   }

   public static ServiceRegistration register(ServiceRegistrar registrar,
                                              JMXConnector proxy, String name)
      throws IOException {
      Entry[] serviceAttrs = new Entry[] {
              new net.jini.lookup.entry.Name(name)
                       };

      System.out.println("Registering proxy: AgentName=" + name );
      debug("" + proxy);
      ServiceItem srvcItem = new ServiceItem(null, proxy, serviceAttrs);
      ServiceRegistration srvcRegistration =
             registrar.register(srvcItem, Lease.ANY);
      debug("Registered ServiceID: " +
                              srvcRegistration.getServiceID().toString());
      return srvcRegistration;
   }

[...]

CODE EXAMPLE 4-3 shows the creation of a connector server named server with the environment map env and the service URL jurl. The connector server instance server then gets a pointer to the Jini lookup service by calling the Jini lookup service method LookupLocator.getRegistrar().

The connector server is registered in the Jini lookup service in the form of a proxy, using the Jini lookup service locator registrar and the agent name under which the connector server will be registered. The proxy is in fact a client stub for the connector server, obtained by a call to the toJMXConnector() method of JMXConnectorServer.

The registration itself is performed by a call to the register() method of the Jini lookup service class ServiceRegistrar, with an array of service items.

Client.java

The Jini lookup service example class Client.java is shown in CODE EXAMPLE 4-1.

CODE EXAMPLE 4-1 Jini Lookup Service Example Class Client.java

public class Client {

   private static boolean debug = false;
   public static ServiceRegistrar getRegistrar()
       throws IOException, ClassNotFoundException, MalformedURLException {
       final String jurl =
                  System.getProperty("jini.lookup.url","jini://localhost");
       final LookupLocator lookup = new LookupLocator(jurl);
       final ServiceRegistrar registrar = lookup.getRegistrar();
       if (registrar instanceof Administrable)
               debug("Registry is administrable.");
       return registrar;
 }

   public static List lookup(ServiceRegistrar registrar,
           String name) throws IOException {
       final ArrayList list = new ArrayList();
       final Class[] classes = new Class[] {JMXConnector.class};
       final Entry[] serviceAttrs = new Entry[] {
           new net.jini.lookup.entry.Name(name)
   };

   ServiceTemplate template =
        new ServiceTemplate(null,classes,serviceAttrs);
   ServiceMatches matches =
        registrar.lookup(template, Integer.MAX_VALUE);
   for(int i = 0; i < matches.totalMatches; i++) {
        debug("Found Service: " + matches.items[i].serviceID);
        if (debug) {
           if (matches.items[i].attributeSets != null) {
                   final Entry[] attrs = matches.items[i].attributeSets;
                   for (int j = 0; j < attrs.length ; j++) {
                       debug("Attribute["+j+"]=" + attrs[j]);
               }
           }
        }

        if(matches.items[i].service != null) {
            JMXConnector c = (JMXConnector)(matches.items[i].service);
            debug("Found a JMXConnector: " + c);
            list.add(c);
        }
   }
   return list;
}

[...]

CODE EXAMPLE 4-1 shows how the connector client obtains a pointer to the Jini lookup service with a call to lookup.getRegistrar(). The client then obtains the list of the connectors registered as entries in the Jini lookup service with the agent name name. Unlike in the SLP example, the agent name you pass to Client when it is launched must be either an exact match of an existing agent name, or null, in which case the Jini lookup service will look up all the agents.

Once the list of connectors has been obtained, in code that is not shown here, the client connects to the MBean server started by Server, and retrieves the list of all the MBeans registered in it.

java.policy

The java.policy file is a Java technology security policy file, configured for this example.

jini.properties.template

A template Jini networking technology properties file, to be configured for this example. Change @INSTALL_HOME_FOR_JINI@ and rename the file to jini.properties.

Running the Jini Lookup Service Example

In addition to the actions you performed in Section "Initial Configuration", before you can run the lookup service examples that use the Jini lookup service, you must perform some further initial actions that are specific to this example. You can then start looking up connectors using the Jini network technology, in conjunction with the connector supported by the JMX technology.

When you run the examples, to help you keep track of which agent has been created with which transport, the agent names include a letter suffix that is the same as the lettering of the corresponding section. For example, the agent from Section a. "RMI connector over JRMP, without an external directory." is called test-server-a.

Setting up the Jini Lookup Service Example

The following steps are required by all of the different transports you can run in this example.

  2. For your convenience when compiling and running the example classes, define some additional environment variables.

    In addition to the common environment variables that you set in Section "Initial Configuration" you can add the path to the Jini lookup service. The directory where you have installed the Jini networking technology is referred to as jini_dir.

    $ JINI_HOME=jini_dir

    $ JINILIB=$JINI_HOME/lib

  3. Define the classp environment variable.

    This example requires the JAR files for the Jini lookup services core and extensions.

    $ classp=$JINILIB/jini-core.jar:$JINILIB/jini-ext.jar

  4. Create a jini.properties file.

    A properties file for UNIX platforms is provided in the same directory as the classes for this example. If you are not running a UNIX platform, you can obtain a properties file for your platform in the following directory:

    $JINI_HOME/example/launcher/jini12_<platform>.properties

  5. Update the jini.properties file.

    You must complete the file to include all the necessary paths, host names and port numbers for your system. Even if you are not running a UNIX platform, you can use the template provided as a guide.

  6. Start the Jini networking technology StartService.

    $ java -cp $JINILIB/jini-examples.jar com.sun.jini.example.launcher.StartService &

    This will open the StartService graphical user interface.

  7. Load your jini.properties file into StartService.

    Click on ‘File’, ‘Open Property File’ and then select your properties file from within work_dir/jmx_examples/Lookup/jini.

  8. Start the Jini lookup services.

    Start the required Jini lookup services by clicking on the ‘Run’ tab and then pressing the ‘START’ button for each of the following:

    • RMID
    • WebServer
    • Reggie
    • LookupBrowser

    You will see confirmation that the services are running.

  9. Compile the Client and Server classes.

    Type the following command:

    $ javac -d . -classpath $classp Server.java Client.java

Running the Jini Lookup Service Example

This example demonstrates the use of the Jini lookup service to look up RMI connector servers that use RMI’s default transport, JRMP, as well as the IIOP transport. In addition, as described in Section "Initial Configuration", different external directories are used to register the RMI connector stubs.

The combinations of transports and external directories demonstrated here are:

  • RMI connector over the JRMP transport, with:
  • No external directory
  • An RMI registry
  • An LDAP registry
  • RMI connector over the IIOP transport, with:
  • No external directory
  • A CORBA naming service
  • An LDAP registry
  2. Start the Server.

    The command you use to start the Server varies according to which external directory you are using. You can start one or more of the following instances of Server with different transports and external registries before starting the Client.

    2. RMI connector over JRMP, without an external directory.

      Start Server by typing the following command:

$ java -classpath .:$classp -Ddebug=true \
  -Dagent.name=test-server-a \
  -Durl="service:jmx:rmi://" \
  -Djava.security.policy=java.policy \
  jini.Server &

      In this command:

      • debug is set to true to provide more complete screen output when the Server runs.
      • The security policy is provided, to allow access to the Jini lookup service.
      • The name of the agent to be created is test-server-a.
      • The service URL specifies that the chosen connector is an RMI connector, running over the RMI default transport JRMP.

      When Server is launched, you will see confirmation of the creation of the RMI connector, and the registration of its URL in the Jini lookup service.

    3. RMI connector over JRMP, using an RMI registry as an external directory.

      Start Server by typing the following command:

$ java -classpath .:$classp -Ddebug=true \
  -Dagent.name=test-server-b \
  -Durl="service:jmx:rmi:///jndi/${jndirmi}/server" \
  -Djava.security.policy=java.policy \
  jini.Server &

      In this command:

      • The security policy is provided, to allow access to the Jini lookup service.
      • The name of the agent created is test-server-b.
      • The service URL specifies the chosen connector as RMI over JRMP, and the external directory in which the RMI connector stub, server, is stored is the RMI registry you identified as jndirmi in Section "Initial Configuration".

      When Server is launched, you will see confirmation of the creation of the RMI connector, and the registration of its URL in the Jini lookup service.

    4. RMI connector over JRMP, using LDAP as the external directory.

      Start Server by typing the following command:

$ java -classpath .:$classp -Ddebug=true \
  -Dagent.name=test-server-c \
  -Durl="service:jmx:rmi:///jndi/${jndildap}/cn=x,dc=Test" \
  -Djava.security.policy=java.policy \
  -Djava.naming.security.principal="$principal" \
  -Djava.naming.security.credentials="$credentials" \
  jini.Server &

      In this command:

      • The security policy is provided, to allow access to the Jini lookup service.
      • The name of the agent created is test-server-c.The service URL specifies the chosen connector as RMI over JRMP, and the external directory in which the RMI connector stub is stored is the LDAP server you identified as jndildap in Section "Initial Configuration".
      • The stub is registered in the Test domain component in the LDAP server.
      • The common name attribute principal and password credentials are given to gain access to the LDAP server.

      When Server is launched, you will see confirmation of the creation of the RMI connector, and the registration of its URL in the Jini lookup service under the agent name test-server-c.

    5. RMI connector over IIOP, without an external directory.

      Start Server by typing the following command:

$ java -classpath .:$classp -Ddebug=true \
  -Dagent.name=test-server-d \
  -Durl="service:jmx:iiop://" \
  -Djava.security.policy=java.policy \
  jini.Server &

      In this command:

      • The security policy is provided, to allow access to the Jini lookup service
      • The name of the agent created is test-server-d
      • The service URL specifies the chosen connector as RMI connector over IIOP.

      When the Server is launched, you will see confirmation of the creation of the RMI connector, and the registration of its automatically generated URL in the Jini lookup service.

    6. RMI connector over IIOP, using CORBA naming as the external directory.

      Start Server by typing the following command:

$ java -classpath .:$classp -Ddebug=true \
  -Dagent.name=test-server-e \
  -Durl="service:jmx:iiop:///jndi/${jndiiiop}/server" \
  -Djava.security.policy=java.policy \
  jini.Server &

      In this command:

      • The security policy is provided, to allow access to the Jini lookup service.
      • The name of the agent created is test-server-e.
      • The service URL specifies the chosen connector as RMI connector over IIOP. The external directory in which the RMI connector stub, server, is stored is the CORBA naming service you identified as jndiiiop in Section "Initial Configuration".

      When Server is launched, you will see confirmation of the creation of the RMI connector, and the registration of its URL in the Jini lookup service under the name test-server-e.

    7. RMI connector over IIOP, using LDAP as the external directory.

      Start Server by typing the following command:

$ java -classpath .:$classp -Ddebug=true \
  -Dagent.name=test-server-f \
  -Durl="service:jmx:iiop:///jndi/${jndildap}/cn=x,dc=Test" \
  -Djava.security.policy=java.policy \
  -Djava.naming.security.principal="$principal" \
  -Djava.naming.security.credentials="$credentials" \
  jini.Server &

      In this command:

      • The security policy is provided, to allow access to the Jini lookup service.
      • The name of the agent created is test-server-f.
      • The service URL specifies the chosen connector as RMI over IIOP.
      • The external directory in which the RMI connector stub is stored is the LDAP server you identified as jndildap in Section "Initial Configuration".
      • The stub is registered in the Test domain component in the LDAP server.
      • The common name attribute principal and password credentials are given to gain access to the LDAP server.

      When Server is launched, you will see confirmation of the creation of the RMI connector, and the registration of its URL in the Jini lookup service under the agent name test-server-f.

    • Start the Client.

    • After starting the Server using the transport and external directory of your choice, start the Client:

$ java -classpath .:$classp -Ddebug=true \
  -Djava.security.policy=java.policy \
  jini.Client

      You will see output confirming the detection of the agents created by the Server and registered in the lookup service. You will also see the identification and confirmation of the connection made to the agents.

      To look up a specific agent, you can do so by typing the following command:

$ java -classpath .:$classp -Ddebug=true \
  -Djava.security.policy=java.policy \
  -Dagent.name=agentName \
  jini.Client

      In the command shown above, agentName is the name of the agent you want to look up. You can also specify a partial agent name by using *; for example, x* for all agent names beginning with the letter x.

Java Naming and Directory Interface (JNDI) / LDAP Lookup Service

JMX technology allows you to register RMI connectors with a JNDI lookup service using an LDAP registry as a back end. This example performs the following operations:

  • The agent:
  • Creates an MBean server
  • Creates a connector server
  • Registers the connector address with the LDAP server
  • The client:
  • Gets a pointer to the JNDI/LDAP lookup Service
  • Looks for any connector servers registered in the JNDI/LDAP lookup service
  • Creates a JMX Remote API connector
  • Retrieves information about the MBeans in the MBean server

The JNDI/LDAP lookup example is contained in the directory work_dir/jmx_examples/Lookup/ldap.

  2. Open the work_dir/jmx_examples/Lookup/ldap directory.

    Inside this directory, you will find the following files:

    • Server.java
    • Client.java
    • jmx-schema.txt
    • 60jmx-schema.ldif
    • README
  3. Open the files in a text editor.

    These classes will be analyzed in the following sections.

Analyzing the Example Classes

The following sections analyze each of the classes used in the JNDI/LDAP lookup service example, and explain how they perform the operations described above.

Server.java

Due to its size, the JNDI/LDAP lookup service Server.java class is shown as a series of code excerpts.

CODE EXAMPLE 4-1 JNDI/LDAP Lookup Service Example Server.java (Excerpt 1)

[...]

public class Server {
   public final static int JMX_DEFAULT_LEASE = 60;
   private static boolean debug = false;
   private final MBeanServer mbs;
   public Server() {
      mbs = MBeanServerFactory.createMBeanServer();
   }

  public static DirContext getRootContext() throws NamingException {
      final Hashtable env = new Hashtable();

      final String factory =
        System.getProperty(Context.INITIAL_CONTEXT_FACTORY,
                           "com.sun.jndi.ldap.LdapCtxFactory");
      final String ldapServerUrl =
        System.getProperty(Context.PROVIDER_URL);
      final String ldapUser =
        System.getProperty(Context.SECURITY_PRINCIPAL,
                           "cn=Directory Manager");
      final String ldapPasswd =
        System.getProperty(Context.SECURITY_CREDENTIALS);
      debug(Context.PROVIDER_URL + "=" + ldapServerUrl);
      debug(Context.SECURITY_PRINCIPAL + "=" + ldapUser);
      if (debug) {
                  System.out.print(Context.SECURITY_CREDENTIALS + "=");
                  final int len = (ldapPasswd==null)?0:ldapPasswd.length();
                  for (int i=0;i<len;i++) System.out.print("*");
                  System.out.println();
      }
      env.put(Context.INITIAL_CONTEXT_FACTORY,factory);
      env.put(Context.SECURITY_PRINCIPAL, ldapUser);
      if (ldapServerUrl != null)
           env.put(Context.PROVIDER_URL, ldapServerUrl);
      if (ldapPasswd != null)
           env.put(Context.SECURITY_CREDENTIALS, ldapPasswd);
      InitialContext root = new InitialLdapContext(env,null);
      return (DirContext)(root.lookup(""));
  }

[...]

CODE EXAMPLE 4-1 shows the initial creation of an MBean server mbs, and the obtention of a pointer to the root context of the LDAP directory tree in which the connector server address is to be registered. All the relevant LDAP access variables, such as the provider URL, the LDAP user name and the security credentials, are given here and passed into the environment map env. The environment map env is then passed as a parameter into a call to InitialLdapContext, from which the initial LDAP context is obtained.

Code that is omitted from CODE EXAMPLE 4-1 retrieves the agent name under which the connector will be registered in the LDAP server.

CODE EXAMPLE 4-2 JNDI/LDAP Lookup Service Example Server.java (Excerpt 2)
[...]

public static void register(DirContext root,
                           JMXServiceURL jmxUrl,
                           String name)
   throws NamingException, IOException {

   final String mydn = System.getProperty("dn","cn="+name);

   debug("dn: " + mydn );

   Object o = null;
   try {
       o = root.lookup(mydn);
   } catch (NameNotFoundException n) {
       Attributes attrs = new BasicAttributes();
       Attribute objclass = new BasicAttribute("objectClass");
       objclass.add("top");
       objclass.add("javaContainer");
       objclass.add("jmxConnector");
       attrs.put(objclass);
       attrs.put("jmxAgentName", name);
       o = root.createSubcontext(mydn,attrs);
   }
   if (o == null) throw new NameNotFoundException();
   final Attributes attrs = root.getAttributes(mydn);
   final Attribute oc = attrs.get("objectClass");
   if (!oc.contains("jmxConnector")) {
       final String msg = "The supplied node [" + mydn +
         "] does not contain the jmxConnector objectclass";
       throw new NamingException(msg);
   }

   final Attributes newattrs = new BasicAttributes();
   newattrs.put("jmxAgentName",name);
   newattrs.put("jmxServiceURL",jmxUrl.toString());
   newattrs.put("jmxAgentHost",InetAddress.getLocalHost().getHostName());
   newattrs.put("jmxProtocolType",jmxUrl.getProtocol());
   newattrs.put("jmxExpirationDate",
                getExpirationDate(JMX_DEFAULT_LEASE));
   root.modifyAttributes(mydn,DirContext.REPLACE_ATTRIBUTE,newattrs);
}

[...]

CODE EXAMPLE 4-2 shows the registration of JMX connector server service URL in the LDAP directory. The DN where the URL will be registered can be passed on the command line through the dn System property, that is, -Ddn=mydn (see later the commands used start the server). If the dn System property is not specified, then you can use the DN: cn=name where name is the agentName. Naturally, this is not mandatory. The location where the URL is registered does not really matter, because the client code never uses that DN directly, but instead performs an LDAP search to find the nodes which have an auxiliary jmxConnector ObjectClass. What is important here is that each URL is registered in its own LDAP node. How to name these nodes is left to the LDAP administrator, who in this case is you. In this example, it is assumed that you have configured your LDAP server by creating a root context under which the node cn=name can be created, and that this root context has been passed to the LDAP initial context through the Context.PROVIDER_URL property (see CODE EXAMPLE 4-1).

The code shown in CODE EXAMPLE 4-2 checks whether the node in which you will register the server URL already exists. If it does not, you try to create it (this will fail if the parent node does not exist). Since the jmxConnector ObjectClass is a simple auxiliary class, you will use the javaContainer ObjectClass as structural class if you need to create a new context. Once again, this is completely optional. Any structural class to which the jmxConnector auxiliary class could be added would be acceptable. It then checks whether the node in which you will register the server already has the jmxConnector auxiliary class. If not, an exception is thrown.

At this point you are sure that the node in which you will register the URL exists, and has the appropriate jmxConnector auxiliary class. So you need only to replace the values of the attributes defined by JMX Remote API for LDAP lookup (see jmx-schema.txt):

  • jmxServiceUrl: contains the String form of the server URL, as obtained from server.getAddress() after the server was started
  • jmxAgentName: contains the JMX agent name
  • jmxProtocolType: contains the JMX protocol type, as returned by jmxUrl.getProtocolType()
  • jmxAgentHost: contains the name of the agent host
  • jmxExpirationDate: contains the date at which the URL will be considered obsolete.
CODE EXAMPLE 4-3 JNDI/LDAP Lookup Service Example Server.java (Excerpt 3)

[...]

   public JMXConnectorServer rmi(String url)
     throws IOException, JMException,
        NamingException, ClassNotFoundException {

     JMXServiceURL jurl = new JMXServiceURL(url);
     final HashMap env = new HashMap();
     // Prepare the environment Map

[...]

     JMXConnectorServer rmis =
        JMXConnectorServerFactory.newJMXConnectorServer(jurl, env, mbs);

     final String agentName = System.getProperty("agent.name",
                                                 "DefaultAgent");
     start(rmis,env,agentName);
     return rmis;
   }

[...]

In CODE EXAMPLE 4-3, a new RMI connector server named rmis is created with the JMX service URL jurl and the appropriate LDAP properties passed to its environment map env. The connector server rmis is launched by calling JMXConnectorServer.start() and is registered in the LDAP server.

CODE EXAMPLE 4-4 JNDI/LDAP Lookup Service Example Server.java (Excerpt 4)

[...]

    public void start(JMXConnectorServer server, Map env, String agentName)
       throws IOException, NamingException {
       server.start();
       final DirContext root=getRootContext();
       final JMXServiceURL address = server.getAddress();
       register(root,address,agentName);
    }

[...]

CODE EXAMPLE 4-4 shows the creation of a JMX connector server server, the obtention of a pointer to the LDAP server root directory root and the creation of a URL for server named address. The root directory, the URL and an agent name are passed as parameters to register() and are registered in the LDAP server.

Client.java

The JNDI/LDAP lookup service Client.java class is shown in CODE EXAMPLE 4-1.

CODE EXAMPLE 4-1 JNDI/LDAP Lookup Service Example Client.java

[...]

public class Client {

   private static boolean debug = false;

   public static void listAttributes(DirContext root, String dn)
     throws NamingException {
     final Attributes attrs = root.getAttributes(dn);
     System.out.println("dn: " + dn);
     System.out.println("attributes: " + attrs);
   }

   public static DirContext getRootContext() throws NamingException {
      final Hashtable env = new Hashtable();
      // Prepare environment map
      [...]

      InitialContext root = new InitialLdapContext(env,null);
      return (DirContext)(root.lookup(""));
   }

   // Confirm URL has not expired
  [...]

   public static List lookup(DirContext root, String protocolType,
                             String name)
      throws IOException, NamingException {
      final ArrayList list = new ArrayList();
      String queryProtocol =
         (protocolType==null)?"":"(jmxProtocolType="+protocolType+")";
      String query =
          "(&" + "(objectClass=jmxConnector) " +
          "(jmxServiceURL=*) " +
          queryProtocol +
          "(jmxAgentName=" + ((name!=null)?name:"*") + "))";

      SearchControls ctrls = new SearchControls();
      ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
      final NamingEnumeration results = root.search("", query, ctrls);
      while (results.hasMore()) {
           final SearchResult r = (SearchResult) results.nextElement();
           debug("Found node: " + r.getName());
           final Attributes attrs = r.getAttributes();
           final Attribute attr = attrs.get("jmxServiceURL");
           if (attr == null) continue;
           final Attribute exp = attrs.get("jmxExpirationDate");
           if ((exp != null) && hasExpired((String)exp.get())) {
               System.out.print(r.getName() + ": ");
               System.out.println("URL expired since: " + exp.get());
               continue;
           }
           final String urlStr = (String)attr.get();
           if (urlStr.length() == 0) continue;

           debug("Found URL: "+ urlStr);

           final JMXServiceURL url = new JMXServiceURL(urlStr);
           final JMXConnector conn =
               JMXConnectorFactory.newJMXConnector(url,null);
           list.add(conn);
           if (debug) listAttributes(root,r.getName());
      }

      return list;

   }
}

In CODE EXAMPLE 4-1, the Client firstly returns a pointer root to the LDAP directory DirContext, then it searches through the directory for object classes of the type jmxConnector. The service URL and expiry date attributes, attr and exp respectively, for the jmxConnector object classes are obtained, exp is checked to make sure that the URL has not expired and a call is made to JMXConnectorFactory to create a new connector conn. The connector conn is added to the list of connectors and is used to access the MBeans in the MBean server created by Server.

jmx-schema.txt

The jmx-schema.txt file is the LDAP schema file for the JMX Remote API.

60jmx-schema.ldif

The 60jmx-schema.ldif file is an ldif file corresponding to the LDAP schema file, jmx-schema.txt, for JMX technology. If you are using Sun ONE Directory Server, this file can be copied directly to the config/schema directory of the Sun ONE Directory Server (see Section "Setting up the JNDI/LDAP Lookup Service Example").

Running the JNDI/LDAP Lookup Service Example

In addition to the actions you performed in Section "Initial Configuration", before you can run the lookup service examples that use the JNDI/LDAP lookup service, you must perform some further initial actions that are specific to this example. You can then start looking up connectors using the JNDI/LDAP network technology, in conjunction with the two connectors supported by the JMX technology.

When you run the examples, to help you keep track of which agent has been created with which transport, the agent names include a letter suffix that is the same as the lettering of the corresponding section. For example, the agent from Section a. "RMI connector over JRMP, without an external directory." is called test-server-a.

Setting up the JNDI/LDAP Lookup Service Example

The following steps are required by all of the different connector/transport combinations you can run in this example.

  2. Stop the LDAP server you started in Section "Initial Configuration".

    Do this according to the type of LDAP server you are using.

  3. Copy the JMX technology schema into your LDAP server’s schema directory.

    For example, if you are using Sun ONE Directory Server 5.0, you would type:

    $ cp 60jmx-schema.ldif /var/ds5/slapd-<hostname>/config/schema

    Otherwise, do this according to the type of LDAP server you are using.

  4. Restart the LDAP server.

    Do this according to the type of LDAP server you are using.

  5. Define the root under which the Server will register its service URL.

    You must provide the Server with the path to the domain component suffix dc=Test that you created in Section "Initial Configuration".

    $ provider="ldap://$ldaphost:$ldapport/dc=Test"

  6. Compile the Client and Server classes.

    $ javac -d . Server.java Client.java

Running the JNDI/LDAP Lookup Service Example With an RMI Connector

This example demonstrates the use of the JNDI/LDAP lookup service to look up RMI connector servers that use RMI’s default transport, JRMP, as well as the IIOP transport. In addition, as described in Section "Initial Configuration", different external directories are used to register the RMI connector stubs.

The combinations of transports and external directories demonstrated here are:

  • RMI connector over the JRMP transport, with:
  • No external directory
  • An RMI registry
  • An LDAP registry
  • RMI connector over the IIOP transport, with:
  • No external directory
  • A CORBA naming service
  • An LDAP registry
  2. Start the Server.

    The command you use to start the Server varies according to which external directory you are using. You can start one or more of the following instances of Server with different transports and external registries before starting the Client.

    2. RMI connector over JRMP, without an external directory.

      Start Server by typing the following command:

$ java -classpath . -Ddebug=true \
  -Dagent.name=test-server-a \
  -Durl="service:jmx:rmi://" \
  -Djava.naming.provider.url="$provider" \
  -Djava.naming.security.principal="$principal" \
  -Djava.naming.security.credentials="$credentials" \
  jndi.Server &

      In this command:

      • debug is set to true to provide more complete screen output when the Server runs.
      • The name of the agent to be created is test-server-a.
      • The URL, provider, that points to the domain component suffix in which the agent will be registered, is given.
      • The common name attribute principal and password credentials are given to gain access to the LDAP server.
      • The service URL specifies that the chosen connector is an RMI connector, running over the RMI default transport JRMP.

      When Server is launched, you will see confirmation of the creation of the RMI connector, and the registration of its URL in the JNDI/LDAP lookup service.

    3. RMI connector over JRMP, using an RMI registry as an external directory.

      Start Server by typing the following command:

$ java -classpath . -Ddebug=true \
  -Dagent.name=test-server-b \
  -Durl="service:jmx:rmi:///jndi/${jndirmi}/server" \
  -Djava.naming.provider.url="$provider" \
  -Djava.naming.security.principal="$principal" \
  -Djava.naming.security.credentials="$credentials" \
  jndi.Server &

      In this command:

      • The name of the agent created is test-server-b.
      • The URL, provider, that points to the domain component suffix in which the agent will be registered, is given.
      • The common name attribute principal and password credentials are given to gain access to the LDAP server.
      • The service URL specifies the chosen connector as RMI over JRMP, and the external directory in which the RMI connector stub, server, is stored is the RMI registry you identified as jndirmi in Section "Initial Configuration".

      When Server is launched, you will see confirmation of the creation of the RMI connector, and the registration of its URL in the JNDI/LDAP lookup service.

    4. RMI connector over JRMP, using LDAP as the external directory.

      Start Server by typing the following command:

$ java -classpath . -Ddebug=true \
  -Dagent.name=test-server-c \
  -Durl="service:jmx:rmi:///jndi/${jndildap}/cn=x,dc=Test" \
  -Djava.naming.provider.url="$provider" \
  -Djava.naming.security.principal="$principal" \
  -Djava.naming.security.credentials="$credentials" \
  jndi.Server &

      In this command:

      • The name of the agent created is test-server-c.
      • The URL, provider, that points to the domain component suffix in which the agent will be registered, is given.
      • The common name attribute principal and password credentials are given to gain access to the LDAP server.
      • The service URL specifies the chosen connector as RMI over JRMP, and the external directory in which the RMI connector stub is stored is the LDAP server you identified as jndildap in Section "Initial Configuration".

      When Server is launched, you will see confirmation of the creation of the RMI connector, and the registration of its URL in the JNDI/LDAP lookup service under the agent name test-server-c.

    5. RMI connector over IIOP, without an external directory.

      Start Server by typing the following command:

$ java -classpath . -Ddebug=true \
  -Dagent.name=test-server-d \
  -Durl="service:jmx:iiop://" \
  -Djava.naming.provider.url="$provider" \
  -Djava.naming.security.principal="$principal" \
  -Djava.naming.security.credentials="$credentials" \
  jndi.Server &

      In this command:

      • The name of the agent created is test-server-d.
      • The URL, provider, that points to the domain component suffix in which the agent will be registered, is given.
      • The common name attribute principal and password credentials are given to gain access to the LDAP server.
      • The service URL specifies that the chosen connector is an RMI connector, running over IIOP.

      When the Server is launched, you will see confirmation of the creation of the RMI connector, and the registration of its automatically generated URL in the JNDI/LDAP lookup service.

    6. RMI connector over IIOP, using CORBA naming as the external directory.

      Start Server by typing the following command:

$ java -classpath . -Ddebug=true \
  -Dagent.name=test-server-e \
  -Durl="service:jmx:iiop:///jndi/${jndiiiop}/server" \
  -Djava.naming.provider.url="$provider" \
  -Djava.naming.security.principal="$principal" \
  -Djava.naming.security.credentials="$credentials" \
  jndi.Server &

      In this command:

      • The name of the agent created is test-server-e.
      • The URL, provider, that points to the domain component suffix in which the agent will be registered, is given.
      • The common name attribute principal and password credentials are given to gain access to the LDAP server.
      • The service URL specifies the chosen connector as RMI connector over IIOP, and the external directory in which the RMI connector stub, server, is stored is the CORBA naming service you identified as jndiiiop in Section "Initial Configuration".

      When Server is launched, you will see confirmation of the creation of the RMI connector, and the registration of its URL in the JNDI/LDAP lookup service under the name test-server-e.

    7. RMI connector over IIOP, using LDAP as the external directory.

      Start Server by typing the following command:

$ java -classpath . -Ddebug=true \
  -Dagent.name=test-server-f \
  -Durl="service:jmx:iiop:///jndi/${jndildap}/cn=x,dc=Test" \
  -Djava.naming.provider.url="$provider" \
  -Djava.naming.security.principal="$principal" \
  -Djava.naming.security.credentials="$credentials" \
  jndi.Server &

      In this command:

      • The name of the agent created is test-server-f.
      • The URL, provider, that points to the domain component suffix in which the agent will be registered, is given.
      • The common name attribute principal and password credentials are given to gain access to the LDAP server.
      • The service URL specifies the chosen connector as RMI over IIOP, and the external directory in which the RMI connector stub is stored is the LDAP server you identified as jndildap in Section "Initial Configuration".

      When Server is launched, you will see confirmation of the creation of the RMI connector, and the registration of its URL in the JNDI/LDAP lookup service under the agent name test-server-f.

    • Start the Client.

    • After starting the Server using the transport and external directory of your choice, start the Client:

$ java -classpath . -Ddebug=true \
  -Djava.naming.provider.url="$provider" \
  -Djava.naming.security.principal="$principal" \
  -Djava.naming.security.credentials="$credentials" \
  jndi.Client

      You will see output confirming the detection of the agents created by the Server and registered in the lookup service. You will also see the identification and confirmation of the connection made to the agents.

      To look up a specific agent, type the following command:

$ java -classpath . -Ddebug=true \
  -Djava.naming.provider.url="$provider" \
  -Djava.naming.security.principal="$principal" \
  -Djava.naming.security.credentials="$credentials" \
  -Dagent.name=agentName \
  jndi.Client

      In the command shown above, agentName is the name of the agent you want to look up. You can also specify a partial agent name by using *; for example, x* for all agent names beginning with the letter x.

Contents | Previous | Next

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class org.w3c.dom.ls.LSException (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
org.w3c.dom.ls.LSException

  • Packages that use LSException
    Package Description
    org.w3c.dom.ls

    • Uses of LSException in org.w3c.dom.ls

      Methods in org.w3c.dom.ls that throw LSException
      Modifier and Type Method and Description
      Document LSParser.parse(LSInput input)
      Parse an XML document from a resource identified by a LSInput.
      Document LSParser.parseURI(String uri)
      Parse an XML document from a location identified by a URI reference [IETF RFC 2396].
      Node LSParser.parseWithContext(LSInput input, Node contextArg, short action)
      Parse an XML fragment from a resource identified by a LSInput and insert the content into an existing document at the position specified with the context and action arguments.
      boolean LSSerializer.write(Node nodeArg, LSOutput destination)
      Serialize the specified node as described above in the general description of the LSSerializer interface.
      String LSSerializer.writeToString(Node nodeArg)
      Serialize the specified node as described above in the general description of the LSSerializer interface.
      boolean LSSerializer.writeToURI(Node nodeArg, String uri)
      A convenience method that acts as if LSSerializer.write was called with a LSOutput with no encoding specified and LSOutput.systemId set to the uri argument.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.ls.LSInput (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.ls.LSInput

  • Packages that use LSInput
    Package Description
    org.w3c.dom.ls

    • Uses of LSInput in org.w3c.dom.ls

      Methods in org.w3c.dom.ls that return LSInput
      Modifier and Type Method and Description
      LSInput DOMImplementationLS.createLSInput()
      Create a new empty input source object where LSInput.characterStream, LSInput.byteStream , LSInput.stringData LSInput.systemId, LSInput.publicId, LSInput.baseURI, and LSInput.encoding are null, and LSInput.certifiedText is false.
      LSInput LSProgressEvent.getInput()
      The input source that is being parsed.
      LSInput LSLoadEvent.getInput()
      The input source that was parsed.
      LSInput LSResourceResolver.resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI)
      Allow the application to resolve external resources.
      Methods in org.w3c.dom.ls with parameters of type LSInput
      Modifier and Type Method and Description
      Document LSParser.parse(LSInput input)
      Parse an XML document from a resource identified by a LSInput.
      Node LSParser.parseWithContext(LSInput input, Node contextArg, short action)
      Parse an XML fragment from a resource identified by a LSInput and insert the content into an existing document at the position specified with the context and action arguments.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.ls.LSLoadEvent (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.ls.LSLoadEvent

No usage of org.w3c.dom.ls.LSLoadEvent
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.ls.LSOutput (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.ls.LSOutput

  • Packages that use LSOutput
    Package Description
    org.w3c.dom.ls

    • Uses of LSOutput in org.w3c.dom.ls

      Methods in org.w3c.dom.ls that return LSOutput
      Modifier and Type Method and Description
      LSOutput DOMImplementationLS.createLSOutput()
      Create a new empty output destination object where LSOutput.characterStream, LSOutput.byteStream, LSOutput.systemId, LSOutput.encoding are null.
      Methods in org.w3c.dom.ls with parameters of type LSOutput
      Modifier and Type Method and Description
      boolean LSSerializer.write(Node nodeArg, LSOutput destination)
      Serialize the specified node as described above in the general description of the LSSerializer interface.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.ls.LSParser (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.ls.LSParser

  • Packages that use LSParser
    Package Description
    org.w3c.dom.ls

    • Uses of LSParser in org.w3c.dom.ls

      Methods in org.w3c.dom.ls that return LSParser
      Modifier and Type Method and Description
      LSParser DOMImplementationLS.createLSParser(short mode, String schemaType)
      Create a new LSParser.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.ls.LSParserFilter (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.ls.LSParserFilter

  • Packages that use LSParserFilter
    Package Description
    org.w3c.dom.ls

    • Uses of LSParserFilter in org.w3c.dom.ls

      Methods in org.w3c.dom.ls that return LSParserFilter
      Modifier and Type Method and Description
      LSParserFilter LSParser.getFilter()
      When a filter is provided, the implementation will call out to the filter as it is constructing the DOM tree structure.
      Methods in org.w3c.dom.ls with parameters of type LSParserFilter
      Modifier and Type Method and Description
      void LSParser.setFilter(LSParserFilter filter)
      When a filter is provided, the implementation will call out to the filter as it is constructing the DOM tree structure.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.ls.LSProgressEvent (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.ls.LSProgressEvent

No usage of org.w3c.dom.ls.LSProgressEvent
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.ls.LSResourceResolver (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.ls.LSResourceResolver

No usage of org.w3c.dom.ls.LSResourceResolver
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.ls.LSSerializer (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.ls.LSSerializer

  • Packages that use LSSerializer
    Package Description
    org.w3c.dom.ls

    • Uses of LSSerializer in org.w3c.dom.ls

      Methods in org.w3c.dom.ls that return LSSerializer
      Modifier and Type Method and Description
      LSSerializer DOMImplementationLS.createLSSerializer()
      Create a new LSSerializer object.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.ls.LSSerializerFilter (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.ls.LSSerializerFilter

  • Packages that use LSSerializerFilter
    Package Description
    org.w3c.dom.ls

    • Uses of LSSerializerFilter in org.w3c.dom.ls

      Methods in org.w3c.dom.ls that return LSSerializerFilter
      Modifier and Type Method and Description
      LSSerializerFilter LSSerializer.getFilter()
      When the application provides a filter, the serializer will call out to the filter before serializing each Node.
      Methods in org.w3c.dom.ls with parameters of type LSSerializerFilter
      Modifier and Type Method and Description
      void LSSerializer.setFilter(LSSerializerFilter filter)
      When the application provides a filter, the serializer will call out to the filter before serializing each Node.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.stylesheets.MediaList (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.stylesheets.MediaList

  • Packages that use MediaList
    Package Description
    org.w3c.dom.css
    org.w3c.dom.stylesheets

    • Uses of MediaList in org.w3c.dom.css

      Methods in org.w3c.dom.css that return MediaList
      Modifier and Type Method and Description
      MediaList CSSMediaRule.getMedia()
      A list of media types for this rule.
      MediaList CSSImportRule.getMedia()
      A list of media types for which this style sheet may be used.

    • Uses of MediaList in org.w3c.dom.stylesheets

      Methods in org.w3c.dom.stylesheets that return MediaList
      Modifier and Type Method and Description
      MediaList StyleSheet.getMedia()
      The intended destination media for style information.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.declaration.MemberDeclaration (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.declaration.MemberDeclaration

  • Packages that use MemberDeclaration
    Package Description
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of MemberDeclaration in com.sun.mirror.declaration

      Subinterfaces of MemberDeclaration in com.sun.mirror.declaration
      Modifier and Type Interface and Description
      interface  AnnotationTypeDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in TypeElement.
      interface  AnnotationTypeElementDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in ExecutableElement.
      interface  ClassDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in TypeElement.
      interface  ConstructorDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in ExecutableElement.
      interface  EnumConstantDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in VariableElement.
      interface  EnumDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in TypeElement.
      interface  ExecutableDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is ExecutableElement.
      interface  FieldDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in VariableElement.
      interface  InterfaceDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in TypeElement.
      interface  MethodDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in ExecutableElement.
      interface  TypeDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in TypeElement.

    • Uses of MemberDeclaration in com.sun.mirror.util

      Methods in com.sun.mirror.util with parameters of type MemberDeclaration
      Modifier and Type Method and Description
      boolean Declarations.hides(MemberDeclaration sub, MemberDeclaration sup)
      Deprecated.
      Tests whether one type, method, or field declaration hides another.
      void SimpleDeclarationVisitor.visitMemberDeclaration(MemberDeclaration d)
      Deprecated.
      Visits a member or constructor declaration.
      void DeclarationVisitor.visitMemberDeclaration(MemberDeclaration d)
      Deprecated.
      Visits a member or constructor declaration.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.javadoc.MemberDoc (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.javadoc.MemberDoc

    • Uses of MemberDoc in com.sun.javadoc

      Subinterfaces of MemberDoc in com.sun.javadoc
      Modifier and Type Interface and Description
      interface  AnnotationTypeElementDoc
      Represents an element of an annotation type.
      interface  ConstructorDoc
      Represents a constructor of a java class.
      interface  ExecutableMemberDoc
      Represents a method or constructor of a java class.
      interface  FieldDoc
      Represents a field in a java class.
      interface  MethodDoc
      Represents a method of a java class.
      Methods in com.sun.javadoc that return MemberDoc
      Modifier and Type Method and Description
      MemberDoc SeeTag.referencedMember()
      Get the member doc for the field, constructor or method referenced by @see.
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.MemberSelectTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.MemberSelectTree

  • Packages that use MemberSelectTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of MemberSelectTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type MemberSelectTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitMemberSelect(MemberSelectTree node, P p)

    • Uses of MemberSelectTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type MemberSelectTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitMemberSelect(MemberSelectTree node, P p)
      R | SimpleTreeVisitor.visitMemberSelect(MemberSelectTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.apt.Messager (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.apt.Messager

  • Packages that use Messager
    Package Description
    com.sun.mirror.apt
    Classes used to communicate information between annotation processors and an annotation processing tool.

    • Uses of Messager in com.sun.mirror.apt

      Methods in com.sun.mirror.apt that return Messager
      Modifier and Type Method and Description
      Messager AnnotationProcessorEnvironment.getMessager()
      Deprecated.
      Returns the messager used to report errors, warnings, and other notices.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.Method (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.Method

  • Packages that use Method
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.
    com.sun.jdi.event
    This package defines JDI events and event processing.

    • Uses of Method in com.sun.jdi

      Methods in com.sun.jdi that return Method
      Modifier and Type Method and Description
      Method ClassType.concreteMethodByName(String name, String signature)
      Returns a the single non-abstract Method visible from this class that has the given name and signature.
      Method Location.method()
      Gets the method containing this Location.
      Methods in com.sun.jdi that return types with arguments of type Method
      Modifier and Type Method and Description
      List<Method> ReferenceType.allMethods()
      Returns a list containing each Method declared in this type, and its superclasses, implemented interfaces, and/or superinterfaces.
      List<Method> ReferenceType.methods()
      Returns a list containing each Method declared directly in this type.
      List<Method> ReferenceType.methodsByName(String name)
      Returns a List containing each visible Method that has the given name.
      List<Method> ReferenceType.methodsByName(String name, String signature)
      Returns a List containing each visible Method that has the given name and signature.
      List<Method> ReferenceType.visibleMethods()
      Returns a list containing each Method declared or inherited by this type.
      Methods in com.sun.jdi with parameters of type Method
      Modifier and Type Method and Description
      Value ClassType.invokeMethod(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Invokes the specified static Method in the target VM.
      Value ObjectReference.invokeMethod(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Invokes the specified Method on this object in the target VM.
      ObjectReference ClassType.newInstance(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Constructs a new instance of this type, using the given constructor Method in the target VM.

    • Uses of Method in com.sun.jdi.event

      Methods in com.sun.jdi.event that return Method
      Modifier and Type Method and Description
      Method MethodExitEvent.method()
      Returns the method that was exited.
      Method MethodEntryEvent.method()
      Returns the method that was entered.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.declaration.MethodDeclaration (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.declaration.MethodDeclaration

  • Packages that use MethodDeclaration
    Package Description
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of MethodDeclaration in com.sun.mirror.declaration

      Subinterfaces of MethodDeclaration in com.sun.mirror.declaration
      Modifier and Type Interface and Description
      interface  AnnotationTypeElementDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in ExecutableElement.
      Methods in com.sun.mirror.declaration that return types with arguments of type MethodDeclaration
      Modifier and Type Method and Description
      Collection<? extends MethodDeclaration> TypeDeclaration.getMethods()
      Deprecated.
      Returns the methods that are directly declared by this class or interface.
      Collection<MethodDeclaration> ClassDeclaration.getMethods()
      Deprecated.
      Returns the methods that are directly declared by this class or interface.

    • Uses of MethodDeclaration in com.sun.mirror.util

      Methods in com.sun.mirror.util with parameters of type MethodDeclaration
      Modifier and Type Method and Description
      boolean Declarations.overrides(MethodDeclaration sub, MethodDeclaration sup)
      Deprecated.
      Tests whether one method overrides another.
      void SimpleDeclarationVisitor.visitMethodDeclaration(MethodDeclaration d)
      Deprecated.
      Visits a method declaration.
      void DeclarationVisitor.visitMethodDeclaration(MethodDeclaration d)
      Deprecated.
      Visits a method declaration.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.javadoc.MethodDoc (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.javadoc.MethodDoc

    • Uses of MethodDoc in com.sun.javadoc

      Subinterfaces of MethodDoc in com.sun.javadoc
      Modifier and Type Interface and Description
      interface  AnnotationTypeElementDoc
      Represents an element of an annotation type.
      Methods in com.sun.javadoc that return MethodDoc
      Modifier and Type Method and Description
      MethodDoc[] ClassDoc.methods()
      Return included methods in this class or interface.
      MethodDoc[] ClassDoc.methods(boolean filter)
      Return methods in this class or interface, filtered to the specified access modifier option.
      MethodDoc MethodDoc.overriddenMethod()
      Return the method that this method overrides.
      MethodDoc[] ClassDoc.serializationMethods()
      Return the serialization methods for this class or interface.
      Methods in com.sun.javadoc with parameters of type MethodDoc
      Modifier and Type Method and Description
      boolean MethodDoc.overrides(MethodDoc meth)
      Tests whether this method overrides another.
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.event.MethodEntryEvent (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.event.MethodEntryEvent

No usage of com.sun.jdi.event.MethodEntryEvent
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.request.MethodEntryRequest (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.request.MethodEntryRequest

  • Packages that use MethodEntryRequest
    Package Description
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of MethodEntryRequest in com.sun.jdi.request

      Methods in com.sun.jdi.request that return MethodEntryRequest
      Modifier and Type Method and Description
      MethodEntryRequest EventRequestManager.createMethodEntryRequest()
      Creates a new disabled MethodEntryRequest.
      Methods in com.sun.jdi.request that return types with arguments of type MethodEntryRequest
      Modifier and Type Method and Description
      List<MethodEntryRequest> EventRequestManager.methodEntryRequests()
      Return an unmodifiable list of the enabled and disabled method entry requests.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.event.MethodExitEvent (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.event.MethodExitEvent

No usage of com.sun.jdi.event.MethodExitEvent
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.request.MethodExitRequest (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.request.MethodExitRequest

  • Packages that use MethodExitRequest
    Package Description
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of MethodExitRequest in com.sun.jdi.request

      Methods in com.sun.jdi.request that return MethodExitRequest
      Modifier and Type Method and Description
      MethodExitRequest EventRequestManager.createMethodExitRequest()
      Creates a new disabled MethodExitRequest.
      Methods in com.sun.jdi.request that return types with arguments of type MethodExitRequest
      Modifier and Type Method and Description
      List<MethodExitRequest> EventRequestManager.methodExitRequests()
      Return an unmodifiable list of the enabled and disabled method exit requests.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.MethodInvocationTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.MethodInvocationTree

  • Packages that use MethodInvocationTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of MethodInvocationTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type MethodInvocationTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitMethodInvocation(MethodInvocationTree node, P p)

    • Uses of MethodInvocationTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type MethodInvocationTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitMethodInvocation(MethodInvocationTree node, P p)
      R | SimpleTreeVisitor.visitMethodInvocation(MethodInvocationTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.MethodTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.MethodTree

  • Packages that use MethodTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of MethodTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type MethodTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitMethod(MethodTree node, P p)

    • Uses of MethodTree in com.sun.source.util

      Methods in com.sun.source.util that return MethodTree
      Modifier and Type Method and Description
      abstract MethodTree Trees.getTree(ExecutableElement method)
      Gets the MethodTree node for a given ExecutableElement.
      Methods in com.sun.source.util with parameters of type MethodTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitMethod(MethodTree node, P p)
      R | SimpleTreeVisitor.visitMethod(MethodTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.Mirror (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.Mirror

  • Packages that use Mirror
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.
    com.sun.jdi.event
    This package defines JDI events and event processing.
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of Mirror in com.sun.jdi

      Subinterfaces of Mirror in com.sun.jdi
      Modifier and Type Interface and Description
      interface  ArrayReference
      Provides access to an array object and its components in the target VM.
      interface  ArrayType
      Provides access to the class of an array and the type of its components in the target VM.
      interface  BooleanType
      The type of all primitive boolean values accessed in the target VM.
      interface  BooleanValue
      Provides access to a primitive boolean value in the target VM.
      interface  ByteType
      The type of all primitive byte values accessed in the target VM.
      interface  ByteValue
      Provides access to a primitive byte value in the target VM.
      interface  CharType
      The type of all primitive char values accessed in the target VM.
      interface  CharValue
      Provides access to a primitive char value in the target VM.
      interface  ClassLoaderReference
      A class loader object from the target VM.
      interface  ClassObjectReference
      An instance of java.lang.Class from the target VM.
      interface  ClassType
      A mirror of a class in the target VM.
      interface  DoubleType
      The type of all primitive double values accessed in the target VM.
      interface  DoubleValue
      Provides access to a primitive double value in the target VM.
      interface  Field
      A class or instance variable in the target VM.
      interface  FloatType
      The type of all primitive float values accessed in the target VM.
      interface  FloatValue
      Provides access to a primitive float value in the target VM.
      interface  IntegerType
      The type of all primitive int values accessed in the target VM.
      interface  IntegerValue
      Provides access to a primitive int value in the target VM.
      interface  InterfaceType
      A mirror of an interface in the target VM.
      interface  LocalVariable
      A local variable in the target VM.
      interface  Location
      A point within the executing code of the target VM.
      interface  LongType
      The type of all primitive long values accessed in the target VM.
      interface  LongValue
      Provides access to a primitive long value in the target VM.
      interface  Method
      A static or instance method in the target VM.
      interface  MonitorInfo
      Information about a monitor owned by a thread.
      interface  ObjectReference
      An object that currently exists in the target VM.
      interface  PathSearchingVirtualMachine
      A virtual machine which searches for classes through paths
      interface  PrimitiveType
      The type associated with non-object values in a target VM.
      interface  PrimitiveValue
      The value assigned to a field or variable of primitive type in a target VM.
      interface  ReferenceType
      The type of an object in a target VM.
      interface  ShortType
      The type of all primitive short values accessed in the target VM.
      interface  ShortValue
      Provides access to a primitive short value in the target VM.
      interface  StackFrame
      The state of one method invocation on a thread's call stack.
      interface  StringReference
      A string object from the target VM.
      interface  ThreadGroupReference
      A thread group object from the target VM.
      interface  ThreadReference
      A thread object from the target VM.
      interface  Type
      The mirror for a type in the target VM.
      interface  TypeComponent
      An entity declared within a user defined type (class or interface).
      interface  Value
      The mirror for a value in the target VM.
      interface  VirtualMachine
      A virtual machine targeted for debugging.
      interface  VoidType
      The type of all primitive void values accessed in the target VM.
      interface  VoidValue
      Provides access to a primitive void value in the target VM.

    • Uses of Mirror in com.sun.jdi.event

      Subinterfaces of Mirror in com.sun.jdi.event
      Modifier and Type Interface and Description
      interface  AccessWatchpointEvent
      Notification of a field access in the target VM.
      interface  BreakpointEvent
      Notification of a breakpoint in the target VM.
      interface  ClassPrepareEvent
      Notification of a class prepare in the target VM.
      interface  ClassUnloadEvent
      Notification of a class unload in the target VM.
      interface  Event
      An occurrence in a target VM that is of interest to a debugger.
      interface  EventQueue
      Manager of incoming debugger events for a target VM.
      interface  EventSet
      Several Event objects may be created at a given time by the target VirtualMachine.
      interface  ExceptionEvent
      Notification of an exception in the target VM.
      interface  LocatableEvent
      Abstract superinterface of events which have both location and thread.
      interface  MethodEntryEvent
      Notification of a method invocation in the target VM.
      interface  MethodExitEvent
      Notification of a method return in the target VM.
      interface  ModificationWatchpointEvent
      Notification of a field modification in the target VM.
      interface  MonitorContendedEnteredEvent
      Notification that a thread in the target VM is entering a monitor after waiting for it to be released by another thread.
      interface  MonitorContendedEnterEvent
      Notification that a thread in the target VM is attempting to enter a monitor that is already acquired by another thread.
      interface  MonitorWaitedEvent
      Notification that a thread in the target VM has finished waiting on an monitor object.
      interface  MonitorWaitEvent
      Notification that a thread in the target VM is about to wait on a monitor object.
      interface  StepEvent
      Notification of step completion in the target VM.
      interface  ThreadDeathEvent
      Notification of a completed thread in the target VM.
      interface  ThreadStartEvent
      Notification of a new running thread in the target VM.
      interface  VMDeathEvent
      Notification of target VM termination.
      interface  VMDisconnectEvent
      Notification of disconnection from target VM.
      interface  VMStartEvent
      Notification of initialization of a target VM.
      interface  WatchpointEvent
      Notification of a field triggered event encountered by a thread in the target VM.

    • Uses of Mirror in com.sun.jdi.request

      Subinterfaces of Mirror in com.sun.jdi.request
      Modifier and Type Interface and Description
      interface  AccessWatchpointRequest
      Request for notification when the contents of a field are accessed in the target VM.
      interface  BreakpointRequest
      Identifies a Location in the target VM at which execution should be stopped.
      interface  ClassPrepareRequest
      Request for notification when a class is prepared in the target VM.
      interface  ClassUnloadRequest
      Request for notification when a class is unloaded in the target VM.
      interface  EventRequest
      Represents a request for notification of an event.
      interface  EventRequestManager
      Manages the creation and deletion of EventRequests.
      interface  ExceptionRequest
      Request for notification when an exception occurs in the target VM.
      interface  MethodEntryRequest
      Request for notification when a method is invoked in the target VM.
      interface  MethodExitRequest
      Request for notification when a method returns in the target VM.
      interface  ModificationWatchpointRequest
      Request for notification when a field is set.
      interface  MonitorContendedEnteredRequest
      Request for notification of a thread in the target VM entering a monitor after waiting for it to be released by another thread.
      interface  MonitorContendedEnterRequest
      Request for notification of a thread in the target VM attempting to enter a monitor already acquired by another thread.
      interface  MonitorWaitedRequest
      Request for notification when a thread in the target VM has finished waiting on a monitor object.
      interface  MonitorWaitRequest
      Request for notification when a thread in the target VM is about to wait on a monitor object.
      interface  StepRequest
      Request for notification when a step occurs in the target VM.
      interface  ThreadDeathRequest
      Request for notification when a thread terminates in the target VM.
      interface  ThreadStartRequest
      Request for notification when a thread starts execution in the target VM.
      interface  VMDeathRequest
      Request for notification when the target VM terminates.
      interface  WatchpointRequest
      Identifies a Field in the target VM being watched.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.mirror.type.MirroredTypeException (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.mirror.type.MirroredTypeException

No usage of com.sun.mirror.type.MirroredTypeException
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.mirror.type.MirroredTypesException (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.mirror.type.MirroredTypesException

No usage of com.sun.mirror.type.MirroredTypesException
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Mixing Signed and Unsigned Code

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
lang="en-US" dir="ltr" xml:lang="en-US">

Mixing Signed and Unsigned Code
Ensuring Application and Applet Security

Contents

  • Overview
  • Mixed Code Protection Options for Users
  • Deploying Signed Applications and Applets Securely Without a Mixed Code Warning
    • Trusted-Only Attribute
    • Trusted-Library Attribute
  • Mixed Code FAQ
  • For More Information

Overview

Signed Java Web Start applications and applets that contain signed and unsigned components could potentially be unsafe unless the mixed code was intended by the application vendor. As of the Java SE 6 Update 19 release (or later), when a program contains both signed and unsigned components, a warning dialog is raised. The following is an example of the dialog that the user may see:

Screen shot of Mixed Code Warning Dialog

Clicking the More Information... link brings up the following panel:

Screen shot of the More Information Panel

Clicking Yes blocks potentially unsafe components from running, and the program may terminate. If the user clicks the No button, the application or applet continues execution with some added protections.

Raising a warning is the default behavior, but there are options available to manage how this situation is handled.

  • For users and systems administrators, various protection options are available. For more information, see Mixed Code Protection Options for Users.
  • For developers and deployers, two manifest attributes are available. For more information, see Deploying Signed Applications and Applets Securely Without a Mixed Code Warning.
Note: If any concepts are unclear, such as how to modify a manifest file, or how to sign a jar file, or how to use a deployment configuration file, see For More Information for useful links.

Mixed Code Protection Options for Users

There are two mechanisms for managing how mixed code programs are handled.
  • From the Java Control Panel

    You can manage how mixed code programs are handled via the Java Control Panel. The following screen shot shows the four levels of control available. See the Mixed code heading towards the bottom of the panel.

    Screen shot of Java Control Panel

    How to access the Java Control Panel varies for each platform and sometimes varies for different releases of a platform. On Microsoft Windows Vista and XP, you can bring up the panel via Start menu > Control Panel > Java Control Panel.

    The first three options enable the software protections, but behave a bit differently.

    • Enable - show warning if needed
      This is the default setting. When a potential security risk is encountered, a warning dialog is raised. Clicking Yes blocks potentially unsafe components from running and may terminate the program. When the user clicks No, the application or applet continues execution with some added protections (packages or resources that are later encountered with the same names but have different trust levels, i.e., sign vs unsigned, will not be loaded).
    • Enable - hide warning and run with protections
      This option suppresses the warning dialog. The code executes as if the user had clicked No from the warning dialog.
    • Enable - hide warning and don't run untrusted code
      This option suppresses the warning dialog and behaves as if the user had clicked Yes from the warning dialog.

    The final option, Disable verification, is not recommended. This option completely disables the software from checking for mixing trusted and untrusted code, leaving the user to run potentially unsafe code with no warning and without the additional protections.

  • From the deployment.properties File

    The mixed code protection options can also be set by using the deployment.security.mixcode deployment property, as described in Deployment Configuration File and Properties.

    • deployment.security.mixcode=ENABLE

      This option enables mixed code verification. When a potential security risk is encountered, a warning dialog is raised. This is the default value for this property.

    • deployment.security.mixcode=HIDE_RUN

      This option suppresses the warning dialog. The code executes as if the user had clicked No from the warning dialog.

    • deployment.security.mixcode=HIDE_CANCEL

      This option suppresses the warning dialog and behaves as if the user had clicked Yes from the warning dialog.

    • deployment.security.mixcode=DISABLE

      This option is not recommended. The software is disabled from checking for mixing trusted and untrusted code, leaving the user to run potentially unsafe code with no warning and without the additional protections.

Version note: To take advantage of these security enhancements, users need to install the Java SE or Java for Business 6 Update 19 release (or later) and use the new Java Plugin, which is enabled by default. To use an earlier JRE with the new Java Plugin, you need to install the Java for Business 5.0 Update 24 release (or later) or the Java for Business 1.4.2_26 release (or later) in order to enable the mixed code security enhancement for those release families.
Note 1: Mixed code checking for the 1.4.2 release is available only for the Windows platform.
Note 2: For Solaris, the new Java Plugin requires Firefox 3 or later. Netscape 7 and Firefox 2 are not supported.
Note 3: For more information on which platforms are supported by the new plugin, see the Release Notes for the Next-Generation Java Plugin.

Deploying Signed Applications and Applets Securely Without a Mixed Code Warning

This section describes best practices for developers and deployers to protect their applications and applets from being maliciously re-purposed by replacing trusted components with untrusted ones.

Two new JAR manifest attributes are available, as of Java SE 6 Update 19, for deploying signed applications and applets. A warning dialog is not displayed when one of these manifest attributes is included.

Developers and deployers should check their signed Java Web Start applications and applets to determine if they mix signed and unsigned code. If users of these applications and applets may inadvertently download these applications and applets from rogue websites, deploying or re-deploying with one of the following attributes should be considered. Existing signed jars need to be re-signed after adding one of these manifest attributes. Note: source code of the classes and resources are not required for re-signing with the new manifest entries.

Trusted-Only Attribute

For applications and applets that do not require unsigned components, the Trusted-Only attribute should be used. No warning dialog will be displayed and an application or applet that loads a jar file containing this attribute will not load any untrusted classes or resources. This attribute prevents a signed application or applet from being re-purposed with unsigned components. You can specify Trusted-Only: true in the manifest file. For example:

Manifest-Version: 1.0
Trusted-Only: true
Created-By: 1.6.0-internal (Sun Microsystems Inc.)

All classes and resources in the application or applet must be signed and trusted.

Trusted-Library Attribute

For applications and applets that are designed to allow unsigned components, the Trusted-Library attribute should be used. No warning dialog will be displayed and an application or applet may load jar files containing untrusted classes or resources. This attribute prevents signed components in an application or applet from being re-purposed with unsigned components. You can specify Trusted-Library: true in the manifest file. For example:

Manifest-Version: 1.0
Trusted-Library: true
Created-By: 1.6.0-internal (Sun Microsystems Inc.)

All classes and resources in a jar file containing this manifest attribute must be signed and trusted.

In a mixed code application or applet, all signed classes and resources must be included in jar files that contain the Trusted-Library attribute.

All trusted library jars are loaded into a separate dedicated class loader which is unique to the application or applet instance. This new Trusted-Library loader is now the parent of the normal Web Start or applet class loader. For backwards compatibility with the original search order, both loaders cooperate to implement a common class path. Consistent with prior releases, jar files are lazily downloaded and opened as needed to find requested classes and resources.

Code in a jar file that is to be marked with the Trusted-Library manifest attribute may need to be modified slightly if it uses calls that are class loader dependent, such as the single parameter version of Class.forName(), Class.getResource(), and Class.getResourceAsStream(), some variants of java.util.ResourceBundle.getBundle(), and any other methods which operate relative to their immediate caller's defining loader. Changes only need to be made if the requested class or resource might be found in a jar file which is not a Trusted-Library (and is therefore loaded by the normal Web Start or applet class loader).

Code in a Trusted-Library can look up the normal loader by invoking Thread.currentThread().getContextClassLoader(). Note, however, that there are uncommon circumstances in which getContextClassLoader() may return null. For example, this may happen when the garbage collector uses a JRE system thread to invoke the Object.finalize() method of an unreachable instance.

If you need to convert class to Class.getResource() or Class.getResourceAsStream() to their ClassLoader equivalents, remember to adjust the string parameter as described by the documentation for those two methods. If the original resource name began with '/', then it was an absolute name and the leading '/' simply needs to be removed. Otherwise, determine if the class instance which was the target of the getResource call is in a named package. If it is an array you should first determine the underlying component type of the array. Invoke Class.getName() on the class or component type instance. If the class name contains any '.' characters, it is in a named package that will need to be prepended to the original resource name. Determine the package name by removing any characters after, and including, the trailing '.' character. Next, replace any remaining '.' characters with '/' characters. Finally, add a trailing '/' and append the original resource name string. This new string can now be passed to the ClassLoader version of the getResource() or getResourceAsStream() methods.

Generally, care must be taken to ensure that the code in the trusted library is written in a careful and secure manner and is otherwise compatible with being loaded in a separate class loader instance from any remaining jars which are part of the application and are loaded by the normal loader.

Mixed Code FAQ

  • Question: I develop and/or deploy applications. How do I know whether I need to be concerned about this issue?

    Answer: If you do not use the new manifest entries and you encounter the warning dialog when running your signed application or applet, your program contains mixed code and is affected.

  • Question: Is there a test I can run to determine whether I am affected?

    Answer: Test your Java Web Start applications and Java applets against Java SE or Java for Business 6 Update 19 or later. If you are running earlier release families, you should additionally install and test your program under 5.0 Update 24 (or later), or 1.4.2_26 (or later), as appropriate. If you see the warning dialog, then the Java Web Start application or applet contains mixed code.

  • Question: What actions can I take?

    Answer: End users can click the "More Information" link before deciding whether to click "Yes" or "No" in response to the warning dialog. IT or System Administrators can choose from one of the Mixed Code protection options and configure enterprise desktops through the respective deployment properties described above. Developers and deployers can use the new manifest entries to protect their applications from tampering. No warning dialog will be displayed when one of these manifest entries is used.

  • Question: What should Java ISVs, OEMs, and application vendors do with their code?

    Answer: Two manifest entries are available to application vendors to deploy, or re-deploy, their Java Web Start applications and Java applets.

  • Question:What versions of Java SE and Java for Business are affected?

    Answer: The following releases from Oracle are affected:

    • Java SE and Java for Business 6 Update 18 and earlier
    • Java for Business 5.0 Update 23 and earlier
    • Java for Business 1.4.2_25 and earlier
  • Question: What about Java applets and Java Web Start applications from the Internet, do I need to be concerned about those?

    Answer: Users will see a warning dialog if a signed Java Web Start application or Java applet contains mixed code regardless of whether it is downloaded from the Internet or Intranet.

  • Question: What if I am behind a corporate firewall?

    Answer: The mixed code issue applies. See the question on applets and applications from the Internet.

  • Question: Is this an issue for Oracle JRockit?

    Answer: No.

  • Question: I am using an implementation of Java from another vendor. Are they affected in the same way?

    Answer: Please contact your vendor for advice on their implementation.

  • Question: What are the risks to remaining on Java SE 6u18 (or earlier) to avoid seeing the warnings?

    Answer: Java SE 6 Update 19 (or later) contains the latest security fixes and Oracle recommends that customers use the latest release.

  • Question: If I move to 6 Update 19 or later, what type of testing do I need to consider?

    Answer: See the question on testing. In addition, the release notes for each update release documents the latest changes included.

  • Question: I am running on Solaris and/or Linux and I use Java applets. How do I leverage these security features?

    Answer: You need to use Firefox 3 and the next-generation Java Plugin. You can get Firefox 3 through sunfreeware.com. They have a full list of Firefox packages available. See Manual Installation and Registration of Solaris Plugin or Manual Installation and Registration of Linux Plugin, as appropriate, for more information.

  • Question: I am a developer. What are the new security exceptions that are added with this enhancement?

    Answer: The following SecurityException messages are described for informational and debugging purposes only. The actual message contents may change between different implementations and releases.

    These SecurityExceptions are thrown when a jar file contains one of the new manifest attributes and the jar file itself contains untrusted components.

    attempted to open sandboxed jar "+ url +" as Trusted-Only
attempted to open sandboxed jar "+ url +" as Trusted-Library
    The following SecurityException is thrown when a jar file contains the new Trusted-Only manifest attribute and untrusted components have previously been accessed.
    attempted to open Trusted-Only jar "+ url +" on sandboxed loader
    The following SecurityException is thrown when at least one jar containing the Trusted-Only manifest attribute has been opened and a subsequent attempt is made to load an untrusted component.
    Trusted-Only loader attempted to load sandboxed resource from "+ url"
    The following two SecurityExceptions are thrown when mixed components are first detected and a decision is made to disallow mixing. In the first case, everything previosly loaded was trusted and then an attempt was made to load an untrusted component. The second case is the reverse condition.
    trusted loader attempted to load sandboxed resource from "+ url"
sandboxed loader attempted to load trusted resource from "+ url"
    The following two SecurityExceptions are thrown after mixed components had previously been detected and a decision was made to allow them to coexist. The exceptions indicate that a component name collision (resource name or class package name) was detected between trusted and untrusted components and the request to load the resource or class was denied.
    "resource \"" + name + "\" does not match trust level of other resources of the same name"
"class \"" + packageName + "\" does not match trust level of other classes in the same package"
    The following two SecurityExceptions are thrown when untrusted components have been previously accessed, an attempt to load a trusted component was previously detected, and a decision was made to allow mixed components to coexist, and a jar containing trusted components is opened and a component name collision is detected between trusted and untrusted components.
    "untrusted resource \"" + name + "\" in class path"
"untrusted class package \"" + packageName + "\" in class path"
  • Question: I have a mixed code Java Web Start application which cannot be easily updated to use the Trusted-Library manifest attribute. Can I sign the jar files in the sandboxed JNLP without having to change the JNLP to request the all-permissions security model?

    Answer: Yes, with some limitations beginning with Java Web Start in Java SE or Java for Business Update 21. The sandboxed jar files must be signed in the same way (same signing certificates) as one or more of the trusted jar files in a JNLP file that uses the all-permissions security model, and the trusted jar file must be opened by Java Web Start prior to any sandboxed resource being loaded which shares the same signer. This means the trusted jar file must be earlier in Java Web Start's jar search order or it is triggered to load independent of the simple search order by use of the jar indexing feature. In Java Web Start, the main application JNLP's jars are searched first, followed in declaration order by any JNLP extensions. Jar files labeled within a JNLP as "eager" are searched first, followed by "lazy" jar files, followed by any jar files labeled as using the "part" feature.

  • Question: I have Java on my phone. Is that affected by this issue?

    Answer: No, Java ME is not affected.

For More Information

  • Secure Coding Guidelines for Java
  • Deployment Configuration File and Properties
  • Modifying a Manifest File, a section in The Java Tutorial, has information on how to work with manifest files.
  • Signing JAR Files, a section in The Java Tutorial.
  • Java Control Panel explains the various options provided by this panel.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.event.ModificationWatchpointEvent (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.event.ModificationWatchpointEvent

No usage of com.sun.jdi.event.ModificationWatchpointEvent
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.request.ModificationWatchpointRequest (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.request.ModificationWatchpointRequest

  • Packages that use ModificationWatchpointRequest
    Package Description
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of ModificationWatchpointRequest in com.sun.jdi.request

      Methods in com.sun.jdi.request that return ModificationWatchpointRequest
      Modifier and Type Method and Description
      ModificationWatchpointRequest EventRequestManager.createModificationWatchpointRequest(Field field)
      Creates a new disabled watchpoint which watches accesses to the specified field.
      Methods in com.sun.jdi.request that return types with arguments of type ModificationWatchpointRequest
      Modifier and Type Method and Description
      List<ModificationWatchpointRequest> EventRequestManager.modificationWatchpointRequests()
      Return an unmodifiable list of the enabled and disabled modification watchpoint requests.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.mirror.declaration.Modifier (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.mirror.declaration.Modifier

  • Packages that use Modifier
    Package Description
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of Modifier in com.sun.mirror.declaration

      Methods in com.sun.mirror.declaration that return Modifier
      Modifier and Type Method and Description
      static Modifier Modifier.valueOf(String name)
      Deprecated.
      Returns the enum constant of this type with the specified name.
      static Modifier[] Modifier.values()
      Deprecated.
      Returns an array containing the constants of this enum type, in the order they are declared.
      Methods in com.sun.mirror.declaration that return types with arguments of type Modifier
      Modifier and Type Method and Description
      Collection<Modifier> Declaration.getModifiers()
      Deprecated.
      Returns the modifiers of this declaration, excluding annotations.

    • Uses of Modifier in com.sun.mirror.util

      Method parameters in com.sun.mirror.util with type arguments of type Modifier
      Modifier and Type Method and Description
      static DeclarationFilter DeclarationFilter.getFilter(Collection<Modifier> mods)
      Deprecated.
      Returns a filter that selects declarations containing all of a collection of modifiers.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.ModifiersTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.ModifiersTree

  • Packages that use ModifiersTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of ModifiersTree in com.sun.source.tree

      Methods in com.sun.source.tree that return ModifiersTree
      Modifier and Type | Method and Description
      ModifiersTree | VariableTree.getModifiers()
      ModifiersTree | MethodTree.getModifiers()
      ModifiersTree | ClassTree.getModifiers()
      Methods in com.sun.source.tree with parameters of type ModifiersTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitModifiers(ModifiersTree node, P p)

    • Uses of ModifiersTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type ModifiersTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitModifiers(ModifiersTree node, P p)
      R | SimpleTreeVisitor.visitModifiers(ModifiersTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Java VisualVM

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java VisualVM - Monitoring an Application

Java VisualVM presents data for local and remote applications in a tab specific for that application. When you open an application in Java VisualVM, each application opens in a new tab in the main window. You can have multiple application tabs open.

Monitoring an Application

You can use Java VisualVM to monitor a local application and view real-time, high-level data on the memory heap, thread activity, and the classes loaded in the Java Virtual Machine (JVM). Monitoring an application imposes low overhead and can be used for extended periods.

screenshot of Monitor tab

Monitoring data is displayed in the following graphs:

  • Heap. The Heap graph displays the total heap size and how much of the heap is currently used. These are the figures that a Java technology-based application (Java application) can obtain using the java.lang.Runtime.totalMemory() and java.lang.Runtime.freeMemory() calls.
  • PermGen. The PermGen graph displays changes in the permanent generation area over time. The permanent generation is the area of the heap where class and method objects are stored. If an application loads a very large number of classes, then the size of the permanent generation might need to be increased using the -XX:MaxPermSize option.
  • Classes The Classes graph displays an overview of the total number of loaded classes and shared classes.
  • Threads. The Threads graphs displays an overview of the number of live and daemon threads in the application's JVM. You can use Java VisualVM to take a thread dump if you want to capture and view exact data on application threads at a specific point in time. For more about working with threads, see the following document:
    • Monitoring Application Threads

The Monitoring tab contains buttons that enable you to perform the following actions:

  • Perform GC. Click Perform GC to perform garbage collection immediately.
  • Heap Dump. Click Heap Dump to take a heap dump. When you take a heap dump, a tab displaying the heap dump opens in the application tab. A node for the heap dump appears under the node for the application in the Applications window. For more about working with a heap dump, see the following document:
    • Browsing a Heap Dump
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.event.MonitorContendedEnteredEvent (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.event.MonitorContendedEnteredEvent

No usage of com.sun.jdi.event.MonitorContendedEnteredEvent
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.request.MonitorContendedEnteredRequest (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.request.MonitorContendedEnteredRequest

  • Packages that use MonitorContendedEnteredRequest
    Package Description
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of MonitorContendedEnteredRequest in com.sun.jdi.request

      Methods in com.sun.jdi.request that return MonitorContendedEnteredRequest
      Modifier and Type Method and Description
      MonitorContendedEnteredRequest EventRequestManager.createMonitorContendedEnteredRequest()
      Creates a new disabled MonitorContendedEnteredRequest.
      Methods in com.sun.jdi.request that return types with arguments of type MonitorContendedEnteredRequest
      Modifier and Type Method and Description
      List<MonitorContendedEnteredRequest> EventRequestManager.monitorContendedEnteredRequests()
      Return an unmodifiable list of the enabled and disabled monitor contended entered requests.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.event.MonitorContendedEnterEvent (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.event.MonitorContendedEnterEvent

No usage of com.sun.jdi.event.MonitorContendedEnterEvent
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.request.MonitorContendedEnterRequest (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.request.MonitorContendedEnterRequest

  • Packages that use MonitorContendedEnterRequest
    Package Description
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of MonitorContendedEnterRequest in com.sun.jdi.request

      Methods in com.sun.jdi.request that return MonitorContendedEnterRequest
      Modifier and Type Method and Description
      MonitorContendedEnterRequest EventRequestManager.createMonitorContendedEnterRequest()
      Creates a new disabled MonitorContendedEnterRequest.
      Methods in com.sun.jdi.request that return types with arguments of type MonitorContendedEnterRequest
      Modifier and Type Method and Description
      List<MonitorContendedEnterRequest> EventRequestManager.monitorContendedEnterRequests()
      Return an unmodifiable list of the enabled and disabled monitor contended enter requests.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.MonitorInfo (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.MonitorInfo

  • Packages that use MonitorInfo
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of MonitorInfo in com.sun.jdi

      Methods in com.sun.jdi that return types with arguments of type MonitorInfo
      Modifier and Type Method and Description
      List<MonitorInfo> ThreadReference.ownedMonitorsAndFrames()
      Returns a List containing a MonitorInfo object for each monitor owned by the thread.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Document Information - Java SE Monitoring and Management Guide

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Contents Next Next

Part No: N/A

Java Platform, Standard Edition 6

October 2006
Contents Next Next
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.event.MonitorWaitedEvent (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.event.MonitorWaitedEvent

No usage of com.sun.jdi.event.MonitorWaitedEvent
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.request.MonitorWaitedRequest (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.request.MonitorWaitedRequest

  • Packages that use MonitorWaitedRequest
    Package Description
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of MonitorWaitedRequest in com.sun.jdi.request

      Methods in com.sun.jdi.request that return MonitorWaitedRequest
      Modifier and Type Method and Description
      MonitorWaitedRequest EventRequestManager.createMonitorWaitedRequest()
      Creates a new disabled MonitorWaitedRequest.
      Methods in com.sun.jdi.request that return types with arguments of type MonitorWaitedRequest
      Modifier and Type Method and Description
      List<MonitorWaitedRequest> EventRequestManager.monitorWaitedRequests()
      Return an unmodifiable list of the enabled and disabled monitor waited requests.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.event.MonitorWaitEvent (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.event.MonitorWaitEvent

No usage of com.sun.jdi.event.MonitorWaitEvent
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.request.MonitorWaitRequest (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.request.MonitorWaitRequest

  • Packages that use MonitorWaitRequest
    Package Description
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of MonitorWaitRequest in com.sun.jdi.request

      Methods in com.sun.jdi.request that return MonitorWaitRequest
      Modifier and Type Method and Description
      MonitorWaitRequest EventRequestManager.createMonitorWaitRequest()
      Creates a new disabled MonitorWaitRequest.
      Methods in com.sun.jdi.request that return types with arguments of type MonitorWaitRequest
      Modifier and Type Method and Description
      List<MonitorWaitRequest> EventRequestManager.monitorWaitRequests()
      Return an unmodifiable list of the enabled and disabled monitor wait requests.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


More Things You Can Do With Java GSS-API and JAAS

The previous tutorial, Use of JAAS Login Utility and Java GSS-API for Secure Message Exchanges, demonstrated how two applications, in particular a client and a server, could use the Java GSS-API to establish a secure context between them and then securely exchange messages.

There are additional operations the context acceptor (the server in our client/server example) can perform once the context has been established with the context initiator (the client). Basically, the server can "impersonate" the client. The level of impersonation depends upon whether or not the client has delegated credentials to the server.

  • Executing Code on Behalf of the Client User
  • Using Credentials Delegated From the Client

Executing Code on Behalf of the Client User

One possible type of client impersonation the server can do is causing code to be executed on behalf of the same entity (user) the client code is executed on behalf of. Normally, a method executed by a thread uses the access control settings for that thread itself. However, when impersonating a client in this tutorial, the server uses the client's access control settings so that the server has access to exactly those resources that the client itself has when it runs.

One major benefit of the approach used in this tutorial is that the JAAS authorization component can be used for access control. Without the JAAS authorization component, the server principal would need access to any resources accessed by the code executed on behalf of the client user, and the server code would need to include access control logic to determine whether the user was authorized to access such resources. By utilizing JAAS authorization, providing principal-based access control, the access control is handled automatically. Permissions for the security-sensitive operations in such code only need to be granted to that user and not also to the server code. See the JAAS Authorization tutorial for more information on JAAS authorization.

  • Basic Approach
  • Sample Code and Policy File
  • Running the Sample Code

Basic Approach

How does the server "impersonate" the client to execute code on behalf of the user running the client code? Essentially the same way the client code is set up to be run on behalf of that user. All the server code needs to know is the user's principal name, which it can obtain from the context established with the client.

Recall that JAAS authentication of the user executing the client code results in creation of a Subject containing a Principal with the user (principal) name. The Subject is subsequently associated with a new access control context (via a Subject.doAsPrivileged call from the Login utility) and the client code is considered to be executed on behalf of the user; subsequent access control decisions are based on whether or not that particular user, executing the client code, is granted the required permissions.

The server code is similarly handled, except in that case the Principal specified for authentication is typically a "service principal", not a user principal. Again, a Subject containing a Principal with the specified principal name is created, Subject.doAsPrivileged is called, and the server code is considered to be executed on behalf of the specified principal; subsequent access control decisions are based on whether or not that particular principal, executing the server code, is granted the required permissions.

Once the client and server have established a mutual context, the context initiator's name (the client's principal name) can be determined by the following:

GSSName clientGSSName = context.getSrcName();

The context acceptor (the server) can use this name to construct a Subject containing a Principal that represents the same entity. For example, if you are using a JRE from Sun Microsystems, you can construct such a Subject via the following:

Subject client =
  com.sun.security.jgss.GSSUtil.createSubject(clientGSSName, null);

The createSubject method creates a new Subject from the GSSName and GSSCredential specified as arguments. If the server code is just going to execute code on behalf of the user in the local JVM, the user's credentials are not required - and in fact cannot even be obtained unless the client has delegated credentials to the server, as discussed in Using Credentials Delegated From the Client. Since the credentials are not needed here, we pass a null for the GSSCredential argument.

Note: If you are not using a JRE from Sun Microsystems, an alternative way to do this is to construct a KerberosPrincipal instance as follows:
KerberosPrincipal principal =
  new KerberosPrincipal(clientGSSName.toString());

Then use this principal to construct a new Subject or populate this principal in the principal set of an existing Subject.

The code that the server would like to execute on behalf of the user should be initiated from the run method of a class that implements java.security.PrivilegedAction (or java.security.PrivilegedExceptionAction). That is, the code can either be in such a run method or invoked from such a run method.

The server code can pass the Subject, along with an instance of the PrivilegedAction (or PrivilegedExceptionAction), to Subject.doAsPrivileged to execute the subsequent code, starting with the run method in the PrivilegedAction, on behalf of the principal (user) in the specified Subject.

For example, suppose the PrivilegedAction class is called ReadFileAction and it takes as an argument a String with the principal name. You can create an instance of this class by

String clientName = clientGSSName.toString();
PrivilegedAction readFile =
    new ReadFileAction(clientName);

The call to doAsPrivileged is then

Subject.doAsPrivileged(client, readFile, null);

Sample Code and Policy File

The following sample code and policy file illustrate the server impersonating the client in order to execute code whose security-sensitive operations are only permitted to be done by the specific user executing the client.

  • SampleServerImp.java
  • ReadFileAction.java
  • serverimp.policy

SampleServerImp.java

The SampleServerImp.java file is exactly the same as the SampleServer.java file from the previous (Use of JAAS Login Utility and Java GSS-API for Secure Message Exchanges) tutorial, except that after exchanging messages with the client, it has the following code to perform a ReadFileAction as the client user:

System.out.println("Impersonating client.");

/*
 * Extract the KerberosPrincipal from the client GSSName and
 * populate it in the principal set of a new Subject. Pass in a
 * null for credentials since credentials will not be needed.
 */
GSSName clientGSSName = context.getSrcName();
System.out.println("clientGSSName: " + clientGSSName);
Subject client =
   com.sun.security.jgss.GSSUtil.createSubject(clientGSSName,
        null);

/*
* Construct an action that will read a file meant only for the
* client
*/
String clientName = clientGSSName.toString();
PrivilegedAction readFile =
   new ReadFileAction(clientName);

/*
* Invoke the action via a doAsPrivileged. This allows the
* action to be executed as the client subject, and it also
* runs that code as privileged. This means that any permission
* checking that happens beyond this point applies only to
* the code being run as the client.
*/
Subject.doAsPrivileged(client, readFile, null);

ReadFileAction.java

The ReadFileAction.java file contains the ReadFileAction class. Its constructor takes as an argument a String for the name of the client user. The client username is used to construct a file name for a file from which ReadFileAction will attempt to read. The file name will be:

./data/<name>_info.txt
where <name> is the client username without its corresponding realm. For example, if the full username is mjones@KRBNT-OPERATIONS.ABC.COM, then the file name is
./data/mjones_info.txt
Note: On Microsoft Windows systems the forward slashes will be backward slashes.

The ReadFileAction run method reads the specified file and prints its contents.

serverimp.policy

ReadFileAction attempts to read a file, which is a security-checked operation. Since ReadFileAction is considered to be executed as the client user (Principal), the appropriate permission must be granted not only to the ReadFileAction code itself, but to the client Principal as well.

Assuming the ReadFileAction class is placed in a JAR file named ReadFileAction.jar, and the user principal name is mjones@KRBNT-OPERATIONS.ABC.COM, this permission can be granted via the following in a policy file:

grant CodeBase "file:./ReadFileAction.jar"
    Principal javax.security.auth.kerberos.KerberosPrincipal
        "mjones@KRBNT-OPERATIONS.ABC.COM" {

    permission java.io.FilePermission "data/mjones_info.txt",
        "read";
};
The serverimp.policy file is exactly the same as the server.policy file from the previous (Use of JAAS Login Utility and Java GSS-API for Secure Message Exchanges) tutorial, except that it grants the SampleServer code the javax.security.auth.AuthPermission "doAsPrivileged" permission it needs in order to call the doAsPrivileged method, and it has the following placeholder for granting the FilePermission shown above:
grant CodeBase "file:./ReadFileAction.jar"
    Principal javax.security.auth.kerberos.KerberosPrincipal
        "your_user_name@your_realm" {

    permission java.io.FilePermission "data/your_user_name_info.txt",
        "read";
};

You must substitute your Kerberos realm for your_realm, and your user name for your_user_name in both your_user_name@your_realm and data/your_user_name_info.txt. If you are working on a Microsoft Windows sytem, you also replace the "/" in data/your_user_name_info.txt with a "\".

Running the Sample Code

To run the sample code illustrating the server impersonating the client, do everything listed in Running the SampleClient and SampleServer Programs in the previous tutorial, except for the following:

  • In the "Prepare SampleServer for Execution" step:
    • Use SampleServerImp.java instead of SampleServer.java. Compile it and create a JAR file named SampleServerImp.jar containing SampleServerImp.class via the following:
      javac SampleServerImp.java
jar -cvf SampleServerImp.jar SampleServerImp.class
    • Use the serverimp.policy policy file instead of server.policy.
    • Use the csImpLogin.conf login configuration file instead of cs.conf.
    • Copy ReadFileAction.java to the same directory as the other files. Compile it and place it in a JAR file via the following:
      javac ReadFileAction.java
jar -cvf ReadFileAction.jar ReadFileAction.class
    • In csImpLogin.conf, replace "service_principal@your_realm" with the Kerberos name of the service principal that represents SampleServer.
    • In serverimp.policy, replace "service_principal@your_realm" in both places it appears with the Kerberos name of the service principal that represents SampleServer. (The same name as that used in the login configuration file.) In addition, substitute your Kerberos realm for your_realm, and your user name for your_user_name in both your_user_name@your_realm and data/your_user_name_info.txt. If you are running on a Microsoft Windows system, then replace the "/" in data/your_user_name_info.txt with a "\".
    • Create a data subdirectory of your current directory and create a short text file of the specified name in that directory. For example, if your user name is mjones, the file to be placed in the data subdirectory should be named mjones_info.txt.
  • In the "Execute SampleServer" step:
    • Use the following commands instead of those specified in that section so that SampleServerImp is executed, serverimp.policy and csImpLogin.conf are used, and ReadFileAction.jar is included.

      Important: In these commands, you must replace <port_number> with an appropriate port number (a high port number such as 4444), <your_realm> with your Kerberos realm, and <your_kdc> with your Kerberos KDC.

      Here is the command for Microsoft Windows systems:

        java -classpath Login.jar;SampleServerImp.jar;ReadFileAction.jar
    -Djava.security.manager
    -Djava.security.krb5.realm=<your_realm>
    -Djava.security.krb5.kdc=<your_kdc>
    -Djava.security.policy=serverimp.policy
    -Djava.security.auth.login.config=csImpLogin.conf
    Login SampleServerImp <port_number>

      Here is the command for UNIX systems:

        java -classpath Login.jar:SampleServerImp.jar:ReadFileAction.jar
    -Djava.security.manager
    -Djava.security.krb5.realm=<your_realm>
    -Djava.security.krb5.kdc=<your_kdc>
    -Djava.security.policy=serverimp.policy
    -Djava.security.auth.login.config=csImpLogin.conf
    Login SampleServerImp <port_number>

      As usual, type the full command on one line. Multiple lines are used here for legibility. If the command is too long for your system, you may need to place it in a .bat file (for Microsoft Windows) or a .sh file (for UNIX) and then run that file to execute the command.

      As when running SampleServer, you will be prompted for the Kerberos password for the service principal under which SampleServerImp is expected to be run. The Kerberos login module specified in the login configuration file will log the service principal into Kerberos. Once authentication is successfully completed, the SampleServerImp code will be executed on behalf of the service principal. It will listen for socket connections on the specified port.

      After you follow the "Prepare SampleClient for Execution" and "Execute SampleClient" instructions as usual and perform the user login, the client code will request a socket connection with SampleServerImp. Once SampleServerImp accepts the connection, SampleClient and SampleServerImp establish a shared context and then exchange messages as described in the previous tutorial.

      After the message exchange, SampleServerImp determines the principal name of the user executing the client code, creates a new Subject containing a Principal with that name, and calls Subject.doAsPrivileged to execute the code in ReadFileAction on behalf of the specified user. ReadFileAction reads the file named your_user_name_info.txt (where your_user_name represents the actual user name) in the data subdirectory of the current directory, and prints out its contents.

      For login troubleshooting suggestions, see Troubleshooting.

Using Credentials Delegated From the Client

The most complete type of client impersonation is possible if the client delegates its credentials to the server.

Recall that prior to context establishment with the context acceptor (the server in our previous tutorial), the context initiator (the client) sets various context options. If the initiator calls the requestCredDeleg method on the context object with a true argument, as in

context.requestCredDeleg(true);
then this requests that the initiator's credentials be delegated to the acceptor during context establishment.

Delegation of credentials from the initiator to the acceptor enables the acceptor to authenticate itself as an agent or delegate of the initiator.

First, after context establishment, the acceptor must determine whether or not credential delegation actually took place. It does so by calling the getCredDelegState method:

boolean delegated = context.getCredDelegState();

If credentials were delegated, the acceptor can obtain those credentials by calling the getDelegCr method:

GSSCredential clientCr = context.getDelegCr();

The resulting GSSCredential object can then be used to initiate subsequent GSS-API contexts as a "delegate" of the initiator. For example, the server could authenticate as the client to a backend server that cares more about who the original client was than who the intermediate server is.

Acting as the client, the server can establish a connection with the backend server, establish a joint security context, and exchange messages in basically the same manner that the client and server did.

One way it could be done is that when the server calls the createContext method of a GSSManager, it could pass createContext the delegated credentials instead of passing a null.

Alternatively, the server code could first call the com.sun.security.jgss.GSSUtil createSubject method and pass it the delegated credentials. That method returns a Subject containing those credentials as the default credentials. The server could then associate this Subject with the current AccessControlContext, as described in How Do You Associate a Subject with an Access Control Context? in the JAAS Authorization tutorial. Then, when the server code calls the GSSManager createContext method, it can pass a null (indicating the credentials for the "current" Subject should be used). In other words, the server would effectively become the client. Subsequent connections to backend servers using GSS could be made exactly as described in the previous tutorials. This approach is useful if you want the code that will use the delegated credentials to be identical to the code that uses the default local credentials.

Permission Required In Order to Delegate Credentials

In order to delegate credentials, the context initiator (SampleClient in our previous tutorial) must have a javax.security.auth.kerberos.DelegationPermission. An example using placeholders in italics for actual values is the following:

permission javax.security.auth.kerberos.DelegationPermission
  "\"service_principal@your_realm\"
     \"krbtgt/your_realm@your_realm\"";

Note that DelegationPermission has a single target in quotes that contains two items, both of which are quoted. Each inner quote is escaped by a "\". Thus the first item is

"service_principal@your_realm"
and the second is
"krbtgt/your_realm@your_realm"

This basically gives the code executing on behalf of the client the permission to forward a Kerberos ticket to the specified peer (service_principal), where the Kerberos ticket is meant to avail service from krbtgt/your_realm@your_realm.

Substitute your realm for all places your_realm appears. Also substitute the service principal name for the service principal representing the server for service_principal@your_realm. (See Kerberos User and Service Principal Names in the previous tutorial.) Suppose your realm is KRBNT-OPERATIONS.ABC.COM and the service principal is "sample/raven.abc.com@KRBNT-OPERATIONS.ABC.COM". Then the permission could appear in a policy file as

permission javax.security.auth.kerberos.DelegationPermission
  "\"sample/raven.abc.com@KRBNT-OPERATIONS.ABC.COM\"
     \"krbtgt/KRBNT-OPERATIONS.ABC.COM@KRBNT-OPERATIONS.ABC.COM\"";

Tutorials Introduction and TOC
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface org.w3c.dom.events.MouseEvent (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.events.MouseEvent

No usage of org.w3c.dom.events.MouseEvent
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Java Virtual Machine Support for Non-Java Languages

The following topics are covered:

  • Introduction
  • Static and Dynamic Typing
  • The Challenge of Compiling Dynamically Typed Languages
  • The invokedynamic Instruction
  • Resources

Introduction

The Java SE platform enables the development of applications with the following features:

  • Can be written once and run anywhere
  • Can be run securely because of the Java sandbox security model
  • Easy to package and deliver

The Java SE platform also provides robust support with respect to the following areas (and more):

  • Concurrency
  • Garbage collection
  • Reflective access to classes and objects
  • JVM Tool Interface (JVM TI): A native programming interface for use by tools. It provides both a way to inspect the state and to control the execution of applications running in the JVM.

Oracle's HotSpot JVM also offers the following tools and features:

  • DTrace: A comprehensive dynamic tracing utility that monitors the behavior of applications programs as well as the operating system itself.
  • Performance optimizations
  • PrintAssembly: A Java HotSpot option that prints assembly code for bytecoded and native methods.

The Java SE 7 platform enables non-Java languages to exploit the infrastructure and potential performance optimizations of the JVM. The key mechanism is the invokedynamic instruction, which simplifies the implementation of compilers and runtime systems for dynamically typed languages on the JVM.

Static and Dynamic Typing

A programming language is statically typed if it performs type checking at compile time. Type checking is the process of verifying that a program is type safe. A program is type safe if the arguments of all of its operations are the correct type.

Java is a statically typed language. All typed information for class and instance variables, method parameters, return values, and other variables is available when a program is compiled. The compiler for the Java programming language uses this type information to produce strongly typed bytecode, which can then be efficiently executed by the JVM at runtime.

The following example of a Hello World program demonstrates static typing. Types are shown in bold.

import java.util.Date;

public class HelloWorld {
    public static void main(String[] argv) {
        String hello = "Hello ";
        Date currDate = new Date();
        for (String a : argv) {
            System.out.println(hello + a);
            System.out.println("Today's date is: " + currDate);
        }
    }
}

A programming language is dynamically typed if it performs type checking at runtime. JavaScript and Ruby are examples of dynamically typed languages. These languages verify at runtime, rather than at compile time, that values in an application conform to expected types. These languages typically do not have any type information available at compile time. The type of an object can be determined only at runtime. Hence, in the past, it was difficult to efficiently implement them on the JVM.

The following is an example of the Hello World program written in the Ruby programming language:

#!/usr/bin/env ruby
require 'date'

hello = "Hello "
currDate = DateTime.now
ARGV.each do|a|
  puts hello + a
  puts "Date and time: " + currDate.to_s
end

Note that every name is introduced without a type declaration. Also, the main program is not located inside of a holder type (the Java class HelloWorld. The Ruby equivalent of the Java for loop is inside the dynamic type of the variable ARGV. The body of the loop is contained in a block called a closure, a common feature in dynamic languages.

Statically Typed Languages Are Not Necessarily Strongly Typed Languages

A programming language that features strong typing specifies restrictions on the types of values supplied to its operations. If a computer language implements strong typing, it prevents the execution of an operation if its arguments have the wrong type. Conversely, a language that features weak typing would implicitly convert (or cast) arguments of an operation if those arguments have wrong or incompatible types.

Statically typed programming languages can employ strong typing or weak typing. Similarly, dynamically typed languages can also apply strong typing or weak typing. For example, the Ruby programming language is dynamically typed and strongly typed. Once a variable has been initialized with a value of some type, the Ruby programming language will not implicitly convert the variable into another data type. The Ruby programming language would not allow the following:

a = "40"
b = a + 2

In this example, the Ruby programming language will not implicitly cast the number 2, which has a Fixnum type, to a string.

The Challenge of Compiling Dynamically Typed Languages

Consider the following dynamically typed method, addtwo, that adds any two numbers (which can be of any numeric type) and returns the sum:

def addtwo(a, b)
       a + b;
end

Suppose your organization is implementing a compiler and runtime system for the programming language in which the method addtwo is written. In a strongly typed language, whether typed statically or dynamically, the behavior of + (the addition operator) depends on the types of the operands. A compiler for a statically-typed language chooses which implementation of + is appropriate based on the static types of a and b. For example, a Java compiler implements + with the iadd JVM instruction if the types of a and b are int. The addition operator will be compiled to a method call because the JVM's iadd instruction requires the operand types to be statically known.

In contrast, a compiler for a dynamically-typed language must defer the choice until runtime. The statement a + b is compiled as the method call +(a, b), where + is the method name. (Note a method named + is permitted in the JVM but not in the Java programming language.) Suppose then that the runtime system for the dynamically-typed language is able to identify that a and b are variables of integer type. The runtime system would prefer to call an implementation of + that is specialized for integer types rather than arbitrary object types.

The challenge of compiling dynamically typed languages is how to implement a runtime system that can choose the most appropriate implementation of a method or function — after the program has been compiled. Treating all variables as objects of Object type would not work efficiently; the Object class does not contain a method named +.

Java SE 7 introduces the invokedynamic instruction that enables the runtime system to customize the linkage between a call site and a method implementation. In this example, the invokedynamic call site is +. An invokedynamic call site is linked to a method by means of a bootstrap method, which is a method specified by the compiler for the dynamically-typed language that is called once by the JVM to link the site. Assuming the compiler emitted an invokedynamic instruction that invokes +, and assuming that the runtime system knows about the method adder(Integer,Integer), the runtime can link the invokedynamic call site to the adder method as follows:

IntegerOps.java

class IntegerOps {

  public static Integer adder(Integer x, Integer y) {
    return x + y;
  }
}

Example.java

import java.util.*;
import java.lang.invoke.*;
import static java.lang.invoke.MethodType.*;
import static java.lang.invoke.MethodHandles.*;

class Example {

  public static CallSite mybsm(
    MethodHandles.Lookup callerClass, String dynMethodName, MethodType dynMethodType)
    throws Throwable {

    MethodHandle mh =
      callerClass.findStatic(
        Example.class,
        "IntegerOps.adder",
        MethodType.methodType(Integer.class, Integer.class, Integer.class));

    if (!dynMethodType.equals(mh.type())) {
      mh = mh.asType(dynMethodType);
    }

    return new ConstantCallSite(mh);
  }
}

In this example, the IntegerOps class belongs to the library that accompanies the dynamic language's runtime system.

The method Example.mybsm is a bootstrap method that links the invokedynamic call site to the adder method.

The object callerClass is a lookup object, which is a factory for creating method handles.

The method MethodHandles.Lookup.findStatic (called from the callerClass lookup object) creates a static method handle for the method adder.

Note: This bootstrap method links an invokedynamic call site only to the code defined in the adder method, and it assumes that the arguments given to the invokedynamic call site will be Integer objects. A bootstrap method requires additional code to properly link invokedynamic call sites to the appropriate code to execute if the parameters of the bootstrap method (in this example, callerClass, dynMethodName, and dynMethodType) vary.

The classes java.lang.invoke.MethodHandles and java.lang.invoke.MethodHandle contain various methods that create method handles based on existing method handles. This example calls the method asType if the method type of the method handle mh does not match the method type specified by the parameter dynMethodType. This enables the bootstrap method to link invokedynamic call sites to Java methods whose method types do not exactly match.

The ConstantCallSite instance returned by the bootstrap method represents a call site to be associated with a distinct invokedynamic instruction. The target for a ConstantCallSite instance is permanent and can never be changed. In this case there is only one Java method, adder, which is a candidate for executing the call site. Note that this method does not have to be a Java method. Instead, if there were several such methods being available to the runtime system, each handling different argument types, the bootstrap method mybsm could dynamically select the correct method, based on the dynMethodType argument.

The invokedynamic Instruction

The invokedynamic instruction simplifies and potentially improves implementations of compilers and runtime systems for dynamic languages on the JVM. The invokedynamic instruction does this by allowing the language implementer to define custom linkage behavior. This contrasts with other JVM instructions such as invokevirtual, in which linkage behavior specific to Java classes and interfaces is hard-wired by the JVM.

Each instance of an invokedynamic instruction is called a dynamic call site. A dynamic call site is originally in an unlinked state, which means that there is no method specified for the call site to invoke. As previously mentioned, a dynamic call site is linked to a method by means of a bootstrap method. A dynamic call site's bootstrap method is a method specified by the compiler for the dynamically-typed language that is called once by the JVM to link the site. The object returned from the bootstrap method permanently determines the call site's behavior.

The invokedynamic instruction contains a constant pool index (in the same format as for the other invoke instructions). This constant pool index references a CONSTANT_InvokeDynamic entry. This entry specifies the bootstrap method (a CONSTANT_MethodHandle entry), the name of the dynamically linked method, and the argument types and return type of the call to the dynamically linked method.

The following is an example of an invokedynamic instruction. In this example, the runtime system links the dynamic call site specified by this invokedynamic instruction (which is +, the addition operator) to the IntegerOps.adder method by using the bootstrap method Example.mybsm. The methods adder and mybsm are defined in the section The Challenge of Compiling Dynamically Typed Languages (line breaks have been added for clarity):

invokedynamic   InvokeDynamic
  REF_invokeStatic:
    Example.mybsm:
      "(Ljava/lang/invoke/MethodHandles/Lookup;
        Ljava/lang/String;
        Ljava/lang/invoke/MethodType;)
      Ljava/lang/invoke/CallSite;":
    +:
      "(Ljava/lang/Integer;
        Ljava/lang/Integer;)
      Ljava/lang/Integer;";

Note: The bytecode examples in these sections use the syntax of the ASM Java bytecode manipulation and analysis framework.

Invoking a dynamically linked method with the invokedynamic instruction involves the following steps:

  1. Defining the Bootstrap Method
  2. Specifying Constant Pool Entries
  3. Using the invokedynamic Instruction

1. Defining the Bootstrap Method

At runtime, when the JVM first encounters an invokedynamic instruction, it calls the bootstrap method. This method links the name specified by the invokedynamic instruction with the code that should be executed (the target method), which is referenced by a method handle. If the JVM executes the same invokedynamic instruction again, it does not call the bootstrap method; it automatically calls the linked method handle.

The bootstrap method's return type must be java.lang.invoke.CallSite. A CallSite object represents the linked state of an invokedynamic instruction and the method handle to which it is linked.

The bootstrap method takes three or more parameters:

  1. A MethodHandles.Lookup object, which is a factory for creating method handles in the context of the invokedynamic instruction.
  2. A String object, the method name mentioned in the dynamic call site.
  3. A MethodType object, the resolved type signature of the dynamic call site.
  4. Optionally, one or more additional static arguments to the invokedynamic instruction. These arguments, drawn from the constant pool, are intended to help language implementers safely and compactly encode additional metadata useful to the bootstrap method. In principle, the name and extra arguments are redundant since each call site could be given its own unique bootstrap method. However, such a practice is likely to produce large class files and constant pools

See the section The Challenge of Compiling Dynamically Typed Languages for an example of a bootstrap method.

2. Specifying Constant Pool Entries

As mentioned previously, the invokedynamic instruction contains a reference to an entry in the constant pool with the tag CONSTANT_InvokeDynamic. This entry contains references to other entries in the constant pool and references to attributes. This section briefly describes constant pool entries used by the invokedynamic instruction. For more information, see the java.lang.invoke package documentation and The Java Virtual Machine Specification.

Example Constant Pool

The following is an excerpt from the constant pool for the class Example, which contains the bootstrap method Example.mybsm that links the method + with the Java method adder:

    class #159; // #47
    Utf8 "adder"; // #83
    Utf8 "(Ljava/lang/Integer;Ljava/lang/Integer;)Ljava/lang/Integer;"; // #84
    Utf8 "mybsm"; // #87
    Utf8 "(Ljava/lang/invoke/MethodHandles/Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;)
      java/lang/invoke/CallSite;"; // #88
    Utf8 "Example"; // #159
    Utf8 "+"; // #166

    // ...

    NameAndType #83 #84; // #228
    Method #47 #228; // #229
    MethodHandle 6b #229; // #230
    NameAndType #87 #88; // #231
    Method #47 #231; // #232
    MethodHandle 6b #232; // #233
    NameAndType #166 #84; // #234
    Utf8 "BootstrapMethods"; // #235
    InvokeDynamic 0s #234; // #236

The constant pool entry for the invokedynamic instruction in this example contains three values:

  • CONSTANT_InvokeDynamic tag
  • Unsigned short of value 0
  • Constant pool index #234.

The value 0 refers to the first bootstrap method specifier in the array of specifiers stored in the BootstrapMethods attribute. Bootstrap method specifiers are not in the constant pool table; they are contained in this separate array of specifiers. Each bootstrap method specifier contains an index to a CONSTANT_MethodHandle constant pool entry, which is the bootstrap method itself.

The following is an excerpt from the same constant pool that shows the BootstrapMethods attribute, which contains the array of bootstrap method specifiers:

  [3] { // Attributes

    // ...

    Attr(#235, 6) { // BootstrapMethods at 0x0F63
      [1] { // bootstrap_methods
        {  //  bootstrap_method
          #233; // bootstrap_method_ref
          [0] { // bootstrap_arguments
          }  //  bootstrap_arguments
        }  //  bootstrap_method
      }
    } // end BootstrapMethods
  } // Attributes

The constant pool entry for the bootstrap method mybsm method handle contains three values:

  • CONSTANT_MethodHandle tag
  • Unsigned byte of value 6
  • Constant pool index #232.

The value 6 is the subtag REF_invokeStatic. See the next section, 3. Using the invokedynamic Instruction, for more information about this subtag.

3. Using the invokedynamic Instruction

The following bytecode uses the invokedynamic instruction to call the bootstrap method mybsm, which links the dynamic call site (+, the addition operator) to the method adder. This example uses the + method to add the numbers 40 and 2 (line breaks have been inserted for clarity):

bipush	40;
invokestatic    Method java/lang/Integer.valueOf:"(I)Ljava/lang/Integer;";
iconst_2;
invokestatic    Method java/lang/Integer.valueOf:"(I)Ljava/lang/Integer;";
invokedynamic   InvokeDynamic
  REF_invokeStatic:
    Example.mybsm:
      "(Ljava/lang/invoke/MethodHandles/Lookup;
        Ljava/lang/String;
        Ljava/lang/invoke/MethodType;)
      Ljava/lang/invoke/CallSite;":
    +:
      "(Ljava/lang/Integer;
        Ljava/lang/Integer;)
      Ljava/lang/Integer;";

The first four instructions put the integers 40 and 2 on the stack and boxes them in the java.lang.Integer wrapper type. The fifth instruction invokes a dynamic method. This instruction refers to a constant pool entry with a CONSTANT_InvokeDynamic tag:

REF_invokeStatic:
  Example.mybsm:
    "(Ljava/lang/invoke/MethodHandles/Lookup;
      Ljava/lang/String;
      Ljava/lang/invoke/MethodType;)
    Ljava/lang/invoke/CallSite;":
  +:
    "(Ljava/lang/Integer;
      Ljava/lang/Integer;)
    Ljava/lang/Integer;";

Four bytes follow the CONSTANT_InvokeDynamic tag in this entry:

  • The first two bytes form a reference to a CONSTANT_MethodHandle entry that references a bootstrap method specifier:

    REF_invokeStatic:
  Example.mybsm:
    "(Ljava/lang/invoke/MethodHandles/Lookup;
      Ljava/lang/String;
      Ljava/lang/invoke/MethodType;)
    Ljava/lang/invoke/CallSite;"

    As mentioned previously, this reference to a bootstrap method specifier is not in the constant pool table; it is contained in a separate array defined by a class file attribute named BootstrapMethods. The bootstrap method specifier contains an index to a CONSTANT_MethodHandle constant pool entry, which is the bootstrap method itself.

    Three bytes follow this CONSTANT_MethodHandle constant pool entry:

    • The first byte is the subtag REF_invokeStatic. This means that this bootstrap method will create a method handle for a static method; note that this bootstrap method is linking the dynamic call site with the static Java method adder.

    • The next two bytes form a CONSTANT_Methodref entry that represents the method for which the method handle is to be created:

      Example.mybsm:
  "(Ljava/lang/invoke/MethodHandles/Lookup;
    Ljava/lang/String;
    Ljava/lang/invoke/MethodType;)
  Ljava/lang/invoke/CallSite;"

      In this example, the fully qualified name of the bootstrap method is Example.mybsm; the argument types are MethodHandles.Lookup, String, and MethodType; and the return type is CallSite.

  • The next two bytes form a reference to a CONSTANT_NameAndType entry:

    +:
  "(Ljava/lang/Integer;
    Ljava/lang/Integer;)
  Ljava/lang/Integer;"

    This constant pool entry specifies the method name (+), argument types (two Integer instances), and return type of the dynamic call site (Integer).

In this example, the dynamic call site is presented with boxed integer values, which exactly match the type of the eventual target, the adder method. In practice, the argument and return types do not need to exactly match. For example, the invokedynamic instruction could pass either or both of its operands on the JVM stack as primitive int values. Either or both operands could also be untyped Object values. The invokedynamic instruction could also receive its result as a primitive int value, or an untyped Object value. In any case, the dynMethodType argument to mybsm will accurately describe the method type required by the invokedynamic instruction.

Independently, the adder method could also have been given primitive or untyped arguments or return values. The bootstrap method is responsible for making up any difference between the dynMethodType and the type of the adder method. As shown in the code, this is easily done with an asType call on the target method.

Resources

  • java.lang.invoke package documentation
  • The Da Vinci Machine Project
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface org.w3c.dom.events.MutationEvent (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.events.MutationEvent

No usage of org.w3c.dom.events.MutationEvent
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Using the Platform MBean Server and Platform MXBeans - Java SE Monitoring and Management Guide

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
previous Previous Contents Next next
Chapter 4

Using the Platform MBean Server and Platform MXBeans

This chapter introduces the MBean server and the MXBeans that are provided as part of the Java Platform, Standard Edition (Java SE platform), which can be used for monitoring and management purposes. Java Management Extensions (JMX) technology MBeans and MBean servers were introduced briefly in Chapter 1, Overview of Java SE Monitoring and Management. More information about the JMX technology can be found in the JMX Technology documentation for the Java SE platform.

Using the Platform MBean Server

An MBean server is a repository of MBeans that provides management applications access to MBeans. Applications do not access MBeans directly, but instead access them through the MBean server via their unique ObjectName. An MBean server implements the interface javax.management.MBeanServer.

The platform MBean server was introduced in the Java 2 Platform, Standard Edition 5.0, and is an MBean server that is built into the Java Virtual Machine (Java VM). The platform MBean server can be shared by all managed components that are running in the Java VM. You access the platform MBean server using the java.lang.management.ManagementFactory method getPlatformMBeanServer. Of course, you can also create your own MBean server using the javax.management.MBeanServerFactory class. However, there is generally no need for more than one MBean server, so using the platform MBean server is recommended.

Accessing Platform MXBeans

A platform MXBean, is an MBean for monitoring and managing the Java VM. Each MXBean encapsulates a part of the VM functionality. A full list of the MXBeans that are provided with the platform is provided in Table 1-1 in Chapter 1, Overview of Java SE Monitoring and Management.

A management application can access platform MXBeans in three different ways.

  • Direct access, via the ManagementFactory class.

  • Direct access, via an MXBean proxy.

  • Indirect access, via the MBeanServerConnection class.

These three ways of accessing the platform MXBeans are described in the next three sections.

Accessing Platform MXBeans via the ManagementFactory Class

An application can make direct calls to the methods of a platform MXBean that is running in the same Java VM as itself. To make direct calls, you can use the static methods of the ManagementFactory class. ManagementFactory has accessor methods for each of the different platform MXBeans, such as, getClassLoadingMXBean(), getGarbageCollectorMXBeans(), getRuntimeMXBean(), and so on. In cases where there are more than one platform MXBean, the method returns a list of the platform MXBeans found.

For example, Example 4-1 uses the static method of ManagementFactory to get the platform MXBean RuntimeMXBean, and then gets the vendor name from the platform MXBean.

Example 4-1 Accessing a Platform MXBean via the ManagementFactory Class
RuntimeMXBean mxbean = ManagementFactory.getRuntimeMXBean();
String vendor = mxbean.getVmVendor();

Accessing Platform MXBeans via an MXBean Proxy

An application can also call platform MXBean methods via an MXBean proxy. To do so, you must construct an MXBean proxy instance that forwards the method calls to a given MBean server by calling the static method ManagementFactory.newPlatformMXBeanProxy(). An application typically constructs a proxy to obtain remote access to a platform MXBean of another Java VM.

For example, Example 4-2 performs exactly the same operation as Example 4-1, but this time uses an MXBean proxy.

Example 4-2 Accessing a Platform MXBean via an MXBean Proxy
MBeanServerConnection mbs;
...
// Get a MBean proxy for RuntimeMXBean interface
RuntimeMXBean proxy =
    ManagementFactory.newPlatformMXBeanProxy(mbs,
                                             ManagementFactory.RUNTIME_MXBEAN_NAME,
                                             RuntimeMXBean.class);
// Get standard attribute "VmVendor"
String vendor = proxy.getVmVendor();

Accessing Platform MXBeans via the MBeanServerConnection Class

An application can indirectly call platform MXBean methods through an MBeanServerConnection that connects to the platform MBean server of another running Java VM. You use the MBeanServerConnection class's getAttribute() method to get an attribute of a platform MXBean, providing the MBean's ObjectName and the attribute name as parameters.

For example, Example 4-3 performs the same job as Example 4-1 and Example 4-2, but uses an indirect call through MBeanServerConnection.

Example 4-3 Accessing a Platform MXBean via the MBeanServerConnection Class
MBeanServerConnection mbs;
...
try {
  ObjectName oname = new ObjectName(ManagementFactory.RUNTIME_MXBEAN_NAME);
  // Get standard attribute "VmVendor"
  String vendor = (String) mbs.getAttribute(oname, "VmVendor");
} catch (....) {
  // Catch the exceptions thrown by ObjectName constructor
  // and MBeanServer.getAttribute method
  ...
}

Using Sun Microsystems' Platform Extension

Java VMs can extend the management interface by defining interfaces for platform-specific measurements and management operations. The static factory methods in the ManagementFactory class will return the MBeans with the platform extension.

The com.sun.management package contains Sun Microsystems' platform extensions. The following sections provide examples of how to access a platform-specific attribute from Sun Microsystems' implementation of the OperatingSystemMXBean.

Accessing MXBean Attributes Directly

Example 4-4 illustrates direct access to one of Sun Microsystems' MXBean interfaces.

Example 4-4 Accessing an MXBean Attribute Directly
com.sun.management.OperatingSystemMXBean mxbean =
  (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();

// Get the number of processors
int numProcessors = mxbean.getAvailableProcessors();

// Get the Sun-specific attribute Process CPU time
long cpuTime = mxbean.getProcessCpuTime();

Accessing MXBean Attributes via MBeanServerConnection

Example 4-5 illustrates access to one of Sun Microsystems' MXBean interfaces via the MBeanServerConnection class.

Example 4-5 Accessing an MXBean Attribute via MBeanServerConnection
MBeanServerConnection mbs;

// Connect to a running Java VM (or itself) and get MBeanServerConnection
// that has the MXBeans registered in it
...

try {
    // Assuming the OperatingSystem MXBean has been registered in mbs
    ObjectName oname = new ObjectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME);

    // Get standard attribute "Name"
    String vendor = (String) mbs.getAttribute(oname, "Name");

    // Check if this MXBean contains Sun Microsystems' extension
    if (mbs.isInstanceOf(oname, "com.sun.management.OperatingSystemMXBean")) {
        // Get platform-specific attribute "ProcessCpuTime"
        long cpuTime = (Long) mbs.getAttribute(oname, "ProcessCpuTime");
    }
} catch (....) {
    // Catch the exceptions thrown by ObjectName constructor
    // and MBeanServer methods
    ...
}

Monitoring Thread Contention and CPU Time

The ThreadMXBean platform MXBean provides support for monitoring thread contention and thread Central Processing Unit (CPU) time.

The Sun HotSpot VM supports thread contention monitoring. You use the ThreadMXBean.isThreadContentionMonitoringSupported() method to determine if a Java VM supports thread contention monitoring. Thread contention monitoring is disabled by default. Use the setThreadContentionMonitoringEnabled() method to enable it.

The Sun HotSpot VM supports the measurement of thread CPU time on most platforms. The CPU time provided by this interface has nanosecond precision but not necessarily nanosecond accuracy.

You use the isThreadCpuTimeSupported() method to determine if a Java VM supports the measurement of the CPU time for any thread. You use isCurrentThreadCpuTimeSupported() to determine if a Java VM supports the measurement of the CPU time for the current thread. A Java VM that supports CPU time measurement for any thread will also support that for the current thread.

A Java VM can disable thread CPU time measurement. You use the isThreadCpuTimeEnabled() method to determine if thread CPU time measurement is enabled . You use the setThreadCpuTimeEnabled() method to enable or disable the measurement of thread CPU time.

Managing the Operating System

The OperatingSystem platform MXBean allows you to access certain operating system resource information, such as the following.

  • Process CPU time.

  • Amount of total and free physical memory.

  • Amount of committed virtual memory (that is, the amount of virtual memory guaranteed to be available to the running process).

  • Amount of total and free swap space.

  • Number of open file descriptors (only for UNIX platforms).

When the Operating System MXBean in the MBeans tab is selected in JConsole, you see all the attributes and operations including the platform extension. You can monitor the changes of a numerical attribute over time by double-clicking the value field of the attribute.

Logging Management

The Java SE platform provides a special MXBean for logging purposes, the LoggingMXBean interface.

The LoggingMXBean enables you to perform the following tasks.

  • Get the name of the log level associated with the specified logger.

  • Get the list of currently registered loggers.

  • Get the name of the parent for the specified logger.

  • Set the specified logger to the specified new level.

The unique ObjectName of the LoggingMXBean is java.util.logging:type=Logging. This object name is stored in LogManager.LOGGING_MXBEAN_NAME.

There is a single global instance of the LoggingMXBean, which you can get by calling LogManager.getLoggingMXBean().

The Logging MXBean defines a LoggerNames attribute describing the list of logger names. To find the list of loggers in your application, you can select the Logging MXBean under the java.util.logging domain in the MBeans tab, and double-click on the value field of the LoggerNames attribute. The Logging MXBean also supports two operations.

  • getLoggerLevel: Returns the log level of a given logger.

  • setLoggerLevel: Sets the log level of a given logger to a new level.

These operations take a logger name as the first parameter. To change the level of a logger, enter the logger name in the first parameter and the name of the level it should be set to in the second parameter of the setLoggerLevel operation.

Detecting Low Memory

Memory use is an important attribute of the memory system. It can be indicative of the following problems.

  • Excessive memory consumption by an application.

  • An excessive workload imposed on the automatic memory management system.

  • Potential memory leakages.

There are two kinds of memory thresholds you can use to detect low memory conditions: a usage threshold and a collection usage threshold. You can detect low memory conditions using either of these thresholds with polling or threshold notification. All these concepts are described in the next sections.

Memory Thresholds

A memory pool can have two kinds of memory thresholds: a usage threshold and a collection usage threshold. Either one of these thresholds may not be supported by a particular memory pool. The values for the usage threshold and collection usage threshold can both be set using the MBeans tab in JConsole.

Usage Threshold

The usage threshold is a manageable attribute of some memory pools. It enables you to monitor memory use with a low overhead. Setting the threshold to a positive value enables a memory pool to perform usage threshold checking. Setting the usage threshold to zero disables usage threshold checking. The default value is supplied by the Java VM.

A Java VM performs usage threshold checking on a memory pool at the most appropriate time, typically during garbage collection. Each memory pool increments a usage threshold count whenever the usage crosses the threshold.

You use the isUsageThresholdSupported() method to determine whether a memory pool supports a usage threshold, since a usage threshold is not appropriate for some memory pools. For example, in a generational garbage collector (such as the one in the HotSpot VM; see Garbage Collection in Chapter 3, Using JConsole), most of the objects are allocated in the young generation, from the Eden memory pool. The Eden pool is designed to be filled up. Garbage collecting the Eden memory pool will free most of its memory space since it is expected to contain mostly short-lived objects that are unreachable at garbage collection time. So, it is not appropriate for the Eden memory pool to support a usage threshold.

Collection Usage Threshold

The collection usage threshold is a manageable attribute of some garbage-collected memory pools. After a Java VM has performed garbage collection on a memory pool, some memory in the pool will still be in use. The collection usage threshold allows you to set a value for this memory. You use the isCollectionUsageThresholdSupported() method of MemoryPoolMXBean to determine if the pool supports a collection usage threshold.

A Java VM may check the collection usage threshold on a memory pool when it performs garbage collection. Set the collection usage threshold to a positive value to enable checking. Set the collection usage threshold to zero (the default) to disable checking.

The usage threshold and collection usage threshold can be set in the MBeans tab of JConsole.

Memory MXBean

The various memory thresholds can be managed via the platform MemoryMXBean. The MemoryMXBean defines the following four attributes.

  • HeapMemoryUsage: A read-only attribute describing the current heap memory usage.

  • NonHeapMemoryUsage: A read-only attribute describing non-heap memory usage.

  • ObjectPendingFinalizationCount: A read-only attribute describing the number of objects pending for finalization.

  • Verbose: A boolean attribute describing the Garbage Collection (GC) verbose tracing setting. This can be set dynamically. The GC verbose traces will be displayed at the location specified when you start the Java VM. The default location for GC verbose output of the Hotspot VM is stdout.

The Memory MXBean supports one operation, gc, for explicit garbage collection requests.

Details of the Memory MXBean interface are defined in the java.lang.management.MemoryMXBean specification.

Memory Pool MXBean

The MemoryPoolMXBean platform MXBean defines a set of operations to manage memory thresholds.

  • getUsageThreshold()

  • setUsageThreshold(long threshold)

  • isUsageThresholdExceeded()

  • isUsageThresholdSupported()

  • getCollectionUsageThreshold()

  • setCollectionUsageThreshold(long threshold)

  • isCollectionUsageThresholdSupported()

  • isCollectionUsageThresholdExceeded()

Each memory pool may have two kinds of memory thresholds for low memory detection support: a usage threshold and a collection usage threshold. Either one of these thresholds might not be supported by a particular memory pool. For more information, see the API reference documentation for the MemoryPoolMXBean class.

Polling

An application can continuously monitor its memory usage by calling either the getUsage() method for all memory pools or the isUsageThresholdExceeded() method for memory pools that support a usage threshold.

Example 4-6 has a thread dedicated to task distribution and processing. At every interval, it determines whether it should receive and process new tasks based on its memory usage. If the memory usage exceeds its usage threshold, it redistributes outstanding tasks to other VMs and stops receiving new tasks until the memory usage returns below the threshold.

Example 4-6 Using Polling
pool.setUsageThreshold(myThreshold);
....
boolean lowMemory = false;
while (true) {
  if (pool.isUsageThresholdExceeded()) {
    lowMemory = true;
    redistributeTasks();  // redistribute tasks to other VMs
    stopReceivingTasks();  // stop receiving new tasks
  } else {
    if (lowMemory) { // resume receiving tasks
      lowMemory = false;
      resumeReceivingTasks();
    }
    // processing outstanding task
    ...
  }
  // sleep for sometime
  try {
    Thread.sleep(sometime);
  } catch (InterruptedException e) {
    ...
  }
}

Example 4-6 does not differentiate the case in which the memory usage has temporarily dropped below the usage threshold from the case in which the memory usage remains above the threshold between two iterations. You can use the usage threshold count returned by getUsageThresholdCount() to determine if the memory usage has returned below the threshold between two polls.

To test the collection usage threshold instead, you use the isCollectionUsageThresholdSupported(), isCollectionThresholdExceeded() and getCollectionUsageThreshold() methods in the same way as above.

Threshold Notifications

When the MemoryMXBean detects that a memory pool has reached or exceeded its usage threshold, it emits a usage threshold exceeded notification. The MemoryMXBean will not issue another usage threshold exceeded notification until the usage has fallen below the threshold and then exceeded it again. Similarly, when the memory usage after garbage collection exceeds the collection usage threshold, the MemoryMXBean emits a collection usage threshold exceeded notification.

Example 4-7 implements the same logic as Example 4-6, but uses usage threshold notification to detect low memory conditions. Upon receiving a notification, the listener notifies another thread to perform actions such as redistributing outstanding tasks, refusing to accept new tasks, or allowing new tasks to be accepted again.

In general, you should design the handleNotification method to do a minimal amount of work, to avoid causing delay in delivering subsequent notifications. You should perform time-consuming actions in a separate thread. Since multiple threads can concurrently invoke the notification listener, the listener should synchronize the tasks it performs properly.

Example 4-7 Using Threshold Notifications
class MyListener implements javax.management.NotificationListener {
  public void handleNotification(Notification notification, Object handback)  {
    String notifType = notification.getType();
    if (notifType.equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {
      // potential low memory, redistribute tasks to other VMs & stop receiving new tasks.
      lowMemory = true;
      notifyAnotherThread(lowMemory);
    }
  }
}

// Register MyListener with MemoryMXBean
MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
NotificationEmitter emitter = (NotificationEmitter) mbean;
MyListener listener = new MyListener();
emitter.addNotificationListener(listener, null, null);

Assuming this memory pool supports a usage threshold, you can set the threshold to some value (representing a number of bytes), above which the application will not accept new tasks.

pool.setUsageThreshold(myThreshold);

After this point, usage threshold detection is enabled and MyListener will handle notification.
previous Previous Contents Next next
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface org.w3c.dom.NamedNodeMap (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.NamedNodeMap

  • Packages that use NamedNodeMap
    Package Description
    org.w3c.dom
    Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.

    • Uses of NamedNodeMap in org.w3c.dom

      Methods in org.w3c.dom that return NamedNodeMap
      Modifier and Type Method and Description
      NamedNodeMap Node.getAttributes()
      A NamedNodeMap containing the attributes of this node (if it is an Element) or null otherwise.
      NamedNodeMap DocumentType.getEntities()
      A NamedNodeMap containing the general entities, both external and internal, declared in the DTD.
      NamedNodeMap DocumentType.getNotations()
      A NamedNodeMap containing the notations declared in the DTD.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.NameList (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.NameList

No usage of org.w3c.dom.NameList
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Native-to-ASCII Converter

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

native2ascii - Native-to-ASCII Converter

Converts a file with characters in any supported character encoding to one with ASCII and/or Unicode escapes, or visa versa.

SYNOPSIS

native2ascii [options] [inputfile [outputfile]]

DESCRIPTION

native2ascii converts files that are encoded to any character encoding that is supported by the Java runtime environment to files encoded in ASCII, using Unicode escapes ("\uxxxx" notation) for all characters that are not part of the ASCII character set. This process is required for properties files containing characters not in ISO-8859-1 character sets. The tool can also perform the reverse conversion.

If outputfile is omitted, standard output is used for output. If, in addition, inputfile is omitted, standard input is used for input.

OPTIONS

-reverse
Perform the reverse operation: Convert a file encoded in ISO-8859-1 with Unicode escapes to a file in any character encoding supported by the Java runtime environment.

-encoding encoding_name
Specifies the name of the character encoding to be used by the conversion procedure. If this option is not present, the default character encoding (as determined by the java.nio.charset.Charset.defaultCharset method) is used. The encoding_name string must be the name of a character encoding that is supported by the Java runtime environment - see the Supported Encodings document.

-J option
Pass option to the Java virtual machine, where option is one of the options described on the reference page for the java application launcher. For example, -J-Xms48m sets the startup memory to 48 megabytes.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.jdi.NativeMethodException (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.NativeMethodException

No usage of com.sun.jdi.NativeMethodException
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Accessibility - New Features

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Accessibility
New Features in the Java™ 2 Platform v1.4

The features described here were introduced in the Java 2 Platform, v1.4.0. These features are also part of subsequent releases of the Java 2 Platform.

Contents

AccessibleExtendedComponent.getAccessibleKeyBinding
AccessibleRole New Constants
Accessibility Support for HTML Object Tags
Support for Tracking HTMLEditorKit Keyboard Link Traversal
Assistive Technologies Property
Screen Reader Property
API Enhancements
AccessibleEditableText
AccessibleExtendedComponent
AccessibleExtendedTable
AccessibleKeyBinding
Mnemonic Tab Navigation
List Navigation by First Letter
Accessibility Support for HTML Components
Screen Magnifier Property

AccessibleExtendedComponent.getAccessibleKeyBinding

Interface AccessibleExtendedComponent has a new method, getAccessibleKeyBinding, to return key bindings associated with an object.

AccessibleRole New Constants

Class AccessibleRole contains the following new constants:

  • DATE_EDITOR
  • FONT_CHOOSER
  • GROUP_BOX
  • SPIN_BOX
  • STATUS_BAR

Accessibility Support for HTML Object Tags

This release adds accessibility support for HTML object tags. CTRL-t and SHIFT-CTRL-t navigate to the next and previous component, respectively, associated with an object tag in an HTML document. CTRL-SPACE activates the default action associated with the component.

Support for Tracking HTMLEditorKit Keyboard Link Traversal

Assistive technologies needed a way to track HTMLEditorKit keyboard link traversal. The constant AccessibleContext.ACCESSIBLE_HYPERTEXT_OFFSET was added to support this feature.

Assistive Technologies Property

The javax.accessibility.assistive_technologies property specifies the assistive technologies to load into the JVM.

Screen Reader Property

The javax.accessibility.screen_reader_present property, when set to true, lets the Java platform libraries know that a screen reader is present on the system. Application developers can check this property. If an application is self-voicing and a screen reader is present, developers can turn off the self-voicing.

API Enhancements

The following new classes and interfaces have been added to the JavaTM Accessibility API:

  • javax.accessibility.AccessibleEditableText
  • javax.accessibility.AccessibleExtendedComponent
  • javax.accessibility.AccessibleExtendedTable
  • javax.accessibility.AccessibleKeyBinding
In addition, javax.accessibility.AccessibleContext was updated to reflect the new classes and interfaces.

AccessibleEditableText

Interface AccessibleEditableText provides support for text editing by assistive technologies.

AccessibleExtendedComponent

Interface AccessibleExtendedComponent provides the standard mechanism for an assistive technology to determine the extended graphical representation of an object.

AccessibleExtendedTable

Interface AccessibleExtendedTable provides extended information about a user-interface component that presents data in a two-dimensional table format.

AccessibleKeyBinding

Interface AccessibleKeyBinding provides the standard mechanism for an assistive technology to determine the key bindings which exist for an object.

Mnemonic Tab Navigation

This new feature provides support for easier tab navigation using mnemonics on a JTabbedPane.

List Navigation by First Letter

This new feature provides support for list navigation using the first letter of list items.

Accessibility Support for HTML Components

This release provides accessibility support for HTML components in Swing.

Screen Magnifier Property

The javax.accessibility.screen_magnifier_present property, when set to true, lets the Java platform libraries know that a screen magnifier is present on the system. Application developers can check this property, and if a screen magnifier is present, developers should make sure their applications are compatible with screen magnification.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Accessibility - New Features

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Accessibility

New Features in Java™ 2 Platform Standard Edition 5

The features described here were introduced in Java 2 Platform Standard Edition 5. These features are also part of subsequent releases of the Java platform. Many of these additions were made to maintain compatibility between the Java Accessibility API and the GNOME Accessibility Framework, described at http://projects.gnome.org/accessibility/

Contents

AccessibleAction New Constant
AccessibleContext New Constants
AccessibleRelation New Constants
AccessibleRole New Constants
AccessibleState New Constants
AccessibleText New Constants
API Enhancements
AccessibleExtendedText
AccessibleStreamable
Accessibility Support for JSpinner and ProgressMonitor

AccessibleAction New Constant

Class AccessibleAction contains the following new constant:

  • TOGGLE_EXPAND

AccessibleContext New Constants

Class AccessibleContext contains the following new constants:

  • ACCESSIBLE_COMPONENT_BOUNDS_CHANGE
  • ACCESSIBLE_INVALIDATE_CHILDREN
  • ACCESSIBLE_TEXT_ATTRIBUTE_CHANGED

AccessibleRelation New Constants

Class AccessibleRelation contains the following new constants:

  • CHILD_NODE_OF
  • CHILD_NODE_OF_PROPERTY
  • EMBEDS
  • EMBEDS_PROPERTY
  • EMBEDDED_BY
  • EMBEDDED_BY_PROPERTY
  • FLOWS_FROM
  • FLOWS_FROM_PROPERTY
  • FLOWS_TO
  • FLOWS_TO_PROPERTY
  • PARENT_WINDOW_OF
  • PARENT_WINDOW_OF_PROPERTY
  • SUBWINDOW_OF
  • SUBWINDOW_OF_PROPERTY

AccessibleRole New Constants

Class AccessibleRole contains the following new constants:

  • EDITBAR
  • FOOTER
  • HEADER
  • PARAGRAPH
  • PROGRESS_MONITOR
  • RULER

AccessibleState New Constants

Class AccessibleState contains the following new constants:

  • INDETERMINATE
  • MANAGES_DESCENDANTS
  • TRANSIENT
  • TRUNCATED

AccessibleText New Constants

Class AccessibleText contains the following new constants:

  • LINE
  • ACCESSIBLE_CHANGED_TEXT
  • ATTRIBUTE_RUN

API Enhancements

The following new classes and interfaces have been added to the JavaTM Accessibility API:

  • javax.accessibility.AccessibleExtendedText
  • javax.accessibility.AccessibleStreamable

AccessibleExtendedText

Interface AccessibleExtendedText provides support for braille and screen reader review mode.

AccessibleStreamable

Interface AccessibleStreamable provides a stream interface to raw data based on mime type.

Accessibility Support for JSpinner and ProgressMonitor

This release provides accessibility support for spinners and progress monitors in Swing.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


New Java Image I/O Features in J2SE 5.0

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

New Java™ Image I/O Features in
J2SE™ 5.0

Image I/O Support for BMP and WBMP Formats

The bug reports that correspond to this change are: 4339462 and 4339384

This change adds readers and writers for BMP and WBMP formats to the Image I/O system. As of J2SE 5.0, all implementations of javax.imageio provide support for reading and writing JPEG, PNG, BMP, and WBMP images, and for reading GIF images.

For more information, see the API documentation for the javax.imageio.plugins.bmp package and javax.imageio.plugins.bmp.BMPImageWriteParam class. Further details are in the metadata descriptions of the BMP and WBMP formats.

Improved Performance

The bug reports that correspond to this change are: 4827358, 4867874, and 4868479

These changes improve the Image I/O system's performance and memory usage when reading and writing JPEG images. The changes do not affect the Image I/O API.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.source.tree.NewArrayTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.NewArrayTree

  • Packages that use NewArrayTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of NewArrayTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type NewArrayTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitNewArray(NewArrayTree node, P p)

    • Uses of NewArrayTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type NewArrayTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitNewArray(NewArrayTree node, P p)
      R | SimpleTreeVisitor.visitNewArray(NewArrayTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.NewClassTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.NewClassTree

  • Packages that use NewClassTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of NewClassTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type NewClassTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitNewClass(NewClassTree node, P p)

    • Uses of NewClassTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type NewClassTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitNewClass(NewClassTree node, P p)
      R | SimpleTreeVisitor.visitNewClass(NewClassTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.Node (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.Node

  • Packages that use Node
    Package Description
    org.w3c.dom
    Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.
    org.w3c.dom.events
    org.w3c.dom.html
    org.w3c.dom.ls
    org.w3c.dom.ranges
    Document Object Model Level 2 Traversal and Range is a platform and language-neutral interfaces that allow programs and scripts to dynamically traverse and identify a range of content in a document.
    org.w3c.dom.stylesheets
    org.w3c.dom.traversal

    • Uses of Node in org.w3c.dom

      Subinterfaces of Node in org.w3c.dom
      Modifier and Type Interface and Description
      interface  Attr
      The Attr interface represents an attribute in an Element object.
      interface  CDATASection
      CDATA sections are used to escape blocks of text containing characters that would otherwise be regarded as markup.
      interface  CharacterData
      The CharacterData interface extends Node with a set of attributes and methods for accessing character data in the DOM.
      interface  Comment
      This interface inherits from CharacterData and represents the content of a comment, i.e., all the characters between the starting ' <!--' and ending '-->'.
      interface  Document
      The Document interface represents the entire HTML or XML document.
      interface  DocumentFragment
      DocumentFragment is a "lightweight" or "minimal" Document object.
      interface  DocumentType
      Each Document has a doctype attribute whose value is either null or a DocumentType object.
      interface  Element
      The Element interface represents an element in an HTML or XML document.
      interface  Entity
      This interface represents a known entity, either parsed or unparsed, in an XML document.
      interface  EntityReference
      EntityReference nodes may be used to represent an entity reference in the tree.
      interface  Notation
      This interface represents a notation declared in the DTD.
      interface  ProcessingInstruction
      The ProcessingInstruction interface represents a "processing instruction", used in XML as a way to keep processor-specific information in the text of the document.
      interface  Text
      The Text interface inherits from CharacterData and represents the textual content (termed character data in XML) of an Element or Attr.
      Methods in org.w3c.dom that return Node
      Modifier and Type Method and Description
      Node Document.adoptNode(Node source)
      Attempts to adopt a node from another document to this document.
      Node Node.appendChild(Node newChild)
      Adds the node newChild to the end of the list of children of this node.
      Node Node.cloneNode(boolean deep)
      Returns a duplicate of this node, i.e., serves as a generic copy constructor for nodes.
      Node Node.getFirstChild()
      The first child of this node.
      Node Node.getLastChild()
      The last child of this node.
      Node NamedNodeMap.getNamedItem(String name)
      Retrieves a node specified by name.
      Node NamedNodeMap.getNamedItemNS(String namespaceURI, String localName)
      Retrieves a node specified by local name and namespace URI.
      Node Node.getNextSibling()
      The node immediately following this node.
      Node Node.getParentNode()
      The parent of this node.
      Node Node.getPreviousSibling()
      The node immediately preceding this node.
      Node DOMLocator.getRelatedNode()
      The node this locator is pointing to, or null if no node is available.
      Node Document.importNode(Node importedNode, boolean deep)
      Imports a node from another document to this document, without altering or removing the source node from the original document; this method creates a new copy of the source node.
      Node Node.insertBefore(Node newChild, Node refChild)
      Inserts the node newChild before the existing child node refChild.
      Node NodeList.item(int index)
      Returns the indexth item in the collection.
      Node NamedNodeMap.item(int index)
      Returns the indexth item in the map.
      Node Node.removeChild(Node oldChild)
      Removes the child node indicated by oldChild from the list of children, and returns it.
      Node NamedNodeMap.removeNamedItem(String name)
      Removes a node specified by name.
      Node NamedNodeMap.removeNamedItemNS(String namespaceURI, String localName)
      Removes a node specified by local name and namespace URI.
      Node Document.renameNode(Node n, String namespaceURI, String qualifiedName)
      Rename an existing node of type ELEMENT_NODE or ATTRIBUTE_NODE.
      Node Node.replaceChild(Node newChild, Node oldChild)
      Replaces the child node oldChild with newChild in the list of children, and returns the oldChild node.
      Node NamedNodeMap.setNamedItem(Node arg)
      Adds a node using its nodeName attribute.
      Node NamedNodeMap.setNamedItemNS(Node arg)
      Adds a node using its namespaceURI and localName.
      Methods in org.w3c.dom with parameters of type Node
      Modifier and Type Method and Description
      Node Document.adoptNode(Node source)
      Attempts to adopt a node from another document to this document.
      Node Node.appendChild(Node newChild)
      Adds the node newChild to the end of the list of children of this node.
      short Node.compareDocumentPosition(Node other)
      Compares the reference node, i.e.
      void UserDataHandler.handle(short operation, String key, Object data, Node src, Node dst)
      This method is called whenever the node for which this handler is registered is imported or cloned.
      Node Document.importNode(Node importedNode, boolean deep)
      Imports a node from another document to this document, without altering or removing the source node from the original document; this method creates a new copy of the source node.
      Node Node.insertBefore(Node newChild, Node refChild)
      Inserts the node newChild before the existing child node refChild.
      boolean Node.isEqualNode(Node arg)
      Tests whether two nodes are equal.
      boolean Node.isSameNode(Node other)
      Returns whether this node is the same node as the given one.
      Node Node.removeChild(Node oldChild)
      Removes the child node indicated by oldChild from the list of children, and returns it.
      Node Document.renameNode(Node n, String namespaceURI, String qualifiedName)
      Rename an existing node of type ELEMENT_NODE or ATTRIBUTE_NODE.
      Node Node.replaceChild(Node newChild, Node oldChild)
      Replaces the child node oldChild with newChild in the list of children, and returns the oldChild node.
      Node NamedNodeMap.setNamedItem(Node arg)
      Adds a node using its nodeName attribute.
      Node NamedNodeMap.setNamedItemNS(Node arg)
      Adds a node using its namespaceURI and localName.

    • Uses of Node in org.w3c.dom.events

      Methods in org.w3c.dom.events that return Node
      Modifier and Type Method and Description
      Node MutationEvent.getRelatedNode()
      relatedNode is used to identify a secondary node related to a mutation event.
      Methods in org.w3c.dom.events with parameters of type Node
      Modifier and Type Method and Description
      void MutationEvent.initMutationEvent(String typeArg, boolean canBubbleArg, boolean cancelableArg, Node relatedNodeArg, String prevValueArg, String newValueArg, String attrNameArg, short attrChangeArg)
      The initMutationEvent method is used to initialize the value of a MutationEvent created through the DocumentEvent interface.

    • Uses of Node in org.w3c.dom.html

      Subinterfaces of Node in org.w3c.dom.html
      Modifier and Type Interface and Description
      interface  HTMLAnchorElement
      The anchor element.
      interface  HTMLAppletElement
      An embedded Java applet.
      interface  HTMLAreaElement
      Client-side image map area definition.
      interface  HTMLBaseElement
      Document base URI.
      interface  HTMLBaseFontElement
      Base font.
      interface  HTMLBodyElement
      The HTML document body.
      interface  HTMLBRElement
      Force a line break.
      interface  HTMLButtonElement
      Push button.
      interface  HTMLDirectoryElement
      Directory list.
      interface  HTMLDivElement
      Generic block container.
      interface  HTMLDListElement
      Definition list.
      interface  HTMLDocument
      An HTMLDocument is the root of the HTML hierarchy and holds the entire content.
      interface  HTMLElement
      All HTML element interfaces derive from this class.
      interface  HTMLFieldSetElement
      Organizes form controls into logical groups.
      interface  HTMLFontElement
      Local change to font.
      interface  HTMLFormElement
      The FORM element encompasses behavior similar to a collection and an element.
      interface  HTMLFrameElement
      Create a frame.
      interface  HTMLFrameSetElement
      Create a grid of frames.
      interface  HTMLHeadElement
      Document head information.
      interface  HTMLHeadingElement
      For the H1 to H6 elements.
      interface  HTMLHRElement
      Create a horizontal rule.
      interface  HTMLHtmlElement
      Root of an HTML document.
      interface  HTMLIFrameElement
      Inline subwindows.
      interface  HTMLImageElement
      Embedded image.
      interface  HTMLInputElement
      Form control.
      interface  HTMLIsIndexElement
      This element is used for single-line text input.
      interface  HTMLLabelElement
      Form field label text.
      interface  HTMLLegendElement
      Provides a caption for a FIELDSET grouping.
      interface  HTMLLIElement
      List item.
      interface  HTMLLinkElement
      The LINK element specifies a link to an external resource, and defines this document's relationship to that resource (or vice versa).
      interface  HTMLMapElement
      Client-side image map.
      interface  HTMLMenuElement
      Menu list.
      interface  HTMLMetaElement
      This contains generic meta-information about the document.
      interface  HTMLModElement
      Notice of modification to part of a document.
      interface  HTMLObjectElement
      Generic embedded object.
      interface  HTMLOListElement
      Ordered list.
      interface  HTMLOptGroupElement
      Group options together in logical subdivisions.
      interface  HTMLOptionElement
      A selectable choice.
      interface  HTMLParagraphElement
      Paragraphs.
      interface  HTMLParamElement
      Parameters fed to the OBJECT element.
      interface  HTMLPreElement
      Preformatted text.
      interface  HTMLQuoteElement
      For the Q and BLOCKQUOTE elements.
      interface  HTMLScriptElement
      Script statements.
      interface  HTMLSelectElement
      The select element allows the selection of an option.
      interface  HTMLStyleElement
      Style information.
      interface  HTMLTableCaptionElement
      Table caption See the CAPTION element definition in HTML 4.0.
      interface  HTMLTableCellElement
      The object used to represent the TH and TD elements.
      interface  HTMLTableColElement
      Regroups the COL and COLGROUP elements.
      interface  HTMLTableElement
      The create* and delete* methods on the table allow authors to construct and modify tables.
      interface  HTMLTableRowElement
      A row in a table.
      interface  HTMLTableSectionElement
      The THEAD , TFOOT , and TBODY elements.
      interface  HTMLTextAreaElement
      Multi-line text field.
      interface  HTMLTitleElement
      The document title.
      interface  HTMLUListElement
      Unordered list.
      Methods in org.w3c.dom.html that return Node
      Modifier and Type Method and Description
      Node HTMLCollection.item(int index)
      This method retrieves a node specified by ordinal index.
      Node HTMLCollection.namedItem(String name)
      This method retrieves a Node using a name.

    • Uses of Node in org.w3c.dom.ls

      Methods in org.w3c.dom.ls that return Node
      Modifier and Type Method and Description
      Node LSParser.parseWithContext(LSInput input, Node contextArg, short action)
      Parse an XML fragment from a resource identified by a LSInput and insert the content into an existing document at the position specified with the context and action arguments.
      Methods in org.w3c.dom.ls with parameters of type Node
      Modifier and Type Method and Description
      short LSParserFilter.acceptNode(Node nodeArg)
      This method will be called by the parser at the completion of the parsing of each node.
      Node LSParser.parseWithContext(LSInput input, Node contextArg, short action)
      Parse an XML fragment from a resource identified by a LSInput and insert the content into an existing document at the position specified with the context and action arguments.
      boolean LSSerializer.write(Node nodeArg, LSOutput destination)
      Serialize the specified node as described above in the general description of the LSSerializer interface.
      String LSSerializer.writeToString(Node nodeArg)
      Serialize the specified node as described above in the general description of the LSSerializer interface.
      boolean LSSerializer.writeToURI(Node nodeArg, String uri)
      A convenience method that acts as if LSSerializer.write was called with a LSOutput with no encoding specified and LSOutput.systemId set to the uri argument.

    • Uses of Node in org.w3c.dom.ranges

      Methods in org.w3c.dom.ranges that return Node
      Modifier and Type Method and Description
      Node Range.getCommonAncestorContainer()
      The deepest common ancestor container of the Range's two boundary-points.
      Node Range.getEndContainer()
      Node within which the Range ends
      Node Range.getStartContainer()
      Node within which the Range begins
      Methods in org.w3c.dom.ranges with parameters of type Node
      Modifier and Type Method and Description
      void Range.insertNode(Node newNode)
      Inserts a node into the Document or DocumentFragment at the start of the Range.
      void Range.selectNode(Node refNode)
      Select a node and its contents
      void Range.selectNodeContents(Node refNode)
      Select the contents within a node
      void Range.setEnd(Node refNode, int offset)
      Sets the attributes describing the end of a Range.
      void Range.setEndAfter(Node refNode)
      Sets the end of a Range to be after a node
      void Range.setEndBefore(Node refNode)
      Sets the end position to be before a node.
      void Range.setStart(Node refNode, int offset)
      Sets the attributes describing the start of the Range.
      void Range.setStartAfter(Node refNode)
      Sets the start position to be after a node
      void Range.setStartBefore(Node refNode)
      Sets the start position to be before a node
      void Range.surroundContents(Node newParent)
      Reparents the contents of the Range to the given node and inserts the node at the position of the start of the Range.

    • Uses of Node in org.w3c.dom.stylesheets

      Methods in org.w3c.dom.stylesheets that return Node
      Modifier and Type Method and Description
      Node StyleSheet.getOwnerNode()
      The node that associates this style sheet with the document.

    • Uses of Node in org.w3c.dom.traversal

      Methods in org.w3c.dom.traversal that return Node
      Modifier and Type Method and Description
      Node TreeWalker.firstChild()
      Moves the TreeWalker to the first visible child of the current node, and returns the new node.
      Node TreeWalker.getCurrentNode()
      The node at which the TreeWalker is currently positioned.
      Node TreeWalker.getRoot()
      The root node of the TreeWalker, as specified when it was created.
      Node NodeIterator.getRoot()
      The root node of the NodeIterator, as specified when it was created.
      Node TreeWalker.lastChild()
      Moves the TreeWalker to the last visible child of the current node, and returns the new node.
      Node TreeWalker.nextNode()
      Moves the TreeWalker to the next visible node in document order relative to the current node, and returns the new node.
      Node NodeIterator.nextNode()
      Returns the next node in the set and advances the position of the NodeIterator in the set.
      Node TreeWalker.nextSibling()
      Moves the TreeWalker to the next sibling of the current node, and returns the new node.
      Node TreeWalker.parentNode()
      Moves to and returns the closest visible ancestor node of the current node.
      Node TreeWalker.previousNode()
      Moves the TreeWalker to the previous visible node in document order relative to the current node, and returns the new node.
      Node NodeIterator.previousNode()
      Returns the previous node in the set and moves the position of the NodeIterator backwards in the set.
      Node TreeWalker.previousSibling()
      Moves the TreeWalker to the previous sibling of the current node, and returns the new node.
      Methods in org.w3c.dom.traversal with parameters of type Node
      Modifier and Type Method and Description
      short NodeFilter.acceptNode(Node n)
      Test whether a specified node is visible in the logical view of a TreeWalker or NodeIterator.
      NodeIterator DocumentTraversal.createNodeIterator(Node root, int whatToShow, NodeFilter filter, boolean entityReferenceExpansion)
      Create a new NodeIterator over the subtree rooted at the specified node.
      TreeWalker DocumentTraversal.createTreeWalker(Node root, int whatToShow, NodeFilter filter, boolean entityReferenceExpansion)
      Create a new TreeWalker over the subtree rooted at the specified node.
      void TreeWalker.setCurrentNode(Node currentNode)
      The node at which the TreeWalker is currently positioned.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.traversal.NodeFilter (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.traversal.NodeFilter

  • Packages that use NodeFilter
    Package Description
    org.w3c.dom.ls
    org.w3c.dom.traversal

    • Uses of NodeFilter in org.w3c.dom.ls

      Subinterfaces of NodeFilter in org.w3c.dom.ls
      Modifier and Type Interface and Description
      interface  LSSerializerFilter
      LSSerializerFilters provide applications the ability to examine nodes as they are being serialized and decide what nodes should be serialized or not.

    • Uses of NodeFilter in org.w3c.dom.traversal

      Methods in org.w3c.dom.traversal that return NodeFilter
      Modifier and Type Method and Description
      NodeFilter TreeWalker.getFilter()
      The filter used to screen nodes.
      NodeFilter NodeIterator.getFilter()
      The NodeFilter used to screen nodes.
      Methods in org.w3c.dom.traversal with parameters of type NodeFilter
      Modifier and Type Method and Description
      NodeIterator DocumentTraversal.createNodeIterator(Node root, int whatToShow, NodeFilter filter, boolean entityReferenceExpansion)
      Create a new NodeIterator over the subtree rooted at the specified node.
      TreeWalker DocumentTraversal.createTreeWalker(Node root, int whatToShow, NodeFilter filter, boolean entityReferenceExpansion)
      Create a new TreeWalker over the subtree rooted at the specified node.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.traversal.NodeIterator (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.traversal.NodeIterator

  • Packages that use NodeIterator
    Package Description
    org.w3c.dom.traversal

    • Uses of NodeIterator in org.w3c.dom.traversal

      Methods in org.w3c.dom.traversal that return NodeIterator
      Modifier and Type Method and Description
      NodeIterator DocumentTraversal.createNodeIterator(Node root, int whatToShow, NodeFilter filter, boolean entityReferenceExpansion)
      Create a new NodeIterator over the subtree rooted at the specified node.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.NodeList (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.NodeList

  • Packages that use NodeList
    Package Description
    org.w3c.dom
    Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.
    org.w3c.dom.html

    • Uses of NodeList in org.w3c.dom

      Methods in org.w3c.dom that return NodeList
      Modifier and Type Method and Description
      NodeList Node.getChildNodes()
      A NodeList that contains all children of this node.
      NodeList Element.getElementsByTagName(String name)
      Returns a NodeList of all descendant Elements with a given tag name, in document order.
      NodeList Document.getElementsByTagName(String tagname)
      Returns a NodeList of all the Elements in document order with a given tag name and are contained in the document.
      NodeList Element.getElementsByTagNameNS(String namespaceURI, String localName)
      Returns a NodeList of all the descendant Elements with a given local name and namespace URI in document order.
      NodeList Document.getElementsByTagNameNS(String namespaceURI, String localName)
      Returns a NodeList of all the Elements with a given local name and namespace URI in document order.

    • Uses of NodeList in org.w3c.dom.html

      Methods in org.w3c.dom.html that return NodeList
      Modifier and Type Method and Description
      NodeList HTMLDocument.getElementsByName(String elementName)
      Returns the (possibly empty) collection of elements whose name value is given by elementName .
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Improved Compiler Warnings When Using Non-Reifiable Formal Parameters with Varargs Methods

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods

This page covers the following topics:

  • Heap Pollution
  • Variable Arguments Methods and Non-Reifiable Formal Parameters
  • Potential Vulnerabilities of Varargs Methods with Non-Reifiable Formal Parameters
  • Suppressing Warnings from Varargs Methods with Non-Reifiable Formal Parameters

Heap Pollution

Most parameterized types, such as ArrayList<Number> and List<String>, are non-reifiable types. A non-reifiable type is a type that is not completely available at runtime. At compile time, non-reifiable types undergo a process called type erasure during which the compiler removes information related to type parameters and type arguments. This ensures binary compatibility with Java libraries and applications that were created before generics. Because type erasure removes information from parameterized types at compile-time, these types are non-reifiable.

Heap pollution occurs when a variable of a parameterized type refers to an object that is not of that parameterized type. This situation can only occur if the program performed some operation that would give rise to an unchecked warning at compile-time. An unchecked warning is generated if, either at compile-time (within the limits of the compile-time type checking rules) or at runtime, the correctness of an operation involving a parameterized type (for example, a cast or method call) cannot be verified.

Consider the following example:

    List l = new ArrayList<Number>();
    List<String> ls = l;       // unchecked warning
    l.add(0, new Integer(42)); // another unchecked warning
    String s = ls.get(0);      // ClassCastException is thrown

During type erasure, the types ArrayList<Number> and List<String> become ArrayList and List, respectively.

The variable ls has the parameterized type List<String>. When the List referenced by l is assigned to ls, the compiler generates an unchecked warning; the compiler is unable to determine at compile time, and moreover knows that the JVM will not be able to determine at runtime, if l refers to a List<String> type; it does not. Consequently, heap pollution occurs.

As a result, at compile time, the compiler generates another unchecked warning at the add statement. The compiler is unable to determine if the variable l refers to a List<String> type or a List<Integer> type (and another heap pollution situation occurs). However, the compiler does not generate a warning or error at the get statement. This statement is valid; it is calling the List<String>.get method to retrieve a String object. Instead, at runtime, the get statement throws a ClassCastException.

In detail, a heap pollution situation occurs when the List object l, whose static type is List<Number>, is assigned to another List object, ls, that has a different static type, List<String>. However, the compiler still allows this assignment. It must allow this assignment to preserve backwards compatibility with versions of Java SE that do not support generics. Because of type erasure, List<Number> and List<String> both become List. Consequently, the compiler allows the assignment of the object l, which has a raw type of List, to the object ls.

Furthermore, a heap pollution situation occurs when the l.add method is called. The static type second formal parameter of the add method is String, but this method is called with an actual parameter of a different type, Integer. However, the compiler still allows this method call. Because of type erasure, the type of the second formal parameter of the add method (which is defined as List<E>.add(int,E)) becomes Object. Consequently, the compiler allows this method call because, after type erasure, the l.add method can add any object of type Object, including an object of Integer type, which is a subtype of Object.

Variable Arguments Methods and Non-Reifiable Formal Parameters

Consider the method ArrayBuilder.addToList in the following example. It is a variable arguments (also known as varargs) method that adds the objects of type T contained in the elements varargs formal parameter to the List listArg:

import java.util.*;

public class ArrayBuilder {

  public static <T> void addToList (List<T> listArg, T... elements) {
    for (T x : elements) {
      listArg.add(x);
    }
  }

  public static void faultyMethod(List<String>... l) {
    Object[] objectArray = l;  // Valid
    objectArray[0] = Arrays.asList(new Integer(42));
    String s = l[0].get(0);    // ClassCastException thrown here
  }

}

import java.util.*;

public class HeapPollutionExample {

  public static void main(String[] args) {

    List<String> stringListA = new ArrayList<String>();
    List<String> stringListB = new ArrayList<String>();

    ArrayBuilder.addToList(stringListA, "Seven", "Eight", "Nine");
    ArrayBuilder.addToList(stringListA, "Ten", "Eleven", "Twelve");
    List<List<String>> listOfStringLists = new ArrayList<List<String>>();
    ArrayBuilder.addToList(listOfStringLists, stringListA, stringListB);

    ArrayBuilder.faultyMethod(Arrays.asList("Hello!"), Arrays.asList("World!"));
  }
}

The Java SE 7 compiler generates the following warning for the definition of the method ArrayBuilder.addToList:

warning: [varargs] Possible heap pollution from parameterized vararg type T

When the compiler encounters a varargs method, it translates the varargs formal parameter into an array. However, the Java programming language does not permit the creation of arrays of parameterized types. In the method ArrayBuilder.addToList, the compiler translates the varargs formal parameter T... elements to the formal parameter T[] elements, an array. However, because of type erasure, the compiler converts the varargs formal parameter to Object[] elements. Consequently, there is a possibility of heap pollution. See the next section, Potential Vulnerabilities of Varargs Methods with Non-Reifiable Formal Parameters, for more information.

Note: The Java SE 5 and 6 compilers generate this warning when the ArrayBuilder.addToList is called; in this example, the warning is generated for the class HeapPollutionExample. These compilers do not generate the warning at the declaration site. However, the Java SE 7 generates the warning at both the declaration site and the call site (unless the warnings are preempted with annotations; see Suppressing Warnings from Varargs Methods with Non-Reifiable Formal Parameters for more information). The advantage of generating a warning when a compiler encounters a varargs method that has a non-reifiable varargs formal parameter at the declaration site as opposed to the call site is that there is only one declaration site; there are potentially many call sites.

Potential Vulnerabilities of Varargs Methods with Non-Reifiable Formal Parameters

The method ArrayBuilder.faultyMethod shows why the compiler warns you about these kinds of methods. The first statement of this method assigns the varargs formal parameter l to the Object array objectArgs:

    Object[] objectArray = l;

This statement can potentially introduce heap pollution. A value that does match the parameterized type of the varargs formal parameter l can be assigned to the variable objectArray, and thus can be assigned to l. However, the compiler does not generate an unchecked warning at this statement. The compiler has already generated a warning when it translated the varargs formal parameter List<String>... l to the formal parameter List[] l. This statement is valid; the variable l has the type List[], which is a subtype of Object[].

Consequently, the compiler does not issue a warning or error if you assign a List object of any type to any array component of the objectArray array as shown by this statement:

    objectArray[0] = Arrays.asList(new Integer(42));

This statement assigns to the first array component of the objectArray array with a List object that contains one object of type Integer.

Suppose you call the ArrayBuilder.makeArray method with the following statement:

    ArrayBuilder.faultyMethod(Arrays.asList("Hello!"), Arrays.asList("World!"));

At runtime, the JVM throws a ClassCastException at the following statement:

    String s = l[0].get(0);    // ClassCastException thrown here

The object stored in the first array component of the variable l has the type List<Integer>, but this statement is expecting an object of type List<String>.

Suppressing Warnings from Varargs Methods with Non-Reifiable Formal Parameters

If you declare a varargs method that has parameterized parameters, and you ensure that the body of the method does not throw a ClassCastException or other similar exception due to improper handling of the varargs formal parameter (as shown in the ArrayBuilder.faultyMethod method), you can suppress the warning that the compiler generates for these kinds of varargs methods by using one of the following options:

  • Add the following annotation to static and non-constructor method declarations:

    @SafeVarargs

    Unlike the @SafeVarargs annotation, the @SafeVarargs annotation is a documented part of the method's contract; this annotation asserts that the implementation of the method will not improperly handle the varargs formal parameter.

  • Add the following annotation to the method declaration:

    @SuppressWarnings({"unchecked", "varargs"})

    Unlike the @SafeVarargs annotation, the @SuppressWarnings("varargs") does not suppress warnings generated from the method's call site.

  • Use the compiler option -Xlint:varargs.

For example, the following version of the ArrayBuilder class has two additional methods, addToList2 and addToList3:

public class ArrayBuilder {

  public static <T> void addToList (List<T> listArg, T... elements) {
    for (T x : elements) {
      listArg.add(x);
    }
  }

  @SuppressWarnings({"unchecked", "varargs"})
  public static <T> void addToList2 (List<T> listArg, T... elements) {
    for (T x : elements) {
      listArg.add(x);
    }
  }

  @SafeVarargs
  public static <T> void addToList3 (List<T> listArg, T... elements) {
    for (T x : elements) {
      listArg.add(x);
    }
  }

  // ...

}
public class HeapPollutionExample {

  // ...

  public static void main(String[] args) {

    // ...

    ArrayBuilder.addToList(listOfStringLists, stringListA, stringListB);
    ArrayBuilder.addToList2(listOfStringLists, stringListA, stringListB);
    ArrayBuilder.addToList3(listOfStringLists, stringListA, stringListB);

    // ...

  }
}

The Java compiler generates the following warnings for this example:

  • addToList:
    • At the method's declaration: [unchecked] Possible heap pollution from parameterized vararg type T
    • When the method is called: [unchecked] unchecked generic array creation for varargs parameter of type List<String>[]
  • addToList2: When the method is called (no warning is generated at the method's declaration): [unchecked] unchecked generic array creation for varargs parameter of type List<String>[]
  • addToList3: No warnings are generated either at the method's declaration or when it is called.

Note: In Java SE 5 and 6, it is the responsibility of the programmer who calls a varargs method that has a non-reifiable varargs formal parameter to determine whether heap pollution would occur. However, if this programmer did not write such a method, he or she cannot easily determine this. In Java SE 7, it is the responsibility of the programmer who writes these kinds of varargs methods to ensure that they properly handle the varargs formal parameter and ensure heap pollution does not occur.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface org.w3c.dom.Notation (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.Notation

No usage of org.w3c.dom.Notation
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Using Activation: Not Extending Activatable

This tutorial describes how to implement an activatable remote object, but differs from the tutorial Using Activation: Extending Activatable in that the implementation for the remote object does not extend the class java.rmi.activation.Activatable. Instead, the implementation uses a static method of the class Activatable to export an activatable remote object. This tutorial uses a Setup program (described in the tutorial Using Activation: the Setup Program) that registers information about an activatable remote object with the JavaTM Remote Method Invocation (Java RMI) activation system daemon (rmid) and then binds a stub for that remote object in an rmiregistry so that clients can look it up. You may want to read that tutorial before this one.

This tutorial has the following steps:

  • Implement the activatable remote object
  • Implement the client
  • Compile the source files
  • Run the Setup program
  • Run the client

The files needed for this tutorial are:

  • MyRemoteInterface.java - a simple remote interface
  • DoesNotExtendActivatable.java - an "activatable" implementation of the remote interface
  • Client.java - a client that uses the remote interface
  • client.policy - the security policy file for the client

Implement the activatable remote object

There are a few basic ways to implement an activatable remote object. This tutorial describes how to implement an activatable remote object by using a static method of the class java.rmi.activation.Activatable to export an activatable remote object.

A remote object is activated when a client invokes a remote method on a stub for an activatable remote object. A stub for an activatable remote object contains the remote object's activation ID and information on how to contact the Java RMI activation system daemon (rmid) for the remote object. If the stub cannot connect to the last-known address (i.e., host/port) for the remote object, the stub will contact the remote object's activator (rmid) to activate the object. When rmid receives an activation request, it starts the remote object's activation group (or container) VM if the group is not already executing, and then rmid asks the group to make an instance of the remote object. Once the group constructs the remote object, it returns the remote object's stub to rmid which, in turn, returns the actual stub to the initiating stub so that the initiating stub can update its information on how to contact the remote object in the future.

Before any of this activation can take place, an application must register information about the activatable remote objects it needs to use. The following separate tutorial describes the information needed to activatate a remote object and how to register this information with rmid:

  • Using Activation: the Setup program

In this example, the activatable remote object implements the following remote interface examples.activation.MyRemoteInterface:

package examples.activation;

import java.rmi.*;

public interface MyRemoteInterface extends Remote {
    Object remoteMethod(Object obj) throws RemoteException;
}

The implementation class, examples.activation.DoesNotExtendActivatable, for the activatable remote object is as follows:

package examples.activation;

import java.rmi.*;
import java.rmi.activation.*;

public class DoesNotExtendActivatable implements MyRemoteInterface {

    private final ActivationID id;

    public DoesNotExtendActivatable(ActivationID id, MarshalledObject data)
        throws RemoteException
    {
        this.id = id;
        Activatable.exportObject(this, id, 0);
    }

    public Object remoteMethod(Object obj) {
        return obj;
    }
}

The class DoesNotExtendActivatable implements the remote interface MyRemoteInterface, but does not extend any class.

The class DoesNotExtendActivatable declares a special "activation" constructor that an activation group calls to construct an instance during the activation process. This special constructor takes two parameters:

  • The first parameter, ActivationID, is an identifier for the activatable remote object. When an application registers an activation descriptor with rmid, rmid assigns it an activation ID, which refers to the information associated with the descriptor. This same activation ID (also contained in the remote object's stub) is passed to this constructor when the remote object is activated.
  • The second parameter is a MarshalledObject that contains initialization data pre-registered with rmid. This initialization data may be a filename for the object's persistent state, for example. This example does not require any initialization data to construct the remote object.

The constructor saves the activation ID in a private field, and then calls the static method Activatable.exportObject, passing the implementation itself (this), the activation ID, and the port number 0, indicating that the object should be exported on an anonymous TCP port. While this implementation does not actually use the activation ID it stores, this example saves the activation ID to demonstrate what a typical implementation of an activatable object might do. Such an implementation may need the activation ID in the future, in order to deactivate the object, for example.

Finally, the class implements the remote interface's single method, remoteMethod to return the object passed as an argument.

Implement the client

The Client program looks up a remote object's stub (one that implements the remote interface MyRemoteInterface) in the registry on the host supplied as the optional first argument, and then invokes the stub's remoteMethod method. The client program is the same as the one described in the tutorial Using Activation: Extending Activatable. For details, see the following section of that tutorial

  • Implement the client

Compile the source files

The source files for this example can be compiled as follows:

javac -d implDir MyRemoteInterface.java DoesNotExtendActivatable.java
javac -d clientDir MyRemoteInterface.java Client.java

where implDir is the destination directory to put the implementation's class files the class files in, and clientDir is the destination directory to put the client's class files in.

Run the Setup program

Once your implementation phase is complete, you need to register information about the activatable object so a client can use it. The Setup program, described by the tutorial Using Activation: the Setup Program, registers an activation descriptor for an activatable object with rmid, and then binds the remote object's stub in an rmiregistry so that clients can look it up.

To run the Setup program for this example, see the section Start rmid, rmiregistry, and the Setup program in the setup program tutorial, which describes how to start rmid, rmiregistry, and the Setup program itself.

After you run rmid and rmiregistry as instructed in the Setup tutorial, you will need to run the Setup program to register an activation descriptor for an activatable object that implements the class examples.activation.DoesNotExtendActivatable. The following command line runs the Setup program, supplying an appropriate file URL for each codebase used:

java -cp setupDir:implDir                       \
     -Djava.security.policy=setup.policy                      \
     -Djava.rmi.server.codebase=file:/implDir/                \
     -Dexamples.activation.setup.codebase=file:/setupDir/     \
     -Dexamples.activation.impl.codebase=file:/impDir/        \
     -Dexamples.activation.name=examples.activation.MyRemoteInterface       \
     -Dexamples.activation.policy=group.policy                \
     examples.activation.Setup examples.activation.DoesNotExtendActivatable

where:

  • setupDir is the root directory for the Setup program's class
  • implDir is the root directory for the implementation's classes
  • setup.policy is the security policy file for the Setup program
  • group.policy is the security policy file for the activation group

Note that the examples.activation.file system property does not need to be specified, because the DoesNotExtendActivatable implementation class does not use it. Also note that each file URL above has the required trailing slash. Examples of group and setup policy files, suitable for this tutorial, are described in the setup tutorial, and are also listed below:

  • setup.policy
  • group.policy

The output from the Setup program should look like this:

Activation group descriptor registered.
Activation descriptor registered.
Stub bound in registry.

Run the client

Once you have successfully registered an activation descriptor for a DoesNotExtendActivatable implementation, you can run the client program, which, during its first execution, will cause the activatable object to activate.

The client program is the same as the one described in the tutorial Using Activation: Extending Activatable. For details, see the following section of that tutorial:

  • Run the client
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.security.auth.NTDomainPrincipal (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.NTDomainPrincipal

No usage of com.sun.security.auth.NTDomainPrincipal
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.auth.module.NTLoginModule (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.module.NTLoginModule

No usage of com.sun.security.auth.module.NTLoginModule
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.auth.NTNumericCredential (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.NTNumericCredential

No usage of com.sun.security.auth.NTNumericCredential
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.auth.NTSid (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.NTSid

  • Packages that use NTSid
    Package Description
    com.sun.security.auth

    • Uses of NTSid in com.sun.security.auth

      Subclasses of NTSid in com.sun.security.auth
      Modifier and Type Class and Description
      class  NTSidDomainPrincipal
      This class extends NTSid and represents a Windows NT user's domain SID.
      class  NTSidGroupPrincipal
      This class extends NTSid and represents one of the groups to which a Windows NT user belongs.
      class  NTSidPrimaryGroupPrincipal
      This class extends NTSid and represents a Windows NT user's primary group SID.
      class  NTSidUserPrincipal
      This class extends NTSid and represents a Windows NT user's SID.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.auth.NTSidDomainPrincipal (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.NTSidDomainPrincipal

No usage of com.sun.security.auth.NTSidDomainPrincipal
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.auth.NTSidGroupPrincipal (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.NTSidGroupPrincipal

No usage of com.sun.security.auth.NTSidGroupPrincipal
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.auth.NTSidPrimaryGroupPrincipal (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.NTSidPrimaryGroupPrincipal

No usage of com.sun.security.auth.NTSidPrimaryGroupPrincipal
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.auth.NTSidUserPrincipal (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.NTSidUserPrincipal

No usage of com.sun.security.auth.NTSidUserPrincipal
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.auth.module.NTSystem (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.module.NTSystem

No usage of com.sun.security.auth.module.NTSystem
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.auth.NTUserPrincipal (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.NTUserPrincipal

No usage of com.sun.security.auth.NTUserPrincipal
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.jdi.ObjectCollectedException (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.ObjectCollectedException

No usage of com.sun.jdi.ObjectCollectedException
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.ObjectReference (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.ObjectReference

  • Packages that use ObjectReference
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.
    com.sun.jdi.event
    This package defines JDI events and event processing.
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of ObjectReference in com.sun.jdi

      Subinterfaces of ObjectReference in com.sun.jdi
      Modifier and Type Interface and Description
      interface  ArrayReference
      Provides access to an array object and its components in the target VM.
      interface  ClassLoaderReference
      A class loader object from the target VM.
      interface  ClassObjectReference
      An instance of java.lang.Class from the target VM.
      interface  StringReference
      A string object from the target VM.
      interface  ThreadGroupReference
      A thread group object from the target VM.
      interface  ThreadReference
      A thread object from the target VM.
      Methods in com.sun.jdi that return ObjectReference
      Modifier and Type | Method and Description
      ObjectReference ThreadReference.currentContendedMonitor()
      Returns an ObjectReference for the monitor, if any, for which this thread is currently waiting.
      ObjectReference | InvocationException.exception()
      ObjectReference MonitorInfo.monitor()
      Returns the ObjectReference object for the monitor.
      ObjectReference ClassType.newInstance(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Constructs a new instance of this type, using the given constructor Method in the target VM.
      ObjectReference StackFrame.thisObject()
      Returns the value of 'this' for the current frame.
      Methods in com.sun.jdi that return types with arguments of type ObjectReference
      Modifier and Type Method and Description
      List<ObjectReference> ReferenceType.instances(long maxInstances)
      Returns instances of this ReferenceType.
      List<ObjectReference> ThreadReference.ownedMonitors()
      Returns a List containing an ObjectReference for each monitor owned by the thread.
      List<ObjectReference> ObjectReference.referringObjects(long maxReferrers)
      Returns objects that directly reference this object.
      Methods in com.sun.jdi with parameters of type ObjectReference
      Modifier and Type Method and Description
      void ThreadReference.stop(ObjectReference throwable)
      Stops this thread with an asynchronous exception.
      Constructors in com.sun.jdi with parameters of type ObjectReference
      Constructor and Description
      InvocationException(ObjectReference exception)

    • Uses of ObjectReference in com.sun.jdi.event

      Methods in com.sun.jdi.event that return ObjectReference
      Modifier and Type Method and Description
      ObjectReference ExceptionEvent.exception()
      Gets the thrown exception object.
      ObjectReference MonitorWaitedEvent.monitor()
      Returns the monitor object this thread waited on.
      ObjectReference MonitorWaitEvent.monitor()
      Returns the monitor object that the thread about to wait.
      ObjectReference MonitorContendedEnteredEvent.monitor()
      Returns the monitor that was entered.
      ObjectReference MonitorContendedEnterEvent.monitor()
      Returns the method that was entered.
      ObjectReference WatchpointEvent.object()
      Returns the object whose field is about to be accessed/modified.

    • Uses of ObjectReference in com.sun.jdi.request

      Methods in com.sun.jdi.request with parameters of type ObjectReference
      Modifier and Type Method and Description
      void WatchpointRequest.addInstanceFilter(ObjectReference instance)
      Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.
      void BreakpointRequest.addInstanceFilter(ObjectReference instance)
      Restricts the events generated by this request to those in which the currently executing instance is the object specified.
      void StepRequest.addInstanceFilter(ObjectReference instance)
      Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.
      void MonitorWaitedRequest.addInstanceFilter(ObjectReference instance)
      Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.
      void MonitorWaitRequest.addInstanceFilter(ObjectReference instance)
      Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.
      void MonitorContendedEnteredRequest.addInstanceFilter(ObjectReference instance)
      Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.
      void MonitorContendedEnterRequest.addInstanceFilter(ObjectReference instance)
      Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.
      void MethodExitRequest.addInstanceFilter(ObjectReference instance)
      Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.
      void MethodEntryRequest.addInstanceFilter(ObjectReference instance)
      Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.
      void ExceptionRequest.addInstanceFilter(ObjectReference instance)
      Restricts the events generated by this request to those in which the currently executing instance ("this") is the object specified.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.management.OperatingSystemMXBean (Monitoring and Management Interface for the Java Platform b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Monitoring and Management Interface for the Java Platform
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.management.OperatingSystemMXBean

    • Uses of OperatingSystemMXBean in com.sun.management

      Subinterfaces of OperatingSystemMXBean in com.sun.management
      Modifier and Type Interface and Description
      interface  UnixOperatingSystemMXBean
      Platform-specific management interface for the Unix operating system on which the Java virtual machine is running.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Monitoring and Management Interface for the Java Platform
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2003, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


orbd - The Object Request Broker Daemon (ORBD)

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

orbd - The Object Request Broker Daemon

orbd is used to enable clients to transparently locate and invoke persistent objects on servers in the CORBA environment.

See also: Naming Service

SYNOPSIS

orbd <options>

DESCRIPTION

The Server Manager included with the orbd tool is used to enable clients to transparently locate and invoke persistent objects on servers in the CORBA environment. The persistent servers, while publishing the persistent object references in the Naming Service, include the port number of the ORBD in the object reference instead of the port number of the Server. The inclusion of an ORBD port number in the object reference for persistent object references has the following advantages:

  • The object reference in the Naming Service remains independent of the server life cycle. For example, the object reference could be published by the server in the Naming Service when it is first installed, and then, independent of how many times the server is started or shutdown, the ORBD will always return the correct object reference to the invoking client.
  • The client needs to lookup the object reference in the Naming Service only once, and can keep re-using this reference independent of the changes introduced due to server life cycle.

To access ORBD's Server Manager, the server must be started using servertool, which is a command-line interface for application programmers to register, unregister, startup, and shutdown a persistent server. For more information on the Server Manager, see the section in this document titled Server Manager.

When orbd starts up, it also starts a naming service. For more information on the naming service, link to Naming Service.

OPTIONS

Required Options

-ORBInitialPort nameserverport
Specifies the port on which the name server should be started. Once started, orbd will listen for incoming requests on this port. Note that when using Solaris software, you must become root to start a process on a port under 1024. For this reason, we recommend that you use a port number greater than or equal to 1024. (required)

OTHER OPTIONS

-port port
Specifies the activation port where ORBD should be started, and where ORBD will be accepting requests for persistent objects. The default value for this port is 1049. This port number is added to the port field of the persistent Interoperable Object References (IOR). (optional)
-defaultdb directory
Specifies the base where the ORBD persistent storage directory orb.db is created. If this option is not specified, the default value is "./orb.db". (optional)
-serverPollingTime milliseconds
Specifies how often ORBD checks for the health of persistent servers registered via servertool. The default value is 1,000 ms. The value specified for milliseconds must be a valid positive integer. (optional)
-serverStartupDelay milliseconds
Specifies how long ORBD waits before sending a location forward exception after a persistent server that is registered via servertool is restarted. The default value is 1,000 ms. The value specified for milliseconds must be a valid positive integer. (optional)
-J option
Pass option to the Java virtual machine, where option is one of the options described on the reference page for the java application launcher. For example, -J-Xms48m sets the startup memory to 48 megabytes. It is a common convention for -J to pass options to the underlying virtual machine.

Starting and Stopping the Naming Service

A Naming Service is a CORBA service that allows CORBA objects to be named by means of binding a name to an object reference. The name binding may be stored in the naming service, and a client may supply the name to obtain the desired object reference.

Prior to running a client or a server, you will start ORBD. ORBD includes a persistent Naming Service and a transient Naming Service, both of which are an implementation of the COS Naming Service.

The Persistent Naming Service provides persistence for naming contexts. This means that this information is persistent across service shutdowns and startups, and is recoverable in the event of a service failure. If ORBD is restarted, the Persistent Naming Service will restore the naming context graph, so that the binding of all clients' and servers' names remains intact (persistent).

For backward compatibility, tnameserv, a Transient Naming Service shipped with older versions of the JDK, is also included in this release of J2SE. A transient naming service retains naming contexts as long as it is running. If there is a service interruption, the naming context graph is lost.

The -ORBInitialPort argument is a required command-line argument for orbd, and is used to set the port number on which the Naming Service will run. The following instructions assume you can use port 1050 for the Java IDL Object Request Broker Daemon. When using Solaris software, you must become root to start a process on a port under 1024. For this reason, we recommend that you use a port number greater than or equal to 1024. You can substitute a different port if necessary.

To start orbd from a UNIX command shell, enter:

  orbd -ORBInitialPort 1050&

From an MS-DOS system prompt (Windows), enter:

  start orbd -ORBInitialPort 1050

Now that ORBD is running, you can run your server and client applications. When running the client and server applications, they must be made aware of the port number (and machine name, if applicable) where the Naming Service is running. One way to do this is to add the following code to your application:

        Properties props = new Properties();
        props.put("org.omg.CORBA.ORBInitialPort", "1050");
        props.put("org.omg.CORBA.ORBInitialHost", "MyHost");
        ORB orb = ORB.init(args, props);

In this example, the Naming Service is running on port 1050 on host "MyHost". Another way is to specify the port number and/or machine name when running the server or client application from the command line. For example, you would start your "HelloApplication" with the following command line:

     java HelloApplication -ORBInitialPort 1050 -ORBInitialHost MyHost

To stop the naming service, use the relevant operating system command, such as pkill orbd on Solaris, or Ctrl+C in the DOS window in which orbd is running. Note that names registered with the naming service may disappear when the service is terminated if the naming service is transient. The Java IDL naming service will run until it is explicitly stopped.

For more information on the Naming Service included with ORBD, see Naming Service.

Server Manager

To access ORBD's Server Manager and run a persistent server, the server must be started using servertool, which is a command-line interface for application programmers to register, unregister, startup, and shutdown a persistent server. When a server is started using servertool, it must be started on the same host and port on which orbd is executing. If the server is run on a different port, the information stored in the database for local contexts will be invalid and the service will not work properly.

Server Manager: an Example

Using the sample tutorial for our demonstration, you would run the idlj compiler and javac compiler as shown in the tutorial. To run the Server Manager, follow these steps for running the application:

Start orbd.

To start orbd from a UNIX command shell, enter:

  orbd -ORBInitialPort 1050

From an MS-DOS system prompt (Windows), enter:

  start orbd -ORBInitialPort 1050

Note that 1050 is the port on which you want the name server to run. -ORBInitialPort is a required command-line argument. When using Solaris software, you must become root to start a process on a port under 1024. For this reason, we recommend that you use a port number greater than or equal to 1024.

Start the servertool:

To start the Hello server, enter:

  servertool -ORBInitialPort 1050

Make sure the name server (orbd) port is the same as in the previous step, for example, -ORBInitialPort 1050. The servertool must be started on the same port as the name server.

The servertool command line interface appears.

Start the Hello server from the servertool prompt:

  servertool  > register -server HelloServer -classpath . -applicationName
                HelloServerApName

The servertool registers the server, assigns it the name of "HelloServerApName", and displays its server id, along with a listing of all registered servers.

Run the client application from another terminal window or prompt:

  java HelloClient -ORBInitialPort 1050 -ORBInitialHost localhost

For this example, you can omit -ORBInitialHost localhost since the name server is running on the same host as the Hello client. If the name server is running on a different host, use -ORBInitialHost nameserverhost to specify the host on which the IDL name server is running.

Specify the name server (orbd) port as done in the previous step, for example, -ORBInitialPort 1050.

When you have finished experimenting with the Server Manager, be sure to shut down or kill the name server (orbd) and servertool.

To shut down orbd from a DOS prompt, select the window that is running the server and enter Ctrl+C to shut it down. To shut down orbdfrom a Unix shell, find the process, and kill it. The server will continue to wait for invocations until it is explicitly stopped.

To shut down the servertool, type quit and press the Enter key on the keyboard.

See Also

  • Naming Service
  • servertool

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.management.OSMBeanFactory (Monitoring and Management Interface for the Java Platform b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Monitoring and Management Interface for the Java Platform
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.management.OSMBeanFactory

No usage of com.sun.management.OSMBeanFactory
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Monitoring and Management Interface for the Java Platform
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2003, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Java Object Serialization Specification: 2 - Object Output Classes

CONTENTS | PREV | NEXT Java Object Serialization Specification
version 6.0

Object Output Classes

CHAPTER 2

Topics:

  • The ObjectOutputStream Class
  • The ObjectOutputStream.PutField Class
  • The writeObject Method
  • The writeExternal Method
  • The writeReplace Method
  • The useProtocolVersion Method

2.1 The ObjectOutputStream Class

Class ObjectOutputStream implements object serialization. It maintains the state of the stream including the set of objects already serialized. Its methods control the traversal of objects to be serialized to save the specified objects and the objects to which they refer.

package java.io;

public class ObjectOutputStream
    extends OutputStream
    implements ObjectOutput, ObjectStreamConstants
{
    public ObjectOutputStream(OutputStream out)
        throws IOException;

    public final void writeObject(Object obj)
        throws IOException;

    public void writeUnshared(Object obj)
        throws IOException;

    public void defaultWriteObject()
        throws IOException, NotActiveException;

    public PutField putFields()
        throws IOException;

    public writeFields()
        throws IOException;

    public void reset() throws IOException;

    protected void annotateClass(Class cl) throws IOException;

    protected void writeClassDescriptor(ObjectStreamClass desc)
        throws IOException;

    protected Object replaceObject(Object obj) throws IOException;

    protected boolean enableReplaceObject(boolean enable)
        throws SecurityException;

    protected void writeStreamHeader() throws IOException;

    public void write(int data) throws IOException;

    public void write(byte b[]) throws IOException;

    public void write(byte b[], int off, int len) throws IOException;

    public void flush() throws IOException;

    protected void drain() throws IOException;

    public void close() throws IOException;

    public void writeBoolean(boolean data) throws IOException;

    public void writeByte(int data) throws IOException;

    public void writeShort(int data) throws IOException;

    public void writeChar(int data) throws IOException;

    public void writeInt(int data) throws IOException;

    public void writeLong(long data) throws IOException;

    public void writeFloat(float data) throws IOException;

    public void writeDouble(double data) throws IOException;

    public void writeBytes(String data) throws IOException;

    public void writeChars(String data) throws IOException;

    public void writeUTF(String data) throws IOException;

    // Inner class to provide access to serializable fields.
    abstract static public class PutField
    {
        public void put(String name, boolean value)
            throws IOException, IllegalArgumentException;

        public void put(String name, char data)
            throws IOException, IllegalArgumentException;

        public void put(String name, byte data)
            throws IOException, IllegalArgumentException;

        public void put(String name, short data)
            throws IOException, IllegalArgumentException;

        public void put(String name, int data)
            throws IOException, IllegalArgumentException;

        public void put(String name, long data)
            throws IOException, IllegalArgumentException;

        public void put(String name, float data)
            throws IOException, IllegalArgumentException;

        public void put(String name, double data)
            throws IOException, IllegalArgumentException;

        public void put(String name, Object data)
            throws IOException, IllegalArgumentException;
    }

    public void useProtocolVersion(int version) throws IOException;

    protected ObjectOutputStream()
        throws IOException;

     protected writeObjectOverride()
        throws NotActiveException, IOException;
}
The single-argument ObjectOutputStream constructor creates an ObjectOutputStream that serializes objects to the given OutputStream. The constructor calls writeStreamHeader to write a magic number and version to the stream that will be read and verified by a corresponding call to readStreamHeader in the single-argument ObjectInputStream constructor. If a security manager is installed, this constructor checks for the "enableSubclassImplementation" SerializablePermission when invoked directly or indirectly by the constructor of a subclass which overrides the putFields and/or writeUnshared methods.

The writeObject method is used to serialize an object to the stream. An object is serialized as follows:

1. If a subclass is overriding the implementation, call the writeObjectOverride method and return. Overriding the implementation is described at the end of this section.
2. If there is data in the block-data buffer, the data is written to the stream and the buffer is reset.
3. If the object is null, null is put in the stream and writeObject returns.
4. If the object has been previously replaced, as described in Step 8, write the handle of the replacement to the stream and writeObject returns.
5. If the object has already been written to the stream, its handle is written to the stream and writeObject returns.
6. If the object is a Class, the corresponding ObjectStreamClass is written to the stream, a handle is assigned for the class, and writeObject returns.
7. If the object is an ObjectStreamClass, a handle is assigned to the object, after which it is written to the stream using one of the class descriptor formats described in section 4.3. In versions 1.3 and later of the Java 2 SDK, Standard Edition, the writeClassDescriptor method is called to output the ObjectStreamClass if it represents a class that is not a dynamic proxy class, as determined by passing the associated Class object to the isProxyClass method of java.lang.reflect.Proxy. Afterwards, an annotation for the represented class is written: if the class is a dynamic proxy class, then the annotateProxyClass method is called; otherwise, the annotateClass method is called. The writeObject method then returns.
8. Process potential substitutions by the class of the object and/or by a subclass of ObjectInputStream.
a. If the class of an object is not an enum type and defines the appropriate writeReplace method, the method is called. Optionally, it can return a substitute object to be serialized.
b. Then, if enabled by calling the enableReplaceObject method, the replaceObject method is called to allow subclasses of ObjectOutputStream to substitute for the object being serialized. If the original object was replaced in the previous step, the replaceObject method is called with the replacement object.
If the original object was replaced by either one or both steps above, the mapping from the original object to the replacement is recorded for later use in Step 4. Then, Steps 3 through 7 are repeated on the new object.
If the replacement object is not one of the types covered by Steps 3 through 7, processing resumes using the replacement object at Step 10.
9. If the object is a java.lang.String, the string is written as length information followed by the contents of the string encoded in modified UTF-8. For details, refer to Section 6.2, "Stream Elements". A handle is assigned to the string, and writeObject returns.
10. If the object is an array, writeObject is called recursively to write the ObjectStreamClass of the array. The handle for the array is assigned. It is followed by the length of the array. Each element of the array is then written to the stream, after which writeObject returns.
11. If the object is an enum constant, the ObjectStreamClass for the enum type of the constant is written by recursively calling writeObject. It will appear in the stream only the first time it is referenced. A handle is assigned for the enum constant. Next, the value returned by the name method of the enum constant is written as a String object, as described in step 9. Note that if the same name string has appeared previously in the stream, a back reference to it will be written. The writeObject method then returns.
12. For regular objects, the ObjectStreamClass for the class of the object is written by recursively calling writeObject. It will appear in the stream only the first time it is referenced. A handle is assigned for the object.
13. The contents of the object are written to the stream.
a. If the object is serializable, the highest serializable class is located. For that class, and each derived class, that class's fields are written. If the class does not have a writeObject method, the defaultWriteObject method is called to write the serializable fields to the stream. If the class does have a writeObject method, it is called. It may call defaultWriteObject or putFields and writeFields to save the state of the object, and then it can write other information to the stream.
b. If the object is externalizable, the writeExternal method of the object is called.
c. If the object is neither serializable or externalizable, the NotSerializableException is thrown.

Exceptions may occur during the traversal or may occur in the underlying stream. For any subclass of IOException, the exception is written to the stream using the exception protocol and the stream state is discarded. If a second IOException is thrown while attempting to write the first exception into the stream, the stream is left in an unknown state and StreamCorruptedException is thrown from writeObject. For other exceptions, the stream is aborted and left in an unknown and unusable state.

The writeUnshared method writes an "unshared" object to the ObjectOutputStream. This method is identical to writeObject, except that it always writes the given object as a new, unique object in the stream (as opposed to a back-reference pointing to a previously serialized instance). Specifically:
  • An object written via writeUnshared is always serialized in the same manner as a newly appearing object (an object that has not been written to the stream yet), regardless of whether or not the object has been written previously.
  • If writeObject is used to write an object that has been previously written with writeUnshared, the previous writeUnshared operation is treated as if it were a write of a separate object. In other words, ObjectOutputStream will never generate back-references to object data written by calls to writeUnshared.
While writing an object via writeUnshared does not in itself guarantee a unique reference to the object when it is deserialized, it allows a single object to be defined multiple times in a stream, so that multiple calls to the ObjectInputStream.readUnshared method (see Section 3.1, "The ObjectInputStream Class") by the receiver will not conflict. Note that the rules described above only apply to the base-level object written with writeUnshared, and not to any transitively referenced sub-objects in the object graph to be serialized.

The defaultWriteObject method implements the default serialization mechanism for the current class. This method may be called only from a class's writeObject method. The method writes all of the serializable fields of the current class to the stream. If called from outside the writeObject method, the NotActiveException is thrown.

The putFields method returns a PutField object the caller uses to set the values of the serializable fields in the stream. The fields may be set in any order. After all of the fields have been set, writeFields must be called to write the field values in the canonical order to the stream. If a field is not set, the default value appropriate for its type will be written to the stream. This method may only be called from within the writeObject method of a serializable class. It may not be called more than once or if defaultWriteObject has been called. Only after writeFields has been called can other data be written to the stream.

The reset method resets the stream state to be the same as if it had just been constructed. Reset will discard the state of any objects already written to the stream. The current point in the stream is marked as reset, so the corresponding ObjectInputStream will reset at the same point. Objects previously written to the stream will not be remembered as already having been written to the stream. They will be written to the stream again. This is useful when the contents of an object or objects must be sent again. Reset may not be called while objects are being serialized. If called inappropriately, an IOException is thrown.

Starting with the Java 2 SDK, Standard Edition, v1.3, the writeClassDescriptor method is called when an ObjectStreamClass needs to be serialized. writeClassDescriptor is responsible for writing a representation of the ObjectStreamClass to the serialization stream. Subclasses may override this method to customize the way in which class descriptors are written to the serialization stream. If this method is overridden, then the corresponding readClassDescriptor method in ObjectInputStream should also be overridden to reconstitute the class descriptor from its custom stream representation. By default, writeClassDescriptor writes class descriptors according to the format specified in Section 6.4, "Grammar for the Stream Format". Note that this method will only be called if the ObjectOutputStream is not using the old serialization stream format (see Section 6.3, "Stream Protocol Versions"). If the serialization stream is using the old format (ObjectStreamConstants.PROTOCOL_VERSION_1), the class descriptor will be written internally in a manner that cannot be overridden or customized.

The annotateClass method is called while a Class is being serialized, and after the class descriptor has been written to the stream. Subclasses may extend this method and write other information to the stream about the class. This information must be read by the resolveClass method in a corresponding ObjectInputStream subclass.

An ObjectOutputStream subclass can implement the replaceObject method to monitor or replace objects during serialization. Replacing objects must be enabled explicitly by calling enableReplaceObject before calling writeObject with the first object to be replaced. Once enabled, replaceObject is called for each object just prior to serializing the object for the first time. Note that the replaceObject method is not called for objects of the specially handled classes, Class and ObjectStreamClass. An implementation of a subclass may return a substitute object that will be serialized instead of the original. The substitute object must be serializable. All references in the stream to the original object will be replaced by the substitute object.

When objects are being replaced, the subclass must ensure that the substituted object is compatible with every field where the reference will be stored, or that a complementary substitution will be made during deserialization. Objects, whose type is not a subclass of the type of the field or array element, will later abort the deserialization by raising a ClassCastException and the reference will not be stored.

The enableReplaceObject method can be called by trusted subclasses of ObjectOutputStream to enable the substitution of one object for another during serialization. Replacing objects is disabled until enableReplaceObject is called with a true value. It may thereafter be disabled by setting it to false. The previous setting is returned. The enableReplaceObject method checks that the stream requesting the replacement can be trusted. To ensure that the private state of objects is not unintentionally exposed, only trusted stream subclasses may use replaceObject. Trusted classes are those classes that belong to a security protection domain with permission to enable Serializable substitution.

If the subclass of ObjectOutputStream is not considered part of the system domain, SerializablePermission "enableSubstitution" must be added to the security policy file. AccessControlException is thrown if the protection domain of the subclass of ObjectInputStream does not have permission to "enableSubstitution" by calling enableReplaceObject. See the document Java Security Architecture (JDK1.2) for additional information about the security model.

The writeStreamHeader method writes the magic number and version to the stream. This information must be read by the readStreamHeader method of ObjectInputStream. Subclasses may need to implement this method to identify the stream's unique format.

The flush method is used to empty any buffers being held by the stream and to forward the flush to the underlying stream. The drain method may be used by subclassers to empty only the ObjectOutputStream's buffers without forcing the underlying stream to be flushed.

All of the write methods for primitive types encode their values using a DataOutputStream to put them in the standard stream format. The bytes are buffered into block data records so they can be distinguished from the encoding of objects. This buffering allows primitive data to be skipped if necessary for class versioning. It also allows the stream to be parsed without invoking class-specific methods.

To override the implementation of serialization, the subclass of ObjectOutputStream should call the protected no-arg ObjectOutputStream, constructor. There is a security check within the no-arg constructor for SerializablePermission "enableSubclassImplementation" to ensure that only trusted classes are allowed to override the default implementation. This constructor does not allocate any private data for ObjectOutputStream and sets a flag that indicates that the final writeObject method should invoke the writeObjectOverride method and return. All other ObjectOutputStream methods are not final and can be directly overridden by the subclass.

2.2 The ObjectOutputStream.PutField Class

Class PutField provides the API for setting values of the serializable fields for a class when the class does not use default serialization. Each method puts the specified named value into the stream. An IllegalArgumentException is thrown if name does not match the name of a serializable field for the class whose fields are being written, or if the type of the named field does not match the second parameter type of the specific put method invoked.

2.3 The writeObject Method

For serializable objects, the writeObject method allows a class to control the serialization of its own fields. Here is its signature:

    private void writeObject(ObjectOutputStream stream)
        throws IOException;
Each subclass of a serializable object may define its own writeObject method. If a class does not implement the method, the default serialization provided by defaultWriteObject will be used. When implemented, the class is only responsible for writing its own fields, not those of its supertypes or subtypes.

The class's writeObject method, if implemented, is responsible for saving the state of the class. Either ObjectOutputStream's defaultWriteObject or writeFields method must be called once (and only once) before writing any optional data that will be needed by the corresponding readObject method to restore the state of the object; even if no optional data is written, defaultWriteObject or writeFields must still be invoked once. If defaultWriteObject or writeFields is not invoked once prior to the writing of optional data (if any), then the behavior of instance deserialization is undefined in cases where the ObjectInputStream cannot resolve the class which defined the writeObject method in question.

The responsibility for the format, structure, and versioning of the optional data lies completely with the class.

2.4 The writeExternal Method

Objects implementing java.io.Externalizable must implement the writeExternal method to save the entire state of the object. It must coordinate with its superclasses to save their state. All of the methods of ObjectOutput are available to save the object's primitive typed fields and object fields.

    public void writeExternal(ObjectOutput stream)
        throws IOException;

A new default format for writing Externalizable data has been introduced in JDK 1.2. The new format specifies that primitive data will be written in block data mode by writeExternal methods. Additionally, a tag denoting the end of the External object is appended to the stream after the writeExternal method returns. The benefits of this format change are discussed in Section 3.6, "The readExternal Method." Compatibility issues caused by this change are discussed in Section 2.6, "The useProtocolVersion Method."

2.5 The writeReplace Method

For Serializable and Externalizable classes, the writeReplace method allows a class of an object to nominate its own replacement in the stream before the object is written. By implementing the writeReplace method, a class can directly control the types and instances of its own instances being serialized.

The method is defined as follows:

   ANY-ACCESS-MODIFIER Object writeReplace() {
                 throws ObjectStreamException;

The writeReplace method is called when ObjectOutputStream is preparing to write the object to the stream. The ObjectOutputStream checks whether the class defines the writeReplace method. If the method is defined, the writeReplace method is called to allow the object to designate its replacement in the stream. The object returned should be either of the same type as the object passed in or an object that when read and resolved will result in an object of a type that is compatible with all references to the object. If it is not, a ClassCastException will occur when the type mismatch is discovered.

2.6 The useProtocolVersion Method

Due to a stream protocol change that was not backwards compatible, a mechanism has been added to enable the current Virtual Machine to write a serialization stream that is readable by a previous release. Of course, the problems that are corrected by the new stream format will exist when using the backwards compatible protocol.

Stream protocol versions are discussed in Section 6.3, "Stream Protocol Versions."

CONTENTS | PREV | NEXT
Copyright © 2005, 2010, Oracle and/or its affiliates. All rights reserved.


Java Deployment Overview

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java™ Deployment Overview

Note: This Java deployment guide describes features release d prior to Java SE 6u10.

  • See Java Rich Internet Applications Deployment Advice document for deployment changes introduced in Java SE 6u10.
  • See Java Runtime Environment Installation document for information on the new Java Kernel installer, Java Runtime Environment installation and update.</ li>

Overview

There are two types of deployment technologies available in Java™ Standard Edition (Java SE) for deploying client-side Java applications on the desktop:

  1. Java Plug-in

    Java Plug-in is a tool used for deploying Java applets that run inside a web browser. Supported web browsers include Internet Explorer, Mozilla, and Netscape Navigator. For more information, see Java Plug-in Developer Guide.
  2. Java Web Start

    Java Web Start is a tool used for deploying standalone Java applications on the desktop, using JNLP (Java Network Launching Protocol). For more information, see Java Web Start Developer Guide.

Many similar deployment features between Java Plug-in and Java Web Start have been consolidated. The focus of this guide is to outline common deployment features and general deployment practices for both products.

Installation of the Java Platform

To deploy a Java applet or application, one must first decide how to deploy the JRE (Java Runtime Environment) . The JRE is available in many install formats for download and manual install. An automatic download and install is available for deploying JRE and applications through the browsers on Windows. Enterprise developers or ISVs who would like the JRE to install silently, can use the silent installation option in the installer. For developers and ISVs deploying the Java Platform in Windows-only environments, they should also check out the Active Directory deployment option in the installer.

Writing Java applets and applications

Applets and applications written in the Java Programming language are the main target for deployment. Java Platform, Standard Edition, v 6 API Specification provides the means, along with various compilers and debuggers, to develop applets and applications in the Java Programming language. See Java(TM) Platform, Standard Edition, v 6 API Specification.

If you are migrating applets from Microsoft VM to Sun's Java Virtual Machine, please check out Applet Compatibility, Java Upgrade Guide and System-Wide Repository for tips on the migration.

Deploying Java applets and applications

To deploy applets and applications over the Internet, it is necessary to specify the applets and applications on the web page for download and launch.

For an applet in a web page displayed in a browser using Sun's JVM, the applet must be embedded in the page with the required tagging structure for Java Plug-in. For topics related to Java Plug-in, see the Java Plug-in Developer Guide.

To seamlessly download, cache, and launch an applications from a web page, such a page will need to contain a link to a special Java Network Launch Protocol (JNLP) file on a web server. Java Web Start, which comes with the JRE, will then be able to download, cache, and launch the application. For topics related to JNLP and Java Web Start, see the Java Web Start Developer Guide.

Networking in Java Deployment

Both Java Plug-in and Java Web Start support the deployment of applets and applications over many types of network protocols (e.g. HTTP, HTTPS, FTP, SOCKS) and many types of security authentication (HTTP Basic, Digest, NTLM).

For deployment of the applets and applications behind a proxy server, Java Plug-in and Java Web Start also provide complete proxy support for various configurations from the browser as well as from the Java Control Panel. See Proxy Configuration.

For applets and applications deployed from servers or connecting to servers, Java Plug-in and Java Web Start also provide complete cookie support as a way for servers to store data on the client side. See Cookie.

Although Java Archive (JAR) is the de facto way to package applets and applications, it is not always the most efficient for network download. Two new compression formats are available for deploying Java applets and applications in Java Plug-in and Java Web Start: gzip and Pack200. See Pack200 and Compression.

Security in Java Deployment

By default, Java applets and applications deployed using Java Plug-in and Java Web Start are run in a secure sandbox which defines the set of permissions granted to an untrusted application. See Security.

With JAR signing, Java applets and applications deployed using Java Plug-in and Java Web Start are allowed to run outside the sandbox with additional permissions, if the users grant the permissions to the trusted application. See jarsigner on how to properly sign an application for deployment.

To ensure the signed applets and applications will continue to work after deployment even if the certificate has expired, deployers should consider signature timestamp signing. This is fully supported by Java Plug-in and Java Web Start. See Signature Timestamp.

During signature verification and HTTPS server/client authentication, certificates and keys in the default Java keystore are used by Java Plug-in and Java Web Start. In addition, Java Plug-in and Java Web Start also support certificates and keys in the browser and on the smart card for various purposes. See Browser Keystores.

Configuration in Java Deployment

Under the cover of Java Plug-in and Java Web Start, many aspects of the deployment environment, including security access controls, networking configuration, certificate stores, etc., are configurable through deployment configuration properties.

For developers who would like to customize the deployment environment, the deployment configuration file can be used for customization.

For enterprise developers or ISVs who would like to centrally deploy a configuration to tens of thousands of systems, they can also leverage the enterprise configuration support that is built-into the deployment configuration infrastructure in Java Plug-in and Java Web Start. See Deployment Configuration File and Properties for more details.

For developers or end users who would like to customize a user specific deployment environment in a user-friendly manner, Java Control Panel is a tool that can be used to serve this purpose. See Java Control Panel.

Debugging in Java Deployment

Debugging Java applets and applications is often done through Java IDEs or Java debuggers. In addition, Java Plug-in and Java Web Start have several built-in facilities that make debugging easier, including Java Console, and Tracing and Logging.

Updating the Java Platform

Java Update is a solution for keeping the Java platform up-to-date automatically with latest updates on end users' supported Windows platform. Java Update is bundled with the JRE, so every system with a JRE installed is also Java Update enabled by default. Java Update keeps most systems up-to-date with latest versions of the JRE. Therefore, developers are encouraged to take advantage of the latest JRE features for development, without worrying too much on deploying the latest JRE on their customers systems. For more information, see Java Update.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


UML Sequence diagram shows how a client and a server normally make a TCP
connection with ServerSocket and Socket classes.


UML Sequence diagram show how a datagram packet is sent with
DatagramPacket and DatagramSocket classes.


UML Sequence diagram shows how to open a connection and access a URL with
the URL and URLConnection classes.


Java VisualVM

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java VisualVM - Viewing Application Overview

Java VisualVM presents data for local and remote applications in a tab specific for that application. When you open an application in Java VisualVM, each application opens in a new tab in the main window. You can have multiple application tabs open.

The Overview tab is opened by default when viewing application data for local applications and remote applications.

screenshot of Overview tab

Overview

The Overview tab displays the following general information about the application and the runtime environment.

  • PID. This is the process ID of the application. The process ID is also displayed next to the application node in the Applications window.
  • Host. This is the location of the system that the application is running on.
  • Main class. The class containing the main method.
  • Arguments. Displays any options passed to the application on startup.
  • JVM. This is the JDK version of the JVM software.
  • Java Home. This is the location of the JDK software.
  • JVM flags. This displays any flags used by the JVM software when starting the JDK software.
  • Heap dump on OOME. This displays the status of the Heap Dump on OOME option. When enabled, a heap dump is taken when the application encounters an OutOfMemory exception. You can enabled or disable the option in the application popup menu.

Saved Data

This sub-tab displays application information that Java VisualVM has stored about the application.

JVM Software Arguments.

This sub-tab displays information about arguments passed to the JVM software on application startup.

System Properties

This sub-tab displays information about the system that the JVM software is running on.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java PKCS#11 Reference Guide

1.0 Introduction

2.0 Sun PKCS#11 Provider

2.1 Requirements
2.2 Configuration
2.3 Accessing Network Security Services (NSS)

3.0 Application Developers

3.1 Token Login
3.2 Token Keys
3.3 Delayed Provider Selection
3.4 JAAS KeyStoreLoginModule
3.5 Tokens as JSSE Keystores and Trust Stores

4.0 Tools

4.1 KeyTool and JarSigner
4.2 PolicyTool

5.0 Provider Developers

5.1 Provider Services
5.1.1 Instantiating Engine Classes
5.1.2 Parameter Support

Appendix A Sun PKCS#11 Provider's Supported Algorithms

Appendix B Sun PKCS#11 Provider's KeyStore Restrictions

Appendix C Example Provider

1.0 Introduction

The Java platform defines a set of programming interfaces for performing cryptographic operations. These interfaces are collectively known as the Java Cryptography Architecture (JCA) and the Java Cryptography Extension (JCE). Specifications are available at the Java SE Security Documentation page.

The cryptographic interfaces are provider-based. Specifically, applications talk to Application Programming Interfaces (APIs), and the actual cryptographic operations are performed in configured providers which adhere to a set of Service Provider Interfaces (SPIs). This architecture supports different provider implementations. Some providers may perform cryptographic operations in software; others may perform the operations on a hardware token (for example, on a smartcard device or on a hardware cryptographic accelerator).

The Cryptographic Token Interface Standard, PKCS#11, is produced by RSA Security and defines native programming interfaces to cryptographic tokens, such as hardware cryptographic accelerators and Smartcards. To facilitate the integration of native PKCS#11 tokens into the Java platform, a new cryptographic provider, the Sun PKCS#11 provider, has been introduced into the J2SE 5.0 release. This new provider enables existing applications written to the JCA and JCE APIs to access native PKCS#11 tokens. No modifications to the application are required. The only requirement is the proper configuration of the provider into the Java Runtime.

Although an application can make use of most PKCS#11 features using existing APIs, some applications might need more flexibility and capabilities. For example, an application might want to deal with Smartcards being removed and inserted dynamically more easily. Or, a PKCS#11 token might require authentication for some non-key-related operations and therefore, the application must be able to log into the token without using keystore. In J2SE 5.0, the JCA was enhanced to allow applications greater flexibility in dealing with different providers.

This document describes how native PKCS#11 tokens can be configured into the Java platform for use by Java applications. It also describes the enhancements that were made to the JCA to make it easier for applications to deal with different types of providers, including PKCS#11 providers.

2.0 Sun PKCS#11 Provider

The Sun PKCS#11 provider, in contrast to most other providers, does not implement cryptographic algorithms itself. Instead, it acts as a bridge between the Java JCA and JCE APIs and the native PKCS#11 cryptographic API, translating the calls and conventions between the two. This means that Java applications calling standard JCA and JCE APIs can, without modification, take advantage of algorithms offered by the underlying PKCS#11 implementations, such as, for example,

  • Cryptographic Smartcards,
  • Hardware cryptographic accelerators, and
  • High performance software implementations.
Note that Java SE only facilitates accessing native PKCS#11 implementations, it does not itself include a native PKCS#11 implementation. However, cryptographic devices such as Smartcards and hardware accelerators often come with software that includes a PKCS#11 implementation, which you need to install and configure according to manufacturer's instructions.

2.1 Requirements

The Sun PKCS#11 provider is supported on Solaris (SPARC and x86) and Linux (x86) in both 32-bit and 64-bit Java processes. It is also supported on 32-bit Windows (x86) but not currently on 64-bit Windows platforms due to the lack of suitable PKCS#11 libraries.

The Sun PKCS#11 provider requires an implementation of PKCS#11 v2.0 or later to be installed on the system. This implementation must take the form of a shared-object library (.so on Solaris and Linux) or dynamic-link library (.dll on Windows). Please consult your vendor documentation to find out if your cryptographic device includes such a PKCS#11 implementation, how to configure it, and what the name of the library file is.

The Sun PKCS#11 provider supports a number of algorithms, provided that the underlying PKCS#11 implementation offers them. The algorithms and their corresponding PKCS#11 mechanisms are listed in the table in Appendix A.

2.2 Configuration

The Sun PKCS#11 provider is implemented by the main class sun.security.pkcs11.SunPKCS11 and accepts the full pathname of a configuration file as an argument. To use the provider, you must first install it by using the Java Cryptography Architecture (JCA). As with all JCA providers, installation of the provider can be done either statically or programmatically. To install the provider statically, add the provider to the Java Security properties file ($JAVA_HOME/lib/security/java.security). For example, here's a fragment of the java.security file that installs the Sun PKCS#11 provider with the configuration file /opt/bar/cfg/pkcs11.cfg.
# configuration for security providers 1-6 ommitted
security.provider.7=sun.security.pkcs11.SunPKCS11 /opt/bar/cfg/pkcs11.cfg
To install the provider dynamically, create an instance of the provider with the appropriate configuration filename and then install it. Here is an example.
String configName = "/opt/bar/cfg/pkcs11.cfg";
Provider p = new sun.security.pkcs11.SunPKCS11(configName);
Security.addProvider(p);

To use more than one slot per PKCS#11 implementation, or to use more than one PKCS#11 implementation, simply repeat the installation for each with the appropriate configuration file. This will result in a Sun PKCS#11 provider instance for each slot of each PKCS#11 implementation.

The configuration file is a text file that contains entries in the following format.

attribute = value The valid values for attribute and value are described in the table in this section. The two mandatory attributes are name and library. Here is a sample configuration file.
name = FooAccelerator
library = /opt/foo/lib/libpkcs11.so
Comments are denoted by lines starting with the # (number) symbol.

Attribute | Value | Description
library | pathname of PKCS#11 implementation | This is the full pathname (including extension) of the PKCS#11 implementation; the format of the pathname is platform dependent. For example, /opt/foo/lib/libpkcs11.so might be the pathname of a PKCS#11 implementation on Solaris and Linux while C:\foo\mypkcs11.dll might be one on Windows.
name | name suffix of this provider instance | This string is concatenated with the prefix SunPKCS11- to produce this provider instance's name (that is, the string returned by its Provider.getName() method). For example, if the name attribute is "FooAccelerator", then the provider instance's name will be "SunPKCS11-FooAccelerator".
description | description of this provider instance | This string will be returned by the provider instance's Provider.getInfo() method. If none is specified, a default description will be returned.
slot | slot id | This is the id of the slot that this provider instance is to be associated with. For example, you would use 1 for the slot with the id 1 under PKCS#11. At most one of slot or slotListIndex may be specified. If neither is specified, the default is a slotListIndex of 0.
slotListIndex | slot index | This is the slot index that this provider instance is to be associated with. It is the index into the list of all slots returned by the PKCS#11 function C_GetSlotList. For example, 0 indicates the first slot in the list. At most one of slot or slotListIndex may be specified. If neither is specified, the default is a slotListIndex of 0.
enabledMechanisms brace enclosed, whitespace-separated list of PKCS#11 mechanisms to enable This is the list PKCS#11 mechanisms that this provider instance should use, provided that they are supported by both the Sun PKCS#11 provider and PKCS#11 token. All other mechanisms will be ignored. Each entry in the list is the name of a PKCS#11 mechanism. Here is an example that lists two PKCS#11 mechanisms.
enabledMechanisms = {
  CKM_RSA_PKCS
  CKM_RSA_PKCS_KEY_PAIR_GEN
}
At most one of enabledMechanisms or disabledMechanisms may be specified. If neither is specified, the mechanisms enabled are those that are supported by both the Sun PKCS#11 provider and the PKCS#11 token.
disabledMechanisms brace enclosed, whitespace-separated list of PKCS#11 mechanisms to disable This is the list of PKCS#11 mechanism that this provider instance should ignore. Any mechanism listed will be ignored by the provider, even if they are supported by the token and the Sun PKCS#11 provider. The strings SecureRandom and KeyStore may be specified to disable those services.

At most one of enabledMechanisms or disabledMechanisms may be specified. If neither is specified, the mechanisms enabled are those that are supported by both the Sun PKCS#11 provider and the PKCS#11 token.
attributes | see below | The attributes option can be used to specify additional PKCS#11 that should be set when creating PKCS#11 key objects. This makes it possible to accomodate tokens that require particular attributes. For details, see the section below.

Attributes Configuration

The attributes option allows you to specify additional PKCS#11 attributes that should be set when creating PKCS#11 key objects. By default, the SunPKCS11 provider only specifies mandatory PKCS#11 attributes when creating objects. For example, for RSA public keys it specifies the key type and algorithm (CKA_CLASS and CKA_KEY_TYPE) and the key values for RSA public keys (CKA_MODULUS and CKA_PUBLIC_EXPONENT). The PKCS#11 library you are using will assign implementation specific default values to the other attributes of an RSA public key, for example that the key can be used to encrypt and verify messages (CKA_ENCRYPT and CKA_VERIFY = true).

The attributes option can be used if you do not like the default values your PKCS#11 implementation assigns or if your PKCS#11 implementation does not support defaults and requires a value to be specified explicitly. Note that specifying attributes that your PKCS#11 implementation does not support or that are invalid for the type of key in question may cause the operation to fail at runtime.

The option can be specified zero or more times, the options are processed in the order specified in the configuration file as described below. The attributes option has the format:

attributes(operation, keytype, keyalgorithm) = {
  name1 = value1
  [...]
}
Valid values for operation are:
  • generate, for keys generated via a KeyPairGenerator or KeyGenerator
  • import, for keys created via a KeyFactory or SecretKeyFactory. This also applies to Java software keys automatically converted to PKCS#11 key objects when they are passed to the initialization method of a cryptographic operation, for example Signature.initSign().
  • *, for keys created using either a generate or a create operation.
Valid values for keytype are CKO_PUBLIC_KEY, CKO_PRIVATE_KEY, and CKO_SECRET_KEY, for public, private, and secret keys, respectively, and * to match any type of key.

Valid values for keyalgorithm are one of the CKK_xxx constants from the PKCS#11 specification, or * to match keys of any algorithm. The algorithms currently supported by the SunPKCS11 provider are CKK_RSA, CKK_DSA, CKK_DH, CKK_AES, CKK_DES, CKK_DES3, CKK_RC4, CKK_BLOWFISH, and CKK_GENERIC.

The attribute names and values are specified as a list of one or more name-value pairs. name must be a CKA_xxx constant from the PKCS#11 specification, for example CKA_SENSITIVE. value can be one of the following:

  • a boolean value, true or false
  • an integer, in decimal form (default) or in hexadecimal form if it begins with 0x.
  • null, indicating that this attribute should not be specified when creating objects.
If the attributes option is specified multiple times, the entries are processed in the order specified with the attributes aggregated and later attributes overriding earlier ones. For example, consider the following configuration file excerpt:
attributes(*,CKO_PRIVATE_KEY,*) = {
  CKA_SIGN = true
}

attributes(*,CKO_PRIVATE_KEY,CKK_DH) = {
  CKA_SIGN = null
}

attributes(*,CKO_PRIVATE_KEY,CKK_RSA) = {
  CKA_DECRYPT = true
}
The first entry says to specify CKA_SIGN = true for all private keys. The second option overrides that with null for Diffie-Hellman private keys, so the CKA_SIGN attribute will not specified for them at all. Finally, the third option says to also specify CKA_DECRYPT = true for RSA private keys. That means RSA private keys will have both CKA_SIGN = true and CKA_DECRYPT = true set.

There is also a special form of the attributes option. You can write attributes = compatibility in the configuration file. That is a shortcut for a whole set of attribute statements. They are designed to provider maximum compatibility with existing Java applications, which may expect, for example, all key components to be accessible and secret keys to be useable for both encryption and decryption. The compatibility attributes line can be used together with other attributes lines, in which case the same aggregation and overriding rules apply as described earlier.

2.3 Accessing Network Security Services (NSS)

Network Security Services (NSS) is a set of open source security libraries used by the Mozilla/Firefox browsers, Sun's Java Enterprise System server software, and a number of other products. Its crypto APIs are based on PKCS#11 but it includes special features that are outside of the PKCS#11 standard. The Sun PKCS#11 provider includes code to interact with these NSS specific features, including several NSS specific configuration directives, which are described below.

For best results, we recommend that you use the latest version of NSS available. It should be at least version 3.11.1.

The Sun PKCS#11 provider uses NSS specific code when any of the nss configuration directives described below are used. In that case, the regular configuration commands library, slot, and slotListIndex cannot be used.

Attribute | Value | Description
nssLibraryDirectory directory containing the NSS and NSPR libraries This is the full pathname of the directory containing the NSS and NSPR libraries. It must be specified unless NSS has already been loaded and initialized by another component running in the same process as the Java VM.

Depending on your platform, you may have to set LD_LIBRARY_PATH or PATH (on Windows) to include this directory in order to allow the operating system to locate the dependent libraries.
nssSecmodDirectory | directory containing the NSS DB files | The full pathname of the directory containing the NSS configuration and key information (secmod.db, key3.db, and cert8.db). This directive must be specified unless NSS has already been initialized by another component (see above) or NSS is used without database files as described below.
nssDbMode one of readWrite, readOnly, and noDb This directives determines how the NSS database is accessed. In read-write mode, full access is possible but only one process at a time should be accessing the databases. Read-only mode disallows modifications to the files.

The noDb mode allows NSS to be used without database files purely as a cryptographic provider. It is not possible to create persistent keys using the PKCS11 KeyStore. This mode is useful because NSS includes highly optimized implementations and algorithms not currently available in Sun's bundled Java based crypto providers, for example Elliptic Curve Cryptography (ECC).
nssModule one of keystore, crypto, fips, and trustanchors NSS makes its functionality available using several different libraries and slots. This directive determines which of these modules is accessed by this instance of SunPKCS11.

The crypto module is the default in noDb mode. It supports crypto operations without login but no persistent keys.

The fips module is the default if the NSS secmod.db has been set to FIPS-140 compliant mode. In this mode, NSS restricts the available algorithms and the PKCS#11 attributes with which keys can be created.

The keystore module is the default in other configurations. It supports persistent keys using the PKCS11 KeyStore, which are stored in the NSS DB files. This module requires login.

The trustanchors module enables access to NSS trust anchor certificates via the PKCS11 KeyStore, if secmod.db has been configured to include the trust anchor library.

Example SunPKCS11 configuration files for NSS

NSS as a pure cryptography provider
name = NSScrypto
nssLibraryDirectory = /opt/tests/nss/lib
nssDbMode = noDb
attributes = compatibility
NSS as a FIPS 140 compliant crypto token:
name = NSSfips
nssLibraryDirectory = /opt/tests/nss/lib
nssSecmodDirectory = /opt/tests/nss/fipsdb
nssModule = fips

3.0 Application Developers

Java applications can use the existing JCA and JCE APIs to access PKCS#11 tokens via the Sun PKCS#11 provider. This is sufficient for many applications but it might be difficult for an application to deal with certain PKCS#11 features, such as unextractable keys and dynamically changing Smartcards. Consequently, a number of enhancements were made to the APIs to better support applications using certain PKCS#11 features. These enhancments are discussed in this section.

3.1 Token Login

Certain PKCS#11 operations, such as accessing private keys, require a login using a Personal Identification Number, or PIN, before the operations can proceed. The most common type of operations that require login are those that deal with keys on the token. In a Java application, such operations often involve first loading the keystore. When accessing the PKCS#11 token as a keystore via the java.security.KeyStore class, you can supply the PIN in the password input parameter to the load method, similar to how applications initialize a keystore prior to J2SE 5.0. The PIN will then be used by the Sun PKCS#11 provider for logging into the token. Here is an example.

char[] pin = ...;
KeyStore ks = KeyStore.getInstance("PKCS11");
ks.load(null, pin);

This is fine for an application that treats PKCS#11 tokens as static keystores. For an application that wants to accommodate PKCS#11 tokens more dynamically, such as Smartcards being inserted and removed, you can use the new KeyStore.Builder class. Here is an example of how to initialize the builder for a PKCS#11 keystore with a callback handler.

KeyStore.CallbackHandlerProtection chp =
    new KeyStore.CallbackHandlerProtection(new MyGuiCallbackHandler());
KeyStore.Builder builder =
    KeyStore.Builder.newInstance("PKCS11", null, chp);

For the Sun PKCS#11 provider, the callback handler must be able to satisfy a PasswordCallback, which is used to prompt the user for the PIN. Whenever the application needs access to the keystore, it uses the builder as follows.

KeyStore ks = builder.getKeyStore();
Key key = ks.getKey(alias, null);

The builder will prompt for a password as needed using the previously configured callback handler. The builder will prompt for a password only for the initial access. If the user of the application continues using the same Smartcard, the user will not be prompted again. If the user removes and inserts a different SmartCard, the builder will prompt for a password for the new card.

Depending on the PKCS#11 token, there may be non-key-related operations that also require token login. Applications that use such operations can use the newly introduced java.security.AuthProvider class. The AuthProvider class extends from java.security.Provider and defines methods to perform login and logout operations on a provider, as well as to set a callback handler for the provider to use.

For the Sun PKCS#11 provider, the callback handler must be able to satisfy a PasswordCallback, which is used to prompt the user for the PIN.

Here is an example of how an application might use an AuthProvider to log into the token.

AuthProvider aprov = (AuthProvider)Security.getProvider("SunPKCS11");
aprov.login(subject, new MyGuiCallbackHandler());

3.2 Token Keys

Java Key objects may or may not contain actual key material.

  • A software Key object does contain the actual key material and allows access to that material.
  • An unextractable key on a secure token (such as a Smartcard) is represented by a Java Key object that does not contain the actual key material. The Key object only contains a reference to the actual key.

Applications and providers must use the correct interfaces to represent these different types of Key objects. Software Key objects (or any Key object that has access to the actual key material) should implement the interfaces in the java.security.interfaces and javax.crypto.interfaces packages (such as DSAPrivateKey). Key objects representing unextractable token keys should only implement the relevant generic interfaces in the java.security and javax.crypto packages (PrivateKey, PublicKey, or SecretKey). Identification of the algorithm of a key should be performed using the Key.getAlgorithm() method.

Applications should note that a Key object for an unextractable token key can only be used by the provider associated with that token.

3.3 Delayed Provider Selection

Prior to J2SE 5.0, the Java cryptography getInstance() methods, such as Cipher.getInstance("DES"), returned the implementation from the first provider that implemented the requested algorithm. This is problematic if an application attempts to use a Key object for an unextractable token key with a provider that only accepts software key objects. In such a case, the provider would throw an InvalidKeyException. This is an issue for the Cipher, KeyAgreement, Mac, and Signature classes.

J2SE 5.0, addresses this issue by delaying the selection of the provider until the relevant initialization method is called. The initialization method accepts a Key object and can determine at that point which provider can accept the specified Key object. This ensures that the selected provider can use the specified Key object. The following represents the affected initialization methods.

  • Cipher.init(..., Key key, ...)
  • KeyAgreement.init(Key key, ...)
  • Mac.init(Key key, ...)
  • Signature.initSign(PrivateKey privateKey)
Furthermore, if an application calls the initialization method multiple times (each time with a different key, for example), the proper provider for the given key is selected each time. In other words, a different provider may be selected for each initialization call.

Although this delayed provider selection is hidden from the application, it does affect the behavior of the getProvider() method for Cipher, KeyAgreement, Mac, and Signature. If getProvider() is called before the initialization operation has occurred (and therefore before provider selection has occurred), then the first provider that supports the requested algorithm is returned. This may not be the same provider as the one selected after the initialization method is called. If getProvider() is called after the initialization operation has occurred, then the actual selected provider is returned. It is recommended that applications only call getProvider() after they have called the relevant initialization method.

In addition to getProvider(), the following additional methods are similarly affected.

  • Cipher.getBlockSize
  • Cipher.getExcemptionMechanism
  • Cipher.getIV
  • Cipher.getOutputSize
  • Cipher.getParameters
  • Mac.getMacLength
  • Signature.getParameters
  • Signature.setParameter

3.4 JAAS KeyStoreLoginModule

Java SE comes with a JAAS keystore login module, KeyStoreLoginModule that allows an application to authenticate using its identity in a specified keystore. After authentication, the application would have acquire its principal and credentials information (certificate and private key) from the keystore. By using this login module and configuring it to use a PKCS#11 token as a keystore, the application can acquire this information from a PKCS#11 token.

Use the following options to configure the KeyStoreLoginModule to use a PKCS#11 token as the keystore.

  • keyStoreURL="NONE"
  • keyStoreType="PKCS11"
  • keyStorePasswordURL=some_pin_url
where some_pin_url is the location of the PIN. If the keyStorePasswordURL option is omitted, then the login module will get the PIN via the application's callback handler, supplying it with a PasswordCallback. Here is an example of a configuration file that uses a PKCS#11 token as a keystore.
other {
    com.sun.security.auth.module.KeyStoreLoginModule required
        keyStoreURL="NONE"
  keyStoreType="PKCS11"
  keyStorePasswordURL="file:/home/joe/scpin";
};

If more than one Sun PKCS#11 provider has been configured dynamically or in the java.security security properties file, you can use the keyStoreProvider option to target a specific provider instance. The argument to this option is the name of the provider. For the Sun PKCS#11 provider, the provider name is of the form SunPKCS11-TokenName, where TokenName is the name suffix that the provider instance has been configured with, as detailed in the configuration attributes table. For example, the following configuration file names the PKCS#11 provider instance with name suffix SmartCard.

other {
    com.sun.security.auth.module.KeyStoreLoginModule required
        keyStoreURL="NONE"
  keyStoreType="PKCS11"
  keyStorePasswordURL="file:/home/joe/scpin"
  keyStoreProvider="SunPKCS11-SmartCard";
};

Some PKCS#11 tokens support login via a protected authentication path. For example, a Smartcard may have a dedicated PIN-pad to enter the pin. Biometric devices will also have their own means to obtain authentication information. If the PKCS#11 token has a protected authentication path, then use the protected=true option and omit the keyStorePasswordURL option. Here is an example of a configuration file for such a token.

other {
    com.sun.security.auth.module.KeyStoreLoginModule required
        keyStoreURL="NONE"
  keyStoreType="PKCS11"
  protected=true;
};

3.5 Tokens as JSSE Keystore and Trust Stores

To use PKCS#11 tokens as JSSE keystores or trust stores, the JSSE application can use the APIs described previously to instantiate a KeyStore that is backed by a PKCS#11 token and pass it to its key manager and trust manager. The JSSE application will then have access to the keys on the token.

JSSE also supports configuring the use of keystores and trust stores via system properties, as described in the JSSE Reference Guide. To use a PKCS#11 token as a keystore or trust store, set the javax.net.ssl.keyStoreType and javax.net.ssl.trustStoreType system properties, respectively, to "PKCS11", and set the javax.net.ssl.keyStore and javax.net.ssl.trustStore system properties, respectively, to NONE. To specify the use of a specific provider instance, use the javax.net.ssl.keyStoreProvider and javax.net.ssl.trustStoreProvider system properties (e.g., "SunPKCS11-SmartCard").

4.0 Tools

In J2SE 5.0, the security tools were updated to support operations using the new Sun PKCS#11 provider. The changes are discussed below.

4.1 KeyTool and JarSigner

If the Sun PKCS#11 provider has been configured in the java.security security properties file (located in the $JAVA_HOME/lib/security directory of the Java runtime), then keytool and jarsigner can be used to operate on the PKCS#11 token by specifying the following options.

  • -keystore NONE
  • -storetype PKCS11
Here an example of a command to list the contents of the configured PKCS#11 token.
keytool -keystore NONE -storetype PKCS11 -list
The PIN can be specified using the -storepass option. If none has been specified, then keytool and jarsigner will prompt for the token PIN. If the token has a protected authentication path (such as a dedicated PIN-pad or a biometric reader), then the -protected option must be specified, and no password options can be specified.

If more than one Sun PKCS#11 provider has been configured in the java.security security properties file, you can use the -providerName option to target a specific provider instance. The argument to this option is the name of the provider.

  • -providerName providerName
For the Sun PKCS#11 provider, providerName is of the form SunPKCS11-TokenName, where TokenName is the name suffix that the provider instance has been configured with, as detailed in the configuration attributes table. For example, the following command lists the contents of the PKCS#11 keystore provider instance with name suffix SmartCard.
keytool -keystore NONE -storetype PKCS11 \
        -providerName SunPKCS11-SmartCard \
        -list

If the Sun PKCS#11 provider has not been configured in the java.security security properties file, you can use the following options to instruct keytool and jarsigner to install the provider dynamically.

  • -providerClass sun.security.pkcs11.SunPKCS11
  • -providerArg ConfigFilePath
ConfigFilePath is the path to the token configuration file. Here is an example of a command to list a PKCS#11 keystore when the Sun PKCS#11 provider has not been configured in the java.security file.
keytool -keystore NONE -storetype PKCS11 \
        -providerClass sun.security.pkcs11.SunPKCS11 \
        -providerArg /foo/bar/token.config \
        -list

4.2 PolicyTool

Prior to J2SE 5.0, the keystore entry in the default policy implementation had the following syntax.

keystore "some_keystore_url", "keystore_type";
This syntax was inadequate for accessing a PKCS#11 keystore because such access usually required a PIN, and there might be multiple PKCS#11 provider instances. To accommodate these requirements, the keystore entry syntax has been updated in J2SE 5.0, to the following.
keystore "some_keystore_url", "keystore_type", "keystore_provider";
keystorePasswordURL "some_password_url";
Where keystore_provider is the keystore provider name (for example, "SunPKCS11-SmartCard"), and some_password_url is a URL pointing to the location of the token PIN. Both keystore_provider and the keystorePasswordURL line are optional. If keystore_provider has not been specified, then the first configured provider that supports the specified keystore type is used. If the keystorePasswordURL line has not been specified, then no password is used.

The following is an example keystore policy entry for a PKCS#11 token.

keystore "NONE", "PKCS11", "SunPKCS11-SmartCard";
keystorePasswordURL "file:/foo/bar/passwordFile";

5.0 Provider Developers

J2SE 5.0 introduces new facilities in the java.security.Provider class for provider implementations to more easily support PKCS#11 tokens and cryptographic services in general. These new facilities are discussed below.

See Appendix C for an example of a simple provider designed to demonstrate the new facilties.

5.1 Provider Services

As described in the above provider documentation, prior to J2SE 5.0, providers were required to create java.util.Property entries describing the services they supported. For each service implemented by the provider, there must be a property whose name is the type of service (Cipher, Signature, etc), followed by a period and the name of the algorithm to which the service applies. The property value must specify the fully qualified name of the class implementing the service. Here is an example of a provider setting KeyAgreement.DiffieHellman property to have the value com.sun.crypto.provider.DHKeyAgreement.

put("KeyAgreement.DiffieHellman",
      "com.sun.crypto.provider.DHKeyAgreement")

J2SE 5.0 introduces a new public static nested class, Provider.Service, to help better encapsulate the properties of a provider service (including its type, attributes, algorithm name, and algorithm aliases). Providers can instantiate Provider.Service objects and register them by calling the Provider.putService() method. This is equivalent to creating a Property entry and calling the Provider.put() method (as was done prior to J2SE 5.0). Note that legacy Property entries registered via Provider.put are still supported.

Here is an example of a provider creating a Service object with the KeyAgreement type, for the DiffieHellman algorithm, implemented by the class com.sun.crypto.provider.DHKeyAgreement.

Service s = new Service(this, "KeyAgreement", "DiffieHellman",
    "com.sun.crypto.provider.DHKeyAgreement", null, null);
putService(s);

Using Provider.Servicee objects instead of legacy Property entries has a couple of major benefits. One benefit is that it allows the provider to have greater flexibility when instantiating engine classes. Another benefit is that it allows the provider to test parameter validity. These features are discussed in detail next.

5.1.1 Instantiating Engine Classes

Prior to J2SE 5.0, the Java Cryptography framework looked up the provider property for a particular service and directly instantiated the engine class registered for that property. J2SE 5.0, has the same behavior by default, but allows the provider to override this behavior and instantiate the engine class for the requested service itself.

To override the default behavior, the provider overrides the Provider.Service.newInstance() method to add its customer behavior. For example, the provider might call a custom constructor, or might perform initialization using information not accessible outside the provider (or that are only known by the provider).

5.1.2 Parameter Support

The Java Cryptography framework may attempt a fast check to determine whether a provider's service implementation can use an application-specified parameter. To perform this fast check, the framework calls Provider.Service.supportsParameter().

In J2SE 5.0, the framework relies on this fast test during delayed provider selection. When an application invokes an initialization method and passes it a Key object, the framework asks an underlying provider whether it supports the object by calling its Service.supportsParameter() method. If supportsParameter() returns false, the framework can immediately remove that provider from consideration. If supportsParameter() returns true, the framework passes the Key object to that provider's initialization engine class implementation. A provider that requires software Key objects should override this method to return false when it is passed non-software keys. Likewise, a provider for a PKCS#11 token that contains unextractable keys should only return true for Key objects that it created, and which therefore correspond to the Keys on its respective token.

Note that the default implementation of supportsParameter() returns true. This allows existing providers to work without modification. However, because of this lenient default implementation, the framework must be prepared to catch exceptions thrown by providers that reject the Key object inside their initialization engine class implementations. The framework treats these cases the same as when supportsParameter() returns false.

Appendix A: Sun PKCS#11 Provider's Supported Algorithms

The following table lists the Java algorithms supported by the Sun PKCS#11 provider and corresponding PKCS#11 mechanisms needed to support them. When multiple mechanisms are listed, they are given in the order of preference and any one of them is sufficent. Note that SunPKCS11 can be instructed to ignore mechanisms by using the disabledMechanisms and enabledMechanisms configuration directives.

For Elliptic Curve mechanisms, SunPKCS11 will only use keys that use the namedCurve choice as encoding for the parameters and only allow the uncompressed point format. The Sun PKCS#11 provider assumes that a token supports all standard named domain parameters.

Java Algorithm | PKCS#11 Mechanisms
Signature.MD2withRSA | CKM_MD2_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509
Signature.MD5withRSA | CKM_MD5_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509
Signature.SHA1withRSA | CKM_SHA1_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509
Signature.SHA256withRSA | CKM_SHA256_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509
Signature.SHA384withRSA | CKM_SHA384_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509
Signature.SHA512withRSA | CKM_SHA512_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509
Signature.SHA1withDSA | CKM_DSA_SHA1, CKM_DSA
Signature.NONEwithDSA | CKM_DSA
Signature.SHA1withECDSA | CKM_ECDSA_SHA1, CKM_ECDSA
Signature.SHA256withECDSA | CKM_ECDSA
Signature.SHA384withECDSA | CKM_ECDSA
Signature.SHA512withECDSA | CKM_ECDSA
Signature.NONEwithECDSA | CKM_ECDSA
Cipher.RSA/ECB/PKCS1Padding | CKM_RSA_PKCS
Cipher.ARCFOUR | CKM_RC4
Cipher.DES/CBC/NoPadding | CKM_DES_CBC
Cipher.DESede/CBC/NoPadding | CKM_DES3_CBC
Cipher.AES/CBC/NoPadding | CKM_AES_CBC
Cipher.Blowfish/CBC/NoPadding | CKM_BLOWFISH_CBC
Cipher.RSA/ECB/NoPadding | CKM_RSA_X_509
Cipher.AES/CTR/NoPadding | CKM_AES_CTR
KeyAgreement.ECDH | CKM_ECDH1_DERIVE
KeyAgreement.DiffieHellman | CKM_DH_PKCS_DERIVE
KeyPairGenerator.RSA | CKM_RSA_PKCS_KEY_PAIR_GEN
KeyPairGenerator.DSA | CKM_DSA_KEY_PAIR_GEN
KeyPairGenerator.EC | CKM_EC_KEY_PAIR_GEN
KeyPairGenerator.DiffieHellman | CKM_DH_PKCS_KEY_PAIR_GEN
KeyGenerator.ARCFOUR | CKM_RC4_KEY_GEN
KeyGenerator.DES | CKM_DES_KEY_GEN
KeyGenerator.DESede | CKM_DES3_KEY_GEN
KeyGenerator.AES | CKM_AES_KEY_GEN
KeyGenerator.Blowfish | CKM_BLOWFISH_KEY_GEN
Mac.HmacMD5 | CKM_MD5_HMAC
Mac.HmacSHA1 | CKM_SHA_1_HMAC
Mac.HmacSHA256 | CKM_SHA256_HMAC
Mac.HmacSHA384 | CKM_SHA384_HMAC
Mac.HmacSHA512 | CKM_SHA512_HMAC
MessageDigest.MD2 | CKM_MD2
MessageDigest.MD5 | CKM_MD5
MessageDigest.SHA1 | CKM_SHA_1
MessageDigest.SHA-256 | CKM_SHA256
MessageDigest.SHA-384 | CKM_SHA384
MessageDigest.SHA-512 | CKM_SHA512
KeyFactory.RSA | Any supported RSA mechanism
KeyFactory.DSA | Any supported DSA mechanism
KeyFactory.EC | Any supported EC mechanism
KeyFactory.DiffieHellman | Any supported Diffie-Hellman mechanism
SecretKeyFactory.ARCFOUR | CKM_RC4
SecretKeyFactory.DES | CKM_DES_CBC
SecretKeyFactory.DESede | CKM_DES3_CBC
SecretKeyFactory.AES | CKM_AES_CBC
SecretKeyFactory.Blowfish | CKM_BLOWFISH_CBC
SecureRandom.PKCS11 | CK_TOKEN_INFO has the CKF_RNG bit set
KeyStore.PKCS11 | Always available

Appendix B: Sun PKCS#11 provider's KeyStore Requirements

The following describes the requirements placed by the Sun PKCS#11 Provider's KeyStore implementation on the underlying native PKCS#11 library. Note that changes may be made in future releases to maximize interoperability with as many existing PKCS#11 libraries as possible.

Read-Only Access

To map existing objects stored on a PKCS#11 token to KeyStore entries, the Sun PKCS#11 Provider's KeyStore implementation performs the following operations.

  1. A search for all private key objects on the token is performed by calling C_FindObjects[Init|Final]. The search template includes the following attributes:
    • CKA_TOKEN = true
    • CKA_CLASS = CKO_PRIVATE_KEY
  2. A search for all certificate objects on the token is performed by calling C_FindObjects[Init|Final]. The search template includes the following attributes:
    • CKA_TOKEN = true
    • CKA_CLASS = CKO_CERTIFICATE
  3. Each private key object is matched with its corresponding certificate by retrieving their respective CKA_ID attributes. A matching pair must share the same unique CKA_ID.

    For each matching pair, the certificate chain is built by following the issuer->subject path. From the end entity certificate, a call fo C_FindObjects[Init|Final] is made with a search template that includes the following attributes:

    • CKA_TOKEN = true
    • CKA_CLASS = CKO_CERTIFICATE
    • CKA_SUBJECT = [DN of certificate issuer]

    This search is continued until either no certificate for the issuer is found, or until a self-signed certificate is found. If more than one certificate is found the first one is used.

    Once a private key and certificate have been matched (and its certificate chain built), the information is stored in a private key entry with the CKA_LABEL value from end entity certificate as the KeyStore alias.

    If the end entity certificate has no CKA_LABEL, then the alias is derived from the CKA_ID. If the CKA_ID can be determined to consist exclusively of printable characters, then a String alias is created by decoding the CKA_ID bytes using the UTF-8 charset. Otherwise, a hex String alias is created from the CKA_ID bytes ("0xFFFF...", for example).

    If multiple certificates share the same CKA_LABEL, then the alias is derived from the CKA_LABEL plus the end entity certificate issuer and serial number ("MyCert/CN=foobar/1234", for example).

  4. Each certificate not part of a private key entry (as the end entity certificate) is checked whether it is trusted. If the CKA_TRUSTED attribute is true, then a KeyStore trusted certificate entry is created with the CKA_LABEL value as the KeyStore alias. If the certificate has no CKA_LABEL, or if multiple certificates share the same CKA_LABEL, then the alias is derived as described above.

    If the CKA_TRUSTED attribute is not supported then no trusted certificate entries are created.

  5. Any private key or certificate object not part of a private key entry or trusted certificate entry is ignored.
  6. A search for all secret key objects on the token is performed by calling C_FindObjects[Init|Final]. The search template includes the following attributes:
    • CKA_TOKEN = true
    • CKA_CLASS = CKO_SECRET_KEY

    A KeyStore secret key entry is created for each secret key object, with the CKA_LABEL value as the KeyStore alias. Each secret key object must have a unique CKA_LABEL.

Write Access

To create new KeyStore entries on a PKCS#11 token to KeyStore entries, the Sun PKCS#11 Provider's KeyStore implementation performs the following operations.

  1. When creating a KeyStore entry (during KeyStore.setEntry, for example), C_CreateObject is called with CKA_TOKEN=true to create token objects for the respective entry contents.

    Private key objects are stored with CKA_PRIVATE=true. The KeyStore alias (UTF8-encoded) is set as the CKA_ID for both the private key and the corresponding end entity certificate. The KeyStore alias is also set as the CKA_LABEL for the end entity certificate object.

    Each certificate in a private key entry's chain is also stored. The CKA_LABEL is not set for CA certificates. If a CA certificate is already in the token, a duplicate is not stored.

    Secret key objects are stored with CKA_PRIVATE=true. The KeyStore alias is set as the CKA_LABEL.

  2. If an attempt is made to convert a session object to a token object (for example, if KeyStore.setEntry is called and the private key object in the specified entry is a session ojbect), then C_CopyObject is called with CKA_TOKEN=true.
  3. If multiple certificates in the token are found to share the same CKA_LABEL, then the write capabilities to the token are disabled.
  4. Since the PKCS#11 specification does not allow regular applications to set CKA_TRUSTED=true (only token initialization applications may do so), trusted certificate entries can not be created.

Miscellaneous

In addition to the searches listed above, the following searches may be used by the Sun PKCS#11 provider's KeyStore implementation to perform internal functions. Specifically, C_FindObjects[Init|Final] may be called with any of the following attribute templates:

  •     CKA_TOKEN    true
    CKA_CLASS    CKO_CERTIFICATE
    CKA_SUBJECT  [subject DN]

  •     CKA_TOKEN    true
    CKA_CLASS    CKO_SECRET_KEY
    CKA_LABEL    [label]

  •     CKA_TOKEN    true
    CKA_CLASS    CKO_CERTIFICATE or CKO_PRIVATE_KEY
    CKA_ID       [cka_id]

Appendix C: Example Provider

package com.foo;

import java.io.*;
import java.lang.reflect.*;
import java.security.*;
import javax.crypto.*;

/**
 * Example provider that demonstrates some of the new API features.
 *
 *  . implement multiple different algorithms in a single class.
 *    Previously each algorithm needed to be implemented in a separate class
 *    (e.g. one for MD5, one for SHA-1, etc.)
 *
 *  . multiple concurrent instances of the provider frontend class each
 *    associated with a different backend.
 *
 *  . it uses "unextractable" keys and lets the framework know which key
 *    objects it can and cannot support
 *
 * Note that this is only a simple example provider designed to demonstrate
 * several of the new features.  It is not explicitly designed for efficiency.
 */
public final class ExampleProvider extends Provider {

    // reference to the crypto backend that implements all the algorithms
    final CryptoBackend cryptoBackend;

    public ExampleProvider(String name, CryptoBackend cryptoBackend) {
        super(name, 1.0, "JCA/JCE provider for " + name);
        this.cryptoBackend = cryptoBackend;
        // register the algorithms we support (MD5, SHA1, DES, and AES)
        putService(new MyService
            (this, "MessageDigest", "MD5", "com.foo.ExampleProvider$MyMessageDigest"));
        putService(new MyService
            (this, "MessageDigest", "SHA1", "com.foo.ExampleProvider$MyMessageDigest"));
        putService(new MyCipherService
            (this, "Cipher", "DES", "com.foo.ExampleProvider$MyCipher"));
        putService(new MyCipherService
            (this, "Cipher", "AES", "com.foo.ExampleProvider$MyCipher"));
    }

    // the API of our fictitious crypto backend
    static abstract class CryptoBackend {
        abstract byte[] digest(String algorithm, byte[] data);
        abstract byte[] encrypt(String algorithm, KeyHandle key, byte[] data);
        abstract byte[] decrypt(String algorithm, KeyHandle key, byte[] data);
        abstract KeyHandle createKey(String algorithm, byte[] keyData);
    }

    // the shell of the representation the crypto backend uses for keys
    private static final class KeyHandle {
        // fill in code
    }

    // we have our own ServiceDescription implementation that overrides newInstance()
    // that calls the (Provider, String) constructor instead of the no-args constructor
    private static class MyService extends Service {

        private static final Class[] paramTypes = {Provider.class, String.class};

        MyService(Provider provider, String type, String algorithm,
                String className) {
            super(provider, type, algorithm, className, null, null);
        }

        public Object newInstance(Object param) throws NoSuchAlgorithmException {
            try {
                // get the Class object for the implementation class
                Class clazz;
                Provider provider = getProvider();
                ClassLoader loader = provider.getClass().getClassLoader();
                if (loader == null) {
                    clazz = Class.forName(getClassName());
                } else {
                    clazz = loader.loadClass(getClassName());
                }
                // fetch the (Provider, String) constructor
                Constructor cons = clazz.getConstructor(paramTypes);
                // invoke constructor and return the SPI object
                Object obj = cons.newInstance(new Object[] {provider, getAlgorithm()});
                return obj;
            } catch (Exception e) {
                throw new NoSuchAlgorithmException("Could not instantiate service", e);
            }
        }
    }

    // custom ServiceDescription class for Cipher objects. See supportsParameter() below
    private static class MyCipherService extends MyService {
        MyCipherService(Provider provider, String type, String algorithm,
                String className) {
            super(provider, type, algorithm, className);
        }
        // we override supportsParameter() to let the framework know which
        // keys we can support. We support instances of MySecretKey, if they
        // are stored in our provider backend, plus SecretKeys with a RAW encoding.
        public boolean supportsParameter(Object obj) {
            if (obj instanceof SecretKey == false) {
                return false;
            }
            SecretKey key = (SecretKey)obj;
            if (key.getAlgorithm().equals(getAlgorithm()) == false) {
                return false;
            }
            if (key instanceof MySecretKey) {
                MySecretKey myKey = (MySecretKey)key;
                return myKey.provider == getProvider();
            } else {
                return "RAW".equals(key.getFormat());
            }
        }
    }

    // our generic MessageDigest implementation. It implements all digest
    // algorithms in a single class. We only implement the bare minimum
    // of MessageDigestSpi methods
    private static final class MyMessageDigest extends MessageDigestSpi {
        private final ExampleProvider provider;
        private final String algorithm;
        private ByteArrayOutputStream buffer;
        MyMessageDigest(Provider provider, String algorithm) {
            super();
            this.provider = (ExampleProvider)provider;
            this.algorithm = algorithm;
            engineReset();
        }
        protected void engineReset() {
            buffer = new ByteArrayOutputStream();
        }
        protected void engineUpdate(byte b) {
            buffer.write(b);
        }
        protected void engineUpdate(byte[] b, int ofs, int len) {
            buffer.write(b, ofs, len);
        }
        protected byte[] engineDigest() {
            byte[] data = buffer.toByteArray();
            byte[] digest = provider.cryptoBackend.digest(algorithm, data);
            engineReset();
            return digest;
        }
    }

    // our generic Cipher implementation, only partially complete. It implements
    // all cipher algorithms in a single class. We implement only as many of the
    // CipherSpi methods as required to show how it could work
    private static abstract class MyCipher extends CipherSpi {
        private final ExampleProvider provider;
        private final String algorithm;
        private int opmode;
        private MySecretKey myKey;
        private ByteArrayOutputStream buffer;
        MyCipher(Provider provider, String algorithm) {
            super();
            this.provider = (ExampleProvider)provider;
            this.algorithm = algorithm;
        }
        protected void engineInit(int opmode, Key key, SecureRandom random)
                throws InvalidKeyException {
            this.opmode = opmode;
            myKey = MySecretKey.getKey(provider, algorithm, key);
            if (myKey == null) {
                throw new InvalidKeyException();
            }
            buffer = new ByteArrayOutputStream();
        }
        protected byte[] engineUpdate(byte[] b, int ofs, int len) {
            buffer.write(b, ofs, len);
            return new byte[0];
        }
        protected int engineUpdate(byte[] b, int ofs, int len, byte[] out, int outOfs) {
            buffer.write(b, ofs, len);
            return 0;
        }
        protected byte[] engineDoFinal(byte[] b, int ofs, int len) {
            buffer.write(b, ofs, len);
            byte[] in = buffer.toByteArray();
            byte[] out;
            if (opmode == Cipher.ENCRYPT_MODE) {
                out = provider.cryptoBackend.encrypt(algorithm, myKey.handle, in);
            } else {
                out = provider.cryptoBackend.decrypt(algorithm, myKey.handle, in);
            }
            buffer = new ByteArrayOutputStream();
            return out;
        }
        // code for remaining CipherSpi methods goes here
    }

    // our SecretKey implementation. All our keys are stored in our crypto
    // backend, we only have an opaque handle available. There is no
    // encoded form of these keys.
    private static final class MySecretKey implements SecretKey {

        final String algorithm;
        final Provider provider;
        final KeyHandle handle;

        MySecretKey(Provider provider, String algorithm, KeyHandle handle) {
            super();
            this.provider = provider;
            this.algorithm = algorithm;
            this.handle = handle;
        }
        public String getAlgorithm() {
            return algorithm;
        }
        public String getFormat() {
            return null; // this key has no encoded form
        }
        public byte[] getEncoded() {
            return null; // this key has no encoded form
        }
        // Convert the given key to a key of the specified provider, if possible
        static MySecretKey getKey(ExampleProvider provider, String algorithm, Key key) {
            if (key instanceof SecretKey == false) {
                return null;
            }
            // algorithm name must match
            if (!key.getAlgorithm().equals(algorithm)) {
                return null;
            }
            // if key is already an instance of MySecretKey and is stored
            // on this provider, return it right away
            if (key instanceof MySecretKey) {
                MySecretKey myKey = (MySecretKey)key;
                if (myKey.provider == provider) {
                    return myKey;
                }
            }
            // otherwise, if the input key has a RAW encoding, convert it
            if (!"RAW".equals(key.getFormat())) {
                return null;
            }
            byte[] encoded = key.getEncoded();
            KeyHandle handle = provider.cryptoBackend.createKey(algorithm, encoded);
            return new MySecretKey(provider, algorithm, handle);
        }
    }
}
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Pack200 and Version Download

Rich Internet Applications Development and Deployment > Rich Internet Applications Deployment Advice > Pack200 and Version Download

Contents

  • Introduction
  • Pack200
    • Usage in a JNLP File
    • Usage in Applet Tag
  • Version Download
    • Usage in a JNLP file

Related Links

  • Pack200 Tools

Introduction

Prior to JavaTM SE 6 update 10 release, engineers had to deploy the JNLPDownloadServlet on the web servers in order to use Pack200 or download specific versions of their application JARs. While this solution works, it limits the flexibility of deploying versioned or Pack200 compressed JARs: Engineers might not have access to deploy JNLPDownloadServlet on web servers.

The Java SE 6 update 10 release introduces two new Java system properties to enable Pack200 and version download - jnlp.packEnabled and jnlp.versionEnabled.

Pack200

When the Java system property jnlp.packEnabled is set to "true" in a jnlp file or an applet tag, the Java Plug-in or Java Web Start software will download the .pack.gz version of JARs. If the .pack.gz version is not available, the unzipped JAR will be searched for.

Note: the compressed version of foo.jar should be named foo.jar.pack.gz.

Usage in a JNLP File

Use the property tag to specify "jnlp.packEnabled" to "true" within the resources tags, i.e.:

<jnlp ...>
   ...
   <resources>
      <property name="jnlp.packEnabled" value="true"/>
         <java version="1.5+" href="http://java.sun.com/products/autodl/j2se"/>
         <jar href="foo.jar" main="true" download="eager"/>
   </resources>
   ...
</jnlp>

In the above case, Java Web Start and the new Java Plug-in will first look for foo.jar.pack.gz. If the file is not found, they will fall back and look for the original, foo.jar.

Usage in Applet Tag

Pass the "-Djnlp.packEnabled" VM argument by using "java_arguments", i.e.:

<HTML>
   ...
   <APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25>
      <PARAM NAME  = "cache_archive" VALUE = "HelloWorld.jar"/>
      <PARAM NAME="java_arguments" VALUE="-Djnlp.packEnabled=true"/>
   </APPLET>
   ...
</HTML>

This feature is only available to New Java Plug-in since it requires passing the VM argument to Java VM. The New Java Plug-in will look for HelloWorld.jar.pack.gz, if this file is not available, it will fall back and look for HelloWorld.jar.

Version Download

Version download is the ability to request that specific versions of certain jar files be used by applets and Java Web Start applications. The jnlp.versionEnabled applies to Java Web Start applications and applets deployed using JNLP.

Usage in a JNLP file

When the Java system property jnlp.versionEnabled is set to "true" in the jnlp file, if the JAR version is specified, the server is checked for the versioned JAR file using the naming convention:

  <file> ::= <name> "__" <options> ".jar"
  <options> ::= "V" <version-id>

Note: version 1.0 of foo.jar should be named foo__V1.0.jar.

The original jar will be used if the versioned jar file is not found. .

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


com.sun.mirror.util (Mirror API b138)

com.sun.mirror.util

Interfaces

  • Declarations
  • DeclarationVisitor
  • SourcePosition
  • Types
  • TypeVisitor

Classes

  • DeclarationFilter
  • DeclarationVisitors
  • SimpleDeclarationVisitor
  • SimpleTypeVisitor


org.w3c.dom.views (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev Package
  • Next Package
  • Frames
  • No Frames
  • All Classes

Package org.w3c.dom.views

  • Interface Summary
    Interface Description
    AbstractView
    A base interface that all views shall derive from.
    DocumentView
    The DocumentView interface is implemented by Document objects in DOM implementations supporting DOM Views.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev Package
  • Next Package
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


org.w3c.dom.html Class Hierarchy (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Hierarchy For Package org.w3c.dom.html

Package Hierarchies:
  • All Packages

Interface Hierarchy

  • org.w3c.dom.DOMImplementation
    • org.w3c.dom.html.HTMLDOMImplementation
  • org.w3c.dom.html.HTMLCollection
  • org.w3c.dom.Node
    • org.w3c.dom.Document
      • org.w3c.dom.html.HTMLDocument
    • org.w3c.dom.Element
      • org.w3c.dom.html.HTMLElement
        • org.w3c.dom.html.HTMLAnchorElement
        • org.w3c.dom.html.HTMLAppletElement
        • org.w3c.dom.html.HTMLAreaElement
        • org.w3c.dom.html.HTMLBaseElement
        • org.w3c.dom.html.HTMLBaseFontElement
        • org.w3c.dom.html.HTMLBodyElement
        • org.w3c.dom.html.HTMLBRElement
        • org.w3c.dom.html.HTMLButtonElement
        • org.w3c.dom.html.HTMLDirectoryElement
        • org.w3c.dom.html.HTMLDivElement
        • org.w3c.dom.html.HTMLDListElement
        • org.w3c.dom.html.HTMLFieldSetElement
        • org.w3c.dom.html.HTMLFontElement
        • org.w3c.dom.html.HTMLFormElement
        • org.w3c.dom.html.HTMLFrameElement
        • org.w3c.dom.html.HTMLFrameSetElement
        • org.w3c.dom.html.HTMLHeadElement
        • org.w3c.dom.html.HTMLHeadingElement
        • org.w3c.dom.html.HTMLHRElement
        • org.w3c.dom.html.HTMLHtmlElement
        • org.w3c.dom.html.HTMLIFrameElement
        • org.w3c.dom.html.HTMLImageElement
        • org.w3c.dom.html.HTMLInputElement
        • org.w3c.dom.html.HTMLIsIndexElement
        • org.w3c.dom.html.HTMLLabelElement
        • org.w3c.dom.html.HTMLLegendElement
        • org.w3c.dom.html.HTMLLIElement
        • org.w3c.dom.html.HTMLLinkElement
        • org.w3c.dom.html.HTMLMapElement
        • org.w3c.dom.html.HTMLMenuElement
        • org.w3c.dom.html.HTMLMetaElement
        • org.w3c.dom.html.HTMLModElement
        • org.w3c.dom.html.HTMLObjectElement
        • org.w3c.dom.html.HTMLOListElement
        • org.w3c.dom.html.HTMLOptGroupElement
        • org.w3c.dom.html.HTMLOptionElement
        • org.w3c.dom.html.HTMLParagraphElement
        • org.w3c.dom.html.HTMLParamElement
        • org.w3c.dom.html.HTMLPreElement
        • org.w3c.dom.html.HTMLQuoteElement
        • org.w3c.dom.html.HTMLScriptElement
        • org.w3c.dom.html.HTMLSelectElement
        • org.w3c.dom.html.HTMLStyleElement
        • org.w3c.dom.html.HTMLTableCaptionElement
        • org.w3c.dom.html.HTMLTableCellElement
        • org.w3c.dom.html.HTMLTableColElement
        • org.w3c.dom.html.HTMLTableElement
        • org.w3c.dom.html.HTMLTableRowElement
        • org.w3c.dom.html.HTMLTableSectionElement
        • org.w3c.dom.html.HTMLTextAreaElement
        • org.w3c.dom.html.HTMLTitleElement
        • org.w3c.dom.html.HTMLUListElement
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Package org.w3c.dom.views (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Package
org.w3c.dom.views

  • Packages that use org.w3c.dom.views
    Package Description
    org.w3c.dom.css
    org.w3c.dom.events
    org.w3c.dom.views
  • Classes in org.w3c.dom.views used by org.w3c.dom.css
    Class and Description
    AbstractView
    A base interface that all views shall derive from.
  • Classes in org.w3c.dom.views used by org.w3c.dom.events
    Class and Description
    AbstractView
    A base interface that all views shall derive from.
  • Classes in org.w3c.dom.views used by org.w3c.dom.views
    Class and Description
    AbstractView
    A base interface that all views shall derive from.
    DocumentView
    The DocumentView interface is implemented by Document objects in DOM implementations supporting DOM Views.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.declaration.PackageDeclaration (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.declaration.PackageDeclaration

  • Packages that use PackageDeclaration
    Package Description
    com.sun.mirror.apt
    Classes used to communicate information between annotation processors and an annotation processing tool.
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of PackageDeclaration in com.sun.mirror.apt

      Methods in com.sun.mirror.apt that return PackageDeclaration
      Modifier and Type Method and Description
      PackageDeclaration AnnotationProcessorEnvironment.getPackage(String name)
      Deprecated.
      Returns the declaration of a package given its fully qualified name.

    • Uses of PackageDeclaration in com.sun.mirror.declaration

      Methods in com.sun.mirror.declaration that return PackageDeclaration
      Modifier and Type Method and Description
      PackageDeclaration TypeDeclaration.getPackage()
      Deprecated.
      Returns the package within which this type is declared.

    • Uses of PackageDeclaration in com.sun.mirror.util

      Methods in com.sun.mirror.util with parameters of type PackageDeclaration
      Modifier and Type Method and Description
      void SimpleDeclarationVisitor.visitPackageDeclaration(PackageDeclaration d)
      Deprecated.
      Visits a package declaration.
      void DeclarationVisitor.visitPackageDeclaration(PackageDeclaration d)
      Deprecated.
      Visits a package declaration.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.javadoc.PackageDoc (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.javadoc.PackageDoc

    • Uses of PackageDoc in com.sun.javadoc

      Methods in com.sun.javadoc that return PackageDoc
      Modifier and Type Method and Description
      PackageDoc ProgramElementDoc.containingPackage()
      Get the package that this program element is contained in.
      PackageDoc[] ClassDoc.importedPackages()
      Deprecated.
      Import declarations are implementation details that should not be exposed here. In addition, this method's return type does not allow for all type-import-on-demand declarations to be returned.
      PackageDoc RootDoc.packageNamed(String name)
      Return a PackageDoc for the specified package name.
      PackageDoc SeeTag.referencedPackage()
      Get the package doc when @see references only a package.
      PackageDoc[] RootDoc.specifiedPackages()
      Return the packages specified on the command line.
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Parallel Compaction

  • Description
  • Enabling Parallel Compaction
  • More Information

Description

Parallel compaction complements the existing parallel collector by performing full GCs in parallel to take advantage of multiprocessor (or multi-threaded) hardware. As the name suggests, it is best suited to platforms that have two or more CPUs or two or more hardware threads. It was first made available in JDK 5.0 update 6; the implementation in JDK 6 contains significant performance improvements.

Prior to the availability of parallel compaction, the parallel collector would perform young generation collections (young GCs) in parallel, but full GCs were performed single-threaded. (During a young GC, only the young generation is collected; during a full GC the entire heap is collected. See the documents referenced below for more details on generations and garbage collection.) Parallel compaction performs full GCs in parallel, resulting in lower garbage collection overhead and better application performance, particularly for applications with large heaps running on multiprocessor hardware.

Enabling Parallel Compaction

Parallel compaction is not enabled by default; add the option

-XX:+UseParallelOldGC

to the java command line to enable parallel compaction. (Parallel compaction will likely be enabled by default on multiprocessor hardware in a future release.)

Note that parallel compaction is not available in combination with the concurrent mark sweep collector; it can only be used with the parallel young generation collector. The documents referenced below provide more information on the available collectors and recommendations for their use.

More Information

The HotSpot memory management whitepaper describes the various collectors available in HotSpot and includes recommendations on when to use parallel compaction as well as a high-level description of the algorithm.

The HotSpot documentation page contains links to Garbage Collection Tuning Guides, specific to each release, which include guidelines for choosing the garbage collector that best suits your requirements and techniques that can help reduce garbage collection overhead.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.javadoc.Parameter (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.javadoc.Parameter

    • Uses of Parameter in com.sun.javadoc

      Methods in com.sun.javadoc that return Parameter
      Modifier and Type Method and Description
      Parameter[] ExecutableMemberDoc.parameters()
      Get argument information.
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.declaration.ParameterDeclaration (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.declaration.ParameterDeclaration

  • Packages that use ParameterDeclaration
    Package Description
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of ParameterDeclaration in com.sun.mirror.declaration

      Methods in com.sun.mirror.declaration that return types with arguments of type ParameterDeclaration
      Modifier and Type Method and Description
      Collection<ParameterDeclaration> ExecutableDeclaration.getParameters()
      Deprecated.
      Returns the formal parameters of this method or constructor.

    • Uses of ParameterDeclaration in com.sun.mirror.util

      Methods in com.sun.mirror.util with parameters of type ParameterDeclaration
      Modifier and Type Method and Description
      void SimpleDeclarationVisitor.visitParameterDeclaration(ParameterDeclaration d)
      Deprecated.
      Visits a parameter declaration.
      void DeclarationVisitor.visitParameterDeclaration(ParameterDeclaration d)
      Deprecated.
      Visits a parameter declaration.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.javadoc.ParameterizedType (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.javadoc.ParameterizedType

    • Uses of ParameterizedType in com.sun.javadoc

      Methods in com.sun.javadoc that return ParameterizedType
      Modifier and Type Method and Description
      ParameterizedType Type.asParameterizedType()
      Return this type as a ParameterizedType if it represents an invocation of a generic class or interface.
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.ParameterizedTypeTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.ParameterizedTypeTree

  • Packages that use ParameterizedTypeTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of ParameterizedTypeTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type ParameterizedTypeTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitParameterizedType(ParameterizedTypeTree node, P p)

    • Uses of ParameterizedTypeTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type ParameterizedTypeTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitParameterizedType(ParameterizedTypeTree node, P p)
      R | SimpleTreeVisitor.visitParameterizedType(ParameterizedTypeTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.javadoc.ParamTag (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.javadoc.ParamTag

    • Uses of ParamTag in com.sun.javadoc

      Methods in com.sun.javadoc that return ParamTag
      Modifier and Type Method and Description
      ParamTag[] ExecutableMemberDoc.paramTags()
      Return the param tags in this method, excluding the type parameter tags.
      ParamTag[] ExecutableMemberDoc.typeParamTags()
      Return the type parameter tags in this method.
      ParamTag[] ClassDoc.typeParamTags()
      Return the type parameter tags of this class or interface.
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.ParenthesizedTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.ParenthesizedTree

  • Packages that use ParenthesizedTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of ParenthesizedTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type ParenthesizedTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitParenthesized(ParenthesizedTree node, P p)

    • Uses of ParenthesizedTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type ParenthesizedTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitParenthesized(ParenthesizedTree node, P p)
      R | SimpleTreeVisitor.visitParenthesized(ParenthesizedTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Advanced JGSS Security Programming

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Part I : Secure Authentication using the Java Authentication and Authorization Service (JAAS)

Exercise 1 : Using the JAAS API

Goal of this exercise:

The goal of this exercise is to learn how to use the Java Authentication and Authorization (JAAS) API to perform authentication.

Background for this exercise:

JAAS provides a standard pluggable authentication framework (PAM) for the Java platform. An application uses the JAAS API to perform authentication - the process of verifying the identity of the user who is using the application and gathering his identity information into a container called a subject. The application can then use the identity information in the subject along with the JAAS API to make authorization decisions, to decide whether the authenticated user is allowed to access protected resources or perform restricted actions. This exercise demonstrates JAAS Authentication. It does not demonstrate JAAS Authorization.

Resources for this exercise:

  1. JAAS Reference Guide
  2. JAAS Tutorials
  3. JAAS javadocs: javax.security.auth, javax.security.auth.callback, javax.security.auth.kerberos, javax.security.auth.login, javax.security.auth.spi, javax.security.auth.x500
  4. JAAS white paper

Steps to follow:

  1. Read the following sample code. This is located in src/Jaas.java. The code performs the following tasks:
  1. Define a callback handler or use a predefined one. [line 2]
  2. Create a LoginContext with a name that identifies which JAAS configuration entry to use. [line 5]
  3. Perform the authentication. [line 8]
  4. Define the task that the authenticated user is to perform [line 11]
  5. Perform the action as the authenticated user [lines 14-15]
  6. Logout.

Subject.doAs will run the code defined in MyAction as the authenticated user [lines 14-15]. This serves two purposes. First, code in MyAction that requires identity information for authentication to a service could get it from the subject. This exercise demonstrates this use. Second, if MyAction accesses any protected resources/operations, the identity information in the current subject would be used to make the corresponding access control decision. This second aspect is not covered in this exercise.

Code listing for Jaas.java.

  1. // Create a callback handler
  2. CallbackHandler callbackHandler = new TextCallbackHandler();
  4. // Create LoginContext with a callback handler
  5. LoginContext context = new LoginContext(name, callbackHandler);
  7. // Perform authentication
  8. context.login();
  10. // Create action to perform
  11. PrivilegedAction action = new MyAction();
  13. // Perform action as authenticated user
  14. Subject subject = context.getSubject();
  15. Subject.doAs(subject, action);
  17. // Logout
  18. context.logout();
  2. Make sure that the %JAVA_HOME%/bin is in the path, and JDK pointed to by the %JAVA_HOME% variable points to Java SE 6.
  3. Compile the modified sample code.

% cd auth/src
% javac Jaas.java
    You will run this code in subsequent exercises after doing some set up. That ends this exercise.

Summary:

This exercise introduced the main classes of the JAAS APIs: LoginContext and Subject. You learned how to use LoginContext to authenticate a user and collect its identity information in a Subject. You then learned how to use the Subject to perform an action as the authenticated user.

Next Steps

  1. Proceed to Exercise 2 to learn how to configure the sample application to use Kerberos for authentication.

Exercise 2: Configuring JAAS for Kerberos Authentication

Goal of this exercise:

The goal of this exercise is to learn how to configure a JAAS application to use Kerberos for authentication.

Kerberos Background for this exercise:

Kerberos is an Internet standard protocol for trusted-third party authentication defined in RFC 4120. It is available on most modern computing platforms today, including Solaris, Windows XP, and Linux.

The Kerberos architecture is centered around a trusted authentication service called the key distribution center, or KDC. Users and services in a Kerberos environment are referred to as principals; each principal shares a secret (such as a password) with the KDC. A principal authenticates to Kerberos by proving to the KDC that it knows the shared secret. If the authentication is successful, the KDC issues a ticket-granting-ticket (TGT) to the principal. When the principal subsequently wants to authenticate to a service on the network, such as a directory service or a file service, (thereby, acting as a "client" of the service), it gives the TGT to the KDC to obtain a service ticket to communicate with the service. Not only does the service ticket indicate the identities of the client and service principals, it also contains a session key that can be used by the client and service to subsequently establish secure communication. To authenticate to the service, the client sends the service ticket to the service. When the service receives the ticket, it decodes it using the secret it shares with the KDC.

In this architecture, a principal only authenticates directly (once) to the KDC. It authenticates indirectly to all other services via the use of service tickets. Service tickets are how the KDC vouches for the identity of a principal. The ability of a principal to access multiple secure services by performing explicit authentication only once is called single sign-on.

JAAS Background for this exercise:

In JAAS, for a client principal, "logging into Kerberos" means acquiring the TGT and placing it in the Subject, so that it can be used for authentication with services that the client will access. For a service principal, "logging into Kerberos" means obtaining the secret keys that the service needs to decode incoming client authentication requests.

Resources for this exercise:

  1. JAAS LoginModule Developer's Guide
  2. The Kerberos Network Authentication Service (v5)
  3. Example Login Configurations
  4. Login module package javadocs: com.sun.security.auth.module
  5. The JAAS and Java GSS-API Tutorials

Steps to follow:

  1. Examine the JAAS configuration file. This is located in src/jaas-krb5.conf

This file contains two entries, one named "client" and one named "server." The "client" entry indicates that the LoginContext must use the com.sun.security.auth.module.Krb5LoginModule. The "server" entry indicates that the LoginContext must use the same login module, and use keys from the sample.keytab file for the principal host/machineName.

Code listing for jaas-krb5.conf.

  1. client {
  2.     com.sun.security.auth.module.Krb5LoginModule required
  3.     principal="test";
  4. };
  5. server {
  6.    com.sun.security.auth.module.Krb5LoginModule required
  7.     useKeyTab=true
  8.     storeKey=true
  9.     keyTab=sample.keytab
  10.     principal="host/machineName";
  11. };

  2. Determine the hostname of your machine by executing the hostname command.
% hostname
  3. Edit this file and change the entry for server principal to use the name of your machine. For example, if your machine name is j1hol-001, this line in the configuration file should look like this.
principal="host/j1hol-001"
  4. Perform client authentication by typing
% java -Djava.security.auth.login.config=jaas-krb5.conf\
Jaas client

You will be prompted for a password. Enter "changeit". You should see the following output.

Output for running the JAAS example using the client entry from jaas-krb5.conf:

  1. Kerberos password for test: changeit
  2. Authenticated principal: [test@J1LABS.EXAMPLE.COM]
  3. Performing secure action...

  5. Perform server authentication by typing
% java -Djava.security.auth.login.config=jaas-krb5.conf\
Jaas server

You should see the following output.

Output for running JAAS example using "server" entry from jaas-krb5.conf.

  1. Authenticated principal: [host/j1hol-001@J1LABS.EXAMPLE.COM]
  2. Performing secure action...

Summary:

In this exercise, you learned how to configure a JAAS application to use a Kerberos login module, both as a client principal who enters his/her username/password interactively, and as a service principal who gets its keys from a keytab file.

Next Steps

  1. Proceed to Part II to learn how to establish secure communication channels using Java security APIs.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Advanced JGSS Security Programming

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Part II : Secure Communications using the Java SE 6 Security API

This part shows you how to build applications that perform secure communications. The Java SE 6 platform provides three standard APIs that allow applications to perform secure communications: The Java Generic Security Service (GSS), the Java SASL API, and the Java Secure Socket Extension (JSSE). When building an application, which of these APIs should you use? The answer depends on many factors, including requirements of the protocol or service, deployment infrastructure, and integration with other security services. For example, if you are building an LDAP client library, you would need to use the Java SASL API because use of SASL is part of LDAP's protocol definition. As an other example, if the service supports SSL, then the client application attempting to access the service would need to use JSSE.

Exercise 3: Using the Java Generic Security Service (GSS) API

Goal of this exercise:

The goal of this exercise is to learn how to use the Java GSS API to perform secure authentication and communication.

Background for this exercise:

The Generic Security Service API provides a uniform C-language interface to access various security services, such as authentication, message integrity, and message confidentiality. The Java GSS API provides the corresponding interface for Java applications. It allows applications to perform authentication and establish secure communication with the peer. One of the most common security service accessed via the GSS-API and Java GSS-API is Kerberos.

Resources for this Exercise:

  1. The JAAS and Java GSS-API Tutorials
  2. Generic Security Service API Version 2: Java Bindings (RFC 2853)
  3. Java GSS javadocs: org.ietf.jgss.

Overview of this Exercise:

This exercise is a client-server application that demonstrates how to communicate securely using the Java GSS API. The client and server parts first authenticate to Kerberos, as shown in Exercise 1. This stores the credentials in the subject. The application then executes an action that performs Java GSS operations (with Kerberos as the underlying GSS mechanism) inside of a Subject.doAs using the subject. The Java GSS Kerberos mechanism, because it is executing inside the doAs, obtains the Kerberos credentials from the subject, and uses them to authenticate with the peer and to exchange messages securely.

Steps to follow:

  1. Read the following code. This is located in src/GssServer.java.

    This code fragment defines the action to execute after the service principal has authenticated to the KDC. It replaces the MyAction of line 11 of Exercise 1. Note the highlighted lines. The code first creates an instance of GSSManager [line 8], which it uses to obtain its own credentials [line 10-11] and to create an instance of GSSContext [line 18]. It uses this context to perform authentication [the loop between lines 22-34]. Upon completing authentication, it accepts encrypted input from the client and uses the established security context to decrypt the data [line 45]. It then uses the security context to encrypt a reply containing the original input and the date [line 49], and then sends it back to the client.

Code listing for GssServer.java.

  1. static class GssServerAction implements PrivilegedExceptionAction {
  2. ...
  3.   public Object run() throws Exception {
  4.     // Create server socket for accepting connections
  5.     ServerSocket ss = new ServerSocket(localPort);

  7.     // Get own Kerberos credentials for accepting connection
  8.     GSSManager manager = GSSManager.getInstance();
  9.     Oid krb5Oid = new Oid("1.2.840.113554.1.2.2");
  10.     GSSCredential serverCreds = manager.createCredential(null,
  11.       GSSCredential.DEFAULT_LIFETIME, krb5Oid, GSSCredential.ACCEPT_ONLY);

  13.     while (true) {
  14.       Socket socket = ss.accept();
  15.       DataInputStream inStream = new DataInputStream(socket.getInputStream());
  16.       DataOutputStream outStream = new DataOutputStream(socket.getOutputStream());

  18.       GSSContext context = manager.createContext((GSSCredential)serverCreds);

  20.       // Do the context establishment loop
  21.       byte[] token = null;
  22.       while (!context.isEstablished()) {
  23.         // Read token
  24.         token = new byte[inStream.readInt()];
  25.         inStream.readFully(token);

  27.         // Process token
  28.         token = context.acceptSecContext(token, 0, token.length);

  30.         // Send a token to the peer if one was generated by acceptSecContext
  31.         outStream.writeInt(token.length);
  32.         outStream.write(token);
  33.         outStream.flush();
  34.       }

  36.       // Context established!

  38.       // Create MessageProp for use with unwrap (will be set upon return from unwrap)
  39.       MessageProp prop = new MessageProp(0, false);

  41.       // Read token from client
  42.       token = new byte[inStream.readInt()];
  43.       inStream.readFully(token);
  44.       // Unwrap (decrypt) token sent by client
  45.       byte[] input = context.unwrap(token, 0, token.length, prop);
  46.       ...
  47.       // Create new token and send to client
  48.       byte[] reply = ...;
  49.       token = context.wrap(reply, 0, reply.length, prop);

  51.       outStream.writeInt(token.length);
  52.       outStream.write(token);
  53.       outStream.flush();
  54.       context.dispose();
  55.       socket.close();
  56.     }
  57.   }
  58. }

  2. Compile the sample code. % javac GssServer.java
  3. Read the following code. This is located in src/GssClient.java.

    This code fragment defines the action to execute after the client principal has authenticated to the KDC. It replaces the MyAction of line 11 of Exercise 1. Note the highlighted lines. The code first creates an instance of GSSManager [line 10], which it uses to obtain a principal name for the service that it is going to communicate with [line 12]. It then creates an instance of GSSContext [line 15,16] to perform authentication [the loop between lines 22-33] with the service. Upon completing authentication, it uses the established security context to encrypt a message [line 42] and sends it to the server. It then reads an encrypted message from the server and decodes it using the established security context [line 53].
Code listing for GssClient.java.

  1. static class GssClientAction implements PrivilegedExceptionAction {
  2. ...
  3.   public Object run() throws Exception {
  4.     // Create socket to server
  5.     Socket socket = new Socket(hostName, port);
  6.     DataInputStream inStream = new DataInputStream(socket.getInputStream());
  7.     DataOutputStream outStream = new DataOutputStream(socket.getOutputStream());

  9.     // Get service's principal name
  10.     GSSManager manager = GSSManager.getInstance();
  11.     Oid krb5Oid = new Oid("1.2.840.113554.1.2.2");
  12.     GSSName serverName = manager.createName(serverPrinc, GSSName.NT_HOSTBASED_SERVICE);

  14.     // Get the context for authentication
  15.     GSSContext context = manager.createContext(serverName, krb5Oid, null,
  16.        GSSContext.DEFAULT_LIFETIME);
  17.     context.requestMutualAuth(true); // Request mutual authentication
  18.     context.requestConf(true); // Request confidentiality

  20.     // Do the context establishment loop
  21.     byte[] token = new byte[0];
  22.     while (!context.isEstablished()) {
  23.       token = context.initSecContext(token, 0, token.length);
  24.       outStream.writeInt(token.length);
  25.       outStream.write(token);
  26.       outStream.flush();

  28.       // Check if we're done
  29.       if (!context.isEstablished()) {
  30.         token = new byte[inStream.readInt()];
  31.         inStream.readFully(token);
  32.       }
  33.     }

  35.     // Context established!

  37.     // Create MessageProp for use with unwrap (true means request confidentiality)
  38.     MessageProp prop = new MessageProp(0, true);

  40.     // Create encrypted message and send to server
  41.     byte[] reply = ...;
  42.     token = context.wrap(reply, 0, reply.length, prop);

  44.     outStream.writeInt(token.length);
  45.     outStream.write(token);
  46.     outStream.flush();

  48.     // Read token from server
  49.     token = new byte[inStream.readInt()];
  50.     inStream.readFully(token);

  52.     // Unwrap (decrypt) token sent by server
  53.     byte[] input = context.unwrap(token, 0, token.length, prop);
  54.     ...
  55.     context.dispose();
  56.     socket.close();
  57.     return null;
  58.   }
  59. }

  4. Compile the sample code.
    % javac GssClient.java
  5. Launch a new window and start the server.
    % xterm &
% java -Djava.security.auth.login.config=jaas-krb5.conf \
       GssServer
  6. Run the client application. GssClient takes two parameters: the service name and the name of the server that the service is running on. For example, if the service is host running on the machine j1hol-001, you would enter the following. When prompted for the password, enter changeit.

% java -Djava.security.auth.login.config=jaas-krb5.conf \
       GssClient host j1hol-001
  7. Observe the following output in the client and server applications' windows.

Output for running GssServer example.

  1. Authenticated principal: [host/j1hol-001@J1LABS.EXAMPLE.COM]
  2. Waiting for incoming connections...
  3. Got connection from client /129.145.128.102
  4. Context Established!
  5. Client principal is test@J1LABS.EXAMPLE.COM
  6. Server principal is host/j1hol-001@J1LABS.EXAMPLE.COM
  7. Mutual authentication took place!
  8. Received data "Hello There!" of length 12
  9. Confidentiality applied: true
  10. Sending: Hello There! Thu May 06 12:11:15 PDT 2005

Output for running GssClient example.

  1. Kerberos password for test: changeit
  2. Authenticated principal: [test@J1LABS.EXAMPLE.COM]
  3. Connected to address j1hol-001/129.145.128.102
  4. Context Established!
  5. Client principal is test@J1LABS.EXAMPLE.COM
  6. Server principal is host@j1hol-001
  7. Mutual authentication took place!
  8. Sending message: Hello There!
  9. Will read token of size 93
  10. Received message: Hello There! Thu May 06 12:11:15 PDT 2005

Summary:

In this exercise, you learned how to write a client-server application that uses the Java GSS API to authenticate and communicate securely with each other.

Next Steps

  1. Proceed to Exercise 4 to learn how to write a client/server application that uses the Java SASL API to authenticate and communicate securely with each other.
  2. Proceed to Exercise 5 to learn how to write a client/server application that uses the JSSE to authenticate and communicate securely with each other.
  3. Proceed to Exercise 6 to learn how to configure the sample programs that you have just used to achieve single sign-on in a Kerberos environment.

Exercise 4: Using the Java SASL API

Goal of this exercise:

The goal of this exercise is to learn how to use the Java SASL API to perform secure authentication and communication.

Background for this exercise:

Simple Authentication and Security Layer (SASL) specifies a challenge-response protocol in which data is exchanged between the client and the server for the purposes of authentication and (optional) establishment of a security layer on which to carry on subsequent communications. SASL allows different mechanisms to be used; each such mechanism is identified by a profile that defines the data to be exchanged and a name. SASL is used with connection-based protocols such as LDAPv3 and IMAPv4. SASL is described in RFC 4422.

The Java SASL API defines an API for applications to use SASL in a mechanism-independent way. For example, if you are writing a library for a networking protocol that uses SASL, you can use the Java SASL API to generate the data to be exchanged with the peer. When the library is deployed, you can dynamically configure the mechanisms to use with the library.

In addition to authentication, you can use SASL to negotiate a security layer to be used after authentication. But unlike the GSS-API, the properties of the security layer (such as whether you want integrity or confidentiality) is decided at negotiation time. (the GSS-API allows confidentiality to be turned on or off per message).

Resources for this exercise:

  1. The Java SASL API Programming and Deployment Guide
  2. The Java SASL API javadocs
  3. Simple Authentication and Security Layer (SASL) (RFC 4422)

Overview of this exercise:

This exercise is a client-server application that demonstrates how to communicate securely using the Java SASL API. The client and server parts first authenticate to Kerberos using Exercise 1. This stores the credentials in the subject. The application then executes an action that performs Java SASL API operations (with Kerberos as the underlying SASL mechanism) inside of a Subject.doAs using the subject. The SASL/Kerberos mechanism, because it is executing inside the doAs, obtains the Kerberos credentials from the subject, and uses them to authenticate with the peer and to exchange messages securely.

This example uses a simple protocol implemented by the AppConnection class. This protocol exchanges authentication commands and data commands. Each command consists of a type (e.g., AppConnection.AUTH_CMD), the length of the data to follow, and the data itself. The data is a SASL buffer if it is for authentication or encrypted/integrity-protected application data; it is plain application data otherwise.

Steps to follow:

  1. Read the following code. This is located in src/SaslTestServer.java.

    This code fragment defines the action to execute after the service principal has authenticated to the KDC. It replaces the MyAction of line 11 of Exercise 1. Note the highlighted lines. The server specifies the quality-of-protections that it will support [line 9] and then creates an instance of SaslServer to perform the authentication [line 21]. The challenge-response protocol of SASL is performed in the while loop [lines 33-49], with the server sending challenges to the client and processing the responses from the client. After authentication, the identity of the authenticated client can be obtained via a call to getAuthorizedID() [line 61]. If a security layer was negotiated, the server can exchange data securely with the client [lines 66,70].

Code listing for SaslTestServer.java.

  1. static class SaslServerAction implements PrivilegedExceptionAction {
  2. ...
  3.   public Object run() throws Exception {
  4.     // Create server socket for accepting connections
  5.     ServerSocket ss = new ServerSocket(localPort);

  7.     // Support all quality-of-protection options
  8.     HashMap<String,Object> props = new HashMap<String,Object>();
  9.     props.put(Sasl.QOP, "auth-conf,auth-int,auth");

  11.     while (true) {
  12.       // Create application-level connection to handle request
  13.       Socket socket = ss.accept();
  14.       AppConnection conn = new AppConnection(socket);

  16.       // Normally, the application protocol will negotiate which
  17.       // SASL mechanism to use. In this simplified example, we
  18.       // will always use "GSSAPI" (the name of the mechanism that does Kerberos via GSS-API)

  20.       // Create SaslServer to perform authentication
  21.       SaslServer srv = Sasl.createSaslServer("GSSAPI", service, serviceName, props, cbh);

  23.       if (srv == null) {
  24.         // ... handle error
  25.       }

  27.       // Read the initial response from client
  28.       byte[] response = conn.receive(AppConnection.AUTH_CMD);
  29.       AppConnection.AppReply clientMsg;
  30.       boolean auth = false;

  32.       // Perform authentication
  33.       while (!srv.isComplete()) {
  34.         try
  35.           // Generate challenge based on response
  36.           byte[] challenge = srv.evaluateResponse(response);
  37.           if (srv.isComplete()) {
  38.             conn.send(AppConnection.SUCCESS, challenge);
  39.             auth = true;
  40.           } else {
  41.             clientMsg = conn.send(AppConnection.AUTH_IN_PROGRESS, challenge);
  42.             response = clientMsg.getBytes();
  43.           }
  44.         } catch (SaslException e) {
  45.           // Send failure notification to client
  46.           conn.send(AppConnection.FAILURE, null);
  47.           break;
  48.         }
  49.       }

  51.       // Authentication completed!

  53.       // Check status of authentication
  54.       if (srv.isCompleted() && auth) {
  55.         System.out.println("authorized client is: " + srv.getAuthorizationID());
  56.       } else {
  57.         // Report failure ...
  58.       }

  60.       // Find out whether security layer was negotiated
  61.       String qop = (String) srv.getNegotiatedProperty(Sasl.QOP);
  62.       boolean sl = (qop.equals("auth-conf") || qop.equals("auth-int"));

  64.       // Read and decrypt message from client
  65.       byte[] msg = conn.receive(AppConnection.DATA_CMD);
  66.       byte[] realMsg = (sl ? srv.unwrap(msg, 0, msg.length) : msg);
  67.       ...
  68.       // Create and encrypt message to send to client
  69.       byte[] reply = ...;
  70.       byte[] realReply = (sl ? srv.wrap(reply, 0, reply.length) : reply);
  71.       conn.send(AppConnection.SUCCESS, realReply);
  72.     }
  73.   }
  74. }

  2. Compile the sample code.
    % javac SaslTestServer.java
  3. Read the following code. This is located in src/SaslTestClient.java. This code fragment defines the action to execute after the client principal has authenticated to the KDC. It replaces the MyAction of line 11 of Exercise 1. Note the highlighted lines. The program first specifies the quality of protection that it wants (in this case, confidentiality) [line 8] and then creates an instance of SaslClient to use for authentication [lines 11-12]. It then checks whether the mechanism has an initial response and if so, gets the response by invoking evaluateChallenge() with an empty byte array [line 20]. It then sends the response to the server to begin the authentication. The challenge-response protocol of SASL is performed in the while loop [lines 24-39], with the client evaluating the challenges that it gets from the server and sending the server the corresponding responses to the challenges. After authentication, the client can proceed to communicate with the server using the negotiated security layer [lines 48,55].

Code listing for SaslTestClient.java.

  1. static class SaslClientAction implements PrivilegedExceptionAction {
  2. ...
  3.   public Object run() throws Exception {
  4.     // Create application-level connection
  5.     AppConnection conn = new AppConnection(serverName, port);

  7.     HashMap<String,Object> props = new HashMap<String,Object>();
  8.     props.put(Sasl.QOP, "auth-conf"); // Request confidentiality

  10.     // Create SaslClient to perform authentication
  11.     SaslClient clnt = Sasl.createSaslClient(
  12.       new String[]{"GSSAPI"}, null, service, serverName, props, cbh);
  13.     if (clnt == null) {
  14.       // ... handle error
  15.     }

  17.     byte[] challenge;

  19.     // Get initial response for authentication
  20.     byte[] response = clnt.hasInitialResponse() ? clnt.evaluateChallenge(EMPTY) : EMPTY;
  21.     AppConnection.AppReply reply = conn.send(AppConnection.AUTH_CMD, response);

  23.     // Repeat until authentication terminates
  24.     while (!clnt.isComplete() &&
  25.       (reply.getStatus() == AppConnection.AUTH_INPROGRESS ||
  26.        reply.getStatus() == AppConnection.SUCCESS))
  27.       // Evaluate challenge to generate response
  28.       challenge = reply.getBytes()
  29.       response = clnt.evaluateChallenge(challenge)

  31.       if (reply.getStatus() == AppConnection.SUCCESS) {
  32.         if (response != null) {
  33.           throw new Exception("Protocol error")
  34.         }
  35.         break;
  36.       }
  37.       // Send response to server and read server's next challenge
  38.       reply = conn.send(AppConnection.AUTH_CMD, response);
  39.     }
  40.     // Authentication completed!
  41.     // Find out whether security layer was negotiated
  42.     String qop = (String) srv.getNegotiatedProperty(Sasl.QOP);
  43.     boolean sl = (qop.equals("auth-conf") || qop.equals("auth-int"));

  45.     byte[] msg = ...;

  47.     // Create and send encrypted data to server
  48.     byte[] encrypted = (sl ? clnt.wrap(msg, 0, msg.length) : msg);
  49.     reply = conn.send(AppConnection.DATA_CMD, encrypted);) {

  51.     ...

  53.     // Read and decrypt data from server
  54.     byte[] encryptedReply = reply.getBytes();
  55.     byte[] clearReply = (sl ? clnt.unwrap(encryptedReply, 0, encryptedReply.length)
  56.       : encryptedReply);
  57.     conn.close();
  58.     return null;
  59.   }
  60. }
  4. Compile the sample code.
    % javac SaslTestClient.java
  5. Launch a new window and start the server. SaslTestServer takes two parameters: the service name and the name of the server that the service is running on. For example, if the service is host running on the machine j1hol-001, you would enter the following.
    % xterm &

% java

 -Djava.security.auth.login.config=jaas-krb5.conf \

       SaslTestServer host j1hol-001
  6. Run the client application. SaslTestClient takes two parameters: the service name and the name of the server that the service is running on. For example, if the service is host running on the machine j1hol-001, you would enter the following. When prompted for the password, enter changeit.
    % java -Djava.security.auth.login.config=jaas-krb5.conf \
    SaslTestClient host j1hol-001
  7. Observe the following output in the client and server applications' windows.

Output for running the SaslTestServer example.

  1. Authenticated principal: [host/j1hol-001@J1LABS.EXAMPLE.COM]
  2. Waiting for incoming connections...
  3. Got connection from client /129.145.128.102
  4. Client authenticated; authorized client is: test@J1LABS.EXAMPLE.COM
  5. Negotiated QOP: auth-conf
  6. Received: Hello There!
  7. Sending: Hello There! Fri May 07 15:32:37 PDT 2005
  8. Received data "Hello There!" of length 12

Output for running the SaslTestClient example.

  1. Kerberos password for test: changeit
  2. Authenticated principal: [test@J1LABS.EXAMPLE.COM]
  3. Connected to address j1hol-001/129.145.128.102
  4. Client authenticated.
  5. Negotiated QOP: auth-conf
  6. Sending: Hello There!
  7. Received: Hello There! Fri May 07 15:32:37 PDT 2005
  8. To try the program using different quality-of-protection, change line 8 in SaslTestClient. For example, replace line 8 with the following line to use integrity protection on (no confidentiality).
    props.put(Sasl.QOP, "auth-int");

Summary:

In this exercise, you learned how to write a client-server application that uses the Java SASL API to authenticate and communicate securely with each other.

Next Steps

  1. Proceed to Exercise 5 to learn how to write a client/server application that uses the JSSE to authenticate and communicate securely with each other.
  2. Proceed to Exercise 6 to learn how to configure the sample programs that you have just used to achieve single sign-on in a Kerberos environment.

Exercise 5: Using the Java Secure Socket Extension with Kerberos

Goal of this exercise:

The goal of this exercise is to learn how to use the JSSE API to perform secure authentication and communication using Kerberos cipher suites.

Background for this exercise:

Secure Socket Layer (SSL) and Transport Layer Security (TLS) are the most widely used protocols for implementing cryptography on the Internet. TLS is the Internet standard evolved from SSL. SSL/TLS provides application-level protocols (such as HTTP and LDAP) with secure authentication and communication. For example, HTTPS is the resulting protocol of using HTTP over SSL/TLS. SSL/TLS is used not only for standard protocols such as HTTP, it is also widely used when building custom applications using custom protocols that need to communicate securely.

SSL/TLS traditionally used certificate-based authentication and is commonly used for server-authentication. For example, when a Web client such as a browser accesses a secure Web site (server) on behalf of a user, the server sends its certificate to the browser so that the browser can verify the identity of the server. This ensures that the user does not divulge confidential information (such as credit card information) to a bogus server. Recently, a new standard allows the use of Kerberos with TLS. This means instead of using certificate-based authentication, an application can use Kerberos credentials and take advantage of the Kerberos infrastructure in the deployment environment. Using Kerberos cipher suites also provides automatic support for mutual authentication in which the client is also authenticated in addition to the server.

The decision of whether to use Java GSS, Java SASL, or JSSE for a particular application often depends upon several factors, including (the protocols being used by) the services with which the application interacts, the deployment environment (PKI or Kerberos-based), and the application's security requirements. JSSE provides a secure end-to-end channel that takes care of the I/O and transport, while Java GSS and Java SASL provide encryption and integrity-protection on the data, but the application is responsible for transporting the secured data to its peer. Some details about factors for deciding when to use JSSE versus Java GSS are presented in the document, When to use Java GSS vs. JSSE.

Resources for this exercise:

  1. Java Secure Socket Extension (JSSE) Reference Guide
  2. The JSSE javadocs: javax.net and javax.net.ssl
  3. The SSL Protocol version 3.0
  4. The TLS Protocol Version 1.0 (RFC 2246)
  5. Addition of Kerberos Cipher Suites to Transport Layer Security TLS (RFC 2712)
  6. When to use Java GSS vs. JSSE

Overview of this exercise:

This exercise is a client-server application that demonstrates how to communicate securely using the JSSE and Kerberos cipher suites. The client and server parts first authenticate to Kerberos using Exercise 1. This stores the credentials in the subject. The application then executes an action that performs JSSE operations (using a Kerberos cipher suite) inside of a Subject.doAs using the subject. The Kerberos cipher suite implementation, because it is executing inside the doAs, obtains the Kerberos credentials from the subject, and uses them to authenticate with the peer and to exchange messages securely. This example sends newline-terminated messages, encrypted using the negotiated cipher suite and integrity-protected, back and forth between client and server.

According to the standard (RFC 2712) all Kerberos-enabled TLS applications use the same service name, namely, "host". That is why in this exercise, you do not need to explicitly supply the Kerberos service name.

Steps to follow:

  1. Read the following code. This is located in src/JsseServer.java

    This code fragment defines the action to execute after the service principal has authenticated to the KDC. It replaces the MyAction of line 11 of Exercise 1. Note the highlighted lines. The server first creates an SSLServerSocket [lines 5-8]. This is analogous to an application creating a plain ServerSocket except an SSLServerSocket will provide automatic authentication, encryption and decryption, as needed. The server then sets the cipher suites that it wants to use [lines 11-12]. The server then runs in a loop, accepting connections from SSL clients [line 17], and reads and writes from the SSL socket [lines 23, 28]. The server can find out the identities of the owners of socket by invoking the getLocalPrincipal() and getPeerPrincipal() methods [lines 32-33].

Code listing for JsseServer.java.

  1. static class JsseServerAction implements PrivilegedExceptionAction {
  2. ...
  3.   public Object run() throws Exception {
  4.     // Create TLS socket for accepting connections
  5.     SSLServerSocketFactory sslssf =
  6.       (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
  7.     SSLServerSocket sslServerSocket =
  8.       (SSLServerSocket) sslssf.createServerSocket(localPort);

  10.     // Enable only a Kerberos cipher suite
  11.     String enabledSuites[] = { "TLS_KRB5_WITH_3DES_EDE_CBC_SHA" };
  12.     sslServerSocket.setEnabledCipherSuites(enabledSuites);
  13.     // Should handle exception if enabledSuites is not supported

  15.     while (true) {
  16.       // Create socket to handle request
  17.       SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
  18.       BufferedReader in = new BufferedReader(new InputStreamReader(
  19.         sslSocket.getInputStream()));
  20.       BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
  21.         sslSocket.getOutputStream()));

  23.       String inStr = in.readLine();
  24.       // ... use inStr

  26.       // Compose and send reply
  27.       String outStr = inStr + " " + new Date().toString() + "\n";
  28.       out.write(outStr);
  29.       out.flush();

  31.       // Get names of principal at both ends of secure connection
  32.       Principal self = sslSocket.getSession().getLocalPrincipal();
  33.       Principal peer = sslSocket.getSession().getPeerPrincipal();

  35.       sslSocket.close();
  36.     }
  37.   }
  38. }

  2. Compile the sample code.
    % javac JsseServer.java
  3. Read the following code. This is located in src/JsseClient.java. This code fragment defines the action to execute after the client principal has authenticated to the KDC. It replaces the MyAction of line 11 of Exercise 1. Note the highlighted lines. The client first creates an SSLSocket. The client then sets the cipher suites that it wants to use [lines 11-12]. The client then exchanges messages with the server using the SSLSocket by reading and writing to the socket's input/output streams. The client can find out the identities of the owners of socket by invoking the getLocalPrincipal() and getPeerPrincipal() methods [lines 26-27].

Code listing for JsseClient.java

  1. static class JsseClientAction implements PrivilegedExceptionAction {
  2. ...
  3.   public Object run() throws Exception {
  4.     // Create SSL connection
  5.     SSLSocketFactory sslsf = (SSLSocketFactory) SSLSocketFactory.getDefault();
  6.     SSLSocket sslSocket = (SSLSocket) sslsf.createSocket(server, port);

  8.     // Enable only a Kerberos cipher suite
  9.     String enabledSuites[] = { "TLS_KRB5_WITH_3DES_EDE_CBC_SHA" };
  10.     sslSocket.setEnabledCipherSuites(enabledSuites);
  11.     // Should handle exception if enabledSuites is not supported

  13.     BufferedReader in = new BufferedReader(new InputStreamReader(
  14.       sslSocket.getInputStream()));
  15.     BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
  16.       sslSocket.getOutputStream()));

  18.     String outStr = ...;
  19.     out.write(outStr);
  20.     out.flush();

  22.     String inStr = in.readLine();
  23.     // ... use inStr

  25.     // Get names of principal at both ends of secure connection
  26.     Principal self = sslSocket.getSession().getLocalPrincipal();
  27.     Principal peer = sslSocket.getSession().getPeerPrincipal();

  29.     sslSocket.close();
  30.     return null;
  31.   }
  32. }

  4. Compile the sample code.
    % javac JsseClient.java
  5. Launch a new window and start the server. JsseServer takes one parameter: the name of the server that the JSSE service is running on. For example, if it is running on the machine j1hol-001, you would enter the following.
    % xterm &

% java

 -Djava.security.auth.login.config=jaas-krb5.conf \

       JsseServer j1hol-001
  6. Run the client application. JsseClient takes one parameter: the name of the server that the JSSE service is running on. For example, if the service is running on the machine j1hol-001, you would enter the following. When prompted for a password, enter changeit.
    % java -Djava.security.auth.login.config=jaas-krb5.conf \
    JsseClient j1hol-001
  7. Observe the following output in the client and server applications' windows.

Output for running the JsseServer example.

  1. Authenticated principal: [host/j1hol-001@J1LABS.EXAMPLE.COM]
  2. Waiting for incoming connections...
  3. Got connection from client /129.145.128.102
  4. Received: Hello There!
  5. Sending: Hello There! Fri May 07 15:32:37 PDT 2005
  6. Cipher suite in use: TLS_KRB5_WITH_3DES_EDE_CBC_SHA
  7. I am: host/j1hol-001@J1LABS.EXAMPLE.COM
  8. Client is: test@J1LABS.EXAMPLE.COM

Output for running the JsseClient example.

  1. Kerberos password for test: changeit
  2. Authenticated principal: [test@J1LABS.EXAMPLE.COM]
  3. Sending: Hello There!
  4. Received: Hello There! Fri May 07 15:32:37 PDT 2005
  5. Cipher suite in use: TLS_KRB5_WITH_3DES_EDE_CBC_SHA
  6. I am: test@J1LABS.EXAMPLE.COM
  7. Server is: host/j1hol-001@J1LABS.EXAMPLE.COM

Summary:

In this exercise, you learned how to write a client-server application that uses JSSE to authenticate and communicate securely with each other, using Kerberos as the underlying authentication system.

Next Steps

  1. Proceed to Exercise 6 to learn how to configure the sample programs in Exercises 3, 4, and 5 to achieve single sign-on in a Kerberos environment.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Advanced JGSS Security Programming

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Part III : Deploying for Single Sign-On in a Kerberos Environment

Exercise 6: Deploying for Single Sign-On

Goal of this exercise:

The goal of this exercise is to learn how to configure a JAAS application that uses Kerberos for authentication to achieve single sign-on. Single sign-on means that the user needs only authenticate once to a system or a collection of services. After the initial authentication, the user can access other services in the system using the same identity as he used for the initial authentication.

Single sign-on can be used to describe different types of authentication. There are HTTP-based network single sign-on protocols. There is Kerberos-based single sign-on for network services. In this particular exercise, we show how to achieve single sign-on in Kerberos-based systems by showing how to import already-acquired Kerberos credentials from the underlying native operating system.

Background and Resources for this exercise:

  1. Single Sign-On Using Kerberos in Java

In addition, see the information provided in Exercises 2 and 4 for background information about Kerberos and Java GSS.

Steps to follow:

  1. Edit the JAAS configuration file. This is located in src/jaas-krb5.conf

This file contains two entries, one named "client" and one named "server." Add the line "useTicketCache=true" to the client entry.

Code listing for updated jaas-krb5.conf.

  1. client {
  2.     com.sun.security.auth.module.Krb5LoginModule required
  3.     useTicketCache=true
  4.     principal="test";
  5. };
  6. server {
  7.    com.sun.security.auth.module.Krb5LoginModule required
  8.     useKeyTab=true
  9.     storeKey=true
  10.     keyTab=sample.keytab
  11.     principal="host/j1hol-001";
  12. };

  2. Perform Kerberos login to the native operating system.
    To login to Kerberos, use kinit command as follows.
    % kinit test
    Then, enter changeit when prompted for the password.
  3. Run the client and server programs in Exercises 1-5 as before and you will note that the client applications no longer ask you to enter a password.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Advanced JGSS Security Programming

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Part IV : Secure Communications using stronger encryption algorithms (Java SE 6.0)

Exercise 7: Configuring to use stronger encryption algorithms in a Kerberos environment, to secure the communication

Goal of this exercise:

The goal of this exercise is to learn how to use various Kerberos encryption algorithms to secure the communication. In J2SE 1.4, Java GSS/Kerberos provided support for only DES encryption type. The Java GSS/Kerberos provider has been enhanced in J2SE 5.0 and later releases to support stronger Kerberos encryption algorithms, and is in compliance with latest Kerberos specification RFC4120. Support for various Kerberos encryption types, such as AES256, AES128, 3DES, RC4-HMAC, and DES are now all available. J2SE 5.0 supports 3DES and DES Kerberos encryption types. Support for AES and RC4-HMAC in Kerberos is available for Java SE 6 onwards.

Here is a list of all the encryption types supported by the Java GSS/Kerberos provider in Java SE 6.0:

  1. AES256-CTS
  2. AES128-CTS
  3. RC4-HMAC
  4. DES3-CBC-SHA1
  5. DES-CBC-MD5
  6. DES-CBC-CRC

Steps to follow:

  1. Configure the Key Distribution Center (KDC) and update the Kerberos database

    At first you need to update to use the Key Distribution Center (KDC) that supports the required Kerberos encryption types, such as Solaris 10 or the latest MIT Kerberos 1.4 from MIT distribution. If you are using the Active Directory on a Windows platform, it only supports DES and RC4-HMAC encryption types.

    You will need to update the Kerberos database, to generate the new keys with stronger encryption algorithms. By default, Solaris 10 KDC will generate the keys for all the above encryption types listed. You can now create a keytab that will include all the keys for all the above encryption types.

    NOTE: If you want to use Windows 2000 KDC, you can configure to use the DES and RC4-HMAC encryption types that are available on the Windows machine.

  2. Edit the Kerberos configuration file. This is located in src/krb5.conf

    You will need to edit the Kerberos configuration file in order to select the desired encryption types used. The required parameters are listed below, that you will need to insert under the libdefaults section of the Kerberos configuration file. For the purpose of this exercise, all the required entries have been added to a sample Kerberos configuration file included with the exercise, and the entries have been commented out. To enable the desired encryption type, you only need to uncomment the required entries.

    • To enable AES256-CTS encryption type

      [libdefaults]
      default_tkt_enctypes = aes256-cts
default_tgs_enctypes = aes256-cts
permitted_enctypes = aes256-cts
      NOTE: Solaris 10 does not support AES256 by default. You will need to install the following packages:-

      SUNWcry, SUNWcryr, SUNWcryptoint
      In addition, JCE in Java SE also does not support AES256 by default.

      You will need to install the JCE crypto policy with the unlimited version to allow AES with 256-bit key.

    • To enable the AES128-CTS encryption type

      [libdefaults]
      default_tkt_enctypes = aes128-cts
      default_tgs_enctypes = aes128-cts
      permitted_enctypes = aes128-cts

    • To enable RC4-HMAC encryption type

      [libdefaults]
      default_tkt_enctypes = rc4-hmac
      default_tgs_enctypes = rc4-hmac
      permitted_enctypes = rc4-hmac

    • To enable DES3-CBC-SHA1 encryption type

      [libdefaults]
      default_tkt_enctypes = des3-cbc-sha1
      default_tgs_enctypes = des3-cbc-sha1
      permitted_enctypes = des3-cbc-sha1

    • To enable DES-CBC-MD5 encryption type

      [libdefaults]
      default_tkt_enctypes = des-cbc-md5
      default_tgs_enctypes = des-cbc-md5
      permitted_enctypes = des-cbc-md5

    • To enable DES-CBC-CRC encryption type

      [libdefaults]
      default_tkt_enctypes = des-cbc-crc
      default_tgs_enctypes = des-cbc-crc
      permitted_enctypes = des-cbc-crc

      NOTE: If the above parameters are not added to the Kerberos configuration file, Solaris 10 will default to use AES128 enctype. If the exportable crypto packages have been installed, it will default to use AES256 enctype.

      NOTE: Destroy any pre-existing Kerberos TGT in the ticket cache from the previous exercise.

% kdestroy

    • Launch a new window and start the server using the updated krb5.conf

      % xterm &
            % java
        -Djava.security.auth.login.config=jaas-krb5.conf \
        -Djava.security.krb5.conf=krb5.conf \
         GSSServer
    • Run the client application using the updated krb5.conf. GssClient takes two parameters: the service name and the name of the server that the service is running on. For example, if the service is host running on the machine j1hol-001, you would enter the following. When prompted for the password, enter changeit.

% java
-Djava.security.auth.login.config=jaas-krb5.conf
         -Djava.security.krb5.conf=krb5.conf \
      GSSClient host j1hol-001

Summary:

In this exercise, you learned how to write a client-server application that uses Java GSS API to authenticate and communicate securely with each other, using stronger Kerberos encryption algorithms. You can enable Kerberos debugging (-Dsun.security.krb5.debug=true), to obtain information about the Kerberos encryption type used.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Advanced JGSS Security Programming

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Part V : Secure Authentication using SPNEGO Java GSS mechanism (Java SE 6.0)

Exercise 8: Using the Java Generic Security Services (GSS) API with SPNEGO

Goal of this exercise:

Currently the only security mechansim available with Java GSS is "Kerberos". The goal of this exercise is to learn how to use other Java GSS mechanisms, such as SPNEGO, to secure the association. This feature is available from Java SE 6 onwards.

What is SPNEGO?

Java GSS is a framework that can support multiple security mechanisms; a way to negotiate a security mechanism underneath GSS-API is needed. This is available via SPNEGO.

SPNEGO is the Simple and Protected GSS-API Negotiation Mechanism, standardized at IETF in RFC 4178. It's a pseudo-security mechanism used to negotiate an underlying security mechanism. It provides the flexibility for client and server to securely negotiate a common GSS security mechanism.

Microsoft makes heavy use of SPNEGO. SPNEGO can be used to inter-operate with Microsoft Server over HTTP, to support HTTP-based Cross-Platform authentication via the Negotiate Protocol.

What do I need do to use SPNEGO in Java GSS?

Currently when using Java GSS with Kerberos, we specify the Kerberos OID to use Kerberos.

Oid krb5Oid = new Oid("1.2.840.113554.1.2.2");

In order to use SPNEGO, you only need to specify the SPNEGO OID as follows:-

Oid spnegoOid = new Oid("1.3.6.1.5.5.2");

And henceforth use the SPNEGO OID when creating a GSSCredential, GSSContext, etc.

Steps to follow:

  1. Read the following code. This is located in src/GssSpNegoClient.java

Code listing for GssSpNegoClient.java.

  1. static class GssSpnegoClientAction implements PrivilegedExceptionAction {
  2. ...
  3.   public Object run() throws Exception {
  4.     // Create socket to server
  5.     Socket socket = new Socket(hostName, port);
  6.     DataInputStream inStream = new DataInputStream(socket.getInputStream());
  7.     DataOutputStream outStream = new DataOutputStream(socket.getOutputStream());

  9.     // Get service's principal name
  10.     GSSManager manager = GSSManager.getInstance();
  11.     Oid spnegoOid = new Oid("1.3.6.1.5.5.2");
  12.     GSSName serverName = manager.createName(serverPrinc, GSSName.NT_HOSTBASED_SERVICE, spnegoOid);

  14.     // Get the context for authentication
  15.     GSSContext context = manager.createContext(serverName, spnegoOid, null,
  16.        GSSContext.DEFAULT_LIFETIME);
  17.     context.requestMutualAuth(true); // Request mutual authentication
  18.     context.requestConf(true); // Request confidentiality

  20.     // Do the context establishment loop
  21.     byte[] token = new byte[0];
  22.     while (!context.isEstablished()) {
  23.       token = context.initSecContext(token, 0, token.length);
  24.       outStream.writeInt(token.length);
  25.       outStream.write(token);
  26.       outStream.flush();

  28.       // Check if we're done
  29.       if (!context.isEstablished()) {
  30.         token = new byte[inStream.readInt()];
  31.         inStream.readFully(token);
  32.       }
  33.     }

  35.     // Context established!

  37.     // Create MessageProp for use with unwrap (true means request confidentiality)
  38.     MessageProp prop = new MessageProp(0, true);

  40.     // Create encrypted message and send to server
  41.     byte[] reply = ...;
  42.     token = context.wrap(reply, 0, reply.length, prop);

  44.     outStream.writeInt(token.length);
  45.     outStream.write(token);
  46.     outStream.flush();

  48.     // Read token from server
  49.     token = new byte[inStream.readInt()];
  50.     inStream.readFully(token);

  52.     // Unwrap (decrypt) token sent by server
  53.     byte[] input = context.unwrap(token, 0, token.length, prop);
  54.     ...
  55.     context.dispose();
  56.     socket.close();
  57.     return null;
  58.   }
  59. }

  2. Compile the sample code.
    % javac GssSpNegoClient.java
  3. Read the following code. This is located in src/GssSpNegoServer.java

Code listing for GssSpNegoServer.java.

  1. static class GssSpNegoServerAction implements PrivilegedExceptionAction {
  2. ...
  3.   public Object run() throws Exception {
  4.     // Create server socket for accepting connections
  5.     ServerSocket ss = new ServerSocket(localPort);

  7.     // Get own Kerberos credentials for accepting connection
  8.     GSSManager manager = GSSManager.getInstance();
  9.     Oid spnegoOid = new Oid("1.3.6.1.5.5.2");
  10.     GSSCredential serverCreds = manager.createCredential(null,
  11.       GSSCredential.DEFAULT_LIFETIME, spnegoOid, GSSCredential.ACCEPT_ONLY);

  13.     while (true) {
  14.       Socket socket = ss.accept();
  15.       DataInputStream inStream = new DataInputStream(socket.getInputStream());
  16.       DataOutputStream outStream = new DataOutputStream(socket.getOutputStream());

  18.       GSSContext context = manager.createContext((GSSCredential)serverCreds);

  20.       // Do the context establishment loop
  21.       byte[] token = null;
  22.       while (!context.isEstablished()) {
  23.         // Read token
  24.         token = new byte[inStream.readInt()];
  25.         inStream.readFully(token);

  27.         // Process token
  28.         token = context.acceptSecContext(token, 0, token.length);

  30.         // Send a token to the peer if one was generated by acceptSecContext
  31.         outStream.writeInt(token.length);
  32.         outStream.write(token);
  33.         outStream.flush();
  34.       }

  36.       // Context established!

  38.       // Create MessageProp for use with unwrap (will be set upon return from unwrap)
  39.       MessageProp prop = new MessageProp(0, false);

  41.       // Read token from client
  42.       token = new byte[inStream.readInt()];
  43.       inStream.readFully(token);
  44.       // Unwrap (decrypt) token sent by client
  45.       byte[] input = context.unwrap(token, 0, token.length, prop);
  46.       ...
  47.       // Create new token and send to client
  48.       byte[] reply = ...;
  49.       token = context.wrap(reply, 0, reply.length, prop);

  51.       outStream.writeInt(token.length);
  52.       outStream.write(token);
  53.       outStream.flush();
  54.       context.dispose();
  55.       socket.close();
  56.     }
  57.   }
  58. }

  4. Compile the sample code.
    % javac GssSpNegoServer.java
  5. Launch a new window and start the server.

% xterm &
% java -Djava.security.auth.login.config=jaas-krb5.conf GssSpNegoServer
  6. Run the client application. GssClient takes two parameters: the service name and the name of the server that the service is running on. For example, if the service is host running on the machine j1hol-001, you would enter the following. When prompted for the password, enter changeit.

% java -Djava.security.auth.login.config=jaas-krb5.conf \
GssSpNegoClient host j1hol-001

Output for running the GssSpNegoServer example.

  1. Authenticated principal: [host/j1hol-001@J1LABS.EXAMPLE.COM]
  2. Waiting for incoming connections...
  3. Got connection from client /129.145.128.102
  4. SPNEGO Negotiated Mechanism = 1.2.840.113554.1.2.2 Kerberos V5
  5. Context Established!
  6. Client principal is test@J1LABS.EXAMPLE.COM
  7. Server principal is host/j1hol-001@J1LABS.EXAMPLE.COM
  8. Mutual authentication took place!
  9. Received data "Hello There!" of length 12
  10. Confidentiality applied: true
  11. Sending: Hello There! Thu May 06 12:11:15 PDT 2005

Output for running the GssSpNegoClient example.

  1. Kerberos password for test: changeit
  2. Authenticated principal: [test@J1LABS.EXAMPLE.COM]
  3. Connected to address j1hol-001/129.145.128.102
  4. SPNEGO Negotiated Mechanism = 1.2.840.113554.1.2.2 Kerberos V5
  5. Context Established!
  6. Client principal is test@J1LABS.EXAMPLE.COM
  7. Server principal is host@j1hol-001
  8. Mutual authentication took place!
  9. Sending message: Hello There!
  10. Will read token of size 93
  11. Received message: Hello There! Thu May 06 12:11:15 PDT 2005

Summary:

In this exercise, you learned how to write a client-server application that uses the Java GSS API with SPNEGO to negotiate an underlying security mechanism, such as Kerberos, and communicate securely using Kerberos as the underlying authentication system.

Note: Microsoft has implemented certain variations of the SPNEGO protocol, hence to inter-operate with Microsoft, we have added an MS mode via a new system property "sun.security.spnego.msinterop". This property is enabled to "true" by default. To disable it, you need to explicitly set this property to "false". To enable SPNEGO debugging, you can set the system property "sun.security.spnego.debug=true".

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Part VI: SPEGNO Authenticatio

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Part VI: HTTP/SPNEGO Authentication

  • Exercise 9: Using HTTP/SPNEGO Authentication

  • What is HTTP SPNEGO
    • Web Authentication
    • Proxy Authentication
  • How to use HTTP/SPNEGO Authentication
    • Kerberos 5 Configuration
    • Username and Password Retrieval
    • Scheme Preference
    • Fallback

  • Example

Exercise 9: Using HTTP/SPNEGO Authentication

What is HTTP SPNEGO

HTTP SPNEGO supports the Negotiate authentication scheme in an HTTP communication. SPNEGO supports types of authentication:

Web Authentication

The Web Server responds with

       HTTP/1.1 401 Unauthorized
       WWW-Authenticate: Negotiate

the client will need to send a header like

       Authorization: Negotiate YY.....

to authenticate itself to the server

Proxy Authentication

The Web Server responses with

       HTTP/1.1 407 Proxy Authentication Required
       Proxy-Authenticate: Negotiate

the client will need to send a header like

       Proxy-Authorization: Negotiate YY.....

to authenticate itself to the proxy server

This feature supports both types of authentication.

How to use HTTP/SPNEGO Authentication

There is no new public API function involved in the new feature, but several configurations are needed to perform a success communication:

Kerberos 5 Configuration

Since the SPNEGO mechanism will call JGSS, which in turns calls the Kerberos V5 login module to do real works. Kerberos 5 configurations are needed. This includes the following:

  • Some way to provide Kerberos configurations. This can be achieved with the Java system property java.security.krb5.conf. For example:

            java -Djava.security.krb5.conf=krb5.conf \
                 -Djavax.security.auth.useSubjectCredsOnly=false \
                 ClassName
  • A JAAS config file denoting what login module to use. HTTP SPNEGO codes will look for the standard entry named com.sun.security.jgss.krb5.initiate.
For example, you can provide a file spnegoLogin.conf:
          com.sun.security.jgss.krb5.initiate {
              com.sun.security.auth.module.Krb5LoginModule
                  required useTicketCache=true;
          };

and run java with:

            java -Djava.security.krb5.conf=krb5.conf \
                 -Djava.security.auth.login.config=spnegoLogin.conf \
                 -Djavax.security.auth.useSubjectCredsOnly=false \
                 ClassName

Username and Password Retrieval

Just like any other HTTP authentication scheme, the client can provide a customized java.net.Authenticator to feed username and password to the HTTP SPNEGO module if they are needed (i.e. there is no credential cache available). The only authentication information needed to be checked in your Authenticator is the scheme which can be retrieved with getRequestingScheme(). The value should be "Negotiate".

This means your Authenticator implementation will look like:
    class MyAuthenticator extends Authenticator {

        public PasswordAuthentication getPasswordAuthentication () {
            if (getRequestingScheme().equalsIgnoreCase("negotiate")) {
                String krb5user;
                char[] krb5pass;
                // get krb5user and krb5pass in your own way
                ....
                return (new PasswordAuthentication (krb5user,
                            krb5pass));
            } else {
                ....
            }
        }
    }

Note : According to the specification of java.net.Authenticator, it's designed to get the username and password at the same time, so do not specify principal=xxx in the JAAS config file.

Scheme Preference

The client can still provide system property http.auth.preference to denote that a certain scheme should always be used as long as the server request for it. You can use "SPNEGO" or "Kerberos" for this system property. "SPNEGO" means you prefer to response the Negotiate scheme using the GSS/SPNEGO mechanism; "Kerberos" means you prefer to response the Negotiate scheme using the GSS/Kerberos mechanism. Normally, when authenticating against a Microsoft product, you can use "SPNEGO". The value "Kerberos" also works for Microsoft servers. It's only needed when you encounter a server which knows Negotiate but doesn't know about SPNEGO.

If http.auth.preference is not set, the internal order choosen is:

  • GSS/SPNEGO -> Digest -> NTLM -> Basic

Noticed that Kerberos does not appear in this list, since whenever Negotiate is supported, GSS/SPNEGO is always chosen.

Fallback

If the server has provided more than one authentication scheme (including Negotiate), according to the processing order mentioned in the last section, Java will try to challenge the Negotiate scheme. However, if the protocol cannot be established successfully (for example; The kerberos configuration is not correct, or the server's hostname is not recorded in the KDC principal DB, or the username and password provided by Authenticator is wrong), then the second strongest scheme will be automatically used.

Note : If http.auth.preference is set to SPNEGO or Kerberos, then SPNEGO assumes you only want to try the Negotiate scheme even if it fails. SPNEGO will not fallback to any other scheme and your program will throw an IOException saying it received a 401 or 407 error from the HTTP response.

Example

Assume that you have an IIS Server running on a Windows Server within an Active Directory. A web page on this server is configured to be protected by Integrated Windows Authentication. This means the server will prompt for both Negotiate and NTLM authentication.

You need to prepare these files to get the protected file:

Code listing for RunHttpSpnego.java

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;

public class RunHttpSpnego {

    static final String kuser = "username"; // your account name
    static final String kpass = "password"; // your password for the account

    static class MyAuthenticator extends Authenticator {
        public PasswordAuthentication getPasswordAuthentication() {
            // I haven't checked getRequestingScheme() here, since for NTLM
            // and Negotiate, the usrname and password are all the same.
            System.err.println("Feeding username and password for "
               + getRequestingScheme());
            return (new PasswordAuthentication(kuser, kpass.toCharArray()));
        }
    }

    public static void main(String[] args) throws Exception {
        Authenticator.setDefault(new MyAuthenticator());
        URL url = new URL(args[0]);
        InputStream ins = url.openConnection().getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
        String str;
        while((str = reader.readLine()) != null)
            System.out.println(str);
    }
}

Code listing for krb.conf

[libdefaults]
    default_realm = AD.LOCAL
[realms]
    AD.LOCAL = {
        kdc = kdc.ad.local
    }

Code listing for login.conf

com.sun.security.jgss.krb5.initiate {
  com.sun.security.auth.module.Krb5LoginModule required
 doNotPrompt=false useTicketCache=true;
};

Then, compile RunHttpSpnego.java and run

java -Djava.security.krb5.conf=krb5.conf \
    -Djava.security.auth.login.config=login.conf \
    -Djavax.security.auth.useSubjectCredsOnly=false \
    RunHttpSpnego \
    http://www.ad.local/hello/hello.html

You will see:

Feeding username and password for Negotiate
<h1>Hello, You got me!</h1>

In fact, if you are running on a Windows machine as a domain user, or, you are running on a Linux or Solaris machine that has already issued the kinit command and got the credential cache. The class MyAuthenticator will be completely ignored, and the output will be simply

<h1>Hello, You got me!</h1>

which shows the username and password are not consulted. This is the so-called Single Sign-On.

Also, You can just run

java RunHttpSpnego \
    http://www.ad.local/hello/hello.html

to see how the fallback is done, in which case you will see

Feeding username and password for ntlm
<h1>Hello, You got me!</h1>
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.PathSearchingVirtualMachine (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.PathSearchingVirtualMachine

No usage of com.sun.jdi.PathSearchingVirtualMachine
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Indeterminate Progress Bars

This document describes the changes we made to implement indeterminate progress bars -- GUI components that look similar to normal progress bars and, like normal progress bars, use animation to show that a time-consuming operation is occurring. Unlike normal progress bars, indeterminate progress bars do not show the degree of completeness of the operation. This document has the following sections:

  • New JProgressBar API
  • New UI Defaults
  • New BasicProgressBarUI API
  • Converting Existing Progress Bar Implementations
  • Implementation Details
  • Javadoc for New API

New JProgressBar API

By default, every progress bar (created using one of several JProgressBar constructors) is determinate. You may make any JProgressBar indeterminate using the setIndeterminate method:

    pb.setIndeterminate(true);

An indeterminate progress bar animates constantly. You can stop the animation and clear the progress bar by making the progress bar determinate and setting the current value to the minimum. For example:

    pb.setValue(pb.getMinimum());
    pb.setIndeterminate(false);

You can switch from determinate to indeterminate mode, and vice versa, at any time. You can check whether the progress bar is indeterminate using the isIndeterminate method.

When a progress bar is indeterminate, it ignores its model (a BoundedRangeModel). However, the model should exist and contain legal data, since L&Fs that haven't been updated for indeterminate progress bars might use the model.

New UI Defaults

To give developers control over the progress bar's speed of animation, we've added two new UI defaults:

  • "ProgressBar.repaintInterval"
  • "ProgressBar.cycleTime"

The "ProgressBar.cycleTime" UI default lets look and feel implementers (as well as other developers)specify how many milliseconds each animation cycle takes. For example, a cycle time of 500 means that the indeterminate-mode progress bar animation repeats twice per second. The default drawing code uses this value --along with the repaint interval, box length, and component inner area --to determine how far to move the bouncing box each time it's drawn. This value must be an even multiple of the repaint interval. For example, if the repaint interval is 100, then valid cycle times are 200, 1000, and 1200, but not 100 or 500. If the user specifies an invalid cycle time,the indeterminate progress bar code automatically increases the cycle time to a suitable value.

To set the repaint interval and cycle time defaults:

    UIManager.put("ProgressBar.repaintInterval", new Integer(250));
    UIManager.put("ProgressBar.cycleTime", new Integer(6000));

To get the repaint interval and cycle time:

    int interval = UIManager.getInt("ProgressBar.repaintInterval");
    int totalTime = UIManager.getInt("ProgressBar.cycleTime");

In the basic, JLF, Motif, and Windows implementations provided by Sun, these defaults are checked when (and only when) the progress bar is switching into indeterminate mode.

New BasicProgressBarUI API

To help programmers implement look-and-feel code for progress bars,we have added the following API to the BasicProgressBarUI class.

Methods related to painting:

  • protected void paintIndeterminate(Graphics g, JComponent c)
  • protected void paintDeterminate(Graphics g, JComponent c)
  • protected Rectangle getBox(Rectangle)

Methods for setting and getting the index of the current frame of animation:

  • protected int getAnimationIndex()
  • protected void setAnimationIndex(int newValue)
  • protected void incrementAnimationIndex()

Methods for starting and stopping custom animation threads:

  • protected void startAnimationTimer()
  • protected void stopAnimationTimer()

The paint method that previously performed all painting for the progress bar now delegates all its drawing to either paintDeterminate or paintIndeterminate, depending on the value of the progress bar's indeterminate property. When the progress bar is in indeterminate mode, the paint method (and thus the paintIndeterminate method) executes every repaint interval milliseconds.The paintIndeterminate method should paint the progress bar to match the animation state, which is specified by the getAnimationIndex method.

The getBox method allows implementations to customize bouncing box painting. For example, MetalProgressBarUI invokes getBox in its paintIndeterminate method to get the box drawn by the superclass (BasicProgressBarUI) and then to add an outline to the box. By overriding the getBox method, an implementer gets full control over the bouncing box's size and position without needing to reimplement paintIndeterminate.

If you override paintIndeterminate or getBox, you might also have to override incrementAnimationIndex so that it cycles correctly through the valid values. The first value (representing the first drawing) is 0. By convention, the second is 1, the third is 2, and so on. The last legal value is, by convention, the total number of drawings in the animation cycle, minus one. To determine the total number of drawings, you may need to take into account the repaint interval and perhaps the component size. As the "by convention" implies, you can implement the animation index to have any meaning and values you wish, as long as zero indicates the beginning of the animation cycle.

If you don't want to use the animation thread we provide, you must override the two xxx AnimationTimer methods. You can then provide your own implementation that periodically increments the animation index and invokes repaint on the progress bar.

As a side effect of the progress bar work, we've added a new method to SwingUtilities:

  • public static Rectangle calculateInnerArea(Component c, Rectangle r)

The calculateInnerArea method is useful to all classes that perform drawing. It returns the area in which the component can draw -- that is, the rectangle (in the component's coordinate system) that includes all of the component except its border area (the component's insets).

Converting Existing Progress Bar Implementations

Converting an existing L&F to indeterminate progress bars is relatively straightforward. If the L&F's progress bar UI class doesn't override paint (or does but also invokes super.paint), then support for indeterminate progress bars is automatic. WindowsProgressBarUI, MotifProgressBarUI, and MetalProgressBarUI are in this lucky camp.

If the L&F's progress bar UI class is a subclass of BasicProgressBarUI and overrides paint without invoking the superclass version, then determinate mode still works, but indeterminate mode looks the same as determinate mode.

Existing drawing code should be moved out of the paint method and into the new paintDeterminate method. Code for indeterminate painting should go in the new paintIndeterminate method. If at all possible, the paint method should not be overridden unless it invokes super.paint. The reason: the BasicProgressBarUI implementation of the paint method may work with the default animation thread to enhance performance and behavior.

The Mac look and feel (both the no-longer-maintained Sun version and the Apple version) is an example of a look and feel that overrides paint without invoking the superclass version.

If you already have a thread scheme for indeterminate painting, you can continue to use that scheme by overriding startAnimationTimer and stopAnimationTimer. Or you can just delete your thread code and use our scheme.

Implementation Details

The BasicProgressBarUI class contains most of our implementation of indeterminate progress bars. Aside from the drawing code, most of the code is in two private inner classes: Animator, which implements the animation thread, andPropertyChangeHandler, which listens for changes to and from indeterminate mode.

The Animator implements the default animation thread, using the Swing Timer class. An Animator instance is created if necessary by the BasicProgressBarUI.startAnimationTimer method, which the property handler invokes when the progress bar switches to indeterminate mode. When the progress bar is indeterminate, the Animator timer fires an action event once every repaint interval milliseconds. Animator's action event handler invokes incrementAnimationIndex, followed by repaint (which causes paintIndeterminate to run). Repaint interval is specified by the ProgressBar.repaintInterval UI default, which is checked by startAnimationTimer.

The PropertyChangeHandler registers itself as a property listener on the progress bar. When it detects the "indeterminate" property changing,the handler notes the change and invokes either stopAnimationTimer or startAnimationTimer.

Javadoc for New API

In javax.swing.JProgressBar:

    public void setIndeterminate(boolean newValue)

    public boolean isIndeterminate()

In javax.swing.plaf.basic.BasicProgressBarUI:

    protected void paintIndeterminate(Graphics g, JComponent c)

    protected void paintDeterminate(Graphics g, JComponent c)

    protected int getAnimationIndex()

    protected void setAnimationIndex(int newValue)

    protected void incrementAnimationIndex()

    protected void startAnimationTimer()

    protected void stopAnimationTimer()

    protected Rectangle getBox(Rectangle r)

In javax.swing.SwingUtilities:

    public static Rectangle calculateInnerArea(JComponent c, Rectangle r)
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java ™ HotSpot Virtual Machine Performance Enhancements

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java HotSpot™ Virtual Machine Performance Enhancements

  • Compressed Oops
  • Zero-Based Compressed Oops
  • Escape Analysis
  • NUMA Collector Enhancements

Compressed Oops

An "oop", or ordinary object pointer in Java Hotspot parlance, is a managed pointer to an object. An oop is normally the same size as a native machine pointer, which means 64 bits on an LP64 system. On an ILP32 system, maximum heap size is somewhat less than 4 gigabytes, which is insufficient for many applications. On an LP64 system, the heap used by a given program might have to be around 1.5 times larger than when it is run on an ILP32 system. This requirement is due to the expanded size of managed pointers. Memory is inexpensive, but these days bandwidth and cache are in short supply, so significantly increasing the size of the heap and only getting just over the 4 gigabyte limit is undesirable.

Managed pointers in the Java heap point to objects which are aligned on 8-byte address boundaries. Compressed oops represent managed pointers (in many but not all places in the JVM software) as 32-bit object offsets from the 64-bit Java heap base address. Because they're object offsets rather than byte offsets, they can be used to address up to four billion objects (not bytes), or a heap size of up to about 32 gigabytes. To use them, they must be scaled by a factor of 8 and added to the Java heap base address to find the object to which they refer. Object sizes using compressed oops are comparable to those in ILP32 mode.

The term decode is used to express the operation by which a 32-bit compressed oop is converted into a 64-bit native address into the managed heap. The inverse operation is referred to as encoding.

For Java SE 7, use of compressed oops is the default for 64-bit JVM processes when -Xmx isn't specified and for values of -Xmx less than 32 gigabytes. For JDK 6, use the -XX:+UseCompressedOops flag with the java command to enable the feature under those circumstances.

Zero-Based Compressed Ordinary Object Pointers (oops)

When using compressed oops in a 64-bit Java Virtual Machine process, the JVM software asks the operating system to reserve memory for the Java heap starting at virtual address zero. If the operating system supports such a request and can reserve memory for the Java heap at virtual address zero, then zero-based compressed oops are used.

Use of zero-based compressed oops means that a 64-bit pointer can be decoded from a 32-bit object offset without adding in the Java heap base address. For heap sizes less than 4 gigabytes, the JVM software can use a byte offset instead of an object offset and thus also avoid scaling the offset by 8. Encoding a 64-bit address into a 32-bit offset is correspondingly efficient.

For Java heap sizes up around 26 gigabytes, any of Solaris, Linux, and Windows operating systems will typically be able to allocate the Java heap at virtual address zero.

Escape Analysis

Escape analysis is a technique by which the Java Hotspot Server Compiler can analyze the scope of a new object's uses and decide whether to allocate it on the Java heap.

The Java Hotspot Server Compiler implements the flow-insensitive escape analysis algorithm described in:

 [Choi99] Jong-Deok Shoi, Manish Gupta, Mauricio Seffano,
          Vugranam C. Sreedhar, Sam Midkiff,
          "Escape Analysis for Java", Procedings of ACM SIGPLAN
          OOPSLA  Conference, November 1, 1999

Based on escape analysis, an object's escape state might be one of the following:

  • GlobalEscape – An object escapes the method and thread. For example, an object stored in a static field, or, stored in a field of an escaped object, or, returned as the result of the current method.
  • ArgEscape – An object passed as an argument or referenced by an argument but does not globally escape during a call. This state is determined by analyzing the bytecode of called method.
  • NoEscape – A scalar replaceable object, meaning its allocation could be removed from generated code.

After escape analysis, the server compiler eliminates scalar replaceable object allocations and associated locks from generated code. The server compiler also eliminates locks for all non-globally escaping objects. It does not replace a heap allocation with a stack allocation for non-globally escaping objects.

Some scenarios for escape analysis are described next.

  • The server compiler might eliminate certain object allocations. Consider the example where a method makes a defensive copy of an object and returns the copy to the caller.
    public class Person {
  private String name;
  private int age;
  public Person(String personName, int personAge) {
    name = personName;
                age = personAge;
  }

  public Person(Person p) { this(p.getName(), p.getAge()); }
  public int getName() { return name; }
  public int getAge() { return age; }
}

public class Employee {
  private Person person;

        // makes a defensive copy to protect against modifications by caller
        public Person getPerson() { return new Person(person) };

        public void printEmployeeDetail(Employee emp) {
          Person person = emp.getPerson();
          // this caller does not modify the object, so defensive copy was unnecessary
                System.out.println ("Employee's name: " + person.getName() + "; age: "  + person.getAge());
        }
}
    The method makes a copy to prevent modification of the original object by the caller. If the compiler determines that the getPerson method is being invoked in a loop, it will inline that method. In addition, through escape analysis, if the compiler determines that the original object is never modified, it might optimize and eliminate the call to make a copy.
  • The server compiler might eliminate synchronization blocks (lock elision) if it determines that an object is thread local. For example, methods of classes such as StringBuffer and Vector are synchronized because they can be accessed by different threads. However, in most scenarios, they are used in a thread local manner. In cases where the usage is thread local, the compiler might optimize and remove the synchronization blocks.

NUMA Collector Enhancements

The Parallel Scavenger garbage collector has been extended to take advantage of the machines with NUMA (Non Uniform Memory Access) architecture. Most modern computers are based on NUMA architecture, in which it takes a different amount of time to access different parts of memory. Typically, every processor in the system has a local memory that provides low access latency and high bandwidth, and remote memory that is considerably slower to access.

In the Java HotSpot Virtual Machine, the NUMA-aware allocator has been implemented to take advantage of such systems and provide automatic memory placement optimizations for Java applications. The allocator controls the eden space of the young generation of the heap, where most of the new objects are created. The allocator divides the space into regions each of which is placed in the memory of a specific node. The allocator relies on a hypothesis that a thread that allocates the object will be the most likely to use the object. To ensure the fastest access to the new object, the allocator places it in the region local to the allocating thread. The regions can be dynamically resized to reflect the allocation rate of the application threads running on different nodes. That makes it possible to increase performance even of single-threaded applications. In addition, "from" and "to" survivor spaces of the young generation, the old generation, and the permanent generation have page interleaving turned on for them. This ensures that all threads have equal access latencies to these spaces on average.

The NUMA-aware allocator is available on the Solaris™ operating system starting in Solaris 9 12/02 and on the Linux operating system starting in Linux kernel 2.6.19 and glibc 2.6.1.

The NUMA-aware allocator can be turned on with the -XX:+UseNUMA flag in conjunction with the selection of the Parallel Scavenger garbage collector. The Parallel Scavenger garbage collector is the default for a server-class machine. The Parallel Scavenger garbage collector can also be turned on explicitly by specifying the -XX:+UseParallelGC option.

NUMA Performance Metrics

When evaluated against the SPEC JBB 2005 benchmark on an 8-chip Opteron machine, NUMA-aware systems showed the following performance increases:

  • 32 bit – About 30 percent increase in performance with NUMA-aware allocator
  • 64 bit – About 40 percent increase in performance with NUMA-aware allocator
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Permissions in JDK 7

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Permissions in Java™ SE 7 Development Kit (JDK)

A permission represents access to a system resource. In order for a resource access to be allowed for an applet (or an application running with a security manager), the corresponding permission must be explicitly granted to the code attempting the access.

A permission typically has a name (often referred to as a "target name") and, in some cases, a comma-separated list of one or more actions. For example, the following code creates a FilePermission object representing read access to the file named abc in the /tmp directory:

perm = new java.io.FilePermission("/tmp/abc", "read");

In this, the target name is "/tmp/abc" and the action string is "read".

Important Note: The above statement creates a permission object. A permission object represents, but does not grant access to, a system resource. Permission objects are constructed and assigned ("granted") to code based on the policy in effect. When a permission object is assigned to some code, that code is granted the permission to access the system resource specified in the permission object, in the specified manner. A permission object may also be constructed by the current security manager when making access decisions. In this case, the (target) permission object is created based on the requested access, and checked against the permission objects granted to and held by the code making the request.

The policy for a Java application environment is represented by a Policy object. In the "JavaPolicy" Policy implementation, the policy can be specified within one or more policy configuration files. The policy file(s) specify what permissions are allowed for code from specified code sources. A sample policy file entry that grants code from the /home/sysadmin directory read access to the file /tmp/abc is

grant codeBase "file:/home/sysadmin/" {
    permission java.io.FilePermission "/tmp/abc", "read";
};

For information about policy file locations and granting permissions in policy files, see Default Policy Implementation and Policy File Syntax. For information about using the Policy Tool to specify the permissions, see the Policy Tool documentation (for Solaris) (for Windows). Using the Policy Tool saves typing and eliminates the need for you to know the required syntax of policy files.

Technically, whenever a resource access is attempted, all code traversed by the execution thread up to that point must have permission for that resource access, unless some code on the thread has been marked as "privileged." See API for Privileged Blocks for more information about "privileged" code.

This document contains tables that describe the built-in JDK permission types and discuss the risks of granting each permission. It also contains tables showing the methods that require permissions to be in effect in order to be successful, and for each lists the required permission.

The following topics are covered:

  • Permission Descriptions and Risks
    • java.security.AllPermission
    • java.security.SecurityPermission
    • java.security.UnresolvedPermission
    • java.awt.AWTPermission
    • java.io.FilePermission
    • java.io.SerializablePermission
    • java.lang.reflect.ReflectPermission
    • java.lang.RuntimePermission
      • NIO-Related Targets
    • java.net.NetPermission
    • java.net.SocketPermission
    • java.sql.SQLPermission
    • java.util.PropertyPermission
    • java.util.logging.LoggingPermission
    • javax.net.ssl.SSLPermission
    • javax.security.auth.AuthPermission
    • javax.security.auth.PrivateCredentialPermission
    • javax.security.auth.kerberos.DelegationPermission
    • javax.security.auth.kerberos.ServicePermission
    • javax.sound.sampled.AudioPermission
  • Methods and the Permissions They Require
  • java.lang.SecurityManager Method Permission Checks

For more information about permissions, including the superclasses java.security.Permission and java.security.BasicPermission, and examples of creating permission objects and granting permissions, see the Security Architecture Specification.

Permission Descriptions and Risks

The following tables describe the built-in JDK permission types and discuss the risks of granting each permission.

AllPermission

The java.security.AllPermission is a permission that implies all other permissions.

Note: Granting AllPermission should be done with extreme care, as it implies all other permissions. Thus, it grants code the ability to run with security disabled. Extreme caution should be taken before granting such a permission to code. This permission should be used only during testing, or in extremely rare cases where an application or applet is completely trusted and adding the necessary permissions to the policy is prohibitively cumbersome.

SecurityPermission

A java.security.SecurityPermission is for security permissions. A SecurityPermission contains a name (also referred to as a "target name") but no actions list; you either have the named permission or you don't.

The target name is the name of a security configuration parameter (see below). Currently the SecurityPermission object is used to guard access to the Policy, Security, Provider, Signer, and Identity objects.

The following table lists all the possible SecurityPermission target names, and for each provides a description of what the permission allows and a discussion of the risks of granting code the permission.

java.security.SecurityPermission Target Name | What the Permission Allows | Risks of Allowing this Permission
createAccessControlContext | Creation of an AccessControlContext | This allows someone to instantiate an AccessControlContext with a DomainCombiner. Extreme care must be taken when granting this permission. Malicious code could create a DomainCombiner that augments the set of permissions granted to code, and even grant the code AllPermission.
getDomainCombiner | Retrieval of an AccessControlContext's DomainCombiner | This allows someone to query the policy via the getPermissions call, which discloses which permissions would be granted to a given CodeSource. While revealing the policy does not compromise the security of the system, it does provide malicious code with additional information which it may use to better aim an attack. It is wise not to divulge more information than necessary.
getPolicy | Retrieval of the system-wide security policy (specifically, of the currently-installed Policy object) | This allows someone to query the policy via the getPermissions call, which discloses which permissions would be granted to a given CodeSource. While revealing the policy does not compromise the security of the system, it does provide malicious code with additional information which it may use to better aim an attack. It is wise not to divulge more information than necessary.
setPolicy | Setting of the system-wide security policy (specifically, the Policy object) | Granting this permission is extremely dangerous, as malicious code may grant itself all the necessary permissions it needs to successfully mount an attack on the system.
createPolicy.{policy type} | Getting an instance of a Policy via Policy.getInstance | Granting this permission enables code to obtain a Policy object. Malicious code may query the Policy object to determine what permissions have been granted to code other than itself.
getProperty.{key} | Retrieval of the security property with the specified key | Depending on the particular key for which access has been granted, the code may have access to the list of security providers, as well as the location of the system-wide and user security policies. while revealing this information does not compromise the security of the system, it does provide malicious code with additional information which it may use to better aim an attack.
setProperty.{key} | Setting of the security property with the specified key | This could include setting a security provider or defining the location of the system-wide security policy. Malicious code that has permission to set a new security provider may set a rogue provider that steals confidential information such as cryptographic private keys. In addition, malicious code with permission to set the location of the system-wide security policy may point it to a security policy that grants the attacker all the necessary permissions it requires to successfully mount an attack on the system.
insertProvider.{provider name} | Addition of a new provider, with the specified name | This would allow somebody to introduce a possibly malicious provider (e.g., one that discloses the private keys passed to it) as the highest-priority provider. This would be possible because the Security object (which manages the installed providers) currently does not check the integrity or authenticity of a provider before attaching it.
removeProvider.{provider name} | Removal of the specified provider | This may change the behavior or disable execution of other parts of the program. If a provider subsequently requested by the program has been removed, execution may fail. Also, if the removed provider is not explicitly requested by the rest of the program, but it would normally be the provider chosen when a cryptography service is requested (due to its previous order in the list of providers), a different provider will be chosen instead, or no suitable provider will be found, thereby resulting in program failure.
clearProviderProperties.{provider name} | "Clearing" of a Provider so that it no longer contains the properties used to look up services implemented by the provider | This disables the lookup of services implemented by the provider. This may thus change the behavior or disable execution of other parts of the program that would normally utilize the Provider, as described under the "removeProvider.{provider name}" permission.
putProviderProperty.{provider name} | Setting of properties for the specified Provider | The provider properties each specify the name and location of a particular service implemented by the provider. By granting this permission, you let code replace the service specification with another one, thereby specifying a different implementation.
removeProviderProperty.{provider name} | Removal of properties from the specified Provider | This disables the lookup of services implemented by the provider. They are no longer accessible due to removal of the properties specifying their names and locations. This may change the behavior or disable execution of other parts of the program that would normally utilize the Provider, as described under the "removeProvider.{provider name}" permission.

The following permissions are associated with classes that have been deprecated: Identity, IdentityScope, Signer. Use of them is discouraged. See the applicable classes for more information.

java.security.SecurityPermission Target Name | What the Permission Allows | Risks of Allowing this Permission
setSystemScope | Setting of the system identity scope | This would allow an attacker to configure the system identity scope with certificates that should not be trusted, thereby granting applet or application code signed with those certificates privileges that would have been denied by the system's original identity scope.
setIdentityPublicKey | Setting of the public key for an Identity | If the identity is marked as "trusted", this allows an attacker to introduce a different public key (e.g., its own) that is not trusted by the system's identity scope, thereby granting applet or application code signed with that public key privileges that would have been denied otherwise.
setIdentityInfo | Setting of a general information string for an Identity | This allows attackers to set the general description for an identity. This may trick applications into using a different identity than intended or may prevent applications from finding a particular identity.
addIdentityCertificate | Addition of a certificate for an Identity | This allows attackers to set a certificate for an identity's public key. This is dangerous because it affects the trust relationship across the system. This public key suddenly becomes trusted to a wider audience than it otherwise would be.
removeIdentityCertificate | Removal of a certificate for an Identity | This allows attackers to remove a certificate for an identity's public key. This is dangerous because it affects the trust relationship across the system. This public key suddenly becomes considered less trustworthy than it otherwise would be.
printIdentity | Viewing the name of a principal and optionally the scope in which it is used, and whether or not it is considered "trusted" in that scope. | The scope that is printed out may be a filename, in which case it may convey local system information. For example, here's a sample printout of an identity named "carol", who is marked not trusted in the user's identity database: carol[/home/luehe/identitydb.obj][not trusted]
getSignerPrivateKey | Retrieval of a Signer's private key | It is very dangerous to allow access to a private key; private keys are supposed to be kept secret. Otherwise, code can use the private key to sign various files and claim the signature came from the Signer.
setSignerKeyPair | Setting of the key pair (public key and private key) for a Signer | This would allow an attacker to replace somebody else's (the "target's") keypair with a possibly weaker keypair (e.g., a keypair of a smaller keysize). This also would allow the attacker to listen in on encrypted communication between the target and its peers. The target's peers might wrap an encryption session key under the target's "new" public key, which would allow the attacker (who possesses the corresponding private key) to unwrap the session key and decipher the communication data encrypted under that session key.

UnresolvedPermission

The java.security.UnresolvedPermission class is used to hold Permissions that were "unresolved" when the Policy was initialized. An unresolved permission is one whose actual Permission class does not yet exist at the time the Policy is initialized (see below).

The policy for a Java runtime (specifying which permissions are available for code from various principals) is represented by a Policy object. Whenever a Policy is initialized or refreshed, Permission objects of appropriate classes are created for all permissions allowed by the Policy.

Many permission class types referenced by the policy configuration are ones that exist locally (i.e., ones that can be found on CLASSPATH). Objects for such permissions can be instantiated during Policy initialization. For example, it is always possible to instantiate a java.io.FilePermission, since the FilePermission class is found on the CLASSPATH.

Other permission classes may not yet exist during Policy initialization. For example, a referenced permission class may be in a JAR file that will later be loaded. For each such class, an UnresolvedPermission is instantiated. Thus, an UnresolvedPermission is essentially a "placeholder" containing information about the permission.

Later, when code calls AccessController.checkPermission on a permission of a type that was previously unresolved, but whose class has since been loaded, previously-unresolved permissions of that type are "resolved". That is, for each such UnresolvedPermission, a new object of the appropriate class type is instantiated, based on the information in the UnresolvedPermission. This new object replaces the UnresolvedPermission, which is removed.

AWTPermission

A java.awt.AWTPermission is for AWT permissions.

The following table lists all the possible AWTPermission target names, and for each provides a description of what the permission allows and a discussion of the risks of granting code the permission.

java.awt.AWTPermission Target Name | What the Permission Allows | Risks of Allowing this Permission
accessClipboard | Posting and retrieval of information to and from the AWT clipboard | This would allow malfeasant code to share potentially sensitive or confidential information.
accessEventQueue | Access to the AWT event queue | After retrieving the AWT event queue, malicious code may peek at and even remove existing events from the system, as well as post bogus events which may purposefully cause the application or applet to misbehave in an insecure manner.
accessSystemTray | Access to the AWT SystemTray instance | This would allow malicious code to add tray icons to the system tray. First, such an icon may look like the icon of some known application (such as a firewall or anti-virus) and order a user to do something unsafe (with help of balloon messages). Second, the system tray may be glutted with tray icons so that no one could add a tray icon anymore.
createRobot | Create java.awt.Robot objects | The java.awt.Robot object allows code to generate native-level mouse and keyboard events as well as read the screen. It could allow malicious code to control the system, run other programs, read the display, and deny mouse and keyboard access to the user.
fullScreenExclusive | Enter full-screen exclusive mode | Entering full-screen exclusive mode allows direct access to low-level graphics card memory. This could be used to spoof the system, since the program is in direct control of rendering.
listenToAllAWTEvents | Listen to all AWT events, system-wide | After adding an AWT event listener, malicious code may scan all AWT events dispatched in the system, allowing it to read all user input (such as passwords). Each AWT event listener is called from within the context of that event queue's EventDispatchThread, so if the accessEventQueue permission is also enabled, malicious code could modify the contents of AWT event queues system-wide, causing the application or applet to misbehave in an insecure manner.
readDisplayPixels | Readback of pixels from the display screen | Interfaces such as the java.awt.Composite interface which allow arbitrary code to examine pixels on the display enable malicious code to snoop on the activities of the user.
replaceKeyboardFocusManager | Sets the KeyboardFocusManager for a particular thread. | When a SecurityManager is installed, the invoking thread must be granted this permission in order to replace the current KeyboardFocusManager. If permission is not granted, a SecurityException will be thrown.
setAppletStub | Setting the stub which implements Applet container services | Malicious code could set an applet's stub and result in unexpected behavior or denial of service to an applet.
setWindowsAlwaysOnTop | Setting always-on-top property of the window: Window.setAlwaysOnTop(boolean) | The malicious window might make itself look and behave like a real full desktop, so that information entered by the unsuspecting user is captured and subsequently misused.
showWindowWithoutWarningBanner | Display of a window without also displaying a banner warning that the window was created by an applet | Without this warning, an applet may pop up windows without the user knowing that they belong to an applet. Since users may make security-sensitive decisions based on whether or not the window belongs to an applet (entering a username and password into a dialog box, for example), disabling this warning banner may allow applets to trick the user into entering such information.
toolkitModality | Creating TOOLKIT_MODAL dialogs and setting the TOOLKIT_EXCLUDE window property. | When a toolkit-modal dialog is shown from an applet, it blocks all other applets in the browser. When launching applications from Java Web Start, its windows (such as the security dialog) may also be blocked by toolkit-modal dialogs, shown from these applications.
watchMousePointer | Getting the information about the mouse pointer position at any time | Constantly watching the mouse pointer, an applet can make guesses about what the user is doing, i.e. moving the mouse to the lower left corner of the screen most likely means that the user is about to launch an application. If a virtual keypad is used so that keyboard is emulated using the mouse, an applet may guess what is being typed.

FilePermission

A java.io.FilePermission represents access to a file or directory. A FilePermission consists of a pathname and a set of actions valid for that pathname.

Pathname is the pathname of the file or directory granted the specified actions. A pathname that ends in "/*" (where "/" is the file separator character, File.separatorChar) indicates a directory and all the files contained in that directory. A pathname that ends with "/-" indicates a directory and (recursively) all files and subdirectories contained in that directory. A pathname consisting of the special token "<<ALL FILES>>" matches any file.

A pathname consisting of a single "*" indicates all the files in the current directory, while a pathname consisting of a single "-" indicates all the files in the current directory and (recursively) all files and subdirectories contained in the current directory.

The actions to be granted are passed to the constructor in a string containing a list of zero or more comma-separated keywords. The possible keywords are "read", "write", "execute", and "delete". Their meaning is defined as follows:

Keyword | Meaning
read | Permission to read.
write | Permission to write (which includes permission to create).
execute | Permission to execute. Allows Runtime.exec to be called. Corresponds to SecurityManager.checkExec.
delete | Permission to delete. Allows File.delete to be called. Corresponds to SecurityManager.checkDelete.

The actions string is converted to lowercase before processing.

Be careful when granting FilePermissions. Think about the implications of granting read and especially write access to various files and directories. The "<<ALL FILES>>" permission with write action is especially dangerous. This grants permission to write to the entire file system. One thing this effectively allows is replacement of the system binary, including the JVM runtime environment.

Note: code can always read a file from the same directory it's in (or a subdirectory of that directory); it does not need explicit permission to do so.

SerializablePermission

A java.io.SerializablePermission is for serializable permissions. A SerializablePermission contains a name (also referred to as a "target name") but no actions list; you either have the named permission or you don't.

The target name is the name of the Serializable permission (see below).

The following table lists all the possible SerializablePermission target names, and for each provides a description of what the permission allows and a discussion of the risks of granting code the permission.

java.io.SerializablePermission Target Name | What the Permission Allows | Risks of Allowing this Permission
enableSubclassImplementation | Implementing a subclass of ObjectOutputStream or ObjectInputStream to override the default serialization or deserialization, respectively, of objects | Code can use this to serialize or deserialize classes in a purposefully malfeasant manner. For example, during serialization, malicious code can use this to purposefully store confidential private field data in a way easily accessible to attackers. Or, during deserializaiton it could, for example, deserialize a class with all its private fields zeroed out.
enableSubstitution | Substitution of one object for another during serialization or deserialization | This is dangerous because malicious code can replace the actual object with one which has incorrect or malignant data.

ReflectPermission

A java.lang.reflect.ReflectPermission is for reflective operations. A ReflectPermission is a named permission and has no actions. The only name currently defined is suppressAccessChecks, which allows suppressing the standard language access checks -- for public, default (package) access, protected, and private members -- performed by reflected objects at their point of use.

The following table provides a summary description of what the permission allows, and discusses the risks of granting code the permission.

java.lang.reflect.ReflectPermission Target Name | What the Permission Allows | Risks of Allowing this Permission
suppressAccessChecks | Warning: Extreme caution should be taken before granting this permission to code, for it provides the ability to access fields and invoke methods in a class. This includes not only public, but protected and private fields and methods as well. | This is dangerous in that information (possibly confidential) and methods normally unavailable would be accessible to malicious code.

RuntimePermission

A java.lang.RuntimePermission is for runtime permissions. A RuntimePermission contains a name (also referred to as a "target name") but no actions list; you either have the named permission or you don't.

The target name is the name of the runtime permission (see below). The naming convention follows the hierarchical property naming convention. Also, an asterisk may appear at the end of the name, following a ".", or by itself, to signify a wildcard match. For example: "loadLibrary.*" or "*" is valid, "*loadLibrary" or "a*b" is not valid.

The following table lists all the possible RuntimePermission target names, and for each provides a description of what the permission allows and a discussion of the risks of granting code the permission.

java.lang.RuntimePermission Target Name | What the Permission Allows | Risks of Allowing this Permission
createClassLoader | Creation of a class loader | This is an extremely dangerous permission to grant. Malicious applications that can instantiate their own class loaders could then load their own rogue classes into the system. These newly loaded classes could be placed into any protection domain by the class loader, thereby automatically granting the classes the permissions for that domain.
getClassLoader | Retrieval of a class loader (e.g., the class loader for the calling class) | This would grant an attacker permission to get the class loader for a particular class. This is dangerous because having access to a class's class loader allows the attacker to load other classes available to that class loader. The attacker would typically otherwise not have access to those classes.
setContextClassLoader | Setting of the context class loader used by a thread | The context class loader is used by system code and extensions when they need to lookup resources that might not exist in the system class loader. Granting setContextClassLoader permission would allow code to change which context class loader is used for a particular thread, including system threads.
enableContextClassLoaderOverride | Subclass implementation of the thread context class loader methods | The context class loader is used by system code and extensions when they need to lookup resources that might not exist in the system class loader. Granting enableContextClassLoaderOverride permission would allow a subclass of Thread to override the methods that are used to get or set the context class loader for a particular thread.
setSecurityManager | Setting of the security manager (possibly replacing an existing one) | The security manager is a class that allows applications to implement a security policy. Granting the setSecurityManager permission would allow code to change which security manager is used by installing a different, possibly less restrictive security manager, thereby bypassing checks that would have been enforced by the original security manager.
createSecurityManager | Creation of a new security manager | This gives code access to protected, sensitive methods that may disclose information about other classes or the execution stack.
getenv.{variable name} | Reading of the value of the specified environment variable | This would allow code to read the value, or determine the existence, of a particular environment variable. This is dangerous if the variable contains confidential data.
exitVM.{exit status} | Halting of the Java Virtual Machine with the specified exit status | This allows an attacker to mount a denial-of-service attack by automatically forcing the virtual machine to halt. Note: The "exitVM.*" permission is automatically granted to all code loaded from the application class path, thus enabling applications to terminate themselves. Also, the "exitVM" permission is equivalent to "exitVM.*".
shutdownHooks | Registration and cancellation of virtual-machine shutdown hooks | This allows an attacker to register a malicious shutdown hook that interferes with the clean shutdown of the virtual machine.
setFactory | Setting of the socket factory used by ServerSocket or Socket, or of the stream handler factory used by URL | This allows code to set the actual implementation for the socket, server socket, stream handler, or RMI socket factory. An attacker may set a faulty implementation which mangles the data stream.
setIO | Setting of System.out, System.in, and System.err | This allows changing the value of the standard system streams. An attacker may change System.in to monitor and steal user input, or may set System.err to a "null" OutputSteam, which would hide any error messages sent to System.err.
modifyThread | Modification of threads, e.g., via calls to Thread interrupt, stop, suspend, resume, setDaemon, setPriority, setName and setUncaughtExceptionHandler methods | This allows an attacker to modify the behavior of any thread in the system.
stopThread | Stopping of threads via calls to the Thread stop method | This allows code to stop any thread in the system provided that it is already granted permission to access that thread. This poses as a threat, because that code may corrupt the system by killing existing threads.
modifyThreadGroup | Modification of thread groups, e.g., via calls to ThreadGroup destroy, getParent, resume, setDaemon, setMaxPriority, stop, and suspend methods | This allows an attacker to create thread groups and set their run priority.
getProtectionDomain | Retrieval of the ProtectionDomain for a class | This allows code to obtain policy information for a particular code source. While obtaining policy information does not compromise the security of the system, it does give attackers additional information, such as local file names for example, to better aim an attack.
getFileSystemAttributes | Retrieval of file system attributes | This allows code to obtain file system information such as disk usage or disk space available to the caller. This is potentially dangerous because it discloses information about the system hardware configuration and some information about the caller's privilege to write files.
readFileDescriptor | Reading of file descriptors | This would allow code to read the particular file associated with the file descriptor read. This is dangerous if the file contains confidential data.
writeFileDescriptor | Writing to file descriptors | This allows code to write to a particular file associated with the descriptor. This is dangerous because it may allow malicous code to plant viruses or at the very least, fill up your entire disk.
loadLibrary.{library name} | Dynamic linking of the specified library | It is dangerous to allow an applet permission to load native code libraries, because the Java security architecture is not designed to and does not prevent malicious behavior at the level of native code.
accessClassInPackage.
{package name} 		Access to the specified package via a class loader's loadClass method when that class loader calls the SecurityManager checkPackageAcesss method This gives code access to classes in packages to which it normally does not have access. Malicious code may use these classes to help in its attempt to compromise security in the system.
defineClassInPackage.
{package name} 		Definition of classes in the specified package, via a class loader's defineClass method when that class loader calls the SecurityManager checkPackageDefinition method. This grants code permission to define a class in a particular package. This is dangerous because malicious code with this permission may define rogue classes in trusted packages like java.security or java.lang, for example.
accessDeclaredMembers | Warning: Extreme caution should be taken before granting this permission to code, for it provides access to the declared members of a class. | This grants code permission to query a class for its public, protected, default (package) access, and private fields and/or methods. Although the code would have access to the private and protected field and method names, it would not have access to the private/protected field data and would not be able to invoke any private methods. Nevertheless, malicious code may use this information to better aim an attack. Additionally, it may invoke any public methods and/or access public fields in the class. This could be dangerous if the code would normally not be able to invoke those methods and/or access the fields because it can't cast the object to the class/interface with those methods and fields.
queuePrintJob | Initiation of a print job request | This could print sensitive information to a printer, or simply waste paper.
getStackTrace | Retrieval of the stack trace information of another thread. | This allows retrieval of the stack trace information of another thread. This might allow malicious code to monitor the execution of threads and discover vulnerabilities in applications.
setDefaultUncaughtExceptionHandler | Setting the default handler to be used when a thread terminates abruptly due to an uncaught exception. | This allows an attacker to register a malicious uncaught exception handler that could interfere with termination of a thread.
preferences | Represents the permission required to get access to the java.util.prefs.Preferences implementations user or system root which in turn allows retrieval or update operations within the Preferences persistent backing store. | This permission allows the user to read from or write to the preferences backing store if the user running the code has sufficient OS privileges to read/write to that backing store. The actual backing store may reside within a traditional filesystem directory or within a registry depending on the platform OS.

NIO-Related Targets

Two NIO-related RuntimePermission targets were added in the 1.4 release of the JavaSE JDK:
selectorProvider
charsetProvider
These RuntimePermissions are required to be granted to classes which subclass and implement java.nio.channel.spi.SelectorProvider or java.nio.charset.spi.CharsetProvider. The permission is checked during invocation of the abstract base class constructor. These permissions ensure trust in classes which implement these security-sensitive provider mechanisms.

See java.nio.channels.spi.SelectorProvider and java.nio.channels.spi.CharsetProvider for more information.

NetPermission

A java.net.NetPermission is for various network permissions. A NetPermission contains a name but no actions list; you either have the named permission or you don't.

The following table lists all the possible NetPermission target names, and for each provides a description of what the permission allows and a discussion of the risks of granting code the permission.

java.net.NetPermission Target Name | What the Permission Allows | Risks of Allowing this Permission
setDefaultAuthenticator | The ability to set the way authentication information is retrieved when a proxy or HTTP server asks for authentication | Malicious code can set an authenticator that monitors and steals user authentication input as it retrieves the input from the user.
requestPasswordAuthentication | The ability to ask the authenticator registered with the system for a password | Malicious code may steal this password.
specifyStreamHandler | The ability to specify a stream handler when constructing a URL | Malicious code may create a URL with resources that it would normally not have access to (like file:/foo/fum/), specifying a stream handler that gets the actual bytes from someplace it does have access to. Thus it might be able to trick the system into creating a ProtectionDomain/CodeSource for a class even though that class really didn't come from that location.
setProxySelector | The ability to set the proxy selector used to make decisions on which proxies to use when making network connections. | Malicious code can set a ProxySelector that directs network traffic to an arbitrary network host.
getProxySelector | The ability to get the proxy selector used to make decisions on which proxies to use when making network connections. | Malicious code can get a ProxySelector to discover proxy hosts and ports on internal networks, which could then become targets for attack.
setCookieHandler | The ability to set the cookie handler that processes highly security sensitive cookie information for an Http session. | Malicious code can set a cookie handler to obtain access to highly security sensitive cookie information. Some web servers use cookies to save user private information such as access control information, or to track user browsing habit.
getCookieHandler | The ability to get the cookie handler that processes highly security sensitive cookie information for an Http session. | Malicious code can get a cookie handler to obtain access to highly security sensitive cookie information. Some web servers use cookies to save user private information such as access control information, or to track user browsing habit.
setResponseCache | The ability to set the response cache that provides access to a local response cache. | Malicious code getting access to the local response cache could access security sensitive information, or create false entries in the response cache.
getResponseCache | The ability to get the response cache that provides access to a local response cache. | Malicious code getting access to the local response cache could access security sensitive information.

SocketPermission

A java.net.SocketPermission represents access to a network via sockets. A SocketPermission consists of a host specification and a set of "actions" specifying ways to connect to that host. The host is specified as

host = (hostname | IPaddress)[:portrange]
portrange = portnumber | -portnumber | portnumber-[portnumber]

The host is expressed as a DNS name, as a numerical IP address, or as "localhost" (for the local machine). The wildcard "*" may be included once in a DNS name host specification. If it is included, it must be in the leftmost position, as in "*.sun.com".

The port or portrange is optional. A port specification of the form "N-", where N is a port number, signifies all ports numbered N and above, while a specification of the form "-N" indicates all ports numbered N and below.

The possible ways to connect to the host are

accept
connect
listen
resolve

The "listen" action is only meaningful when used with "localhost". The "resolve" (resolve host/ip name service lookups) action is implied when any of the other actions are present.

As an example of the creation and meaning of SocketPermissions, note that if you have the following entry in your policy file:

grant signedBy "mrm" {
    permission java.net.SocketPermission "puffin.eng.sun.com:7777", "connect, accept";
};

this causes the following permission object to be generated and granted to code signed by "mrm."

p1 = new SocketPermission("puffin.eng.sun.com:7777", "connect,accept");

p1 represents a permission allowing connections to port 7777 on puffin.eng.sun.com, and also accepting connections on that port.

Similarly, if you have the following entry in your policy:

grant signedBy "paul" {
    permission java.net.SocketPermission "localhost:1024-", "accept, connect, listen";
};

this causes the following permission object to be generated and granted to code signed by "paul."

p2 = new SocketPermission("localhost:1024-", "accept,connect,listen");

p2 represents a permission allowing accepting connections on, connecting to, or listening on any port between 1024 and 65535 on the local host.

Note: Granting code permission to accept or make connections to remote hosts may be dangerous because malevolent code can then more easily transfer and share confidential data among parties who may not otherwise have access to the data.

SQLPermission

The permission for which the SecurityManager will check when code that is running in an applet, or an application with an instance of SecurityManager enabled, calls one of the following methods:

  • java.sql.DriverManager.setLogWriter
  • java.sql.DriverManager.setLogStream (deprecated)
  • javax.sql.rowset.spi.SyncFactory.setJNDIContext
  • javax.sql.rowset.spi.SyncFactory.setLogger
  • java.sql.Connection.setNetworktimeout
  • java.sql.Connection.abort

If there is no SQLPermission object, these methods throw a java.lang.SecurityException as a runtime exception.

A SQLPermission object contains a name (also referred to as a "target name") but no actions list; there is either a named permission or there is not. The target name is the name of the permission (see the following table that lists all the possible SQLPermission names). The naming convention follows the hierarchical property naming convention. In addition, an asterisk (*) may appear at the end of the name, following a dot (.), or by itself, to signify a wildcard match. For example: loadLibrary.* or * is valid, but *loadLibrary or a*b is not valid.

The following table lists all the possible SQLPermission target names. The table gives a description of what the permission allows and a discussion of the risks of granting code the permission.

Permission Target Name | What Permission Allows | Risks of Allowing This Permission
setLog | Setting of the logging stream | This is a dangerous permission to grant. The contents of the log can contain usernames and passwords, SQL statements, and SQL data.
callAbort | Invocation of the Connection method abort | Permits an application to terminate a physical connection to a database.
setSyncFactory | Invocation of the SyncFactory methods setJNDIContext and setLogger | Permits an application to specify the JNDI context from which the SyncProvider implementations can be retrieved from and the logging object to be used by the SyncProvider implementation.
setNetworkTimeout | Invocation of the Connection method setNetworkTimeout | Permits an application to specify the maximum period a Connection or objects created from the Connection object will wait for the database to reply to any one request.

The person running an applet decides what permissions to allow and runs the Policy Tool to create an instance of SQLPermission in a policy file. A programmer does not use a constructor directly to create an instance of SQLPermission but rather uses a tool.

PropertyPermission

A java.util.PropertyPermission is for property permissions.

The name is the name of the property ("java.home", "os.name", etc). The naming convention follows the hierarchical property naming convention. Also, an asterisk may appear at the end of the name, following a ".", or by itself, to signify a wildcard match. For example: "java.*" or "*" is valid, "*java" or "a*b" is not valid.

The actions to be granted are passed to the constructor in a string containing a list of zero or more comma-separated keywords. The possible keywords are "read" and "write". Their meaning is defined as follows:

Keyword | Meaning
read | Permission to read. Allows System.getProperty to be called.
write | Permission to write. Allows System.setProperty to be called.

The actions string is converted to lowercase before processing.

Care should be taken before granting code permission to access certain system properties. For example, granting permission to access the "java.home" system property gives potentially malevolent code sensitive information about the system environment (the location of the runtime environment's directory). Also, granting permission to access the "user.name" and "user.home" system properties gives potentially malevolent code sensitive information about the user environment (the user's account name and home directory).

LoggingPermission

A SecurityManager will check the java.util.logging.LoggingPermission object when code running with a SecurityManager calls one of the logging control methods (such as Logger.setLevel).

Currently there is only one named LoggingPermission, "control". control grants the ability to control the logging configuration; for example by adding or removing Handlers, by adding or removing Filters, or by changing logging levels.

Normally you do not create LoggingPermission objects directly; instead they are created by the security policy code based on reading the security policy file.

SSLPermission

The javax.net.ssl.SSLPermission class is for various network permissions. An SSLPermission contains a name (also referred to as a "target name") but no actions list; you either have the named permission or you don't.

The target name is the name of the network permission (see below). The naming convention follows the hierarchical property naming convention. Also, an asterisk may appear at the end of the name, following a ".", or by itself, to signify a wildcard match. For example: "foo.*" or "*" is valid, "*foo" or "a*b" is not valid.

The following table lists all the possible SSLPermission target names, and for each provides a description of what the permission allows and a discussion of the risks of granting code the permission.

Permission Target Name | What the Permission Allows | Risks of Allowing this Permission
setHostnameVerifier | The ability to set a callback which can decide whether to allow a mismatch between the host being connected to by an HttpsURLConnection and the common name field in server certificate. | Malicious code can set a verifier that monitors host names visited by HttpsURLConnection requests or that allows server certificates with invalid common names.
getSSLSessionContext | The ability to get the SSLSessionContext of an SSLSession. | Malicious code may monitor sessions which have been established with SSL peers or might invalidate sessions to slow down performance.
setDefaultSSLContext | The ability to set the default SSL context. | When applications use default SSLContext, by setting the default SSL context, malicious code may use unproved trust material, key material and random generator, or use dangerous SSL socket factory and SSL server socket factory.

AuthPermission

The javax.security.auth.AuthPermission class is for authentication permissions. An AuthPermission contains a name (also referred to as a "target name") but no actions list; you either have the named permission or you don't.

Currently the AuthPermission object is used to guard access to the Subject, SubjectDomainCombiner, LoginContext and Configuration objects.

The following table lists all the possible AuthPermission target names, and for each provides a description of what the permission allows and a discussion of the risks of granting code the permission.

Permission Target Name | What the Permission Allows | Risks of Allowing this Permission
doAs | Invocation of the Subject.doAs methods | This enables an application to invoke code (Actions) under the identity of any Subject specified to the doAs method.
doAsPrivileged | Invocation of the Subject.doAsPrivileged methods | This enables an application to invoke code (Actions) under the identity of any Subject specified to the doAsPrivileged method. Additionally, the caller may remove itself from the call stack (and hence from subsequent security decisions) if it passes null as the AccessControlContext.
getSubject | Retrieving the Subject from the provided AccessControlContext | This permits an application to gain access to an authenticated Subject. The application can then access the Subject's authenticated Principals and public credentials.
getSubjectFromDomainCombiner | Retrieving the Subject from a SubjectDomainCombiner | This permits an application to gain access to the authenticated Subject associated with a SubjectDomainCombiner. The application can then access the Subject's authenticated Principals and public credentials.
setReadOnly | Setting a Subject read-only | This permits an application to set a Subject's Principal, public credential and private credential sets to be read-only. This can be potentially used as a type of denial of service attack.
modifyPrincipals | Make modifications to a Subject's Principal set | Access control decisions are based on the Principals associated with a Subject. This permission permits an application to make any modifications to a Subject's Principal set, thereby affecting subsequent security decisions.
modifyPublicCredentials | Make modifications to a Subject's public credential set | This permission permits an application to add or remove public credentials from a Subject. This may affect code that relies on the proper set of private credentials to exist in that Subject.
modifyPrivateCredentials | Make modifications to a Subject's private credential set | This permission permits an application to add or remove private credentials from a Subject. This may affect code that relies on the proper set of private credentials to exist in that Subject.
refreshCredential | Refresh a credential Object that implements the Refreshable interface | This permission permits an application to refresh a credential that is intended to expire.
destroyCredential | Destroy a credential Object that implements the Destroyable interface | This permission permits an application to potentially destroy a credential as a denial of service attack.
createLoginContext.{name} | Instantiate a LoginContext with the specified name | For security purposes, an administrator might not want an application to be able to authenticate to any LoginModule. This permission permits an application to authenticate to the LoginModules configured for the specified name.
getLoginConfiguration | Retrieve the system-wide login Configuration | Allows an application to determine all the LoginModules that are configured for every application in the system.
setLoginConfiguration | Set the system-wide login Configuration | Allows an application to configure the LoginModules for every application in the system.
createLoginConfiguration.{configuration type} | Obtain a Configuration object via Configuration.getInstance | Allows an application to see all the LoginModules that are specified in the configuration.
refreshLoginConfiguration | Refresh the system-wide login Configuration | Allows an application to refresh the login Configuration.

PrivateCredentialPermission

The javax.security.auth.PrivateCredentialPermission class is used to protect access to private Credentials belonging to a particular Subject. The Subject is represented by a Set of Principals.

The target name of this Permission specifies a Credential class name, and a Set of Principals. The only valid value for this Permission's actions is, "read". The target name must abide by the following syntax:

CredentialClass {PrincipalClass "PrincipalName"}*
For example, the following permission grants access to the com.sun.PrivateCredential owned by Subjects which have a com.sun.Principal with the name, "duke".

Note: Although this example, as well as all the examples below, do not contain Codebase, SignedBy, or Principal information in the grant statement (for simplicity reasons), actual policy configurations should specify that information when appropriate.

grant {
    permission javax.security.auth.PrivateCredentialPermission
             "com.sun.PrivateCredential com.sun.Principal \"duke\"",
             "read";
};
If CredentialClass is "*", then access is granted to all private Credentials belonging to the specified Subject. If "PrincipalName" is "*", then access is granted to the specified Credential owned by any Subject that has the specified Principal (the actual PrincipalName doesn't matter). For example, the following grants access to the a.b.Credential owned by any Subject that has an a.b.Principal.
grant {
    permission javax.security.auth.PrivateCredentialPermission
             "a.b.Credential a.b.Principal "*"",
             "read";
};
If both the PrincipalClass and "PrincipalName" are "*", then access is granted to the specified Credential owned by any Subject. In addition, the PrincipalClass/PrincipalName pairing may be repeated:
grant {
    permission javax.security.auth.PrivateCredentialPermission
             "a.b.Credential a.b.Principal "duke" c.d.Principal "dukette"",
             "read";
};
The above code grants access to the private Credential, "a.b.Credential", belonging to a Subject with at least two associated Principals: "a.b.Principal" with the name, "duke", and "c.d.Principal", with the name, "dukette".

DelegationPermission

The javax.security.auth.kerberos.DelegationPermission class is used to restrict the usage of the Kerberos delegation model; ie, forwardable and proxiable tickets.

The target name of this Permission specifies a pair of kerberos service principals. The first is the subordinate service principal being entrusted to use the Ticket Granting Ticket (TGT). The second service principal designates the target service the subordinate service principal is to interact with on behalf of the initiating KerberosPrincipal. This latter service principal is specified to restrict the use of a proxiable ticket.

For example, to specify the "host" service use of a forwardable TGT, the target permission is specified as follows:

DelegationPermission("\"host/foo.example.com@EXAMPLE.COM\" \"krbtgt/EXAMPLE.COM@EXAMPLE.COM\"");
To give the "backup" service a proxiable NFS service ticket, the target permission might be specified:
DelegationPermission("\"backup/bar.example.com@EXAMPLE.COM\" \"nfs/home.EXAMPLE.COM@EXAMPLE.COM\"");

ServicePermission

The javax.security.auth.kerberos.ServicePermission class is used to protect Kerberos services and the credentials necessary to access those services. There is a one to one mapping of a service principal and the credentials necessary to access the service. Therefore granting access to a service principal implicitly grants access to the credential necessary to establish a security context with the service principal. This applies regardless of whether the credentials are in a cache or acquired via an exchange with the KDC. The credential can be either a ticket granting ticket, a service ticket or a secret key from a key table.

A ServicePermission contains a service principal name and a list of actions which specify the context the credential can be used within.

The service principal name is the canonical name of the KereberosPrincipal supplying the service, that is the KerberosPrincipal represents a Kerberos service principal. This name is treated in a case sensitive manner.

Granting this permission implies that the caller can use a cached credential (Ticket Granting Ticket, service ticket or secret key) within the context designated by the action. In the case of the TGT, granting this permission also implies that the TGT can be obtained by an Authentication Service exchange.

The possible actions are:

Action | Meaning
initiate | Allows the caller to use the credential to initiate a security context with a service principal.
accept | Allows the caller to use the credential to accept security context as a particular principal.
For example, to specify the permission to access to the TGT to initiate a security context the permission is constructed as follows:
     ServicePermission("krbtgt/EXAMPLE.COM@EXAMPLE.COM", "initiate");
To obtain a service ticket to initiate a context with the "host" service the permission is constructed as follows:
ServicePermission("host/foo.example.com@EXAMPLE.COM", "initiate");
For a Kerberized server the action is "accept". For example, the permission necessary to access and use the secret key of the Kerberized "host" service (telnet and the likes) would be constructed as follows:
ServicePermission("host/foo.example.com@EXAMPLE.COM", "accept");

AudioPermission

The javax.sound.sampled.AudioPermission class represents access rights to the audio system resources. An AudioPermission contains a target name but no actions list; you either have the named permission or you don't.

The target name is the name of the audio permission (see the table below). The names follow the hierarchical property-naming convention. Also, an asterisk can be used to represent all the audio permissions.

The following table lists the possible AudioPermission target names. For each name, the table provides a description of exactly what that permission allows, as well as a discussion of the risks of granting code the permission.

Permission Target Name | What the Permission Allows | Risks of Allowing this Permission
play | Audio playback through the audio device or devices on the system. Allows the application to obtain and manipulate lines and mixers for audio playback (rendering). | In some cases use of this permission may affect other applications because the audio from one line may be mixed with other audio being played on the system, or because manipulation of a mixer affects the audio for all lines using that mixer.
record | Audio recording through the audio device or devices on the system. Allows the application to obtain and manipulate lines and mixers for audio recording (capture). | In some cases use of this permission may affect other applications because manipulation of a mixer affects the audio for all lines using that mixer. This permission can enable an applet or application to eavesdrop on a user.

Methods and the Permissions They Require

The following table contains a list of all the methods that require permissions, and for each tells which SecurityManager method it calls and which permission is checked for by the default implementation of that SecurityManager method.

Thus, with the default SecurityManager method implementations, a call to a method in the left-hand column can only be successful if the permission specified in the corresponding entry in the right-hand column is allowed by the policy currently in effect. For example, the following row:

Method SecurityManager Method Called Permission
java.awt.Toolkit
    getSystemEventQueue();
checkAwtEventQueueAccess java.awt.AWTPermission "accessEventQueue";

specifies that a call to the getSystemEventQueue method in the java.awt.Toolkit class results in a call to the checkAwtEventQueueAccess SecurityManager method, which can only be successful if the following permission is granted to code on the call stack:

  java.awt.AWTPermission "accessEventQueue";

The convention of:

Method SecurityManager Method Called Permission
 some.package.class
   public static void someMethod(String foo);
checkXXX SomePermission "{foo}";

means the runtime value of foo replaces the string {foo} in the permission name.

As an example, here is one table entry:

Method SecurityManager Method Called Permission
java.io.FileInputStream
    FileInputStream(String name)
checkRead(String) java.io.FilePermission "{name}", "read";

If the FileInputStream method (in this case, a constructor) is called with "/test/MyTestFile" as the name argument, as in

  FileInputStream("/test/MyTestFile");

then in order for the call to succeed, the following permission must be set in the current policy, allowing read access to the file "/test/MyTestFile":

  java.io.FilePermission "/test/MyTestFile", "read";

More specifically, the permission must either be explicitly set, as above, or implied by another permission, such as the following:

  java.io.FilePermission "/test/*", "read";

which allows read access to any files in the "/test" directory.

In some cases, a term in braces is not exactly the same as the name of a specific method argument but is meant to represent the relevant value. Here is an example:

Method SecurityManager Method Called Permission
java.net.DatagramSocket
  public synchronized void
      receive(DatagramPacket p);
checkAccept({host}, {port}) java.net.SocketPermission "{host}:{port}", "accept";

Here, the appropriate host and port values are calculated by the receive method and passed to checkAccept.

In most cases, just the name of the SecurityManager method called is listed. Where the method is one of multiple methods of the same name, the argument types are also listed, for example for checkRead(String) and checkRead(FileDescriptor). In other cases where arguments may be relevant, they are also listed.

The following table is ordered by package name. That is, the methods in classes in the java.awt package are listed first, followed by methods in classes in the java.io package, and so on.

Methods and the Permissions They Require
Method SecurityManager Method Called Permission
java.awt.Graphics2d
  public abstract void
    setComposite(Composite comp)
checkPermission java.awt.AWTPermission "readDisplayPixels" if this Graphics2D context is drawing to a Component on the display screen and the Composite is a custom object rather than an instance of the AlphaComposite class. Note: The setComposite method is actually abstract and thus can't invoke security checks. Each actual implementation of the method should call the java.lang.SecurityManager checkPermission method with a java.awt.AWTPermission("readDisplayPixels") permission under the conditions noted.
java.awt.Robot
  public Robot()
  public Robot(GraphicsDevice screen)
checkPermission java.awt.AWTPermission "createRobot"
java.awt.Toolkit
  public void addAWTEventListener(
          AWTEventListener listener,
          long eventMask)
  public void removeAWTEventListener(
     AWTEventListener listener)
checkPermission java.awt.AWTPermission "listenToAllAWTEvents"
java.awt.Toolkit
  public abstract PrintJob getPrintJob(
           Frame frame, String jobtitle,
           Properties props)
checkPrintJobAccess

java.lang.RuntimePermission "queuePrintJob"

Note: The getPrintJob method is actually abstract and thus can't invoke security checks. Each actual implementation of the method should call the java.lang.SecurityManager checkPrintJobAccess method, which is successful only if the java.lang.RuntimePermission "queuePrintJob" permission is currently allowed.

java.awt.Toolkit
  public abstract Clipboard
                    getSystemClipboard()
checkSystemClipboardAccess

java.awt.AWTPermission "accessClipboard"

Note: The getSystemClipboard method is actually abstract and thus can't invoke security checks. Each actual implementation of the method should call the java.lang.SecurityManager checkSystemClipboardAccess method, which is successful only if the java.awt.AWTPermission "accessClipboard" permission is currently allowed.

java.awt.Toolkit
  public final EventQueue
               getSystemEventQueue()
checkAwtEventQueueAccess java.awt.AWTPermission "accessEventQueue"
java.awt.Window
  Window()
checkTopLevelWindow If java.awt.AWTPermission "showWindowWithoutWarningBanner" is set, the window will be displayed without a banner warning that the window was created by an applet. It it's not set, such a banner will be displayed.
java.beans.Beans
  public static void setDesignTime(
                 boolean isDesignTime)
  public static void setGuiAvailable(
                 boolean isGuiAvailable)

java.beans.Introspector
  public static synchronized void
    setBeanInfoSearchPath(String path[])

java.beans.PropertyEditorManager
  public static void registerEditor(
                 Class targetType,
                 Class editorClass)
  public static synchronized void
    setEditorSearchPath(String path[])
checkPropertiesAccess java.util.PropertyPermission "*", "read,write"
java.io.File
  public boolean delete()
  public void deleteOnExit()
checkDelete(String) java.io.FilePermission "{name}", "delete"
java.io.FileInputStream
  FileInputStream(FileDescriptor fdObj)
checkRead(FileDescriptor) java.lang.RuntimePermission "readFileDescriptor"
java.io.FileInputStream
  FileInputStream(String name)
  FileInputStream(File file)

java.io.File
  public boolean exists()
  public boolean canRead()
  public boolean isFile()
  public boolean isDirectory()
  public boolean isHidden()
  public long lastModified()
  public long length()
  public String[] list()
  public String[] list(
           FilenameFilter filter)
  public File[] listFiles()
  public File[] listFiles(
           FilenameFilter filter)
  public File[] listFiles(
           FileFilter filter)

java.io.RandomAccessFile
  RandomAccessFile(String name, String mode)
  RandomAccessFile(File file, String mode)
      (where mode is "r" in both of these)
checkRead(String) java.io.FilePermission "{name}", "read"
java.io.FileOutputStream
  FileOutputStream(FileDescriptor fdObj)
checkWrite(FileDescriptor) java.lang.RuntimePermission "writeFileDescriptor"
java.io.FileOutputStream
  FileOutputStream(File file)
  FileOutputStream(String name)
  FileOutputStream(String name,
                   boolean append)

java.io.File
  public boolean canWrite()
  public boolean createNewFile()
  public static File createTempFile(
          String prefix, String suffix)
  public static File createTempFile(
          String prefix,  String suffix,
          File directory)
  public boolean mkdir()
  public boolean mkdirs()
  public boolean renameTo(File dest)
  public boolean setLastModified(long time)
  public boolean setReadOnly()
checkWrite(String) java.io.FilePermission "{name}", "write"
java.io.ObjectInputStream
  protected final boolean
    enableResolveObject(boolean enable);

java.io.ObjectOutputStream
  protected final boolean
    enableReplaceObject(boolean enable)
checkPermission java.io.SerializablePermission "enableSubstitution"
java.io.ObjectInputStream
  protected ObjectInputStream()

java.io.ObjectOutputStream
  protected ObjectOutputStream()
checkPermission java.io.SerializablePermission "enableSubclassImplementation"
java.io.RandomAccessFile
  RandomAccessFile(String name, String mode)
      (where mode is "rw")
checkRead(String) and checkWrite(String) java.io.FilePermission "{name}", "read,write"
java.lang.Class
  public static Class forName(
     String name, boolean initialize,
     ClassLoader loader)
checkPermission If loader is null, and the caller's class loader is not null, then java.lang.RuntimePermission("getClassLoader")
java.lang.Class
  public ClassLoader getClassLoader()
checkPermission If the caller's class loader is null, or is the same as or an ancestor of the class loader for the class whose class loader is being requested, no permission is needed. Otherwise,
java.lang.RuntimePermission "getClassLoader"
is required.
java.lang.Class
  public Class[] getDeclaredClasses()
  public Field[] getDeclaredFields()
  public Method[] getDeclaredMethods()
  public Constructor[]
    getDeclaredConstructors()
  public Field getDeclaredField(
                       String name)
  public Method getDeclaredMethod(...)
  public Constructor
    getDeclaredConstructor(...)
checkMemberAccess(this, Member.DECLARED) and, if this class is in a package, checkPackageAccess({pkgName}) Default checkMemberAccess does not require any permissions if "this" class's classloader is the same as that of the caller. Otherwise, it requires java.lang.RuntimePermission "accessDeclaredMembers". If this class is in a package, java.lang.RuntimePermission "accessClassInPackage.{pkgName}" is also required.
java.lang.Class
  public Class[] getClasses()
  public Field[] getFields()
  public Method[] getMethods()
  public Constructor[] getConstructors()
  public Field getField(String name)
  public Method getMethod(...)
  public Constructor getConstructor(...)
checkMemberAccess(this, Member.PUBLIC) and, if class is in a package, checkPackageAccess({pkgName}) Default checkMemberAccess does not require any permissions when the access type is Member.PUBLIC. If this class is in a package, java.lang.RuntimePermission "accessClassInPackage.{pkgName}" is required.
java.lang.Class
   public ProtectionDomain
            getProtectionDomain()
checkPermission java.lang.RuntimePermission "getProtectionDomain"
java.lang.ClassLoader
  ClassLoader()
  ClassLoader(ClassLoader parent)
checkCreateClassLoader java.lang.RuntimePermission "createClassLoader"
java.lang.ClassLoader
  public static ClassLoader
           getSystemClassLoader()
  public ClassLoader getParent()
checkPermission If the caller's class loader is null, or is the same as or an ancestor of the class loader for the class whose class loader is being requested, no permission is needed. Otherwise,
java.lang.RuntimePermission "getClassLoader"
is required.
java.lang.Runtime
  public Process exec(String command)
  public Process exec(String command,
                      String envp[])
  public Process exec(String cmdarray[])
  public Process exec(String cmdarray[],
                      String envp[])
checkExec java.io.FilePermission "{command}", "execute"
java.lang.Runtime
  public void exit(int status)
  public static void
      runFinalizersOnExit(boolean value)
java.lang.System
  public static void exit(int status)
  public static void
      runFinalizersOnExit(boolean value)
checkExit(status) where status is 0 for runFinalizersOnExit java.lang.RuntimePermission "exitVM.{status}"
java.lang.Runtime
  public void addShutdownHook(Thread hook)
  public boolean removeShutdownHook(Thread hook)
checkPermission java.lang.RuntimePermission "shutdownHooks"
java.lang.Runtime
  public void load(String lib)
  public void loadLibrary(String lib)
java.lang.System
  public static void load(String filename)
  public static void loadLibrary(
                          String libname)
checkLink({libName}) where {libName} is the lib, filename or libname argument java.lang.RuntimePermission "loadLibrary.{libName}"
java.lang.SecurityManager methods
checkPermission See the next table.
java.lang.System
  public static Properties
      getProperties()
  public static void
      setProperties(Properties props)
checkPropertiesAccess java.util.PropertyPermission "*", "read,write"
java.lang.System
  public static String
      getProperty(String key)
  public static String
      getProperty(String key, String def)
checkPropertyAccess java.util.PropertyPermission "{key}", "read"
java.lang.System
  public static void setIn(InputStream in)
  public static void setOut(PrintStream out)
  public static void setErr(PrintStream err)
checkPermission java.lang.RuntimePermission "setIO"
java.lang.System
  public static String
    setProperty(String key, String value)
checkPermission java.util.PropertyPermission "{key}", "write"
java.lang.System
  public static synchronized void
    setSecurityManager(SecurityManager s)
checkPermission java.lang.RuntimePermission "setSecurityManager"
java.lang.Thread
  public ClassLoader getContextClassLoader()
checkPermission If the caller's class loader is null, or is the same as or an ancestor of the context class loader for the thread whose context class loader is being requested, no permission is needed. Otherwise,
java.lang.RuntimePermission "getClassLoader"
is required.
java.lang.Thread
  public void setContextClassLoader
                      (ClassLoader cl)
checkPermission java.lang.RuntimePermission "setContextClassLoader"
java.lang.Thread
  public final void checkAccess()
  public void interrupt()
  public final void suspend()
  public final void resume()
  public final void setPriority
                     (int newPriority)
  public final void setName(String name)
  public final void setDaemon(boolean on)
checkAccess(this) java.lang.RuntimePermission "modifyThread"
java.lang.Thread
  public static int
      enumerate(Thread tarray[])
checkAccess({threadGroup}) java.lang.RuntimePermission "modifyThreadGroup"
java.lang.Thread
  public final void stop()
checkAccess(this). Also checkPermission if the current thread is trying to stop a thread other than itself. java.lang.RuntimePermission "modifyThread".
Also java.lang.RuntimePermission "stopThread" if the current thread is trying to stop a thread other than itself.
java.lang.Thread
  public final synchronized void
                    stop(Throwable obj)
checkAccess(this). Also checkPermission if the current thread is trying to stop a thread other than itself or obj is not an instance of ThreadDeath. java.lang.RuntimePermission "modifyThread".
Also java.lang.RuntimePermission "stopThread" if the current thread is trying to stop a thread other than itself or obj is not an instance of ThreadDeath.
java.lang.Thread
  Thread()
  Thread(Runnable target)
  Thread(String name)
  Thread(Runnable target, String name)

java.lang.ThreadGroup
  ThreadGroup(String name)
  ThreadGroup(ThreadGroup parent,
              String name)
checkAccess({parentThreadGroup}) java.lang.RuntimePermission "modifyThreadGroup"
java.lang.Thread
  Thread(ThreadGroup group, ...)

java.lang.ThreadGroup
  public final void checkAccess()
  public int enumerate(Thread list[])
  public int enumerate(Thread list[],
      boolean recurse)
  public int enumerate(ThreadGroup list[])
  public int enumerate(ThreadGroup list[],
      boolean recurse)
  public final ThreadGroup getParent()
  public final void
      setDaemon(boolean daemon)
  public final void setMaxPriority(int pri)
  public final void suspend()
  public final void resume()
  public final void destroy()
checkAccess(this) for ThreadGroup methods, or checkAccess(group) for Thread methods java.lang.RuntimePermission "modifyThreadGroup"
java.lang.ThreadGroup
  public final void interrupt()
checkAccess(this) Requires java.lang.RuntimePermission "modifyThreadGroup".
Also requires java.lang.RuntimePermission "modifyThread", since the java.lang.Thread interrupt() method is called for each thread in the thread group and in all of its subgroups. See the Thread interrupt() method.
java.lang.ThreadGroup
  public final void stop()
checkAccess(this) Requires java.lang.RuntimePermission "modifyThreadGroup".
Also requires java.lang.RuntimePermission "modifyThread" and possibly java.lang.RuntimePermission "stopThread", since the java.lang.Thread stop() method is called for each thread in the thread group and in all of its subgroups. See the Thread stop() method.
java.lang.reflect.AccessibleObject
  public static void setAccessible(...)
  public void setAccessible(...)
checkPermission java.lang.reflect.ReflectPermission "suppressAccessChecks"
java.net.Authenticator
  public static PasswordAuthentication
       requestPasswordAuthentication(
             InetAddress addr,
             int port,
             String protocol,
             String prompt,
             String scheme)
checkPermission java.net.NetPermission "requestPasswordAuthentication"
java.net.Authenticator
  public static void
      setDefault(Authenticator a)
checkPermission java.net.NetPermission "setDefaultAuthenticator"
java.net.MulticastSocket
  public void
      joinGroup(InetAddress mcastaddr)
  public void
      leaveGroup(InetAddress mcastaddr)
checkMulticast(InetAddress) java.net.SocketPermission( mcastaddr.getHostAddress(), "accept,connect")
java.net.DatagramSocket
  public void send(DatagramPacket p)
checkMulticast(p.getAddress()) or checkConnect(
p.getAddress().getHostAddress(), p.getPort()) 		if (p.getAddress().isMulticastAddress()) {
java.net.SocketPermission(
(p.getAddress()).getHostAddress(), "accept,connect")
}
else {
port = p.getPort();
host = p.getAddress().getHostAddress();
if (port == -1) java.net.SocketPermission "{host}","resolve";
else java.net.SocketPermission "{host}:{port}","connect"
}
java.net.MulticastSocket
  public synchronized void
      send(DatagramPacket p, byte ttl)
checkMulticast(p.getAddress(), ttl) or checkConnect(
p.getAddress().getHostAddress(), p.getPort()) 		if (p.getAddress().isMulticastAddress()) {
java.net.SocketPermission(
(p.getAddress()).getHostAddress(), "accept,connect")
}
else {
port = p.getPort();
host = p.getAddress().getHostAddress();
if (port == -1) java.net.SocketPermission "{host}","resolve";
else java.net.SocketPermission "{host}:{port}","connect"
}
java.net.InetAddress
  public String getHostName()
  public static InetAddress[]
                  getAllByName(String host)
  public static InetAddress getLocalHost()

java.net.DatagramSocket
  public InetAddress getLocalAddress()
checkConnect({host}, -1) java.net.SocketPermission "{host}", "resolve"
java.net.ServerSocket
  ServerSocket(...)

java.net.DatagramSocket
  DatagramSocket(...)

java.net.MulticastSocket
  MulticastSocket(...)
checkListen({port}) if (port == 0) java.net.SocketPermission "localhost:1024-","listen";
else java.net.SocketPermission "localhost:{port}","listen"
java.net.ServerSocket
  public Socket accept()
  protected final void implAccept(Socket s)
checkAccept({host}, {port}) java.net.SocketPermission "{host}:{port}", "accept"
java.net.ServerSocket
  public static synchronized void
      setSocketFactory(...)

java.net.Socket
  public static synchronized void
      setSocketImplFactory(...)

java.net.URL
  public static synchronized void
      setURLStreamHandlerFactory(...)

 java.net.URLConnection
   public static synchronized void
      setContentHandlerFactory(...)
   public static void
      setFileNameMap(FileNameMap map)

java.net.HttpURLConnection
   public static void
       setFollowRedirects(boolean set)

java.rmi.activation.ActivationGroup
  public static synchronized
        ActivationGroup createGroup(...)
  public static synchronized void
      setSystem(ActivationSystem system)

java.rmi.server.RMISocketFactory
   public synchronized static void
      setSocketFactory(...)
checkSetFactory java.lang.RuntimePermission "setFactory"
java.net.Socket
  Socket(...)
checkConnect({host}, {port}) java.net.SocketPermission "{host}:{port}", "connect"
java.net.DatagramSocket
  public synchronized void
      receive(DatagramPacket p)
checkAccept({host}, {port}) java.net.SocketPermission "{host}:{port}", "accept"
java.net.URL
  URL(...)
checkPermission java.net.NetPermission "specifyStreamHandler"
java.net.URLClassLoader
  URLClassLoader(...)
checkCreateClassLoader java.lang.RuntimePermission "createClassLoader"
java.security.AccessControlContext
  public AccessControlContext(AccessControlContext acc,
                                DomainCombiner combiner)
  public DomainCombiner getDomainCombiner()
checkPermission java.security.SecurityPermission "createAccessControlContext"
java.security.Identity
  public void addCertificate(...)
checkSecurityAccess(
"addIdentityCertificate") 		java.security.SecurityPermission "addIdentityCertificate"
java.security.Identity
  public void removeCertificate(...)
checkSecurityAccess(
"removeIdentityCertificate") 		java.security.SecurityPermission "removeIdentityCertificate"
java.security.Identity
  public void setInfo(String info)
checkSecurityAccess(
"setIdentityInfo") 		java.security.SecurityPermission "setIdentityInfo"
java.security.Identity
  public void setPublicKey(PublicKey key)
checkSecurityAccess(
"setIdentityPublicKey") 		java.security.SecurityPermission "setIdentityPublicKey"
java.security.Identity
  public String toString(...)
checkSecurityAccess(
"printIdentity") 		java.security.SecurityPermission "printIdentity"
java.security.IdentityScope
  protected static void setSystemScope()
checkSecurityAccess(
"setSystemScope") 		java.security.SecurityPermission "setSystemScope"
java.security.Permission
  public void checkGuard(Object object)
checkPermission(this) this Permission object is the permission checked
java.security.Policy
  public static Policy getPolicy()
checkPermission java.security.SecurityPermission "getPolicy"
java.security.Policy
  public static void
      setPolicy(Policy policy)
checkPermission java.security.SecurityPermission "setPolicy"
java.security.Policy
  public static Policy
      getInstance(String type, SpiParameter params)
      getInstance(String type, SpiParameter params, String provider)
      getInstance(String type, SpiParameter params, Provider provider)
checkPermission java.security.SecurityPermission "createPolicy.{type}"
java.security.Provider
  public synchronized void clear()
checkSecurityAccess(
"clearProviderProperties."+{name}) 		java.security.SecurityPermission "clearProviderProperties.{name}" where name is the provider name.
java.security.Provider
  public synchronized Object
      put(Object key, Object value)
checkSecurityAccess(
"putProviderProperty."+{name}) 		java.security.SecurityPermission "putProviderProperty.{name}" where name is the provider name.
java.security.Provider
  public synchronized Object
      remove(Object key)
checkSecurityAccess(
"removeProviderProperty."+{name}) 		java.security.SecurityPermission "removeProviderProperty.{name}" where name is the provider name.
java.security.SecureClassLoader
  SecureClassLoader(...)
checkCreateClassLoader java.lang.RuntimePermission "createClassLoader"
java.security.Security
  public static void getProperty(String key)
checkPermission java.security.SecurityPermission "getProperty.{key}"
java.security.Security
  public static int
      addProvider(Provider provider)
  public static int
      insertProviderAt(Provider provider,
                       int position);
checkSecurityAccess(
"insertProvider."+provider.getName()) 		java.security.SecurityPermission "insertProvider.{name}"
java.security.Security
  public static void
      removeProvider(String name)
checkSecurityAccess(
"removeProvider."+name) 		java.security.SecurityPermission "removeProvider.{name}"
java.security.Security
  public static void
    setProperty(String key, String datum)
checkSecurityAccess(
"setProperty."+key) 		java.security.SecurityPermission "setProperty.{key}"
java.security.Signer
  public PrivateKey getPrivateKey()
checkSecurityAccess(
"getSignerPrivateKey") 		java.security.SecurityPermission "getSignerPrivateKey"
java.security.Signer
  public final void
      setKeyPair(KeyPair pair)
checkSecurityAccess(
"setSignerKeypair") 		java.security.SecurityPermission "setSignerKeypair"
java.sql.DriverManager
  public static synchronized void
      setLogWriter(PrintWriter out)
checkPermission java.sql.SQLPermission "setLog"
java.sql.DriverManager
  public static synchronized void
      setLogStream(PrintWriter out)
checkPermission java.sql.SQLPermission "setLog"
java.util.Locale
  public static synchronized void
            setDefault(Locale newLocale)
checkPermission java.util.PropertyPermission "user.language","write"
java.util.zip.ZipFile
  ZipFile(String name)
checkRead java.io.FilePermission "{name}","read"
javax.security.auth.Subject
    public static Subject getSubject(final AccessControlContext acc)
checkPermission javax.security.auth.AuthPermission "getSubject"
javax.security.auth.Subject
    public void setReadOnly()
checkPermission javax.security.auth.AuthPermission "setReadOnly"
javax.security.auth.Subject
    public static Object doAs(final Subject subject,
                                final PrivilegedAction action)
checkPermission javax.security.auth.AuthPermission "doAs"
javax.security.auth.Subject
    public static Object doAs(final Subject subject,
                                final PrivilegedExceptionAction action)
        throws java.security.PrivilegedActionException
checkPermission javax.security.auth.AuthPermission "doAs"
javax.security.auth.Subject
    public static Object doAsPrivileged(final Subject subject,
                                final PrivilegedAction action,
                                final AccessControlContext acc)
checkPermission javax.security.auth.AuthPermission "doAsPrivileged"
javax.security.auth.Subject
    public static Object doAsPrivileged(final Subject subject,
                                final PrivilegedExceptionAction action,
                                final AccessControlContext acc)
        throws java.security.PrivilegedActionException
checkPermission javax.security.auth.AuthPermission "doAsPrivileged"
javax.security.auth.SubjectDomainCombiner
    public Subject getSubject()
checkPermission javax.security.auth.AuthPermission "getSubjectFromDomainCombiner"
javax.security.auth.SubjectDomainCombiner
    public Subject getSubject()
checkPermission javax.security.auth.AuthPermission "getSubjectFromDomainCombiner"
javax.security.auth.login.LoginContext
    public LoginContext(String name)
        throws LoginException
checkPermission javax.security.auth.AuthPermission "createLoginContext.{name}"
javax.security.auth.login.LoginContext
    public LoginContext(String name,
                        Subject subject)
         throws LoginException
checkPermission javax.security.auth.AuthPermission "createLoginContext.{name}"
javax.security.auth.login.LoginContext
    public LoginContext(String name,
                        CallbackHandler callbackHandler)
         throws LoginException
checkPermission javax.security.auth.AuthPermission "createLoginContext.{name}"
javax.security.auth.login.LoginContext
    public LoginContext(String name,
                        Subject subject,
                        CallbackHandler callbackHandler)
         throws LoginException
checkPermission javax.security.auth.AuthPermission "createLoginContext.{name}"
javax.security.auth.login.Configuration
    public static Configuration getConfiguration()
checkPermission javax.security.auth.AuthPermission "getLoginConfiguration"
javax.security.auth.login.Configuration
    public static void setConfiguration(Configuration configuration)
checkPermission javax.security.auth.AuthPermission "setLoginConfiguration"
javax.security.auth.login.Configuration
    public static void refresh()
checkPermission javax.security.auth.AuthPermission "refreshLoginConfiguration"
javax.security.auth.login.Configuration
  public static Configuration
      getInstance(String type, SpiParameter params)
      getInstance(String type, SpiParameter params, String provider)
      getInstance(String type, SpiParameter params, Provider provider)
checkPermission javax.security.auth.AuthPermission "createLoginConfiguration.{type}"

java.lang.SecurityManager Method Permission Checks

This table shows which permissions are checked for by the default implementations of the java.lang.SecurityManager methods.

Each of the specified check methods calls the SecurityManager checkPermission method with the specified permission, except for the checkConnect and checkRead methods that take a context argument. Those methods expect the context to be an AccessControlContext and they call the context's checkPermission method with the specified permission.

Method | Permission
public void checkAccept(String host, int port); | java.net.SocketPermission "{host}:{port}", "accept";
public void checkAccess(Thread t); | java.lang.RuntimePermission "modifyThread";
public void checkAccess(ThreadGroup g); | java.lang.RuntimePermission "modifyThreadGroup";
public void checkAwtEventQueueAccess(); | java.awt.AWTPermission "accessEventQueue";
public void checkConnect(String host, int port); if (port == -1) java.net.SocketPermission "{host}","resolve";
else java.net.SocketPermission "{host}:{port}","connect";
public void checkConnect(String host, int port, Object context); if (port == -1) java.net.SocketPermission "{host}","resolve";
else java.net.SocketPermission "{host}:{port}","connect";
public void checkCreateClassLoader(); | java.lang.RuntimePermission "createClassLoader";
public void checkDelete(String file); | java.io.FilePermission "{file}", "delete";
public void checkExec(String cmd); if cmd is an absolute path: java.io.FilePermission "{cmd}", "execute";
else java.io.FilePermission "<<ALL_FILES>>", "execute";
public void checkExit(int status); | java.lang.RuntimePermission "exitVM.{status}";
public void checkLink(String lib); | java.lang.RuntimePermission "loadLibrary.{lib}";
public void checkListen(int port); if (port == 0) java.net.SocketPermission "localhost:1024-","listen";
else java.net.SocketPermission "localhost:{port}","listen";
public void checkMemberAccess(Class clazz, int which);
if (which != Member.PUBLIC) {
  if (currentClassLoader() != clazz.getClassLoader()) {
    checkPermission(
      new java.lang.RuntimePermission("accessDeclaredMembers"));
  }
}
public void checkMulticast(InetAddress maddr); | java.net.SocketPermission(maddr.getHostAddress(),"accept,connect");
public void checkMulticast(InetAddress maddr, byte ttl); | java.net.SocketPermission(maddr.getHostAddress(),"accept,connect");
public void checkPackageAccess(String pkg); | java.lang.RuntimePermission "accessClassInPackage.{pkg}";
public void checkPackageDefinition(String pkg); | java.lang.RuntimePermission "defineClassInPackage.{pkg}";
public void checkPrintJobAccess(); | java.lang.RuntimePermission "queuePrintJob";
public void checkPropertiesAccess(); | java.util.PropertyPermission "*", "read,write";
public void checkPropertyAccess(String key); | java.util.PropertyPermission "{key}", "read,write";
public void checkRead(FileDescriptor fd); | java.lang.RuntimePermission "readFileDescriptor";
public void checkRead(String file); | java.io.FilePermission "{file}", "read";
public void checkRead(String file, Object context); | java.io.FilePermission "{file}", "read";
public void checkSecurityAccess(String action); | java.security.SecurityPermission "{action}";
public void checkSetFactory(); | java.lang.RuntimePermission "setFactory";
public void checkSystemClipboardAccess(); | java.awt.AWTPermission "accessClipboard";
public boolean checkTopLevelWindow(Object window); | java.awt.AWTPermission "showWindowWithoutWarningBanner";
public void checkWrite(FileDescriptor fd); | java.lang.RuntimePermission "writeFileDescriptor";
public void checkWrite(String file); | java.io.FilePermission "{file}", "write";
public SecurityManager(); | java.lang.RuntimePermission "createSecurityManager";
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Using Activation: Persistence

This tutorial describes how to implement an activatable remote object that uses persistent state in its implementation. This tutorial uses a Setup program (described in the tutorial Using Activation: the Setup Program) that registers information about an activatable remote object with the JavaTM Remote Method Invocation (Java RMI) activation system daemon (rmid) and then binds a stub for that remote object in an rmiregistry so that clients can look it up. You may want to read that tutorial before this one.

This tutorial has the following steps:

  • Implement the activatable remote object
  • Implement the client
  • Compile the source files
  • Run the Setup program
  • Run the client

The files needed for this tutorial are:

  • Counter.java - a remote interface for counting
  • CounterImpl.java - an "activatable" implementation of the remote interface
  • CounterClient.java - a client that uses the remote interface
  • client.policy - the security policy file for the client

Implement the activatable remote object

There are a few basic ways to implement an activatable remote object. This tutorial describes how to implement an activatable remote object that uses persistent state in its implementation.

A remote object is activated when a client invokes a remote method on a stub for an activatable remote object. A stub for an activatable remote object contains the remote object's activation ID and information on how to contact the Java RMI activation system daemon (rmid) for the remote object. If the stub cannot connect to the last-known address (i.e., host/port) for the remote object, the stub will contact the remote object's activator (rmid) to activate the object. When rmid receives an activation request, it starts the remote object's activation group (or container) virtual machine (VM) if the group is not already executing, and then rmid asks the group to make an instance of the remote object. Once the group constructs the remote object, it returns the remote object's stub to rmid which, in turn, returns the actual stub to the initiating stub so that the initiating stub can update its information on how to contact the remote object in the future.

Before any of this activation can take place, an application must register information about the activatable remote objects it needs to use. The following separate tutorial describes the information needed to activatate a remote object and how to register this information with rmid:

  • Using Activation: the Setup program

This example defines the remote interface Counter with a single operation, increment. The implementation class CounterImpl persistently stores the result of the operation increment in a file, so that the result of the increment operation will survive across an object activation/deactivation cycle or even survive a machine reboot or crash. To make all this work, a CounterImpl object, when activated, needs the name of the file it will use to read and store counter values. A user can register an activation descriptor that contains this file name (in a MarshalledObject) as the "initialization data". The object's activation group will pass this pre-registered marshalled data (the file name) to the object's constructor when the group constructs the object during activation.

The remote interface examples.activation.Counter is defined as follows:

package examples.activation;

import java.rmi.Remote;
import java.io.IOException;

public interface Counter extends Remote {

    int increment() throws IOException;
}

The implementation class, examples.activation.CounterImpl, for the activatable remote object is as follows:

package examples.activation;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.rmi.MarshalledObject;
import java.rmi.activation.Activatable;
import java.rmi.activation.ActivationID;

public class CounterImpl implements Counter {
    private RandomAccessFile raf;
    private int count;
    private final Object countLock = new Object();

    public CounterImpl(ActivationID id, MarshalledObject data)
        throws Exception
    {
        if (data != null) {
            String filename = (String) data.get();
            synchronized (countLock) {
                count = openFile(filename);
            }
            System.err.println("count upon activation = " + count);
        }

        Activatable.exportObject(this, id, 0);
    }

    private int openFile(String filename) throws IOException {

        if (filename != null && !filename.equals("")) {
            File file = new File(filename);
            boolean fileExists = file.exists();
            raf = new RandomAccessFile(file, "rws");
            return (fileExists) ? raf.readInt() : writeCount(0);

        } else {
            throw new IOException("invalid filename");
        }
    }

    private int writeCount(int value) throws IOException {
        raf.setLength(0);
        raf.writeInt(value);
        return value;
    }

    public int increment() throws IOException {
        synchronized (countLock) {
            return writeCount(++count);
        }
    }
}

The class CounterImpl implements the remote interface Counter, but does not extend any class.

The class declares a special "activation" constructor that an activation group calls to construct an instance during the activation process. This special constructor takes two parameters:

  • The first parameter, ActivationID, is an identifier for the activatable remote object. When an application registers an activation descriptor with rmid, rmid assigns it an activation ID, which refers to the information associated with the descriptor. This same activation ID (also contained in the remote object's stub) is passed to this constructor when the remote object is activated.
  • The second parameter is a MarshalledObject that contains initialization data pre-registered with rmid. In this example, the marshalled data is the name of a file containing the object's persistent state which is the latest counter value.

The constructor obtains the file name contained in the MarshalledObject which was passed as the second parameter. Next, the constructor calls the local method openFile to open the file and return the current counter value. If the file exists, the openFile method reads the value last saved to the file; otherwise, it creates a new file and initializes the count to zero. The constructor then calls the static method Activatable.exportObject, passing the implementation itself (this), the activation ID, and the port number 0, indicating that the object should be exported on an anonymous TCP port. While this implementation does not use the activation ID passed as a parameter to the constructor, another implementation may wish to save the activation ID for future use, in order to deactivate the object, for example.

Finally, the class implements the remote interface's single method, increment to increment the count, save the count to the file, and return the incremented count. Note that there is a flaw in the implementation of the writeCount method. If the machine crashes between the calls to setLength and writeInt, the value of the counter will be lost. Making this implementation more robust to a crash within that small window is an exercise left to the reader.

Implement the client

The CounterClient program looks up a remote object's stub (one that implements the remote interface Counter) in the registry on the host supplied as the optional first argument, and then invokes the stub's increment method and displays the result. When this client invokes a remote method on the stub acquired from the registry, the remote object will activate if not already active.

The source for the program is as follows:

package examples.activation;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class CounterClient {

    public static void main(String args[])  throws Exception {

        String hostname = "localhost";
        if (args.length < 1) {
            System.err.println(
                "usage: java [options] examples.activation.CounterClient [host]");
            System.exit(1);
        } else {
            hostname = args[0];
        }

        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new SecurityManager());
        }

        String name = System.getProperty("examples.activation.name");
        Registry registry = LocateRegistry.getRegistry(hostname);
        Counter stub = (Counter) registry.lookup(name);
        System.err.println("Obtained stub from the registry.");

        System.err.println("Invoking increment method...");
        int count = stub.increment();
        System.err.println("Returned from increment remote call.");
        System.err.println("count = " + count);
    }
}

This program should be run as follows:

java -cp clientDir                               \
     -Djava.security.policy=client.policy        \
     -Dexamples.activation.client.codebase=clientCodebase   \
     -Dexamples.activation.name=name             \
     examples.activation.CounterClient [host]

where:

  • clientDir is the root directory for the client program (its class path),
  • client.policy is the security policy file for this program,
  • clientCodebase is the location (URL) for this program's class (used in granting permissions to this program in the client.policy file)
  • name is the name for the object's stub in the registry
  • host is the server's host

Note: rmid must be running on its default port, and rmiregistry must be running on its default port (both on the remote host) prior to running this program.

The following is an example client.policy file that grants the appropriate permissions for the activation examples:

grant codeBase "${examples.activation.client.codebase}" {

    // permissions to read system properties required by the client
    permission java.util.PropertyPermission "examples.activation.name","read";

    // permission to connect to the registry, activation system, and remote host
    permission java.net.SocketPermission "*:1024-","connect";
};

The codebase to which permissions are granted is a file URL specifying the location of the client's classes. This file URL is the value of the examples.activation.client.codebase system property, defined when the client program is run. The client needs two permissions:

  • java.util.PropertyPermission - to read the system property examples.activation.name that specifies the name for the stub in the registry
  • java.net.SocketPermission - to connect to the registry, activation system, and remote object's host

Compile the source files

The source files for this example can be compiled as follows:

javac -d implDir Counter.java CounterImpl.java
javac -d clientDir Counter.java CounterClient.java

where implDir is the destination directory to put the implementation's class files in, and clientDir is the destination directory to put the client's class files in.

Run the Setup program

Once your implementation phase is complete, you need to register information about the activatable object so a client can use it. The Setup program, described by the tutorial Using Activation: the Setup Program, registers an activation descriptor for an activatable object with rmid, and then binds the remote object's stub in an rmiregistry so that clients can look it up.

To run the Setup program for this example, see the section Start rmid, rmiregistry, and the Setup program in the Setup program tutorial, which describes how to start rmid, rmiregistry, and the Setup program itself.

After you run rmid and rmiregistry as instructed in the Setup tutorial, you will need to run the Setup program to register an activation descriptor for an activatable object that implements the class examples.activation.CounterImpl. The following command line runs the Setup program, supplying an appropriate file URL for each codebase used:

java -cp setupDir:implDir                       \
     -Djava.security.policy=setup.policy                      \
     -Djava.rmi.server.codebase=file:/implDir/                \
     -Dexamples.activation.setup.codebase=file:/setupDir/     \
     -Dexamples.activation.impl.codebase=file:/impDir/        \
     -Dexamples.activation.name=examples.activation.Counter                 \
     -Dexamples.activation.policy=group.policy                \
     -Dexamples.activation.file=file                          \
         examples.activation.Setup examples.activation.CounterImpl

where:

  • setupDir is the root directory for the Setup program's class
  • implDir is the root directory for the implementation's classes
  • setup.policy is the security policy file for the Setup program
  • group.policy is the security policy file for the activation group
  • file is the name of a file containing the object's persistent state which is registered as the data in the object's activation descriptor

Note that each file URL above has the required trailing slash. Examples of group and setup policy files, suitable for this tutorial, are described in the Setup tutorial, and are listed below:

  • setup.policy
  • group.policy

The output from the Setup program should look like this:

Activation group descriptor registered.
Activation descriptor registered.
Stub bound in registry.

Run the client

Once you have successfully registered an activation descriptor for a CounterImpl implementation, you can run the client program, which, during its first execution, will cause the activatable object to activate.

The following command line illustrates how to run the client program, specifying a file URL for the client codebase:

java -cp clientDir                                              \
     -Djava.security.policy=client.policy                       \
     -Dexamples.activation.client.codebase=file:/clientDir/     \
     -Dexamples.activation.name=examples.activation.Counter                   \
     examples.activation.CounterClient [host]

where:

  • clientDir is the root directory for the client program (its class path).
  • client.policy is the security policy file for this program.
  • name is the name for the object's stub in the registry.
  • host is the server's host.

Notes:

  • The client codebase must have a trailing slash.
  • The name must match the name supplied to the Setup program. In this example, we used the name examples.activation.Counter.
  • rmid and rmiregistry must be running on the server's host. If the server's host is not the local host, the host argument must specify the remote host that they are running on.

The output from the client should look like this:

Obtained stub from the registry.
Invoking increment method...
Returned from increment remote call.
count = 1
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


PersistenceService (JNLP API Reference 1.7.0)

  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method
javax.jnlp

Interface PersistenceService

  • public interface PersistenceService
    PersistenceService provides methods for storing data locally on the client system, even for applications that are running in the untrusted execution environment. The service is somewhat similar to that which the cookie mechanism provides to HTML-based applications.

    Each entry in the persistence data store is named with a URL. This provides a similar hierarchical structure as a traditional file system.

    An application is only allowed to access data stored with a URL that is based on its codebase. For example, given the codebase http://www.mysite.com/apps/App1/, the application would be allowed to access the data at the associated URLs:

    • http://www.mysite.com/apps/App1/
    • http://www.mysite.com/apps/
    • http://www.mysite.com/

    This scheme allows sharing of data between different applications from the same host. For example, if another application is located at http://www.mysite.com/apps/App2/, then they can share data between them in the http://www.mysite.com/ and http://www.mysite.com/apps/ directories.

    A JNLP client should track the amount of storage that a given application uses. A PersistenceService implementation provides methods to get the current storage usage and limits and to request more storage. Storage is allocated on a per file basis, but a JNLP Client will typically grant or deny the request based on the total storage is use by an application.

    Data stored using this mechanism is intended to be a local copy of data stored on a remote server. The individual entries can be tagged as either cached, meaning the server has an up-to-date copy, dirty, meaning the server does not have an up-to-date copy, or temporary, meaning that the file can always be recreated.

    Since:
    1.0

    • Field Summary

      Fields
      Modifier and Type | Field and Description
      static int | CACHED
      static int | DIRTY
      static int | TEMPORARY

    • Method Summary

      Methods
      Modifier and Type Method and Description
      long create(java.net.URL url, long maxsize)
      Creates a new persistent storage entry on the client side named with the given URL.
      void delete(java.net.URL url)
      Removes the stream associated with the given URL from the client-side date persistence store.
      FileContents get(java.net.URL url)
      Returns a FileContents object representing the contents of this file.
      java.lang.String[] getNames(java.net.URL url)
      Returns an array of Strings containing the names of all the entries for a given URL.
      int getTag(java.net.URL url)
      Returns an int corresponding to the current value of the tag for the persistent data store entry associated with the given URL.
      void setTag(java.net.URL url, int tag)
      Tags the persistent data store entry associated with the given URL with the given tag value.

    • Field Detail

      • CACHED

        static final int CACHED
        See Also:
        Constant Field Values

      • TEMPORARY

        static final int TEMPORARY
        See Also:
        Constant Field Values

      • DIRTY

        static final int DIRTY
        See Also:
        Constant Field Values

    • Method Detail

      • create

        long create(java.net.URL url,
          long maxsize)
            throws java.net.MalformedURLException,
                   java.io.IOException
        Creates a new persistent storage entry on the client side named with the given URL.
        Parameters:
        url - the URL representing the name of the entry in the persistent data store.
        maxsize - maximum size of storage that can be written to this entry.
        Returns:
        the maximum size of storage that got granted, in bytes.
        Throws:
        java.net.MalformedURLException - if the application is denied access to the persistent data store represented by the given URL.
        java.io.IOException - if an I/O exception occurs, or the entry already exists.

      • get

        FileContents get(java.net.URL url)
                 throws java.net.MalformedURLException,
                        java.io.IOException,
                        java.io.FileNotFoundException
        Returns a FileContents object representing the contents of this file.
        Parameters:
        url - the URL representing the persistent data store entry.
        Returns:
        the file contents as a FileContents.
        Throws:
        java.io.IOException - if an I/O error occurs.
        java.net.MalformedURLException - if the application is denied access to the persistent data store represented by the given URL.
        java.io.FileNotFoundException - if a persistence store for the given URL is not found.

      • delete

        void delete(java.net.URL url)
            throws java.net.MalformedURLException,
                   java.io.IOException
        Removes the stream associated with the given URL from the client-side date persistence store.
        Parameters:
        url - the URL representing the entry to delete from the persistent data store.
        Throws:
        java.net.MalformedURLException - if the application is denied access to the persistent data store represented by the given URL.
        java.io.IOException - if an I/O exception occurs.

      • getNames

        java.lang.String[] getNames(java.net.URL url)
                            throws java.net.MalformedURLException,
                                   java.io.IOException
        Returns an array of Strings containing the names of all the entries for a given URL.
        Parameters:
        url - the URL representing the root directory to search for entry names.
        Returns:
        a String array containing the entries names.
        Throws:
        java.net.MalformedURLException - if the application is denied access to the persistent data store represented by the given URL.
        java.io.IOException - if an I/O exception occurs.

      • getTag

        int getTag(java.net.URL url)
           throws java.net.MalformedURLException,
                  java.io.IOException
        Returns an int corresponding to the current value of the tag for the persistent data store entry associated with the given URL.
        Parameters:
        url - the URL representing the persistent data store entry for which the tag value is requested.
        Returns:
        an int containing one of the following tag values:
        • CACHED
        • TEMPORARY
        • DIRTY
        Throws:
        java.net.MalformedURLException - if the application is denied access to the persistent data store represented by the given URL.
        java.io.IOException - if an I/O exception occurs.

      • setTag

        void setTag(java.net.URL url,
          int tag)
            throws java.net.MalformedURLException,
                   java.io.IOException
        Tags the persistent data store entry associated with the given URL with the given tag value.
        Parameters:
        url - the URL representing the persistent data store entry for which to set the tag value.
        tag - the tag value to set.
        Throws:
        java.net.MalformedURLException - if the application is denied access to the persistent data store represented by the given URL.
        java.io.IOException - if an I/O exception occurs.
  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.


Java IDL: Portable Interceptors (PI)

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java IDL and Java RMI-IIOP Technologies: Using Portable Interceptors (PI)

Last Update: 4/25/2002

NOTICE: This document is intended for advanced CORBA developers.

The Java CORBA Object Request Broker (ORB) provides hooks, or interception points, through which ORB services can intercept the normal flow of execution of the ORB. These Portable Interceptors provide a mechanism for plugging in additional ORB behavior, or, by modifying the communications between client and server, for modifying the behavior of the ORB. The example that follows shows different ways of using Portable Interceptors.

Support for Portable Interceptors is a major recent addition to the CORBA specification. Using RequestInterceptors, one can easily write and attach portable ORB hooks that will intercept any ORB-mediated invocation. Using IORInterceptors, one can write code to annotate CORBA object references.

It is highly recommended that you read the Portable Interceptors Specification at ptc/2001-03-04 before reading this document.

The following topics are included in this document:

  • Interceptor Types
  • Registering ORBInitializers in Java
    • Notes About the Scope of Interceptors
    • Notes on Interceptor Order
    • Notes about Registering Interceptors
  • Portable Interceptor Current (PICurrent)
    • Obtaining PICurrent
    • Obtaining PICurrent
    • Request Scope vs Thread Scope
  • Portable Interceptor Example
    • Flowing Context Information between Clients and Servers
    • Avoiding Infinite Recursion During Interceptor Outcalls
    • Avoiding Recursion for Colocated Outcall References
    • Avoid recursion by using multiple ORBs
  • Example Code
  • Compiling and running the application

Interceptor Types

There are currently three types of interceptors that can be registered, as shown below. Examples of each are shown in the example that follows.

  • IORInterceptor

    In some cases, a portable ORB service implementation may need to add information describing the server's or object's ORB service-related capabilities to object references in order to enable the ORB service implementation in the client to function properly. This is supported through the IORInterceptor and IORInfo interfaces. The IOR Interceptor is used to establish tagged components in the profiles within an Interoperable Object Reference (IOR).

    An example of an IOR Interceptor is shown in the file AServiceIORInterceptor.java in the example that follows.

  • ClientRequestInterceptor

    A request Interceptor is designed to intercept the flow of a request/reply sequence through the ORB at specific points so that services can query the request information and manipulate the service contexts which are propagated between clients and servers. The primary use of request Interceptors is to enable ORB services to transfer context information between clients and servers.

    A ClientRequestInterceptor intercepts the flow of a request/reply sequence through the ORB on the client side.

  • An example of a ClientRequestInterceptor is shown in the file LoggingServiceClientInterceptor.java in the example that follows.

  • ServerRequestInterceptor

    A ServerRequestInterceptor intercepts the flow of a request/reply sequence through the ORB on the server side.

    An example of a ServerRequestInterceptor is shown in the file LoggingServiceServerInterceptor.java in the example that follows.

Registering ORBInitializers in Java

The ORBInitializer interface facilitates interceptor registration and ORB initialization.

Interceptors are intended to be a means by which ORB services gain access to ORB processing, effectively becoming part of the ORB. Since interceptors are part of the ORB, when ORB.init returns an ORB, the interceptors shall have been registered. Interceptors cannot be registered on an ORB after it has been returned by a call to ORB.init.

ORBInitializers are registered via Java ORB properties. An interceptor is registered by registering an associated ORBInitializer object which implements the ORBInitializer interface. When an ORB is initializing, it shall call each registered ORBInitializer, passing it an ORBInitInfo object which is used to register its interceptor.

The property names are of the form:

org.omg.PortableInterceptor.ORBInitializerClass.<Service>

where <Service> is the string name of a class which implements

org.omg.PortableInterceptor.ORBInitializer
To avoid name collisions, the reverse DNS name convention should be used. For example, if company X has three initializers, it could define the following properties:
  • org.omg.PortableInterceptor.ORBInitializerClass.com.x.Init1
  • org.omg.PortableInterceptor.ORBInitializerClass.com.x.Init2
  • org.omg.PortableInterceptor.ORBInitializerClass.com.x.Init3

Note: Any values associated with ORBInitializerClass properties are ignored.

During ORB.init, these ORB properties which begin with org.omg.PortableInterceptor.ORBInitializerClass shall be collected, the <Service> portion of each property shall be extracted, an object shall be instantiated with the <Service> string as its class name, and the pre_init and post_init methods shall be called on that object. If there are any exceptions, the ORB shall ignore them and proceed.

Notes About the Scope of Interceptors

  • Interceptors are registered on a per-ORB basis.
  • To achieve virtual per-POA interceptors, instantiate each POA with a different ORB.

Notes on Interceptor Order

  • While interceptors may be ordered administratively, there is no concept of order with respect to the registration of interceptors. Request Interceptors are concerned with service contexts. Service contexts have no order, so there is no purpose for request interceptors to have an order. IOR Interceptors are concerned with tagged components. Tagged components also have no order, so there is no purpose for IOR Interceptors to have an order.

Notes about Registering Interceptors

  • Registration code should avoid using the ORB (i.e., calling ORB.init with the provided orb_id). Since registration occurs during ORB initialization, results of invocations on this ORB while it is in this state are undefined.

Portable Interceptor Current (PICurrent)

The PortableInterceptor::Current object (hereafter referred to as PICurrent) is a Current object that is used specifically by portable Interceptors to transfer thread context information to a request context. Portable Interceptors are not required to use PICurrent, but if information from a client's thread context is required at an Interceptor's interception points, then PICurrent can be used to propagate that information. PICurrent allows portable service code to be written regardless of an ORB's threading model.

Note: PICurrent is typically NOT used directly by CORBA client or server code. Instead, it is generally used by interceptor-based service implementations as demonstrated in the AService example interceptor which follows.

Obtaining PICurrent

Before an invocation is made, PICurrent is obtained via a call to ORB::resolve_initial_references ( PICurrent ). From within the interception points, the data on PICurrent that has moved from the thread scope to the request scope is available via the get_slot operation on the RequestInfo object. A PICurrent can still be obtained via resolve_initial_references, but that is the Interceptor's thread scope PICurrent.

Request Scope vs Thread Scope

The thread scope PICurrent (TSC) is the PICurrent that exists within a thread's context. A request scope PICurrent (RSC) is the PICurrent associated with the request. On the client-side, the thread scope PICurrent is logically copied to the request scope PICurrent from the thread s context when a request begins and is attached to the ClientRequestInfo object. On the server-side, the request scope PICurrent is attached to the ServerRequestInfo and follows the request processing. It is logically copied to the thread scope PICurrent after the list of receive_request_service_contexts interception points are processed. See the Updated Interceptors specification, Section, 21.4.4.5, Flow of PICurrent between Scopes for a detailed discussion of the scope of PICurrent.

Portable Interceptor Example

This section contains an example logging service application. The sample code for this application is quite complicated because it covers even subtle "corner cases". The following scenarios are covered in this sample application:

  1. A logging service which logs invocations. Neither client nor server explicitly use the logging service.
  2. An "empty" service which passes information from the client to the server. The client and server explicitly use this service but are not aware that it is implemented using interceptors.

Note: These examples explicitly register ORBInitializers to make the code easier to experiment with and setup. Typically this would not be done. Instead, this information would be passed as -D properties to the Java virtual machine when the applications are started. That way the applications are not coupled to the fact that either the service exists (e.g., the logging service) or that a service that they explicitly use (e.g., the AService interface) is implemented as an interceptor.

The purpose of the logging service example is to show how to avoid infinite recursion when making outcalls (i.e., invocations on CORBA references) from within interception points. This turns out to be quite involved when all corner cases are covered.

The purpose of the "empty" service example is to show how to implement services which flow context information from client to server and back.

Flowing Context Information between Clients and Servers

A typical interceptor-based service will flow context information between clients and servers. The AService example shows how this information is flowed from the client thread into the client interceptors, across the wire into the server interceptors, to the servant thread and back.

It is important to note that neither the client nor the servant is aware that the service is implemented using interceptors. Instead, they interact with the service through local object references (the aService reference in this example).

AService diagram

AService diagram

Description of the steps of the AService diagram:

  1. The client invokes aService.begin().

    1.a. aService.begin() sets the service context information in a slot it has reserved in PICurrent.

  2. The client invokes a method on some reference (i.e., ref.method()). This invocation is taking place inside the context of the service since aService.begin() has been invoked.
  3. send_request is entered for the ref.method call.
  4. get_effective_component(s) may be called to determine if the reference being invoked needs to interact with the service.
  5. get_slot is called to retrieve the context set in step 1a. Slots set in PICurrent are logically copied and made available to ClientRequestInfo.
  6. The service interceptor adds a service context containing the appropriate context (most likely depending on the context set in step 1a and any components retrieved in step 4). It uses add_request_service_context to add this context information to the request which is sent over the wire.
  7. The ref.method request arrives at the server, activating the receive_request_service_contexts interception point.
  8. get_request_service_context is used to retrieve the service context added at step 6.
  9. ServerRequestInfo.set_slot is used to transfer the context information from the service context retrieved in step 8 to the logical thread local data.
  10. receive_request is entered.
  11. The "ref" Servant's "method" is entered.
  12. The servant method invokes aService.verify() to interact with the service.
  13. The service uses get_slot on PICurrent to retrieve the context information sent from the client side. The service may also use set_slot on PICurrent to set any return context information.
  14. After the Servant completes, the send_* interception point is entered. If the service set any return context information, it would add a service context to the return. This is not shown in this example.
  15. When the reply arrives at the client, the receive_* interception point is entered. If the service set any return context information, it would be retrieved at this point. This is not shown in this example.

Avoiding Infinite Recursion During Interceptor Outcalls

Some services may need to make invocations on other CORBA object references from within interception points. When making outcalls from within interception points, steps must be taken to avoid infinite recursion since those outcalls will flow through the interception points. The LoggingService example illustrates this case.

The LoggingService example is comprised of ClientRequestInterceptors registered in a client program, and ServerRequestInterceptors registered in a server program. These interceptors send information from the client and server to a LoggingService implemenation which logs this information.

However, since the LoggingService implementation is itself a CORBA server, we must ensure that we do not log calls to the logger. The following diagrams illustrate the steps taken to avoid infinite recursion.

The following diagram shows the simplest case of avoiding recursion when calling an external logger from within interceptors. These steps are useful for the case where the client ORB only contains ClientRequestInterceptors, the server ORB only contains ServerRequestInterceptors, and the LoggingService is external to both the client and server ORBs.

LoggingService diagram

Logging Service diagram

Description of the steps of the LoggingService diagram:

  1. The client invokes a method on some reference.
  2. The client interceptor's send_request method is entered for the method invoked in step 1.
  3. A slot reserved for indicating an outcall is set to true on PICurrent.
  4. The same slot is checked on ClientRequestInfo via get_slot. This value will not be set since it represents the client's thread state at step 1. Therefore a call to the logger will be made.
  5. send_request is recursively entered for the logger invocation made in step 4.
  6. A slot reserved for indicating an outcall is set to true on PICurrent. Note, this slot is always unconditionally set. This is necessary when there are 2 or more interceptors doing outcalls. Since interceptors do not know about the existence of other interceptors we always set the PICurrent slot.
  7. The slot is checked on ClientRequestInfo via get_slot. This time the value is set (from step 3). Therefore we do not log this call (which is the call to the logger itself). The send_request point that entered at step 5 finishes.
  8. The ORB sends the log invocation made at step 4 to the logging service.
  9. The send_request point for step 2 finishes. The ORB sends the initial client invocation made in step 1 to the server for the appropriate reference.
  10. The server's receive_request_service_contexts point is entered. It logs the incoming request. A server which does not contain client interceptors which make outcalls and which does not contain the implementation of the logger itself does not need to set recursion avoidance slots. That is what this diagram represents.
  11. - 13. Therefore all the server side interception points are entered with no further checking and the response from the method initially invoked by the client is returned to the client ORB.
  14. The client's receive_* point is entered. Steps similar to steps 2 through 9 will occur if this point needs to make an outcall.

Avoiding Recursion for Colocated Outcall References

The following diagram illustrates the case where the LoggingService may be colocated in the same ORB as the reference being invoked by the client. In general, it is not possible to know that a particular object reference is NOT colocated with any other objects hosted by that ORB. Therefore, to cover all corner cases, more steps must be taken.

This diagram shows only the server side. The client side steps are identical to those in the preceding diagram.

LoggingServiceColocated diagram

LoggingServiceColocated diagram

Description of the steps of the LoggingServiceColocated diagram:

  1. The request from the client ORB arrives, activating the receive_request_service_contexts interception point.
  2. A slot reserved for indicating an outcall is set to true on PICurrent.
  3. ServerRequestInfo.get_request_service_context is used to check for the presence of a service context indicating an outcall. The service context is not present so the logger is invoked from within the interception point.
  4. The send_request interception point is entered for the logger request.
  5. get_slot checks for the outcall indicator.
  6. The outcall indicator slot has been set (from step 2), therefore add_request_service_context is used to a service context indicating an outcall. This is necessary since there is no logical relationship between client and server threads.
  7. The logger invocation arrives at receive_request_service_contexts.
  8. A slot reserved for indicating an outcall is set to true on PICurrent.
  9. ServerRequestInfo.get_request_service_context is used to check for the presence of a service context indicating an outcall. The service context is present so no further action is taken. receive_request_service_contexts exits.
  10. The logger request proceeds to receive_request. Steps similar to those taken inside receive_request_service_context are necessary if the logger is called at the receive_request point (this is not shown in the diagram (although the example code logs all points)).
  11. The logger request arrives at the LoggingService Servant, which logs the initial client request (not invocation of the logger).
  12. The logger request proceeds to ServerRequestInterceptor.send_* (most likely send_reply).
  13. The logger request proceeds to ClientRequestInterceptor.receive_* (most likely receive_reply).

    After Step 13, the original request that left off at Step 3 would be serviced.

The main point illustrated in this example is the necessity of using both client and server interceptors in conjunction with PICurrent slots and service contexts to indicate an outcall.

Avoid recursion by using multiple ORBs

A simpler way to avoid recursion is to ensure that the outcall references are associated with a different ORB that does not have the logging interceptors registered. That way the outcall invocations never go through interceptors.

This seems like a simple solution, but, in general, interceptors are registered via properties passed to the VM during startup. This means that all ORBs created in that VM will contain all interceptors so this solution will not work.

This solution will only work where interceptors are explicitly registered in client code during ORB.init. However, that is neither a typical nor a recommended way to register interceptor-based services.

Example Code

The following files contain the code which the above diagrams illustrate. Instructions for compiling and executing these examples follow the code. The files included in this example are:

  • serviceexample.idl
  • LoggingServiceClientORBInitializer.java
  • LoggingServiceClientInterceptor.java
  • LoggingServiceServerORBInitializer.java
  • LoggingServiceServerInterceptor.java
  • LoggingServiceImpl.java
  • AServiceORBInitializer.java
  • AServiceImpl.java
  • AServiceInterceptor.java
  • AServiceIORInterceptor.java
  • ArbitaryObjectImpl.java
  • Client.java
  • ColocatedServers.java

serviceexample.idl

This is the Interface Definition Language (IDL) file that contains definitions of an arbitrary object on which to make invocations and two services which will service calls to the arbitrary object.

// serviceexample.idl
// Copyright and License

module pi
{
module serviceexample
{

    // Create some arbitrary object to call.  Those calls
    // will be serviced by the service implemented using interceptors.

    exception ArbitraryObjectException { string reason; };

    interface ArbitraryObject
    {
             string         arbitraryOperation1 ( in string a1 );

        oneway void         arbitraryOperation2 ( in long a1 );

               void         arbitraryOperation3 ( in string a1 )
                                raises (ArbitraryObjectException);
    };

    // This would typically be in a file separate from the "ArbitraryObject"
    // and probably unknown to it.

    interface LoggingService
    {
        void log ( in string a1 );
    };

    // This would also typically be in a file of its own.
    // IMPORTANT: the interface should be a local object to avoid
    // unnecessary overhead.

    /*local*/ interface AService
    {
        void begin();
        void end();
        void verify();
    };

    // Tagged component for adding to an IOR to indicate that
    // the AService must be in effect when invocations are made
    // on the object containing this tagged component.

    // Note: we explicitly declare the tag type rather than using
    // the IOP typedef (commented out) to simplify compiling this
    // example (i.e., to avoid includes and make include path directives).
    //const IOP::ComponentId TAG_ASERVICE_COMPONENT = 2345;
    const unsigned long TAG_ASERVICE_COMPONENT = 2345;

    struct ASERVICE_COMPONENT {
        boolean requiresAService;
    };

}; // module serviceexample

}; // module pi

LoggingServiceClientORBInitializer.java

This file creates and registers the logging service interceptor used by object clients.

// LoggingServiceClientORBInitializer.java
// Copyright and License

package pi.serviceexample;

import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.PortableInterceptor.Current;
import org.omg.PortableInterceptor.CurrentHelper;
import org.omg.PortableInterceptor.ORBInitInfo;

public class LoggingServiceClientORBInitializer
    extends org.omg.CORBA.LocalObject
    implements org.omg.PortableInterceptor.ORBInitializer
{
    public void pre_init(ORBInitInfo info)
    {
    }

    public void post_init(ORBInitInfo info)
    {
        try {

            // Get a reference to the LoggingService object.

            NamingContext nameService =
                NamingContextHelper.narrow(
                    info.resolve_initial_references("NameService"));

            NameComponent path[] =
                { new NameComponent("LoggingService", "") };
            LoggingService loggingService =
                LoggingServiceHelper.narrow(nameService.resolve(path));

            // Get a reference to TSC PICurrent.

            Current piCurrent =
                CurrentHelper.narrow(
                    info.resolve_initial_references("PICurrent"));

            // Allocate a slot id to use for the interceptor to indicate
            // that it is making an outcall.  This is used to avoid
            // infinite recursion.

            int outCallIndicatorSlotId = info.allocate_slot_id();

            // Create (with the above data) and register the client
            // side interceptor.

            LoggingServiceClientInterceptor interceptor =
                new LoggingServiceClientInterceptor(loggingService,
                                                    piCurrent,
                                                    outCallIndicatorSlotId);

            info.add_client_request_interceptor(interceptor);
        } catch (Throwable t) {
            System.out.println("Exception handling not shown.");
        }
    }
}

LoggingServiceClientInterceptor.java

This interceptor logs client side interception points. It illustrates how to make invocations on other objects from within an interceptor and how to avoid infinite recursion during those "outcall" invocations.

// LoggingServiceClientInterceptor.java
// Copyright and License

package pi.serviceexample;

import org.omg.CORBA.Any;
import org.omg.CORBA.ORB;
import org.omg.CORBA.TCKind;
import org.omg.IOP.ServiceContext;
import org.omg.PortableInterceptor.ClientRequestInterceptor;
import org.omg.PortableInterceptor.ClientRequestInfo;
import org.omg.PortableInterceptor.Current;
import org.omg.PortableInterceptor.InvalidSlot;

public class LoggingServiceClientInterceptor
    extends org.omg.CORBA.LocalObject
    implements ClientRequestInterceptor
{
    private LoggingService loggingService;
    private Current piCurrent;
    private int outCallIndicatorSlotId;

    public LoggingServiceClientInterceptor(LoggingService loggingService,
                                           Current piCurrent,
                                           int outCallIndicatorSlotId)
    {
        this.loggingService = loggingService;
        this.piCurrent = piCurrent;
        this.outCallIndicatorSlotId = outCallIndicatorSlotId;
    }

    //
    // Interceptor operations
    //

    public String name()
    {
        return "LoggingServiceClientInterceptor";
    }

    public void destroy()
    {
    }

    //
    // ClientRequestInterceptor operations
    //

    public void send_request(ClientRequestInfo ri)
    {
        log(ri, "send_request");
    }

    public void send_poll(ClientRequestInfo ri)
    {
        log(ri, "send_poll");
    }

    public void receive_reply(ClientRequestInfo ri)
    {
        log(ri, "receive_reply");
    }

    public void receive_exception(ClientRequestInfo ri)
    {
        log(ri, "receive_exception");
    }

    public void receive_other(ClientRequestInfo ri)
    {
        log(ri, "receive_other");
    }

    //
    // Utilities.
    //

    public void log(ClientRequestInfo ri, String point)
    {
        // IMPORTANT: Always set the TSC out call indicator in case
        // other interceptors make outcalls for this request.
        // Otherwise the outcall will not be set for the other interceptor's
        // outcall resulting in infinite recursion.

        Any indicator = ORB.init().create_any();
        indicator.insert_boolean(true);
        try {
            piCurrent.set_slot(outCallIndicatorSlotId, indicator);
        } catch (InvalidSlot e) { }

        try {
            indicator = ri.get_slot(outCallIndicatorSlotId);

            // If the RSC out call slot is not set then log this invocation.
            // If it is set that indicates the interceptor is servicing the
            // invocation of loggingService itself.  In that case do
            // nothing (to avoid infinite recursion).

            if (indicator.type().kind().equals(TCKind.tk_null)) {
                loggingService.log(ri.operation() + " " + point);
            }
        } catch (InvalidSlot e) {
            System.out.println("Exception handling not shown.");
        }
    }
}

LoggingServiceServerORBInitializer.java

This file creates and registers the logging service interceptor used by object servers. Even though this interceptor is meant to only log server-side interception points, it is both a client and server interceptor. The code illustrates how to avoid infinite recursion in the case where the object being called is colocated in the same ORB in which the interceptors are registered.

// LoggingServiceServerORBInitializer.java
// Copyright and License

package pi.serviceexample;

import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.PortableInterceptor.Current;
import org.omg.PortableInterceptor.CurrentHelper;
import org.omg.PortableInterceptor.ORBInitInfo;

public class LoggingServiceServerORBInitializer
    extends org.omg.CORBA.LocalObject
    implements org.omg.PortableInterceptor.ORBInitializer
{
    public void pre_init(ORBInitInfo info)
    {
    }

    public void post_init(ORBInitInfo info)
    {
        try {

            // Create and register the logging service interceptor.
            // Give that interceptor references to the NameService and
            // PICurrent to avoid further lookups (i.e., optimization).
            // More importantly, allocate and give the interceptor
            // a slot id which is will use to tell itself not to
            // log calls that the interceptor makes to the logging process.

            NamingContext nameService =
                NamingContextHelper.narrow(
                    info.resolve_initial_references("NameService"));

            Current piCurrent =
                CurrentHelper.narrow(
                    info.resolve_initial_references("PICurrent"));

            int outCallIndicatorSlotId = info.allocate_slot_id();

            LoggingServiceServerInterceptor interceptor =
                new LoggingServiceServerInterceptor(nameService,
                                                    piCurrent,
                                                    outCallIndicatorSlotId);

            info.add_client_request_interceptor(interceptor);
            info.add_server_request_interceptor(interceptor);
        } catch (Throwable t) {
            System.out.println("Exception handling not shown.");
        }
    }
}

LoggingServiceServerInterceptor.java

This interceptor logs server side interception points, and is implemented as both a ClientRequestInterceptor and a ServerRequestInterceptor to illustrate the need to set some "out call" service context data (in addition to setting an out call slot) to avoid infinite recursion for the case noted in the description of LoggingServiceServerORBInitializer.java.

// LoggingServiceServerInterceptor.java
// Copyright and License

package pi.serviceexample;

import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.Any;
import org.omg.CORBA.BAD_PARAM;
import org.omg.CORBA.ORB;
import org.omg.CORBA.TCKind;
import org.omg.IOP.ServiceContext;
import org.omg.PortableInterceptor.ClientRequestInterceptor;
import org.omg.PortableInterceptor.ClientRequestInfo;
import org.omg.PortableInterceptor.Current;
import org.omg.PortableInterceptor.InvalidSlot;
import org.omg.PortableInterceptor.ServerRequestInterceptor;
import org.omg.PortableInterceptor.ServerRequestInfo;

public class LoggingServiceServerInterceptor
    extends org.omg.CORBA.LocalObject
    implements ClientRequestInterceptor,
               ServerRequestInterceptor
{
    private NamingContext nameService;
    private LoggingService loggingService;
    private Current piCurrent;
    private int outCallIndicatorSlotId;
    private static final int serviceContextId = 100001;
    private static final byte[] serviceContextData = {1};

    // Returns a reference to the logging process.

    private LoggingService loggingService()
    {
        if (loggingService == null) {
            NameComponent path[] =
                { new NameComponent("LoggingService", "") };
            try {
                loggingService =
                    LoggingServiceHelper.narrow(nameService.resolve(path));
            } catch (Throwable t) {
                System.out.println("Exception handling not shown.");
            }
        }
        return loggingService;
    }

    public LoggingServiceServerInterceptor(NamingContext nameService,
                                           Current piCurrent,
                                           int outCallIndicatorSlotId)
    {
        this.nameService = nameService;
        this.piCurrent = piCurrent;
        this.outCallIndicatorSlotId = outCallIndicatorSlotId;
    }

    //
    // Interceptor operations
    //

    public String name()
    {
        return "LoggingServiceServerInterceptor";
    }

    public void destroy()
    {
    }

    //
    // ClientRequestInterceptor operations
    //

    public void send_request(ClientRequestInfo ri)
    {

        // If the server interceptor sets the recursion slot then
        // put in the service context so the server doesn't make
        // the call again in the case where the server side interceptor
        // is colocated in the same ORB as the object being invoked.

        try {
            Any indicator = ri.get_slot(outCallIndicatorSlotId);
            if (indicator.type().kind().equals(TCKind.tk_boolean)) {
                ServiceContext serviceContext =
                    new ServiceContext(serviceContextId, serviceContextData);
                ri.add_request_service_context(serviceContext, false);
            }
        } catch (InvalidSlot e) {
            System.out.println("Exception handling not shown.");
        }
    }

    public void send_poll(ClientRequestInfo ri)
    {
    }

    public void receive_reply(ClientRequestInfo ri)
    {
    }

    public void receive_exception(ClientRequestInfo ri)
    {
    }

    public void receive_other(ClientRequestInfo ri)
    {
    }

    //
    // ServerRequestInterceptor operations
    //

    public void receive_request_service_contexts(ServerRequestInfo ri)
    {
        log(ri, "receive_request_service_contexts");
    }

    public void receive_request(ServerRequestInfo ri)
    {
        log(ri, "receive_request");
    }

    public void send_reply(ServerRequestInfo ri)
    {
        log(ri, "send_reply");
    }

    public void send_exception(ServerRequestInfo ri)
    {
        log(ri, "send_exception");
    }

    public void send_other(ServerRequestInfo ri)
    {
        log(ri, "send_other");
    }

    //
    // Utilities.
    //

    public void log(ServerRequestInfo ri, String point)
    {
        // This is only relevant for the colocated example.
        // Do not attempt to log until the logging service object
        // has been bound in naming.  Otherwise the attempt to call
        // rebind on naming will call log which will fail.
        if (! ColocatedServers.colocatedBootstrapDone) {
            return;
        }

        // IMPORTANT:
        // The conditional logging of the invocation is only necessary
        // if there is a chance that the object being invoked is colocated
        // in the same ORB as this interceptor.  Otherwise the outcall to
        // the logging service can be made unconditionally.

        // Always set the recursion slot.

        Any indicator = ORB.init().create_any();
        indicator.insert_boolean(true);
        try {
            piCurrent.set_slot(outCallIndicatorSlotId, indicator);
        } catch (InvalidSlot e) {
            System.out.println("Exception handling not shown.");
        }

        // Make the out call if you have not already done so.

        try {

            // Only the presence of the service context counts.
            // The data is ignored.

            ri.get_request_service_context(serviceContextId);
        } catch (BAD_PARAM e) {
            // Recursion indicator not set so make the call.
            loggingService().log(ri.operation() + " " + point);
        }
    }
}

LoggingServiceImpl.java

This file is the implementation of the logging object to which the logging service interceptors send their data.

//
// Copyright and License

package pi.serviceexample;

import org.omg.CORBA.ORB;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.PortableServer.POAHelper;

import java.util.Properties;

class LoggingServiceImpl
    extends LoggingServicePOA
{
    public static ORB orb;

    //
    // The IDL operations.
    //

    public void log(String a1)
    {
        System.out.println(a1);
    }

    //
    // The server.
    //

    public static void main(String[] av)
    {
        try {
            if (orb == null) {
                orb = ORB.init(av, null);
            }

            POA rootPOA =  POAHelper.narrow( orb.resolve_initial_references("RootPOA"));
            rootPOA.the_POAManager().activate();

            byte[] objectId =
                rootPOA.activate_object(new LoggingServiceImpl());
            org.omg.CORBA.Object ref = rootPOA.id_to_reference(objectId);

            NamingContext nameService =
                NamingContextHelper.narrow(
                    orb.resolve_initial_references("NameService"));
            NameComponent path[] =
                { new NameComponent("LoggingService", "") };
            nameService.rebind(path, ref);

            // Only relevant for colocated example.
            ColocatedServers.colocatedBootstrapDone = true;

            System.out.println("LoggingService ready.");

            orb.run();

        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
        System.exit(0);
    }
}

AServiceORBInitializer.java

The file creates and registers the AServiceInterceptor as both a client and server interceptor, creates and registers the AServiceIORInterceptor which puts a TaggedComponent into IORs, and creates a local object to be used by applications to explicitly control the services offered by AService. This local object is registered as an initial service with the ORB such that it can be obtained by clients using org.omg.CORBA.ORB.resolve_initial_references.

// AServiceORBInitializer.java
// Copyright and License

package pi.serviceexample;

import org.omg.IOP.Codec;
import org.omg.IOP.CodecFactory;
import org.omg.IOP.CodecFactoryHelper;
import org.omg.IOP.Encoding;
import org.omg.PortableInterceptor.Current;
import org.omg.PortableInterceptor.CurrentHelper;
import org.omg.PortableInterceptor.ORBInitInfo;

public class AServiceORBInitializer
    extends org.omg.CORBA.LocalObject
    implements org.omg.PortableInterceptor.ORBInitializer
{
    private AServiceImpl aServiceImpl;
    private AServiceInterceptor aServiceInterceptor;

    public void pre_init(ORBInitInfo info)
    {
        try {
            int id = info.allocate_slot_id();

            aServiceInterceptor = new AServiceInterceptor(id);

            info.add_client_request_interceptor(aServiceInterceptor);
            info.add_server_request_interceptor(aServiceInterceptor);

            // Create and register a reference to the service to be
            // used by client code.

            aServiceImpl = new AServiceImpl(id);

            info.register_initial_reference("AService", aServiceImpl);

        } catch (Throwable t) {
            System.out.println("Exception handling not shown.");
        }
    }

    public void post_init(ORBInitInfo info)
    {
        try {

            Current piCurrent =
                CurrentHelper.narrow(
                    info.resolve_initial_references("PICurrent"));
            aServiceImpl.setPICurrent(piCurrent);

            CodecFactory codecFactory =
                CodecFactoryHelper.narrow(
                    info.resolve_initial_references("CodecFactory"));
            Encoding encoding = new Encoding((short)0, (byte)1, (byte)2);
            Codec codec = codecFactory.create_codec(encoding);
            aServiceInterceptor.setCodec(codec);

            AServiceIORInterceptor aServiceIORInterceptor =
                new AServiceIORInterceptor(codec);
            info.add_ior_interceptor(aServiceIORInterceptor);

        } catch (Throwable t) {
            System.out.println("Exception handling not shown.");
        }
    }

}

AServiceImpl.java

This file contains an object that is explicitly used by client and servant code to communicate with the service. When the client calls begin() on the service, the service causes a ServiceID specific to the service to be put in the TSC PICurrent slot reserved by this service. When the client calls end() on the service, it sets the TSC slot to a non-valid value to indicate that the service is not in effect. Servants use the verify() method to determine whether the ServiceID was passed from the client side to the server side.

//
// Copyright and License

package pi.serviceexample;

import org.omg.CORBA.Any;
import org.omg.CORBA.TCKind;
import org.omg.CORBA.LocalObject;
import org.omg.CORBA.ORB;
import org.omg.PortableInterceptor.Current;
import org.omg.PortableInterceptor.InvalidSlot;

class AServiceImpl
    extends LocalObject
    implements AService
{
    private int slotId;

    private int currentServiceId = 0;

    private Current piCurrent;

    private Any NOT_IN_EFFECT;

    public AServiceImpl(int slotId)
    {
        this.slotId = slotId;
        NOT_IN_EFFECT = ORB.init().create_any();
    }

    // Package protected so the AService ORBInitializer can access this
    // non-IDL defined method.
    void setPICurrent(Current piCurrent)
    {
        this.piCurrent = piCurrent;
    }

    public void begin()
    {
        Any any = ORB.init().create_any();
        any.insert_long(++currentServiceId);
        setSlot(any);
    }

    public void end()
    {
        setSlot(NOT_IN_EFFECT);
    }

    public void verify()
    {
        try {
            Any any = piCurrent.get_slot(slotId);
            if (any.type().kind().equals(TCKind.tk_long)) {
                System.out.println("Service present: " + any.extract_long());
            } else {
                System.out.println("Service not present");
            }
        } catch (InvalidSlot e) {
            System.out.println("Exception handling not shown.");
        }
    }

    // Synchronized because two threads in the same ORB could be
    // sharing this object.
    synchronized private void setSlot(Any any)
    {
        try {
            piCurrent.set_slot(slotId, any);
        } catch (InvalidSlot e) {
            System.out.println("Exception handling not shown.");
        }
    }
}

AServiceInterceptor.java

This interceptor is responsible for arranging to pass the client side AService information to the service side.

On the client side, if AService.begin() has been called, the send_request(ri) point will see the service id in the RSC slot. In this case, it inserts the value of that service id into an org.omg.CORBA.ServiceContext and adds that service context to the data to be passed along with the invocation.

On the server side, receive_request_service_context(ri) looks for the presence of that service context. When present, it extracts the service id value from the ServiceContext and sets the RSC slot to that value. When the servant is executing, the value of that RSC slot is available in the TSC slot.

// AServiceInterceptor.java
// Copyright and License

package pi.serviceexample;

import org.omg.CORBA.Any;
import org.omg.CORBA.BAD_PARAM;
import org.omg.CORBA.ORB;
import org.omg.CORBA.TCKind;
import org.omg.IOP.Codec;
import org.omg.IOP.CodecPackage.FormatMismatch;
import org.omg.IOP.CodecPackage.TypeMismatch;
import org.omg.IOP.ServiceContext;
import org.omg.IOP.TaggedComponent;
import org.omg.PortableInterceptor.ClientRequestInterceptor;
import org.omg.PortableInterceptor.ClientRequestInfo;
import org.omg.PortableInterceptor.InvalidSlot;
import org.omg.PortableInterceptor.ServerRequestInterceptor;
import org.omg.PortableInterceptor.ServerRequestInfo;

public class AServiceInterceptor
    extends org.omg.CORBA.LocalObject
    implements ClientRequestInterceptor, ServerRequestInterceptor
{
    private int slotId;
    private Codec codec;

    private static final int serviceContextId = 1234;

    public AServiceInterceptor(int slotId)
    {
        this.slotId = slotId;
    }

    void setCodec(Codec codec)
    {
        this.codec = codec;
    }

    //
    // Interceptor operations
    //

    public String name()
    {
        return "AServiceInterceptor";
    }

    public void destroy()
    {
    }

    //
    // ClientRequestInterceptor operations
    //

    public void send_request(ClientRequestInfo ri)
    {
        //
        // See if the target object contains an ASERVICE_COMPONENT.
        //

        try {
            TaggedComponent taggedComponent =
                ri.get_effective_component(TAG_ASERVICE_COMPONENT.value);

            Any sAny = null;
            try {
                sAny = codec.decode_value(taggedComponent.component_data,
                                          ASERVICE_COMPONENTHelper.type());
            } catch (TypeMismatch e) {
                System.out.println("Exception handling not shown.");
            } catch (FormatMismatch e) {
                System.out.println("Exception handling not shown.");
            }

            ASERVICE_COMPONENT aServiceComponent =
                ASERVICE_COMPONENTHelper.extract(sAny);

            //
            // Only send the service context if the target object requires it.
            //

            if (aServiceComponent.requiresAService) {
                try {
                    Any any = ri.get_slot(slotId);
                    if (any.type().kind().equals(TCKind.tk_long)) {
                        int serviceId = any.extract_long();
                        byte[] serviceContextData = {
                            // Little endian to make it
                            // easier to see in debugger.
                            (byte)((serviceId >>>  0) &  0xFF),
                            (byte)((serviceId >>>  8) &  0xFF),
                            (byte)((serviceId >>> 16) &  0xFF),
                            (byte)((serviceId >>> 24) &  0xFF)
                        };
                        ri.add_request_service_context(
                            new ServiceContext(serviceContextId,
                                               serviceContextData),
                            false);
                    }
                } catch (InvalidSlot e) {
                    System.out.println("Exception handling not shown.");
                }
            }
        } catch (BAD_PARAM e) {
            // If it is not present, do nothing.
            ;
        }
    }

    public void send_poll(ClientRequestInfo ri)
    {
    }

    public void receive_reply(ClientRequestInfo ri)
    {
    }

    public void receive_exception(ClientRequestInfo ri)
    {
    }

    public void receive_other(ClientRequestInfo ri)
    {
    }

    //
    // ServerRequestInterceptor operations
    //

    public void receive_request_service_contexts(ServerRequestInfo ri)
    {
        try {
            ServiceContext serviceContext =
                ri.get_request_service_context(serviceContextId);
            byte[] data = serviceContext.context_data;
            int b1, b2, b3, b4;
            b4 = (data[0] <<  0) & 0x000000FF;
            b3 = (data[1] <<  8) & 0x0000FF00;
            b2 = (data[2] << 16) & 0x00FF0000;
            b1 = (data[3] << 24) & 0xFF000000;
            int serviceId = (b1 | b2 | b3 | b4);
            Any any = ORB.init().create_any();
            any.insert_long(serviceId);
            ri.set_slot(slotId, any);
        } catch (BAD_PARAM e) {
            // Not present means service is not in effect.
            // Do nothing.
            ;
        } catch (InvalidSlot e) {
            System.out.println("Exception handling not shown.");
        }
    }

    public void receive_request(ServerRequestInfo ri)
    {
    }

    public void send_reply(ServerRequestInfo ri)
    {
    }

    public void send_exception(ServerRequestInfo ri)
    {
    }

    public void send_other(ServerRequestInfo ri)
    {
    }
}

AServiceIORInterceptor.java

This file adds a TaggedComponent to IORs.

// AServiceIORInterceptor.java
// Copyright and License

package pi.serviceexample;

import org.omg.CORBA.Any;
import org.omg.CORBA.LocalObject;
import org.omg.CORBA.ORB;
import org.omg.IOP.TaggedComponent;
import org.omg.IOP.Codec;
import org.omg.IOP.CodecPackage.InvalidTypeForEncoding;
import org.omg.PortableInterceptor.IORInfo;
import org.omg.PortableInterceptor.IORInterceptor;

public class AServiceIORInterceptor
    extends org.omg.CORBA.LocalObject
    implements IORInterceptor
{
    private Codec codec;

    public AServiceIORInterceptor(Codec codec)
    {
        this.codec = codec;
    }

    //
    // Interceptor operations
    //

    public String name()
    {
        return "AServiceInterceptor";
    }

    public void destroy()
    {
    }

    //
    // IOR Interceptor operations
    //

    public void establish_components(IORInfo info)
    {
        //
        // Note: typically, rather than just inserting a tagged component
        // this interceptor would check info.get_effective_policy(int)
        // to determine if a tagged component reflecting that policy
        // should be added to the IOR.  That is not shown in this example.
        //

        ASERVICE_COMPONENT aServiceComponent = new ASERVICE_COMPONENT(true);
        Any any = ORB.init().create_any();
        ASERVICE_COMPONENTHelper.insert(any, aServiceComponent);
        byte[] value = null;
        try {
            value = codec.encode_value(any);
        } catch (InvalidTypeForEncoding e) {
            System.out.println("Exception handling not shown.");
        }
        TaggedComponent taggedComponent =
            new TaggedComponent(TAG_ASERVICE_COMPONENT.value, value);
        info.add_ior_component(taggedComponent);
    }

}

ArbitaryObjectImpl.java

This file is an implementation and server for the ArbitraryObject IDL interface. The implementations of the IDL interface operations explicitly call the AServiceImpl.verify() method to illustrate the end-to-end passing of data from the client (via AService.begin()) to the servant.

// ArbitaryObjectImpl.java
// Copyright and License

package pi.serviceexample;

import org.omg.CORBA.ORB;
import org.omg.CORBA.ORBPackage.InvalidName;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.PortableServer.POAHelper;

import java.util.Properties;

class ArbitraryObjectImpl
    extends ArbitraryObjectPOA
{
    public static ORB orb;

    private AService aService;

    //
    // The IDL operations.
    //

    public String arbitraryOperation1(String a1)
    {
        verifyService();
        return "I got this from the client: " + a1;
    }

    public void arbitraryOperation2 (int a1)
    {
        verifyService();
    }

    public void arbitraryOperation3(String a1)
        throws ArbitraryObjectException
    {
        verifyService();
        if (a1.equals("throw exception")) {
            throw new ArbitraryObjectException("because you told me to");
        }
    }

    private void verifyService()
    {
        getAService().verify();
    }

    private AService getAService()
    {
        // Only look up the service once, then cache it.

        if (aService == null) {
            try {
                aService =
                    AServiceHelper.narrow(
                        orb.resolve_initial_references("AService"));
            } catch (InvalidName e) {
                System.out.println("Exception handling not shown.");
            }
        }
        return aService;
    }

    //
    // The server.
    //

    public static void main(String[] av)
    {
        try {
            if (orb == null) {
                Properties props = new Properties();
                props.put("org.omg.PortableInterceptor.ORBInitializerClass."
                          + "pi.serviceexample.AServiceORBInitializer",
                          "");
                props.put("org.omg.PortableInterceptor.ORBInitializerClass."
                          + "pi.serviceexample.LoggingServiceServerORBInitializer",
                          "");
                orb = ORB.init(av, props);
            }

            POA rootPOA =  POAHelper.narrow( orb.resolve_initial_references("RootPOA"));
            // Create a POA so the IOR interceptor executes.
            POA childPOA = rootPOA.create_POA("childPOA", null, null);
            childPOA.the_POAManager().activate();

            byte[] objectId =
                childPOA.activate_object(new ArbitraryObjectImpl());
            org.omg.CORBA.Object ref = childPOA.id_to_reference(objectId);

            NamingContext nameService =
                NamingContextHelper.narrow(
                    orb.resolve_initial_references("NameService"));
            NameComponent path[] =
                { new NameComponent("ArbitraryObject", "") };
            nameService.rebind(path, ref);

            System.out.println("ArbitaryObject ready.");

            orb.run();

        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
        System.exit(0);
    }
}

Client.java

This is a client that calls methods on ArbitraryObject. It makes some of those calls within the context of AService and some outside of its context. It is unaware of the existence of the logging interceptor (except that it explicitly registers the LoggingServerClientORBInitializer as noted above).

// Client.java
// Copyright and License

package pi.serviceexample;

import org.omg.CORBA.ORB;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;

import java.util.Properties;

public class Client
{
    public static void main(String av[])
    {
        try {
            Properties props = new Properties();
            props.put("org.omg.PortableInterceptor.ORBInitializerClass."
                      + "pi.serviceexample.AServiceORBInitializer",
                      "");
            props.put("org.omg.PortableInterceptor.ORBInitializerClass."
                      + "pi.serviceexample.LoggingServiceClientORBInitializer",
                      "");
            ORB orb = ORB.init(av, props);

            //
            // The client obtains a reference to a service.
            // The client does not know the service is implemented
            // using interceptors.
            //

            AService aService =
                AServiceHelper.narrow(
                    orb.resolve_initial_references("AService"));

            //
            // The client obtains a reference to some object that
            // it will invoke.
            //

            NamingContext nameService =
                NamingContextHelper.narrow(
                    orb.resolve_initial_references("NameService"));
            NameComponent arbitraryObjectPath[] =
                { new NameComponent("ArbitraryObject", "") };
            ArbitraryObject arbitraryObject =
                ArbitraryObjectHelper.narrow(nameService.resolve(arbitraryObjectPath));

            //
            // The client begins the service so that invocations of
            // any object will be done with that service in effect.
            //

            aService.begin();

            arbitraryObject.arbitraryOperation1("one");
            arbitraryObject.arbitraryOperation2(2);

            //
            // The client ends the service so that further invocations
            // of any object will not be done with that service in effect.
            //

            aService.end();

            // This invocation is not serviced by aService since
            // it is outside the begin/end.
            arbitraryObject.arbitraryOperation3("just return");

            aService.begin();
            try {
                arbitraryObject.arbitraryOperation3("throw exception");
                throw new RuntimeException("should not see this");
            } catch (ArbitraryObjectException e) {
                // Expected in this example, so do nothing.
            }
            aService.end();

        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
        System.out.println("Client done.");
        System.exit(0);
    }
}

ColocatedServers.java

This is a server which runs both ArbitraryObject and LoggingService in the same ORB. This means that these objects are colocated.

The server is created this way in order to exercise the code in LoggingServiceServerInterceptor that illustrates when interceptors make out calls to objects colocated in the same ORB extra steps must be taken to avoid infinite recursion.

// ColocatedServers.java
// Copyright and License

package pi.serviceexample;

import org.omg.CORBA.ORB;
import java.util.Properties;

public class ColocatedServers
{
    public static ORB orb;

    public static boolean colocatedBootstrapDone = false;

    public static void main (String[] av)
    {
        try {

            //
            // Share an ORB between objects servers.
            //

            Properties props = new Properties();
            props.put("org.omg.PortableInterceptor.ORBInitializerClass."
                      + "pi.serviceexample.AServiceORBInitializer",
                      "");
            props.put("org.omg.PortableInterceptor.ORBInitializerClass."
                      + "pi.serviceexample.LoggingServiceServerORBInitializer",
                      "");
            ORB orb = ORB.init(av, props);
            ArbitraryObjectImpl.orb = orb;
            LoggingServiceImpl.orb = orb;

            //
            // Start both object servers.
            //

            ServerThread ServerThread = new ServerThread(av);
            ServerThread.start();
            ArbitraryObjectImpl.main(av);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }
}

class ServerThread extends Thread
{
    String[] av;
    ServerThread (String[] av)
    {
        this.av = av;
    }
    public void run ()
    {
        LoggingServiceImpl.main(av);
    }
}

Compiling and running the application

The example code, which contains the logging example and the service example, may be compiled and run using a Makefile such as that shown below:

# Makefile for the Example Files
# Copyright and License

JAVA_HOME=/path_to_J2SE_installation

CLASSPATH=.

JAVAC=$(JAVA_HOME)/bin/javac
JAVA=$(JAVA_HOME)/bin/java

ORB_INITIAL_PORT=1050

IDLJ=$(JAVA_HOME)/bin/idlj
IDLJ_FLAGS=-fall -td $(CLASSPATH) -verbose

ORBD=${JAVA_HOME}/bin/orbd -ORBInitialPort ${ORB_INITIAL_PORT}

build:
        $(IDLJ) $(IDLJ_FLAGS) serviceexample.idl
        $(JAVAC) -d $(CLASSPATH) *.java
        $(JAVAC) pi/serviceexample/*.java

runorbd:
        $(ORBD)

runloggingservice:
        $(JAVA) -classpath $(CLASSPATH) pi.serviceexample.LoggingServiceImpl \
                -ORBInitialPort ${ORB_INITIAL_PORT}

runarbitraryobject:
        $(JAVA) -classpath $(CLASSPATH) pi.serviceexample.ArbitraryObjectImpl \
                -ORBInitialPort ${ORB_INITIAL_PORT}

runcolocatedservers:
        $(JAVA) -classpath $(CLASSPATH) pi.serviceexample.ColocatedServers \
                -ORBInitialPort ${ORB_INITIAL_PORT}

runclient:
        $(JAVA) -classpath $(CLASSPATH) pi.serviceexample.Client \
                -ORBInitialPort ${ORB_INITIAL_PORT}

clean:
        rm -rf pi
        rm -rf orb.db

# Order of steps:
# Build:     clean build
# Remote:    runorbd runloggingservice runarbitraryobjectimpl runclient
# Colocated: runorbd runcolocatedservers runclient

The following steps show how to build and run the example on the Solaris operating system using the above Makefile. From the command prompt, run these commands as shown. The % symbol is used as a reminder that these are commands that are to be run from the command prompt.

  1. % make clean
  2. % make build
  3. % make runorbd &
  4. % make runloggingservice &
  5. % make runarbitraryobject &
  6. % make runclient

    After this step, you will see output such as this:

    resolve send_request
resolve receive_reply
arbitraryOperation1 send_request
Service present: 1
arbitraryOperation1 receive_reply
arbitraryOperation2 send_request
Service present: 1
arbitraryOperation2 receive_other
arbitraryOperation3 send_request
Service not present
arbitraryOperation3 receive_reply
arbitraryOperation3 send_request
Service present: 2
arbitraryOperation3 receive_exception
Client done.
  7. % jobs

    After this step, you will see output such as this:

    [1]   Running                 make runorbd &
[2]-  Running                 make runloggingservice &
[3]+  Running                 make runarbitraryobject &
  8. % kill %2 %3
  9. % make runcolocatedservers &
  10. % make runclient

    After this step, you will see output such as this:

    log receive_request_service_contexts
log receive_request
resolve send_request
log send_reply
log receive_request_service_contexts
log receive_request
resolve receive_reply
log send_reply
log receive_request_service_contexts
log receive_request
arbitraryOperation1 send_request
log send_reply
arbitraryOperation1 receive_request_service_contexts
arbitraryOperation1 receive_request
Service present: 1
arbitraryOperation1 send_reply
log receive_request_service_contexts
log receive_request
arbitraryOperation1 receive_reply
log send_reply
log receive_request_service_contexts
log receive_request
arbitraryOperation2 send_request
log send_reply
arbitraryOperation2 receive_request_service_contexts
arbitraryOperation2 receive_request
log receive_request_service_contexts
Service present: 1
arbitraryOperation2 send_reply
log receive_request
arbitraryOperation2 receive_other
log send_reply
log receive_request_service_contexts
log receive_request
arbitraryOperation3 send_request
log send_reply
arbitraryOperation3 receive_request_service_contexts
arbitraryOperation3 receive_request
Service not present
arbitraryOperation3 send_reply
log receive_request_service_contexts
log receive_request
arbitraryOperation3 receive_reply
log send_reply
log receive_request_service_contexts
log receive_request
arbitraryOperation3 send_request
log send_reply
arbitraryOperation3 receive_request_service_contexts
arbitraryOperation3 receive_request
Service present: 2
arbitraryOperation3 send_exception
log receive_request_service_contexts
log receive_request
arbitraryOperation3 receive_exception
log send_reply
Client done.
  11. % jobs

    After this step, you will see output such as this:

    [1]-  Running                 make runorbd &
[4]+  Running                 make runcolocatedservers &
  12. % kill %1 %4
  13. % make clean
See Also:
ORBInitInfo
org.omg.PortableInterceptor package.
Portable Interceptors Specification at ptc/2001-08-31
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java™ Plug-in Configuration

Applet Developer's Guide > Java Plug-in Configuration

Contents

  • Switching To Classic (old) Java Plug-in
    • Windows
    • Solaris
  • Enabling Java Runtime Environments

Switching To Classic (old) Java Plug-in

The classic and next generation Java Plug-ins are shipped in Java SE 6 update 10 and later releases. This is to enable users to use the classic Java Plug-in if the applets exhibit different behavior in the next generation Java Plug-in. Follow the instructions for your operating system to switch Java Plug-ins.

Windows

On the Windows platform only, the Java Plug-in setting can be switched in the Java Control Panel. In the Advanced tab, under the Java Plug-in node, uncheck the "Enable the next generation Java Plug-in" checkbox to use the classic Java Plug-in. Click OK and restart the browser.

Enable Next Generation Plug-In in Java Control Panel

Linux, Solaris

On the Linux and Solaris platforms, you may have previously created a symlink to .../jre/lib/{i386,sparc}/libnpjp2.so into either your Firefox 3 firefox/plugins directory or your ~/.mozilla/plugins directory.

Replace the symlink to libnpjp2.so (next generation Java Plug-in) with a symlink to libjavaplugin_oji.so (classic Java Plug-in). This must currently be done manually.

Enabling Java Runtime Environments

You can change the JREs available to your Java Plug-in for applet execution, via the Java tab in the Java Control Panel. Click View to view and change Java Runtime Settings. Check the Enabled checkbox to make a JRE available to the Java Plug-in.

Enable JRE available to Java Plug

Click Find to find and add JREs that may just have been unzipped and not installed via an installer.

Click Add or Remove to explicitly add or remove JREs from the list.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL: Portable Object Adapter (POA)

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Portable Object Adapter (POA)

What is the Portable Object Adapter (POA)?

An object adapter is the mechanism that connects a request using an object reference with the proper code to service that request. The Portable Object Adapter, or POA, is a particular type of object adapter that is defined by the CORBA specification. The POA is designed to meet the following goals:

  • Allow programmers to construct object implementations that are portable between different ORB products.
  • Provide support for objects with persistent identities.
  • Provide support for transparent activation of objects.
  • Allow a single servant to support multiple object identities simultaneously.

This document presents an introduction to using the POA with the Java 2 Platform, Standard Edition. For a more complete description of the POA, see Chapter 11 of the CORBA 2.3.1 Specification.

Creating and Using the POA

The steps for creating and using a POA will vary according to the specific application being developed. The following steps generally occur during the POA life cycle:

  1. Get the root POA
  2. Define the POA's policies
  3. Create the POA
  4. Activate the POAManager
  5. Activate the servants, which may include activating the Tie
  6. Create the object reference from the POA

Each step is described in more detail in the sections that follow.

Step 1: Get the root POA

The first step is to get the first POA, which is called the rootPOA. The root POA is managed by the ORB and provided to the application using the ORB initialization interface under the initial object name "RootPOA".

An example of code that will get the root POA object and cast it to a POA is:

      ORB orb = ORB.init( args, null );
      POA rootPOA = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
Step 2: Define the POA's Policies

The Portable Object Adapter (POA) is designed to provide an object adapter that can be used with multiple ORB implementations with no rewriting needed to deal with different vendors' implementations.

The POA is also intended to allow persistent objects -- at least, from the client's perspective. That is, as far as the client is concerned, these objects are always alive, and maintain data values stored in them, even though physically, the server may have been restarted many times.

The POA allows the object implementer a lot more control over the object's identity, state, storage, and life cycle. You can create a POA without defining any policies and the default values will be used. The root POA has the following policies by default:

  • Thread Policy: ORB_CTRL_MODEL
  • Lifespan Policy: TRANSIENT
  • Object Id Uniqueness Policy: UNIQUE_ID
  • Id Assignment Policy: SYSTEM_ID
  • Servant Retention Policy: RETAIN
  • Request Processing Policy: USE_ACTIVE_OBJECT_MAP_ONLY
  • Implicit Activation Policy: IMPLICIT_ACTIVATION

The following code snippet shows how policies are set in the RMI-IIOP (with POA) example:

      Policy[] tpolicy = new Policy[3];
      tpolicy[0] = rootPOA.create_lifespan_policy(
        LifespanPolicyValue.TRANSIENT );
      tpolicy[1] = rootPOA.create_request_processing_policy(
        RequestProcessingPolicyValue.USE_ACTIVE_OBJECT_MAP_ONLY );
      tpolicy[2] = rootPOA.create_servant_retention_policy(
        ServantRetentionPolicyValue.RETAIN);

Each policy is discussed briefly in the following topics. For more information on POA policies, refer to Chapter 11, Portable Object Adapter of the CORBA/IIOP 2.3.1 Specification.

Thread Policy

This policy specifies the threading model used with the created POA. The default is ORB_CTRL_MODEL.

The ThreadPolicyValue can have the following values:

  • ORB_CTRL_MODEL - The ORB is responsible for assigning requests for an ORB-controlled POA to threads.
  • SINGLE_THREAD_MODEL - Requests for a single-threaded POA are processed sequentially. (NOTE: This policy is not supported in the ORB shipped with Sun's J2SE v.1.4.1 or higher).

Lifespan Policy

This policy specifies the lifespan of the objects implemented in the created POA. The default is TRANSIENT.

The LifespanPolicyValue can have the following values:

  • TRANSIENT - The objects implemented in the POA cannot outlive the POA instance in which they are first created.
  • PERSISTENT - The objects implemented in the POA can outlive the process in which they are first created.

Object Id Uniqueness Policy

This policy specifies whether the servants activated in the created POA must have unique object identities. The default is UNIQUE_ID.

The IdUniquenessPolicyValue can have the following values:

  • UNIQUE_ID - Servants activated with that POA support exactly one Object Id.
  • MULTIPLE_ID - A servant activated with that POA may support one or more Object Ids.

Id Assignment Policy

This policy specifies whether Object Ids in the created POA are generated by the application or by the ORB. The default is SYSTEM_ID.

The IdAssignmentPolicyValue can have the following values:

  • USER_ID - Objects created with that POA are assigned Object Ids only by the application.
  • SYSTEM_ID - Objects created with that POA are assigned a unique object id by the POA. If the POA also has the PERSISTENT policy, assigned Object Ids must be unique across all instantiations of the same POA.

Servant Retention Policy

This policy specifies whether the created POA retains active servants in an Active Object Map. The default is RETAIN.

The ServantRetentionPolicyValue can have the following values.

  • RETAIN - to indicate that the POA will retain active servants in its Active Object Map.
  • NON_RETAIN - to indicate Servants are not retained by the POA.

Request Processing Policy

This policy specifies how requests are processed by the created POA. The default is USE_ACTIVE_OBJECT_MAP_ONLY.

The RequestProcessingPolicyValue can have the following values:

  • USE_ACTIVE_OBJECT_MAP_ONLY - If the object ID is not found in the Active Object Map, an OBJECT_NOT_EXIST exception is returned to the client. The RETAIN policy is also required.
  • USE_DEFAULT_SERVANT - If the object ID is not found in the Active Object Map or the NON_RETAIN policy is present, and a default servant has been registered with the POA using the set_servant operation, the request is dispatched to the default servant.
  • USE_SERVANT_MANAGER - If the object ID is not found in the Active Object Map or the NON_RETAIN policy is present, and a servant manager has been registered with the POA using the set_servant_manager operation, the servant manager is given the opportunity to locate or activate a servant or raise an exception.

Implicit Activation Policy

This policy specifies whether implicit activation of servants is supported in the created POA. The default value is IMPLICIT_ACTIVATION.

The ImplicitActivationPolicyValue can have the following values:

  • IMPLICIT_ACTIVATION - Indicates implicit activation of servants. This requires SYSTEM_ID and RETAIN policies to be set.
  • NO_IMPLICIT_ACTIVATION - Indicates no implicit servant activation.
Step 3: Create the POA

Creating a new POA allows the application developer to declare specific policy choices for the new POA and to provide a different adapter activator and servant manager (these are callback objects used by the POA to activate POAs on demand and activate servants). Creating new POAs also allows the application developer to partition the name space of objects, as Object Ids are interpreted relative to a POA. Finally, by creating new POAs, the developer can independently control request processing for multiple sets of objects.

A POA is created as a child of an existing POA using the create_POA operation on the parent POA. To create a new POA, pass in the following information:

  • Name of the POA. The POA is given a name that must be unique with respect to all other POAs with the same parent. In the following example, the POA is named childPOA.
  • POA Manager. Specify the POA Manager to be associated with the new POA. If, as is shown in the following example, null is passed for this parameter, a new POA Manager will be created. The user can also choose to pass the POA Manager of another POA.
  • Policy List. Specify the policy list to be associated with the POA to control its behavior. In the following example, a persistent lifespan policy has already been defined for this POA.

The following code snippet shows how the POA is created in the Hello World: Persistent Server example.

// Create a POA by passing the Persistent Policy
POA persistentPOA = rootPOA.create_POA("childPOA", null,
   persistentPolicy );
Step 4: Activate the POAManager

Each POA object has an associated POAManager object that controls the processing state of the POAs with which it is associated, such as whether requests to the POA are queued or discarded. The POAManager can also deactivate the POA. A POA Manager may be associated with one or more POA objects.

The POAManager can have the following states:

  • Holding - In this state, associated POAs will queue incoming requests.
  • Active - In this state, associated POAs will start processing requests.
  • Discarding - In this state, associated POAs will discard incoming requests.
  • Inactive - In this state, associated POAs will reject the requests that have not begun executing as well as any new requests.

The POAManagerOperations javadocs contain more information on these states.

POA Managers are not automatically activated when they are created. The following code snippet shows how the POAManager is activated in the Hello World: Persistent Server example. If the POA Manager is not activated in this way, all calls to the Servant will hang because, by default, the POA Manager is in the HOLD state.

            // Activate PersistentPOA's POAManager. Without this step,
            // all calls to Persistent Server will hang because POAManager
            // will be in the 'HOLD' state.
            persistentPOA.the_POAManager().activate( );

Step 5: Activate the servants

The following information is quoted from section 11.2.5 of the CORBA Specification.

At any point in time, a CORBA object may or may not be associated with an active servant.

If the POA has the RETAIN policy, the servant and its associated Object Id are entered into the Active Object Map of the appropriate POA. This type of activation can be accomplished in one of the following ways.

  • The server application itself explicitly activates individual objects (via the activate_object or activate_object_with_id operations).
  • The server application instructs the POA to activate objects on demand by having the POA invoke a user-supplied servant manager. The server application registers this servant manager with set_servant_manager.
  • Under some circumstances (when the IMPLICIT_ACTIVATION policy is also in effect and the language binding allows such an operation), the POA may implicitly activate an object when the server application attempts to obtain a reference for a servant that is not already active (that is, not associated with an Object Id).

If the USE_DEFAULT_SERVANT policy is also in effect, the server application instructs the POA to activate unknown objects by having the POA invoke a single servant no matter what the Object Id is. The server application registers this servant with set_servant.

If the POA has the NON_RETAIN policy, for every request, the POA may use either a default servant or a servant manager to locate an active servant. From the POA's point of view, the servant is active only for the duration of that one request. The POA does not enter the servant-object association into the Active Object Map.

When using RMI-IIOP technology, your implementations use delegation (known as the Tie model) to associate your implementation with the interface. When you create an instance of your implementation, you also need to create a Tie object to associate it with a CORBA interface. The following code snippet shows how to activate the Tie, if the POA policy is USE_ACTIVE_OBJECT_MAP_ONLY. This sample code is from the RMI-IIOP with POA example.

_HelloImpl_Tie tie = (_HelloImpl_Tie)Util.getTie( helloImpl );
String helloId = "hello";
byte[] id = helloId.getBytes();
tPOA.activate_object_with_id( id, tie );

The CORBA Specification discusses creating object references (section 11.2.4), activating objects (section 11.2.5), and processing requests (section 11.2.6) in more detail than is done in this document. Please refer to the CORBA 2.3.1 Specification for more information.

Step 6: Create the object reference

Object references are created in servers. Once created, they may be exported to clients. Object references encapsulate object identity information and information required by the ORB to identify and locate the server and the POA with which the object is associated. References are created in the following ways:

  • Explicitly activate a servant and associate it with an object reference.

    The following example is from Hello World: Persistent Server. This example uses the servant_to_reference operation to map an activated servant to its corresponding object reference.

    // Resolve Root Naming context and bind a name for the
// servant.
org.omg.CORBA.Object obj = orb.resolve_initial_references(
  "NameService" );
NamingContextExt rootContext = NamingContextExtHelper.narrow( obj );

NameComponent[] nc = rootContext.to_name(
  "PersistentServerTutorial" );
rootContext.rebind( nc, persistentPOA.servant_to_reference(
  servant ) );
  • Server application directly creates a reference.

    The following example is from the RMI-IIOP with POA example. In this example, the following code directly creates a reference. In doing so, they bring the abstract object into existence, but do not associate it with an active servant.

    // Publish the object reference using the same object id
// used to activate the Tie object.
Context initialNamingContext = new InitialContext();
initialNamingContext.rebind("HelloService",
tPOA.create_reference_with_id(id,
  tie._all_interfaces(tPOA,id)[0]) );
  • Server application causes a servant to implicitly activate itself.

    The behavior can occur only if the POA has been created with the IMPLICIT_ACTIVATION policy, which is the default behavior.

Once an reference is created in the server, it can be made available to clients. For more information on creating object references and exporting to clients, refer to section 11.2.4 of the CORBA 2.3.1 Specification for more information.

Adapter Activators

  • For an example application that uses Adapter Activators, see Using Adapter Activators.

An adapter activator is optional. You would use an adapter activator if POAs need to be created during request processing. If all needed POAs are created when the application is executed, an adapter activator is not required.

An adapter activator supplies a POA with the ability to create child POAs on demand, as a side-effect of receiving a request that names the child POA (or one of its children), or when the find_POA method is called with an activate parameter value of TRUE. The ORB will invoke an operation on an adapter activator when a request is received for a child POA that does not currently exist. The adapter activator can then create the required POA on demand.

A request must be capable of conveying the Object Id of the target object as well as the identification of the POA that created the target object reference. When a client issues a request, the ORB first locates an appropriate server (perhaps starting one if needed) and then it locates the appropriate POA within that server.

If the POA does not exist in the server process, the application has the opportunity to re-create the required POA by using an adapter activator. An adapter activator is a user-implemented object that can be associated with a POA. It is invoked by the ORB when a request is received for a non-existent child POA. The adapter activator has the opportunity to create the required POA. If it does not, the client receives the ADAPTER_NONEXISTENT exception.

Once the ORB has located the appropriate POA, it delivers the request to that POA. The further processing of that request depends both upon the policies associated with that POA as well as the object's current state of activation.

For more information on Adapter Activators, refer to section 11.3.3 of the CORBA 2.3.1 Specification or the AdapterActivatorOperations API documentation.

Servant Managers

Servant Managers are optional. You would use a servant manager to allow the POA to activate servants on demand when a request for an inactive object is received. If your server loads all objects when it starts up, you do not need a servant manager.

A servant manager is a callback object that the application developer can associate with a POA. The ORB will invoke operations on servant managers to activate servants on demand, and to deactivate servants. Servant managers are responsible for managing the association of an object reference (as characterized by its Object Id value) with a particular servant, and for determining whether an object reference exists or not. Each servant manager type contains two operations, the first called to find and return a servant and the second to deactivate a servant. The operations differ according to the amount of information usable for their situation.

To use servant managers, the USE_SERVANT_MANAGER policy must be set. Once set, the type of servant manager used in a particular situation depends on other policies in the POA. The two types of servant managers are:

  • ServantActivator

    When the POA has the RETAIN policy, it uses servant managers that are ServantActivators.

    This type is typically used to activate persistent objects.

    • For an example that uses Servant Activators, see Using Servant Activators.
  • ServantLocator

    When the POA has the NON_RETAIN policy, it uses servant managers that are ServantLocators. Because the POA knows that the servant returned by this servant manager will be used only for a single request, it can supply extra information to the servant manager's operations and the servant manager's pair of operations may be able to cooperate to do something different than a ServantActivator. When the POA uses the ServantLocator interface, immediately after performing the operation invocation on the servant returned by preinvoke, the POA will invoke postinvoke on the servant manager, passing the ObjectId value and the Servant value as parameters (among others). This feature may be used to force every request for objects associated with a POA to be mediated by the servant manager.

    This type is typically used to activate transient objects.

    • For an example that uses Servant Locators see Using Servant Locators.

For more information on Servant Managers, refer to section 11.3.4 of the CORBA 2.3.1 Specification.

POA Q&A

Is POAManager.activate() required for a newly created POA?

POAManager.activate() is required for a newly created POA if a null is passed for the POAManager parameter to POA::createPOA . If null is passed, a new POAManager is created and associated with the created POA. In this case, POAManager.activate() is needed.

To control several POAs with the same POAManager, you would:

  1. Create a POA or use the rootPOA
  2. Obtain the POA's manager via POA::the_POAManager
  3. Pass the POAManager to subsequent createPOA calls

There is no implicit relationship between the Root POA's POAManager and other POAs unless explicitly programmed by the programmer as shown above.

For more information, read section 11.3.2 of the CORBA specification, formal/99-10-07.

For more information

For more information about the Portable Object Adapter, read Chapter 11 of the CORBA/IIOP v.2.3.1 Specification from the Object Management Group's website.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.security.auth.PolicyFile (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.PolicyFile

No usage of com.sun.security.auth.PolicyFile
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Default Policy Implementation and Policy File Syntax

The policy for a Java™ programming language application environment (specifying which permissions are available for code from various sources, and executing as various principals) is represented by a Policy object. More specifically, it is represented by a Policy subclass providing an implementation of the abstract methods in the Policy class (which is in the java.security package).

The source location for the policy information utilized by the Policy object is up to the Policy implementation. The Policy reference implementation obtains its information from static policy configuration files.

The rest of this document pertains to the Policy reference implementation and the syntax that must be used in policy files it reads. For information about using the Policy Tool to create a policy file (without needing to know the required syntax), see the Policy Tool documentation (for Solaris/Linux) (for Windows).

Here is an outline for the rest of this document:

Default Policy Implementation
Default Policy File Locations
Changing the Policy Implementation
Policy File Syntax
Policy File Examples
Property Expansion in Policy Files
General Expansion in Policy Files
Related Documentation

Default Policy Implementation

In the Policy reference implementation, the policy can be specified within one or more policy configuration files. The configuration file(s) specify what permissions are allowed for code from a specified code source, and executed by a specified principal. Each configuration file must be encoded in UTF-8.

A policy file can be composed via a simple text editor, or via the graphical Policy Tool utility.

There is by default a single system-wide policy file, and a single (optional) user policy file.

The Policy reference implementation is initialized the first time its getPermissions method is called, or whenever its refresh method is called. Initialization involves parsing the policy configuration file(s) (see Policy File Syntax), and then populating the Policy object.

Default Policy File Locations

As mentioned previously, there is by default a single system-wide policy file, and a single user policy file.

The system policy file is by default located at

java.home/lib/security/java.policy  (Solaris/Linux)
java.home\lib\security\java.policy  (Windows)

Note: java.home refers to the value of the system property named "java.home", which specifies the directory that houses the runtime environment -- either the jre directory in the Java SE Development Kit (JDK) or the top-level directory of the Java SE Runtime Environment (JRE).

The system policy file is meant to grant system-wide code permissions. The java.policy file installed with the JDK grants all permissions to standard extensions, allows anyone to listen on un-privileged ports, and allows any code to read certain "standard" properties that are not security-sensitive, such as the "os.name" and "file.separator" properties.

The user policy file is by default located at

user.home/.java.policy  (Solaris/Linux)
user.home\.java.policy  (Windows)

Note: user.home refers to the value of the system property named "user.home", which specifies the user's home directory.

When the Policy is initialized, the system policy is loaded in first, and then the user policy is added to it. If neither policy is present, a built-in policy is used. This built-in policy is the same as the java.policy file installed with the JRE.

Policy file locations are specified in the security properties file, which is located at

java.home/lib/security/java.security  (Solaris/Linux)
java.home\lib\security\java.security  (Windows)
As noted above, java.home indicates the directory that houses the runtime environment--either the jre directory in the JDK or the top-level directory of the JRE. The policy file locations are specified as the values of properties whose names are of the form
policy.url.n
where n is a number. You specify each such property value in a line of the following form:
policy.url.n=URL
Here, URL is a URL specification.

For example, the default system and user policy files are defined in the security properties file as

policy.url.1=file:${java.home}/lib/security/java.policy
policy.url.2=file:${user.home}/.java.policy

(See Property Expansion for information about specifying property values via a special syntax, such as specifying the java.home property value via ${java.home}.)

You can actually specify a number of URLs (including ones of the form "http://"), and all the designated policy files will get loaded. You can also comment out or change the second one to disable reading the default user policy file.

The algorithm starts at policy.url.1, and keeps incrementing until it does not find a URL. Thus if you have policy.url.1 and policy.url.3, policy.url.3 will never be read.

Specifying an Additional Policy File at Runtime

It is also possible to specify an additional or a different policy file when invoking execution of an application. This can be done via the "-Djava.security.policy" command line argument, which sets the value of the java.security.policy property. For example, if you use

    java -Djava.security.manager -Djava.security.policy=someURL SomeApp
where someURL is a URL specifying the location of a policy file, then the specified policy file will be loaded in addition to all the policy files that are specified in the security properties file.

Notes:

  • The URL can be any regular URL or simply the name of a policy file in the current directory, as in
        java -Djava.security.manager -Djava.security.policy=mypolicy SomeApp
  • The "-Djava.security.manager" argument ensures that the default security manager is installed, and thus the application is subject to policy checks. It is not required if the application SomeApp installs a security manager.

If you use

    java -Djava.security.manager -Djava.security.policy==someURL SomeApp
(note the double equals) then just the specified policy file will be used; all the ones indicated in the security properties file will be ignored.

If you want to pass a policy file to the appletviewer, then use a "-J-Djava.security.policy" argument as follows:

    appletviewer -J-Djava.security.policy=someURL myApplet
Note: The "-Djava.security.policy" policy file value will be ignored (for both java and appletviewer commands) if the "policy.allowSystemProperty" property in the security properties file is set to false. The default is true.

Changing the Policy Implementation

An alternative policy class can be given to replace the Policy reference implementation class, as long as the former is a subclass of the abstract Policy class and implements the getPermissions method (and other methods as necessary).

The Policy reference implementation can be changed by editing the security properties file, which is the java.security file in the lib/security directory of the JDK or JRE.

One of the types of properties you can set in java.security is of the following form:

    policy.provider=PolicyClassName

PolicyClassName must specify the fully qualified name of the desired Policy implementation class. The default security properties file entry for this property is the following:

    policy.provider=sun.security.provider.PolicyFile

To customize, you can change the property value to specify another class, as in

    policy.provider=com.mycom.MyPolicy

Policy File Syntax

The policy configuration file(s) for a JDK or JRE installation specifies what permissions (which types of system resource accesses) are granted to code from a specified code source, and executed as a specified principal.

For an applet (or an application running under a security manager) to be allowed to perform secured actions (such as reading or writing a file), the applet (or application) must be granted permission for that particular action. In the Policy reference implementation, that permission must be granted by a grant entry in a policy configuration file. See below and the "Java Security Architecture Specification" for more information. (The only exception is that code always automatically has permission to read files from its same (URL) location, and subdirectories of that location; it does not need explicit permission to do so.)

A policy configuration file essentially contains a list of entries. It may contain a "keystore" entry, and contains zero or more "grant" entries.

Keystore Entry

A keystore is a database of private keys and their associated digital certificates such as X.509 certificate chains authenticating the corresponding public keys. The keytool utility (for Solaris/Linux) (for Windows) is used to create and administer keystores. The keystore specified in a policy configuration file is used to look up the public keys of the signers specified in the grant entries of the file. A keystore entry must appear in a policy configuration file if any grant entries specify signer aliases, or if any grant entries specify principal aliases (see below).

At this time, there can be only one keystore/keystorePasswordURL entry in the policy file (other entries following the first one are ignored). This entry can appear anywhere outside the file's grant entries. It has the following syntax:

keystore "some_keystore_url", "keystore_type", "keystore_provider";
keystorePasswordURL "some_password_url";
some_keystore_url specifies the URL location of the keystore, some_password_url specifies the URL location of the keystore password, keystore_type specifies the keystore type, and keystore_provider specifies the keystore provider. Note that the input stream from some_keystore_url is passed to the KeyStore.load method. If NONE is specified as the URL, then a null stream is passed to the KeyStore.load method. NONE should be specified if the KeyStore is not file-based, for example, if it resides on a hardware token device.

The URL is relative to the policy file location. Thus if the policy file is specified in the security properties file as:

    policy.url.1=http://foo.bar.com/fum/some.policy
and that policy file has an entry:
    keystore ".keystore";
then the keystore will be loaded from:
    http://foo.bar.com/fum/.keystore
The URL can also be absolute.

A keystore type defines the storage and data format of the keystore information, and the algorithms used to protect private keys in the keystore and the integrity of the keystore itself. The default type supported by Sun Microsystems is a proprietary keystore type named "JKS". Thus, if the keystore type is "JKS", it does not need to be specified in the keystore entry.

Grant Entries

Code being executed is always considered to come from a particular "code source" (represented by an object of type CodeSource). The code source includes not only the location (URL) where the code originated from, but also a reference to the certificate(s) containing the public key(s) corresponding to the private key(s) used to sign the code. Certificates in a code source are referenced by symbolic alias names from the user's keystore. Code is also considered to be executed as a particular principal (represented by an object of type Principal), or group of principals.

Each grant entry includes one or more "permission entries" preceded by optional codeBase, signedBy, and principal name/value pairs that specify which code you want to grant the permissions. The basic format of a grant entry is the following:

  grant signedBy "signer_names", codeBase "URL",
        principal principal_class_name "principal_name",
        principal principal_class_name "principal_name",
        ... {

      permission permission_class_name "target_name", "action",
          signedBy "signer_names";
      permission permission_class_name "target_name", "action",
          signedBy "signer_names";
      ...
  };
All non-italicized items above must appear as is (although case doesn't matter and some are optional, as noted below). Italicized items represent variable values.

A grant entry must begin with the word grant.

The SignedBy, Principal, and CodeBase Fields

The signedBy, codeBase, and principal values are optional, and the order of these fields does not matter.

A signedBy value indicates the alias for a certificate stored in the keystore. The public key within that certificate is used to verify the digital signature on the code; you grant the permission(s) to code signed by the private key corresponding to the public key in the keystore entry specified by the alias.

The signedBy value can be a comma-separated list of multiple aliases. An example is "Adam,Eve,Charles", which means "signed by Adam and Eve and Charles"; the relationship is AND, not OR. To be more exact, a statement like "Code signed by Adam" means "Code in a class file contained in a JAR which is signed using the private key corresponding to the public key certificate in the keystore whose entry is aliased by Adam".

The signedBy field is optional in that, if it is omitted, it signifies "any signer". It doesn't matter whether the code is signed or not or by whom.

A principal value specifies a class_name/principal_name pair which must be present within the executing thread's principal set. The principal set is associated with the executing code by way of a Subject.

The principal_class_name may be set to the wildcard value, *, which allows it to match any Principal class. In addition, the principal_name may also be set to the wildcard value, *, allowing it to match any Principal name. When setting the principal_class_name or principal_name to *, do not surround the * with quotes. Also, if you specify a wildcard principal class, you must also specify a wildcard principal name.

The principal field is optional in that, if it is omitted, it signifies "any principals".

Note on KeyStore Alias Replacement:

If the principal class_name/principal_name pair is specified as a single quoted string, it is treated as a keystore alias. The keystore is consulted and queried (via the alias) for an X509 Certificate. If one is found, the principal class_name is automatically treated as javax.security.auth.x500.X500Principal, and the principal_name is automatically treated as the subject distinguished name from the certificate. If an X509 Certificate mapping is not found, the entire grant entry is ignored.

A codeBase value indicates the code source location; you grant the permission(s) to code from that location. An empty codeBase entry signifies "any code"; it doesn't matter where the code originates from.

Note: a codeBase value is a URL and thus should always utilize slashes (never backslashes) as the directory separator, even when the code source is actually on a Windows system. Thus, if the source location for code on a Windows system is actually C:\somepath\api\, then the policy codeBase entry should look like:

    grant codeBase "file:/C:/somepath/api/" {
        ...
    };
The exact meaning of a codeBase value depends on the characters at the end. A codeBase with a trailing "/" matches all class files (not JAR files) in the specified directory. A codeBase with a trailing "/*" matches all files (both class and JAR files) contained in that directory. A codeBase with a trailing "/-" matches all files (both class and JAR files) in the directory and recursively all files in subdirectories contained in that directory. The following table illustrates the different cases.
Codebase URL of Downloaded Code | Codebase URL in Policy | Match?
java.sun.com/people/gong/ | java.sun.com/people/gong | Y
java.sun.com/people/gong/ | java.sun.com/people/gong/ | Y
java.sun.com/people/gong/ | java.sun.com/people/gong/* | Y
java.sun.com/people/gong/ | java.sun.com/people/gong/- | Y
java.sun.com/people/gong/appl.jar | java.sun.com/people/gong/ | N
java.sun.com/people/gong/appl.jar | java.sun.com/people/gong/- | Y
java.sun.com/people/gong/appl.jar | java.sun.com/people/gong/* | Y
java.sun.com/people/gong/appl.jar | java.sun.com/people/- | Y
java.sun.com/people/gong/appl.jar | java.sun.com/people/* | N
java.sun.com/people/gong/ | java.sun.com/people/- | Y
java.sun.com/people/gong/ | java.sun.com/people/* | N

The Permission Entries

A permission entry must begin with the word permission. The word permission_class_name in the template above would actually be a specific permission type, such as java.io.FilePermission or java.lang.RuntimePermission.

The "action" is required for many permission types, such as java.io.FilePermission (where it specifies what type of file access is permitted). It is not required for categories such as java.lang.RuntimePermission where it is not necessary--you either have the permission specified by the "target_name" value following the permission_class_name or you don't.

The signedBy name/value pair for a permission entry is optional. If present, it indicates a signed permission. That is, the permission class itself must be signed by the given alias(es) in order for the permission to be granted. For example, suppose you have the following grant entry:

  grant {
      permission Foo "foobar", signedBy "FooSoft";
  };

Then this permission of type Foo is granted if the Foo.class permission was placed in a JAR file and the JAR file was signed by the private key corresponding to the public key in the certificate specified by the "FooSoft" alias, or if Foo.class is a system class, since system classes are not subject to policy restrictions.

Items that appear in a permission entry must appear in the specified order (permission, permission_class_name, "target_name", "action", and signedBy "signer_names"). An entry is terminated with a semicolon.

Case is unimportant for the identifiers (permission, signedBy, codeBase, etc.) but is significant for the permission_class_name or for any string that is passed in as a value.

Note Regarding File Path Specifications on Windows Systems

Note: When you are specifying a java.io.FilePermission, the "target_name" is a file path. On Windows systems, whenever you directly specify a file path in a string (but not in a codeBase URL), you need to include two backslashes for each actual single backslash in the path, as in

  grant {
      permission java.io.FilePermission "C:\\users\\cathy\\foo.bat", "read";
  };
The reason this is necessary is because the strings are processed by a tokenizer (java.io.StreamTokenizer), which allows "\" to be used as an escape string (for example, "\n" to indicate a new line) and which thus requires two backslashes to indicate a single backslash. After the tokenizer has processed the above file path string, converting double backslashes to single backslashes, the end result is
    "C:\users\cathy\foo.bat"

Policy File Examples

An example of two entries in a policy configuration file is

  // If the code is signed by "Duke", grant it read/write access to all
  // files in /tmp:
  grant signedBy "Duke" {
      permission java.io.FilePermission "/tmp/*", "read,write";
  };

  // Grant everyone the following permission:
  grant {
      permission java.util.PropertyPermission "java.vendor", "read";
  };

The contents of another sample policy configuration file appear below.

  grant signedBy "sysadmin", codeBase "file:/home/sysadmin/*" {
      permission java.security.SecurityPermission "Security.insertProvider.*";
      permission java.security.SecurityPermission "Security.removeProvider.*";
      permission java.security.SecurityPermission "Security.setProperty.*";
  };
This specifies that only code that satisfies the following conditions can call methods in the Security class to add or remove providers or to set Security properties:
  • The code was loaded from a signed JAR file that is in the "/home/sysadmin/" directory on the local file system.
  • The signature can be verified using the public key referenced by the alias name "sysadmin" in the keystore.

Either component of the code source (or both) may be missing. An example where codeBase is missing is:

  grant signedBy "sysadmin" {
      permission java.security.SecurityPermission "Security.insertProvider.*";
      permission java.security.SecurityPermission "Security.removeProvider.*";
  };
If this policy is in effect, code that comes in a JAR File signed by "sysadmin" can add/remove providers, regardless of where the JAR File originated from.

An example without a signer is:

  grant codeBase "file:/home/sysadmin/-" {
      permission java.security.SecurityPermission "Security.insertProvider.*";
      permission java.security.SecurityPermission "Security.removeProvider.*";
  };
In this case, code that comes from anywhere beneath the "/home/sysadmin/" directory on the local filesystem can add/remove providers. The code does not need to be signed.

An example where neither codeBase nor signedBy is included is:

  grant {
      permission java.security.SecurityPermission "Security.insertProvider.*";
      permission java.security.SecurityPermission "Security.removeProvider.*";
  };
Here, with both code source components missing, any code (regardless of where it originated from, or whether or not it is signed, or who signed it) can add/remove providers.

The following represents a principal-based entry.

  grant principal javax.security.auth.x500.X500Principal "cn=Alice" {
      permission java.io.FilePermission "/home/Alice", "read, write";
  };
This permits any code executing as the X500Principal, "cn=Alice", permission to read and write to "/home/Alice".

The following represents a principal-based entry with a wildcard value.

  grant principal javax.security.auth.x500.X500Principal * {
      permission java.io.FilePermission "/tmp", "read, write";
  };
This permits any code executing as an X500Principal (regardless of the distinguished name), permission to read and write to "/tmp".

The following example shows a grant statement with both codesource and principal information.

  grant codebase "http://www.games.com",
        signedBy "Duke",
        principal javax.security.auth.x500.X500Principal "cn=Alice" {
      permission java.io.FilePermission "/tmp/games", "read, write";
  };
This allows code downloaded from "www.games.com", signed by "Duke", and executed by "cn=Alice", permission to read and write into the "/tmp/games" directory.

The following example shows a grant statement with KeyStore alias replacement:

  keystore "http://foo.bar.com/blah/.keystore";

  grant principal "alice" {
      permission java.io.FilePermission "/tmp/games", "read, write";
  };
"alice" will be replaced by
    javax.security.auth.x500.X500Principal "cn=Alice"
assuming the X.509 certificate associated with the keystore alias, alice, has a subject distinguished name of "cn=Alice". This allows code executed by the X500Principal "cn=Alice" permission to read and write into the "/tmp/games" directory.

Property Expansion in Policy Files

Property expansion is possible in policy files and in the security properties file.

Property expansion is similar to expanding variables in a shell. That is, when a string like

    ${some.property}
appears in a policy file, or in the security properties file, it will be expanded to the value of the system property. For example,
    permission java.io.FilePermission "${user.home}", "read";
will expand "${user.home}" to use the value of the "user.home" system property. If that property's value is "/home/cathy", then the above is equivalent to
    permission java.io.FilePermission "/home/cathy", "read";
In order to assist in platform-independent policy files, you can also use the special notation of "${/}", which is a shortcut for "${file.separator}". This allows things like
    permission java.io.FilePermission "${user.home}${/}*", "read";
If the value of the "user.home" property is /home/cathy, and you are on Solaris/Linux, the above gets converted to:
    permission java.io.FilePermission "/home/cathy/*", "read";
If on the other hand the "user.home" value is C:\users\cathy and you are on a Windows system, the above gets converted to:
    permission java.io.FilePermission "C:\users\cathy\*", "read";
Also, as a special case, if you expand a property in a codebase, such as
    grant codeBase "file:${java.home}/lib/ext/"
then any file.separator characters will be automatically converted to /'s. Thus on a Windows system, the above would get converted to
    grant codeBase "file:C:/jdk1.4/jre/lib/ext/"
even if "java.home" is set to C:\jdk1.4\jre. Thus you don't need to use ${/} in codebase strings (and you shouldn't).

Property expansion takes place anywhere a double quoted string is allowed in the policy file. This includes the "signer_names", "URL", "target_name", and "action" fields.

Whether or not property expansion is allowed is controlled by the value of the "policy.expandProperties" property in the security properties file. If the value of this property is true (the default), expansion is allowed.

Note: You can't use nested properties; they will not work. For example,

    "${user.${foo}}"
doesn't work, even if the "foo" property is set to "home". The reason is the property parser doesn't recognize nested properties; it simply looks for the first "${", and then keeps looking until it finds the first "}" and tries to interpret the result (in this case, "${user.$foo}") as a property, but fails if there is no such property.

Note: If a property can't be expanded in a grant entry, permission entry, or keystore entry, that entry is ignored. For example, if the system property "foo" is not defined and you have:

    grant codeBase "${foo}" {
        permission ...;
        permission ...;
    };
then all the permissions in this grant entry are ignored. If you have
    grant {
        permission Foo "${foo}";
        permission Bar "barTarget";
    };
then only the "permission Foo..." entry is ignored. And finally, if you have
    keystore "${foo}";
then the keystore entry is ignored.

Windows Systems, File Paths, and Property Expansion

As noted above, on Windows systems, when you directly specify a file path in a string (but not in a codeBase URL), you need to include two backslashes for each actual single backslash in the path, as in
    grant {
        permission java.io.FilePermission "C:\\users\\cathy\\foo.bat", "read";
    };
This is because the strings are processed by a tokenizer (java.io.StreamTokenizer), which allows "\" to be used as an escape string (e.g., "\n" to indicate a new line) and which thus requires two backslashes to indicate a single backslash. After the tokenizer has processed the above file path string, converting double backslashes to single backslashes, the end result is
    "C:\users\cathy\foo.bat"
Expansion of a property in a string takes place after the tokenizer has processed the string. Thus if you have the string
    "${user.home}\\foo.bat"
then first the tokenizer processes the string, converting the double backslashes to a single backslash, and the result is
    "${user.home}\foo.bat"
Then the ${user.home} property is expanded and the end result is
    "C:\users\cathy\foo.bat"
assuming the "user.home" value is C:\users\cathy. Of course, for platform independence, it would be better if the string was initially specified without any explicit slashes, i.e., using the ${/} property instead, as in
    "${user.home}${/}foo.bat"

General Expansion in Policy Files

Generalized forms of expansion are also supported in policy files. For example, permission names may contain a string of the form:
${{protocol:protocol_data}}
If such a string occurs in a permission name, then the value in protocol determines the exact type of expansion that should occur, and protocol_data is used to help perform the expansion. protocol_data may be empty, in which case the above string should simply take the form:
${{protocol}}

There are two protocols supported in the default policy file implementation:

  1. ${{self}}

    The protocol, self, denotes a replacement of the entire string, ${{self}}, with one or more principal class/name pairs. The exact replacement performed depends upon the contents of the grant clause to which the permission belongs.

    If the grant clause does not contain any principal information, the permission will be ignored (permissions containing ${{self}} in their target names are only valid in the context of a principal-based grant clause). For example, BarPermission will always be ignored in the following grant clause:

                grant codebase "www.foo.com", signedby "duke" {
                permission BarPermission "... ${{self}} ...";
            };
    If the grant clause contains principal information, ${{self}} will be replaced with that same principal information. For example, ${{self}} in BarPermission will be replaced with javax.security.auth.x500.X500Principal "cn=Duke" in the following grant clause:
    grant principal javax.security.auth.x500.X500Principal "cn=Duke" {
    permission BarPermission "... ${{self}} ...";
};
    If there is a comma-separated list of principals in the grant clause, then ${{self}} will be replaced by the same comma-separated list or principals. In the case where both the principal class and name are wildcarded in the grant clause, ${{self}} is replaced with all the principals associated with the Subject in the current AccessControlContext.

    The following example describes a scenario involving both self and KeyStore alias replacement together:

    keystore "http://foo.bar.com/blah/.keystore";

grant principal "duke" {
    permission BarPermission "... ${{self}} ...";
};
    In the above example, "duke" will first be expanded into javax.security.auth.x500.X500Principal "cn=Duke" assuming the X.509 certificate associated with the KeyStore alias, "duke", has a subject distinguished name of "cn=Duke". Next, ${{self}} will be replaced with the same principal information that was just expanded in the grant clause: javax.security.auth.x500.X500Principal "cn=Duke".
  2. ${{alias:alias_name}}

    The protocol, alias, denotes a java.security.KeyStore alias substitution. The KeyStore used is the one specified in the KeyStore entry. alias_name represents an alias into the KeyStore. ${{alias:alias_name}} is replaced with javax.security.auth.x500.X500Principal "DN", where DN represents the subject distinguished name of the certificate belonging to alias_name. For example:

    keystore "http://foo.bar.com/blah/.keystore";

grant codebase "www.foo.com" {
    permission BarPermission "... ${{alias:duke}} ...";
};
    In the above example the X.509 certificate associated with the alias, duke, is retrieved from the KeyStore, foo.bar.com/blah/.keystore. Assuming duke's certificate specifies "o=dukeOrg, cn=duke" as the subject distinguished name, then ${{alias:duke}} is replaced with javax.security.auth.x500.X500Principal "o=dukeOrg, cn=duke".

    The permission entry is ignored under the following error conditions:

    • The keystore entry is unspecified
    • The alias_name is not provided
    • The certificate for alias_name can not be retrieved
    • The certificate retrieved is not an X.509 certificate

Related Documentation

  • Permissions in the JavaSE JDK
  • Policy Tool (for Solaris) (for Win32) (for Solaris/Linux) (for Windows)

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Policy Tool - Policy File Creation and Management Tool

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Policy File Creation and Management

Creates and modifies the external policy configuration files that define your installation's Java security policy.

Table of Contents

Introduction

Policy Tool Usage
Starting Policy Tool
Creating a new Policy File
Opening a Different Policy File
Specifying the Keystore
Adding a New Policy Entry
Adding a New Principal
Editing a Principal
Removing a Principal
Adding a New Permission
Editing a Permission
Removing a Permission
Completing the Addition of a Policy Entry
Editing a Policy Entry
Removing a Policy Entry
Saving the Policy File
Exiting the Policy Tool
Viewing the Warning Log

Examples
Starting Creation of the User Policy File
Adding a Policy Entry
Specifying a Keystore
Adding a Policy Entry with a SignedBy Alias
Adding a Policy Entry with a Principal
Saving the User Policy File
Exiting Policy Tool

See Also

Introduction

The policy for a Java runtime (specifying which permissions are available for code from various sources, when executing as various principals) is represented by a Policy object. The default Policy implementation obtains its information from static ASCII policy configuration files.

A policy file can be composed via a simple text editor, or via the graphical Policy Tool utility described in this document. Using the Policy Tool saves typing and eliminates the need for you to know the required policy file syntax thus reducing errors.

The Policy Tool Usage section describes how to use the Policy Tool to create and modify policy files.

The Examples section provides detailed examples of the use of Policy Tool.

The See Also section provides links to related documentation.

Policy Tool Usage

Starting Policy Tool

To start Policy Tool, simply type the following at the command line.

  policytool

This brings up the "Policy Tool" window.

Whenever Policy Tool is started, it tries to fill in this window with policy information from what is sometimes referred to as the "user policy file". The user policy file is by default a file named .java.policy in your home directory. If Policy Tool cannot find the user policy file, it reports the situation and displays a blank "Policy Tool" window (that is, a window with headings and buttons but no data in it):

Blank Policy Tool window

You can then proceed to either open whatever policy file you want to work on or create a new policy file, by adding policy entries, optionally specifying a keystore, and saving the file).

The first time you run the Policy Tool, there will not be a user policy file (unless you created one manually).

Creating a new Policy File

To create a new policy file, start by simply selecting the New command from the File menu. This will close the currently open policy file (if any, after first prompting you to save it if needed) and bring up a new policy tool window, that is, a window with headings and buttons but no data in it.

Please Note: this is not necessary the first time you run the Policy Tool. Since the tool tries to open the user policy file and one doesn't exist yet (unless it was created manually), the tool will bring up a window without any data in it.

Once you have a new policy tool window, you can then create the policy entries, and specify the keystore (if any of the policy entries specify a keystore alias). At any point, you can save the policy file.

Opening a Different Policy File

To work on a different policy file than the one currently being worked on (if any), use the Open command in the File menu.

This will close the currently open policy file (if any, after first prompting you to save it if needed) and will present you with an Open dialog, which you can use to navigate the directory structure until you get to the directory containing the policy file you want to work on. Select that file, then select the OK button.

The "Policy Tool" window will then be filled in with information from the policy file, including the policy file name, the keystore URL (if any), and the CodeBase, SignedBy and Principal parts of each policy entry in the policy file.

Specifying the Keystore

To specify the keystore containing the key information for the aliases specified in the SignedBy parts of policy entries, select the Edit command in the Keystore menu.

This brings up a dialog box in which you specify the new keystore URL and optionally the keystore type.

As an example, to specify the keystore named "mykeystore" in the /tests/ directory, type the following file: URL into the text box labeled "New KeyStore URL".

  file:/tests/mykeystore

To also specify that the keystore type is "JKS" (the proprietary keystore type supported by Sun Microsystems), type the following into the text box labeled "New KeyStore Type".

  JKS

When you are done specifying the keystore URL and type (if any), select OK (or you can select Cancel to cancel the operation). If you didn't cancel, the text box labeled "Keystore:" is now filled in with the keystore URL and type.

Adding a New Policy Entry

To add a new policy entry, select the Add Policy Entry button in the main "Policy Tool" window.

This brings up a "Policy Entry" dialog box:

Blank Add Entry Dialog

Using this dialog box, you specify

  • an optional CodeBase entry indicating the URL location where the code originates from. For example, to indicate code from the local /JavaSoft/TESTS/ directory, type the following file URL into the CodeBase text box:
      file:/JavaSoft/TESTS/
  • an optional SignedBy entry indicating the alias name from the keystore used to reference the signer whose private key was used to sign the code. For example, to indicate the alias named "duke", simply type the following into the SignedBy text box:
      duke
  • an optional Principals entry indicating the list of principals that the code has to be executed as in order for the permission(s) to be granted. See Adding a New Principal.
  • one or more permission entries indicating which permissions are granted to the code from the source indicated by the CodeBase and SignedBy values (or to any code if no such values are specified) when running as the specified principals in the Principals list. See Adding a New Permission.

The SignedBy value is a string alias that is mapped (using the keystore) to a set of public keys that are associated with the signers. These keys are used to verify that classes from the specified code source are really signed by these signers.

The SignedBy value can be a comma-separated string containing names of multiple signers, an example of which is "Adam,Eve,Charles", which means "signed by Adam and Eve and Charles" (i.e., the relationship is AND, not OR).

The SignedBy value is optional in that, if it is omitted, it signifies "any signer," or in other words, it doesn't matter whether the code is signed or not. Similarly, if there is no CodeBase entry, then it signifies "any code"; it doesn't matter where the code originates from.

Thus, if there is no CodeBase entry, then all code signed by the specified alias(es) will be granted the specified permissions. If there is no SignedBy entry, then all code from the specified CodeBase will be granted the specified permissions, regardless of whether the code is signed or not, and by whom. If there is no CodeBase entry, and also no SignedBy entry, then all code will be granted the specified permissions.

Note: The exact meaning of a CodeBase value depends on the characters at the end. A CodeBase with a trailing "/" matches all class files (not JAR files) in the specified directory. A CodeBase with a trailing "/*" matches all files (both class and JAR files) contained in that directory. A CodeBase with a trailing "/-" matches all files (both class and JAR files) in the directory and recursively all files in subdirectories contained in that directory.

The Principals entry specifies a list of "principal values". Each principal value specifies a principal_type/principal_name pair which must be present within the executing thread's principal set. The Principals entry is optional in that, if it is omitted, it signifies "any principals".

If there is no principal_type specified and the principal_name is a quoted string, the string is treated as a keystore alias when the policy file is processed at runtime. The keystore is consulted and queried (via the alias) for an X509 Certificate. If one is found, the principal type is automatically assumed to be javax.security.auth.x500.X500Principal, and the actual principal name is assumed to be the subject distinguished name from the certificate. If an X509 Certificate mapping is not found, the entire policy entry granting permissions to the specified principal is ignored.

Adding a New Principal

To add a new principal, select the Add Principal button in the "Policy Entry" dialog box. This brings up the "Principals" dialog box:

Blank Add Principals Dialog

To add the principal:

  1. Type or select a principal type.

    The drop-down list labeled "Principal Type:" contains a list of built-in principal types. If you want such a type, select it from the list, and the complete principal type name appears in the text box to the right of the drop-down list.

    If you instead want to specify a principal type defined by you or others, type the principal type into the text box.

  2. Type a principal name.

    Type the principal name directly into the text box to the right of the "Principal Name:" text box. For example, to specify the principal named duke, type

    duke

When you are done specifying the principal information, select the OK button (or Cancel to cancel). The new principal appears in a line in the "Principals" entry.

You can then add additional principals by following the same sequence of steps. Or you can edit or remove an existing principal.

Editing a Principal

To edit an existing principal, select the line for that principal in the "Principals:" entry, then select the Edit Principal button. Alternatively, you can simply double-click the line for that principal.

This brings up the same type of "Principals" dialog box as appears when you are adding a new principal, except in this case the dialog box is filled in with the existing principal information. To change the information, either make new selections from the drop-down lists or replace the information in the text boxes.

When you are done, select the OK button (or Cancel to cancel changes). The Principals:" entry now shows the principal with your modifications.

Removing a Principal

To remove an existing principal, select the line for that principal in the "Principals:" entry, then select the Remove Principal button.

Adding a New Permission

To add a new permission, select the Add Permission button in the "Policy Entry" dialog box. This brings up the "Permissions" dialog box:

Blank Add Permissions Dialog

To add the permission:

  1. Type or select a permission type.

    The drop-down list labeled "Permission:" contains a list of built-in permission types. If you want such a type, select it from the list, and the complete permission type name appears in the text box to the right of the drop-down list.

    If you instead want to specify a permission type defined by you or others, type the permission type into the text box.

  2. Type or select a permission target name.

    If you selected a built-in permission from the "Permission:" drop-down list, and permissions of that type have specific target name values, then the drop-down list labeled "Target Name:" contains a list of those values, from which you can choose.

    In some cases, where the target name possibilities are infinite but there are some built-in target name specifications that have special meaning, such target names will appear in the drop-down list. For example, the special target name of "<<All Files>>" will appear in the list for File Permissions.

    To specify a target name not available in the drop-down list, type the target name directly into the text box to the right of the "Target Name:" drop-down list. For example, to specify the file named data in the /JavaSoft/ptTest/ directory, type

      /JavaSoft/ptTest/data
  3. Type or select one or more actions, if actions are relevant.

    Some permissions just have a target name, but no actions. For such permissions, leave the text box to the right of the "Actions:" drop-down list blank. (It will automatically be darkened and unavailable for this type of built-in permission.)

    For permissions requiring action specifications, type the comma-separated list of actions into the text box, or select them from the drop-down list. For example, to specify both read and write access to a file specified for a File Permission, first select read (or write, order doesn't matter) from the list. The word "read" appears in the text box. Then select write, and the word "write" will be appended, preceded by a comma and a space.

  4. Type a SignedBy alias into the text box to the right of the "Signed By" label, if required. The SignedBy value for a permission entry is optional. If present, it indicates a signed permission. That is, the permission class itself must be signed by the given alias(es) in order for the permission to be granted.

When you are done specifying the permission information, select the OK button (or Cancel to cancel). The new permission appears in a line in the "Policy Entry" dialog.

You can then add additional permissions by following the same sequence of steps. Or you can edit an existing permission or remove a permission.

Editing a Permission

To edit an existing permission, select the line for that permission in the "Policy Entry" dialog box, then select the Edit Permission button. Alternatively, you can simply double-click the line for that permission.

This brings up the same type of "Permissions" dialog box as appears when you are adding a new permission, except in this case the dialog box is filled in with the existing permission information. To change the information, either make new selections from the drop-down lists or replace the information in the text boxes.

When you are done, select the OK button (or Cancel to cancel changes). The "Policy Entry" dialog now shows the permission with any modifications you made.

Removing a Permission

To remove an existing permission, select the line for that permission in the "Policy Entry" dialog box, then select the Remove Permission button.

Completing the Addition of a Policy Entry

Once you are done adding a policy entry, select the Done button in the "Policy Entry" dialog, or Cancel to cancel.

If you selected Done, the "Policy Tool" window now contains a line representing the policy entry. The line contains the CodeBase, SignedBy and Principals information (if any). If none was specified in the "Policy Entry" dialog, just

  CodeBase <ALL>

appears.

Note: a warning is displayed upon closing the policy entry if it contains any SignedBy aliases that don't yet exist in your keystore. Select OK and make a note to create such an alias, or edit the policy entry to fix the alias if was wrong.

Editing a Policy Entry

To edit an existing policy entry, select the line for that entry in the main "Policy Tool" window, then select the Edit Policy Entry button. Alternatively, you can simply double-click the line for that entry.

This brings up the same type of "Policy Entry" dialog box as appears when you are adding a new policy entry, except in this case the dialog box is filled in with the existing policy entry information. To change the information, simply retype it (for the CodeBase and SignedBy values) or use the buttons (for the Principals and Permissions values).

When you are done, select the Done button (or Cancel to cancel).

Removing a Policy Entry

To delete a policy entry from the policy file, select the line for that entry in the main "Policy Tool" window, then select the Remove Policy Entry button.

The complete policy entry is displayed, and you can then either select OK to remove the entry, or Cancel to keep it.

Saving the Policy File

To save changes to an existing policy file, simply select the Save command in the File menu.

To save a new policy file you've been creating, or to copy an existing policy file to a new policy file with a different name, select the Save As command from the File menu. This brings up the Save As dialog box.

Navigate the directory structure to get to the directory in which you want to save the policy file. Type the desired file name, then select the OK button. The policy file is now saved, and its name and path are shown in the text box labeled "Policy File:"

Exiting the Policy Tool

To exit Policy Tool, select the Exit command from the File menu.

Viewing the Warning Log

If Policy Tool ever reports that warnings have been stored in the Warning Log, you can view the log by selecting the View Warning Log command in the File menu.

For example, if you have a policy file with a Keystore URL specifying a keystore that doesn't yet exist, you will get such a warning at various times, e.g., when you open the file. You can continue to work on the policy file even if warnings exist.

Examples

The following examples show how to

  • create the user policy file from scratch
  • add a policy entry
  • specify a keystore
  • add a policy entry for signed code
  • add a policy entry for authenticated code
  • save the user policy file, and
  • exit the Policy Tool

Starting Creation of the User Policy File

Initially, there is no user policy file (unless you created one manually). So to create the user policy file, first simply start Policy Tool by typing the following at the command line.

  policytool

This brings up the "Policy Tool" window.

Whenever Policy Tool is started, it tries to fill in this window with policy information from what is sometimes referred to as the "user policy file". The user policy file is by default a file named .java.policy in your home directory. If Policy Tool cannot find the user policy file, it reports the situation and displays a blank "Policy Tool" window (that is, a window with headings and buttons but no data in it):

Blank Policy Tool window

You can now create the user policy file by adding entries and saving the file.

Adding a Policy Entry

Suppose you want to grant all classes from the /tests/ directory permission to read the file named mydata in the /temp/data/ directory. To do so, first select the Add Policy Entry button in the main "Policy Tool" window.

This brings up a "Policy Entry" dialog box:

Blank Add Entry Dialog

Using this dialog box, type the file URL

  file:/tests/

into the CodeBase text box.

Leave the SignedBy text box blank, since you aren't requiring the code to be signed.

Leave the Principals list blank, since you aren't requiring the code to be authenticated.

To add the permission, select the Add Permission button. This brings up the "Permissions" dialog box:

Blank Add Permissions Dialog

To add the permission:

  1. Select "File Permission" from the "Permission:" drop-down list. The complete permission type name (java.io.FilePermission) now appears in the text box to the right of the drop-down list.
  2. Type the following in the text box to the right of the list labeled "Target Name:":
      /temp/data/mydata
  3. Specify read access by either selecting "read" from the "Actions:" drop-down list or directly typing "read" into the text box to the right of the "Actions:" drop-down list.

Now the "Permission" dialog box looks like the following:

First File Permission

When you are done specifying the permission information, select the OK button. The new permission appears in a line in the "Policy Entry" dialog.

First Policy Entry

You are now done specifying this policy entry, so select the Done button. The "Policy Tool" window now contains a line representing the policy entry. The line just contains the CodeBase value:

Policy Tool with one CodeBase

Specifying a Keystore

Suppose you also want to grant any code from the URL "http://java.sun.com/" and signed by the alias "duke" read access to all files in the /tmp/ directory. Suppose you also want to give such code permission to initiate outgoing socket connections to any hosts. You need to do two things:

  1. Specify the keystore containing the alias, and
  2. Create the policy entry granting the permissions.

To specify the keystore containing the key information for the aliases specified in any SignedBy parts of policy entries, select the Edit command in the Keystore menu of the main "Policy Tool" window.

This brings up a dialog box in which you specify the new keystore URL and optionally the keystore type.

As an example, to specify the keystore named "mykeystore" in the /tests/ directory, type the following file: URL into the text box labeled "New KeyStore URL":

  file:/tests/mykeystore

If the keystore type is the default type, as specified by the "keystore.type" property value in the security properties file, you don't need to type a "New KeyStore Type" value. The default value of that property is "JKS" (the proprietary keystore type supported by Sun Microsystems).

To specify the keystore type, type its value into the text box labeled "New KeyStore Type." For example, to indicate that the keystore type is "JKS" type

  JKS

The result is:

When you are done specifying the keystore URL and type, select OK. The text box labeled "Keystore:" is now filled in with the URL and type.

Next, you need to specify the policy entry:

Adding a Policy Entry with a SignedBy Alias

Select the Add Policy Entry button in the main "Policy Tool" window. This brings up the "Policy Entry" dialog box. Type the following into the CodeBase text box:

  http://java.sun.com/*

The "*" indicates that both class and JAR files in the specified directory are to be considered to match this CodeBase.

Now, type the following alias into the SignedBy text box:

  duke

Leave the Principals list blank, since you aren't requiring the code to be authenticated.

To add the first permission, select the Add Permission button. This brings up the "Permissions" dialog box. Do the following

  1. Select "File Permission" from the "Permission:" drop-down list. The complete permission type name (java.io.FilePermission) now appears in the text box to the right of the drop-down list.
  2. Type the following in the text box to the right of the list labeled "Target Name:" to specify all files in the /tmp/ directory:
      /tmp/*
  3. Specify read access by selecting "read" from the "Actions:" drop-down list.

Now the "Permissions" dialog box looks like the following:

Second File Permission

Select the OK button. The new permission appears in a line in the "Policy Entry" dialog.

Now you need to add the other permission. Select the Add Permission button. In the "Permissions" dialog box, do the following

  1. Select "Socket Permission" from the "Permission:" drop-down list. The complete permission type name (java.net.SocketPermission) now appears in the text box to the right of the drop-down list.
  2. Type the following in the text box to the right of the list labeled "Target Name:" to specify all hosts:
      *
  3. Specify permission to make connections by selecting "connect" from the "Actions:" drop-down list.

Now the "Permissions" dialog box looks like the following:

Select the OK button. The new permission appears in a line in the "Policy Entry" dialog.

Policy Entry with Two Permissions

You are now done specifying this policy entry, so select the Done button in the "Policy Entry" dialog. The "Policy Tool" window now contains a line representing the policy entry, showing the CodeBase, SignedBy and Principals values.

Policy Tool with Two Entries

Adding a Policy Entry with a Principal

Suppose you want to grant the principal whose X500 name is

CN=Duke,OU=JavaSoft,O=Sun Microsystems,C=US

permission to write to the /tmp/ directory.

Select the Add Policy Entry button in the main "Policy Tool" window. This brings up the "Policy Entry" dialog box.

Leave the CodeBase text box blank since you aren't limiting where the code comes from.

Leave the SignedBy text box blank since you aren't requiring the code to be signed.

Select the Add Principal button. In the "Principals" dialog box, do the following

  1. Select "X500Principal" from the "Principal Type:" drop-down list. The complete principal type name (com.sun.security.auth.X500Principal) now appears in the text box to the right of the drop-down list.
  2. Type the following in the text box to the right of the list labeled "Principal Name:" to specify an X500 name for the X500Principal:
    CN=Duke,OU=JavaSoft,O=Sun Microsystems,C=US

Now the "Principals" dialog box looks like the following:

Select the OK button. The new principal appears in a line in the "Principals" list.

Policy Entry with One Principal

To add the permission, select the Add Permission button. This brings up the "Permissions" dialog box. Do the following

  1. Select "File Permission" from the "Permission:" drop-down list. The complete permission type name (java.io.FilePermission) now appears in the text box to the right of the drop-down list.
  2. Type the following in the text box to the right of the list labeled "Target Name:" to specify all files in the /tmp/ directory:
      /tmp/*
  3. Specify write access by first selecting "write" from the "Actions:" drop-down list.

Select the OK button. The new permission appears in a line in the "Policy Entry" dialog.

Policy Entry with One Principal and one Permission

You are now done specifying this policy entry, so select the Done button in the "Policy Entry" dialog. The "Policy Tool" window now contains a line representing the policy entry, showing the CodeBase, SignedBy and Principals values.

Policy Tool with Three Entries

Saving the User Policy File

Let's assume you want to save the policy file you've been creating with the default name (.java.policy) in the default location (your home directory).

To save the user policy file, select the Save As command from the File menu. This brings up the Save As dialog box.

Navigate the directory structure to get to your home directory. Type

  .java.policy

(note the initial period) as the file name, then select the OK button. The policy file is now saved, and its name and path are shown in the text box labeled "Policy File:".

Policy Tool with Three Entries, Keystore, and Policy File Name

Exiting Policy Tool

When you want to exit Policy Tool, do so by selecting the Exit command from the File menu.

See Also

  • Permissions in the Java ™ Development Kit
  • Default Policy Information and Policy File Syntax
  • keytool tool man page
  • Security Architecture Specification
  • The Security trail of the Java Tutorial for examples of the use of the security tools including Policy Tool
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


policytool - Policy File Admin GUI

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

policytool - PolicyTool Administration GUI Utility

policytool reads and writes a plain text policy file based on user input via the utility GUI.
  • Synopsis
  • Description
  • Options
  • See Also

SYNOPSIS

Run the policytool Administrator's utility
policytool
Run policytool and load the specified policy file
policytool[-file][filename]

where:
file
directs policytool to load a local policy file
filename
The file name

DESCRIPTION

policytool is an Administrator's GUI that allows system administrators to manage the contents of local policy files. A policy file is a plain-text file with a .policy extension, that maps remote requestors by domain, to permission objects. For details, see Default Policy Implementation and Syntax.

OPTIONS

file
Loads filename.

SEE ALSO

Default Policy Implementation and Syntax
Policy Tool Users' Guide
Security Permissions
Security Overview
Security Architecture
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Popup & PopupFactory

The bugtraq report that corresponds to this change is: 4303635.

Certain Components, such as JPopupMenu and JToolTip, present themselves above all other Components in a particular containment hierarchy. Rather than each of these Components containing the same code to obtain the same behavior, they delegate to a Popup which can be obtained from a PopupFactory. A Popup is able to display a Component at a particular location on the screen. Based on the size and location of the requested Component, PopupFactory returns an appropriate Popup.

Previously, Popup and PopupFactory were package private. For JDK 1.4, we have exposed these classes to enable custom look and feel implementations to create their own Popups. This allows other look and feels to position menus in an appropriate manner for their look and feel. To this end, we have made these classes public:

public class PopupFactory {
    public static void setSharedInstance(PopupFactory factory);
    public static PopupFactory getSharedInstance();
    public Popup getPopup(Component owner, Component contents, int x, int y) throws IllegalArgumentException;
    }

public class Popup {
    protected Popup(Component owner, Component contents, int x, int y);
    protected Popup();
    public void show();
    public void hide();
    }

To enable the Popup used by JPopupMenu to be replaced by the UI, we added the following to PopupMenuUI:

    public Popup getPopup(JPopupMenu popup, int x, int y);

PopupMenuUI.getPopup's implementation obtains the Popup from the shared PopupFactory, but custom look and feel implementations may override this and return whatever Popup they desire.

Semantic Changes

JPopupMenu previously defined the method setLocation. Prior to this release, this method would invoke setLocation on the Popup, but as we have removed this method from Popup, JPopupMenu now recreates the Popup.

JPopupMenu also defined the method setPopupSize, which invoked setSize on the Popup if it was visible. Internally, we changed this method to set the preferred size of the JPopupMenu, which gives the same results. If the JPopupMenu is visible when this is invoked, the Popup will be recreated. The JPopupMenu javadoc changed to reflect the new behavior:

    public void setPopupSize(Dimension d);

    public void setPopupSize(int width, int height);
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Swing Changes Since Java 2 SDK, v1.4

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Swing Changes Since Java™ 2 SDK, Standard Edition, v 1.4

The Swing Changes and New Features for Java 2 SDK, Standard Edition, v 1.4 document describes changes for all the 1.4.* releases. This document provides links to changes specific to the 1.4.1 and 1.4.2 releases.

Changes for the Incremental Release, Java 2 SDK, S.E., v1.4.1

For Swing, this release primarily features bugfixes. Bugs that have been fixed include:

Focus related bugs:

  • 4632782: JPopupMenu may now be prevented from taking focus
  • 4628933: Heavy weight windows may lose focus when running on some versions of Microsoft Windows with a remote display application
  • 4659800: Default button should follow the focus on Microsoft Windows look and feel
  • JTabbedPane and Focus Clarification

Drag and drop related bugs:

  • 4513715: Drop no longer clobbers selected text
  • 4513638: Cut/copy/drag fixed for JEditorPane with RTFEditorKit
  • Import/export behavior has changed for the JEditorPane component

Miscellaneous:

  • 4532517: Workaround for input verifier bug
  • 4419964, 4668963: Metal look and feel can now pick up font sizes from the desktop on Microsoft Windows
  • 4615396: Some locales will only honor font size from the desktop
  • 4668511: Deadlock in JColorChooser
  • 4218431: Document that multiple file selection is supported in JFileChooser

Changes for the Incremental Release, Java 2 SDK, S.E., v1.4.2

In addition to many bugfixes, this release features these new enhancements:

JFileChooser Performance Enhancements

The bugtraq reports that correspond to this change are: 4679673 and 4712307.

This release features many performance improvements to JFileChooser. In some situations, JFileChooser now performs 300 times faster.

Windows XP look and feel

Release 1.4.2 introduces support for the standard Microsoft Windows XP appearance as the default when running on the Windows XP platform. This look and feel automatically appears if your app is using Swing's WindowsLookAndFeel class (either by way of UIManager.getSystemLookAndFeelClassName() or by explicitly using com.sun.java.swing.plaf.windows.WindowsLookAndFeel) on a machine running the Windows XP operating system. The following example illustrates the preferred way of setting the look and feel to match that of the native platform:

  UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

If you prefer your Swing app to look like a classic Windows app you can turn of the XP look using the system property swing.noxp=true. This is typically used as a command line parameter, eg:

  java -Dswing.noxp=true -jar SwingSet2.jar

Note that the swing.noxp property may not be supported in future releases.

GTK+ look and feel

Release 1.4.2 introduces a look and feel based on GTK+ 2.0. In order to get this look and feel you need to explicitly ask for it by way of UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel") or by defining the system property swing.defaultlaf to be com.sun.java.swing.plaf.gtk.GTKLookAndFeel. In the next release we will make UIManager.getSystemLookAndFeelClassName() return this look and feel when appropriate.

The GTK+ look and feel can be customized by way of resource files. Swing's GTK+ look and feel uses the following algorithm to locate the resource files:

  1. If the system property swing.gtkthemefile exists, parse it and stop, for example: java -Dswing.gtkthemefile=/tmp/customTheme -jar SwingSet2.jar.
  2. If the file user.home/.gtkrc-2.0 exists, parse it and continue.
  3. Determine the user selected theme name (THEMENAME) by way of the desktop property gnome.net/ThemeName which is determined using XSETTINGS. If this property is null, use Default as THEMENAME.
    1. If the file user.home/.themes/THEMENAME/gtk-2.0/gtkrc exists parse it and stop.
    2. If the system property swing.gtkthemedir exists and the file swing.gtkthemedir/THEMENAME/gtk-2.0/gtkrc exists, parse it and stop.
    3. If the system property swing.gtkthemedir doesn't exist and the file /usr/share/themes/THEMENAME/gtk-2.0/gtkrc exists, parse it and stop.
    4. Lastly if swing.gtkthemedir is defined parse swing.gtkthemedir/THEMENAME/gtk/gtkrc, otherwise parse /usr/share/themes/THEMENAME/gtk/gtkrc.

One way GTK+ can be customized is by way of a theme engine. A handful of engines exist. In 1.4.2, Swing supports theme files for Default, pixmap, and bluecurve engines. We are investigating ways to open up the API to allow for the creation of additional GTK engines. Visit http://www.themes.org for examples.

GTK+ allows for specifying fonts in two ways: using an XLFD or using a pango string. Pango provides for facilities similar to the composite Fonts on the Java platform, that is, a font that consists of a number of different fonts for different code points. Because pango's composite fonts do not exactly match Java's composite fonts, a Swing app with the GTKLookAndFeel will not exactly match a native GTK+ app. We are investigating ways to deal with this. One option is to replace your pango font file with a version equivalent to Java's font.properties file. Additionally we currently ignore XLFDs and pass Pango strings (after mapping sans to sansserif and monospace to monospaced) directly to a java.awt.Font.

GTK+ does not provide MDI (JInternalFrame) capabilities nor does it directly support theming of top level windows, rather that is left up to the WindowManager. For Swing's MDI classes we support theming by way of Metacity. We currently only support the Crux and Bluecurve themes. If we can not locate either of these themes we fall back to our own custom theme. You can use the system property swing.metacitythemename to name a particular theme to use, otherwise we will look in user.dir/.gconf/apps/metacity/general/%gconf.xml to determine the name of theme and look in /usr/share/themes/THEMENAME/metacity-1/metacity-theme-1.xml or /usr/gnome/share/themes/THEMENAME/metacity-1/metacity-theme-1.xml for the actual resource file. The following example shows how to trigger Swing to use a specific metacity theme:

  java -Dswing.metacitythemename=Bluecurve -jar SwingSet2.jar

GTK+ resource files allow for customizing a number of look and feel options beyond the look. In 1.4.2 we support the primary style configurations (fg, bg, base ..), gtk-font-name, gtk-icon-sizes, stock icons (for optionpane), focus-line-width, focus-padding, focus-line-pattern, internal-padding, shadow-type (for menubars), and trough-border.

GTK provides a mechanism for which running applications can pick up a theme change and automatically update the UI, this will be supported in a future version of Swing's GTK look and feel.

GTK Incompatabilities

Correctly supporting a GTK+ look and feel posed a number of challenges to Swing's current architecture. In Swing an opaque component ALWAYS paints its background by way of ComponentUI's update method, in GTK+ a nonopaque component may or may not paint the background, depending upon the engine. To correctly mirror GTK+ a number of Components that previously were opaque have been made nonopaque (by way of the ComponentUI subclass's installUI method). Additionally because the look of a component can change based on the containment hierarchy the opacity may change after the constructor has completed. A ramification of this is that if you invoke setOpaque() on a component, it may change out from under you. We will fix this in the next release.

GTK+ calls into the engine to paint border decorations before the actual contents of the widget are painted. Some engines, most notably the pixmap engine, rely on this ordering to correctly render decorations behind the contents. In Swing the border is rendered after the widget contents are painted. In the GTKLookAndFeel we install a Border only to provide space, and let the UI do the actual rendering of the border decorations as part of the paint method. The ramification of this is that if you install a Border on a widget with the GTKLookAndFeel you will likely not get the effect you are after. Again, we are investigating alternatives and will provide a better solution in the next release.

1.4.2 Bugs

One bug worth mentioning:
  • 4759306: JColorChooser.setPreviewPanel does not remove the old one.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Preface

The Java Management Extensions (JMX) Technology Tutorial provides examples of how to use the main features of the JMX technology that is provided with the Java Platform, Standard Edition .

Before You Read This Book

The Java Management Extensions (JMX) Technology Tutorial demonstrates the concepts and technology that are introduced in the Java Management Extensions (JMX) Technology Overview. You should, therefore, read the overview before attempting to work through this tutorial. To make full use of the information in this tutorial, you should be familiar with the following protocols and specifications:

  • Remote Method Invocation (RMI)
  • Lightweight Directory Access Protocol (LDAP)
  • Service Location Protocol (SLP)
  • JiniTM Network Technology
  • Java Naming and Directory InterfaceTM (JNDI) API
  • Java Secure Socket Extension (JSSE)
  • Java Authentication and Authorization Service (JAAS)

How This Book Is Organized

This tutorial provides examples in broad categories, presented in the following chapters.

  • Chapter 1, "Getting Started" gives you some initial configuration information.
  • Chapter 2, "Essentials of the JMX API" introduces the core notions of the JMX specification.
  • Chapter 3, "JMX Connectors" provides examples of how to implement the standard and dynamic types of MBean, and perform operations on them both locally and remotely.
  • Chapter 4, "Lookup Services" demonstrates the lookup services that can be used in conjunction with the JMX technology.
  • Chapter 5, "Security" shows some examples of security configurations.

Related Documentation

This tutorial is accompanied by the following documents:

  • Java Management Extensions Technology Overview
  • Java Management Extensions Specification 1.4

About This Tutorial

As previously stated, this tutorial demonstrates some of the concepts that are described in the Java Management Extensions (JMX) Technology Overview. This tutorial is intended to be read in order, from beginning to end, working through the examples as you go. Actions you perform at the beginning of the tutorial might be required parts of subsequent examples. Consequently, starting mid-way through the tutorial might cause you to skip actions required by certain examples.

Where you are required to perform a task, the instructions are presented in bold text and marked with an action number; sub-tasks are marked with a lower-case letter, as shown in the following example:

  2. Perform a task.

    Description of how to perform that task.

    2. Perform a sub-task.

      Description of how to perform that sub-task.

    • Perform another task.

    • And so on

Typographic Conventions

Typeface | Meaning | Examples
AaBbCc123 | The names of commands, files, and directories; on-screen computer output | Edit your .login file. Use ls -a to list all files. % You have mail.
AaBbCc123 | What you type, when contrasted with on-screen computer output | % su Password:
AaBbCc123 | Book titles, new words or terms, words to be emphasized Command-line variable; replace with a real name or value | Read Chapter 6 in the User’s Guide. These are called class options. You must be superuser to do this. To delete a file, type rm filename.

Shell Prompts

Shell | Prompt
C shell | machine_name%
C shell superuser | machine_name#
Bourne shell and Korn shell | $
Bourne shell and Korn shell superuser | #

Contents | Previous | Next

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.mirror.type.PrimitiveType (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.type.PrimitiveType

  • Packages that use PrimitiveType
    Package Description
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of PrimitiveType in com.sun.mirror.util

      Methods in com.sun.mirror.util that return PrimitiveType
      Modifier and Type Method and Description
      PrimitiveType Types.getPrimitiveType(PrimitiveType.Kind kind)
      Deprecated.
      Returns a primitive type.
      Methods in com.sun.mirror.util with parameters of type PrimitiveType
      Modifier and Type Method and Description
      void TypeVisitor.visitPrimitiveType(PrimitiveType t)
      Deprecated.
      Visits a primitive type.
      void SimpleTypeVisitor.visitPrimitiveType(PrimitiveType t)
      Deprecated.
      Visits a primitive type.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.mirror.type.PrimitiveType.Kind (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.mirror.type.PrimitiveType.Kind

  • Packages that use PrimitiveType.Kind
    Package Description
    com.sun.mirror.type
    Interfaces used to model types.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of PrimitiveType.Kind in com.sun.mirror.type

      Methods in com.sun.mirror.type that return PrimitiveType.Kind
      Modifier and Type Method and Description
      PrimitiveType.Kind PrimitiveType.getKind()
      Deprecated.
      Returns the kind of primitive type that this object represents.
      static PrimitiveType.Kind PrimitiveType.Kind.valueOf(String name)
      Deprecated.
      Returns the enum constant of this type with the specified name.
      static PrimitiveType.Kind[] PrimitiveType.Kind.values()
      Deprecated.
      Returns an array containing the constants of this enum type, in the order they are declared.

    • Uses of PrimitiveType.Kind in com.sun.mirror.util

      Methods in com.sun.mirror.util with parameters of type PrimitiveType.Kind
      Modifier and Type Method and Description
      PrimitiveType Types.getPrimitiveType(PrimitiveType.Kind kind)
      Deprecated.
      Returns a primitive type.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.PrimitiveTypeTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.PrimitiveTypeTree

  • Packages that use PrimitiveTypeTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of PrimitiveTypeTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type PrimitiveTypeTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitPrimitiveType(PrimitiveTypeTree node, P p)

    • Uses of PrimitiveTypeTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type PrimitiveTypeTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitPrimitiveType(PrimitiveTypeTree node, P p)
      R | SimpleTreeVisitor.visitPrimitiveType(PrimitiveTypeTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.PrimitiveValue (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.PrimitiveValue

  • Packages that use PrimitiveValue
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of PrimitiveValue in com.sun.jdi

      Subinterfaces of PrimitiveValue in com.sun.jdi
      Modifier and Type Interface and Description
      interface  BooleanValue
      Provides access to a primitive boolean value in the target VM.
      interface  ByteValue
      Provides access to a primitive byte value in the target VM.
      interface  CharValue
      Provides access to a primitive char value in the target VM.
      interface  DoubleValue
      Provides access to a primitive double value in the target VM.
      interface  FloatValue
      Provides access to a primitive float value in the target VM.
      interface  IntegerValue
      Provides access to a primitive int value in the target VM.
      interface  LongValue
      Provides access to a primitive long value in the target VM.
      interface  ShortValue
      Provides access to a primitive short value in the target VM.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.security.auth.PrincipalComparator (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.security.auth.PrincipalComparator

No usage of com.sun.security.auth.PrincipalComparator
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Java Print Service API User Guide: 5 - Printing and Streaming 2D Graphics

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT
CHAPTER 5

Printing and Streaming 2D Graphics

The Java 2D™ printing API is the java.awt.print package that is part of the Java™ 2 SE, version 1.2 and later. The Java 2D printing API provides for creating a PrinterJob, displaying a printer dialog to the user, and printing paginated graphics using the same java.awt.Graphics and java.awt.Graphics2D classes that are used to draw to the screen.

Many of the features that are new in the Java Print Service, such as printer discovery and specification of printing attributes, are also very important to users of the Java 2D printing API. To make these features available to users of Java 2D printing, the java.awt.print package has been updated for version 1.4 of the Java™ 2 SE to allow access to the Java™ Print Service from the Java 2D printing API.

Developers of Java 2D printing applications have four ways of using the Java Print Service with the Java 2D API:

  • Print 2D graphics using PrinterJob.
  • Stream 2D graphics using PrinterJob
  • Print 2D graphics using DocPrintJob and a service-formatted DocFlavor
  • Stream 2D graphics using DocPrintJob and a service-formatted DocFlavor
The Using PrinterJob to Print or Stream Graphics section explains the first two methods. The Using Service-Formatted Data section explains the other two methods.
CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 5 - Printing and Streaming 2D Graphics

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

Using PrinterJob to Print or Stream Graphics

The new API injava.awt.print consists of these new PrinterJob methods:
  • Static convenience methods to look up print services that can image 2D graphics, which are returned as an array of PrintService or StreamPrintServiceFactory objects depending on the method.
  • Methods to set and get a PrintService on a PrinterJob.
  • A pageDialog method that takes a PrintRequestAttributeSet parameter.
  • A printDialog method that takes a PrintRequestAttributeSet parameter.
  • A print method that takes a PrintRequestAttributeSet parameter.
Because the new printDialog and pageDialog methods take an attribute set, users can edit the initail attribute settings from the dialogs.

Applications can use PrinterJob to print 2D graphics to a printer or to an output stream. The lookupPrintServices method returns an array of PrintService objects, each of which represents a printer that can print 2D graphics. The lookupStreamPrintServices method returns an array of StreamPrintServiceFactory objects, each of which can return a StreamPrintService. An application uses the StreamPrintService to send print data to an output stream. As with printing documents, applications can use a StreamPrintService to transcode 2D graphics to other formats. This section discusses using PrinterJob to submit 2D graphics to a printer and to an output stream.

Printing 2D Graphics

The new pageDialog, printDialog, and print methods allow an application to initialize print settings and pass these settings to a dialog so that a user can update the settings before submitting the print request, as demonstrated by this code sample:

// Step 1: Set up initial print settings.
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
// Step 2: Obtain a print job.
PrinterJob pj = PrinterJob.getPrinterJob();
// Step 3: Find print services.
PrintService []services = PrinterJob.lookupPrintServices();
if (services.length > 0) {
        System.out.println("selected printer: " + services[0]);
        try {
        pj.setPrintService(service[0]);
        // Step 2: Pass the settings to a page dialog and print dialog.
        pj.pageDialog(aset);
        if (pj.printDialog(aset)) {
                // Step 4: Update the settings made by the user in the dialogs.
                // Step 5: Pass the final settings into the print request.
                pj.print(aset);
        }
        } catch (PrinterException(pe)) {
                System.err.println(pe):
        }
}
See Example: Print2DPrinterJob.java for the complete application.

Note that Step 4 in this code sample does not seem to correspond to any particular line of code. In fact, the user updates the print settings in the dialogs, and the updated settings are saved in the PrintRequestAttributeSet, aset.

One problem with using Java 2D and the Java Print Service together is that some attributes, such as number of copies, are defined in both APIs. If such an attribute is specified in a PrintRequestAttributeSet, it takes precedence over the same attribute specified in the PrinterJob. Note that if a user updates the number of copies in a print dialog, the PrinterJob is automatically updated to reflect that, which reconfirms the existing behavior.

The PageFormat specification also overlaps with the Java Print Service Media, MediaPrintableArea, and OrientationRequested attributes. If an application uses the Printable interface and the print(PrintRequestAttributeSet) method, the media, orientation, and imageable area attributes contained in the attribute set are added to a new PageFormat, which is passed to the print method of the Printable object. If an application uses the Pageable interface, the PageFormat does not change.

Streaming 2D Graphics

An application can also use a PrinterJob and a StreamPrintService to send print data to an output stream. This example is similar to the example in the previous section, except a StreamPrintService is used in place of a PrintService:

PrinterJob job = PrinterJob.getPrinterJob();
String psMimeType = "application/postscript";
FileOutputStream outstream;
StreamPrintService psPrinter;
StreamPrintServiceFactory []spsFactories =
        PrinterJob.lookupStreamPrintServices(psMimeType);
if (factories.length > 0) {
        try {
                outstream = new File("out.ps");
                psPrinter = factories[0].getPrintService(fos);
                // psPrinter can now be set as the service on a PrinterJob
        } catch (FileNotFoundException e) { }
}
job.setPrintService(service[0]); // if app wants to specify this printer.
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new Copies(2));
job.print(aset);
}

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 5 - Printing and Streaming 2D Graphics

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

Using Service-Formatted Data

You can print or stream 2D graphics encapsulated in a Pageable or Printable object using a DocPrintJob and a service-formatted DocFlavor. A DocFlavor can represent any kind of data, including Java objects. An implementation of the Pageable or Printable interface is a Java object. As discussed in the Specifying Document Types chapter, the Java Print Service API includes pre-defined DocFlavor object constants for print data in the form of a Java object. An application can look up print services or stream print services supporting this type of data, encapsulate the object in a Doc implemetation and submit it to the service in a DocPrintJob. The Printing the Service-Formatted Data section demonstrates printing the data. The Streaming Service-Formatted Print Data section demonstrates streaming the data. Registering for events on 2D graphics printing applications using DocPrintJob is done the same way as for document printing applications using DocPrintJob. See Registering for Events for more information.

Printing the Service-Formatted Data

To locate print services that can handle the service-formatted data, pass the appropriate service-formatted DocFlavor object constant to the lookupPrintServices method:

PrintService []services =
        PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PRINTABLE,
                                                        null);
The printing application implements the Printable interface. To create the Doc, use SimpleDoc, passing this in for the printData, the service-formatted DocFlavor constant for the DocFlavor, and an optional attribute set:

Doc  doc = new SimpleDoc(this, DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);
Create the DocPrintJob, and submit it to the service:

DocPrintJob pj = service[0].createPrintJob();
pj.print(doc);
See Example: Print2DGraphics.java for the complete application.

Streaming Service-Formatted Print Data

A stream print service can be used to export 2D graphics encapsulated in a Java object to another format. This example exports graphics in a Printable to Postscript:

DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE
StreamPrintServiceFactory []factories =
        StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor,
                                                        "application/postscript"));
if (factories.length == 0) {
        System.err.println("No suitable factories");
        System.exit(0);
}
try{
        FileOutputStream fos = new FileOutputStream("out.ps");
        StreamPrintService sps = factories[0].getPrintService(fos);
}
Doc  doc = new SimpleDoc(this, flavor, null);
sps.createPrintJob().print(doc);
See Example: Print2DtoStream.java for the complete application

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 4 - Printing and Streaming Documents

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT
CHAPTER 4

Printing and Streaming Documents

Before submitting a print job, an application needs to locate print services that have the capability to handle the print data. Once the appropriate service is located, the application obtains a print job from it and submits the print job to the service.

This chapter demonstrates how to print and stream documents by:

  • Locating appropriate services using the elements presented in the two previous chapters: Attributes and Document Flavors
  • Creating a print job
  • Submitting the print job to the printer or service
  • Registering for events on the print job or service.

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 4 - Printing and Streaming Documents

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

StreamPrintService Versus PrintService

The Java™ Print Service API includes a PrintService class and a StreamPrintService class. A StreamPrintService extends PrintService, and so a StreamPrintService can be used anywhere a PrintService can be used. However, PrintService and StreamPrintService are used for different purposes. APrintService is used to direct output to a printer; a StreamPrintService is used to export formatted print data to a stream, usually to a different format. When locating a StreamPrintService, you specify the required output format in the form of a MIME type argument and provide an OutputStream to receive the data. You do not provide a representation class when locating a StreamPrintService, as you do when locating a PrintService, because the output is always delivered to an OutputStream.

After locating a service, you obtain a print job and submit the print job to the service in the same way whether you are using a PrintService or a StreamPrintServie. The major differences between StreamPrintService and PrintService are in the way they are located. The next section discusses locating both print services and stream print services.

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 4 - Printing and Streaming Documents

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

Locating Services

An application locates a print service in a slightly differently way from locating a stream print service. The Discovering Print Services section explains locating print services. The Discovering Stream Prin t Services section explains locating stream print services.

Discovering Print Services

Before sending a print job to a printer, the application needs to find printers that have the capabilities to handle the print job. To print a double-sided document, the application first needs to find printers that have the double-sided printing capabili ty.

The javax.print.PrintServiceLookup class included in the Java Print Service API provides static methods that applications use to locate printers.

An application invokes the lookupPrintServices method of PrintServiceLookup with a DocFlavor and an AttrbuteSet:

DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(MediaSizeName.ISO_A4);
aset.add(new Copies(2));
PrintService[] service =
        PrintServiceLookup.lookupPrintServices(flavor,
                        aset);
This method returns an array of print services representing printers that have the capabilities specified in the attribute set and can print the data format specified in the doc flavor. See the Attributes c hapter and the Specifying Document Types chapter for more help in choosing a DocFlavor and creating an AttributeSet.

The base set of printers returned from the lookupPrintServices method are the same as the set of printers returned by the platform. For example, when using Windows NT, the set of returned printers is the same as the set of printers visible in the Windows Printer Control Panel. Likewise, when using Solaris, the returned printers are the same as those enumerated by the System V Unix "lpstat" command. However, since third parties can augment these sets, additional printers, such as JINI printers, can be retu rned.

After obtaining a suitable PrintService, the application can access its many query methods to determine what values are supported for attribute categories. The Obtaining a Print Job section explains how to g et a print job from the PrintService.

Discovering Stream Print Services

An application uses stream print services to convert print data to different formats. This is useful, for example, if you do not have a printer that can print the format of a particular piece of print data. This section demonstrates how to convert a GIF d ocument into Postscript using a StreamPrintService.

The StreamPrintServiceFactory class has a lookupStreamPrintServiceFactories method for locating stream print services. This method, like the lookupPrintServices method in PrintServiceLookup, takes a DocFlavor that represents the type of the input document --in this case, DocFlavor.INPUT_STREAM.GIF. Unlike lookupPrintServices, this method also takes a MIME type. This MIME type represents the format of the output. Since this example converts GIF to postscript, the MIME type is "application/postscript" ;. The DocFlavor class has the getMimeType method for returning the MIME type from a DocFlavor. The lookupStreamPrintServicesFactories method returns an array of StreamPrintServiceFactory objects, which are factories for StreamPrintService instances. This code sample demonstrates obtaining an array of StreamPrintServiceFactory objects that can return StreamPrintService objects able to convert a GIF image into PostScript:

DocFlavor flavor = DocFlavor.INPUT_STREAM.GIF;
String psMimeType = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();
StreamPrintServiceFactory[] psfactories =
        StreamPrintServiceFactory.lookupStreamPrintServiceFactories(
                flavor, psMimeType);
The StreamPrintServiceFactory object has an instance method called getPrintService that takes an OutputStream parameter and creates a StreamPrintService instance that writes to that stream:

FileOutputStream fos = new FileOutputStream(filename);
StreamPrintService psService = psfactories[0].getPrintService(fos);
The JDK V1.4 includes one stream print service that can export Postscript from graphics calls, such as through the Pageable and Printable interfaces. To verify the availability of this service, use the StreamPrintServiceFactory class to try to l ocate it. The Printing and Streaming 2D Graphics chapter discusses streaming 2D graphics.

StreamPrintService implements PrintService, which means you can use a StreamPrintService wherever you can use a PrintService. The application is responsible for closing the output stream after a job has printed to the stream. Once the stream is closed, th e StreamPrintService instance can no longer be used.

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 4 - Printing and Streaming Documents

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

Obtaining a Print Job

A print job is a submitted print request and includes one or more pieces of print data and a set of processing instructions. The Java Print Service represents a print job with the DocPrintJob object. Whether you are sending print data to a stream or to a printer, you create a print job in the same way: by calling createPrintJob on the service:

   DocPrintJob pj = pservices[0].createPrintJob();
An application obtains a print job from a service because the service only creates print jobs that are capable of handling data that the particular service can accept.

The DocPrintJob interface provides the print method, which takes a PrintRequestAttributeSet parameter and a Doc encapsulating the print data and the doc flavor:

   pj.print(doc, aset);
The next section discusses creating a Doc.
CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 4 - Printing and Streaming Documents

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

Creating a Doc

To create a Doc you must provide an implementation of the Doc interface. The Java Print Service API provides a convenient implementation of Doc called SimpleDoc. An application is not required to use the SimpleDoc implementation, but to ensure compliance with Doc, any Doc implementation must observe the same required semantics that SimpleDoc implements, which are:
  • Every Doc implemenation must implement all five methods of the Doc interface.
  • The Doc implementation must allow multiple threads to access the Doc object.
  • Every time a Doc method is called, it returns the same object. This means you do not return a new stream. Since there is only one input stream there can only be one consumer of the Doc.
  • The Doc returns a stream for the service if requested
  • The Doc checks if the data type matches the doc flavor
  • The attributes returned from getAttributes always override those passed in the print method.
Before creating a Doc, you need to load your document from the file. The representation class of the DocFlavor determines how you load the document from the file. In this case, the representation class is an InputStream:

   FileInputStream fis = new FileInputStream("java2dlogo.gif");
Once you have the stream, pass it to SimpleDoc with the DocFlavor and a DocAttributeSet, ifi you have one. If you don't have a DocAttributeSet, pass in null instead:

   Doc doc = new SimpleDoc(fis, flavor, null);
See Example: PrintGIF.java for an example of a custom Doc implementation.

The next section demonstrates how to register for events on your print job or service.

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 4 - Printing and Streaming Documents

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

Registering for Events

The Java Print Service API allows services to report two types of events to applications: printer status updates and print job progress updates. The events API, which includes the javax.print.event package and methods to register listeners on a service and DocPrintJob, follows the familiar listener model used in AWT.

Print Service Events

Print Service event listeners monitor a service's changes in status and report events as changes in the values of print service attributes. An application can monitor events on a print service by implementing the javax.print.event.PrintServiceAttributeListener interface and installing itself as a listener on a PrintService as shown in this example:

public class PrintPS implements PrintServiceAttributeListener {
        ...
        pservices[0].addPrintServiceAttributeListener(this);
        ...
        public void attributeUpdate(PrintServiceAttributeEvent e){
                // Do something if an attribute is updated
        }
...
The PrintServiceAttributeListener.attributeUpdate() method is called when print service attributes change. The service uses the PrintServiceAttributeListener interface to decide which events it supports.

An application can discover which print service attributes a service supports by using the same query methods it uses to discover which request attributes a service supports. For example, to discover if the service supports the QueuedJobCount attribute an application calls:

service.isAttributeCategorySupported(QueuedJobCount.class);
The service determines how frequently it reports updates on attributes. If many attributes are supported, the service might batch events, which means an application isn't guaranteed to receive a particular event. The delivered event contains only attributes that have changed in value, which means that static service attributes, such as the printer model, will never be reported in an event.

Print Job Events

Most printing clients are more interested in monitoring a print job than monitoring a service's status. A client can install two different kinds of listeners on a DocPrintJob: PrintJobAttributeListener and PrintJobListener.

PrintJobAttributeListener

PrintJobAttributeListener is similar to the service attribute listener: the job reports changes in attributes that implement the PrintJobAttribute interface. Usually these attributes are also print request attributes and are fixed over the lifetime of a print job. Only a few attributes, such as JobMediaSheetsCompleted, are likely to change. Since few clients are interested in this granularity of detail, and even fewer services support this capability, clients will most likely use PrintJobListener to monitor a job's progress.

PrintJobListener

PrintJobListener is easier to use than PrintJobAttributeListener because it delivers simple messages, such as printJobCompleted or printJobFailed. The interface has only six methods, each of which reports a significant but simple piece of information as an event. As a convenience, the adapter class, PrintJobAdapter, provides default implementations of these six methods.

One message in particular: printJobNoMoreEvents is unusual but useful. A client is often interested in knowing if a job has finished or failed. If possible, a service should deliver such "terminal" events, but sometimes the service cannot be sure if the job finished or failed, and a "completed" message is misleading in this case. For example, a job might be spooled to a network print service that has a queue that's not visible. In this case, the "no more events" message is not sufficient to say that the job has succeeded, but the client can at least infer that it is not known to have failed. The following example demonstrates adding a listener that monitors printJobNoMoreEvents messages:

public class PrintPS extends PrintJobAdapter{
        ...
        pj.addPrintJobListener(this);
        ...
        public void printJobNoMoreEvents(PrintJobEvent e){
                // Do something here
        }
...

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 4 - Printing and Streaming Documents

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

Submitting the Print Job

Once you have the Doc and DocPrintJob, you can call the DocPrintJob object's print method to submit the document to the service. The Submitting the Print Job to the Printer section completes the printin g example. The Submitting the Print Job to the Stream section completes the streaming example.

Submitting the Print Job to the Printer

This section completes the printing application explained in this chapter. This example prints five copies of a PostScript document, double-sided on A4 paper, and stapled.

       DocFlavor psFlavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
        aset.add(new Copies(2));
        aset.add(MediaSizeName.ISO_A4);
        aset.add(Sides.TWO_SIDED_LONG_EDGE);
        aset.add(Finishings.STAPLE);
        PrintService[] pservices = PrintServiceLookup.lookupPrintServices(psFlavor,
                                                        aset);
        if (services.length > 0) {
                DocPrintJob pj = pservices[0].createPrintJob();
                try {
                        FileInputStream fis = new FileInputStream("example.ps");
                        Doc doc = new SimpleDoc(fis, psFlavor, null);
                        pj.print(doc, aset);
                } catch (IOException e) {
                        System.err.println(e);
                } catch (PrintException e) {
                        System.err.println(e);
                }
        }
See Example: PrintPS.java for the complete application.

Submitting the Print Job to the Stream

This section completes the streaming example explained in this chapter. This example converts a GIF document to PostScript and embeds the specified printing attributes into the PostScript document.

       DocFlavor flavor = DocFlavor.INPUT_STREAM.GIF;
        String psMimeType = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();
        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
        aset.add(new Copies(2));
        aset.add(MediaSizeName.ISO_A4);
        aset.add(Sides.TWO_SIDED_LONG_EDGE);
        aset.add(Finishings.STAPLE);
        StreamPrintServiceFactory[] factories =
                StreamPrintServiceFactory.lookupStreamPrintServiceFactories(
                                flavor, psMimeType);
        if(factories.length==0) {
                System.err.println("No suitable factories");
                System.exit(0);
        }
        try {
                FileInputStream fis = new FileInputStream("java2dlogo.gif");
                String filename = "newfile.ps";
                FileOutputStream fos = new FileOutputSteam(filename);
                StreamPrintService sps= factories[0].getPrintService(fos);
                DocPrintJob pj = sps.createPrintJob();
                Doc doc = new SimpleDoc(fos, psFlavor, aset);
                pj.print(doc, aset);
        } catch (IOException e) {
                System.err.println(e);
        } catch (PrintException e) {
                System.err.println(e);
        }
}
See Example: PrintGIFtoStream.java for the complete application.

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Print Service API User Guide: 4 - Printing and Streaming Documents

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

Print Service Providers

Print Service Providers are third parties that write an implementation of the abstract class PrintServiceLookup and install it according to the SPI JAR file specification.

This class provides a standardized API for looking up instances of print services. For example an IPP print service provider, a JINI lookup service, or a JNDI-based directory service may each be implementations of this class which can return PrintServices.

The API is reasonably simple and generally requires implementation of the PrintServiceLookup class, and the PrintService interface, and DocPrintJob. The PrintService should also support the events defined by the Java Print Service API.

How much more code there is depends on the document types that are supported. If a printer wants to be able to print a JPEG image and the printer already has such capability in hardware, its little more than a case of properly spooling the data. However, to print 2D graphics, a class that can turn the graphics calls into a printer-formatted raster is a significant body of work.

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


PrintService (JNLP API Reference 1.7.0)

  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method
javax.jnlp

Interface PrintService

  • public interface PrintService
    PrintService provides methods for access to printing functions, even for applications that are running in the untrusted execution environment. Using this service, an application can submit a print job to the JNLP client. The client can then display this request to the user, and if accepted, queue the request to the printer.
    Since:
    1.0

    • Method Summary

      Methods
      Modifier and Type Method and Description
      java.awt.print.PageFormat getDefaultPage()
      Creates a new PageFormat instance and sets it to the default size and orientation.
      boolean print(java.awt.print.Pageable document)
      Prints a document using the given Pageable object
      boolean print(java.awt.print.Printable painter)
      Prints a document using the given Printable object
      java.awt.print.PageFormat showPageFormatDialog(java.awt.print.PageFormat page)
      Displays a dialog that allows modification of a PageFormat instance.

    • Method Detail

      • getDefaultPage

        java.awt.print.PageFormat getDefaultPage()
        Creates a new PageFormat instance and sets it to the default size and orientation.
        Returns:
        a PageFormat set to the default size and orientation.

      • showPageFormatDialog

        java.awt.print.PageFormat showPageFormatDialog(java.awt.print.PageFormat page)
        Displays a dialog that allows modification of a PageFormat instance. The page argument is used to initialize controls in the page setup dialog. If the user cancels the dialog then this method returns the original page object unmodified. If the user okays the dialog then this method returns a new PageFormat object with the indicated changes. In either case, the original page object is not modified.
        Parameters:
        page - the default PageFormat presented to the user for modification.
        Returns:
        the original page object if the dialog is cancelled; a new PageFormat object containing the format indicated by the user if the dialog is acknowledged.

      • print

        boolean print(java.awt.print.Pageable document)
        Prints a document using the given Pageable object
        Parameters:
        document - the pages to be printed. It can not be null.
        Returns:
        true if printing was successfull, false otherwise.

      • print

        boolean print(java.awt.print.Printable painter)
        Prints a document using the given Printable object
        Parameters:
        painter - the Printable called to render each page of the document.
        Returns:
        true if printing was successfull, false otherwise.
  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.


Uses of Interface org.w3c.dom.ProcessingInstruction (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.ProcessingInstruction

  • Packages that use ProcessingInstruction
    Package Description
    org.w3c.dom
    Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.

    • Uses of ProcessingInstruction in org.w3c.dom

      Methods in org.w3c.dom that return ProcessingInstruction
      Modifier and Type Method and Description
      ProcessingInstruction Document.createProcessingInstruction(String target, String data)
      Creates a ProcessingInstruction node given the specified name and data strings.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Java VisualVM

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java VisualVM - Profiling Applications

Java VisualVM presents data for local and remote applications in a tab specific for that application. You can have multiple application tabs open. Each application tab contains sub-tabs that display different types of information about the application.

Profiling applications

The Profiler tab of an application enables you to start and stop the profiling session of a local application. Profiling results are displayed in the Profiler tab. You can use the toolbar to refresh the profiling results, invoke garbage collection and save the profiling data.

By default the profiling tool is not running until you are ready to profile the application. You can choose from the following profiling options:

  • CPU Profiling. Choose this to profile the performance of the application.
  • Memory Profiling. Choose this to analyze the memory usage of the application. The results display the objects allocated by the application and the class allocating those objects.

When you start a profiling session, Java VisualVM attaches to the local application and starts collecting profiling data. When profiling results are available they are automatically displayed in the Profiler tab.

Using the toolbar

You can use the following buttons in the Profiling Results toolbar to work with profiling results:

  • Update Result Automatically. When active, the displayed profiling results are automatically updated at short intervals (about 2 seconds).
  • Update Result Now. Click to update results immediately.
  • Run Garbage Collection. Click to run garbage collection.
  • Reset Collected Results. Click to discard the already accumulated profiling results.
  • Take Snapshot. Click to take a snapshot of the current profile data. When you take a snapshot, the snapshot is opened in a new sub-tab.
  • Save Current View. Click to save the current view of the profiling results as a .png image file. When you click the button you are prompted to choose the location where you want to save the image.

Filtering profiling results

The filter box below the profiling results enables you to filter the displayed results according to the name of the method. To filter the results, enter a term in the method name filter box, select which filtering method to use and press Return. You can see and select previous filter terms by clicking the arrow to the right of the method name filter box.

Modifying profiling settings

The Java VisualVM profiling tool supplies default settings for profiling applications. You can view the default settings by selecting the Settings checkbox in the Profiler tab. You can modify the profiling settings when no profiling session is in progress.

CPU Profiling

This profile command returns detailed data on method-level CPU performance (execution time), showing the total execution time and number of invocations for each method. When analyzing application performance, Java VisualVM instruments all of the methods of the profiled application. Threads emit the "method entry" event when entering a method and generate the corresponding "method exit" event when exiting the method. Both of these events contain timestamps. This data is processed in real time.

Screenshot of Profiler tab showing CPU profiling results

screenshot of Profiler tab showing CPU profiling

Screenshot of Profiler tab showing CPU profiling settings

screenshot of Profiler tab showing CPU profiling

Memory Profiling

When you analyse memory usage, Java VisualVM starts instrumenting the loaded classes and displays the total number of objects allocated by each class (including array classes) in a table. For each class currently loaded class in the Java Virtual Machine (JVM), the profiling results display the size and number of objects allocated since the profiling session started. The results are automatically updated as new objects are allocated and as new classes are loaded.

Java VisualVM displays the number of objects as an absolute number and as a percentage. The bytes allocated are also displayed as a graph representing the percentage of bytes as well as the total number of bytes allocated by each class.

Screenshot of Profiler tab showing memory profiling results

screenshot of Profiler tab showing memory profiling

Screenshot of Profiler tab showing memory profiling settings

screenshot of Profiler tab showing memory profiling settings

Taking Profiler Snapshots

Java VisualVM enables you to take profiler snapshots to capture the results of a profiling session. A profiler snapshot captures the results at the moment the snapshot is taken. To take a snapshot, click the Take Snapshot of Collected Results button in the toolbar while a profiling session is in progress. When you take the snapshot, the snapshot opens as a tab in the application tab. A node for the snapshot also appears under the application node in the Applications window.

Screenshot of memory profiling snapshot

screenshot of memory profiling snapshot

Screenshot of CPU profiling snapshot

screenshot of CPU profiling snapshot

For more about profiler snapshots, see the following document:

  • Working with Snapshots
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL: Programming Guide

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Programming Guide

  • Getting Started: Hello World has a transient server
  • Example: Persistent Server
  • Example: POA-Tie Server-Side Model
  • Example: ImplBase Server-Side Model
  • Example: Interoperable Naming Service
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.javadoc.ProgramElementDoc (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.javadoc.ProgramElementDoc

    • Uses of ProgramElementDoc in com.sun.javadoc

      Subinterfaces of ProgramElementDoc in com.sun.javadoc
      Modifier and Type Interface and Description
      interface  AnnotationTypeDoc
      Represents an annotation type.
      interface  AnnotationTypeElementDoc
      Represents an element of an annotation type.
      interface  ClassDoc
      Represents a java class or interface and provides access to information about the class, the class's comment and tags, and the members of the class.
      interface  ConstructorDoc
      Represents a constructor of a java class.
      interface  ExecutableMemberDoc
      Represents a method or constructor of a java class.
      interface  FieldDoc
      Represents a field in a java class.
      interface  MemberDoc
      Represents a member of a java class: field, constructor, or method.
      interface  MethodDoc
      Represents a method of a java class.
      Methods in com.sun.javadoc that return ProgramElementDoc
      Modifier and Type Method and Description
      ProgramElementDoc TypeVariable.owner()
      Return the class, interface, method, or constructor within which this type variable is declared.
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

Appendix 1: JNDI Standard Environment Properties

Environment Configuration

Property Name | Description
java.naming.applet (Context.APPLET) | An instance of java.applet.Applet whose applet parameters are used to obtain some environment properties. See Chapter 6 for details. No default.

Program Configuration 2

Property Name | Description
java.naming.factory.initial (Context.INITIAL_CONTEXT_FACTORY) | Class name of initial context factory to use. See InitialContext . No default.
java.naming.factory.object (Context.OBJECT_FACTORIES) | Colon-separated list of class names of object factory classes to use. See NamingManager.getObjectInstance() and DirectoryManager.getObjectInstance() . Defaults to empty list.
java.naming.factory.state (Context.STATE_FACTORIES) | Colon-separated list of class names of state factory classes to use. See NamingManager.getStateToBind() and DirectoryManager.getStateToBind() . Defaults to empty list.
java.naming.factory.control (LdapContext.CONTROL_FACTORIES) | Colon-separated list of class names of response control factory classes to use. See ControlFactory.getControlInstance() . Defaults to empty list.
java.naming.factory.url.pkgs (Context.URL_PKG_PREFIXES) | Colon-separated list of package prefixes to use when loading in URL context factories. com.sun.jndi.url is always added to end of list. See NamingManager.getURLContext() . Defaults to empty list.

Access Configuration 3

Property Name | Description
java.naming.provider.url (Context.PROVIDER_URL) | Specifies configuration information for provider to use. Defaults to provider default, using provider's own configuration or discovery protocols.
java.naming.dns.url (Context.DNS_URL) | Specifies the DNS host and domain names. No default.

Service-Related

Property Name | Description
java.naming.authoritative (Context.AUTHORITATIVE) | Specifies the authoritativeness of the service requested. If "true", specifies most authoritative source is to be used (e.g., bypass any caches, or bypass replicas in some systems). Otherwise, source need not be (but can be) authoritative. Defaults to "false".
java.naming.batchsize (Context.BATCHSIZE) | Specifies the preferred batch size to use when returning data via the service's protocol. This is a hint to the provider to return the results of operations in batches of the specified size, so that the provider can optimize its performance and usage of resources. It does not affect the total number or size of the data returned. Defaults to provider default.
java.naming.referral (Context.REFERRAL) | Specifies that referrals encountered by the service provider are to be followed automatically. If "follow", follow referrals automatically. If "ignore", ignore referrals encountered. If "throw", throw ReferralException when a referral is encountered. Defaults to provider default.

Security

Property Name | Description
java.naming.security.protocol (Context.SECURITY_PROTOCOL) | Security protocol to use for service. Defaults to provider default.
java.naming.security.authentication (Context.SECURITY_AUTHENTICATION) | Takes values "none", "simple", "strong", or a provider-specific string (e.g., "CRAM-MD5 DIGEST-MD5 EXTERNAL"). Defaults to provider default.
java.naming.security.principal (Context.SECURITY_PRINCIPAL) | Identity of principal (e.g., user) for the authentication scheme. Defaults to provider default.
java.naming.security.credentials (Context.SECURITY_CREDENTIALS) | Principal's credentials for the authentication scheme. The particular type of credentials is determined by the authentication scheme chosen. Examples of different types of credentials are passwords, keys, and certificates. Defaults to provider default.

Internationalization

Property Name | Description
java.naming.language (Context.LANGUAGE) | Specifies a colon-separated list of preferred language to use with this service (e.g., "en-US", "fr", "fr-CH", "ja-JP-kanji"). Languages are specified using tags defined in RFC 1766. Defaults to provider default.

1. The Context and LdapContext interfaces define constants for these property names. The names of the constants are shown in parentheses below the property's string names.

2. These properties may be set in the Java runtime's system properties or in an applet's parameter list.

3. These properties may be set in the Java runtime's system properties or in an applet's parameter list.

CONTENTS | PREV | NEXT

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Object Serialization Specification: 6 - Object Serialization Stream Protocol

CONTENTS | PREV | NEXT Java Object Serialization Specification
version 6.0

Object Serialization Stream Protocol

CHAPTER 6

Topics:

  • Overview
  • Stream Elements
  • Stream Protocol Versions
  • Grammar for the Stream Format
  • Example

6.1 Overview

The stream format satisfies the following design goals:

  • Is compact and is structured for efficient reading.
  • Allows skipping through the stream using only the knowledge of the structure and format of the stream. Does not require invoking any per class code.
  • Requires only stream access to the data.

6.2 Stream Elements

A basic structure is needed to represent objects in a stream. Each attribute of the object needs to be represented: its classes, its fields, and data written and later read by class-specific methods. The representation of objects in the stream can be described with a grammar. There are special representations for null objects, new objects, classes, arrays, strings, and back references to any object already in the stream. Each object written to the stream is assigned a handle that is used to refer back to the object. Handles are assigned sequentially starting from 0x7E0000. The handles restart at 0x7E0000 when the stream is reset.

A class object is represented by the following:

  • Its ObjectStreamClass object.

An ObjectStreamClass object for a Class that is not a dynamic proxy class is represented by the following:

  • The Stream Unique Identifier (SUID) of compatible classes.
  • A set of flags indicating various properties of the class, such as whether the class defines a writeObject method, and whether the class is serializable, externalizable, or an enum type
  • The number of serializable fields
  • The array of fields of the class that are serialized by the default mechanismFor arrays and object fields, the type of the field is included as a string which must be in "field descriptor" format (e.g., "Ljava/lang/Object;") as specified in The Java Virtual Machine Specification.
  • Optional block-data records or objects written by the annotateClass method
  • The ObjectStreamClass of its supertype (null if the superclass is not serializable)

An ObjectStreamClass object for a dynamic proxy class is represented by the following:

  • The number of interfaces that the dynamic proxy class implements
  • The names of all of the interfaces implemented by the dynamic proxy class, listed in the order that they are returned by invoking the getInterfaces method on the Class object.
  • Optional block-data records or objects written by the annotateProxyClass method.
  • The ObjectStreamClass of its supertype, java.lang.reflect.Proxy.
The representation of String objects consists of length information followed by the contents of the string encoded in modified UTF-8. The modified UTF-8 encoding is the same as used in the Java Virtual Machine and in the java.io.DataInput and DataOutput interfaces; it differs from standard UTF-8 in the representation of supplementary characters and of the null character. The form of the length information depends on the length of the string in modified UTF-8 encoding. If the modified UTF-8 encoding of the given String is less than 65536 bytes in length, the length is written as 2 bytes representing an unsigned 16-bit integer. Starting with the Java 2 platform, Standard Edition, v1.3, if the length of the string in modified UTF-8 encoding is 65536 bytes or more, the length is written in 8 bytes representing a signed 64-bit integer. The typecode preceding the String in the serialization stream indicates which format was used to write the String.

Arrays are represented by the following:

  • Their ObjectStreamClass object.
  • The number of elements.
  • The sequence of values. The type of the values is implicit in the type of the array. for example the values of a byte array are of type byte.

Enum constants are represented by the following:

  • The ObjectStreamClass object of the constant's base enum type.
  • The constant's name string.

New objects in the stream are represented by the following:

  • The most derived class of the object.
  • Data for each serializable class of the object, with the highest superclass first. For each class the stream contains the following:
    • The serializable fields.See Section 1.5, "Defining Serializable Fields for a Class."
    • If the class has writeObject/readObject methods, there may be optional objects and/or block-data records of primitive types written by the writeObject method followed by an endBlockData code.

All primitive data written by classes is buffered and wrapped in block-data records, regardless if the data is written to the stream within a writeObject method or written directly to the stream from outside a writeObject method. This data can only be read by the corresponding readObject methods or be read directly from the stream. Objects written by the writeObject method terminate any previous block-data record and are written either as regular objects or null or back references, as appropriate. The block-data records allow error recovery to discard any optional data. When called from within a class, the stream can discard any data or objects until the endBlockData.

6.3 Stream Protocol Versions

It was necessary to make a change to the serialization stream format in JDK 1.2 that is not backwards compatible to all minor releases of JDK 1.1. To provide for cases where backwards compatibility is required, a capability has been added to indicate what PROTOCOL_VERSION to use when writing a serialization stream. The method ObjectOutputStream.useProtocolVersion takes as a parameter the protocol version to use to write the serialization stream.

The Stream Protocol Versions are as follows:

  • ObjectStreamConstants.PROTOCOL_VERSION_1: Indicates the initial stream format.

  • ObjectStreamConstants.PROTOCOL_VERSION_2: Indicates the new external data format. Primitive data is written in block data mode and is terminated with TC_ENDBLOCKDATA.

    Block data boundaries have been standardized. Primitive data written in block data mode is normalized to not exceed 1024 byte chunks. The benefit of this change was to tighten the specification of serialized data format within the stream. This change is fully backward and forward compatible.

JDK 1.2 defaults to writing PROTOCOL_VERSION_2.

JDK 1.1 defaults to writing PROTOCOL_VERSION_1.

JDK 1.1.7 and greater can read both versions.

Releases prior to JDK 1.1.7 can only read PROTOCOL_VERSION_1.

6.4 Grammar for the Stream Format

The table below contains the grammar for the stream format. Nonterminal symbols are shown in italics. Terminal symbols in a fixed width font. Definitions of nonterminals are followed by a ":". The definition is followed by one or more alternatives, each on a separate line. The following table describes the notation:

Notation | Meaning
(datatype) | This token has the data type specified, such as byte.
token[n] | A predefined number of occurrences of the token, that is an array.
x0001 | A literal value expressed in hexadecimal. The number of hex digits reflects the size of the value.
<xxx> | A value read from the stream used to indicate the length of an array.

Note that the symbol (utf) is used to designate a string written using 2-byte length information, and (long-utf) is used to designate a string written using 8-byte length information. For details, refer to Section 6.2, "Stream Elements".

6.4.1 Rules of the Grammar

A Serialized stream is represented by any stream satisfying the stream rule.

stream:
  magic version contents

contents:
  content
  contents content

content:
  object
  blockdata

object:
  newObject
  newClass
  newArray
  newString
  newEnum
  newClassDesc
  prevObject
  nullReference
  exception
  TC_RESET

newClass:
  TC_CLASS classDesc newHandle

classDesc:
  newClassDesc
  nullReference
  (ClassDesc)prevObject      // an object required to be of type
                             // ClassDesc

superClassDesc:
  classDesc

newClassDesc:
  TC_CLASSDESC className serialVersionUID newHandle classDescInfo
  TC_PROXYCLASSDESC newHandle proxyClassDescInfo

classDescInfo:
  classDescFlags fields classAnnotation superClassDesc

className:
  (utf)

serialVersionUID:
  (long)

classDescFlags:
  (byte)                  // Defined in Terminal Symbols and
                            // Constants

proxyClassDescInfo:
  (int)<count> proxyInterfaceName[count] classAnnotation
      superClassDesc

proxyInterfaceName:

  (utf)

fields:
  (short)<count>  fieldDesc[count]

fieldDesc:
  primitiveDesc
  objectDesc

primitiveDesc:
  prim_typecode fieldName

objectDesc:
  obj_typecode fieldName className1

fieldName:
  (utf)

className1:
  (String)object             // String containing the field's type,
                             // in field descriptor format

classAnnotation:
  endBlockData
  contents endBlockData      // contents written by annotateClass

prim_typecode:
  `B'	// byte
  `C'	// char
  `D'	// double
  `F'	// float
  `I'	// integer
  `J'	// long
  `S'	// short
  `Z'	// boolean

obj_typecode:
  `[`	// array
  `L'	// object

newArray:
  TC_ARRAY classDesc newHandle (int)<size> values[size]

newObject:
  TC_OBJECT classDesc newHandle classdata[]  // data for each class

classdata:
  nowrclass                 // SC_SERIALIZABLE & classDescFlag &&
                            // !(SC_WRITE_METHOD & classDescFlags)
  wrclass objectAnnotation  // SC_SERIALIZABLE & classDescFlag &&
                            // SC_WRITE_METHOD & classDescFlags
  externalContents          // SC_EXTERNALIZABLE & classDescFlag &&
                            // !(SC_BLOCKDATA  & classDescFlags
  objectAnnotation          // SC_EXTERNALIZABLE & classDescFlag&&
                            // SC_BLOCKDATA & classDescFlags

nowrclass:
  values                    // fields in order of class descriptor

wrclass:
  nowrclass

objectAnnotation:
  endBlockData
  contents endBlockData     // contents written by writeObject
                            // or writeExternal PROTOCOL_VERSION_2.

blockdata:
  blockdatashort
  blockdatalong

blockdatashort:
  TC_BLOCKDATA (unsigned byte)<size> (byte)[size]

blockdatalong:
  TC_BLOCKDATALONG (int)<size> (byte)[size]

endBlockData	:
  TC_ENDBLOCKDATA

externalContent:          // Only parseable by readExternal
  ( bytes)                // primitive data
    object

externalContents:         // externalContent written by
  externalContent         // writeExternal in PROTOCOL_VERSION_1.
  externalContents externalContent

newString:
  TC_STRING newHandle (utf)
  TC_LONGSTRING newHandle (long-utf)

newEnum:
  TC_ENUM classDesc newHandle enumConstantName

enumConstantName:
  (String)object

prevObject
  TC_REFERENCE (int)handle

nullReference
  TC_NULL

exception:
  TC_EXCEPTION reset (Throwable)object	 reset

magic:
  STREAM_MAGIC

version
  STREAM_VERSION

values:          // The size and types are described by the
                 // classDesc for the current object

newHandle:       // The next number in sequence is assigned
                 // to the object being serialized or deserialized

reset:           // The set of known objects is discarded
                 // so the objects of the exception do not
                 // overlap with the previously sent objects
                 // or with objects that may be sent after
                 // the exception

6.4.2 Terminal Symbols and Constants

The following symbols in java.io.ObjectStreamConstants define the terminal and constant values expected in a stream.

    final static short STREAM_MAGIC = (short)0xaced;
    final static short STREAM_VERSION = 5;
    final static byte TC_NULL = (byte)0x70;
    final static byte TC_REFERENCE = (byte)0x71;
    final static byte TC_CLASSDESC = (byte)0x72;
    final static byte TC_OBJECT = (byte)0x73;
    final static byte TC_STRING = (byte)0x74;
    final static byte TC_ARRAY = (byte)0x75;
    final static byte TC_CLASS = (byte)0x76;
    final static byte TC_BLOCKDATA = (byte)0x77;
    final static byte TC_ENDBLOCKDATA = (byte)0x78;
    final static byte TC_RESET = (byte)0x79;
    final static byte TC_BLOCKDATALONG = (byte)0x7A;
    final static byte TC_EXCEPTION = (byte)0x7B;
    final static byte TC_LONGSTRING = (byte) 0x7C;
    final static byte TC_PROXYCLASSDESC = (byte) 0x7D;
    final static byte TC_ENUM = (byte) 0x7E;
    final static  int   baseWireHandle = 0x7E0000;
The flag byte classDescFlags may include values of

    final static byte SC_WRITE_METHOD = 0x01; //if SC_SERIALIZABLE
     final static byte SC_BLOCK_DATA = 0x08;    //if SC_EXTERNALIZABLE
    final static byte SC_SERIALIZABLE = 0x02;
    final static byte SC_EXTERNALIZABLE = 0x04;
    final static byte SC_ENUM = 0x10;
The flag SC_WRITE_METHOD is set if the Serializable class writing the stream had a writeObject method that may have written additional data to the stream. In this case a TC_ENDBLOCKDATA marker is always expected to terminate the data for that class.

The flag SC_BLOCKDATA is set if the Externalizable class is written into the stream using STREAM_PROTOCOL_2. By default, this is the protocol used to write Externalizable objects into the stream in JDK 1.2. JDK 1.1 writes STREAM_PROTOCOL_1.

The flag SC_SERIALIZABLE is set if the class that wrote the stream extended java.io.Serializable but not java.io.Externalizable, the class reading the stream must also extend java.io.Serializable and the default serialization mechanism is to be used.

The flag SC_EXTERNALIZABLE is set if the class that wrote the stream extended java.io.Externalizable, the class reading the data must also extend Externalizable and the data will be read using its writeExternal and readExternal methods.

The flag SC_ENUM is set if the class that wrote the stream was an enum type. The receiver's corresponding class must also be an enum type. Data for constants of the enum type will be written and read as described in Section 1.12, "Serialization of Enum Constants".

Example

Consider the case of an original class and two instances in a linked list:

class List implements java.io.Serializable {
    int value;
    List next;
    public static void main(String[] args) {
        try {
            List list1 = new List();
            List list2 = new List();
            list1.value = 17;
            list1.next = list2;
            list2.value = 19;
            list2.next = null;

            ByteArrayOutputStream o = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(o);
            out.writeObject(list1);
            out.writeObject(list2);
            out.flush();
            ...
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
The resulting stream contains:

00: ac ed 00 05 73 72 00 04 4c 69 73 74 69 c8 8a 15 >....sr..Listi...<

10: 40 16 ae 68 02 00 02 49 00 05 76 61 6c 75 65 4c >Z......I..valueL<

20: 00 04 6e 65 78 74 74 00 06 4c 4c 69 73 74 3b 78 >..nextt..LList;x<

30: 70 00 00 00 11 73 71 00 7e 00 00 00 00 00 13 70 >p....sq.~......p<

40: 71 00 7e 00 03                                  >q.~..<

CONTENTS | PREV | NEXT
Copyright © 2005, 2010, Oracle and/or its affiliates. All rights reserved.


Protocol Support

This chapter includes the following topics:

  • HTTP, FTP, and GOPHER
  • HTTPS
  • Socks
  • NTLM Authentication

HTTP, FTP, and GOPHER

Java Plug-in supports HTTP, FTP, and GOPHER protocols, including built-in proxy configuration support.

HTTPS

Introduction

HTTPS is supported in Java Plug-in through Java Secure Socket Extension (JSEE), which provides a Java implementation of SSL and HTTPS for the Java platform.

Error handling support

When accessing an HTTPS server, errors may occur. Java Plug-in has hooked into JSSE to provide the following types of error handling:

  • Hostname mismatch: If the HTTPS server host name does not match the name on the server certificate, a warning dialog will appear.
  • Untrusted server certificate: If the server certificate can not be verified during the SSL handshaking, a warning dialog will appear.
  • Untrusted client certificate: In case client authentication is required by the server and the client certificate cannot be verified, a warning dialog will be appear.
  • Server authentication: If the client accesses a protected directory on the HTTPS server, the users will be prompted for a username and password. Note: Only basic authentication is currently supported.

Potential issues with HTTPS through JSSE

Although support of HTTPS through JSSE eliminates many browser-specific problems, there are several issues that developers should be aware of:

  • Untrusted server certificate: When SSL handshaking takes place in establishing an HTTPS connection, the server certificate is verified against the root CA store in Java SE. However, Java SE supports fewer root CA certificates than does the browser. As a result, you may have problems with untrusted server certificates.
  • Client authentication: Java Plugin supports browser keystore in JRE 1.5 or later. With browser keystore client authentication of HTTPS server is performed differently for Internet Explorer and Mozilla family browsers. For Internet Explorer the certificate is not imported into the JRE keystore. For Mozilla family browsers, a JSS package should be installed to read the certificate from the Mozilla keystore. By default browser keystore support is turned on.
  • Level of error handling: Java Plug-in currently handles the types of error listed in the previous section. However, if there are additional types of error that Java Plug-in doesn't recognize, the Java applet code may break.

Socks

Java Plug-in currently supports SOCKS version 4.

Note: For HTTP/HTTPS, a SOCKS proxy server may be used with a web proxy server to add caching. The behavior, however, may differ from that observed when running a similar configuration in a browser without Java Plug-in.

NTLM Authentication

Java Plug-in supports NTLM authentication protocol for HTTP/HTTPS. When attempting to access a server requiring NTLM authentication, the following dialog is displayed:

NTLM Authentication required. Provide your username, password and domain name

To authenticate enter User Name, Password and the Domain in the respective fields.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Proxy Configuration

Proxy Configuration covers the following topics:

  • Introduction
  • How Java Plug-in and Java Web Start Obtain Proxy Information
  • Manual Proxy Configuration
  • Automatic Proxy Configuration
  • java.net.ProxySelector API in J2SE 5.0

Introduction

For enterprise customers it is important to be able to set up secure computing environments within their companies, and proxy configuration is an essential part of doing that. Proxy configuration acts as a security barrier; it ensures that the proxy server monitors all traffic between the Internet and the intranet. This is normally an integral part of security enforcement in corporate firewalls within intranets. Enterprise customers who want to use Java Plug-in to deploy applets, or Java Web Start to run applications, on their intranet web pages may also set up proxy support. This support is required for Java Plug-in and Java Web Start to work in an intranet environment and can be set up through the Java Control Panel.

Java Control Panel

The Java Control Panel provides four proxy options via the Network Setting subpanel:

  • Use browser settings
  • Use proxy server
  • Use automatic proxy configuration script
  • Direct connection

Use browser settings

If "Use browser settings" is selected, then proxy information is entered entirely through the browser. For Internet Explorer, go to Tools>Internet Options ... and select the Connections tab and then LAN Settings ... ; for Netscape, go to Edit>Preferences ... and select Advanced under Category and then Proxies. How this works and the three types of connections that can be set up through the browser (Direct, Manual, and Automatic) are described in the following sections.

Use proxy Server

If you select "Use proxy server" in the Java Control Panel, you have two choices here:

  1. You can set the Address and the Port for a proxy server with the option to bypass it for local addresses.
  2. You can individually set the proxy server for HTTP, Secure, FTP, and Socks connections. You can also provide a list of addresses for which you do not want to use a proxy server.

Use automatic proxy configuration script

If you select "Use automatic proxy configuration script", then you must enter the URL for the location of the JavaScript called FindProxyForURL(URL url) that returns the proxy server to be used for a URL. Support for this script is the same as described below under Automatic Proxy Configuration.

Direct connection

Direct connection does not use a proxy. For certain situations, such as when mobile users connect to the company through a modem, direct connection to the intranet environment is required, and proxies should not be used in these cases.

How Java Plug-in and Java Web Start Obtain Proxy Information From the Browser

Because browsers on different platforms store proxy information differently, there is no generic mechanism to obtain proxy information. Here's how proxy information is obtained for two different browser-platform combinations:

Microsoft Internet Explorer: Internet Explorer stores proxy information in the same set of keys in the windows registry. Java Plug-in and
Java Web Start extract this information directly from the registry.

Mozilla: Mozilla stores proxy information in a preference file under the user profile directory on the local machine. Mozilla also has public APIs available for determining proxy information. Java Plug-in uses the Mozilla public APIs to obtain the proxy information; Java Web Start obtains the proxy information through reading and parsing the preference file.

Netscape Navigator: Navigator stores proxy information in a preference file under the user profile directory on the local machine. Java Plug-in and Java Web Start read and parse this file to obtain the proxy information.

Java Plug-in and Java Web Start obtain proxy information at startup time. If you change the proxy settings after Java Plug-in or Java Web Start have started, you may force reloading of the proxy information from the browser through the p option in the Java Console. Java Web Start is restarted for each application, so new proxy information will be used automatically on subsequent launches.

Manual Proxy Configuration

Internet Explorer, Mozilla, and Netscape Navigator support manual proxy configuration. Users can specify the proxy server and port for each protocol. Users can also specify one proxy server and port for all protocols. To minimize the workload of the proxy server, some sites might bypass the proxy server completely when a machine is connecting to another machine inside the intranet environment. To do this, network administrators and users can specify a proxy server bypass list in the browser's proxy setting.

Internet Explorer: Java Plug-in and Java Web Start recognize and supports the proxy server and port setting associated with the protocol. IE supports various syntaxes in the proxy server bypass list, as follows:

  • IP address/hostname only
  • IP address/hostname with wildcard
  • IP address/hostname with protocol

For example, if you specify "121.141.23.5;*.eng;http://*.com" in the proxy server bypass list, then the browser bypasses the proxy whenever one of the following occurs:

  • "121.141.23.5" is requested
  • the URL hostname ends with ".eng"
  • the URL protocol is http and the URL hostname ends with ".com"

Currently Java Plug-in and Java Web Start support the first two syntaxes in the proxy server bypass list in IE. IE also supports bypassing the proxy server for local (intranet) addresses without using the proxy server bypass list. Java Plug-in and Java Web Start support this option by bypassing the proxy server if the URL hostname is plain; i.e., the hostname contains no dot (.).

Mozilla and Netscape Navigator: Java Plug-in and Java Web Start recognize and supports the proxy server and port setting associated with the protocol. For example, if you specify ".eng,.sun.com" in the proxy server bypass list in Mozilla , it bypasses the proxy whenever the URL hostname ends with ".eng" or ".sun.com". Java Plug-in and Java Web Start fully support this syntax in the proxy server bypass list in Mozilla and Navigator.

For more information about manual proxy configuration in your browser, consult the user guide for your browser.

Automatic Proxy Configuration

Automatic proxy configuration is supported in the browser by setting a particular URL that contains a JavaScript file with .pac or .js extension. This file contains a function called FindProxyForURL that contains the logic to determine which proxy server to use when the browser receives a connection request. This function is written by the system administrator for the particular intranet environment. When the browser starts up, it recognizes the URL of the JavaScript file and downloads the file to the local machine using direct connection. Then whenever it needs to make a new connection, the browser executes the JavaScript function FindProxyForURL in the file to obtain the proxy information to set up the connection.

Java Plug-in:

Internet Explorer: During startup, Java Plug-in downloads the JavaScript file to the local machine using direct connection. Then whenever it needs to make a new connection, it executes the FindProxyForURL function to obtain the proxy information using the JavaScript engine in Internet Explorer.

Mozilla/Netscape Navigator: During startup, Java Plug-in downloads the JavaScript file to the local machine using direct connection. Then
whenever it needs to make a new connection, it executes the FindProxyForURL function to obtain the proxy information by using the JavaScript engine in Mozilla/Navigator.

Java Web Start:

Windows: During startup, Java Web Start downloads the JavaScript file to the local machine using direct connection. Then whenever it needs to make a new connection, it executes the FindProxyForURL function to obtain the proxy information using the JavaScript engine in Internet Explorer.

Linux/Solaris: During startup, Java Web Start downloads the JavaScript file to the local machine using direct connection. Then whenever it needs to make a new connection, it will parse the FindProxyForURL function and try its best guess to obtain the proxy information.

Notes on FindProxyForURL

Given a JavaScript engine, the following is applicable to Java Plug-in on all platforms and to Java Web Start on Windows only.

  1. There are a number of JavaScript helper functions which can be called from the JavaScript function FindProxyForURL. Java Plug-in and Java Web Start provide their own implementations of these functions to completely emulate automatic proxy configuration. Regarding the implementation of these helper function, note the following:
    • Function dnsResolve always returns an empty string if the host is not an IP address.
    • Function isResolvable always returns false if the host is not an IP address.
    • Function isInNet always returns false if the host is not an IP address.
  2. Executing the function FindProxyForURL always returns proxy information as a string. Java Plug-in and Java Web Start extract the setting in the following way:
    • If "DIRECT" is in the string, Java Plug-in and Java Web Start assume direct connection.
    • If "PROXY" is in the string, they use the first proxy setting for the connection.
    • If "SOCKS" is in the string, they use the SOCKS v4 for the connection.
    • Otherwise, the proxy information in the string is incorrect. In this cases, Java Plug-in and Java Web Start assume direct connection.

For more information about automatic proxy configuration in your browser, consult the user guide for your browser.

java.net.ProxySelector API in J2SE 5.0

Developers may sometimes need to determine the proxy configuration of a given host. By knowing the proxy configuration they can write more intelligent code to connect to the host through the proper proxy server. In J2SE 5.0, java.net.ProxySelector is a new API for proxy configuration support. Here is a simple code example:

private Proxy findProxy(URI uri)
{
     try
     {
          ProxySelector selector = ProxySelector.getDefault();
          List<Proxy> proxyList = selector.select(uri);
          if (proxyList.size() > 1)
               return proxyList.get(0);
     }
     catch (IllegalArgumentException e)
     {
     }
     return Proxy.NO_PROXY;
}

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Networking and Proxies

1) Introduction

In today's networking environments, particularly corporate ones, application developers have to deal with proxies almost as often as system administrators. In some cases the application should use the system default settings, in other cases it will we want to have a very tight control over what goes through which proxy, and, somewhere in the middle, most applications will be happy to delegate the decision to their users by providing them with a GUI to set the proxy settings, as is the case in most browsers.

In any case, a development platform, like Java, should provide mechanisms to deal with these proxies that are both powerful and flexible. Unfortunately, until recently, the Java platform wasn't very flexible in that department. But all that changed in J2SE 5.0 as new API have been introduced to address this shortcoming, and the purpose of this paper is to provide an in-depth explanation of all these APIs and mechanisms, the old ones, which are still valid, as well as the new ones.

2) System Properties

Up until J2SE 1.4 system properties were the only way to set proxy servers within the Java networking API for any of the protocol handlers. To make matters more complicated, the names of these properties have changed from one release to another and some of them are now obsolete even if they are still supported for compatibility's sake.

The major limitation of using system properties is that they are an “all or nothing” switch. Meaning that once a proxy has been set for a particular protocol, it will affect all connections for that protocol. It's a VM wide behavior.

There are 2 main ways to set system properties:

  • As a command line option when invoking the VM
  • Using the System.setProperty(String, String) method, assuming, of course that you have permission to do so.

Now, let's take a look, protocol by protocol, at the properties you can use to set proxies. All proxies are defined by a host name and a port number. The later is optional as, if it is not specified, a standard default port will be used.

2.1) HTTP

There are 3 properties you can set to specify the proxy that will be used by the http protocol handler:

  • http.proxyHost: the host name of the proxy server
  • http.proxyPort: the port number, the default value being 80.
  • http.nonProxyHosts:a list of hosts that should be reached directly, bypassing the proxy. This is a list of patterns separated by '|'. The patterns may start or end with a '*' for wildcards. Any host matching one of these patterns will be reached through a direct connection instead of through a proxy.

Let's look at a few examples assuming we're trying to execute the main method of the GetURL class:

$ java -Dhttp.proxyHost=webcache.mydomain.com GetURL

All http connections will go through the proxy server at webcache.mydomain.com listening on port 80 (we didn't specify any port, so the default one is used).

$ java -Dhttp.proxyHost=webcache.mydomain.com -Dhttp.proxyPort=8080
-Dhttp.noProxyHosts=”localhost|host.mydomain.com” GetURL

In that second example, the proxy server will still be at webcache.mydomain.com, but this time listening on port 8080. Also, the proxy won't be used when connecting to either localhost or host.mydonain.com.

As mentioned earlier, these settings affect all http connections during the entire lifetime of the VM invoked with these options. However it is possible, using the System.setProperty() method, to have a slightly more dynamic behavior.

Here is a code excerpt showing how this can be done:

//Set the http proxy to webcache.mydomain.com:8080

System.setProperty("http.proxyHost", "webcache.mydomain.com");
System.setProperty("http.proxyPort", "8080");

// Next connection will be through proxy.
URL url = new URL("http://java.sun.com/");
InputStream in = url.openStream();

// Now, let's 'unset' the proxy.
System.setProperty("http.proxyHost", null);

// From now on http connections will be done directly.

Now,this works reasonably well, even if a bit cumbersome, but it can get tricky if your application is multi-threaded. Remember, system properties are “VM wide” settings, so all threads are affected. Which means that the code in one thread could, as a side effect, render the code in an other thread inoperative.

2.2) HTTPS

The https (http over SSL) protocol handler has its own set of properties:

  • htttps.proxyHost
  • https.proxyPort

As you probably guessed these work in the exact same manner as their http counterparts, so we won't go into much detail except to mention that the default port number, this time, is 443 and that for the "non proxy hosts" list, the HTTPS protocol handler will use the same as the http handler (i.e. http.nonProxyHosts).

2.3) FTP

Settings for the FTP protocol handler follow the same rules as for http, the only difference is that each property name is now prefixed with 'ftp.' instead of 'http.'

Therefore the system properties are:

  • ftp.proxHost
  • ftp.proxyPort
  • ftp.nonProxyHosts

Note that, this time, there is a separate property for the "non proxy hosts" list. Also, as for http, the default port number value is 80. It should be noted that when going through a proxy, the FTP protocol handler will actually use HTTP to issue commands to the proxy server, which explains why this is the same default port number.

Let's examine a quick example:

$ java -Dhttp.proxyHost=webcache.mydomain.com
-Dhttp.proxyPort=8080 -Dftp.proxyHost=webcache.mydomain.com -Dftp.proxyPort=8080 GetURL

Here, both the HTTP and the FTP protocol handlers will use the same proxy server at webcache.mydomain.com:8080.

2.4) SOCKS

The SOCKS protocol, as defined in RFC 1928, provides a framework for client server applications to safely traverse a firewall both at the TCP and UDP level. In that sense it is a lot more generic than higher level proxies (like HTTP or FTP specific proxies). J2SE 5.0 provides SOCKS support for client TCP sockets.

There are 2 system properties related to SOCKS:

  • socksProxyHost for the host name of the SOCKS proxy server
  • socksProxyPort for the port number, the default value being 1080

Note that there is no dot ('.') after the prefix this time. This is for historical reasons and to ensure backward compatibility. Once a SOCKS proxy is specified in this manner, all TCP connections will be attempted through the proxy.

Example:

$ java -DsocksProxyHost=socks.mydomain.com GetURL

Here, during the execution of the code, every outgoing TCP socket will go through the SOCKS proxy server at socks.mydomain.com:1080.

Now, what happens when both a SOCKS proxy and a HTTP proxy are defined? Well the rule is that settings for higher level protocols, like HTTP or FTP, take precedence over SOCKS settings. So, in that particular case, when establishing a HTTP connection, the SOCKS proxy settings will be ignored and the HTTP proxy will be contacted. Let's look at an example:

$ java -Dhttp.proxyHost=webcache.mydomain.com -Dhttp.proxyPort=8080
-DsocksProxyHost=socks.mydomain.com GetURL

Here, an http URL will go through webcache.mydomain.com:8080 because the http settings take precedence. But what about an ftp URL? Since no specific proxy settings were assigned for FTP, and since FTP is on top of TCP, then FTP connections will be attempted through the SOCKS proxy server at socks.mydomsain.com:1080. If an FTP proxy had been specified, then that proxy would have been used instead.

3) Proxy class

As we have seen, the system properties are powerful, but not flexible. The "all or nothing" behavior was justly deemed too severe a limitation by most developers. That's why it was decided to introduce a new, more flexible, API in J2SE 5.0 so that it would be possible to have connection based proxy settings.

The core of this new API is the Proxy class which represents a proxy definition, typically a type (http, socks) and a socket address. There are, as of J2SE 5.0, 3 possible types:

  • DIRECT which represents a direct connection, or absence of proxy.
  • HTTP which represents a proxy using the HTTP protocol.
  • SOCKS which represents proxy using either SOCKS v4 or v5.

So, in order to create an HTTP proxy object you would call:

SocketAddress addr = new
InetSocketAddress("webcache.mydomain.com", 8080);
Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);

Remember, this new proxy object represents a proxy definition, nothing more. How do we use such an object? A new openConnection() method has been added to the URL class and takes a Proxy as an argument, it works the same way as openConnection() with no arguments, except it forces the connection to be established through the specified proxy, ignoring all other settings, including the system properties mentioned above.

So completing the previous example, we can now add:

URL url = new URL("http://java.sun.com/");
URConnection conn = url.openConnection(proxy);

Simple, isn't it?

The same mechanism can be used to specify that a particular URL has to be reached directly, because it's on the intranet for example. That's where the DIRECT type comes into play. But, you don't need to create a proxy instance with the DIRECT type, all you have to do is use the NO_PROXY static member:

URL url2 = new URL("http://infos.mydomain.com/");
URLConnection conn2 = url2.openConnection(Proxy.NO_PROXY);

Now, this guarantees you that this specific URL will be retrieved though a direct connection bypassing any other proxy settings, which can be convenient.

Note that you can force a URLConnection to go through a SOCKS proxy as well:

SocketAddress addr = new InetSocketAddress("socks.mydomain.com", 1080);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);
URL url = new URL("ftp://ftp.gnu.org/README");
URLConnection conn = url.openConnection(proxy);

That particular FTP connection will be attempted though the specified SOCKS proxy. As you can see, it's pretty straightforward.

Last, but not least, you can also specify a proxy for individual TCP sockets by using the newly introduced socket constructor:

SocketAddress addr = new InetSocketAddress("socks.mydomain.com", 1080);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);
Socket socket = new Socket(proxy);
InetSocketAddress dest = new InetSocketAddress("server.foo.com", 1234);
socket.connect(dest);

Here the socket will try to connect to its destination address (server.foo.com:1234) through the specified SOCKS proxy.

As for URLs, the same mechanism can be used to ensure that a direct (i.e. not through any proxy) connection should be attempted no matter what the global settings are:

Socket socket = new Socket(Proxy.NO_PROXY);
socket.connect(new InetAddress("localhost", 1234));

Note that this new constructor, as of J2SE 5.0, accepts only 2 types of proxy: SOCKS or DIRECT (i.e. the NO_PROXY instance).

4) ProxySelector

As you can see, with J2SE 5.0, the developer gains quite a bit of control and flexibility when it comes to proxies. Still, there are situations where one would like to decide which proxy to use dynamically, for instance to do some load balancing between proxies, or depending on the destination, in which case the API described so far would be quite cumbersome. That's where the ProxySelector comes into play.

In a nutshell the ProxySelector is a piece of code that will tell the protocol handlers which proxy to use, if any, for any given URL. For example, consider the following code:

URL url = new URL("http://java.sun.com/index.html");
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();

At that point the HTTP protocol handler is invoked and it will query the proxySelector. The dialog might go something like that:

Handler: Hey dude, I'm trying to reach java.sun.com, should I use a proxy?
ProxySelector: Which protocol do you intend to use?
Handler: http, of course!
ProxySelector: On the default port?
Handler: Let me check.... Yes, default port.
ProxySelector: I see. Then you shall use webcache.mydomain.com on port 8080 as a proxy.
Handler: Thanks. <pause> Dude, webcache.mydomain.com:8080 doesn't seem to be responding! Any other option?
ProxySelector: Dang! OK, try webcache2.mydomain.com, on port 8080 as well.
Handler: Sure. Seems to be working. Thanks.
ProxySelector: No sweat. Bye.

Of course I'm embellishing a bit, but you get the idea.

The best thing about the ProxySelector is that it is plugable! Which means that if you have needs that are not covered by the default one, you can write a replacement for it and plug it in!

So what is a ProxySelector? Let's take a look at the class definition:

public abstract class ProxySelector {
        public static ProxySelector getDefault();
        public static void setDefault(ProxySelector ps);
        public abstract List<Proxy> select(URI uri);
        public abstract void connectFailed(URI uri,
                SocketAddress sa, IOException ioe);
}

As we can see, ProxySelector is an abstract class with 2 static methods to set, or get, the default implementation, and 2 instance methods that will be used by the protocol handlers to determine which proxy to use or to notify that a proxy seems to be unreachable. If you want to provide your own ProxySelector, all you have to do is extend this class, provide an implementation for these 2 instance methods then call ProxySelector.setDefault() passing an instance of your new class as an argument. At this point the protocol handlers, like http or ftp, will query the new ProxySelector when trying to decide what proxy to use.

Before we see in details how to write such a ProxySelector, let's talk about the default one. J2SE 5.0 provides a default implementation which enforces backward compatibility. In other terms, the default ProxySelector will check the system properties described earlier to determine which proxy to use. However, there is a new, optional feature: On recent Windows systems and on Gnome 2.x platforms it is possible to tell the default ProxySelector to use the system proxy settings (both recent versions of Windows and Gnome 2.x let you set proxies globally through their user interface). If the system property java.net.useSystemProxies is set to true (by default it is set to false for compatibility sake), then the default ProxySelector will try to use these settings. You can set that system property on the command line, or you can edit the JRE installation file lib/net.properties, that way you have to change it only once on a given system.

Now let's examine how to write, and install, a new ProxySelector.

Here is what we want to achieve: We're pretty happy with the default ProxySelector behavior, except when it comes to http and https. On our network we have more than one possible proxy for these protocols and we'd like our application to try them in sequence (i.e.: if the 1st one doesn't respond, then try the second one and so on). Even more, if one of them fails too many time, we'll remove it from the list in order to optimize things a bit.

All we need to do is subclass java.net.ProxySelector and provide implementations for both the select() and connectFailed() methods.

The select() method is called by the protocol handlers before trying to connect to a destination. The argument passed is a URI describing the resource (protocol, host and port number). The method will then return a List of Proxies. For instance the following code:

URL url = new URL("http://java.sun.com/index.html");
InputStream in = url.openStream();

will trigger the following pseudo-call in the protocol handler:

List<Proxy> l = ProxySelector.getDefault().select(new URI("http://java.sun.com/"));

In our implementation, all we'll have to do is check that the protocol from the URI is indeed http (or https), in which case we will return the list of proxies, otherwise we just delegate to the default one. To do that, we'll need, in the constructor, to store a reference to the old default, because ours will become the default.

So it is starting to look like this:

public class MyProxySelector extends ProxySelector {
        ProxySelector defsel = null;
        MyProxySelector(ProxySelector def) {
                defsel = def;
        }

        public java.util.List<Proxy> select(URI uri) {
                if (uri == null) {
                        throw new IllegalArgumentException("URI can't be null.");
                }
                String protocol = uri.getScheme();
                if ("http".equalsIgnoreCase(protocol) ||
                        "https".equalsIgnoreCase(protocol)) {
                        ArrayList<Proxy> l = new ArrayList<Proxy>();
                        // Populate the ArrayList with proxies
                        return l;
                }
                if (defsel != null) {
                        return defsel.select(uri);
                } else {
                        ArrayList<Proxy> l = new ArrayList<Proxy>();
                        l.add(Proxy.NO_PROXY);
                        return l;
                }
        }
}

First note the constructor that keeps a reference to the old default selector. Second, notice the check for illegal argument in the select() method in order to respect the specifications. Finally, notice how the code defers to the old default, if there was one, when necessary. Of course, in this example, I didn't detail how to populate the ArrayList, as it not of particular interest, but the complete code is available in the appendix if you're curious.

As it is, the class is incomplete since we didn't provide an implementation for the connectFailed() method. That's our very next step.

The connectFailed() method is called by the protocol handler whenever it failed to connect to one of the proxies returned by the select() method. 3 arguments are passed: the URI the handler was trying to reach, which should be the one used when select() was called, the SocketAddress of the proxy that the handler was trying to contact and the IOException that was thrown when trying to connect to the proxy. With that information, we'll just do the following: If the proxy is in our list, and it failed 3 times or more, we'll just remove it from our list, making sure it won't be used again in the future. So the code is now:

public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
        if (uri == null || sa == null || ioe == null) {
                throw new IllegalArgumentException("Arguments can't be null.");
        }
        InnerProxy p = proxies.get(sa);
        if (p != null) {
                if (p.failed() >= 3)
                        proxies.remove(sa);
        } else {
                if (defsel != null)
                        defsel.connectFailed(uri, sa, ioe);
        }
}

Pretty straightforward isn't it. Again we have to check the validity of the arguments (specifications again). The only thing we do take into account here is the SocketAddress, if it's one of the proxies in our list, then we do deal with it, otherwise we defer, again, to the default selector.

Now that our implementation is, mostly, complete, all we have to do in the application is to register it and we're done:

public static void main(String[] args) {
        MyProxySelector ps = new MyProxySelector(ProxySelector.getDefault());
        ProxySelector.setDefault(ps);
        // rest of the application
}

Of course, I simplified things a bit for the sake of clarity, in particular you've probably noticed I didn't do much Exception catching, but I'm confident you can fill in the blanks.

It should be noted that both Java Plugin and Java Webstart do replace the default ProxySelector with a custom one to integrate better with the underlying platform or container (like the web browser). So keep in mind, when dealing with ProxySelector, that the default one is typically specific to the underlying platform and to the JVM implementation. That's why it is a good idea, when providing a custom one, to keep a reference to the older one, as we've done in the above example, and use it when necessary.

5) Conclusion

As we have now established J2SE 5.0 provides quite a number of ways to deal with proxies. From the very simple (using the system proxy settings) to the very flexible (changing the ProxySelector, albeit for experienced developers only), including the per connection selection courtesy of the Proxy class.

Appendix

Here is the full source of the ProxySelector we developed in this paper. Keep in mind that this was written for educational purposes only, and was therefore kept pretty simple on purpose.

import java.net.*;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.IOException;

public class MyProxySelector extends ProxySelector {
        // Keep a reference on the previous default
    ProxySelector defsel = null;

        /*
         * Inner class representing a Proxy and a few extra data
         */
        class InnerProxy {
        Proxy proxy;
                SocketAddress addr;
                // How many times did we fail to reach this proxy?
                int failedCount = 0;

                InnerProxy(InetSocketAddress a) {
                        addr = a;
                        proxy = new Proxy(Proxy.Type.HTTP, a);
                }

                SocketAddress address() {
                        return addr;
                }

                Proxy toProxy() {
                        return proxy;
                }

                int failed() {
                        return ++failedCount;
                }
        }

        /*
         * A list of proxies, indexed by their address.
         */
        HashMap<SocketAddress, InnerProxy> proxies = new HashMap<SocketAddress, InnerProxy>();

        MyProxySelector(ProxySelector def) {
          // Save the previous default
          defsel = def;

          // Populate the HashMap (List of proxies)
          InnerProxy i = new InnerProxy(new InetSocketAddress("webcache1.mydomain.com", 8080));
          proxies.put(i.address(), i);
          i = new InnerProxy(new InetSocketAddress("webcache2.mydomain.com", 8080));
          proxies.put(i.address(), i);
          i = new InnerProxy(new InetSocketAddress("webcache3.mydomain.com", 8080));
          proxies.put(i.address(), i);
          }

          /*
           * This is the method that the handlers will call.
           * Returns a List of proxy.
           */
          public java.util.List<Proxy> select(URI uri) {
                // Let's stick to the specs.
                if (uri == null) {
                        throw new IllegalArgumentException("URI can't be null.");
                }

                /*
                 * If it's a http (or https) URL, then we use our own
                 * list.
                 */
                String protocol = uri.getScheme();
                if ("http".equalsIgnoreCase(protocol) ||
                        "https".equalsIgnoreCase(protocol)) {
                        ArrayList<Proxy> l = new ArrayList<Proxy>();
                        for (InnerProxy p : proxies.values()) {
                          l.add(p.toProxy());
                        }
                        return l;
                }

                /*
                 * Not HTTP or HTTPS (could be SOCKS or FTP)
                 * defer to the default selector.
                 */
                if (defsel != null) {
                        return defsel.select(uri);
                } else {
                        ArrayList<Proxy> l = new ArrayList<Proxy>();
                        l.add(Proxy.NO_PROXY);
                        return l;
                }
        }

        /*
         * Method called by the handlers when it failed to connect
         * to one of the proxies returned by select().
         */
        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
                // Let's stick to the specs again.
                if (uri == null || sa == null || ioe == null) {
                        throw new IllegalArgumentException("Arguments can't be null.");
                }

                /*
                 * Let's lookup for the proxy
                 */
                InnerProxy p = proxies.get(sa);
                        if (p != null) {
                                /*
                                 * It's one of ours, if it failed more than 3 times
                                 * let's remove it from the list.
                                 */
                                if (p.failed() >= 3)
                                        proxies.remove(sa);
                        } else {
                                /*
                                 * Not one of ours, let's delegate to the default.
                                 */
                                if (defsel != null)
                                  defsel.connectFailed(uri, sa, ioe);
                        }
     }
}
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Dynamic Proxy Classes

Contents

Introduction
Dynamic Proxy API
Serialization
Examples

Introduction

A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface. Thus, a dynamic proxy class can be used to create a type-safe proxy object for a list of interfaces without requiring pre-generation of the proxy class, such as with compile-time tools. Method invocations on an instance of a dynamic proxy class are dispatched to a single method in the instance's invocation handler, and they are encoded with a java.lang.reflect.Method object identifying the method that was invoked and an array of type Object containing the arguments.

Dynamic proxy classes are useful to an application or library that needs to provide type-safe reflective dispatch of invocations on objects that present interface APIs. For example, an application can use a dynamic proxy class to create an object that implements multiple arbitrary event listener interfaces-- interfaces that extend java.util.EventListener-- to process a variety of events of different types in a uniform fashion, such as by logging all such events to a file.

Dynamic Proxy Class API

A dynamic proxy class (simply referred to as a proxy class below) is a class that implements a list of interfaces specified at runtime when the class is created.

A proxy interface is such an interface that is implemented by a proxy class.

A proxy instance is an instance of a proxy class.

Creating a Proxy Class

Proxy classes, as well as instances of them, are created using the static methods of the class java.lang.reflect.Proxy.

The Proxy.getProxyClass method returns the java.lang.Class object for a proxy class given a class loader and an array of interfaces. The proxy class will be defined in the specified class loader and will implement all of the supplied interfaces. If a proxy class for the same permutation of interfaces has already been defined in the class loader, then the existing proxy class will be returned; otherwise, a proxy class for those interfaces will be generated dynamically and defined in the class loader.

There are several restrictions on the parameters that may be passed to Proxy.getProxyClass:

  • All of the Class objects in the interfaces array must represent interfaces, not classes or primitive types.
  • No two elements in the interfaces array may refer to identical Class objects.
  • All of the interface types must be visible by name through the specified class loader. In other words, for class loader cl and every interface i, the following expression must be true:
            Class.forName(i.getName(), false, cl) == i
  • All non-public interfaces must be in the same package; otherwise, it would not be possible for the proxy class to implement all of the interfaces, regardless of what package it is defined in.
  • For any set of member methods of the specified interfaces that have the same signature:
    • If the return type of any of the methods is a primitive type or void, then all of the methods must have that same return type.
    • Otherwise, one of the methods must have a return type that is assignable to all of the return types of the rest of the methods.
  • The resulting proxy class must not exceed any limits imposed on classes by the virtual machine. For example, the VM may limit the number of interfaces that a class may implement to 65535; in that case, the size of the interfaces array must not exceed 65535.

If any of these restrictions are violated, Proxy.getProxyClass will throw an IllegalArgumentException. If the interfaces array argument or any of its elements are null, a NullPointerException will be thrown.

Note that the order of the specified proxy interfaces is significant: two requests for a proxy class with the same combination of interfaces but in a different order will result in two distinct proxy classes. Proxy classes are distinguished by the order of their proxy interfaces in order to provide deterministic method invocation encoding in cases where two or more of the proxy interfaces share a method with the same name and parameter signature; this reasoning is described in more detail in the section below titled Methods Duplicated in Multiple Proxy Interfaces.

So that a new proxy class does not need to be generated each time Proxy.getProxyClass is invoked with the same class loader and list of interfaces, the implementation of the dynamic proxy class API should keep a cache of generated proxy classes, keyed by their corresponding loaders and interface list. The implementation should be careful not to refer to the class loaders, interfaces, and proxy classes in such a way as to prevent class loaders, and all of their classes, from being garbage collected when appropriate.

Proxy Class Properties

A proxy class has the following properties:

  • Proxy classes are public, final, and not abstract.
  • The unqualified name of a proxy class is unspecified. The space of class names that begin with the string "$Proxy" is, however, to be reserved for proxy classes.
  • A proxy class extends java.lang.reflect.Proxy.
  • A proxy class implements exactly the interfaces specified at its creation, in the same order.
  • If a proxy class implements a non-public interface, then it will be defined in the same package as that interface. Otherwise, the package of a proxy class is also unspecified. Note that package sealing will not prevent a proxy class from being successfully defined in a particular package at runtime, and neither will classes already defined in the same class loader and the same package with particular signers.
  • Since a proxy class implements all of the interfaces specified at its creation, invoking getInterfaces on its Class object will return an array containing the same list of interfaces (in the order specified at its creation), invoking getMethods on its Class object will return an array of Method objects that include all of the methods in those interfaces, and invoking getMethod will find methods in the proxy interfaces as would be expected.
  • The Proxy.isProxyClass method will return true if it is passed a proxy class-- a class returned by Proxy.getProxyClass or the class of an object returned by Proxy.newProxyInstance-- and false otherwise. The reliability of this method is important for the ability to use it to make security decisions, so its implementation should not just test if the class in question extends java.lang.reflect.Proxy.
  • The java.security.ProtectionDomain of a proxy class is the same as that of system classes loaded by the bootstrap class loader, such as java.lang.Object, because the code for a proxy class is generated by trusted system code. This protection domain will typically be granted java.security.AllPermission.

Creating a Proxy Instance

Each proxy class has one public constructor that takes one argument, an implementation of the interface InvocationHandler.

Each proxy instance has an associated invocation handler object, the one that was passed to its constructor. Rather than having to use the reflection API to access the public constructor, a proxy instance can be also be created by calling the Proxy.newProxyInstance method, which combines the actions of calling Proxy.getProxyClass with invoking the constructor with an invocation handler. Proxy.newProxyInstance throws IllegalArgumentException for the same reasons that Proxy.getProxyClass does.

Proxy Instance Properties

A proxy instance has the following properties:

  • Given a proxy instance proxy and one of the interfaces implemented by its proxy class Foo, the following expression will return true:
            proxy instanceof Foo
    and the following cast operation will succeed (rather than throwing a ClassCastException):
            (Foo) proxy
  • The static Proxy.getInvocationHandler method will return the invocation handler associated with the proxy instance passed as its argument. If the object passed to Proxy.getInvocationHandler is not a proxy instance, then an IllegalArgumentException will be thrown.
  • An interface method invocation on a proxy instance will be encoded and dispatched to the invocation handler's invoke method as described below.

    The proxy instance itself will be passed as the first argument of invoke, which is of type Object.

    The second argument passed to invoke will be the java.lang.reflect.Method instance corresponding to the interface method invoked on the proxy instance. The declaring class of the Method object will be the interface that the method was declared in, which may be a superinterface of the proxy interface that the proxy class inherits the method through.

    The third argument passed to invoke will be an array of objects containing the values of the arguments passed in the method invocation on the proxy instance. Arguments of primitive types are wrapped in an instance of the appropriate primitive wrapper class, such as java.lang.Integer or java.lang.Boolean. The implementation of the invoke method is free to modify the contents of this array.

    The value returned by the invoke method will become the return value of the method invocation on the proxy instance. If the declared return value of the interface method is a primitive type, then the value returned by invoke must be an instance of the corresponding primitive wrapper class; otherwise, it must be a type assignable to the declared return type. If the value returned by invoke is null and the interface method's return type is primitive, then a NullPointerException will be thrown by the method invocation on the proxy instance. If the value returned by invoke is otherwise not compatible with the method's declared return type as described above, a ClassCastException will be thrown by the proxy instance.

    If an exception is thrown by the invoke method, it will be also thrown by the method invocation on the proxy instance. The exception's type must be assignable to either any of the exception types declared in the signature of the interface method or to the unchecked exception types java.lang.RuntimeException or java.lang.Error. If a checked exception is thrown by invoke that is not assignable to any of the exception types declared in the throws clause of the interface method, then an UndeclaredThrowableException will be thrown by the method invocation on the proxy instance. The UndeclaredThrowableException will be constructed with the exception that was thrown by the invoke method.

  • An invocation of the hashCode, equals, or toString methods declared in java.lang.Object on a proxy instance will be encoded and dispatched to the invocation handler's invoke method in the same manner as interface method invocations are encoded and dispatched, as described above. The declaring class of the Method object passed to invoke will be java.lang.Object. Other public methods of a proxy instance inherited from java.lang.Object are not overridden by a proxy class, so invocations of those methods behave like they do for instances of java.lang.Object.

Methods Duplicated in Multiple Proxy Interfaces

When two or more interfaces of a proxy class contain a method with the same name and parameter signature, the order of the proxy class's interfaces becomes significant. When such a duplicate method is invoked on a proxy instance, the Method object passed to the invocation handler will not necessarily be the one whose declaring class is assignable from the reference type of the interface that the proxy's method was invoked through. This limitation exists because the corresponding method implementation in the generated proxy class cannot determine which interface it was invoked through. Therefore, when a duplicate method is invoked on a proxy instance, the Method object for the method in the foremost interface that contains the method (either directly or inherited through a superinterface) in the proxy class's list of interfaces is passed to the invocation handler's invoke method, regardless of the reference type through which the method invocation occurred.

If a proxy interface contains a method with the same name and parameter signature as the hashCode, equals, or toString methods of java.lang.Object, when such a method is invoked on a proxy instance, the Method object passed to the invocation handler will have java.lang.Object as its declaring class. In other words, the public, non-final methods of java.lang.Object logically precede all of the proxy interfaces for the determination of which Method object to pass to the invocation handler.

Note also that when a duplicate method is dispatched to an invocation handler, the invoke method may only throw checked exception types that are assignable to one of the exception types in the throws clause of the method in all of the proxy interfaces that it can be invoked through. If the invoke method throws a checked exception that is not assignable to any of the exception types declared by the method in one of the proxy interfaces that it can be invoked through, then an unchecked UndeclaredThrowableException will be thrown by the invocation on the proxy instance. This restriction means that not all of the exception types returned by invoking getExceptionTypes on the Method object passed to the invoke method can necessarily be thrown successfully by the invoke method.

Serialization

Since java.lang.reflect.Proxy implements java.io.Serializable, proxy instances can be serialized, as described in this section. If a proxy instance contains an invocation handler that is not assignable to java.io.Serializable, however, then a java.io.NotSerializableException will be thrown if such an instance is written to a java.io.ObjectOutputStream. Note that for proxy classes, implementing java.io.Externalizable has the same effect with respect to serialization as implementing java.io.Serializable: the writeExternal and readExternal methods of the Externalizable interface will never be invoked on a proxy instance (or an invocation handler) as part of its serialization process. As with all Class objects, the Class object for a proxy class is always serializable.

A proxy class has no serializable fields and a serialVersionUID of 0L. In other words, when the Class object for a proxy class is passed to the static lookup method of java.io.ObjectStreamClass, the returned ObjectStreamClass instance will have the following properties:

  • Invoking its getSerialVersionUID method will return 0L.
  • Invoking its getFields method will return an array of length zero.
  • Invoking its getField method with any String argument will return null.

The stream protocol for Object Serialization supports a type code named TC_PROXYCLASSDESC, which is a terminal symbol in the grammar for the stream format; its type and value are defined by the following constant field in the java.io.ObjectStreamConstants interface:

    final static byte TC_PROXYCLASSDESC = (byte)0x7D;

The grammar also includes the following two rules, the first being an alternate expansion of the original newClassDesc rule:

newClassDesc:
TC_PROXYCLASSDESC newHandle proxyClassDescInfo

proxyClassDescInfo:
(int)<count> proxyInterfaceName[count] classAnnotation superClassDesc

proxyInterfaceName:
(utf)

When an ObjectOutputStream serializes the class descriptor for a class that is a proxy class, as determined by passing its Class object to the Proxy.isProxyClass method, it uses the TC_PROXYCLASSDESC type code instead of TC_CLASSDESC, following the rules above. In the expansion of proxyClassDescInfo, the sequence of proxyInterfaceName items are the names of all of the interfaces implemented by the proxy class, in the order that they are returned by invoking the getInterfaces method on the Class object. The classAnnotation and superClassDesc items have the same meaning as they do in the classDescInfo rule. For a proxy class, superClassDesc is the class descriptor for its superclass, java.lang.reflect.Proxy; including this descriptor allows for the evolution of the serialized representation of the class Proxy for proxy instances.

For non-proxy classes, ObjectOutputStream calls its protected annotateClass method to allow subclasses to write custom data to the stream for a particular class. For proxy classes, instead of annotateClass, the following method in java.io.ObjectOutputStream is called with the Class object for the proxy class:

    protected void annotateProxyClass(Class cl) throws IOException;

The default implementation of annotateProxyClass in ObjectOutputStream does nothing.

When an ObjectInputStream encounters the type code TC_PROXYCLASSDESC, it deserializes the class descriptor for a proxy class from the stream, formatted as described above. Instead of calling its resolveClass method to resolve the Class object for the class descriptor, the following method in java.io.ObjectInputStream is called:

    protected Class resolveProxyClass(String[] interfaces)
        throws IOException, ClassNotFoundException;

The list of interface names that were deserialized in the proxy class descriptor are passed as the interfaces argument to resolveProxyClass.

The default implementation of resolveProxyClass in ObjectInputStream returns the results of calling Proxy.getProxyClass with the list of Class objects for the interfaces named in the interfaces parameter. The Class object used for each interface name i is the value retuned by calling

        Class.forName(i, false, loader)
where loader is the first non-null class loader up the execution stack, or null if no non-null class loaders are on the stack. This is the same class loader choice made by the default behavior of the resolveClass method. This same value of loader is also the class loader passed to Proxy.getProxyClass. If Proxy.getProxyClass throws an IllegalArgumentException, resolveClass will throw a ClassNotFoundException containing the IllegalArgumentException.

Since a proxy class never has its own serializable fields, the classdata[] in the stream representation of a proxy instance consists wholly of the instance data for its superclass, java.lang.reflect.Proxy. Proxy has one serializable field, h, which contains the invocation handler for the proxy instance.

Examples

Here is a simple example that prints out a message before and after a method invocation on an object that implements an arbitrary list of interfaces:

public interface Foo {
    Object bar(Object obj) throws BazException;
}

public class FooImpl implements Foo {
    Object bar(Object obj) throws BazException {
        // ...
    }
}

public class DebugProxy implements java.lang.reflect.InvocationHandler {

    private Object obj;

    public static Object newInstance(Object obj) {
        return java.lang.reflect.Proxy.newProxyInstance(
            obj.getClass().getClassLoader(),
            obj.getClass().getInterfaces(),
            new DebugProxy(obj));
    }

    private DebugProxy(Object obj) {
        this.obj = obj;
    }

    public Object invoke(Object proxy, Method m, Object[] args)
        throws Throwable
    {
        Object result;
        try {
            System.out.println("before method " + m.getName());
            result = m.invoke(obj, args);
        } catch (InvocationTargetException e) {
            throw e.getTargetException();
        } catch (Exception e) {
            throw new RuntimeException("unexpected invocation exception: " +
                                       e.getMessage());
        } finally {
            System.out.println("after method " + m.getName());
        }
        return result;
    }
}

To construct a DebugProxy for an implementation of the Foo interface and call one of its methods:

    Foo foo = (Foo) DebugProxy.newInstance(new FooImpl());
    foo.bar(null);

Here is an example of a utility invocation handler class that provides default proxy behavior for methods inherited from java.lang.Object and implements delegation of certain proxy method invocations to distinct objects depending on the interface of the invoked method:

import java.lang.reflect.*;

public class Delegator implements InvocationHandler {

    // preloaded Method objects for the methods in java.lang.Object
    private static Method hashCodeMethod;
    private static Method equalsMethod;
    private static Method toStringMethod;
    static {
        try {
            hashCodeMethod = Object.class.getMethod("hashCode", null);
            equalsMethod =
                Object.class.getMethod("equals", new Class[] { Object.class });
            toStringMethod = Object.class.getMethod("toString", null);
        } catch (NoSuchMethodException e) {
            throw new NoSuchMethodError(e.getMessage());
        }
    }

    private Class[] interfaces;
    private Object[] delegates;

    public Delegator(Class[] interfaces, Object[] delegates) {
        this.interfaces = (Class[]) interfaces.clone();
        this.delegates = (Object[]) delegates.clone();
    }

    public Object invoke(Object proxy, Method m, Object[] args)
        throws Throwable
    {
        Class declaringClass = m.getDeclaringClass();

        if (declaringClass == Object.class) {
            if (m.equals(hashCodeMethod)) {
                return proxyHashCode(proxy);
            } else if (m.equals(equalsMethod)) {
                return proxyEquals(proxy, args[0]);
            } else if (m.equals(toStringMethod)) {
                return proxyToString(proxy);
            } else {
                throw new InternalError(
                    "unexpected Object method dispatched: " + m);
            }
        } else {
            for (int i = 0; i < interfaces.length; i++) {
                if (declaringClass.isAssignableFrom(interfaces[i])) {
                    try {
                        return m.invoke(delegates[i], args);
                    } catch (InvocationTargetException e) {
                        throw e.getTargetException();
                    }
                }
            }

            return invokeNotDelegated(proxy, m, args);
        }
    }

    protected Object invokeNotDelegated(Object proxy, Method m,
                                        Object[] args)
        throws Throwable
    {
        throw new InternalError("unexpected method dispatched: " + m);
    }

    protected Integer proxyHashCode(Object proxy) {
        return new Integer(System.identityHashCode(proxy));
    }

    protected Boolean proxyEquals(Object proxy, Object other) {
        return (proxy == other ? Boolean.TRUE : Boolean.FALSE);
    }

    protected String proxyToString(Object proxy) {
        return proxy.getClass().getName() + '@' +
            Integer.toHexString(proxy.hashCode());
    }
}

Subclasses of Delegator can override invokeNotDelegated to implement the behavior of proxy method invocations not to be directly delegated to other objects, and they can override proxyHashCode, proxyEquals, and proxyToString to override the default behavior of the methods the proxy inherits from java.lang.Object.

To construct a Delegator for an implementation of the Foo interface:

    Class[] proxyInterfaces = new Class[] { Foo.class };
    Foo foo = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
        proxyInterfaces,
        new Delegator(proxyInterfaces, new Object[] { new FooImpl() }));

Note that the implementation of the Delegator class given above is intended to be more illustrative than optimized; for example, instead of caching and comparing the Method objects for the hashCode, equals, and toString methods, it could just match them by their string names, because none of those method names are overloaded in java.lang.Object.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface org.w3c.dom.ranges.Range (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.ranges.Range

  • Packages that use Range
    Package Description
    org.w3c.dom.ranges
    Document Object Model Level 2 Traversal and Range is a platform and language-neutral interfaces that allow programs and scripts to dynamically traverse and identify a range of content in a document.

    • Uses of Range in org.w3c.dom.ranges

      Methods in org.w3c.dom.ranges that return Range
      Modifier and Type Method and Description
      Range Range.cloneRange()
      Produces a new Range whose boundary-points are equal to the boundary-points of the Range.
      Range DocumentRange.createRange()
      This interface can be obtained from the object implementing the Document interface using binding-specific casting methods.
      Methods in org.w3c.dom.ranges with parameters of type Range
      Modifier and Type Method and Description
      short Range.compareBoundaryPoints(short how, Range sourceRange)
      Compare the boundary-points of two Ranges in a document.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Class org.w3c.dom.ranges.RangeException (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
org.w3c.dom.ranges.RangeException

  • Packages that use RangeException
    Package Description
    org.w3c.dom.ranges
    Document Object Model Level 2 Traversal and Range is a platform and language-neutral interfaces that allow programs and scripts to dynamically traverse and identify a range of content in a document.

    • Uses of RangeException in org.w3c.dom.ranges

      Methods in org.w3c.dom.ranges that throw RangeException
      Modifier and Type Method and Description
      void Range.insertNode(Node newNode)
      Inserts a node into the Document or DocumentFragment at the start of the Range.
      void Range.selectNode(Node refNode)
      Select a node and its contents
      void Range.selectNodeContents(Node refNode)
      Select the contents within a node
      void Range.setEnd(Node refNode, int offset)
      Sets the attributes describing the end of a Range.
      void Range.setEndAfter(Node refNode)
      Sets the end of a Range to be after a node
      void Range.setEndBefore(Node refNode)
      Sets the end position to be before a node.
      void Range.setStart(Node refNode, int offset)
      Sets the attributes describing the start of the Range.
      void Range.setStartAfter(Node refNode)
      Sets the start position to be after a node
      void Range.setStartBefore(Node refNode)
      Sets the start position to be before a node
      void Range.surroundContents(Node newParent)
      Reparents the contents of the Range to the given node and inserts the node at the position of the start of the Range.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Debugging SSL/TLS Connections

Understanding SSL/TLS connection problems can sometimes be difficult, especially when it is not clear what messages are actually being sent and received. The SunJSSE has a built-in debug facility and is activated by the System property javax.net.debug.

What follows is a brief example how to read the debug output. Please be aware that the output is non-standard, and may change from release to release. We are using the default SunJSSE X509KeyManager and X509TrustManager which prints debug information.

This example assumes a basic understanding of the SSL/TLS protocol. Please see the The SSL Protocol Overview section of the JSSE Reference Guide for more information on the protocols (handshake messages, etc.).

In this example, we connect using the SSLSocketClientWithClientAuth sample application to a simple HTTPS server that requires client authentication, then send a HTTPS request and receive the reply.

    java  -Djavax.net.debug=all  \
        -Djavax.net.ssl.trustStore=trustStore
        SSLSocketClientWithClientAuth bongos 2001 /index.html
First, the X509KeyManager is initialized and discovers there is one keyEntry in the supplied KeyStore for a subject called "duke". If a server requests a client to authenticate itself, the X509KeyManager will search its list of keyEntries for an appropriate credential.
***
found key for : duke
chain [0] = [
[
  Version: V1
  Subject: CN=Duke, OU=Java Software, O="Sun Microsystems, Inc.",
  L=Cupertino, ST=CA, C=US
  Signature Algorithm: MD5withRSA, OID = 1.2.840.113549.1.1.4

  Key:  Sun RSA public key, 1024 bits
  modulus: 134968166047563266914058280571444028986498087544923991226919517
  667593269213420979048109900052353578998293280426361122296881234393722020
  704208851688212064483570055963805034839797994154526862998272017486468599
  962268346037652120279791547218281230795146025359480589335682217749874703
  510467348902637769973696151441
  public exponent: 65537
  Validity: [From: Tue May 22 16:46:46 PDT 2001,
               To: Sun May 22 16:46:46 PDT 2011]
  Issuer: CN=Duke, OU=Java Software, O="Sun Microsystems, Inc.",
  L=Cupertino, ST=CA, C=US
  SerialNumber: [    3b0afa66]

]
  Algorithm: [MD5withRSA]
  Signature:
0000: 5F B5 62 E9 A0 26 1D 8E   A2 7E 7C 02 08 36 3A 3E  _.b..&.......6:>
0010: C9 C2 45 03 DD F9 BC 06   FC 25 CF 30 92 91 B1 4E  ..E......%.0...N
0020: 62 17 08 48 14 68 80 CF   DD 89 11 EA 92 7F CE DD  b..H.h..........
0030: B4 FD 12 A8 71 C7 9E D7   C3 D0 E3 BD BB DE 20 92  ....q......... .
0040: C2 3B C8 DE CB 25 23 C0   8B B6 92 B9 0B 64 80 63  .;...%#......d.c
0050: D9 09 25 2D 7A CF 0A 31   B6 E9 CA C1 37 93 BC 0D  ..%-z..1....7...
0060: 4E 74 95 4F 58 31 DA AC   DF D8 BD 89 BD AF EC C8  Nt.OX1..........
0070: 2D 18 A2 BC B2 15 4F B7   28 6F D3 00 E1 72 9B 6C  -.....O.(o...r.l

]
***
The X509TrustManager is next initialized, and finds a certificate for a Certificate Authority (CA) named "JSSE Test CA". Any server presenting valid credentials signed by this CA will be trusted.
trustStore is: trustkeys
trustStore type is : jks
trustStore provider is :
init truststore
adding as trusted cert:
  Subject: CN=JSSE Test CA, OU=JWS, O=Sun,
      L=Santa Clara, ST=CA, C=US
  Issuer:  CN=JSSE Test CA, OU=JWS, O=Sun,
      L=Santa Clara, ST=CA, C=US
  Algorithm: RSA; Serial number: 0x0
  Valid from Mon Jul 19 13:30:15 PDT 2004 until Fri Dec 05 12:30:15 PST 2031
We finish some additional initialization code, and after this, we are now finally ready to make the connection to the server.
trigger seeding of SecureRandom
done seeding SecureRandom
export control - checking the cipher suites
export control - no cached value available...
export control - storing legal entry into cache...
%% No cached client session
The connection to the server is made, and we see the initial ClientHello message, which contains:
  • random information to initialize the cryptographic routines,
  • the SessionID, which if non-null, would be used in reestablishing a previous session,
  • the list of ciphersuites that the client requests,
  • and no compression algorithms.
This is followed by the output of various filters, such as encapsulating the TLSv1 header into the SSLv2Hello header format (See setEnabledProtocols()).
*** ClientHello, TLSv1
RandomCookie:  GMT: 1073239164 bytes = { 10, 80, 71, 86, 124, 135, 104,
151, 72, 153, 70, 28, 97, 232, 160, 217, 146, 178, 87, 255, 122, 147, 83,
197, 60, 187, 227, 76 }
Session ID:  {}
Cipher Suites: [SSL_RSA_WITH_RC4_128_MD5, SSL_RSA_WITH_RC4_128_SHA,
TLS_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA,
SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
SSL_RSA_WITH_DES_CBC_SHA, SSL_DHE_RSA_WITH_DES_CBC_SHA,
SSL_DHE_DSS_WITH_DES_CBC_SHA, SSL_RSA_EXPORT_WITH_RC4_40_MD5,
SSL_RSA_EXPORT_WITH_DES40_CBC_SHA, SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA,
SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA]
Compression Methods:  { 0 }
***
[write] MD5 and SHA1 hashes:  len = 73
0000: 01 00 00 45 03 01 40 F8   54 7C 0A 50 47 56 7C 87  ...E..@.T..PGV..
0010: 68 97 48 99 46 1C 61 E8   A0 D9 92 B2 57 FF 7A 93  h.H.F.a.....W.z.
0020: 53 C5 3C BB E3 4C 00 00   1E 00 04 00 05 00 2F 00  S.<..L......../.
0030: 33 00 32 00 0A 00 16 00   13 00 09 00 15 00 12 00  3.2.............
0040: 03 00 08 00 14 00 11 01   00                       .........
main, WRITE: TLSv1 Handshake, length = 73
[write] MD5 and SHA1 hashes:  len = 98
0000: 01 03 01 00 39 00 00 00   20 00 00 04 01 00 80 00  ....9... .......
0010: 00 05 00 00 2F 00 00 33   00 00 32 00 00 0A 07 00  ..../..3..2.....
0020: C0 00 00 16 00 00 13 00   00 09 06 00 40 00 00 15  ............@...
0030: 00 00 12 00 00 03 02 00   80 00 00 08 00 00 14 00  ................
0040: 00 11 40 F8 54 7C 0A 50   47 56 7C 87 68 97 48 99  ..@.T..PGV..h.H.
0050: 46 1C 61 E8 A0 D9 92 B2   57 FF 7A 93 53 C5 3C BB  F.a.....W.z.S.<.
0060: E3 4C                                              .L
main, WRITE: SSLv2 client hello message, length = 98
Section labeled "[Raw write]" represent the actual data sent to the raw output object (in this case, an OutputStream).
[Raw write]: length = 100
0000: 80 62 01 03 01 00 39 00   00 00 20 00 00 04 01 00  .b....9... .....
0010: 80 00 00 05 00 00 2F 00   00 33 00 00 32 00 00 0A  ....../..3..2...
0020: 07 00 C0 00 00 16 00 00   13 00 00 09 06 00 40 00  ..............@.
0030: 00 15 00 00 12 00 00 03   02 00 80 00 00 08 00 00  ................
0040: 14 00 00 11 40 F8 54 7C   0A 50 47 56 7C 87 68 97  ....@.T..PGV..h.
0050: 48 99 46 1C 61 E8 A0 D9   92 B2 57 FF 7A 93 53 C5  H.F.a.....W.z.S.
0060: 3C BB E3 4C                                        <..L
After sending the initial ClientHello, we wait for the server's response, a ServerHello. "[Raw read]" displays the raw data read from the input device (InputStream), before any processing has been performed.
[Raw read]: length = 5
0000: 16 03 01 06 F0                                     .....
[Raw read]: length = 1776
0000: 02 00 00 46 03 01 40 FC   31 10 79 AB 17 66 FA 8B  ...F..@.1.y..f..
0010: 3F AA FD 5E 48 23 FA 90   31 D8 3C B9 A3 2C 8C F5  ?..^H#..1.<..,..
0020: E9 81 9B A2 63 6C 20 40   FC 31 10 BD 8D A5 91 06  ....cl @.1......
0030: 8B E1 E6 80 C6 5A 5C D9   8D 0A AE CA 58 4A BA 36  .....Z\.....XJ.6
0040: B1 3D 04 8D 82 21 B4 00   04 00 0B 00 06 1B 00 06  .=...!..........
0050: 18 00 03 11 30 82 03 0D   30 82 02 76 A0 03 02 01  ....0...0..v....
0060: 02 02 01 01 30 0D 06 09   2A 86 48 86 F7 0D 01 01  ....0...*.H.....
0070: 04 05 00 30 63 31 0B 30   09 06 03 55 04 06 13 02  ...0c1.0...U....
0080: 55 53 31 0B 30 09 06 03   55 04 08 13 02 43 41 31  US1.0...U....CA1
0090: 14 30 12 06 03 55 04 07   13 0B 53 61 6E 74 61 20  .0...U....Santa
00A0: 43 6C 61 72 61 31 0C 30   0A 06 03 55 04 0A 13 03  Clara1.0...U....
00B0: 53 75 6E 31 0C 30 0A 06   03 55 04 0B 13 03 4A 57  Sun1.0...U....JW
00C0: 53 31 15 30 13 06 03 55   04 03 13 0C 4A 53 53 45  S1.0...U....JSSE
00D0: 20 54 65 73 74 20 43 41   30 1E 17 0D 30 34 30 37   Test CA0...0407
00E0: 31 39 32 30 33 30 35 31   5A 17 0D 33 31 31 32 30  19203051Z..31120
00F0: 35 32 30 33 30 35 31 5A   30 48 31 0B 30 09 06 03  5203051Z0H1.0...
0100: 55 04 06 13 02 55 53 31   0B 30 09 06 03 55 04 08  U....US1.0...U..
0110: 13 02 43 41 31 0C 30 0A   06 03 55 04 0A 13 03 53  ..CA1.0...U....S
0120: 75 6E 31 0D 30 0B 06 03   55 04 0B 13 04 4A 61 76  un1.0...U....Jav
0130: 61 31 0F 30 0D 06 03 55   04 03 13 06 62 6F 6E 67  a1.0...U....bong
0140: 6F 73 30 81 9F 30 0D 06   09 2A 86 48 86 F7 0D 01  os0..0...*.H....
0150: 01 01 05 00 03 81 8D 00   30 81 89 02 81 81 00 CC  ........0.......
0160: 09 74 CB 43 AB 6D ED F6   35 AA 0E 49 29 D9 E0 F0  .t.C.m..5..I)...
0170: A1 D5 E2 3E 8F 5E C5 CE   F4 DE C1 A4 F3 CB 8C 45  ...>.^.........E
0180: 0B 0F 6E 21 E1 00 65 CB   3C D1 5C EF 6A FB 5D 96  ..n!..e.<.\.j.].
0190: 93 F4 71 41 41 45 FF 37   86 4C AB F9 EA 9A 3F A5  ..qAAE.7.L....?.
01A0: 82 60 BF 0A 81 84 C9 3E   AC 0F 3D 20 3D AC A0 69  .`.....>..= =..i
01B0: EF CA 4A A7 94 AD C8 A5   CE 37 66 52 D1 25 43 CB  ..J......7fR.%C.
01C0: 10 44 07 1E 93 74 D9 68   01 D7 06 48 C9 0D 52 2D  .D...t.h...H..R-
01D0: D5 6A 2E A6 48 4C 59 E2   5C C6 C1 5C C8 4C 1B 02  .j..HLY.\..\.L..
01E0: 03 01 00 01 A3 81 EB 30   81 E8 30 09 06 03 55 1D  .......0..0...U.
01F0: 13 04 02 30 00 30 2C 06   09 60 86 48 01 86 F8 42  ...0.0,..`.H...B
0200: 01 0D 04 1F 16 1D 4F 70   65 6E 53 53 4C 20 47 65  ......OpenSSL Ge
0210: 6E 65 72 61 74 65 64 20   43 65 72 74 69 66 69 63  nerated Certific
0220: 61 74 65 30 1D 06 03 55   1D 0E 04 16 04 14 58 D7  ate0...U......X.
0230: 3A A9 37 AA 3E 14 27 FC   EC CC 45 08 04 8E 2A 8B  :.7.>.'...E...*.
0240: 77 28 30 81 8D 06 03 55   1D 23 04 81 85 30 81 82  w(0....U.#...0..
0250: 80 14 08 A3 7E 35 96 15   FA B0 F5 1B 5F CD 4F 54  .....5......_.OT
0260: EF 31 33 70 E4 A7 A1 67   A4 65 30 63 31 0B 30 09  .13p...g.e0c1.0.
0270: 06 03 55 04 06 13 02 55   53 31 0B 30 09 06 03 55  ..U....US1.0...U
0280: 04 08 13 02 43 41 31 14   30 12 06 03 55 04 07 13  ....CA1.0...U...
0290: 0B 53 61 6E 74 61 20 43   6C 61 72 61 31 0C 30 0A  .Santa Clara1.0.
02A0: 06 03 55 04 0A 13 03 53   75 6E 31 0C 30 0A 06 03  ..U....Sun1.0...
02B0: 55 04 0B 13 03 4A 57 53   31 15 30 13 06 03 55 04  U....JWS1.0...U.
02C0: 03 13 0C 4A 53 53 45 20   54 65 73 74 20 43 41 82  ...JSSE Test CA.
02D0: 01 00 30 0D 06 09 2A 86   48 86 F7 0D 01 01 04 05  ..0...*.H.......
02E0: 00 03 81 81 00 05 3E 17   DA F2 05 CB 4E 9E BF 12  ......>.....N...
02F0: CE 13 76 FF B2 FB 7F 9C   3D 45 28 43 6C 98 28 E3  ..v.....=E(Cl.(.
0300: 92 17 C2 C6 F1 62 CA 60   C2 B0 EC E6 7E 4C 2F C2  .....b.`.....L/.
0310: 40 FE 06 CB 34 60 B1 F4   26 1C E8 46 39 24 E1 8A  @...4`..&..F9$..
0320: 71 F2 13 90 A4 0A 7B 0B   13 AB 51 68 53 D9 7A 31  q.........QhS.z1
0330: 5A C1 7E 3C 44 2C 49 70   57 25 F9 18 FE 5D A5 42  Z..<D,IpW%...].B
0340: 7F 3E 61 1F 29 A3 31 46   02 C6 D2 8C 27 79 40 76  .>a.).1F....'y@v
0350: 97 B6 25 19 BE 6C 6A 92   DC EF 11 BE E7 4A FF 2A  ..%..lj......J.*
0360: E6 D6 AC 39 31 00 03 01   30 82 02 FD 30 82 02 66  ...91...0...0..f
0370: A0 03 02 01 02 02 01 00   30 0D 06 09 2A 86 48 86  ........0...*.H.
0380: F7 0D 01 01 04 05 00 30   63 31 0B 30 09 06 03 55  .......0c1.0...U
0390: 04 06 13 02 55 53 31 0B   30 09 06 03 55 04 08 13  ....US1.0...U...
03A0: 02 43 41 31 14 30 12 06   03 55 04 07 13 0B 53 61  .CA1.0...U....Sa
03B0: 6E 74 61 20 43 6C 61 72   61 31 0C 30 0A 06 03 55  nta Clara1.0...U
03C0: 04 0A 13 03 53 75 6E 31   0C 30 0A 06 03 55 04 0B  ....Sun1.0...U..
03D0: 13 03 4A 57 53 31 15 30   13 06 03 55 04 03 13 0C  ..JWS1.0...U....
03E0: 4A 53 53 45 20 54 65 73   74 20 43 41 30 1E 17 0D  JSSE Test CA0...
03F0: 30 34 30 37 31 39 32 30   33 30 31 35 5A 17 0D 33  040719203015Z..3
0400: 31 31 32 30 35 32 30 33   30 31 35 5A 30 63 31 0B  11205203015Z0c1.
0410: 30 09 06 03 55 04 06 13   02 55 53 31 0B 30 09 06  0...U....US1.0..
0420: 03 55 04 08 13 02 43 41   31 14 30 12 06 03 55 04  .U....CA1.0...U.
0430: 07 13 0B 53 61 6E 74 61   20 43 6C 61 72 61 31 0C  ...Santa Clara1.
0440: 30 0A 06 03 55 04 0A 13   03 53 75 6E 31 0C 30 0A  0...U....Sun1.0.
0450: 06 03 55 04 0B 13 03 4A   57 53 31 15 30 13 06 03  ..U....JWS1.0...
0460: 55 04 03 13 0C 4A 53 53   45 20 54 65 73 74 20 43  U....JSSE Test C
0470: 41 30 81 9F 30 0D 06 09   2A 86 48 86 F7 0D 01 01  A0..0...*.H.....
0480: 01 05 00 03 81 8D 00 30   81 89 02 81 81 00 9A 0A  .......0........
0490: B6 45 66 D5 DE 4A D9 3C   8C AC A6 B5 A5 88 B4 CF  .Ef..J.<........
04A0: 14 E1 A6 1B 25 25 4F 44   C9 1F 22 38 32 29 CF A1  ....%%OD.."82)..
04B0: 7C 18 30 93 DC 2B EC 2B   67 EE 2E 08 66 2D 0F 47  ..0..+.+g...f-.G
04C0: E0 12 3A DC E0 03 E9 65   16 F6 18 C6 16 14 56 24  ..:....e......V$
04D0: 55 7D 32 3E F9 66 A2 DD   55 EB 4D 0A 67 C7 5D 21  U.2>.f..U.M.g.]!
04E0: 9B 29 EA 2E 51 C5 83 A3   55 FF 35 CA A6 99 8F 46  .)..Q...U.5....F
04F0: F8 8E 56 BB A2 B1 39 83   D8 61 42 79 E0 95 78 FA  ..V...9..aBy..x.
0500: C6 E3 65 B0 FD 74 2D 64   51 71 04 F2 A1 91 02 03  ..e..t-dQq......
0510: 01 00 01 A3 81 C0 30 81   BD 30 1D 06 03 55 1D 0E  ......0..0...U..
0520: 04 16 04 14 08 A3 7E 35   96 15 FA B0 F5 1B 5F CD  .......5......_.
0530: 4F 54 EF 31 33 70 E4 A7   30 81 8D 06 03 55 1D 23  OT.13p..0....U.#
0540: 04 81 85 30 81 82 80 14   08 A3 7E 35 96 15 FA B0  ...0.......5....
0550: F5 1B 5F CD 4F 54 EF 31   33 70 E4 A7 A1 67 A4 65  .._.OT.13p...g.e
0560: 30 63 31 0B 30 09 06 03   55 04 06 13 02 55 53 31  0c1.0...U....US1
0570: 0B 30 09 06 03 55 04 08   13 02 43 41 31 14 30 12  .0...U....CA1.0.
0580: 06 03 55 04 07 13 0B 53   61 6E 74 61 20 43 6C 61  ..U....Santa Cla
0590: 72 61 31 0C 30 0A 06 03   55 04 0A 13 03 53 75 6E  ra1.0...U....Sun
05A0: 31 0C 30 0A 06 03 55 04   0B 13 03 4A 57 53 31 15  1.0...U....JWS1.
05B0: 30 13 06 03 55 04 03 13   0C 4A 53 53 45 20 54 65  0...U....JSSE Te
05C0: 73 74 20 43 41 82 01 00   30 0C 06 03 55 1D 13 04  st CA...0...U...
05D0: 05 30 03 01 01 FF 30 0D   06 09 2A 86 48 86 F7 0D  .0....0...*.H...
05E0: 01 01 04 05 00 03 81 81   00 73 6A 46 A2 05 E3 D8  .........sjF....
05F0: 6E 5C F4 18 A2 74 BC CF   EB 0C 5B FF 81 1C 28 85  n\...t....[...(.
0600: C7 FA E4 ED 5C 4F 71 22   FB 26 E3 01 3D 0C 10 AA  ....\Oq".&..=...
0610: BB 3E 90 ED 0E 1F 0C 9B   B1 8C 49 6A 51 E4 C3 52  .>........IjQ..R
0620: D6 FB 42 6C B4 A9 A9 57   A5 84 00 42 6D 37 37 6D  ..Bl...W...Bm77m
0630: C7 6C 23 BC DC 60 D1 9D   6F B3 75 47 3A 15 33 1A  .l#..`..o.uG:.3.
0640: EC 90 09 9D F9 EB BD 88   96 E7 1D 41 BC 01 8D CA  ...........A....
0650: 88 D9 5B 04 09 8F 3E EA   C8 15 A0 AA 4E 85 95 AE  ..[...>.....N...
0660: 2F 0E 31 92 AC 3C FB 2F   C4 0D 00 00 7F 02 01 02  /.1..<./........
0670: 00 7A 00 78 30 76 31 0B   30 09 06 03 55 04 06 13  .z.x0v1.0...U...
0680: 02 55 53 31 0B 30 09 06   03 55 04 08 13 02 43 41  .US1.0...U....CA
0690: 31 12 30 10 06 03 55 04   07 13 09 43 75 70 65 72  1.0...U....Cuper
06A0: 74 69 6E 6F 31 1F 30 1D   06 03 55 04 0A 13 16 53  tino1.0...U....S
06B0: 75 6E 20 4D 69 63 72 6F   73 79 73 74 65 6D 73 2C  un Microsystems,
06C0: 20 49 6E 63 2E 31 16 30   14 06 03 55 04 0B 13 0D   Inc.1.0...U....
06D0: 4A 61 76 61 20 53 6F 66   74 77 61 72 65 31 0D 30  Java Software1.0
06E0: 0B 06 03 55 04 03 13 04   44 75 6B 65 0E 00 00 00  ...U....Duke....
main, READ: TLSv1 Handshake, length = 1776
The data is unpackaged, and if the message is in the SSL/TLS format, it is parsed into a ServerHello. If you connected to a non-SSL/TLS socket (plaintext?), the received data will not be in SSL/TLS format, and you'll have problems connecting.

The ServerHello specifies several things:

  • The server's random data, also used to initialize the cryptographic algorithms,
  • the identifier of this session (if the client wants to try to rejoin this session using a different connection, it can send this ID in its ClientHello. If the client session ID equals the server session ID, an abbreviated handshake takes place, and the previously established parameters are used),
  • the selected cipher suite,
  • and the compression method (none in this case).
Lastly note that the ServerHello has specified that the connection should use "TLSv1", rather than "SSLv3."

*** ServerHello, TLSv1
RandomCookie:  GMT: 1073492240 bytes = { 121, 171, 23, 102, 250, 139, 63,
170, 253, 94, 72, 35, 250, 144, 49, 216, 60, 185, 163, 44, 140, 245, 233,
129, 155, 162, 99, 108 }
Session ID:  {64, 252, 49, 16, 189, 141, 165, 145, 6, 139, 225, 230, 128,
198, 90, 92, 217, 141, 10, 174, 202, 88, 74, 186, 54, 177, 61, 4, 141, 130,
33, 180}
Cipher Suite: SSL_RSA_WITH_RC4_128_MD5
Compression Method: 0
***
%% Created:  [Session-1, SSL_RSA_WITH_RC4_128_MD5]
** SSL_RSA_WITH_RC4_128_MD5
[read] MD5 and SHA1 hashes:  len = 74
0000: 02 00 00 46 03 01 40 FC   31 10 79 AB 17 66 FA 8B  ...F..@.1.y..f..
0010: 3F AA FD 5E 48 23 FA 90   31 D8 3C B9 A3 2C 8C F5  ?..^H#..1.<..,..
0020: E9 81 9B A2 63 6C 20 40   FC 31 10 BD 8D A5 91 06  ....cl @.1......
0030: 8B E1 E6 80 C6 5A 5C D9   8D 0A AE CA 58 4A BA 36  .....Z\.....XJ.6
0040: B1 3D 04 8D 82 21 B4 00   04 00                    .=...!....
The server next identifies itself to the client by passing a Certificate chain. In this example, we have a certificate for the subject "bongos", signed by the issuer "JSSE Test CA". We know that "JSSE Test CA" is a trusted CA, so if the certificate chain verifies correctly by our X509TrustManager, we can accept this connection.

There are many different ways of establishing trust, so if the default X509TrustManager is not doing the types of trust management you need, you can supply your own X509TrustManager to the SSLContext.

*** Certificate chain
chain [0] = [
[
  Version: V3
  Subject:
  CN=bongos, OU=Java, O=Sun, ST=CA, C=US
  Signature Algorithm: MD5withRSA, OID = 1.2.840.113549.1.1.4

  Key:  Sun RSA public key, 1024 bits
  modulus: 143279610700427050704216702734995283650706638118826657356308087
  682552751165540126665070195006746918193702313900836063802045448392771274
  463088345157808670190122017153821642985630288017629294930800445939721128
  735250668515619736933648548512047941708018130926985936894512063397816602
  623867976474763783110866258971
  public exponent: 65537
  Validity: [From: Mon Jul 19 13:30:51 PDT 2004,
               To: Fri Dec 05 12:30:51 PST 2031]
  Issuer: CN=JSSE Test CA, OU=JWS, O=Sun,
      L=Santa Clara, ST=CA, C=US
  SerialNumber: [    01]

Certificate Extensions: 3

[1]: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: 58 D7 3A A9 37 AA 3E 14   27 FC EC CC 45 08 04 8E  X.:.7.>.'...E...
0010: 2A 8B 77 28                                        *.w(
]
]

[2]: ObjectId: 2.5.29.35 Criticality=false
AuthorityKeyIdentifier [
KeyIdentifier [
0000: 08 A3 7E 35 96 15 FA B0   F5 1B 5F CD 4F 54 EF 31  ...5......_.OT.1
0010: 33 70 E4 A7                                        3p..
]

[CN=JSSE Test CA, OU=JWS, O=Sun, L=Santa Clara, ST=CA, C=US]
SerialNumber: [    00]
]

[3]: ObjectId: 2.5.29.19 Criticality=false
BasicConstraints:[
CA:false
PathLen: undefined
]

]
  Algorithm: [MD5withRSA]
  Signature:
0000: 05 3E 17 DA F2 05 CB 4E   9E BF 12 CE 13 76 FF B2  .>.....N.....v..
0010: FB 7F 9C 3D 45 28 43 6C   98 28 E3 92 17 C2 C6 F1  ...=E(Cl.(......
0020: 62 CA 60 C2 B0 EC E6 7E   4C 2F C2 40 FE 06 CB 34  b.`.....L/.@...4
0030: 60 B1 F4 26 1C E8 46 39   24 E1 8A 71 F2 13 90 A4  `..&..F9$..q....
0040: 0A 7B 0B 13 AB 51 68 53   D9 7A 31 5A C1 7E 3C 44  .....QhS.z1Z..<D
0050: 2C 49 70 57 25 F9 18 FE   5D A5 42 7F 3E 61 1F 29  ,IpW%...].B.>a.)
0060: A3 31 46 02 C6 D2 8C 27   79 40 76 97 B6 25 19 BE  .1F....'y@v..%..
0070: 6C 6A 92 DC EF 11 BE E7   4A FF 2A E6 D6 AC 39 31  lj......J.*...91

]
chain [1] = [
[
  Version: V3
  Subject: CN=JSSE Test CA, OU=JWS, O=Sun,
      L=Santa Clara, ST=CA, C=US
  Signature Algorithm: MD5withRSA, OID = 1.2.840.113549.1.1.4

  Key:  Sun RSA public key, 1024 bits
  modulus: 108171861314934294923646852258201093253619460299818135230481040
  615923025149195168140458238629251726950220398889722590740552079782864577
  976838691751841449679901644183317203824143803940037883199193775839934767
  304560313841716869284745769157293013188246601563271959824290073095150730
  505329011956986145636520993169
  public exponent: 65537
  Validity: [From: Mon Jul 19 13:30:15 PDT 2004,
               To: Fri Dec 05 12:30:15 PST 2031]
  Issuer: CN=JSSE Test CA, OU=JWS, O=Sun,
      L=Santa Clara, ST=CA, C=US
  SerialNumber: [    00]

Certificate Extensions: 3
[1]: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: 08 A3 7E 35 96 15 FA B0   F5 1B 5F CD 4F 54 EF 31  ...5......_.OT.1
0010: 33 70 E4 A7                                        3p..
]
]

[2]: ObjectId: 2.5.29.35 Criticality=false
AuthorityKeyIdentifier [
KeyIdentifier [
0000: 08 A3 7E 35 96 15 FA B0   F5 1B 5F CD 4F 54 EF 31  ...5......_.OT.1
0010: 33 70 E4 A7                                        3p..
]

[CN=JSSE Test CA, OU=JWS, O=Sun, L=Santa Clara, ST=CA, C=US]
SerialNumber: [    00]
]

[3]: ObjectId: 2.5.29.19 Criticality=false
BasicConstraints:[
CA:true
PathLen:2147483647
]

]
  Algorithm: [MD5withRSA]
  Signature:
0000: 73 6A 46 A2 05 E3 D8 6E   5C F4 18 A2 74 BC CF EB  sjF....n\...t...
0010: 0C 5B FF 81 1C 28 85 C7   FA E4 ED 5C 4F 71 22 FB  .[...(.....\Oq".
0020: 26 E3 01 3D 0C 10 AA BB   3E 90 ED 0E 1F 0C 9B B1  &..=....>.......
0030: 8C 49 6A 51 E4 C3 52 D6   FB 42 6C B4 A9 A9 57 A5  .IjQ..R..Bl...W.
0040: 84 00 42 6D 37 37 6D C7   6C 23 BC DC 60 D1 9D 6F  ..Bm77m.l#..`..o
0050: B3 75 47 3A 15 33 1A EC   90 09 9D F9 EB BD 88 96  .uG:.3..........
0060: E7 1D 41 BC 01 8D CA 88   D9 5B 04 09 8F 3E EA C8  ..A......[...>..
0070: 15 A0 AA 4E 85 95 AE 2F   0E 31 92 AC 3C FB 2F C4  ...N.../.1..<./.

]
We recoginise this cert! We can trust it, and continue on with the handshake.
***
Found trusted certificate:
[
[
  Version: V3
  Subject: CN=JSSE Test CA, OU=JWS, O=Sun, L=Santa Clara, ST=CA, C=US
  Signature Algorithm: MD5withRSA, OID = 1.2.840.113549.1.1.4

  Key:  Sun RSA public key, 1024 bits
  modulus: 108171861314934294923646852258201093253619460299818135230481040
  615923025149195168140458238629251726950220398889722590740552079782864577
  976838691751841449679901644183317203824143803940037883199193775839934767
  304560313841716869284745769157293013188246601563271959824290073095150730
  505329011956986145636520993169
  public exponent: 65537
  Validity: [From: Mon Jul 19 13:30:15 PDT 2004,
               To: Fri Dec 05 12:30:15 PST 2031]
  Issuer: CN=JSSE Test CA, OU=JWS, O=Sun, L=Santa Clara, ST=CA, C=US
  SerialNumber: [    00]

Certificate Extensions: 3
[1]: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: 08 A3 7E 35 96 15 FA B0   F5 1B 5F CD 4F 54 EF 31  ...5......_.OT.1
0010: 33 70 E4 A7                                        3p..
]
]

[2]: ObjectId: 2.5.29.35 Criticality=false
AuthorityKeyIdentifier [
KeyIdentifier [
0000: 08 A3 7E 35 96 15 FA B0   F5 1B 5F CD 4F 54 EF 31  ...5......_.OT.1
0010: 33 70 E4 A7                                        3p..
]

[CN=JSSE Test CA, OU=JWS, O=Sun, L=Santa Clara, ST=CA, C=US]
SerialNumber: [    00]
]

[3]: ObjectId: 2.5.29.19 Criticality=false
BasicConstraints:[
CA:true
PathLen:2147483647
]

]
  Algorithm: [MD5withRSA]
  Signature:
0000: 73 6A 46 A2 05 E3 D8 6E   5C F4 18 A2 74 BC CF EB  sjF....n\...t...
0010: 0C 5B FF 81 1C 28 85 C7   FA E4 ED 5C 4F 71 22 FB  .[...(.....\Oq".
0020: 26 E3 01 3D 0C 10 AA BB   3E 90 ED 0E 1F 0C 9B B1  &..=....>.......
0030: 8C 49 6A 51 E4 C3 52 D6   FB 42 6C B4 A9 A9 57 A5  .IjQ..R..Bl...W.
0040: 84 00 42 6D 37 37 6D C7   6C 23 BC DC 60 D1 9D 6F  ..Bm77m.l#..`..o
0050: B3 75 47 3A 15 33 1A EC   90 09 9D F9 EB BD 88 96  .uG:.3..........
0060: E7 1D 41 BC 01 8D CA 88   D9 5B 04 09 8F 3E EA C8  ..A......[...>..
0070: 15 A0 AA 4E 85 95 AE 2F   0E 31 92 AC 3C FB 2F C4  ...N.../.1..<./.

]
We read the next few bytes of the handshake...
[read] MD5 and SHA1 hashes:  len = 1567
0000: 0B 00 06 1B 00 06 18 00   03 11 30 82 03 0D 30 82  ..........0...0.
0010: 02 76 A0 03 02 01 02 02   01 01 30 0D 06 09 2A 86  .v........0...*.
0020: 48 86 F7 0D 01 01 04 05   00 30 63 31 0B 30 09 06  H........0c1.0..
0030: 03 55 04 06 13 02 55 53   31 0B 30 09 06 03 55 04  .U....US1.0...U.
0040: 08 13 02 43 41 31 14 30   12 06 03 55 04 07 13 0B  ...CA1.0...U....
0050: 53 61 6E 74 61 20 43 6C   61 72 61 31 0C 30 0A 06  Santa Clara1.0..
0060: 03 55 04 0A 13 03 53 75   6E 31 0C 30 0A 06 03 55  .U....Sun1.0...U
0070: 04 0B 13 03 4A 57 53 31   15 30 13 06 03 55 04 03  ....JWS1.0...U..
0080: 13 0C 4A 53 53 45 20 54   65 73 74 20 43 41 30 1E  ..JSSE Test CA0.
0090: 17 0D 30 34 30 37 31 39   32 30 33 30 35 31 5A 17  ..040719203051Z.
00A0: 0D 33 31 31 32 30 35 32   30 33 30 35 31 5A 30 48  .311205203051Z0H
00B0: 31 0B 30 09 06 03 55 04   06 13 02 55 53 31 0B 30  1.0...U....US1.0
00C0: 09 06 03 55 04 08 13 02   43 41 31 0C 30 0A 06 03  ...U....CA1.0...
00D0: 55 04 0A 13 03 53 75 6E   31 0D 30 0B 06 03 55 04  U....Sun1.0...U.
00E0: 0B 13 04 4A 61 76 61 31   0F 30 0D 06 03 55 04 03  ...Java1.0...U..
00F0: 13 06 62 6F 6E 67 6F 73   30 81 9F 30 0D 06 09 2A  ..bongos0..0...*
0100: 86 48 86 F7 0D 01 01 01   05 00 03 81 8D 00 30 81  .H............0.
0110: 89 02 81 81 00 CC 09 74   CB 43 AB 6D ED F6 35 AA  .......t.C.m..5.
0120: 0E 49 29 D9 E0 F0 A1 D5   E2 3E 8F 5E C5 CE F4 DE  .I)......>.^....
0130: C1 A4 F3 CB 8C 45 0B 0F   6E 21 E1 00 65 CB 3C D1  .....E..n!..e.<.
0140: 5C EF 6A FB 5D 96 93 F4   71 41 41 45 FF 37 86 4C  \.j.]...qAAE.7.L
0150: AB F9 EA 9A 3F A5 82 60   BF 0A 81 84 C9 3E AC 0F  ....?..`.....>..
0160: 3D 20 3D AC A0 69 EF CA   4A A7 94 AD C8 A5 CE 37  = =..i..J......7
0170: 66 52 D1 25 43 CB 10 44   07 1E 93 74 D9 68 01 D7  fR.%C..D...t.h..
0180: 06 48 C9 0D 52 2D D5 6A   2E A6 48 4C 59 E2 5C C6  .H..R-.j..HLY.\.
0190: C1 5C C8 4C 1B 02 03 01   00 01 A3 81 EB 30 81 E8  .\.L.........0..
01A0: 30 09 06 03 55 1D 13 04   02 30 00 30 2C 06 09 60  0...U....0.0,..`
01B0: 86 48 01 86 F8 42 01 0D   04 1F 16 1D 4F 70 65 6E  .H...B......Open
01C0: 53 53 4C 20 47 65 6E 65   72 61 74 65 64 20 43 65  SSL Generated Ce
01D0: 72 74 69 66 69 63 61 74   65 30 1D 06 03 55 1D 0E  rtificate0...U..
01E0: 04 16 04 14 58 D7 3A A9   37 AA 3E 14 27 FC EC CC  ....X.:.7.>.'...
01F0: 45 08 04 8E 2A 8B 77 28   30 81 8D 06 03 55 1D 23  E...*.w(0....U.#
0200: 04 81 85 30 81 82 80 14   08 A3 7E 35 96 15 FA B0  ...0.......5....
0210: F5 1B 5F CD 4F 54 EF 31   33 70 E4 A7 A1 67 A4 65  .._.OT.13p...g.e
0220: 30 63 31 0B 30 09 06 03   55 04 06 13 02 55 53 31  0c1.0...U....US1
0230: 0B 30 09 06 03 55 04 08   13 02 43 41 31 14 30 12  .0...U....CA1.0.
0240: 06 03 55 04 07 13 0B 53   61 6E 74 61 20 43 6C 61  ..U....Santa Cla
0250: 72 61 31 0C 30 0A 06 03   55 04 0A 13 03 53 75 6E  ra1.0...U....Sun
0260: 31 0C 30 0A 06 03 55 04   0B 13 03 4A 57 53 31 15  1.0...U....JWS1.
0270: 30 13 06 03 55 04 03 13   0C 4A 53 53 45 20 54 65  0...U....JSSE Te
0280: 73 74 20 43 41 82 01 00   30 0D 06 09 2A 86 48 86  st CA...0...*.H.
0290: F7 0D 01 01 04 05 00 03   81 81 00 05 3E 17 DA F2  ............>...
02A0: 05 CB 4E 9E BF 12 CE 13   76 FF B2 FB 7F 9C 3D 45  ..N.....v.....=E
02B0: 28 43 6C 98 28 E3 92 17   C2 C6 F1 62 CA 60 C2 B0  (Cl.(......b.`..
02C0: EC E6 7E 4C 2F C2 40 FE   06 CB 34 60 B1 F4 26 1C  ...L/.@...4`..&.
02D0: E8 46 39 24 E1 8A 71 F2   13 90 A4 0A 7B 0B 13 AB  .F9$..q.........
02E0: 51 68 53 D9 7A 31 5A C1   7E 3C 44 2C 49 70 57 25  QhS.z1Z..<D,IpW%
02F0: F9 18 FE 5D A5 42 7F 3E   61 1F 29 A3 31 46 02 C6  ...].B.>a.).1F..
0300: D2 8C 27 79 40 76 97 B6   25 19 BE 6C 6A 92 DC EF  ..'y@v..%..lj...
0310: 11 BE E7 4A FF 2A E6 D6   AC 39 31 00 03 01 30 82  ...J.*...91...0.
0320: 02 FD 30 82 02 66 A0 03   02 01 02 02 01 00 30 0D  ..0..f........0.
0330: 06 09 2A 86 48 86 F7 0D   01 01 04 05 00 30 63 31  ..*.H........0c1
0340: 0B 30 09 06 03 55 04 06   13 02 55 53 31 0B 30 09  .0...U....US1.0.
0350: 06 03 55 04 08 13 02 43   41 31 14 30 12 06 03 55  ..U....CA1.0...U
0360: 04 07 13 0B 53 61 6E 74   61 20 43 6C 61 72 61 31  ....Santa Clara1
0370: 0C 30 0A 06 03 55 04 0A   13 03 53 75 6E 31 0C 30  .0...U....Sun1.0
0380: 0A 06 03 55 04 0B 13 03   4A 57 53 31 15 30 13 06  ...U....JWS1.0..
0390: 03 55 04 03 13 0C 4A 53   53 45 20 54 65 73 74 20  .U....JSSE Test
03A0: 43 41 30 1E 17 0D 30 34   30 37 31 39 32 30 33 30  CA0...0407192030
03B0: 31 35 5A 17 0D 33 31 31   32 30 35 32 30 33 30 31  15Z..31120520301
03C0: 35 5A 30 63 31 0B 30 09   06 03 55 04 06 13 02 55  5Z0c1.0...U....U
03D0: 53 31 0B 30 09 06 03 55   04 08 13 02 43 41 31 14  S1.0...U....CA1.
03E0: 30 12 06 03 55 04 07 13   0B 53 61 6E 74 61 20 43  0...U....Santa C
03F0: 6C 61 72 61 31 0C 30 0A   06 03 55 04 0A 13 03 53  lara1.0...U....S
0400: 75 6E 31 0C 30 0A 06 03   55 04 0B 13 03 4A 57 53  un1.0...U....JWS
0410: 31 15 30 13 06 03 55 04   03 13 0C 4A 53 53 45 20  1.0...U....JSSE
0420: 54 65 73 74 20 43 41 30   81 9F 30 0D 06 09 2A 86  Test CA0..0...*.
0430: 48 86 F7 0D 01 01 01 05   00 03 81 8D 00 30 81 89  H............0..
0440: 02 81 81 00 9A 0A B6 45   66 D5 DE 4A D9 3C 8C AC  .......Ef..J.<..
0450: A6 B5 A5 88 B4 CF 14 E1   A6 1B 25 25 4F 44 C9 1F  ..........%%OD..
0460: 22 38 32 29 CF A1 7C 18   30 93 DC 2B EC 2B 67 EE  "82)....0..+.+g.
0470: 2E 08 66 2D 0F 47 E0 12   3A DC E0 03 E9 65 16 F6  ..f-.G..:....e..
0480: 18 C6 16 14 56 24 55 7D   32 3E F9 66 A2 DD 55 EB  ....V$U.2>.f..U.
0490: 4D 0A 67 C7 5D 21 9B 29   EA 2E 51 C5 83 A3 55 FF  M.g.]!.)..Q...U.
04A0: 35 CA A6 99 8F 46 F8 8E   56 BB A2 B1 39 83 D8 61  5....F..V...9..a
04B0: 42 79 E0 95 78 FA C6 E3   65 B0 FD 74 2D 64 51 71  By..x...e..t-dQq
04C0: 04 F2 A1 91 02 03 01 00   01 A3 81 C0 30 81 BD 30  ............0..0
04D0: 1D 06 03 55 1D 0E 04 16   04 14 08 A3 7E 35 96 15  ...U.........5..
04E0: FA B0 F5 1B 5F CD 4F 54   EF 31 33 70 E4 A7 30 81  ...._.OT.13p..0.
04F0: 8D 06 03 55 1D 23 04 81   85 30 81 82 80 14 08 A3  ...U.#...0......
0500: 7E 35 96 15 FA B0 F5 1B   5F CD 4F 54 EF 31 33 70  .5......_.OT.13p
0510: E4 A7 A1 67 A4 65 30 63   31 0B 30 09 06 03 55 04  ...g.e0c1.0...U.
0520: 06 13 02 55 53 31 0B 30   09 06 03 55 04 08 13 02  ...US1.0...U....
0530: 43 41 31 14 30 12 06 03   55 04 07 13 0B 53 61 6E  CA1.0...U....San
0540: 74 61 20 43 6C 61 72 61   31 0C 30 0A 06 03 55 04  ta Clara1.0...U.
0550: 0A 13 03 53 75 6E 31 0C   30 0A 06 03 55 04 0B 13  ...Sun1.0...U...
0560: 03 4A 57 53 31 15 30 13   06 03 55 04 03 13 0C 4A  .JWS1.0...U....J
0570: 53 53 45 20 54 65 73 74   20 43 41 82 01 00 30 0C  SSE Test CA...0.
0580: 06 03 55 1D 13 04 05 30   03 01 01 FF 30 0D 06 09  ..U....0....0...
0590: 2A 86 48 86 F7 0D 01 01   04 05 00 03 81 81 00 73  *.H............s
05A0: 6A 46 A2 05 E3 D8 6E 5C   F4 18 A2 74 BC CF EB 0C  jF....n\...t....
05B0: 5B FF 81 1C 28 85 C7 FA   E4 ED 5C 4F 71 22 FB 26  [...(.....\Oq".&
05C0: E3 01 3D 0C 10 AA BB 3E   90 ED 0E 1F 0C 9B B1 8C  ..=....>........
05D0: 49 6A 51 E4 C3 52 D6 FB   42 6C B4 A9 A9 57 A5 84  IjQ..R..Bl...W..
05E0: 00 42 6D 37 37 6D C7 6C   23 BC DC 60 D1 9D 6F B3  .Bm77m.l#..`..o.
05F0: 75 47 3A 15 33 1A EC 90   09 9D F9 EB BD 88 96 E7  uG:.3...........
0600: 1D 41 BC 01 8D CA 88 D9   5B 04 09 8F 3E EA C8 15  .A......[...>...
0610: A0 AA 4E 85 95 AE 2F 0E   31 92 AC 3C FB 2F C4     ..N.../.1..<./.
...and parse it to find that it's a CertificateRequest message.

The server is asking the client to identify itself with a X509 certificate subject having the common name (CN=) "Duke". The server's X509TrustManager has the option of rejecting any credentials provided by the client (or lack thereof). In a real-world situation, you'd probably use a certificate signed by a CA, and the list of trusted CA's would be included in this message instead.

Lastly, we receive the ServerHelloDone message, which signals to the client that the server has finished sending its part of the handshake.

*** CertificateRequest
Cert Types: RSA, DSS,
Cert Authorities:
CN=Duke, OU=Java Software, O="Sun Microsystems, Inc.",
L=Cupertino, ST=CA, C=US>
[read] MD5 and SHA1 hashes:  len = 131
0000: 0D 00 00 7F 02 01 02 00   7A 00 78 30 76 31 0B 30  ........z.x0v1.0
0010: 09 06 03 55 04 06 13 02   55 53 31 0B 30 09 06 03  ...U....US1.0...
0020: 55 04 08 13 02 43 41 31   12 30 10 06 03 55 04 07  U....CA1.0...U..
0030: 13 09 43 75 70 65 72 74   69 6E 6F 31 1F 30 1D 06  ..Cupertino1.0..
0040: 03 55 04 0A 13 16 53 75   6E 20 4D 69 63 72 6F 73  .U....Sun Micros
0050: 79 73 74 65 6D 73 2C 20   49 6E 63 2E 31 16 30 14  ystems, Inc.1.0.
0060: 06 03 55 04 0B 13 0D 4A   61 76 61 20 53 6F 66 74  ..U....Java Soft
0070: 77 61 72 65 31 0D 30 0B   06 03 55 04 03 13 04 44  ware1.0...U....D
0080: 75 6B 65                                           uke
*** ServerHelloDone
[read] MD5 and SHA1 hashes:  len = 4
0000: 0E 00 00 00                                        ....
We need to send client credentials back to the server, so the client's X509KeyManager is now consulted. We look for a match between the list of accepted issuers (above), and the certificates we have in our KeyStore. In this case (luckily?), there is a match: we have credentials for "duke". It's now up to the server's X509TrustManager to decide whether to accept these credentials.
matching alias: duke
*** Certificate chain
chain [0] = [
[
  Version: V1
  Subject: CN=Duke, OU=Java Software, O="Sun Microsystems, Inc.",
  L=Cupertino, ST=CA, C=US
  Signature Algorithm: MD5withRSA, OID = 1.2.840.113549.1.1.4

  Key:  Sun RSA public key, 1024 bits
  modulus: 134968166047563266914058280571444028986498087544923991226919517
  667593269213420979048109900052353578998293280426361122296881234393722020
  704208851688212064483570055963805034839797994154526862998272017486468599
  962268346037652120279791547218281230795146025359480589335682217749874703
  510467348902637769973696151441
  public exponent: 65537
  Validity: [From: Tue May 22 16:46:46 PDT 2001,
               To: Sun May 22 16:46:46 PDT 2011]
  Issuer: CN=Duke, OU=Java Software, O="Sun Microsystems, Inc.",
  L=Cupertino, ST=CA, C=US
  SerialNumber: [    3b0afa66]

]
  Algorithm: [MD5withRSA]
  Signature:
0000: 5F B5 62 E9 A0 26 1D 8E   A2 7E 7C 02 08 36 3A 3E  _.b..&.......6:>
0010: C9 C2 45 03 DD F9 BC 06   FC 25 CF 30 92 91 B1 4E  ..E......%.0...N
0020: 62 17 08 48 14 68 80 CF   DD 89 11 EA 92 7F CE DD  b..H.h..........
0030: B4 FD 12 A8 71 C7 9E D7   C3 D0 E3 BD BB DE 20 92  ....q......... .
0040: C2 3B C8 DE CB 25 23 C0   8B B6 92 B9 0B 64 80 63  .;...%#......d.c
0050: D9 09 25 2D 7A CF 0A 31   B6 E9 CA C1 37 93 BC 0D  ..%-z..1....7...
0060: 4E 74 95 4F 58 31 DA AC   DF D8 BD 89 BD AF EC C8  Nt.OX1..........
0070: 2D 18 A2 BC B2 15 4F B7   28 6F D3 00 E1 72 9B 6C  -.....O.(o...r.l

]
***
In the case of this particular cipher suite, we must now pass a message called a ClientKeyExchange, which helps establish a shared secret between the two parties.

All of this data is eventually collected and written to the raw device.

*** ClientKeyExchange, RSA PreMasterSecret, TLSv1
Random Secret:  { 3, 1, 132, 84, 245, 214, 235, 245, 168, 8, 186, 250,
122, 34, 97, 45, 117, 220, 64, 232, 152, 249, 14, 178, 135, 128, 184,
26, 143, 104, 37, 184, 81, 208, 84, 69, 97, 138, 80, 201, 187, 14, 57,
83, 69, 120, 190, 121 }
[write] MD5 and SHA1 hashes:  len = 754
0000: 0B 00 02 68 00 02 65 00   02 62 30 82 02 5E 30 82  ...h..e..b0..^0.
0010: 01 C7 02 04 3B 0A FA 66   30 0D 06 09 2A 86 48 86  ....;..f0...*.H.
0020: F7 0D 01 01 04 05 00 30   76 31 0B 30 09 06 03 55  .......0v1.0...U
0030: 04 06 13 02 55 53 31 0B   30 09 06 03 55 04 08 13  ....US1.0...U...
0040: 02 43 41 31 12 30 10 06   03 55 04 07 13 09 43 75  .CA1.0...U....Cu
0050: 70 65 72 74 69 6E 6F 31   1F 30 1D 06 03 55 04 0A  pertino1.0...U..
0060: 13 16 53 75 6E 20 4D 69   63 72 6F 73 79 73 74 65  ..Sun Microsyste
0070: 6D 73 2C 20 49 6E 63 2E   31 16 30 14 06 03 55 04  ms, Inc.1.0...U.
0080: 0B 13 0D 4A 61 76 61 20   53 6F 66 74 77 61 72 65  ...Java Software
0090: 31 0D 30 0B 06 03 55 04   03 13 04 44 75 6B 65 30  1.0...U....Duke0
00A0: 1E 17 0D 30 31 30 35 32   32 32 33 34 36 34 36 5A  ...010522234646Z
00B0: 17 0D 31 31 30 35 32 32   32 33 34 36 34 36 5A 30  ..110522234646Z0
00C0: 76 31 0B 30 09 06 03 55   04 06 13 02 55 53 31 0B  v1.0...U....US1.
00D0: 30 09 06 03 55 04 08 13   02 43 41 31 12 30 10 06  0...U....CA1.0..
00E0: 03 55 04 07 13 09 43 75   70 65 72 74 69 6E 6F 31  .U....Cupertino1
00F0: 1F 30 1D 06 03 55 04 0A   13 16 53 75 6E 20 4D 69  .0...U....Sun Mi
0100: 63 72 6F 73 79 73 74 65   6D 73 2C 20 49 6E 63 2E  crosystems, Inc.
0110: 31 16 30 14 06 03 55 04   0B 13 0D 4A 61 76 61 20  1.0...U....Java
0120: 53 6F 66 74 77 61 72 65   31 0D 30 0B 06 03 55 04  Software1.0...U.
0130: 03 13 04 44 75 6B 65 30   81 9F 30 0D 06 09 2A 86  ...Duke0..0...*.
0140: 48 86 F7 0D 01 01 01 05   00 03 81 8D 00 30 81 89  H............0..
0150: 02 81 81 00 C0 33 77 E7   1F D0 CE CE BD 43 2F 8D  .....3w......C/.
0160: EB C6 D3 07 A9 00 F5 75   4D C8 4B 04 52 42 EE 69  .......uM.K.RB.i
0170: F3 30 E9 A0 C6 07 B7 C8   55 2D B9 5B 57 7A 4C AD  .0......U-.[WzL.
0180: 1A 30 63 5C 7D 6D 16 BF   ED 54 13 49 8A 1B E6 29  .0c\.m...T.I...)
0190: 26 20 85 F9 5E 2B 2F A7   12 9C 98 2D 83 F6 EE B1  & ..^+/....-....
01A0: 85 68 DA B5 8E 4C 1D 2D   8E 21 97 B0 30 C8 3A 57  .h...L.-.!..0.:W
01B0: F4 E1 18 9E F6 98 B2 D5   3D 8E D5 2B 09 E2 E1 A0  ........=..+....
01C0: 49 C1 A6 43 CE EA 57 7F   3B 5C 3A C9 BA DB B7 F0  I..C..W.;\:.....
01D0: 89 69 BF 91 02 03 01 00   01 30 0D 06 09 2A 86 48  .i.......0...*.H
01E0: 86 F7 0D 01 01 04 05 00   03 81 81 00 5F B5 62 E9  ............_.b.
01F0: A0 26 1D 8E A2 7E 7C 02   08 36 3A 3E C9 C2 45 03  .&.......6:>..E.
0200: DD F9 BC 06 FC 25 CF 30   92 91 B1 4E 62 17 08 48  .....%.0...Nb..H
0210: 14 68 80 CF DD 89 11 EA   92 7F CE DD B4 FD 12 A8  .h..............
0220: 71 C7 9E D7 C3 D0 E3 BD   BB DE 20 92 C2 3B C8 DE  q......... ..;..
0230: CB 25 23 C0 8B B6 92 B9   0B 64 80 63 D9 09 25 2D  .%#......d.c..%-
0240: 7A CF 0A 31 B6 E9 CA C1   37 93 BC 0D 4E 74 95 4F  z..1....7...Nt.O
0250: 58 31 DA AC DF D8 BD 89   BD AF EC C8 2D 18 A2 BC  X1..........-...
0260: B2 15 4F B7 28 6F D3 00   E1 72 9B 6C 10 00 00 82  ..O.(o...r.l....
0270: 00 80 4E DD E7 77 F1 91   6B 31 4E FA D6 61 D9 69  ..N..w..k1N..a.i
0280: 82 BD 22 40 83 FD 76 E6   FF A7 18 95 A0 04 28 0D  .."@..v.......(.
0290: 0D F7 44 6F 0C 42 4F 17   77 A0 99 56 2A 13 77 28  ..Do.BO.w..V*.w(
02A0: 0B 09 48 C1 B9 8C 09 ED   9F C6 2E 32 18 DB BD ED  ..H........2....
02B0: AF C3 AB E7 AD 8F DF 9E   AB 07 43 B4 50 EF 74 98  ..........C.P.t.
02C0: EA FC E8 4D C9 DA FC B0   B2 C7 D4 83 50 B5 84 B8  ...M........P...
02D0: 44 86 7B 5D 8A C2 F8 04   80 06 E6 84 42 33 B2 EE  D..]........B3..
02E0: 05 E6 D3 48 0E 23 E5 1F   63 4C 53 98 B8 8C 45 BA  ...H.#..cLS...E.
02F0: C8 19                                              ..
main, WRITE: TLSv1 Handshake, length = 754
[Raw write]: length = 759
0000: 16 03 01 02 F2 0B 00 02   68 00 02 65 00 02 62 30  ........h..e..b0
0010: 82 02 5E 30 82 01 C7 02   04 3B 0A FA 66 30 0D 06  ..^0.....;..f0..
0020: 09 2A 86 48 86 F7 0D 01   01 04 05 00 30 76 31 0B  .*.H........0v1.
0030: 30 09 06 03 55 04 06 13   02 55 53 31 0B 30 09 06  0...U....US1.0..
0040: 03 55 04 08 13 02 43 41   31 12 30 10 06 03 55 04  .U....CA1.0...U.
0050: 07 13 09 43 75 70 65 72   74 69 6E 6F 31 1F 30 1D  ...Cupertino1.0.
0060: 06 03 55 04 0A 13 16 53   75 6E 20 4D 69 63 72 6F  ..U....Sun Micro
0070: 73 79 73 74 65 6D 73 2C   20 49 6E 63 2E 31 16 30  systems, Inc.1.0
0080: 14 06 03 55 04 0B 13 0D   4A 61 76 61 20 53 6F 66  ...U....Java Sof
0090: 74 77 61 72 65 31 0D 30   0B 06 03 55 04 03 13 04  tware1.0...U....
00A0: 44 75 6B 65 30 1E 17 0D   30 31 30 35 32 32 32 33  Duke0...01052223
00B0: 34 36 34 36 5A 17 0D 31   31 30 35 32 32 32 33 34  4646Z..110522234
00C0: 36 34 36 5A 30 76 31 0B   30 09 06 03 55 04 06 13  646Z0v1.0...U...
00D0: 02 55 53 31 0B 30 09 06   03 55 04 08 13 02 43 41  .US1.0...U....CA
00E0: 31 12 30 10 06 03 55 04   07 13 09 43 75 70 65 72  1.0...U....Cuper
00F0: 74 69 6E 6F 31 1F 30 1D   06 03 55 04 0A 13 16 53  tino1.0...U....S
0100: 75 6E 20 4D 69 63 72 6F   73 79 73 74 65 6D 73 2C  un Microsystems,
0110: 20 49 6E 63 2E 31 16 30   14 06 03 55 04 0B 13 0D   Inc.1.0...U....
0120: 4A 61 76 61 20 53 6F 66   74 77 61 72 65 31 0D 30  Java Software1.0
0130: 0B 06 03 55 04 03 13 04   44 75 6B 65 30 81 9F 30  ...U....Duke0..0
0140: 0D 06 09 2A 86 48 86 F7   0D 01 01 01 05 00 03 81  ...*.H..........
0150: 8D 00 30 81 89 02 81 81   00 C0 33 77 E7 1F D0 CE  ..0.......3w....
0160: CE BD 43 2F 8D EB C6 D3   07 A9 00 F5 75 4D C8 4B  ..C/........uM.K
0170: 04 52 42 EE 69 F3 30 E9   A0 C6 07 B7 C8 55 2D B9  .RB.i.0......U-.
0180: 5B 57 7A 4C AD 1A 30 63   5C 7D 6D 16 BF ED 54 13  [WzL..0c\.m...T.
0190: 49 8A 1B E6 29 26 20 85   F9 5E 2B 2F A7 12 9C 98  I...)& ..^+/....
01A0: 2D 83 F6 EE B1 85 68 DA   B5 8E 4C 1D 2D 8E 21 97  -.....h...L.-.!.
01B0: B0 30 C8 3A 57 F4 E1 18   9E F6 98 B2 D5 3D 8E D5  .0.:W........=..
01C0: 2B 09 E2 E1 A0 49 C1 A6   43 CE EA 57 7F 3B 5C 3A  +....I..C..W.;\:
01D0: C9 BA DB B7 F0 89 69 BF   91 02 03 01 00 01 30 0D  ......i.......0.
01E0: 06 09 2A 86 48 86 F7 0D   01 01 04 05 00 03 81 81  ..*.H...........
01F0: 00 5F B5 62 E9 A0 26 1D   8E A2 7E 7C 02 08 36 3A  ._.b..&.......6:
0200: 3E C9 C2 45 03 DD F9 BC   06 FC 25 CF 30 92 91 B1  >..E......%.0...
0210: 4E 62 17 08 48 14 68 80   CF DD 89 11 EA 92 7F CE  Nb..H.h.........
0220: DD B4 FD 12 A8 71 C7 9E   D7 C3 D0 E3 BD BB DE 20  .....q.........
0230: 92 C2 3B C8 DE CB 25 23   C0 8B B6 92 B9 0B 64 80  ..;...%#......d.
0240: 63 D9 09 25 2D 7A CF 0A   31 B6 E9 CA C1 37 93 BC  c..%-z..1....7..
0250: 0D 4E 74 95 4F 58 31 DA   AC DF D8 BD 89 BD AF EC  .Nt.OX1.........
0260: C8 2D 18 A2 BC B2 15 4F   B7 28 6F D3 00 E1 72 9B  .-.....O.(o...r.
0270: 6C 10 00 00 82 00 80 4E   DD E7 77 F1 91 6B 31 4E  l......N..w..k1N
0280: FA D6 61 D9 69 82 BD 22   40 83 FD 76 E6 FF A7 18  ..a.i.."@..v....
0290: 95 A0 04 28 0D 0D F7 44   6F 0C 42 4F 17 77 A0 99  ...(...Do.BO.w..
02A0: 56 2A 13 77 28 0B 09 48   C1 B9 8C 09 ED 9F C6 2E  V*.w(..H........
02B0: 32 18 DB BD ED AF C3 AB   E7 AD 8F DF 9E AB 07 43  2..............C
02C0: B4 50 EF 74 98 EA FC E8   4D C9 DA FC B0 B2 C7 D4  .P.t....M.......
02D0: 83 50 B5 84 B8 44 86 7B   5D 8A C2 F8 04 80 06 E6  .P...D..].......
02E0: 84 42 33 B2 EE 05 E6 D3   48 0E 23 E5 1F 63 4C 53  .B3.....H.#..cLS
02F0: 98 B8 8C 45 BA C8 19                               ...E...
At this point, we have everything we need to generate the actual secrets.
SESSION KEYGEN:
PreMaster Secret:
0000: 03 01 84 54 F5 D6 EB F5   A8 08 BA FA 7A 22 61 2D  ...T........z"a-
0010: 75 DC 40 E8 98 F9 0E B2   87 80 B8 1A 8F 68 25 B8  u.@..........h%.
0020: 51 D0 54 45 61 8A 50 C9   BB 0E 39 53 45 78 BE 79  Q.TEa.P...9SEx.y
CONNECTION KEYGEN:
Client Nonce:
0000: 40 FC 30 AE 2D 63 84 BB   C5 4B 27 FD 58 21 CA 90  @.0.-c...K'.X!..
0010: 05 F6 A7 7B 37 BB 72 E1   FC 1D 1B 6A F5 1C C8 9F  ....7.r....j....
Server Nonce:
0000: 40 FC 31 10 79 AB 17 66   FA 8B 3F AA FD 5E 48 23  @.1.y..f..?..^H#
0010: FA 90 31 D8 3C B9 A3 2C   8C F5 E9 81 9B A2 63 6C  ..1.<..,......cl
Master Secret:
0000: B0 00 22 34 59 03 16 B7   7A 6C 56 9B 89 D2 7A CC  .."4Y..<.c.
Server MAC write Secret:
0000: 1E 4D D1 D3 0A 78 EE B7   4F EC 15 79 B2 59 18 40  .M...x..O..y.Y.@
Client write key:
0000: 10 D0 D6 C2 D9 B7 62 CB   2C 74 BF 5F 85 3C 6F E7  ......b.,t._.<o.
Server write key:
0000: 06 65 DF BD 16 4B A5 7D   8C 66 2A 80 C1 45 B4 F3  .e...K...f*..E..
... no IV for cipher
>
Send a quick confirmation to the server verifying that we know the private key corresponding to the client certificate we just sent.
*** CertificateVerify
[write] MD5 and SHA1 hashes:  len = 134
0000: 0F 00 00 82 00 80 45 41   43 4B 47 1D F0 EE D1 14  ......EACKG.....
0010: AE F9 B3 2C 1F B9 FE 7B   3E 91 50 C5 0F F1 57 4F  ...,....>.P...WO
0020: 55 F1 4B C3 79 16 A8 F1   72 6B 10 CA CC 83 02 FC  U.K.y...rk......
0030: 97 3D 04 29 44 4C 58 74   84 94 19 63 BB 8A 2C 78  .=.)DLXt...c..,x
0040: 43 A0 DD 5E 54 52 AA 97   15 92 1C 39 6B 10 2E BF  C..^TR.....9k...
0050: F2 DA AE 2D 8F FB 50 44   9E E2 1F 7D C9 C5 CB A0  ...-..PD........
0060: 31 A0 F9 AA 93 2D 1B 07   1B FA E0 EE 95 E7 88 D7  1....-..........
0070: AD 4A 3A 40 DC FB DF 9E   EB 75 04 14 E2 F2 BB DC  .J:@.....u......
0080: 1B 7E 6E D5 8C 62                                  ..n..b
main, WRITE: TLSv1 Handshake, length = 134
[Raw write]: length = 139
0000: 16 03 01 00 86 0F 00 00   82 00 80 45 41 43 4B 47  ...........EACKG
0010: 1D F0 EE D1 14 AE F9 B3   2C 1F B9 FE 7B 3E 91 50  ........,....>.P
0020: C5 0F F1 57 4F 55 F1 4B   C3 79 16 A8 F1 72 6B 10  ...WOU.K.y...rk.
0030: CA CC 83 02 FC 97 3D 04   29 44 4C 58 74 84 94 19  ......=.)DLXt...
0040: 63 BB 8A 2C 78 43 A0 DD   5E 54 52 AA 97 15 92 1C  c..,xC..^TR.....
0050: 39 6B 10 2E BF F2 DA AE   2D 8F FB 50 44 9E E2 1F  9k......-..PD...
0060: 7D C9 C5 CB A0 31 A0 F9   AA 93 2D 1B 07 1B FA E0  .....1....-.....
0070: EE 95 E7 88 D7 AD 4A 3A   40 DC FB DF 9E EB 75 04  ......J:@.....u.
0080: 14 E2 F2 BB DC 1B 7E 6E   D5 8C 62                 .......n..b
Almost finished! Tell the server we're changing to the newly established cipher suite. All further messages will be encrypted using the parameters we just established. We send an encrypted Finished message to verify everything worked.
main, WRITE: TLSv1 Change Cipher Spec, length = 1
[Raw write]: length = 6
0000: 14 03 01 00 01 01                                  ......
*** Finished
verify_data:  { 242, 98, 66, 170, 124, 124, 204, 231, 73, 15, 237, 172 }
***
[write] MD5 and SHA1 hashes:  len = 16
0000: 14 00 00 0C F2 62 42 AA   7C 7C CC E7 49 0F ED AC  .....bB.....I...
Padded plaintext before ENCRYPTION:  len = 32
0000: 14 00 00 0C F2 62 42 AA   7C 7C CC E7 49 0F ED AC  .....bB.....I...
0010: FA 06 3C 9F 8C 41 1D ED   2B 06 D0 5A ED 31 F2 80  ..<..A..+..Z.1..
main, WRITE: TLSv1 Handshake, length = 32
Note next that when the message above is actually written to the raw output device (following the 5 bytes of header information), the message is now encrypted.
[Raw write]: length = 37
0000: 16 03 01 00 20 15 8C 25   BA 4E 73 F5 27 79 49 B1  .... ..%.Ns.'yI.
0010: E9 F5 7E C8 48 A7 D3 A6   9B BD 6F 8E A5 8E 2B B7  ....H.....o...+.
0020: EE DC BD F4 D7                                     .....
We now wait for the server to send the same (Change Cipher Spec/Finshed), so we can know it completed negotiations successfully.
[Raw read]: length = 5
0000: 14 03 01 00 01                                     .....
[Raw read]: length = 1
0000: 01                                                 .
main, READ: TLSv1 Change Cipher Spec, length = 1
[Raw read]: length = 5
0000: 16 03 01 00 20                                     ....
[Raw read]: length = 32
0000: 1F F5 FA C8 79 20 CE 91   AA 68 7F 6C F3 5A DB 7B  ....y ...h.l.Z..
0010: A5 1C 31 1F 6F 41 50 C5   C6 25 25 8D 48 50 3F F1  ..1.oAP..%%.HP?.
main, READ: TLSv1 Handshake, length = 32
Padded plaintext after DECRYPTION:  len = 32
0000: 14 00 00 0C 07 38 46 5F   62 AD 41 B3 DC 79 30 FD  .....8F_b.A..y0.
0010: 34 F2 3B 54 1C D4 68 0E   92 0B 9C 7E ED 47 9F 3B  4.;T..h......G.;
*** Finished
verify_data:  { 7, 56, 70, 95, 98, 173, 65, 179, 220, 121, 48, 253 }
***
[read] MD5 and SHA1 hashes:  len = 16
0000: 14 00 00 0C 07 38 46 5F   62 AD 41 B3 DC 79 30 FD  .....8F_b.A..y0.
Everything completed successfully! Let's cache the established session in case we want to reestablish this session after this connection is dropped.

At this point, a SSL/TLS client should examine the credentials of the peer to make sure that it is communicating with the expected server. A HttpsURLConnection would check the hostname and call HostnameVerifier if there was a problem, but the raw SSLSocket doesn't. This verification should be done by hand, but we're ignoring this for now.

So, after all that, we're finally ready to exchange application data. We send a "GET /index.html HTTP1.1" command.

%% Cached client session: [Session-1, SSL_RSA_WITH_RC4_128_MD5]
Padded plaintext before ENCRYPTION:  len = 42
0000: 47 45 54 20 2F 69 6E 64   65 78 2E 68 74 6D 6C 20  GET /index.html
0010: 48 54 54 50 2F 31 2E 31   0A 0A CA CB D1 10 9D 0E  HTTP/1.1........
0020: 13 3C D9 66 6B 9E 36 87   ED 9B                    .<.fk.6...
main, WRITE: TLSv1 Application Data, length = 42
Note again the data over the wire is encrypted (skipping the 5 header bytes).
[Raw write]: length = 47
0000: 17 03 01 00 2A 8A E9 EC   2C 8D 19 B6 E2 50 C1 E2  ....*...,....P..
0010: 22 1A C0 97 95 23 99 E1   20 DD F3 2A B4 DC 14 57  "....#.. ..*...W
0020: 32 71 58 98 01 BE 70 11   A3 FC 8E 3A 7C 8D BF     2qX...p....:...
We get the application data back. First the HTTPS header, then the actual data.
[Raw read]: length = 5
0000: 17 03 01 00 50                                     ....P
[Raw read]: length = 80
0000: 70 10 0D D6 FA ED 51 FC   C2 7E CE 24 2E F1 2F F7  p.....Q....$../.
0010: E7 CD A5 D6 2D 1B 10 FD   48 56 9C 1B B5 EC 8F 1E  ....-...HV......
0020: DB DA F9 83 62 52 15 38   70 4B C1 85 13 EF CA 17  ....bR.8pK......
0030: 89 37 D3 45 C0 88 BB 92   63 F6 9C DE 69 E6 60 3E  .7.E....c...i.`>
0040: 1F F7 4D C1 56 61 79 01   49 55 FB 38 6B 16 81 BC  ..M.Vay.IU.8k...
main, READ: TLSv1 Application Data, length = 80
Padded plaintext after DECRYPTION:  len = 80
0000: 48 54 54 50 2F 31 2E 30   20 32 30 30 20 4F 4B 0D  HTTP/1.0 200 OK.
0010: 0A 43 6F 6E 74 65 6E 74   2D 4C 65 6E 67 74 68 3A  .Content-Length:
0020: 20 35 38 0D 0A 43 6F 6E   74 65 6E 74 2D 54 79 70   58..Content-Typ
0030: 65 3A 20 74 65 78 74 2F   68 74 6D 6C 0D 0A 0D 0A  e: text/html....
0040: 40 18 A1 FF 1D 5A D4 55   98 DB E3 95 01 A0 91 AF  @....Z.U........
HTTP/1.0 200 OK
Content-Length: 58
Content-Type: text/html
[Raw read]: length = 5
0000: 17 03 01 00 4A                                     ....J
[Raw read]: length = 74
0000: 75 DA F2 58 C3 5E 58 DE   14 AD FE 71 A3 78 07 58  u..X.^X....q.x.X
0010: EB E9 2B A2 D7 82 5C 6E   C9 9C 58 84 D7 A8 C6 F8  ..+...\n..X.....
0020: DE C6 5B BA 10 59 DF CC   11 AE 35 F7 C7 0F F6 C2  ..[..Y....5.....
0030: 3E 67 4E 95 30 AA 91 0B   E4 4F 5C C7 BF 50 AC 61  >gN.0....O\..P.a
0040: 87 B7 80 75 F0 81 F1 00   63 C9                    ...u....c.
main, READ: TLSv1 Application Data, length = 74
Padded plaintext after DECRYPTION:  len = 74
0000: 3C 48 54 4D 4C 3E 0A 3C   48 31 3E 48 65 6C 6C 6F  <HTML>.<H1>Hello
0010: 20 57 6F 72 6C 64 3C 2F   48 31 3E 0A 54 68 65 20   World</H1>.The
0020: 74 65 73 74 20 69 73 20   63 6F 6D 70 6C 65 74 65  test is complete
0030: 21 0A 3C 2F 48 54 4D 4C   3E 0A 38 2E 68 72 F1 47  !.</HTML>.8.hr.G
0040: E8 56 D1 EA A6 FC 3C 30   6F F3                    .V....<0o.
 <HTML>
<H1>Hello World<H1>
The test is complete!
<HTML>
Read from the socket again to see if there is any more data. We get a close_notify message, which means this connection is shutting down properly. We send our own in turn, then close the socket.
[Raw read]: length = 5
0000: 15 03 01 00 12                                     .....
[Raw read]: length = 18
0000: 09 AB 95 00 43 8D C8 7C   83 18 EB C4 8C 99 43 A6  ....C.........C.
0010: 76 49                                              vI
main, READ: TLSv1 Alert, length = 18
Padded plaintext after DECRYPTION:  len = 18
0000: 01 00 FA 44 D5 57 71 5C   CC C7 D9 D0 04 23 10 D8  ...D.Wq\.....#..
0010: 21 7B                                              !.
main, RECV TLSv1 ALERT:  warning, close_notify
main, called closeInternal(false)
main, SEND TLSv1 ALERT:  warning, description = close_notify
Padded plaintext before ENCRYPTION:  len = 18
0000: 01 00 8A 2C A2 36 9C 88   22 50 6E BC 95 3B B2 C4  ...,.6.."Pn..;..
0010: FE F2                                              ..
main, WRITE: TLSv1 Alert, length = 18
[Raw write]: length = 23
0000: 15 03 01 00 12 19 BE 10   8D FA F1 CA DD AB CC 91  ................
0010: 2E 49 08 71 2B C1 05                               .I.q+..
main, called close()
main, called closeInternal(true)
main, called close()
main, called closeInternal(true)
main, called close()
main, called closeInternal(true)
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java 2D(TM) Programmer's Guide, Imaging Sample Programs

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java 2DTM Programmer's Guide Imaging Sample Programs

These sample programs demonstrate new Java 2DTM Imaging features available in the Java TM 2 SDK, version 1.2 -- you will need to download the Java 2 SDKTM 1.2 or a more recent version of the SDK to run these programs.

Downloading the Sample Programs

Click the following link to download a zip file that contains all of the Imaging sample programs and necessary images.

  • Download Java 2D Imaging Programs and images [zip]

List of Sample Programs

Java Files | Description
BufferedShapeMover.java | Illustrates off-screen buffering.
Blur.java | Illustrates blurring using convolution.
Edge.java | Illustrates edge detection using convolution.
LookUp.java | Illustrates lookup-table manipulation.
Rescale.java | Illustrates rescaling.
Sharpen.java | Illustrates sharpening using convolution.

Compiling the Sample Programs

You can compile a sample by running javac on the sample's .java file. For example, to compile the Blur sample, type:

javac Blur.java

(This assumes javac is in your executible path and that you are using Java 2 SDK 1.2 FCS or greater)

Running the Sample Programs

These sample programs are designed to run as standalone Java applications or applets. To run a sample as an application, execute the java command on the class name. For example, to run the Blur application, type:

java Blur

(This assumes java is in your executible path and that you are using Java 2 SDK 1.2 FCS or greater)

You can also run the samples as applets by running appletviewer on the particular sample's html file. For example, if you would like to run the Blur applet, you would type the following line while you are in the same directory as the html file.

appletviewer Blur.html

(This assumes appletviewer is in your executible path and that you are using Java 2 SDK 1.2 FCS or greater)

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


More detailed instructions on how to compile/run this example can be
found in the sample top-level README file.

The following urls have more information about RMI and the
HelloWorld example:

        http://java.sun.com/j2se/1.5.0/docs/guide/rmi/index.html
    http://java.sun.com/docs/books/tutorial/rmi/index.html


Uses of Interface org.w3c.dom.css.Rect (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.css.Rect

  • Packages that use Rect
    Package Description
    org.w3c.dom.css

    • Uses of Rect in org.w3c.dom.css

      Methods in org.w3c.dom.css that return Rect
      Modifier and Type Method and Description
      Rect CSSPrimitiveValue.getRectValue()
      This method is used to get the Rect value.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Java IDL: Reference

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Reference

All packages that begin with org.omg are part of the Java IDL API. Those of most interest are:

  • package org.omg.CORBA - provides the mapping of the OMG CORBA APIs to the Java[tm] programming language
  • package org.omg.CosNaming - provides the naming service for Java IDL
  • package org.omg.PortableServer - provides classes and interfaces for making the server side of your applications portable across multivendor ORBs
  • package org.omg.PortableInterceptor - provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB
  • package org.omg.DynamicAny - provides classes and interfaces to enable Any values to be dynamically interpreted (traversed) and constructed through DynAny objects
  • org.omg.CORBA.ORB - provides APIs for the CORBA Object Request Broker features

Mapping IDL to Java

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.mirror.type.ReferenceType (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.type.ReferenceType

  • Packages that use ReferenceType
    Package Description
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.
    com.sun.mirror.type
    Interfaces used to model types.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of ReferenceType in com.sun.mirror.declaration

      Methods in com.sun.mirror.declaration that return types with arguments of type ReferenceType
      Modifier and Type Method and Description
      Collection<ReferenceType> TypeParameterDeclaration.getBounds()
      Deprecated.
      Returns the bounds of this type parameter.
      Collection<ReferenceType> ExecutableDeclaration.getThrownTypes()
      Deprecated.
      Returns the exceptions and other throwables listed in this method or constructor's throws clause.

    • Uses of ReferenceType in com.sun.mirror.type

      Subinterfaces of ReferenceType in com.sun.mirror.type
      Modifier and Type Interface and Description
      interface  AnnotationType
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in DeclaredType.
      interface  ArrayType
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is ArrayType.
      interface  ClassType
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in DeclaredType.
      interface  DeclaredType
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in DeclaredType.
      interface  EnumType
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in DeclaredType.
      interface  InterfaceType
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in DeclaredType.
      interface  TypeVariable
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is TypeVariable.
      Methods in com.sun.mirror.type that return types with arguments of type ReferenceType
      Modifier and Type Method and Description
      Collection<ReferenceType> WildcardType.getLowerBounds()
      Deprecated.
      Returns the lower bounds of this wildcard.
      Collection<ReferenceType> WildcardType.getUpperBounds()
      Deprecated.
      Returns the upper bounds of this wildcard.

    • Uses of ReferenceType in com.sun.mirror.util

      Methods in com.sun.mirror.util with parameters of type ReferenceType
      Modifier and Type Method and Description
      void TypeVisitor.visitReferenceType(ReferenceType t)
      Deprecated.
      Visits a reference type.
      void SimpleTypeVisitor.visitReferenceType(ReferenceType t)
      Deprecated.
      Visits a reference type.
      Method parameters in com.sun.mirror.util with type arguments of type ReferenceType
      Modifier and Type Method and Description
      WildcardType Types.getWildcardType(Collection<ReferenceType> upperBounds, Collection<ReferenceType> lowerBounds)
      Deprecated.
      Returns a new wildcard.
      WildcardType Types.getWildcardType(Collection<ReferenceType> upperBounds, Collection<ReferenceType> lowerBounds)
      Deprecated.
      Returns a new wildcard.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


JAXP 1.4 Release Notes

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

JavaTM API for XML Processing Release Notes

Specification Version: 1.4
Reference Implementation (RI) Version: 1.4.0

This document contains installation instructions and other notes that may help you use this software library more effectively. See also the JAXP FAQ for more information.

Note:
If you are reading this page online, this is the most current version of the release notes. If this page was downloaded as part of the release bundle, please see the JAXP Documentation page for the most current version of the release notes.

Contents

  • Feature Changes
  • gMonth
  • JAXP Specification Changes since 1.3

Feature Changes

An important technical change in JAXP 1.4 is the addition of the javax.xml.stream.* packages from StAX, the Streaming API for XML (JSR 173). With this addition, JAXP 1.4 now supports validation and transformation of documents with the streaming API. Since JAXP 1.4 is integrated in Java SE 6, the StAX support is transparent on any system running the latest Java.

gMonth

JAXP 1.4 changed its XML Schema validation logic for gMonth to reflect the changes made in the XML Schema 1.0 Specification Errata: E2-12 Error. Specifically, it will now reject gMonths with a lexical representation of "--MM--" as invalid.

JAXP Specification Changes since 1.3

Refer also to JAXP 1.4 Specification Chapter 9. Changes Since JAXP 1.3.

The following sections summarize the significant changes introduced in JAXP 1.4. For additional details, please see the appropriate JavaDoc.

1. Package javax.xml.datatype

1.1. Class DatatypeFactory

  • Changed DATATYPEFACTORY_IMPLEMENTATION_CLASS to com.sun.org.apache.xerces.internal.jaxp.datatype.DatatypeFactoryImpl.

  • Added newInstance(String, ClassLoader) method.

1.2. Class Duration

  • Return false if the argument to equals() is null instead of throwing NullPointerException.

1.3. Class XMLGregorianCalendar

  • Return false if the argument to equals() is null instead of throwing NullPointerException.

2. Package javax.xml.parsers

2.1. Class DocumentBuilderFactory

  • Added newInstance(String, ClassLoader) method.

2.2. Class SAXParserFactory

  • Added newInstance(String, ClassLoader) method.

3. Package javax.xml.stream

Added the javax.xml.stream package to support StAX. The package consists of the following interfaces:

  • EventFilter

  • Location

  • StreamFilter

  • XMLEventReader

  • XMLEventWriter

  • XMLReporter

  • XMLResolver

  • XMLStreamConstants

  • XMLStreamReader

  • XMLStreamWriter

Classes:

  • XMLEventFactory

  • XMLInputFactory

  • XMLOutputFactory

Exceptions:

  • XMLStreamException

And errors:

  • FactoryConfigurationError

4. Package javax.xml.stream.events

Added the javax.xml.stream.events package to support StAX. The package consists of the following interfaces:

  • Attribute

  • Characters

  • Comment

  • DTD

  • EndDocument

  • EndElement

  • EntityDeclaration

  • EntityReference

  • Namespace

  • NotationDeclaration

  • ProcessingInstruction

  • StartDocument

  • StartElement

  • XMLEvent

4.1. Package javax.xml.stream.util

Added the javax.xml.stream.util package to support StAX. The package consists of the following interfaces:

  • XMLEventAllocator

  • XMLEventConsumer

And classes:

  • EventReaderDelegate

  • StreamReaderDelegate

5. Package javax.xml.transform

5.1. Class ErrorListener

  • Clarified the semantics of fatalError().

5.2. Class Transformer

  • Clarified the semantics of getOutputProperty() with respect to properties that have not been set explicitly with either setOutputProperty() or xsl:output in the stylesheet.

5.3. Class TransformerFactory

  • Added newInstance(String, ClassLoader) method.

5.4. Package javax.xml.transform.stax

Added the javax.xml.transform.stax package to support StAX. The package consists of the following interfaces:

  • TemplatesHandler

  • TransformerHandler

And classes:

  • StAXResult

  • StAXSource

6. Package javax.xml.validation

6.1. Class Schema

  • Clarified that the features set on the SchemaFactory should be passed to the Validator created with newValidator().

  • Clarified that the features set on the SchemaFactory should be passed to the ValidatorHandler created with newValidatorHandler().

6.2. Class SchemaFactory

  • Added newInstance(String, ClassLoader) method.

  • Clarified that the features set on the SchemaFactory should be passed to the Schemas created with newSchema(). Included a note to implementors and developers about the subtleties associated with newSchema() in this context.

  • Clarified that the inputs to newSchema(Source[]) are expected to be XML documents or elements.

  • Updated documentation of setFeature() to clarify that the features set on the SchemaFactory should be passed to the Schemas created with this factory and by extension to the Validator and ValidatorHandlers created from that Schema.

6.3. Class SchemaFactoryLoader

The SchemaFactoryLoader class was created during the JAXP 1.3 development process. Shortly before JAXP 1.3 was finished, the factory mechanisms associated with validation were changed, and this class was removed. Unfortunately, the file was left in a repository and it slipped into the Java 2 Platform Standard Edition 5.0 API Specification.

Since the class can neither be added to JAXP 1.3 nor removed from the Java 5.0 API Specification due to backwards compatibility issues, it is being added to JAXP 1.4. The class is harmless and should not be used. It is being added simply to avoid the confusion that arises when developers notice that it's defined in the platform but not in JAXP.

Do not use this class.

6.4. Class TypeInfoProvider

  • Extended the semantics of getElementTypeInfo(), allowing it to be called from either the startElement event or the endElement event. This allows the API to support W3C XML Schema union types more usefully.

    When W3C XML Schema validation is being performed, in the case where an element has a union type, the TypeInfo returned by a call to getElementTypeInfo() from the startElement event will be the union type. The TypeInfo returned by a call from the endElement event will be the actual member type used to validate the element.

6.5. Class Validator

  • The Validator may now accept Sources other than DOMSource and SAXSource; for example, StAXSource.

  • Clarified that the inputs to validate() are expected to be XML documents or elements.

7. Package javax.xml.xpath

7.1. Class XPath

  • Clarified that it is the XPathVariableResolver in effect at compile time that is used to resolve any variables that appear in the expression.

7.2. Class XPathFactory

  • Added newInstance(String, ClassLoader) method.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Serialization Enhancements in Previous Releases

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Object Serialization Enhancements
in Previous Releases

The following are enhancements to serialization prior to Java™ SE Development Kit 6 (JDK). For enhancements in the current release, see Serialization Changes and Enhancements in Java SE Development Kit 6.

Support for serialization of enumerated type instances (since 5.0)
Support has been added to serialization to handle enumerated types, which are new in version 5.0. The rules for serializing an enum instance differ from those for serializing an "ordinary" serializable object: the serialized form of an enum instance consists only of its enum constant name, along with information identifying its base enum type. Deserialization behavior differs as well--the class information is used to find the appropriate enum class, and the Enum.valueOf method is called with that class and the received constant name in order to obtain the enum constant to return.
Bug fix: java.io.StreamCorruptedException thrown due to java.lang.ClassNotFoundException (since 5.0)
In previous releases starting with version 1.4.0, a ClassNotFoundException thrown by the ObjectInputStream.readClassDescriptor method would be reflected to the top-level caller of ObjectInputStream.readObject as a StreamCorruptedException with an empty cause. It is now reflected to the top-level caller as an InvalidClassException with the original ClassNotFoundException as the cause.
Bug fix: thread waiting on a java.io.ObjectStreamClass$EntryFuture for notification from [sic] (since 5.0)
In previous releases starting with version 1.4.0, the ObjectStreamClass.lookup method could deadlock if called from within the static initializer of the class represented by the method's Class argument. Deadlock should no longer occur in this case.
Bug fix: no spec for serialVersionUID (since 5.0)
The javadoc for the Serializable interface has been expanded to more completely specify the role and usage of serialVersionUIDs, and to emphasize the need to specify explicit serialVersionUIDs for serializable classes.
Support for deserialization of unshared objects (since 1.4)
Serialization now provides extra support for deserialization of objects which are known to be unshared in the data-serialization stream. The new support is provided by the following API additions in package java.io:
  • ObjectInputStream.readUnshared()
  • ObjectOutputStream.writeUnshared(Object obj)
  • ObjectStreamField(String name, Class type, boolean unshared)

These APIs can be used to more efficiently read contained array objects in a secure fashion; for more information, see section A.6 of the Java Object Serialization Specification, "Guarding Unshared Deserialized Objects".

Security permissions now required to override putFields, readFields (since 1.4)
Beginning with J2SE 1.4.0, ObjectOutputStream's public one-argument constructor requires the "enableSubclassImplementation" SerializablePermission when invoked (either directly or indirectly) by a subclass which overrides ObjectOutputStream.putFields or ObjectOutputStream.writeUnshared.

Also beginning with J2SE 1.4.0, ObjectInputStream's public one-argument constructor requires the "enableSubclassImplementation" SerializablePermission when invoked (either directly or indirectly) by a subclass which overrides ObjectInputStream.readFields or ObjectInputStream.readUnshared.

These changes will not affect the great majority of applications. However, it will affect any ObjectInputStream/ObjectOutputStream subclasses which override the putFields or readFields methods without also overriding the rest of the serialization infrastructure.

Support for class-defined readObjectNoData method (since 1.4)
In addition to supporting class-defined writeObject() and readObject() methods, serialization now includes support for class-defined readObjectNoData() methods. Each class-defined readObjectNoData() method is required to have the following signature:
private void readObjectNoData() throws ObjectStreamException;
The readObjectNoData() method is analogous to the class-defined readObject() method, except that (if defined) it is called in cases where the class descriptor for a superclass of the object being deserialized (and hence the object data described by that class descriptor) is not present in the serialization stream. More formally: If object O of class C is being deserialized, and S is a superclass of C in the VM which is deserializing O, then S.readObjectNoData() is invoked by ObjectInputStream during the deserialization of O if and only if the following conditions are true:
  1. S implements java.io.Serializable (directly or indirectly).
  2. S defines an readObjectNoData() method with the signature listed above.
  3. The serialization stream containing O does not include a class descriptor for S among its list of superclass descriptors for C.
Note that readObjectNoData() is never invoked in cases where a class-defined readObject() method could be called, though serializable class implementors can call readObjectNoData() from within readObject() as a means of consolidating initialization code.

See the class description in the API specification of ObjectInputStream for more information.

Bug fix: Deserialization fails for Class object of primitive type (since 1.4)
In previous releases, bug 4171142 caused attempts to deserialize Class objects of primitive types to fail with a ClassNotFoundException. The problem was that ObjectInputStream.resolveClass() did not work for ObjectStreamClass descriptors for primitive types. This bug is fixed in J2SE 1.4.0.
Bug fix: ObjectInputStream.resolveProxyClass can fail for non-public interface cases (since 1.4)
In previous releases, ObjectInputStream.resolveProxyClass would not always select the proper class loader to define the proxy class in if one or more of the proxy interfaces were non-public. In this release, if ObjectInputStream.resolveProxyClass detects a non-public interface, it attempts to define the implementing proxy class in the same class loader as the interface (barring conflicts, in which case an exception is thrown), which is necessary in order for the proxy to implement the interface.
Bug fix: Invalid serialPersistentFields field name causes NullPointerException (since 1.4)
In previous releases, bug 4387368 caused NullPointerExceptions to be thrown when serializing objects which used default serialization but also declared serialPersistentField entries which did not map to actual class fields. Serialization will now throw InvalidClassExceptions in such cases (since it is never necessary to define such "unbacked" serialPersistentFields when using default serialization).
Bug fix: ClassNotFoundException in skipped objects causes serialization to fail (since 1.4)
In previous releases, ClassNotFoundExceptions triggered by "skipped" objects--objects associated with fields not present in the classes loaded by the deserializing party--would cause deserialization of the entire object graph to fail, even though the skipped values would not be included in the graph. This release of serialization addresses this problem by ignoring ClassNotFoundExceptions associated with such skipped objects, thus eliminating a class of unnecessary deserialization errors. Other miscellaneous changes have also been made to improve the overall robustness of serialization with regards to ClassNotFoundExceptions encountered during deserialization.
Strings longer than 64K can now be serialized (since 1.3)
Prior to 1.3, an attempt to serialize a string longer than 64K would result in a java.io.UTFDataFormatException being thrown. In 1.3, the serialization protocol has been enhanced to allow strings longer than 64K to be serialized. Note that if a 1.2 (or earlier) JVM attempts to read a long string written from a 1.3-compatible JVM, the 1.2 (or earlier) JVM will receive a java.io.StreamCorruptedException.
Serialization performance enhancements (since 1.3)
Several changes have been made to serialization to improve overall performance:
  • UTF string reads/writes have been optimized to reduce unnecessary memory allocation and synchronization/method call overhead.
  • Code for reading and writing primitive data arrays has been streamlined. Float and double array reads/writes have been reimplemented to minimize the number of calls to native methods.
  • Internal buffering has been improved.
  • Reflective operations for getting/setting primitive field values have been batched to minimize the number of separate native method calls.
Improved exception reporting (since 1.3)
If a class cannot be found during the class resolution process of deserialization, the original java.lang.ClassNotFoundException is thrown instead of a generic one so that more information about the failure is available. Also, deserialization exception reporting now includes maintaining the name of the original class that could not be found instead of reporting a higher-level class that was being deserialized. For example, if (in an RMI call) the stub class can be found but the remote interface class cannot, the serialization mechanism will now report correctly that the interface class was the class that could not be found instead of erroneously reporting that the stub class could not be found.
java.io.ObjectOutputStream.writeClassDescriptor,
java.io.ObjectInputStream.readClassDescriptor (since 1.3)
The writeClassDescriptor and readClassDescriptor methods have been added to provide a means of customizing the serialized representation of java.io.ObjectStreamClass class descriptors. writeClassDescriptor is called when an instance of java.io.ObjectStreamClass needs to be serialized, and is responsible for writing the ObjectStreamClass to the serialization stream. Conversely, readClassDescriptor is called when the ObjectInputStream expects an ObjectStreamClass instance as the next item in the serialization stream. By overriding these methods, subclasses of ObjectOutputStream and ObjectInputStream can transmit class descriptors in an application-specific format. For more information, refer to sections 2.1 and 3.1 of the Java Object Serialization Specification.
java.io.ObjectOutputStream.annotateProxyClass,
java.io.ObjectInputStream.resolveProxyClass (since 1.3)
These methods are similar in purpose to ObjectOutputStream.annotateClass and ObjectInputStream.resolveClass, except that they apply to dynamic proxy classes (see java.lang.reflect.Proxy), as opposed to non-proxy classes. Subclasses of ObjectOutputStream may override annotateProxyClass to store custom data in the stream along with descriptors for dynamic proxy classes. ObjectInputStream subclasses may then override resolveProxyClass to make use of the custom data in selecting a local class to associate with the given proxy class descriptor. For details, see section 4 of the Java Object Serialization Specification.
The javadoc tool tags @serial, @serialField, and @serialData (since 1.2)
The javadoc tags @serial, @serialField, and @serialData have been added to provide a way to document the serialized form of a class. Javadoc generates a serialization specification based on the contents of these tags. For details, refer to section 1.6 of the Java Object Serialization Specification.
Protocol versioning (since 1.2)
Prior to 1.2, object serialization used a protocol that did not support skipping over objects implementing the java.io.Externalizable interface if the classes for those objects were not available. In 1.2, a new protocol version was added which addressed this deficiency. For backwards compatibility, ObjectOutputStream and ObjectInputStream can read and write serialization streams written in either protocol; the protocol version used can be selected by calling the ObjectOutputStream.useProtocolVersion method. For details and a discussion of compatibility issues, see section 6.3 of the Java Object Serialization Specification.
Class-defined writeReplace and readResolve methods (since 1.2)
Since 1.2, classes can define writeReplace and readResolve methods which allow instances of the given classes to nominate replacements for themselves during serialization and deserialization. The required signatures of these methods, along with further details, are described in sections 2.5 and 3.6 of the Java Object Serialization Specification.
java.io.ObjectOutputStream.writeObjectOverride, java.io.ObjectInputStream.readObjectOverride (since 1.2)
Since 1.2, subclasses of ObjectOutputStream and ObjectInputStream can implement a custom serialization protocol by overriding the writeObjectOverride and readObjectOverride methods. Note that these methods will only be called if the ObjectOutputStream/ObjectInputStream subclasses possess the permission java.io.SerializablePermission("enableSubclassImplementation"), and call the no-argument constructors of ObjectOutputStream/ObjectInputStream. See sections 2.1 and 3.1 of the Java Object Serialization Specification for more information.
Security permission checks (since 1.2)
Subclasses of ObjectOutputStream and ObjectInputStream may override inherited methods to obtain "hooks" into certain aspects of the serialization process. Since 1.2, object serialization uses the 1.2 security model to verify that subclasses possess adequate permissions to override certain hooks. The permissions java.io.SerializablePermission("enableSubclassImplementation") and java.io.SerializablePermission("enableSubstitution") govern whether or not the methods ObjectOutputStream.writeObjectOverride, ObjectOutputStream.replaceObject, ObjectInputStream.readObjectOverride, and ObjectInputStream.resolveObject will be called during the course of serialization. See sections 2.1 and 3.1 of the Java Object Serialization Specifications for more information.
Defining serializable fields for a class (since 1.2)
By default, the values of all non-static and non-transient fields of a serializable class are written when an instance of that class is serialized. In 1.2, a new mechanism was introduced to allow classes finer control of this process. By declaring a special field serialPersistentFields, serializable classes can dictate which fields will be written when instances of the class (or subclasses) are serialized. This feature also enables classes to "define" serializable fields which do not correspond directly to actual fields in the class. Used in conjunction with the serializable fields API (described below), this capability allows fields to be added or removed from a class without altering the serialized representation of the class. See sections 1.5 and 1.7 of the Java Object Serialization Specification for details.
Serializable fields API (since 1.2)
Introduced in 1.2, the serializable fields API allows class-defined writeObject/readObject methods to explicitly set and retrieve serializable field values by name and type. This API is particularly useful for classes that need to maintain backwards compatibility with older class versions; in some cases, the older version of the class may have defined a set of serializable fields that cannot be mapped directly to the fields of the current class. In this case, newer versions of the class can define custom writeObject and readObject methods that convert the internal state of a given instance of the (new) class into the "old" serialized form, and vice versa. For more information, see section 1.7 of the Java Object Serialization Specification.
*As used on this web site, the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Serialization Release Notes

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Serialization Changes and Enhancements
in JavaTM SE Development Kit 6

The following are enhancements to serialization in Java SE Development Kit 6 (JDK). For a summary of enhancements in previous releases, see Enhancements in Previous Releases.
java.io.ObjectStreamClass.lookupAny
In previous releases, it was difficult to programmatically obtain an ObjectStreamClass instance for a non-serializable Class, although doing so can be desirable when customizing the stream format for class descriptors (see 4413615 for more information). The new method ObjectStreamClass.lookupAny can now be used for this purpose.
Bug fix: delayed garbage collection
In previous releases, bug 6232010 could cause serializable classes and subclasses of ObjectOutputStream and ObjectInputStream to be strongly referenced long after their use in a serialization operation, thus possibly delaying garbage collection of their defining class loaders indefinitely. Internal caches in the serialization implementation have been restructured to fix this bug.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


System-Wide Repository

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

System-Wide Repository (Windows only)

Previous to this release, when a new JRE was installed, JAR and native libraries for the old release were not visible to the new one. Thus applications and applets that relied on those libraries would not work, and developers were forced to redeploy their libraries to the new JRE. The new System-Wide Repository is the solution to that problem. It provides a global or system-wide location where the VM can search for libraries, JAR or native, indepenent of the JRE location. It provides functionality similar to the repository in the Microsoft VM (see How Does the Virtual Machine Search for Java Classes?).

Note: In this release the system-wide repository is supported only by Java Plug-in and only on Windows.

The table below shows the location of the new System-Wide Repository:

Type of Library | System-Wide Location
DLL | Any directory in the System Path environment variable.
Untrusted JAR | <Windows Directory>\Sun\Java\Deployment\Lib\Untrusted
Trusted JAR | <Windows Directory>\Sun\Java\Deployment\Lib\Trusted

<Windows Directory> is the Windows OS directory on the drive where Windows was installed (also called %SystemRoot%).

For example, on Windows XP, where Windows has been installed on the C drive (typical), the locations of these libraries would be as follows:

Type of Library | System-Wide Location
DLL | Any directory in the System Path variable; e.g., C:\WINDOWS\repository if C:\WINDOWS\repository has been set in the System Path variable.
Untrusted JAR | C:\WINDOWS\Sun\Java\Deployment\Lib\Untrusted
Trusted JAR | C:\WINDOWS\Sun\Java\Deployment\Lib\Trusted

Note the following:

  1. The classes in the JARS from the system-wide trusted repository are loaded by the extension class loader, whereas the classes in the JARs from system-wide untrusted repository are loaded by the applet class loader. Thus the former classes are given the AllPermission permissions, while the latter are given only default applet permissions.
  2. The repository does not provide version or namespaces control. It is up to the deployer to avoid version and namespaces conflicts at deployment time.
  3. The system-wide trusted repository implementation is based on the system property java.ext.dirs. If the user selects his/her own java.ext.dirs system property via the Java Control Panel, the JARs in the system-wide trusted repository will not be loaded by Java Plug-in.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Accessing Resources

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Location-Independent Access to Resources

  • Overview
  • Resources, names, and contexts
  • System Resources
  • Non-System Resources
  • Resource Names
  • Usimg Methods of java.lang.Class
  • Using Methods of java.lang.ClassLoader
  • Security
  • Examples
  • References

Overview

A resource is data (images, audio, text, and so on) that a program needs to access in a way that is independent of the location of the program code. Java programs can use two mechanisms to access resources: Applets use Applet.getCodeBase() to get the base URL for the applet code and then extend the base URL with a relative path to load the desired resource, for example with Applet.getAudioClip(url). Applications use "well known locations" such as System.getProperty("user.home") or System.getProperty("java.home"), then add "/lib/resource", and open that file.

Methods in the classes Class and ClassLoader provide a location-independent way to locate resources. For example, they enable locating resources for:

  • An applet loaded from the Internet using multiple HTTP connections.
  • An applet loaded using JAR files.
  • A Java Bean loaded or installed in the CLASSPATH.
  • A "library" installed in the CLASSPATH.

These methods do not provide specific support for locating localized resources. Localized resources are supported by the internationalization facilities.

Resources, names, and contexts

A resource is identified by a string consisting of a sequence of substrings, delimited by slashes (/), followed by a resource name. Each substring must be a valid Java identifier. The resource name is of the form shortName or shortName.extension. Both shortName and extension must be Java identifiers.

The name of a resource is independent of the Java implementation; in particular, the path separator is always a slash (/). However, the Java implementation controls the details of how the contents of the resource are mapped into a file, database, or other object containing the actual resource.

The interpretation of a resource name is relative to a class loader instance. Methods implemented by the ClassLoader class do this interpretation.

System Resources

A system resource is a resource that is either built-in to the system, or kept by the host implementation in, for example, a local file system. Programs access system resources through the ClassLoader methods getSystemResource and getSystemResourceAsStream.

For example, in a particular implementation, locating a system resource may involve searching the entries in the CLASSPATH. The ClassLoader methods search each directory, ZIP file, or JAR file entry in the CLASSPATH for the resource file, and, if found, returns either an InputStream, or the resource name. If not found, the methods return null. A resource may be found in a different entry in the CLASSPATH than the location where the class file was loaded.

Non-System Resources

The implementation of getResource on a class loader depends on the details of the ClassLoader class. For example, AppletClassLoader:

  • First tries to locate the resource as a system resource; then, if not found,
  • Searches through the resources in archives (JAR files) already loaded in this CODEBASE; then, if not found,
  • Uses CODEBASE and attempts to locate the resource (which may involve contacting a remote site).

All class loaders will search for a resource first as a system resource, in a manner analogous to searcing for class files. This search rule permits overwriting locally any resource. Clients should choose a resource name that will be unique (using the company or package name as a prefix, for instance).

Resource Names

A common convention for the name of a resource used by a class is to use the fully qualified name of the package of the class, but convert all periods (.) to slashes (/), and add a resource name of the form name.extension. To support this, and to simplify handling the details of system classes (for which getClassLoader returns null), the class Class provides two convenience methods that call the appropriate methods in ClassLoader.

The resource name given to a Class method may have an initial starting "/" that identifies it as an "absolute" name. Resource names that do not start with a "/" are "relative".

Absolute names are stripped of their starting "/" and are passed, without any further modification, to the appropriate ClassLoader method to locate the resource. Relative names are modified according to the convention described previously and then are passed to a ClassLoader method.

Using Methods of java.lang.Class

The Class class implements several methods for loading resources.

The method getResource() returns a URL for the resource. The URL (and its representation) is specific to the implementation and the JVM (that is, the URL obtained in one runtime instance may not work in another). Its protocol is usually specific to the ClassLoader loading the resource. If the resource does not exist or is not visible due to security considerations, the methods return null.

If the client code wants to read the contents of the resource as an InputStream, it can apply the openStream() method on the URL. This is common enough to justify adding getResourceAsStream() to Class and ClassLoader. getResourceAsStream() the same as calling getResource().openStream(), except that getResourceAsStream() catches IO exceptions returns a null InputStream.

Client code can also request the contents of the resource as an object by applying the java.net.URL.getContent() method on the URL. This is useful when the resource contains the data for an image, for instance. In the case of an image, the result is an awt.image.ImageProducer object, not an Image object.

The getResource and getResourceAsStream methods find a resource with a given name. They return null if they do not find a resource with the specified name. The rules for searching for resources associated with a given class are implemented by the class's ClassLoader. The Class methods delegate to ClassLoader methods, after applying a naming convention: if the resource name starts with "/", it is used as is. Otherwise, the name of the package is prepended, after converting all periods (.) to slashes (/).

public InputStream getResourceAsStream(String name) {
  name = resolveName(name);
  ClassLoader cl = getClassLoader();
  if (cl==null) {
    return ClassLoader.getSystemResourceAsStream(name); // A system class.
  }
  return cl.getResourceAsStream(name);
}

public java.net.URL getResource(String name) {
  name = resolveName(name);
  ClassLoader cl = getClassLoader();
  if (cl==null) {
    return ClassLoader.getSystemResource(name);  // A system class.
  }
  return cl.getResource(name);
}

The resolveName method adds a package name prefix if the name is not absolute, and removes any leading "/" if the name is absolute. It is possible, though uncommon, to have classes in diffent packages sharing the same resource.

private String resolveName(String name) {
  if (name == null) {
    return name;
  }
  if (!name.startsWith("/")) {
    Class c = this;
    while (c.isArray()) {
      c = c.getComponentType();
    }
    String baseName = c.getName();
    int index = baseName.lastIndexOf('.');
    if (index != -1) {
      name = baseName.substring(0, index).replace('.', '/') + "/" + name;
    }
  } else {
    name = name.substring(1);
  }
  return name;
}

Using Methods of java.lang.ClassLoader

The ClassLoader class has two sets of methods to access resources. One set returns an InputStream for the resource. The other set returns a URL. The methods that return an InputStream are easier to use and will satisfy many needs, while the methods that return URLs provide access to more complex information, such as an Image and an AudioClip.

The ClassLoadermanges resources similarly to the way it manages classes. A ClassLoader controls how to map the name of a resource to its content. ClassLoader also provides methods for accessing system resources, analogous to the system classes. The Class class provides some convenience methods that delegate functionality to the ClassLoader methods.

Many Java programs will access these methods indirectly through the I18N (localization) APIs. Others will access it through methods in Class. A few will directly invoke the ClassLoader methods.

The methods in ClassLoader use the given String as the name of the resource without applying any absolute/relative transformation (see the methods in Class). The name should not have a leading "/".

System resources are those that are handled by the host implemenation directly. For example, they may be located in the CLASSPATH.

The name of a resource is a "/"-separated sequence of identifiers. The Class class provides convenience methods for accessing resources; the methods implement a convention where the package name is prefixed to the short name of the resource.

Resources can be accessed as an InputStream, or a URL.

The getSystemResourceAsStream method returns an InputStream for the specified system resource or null if it does not find the resource. The resource name may be any system resource.

The getSystemResource method finds a system resource with the specified name. It returns a URL to the resource or null if it does not find the resource. Calling java.net.URL.getContent() with the URL will return an object such as ImageProducer, AudioClip, or InputStream.

The getResourceAsStream method returns an InputStream for the specified resource or null if it does not find the resource.

The getResource method finds a resource with the specified name. It returns a URL to the resource or null if it does not find the resource. Calling java.net.URL.getContent() with the URL will return an object such as ImageProducer, AudioClip, or InputStream.

Security

Since getResource() provides access to information, it must have well-defined and well-founded security rules. If security considerations do not allow a resource to be visible in some security context, the getResource() method will fail (return null) as if the resource were not present at all, this addresses existence attacks.

Class loaders may not provide access to the contents of a .class file for both security and performance reasons. Whether it is possible to obtain a URL for a .class file depends on the specifics, as shown below.

There are no specified security issues or restrictions regarding resources that are found by a non-system class loader. AppletClassLoader provides access to information that is loaded from a source location, either individually, or in a group through a JAR file; thus AppletClassLoader should apply the same checkConnect() rules when dealing with URLs through getResource().

The system ClassLoader provides access to information in the CLASSPATH. A CLASSPATH may contain directories and JAR files. Since a JAR file is created intentionally, it has a different significance than a directory where things may end up in a more casual manner. In particular, we are more strict on getting information out of a directory than out from a JAR file.

If a resource is in a directory:

  • getResource() invocations will use File.exists() to determine whether to make the corresponding file visible to the user. Recall that File.exists() uses the checkRead() method in the security manager.
  • the same applies to getResourceAsStream().

If the resource is in a JAR file:

  • getResource() invocations will succeed for all files, regardless of whether the invocation is done from within a system or a non-system class.
  • getResourceAsStream() invocations will succeed for non .class resources, and so will for java.net.URL.getContent() on corresponding URLs.

Examples

This section provides two examples of client code. The first example uses "absolute resource" names and traditional mechanisms to get a Class object.

package pkg;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;

class Test {

  private static final String absName = "/pkg/mumble.baf";

  public static void test1() {
    Class c=null;
    try {
      c = Class.forName("pkg.Test");
    } catch (Exception ex) {
      // This should not happen.
    }
    InputStream s = c.getResourceAsStream(absName);
    // do something with it.
  }

  public void test2() {
    InputStream s = this.getClass().getResourceAsStream(absName);
  // do something with it.
  }
}

This example uses "relative resource" names and the mechanism available from the compiler through the -experimental flag, to get a Class object.

package pkg;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;

class Test {
  private static final String relName = "mumble.baf";
  public static void test1() {
  InputStream s = Test.class.getResourceAsStream(relName);
  // do something with it.
}

  public void test2() {
    InputStream s = Test.class.getResourceAsStream(relName);
    // do something with it.
  }

API References

  • java.lang.Class
  • java.lang.ClassLoader
  • java.net.URLClassLoader
  • java.util.ResourceBundle
  • java.lang.SecurityManager
  • java.security
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class javax.smartcardio.ResponseAPDU (Java Smart Card I/O b138)

  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
javax.smartcardio.ResponseAPDU

    • Uses of ResponseAPDU in javax.smartcardio

      Methods in javax.smartcardio that return ResponseAPDU
      Modifier and Type Method and Description
      abstract ResponseAPDU CardChannel.transmit(CommandAPDU command)
      Transmits the specified command APDU to the Smart Card and returns the response APDU.
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.ReturnTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.ReturnTree

  • Packages that use ReturnTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of ReturnTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type ReturnTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitReturn(ReturnTree node, P p)

    • Uses of ReturnTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type ReturnTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitReturn(ReturnTree node, P p)
      R | SimpleTreeVisitor.visitReturn(ReturnTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.css.RGBColor (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.css.RGBColor

  • Packages that use RGBColor
    Package Description
    org.w3c.dom.css

    • Uses of RGBColor in org.w3c.dom.css

      Methods in org.w3c.dom.css that return RGBColor
      Modifier and Type Method and Description
      RGBColor CSSPrimitiveValue.getRGBColorValue()
      This method is used to get the RGB color.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Properties That Affect the Behavior of Rich Internet Applications

The following properties can be specified in a rich Internet application's JNLP file to control the behavior of the rich Internet application (RIA - applet and Java Web Start applications).

Property | Allowed Value | Description
javaws.cfg.jauthenticator | true / false | A value of "true" or "all" prevents Java Web Start software from installing the default JAuthenticator.
jnlp.concurrentDownloads | integer | Number of threads for concurrent download of JAR files
jnlp.packEnabled | true / false | A value of "true" indicates that the application's JAR files have been compressed using the Pack200 tool. See Pack200 and Version Download for more information.
jnlp.versionEnabled | true / false | A value of "true" indicates that the application's JAR files have been versioned to enable the version download protocol. See Pack200 and Version Download for more information.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Remote Method Invocation: 7 - Remote Object Activation

CONTENTS | PREV | NEXT Java Remote Method Invocation

Remote Object Activation

CHAPTER 7

Topics:

  • Overview
  • Activation Protocol
  • Implementation Model for an "Activatable" Remote Object
  • Activation Interfaces

CONTENTS | PREV | NEXT

Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 7 - Remote Object Activation

CONTENTS | PREV | NEXT Java Remote Method Invocation

7.1 Overview

Distributed object systems are designed to support long-lived persistent objects. Given that these systems will be made up of many thousands (perhaps millions) of such objects, it would be unreasonable for object implementations to become active and remain active, taking up valuable system resources, for indefinite periods of time. In addition, clients need the ability to store persistent references to objects so that communication among objects can be re-established after a system crash, since typically a reference to a distributed object is valid only while the object is active.

Object activation is a mechanism for providing persistent references to objects and managing the execution of object implementations. In RMI, activation allows objects to begin execution on an as-needed basis. When an activatable remote object is accessed (via a method invocation) if that remote object is not currently executing, the system initiates the object's execution inside an appropriate JVM.

7.1.1 Terminology

An active object is a remote object that is instantiated and exported in a JVM on some system. A passive object is one that is not yet instantiated (or exported) in a JVM, but which can be brought into an active state. Transforming a passive object into an active object is a process known as activation. Activation requires that an object be associated with a JVM, which may entail loading the class for that object into a JVM and the object restoring its persistent state (if any).

In the RMI system, we use lazy activation. Lazy activation defers activating an object until a client's first use (i.e., the first method invocation).

7.1.2 Lazy Activation

Lazy activation of remote objects is implemented using a faulting remote reference (sometimes referred to as a fault block). A faulting remote reference to a remote object "faults in" the active object's reference upon the first method invocation to the object. Each faulting reference maintains both a persistent handle (an activation identifier) and a transient remote reference to the target remote object. The remote object's activation identifier contains enough information to engage a third party in activating the object. The transient reference is the actual "live" reference to the active remote object that can be used to contact the executing object.

In a faulting reference, if the live reference to a remote object is null, the target object is not known to be active. Upon method invocation, the faulting reference (for that object) engages in the activation protocol to obtain a "live" reference, which is a remote reference (such as a unicast remote reference) for the newly-activated object. Once the faulting reference obtains the live reference, the faulting reference forwards method invocations to the underlying remote reference which, in turn, forwards the method invocation to the remote object.

In more concrete terms, a remote object's stub contains a "faulting" remote reference type that contains both:

  • an activation identifier for a remote object, and
  • a "live" reference (possibly null) containing the "active" remote reference type of the remote object (for example, a remote reference type with unicast semantics).
Note - The RMI system preserves "at most once" semantics for remote calls. In other words, a call to an activatable or unicast remote object is sent at most once. Thus, if a call to a remote object fails (indicated by a RemoteException being thrown), the client can be guaranteed that the remote method executed no more than once (and perhaps not at all).

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 7 - Remote Object Activation

CONTENTS | PREV | NEXT Java Remote Method Invocation

7.2 Activation Protocol

During a remote method invocation, if the "live" reference for a target object is unknown, the faulting reference engages in the activation protocol. The activation protocol involves several entities: the faulting reference, the activator, an activation group, and the remote object being activated.

The activator (usually one per host) is the entity which supervises activation by being both:

  • a database of information that maps activation identifiers to the information necessary to activate an object (the object's class, the location--a URL path--from which the class can be loaded, specific data the object may need to bootstrap, etc.), and
  • a manager of Java virtual machines, that starts up JVMs (when necessary) and forwards requests for object activation (along with the necessary information) to the correct activation group inside a remote JVM.
Note that the activator keeps the current mapping of activation identifiers to active objects as a cache, so that the group does not need to be consulted on each activation request.

An activation group (one per JVM) is the entity which receives a request to activate an object in the JVM and returns the activated object back to the activator.

The activation protocol is as follows. A faulting reference uses an activation identifier and calls the activator (an internal RMI interface) to activate the object associated with the identifier. The activator looks up the object's activation descriptor (registered previously). The object's descriptor contains:

  • the object's group identifier, specifying the JVM in which it is activated,
  • the object's class name,
  • a URL path from which to load the object's class code, and
  • object-specific initialization data in marshalled form (initialization data might be the name of a file containing the object's persistent state, for example).
If the activation group in which this object should reside exists, the activator forwards the activation request to that group. If the activation group does not exist, the activator initiates a JVM executing an activation group and then forwards the activation request to that group.

The activation group loads the class for the object and instantiates the object using a special constructor that takes several arguments, including the activation descriptor registered previously.

When the object is finished activating, the activation group passes back a marshalled object reference to the activator that then records the activation identifier and active reference pairing and returns the active (live) reference to the faulting reference. The faulting reference (inside the stub) then forwards method invocations via the live reference directly to the remote object.

Note - In Java 2 SDK, Standard Edition, v 1.2, RMI provides an implementation of the activation system interfaces. In order to use activation, you must first run the activation system daemon rmid.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 7 - Remote Object Activation

CONTENTS | PREV | NEXT Java Remote Method Invocation

7.3 Implementation Model for an "Activatable" Remote Object

In order to make a remote object that can be accessed via an activation identifier over time, a developer needs to:
  • register an activation descriptor for the remote object, and
  • include a special constructor in the object's class that the RMI system calls when it activates the activatable object.
An activation descriptor (ActivationDesc) can be registered in one of several ways:
  • via a call to the static register method of the class Activatable, or
  • by creating an "activatable" object via the first or second constructor of the Activatable class, or
  • by exporting an "activatable" object explicitly via Activatable's first or second exportObject method.
For a specific object, only one of the above methods should be used to register the object for activation. See the section below on "Constructing an Activatable Remote Object" for examples on how to implement activatable objects.

7.3.1 The ActivationDesc Class

An ActivationDesc contains the information necessary to activate an object. It contains the object's activation group identifier, the class name for the object, a codebase path (or URLs) from which the object's code can be loaded, and a MarshalledObject that may contain object-specific initialization data used during each activation.

A descriptor registered with the activation system is consulted (during the activation process) to obtain information in order to re-create or activate an object. The MarshalledObject in the object's descriptor is passed as the second argument to the remote object's constructor for the object to use during activation.

package java.rmi.activation;

public final class ActivationDesc implements java.io.Serializable
{

        public ActivationDesc(String className,
                              String codebase,
                              java.rmi.MarshalledObject data)
                throws ActivationException;

        public ActivationDesc(String className,
                              String codebase,
                              java.rmi.MarshalledObject data,
                              boolean restart)
                throws ActivationException;

        public ActivationDesc(ActivationGroupID groupID,
                              String className,
                              String codebase,
                              java.rmi.MarshalledObject data,
                              boolean restart);

        public ActivationDesc(ActivationGroupID groupID,
                              String className,
                              String codebase,
                              java.rmi.MarshalledObject data);

        public ActivationGroupID getGroupID();

        public String getClassName();

        public String getLocation();

        public java.rmi.MarshalledObject getData()

        public boolean getRestartMode();
}
The first constructor for ActivationDesc constructs an object descriptor for an object whose class is className, that can be loaded from codebase path, and whose initialization information, in marshalled form, is data. If this form of the constructor is used, the object's group identifier defaults to the current identifier for ActivationGroup for this JVM. All objects with the same ActivationGroupID are activated in the same JVM. If the current group is inactive an ActivationException is thrown. If the groupID is null, an IllegalArgumentException is thrown.

The second constructor for ActivationDesc constructs an object descriptor in the same manner as the first constructor except an additional parameter, restart, must be supplied. If the object requires restart service, meaning that the object will be restarted automatically when the activator is restarted (as opposed to being activated lazily upon demand), restart should be true. If restart is false, the object is simply activated upon demand (via a remote method call).

The third constructor for ActivationDesc constructs an object descriptor for an object whose group identifier is groupID, whose class name is className that can be loaded from the codebase path, and whose initialization information is data. All objects with the same groupID are activated in the same JVM.

The fourth constructor for ActivationDesc constructs an object descriptor in the same manner as the third constructor, but allows a restart mode to be specified. If an object requires restart service (as defined above), restart should be true.

The getGroupID method returns the group identifier for the object specified by the descriptor. A group provides a way to aggregate objects into a single Java virtual machine.

The getClassName method returns the class name for the object specified by the activation descriptor.

The getLocation method returns the codebase path from where the object's class can be downloaded.

The getData method returns a "marshalled object" containing initialization (activation) data for the object specified by the descriptor.

The getRestartMode method returns true if the restart mode is enabled for this object, otherwise it returns false.

7.3.2 The ActivationID Class

The activation protocol makes use of activation identifiers to denote remote objects that can be activated over time. An activation identifier (an instance of the class ActivationID) contains several pieces of information needed for activating an object:
  • a remote reference to the object's activator, and
  • a unique identifier for the object.
An activation identifier for an object can be obtained by registering an object with the activation system. Registration is accomplished in a few ways (also noted above):
  • via the Activatable.register method, or
  • via the first or second Activatable constructor, which both registers and exports the object, or
  • via the first or second Activatable.exportObject method, this method both registers and exports the object.
package java.rmi.activation;

public class ActivationID implements java.io.Serializable
{
        public ActivationID(Activator activator);

        public Remote activate(boolean force)
                throws ActivationException, UnknownObjectException,
                       java.rmi.RemoteException;

        public boolean equals(Object obj);

        public int hashCode();
}
The constructor for ActivationID takes a single argument, activator, that specifies a remote reference to the activator responsible for activating the object associated with this activation identifier. An instance of ActivationID is globally unique.

The activate method activates the object associated with the activation identifier. If the force parameter is true, the activator considers any cached reference for the remote object as stale, thus forcing the activator to contact the group when activating the object. If force is false, then returning the cached value is acceptable. If activation fails, ActivationException is thrown. If the object identifier is not known to the activator, then the method throws UnknownObjectException. If the remote call to the activator fails, then RemoteException is thrown.

The equals method implements content equality. It returns true if all fields are equivalent (either identical or equivalent according to each field's Object.equals semantics). If p1 and p2 are instances of the class ActivationID, the hashCode method will return the same value if p1.equals(p2) returns true.

7.3.3 The Activatable Class

The Activatable class provides support for remote objects that require persistent access over time and that can be activated by the system. The class Activatable is the main API that developers need to use to implement and manage activatable objects. Note that you must first run the activation system daemon, rmid, before objects can be registered and/or activated.

package java.rmi.activation;

public abstract class Activatable
        extends java.rmi.server.RemoteServer
{
        protected Activatable(String codebase,
                              java.rmi.MarshalledObject data,
                              boolean restart,
                              int port)
                throws ActivationException, java.rmi.RemoteException;

        protected Activatable(String codebase,
                              java.rmi.MarshalledObject data,
                              boolean restart, int port,
                              RMIClientSocketFactory csf,
                              RMIServerSocketFactory ssf)
                throws ActivationException, java.rmi.RemoteException;

        protected Activatable(ActivationID id, int port)
                throws java.rmi.RemoteException;

        protected Activatable(ActivationID id, int port,
                              RMIClientSocketFactory csf,
                              RMIServerSocketFactory ssf)
                throws java.rmi.RemoteException;

        protected ActivationID getID();

        public static Remote register(ActivationDesc desc)
                throws UnknownGroupException, ActivationException,
                       java.rmi.RemoteException;

        public static boolean inactive(ActivationID id)
                throws UnknownObjectException, ActivationException,
                       java.rmi.RemoteException;

        public static void unregister(ActivationID id)
                throws UnknownObjectException, ActivationException,
                       java.rmi.RemoteException;

        public static ActivationID exportObject(Remote obj,
                                                String codebase,
                                                MarshalledObject data,
                                                boolean restart,
                                                int port)
                throws ActivationException, java.rmi.RemoteException;

        public static ActivationID exportObject(Remote obj,
                                                String codebase,
                                                MarshalledObject data,
                                                boolean restart,
                                                int port,
                                                RMIClientSocketFactory csf,
                                                RMIServerSocketFactory ssf)
                throws ActivationException, java.rmi.RemoteException;

        public static Remote exportObject(Remote obj,
                                          ActivationID id,
                                          int port)
                throws java.rmi.RemoteException;

        public static Remote exportObject(Remote obj,
                                          ActivationID id,
                                          int port,
                                          RMIClientSocketFactory csf,
                                          RMIServerSocketFactory ssf)
                throws java.rmi.RemoteException;

        public static boolean unexportObject(Remote obj, boolean force)
                throws java.rmi.NoSuchObjectException;
}
An implementation for an activatable remote object may or may not extend the class Activatable. A remote object implementation that does extend the Activatable class inherits the appropriate definitions of the hashCode and equals methods from the superclass java.rmi.server.RemoteObject. So, two remote object references that refer to the same Activatable remote object will be equivalent (the equals method will return true). Also, an instance of the class Activatable will be "equals" to the appropriate stub object for the instance (i.e., the Object.equals method will return true if called with the matching stub object for the implementation as an argument, and vice versa).

Activatable Class Methods

The first constructor for the Activatable class is used to register and export the object on a specified port (an anonymous port is chosen if port is zero). The object's URL path for downloading its class code is codebase, and its initialization data is data. If restart is true, the object will be restarted automatically when the activator is restarted and if the group crashes. If restart is false, the object will be activated on demand (via a remote method call to the object).

A concrete subclass of the Activatable class must call this constructor to register and export the object during initial construction. As a side-effect of activatable object construction, the remote object is both "registered" with the activation system and "exported" (on an anonymous port, if port is zero) to the RMI runtime so that it is available to accept incoming calls from clients.

The constructor throws ActivationException if registering the object with the activation system fails. RemoteException is thrown if exporting the object to the RMI runtime fails.

The second constructor is the same as the first Activatable constructor but allows the specification of the client and server socket factories used to communicate with this activatable object. See the section in about "RMI Socket Factories" for details.

The third constructor is used to activate and export the object (with the ActivationID, id) on a specified port. A concrete subclass of the Activatable class must call this constructor when the object itself is activated via its special "activation" constructor whose parameters must be:

  • the object's activation identifier (ActivationID), and
  • the object's initialization/bootstrap data (a MarshalledObject).
As a side-effect of construction, the remote object is "exported" to the RMI runtime (on the specified port) and is available to accept incoming calls from clients. The constructor throws RemoteException if exporting the object to the RMI runtime fails.

The fourth constructor is the same as the third constructor, but allows the specification of the client and server socket factories used to communicate with this activatable object.

The getID method returns the object's activation identifier. The method is protected so that only subclasses can obtain an object's identifier. The object's identifier is used to report the object as inactive or to unregister the object's activation descriptor.

The register method registers, with the activation system, an object descriptor, desc, for an activatable remote object so that it can be activated on demand. This method is used to register an activatable object without having to first create the object. This method returns the Remote stub for the activatable object so that it can be saved and called at a later time thus forcing the object to be created/activated for the first time. The method throws UnknownGroupException if the group identifier in desc is not registered with the activation system. ActivationException is thrown if the activation system is not running. Finally, RemoteException is thrown if the remote call to the activation system fails.

The inactive method is used to inform the system that the object with the corresponding activation id is currently inactive. If the object is currently known to be active, the object is unexported from the RMI runtime (only if there are no pending or executing calls) so the that it can no longer receive incoming calls. This call also informs this JVM's ActivationGroup that the object is inactive; the group, in turn, informs its ActivationMonitor. If the call completes successfully, subsequent activate requests to the activator will cause the object to reactivate. The inactive method returns true if the object was successfully unexported (meaning that it had no pending or executing calls at the time) and returns false if the object could not be unexported due to pending or in-progress calls. The method throws UnknownObjectException if the object is not known (it may already be inactive); an ActivationException is thrown if the group is not active; a RemoteException is thrown if the call informing the monitor fails. The operation may still succeed if the object is considered active but has already unexported itself.

The unregister method revokes previous registration for the activation descriptor associated with id. An object can no longer be activated via that id. If the object id is unknown to the activation system, an UnknownObjectException is thrown. If the activation system is not running, an ActivationException is thrown. If the remote call to the activation system fails, then a RemoteException is thrown.

The first exportObject method may be invoked explicitly by an "activatable" object that does not extend the Activatable class, in order to both

  • register the object's activation descriptor, desc, constructed from the supplied codebase and data, with the activation system so the object can be activated, and
  • export the remote object, obj, on a specific port. If the port is zero, then an anonymous port is chosen.
Once the object is exported, it can receive incoming RMI calls.

This exportObject method returns the activation identifier obtained from registering the descriptor, desc, with the activation system. If the activation group is not active in the JVM, then ActivationException is thrown. If the object registration or export fails, then RemoteException is thrown.

This method does not need to be called if obj extends Activatable, since the first Activatable constructor calls this method.

The second exportObject method is the same as the first except it allows the specification of client and server socket factories used to communicate with the activatable object.

The third exportObject method exports an "activatable" remote object (not necessarily of type Activatable) with the identifier, id, to the RMI runtime to make the object, obj, available to receive incoming calls. The object is exported on an anonymous port, if port is zero.

During activation, this exportObject method should be invoked explicitly by an "activatable" object, that does not extend the Activatable class. There is no need for objects that do extend the Activatable class to invoke this method directly; this method is called by the third constructor above (which a subclass should invoke from its special activation constructor).

This exportObject method returns the Remote stub for the activatable object. If the object export fails, then the method throws RemoteException.

The fourth exportObject method is the same as the third but allows the specification of the client and server socket factories used to communicate with this activatable object.

The unexportObject method makes the remote object, obj, unavailable for incoming calls. If the force parameter is true, the object is forcibly unexported even if there are pending calls to the remote object or the remote object still has calls in progress. If the force parameter is false, the object is only unexported if there are no pending or in progress calls to the object. If the object is successfully unexported, the RMI runtime removes the object from its internal tables. Removing the object from RMI use in this forcible manner may leave clients holding stale remote references to the remote object. This method throws java.rmi.NoSuchObjectException if the object was not previously exported to the RMI runtime.

Constructing an Activatable Remote Object

In order for an object to be activated, the "activatable" object implementation class (whether or not it extends the Activatable class) must define a special public constructor that takes two arguments, its activation identifier of type ActivationID, and its activation data, a java.rmi.MarshalledObject, supplied in the activation descriptor used during registration. When an activation group activates a remote object inside its JVM, it constructs the object via this special constructor (described in more detail below). The remote object implementation may use the activation data to initialize itself in a suitable manner. The remote object may also wish to retain its activation identifier, so that it can inform the activation group when it becomes inactive (via a call to the Activatable.inactive method).

The first and second constructor forms for Activatable are used to both register and export an activatable object on a specified port. This constructor should be used when initially constructing the object; the third form of the constructor is used when re-activating the object.

A concrete subclass of Activatable must call the first or second constructor form to register and export the object during initial construction. This constructor first creates an activation descriptor (ActivationDesc) with the object's class name, the object's supplied codebase and data, and whose activation group is the default group for the JVM. Next, the constructor registers this descriptor with the default ActivationSystem. Finally, the constructor exports the activatable object to the RMI runtime on the specific port (if port is zero, then an anonymous port is chosen) and reports the object as an activeObject to the local ActivationGroup. If an error occurs during registration or export, the constructor throws RemoteException. Note that the constructor also initializes its ActivationID (obtained via registration), so that subsequent calls to the protected method getID will return the object's activation identifier.

The third constructor form for Activatable is used to export the object on a specified port. A concrete subclass of Activatable must call the third constructor form when it is activated via the object's own "activation" constructor, which takes two arguments:

  • the object's ActivationID
  • the object's initialization data, a MarshalledObject
This constructor only exports the activatable object to the RMI runtime on the specific port (if port is 0, then an anonymous port is chosen). It does not inform the ActivationGroup that the object is active, since it is the ActivationGroup that is activating the object and knows it to be active already.

The following is an example of a remote object interface, Server, and an implementation, ServerImpl, that extends the Activatable class:

package examples;

public interface Server extends java.rmi.Remote {
        public void doImportantStuff()
                throws java.rmi.RemoteException;
}

public class ServerImpl extends Activatable implements Server
{
        // Constructor for initial construction, registration and export
        public ServerImpl(String codebase, MarshalledObject data)
                throws ActivationException, java.rmi.RemoteException
        {
                // register object with activation system, then
                // export on anonymous port
                super(codebase, data, false, 0);
        }

        // Constructor for activation and export; this constructor
        // is called by the ActivationInstantiator.newInstance
        // method during activation in order to construct the object.
        public ServerImpl(ActivationID id, MarshalledObject data)
                throws java.rmi.RemoteException
        {
                // call the superclass's constructor in order to
                // export the object to the RMI runtime.
                super(id, 0);
                // initialize object (using data, for example)
        }

        public void doImportantStuff() { ... }
}
An object is responsible for exporting itself. The constructors for Activatable take care of exporting the object to the RMI runtime with the live reference type of a UnicastRemoteObject, so the object implementation extending Activatable does not need to worry about the detail of exporting the object explicitly (other than invoking the appropriate superclasses constructor). If an object implementation does not extend the class Activatable, the object must export the object explicitly via a call to one of the Activatable.exportObject static methods.

In the following example, ServerImpl does not extend Activatable, but rather another class, so ServerImpl is responsible for exporting itself during initial construction and activation. The following class definition shows ServerImpl's initialization constructor and its special "activation" constructor and the appropriate call to export the object within each constructor:

package examples;

public class ServerImpl extends SomeClass implements Server
{
        // constructor for initial creation
        public ServerImpl(String codebase, MarshalledObject data)
                throws ActivationException, java.rmi.RemoteException
        {
                // register and export the object
                Activatable.exportObject(this, codebase, data, false, 0);
        }

        // constructor for activation
        public ServerImpl(ActivationID id, MarshalledObject data)
                throws java.rmi.RemoteException
        {
                // export the object
                Activatable.exportObject(this, id, 0);
        }

        public void doImportantStuff() { ... }
}

Registering an Activation Descriptor Without Creating the Object

To register an activatable remote object with the activation system without first creating the object, the programmer can simply register an activation descriptor (an instance of the class ActivationDesc) for the object. An activation descriptor contains all the necessary information so that the activation system can activate the object when needed. An activation descriptor for an instance of the class examples.ServerImpl can be registered in the following manner (exception handling elided):

 Server server;
ActivationDesc desc;
String codebase = "http://zaphod/codebase/";

MarshalledObject data = new
MarshalledObject("some data");
desc = new ActivationDesc( "examples.ServerImpl", codebase,
data);
server = (Server)Activatable.register(desc);

The register call returns a Remote stub that is the stub for the examples.ServerImpl object and implements the same set of remote interfaces that examples.ServerImpl implements (i.e, the stub implements the remote interface Server). This stub object (above, cast and assigned to server) can be passed as a parameter in any method call expecting an object that implements the examples.Server remote interface.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 7 - Remote Object Activation

CONTENTS | PREV | NEXT Java Remote Method Invocation

7.4 Activation Interfaces

In the RMI activation protocol, there are two guarantees that the activator must make for the system to function properly:
  • like all system daemons, the activator should remain running while the machine is up, and
  • the activator must not reactivate remote objects that are already active.
The activator maintains a database of appropriate information for the groups and objects that it participates in activating.

7.4.1 The Activator Interface

The activator is one of the entities that participates during the activation process. As described earlier, a faulting reference (inside a stub) calls the activator's activate method to obtain a "live" reference to an activatable remote object. Upon receiving a request for activation, the activator looks up the activation descriptor for the activation identifier, id, determines the group in which the object should be activated, and invokes the newInstance method on the activation group's instantiator (the remote interface ActivationGroup is described below). The activator initiates the execution of activation groups as necessary. For example, if an activation group for a specific group descriptor is not already executing, the activator will spawn a child JVM for the activation group to establish the group in the new JVM.

The activator is responsible for monitoring and detecting when activation groups fail so that it can remove stale remote references from its internal tables.

package java.rmi.activation;
public interface Activator extends java.rmi.Remote
{
        java.rmi.MarshalledObject activate(ActivationID id,
                                           boolean force)
                throws UnknownObjectException, ActivationException,
                       java.rmi.RemoteException;
}
The activate method activates the object associated with the activation identifier, id. If the activator knows the object to be active already and the force parameter is false, the stub with a "live" reference is returned immediately to the caller; otherwise, if the activator does not know that the corresponding remote object is active or the force parameter is true, the activator uses the activation descriptor information (previously registered to obtain the id) to determine the group (JVM) in which the object should be activated. If an ActivationInstantiator corresponding to the object's group already exists, the activator invokes the activation instantiator's newInstance method, passing it the id and the object's activation descriptor.

If the activation instantiator (group) for the object's group descriptor does not yet exist, the activator starts a new incarnation of an ActivationInstantiator executing (by spawning a child process, for example). When the activator re-creates an ActivationInstantiator for a group, it must increment the group's incarnation number. Note that the incarnation number is zero-based. The activation system uses incarnation numbers to detect late ActivationSystem.activeGroup and ActivationMonitor.inactiveGroup calls. The activation system discards calls with an earlier incarnation number than the current number for the group.

Note - The activator must communicate both the activation group's identifier, descriptor, and incarnation number when it starts up a new activation group. The activator spawns an activation group in a separate JVM (as a separate or child process, for example), and therefore must pass information specifying the information necessary to create the group via the ActivationGroup.createGroup method. How the activator sends this information to the spawned process is unspecified, however, this information could be sent in the form of marshalled objects to the child process's standard input.
When the activator receives the activation group's call back (via the ActivationSystem.activeGroup method) specifying the activation group's reference and incarnation number, the activator can then invoke that activation instantiator's newInstance method to forward each pending activation request to the activation instantiator and return the result (a marshalled remote object reference, a stub) to each caller.

Note that the activator receives a MarshalledObject instead of a Remote object so that the activator does not need to load the code for that object, or participate in distributed garbage collection for that object. If the activator kept a strong reference to the remote object, the activator would then prevent the object from being garbage collected under the normal distributed garbage collection mechanism.

The activate method throws ActivationException if activation fails. Activation may fail for a variety of reasons: the class could not be found, the activation group could not be contacted, etc. The activate method throws UnknownObjectException if no activation descriptor for the activation identifier, id, has been previously registered with this activator. RemoteException is thrown if the remote call to the activator fails.

7.4.2 The ActivationSystem Interface

The ActivationSystem provides a means for registering groups and activatable objects to be activated within those groups. The ActivationSystem works closely with both the Activator, which activates objects registered via the ActivationSystem, and the ActivationMonitor, which obtains information about active and inactive objects and inactive groups.
package java.rmi.activation;
public interface ActivationSystem extends java.rmi.Remote
{
        public static final int SYSTEM_PORT = 1098;

        ActivationGroupID registerGroup(ActivationGroupDesc desc)
                throws ActivationException, java.rmi.RemoteException;

        ActivationMonitor activeGroup(ActivationGroupID id,
                                      ActivationInstantiator group,
                                      long incarnation)
                throws UnknownGroupException, ActivationException,
                       java.rmi.RemoteException;

        void unregisterGroup(ActivationGroupID id)
                throws ActivationException, UnknownGroupException,
                       java.rmi.RemoteException;

        ActivationID registerObject(ActivationDesc desc)
                throws ActivationException, UnknownGroupException,
                       java.rmi.RemoteException;

        void unregisterObject(ActivationID id)
                throws ActivationException, UnknownObjectException,
                       java.rmi.RemoteException;

        void shutdown() throws java.rmi.RemoteException;
}
Note - As a security measure, all of the above methods (registerGroup, activeGroup, unregisterGroup, registerObject, unregisterObject, and shutdown) will throw java.rmi.AccessException, a subclass of java.rmi.RemoteException, if called from a client that does not reside on the same host as the activation system.
The registerObject method is used to register an activation descriptor, desc, and obtain an activation identifier for an activatable remote object. The ActivationSystem creates an ActivationID (an activation identifier) for the object specified by the descriptor, desc, and records, in stable storage, the activation descriptor and its associated identifier for later use. When the Activator receives an activate request for a specific identifier, it looks up the activation descriptor (registered previously) for the specified identifier and uses that information to activate the object. If the group referred to in desc is not registered with this system, then the method throws UnknownGroupException. If registration fails (e.g., database update failure, etc), then the method throws ActivationException. If the remote call fails, then RemoteException is thrown.

The unregisterObject method removes the activation identifier, id, and associated descriptor previously registered with the ActivationSystem. After the call completes, the object can no longer be activated via the object's activation id. If the object id is unknown (not registered) the method throws UnknownObjectException. If the unregister operation fails (e.g., database update failure, etc.), then the method throws ActivationException. If the remote call fails, then RemoteException is thrown.

The registerGroup method registers the activation group specified by the group descriptor, desc, with the activation system and returns the ActivationGroupID assigned to that group. An activation group must be registered with the ActivationSystem before objects can be registered within that group. If group registration fails, the method throws ActivationException. If the remote call fails, then RemoteException is thrown.

The activeGroup method is a call back from the ActivationGroup (with the identifier, id), to inform the activation system that group is now active and is the ActivationInstantiator for that JVM. This call is made internally by the ActivationGroup.createGroup method to obtain an ActivationMonitor that the group uses to update the system regarding objects' and the group's status (i.e., that the group or objects within that group have become inactive). If the group is not registered, then the method throws UnknownGroupException. If the group is already active, then ActivationException is thrown. If the remote call to the activation system fails, then RemoteException is thrown.

The unregisterGroup method removes the activation group with identifier, id, from the activation system. An activation group makes this call back to inform the activator that the group should be destroyed. If this call completes successfully, objects can no longer be registered or activated within the group. All information of the group and its associated objects is removed from the system. The method throws UnknownGroupException if the group is not registered. If the remote call fails, then RemoteException is thrown. If the unregister fails, ActivationException is thrown (e.g., database update failure, etc.).

The shutdown method gracefully terminates (asynchronously) the activation system and all related activation processes (activator, monitors and groups). All groups spawned by the activation daemon will be destroyed and the activation daemon will exit. In order to shut down the activation system daemon, rmid, execute the command:

                rmid -stop [-port num]
This command will shut down the activation daemon on the specified port (if no port is specified, the daemon on the default port will be shut down).

7.4.3 The ActivationMonitor Class

An ActivationMonitor is specific to an ActivationGroup and is obtained when a group is reported via a call to ActivationSystem.activeGroup (this is done internally by the ActivationGroup.createGroup method). An activation group is responsible for informing its ActivationMonitor when:
a. its objects become active,

b. its objects become inactive, or

c. the group as a whole becomes inactive.

package java.rmi.activation;
public interface ActivationMonitor
        extends java.rmi.Remote
{

        public abstract void inactiveObject(ActivationID id)
                throws UnknownObjectException, RemoteException;

        public void activeObject(ActivationID id,
                                 java.rmi.MarshalledObject mobj)
                throws UnknownObjectException, java.rmi.RemoteException;

        public void inactiveGroup(ActivationGroupID id,
                                  long incarnation)
                throws UnknownGroupException, java.rmi.RemoteException;
}
An activation group calls its monitor's inactiveObject method when an object in its group becomes inactive (deactivates). An activation group discovers that an object (that it participated in activating) in its JVM is no longer active via a call to the activation group's inactiveObject method.

The inactiveObject call informs the ActivationMonitor that the remote object reference it holds for the object with the activation identifier, id, is no longer valid. The monitor considers the reference associated with id as a stale reference. Since the reference is considered stale, a subsequent activate call for the same activation identifier results in re-activating the remote object. If the object is not known to the ActivationMonitor, the method throws UnknownObjectException. If the remote call fails, then RemoteException is thrown.

The activeObject call informs the ActivationMonitor that the object associated with id is now active. The parameter obj is the marshalled representation of the object's stub. An ActivationGroup must inform its monitor if an object in its group becomes active by other means than being activated directly by the system (i.e., the object is registered and "activated" itself). If the object id is not previously registered, then the method throws UnknownObjectException. If the remote call fails, then RemoteException is thrown.

The inactiveGroup call informs the monitor that the group specified by id and incarnation is now inactive. The group will be re-created with a greater incarnation number upon a subsequent request to activate an object within the group. A group becomes inactive when all objects in the group report that they are inactive. If either the group id is not registered or the incarnation number is smaller than the current incarnation for the group, then the method throws UnknownGroupException. If the remote call fails, then RemoteException is thrown.

7.4.4 The ActivationInstantiator Class

The ActivationInstantiator is responsible for creating instances of activatable objects. A concrete subclass of ActivationGroup implements the newInstance method to handle creating objects within the group.

package java.rmi.activation;
public interface ActivationInstantiator
        extends java.rmi.Remote
{
        public MarshalledObject newInstance(ActivationID id,
                                            ActivationDesc desc)
                throws ActivationException, java.rmi.RemoteException;

}
The activator calls an instantiator's newInstance method in order to re-create in that group an object with the activation identifier, id, and descriptor, desc. The instantiator is responsible for:
  • determining the class for the object using the descriptor's getClassName method,
  • loading the class from the codebase path obtained from the descriptor (using the getLocation method),
  • creating an instance of the class by invoking the special "activation" constructor of the object's class that takes two arguments: the object's ActivationID, and the MarshalledObject containing object-specific initialization data, and
  • returning a MarshalledObject containing the remote object it created.
An instantiator is also responsible for reporting when objects it creates or activates are no longer active, so that it can make the appropriate inactiveObject call to its ActivationMonitor (see the ActivationGroup class for more details).

If object activation fails, then the newInstance method throws ActivationException. If the remote call fails, then the method throws RemoteException.

7.4.5 The ActivationGroupDesc Class

An activation group descriptor (ActivationGroupDesc) contains the information necessary to create or re-create an activation group in which to activate objects in the same JVM.

Such a descriptor contains:

  • the group's class name (a class name of null indicates the default ActivationGroup implementation),
  • the group's codebase path (the location of the group's class), and
  • a "marshalled" object that can contain object-specific initialization data.
The group's class must be a concrete subclass of ActivationGroup. A subclass of ActivationGroup is created or re-created via the ActivationGroup.createGroup static method, which invokes a special constructor that takes two arguments:
  • the group's ActivationGroupID, and
  • the group's initialization data (in a java.rmi.MarshalledObject)
package java.rmi.activation;
public final class ActivationGroupDesc
        implements java.io.Serializable
{

        public ActivationGroupDesc(java.util.Properties props,
                                   CommandEnvironment env);;

        public ActivationGroupDesc(String className,
                                   String codebase,
                                   java.rmi.MarshalledObject data,
                                   java.util.Properties props,
                                   CommandEnvironment env);

        public String getClassName();

        public String getLocation();

        public java.rmi.MarshalledObject getData();

        public CommandEnvironment getCommandEnvironment();

        public java.util.Properties getPropertiesOverrides();

}
The first constructor creates a group descriptor that uses system default for group implementation and code location. Properties specify Java application environment overrides (which will override system properties in the group implementation's JVM). The command environment can control the exact command/options used in starting the child JVM, or can be null to accept rmid's default. This constructor will create an ActivationGroupDesc with a null group class name, which indicates the system's default ActivationGroup implementation.

The second constructor is the same as the first, but allows the specification of Properties and CommandEnvironment.

The getClassName method returns the group's class name (possibly null). A null group class name indicates the system's default ActivationGroup implementation.

The getLocation method returns the codebase path from where the group's class can be loaded.

The getData method returns the group's initialization data in marshalled form.

The getCommandEnvironment method returns the command environment (possibly null).

The getPropertiesOverrides method returns the properties overrides (possibly null) for this descriptor.

7.4.6 The ActivationGroupDesc.CommandEnvironment Class

The CommandEnvironment class allows overriding default system properties and specifying implemention-defined options for an ActivationGroup.
public static class CommandEnvironment
        implements java.io.Serializable
{
        public CommandEnvironment(String cmdpath, String[] args);
        public boolean equals(java.lang.Object);
        public String[] getCommandOptions();
        public String getCommandPath();
        public int hashCode();

}
The constructor creates a CommandEnvironment with the given command, cmdpath, and additional command line options, args.

The equals implements content equality for command environment objects. The hashCode method is implemented appropriately so that a CommandEnvironment can be stored in a hash table if necessary.

The getCommandOptions method returns the environment object's command line options.

The getCommandPath method returns the environment object's command string.

7.4.7 The ActivationGroupID Class

The identifier for a registered activation group serves several purposes:
  • it identifies the group uniquely within the activation system, and
  • it contains a reference to the group's activation system so that the group can contact its activation system when necessary.
The ActivationGroupID is returned from the call to ActivationSystem.registerGroup and is used to identify the group within the activation system. This group identifier is passed as one of the arguments to the activation group's special constructor when an activation group is created or re-created.

package java.rmi.activation;
public class ActivationGroupID implements java.io.Serializable
{
        public ActivationGroupID(ActivationSystem system);

        public ActivationSystem getSystem();

        public boolean equals(Object obj);

        public int hashCode();
}
The ActivationGroupID constructor creates a unique group identifier whose ActivationSystem is system.

The getSystem method returns the activation system for the group.

The hashCode method returns a hashcode for the group's identifier. Two group identifiers that refer to the same remote group will have the same hash code.

The equals method compares two group identifiers for content equality. The method returns true if both of the following conditions are true: 1) the unique identifiers are equivalent (by content), and 2) the activation system specified in each refers to the same remote object.

7.4.8 The ActivationGroup Class

An ActivationGroup is responsible for creating new instances of activatable objects in its group, informing its ActivationMonitor when:
a. its objects become active,

b. its objects become inactive, or

c. the group as a whole becomes inactive.
An ActivationGroup is initially created in one of several ways:
  • as a side-effect of creating a "default" ActivationDesc for an object, or
  • by an explicit call to the ActivationGroup.createGroup method, or
  • as a side-effect of activating the first object in a group whose ActivationGroupDesc was only registered.
Only the activator can re-create an ActivationGroup. The activator spawns, as needed, a separate JVM (as a child process, for example) for each registered activation group and directs activation requests to the appropriate group. It is implementation specific how JVMs are spawned. An activation group is created via the ActivationGroup.createGroup static method. The createGroup method has two requirements on the group to be created: 1) the group must be a concrete subclass of ActivationGroup, and 2) the group must have a constructor that takes two arguments:
  • the group's ActivationGroupID, and
  • the group's initialization data (in a MarshalledObject)
When created, the default implementation of ActivationGroup will set the system properties to the system properties in force when the ActivationGroupDesc was created, and will set the security manager to the java.rmi.RMISecurityManager. If your application requires some specific properties to be set when objects are activated in the group, the application should set the properties before creating any ActivationDescs (before the default ActivationGroupDesc is created).
package java.rmi.activation;
public abstract class ActivationGroup
        extends UnicastRemoteObject
        implements ActivationInstantiator
{
        protected ActivationGroup(ActivationGroupID groupID)
                throws java.rmi.RemoteException;

        public abstract MarshalledObject newInstance(ActivationID id,
                                                     ActivationDesc desc)
                throws ActivationException, java.rmi.RemoteException;

        public abstract boolean inactiveObject(ActivationID id)
                throws ActivationException, UnknownObjectException,
                       java.rmi.RemoteException;

        public static ActivationGroup createGroup(ActivationGroupID id,
                                                  ActivationGroupDesc desc,
                                                  long incarnation)
                throws ActivationException;

        public static ActivationGroupID currentGroupID();

        public static void setSystem(ActivationSystem system)
                throws ActivationException;

        public static ActivationSystem getSystem()
                throws ActivationException;

        protected void activeObject(ActivationID id,
                                    java.rmi.MarshalledObject mobj)
                throws ActivationException, UnknownObjectException,
                       java.rmi.RemoteException;

        protected void inactiveGroup()
                throws UnknownGroupException, java.rmi.RemoteException;

}
The activator calls an activation group's newInstance method in order to activate an object with the activation descriptor, desc. The activation group is responsible for:
  • determining the class for the object using the descriptor's getClassName method,
  • loading the class from the URL path obtained from the descriptor (using the getLocation method),
  • creating an instance of the class by invoking the special constructor of the object's class that takes two arguments: the object's ActivationID, and a MarshalledObject containing the object's initialization data, and
  • returning a serialized version of the remote object it just created to the activator.
The method throws ActivationException if the instance for the given descriptor could not be created.

The group's inactiveObject method is called indirectly via a call to the Activatable.inactive method. A remote object implementation must call Activatable's inactive method when that object deactivates (the object deems that it is no longer active). If the object does not call Activatable.inactive when it deactivates, the object will never be garbage collected since the group keeps strong references to the objects it creates.

The group's inactiveObject method unexports the remote object, associated with id (only if there are no pending or executing calls to the remote object) from the RMI runtime so that the object can no longer receive incoming RMI calls. If the object currently has pending or executing calls, inactiveObject returns false and no action is taken.

If the unexportObject operation was successful (meaning that the object has no pending or executing calls), the group informs its ActivationMonitor (via the monitor's inactiveObject method) that the remote object is not currently active so that the remote object will be reactivated by the activator upon a subsequent activation request. If the operation was successful, inactiveObject returns true. The operation may still succeed if the object is considered active by the ActivationGroup but has already been unexported.

The inactiveObject method throws an UnknownObjectException if the activation group has no knowledge of this object (e.g., the object was previously reported as inactive, or the object was never activated via the activation group). If the inactive operation fails (e.g., if the remote call to the activator or activation group fails), RemoteException is thrown.

The createGroup method creates and sets the activation group for the current JVM. The activation group can only be set if it is not currently set. An activation group is set using the createGroup method when the Activator initiates the re-creation of an activation group in order to carry out incoming activate requests. A group must first register a group descriptor with the ActivationSystem before it can be created via this method (passing it the ActivationID obtained from previous registration).

The group specified by the ActivationGroupDesc, desc, must be a concrete subclass of ActivationGroup and have a public constructor that takes two arguments; the ActivationGroupID for the group and a MarshalledObject containing the group's initialization data (obtained from its ActivationGroupDesc). If the ActivationGroupDesc.getClassName method returns null, the system's default group implementation is used. Note: if your application creates its own custom activation group, the group must set a security manager in the constructor, or objects cannot be activated in the group.

After the group is created, the ActivationSystem is informed that the group is active by calling the activeGroup method, which returns the ActivationMonitor for the group. The application need not call activeGroup independently since that callback is taken care of by the createGroup method.

Once a group is created, subsequent calls to the currentGroupID method will return the identifier for this group until the group becomes inactive, at which point the currentGroupID method will return null.

The parameter incarnation indicates the current group incarnation, i.e., the number of times the group has been activated. The incarnation number is used as a parameter to the activeGroup method, once the group has been successfully created. The incarnation number is zero-based. If the group already exists, or if an error occurs during group creation, the createGroup method throws ActivationException.

The setSystem method sets the ActivationSystem, system, for the JVM. The activation system can only be set if no group is currently active. If the activation system is not set via an explicit call to setSystem, then the getSystem method will attempt to obtain a reference to the ActivationSystem by looking up the name java.rmi.activation.ActivationSystem in the Activator's registry. By default, the port number used to look up the activation system is defined by ActivationSystem.SYSTEM_PORT. This port can be overridden by setting the property java.rmi.activation.port. If the activation system is already set when setSystem is called, the method throws ActivationException.

The getSystem method returns the activation system for the JVM. The activation system may be set by the setSystem method (described above).

The activeObject method is a protected method used by subclasses to make the activeObject call back to the group's monitor to inform the monitor that the remote object with the specified activation id and whose stub is contained in mobj is now active. The call is simply forwarded to the group's ActivationMonitor.

The inactiveGroup method is a protected method used by subclasses to inform the group's monitor that the group has become inactive. A subclass makes this call when each object the group participated in activating in the JVM has become inactive.

7.4.9 The MarshalledObject Class

A MarshalledObject is a container for an object that allows that object to be passed as a parameter in an RMI call, but postpones deserializing the object at the receiver until the application explicitly requests the object (via a call to the container object). The Serializable object contained in the MarshalledObject is serialized and deserialized (when requested) with the same semantics as parameters passed in RMI calls, which means that any remote object in the MarshalledObject is represented by a serialized instance of its stub. The object contained by the MarshalledObject may be a remote object, a non-remote object, or an entire graph of remote and non-remote objects.

When an object is placed inside the MarshalledObject wrapper, the serialized form of the object is annotated with the codebase URL (where the class can be loaded); likewise, when the contained object is retrieved from its MarshalledObject wrapper, if the code for the object is not available locally, the URL (annotated during serialization) is used to locate and load the bytecodes for the object's class.

package java.rmi;
public final class MarshalledObject implements java.io.Serializable
{
        public MarshalledObject(Object obj)
                throws java.io.IOException;

        public Object get()
                throws java.io.IOException, ClassNotFoundException;

        public int hashCode();

        public boolean equals();
}
MarshalledObject's constructor takes a serializable object, obj, as its single argument and holds the marshalled representation of the object in a byte stream. The marshalled representation of the object preserves the semantics of objects that are passed in RMI calls:
  • each class in the stream is annotated with its codebase URL so that when the object is reconstructed (by a call to the get method), the bytecodes for each class can be located and loaded, and
  • remote objects are replaced with their proxy stubs.
When an instance of the class MarshalledObject is written to a java.io.ObjectOutputStream, the contained object's marshalled form (created during construction) is written to the stream; thus, only the byte stream is serialized.

When a MarshalledObject is read from a java.io.ObjectInputStream, the contained object is not deserialized into a concrete object; the object remains in its marshalled representation until the marshalled object's get method is called.

The get method always reconstructs a new copy of the contained object from its marshalled form. The internal representation is deserialized with the semantics used for unmarshalling parameters for RMI calls. So, the deserialization of the object's representation loads class code (if not available locally) using the URL annotation embedded in the serialized stream for the object.

The hashCode of the marshalled representation of the object is the same as the object passed to the constructor. The equals method will return true if the marshalled representation of the objects being compared are equivalent. The comparison that equals uses ignores a class's codebase annotation, meaning that two objects are equivalent if they have the same serialized representation except for the codebase of each class in the serialized representation.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 3 - RMI System Overview

CONTENTS | PREV | NEXT Java Remote Method Invocation

RMI System Overview

CHAPTER 3

Topics:

  • Stubs and Skeletons
  • Thread Usage in Remote Method Invocations
  • Garbage Collection of Remote Objects
  • Dynamic Class Loading
  • RMI Through Firewalls Via Proxies

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 3 - RMI System Overview

CONTENTS | PREV | NEXT Java Remote Method Invocation

3.1 Stubs and Skeletons

RMI uses a standard mechanism (employed in RPC systems) for communicating with remote objects: stubs and skeletons. A stub for a remote object acts as a client's local representative or proxy for the remote object. The caller invokes a method on the local stub which is responsible for carrying out the method call on the remote object. In RMI, a stub for a remote object implements the same set of remote interfaces that a remote object implements.

When a stub's method is invoked, it does the following:

  • initiates a connection with the remote JVM containing the remote object,
  • marshals (writes and transmits) the parameters to the remote JVM,
  • waits for the result of the method invocation,
  • unmarshals (reads) the return value or exception returned, and
  • returns the value to the caller.
The stub hides the serialization of parameters and the network-level communication in order to present a simple invocation mechanism to the caller.

In the remote JVM, each remote object may have a corresponding skeleton (in Java 2 platform-only environments, skeletons are not required). The skeleton is responsible for dispatching the call to the actual remote object implementation. When a skeleton receives an incoming method invocation it does the following:

  • unmarshals (reads) the parameters for the remote method,
  • invokes the method on the actual remote object implementation, and
  • marshals (writes and transmits) the result (return value or exception) to the caller.
In the Java 2 SDK, Standard Edition, v1.2 an additional stub protocol was introduced that eliminates the need for skeletons in Java 2 platform-only environments. Instead, generic code is used to carry out the duties performed by skeletons in JDK1.1. Stubs and skeletons are generated by the rmic compiler.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 3 - RMI System Overview

CONTENTS | PREV | NEXT Java Remote Method Invocation

3.2 Thread Usage in Remote Method Invocations

A method dispatched by the RMI runtime to a remote object implementation may or may not execute in a separate thread. The RMI runtime makes no guarantees with respect to mapping remote object invocations to threads. Since remote method invocation on the same remote object may execute concurrently, a remote object implementation needs to make sure its implementation is thread-safe.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 3 - RMI System Overview

CONTENTS | PREV | NEXT Java Remote Method Invocation

3.3 Garbage Collection of Remote Objects

In a distributed system, just as in the local system, it is desirable to automatically delete those remote objects that are no longer referenced by any client. This frees the programmer from needing to keep track of the remote objects' clients so that it can terminate appropriately. RMI uses a reference-counting garbage collection algorithm similar to Modula-3's Network Objects. (See "Network Objects" by Birrell, Nelson, and Owicki, Digital Equipment Corporation Systems Research Center Technical Report 115, 1994.)

To accomplish reference-counting garbage collection, the RMI runtime keeps track of all live references within each Java virtual machine. When a live reference enters a Java virtual machine, its reference count is incremented. The first reference to an object sends a "referenced" message to the server for the object. As live references are found to be unreferenced in the local virtual machine, the count is decremented. When the last reference has been discarded, an unreferenced message is sent to the server. Many subtleties exist in the protocol; most of these are related to maintaining the ordering of referenced and unreferenced messages in order to ensure that the object is not prematurely collected.

When a remote object is not referenced by any client, the RMI runtime refers to it using a weak reference. The weak reference allows the Java virtual machine's garbage collector to discard the object if no other local references to the object exist. The distributed garbage collection algorithm interacts with the local Java virtual machine's garbage collector in the usual ways by holding normal or weak references to objects.

As long as a local reference to a remote object exists, it cannot be garbage-collected and it can be passed in remote calls or returned to clients. Passing a remote object adds the identifier for the virtual machine to which it was passed to the referenced set. A remote object needing unreferenced notification must implement the java.rmi.server.Unreferenced interface. When those references no longer exist, the unreferenced method will be invoked. unreferenced is called when the set of references is found to be empty so it might be called more than once. Remote objects are only collected when no more references, either local or remote, still exist.

Note that if a network partition exists between a client and a remote server object, it is possible that premature collection of the remote object will occur (since the transport might believe that the client crashed). Because of the possibility of premature collection, remote references cannot guarantee referential integrity; in other words, it is always possible that a remote reference may in fact not refer to an existing object. An attempt to use such a reference will generate a RemoteException which must be handled by the application.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 3 - RMI System Overview

CONTENTS | PREV | NEXT Java Remote Method Invocation

3.4 Dynamic Class Loading

RMI allows parameters, return values and exceptions passed in RMI calls to be any object that is serializable. RMI uses the object serialization mechanism to transmit data from one virtual machine to another and also annotates the call stream with the appropriate location information so that the class definition files can be loaded at the receiver.

When parameters and return values for a remote method invocation are unmarshalled to become live objects in the receiving JVM, class definitions are required for all of the types of objects in the stream. The unmarshalling process first attempts to resolve classes by name in its local class loading context (the context class loader of the current thread). RMI also provides a facility for dynamically loading the class definitions for the actual types of objects passed as parameters and return values for remote method invocations from network locations specified by the transmitting endpoint. This includes the dynamic downloading of remote stub classes corresponding to particular remote object implementation classes (and used to contain remote references) as well as any other type that is passed by value in RMI calls, such as the subclass of a declared parameter type, that is not already available in the class loading context of the unmarshalling side.

To support dynamic class loading, the RMI runtime uses special subclasses of java.io.ObjectOutputStream and java.io.ObjectInputStream for the marshal streams that it uses for marshalling and unmarshalling RMI parameters and return values. These subclasses respectively override the annotateClass method of ObjectOutputStream and the resolveClass method of ObjectInputStream to communicate information about where to locate class files containing the definitions for classes corresponding to the class descriptors in the stream.

For every class descriptor written to an RMI marshal stream, the annotateClass method adds to the stream the result of calling java.rmi.server.RMIClassLoader.getClassAnnotation for the class object, which may be null or may be a String object representing the codebase URL path (a space-separated list of URLs) from which the remote endpoint should download the class definition file for the given class.

For every class descriptor read from an RMI marshal stream, the resolveClass method reads a single object from the stream. If the object is a String (and the value of the java.rmi.server.useCodebaseOnly property is not true), then resolveClass returns the result of calling RMIClassLoader.loadClass with the annotated String object as the first parameter and the name of the desired class in the class descriptor as the second parameter. Otherwise, resolveClass returns the result of calling RMIClassLoader.loadClass with the name of the desired class as the only parameter.

See the section "The RMIClassLoader Class" for more details about class loading in RMI.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 3 - RMI System Overview

CONTENTS | PREV | NEXT Java Remote Method Invocation

3.5 RMI Through Firewalls Via Proxies

The RMI transport layer normally attempts to open direct sockets to hosts on the Internet. Many intranets, however, have firewalls that do not allow this. The default RMI transport, therefore, provides two alternate HTTP-based mechanisms which enable a client behind a firewall to invoke a method on a remote object which resides outside the firewall.

As described in this section, the HTTP-based mechanism that the RMI transport layer uses for RMI calls only applies to firewalls with HTTP proxy servers.

3.5.1 How an RMI Call is Packaged within the HTTP Protocol

To get outside a firewall, the transport layer embeds an RMI call within the firewall-trusted HTTP protocol. The RMI call data is sent outside as the body of an HTTP POST request, and the return information is sent back in the body of the HTTP response. The transport layer will formulate the POST request in one of two ways:
  • If the firewall proxy will forward an HTTP request directed to an arbitrary port on the host machine, then it is forwarded directly to the port on which the RMI server is listening. The default RMI transport layer on the target machine is listening with a server socket that is capable of understanding and decoding RMI calls inside POST requests.
  • If the firewall proxy will only forward HTTP requests directed to certain well-known HTTP ports, then the call is forwarded to the HTTP server listening on port 80 of the host machine, and a CGI script is executed to forward the call to the target RMI server port on the same machine.

3.5.2 The Default Socket Factory

The RMI transport implementation includes an extension of the class java.rmi.server.RMISocketFactory, which is the default resource-provider for client and server sockets used to send and receive RMI calls; this default socket factory can be obtained via the java.rmi.server.RMISocketFactory.getDefaultSocketFactory method. This default socket factory creates sockets that transparently provide the firewall tunnelling mechanism as follows:
  • Client sockets first attempt a direct socket connection. Client sockets automatically attempt HTTP connections to hosts that cannot be contacted with a direct socket if that direct socket connection results in either a java.net.NoRouteToHostException or a java.net.UnknownHostException being thrown. If a direct socket connection results in any other java.io.IOException being thrown, such as a java.net.ConnectException, the implementation may attempt an HTTP connection.
  • Server sockets automatically detect if a newly-accepted connection is an HTTP POST request, and if so, return a socket that will expose only the body of the request to the transport and format its output as an HTTP response.
Client-side sockets, with this default behavior, are provided by the factory's java.rmi.server.RMISocketFactory.createSocket method. Server-side sockets with this default behavior are provided by the factory's java.rmi.server.RMISocketFactory.createServerSocket method.

3.5.3 Configuring the Client

A client can disable the packaging of RMI calls as HTTP requests by setting the java.rmi.server.disableHttp property to equal the boolean value true.

3.5.4 Configuring the Server

Note - The host name should not be specified as the host's IP address, because some firewall proxies will not forward to such a host name.
  1. In order for a client outside the server host's domain to be able to invoke methods on a server's remote objects, the client must be able to find the server. To do this, the remote references that the server exports must contain the fully-qualified name of the server host.

    Depending on the server's platform and network environment, this information may or may not be available to the Java virtual machine on which the server is running. If it is not available, the host's fully qualified name must be specified with the property java.rmi.server.hostname when starting the server.

    For example, use this command to start the RMI server class ServerImpl on the machine chatsubo.javasoft.com:

       java -Djava.rmi.server.hostname=chatsubo.javasoft.com ServerImpl
  2. If the server will not support RMI clients behind firewalls that can forward to arbitrary ports, use this configuration:
    1. An HTTP server is listening on port 80.
    2. A CGI script is located at the aliased URL path
          /cgi-bin/java-rmi.cgi
      This script:
      • Invokes the local interpreter for the Java programming language to execute a class internal to the transport layer which forwards the request to the appropriate RMI server port.
      • Defines properties in the Java virtual machine with the same names and values as the CGI 1.0 defined environment variables.
An example script is supplied in the RMI distribution for the Solaris and Windows 32 operating systems. Note that the script must specify the complete path to the interpreter for the Java programming language on the server machine.

3.5.5 Performance Issues and Limitations

Calls transmitted via HTTP requests are at least an order of magnitude slower that those sent through direct sockets, without taking proxy forwarding delays into consideration.

Because HTTP requests can only be initiated in one direction through a firewall, a client cannot export its own remote objects outside the firewall, because a host outside the firewall cannot initiate a method invocation back on the client.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 4 - Client Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

Client Interfaces

CHAPTER 4

When writing an applet or an application that uses remote objects, the programmer needs to be aware of the RMI system's client visible interfaces that are available in the java.rmi package.

Topics:

  • The Remote Interface
  • The RemoteException Class
  • The Naming Class

CONTENTS | PREV | NEXT
Copyright 1997,2006, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 4 - Client Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

4.1 The Remote Interface

See the Remote API documentation, and for more details on how to define a remote interface see the section "The java.rmi.Remote Interface".

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 4 - Client Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

4.2 The RemoteException Class

See the RemoteException API documentation.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 4 - Client Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

4.3 The Naming Class

See the Naming API documentation.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 9 - Garbage Collector Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

Garbage Collector Interfaces

CHAPTER 9

The interfaces and classes in this chapter are used by the distributed garbage collector (DGC) for RMI.

Topics:

  • The DGC Interface
  • The Lease Class
  • The ObjID Class
  • The UID Class
  • The VMID Class

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 9 - Garbage Collector Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

9.1 The DGC Interface

See the DGC API documentation.

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 9 - Garbage Collector Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

9.2 The Lease Class

See the Lease API documentation.

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 9 - Garbage Collector Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

9.3 The ObjID Class

See the ObjID API documentation.

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 9 - Garbage Collector Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

9.4 The UID Class

See the UID API documentation.

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 9 - Garbage Collector Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

9.5 The VMID Class

See the VMID API documentation.

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: - Exceptions In RMI

CONTENTS | PREV | NEXT Java Remote Method Invocation

Exceptions In RMI

APPENDIX A

Topics:

  • Exceptions During Remote Object Export
  • Exceptions During RMI Call
  • Exceptions or Errors During Return
  • Naming Exceptions
  • Activation Exceptions
  • Other Exceptions

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: - Exceptions In RMI

CONTENTS | PREV | NEXT Java Remote Method Invocation

A.1 Exceptions During Remote Object Export

When a remote object class is created that extends UnicastRemoteObject, the object is exported, meaning it can receive calls from external Java virtual machines and can be passed in an RMI call as either a parameter or return value. An object can either be exported on an anonymous port or on a specified port. For objects not extended from UnicastRemoteObject, the java.rmi.server.UnicastRemoteObject.exportObject method is used to explicitly export the object.
Exception
 Context

java.rmi.StubNotFoundException

Class of stub not found.

Name collision with class of same name as stub causes one of these errors:

  • Stub can't be instantiated
  • Stub not of correct class

Bad URL due to wrong codebase.

Stub not of correct class.

java.rmi.server.SkeletonNotFoundException

note: this exception is deprecated as of Java 2 SDK, Standard Edition, v1.2

Class of skeleton not found.

Name collision with class of same name as skeleton causes one of these errors:

  • Skeleton can't be instantiated
  • Skeleton not of correct class

Bad URL due to wrong codebase.

Skeleton not of correct class.

java.rmi.server.ExportException

The port is in use by another VM.

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: - Exceptions In RMI

CONTENTS | PREV | NEXT Java Remote Method Invocation

A.2 Exceptions During RMI Call

Exception | Context
java.rmi.UnknownHostException | Unknown host.
java.rmi.ConnectException | Connection refused to host.
java.rmi.ConnectIOException | I/O error creating connection.
java.rmi.MarshalException | I/O error marshaling transport header, marshaling call header, or marshaling arguments.
java.rmi.NoSuchObjectException | Attempt to invoke a method on an object that is no longer available.
java.rmi.StubNotFoundException | Remote object not exported.
java.rmi.activation.ActivateFailedException | Thrown by RMI runtime when activation fails during a remote call to an activatable object

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: - Exceptions In RMI

CONTENTS | PREV | NEXT Java Remote Method Invocation

A.3 Exceptions or Errors During Return

Exception
 Context

java.rmi.UnmarshalException

Corrupted stream leads to either an I/O or protocol error when:

  • Marshaling return header
  • Checking return type
  • Checking return code
  • Unmarshaling return

Return value class not found.

java.rmi.UnexpectedException

An exception not mentioned in the method signature occurred (excluding runtime exceptions). The UnexpectedException exception object contains the underlying exception that was thrown by the server.

java.rmi.ServerError

Any error that occurs while the server is executing a remote method. The ServerError exception object contains the underlying error that was thrown by the server,

java.rmi.ServerException

This exception is thrown as a result of a remote method invocation when a RemoteException is thrown while processing the invocation on the server, either while unmarshalling the arguments or executing the remote method itself. For examples, see Section A.3.1, "Possible Causes of java.rmi.ServerException".

java.rmi.ServerRuntimeException

note: this exception is deprecated as of Java 2 SDK, Standard Edition, v1.2

This exception is not thrown by servers running Java 2 SDK, Standard Edition, v1.2-compatible versions. A RuntimeException is propagated to clients intact.

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: - Exceptions In RMI

CONTENTS | PREV | NEXT Java Remote Method Invocation

A.3.1 Possible Causes of java.rmi.ServerException

These are some of the underlying exceptions which can occur on the server when the server is itself executing a remote method invocation. These exceptions are wrapped in a java.rmi.ServerException; that is the java.rmi.ServerException contains the original exception for the client to extract. These exceptions are wrapped by ServerException so that the client will know that its own remote method invocation on the server did not fail, but that a secondary remote method invocation made by the server failed.

Exception | Context
java.rmi.server.SkeletonMismatchException note: this exception is deprecated as of the Java 2 SDK, Standard Edition, v1.2 | Hash mismatch of stub and skeleton.
java.rmi.UnmarshalException | I/O error unmarshaling call header. I/O error unmarshaling arguments. Invalid method number or method hash.
java.rmi.MarshalException | Protocol error marshaling return.
java.rmi.RemoteException | A RemoteException occurring as a result of a remote invocation by the server.

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: - Exceptions In RMI

CONTENTS | PREV | NEXT Java Remote Method Invocation

A.4 Naming Exceptions

The following table lists the exceptions specified in methods of the java.rmi.Naming class and the java.rmi.registry.Registry interface.

Exception | Context
java.rmi.AccessException | Operation disallowed. The registry restricts bind, rebind, and unbind to the same host. The lookup operation can originate from any host.
java.rmi.AlreadyBoundException | Attempt to bind a name that is already bound.
java.rmi.NotBoundException | Attempt to look up a name that is not bound.
java.rmi.UnknownHostException | Attempt to contact a registry on an unknown host.

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: - Exceptions In RMI

CONTENTS | PREV | NEXT Java Remote Method Invocation

A.5 Activation Exceptions

The following table lists the exceptions that can be thrown in activities involving activatable objects. The activation API is in the package java.rmi.activation.
Exception | Context
java.rmi.activation.ActivateFailedException | Thrown by RMI runtime when activation fails during a remote call to an activatable object.
java.rmi.activation.ActivationException | General exception class used by the activation interfaces and classes.
java.rmi.activation.UnknownGroupException | Thrown by methods of the activation classes and interfaces when the ActivationGroupID parameter or ActivationGroupID in an ActivationGroupDesc parameter is invalid.
java.rmi.activation.UnknownObjectException | Thrown by methods of the activation classes and interfaces when the ActivationID parameter is invalid.

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: - Exceptions In RMI

CONTENTS | PREV | NEXT Java Remote Method Invocation

A.6 Other Exceptions

Exception | Context
java.rmi.RMISecurityException note: this exception is deprecated as of the Java 2 SDK, Standard Edition, v1.2 | A security exception that is thrown by the RMISecurityManager.
java.rmi.server.ServerCloneException | Clone failed.
java.rmi.server.ServerNotActiveException | Attempt to get the client host via the RemoteServer.getClientHost method when the remote server is not executing in a remote method.
java.rmi.server.SocketSecurityException | Attempt to export object on an illegal port.

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 1 - Introduction

CONTENTS | PREV | NEXT Java Remote Method Invocation

Introduction

CHAPTER 1

Topics:

  • Background
  • System Goals

CONTENTS | PREV | NEXT

Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 1 - Introduction

CONTENTS | PREV | NEXT Java Remote Method Invocation

1.1 Background

Distributed systems require that computations running in different address spaces, potentially on different hosts, be able to communicate. For a basic communication mechanism, the JavaTM programming language supports sockets, which are flexible and sufficient for general communication. However, sockets require the client and server to engage in applications-level protocols to encode and decode messages for exchange, and the design of such protocols is cumbersome and can be error-prone.

An alternative to sockets is Remote Procedure Call (RPC), which abstracts the communication interface to the level of a procedure call. Instead of working directly with sockets, the programmer has the illusion of calling a local procedure, when in fact the arguments of the call are packaged up and shipped off to the remote target of the call. RPC systems encode arguments and return values using an external data representation, such as XDR.

RPC, however, does not translate well into distributed object systems, where communication between program-level objects residing in different address spaces is needed. In order to match the semantics of object invocation, distributed object systems require remote method invocation or RMI. In such systems, a local surrogate (stub) object manages the invocation on a remote object.

The Java platform's remote method invocation system described in this specification has been specifically designed to operate in the Java application environment. The Java programming language's RMI system assumes the homogeneous environment of the Java virtual machine (JVM), and the system can therefore take advantage of the Java platform's object model whenever possible.

CONTENTS | PREV | NEXT

Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 1 - Introduction

CONTENTS | PREV | NEXT Java Remote Method Invocation

1.2 System Goals

The goals for supporting distributed objects in the Java programming language are:

  • Support seamless remote invocation on objects in different virtual machines
  • Support callbacks from servers to applets
  • Integrate the distributed object model into the Java programming language in a natural way while retaining most of the Java programming language's object semantics
  • Make differences between the distributed object model and local Java platform's object model apparent
  • Make writing reliable distributed applications as simple as possible
  • Preserve the type-safety provided by the Java platform's runtime environment
  • Support various reference semantics for remote objects; for example live (nonpersistent) references, persistent references, and lazy activation
  • Maintain the safe environment of the Java platform provided by security managers and class loaders

Underlying all these goals is a general requirement that the RMI model be both simple (easy to use) and natural (fits well in the language).

The first two chapters in this specification describe the distributed object model for the Java programming language and the system overview. The remaining chapters describe the RMI client and server visible APIs which are part of the Java SE platform.

CONTENTS | PREV | NEXT

Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 2 - Distributed Object Model

CONTENTS | PREV | NEXT Java Remote Method Invocation

Distributed Object Model

CHAPTER 2

Topics:

  • Distributed Object Applications
  • Definition of Terms
  • The Distributed and Nondistributed Models Contrasted
  • Overview of RMI Interfaces and Classes
  • Implementing a Remote Interface
  • Parameter Passing in Remote Method Invocation
  • Locating Remote Objects

CONTENTS | PREV | NEXT

Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 2 - Distributed Object Model

CONTENTS | PREV | NEXT Java Remote Method Invocation

2.1 Distributed Object Applications

RMI applications are often comprised of two separate programs: a server and a client. A typical server application creates a number of remote objects, makes references to those remote objects accessible, and waits for clients to invoke methods on those remote objects. A typical client application gets a remote reference to one or more remote objects in the server and then invokes methods on them. RMI provides the mechanism by which the server and the client communicate and pass information back and forth. Such an application is sometimes referred to as a distributed object application.

Distributed object applications need to:

  • Locate remote objects

    Applications can use one of two mechanisms to obtain references to remote objects. An application can register its remote objects with RMI's simple naming facility, the rmiregistry, or the application can pass and return remote object references as part of its normal operation.

  • Communicate with remote objects

    Details of communication between remote objects are handled by RMI; to the programmer, remote communication looks like a standard method invocation.

  • Load class bytecodes for objects that are passed as parameters or return values

    Because RMI allows a caller to pass objects to remote objects, RMI provides the necessary mechanisms for loading an object's code as well as transmitting its data.

The illustration below depicts an RMI distributed application that uses the registry to obtain references to a remote object. The server calls the registry to associate a name with a remote object. The client looks up the remote object by its name in the server's registry and then invokes a method on it. The illustration also shows that the RMI system uses an existing web server to load bytecodes of classes written in the Java programming language, from server to client and from client to server, for objects when needed. RMI can load class bytecodes using any URL protocol (e.g., HTTP, FTP, file, etc.) that is supported by the Java platform.
This illustration depicts an RMI distributed application that uses the registry to obtain references to a remote object.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 2 - Distributed Object Model

CONTENTS | PREV | NEXT Java Remote Method Invocation

2.2 Definition of Terms

In the Java SE platform's distributed object model, a remote object is one whose methods can be invoked from another Java virtual machine, potentially on a different host. An object of this type is described by one or more remote interfaces, which are interfaces written in the Java programming language that declare the methods of the remote object.

Remote method invocation (RMI) is the action of invoking a method of a remote interface on a remote object. Most importantly, a method invocation on a remote object has the same syntax as a method invocation on a local object.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 2 - Distributed Object Model

CONTENTS | PREV | NEXT Java Remote Method Invocation

2.3 The Distributed and Nondistributed Models Contrasted

The Java SE platform's distributed object model is similar to the Java SE platform's object model in the following ways:

  • A reference to a remote object can be passed as an argument or returned as a result in any method invocation (local or remote).
  • A remote object can be cast to any of the set of remote interfaces supported by the implementation using the syntax for casting built into the Java programming language.
  • The built-in instanceof operator can be used to test the remote interfaces supported by a remote object.
The Java SE platform's distributed object model differs from the Java SE platform's object model in these ways:

  • Clients of remote objects interact with remote interfaces, never with the implementation classes of those interfaces.
  • Non-remote arguments to, and results from, a remote method invocation are passed by copy rather than by reference. This is because references to objects are only useful within a single virtual machine.
  • A remote object is passed by reference, not by copying the actual remote implementation.
  • The semantics of some of the methods defined by class java.lang.Object are specialized for remote objects.
  • Since the failure modes of invoking remote objects are inherently more complicated than the failure modes of invoking local objects, clients must deal with additional exceptions that can occur during a remote method invocation.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 2 - Distributed Object Model

CONTENTS | PREV | NEXT Java Remote Method Invocation

2.4 Overview of RMI Interfaces and Classes

The interfaces and classes that are responsible for specifying the remote behavior of the RMI system are defined in the java.rmi package hierarchy. The following figure shows the relationship between several of these interfaces and classes:
relationship between several of these interfaces and classes

2.4.1 The java.rmi.Remote Interface

In RMI, a remote interface is an interface that declares a set of methods that may be invoked from a remote Java virtual machine. A remote interface must satisfy the following requirements:
  • A remote interface must at least extend, either directly or indirectly, the interface java.rmi.Remote.
  • Each method declaration in a remote interface or its super-interfaces must satisfy the requirements of a remote method declaration as follows:
    • A remote method declaration must include the exception java.rmi.RemoteException (or one of its superclasses such as java.io.IOException or java.lang.Exception) in its throws clause, in addition to any application-specific exceptions (note that application specific exceptions do not have to extend java.rmi.RemoteException).
    • In a remote method declaration, a remote object declared as a parameter or return value (either declared directly in the parameter list or embedded within a non-remote object in a parameter) must be declared as the remote interface, not the implementation class of that interface.
The interface java.rmi.Remote is a marker interface that defines no methods:
    public interface Remote {}
A remote interface must at least extend the interface java.rmi.Remote (or another remote interface that extends java.rmi.Remote). However, a remote interface may extend a non-remote interface under the following condition:
  • A remote interface may also extend another non-remote interface, as long as all of the methods (if any) of the extended interface satisfy the requirements of a remote method declaration.
For example, the following interface BankAccount defines a remote interface for accessing a bank account. It contains remote methods to deposit to the account, to get the account balance, and to withdraw from the account:
    public interface BankAccount extends java.rmi.Remote {
        public void deposit(float amount)
                throws java.rmi.RemoteException;
        public void withdraw(float amount)
                throws OverdrawnException, java.rmi.RemoteException;
        public float getBalance()
                throws java.rmi.RemoteException;
}
The next example shows a valid remote interface Beta that extends a non-remote interface Alpha, which has remote methods, and the interface java.rmi.Remote:
    public interface Alpha {
        public final String okay = "constants are okay too";
        public Object foo(Object obj)
                throws java.rmi.RemoteException;
        public void bar() throws java.io.IOException;
        public int baz() throws java.lang.Exception;
}

public interface Beta extends Alpha, java.rmi.Remote {
        public void ping() throws java.rmi.RemoteException;
}

2.4.2 The RemoteException Class

The java.rmi.RemoteException class is the superclass of exceptions thrown by the RMI runtime during a remote method invocation. To ensure the robustness of applications using the RMI system, each remote method declared in a remote interface must specify java.rmi.RemoteException (or one of its superclasses such as java.io.IOException or java.lang.Exception) in its throws clause.

The exception java.rmi.RemoteException is thrown when a remote method invocation fails for some reason. Some reasons for remote method invocation failure include:

  • Communication failure (the remote server is unreachable or is refusing connections; the connection is closed by the server, etc.)
  • Failure during parameter or return value marshalling or unmarshalling
  • Protocol errors
The class RemoteException is a checked exception (one that must be handled by the caller of a remote method and is checked by the compiler), not a RuntimeException.

2.4.3 The RemoteObject Class and its Subclasses

RMI server functions are provided by java.rmi.server.RemoteObject and its subclasses, java.rmi.server.RemoteServer and java.rmi.server.UnicastRemoteObject and java.rmi.activation.Activatable.
  • The class java.rmi.server.RemoteObject provides implementations for the java.lang.Object methods, hashCode, equals, and toString that are sensible for remote objects.
  • The methods needed to create remote objects and export them (make them available to remote clients) are provided by the classes UnicastRemoteObject and Activatable. The subclass identifies the semantics of the remote reference, for example whether the server is a simple remote object or is an activatable remote object (one that executes when invoked).
  • The java.rmi.server.UnicastRemoteObject class defines a singleton (unicast) remote object whose references are valid only while the server process is alive.
  • The class java.rmi.activation.Activatable is an abstract class that defines an activatable remote object that starts executing when its remote methods are invoked and can shut itself down when necessary.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 2 - Distributed Object Model

CONTENTS | PREV | NEXT Java Remote Method Invocation

2.5 Implementing a Remote Interface

The general rules for a class that implements a remote interface are as follows:
  • The class usually extends java.rmi.server.UnicastRemoteObject, thereby inheriting the remote behavior provided by the classes java.rmi.server.RemoteObject and java.rmi.server.RemoteServer.
  • The class can implement any number of remote interfaces.
  • The class can extend another remote implementation class.
  • The class can define methods that do not appear in the remote interface, but those methods can only be used locally and are not available remotely.
For example, the following class BankAcctImpl implements the BankAccount remote interface and extends the java.rmi.server.UnicastRemoteObject class:
package mypackage;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class BankAccountImpl
        extends UnicastRemoteObject
        implements BankAccount
{
        private float balance = 0.0;

        public BankAccountImpl(float initialBalance)
                throws RemoteException
        {
                balance = initialBalance;
        }
        public void deposit(float amount) throws RemoteException {
                ...
        }
        public void withdraw(float amount) throws OverdrawnException,
                RemoteException {
                ...
        }
        public float getBalance() throws RemoteException {
                ...
        }
}
Note that if necessary, a class that implements a remote interface can extend some other class besides java.rmi.server.UnicastRemoteObject. However, the implementation class must then assume the responsibility for exporting the object (taken care of by the UnicastRemoteObject constructor) and for implementing (if needed) the correct remote semantics of the hashCode, equals, and toString methods inherited from the java.lang.Object class.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 2 - Distributed Object Model

CONTENTS | PREV | NEXT Java Remote Method Invocation

2.6 Parameter Passing in Remote Method Invocation

An argument to, or a return value from, a remote object can be any object that is serializable. This includes primitive types, remote objects, and non-remote objects that implement the java.io.Serializable interface. For more details on how to make classes serializable, see the "Java Object Serialization Specification." Classes, for parameters or return values, that are not available locally are downloaded dynamically by the RMI system. See the section on "Dynamic Class Loading" for more information on how RMI downloads parameter and return value classes when reading parameters, return values and exceptions.

2.6.1 Passing Non-remote Objects

A non-remote object, that is passed as a parameter of a remote method invocation or returned as a result of a remote method invocation, is passed by copy; that is, the object is serialized using the object serialization mechanism of the Java SE platform.

So, when a non-remote object is passed as an argument or return value in a remote method invocation, the content of the non-remote object is copied before invoking the call on the remote object.

When a non-remote object is returned from a remote method invocation, a new object is created in the calling virtual machine.

2.6.2 Passing Remote Objects

When passing an exported remote object as a parameter or return value in a remote method call, the stub for that remote object is passed instead. Remote objects that are not exported will not be replaced with a stub instance. A remote object passed as a parameter can only implement remote interfaces.

2.6.3 Referential Integrity

If two references to an object are passed from one JVM to another JVM in parameters (or in the return value) in a single remote method call and those references refer to the same object in the sending JVM, those references will refer to a single copy of the object in the receiving JVM. More generally stated: within a single remote method call, the RMI system maintains referential integrity among the objects passed as parameters or as a return value in the call.

2.6.4 Class Annotation

When an object is sent from one JVM to another in a remote method call, the RMI system annotates the class descriptor in the call stream with information (the URL) of the class so that the class can be loaded at the receiver. It is a requirement that classes be downloaded on demand during remote method invocation.

2.6.5 Parameter Transmission

Parameters in an RMI call are written to a stream that is a subclass of the class java.io.ObjectOutputStream in order to serialize the parameters to the destination of the remote call. The ObjectOutputStream subclass overrides the replaceObject method to replace each exported remote object with its corresponding stub instance. Parameters that are objects are written to the stream using the ObjectOutputStream's writeObject method. The ObjectOutputStream calls the replaceObject method for each object written to the stream via the writeObject method (that includes objects referenced by those objects that are written). The replaceObject method of RMI's subclass of ObjectOutputStream returns the following:
  • If the object passed to replaceObject is an instance of java.rmi.Remote and that object is exported to the RMI runtime, then it returns the stub for the remote object. If the object is an instance of java.rmi.Remote and the object is not exported to the RMI runtime, then replaceObject returns the object itself. A stub for a remote object is obtained via a call to the method java.rmi.server.RemoteObject.toStub.
  • If the object passed to replaceObject is not an instance of java.rmi.Remote, then the object is simply returned.
RMI's subclass of ObjectOutputStream also implements the annotateClass method that annotates the call stream with the location of the class so that it can be downloaded at the receiver. See the section "Dynamic Class Loading" for more information on how annotateClass is used.

Since parameters are written to a single ObjectOutputStream, references that refer to the same object at the caller will refer to the same copy of the object at the receiver. At the receiver, parameters are read by a single ObjectInputStream.

Any other default behavior of ObjectOutputStream for writing objects (and similarly ObjectInputStream for reading objects) is maintained in parameter passing. For example, the calling of writeReplace when writing objects and readResolve when reading objects is honored by RMI's parameter marshal and unmarshal streams.

In a similar manner to parameter passing in RMI as described above, a return value (or exception) is written to a subclass of ObjectOutputStream and has the same replacement behavior as parameter transmission.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 2 - Distributed Object Model

CONTENTS | PREV | NEXT Java Remote Method Invocation

2.7 Locating Remote Objects

A simple bootstrap name server is provided for storing named references to remote objects. A remote object reference can be stored using the URL-based methods of the class java.rmi.Naming.

For a client to invoke a method on a remote object, that client must first obtain a reference to the object. A reference to a remote object is usually obtained as a parameter or return value in a method call. The RMI system provides a simple bootstrap name server from which to obtain remote objects on given hosts. The java.rmi.Naming class provides Uniform Resource Locator (URL) based methods to look up, bind, rebind, unbind, and list the name-object pairings maintained on a particular host and port.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: - Properties In RMI

CONTENTS | PREV | NEXT Java Remote Method Invocation

Properties In RMI

APPENDIX B

Topics:

  • Server Properties
  • Activation Properties
  • Other Properties

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: - Properties In RMI

CONTENTS | PREV | NEXT Java Remote Method Invocation

B.1 Server Properties

The following table contains a list of properties typically used by servers for configuration. Note that properties are typically restricted from being set from applets.
Property | Description
java.rmi.server.codebase | Indicates the codebase URL of classes originating from the JVM. The codebase property is used to annotate class descriptors of classes originating from a JVM so that the class for an object sent as a parameter or return value in a remote method call can be loaded at the receiver.
java.rmi.server.disableHttp | If set to true, disables the use of HTTP for RMI calls. This means that RMI will never resort to using HTTP to invoke a call via a firewall. Defaults to false (HTTP usage is enabled).
java.rmi.server.hostname | RMI uses IP addresses to indicate the location of a server (embedded in a remote reference). If the use of a hostname is desired, this property is used to specify the fully-qualified hostname for RMI to use for remote objects exported to the local JVM. The property can also be set to an IP address. Not set by default.
java.rmi.dgc.leaseValue | Sets the lease duration that the RMI runtime grants to clients referencing remote objects in the JVM. Defaults to 10 minutes.
java.rmi.server.logCalls | If set to true, server call logging is turned on and prints to stderr. Defaults to false.
java.rmi.server.useCodebaseOnly | If set to true, when RMI loads classes (if not available via CLASSPATH) they are only loaded using the URL specified by the property java.rmi.server.codebase.
java.rmi.server.useLocalHostname | If the java.rmi.server.hostname property is not set and this property is set, then RMI will not use an IP address to denote the location (embedded in remote references) of remote objects that are exported into the JVM. Instead, RMI will use the value of the call to the method java.net.InetAddress.getLocalHost.

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


ava Remote Method Invocation: - Properties In RMI

CONTENTS | PREV | NEXT Java Remote Method Invocation

B.2 Activation Properties

The following table contains a list of properties used in activation.
Property | Description
java.rmi.activation.port | The port number on which the ActivationSystem is exported. This port number should be specified in a JVM if the activation daemon rmid uses a port other than the default.
java.rmi.activation.activator.class | The class that implements the interface java.rmi.activation.Activator. This property is used internally to locate the resident implementation of the Activator from which the stub class name can be found.

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: - Properties In RMI

CONTENTS | PREV Java Remote Method Invocation

B.3 Other Properties

These properties are used to locate specific implementation classes within implementation packages. Note: all these properties have been deprecated as of Java 2 SDK, Standard Edition, v1.2.
Property | Description
java.rmi.loader.packagePrefix note: this exception is deprecated as of Java 2 SDK, Standard Edition, v1.2 | The package prefix for the class that implements the interface java.rmi.server.LoaderHandler. Defaults to sun.rmi.server.
java.rmi.registry.packagePrefix note: this exception is deprecated as of Java 2 SDK, Standard Edition, v1.2 | The package prefix for the class that implements the interface java.rmi.registry.RegistryHandler. Defaults to sun.rmi.registry.
java.rmi.server.packagePrefix note: this exception is deprecated as of Java 2 SDK, Standard Edition, v1.2 | The server package prefix. Assumes that the implementation of the server reference classes (such as UnicastRef and UnicastServerRef) are located in the package defined by the prefix. Defaults to sun.rmi.server.

CONTENTS | PREV
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 10 - RMI Wire Protocol

CONTENTS | PREV | NEXT Java Remote Method Invocation

RMI Wire Protocol

CHAPTER 10

Topics:

  • Overview
  • RMI Transport Protocol
  • RMI's Use of Object Serialization Protocol
  • RMI's Use of HTTP POST Protocol
  • Application-Specific Values for RMI
  • RMI's Multiplexing Protocol

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 10 - RMI Wire Protocol

CONTENTS | PREV | NEXT Java Remote Method Invocation

10.1 Overview

The RMI protocol makes use of two other protocols for its on-the-wire format: Java Object Serialization and HTTP. The Object Serialization protocol is used to marshal call and return data. The HTTP protocol is used to "POST" a remote method invocation and obtain return data when circumstances warrant. Each protocol is documented as a separate grammar. Nonterminal symbols in production rules may refer to rules governed by another protocol (either Object Serialization or HTTP). When a protocol boundary is crossed, subsequent productions use that embedded protocol.

Notes about Grammar Notation

  • We use a similar notation to that used in The Java Language Specification.
  • Control codes in the stream are represented by literal values expressed in hexadecimal.
  • Some nonterminal symbols in the grammar represent application specific values supplied in a method invocation. The definition of such a nonterminal consists of its Java programming language type. A table mapping each of these nonterminals to its respective type follows the grammar.

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 10 - RMI Wire Protocol

CONTENTS | PREV | NEXT Java Remote Method Invocation

10.2 RMI Transport Protocol

The wire format for RMI is represented by a Stream. The terminology adopted here reflects a client perspective. Out refers to output messages and In refers to input messages. The contents of the transport header are not formatted using object serialization.
Stream:
Out

In

The input and output streams used by RMI are paired. Each Out stream has a corresponding In stream. An Out stream in the grammar maps to the output stream of a socket (from the client's perspective). An In stream (in the grammar) is paired with the corresponding socket's input stream. Since output and input streams are paired, the only header information needed on an input stream is an acknowledgment as to whether the protocol is understood; other header information (such as the magic number and version number) can be implied by the context of stream pairing.

10.2.1 Format of an Output Stream

An output stream in RMI consists of transport Header information followed by a sequence of Messages. Alternatively, an output stream can contain an invocation embedded in the HTTP protocol.

Out:

Header Messages
HttpMessage

Header:

0x4a 0x52 0x4d 0x49 Version Protocol

Version:

0x00 0x01

Protocol:

StreamProtocol
SingleOpProtocol
MultiplexProtocol

StreamProtocol:

0x4b

SingleOpProtocol:

0x4c

MultiplexProtocol:

0x4d

Messages:

Message
Messages Message

The Messages are wrapped within a particular protocol as specified by Protocol. For the SingleOpProtocol, there may only be one Message after the Header, and there is no additional data that the Message is wrapped in. The SingleOpProtocol is used for invocation embedded in HTTP requests, where interaction beyond a single request and response is not possible.

For the StreamProtocol and the MultiplexProtocol, the server must respond with a a byte 0x4e acknowledging support for the protocol, and an EndpointIdentifier that contains the host name and port number that the server can see is being used by the client. The client can use this information to determine its host name if it is otherwise unable to do that for security reasons. The client must then respond with another EndpointIdentifier that contains the client's default endpoint for accepting connections. This can be used by a server in the MultiplexProtocol case to identify the client.

For the StreamProtocol, after this endpoint negotiation, the Messages are sent over the output stream without any additional wrapping of the data. For the MultiplexProtocol, the socket connection is used as the concrete connection for a multiplexed connection, as described in Section 10.6, "RMI's Multiplexing Protocol." Virtual connections initiated over this multiplexed connection consist of a series of Messages as described below.

There are three types of output messages: Call, Ping and DgcAck. A Call encodes a method invocation. A Ping is a transport-level message for testing liveness of a remote virtual machine. A DGCAck is an acknowledgment directed to a server's distributed garbage collector that indicates that remote objects in a return value from a server have been received by the client.

Message:

Call
Ping
DgcAck

Call:

0x50 CallData

Ping:

0x52

DgcAck:

0x54 UniqueIdentifier

10.2.2 Format of an Input Stream

There are currently three types of input messages: ReturnData, HttpReturn and PingAck. ReturnData is the result of a "normal" RMI call. An HttpReturn is a return result from an invocation embedded in the HTTP protocol. A PingAck is the acknowledgment for a Ping message.

In:

ProtocolAck Returns
ProtocolNotSupported
HttpReturn

ProtocolAck:

0x4e

ProtocolNotSupported:

0x4f

Returns:

Return
Returns Return

Return:

ReturnData
PingAck

ReturnData:

0x51 ReturnValue

PingAck:

0x53

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 10 - RMI Wire Protocol

CONTENTS | PREV | NEXT Java Remote Method Invocation

10.3 RMI's Use of Object Serialization

Call and return data in RMI calls are formatted using the Java Object Serialization protocol. Each method invocation's CallData is written to a Java object output stream that contains the ObjectIdentifier (the target of the call), an Operation (a number representing the method to be invoked), a Hash (a number that verifies that client stub and remote object skeleton use the same stub protocol), followed by a list of zero or more Arguments for the call.

In the JDK1.1 stub protocol the Operation represents the method number as assigned by rmic, and the Hash was the stub/skeleton hash which is the stub's interface hash. As of the Java 2 stub protocol (Java 2 stubs are generated using the -v1.2 option with rmic), Operation has the value -1 and the Hash is a hash representing the method to call. The hash is described in the section "The RemoteRef Interface".

CallData:

ObjectIdentifier Operation Hash Argumentsopt

ObjectIdentifier:

ObjectNumber UniqueIdentifier

UniqueIdentifier:

Number Time Count

Arguments:

Value

Arguments Value

Value:

Object

Primitive

A ReturnValue of an RMI call consists of a return code to indicate either a normal or exceptional return, a UniqueIdentifier to tag the return value (used to send a DGCAck if necessary) followed by the return result: either the Value returned or the Exception thrown.

ReturnValue:

0x01 UniqueIdentifier Valueopt

0x02 UniqueIdentifier Exception
Note - ObjectIdentifier, UniqueIdentifier, and EndpointIdentifier are not written out using default serialization, but each uses its own special write method (this is not the writeObject method used by object serialization); the write method for each type of identifier adds its component data consecutively to the output stream.

10.3.1 Class Annotation and Class Loading

RMI overrides the annotateClass and resolveClass methods of ObjectOutputStream and ObjectInputStream respectively. Each class is annotated with the codebase URL (the location from which the class can be loaded). In the annotateClass method, the classloader that loaded the class is queried for its codebase URL. If the classloader is non-null and the classloader has a non-null codebase, then the codebase is written to the stream using the ObjectOutputStream.writeObject method; otherwise a null is written to the stream using the writeObject method. Note: as an optimization, classes in the "java" package are not annotated, since they are always available to the receiver.

The class annotation is resolved during deserialization using the ObjectInputStream.resolveClass method. The resolveClass method first reads the annotation via the ObjectInputStream.readObject method. If the annotation, a codebase URL, is non-null, then it obtains the classloader for that URL and attempts to load the class. The class is loaded by using a java.net.URLConnection to fetch the class bytes (the same mechanism used by a web browser's applet classloader).

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 10 - RMI Wire Protocol

CONTENTS | PREV | NEXT Java Remote Method Invocation

10.4 RMI's Use of HTTP POST Protocol

In order to invoke remote methods through a firewall, some RMI calls make use of the HTTP protocol, more specifically HTTP POST. The URL specified in the post header can be one of the following:

http://<host>:<port>/
http://<host>:80/cgi-bin/java-rmi?forward=<port>

The first URL is used for direct communication with an RMI server on the specific host and port. The second URL form is used to invoke a "cgi" script on the server which forwards the invocation to the server on the specified port.

An HttpPostHeader is a standard HTTP header for a POST request. An HttpResponseHeader is a standard HTTP response to a post. If the response status code is not 200, then it is assumed that there is no Return. Note that only a single RMI call is embedded in an HTTP POST request.

HttpMessage:

HttpPostHeader Header Message

HttpReturn:

HttpResponseHeader Return
Note - Only the SingleOpProtocol appears in the Header of an HttpMessage. An HttpReturn does not contain a protocol acknowledgment byte.

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 10 - RMI Wire Protocol

CONTENTS | PREV | NEXT Java Remote Method Invocation

10.5 Application-Specific Values for RMI

This table lists the nonterminal symbols that represent application-specific values used by RMI. The table maps each symbol to its respective type. Each is formatted using the protocol in which it is embedded.

Symbol | type
Count | short
Exception | java.lang.Exception
Hash | long
Hostname | UTF
Number | int
Object | java.lang.Object
ObjectNumber | long
Operation | int
PortNumber | int
Primitive | byte, int, short, long...
Time | long

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 10 - RMI Wire Protocol

CONTENTS | PREV | NEXT Java Remote Method Invocation

10.6 RMI's Multiplexing Protocol

The purpose of multiplexing is to provide a model where two endpoints can each open multiple full duplex connections to the other endpoint in an environment where only one of the endpoints is able to open such a bidirectional connection using some other facility (e.g., a TCP connection). RMI use this simple multiplexing protocol to allow a client to connect to an RMI server object in some situations where that is otherwise not possible. For example, some security managers for applet environments disallow the creation of server sockets to listen for incoming connections, thereby preventing such applets to export RMI objects and service remote calls from direct socket connections. If the applet can open a normal socket connection to its codebase host, however, then it can use the multiplexing protocol over that connection to allow the codebase host to invoke methods on RMI objects exported by the applet. This section describes how the format and rules of the multiplexing protocol.

10.6.1 Definitions

This sections defines some terms as they are used in the rest of the description of the protocol.

An endpoint is one of the two users of a connection using the multiplexing protocol.

The multiplexing protocol must layer on top of one existing bidirectional, reliable byte stream, presumably initiated by one of the endpoints to the other. In current RMI usage, this is always a TCP connection, made with a java.net.Socket object. This connection will be referred to as the concrete connection.

The multiplexing protocol facilitates the use of virtual connections, which are themselves bidirectional, reliable byte streams, representing a particular session between two endpoints. The set of virtual connections between two endpoints over a single concrete connection comprises a multiplexed connection. Using the multiplexing protocol, virtual connections can be opened and closed by either endpoint. The state of an virtual connection with respect to a given endpoint is defined by the elements of the multiplexing protocol that are sent and received over the concrete connection. Such state involves if the connection is open or closed, the actual data that has been transmitted across, and the related flow control mechanisms. If not otherwise qualified, the term connection used in the remainder of this section means virtual connection.

A virtual connections within a given multiplexed connection is identified by a 16 bit integer, known as the connection identifier. Thus, there exist 65,536 possible virtual connections in one multiplexed connection. The implementation may limit the number of these virtual connections that may be used simultaneously.

10.6.2 Connection State and Flow Control

Connections are manipulated using the various operations defined by the multiplexing protocol. The following are the names of the operations defined by the protocol: OPEN, CLOSE, CLOSEACK, REQUEST, and TRANSMIT. The exact format and rules for all the operations are detailed in Section 10.6.3, "Protocol Format."

The OPEN, CLOSE, and CLOSEACK operations control connections becoming opened and closed, while the REQUEST and TRANSMIT operations are used to transmit data across an open connection within the constraints of the flow control mechanism.

Connection States

A virtual connection is open with respect to a particular endpoint if the endpoint has sent an OPEN operation for that connection, or it has received an OPEN operation for that connection (and it had not been subsequently closed). The various protocol operations are described below.

A virtual connection is pending close with respect to a particular endpoint if the endpoint has sent a CLOSE operation for that connection, but it has not yet received a subsequent CLOSE or CLOSEACK operation for that connection.

A virtual connection is closed with respect to a particular endpoint if it has never been opened, or if it has received a CLOSE or a CLOSEACK operation for that connection (and it has not been subsequently opened).

Flow Control

The multiplexing protocol uses a simple packeting flow control mechanism to allow multiple virtual connections to exist in parallel over the same concrete connection. The high level requirement of the flow control mechanism is that the state of all virtual connections is independent; the state of one connection may not affect the behavior of others. For example, if the data buffers handling data coming in from one connection become full, this cannot prevent the transmission and processing of data for any other connection. This is necessary if the continuation of one connection is dependent on the completion of the use of another connection, such as would happen with recursive RMI calls. Therefore, the practical implication is that the implementation must always be able to consume and process all of the multiplexing protocol data ready for input on the concrete connection (assuming that it conforms to this specification).

Each endpoint has two state values associated with each connection: how many bytes of data the endpoint has requested but not received (input request count) and how many bytes the other endpoint has requested but have not been supplied by this endpoint (output request count).

An endpoint's output request count is increased when it receives a REQUEST operation from the other endpoint, and it is decreased when it sends a TRANSMIT operation. An endpoint's input request count is increased when it sends a REQUEST operation, and it is decreased when it receives a TRANSMIT operation. It is a protocol violation if either of these values becomes negative.

It is a protocol violation for an endpoint to send a REQUEST operation that would increase its input request count to more bytes that it can currently handle without blocking. It should, however, make sure that its input request count is greater than zero if the user of the connection is waiting to read data.

It is a protocol violation for an endpoint to send a TRANSMIT operation containing more bytes that its output request count. It may buffer outgoing data until the user of the connection requests that data written to the connection be explicitly flushed. If data must be sent over the connection, however, by either an explicit flush or because the implementation's output buffers are full, then the user of the connection may be blocked until sufficient TRANSMIT operations can proceed.

Beyond the rules outlined above, implementations are free to send REQUEST and TRANSMIT operations as deemed appropriate. For example, an endpoint may request more data for a connection even if its input buffer is not empty.

10.6.3 Protocol Format

The byte stream format of the multiplexing protocol consists of a contiguous series of variable length records. The first byte of the record is an operation code that identifies the operation of the record and determines the format of the rest of its content. The following legal operation codes are defined:
value | name
0xE1 | OPEN
0xE2 | CLOSE
0xE3 | CLOSEACK
0xE4 | REQUEST
0xE5 | TRANSMIT

It is a protocol violation if the first byte of a record is not one of the defined operation codes. The following sections describe the format of the records for each operation code.

OPEN operation

This is the format for records of the OPEN operation:

size (bytes) | name | description
1 | opcode | operation code (OPEN)
2 | ID | connection identifier

An endpoint sends an OPEN operation to open the indicated connection. It is a protocol violation if ID refers to a connection that is currently open or pending close with respect to the sending endpoint. After the connection is opened, both input and request count states for the connection are zero for both endpoints.

Receipt of an OPEN operation indicates that the other endpoint is opening the indicated connection. After the connection is opened, both input and output request count states for the connection are zero for both endpoints.

To prevent identifier collisions between the two endpoints, the space of valid connection identifiers is divided in half, depending on the value of the most significant bit. Each endpoint is only allowed to open connections with a particular value for the high bit. The endpoint that initiated the concrete connection must only open connections with the high bit set in the identifier and the other endpoint must only open connections with a zero in the high bit. For example, if an RMI applet that cannot create a server socket initiates a multiplexed connection to its codebase host, the applet may open virtual connections in the identifier range 0x8000-7FFF, and the server may open virtual connection in the identifier range 0-0x7FFF.

CLOSE operation

This is the format for records of the CLOSE operation:
size (bytes) | name | description
1 | opcode | operation code (OPEN)
2 | ID | connection identifier

An endpoint sends a CLOSE operation to close the indicated connection. It is a protocol violation if ID refers to a connection that is currently closed or pending close with respect to the sending endpoint (it may be pending close with respect to the receiving endpoint if it has also sent a CLOSE operation for this connection). After sending the CLOSE, the connection becomes pending close for the sending endpoint. Thus, it may not reopen the connection until it has received a CLOSE or a CLOSEACK for it from the other endpoint.

Receipt of a CLOSE operation indicates that the other endpoint has closed the indicated connection, and it thus becomes closed on the receiving endpoint. Although the receiving endpoint may not send any more operations for this connection (until it is opened again), it still should provide data in the implementation's input buffers to readers of the connection. If the connection had previously been open instead of pending close, the receiving endpoint must respond with a CLOSEACK operation for the connection.

CLOSEACK operation

The following is the format for records with the CLOSEACK operation:
size (bytes) | name | description
1 | opcode | operation code (OPEN)
2 | ID | connection identifier

An endpoint sends a CLOSEACK operation to acknowledge a CLOSE operation from the receiving endpoint. It is a protocol violation if ID refers to a connection that is not pending close for the receiving endpoint when the operation is received.

Receipt of a CLOSEACK operation changes the state of the indicated connection from pending close to closed, and thus the connection may be reopened in the future.

REQUEST operation

This is the format for records of the REQUEST operation:
size (bytes) | name | description
1 | opcode | operation code (OPEN)
2 | ID | connection identifier
4 | count | number of additional bytes requested

An endpoint sends a REQUEST operation to increase its input request count for the indicated connection. It is a protocol violation if ID does not refer to a connection that is open with respect to the sending endpoint. The endpoint's input request count is incremented by the value count. The value of count is a signed 32 bit integer, and it is a protocol violation if it is negative or zero.

Receipt of a REQUEST operation causes the output request count for the indicated connection to increase by count. If the connection is pending close by the receiving endpoint, then any REQUEST operations may be ignored.

TRANSMIT operation

This is the format for records of the TRANSMIT operation.

size (bytes) | name | description
1 | opcode | operation code (OPEN)
2 | ID | connection identifier
4 | count | number of bytes in transmission
count | data | transmission data

An endpoint sends a TRANSMIT operation to actually transmit data over the indicated connection. It is a protocol violation if ID does not refer to a connection that is open with respect to the sending endpoint. The endpoint's output request count is decremented by the value count. The value of count is a signed 32 bit integer, and it is a protocol violation if it is negative or zero. It is also a protocol violation if the TRANSMIT operation would cause the sending endpoint's output request count to become negative.

Receipt of a TRANSMIT operation causes the count bytes of data to be added to the queue of bytes available for reading from the connection. The receiving endpoint's input request count is decremented by count. If this causes the input request count to become zero and the user of the connection is trying to read more data, the endpoint should respond with another REQUEST operation. If the connection is pending close by the receiving endpoint, then any TRANSMIT operations may be ignored.

Protocol Violations

If a protocol violation occurs, as defined above or if a communication error is detected in the concrete connection, then the multiplexed connection is shut down. The real connection is terminated, and all virtual connections become closed immediately. Data already available for reading from virtual connections may be read by the users of the connections.

CONTENTS | PREV | NEXT
Copyright © (c) 1997,2006, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 6 - Registry Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

Registry Interfaces

CHAPTER 6 The RMI system uses the java.rmi.registry.Registry interface and the java.rmi.registry.LocateRegistry class to provide a well-known bootstrap service for retrieving and registering objects by simple names.

A registry is a remote object that maps names to remote objects. Any server process can support its own registry or a single registry can be used for a host.

The methods of LocateRegistry are used to get a registry operating on a particular host or host and port. The methods of the java.rmi.Naming class makes calls to a remote object that implements the Registry interface using the appropriate LocateRegistry.getRegistry method.

Topics:

  • The Registry Interface
  • The LocateRegistry Class
  • The RegistryHandler Interface

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 6 - Registry Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

6.1 The Registry Interface

See the Registry API documentation.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 6 - Registry Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

6.2 The LocateRegistry Class

The class java.rmi.registry.LocateRegistry is used to obtain a reference (construct a stub) to a bootstrap remote object registry on a particular host (including the local host), or to create a remote object registry that accepts calls on a specific port.

The registry implements a simple flat naming syntax that associates the name of a remote object (a string) with a remote object reference. The name and remote object bindings are not remembered across server restarts.

Note that a getRegistry call does not actually make a connection to the remote host. It simply creates a local reference to the remote registry and will succeed even if no registry is running on the remote host. Therefore, a subsequent method invocation to a remote registry returned as a result of this method may fail.

package java.rmi.registry;

public final class LocateRegistry {

        public static Registry getRegistry()
                throws java.rmi.RemoteException {...}
        public static Registry getRegistry(int port)
                throws java.rmi.RemoteException {...}
        public static Registry getRegistry(String host)
                throws java.rmi.RemoteException {...}
        public static Registry getRegistry(String host, int port)
                throws java.rmi.RemoteException {...}
        public static Registry getRegistry(String host, int port,
                                           RMIClientSocketFactory csf)
                throws RemoteException {...}
        public static Registry createRegistry(int port)
                throws java.rmi.RemoteException {...}
        public static Registry createRegistry(int port,
                                              RMIClientSocketFactory csf,
                                              RMIServerSocketFactory ssf)
                throws RemoteException {...}
}
The first four getRegistry methods return a reference to a registry on the current host, current host at a specified port, a specified host, or at a particular port on a specified host. What is returned is the remote stub for the registry with the specified host and port information.

The fifth getRegistry method (that takes an RMIClientSocketFactory as one of its arguments), returns a locally created remote stub to the remote object Registry on the specified host and port. Communication with the remote registry whose stub is constructed with this method will use the supplied RMIClientSocketFactory, csf, to create Socket connections to the registry on the remote host and port.

Note - A registry returned from the getRegistry method is a specially constructed stub that contains a well-known object identifier. Passing a registry stub from one JVM to another is not supported (it may or may not work depending on the implementation). Use the LocateRegistry.getRegistry methods to obtain the appropriate registry for a host.
The createRegistry method creates and exports a registry on the local host on the specified port.

The second createRegistry method allows more flexibility in communicating with the registry. This call creates and exports a Registry on the local host that uses custom socket factories for communication with that registry. The registry that is created listens for incoming requests on the given port using a ServerSocket created from the supplied RMIServerSocketFactory. A client that receives a reference to this registry will use a Socket created from the supplied RMIClientSocketFactory.

Note - Starting a registry with the createRegistry method does not keep the server process alive.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 6 - Registry Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

6.3 The RegistryHandler Interface

See the RegistryHandler API documentation.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 5 - Server Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

Server Interfaces

CHAPTER 5 The java.rmi.server package contains interfaces and classes typically used to implement remote objects.

Topics:

  • The RemoteObject Class
  • The RemoteServer Class
  • The UnicastRemoteObject Class
  • The Unreferenced Interface
  • The RMISecurityManager Class
  • The RMIClassLoader Class
  • The LoaderHandler Interface
  • RMI Socket Factories
  • The RMIFailureHandler Interface
  • The LogStream Class
  • Stub and Skeleton Compiler

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 5 - Server Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

5.1 The RemoteObject Class

See the RemoteObject API documentation.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 5 - Server Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

5.2 The RemoteServer Class

See the RemoteServer API documentation.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 5 - Server Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

5.3 The UnicastRemoteObject Class

The class java.rmi.server.UnicastRemoteObject provides support for creating and exporting remote objects. The class implements a remote server object with the following characteristics:
  • References to such objects are valid only for, at most, the life of the process that creates the remote object.
  • Communication with the remote object uses a TCP transport.
  • Invocations, parameters, and results use a stream protocol for communicating between client and server.
package java.rmi.server;

public class UnicastRemoteObject extends RemoteServer {

        protected UnicastRemoteObject()
                throws java.rmi.RemoteException {...}
        protected UnicastRemoteObject(int port)
                throws java.rmi.RemoteException {...}
        protected UnicastRemoteObject(int port,
                                      RMIClientSocketFactory csf,
                                      RMIServerSocketFactory ssf)
                throws java.rmi.RemoteException {...}

        public Object clone()
                throws java.lang.CloneNotSupportedException {...}
        public static RemoteStub exportObject(java.rmi.Remote obj)
                throws java.rmi.RemoteException {...}
        public static Remote exportObject(java.rmi.Remote obj, int port)
                throws java.rmi.RemoteException {...}
        public static Remote exportObject(Remote obj, int port,
                                          RMIClientSocketFactory csf,
                                          RMIServerSocketFactory ssf)
                throws java.rmi.RemoteException {...}
        public static boolean unexportObject(java.rmi.Remote obj,
                                             boolean force)
                throws java.rmi.NoSuchObjectException {...}
}

5.3.1 Constructing a New Remote Object

A remote object implementation (one that implements one or more remote interfaces) must be created and exported. Exporting a remote object makes that object available to accept incoming calls from clients. For a remote object implementation that is exported as a UnicastRemoteObject, the exporting involves listening on a TCP port (note that more than one remote object can accept incoming calls on the same port, so listening on a new port is not always necessary). A remote object implementation can extend the class UnicastRemoteObject to make use of its constructors that export the object, or it can extend some other class (or none at all) and export the object via UnicastRemoteObject's exportObject methods.

The no argument constructor creates and exports a remote object on an anonymous (or arbitrary) port, chosen at runtime. The second form of the constructor takes a single argument, port, that specifies the port number on which the remote object accepts incoming calls. The third constructor creates and exports a remote object that accepts incoming calls on the specified port via a ServerSocket created from the RMIServerSocketFactory; clients will make connections to the remote object via Sockets supplied from the RMIClientSocketFactory.

5.3.2 Exporting an Implementation Not Extended From RemoteObject

An exportObject method (any of the forms) is used to export a simple peer-to-peer remote object that is not implemented by extending the UnicastRemoteObject class. The first form of the exportObject method takes a single parameter, obj, which is the remote object that will accept incoming RMI calls; this exportObject method exports the object on an anonymous (or arbitrary) port, chosen at runtime. The second exportObject method takes two parameters, both the remote object, obj, and port, the port number on which the remote object accepts incoming calls. The third exportObject method exports the object, obj, with the specified RMIClientSocketFactory, csf, and RMIServerSocketFactory, ssf, on the specified port.

The exportObject method returns a Remote stub which is the stub object for the remote object, obj, that is passed in place of the remote object in an RMI call.

5.3.3 Passing a UnicastRemoteObject in an RMI Call

As stated above, when an exported object of type UnicastRemoteObject is passed as a parameter or return value in an RMI call, the object is replaced by the remote object's stub. An exported remote object implementation remains in the virtual machine in which it was created and does not move (even by value) from that virtual machine. In other words, an exported remote object is passed by reference in an RMI call; exported remote object implementations cannot be passed by value.

5.3.4 Serializing a UnicastRemoteObject

Information contained in UnicastRemoteObject is transient and is not saved if an object of that type is written to a user-defined ObjectOutputStream (for example, if the object is written to a file using serialization). An object that is an instance of a user-defined subclass of UnicastRemoteObject, however, may have non-transient data that can be saved when the object is serialized.

When a UnicastRemoteObject is read from an ObjectInputStream using UnicastRemoteObject's readObject method, the remote object is automatically exported to the RMI runtime so that it may receive RMI calls. If exporting the object fails for some reason, deserializing the object will terminate with an exception.

5.3.5 Unexporting a UnicastRemoteObject

The unexportObject method makes the remote object, obj, unavailable for incoming calls. If the force parameter is true, the object is forcibly unexported even if there are pending calls to the remote object or the remote object still has calls in progress. If the force parameter is false, the object is only unexported if there are no pending or in-progress calls to the object. If the object is successfully unexported, the RMI runtime removes the object from its internal tables. Unexporting the object in this forcible manner may leave clients holding stale remote references to the remote object. This method throws java.rmi.NoSuchObjectException if the object was not previously exported to the RMI runtime.

5.3.6 The clone method

Objects are only clonable using the Java programming language's default mechanism if they support the java.lang.Cloneable interface. The class java.rmi.server.UnicastRemoteObject does not implement this interface, but does implement the clone method so that if subclasses need to implement Cloneable, the remote object will be capable of being cloned properly. The clone method can be used by a subclass to create a cloned remote object with initially the same contents, but is exported to accept remote calls and is distinct from the original object.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 5 - Server Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

5.4 The Unreferenced Interface

package java.rmi.server;

public interface Unreferenced {
        public void unreferenced();
}
The java.rmi.server.Unreferenced interface allows a server object to receive notification that there are no clients holding remote references to it. The distributed garbage collection mechanism maintains for each remote object, the set of client virtual machines that hold references to that remote object. As long as some client holds a remote reference to the remote object, the RMI runtime keeps a local reference to the remote object. Each time the remote object's "reference" set becomes empty (meaning that the number of clients that reference the object becomes zero), the Unreferenced.unreferenced method is invoked (if that remote object implements the Unreferenced interface). A remote object is not required to support the Unreferenced interface.

As long as some local reference to the remote object exists, it may be passed in remote calls or returned to clients. The process that receives the reference is added to the reference set for the remote object. When the reference set becomes empty, the remote object's unreferenced method will be invoked. As such, the unreferenced method can be called more than once (each time the set is newly emptied). Remote objects are only collected when no more references, either local references or those held by clients, still exist.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 5 - Server Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

5.5 The RMISecurityManager Class

See the RMISecurityManager API documentation.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 5 - Server Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

5.6 The RMIClassLoader Class

See the RMIClassLoader API documentation.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 5 - Server Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

5.7 The LoaderHandler Interface

See the LoaderHandler API documentation.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 5 - Server Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

5.8 RMI Socket Factories

When the RMI runtime implementation needs instances of java.net.Socket and java.net.ServerSocket for its connections, instead of instantiating objects of those classes directly, it calls the createSocket and createServerSocket methods on the current RMISocketFactory object, returned by the static method RMISocketFactory.getSocketFactory. This allows the application to have a hook to customize the type of sockets used by the RMI transport, such as alternate subclasses of the java.net.Socket and java.net.ServerSocket classes. The instance of RMISocketFactory to be used can be set once by trusted system code. In JDK1.1, this customization was limited to relatively global decisions about socket type, because the only parameters supplied to the factory's methods were host and port (for createSocket) and just port (for createServerSocket).

In the Java SE platform, the new interfaces RMIServerSocketFactory and RMIClientSocketFactory have been introduced to provide more flexible customization of what protocols are used to communicate with remote objects.

To allow applications using RMI to take advantage of these new socket factory interfaces, several new constructors and exportObject methods, that take the client and server socket factory as additional parameters, have been added to both UnicastRemoteObject and java.rmi.activation.Activatable.

Remote objects exported with either of the new constructors or exportObject methods (with RMIClientSocketFactory and RMIServerSocketFactory parameters) will be treated differently by the RMI runtime. For the lifetime of such a remote object, the runtime will use the custom RMIServerSocketFactory to create a ServerSocket to accept incoming calls to the remote object and use the custom RMIClientSocketFactory to create a Socket to connect clients to the remote object.

The implementation of RemoteRef and ServerRef used in the stubs and skeletons for remote objects exported with custom socket factories is UnicastRef2 and UnicastServerRef2, respectively. The wire representation of the UnicastRef2 type contains a different representation of the "endpoint" to contact than the UnicastRef type has (which used just a host name string in UTF format, following by an integer port number). For UnicastRef2, the endpoint's wire representation consists of a format byte specifying the contents of the rest of the endpoint's representation (to allow for future expansion of the endpoint representation) followed by data in the indicated format. Currently, the data may consist of a hostname in UTF format, a port number, and optionally (as specified by the endpoint format byte) the serialized representation of an RMIClientSocketFactory object that is used by clients to generate socket connections to remote object at this endpoint. The endpoint representation does not contain the RMIServerSocketFactory object that was specified when the remote object was exported.

When calls are made through references of the UnicastRef2 type, the runtime uses the createSocket method of the RMIClientSocketFactory object in the endpoint when creating sockets for connections to the referent remote object. Also, when the runtime makes DGC "dirty" and "clean" calls for a particular remote object, it must call the DGC on the remote JVM using a connection generated from the same RMIClientSocketFactory object as specified in the remote reference, and the DGC implementation on the server side should verify that this was done correctly.

Remote objects exported with the older constructor or method on UnicastRemoteObject that do not take custom socket factories as arguments will have RemoteRef and ServerRef of type UnicastRef and UnicastServerRef as before and use the old wire representation for their endpoints, i.e. a host string in UTF format followed by an integer specifying the port number. This is so that RMI servers that do not use new 1.2 features will interoperate with older RMI clients.

5.8.1 The RMISocketFactory Class

The java.rmi.server.RMISocketFactory abstract class provides an interface for specifying how the transport should obtain sockets. Note that the class below uses Socket and ServerSocket from the java.net package.
package java.rmi.server;

public abstract class RMISocketFactory
        implements RMIClientSocketFactory, RMIServerSocketFactory
{

        public abstract Socket createSocket(String host, int port)
                throws IOException;
   public abstract ServerSocket createServerSocket(int port)
                throws IOException;
        public static void setSocketFactory(RMISocketFactory fac)
                throws IOException {...}
        public static RMISocketFactory getSocketFactory() {...}
        public static void setFailureHandler(RMIFailureHandler fh) {...}
        public static RMIFailureHandler getFailureHandler() {...}
}
The static method setSocketFactory is used to set the socket factory from which RMI obtains sockets. The application may invoke this method with its own RMISocketFactory instance only once. An application-defined implementation of RMISocketFactory could, for example, do preliminary filtering on the requested connection and throw exceptions, or return its own extension of the java.net.Socket or java.net.ServerSocket classes, such as ones that provide a secure communication channel. Note that the RMISocketFactory may only be set if the current security manager allows setting a socket factory; if setting the socket factory is disallowed, a SecurityException will be thrown.

The static method getSocketFactory returns the socket factory used by RMI. The method returns null if the socket factory is not set.

The transport layer invokes the createSocket and createServerSocket methods on the RMISocketFactory returned by the getSocketFactory method when the transport needs to create sockets. For example:

    RMISocketFactory.getSocketFactory().createSocket(myhost, myport)
The method createSocket should create a client socket connected to the specified host and port. The method createServerSocket should create a server socket on the specified port.

The default transport's implementation of RMISocketFactory provides for transparent RMI through firewalls using HTTP as follows:

  • On createSocket, the factory automatically attempts HTTP connections to hosts that cannot be contacted with a direct socket.
  • On createServerSocket, the factory returns a server socket that automatically detects if a newly accepted connection is an HTTP POST request. If so, it returns a socket that will transparently expose only the body of the request to the transport and format its output as an HTTP response.
The method setFailureHandler sets the failure handler to be called by the RMI runtime if the creation of a server socket fails. The failure handler returns a boolean to indicate if retry should occur. The default failure handler returns false, meaning that by default recreation of sockets is not attempted by the runtime.

The method getFailureHandler returns the current handler for socket creation failure, or null if the failure handler is not set.

5.8.2 The RMIServerSocketFactory Interface

See the RMIServerSocketFactory API documentation.

5.8.3 The RMIClientSocketFactory Interface

See the RMIClientSocketFactory API documentation.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 5 - Server Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

5.9 The RMIFailureHandler Interface

The java.rmi.server.RMIFailureHandler interface provides a method for specifying how the RMI runtime should respond when server socket creation fails (except during object export).
package java.rmi.server;

public interface RMIFailureHandler {

        public boolean failure(Exception ex);
}
The failure method is invoked with the exception that prevented the RMI runtime from creating a java.net.ServerSocket. The method returns true if the runtime should attempt to retry and false otherwise.

Before this method can be invoked, a failure handler needs to be registered via the RMISocketFactory.setFailureHandler call. If the failure handler is not set, the RMI runtime attempts to re-create the ServerSocket after waiting for a short period of time.

Note that the RMIFailureHandler is not called when ServerSocket creation fails upon initial export of the object. The RMIFailureHandler will be called when there is an attempt to create a ServerSocket after a failed accept on that ServerSocket.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 5 - Server Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

5.10 The LogStream Class

See the LogStream API documentation.

CONTENTS | PREV | NEXT
Copyright 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 5 - Server Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

5.11 Stub and Skeleton Compiler

The rmic stub and skeleton compiler is used to compile the appropriate stubs and skeletons for a specific remote object implementation.

Please see the following URLs for further information on rmic:

  • For the SolarisTM Operating System:
    http://java.sun.com/products/jdk/1.6.0/docs/tooldocs/solaris/rmic.html
  • For the Windows platform:
    http://java.sun.com/products/jdk/1.6.0/docs/tooldocs/windows/rmic.html

CONTENTS | PREV | NEXT
Copyright (c) 1997,2006, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 8 - Stub/Skeleton Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

Stub/Skeleton Interfaces

CHAPTER 8

This section contains the interfaces and classes used by the stubs and skeletons generated by the rmic stub compiler.

Topics:

  • The RemoteStub Class
  • The RemoteCall Interface
  • The RemoteRef Interface
  • The ServerRef Interface
  • The Skeleton Interface
  • The Operation Class

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 8 - Stub/Skeleton Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

8.1 The RemoteStub Class

The java.rmi.server.RemoteStub class is the common superclass for stubs of remote objects. Stub objects are surrogates that support exactly the same set of remote interfaces defined by the actual implementation of a remote object.
package java.rmi.server;

public abstract class RemoteStub extends java.rmi.RemoteObject {
        protected RemoteStub() {...}
        protected RemoteStub(RemoteRef ref) {...}

        protected static void setRef(RemoteStub stub, RemoteRef ref) {...}
}
The first constructor of RemoteStub creates a stub with a null remote reference. The second constructor creates a stub with the given remote reference, ref.

The setRef method is deprecated (and unsupported) as of the Java 2 SDK, Standard Edition, v1.2.

8.1.1 Type Equivalency of Remote Objects with a Stub Class

Clients interact with stub (surrogate) objects that have exactly the same set of remote interfaces defined by the remote object's class; the stub class does not include the non-remote portions of the class hierarchy that constitutes the object's type graph. This is because the stub class is generated from the most refined implementation class that implements one or more remote interfaces. For example, if C extends B and B extends A, but only B implements a remote interface, then a stub is generated from B, not C.

Because the stub implements the same set of remote interfaces as the remote object's class, the stub has the same type as the remote portions of the server object's type graph. A client, therefore, can make use of the built-in Java programming language operations to check a remote object's type and to cast from one remote interface to another.

Stubs are generated using the rmic compiler.

8.1.2 The Semantics of Object Methods Declared final

The following methods are declared final in the java.lang.Object class and therefore cannot be overridden by any implementation:
  • getClass
  • notify
  • notifyAll
  • wait
The default implementation for getClass is appropriate for all objects written in the Java programming language, local or remote; so, the method needs no special implementation for remote objects. When used on a remote stub, the getClass method reports the exact type of the stub object, generated by rmic. Note that stub type reflects only the remote interfaces implemented by the remote object, not that object's local interfaces.

The wait and notify methods of java.lang.Object deal with waiting and notification in the context of the Java programming language's threading model. While use of these methods for remote stubs does not break the threading model, these methods do not have the same semantics as they do for local objects written in the Java programming language. Specifically, these methods operate on the client's local reference to the remote object (the stub), not the actual object at the remote site.

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 8 - Stub/Skeleton Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

8.2 The RemoteCall Interface

The interface RemoteCall is an abstraction used by the stubs and skeletons of remote objects to carry out a call to a remote object.
Note - The RemoteCall interface is deprecated as of the Java 2 SDK, Standard Edition, v1.2. The 1.2 stub protocol does not make use of this interface anymore. As of the Java 2 SDK, Standard Edition, v1.2, stubs now use the new invoke method which does not require RemoteCall as a parameter.
package java.rmi.server;

import java.io.*;

public interface RemoteCall {
        ObjectOutput getOutputStream() throws IOException;
        void releaseOutputStream() throws IOException;
        ObjectInput getInputStream() throws IOException;
        void releaseInputStream() throws IOException;
        ObjectOutput getResultStream(boolean success)
                throws IOException, StreamCorruptedException;
        void executeCall() throws Exception;
        void done() throws IOException;
}
The method getOutputStream returns the output stream into which either the stub marshals arguments or the skeleton marshals results.

The method releaseOutputStream releases the output stream; in some transports this will release the stream.

The method getInputStream returns the InputStream from which the stub unmarshals results or the skeleton unmarshals parameters.

The method releaseInputStream releases the input stream. This will allow some transports to release the input side of a connection early.

The method getResultStream returns an output stream (after writing out header information relating to the success of the call). Obtaining a result stream should only succeed once per remote call. If success is true, then the result to be marshaled is a normal return; otherwise the result is an exception. StreamCorruptedException is thrown if the result stream has already been obtained for this remote call.

The method executeCall does whatever it takes to execute the call.

The method done allows cleanup after the remote call has completed.

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 8 - Stub/Skeleton Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

8.3 The RemoteRef Interface

The interface RemoteRef represents the handle for a remote object. Each stub contains an instance of RemoteRef that contains the concrete representation of a reference. This remote reference is used to carry out remote calls on the remote object for which it is a reference.
package java.rmi.server;

public interface RemoteRef extends java.io.Externalizable {
        Object invoke(Remote obj,
                                   java.lang.reflect.Method method,
                                   Object[] params,
                                   long opnum)
                throws Exception;

        RemoteCall newCall(RemoteObject obj, Operation[] op, int opnum,
                           long hash) throws RemoteException;
        void invoke(RemoteCall call) throws Exception;
        void done(RemoteCall call) throws RemoteException;
        String getRefClass(java.io.ObjectOutput out);
        int remoteHashCode();
        boolean remoteEquals(RemoteRef obj);
        String remoteToString();
}
The invoke(Remote,Method,Object[],long) method delegates method invocation to the stub's (obj) remote reference and allows the reference to take care of setting up the connection to the remote host, marshaling some representation for the method and parameters, params, then communicating the method invocation to the remote host. This method either returns the result of the method invocation on the remote object which resides on the remote host or throws a RemoteException if the call failed or an application-level exception if the remote invocation throws an exception. Note that the operation number, opnum, represents a hash of the method signature and may be used to encode the method for transmission.

The method hash to be used for the opnum parameter is a 64-bit (long) integer computed from the first two 32-bit values of the message digest of a particular byte stream using the National Institute of Standards and Technology (NIST) Secure Hash Algorithm (SHA-1). This byte stream contains a string as if it was written using the java.io.DataOutput.writeUTF method, consisting of the remote method's name followed by its method descriptor (see The Java Virtual Machine Specification (JVMS) for a description of method descriptors).

For example, if a method of a remote interface has the following name and signature:

   void myRemoteMethod(int count, Object obj, boolean flag)
the string containing the remote method's name and descriptor would be the following:
   myRemoteMethod(ILjava/lang/Object;Z)V
The 64-bit hash value is the little-endian composition of an eight byte sequence where the first four bytes are the first 32-bit value of the message digest in big-endian byte order and the last four bytes are the second 32-bit value of the message digest in big-endian byte order. For example, if the first two 32-bit values of the message digest are 0xB0B1B2B3 and 0xB4B5B6B7, then the hash value would be 0xB7B6B5B4B3B2B1B0.
Note - The methods newCall(RemoteObject,Operation[],int,long), invoke(RemoteCall), and done(RemoteCall) are deprecated as of the Java 2 SDK, Standard Edition, v1.2. The stubs generated by rmic using the 1.2 stub protocol version do not use these methods any longer. The sequence of calls consisting of newCall, invoke, and done have been replaced by a new invoke method that takes a Method object as one of its parameters.
The method newCall creates an appropriate call object for a new remote method invocation on the remote object obj. The operation array, op, contains the available operations on the remote object. The operation number, opnum, is an index into the operation array which specifies the particular operation for this remote call. The interface hash is a 64-bit value used to enforce compatibility between a stub and skeleton using the v1.1 stub protocol. The interface hash is computed from the first two 32-bit values of the message digest of a particular byte stream using SHA-1. This byte stream contains data as if it was written using the writeInt and writeUTF methods of the interface java.io.DataOutput, consisting of the following items:
  • (int) stub version number, always 1
  • for each remote method, in order of operation number:
  • (UTF-8) remote method name
  • (UTF-8) remote method descriptor (see The Java Virtual Machine Specification)
  • for each declared exception, in lexicographic order of binary name:
    • (UTF-8) the name of the exception class

The interface hash value is composed from the message digest in the same manner as described above for the method hash used in the invoke method.

The method invoke(RemoteCall) executes the remote call. invoke will raise any "user" exceptions which should pass through and not be caught by the stub. If any exception is raised during the remote invocation, invoke should take care of cleaning up the connection before raising the "user exception" or RemoteException.

The method done allows the remote reference to clean up (or reuse) the connection. done should only be called if the invoke call returns successfully (non-exceptionally) to the stub.

The method getRefClass returns the nonpackage-qualified class name of the reference type to be serialized onto the stream out.

The method remoteHashCode returns a hashcode for a remote object. Two remote object stubs that refer to the same remote object will have the same hash code (in order to support remote objects as keys in hashtables). A RemoteObject forwards a call to its hashCode method to the remoteHashCode method of the remote reference.

The method remoteEquals compares two remote objects for equality. Two remote objects are equal if they refer to the same remote object. For example, two stubs are equal if they refer to the same remote object. A RemoteObject forwards a call to its equals method to the remoteEquals method of the remote reference.

The method remoteToString returns a String that represents the reference of this remote object.

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 8 - Stub/Skeleton Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

8.4 The ServerRef Interface

The interface ServerRef represents the server-side handle for a remote object implementation.
package java.rmi.server;

public interface ServerRef extends RemoteRef {
        RemoteStub exportObject(java.rmi.Remote obj, Object data)
                throws java.rmi.RemoteException;
        String getClientHost() throws ServerNotActiveException;
}
The method exportObject finds or creates a client stub object for the supplied Remote object implementation obj.The parameter data contains information necessary to export the object (such as port number).

The method getClientHost returns the host name of the current client. When called from a thread actively handling a remote method invocation, the host name of the client invoking the call is returned. If a remote method call is not currently being service, then ServerNotActiveException is called.

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 8 - Stub/Skeleton Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

8.5 The Skeleton Interface

The interface Skeleton is used solely by the implementation of skeletons generated by the rmic compiler. A skeleton for a remote object is a server-side entity that dispatches calls to the actual remote object implementation.
Note - The Skeleton interface was deprecated as of the Java 2 SDK, Standard Edition, v 1.2. Every 1.1 (and version 1.1 compatible skeletons generated in 1.2 using rmic -vcompat, the default) skeleton class generated by the rmic stub compiler implements this interface. Skeletons are no longer required for remote method call dispatch as of Java 2 SDK, Standard Edition, v1.2-compatible versions. To generate stubs that are compatible with 1.2 or later versions, use the command rmic with the option -v 1.2.
package java.rmi.server;

public interface Skeleton {
    void dispatch(Remote obj, RemoteCall call, int opnum, long hash)
                throws Exception;
    Operation[] getOperations();
}
The dispatch method unmarshals any arguments from the input stream obtained from the call object, invokes the method (indicated by the operation number opnum) on the actual remote object implementation obj, and marshals the return value or throws an exception if one occurs during the invocation.

The getOperations method returns an array containing the operation descriptors for the remote object's methods.

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: 8 - Stub/Skeleton Interfaces

CONTENTS | PREV | NEXT Java Remote Method Invocation

8.6 The Operation Class

The class Operation holds a description of a method in the Java programming language for a remote object.
Note - The Operation interface is deprecated as of the Java 2 SDK, Standard Edition, v1.2. The 1.2 stub protocol no longer uses the old RemoteRef.invoke method which takes an Operation as one of its arguments. As of the Java 2 SDK, Standard Edition, v1.2, stubs now use the new invoke method which does not require Operation as a parameter.
package java.rmi.server;

public class Operation {
        public Operation(String op) {...}
        public String getOperation() {...}
        public String toString() {...}
}
An Operation object is typically constructed with the method signature.

The method getOperation returns the contents of the operation descriptor (the value with which it was initialized).

The method toString also returns the string representation of the operation descriptor (typically the method signature).

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Java Remote Method Invocation: Contents

Java™ Remote Method Invocation Specification

Java Remote Method Invocation (Java RMI) is a distributed object model for the Java programming language that retains the semantics of the Java platform's object model, making distributed objects easy to implement and to use. The system combines aspects of the Modula-3 Network Objects system and Spring's subcontract and includes some novel features made possible by the Java SE platform.

Revision 1.11, JavaTM SE Developer Kit, v6

CONTENTS | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


RMI-IIOP Programmer's Guide

This document discusses how to write Java Remote Method Invocation (RMI) programs that can access remote objects by using the Internet Inter-ORB Protocol (IIOP). By making your RMI programs conform to a small set of restrictions, your CORBA clients in any language can access RMI-IIOP servers. RMI-IIOP gives you RMI ease-of-use coupled with CORBA/IIOP language interoperability.

What is RMI-IIOP?

RMI

With RMI you can write distributed programs in the Java programming language. RMI is easy to use, you don't need to learn a separate interface definition language (IDL), and you get Java's inherent "write once, run anywhere" benefit. Clients, remote interfaces, and servers are written entirely in Java. RMI uses the Java Remote Method Protocol (JRMP) for remote Java object communication. To get a quick introduction to writing RMI programs, see the RMI Tutorial web page. That document describes writing a simple "Hello World" RMI program.

RMI lacks interoperability with other languages because it does not use CORBA-IIOP as the communication protocol.

IIOP, CORBA, and Java IDL

IIOP is CORBA's communication protocol using TCP/IP as the transport. It specifies a standard for client and server communication. CORBA is a standard distributed object architecture developed by the Object Management Group (OMG). Interfaces to remote objects are described in a platform-neutral interface definition language (IDL). Mappings from IDL to specific programming languages are implemented, binding the language to CORBA/IIOP.

The Java(TM) 2 Platform, Standard Edition (J2SE) CORBA/IIOP implementation is known as Java IDL. Along with the idlj compiler, Java IDL can be used to define, implement, and access CORBA objects from the Java programming language.

The Java IDL web page gives you a good, Java-centric view of CORBA/IIOP programming. To get a quick introduction to writing Java IDL programs, see the Getting Started: Hello World web page.

RMI-IIOP

Previously Java programmers had to choose between RMI and CORBA/IIOP (Java IDL) for distributed programming solutions. Now, by adhering to a few restrictions, RMI server objects can use the IIOP protocol and communicate with CORBA client objects written in any language. This solution is known as RMI-IIOP. RMI-IIOP combines RMI-style ease of use with CORBA cross-language interoperability.

Table of Contents

  • The rmic Compiler
  • The idlj Compiler
  • How to Make RMI Programs Use IIOP
  • Restrictions When Running RMI Programs Over IIOP
  • Other Things You Should Know

The rmic Compiler

The RMI-IIOP software comes with an rmic compiler that can generate IIOP stubs and ties, and emit IDL, in accordance with the Java Language to OMG IDL Language Mapping Specification, in accordance with the compliance statement.

Here are the primary rmic flags that support the CORBA/IIOP functionality:

-iiop -- Generates IIOP stubs/ties.
-iiop -poa -- Generates IIOP stubs/ties that work with a Portable Object Adapter (POA).
-idl -- Generates IDL.

The following options are used in conjunction with the -idl option.

-noValueMethods -- Stops generation of IDL for methods and constructors within IDL valuetypes.
-always -- Forces regeneration even when existing stubs/ties/idl are newer than the input class. Only valid when -iiop and/or -idl flags are present.
-idlModule <fromJavaPackage<.class>> <toIDLModule> -- Specifies IDLEntity package mapping. For example: -idlModule foo.bar my::real::idlmod
-idlFile <fromJavaPackage<.class>> <toIDLFile> -- Specifies IDLEntity file mapping. For example: -idlFile test.pkg.X TEST16.idl

For more detailed information on the rmic compiler, read the rmic documentation.

The -iiop Flag

Using rmic with the -iiop option generates IIOP stub and tie classes instead of Java Remote Method Protocol (JRMP) stub and skeleton classes. A stub class is a local proxy for a remote object. Stub classes are used by clients to send calls to a server. Each remote interface requires a stub class, which implements that remote interface. The client's reference to a remote object is actually a reference to a stub. Tie classes are used on the server side to process incoming calls, and dispatch the calls to the proper implementation class. Each implementation class requires a tie class.

Stub classes are also generated for abstract interfaces. An abstract interface is an interface that does not extend java.rmi.Remote, but whose methods all throw either java.rmi.RemoteException or a superclass of java.rmi.RemoteException. Interfaces that do not extend java.rmi.Remote and have no methods are also abstract interfaces.

QUESTION: I have a RMI-IIOP application which was running on J2SE 1.3. When I generate new stubs and skeletons using rmic -iiop -poa <RMI Interface>, it does not work. Why ?

ANSWER: There are 2 different ways to compile and run RMI-IIOP programs, which are listed below. We do not recommend that you combine these.

  1. The default RMI-IIOP behavior. An example of an application that uses the default RMI-IIOP behavior can be found at Tutorial: Getting Started Using RMI-IIOP.
  2. POA-based RMI-IIOP. An example of an application that uses the non-standard POA-based RMI-IIOP behavior can be found at Getting Started Using RMI-IIOP: Example Using POA-based server-side model.

The -iiop -poa Flag

New to this release of Java SE is the -iiop -poa option. Using the -iiop flag with the -poa option changes the inheritance from org.omg.CORBA_2_3.portable.ObjectImpl to org.omg.PortableServer.Servant. This type of mapping is nonstandard and is not specified by the Java Language to OMG IDL Language Mapping Specification.

The PortableServer module for the Portable Object Adapter (POA) defines the native Servant type. In the Java programming language, the Servant type is mapped to the Java org.omg.PortableServer.Servant class. It serves as the base class for all POA servant implementations and provides a number of methods that may be invoked by the application programmer, as well as methods which are invoked by the POA itself and may be overridden by the user to control aspects of servant behavior.

The -idl Flag

Using rmic with the -idl option generates OMG IDL for the classes specified and any classes referenced. You would want to use this option when you have a CORBA client in another language that wants to talk to an RMI-IIOP server.

Note: After the OMG IDL is generated using rmic -idl, use the generated IDL with an IDL-to-C++ or other language compiler, but not with the IDL-to-Java language compiler. "Round tripping" is not recommended and should not be necessary. The IDL generation facility is intended to be used with other languages such as C++. Java clients or servers can use the original RMI-IIOP types.

IDL provides a purely declarative, programming language independent means for specifying the API for an object. The IDL is used as a specification for methods and data that can be written in and invoked from any language that provides CORBA bindings. This includes Java and C++ among others. See the Java Language to IDL Mapping (OMG) document for a complete description.

Note: The generated IDL can only be compiled using an IDL compiler that supports the CORBA 2.3 extensions to IDL.

The -noValueMethods Flag

The -noValueMethods option, when used with -idl, ensures that methods and initializers are not included in valuetypes emitted during IDL Generation. These are optional for valuetypes and are otherwise omitted.

See the RMIC tool page (Solaris Version/Windows version) for a complete rmic description.

The idlj Compiler

The RMI-IIOP software includes an IDL-to-Java compiler. This compiler supports the CORBA Objects By Value feature, which is required for interoperation with RMI-IIOP. It is written in Java, and so can run on any platform. See the IDL-to-Java Compiler User's Guide for details of how to use this compiler.

How to Make RMI Programs Use IIOP

The following steps are a general guide to converting an RMI application to RMI-IIOP.
  1. If you are using the RMI registry for naming services, you need to switch to CosNaming. In the createORB() method, do not pass the org.omg.ORBClass property. Instead, use ORB.init( args, null ). You need to do the following:
    1. In both your client and server code, you need to create an InitialContext for JNDI using the following code:
               import javax.naming.*;
         ...
         Context ic = new InitialContext();
    2. Modify all uses of RMI registry lookup() and bind() to use JNDI lookup() and bind()instead. For example, instead of your RMI server using:
               import java.rmi.*;
         ...
         Naming.rebind("MyObject", myObj);
      use:
               import javax.naming.*;
         ...
         ic.rebind("MyObject", myObj);
    3. If the client is an applet, the client applet needs to pass this to the JNDI CosNaming plugin. Replace the above code with the following:
              import java.util.*;
        import javax.naming.*;
        ...
        Hashtable env = new Hashtable();
        env.put("java.naming.applet", this);
        Context ic = new InitialContext(env);
  2. If you are not using the RMI registry for naming services, you have some other way of bootstrapping your initial remote object reference. For example, your server code may be using Java serialization to write an RMI object reference to an ObjectOutputStream and passing this to your client code for deserializing into an RMI stub.

    On the server side, use the PortableRemoteObject.toStub() call to obtain a stub, then use writeObject() to serialize this stub to an ObjectOutputStream. The code to do this looks something like:

    org.omg.CORBA.ORB myORB = org.omg.CORBA.ORB.init(new String[0], null);
Wombat myWombat = new WombatImpl();
javax.rmi.CORBA.Stub myStub = (javax.rmi.CORBA.Stub)PortableRemoteObject.toStub(myWombat);
myStub.connect(myORB);
// myWombat is now connected to myORB.  To connect other objects to the
// same ORB, use PortableRemoteObject.connect(nextWombat, myWombat);
FileOutputStream myFile = new FileOutputStream("t.tmp");
ObjectOutputStream myStream = new ObjectOutputStream(myFile);
myStream.writeObject(myStub);
    On the client side, use readObject() to deserialize a remote reference to the object from an ObjectInputStream, with code like:
    FileInputStream myFile = new FileInputStream("t.tmp");
ObjectInputStream myStream = new ObjectInputStream(myFile);
Wombat myWombat = (Wombat)myStream.readObject();
org.omg.CORBA.ORB myORB = org.omg.CORBA.ORB.init(new String[0], null);
((javax.rmi.CORBA.Stub)myWombat).connect(myORB);
// myWombat is now connected to myORB.  To connect other objects to the
// same ORB, use PortableRemoteObject.connect(nextWombat, myWombat);
  3. Either change your remote implementation classes to inherit from javax.rmi.PortableRemoteObject, or explicitly export implementation objects after creation by calling PortableRemoteObject.exportObject(). For more discussion on this topic, read Connecting IIOP stubs to the ORB.
  4. Change all the places in your code where there is a Java cast of a remote interface to use javax.rmi.PortableRemoteObject.narrow().
  5. Don't depend on Distributed Garbage Collection (DGC) or use any of the RMI DGC facilities. Use PortableRemoteObject.unexportObject() to unexport objects that are no longer in use.
  6. Regenerate the RMI stubs and ties using the rmic command with the -iiop option. This will produce stub and tie files with the following names:
         _<implementionName>_Tie.class
     _<interfaceName>_Stub.class
  7. Before starting the server, start the CosNaming server (in its own process) using the following command:
         orbd -ORBInitialPort port#
    You must specify the port number when starting ORBD.
  8. When starting client and server applications, specify the following system properties:
         java -Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory
          -Djava.naming.provider.url=iiop://<hostname>:1050
           <appl_class>
    This example uses the name service port number of 1050. If you specified a different port in step 7, you need to use the same port number in the provider URL here. The <hostname> in the provider URL is the host name that was used to start the CosNaming server in step 7.

  9. If the client is an applet, specify the following properties in the applet tag:
         java.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory
     java.naming.provider.url=iiop://<hostname>:1050
    This example uses the name service port number of 1050. If you specified a different port in step 7, you need to use the same port number in the provider URL here. The <hostname> in the provider URL is the host name that was used to start the CosNaming server in step 7.

For tutorials that describe creating a new RMI-IIOP application, link to Getting Started Using RMI-IIOP: Example Using POA-based server-side model or Tutorial: Getting Started Using RMI-IIOP.

Connecting IIOP stubs to the ORB

When your application uses IIOP stubs, as opposed to JRMP stubs, you need to properly connect the IIOP stubs with the ORB before invoking operations on the IIOP stubs (this is not necessary with JRMP stubs). This section discusses the extra 'connect' step required for the IIOP stub case.

The PortableRemoteObject.exportObject() call only creates a tie object and caches it for future usage. The created tie does not have a delegate or an ORB associated. This is known as explicit invocation.

The PortableRemoteObject.exportObject() happens automatically when the servant instance is created. This happens when a PortableRemoteObject constructor is called as a base class. This is known as implicit invocation.

Later, when PortableRemoteObject.toStub() is called by the application, it creates the corresponding Stub object and associates it with the cached Tie object. But since the Tie is not connected and does not have a delegate, the newly created stub also does not have a delegate or ORB.

The delegate is set for the stub only when the application calls Stub.connect(orb). Thus, any operations on the stub made before the ORB connection is made will fail.

The Java Language to IDL Mapping Specification says the following about the Stub.connect() method:

The connect method makes the stub ready for remote communication using the specified ORB object orb. Connection normally happens implicitly when the stub is received or sent as an argument on a remote method call, but it is sometimes useful to do this by making an explicit call (e.g., following deserialization). If the stub is already connected to orb (i.e., has a delegate set for orb), then connect takes no action. If the stub is connected to some other ORB, then a RemoteException is thrown. Otherwise, a delegate is created for this stub and the ORB object orb.

For servants that are not POA-activated, Stub.connect(orb) is necessary as a required setup.

Restrictions When Running RMI Programs Over IIOP

To make existing RMI programs run over IIOP, you need to observe the following restrictions.
  1. Make sure all constant definitions in remote interfaces are of primitive types or String and evaluated at compile time.
  2. Don't use Java names that conflict with IDL mangled names generated by the Java to IDL mapping rules. See section 28.3.2 of the Java Language to IDL Mapping specification for the Java to IDL name mapping rules.
  3. Don't inherit the same method name into a remote interface more than once from different base remote interfaces.
  4. Be careful when using names that differ only in case. The use of a type name and a variable of that type whose name differs from the type name only in case is supported. Most other combinations of names that differ only in case are not supported.
  5. Don't depend on runtime sharing of object references to be preserved exactly when transmitting object references across IIOP. Runtime sharing of other objects is preserved correctly.
  6. Don't use the following features of RMI:
    • RMISocketFactory
    • UnicastRemoteObject
    • Unreferenced
    • The Distributed Garbage Collection (DGC) interfaces

Other Things You Should Know

Servers Need to be Thread Safe

Since remote method invocation on the same remote object may execute concurrently, a remote object implementation needs to make sure its implementation is thread-safe.

Interoperating with Other ORBs

RMI-IIOP should interoperate with other ORBS that support the CORBA 2.3 specification. It will not interoperate with older ORBs, because these are unable to handle the IIOP encodings for Objects By Value. This support is needed to send RMI value classes (including strings) over IIOP.

NOTE: Although it is true that ORBs written in different languages should be able to talk to each other, we haven't tested the interoperability of the Java ORB with other vendor's ORBs.

When do I use UnicastRemoteObject vs PortableRemoteObject?

UnicastRemoteObject should be used as the superclass for the object implementation in RMI programming. PortableRemoteObject should be used in RMI-IIOP programming. If PortableRemoteObject is used, you can switch the transport protocol to either JRMP or IIOP during runtime.

Known Problems

  • JNDI 1.1 does not support java.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory as an Applet parameter. Instead, it must be explicitly passed as a property to the InitialContext constructor. This capability is supported in JNDI 1.2.
  • When running the Naming Service on Solaris, you must use a port number greater than 1024.
  • On Solaris, you may experience an "out of file descriptors" problem when running RMI-IIOP applications. This may occur if you are using too many file descriptors, which can happen because each JAR file in the classpath consumes one file descriptor and the JDK 1.1.6 setup adds numerous JAR files to the classpath. Before running applications, set the file descriptor limit to a number greater than its default value of 64. For example, set the ulimit number to 90 or higher, as follows:
  • ulimit -n 90

Background Reading

Here are some sites to get you up to speed with this technology:
  • The RMI-IIOP home page contains links to RMI-IIOP documentation, sample code, specifications, news, other related web sites, and more. Check it out!
  • The RMI-IIOP Tutorial gives a step-by-step example for creating and running a simple RMI-IIOP application.
  • The Java RMI home page contains links to RMI documentation, examples, specification, and more. Make sure you read this.
  • The RMI trail in the Java Tutorial.
  • The RMI API documentation.
  • The Java IDL web page will familiarize you with Sun's CORBA/IIOP implementation.
  • The Java IDL Tutorial is the newest version of the IDL trail from the Java Tutorial.
  • The Java Language to IDL Mapping, ptc/00-01-06 document is a detailed technical specification of RMI-IIOP. For further information on how the specification is implemented in this version of Java SE, see the compliance document.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


rmic - The Java RMI Compiler

rmic generates stub, skeleton, and tie classes for remote objects using either the JRMP or IIOP protocols. Also generates OMG IDL.

SYNOPSIS

rmic [ options ] package-qualified-class-name(s)

DESCRIPTION

The rmic compiler generates stub and skeleton class files (JRMP protocol) and stub and tie class files (IIOP protocol) for remote objects. These classes files are generated from compiled Java programming language classes that are remote object implementation classes. A remote implementation class is a class that implements the interface java.rmi.Remote. The class names in the rmic command must be for classes that have been compiled successfully with the javac command and must be fully package qualified. For example, running rmic on the class file name HelloImpl as shown here:
rmic hello.HelloImpl
creates the HelloImpl_Stub.class file in the hello subdirectory (named for the class's package).

A skeleton for a remote object is a JRMP protocol server-side entity that has a method that dispatches calls to the actual remote object implementation.

A tie for a remote object is a server-side entity similar to a skeleton, but which communicates with the client using the IIOP protocol.

A stub is a client-side proxy for a remote object which is responsible for communicating method invocations on remote objects to the server where the actual remote object implementation resides. A client's reference to a remote object, therefore, is actually a reference to a local stub.

By default, rmic generates stub classes that use the 1.2 JRMP stub protocol version only, as if the -v1.2 option had been specified. (Note that the -vcompat option was the default in releases prior to 5.0.) Use the -iiop option to generate stub and tie classes for the IIOP protocol.

A stub implements only the remote interfaces, not any local interfaces that the remote object also implements. Because a JRMP stub implements the same set of remote interfaces as the remote object itself, a client can use the Java programming language's built-in operators for casting and type checking. For IIOP, the PortableRemoteObject.narrow method must be used.

OPTIONS

-bootclasspath path
Overrides location of bootstrap class files
-classpath path
Specifies the path rmic uses to look up classes. This option overrides the default or the CLASSPATH environment variable if it is set. Directories are separated by semicolons. Thus the general format for path is:
.;<your_path>
For example:
.;C:\usr\local\java\classes
-d directory
Specifies the root destination directory for the generated class hierarchy. You can use this option to specify a destination directory for the stub, skeleton, and tie files. For example, the command
% rmic -d C:\java\classes foo.MyClass
would place the stub and skeleton classes derived from MyClass into the directory C:\java\classes\foo. If the -d option is not specified, the default behavior is as if "-d ." were specified: the package hierarchy of the target class is created in the current directory, and stub/tie/skeleton files are placed within it. (Note that in some previous versions of rmic, if -d was not specified, then the package hierarchy was not created, and all of the output files were placed directly in the current directory.)
-extdirs path
Overrides location of installed extensions
-g
Enables generation of all debugging information, including local variables. By default, only line number information is generated.
-idl
Causes rmic to generate OMG IDL for the classes specified and any classes referenced. IDL provides a purely declarative, programming language-independent way of specifying an object's API. The IDL is used as a specification for methods and data that can be written in and invoked from any language that provides CORBA bindings. This includes Java and C++ among others. See the Java Language to IDL Mapping (OMG) document for a complete description.

When the -idl option is used, other options also include:

-always or -alwaysgenerate
Forces re-generation even when existing stubs/ties/IDL are newer than the input class.
-factory
Uses factory keyword in generated IDL.
-idlModule fromJavaPackage[.class] toIDLModule
Specifies IDLEntity package mapping. For example: -idlModule foo.bar my::real::idlmod.
-idlFile fromJavaPackage[.class] toIDLFile
Specifies IDLEntity file mapping. For example: -idlFile test.pkg.X TEST16.idl.
-iiop
Causes rmic to generate IIOP stub and tie classes, rather than JRMP stub and skeleton classes. A stub class is a local proxy for a remote object and is used by clients to send calls to a server. Each remote interface requires a stub class, which implements that remote interface. A client's reference to a remote object is actually a reference to a stub. Tie classes are used on the server side to process incoming calls, and dispatch the calls to the proper implementation class. Each implementation class requires a tie class.

Invoking rmic with the -iiop generates stubs and ties that conform to this naming convention:

_<implementationName>_stub.class

_<interfaceName>_tie.class

When the -iiop option is used, other options also include:

-always or -alwaysgenerate
Forces re-generation even when existing stubs/ties/IDL are newer than the input class.
-nolocalstubs
Do not create stubs optimized for same-process clients and servers.
-noValueMethods
Must be used with the -idl option. Prevents addition of valuetype methods and initializers to emitted IDL. These methods and initializers are optional for valuetypes, and are generated unless the -noValueMethods option is specified when using the -idl option.
-poa
Changes the inheritance from org.omg.CORBA_2_3.portable.ObjectImpl to org.omg.PortableServer.Servant.

The PortableServer module for the Portable Object Adapter (POA) defines the native Servant type. In the Java programming language, the Servant type is mapped to the Java org.omg.PortableServer.Servant class. It serves as the base class for all POA servant implementations and provides a number of methods that may be invoked by the application programmer, as well as methods which are invoked by the POA itself and may be overridden by the user to control aspects of servant behavior. Based on the OMG IDL to Java Language Mapping Specification, CORBA V 2.3.1 ptc/00-01-08.pdf.

-J
Used in conjunction with any java option, it passes the option following the -J (no spaces between the -J and the option) on to the java interpreter.
-keep or -keepgenerated
Retains the generated .java source files for the stub, skeleton, and/or tie classes and writes them to the same directory as the .class files.
-nowarn
Turns off warnings. If used the compiler does not print out any warnings.
-nowrite
Does not write compiled classes to the file system.
-vcompat
Generates stub and skeleton classes compatible with both the 1.1 and 1.2 JRMP stub protocol versions. (This option was the default in releases prior to 5.0.) The generated stub classes will use the 1.1 stub protocol version when loaded in a JDK 1.1 virtual machine and will use the 1.2 stub protocol version when loaded into a 1.2 (or later) virtual machine. The generated skeleton classes will support both 1.1 and 1.2 stub protocol versions. The generated classes are relatively large in order to support both modes of operation.
-verbose
Causes the compiler and linker to print out messages about what classes are being compiled and what class files are being loaded.
-v1.1
Generates stub and skeleton classes for the 1.1 JRMP stub protocol version only. Note that this option is only useful for generating stub classes that are serialization-compatible with pre-existing, statically-deployed stub classes that were generated by the rmic tool from JDK 1.1 and that cannot be upgraded (and dynamic class loading is not being used).
-v1.2
(default) Generates stub classes for the 1.2 JRMP stub protocol version only. No skeleton classes are generated with this option because skeleton classes are not used with the 1.2 stub protocol version. The generated stub classes will not work if they are loaded into a JDK 1.1 virtual machine.

ENVIRONMENT VARIABLES

CLASSPATH
Used to provide the system a path to user-defined classes. Directories are separated by semicolons. For example,
.;C:\usr\local\java\classes

SEE ALSO

java, javac, CLASSPATH
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


rmid - The Java RMI Activation System Daemon

rmid starts the activation system daemon that allows objects to be registered and activated in a Java virtual machine (JVM).

SYNOPSIS

rmid [options]

DESCRIPTION

The rmid tool starts the activation system daemon. The activation system daemon must be started before activatable objects can be either registered with the activation system or activated in a JVM. See the RMI Specification and Activation tutorials for details on how to write programs that use activatable remote objects.

The daemon can be started by executing the rmid command, and specifying a security policy file, as follows:

    rmid -J-Djava.security.policy=rmid.policy

Note: When running Sun's implementation of rmid, by default you will need to specify a security policy file so that rmid can verify whether or not the information in each ActivationGroupDesc is allowed to be used to launch a JVM for an activation group. Specifically, the command and options specified by the CommandEnvironment and any Properties passed to an ActivationGroupDesc's constructor must now be explicitly allowed in the security policy file for rmid. The value of the sun.rmi.activation.execPolicy property dictates the policy that rmid uses to determine whether or not the information in an ActivationGroupDesc may be used to launch a JVM for an activation group.

Executing rmid by default

  • starts the Activator and an internal registry on the default port, 1098, and
  • binds an ActivationSystem to the name java.rmi.activation.ActivationSystem in this internal registry.
To specify an alternate port for the registry, you must specify the -port option when starting up rmid. For example,
    rmid -J-Djava.security.policy=rmid.policy -port 1099
starts the activation system daemon and a registry on the registry's default port, 1099.

OPTIONS

-C<someCommandLineOption>
Specifies an option that is passed as a command-line argument to each child process (activation group) of rmid when that process is created. For example, you could pass a property to each Java virtual machine spawned by the activation system daemon:
    rmid -C-Dsome.property=value
This ability to pass command-line arguments to child processes can be useful for debugging. For example, the following command:
    rmid -C-Djava.rmi.server.logCalls=true
will enable server-call logging in all child JVMs.

-J<someCommandLineOption>
Specifies an option that is passed to the java interpreter running rmid. For example, to specify that rmid use a policy file named rmid.policy, the -J option can be used to define the java.security.policy property on rmid's command line, for example:
    rmid -J-Djava.security.policy=rmid.policy
-J-Dsun.rmi.activation.execPolicy=<policy>
Specifies the policy that rmid employs to check commands and command-line options used to launch the JVM in which an activation group runs. Please note that this option exists only in Sun's implementation of the RMI activation daemon. If this property is not specified on the command line, the result is the same as if -J-Dsun.rmi.activation.execPolicy=default were specified. The possible values of <policy> can be default, <policyClassName>, or none:

  • default (or if this property is unspecified)

    The default execPolicy allows rmid to execute commands with specific command-line options only if rmid has been granted permission to execute those commands and options in the security policy file that rmid uses. Only the default activation group implementation can be used with the default execution policy.

    rmid launches a JVM for an activation group using the information in the group's registered activation group descriptor, an ActivationGroupDesc. The group descriptor specifies an optional ActivationGroupDesc.CommandEnvironment which includes the command to execute to start the activation group as well as any command line options to be added to the command line. By default, rmid uses the java command found in java.home. The group descriptor also contains properties overrides that are added to the command line as options defined as:

        -D<property>=<value>

    The permission com.sun.rmi.rmid.ExecPermission is used to grant rmid permission to execute a command, specified in the group descriptor's CommandEnvironment to launch an activation group. The permission com.sun.rmi.rmid.ExecOptionPermission is used to allow rmid to use command-line options, specified as properties overrides in the group descriptor or as options in the CommandEnvironment, when launching the activation group.

    When granting rmid permission to execute various commands and options, the permissions ExecPermission and ExecOptionPermission need to be granted universally (i.e., granted to all code sources).

    ExecPermission
    The ExecPermission class represents permission for rmid to execute a specific command to launch an activation group.

    Syntax
    The name of an ExecPermission is the path name of a command to grant rmid permission to execute. A path name that ends in "\*" indicates all the files contained in that directory (where "\" is the file-separator character, File.separatorChar). A path name that ends with "\-" indicates all files and subdirectories contained in that directory (recursively). A path name consisting of the special token "<<ALL FILES>>" matches any file.

    Note: A path name consisting of a single "*" indicates all the files in the current directory, while a path name consisting of a single "-" indicates all the files in the current directory and (recursively) all files and subdirectories contained in the current directory.

    ExecOptionPermission
    The ExecOptionPermission class represents permission for rmid to use a specific command-line option when launching an activation group. The name of an ExecOptionPermission is the value of a command line option.

    Syntax
    Options support a limited wildcard scheme. An asterisk signifies a wildcard match, and it may appear as the option name itself (i.e., it matches any option), or an asterisk may appear at the end of the option name only if the asterisk follows either a "." or "=".

    For example: "*" or "-Dfoo.*" or "-Da.b.c=*" is valid, "*foo" or "-Da*b" or "ab*" is not.

    Policy file for rmid
    When granting rmid permission to execute various commands and options, the permissions ExecPermission and ExecOptionPermission need to be granted universally (i.e., granted to all code sources). It is safe to grant these permissions universally because only rmid checks these permissions.

    An example policy file that grants various execute permissions to rmid is:

    grant {
    permission com.sun.rmi.rmid.ExecPermission
        "c:\\files\\apps\\java\\jdk1.7.0\\win\\bin\\java";

    permission com.sun.rmi.rmid.ExecPermission
        "c:\\files\\apps\\rmidcmds\\*";

    permission com.sun.rmi.rmid.ExecOptionPermission
        "-Djava.security.policy=c:\\files\\policies\\group.policy";

    permission com.sun.rmi.rmid.ExecOptionPermission
        "-Djava.security.debug=*";

    permission com.sun.rmi.rmid.ExecOptionPermission
        "-Dsun.rmi.*";
};
    The first permission granted allow rmid to execute the 1.7.0 version of the java command, specified by its explicit path name. Note that by default, the version of the java command found in java.home is used (the same one that rmid uses), and does not need to be specified in the policy file. The second permission allows rmid to execute any command in the directory c:\files\apps\rmidcmds\.

    The third permission granted, an ExecOptionPermission, allows rmid to launch an activation group that defines the security policy file to be c:\files\policies\group.policy. The next permission allows the java.security.debug property to be used by an activation group. The last permission allows any property in the sun.rmi property name hierarchy to be used by activation groups.

    To start rmid with a policy file, the java.security.policy property needs to be specified on rmid's command line, for example:

                      rmid -J-Djava.security.policy=rmid.policy

  • <policyClassName>

    If the default behavior is not flexible enough, an administrator can provide, when starting rmid, the name of a class whose checkExecCommand method is executed in order to check commands to be executed by rmid.

    The policyClassName specifies a public class with a public, no-argument constructor and an implementation of the following checkExecCommand method:

        public void checkExecCommand(ActivationGroupDesc desc,
                                 String[] command)
        throws SecurityException;
    Before launching an activation group, rmid calls the policy's checkExecCommand method, passing it the activation group descriptor and an array containing the complete command to launch the activation group. If the checkExecCommand throws a SecurityException, rmid will not launch the activation group and an ActivationException will be thrown to the caller attempting to activate the object.

  • none

    If the sun.rmi.activation.execPolicy property value is "none", then rmid will not perform any validation of commands to launch activation groups.

-log dir
Specifies the name of the directory the activation system daemon uses to write its database and associated information. The log directory defaults to creating a directory, log, in the directory in which the rmid command was executed.

-port port
Specifies the port rmid's registry uses. The activation system daemon binds the ActivationSystem, with the name java.rmi.activation.ActivationSystem, in this registry. Thus, the ActivationSystem on the local machine can be obtained using the following Naming.lookup method call:
    import java.rmi.*;
    import java.rmi.activation.*;

    ActivationSystem system; system = (ActivationSystem)
    Naming.lookup("//:port/java.rmi.activation.ActivationSystem");
-stop
Stops the current invocation of rmid, for a port specified by the -port option. If no port is specified, it will stop the rmid running on port 1098.

ENVIRONMENT VARIABLES

CLASSPATH
Used to provide the system a path to user-defined classes. Directories are separated by colons on UNIX and Macintosh and by semicolons on Win95. For example:
    .;C:\usr\local\java\classes

SEE ALSO

rmic, CLASSPATH, java

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Configuring inetd to Launch rmid

On the Solaris Operating System (Solaris OS), the Internet services daemon inetd provides an alternative to starting up services at system boot time. This daemon, a server process for Internet standard services, can be configured to start services on demand. For details on the Internet services daemon, see the Solaris OS inetd(1M) man page.

As of the J2SE(tm) 5.0 release, inetd can be configured to start the Java RMI activation daemon rmid on demand. In this case, rmid does not need to be started up at boot time or started up manually. Instead, rmid will be started when a client attempts to connect to it, such as in order to activate an object.

Note: If restartable services are registered with rmid, rmid should be started at system boot type (not by inetd) so that the restartable services are always running when the system is up.

To configure inetd to launch rmid, you will need to add an entry to each of two configuration files that inetd uses, /etc/inetd.conf and /etc/services. Editing these files requires root access to the machine that rmid will run on.

After inetd has been reconfigured, you should test your configuration to make sure that it works properly.

This tutorial has the following steps:

  • Configure /etc/inetd.conf
  • Configure /etc/services
  • Force inetd to read its new configuration
  • Test your configuration

Configure /etc/inetd.conf

The /etc/inetd.conf configuration file contains entries for the services to be launched when inetd receives a request over a socket. For details on the format of this configuration file see the Solaris OS inetd.conf(4) man page.

To configure inetd to launch rmid, add the following entry to the /etc/inetd.conf configuration file (requires root access to the machine):

rmid stream tcp wait nobody jreHome/bin/rmid  \
     rmid -log logDir/rmid.log rmidOptions
where jreHome is a path to the installed JRE, logDir is the directory for the log file, and rmidOptions is any other options for rmid (for example, property initializations). When rmid is launched by inetd the -log option must be specified, and the -port option must not be specified, since the port is derived from the /etc/services configuration.

If rmid needs to be run as a user other than nobody, replace nobody above with the user ID under which rmid should run.

Configure /etc/services

Next, rmid needs to be listed as a service in the /etc/services configuration file. For details on the format of this configuration file see the Solaris OS services(4) man page.

To list rmid as a service, add the following entry to the /etc/services configuration file (requires root access to the machine):

rmid        port/tcp

where port is the port number for the ActivationSystem and the Activator remote objects that rmid exports. This port number is typically 1098, but another port number can be used as long as the clients and activatable services define the system property java.rmi.activation.port to that port.

Force inetd to read its new configuration

Now that the configuration has been modified, inetd needs to read the new configuration so that it can listen on the appropriate ports for the services that are configured.

But first, it is important to make sure that rmid is not already running. To do this, run the following command:

% ps -ef | grep rmid

If the above command does not print out the information for a running rmid process, then rmid is not running. If it does, then you will need to shut down rmid first before continuing.

Next, inetd needs to read its new configuration. To force inetd to reread its configuration, the running inetd process must be sent a hangup signal. First, find the process ID for the running inetd process by running the following command:

% ps -ef | grep inetd

which will print out something like this:

root   171     1  0   Sep 30 ?        0:02 /usr/sbin/inetd -s

In this example, the process ID for inetd is 171. Now, the inetd process can be sent a hangup signal by running the following command and supplying the process ID (requires root access):

% kill -HUP 171

Now, inetd is all set to launch rmid when a program attempts to connect to the port configured above.

Test your configuration

To test that inetd is configured properly, you can run a simple program that looks up the ActivationSystem which will, in turn, cause inetd to launch rmid if the configuration is correct.

The following is a simple program to look up the ActivationSystem on a port, supplied as the value of the java.rmi.activation.port system property:

package example.inetd;

import java.rmi.activation.ActivationSystem;
import java.rmi.activation.ActivationGroup;

public class GetActivationSystem {

    public static void main(String[] args) throws Exception {

        ActivationSystem system = ActivationGroup.getSystem();
        System.err.println("ActivationSystem = " + system);
    }
}

Compile and run this program as follows:

% javac -d classDir GetActivationSystem.java
% java -classpath classDir -Djava.rmi.activation.port=port
example.inetd.GetActivationSystem
where classDir is the class path for this example class, and port is the port for the ActivationSystem configured for rmid in the /etc/services file.

If the program prints out the ActivationSystem successfully then rmid was launched by inetd.

If the program either hangs or prints an exception trace, check the output file produced by rmid. When rmid is launched by inetd, any output written to System.err is written to a file located in the directory specified by the property java.io.tmpdir, typically /var/tmp on the Solaris OS. The output file is prefixed with "rmid-err" and has the suffix of ".tmp". The file name also contains other characters (typically numbers) in between to keep the file name unique.

If rmid starts up successfully from inetd, the output file should contain text similar to the following (with no warning or error messages):

Tue Sep 30 13:07:38 EDT 2003
rmid startup with inherited channel: sun.nio.ch.ServerSocketChannelImpl[/129.148.70.120:1098]

If the file does not exist, the above text is not in the file, or additional error output is in the file, then recheck the configuration. Upon changing the inetd configuration, remember to send inetd a hangup signal so that it rereads its altered configuration, and remember to terminate any rmid process started from the previous attempt before continuing.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Getting Started Using RMI-IIOP: POA Model

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Getting Started Using RMI-IIOP:
Example Using POA-based server-side model

This tutorial shows you the steps to follow to create a distributed version of the classic "Hello World" program using Java™ Remote Method Invocation (RMI) over Internet Inter-ORB Protocol (IIOP). RMI-IIOP adds CORBA (Common Object Request Broker Architecture) capability to Java connectivity to many other programming languages and platforms. RMI-IIOP enables distributed Web-enabled Java remote Management Group. Runtime components include a Java ORB for distributed computing using IIOP communication.

RMI-IIOP is for Java programmers who want to program to the RMI interfaces, but use IIOP as the underlying transport. RMI-IIOP provides interoperability with other CORBA objects implemented in various languages - but only if all the remote interfaces are originally defined as Java RMI interfaces. It is of particular interest to programmers using Enterprise JavaBeans (EJB), since the remote object model for EJBs is RMI-based.

Another option for creating distributed applications is Java™ IDL. Java IDL is for CORBA programmers who want to program in the Java programming language based on interfaces defined in CORBA Interface Definition Language (IDL). This is "business as usual" CORBA programming, supporting Java in exactly the same way as other languages like C++ or COBOL.

Tutorial: The Hello World Application

The distributed Hello World example uses a client application to make a remote method call via IIOP to a server, running on the host from which the client was downloaded. When the client runs, "Hello World!" is displayed.

This tutorial is organized as follows:

  1. The steps to write the source files
  2. The steps to compile the class files
  3. The steps to start the Naming Service, server, and client

Write or Download the Source Files

There are three tasks to complete in this section:

  1. Define the functions of the remote class as an interface written in the Java programming language
  2. Write the implementation class
  3. Write the server class
  4. Write a client program that uses the remote service
The source files created in this tutorial (and which can be downloaded here) are:
  • HelloInterface.java - a remote interface
  • HelloImpl.java - a remote object implementation that implements HelloInterface
  • HelloServer.java - an RMI server that creates an instance of the remote object implementation and binds that instance to a name in the Naming Service
  • HelloClient.java - a client application that invokes the remote method, sayHello()

Define the functions of the remote class as an interface written in the Java programming language

In the Java programming language, a remote object is an instance of a class that implements a Remote interface. Your remote interface will declare each of the methods that you would like to call from other machines. Remote interfaces have the following characteristics:
  • The remote interface must be declared public. Otherwise, a client will get an error when attempting to load a remote object that implements the remote interface, unless that client is in the same package as the remote interface.
  • The remote interface extends the java.rmi.Remote interface.
  • Each method must declare java.rmi.RemoteException (or a superclass of RemoteException) in its throws clause, in addition to any application-specific exceptions.
  • The data type of any remote object that is passed as an argument or return value (either directly or embedded within a local object) must be declared as the remote interface type (for example, HelloInterface) not the implementation class (HelloImpl).

For this example, create all of the source files in the same directory, for example, $HOME/mysrc/RMIHelloPOA. Here is the interface definition for the remote interface, HelloInterface. The interface contains just one method, sayHello:

//HelloInterface.java
import java.rmi.Remote;

public interface HelloInterface extends java.rmi.Remote {
  public void sayHello() throws java.rmi.RemoteException;
}
Because remote method invocations can fail in very different ways from local method invocations (due to network-related communication problems and server problems), remote methods will report communication failures by throwing a java.rmi.RemoteException. If you want more information on failure and recovery in distributed systems, you may wish to read A Note on Distributed Computing.

Write The Implementation Class

At a minimum, a remote object implementation class, HelloImpl.java must:

  • Declare that it implements at least one remote interface
  • Define the constructor for the remote object
  • Provide implementations for the methods that can be invoked remotely
An explanation of each of the preceding steps follows the source for HelloImpl.java:
//HelloImpl.java
import javax.rmi.PortableRemoteObject;

public class HelloImpl extends PortableRemoteObject implements HelloInterface {
  public HelloImpl() throws java.rmi.RemoteException {
    super();     // invoke rmi linking and remote object initialization
  }

  public void sayHello() throws java.rmi.RemoteException {
    System.out.println( "It works!  Hello World!!" );
  }
}

Implement a remote interface

In the Java programming language, when a class declares that it implements an interface, a contract is formed between the class and the compiler. By entering into this contract, the class is promising that it will provide method bodies, or definitions, for each of the method signatures declared in that interface. Interface methods are implicitly public and abstract, so if the implementation class doesn't fulfill its contract, it becomes by definition an abstract class, and the compiler will point out this fact if the class was not declared abstract.

The implementation class in this example is HelloImpl. The implementation class declares which remote interface(s) it is implementing. Here is the HelloImpl class declaration:

  public class HelloImpl extends PortableRemoteObject
    implements HelloInterface{
As a convenience, the implementation class can extend a remote class, which in this example is javax.rmi.PortableRemoteObject. By extending PortableRemoteObject, the HelloImpl class can be used to create a remote object that uses IIOP-based transport for communication.

Define the constructor for the remote object

The constructor for a remote class provides the same functionality as the constructor for a non-remote class: it initializes the variables of each newly created instance of the class, and returns an instance of the class to the program which called the constructor.

In addition, the remote object instance will need to be "exported". Exporting a remote object makes it available to accept incoming remote method requests, by listening for incoming calls to the remote object on an anonymous port. When you extend javax.rmi.PortableRemoteObject, your class will be exported automatically upon creation.

Because the object export could potentially throw a java.rmi.RemoteException, you must define a constructor that throws a RemoteException, even if the constructor does nothing else. If you forget the constructor, javac will produce the following error message:

        HelloImpl.java:3: unreported exception java.rmi.RemoteException; must be
        caught or declared to be thrown.

        public class HelloImpl extends PortableRemoteObject implements HelloInterface{
               ^
        1 error
To review: The implementation class for a remote object needs to:
  • Implement a remote interface
  • Export the object so that it can accept incoming remote method calls
  • Declare its constructor(s) to throw at least a java.rmi.RemoteException
Here is the constructor for the HelloImpl class:
  public HelloImpl() throws java.rmi.RemoteException {
    super();
  }
Note the following:
  • The super method call invokes the no-argument constructor of javax.rmi.PortableRemoteObject, which exports the remote object.
  • The constructor must throw java.rmi.RemoteException, because RMI's attempt to export a remote object during construction might fail if communication resources are not available.

java.rmi.RemoteException is a checked exception, not a runtime exception.

Although the call to the superclass's no-argument constructor, super(), occurs by default (even if omitted), it is included in this example to make clear the fact that the superclass will be constructed before the class.

Provide an implementation for each remote method

The implementation class for a remote object contains the code that implements each of the remote methods specified in the remote interface. For example, here is the implementation for the sayHello() method, which returns the string "It works! Hello World!!" to the caller:
  public void sayHello() throws java.rmi.RemoteException {
    System.out.println( "It works!  Hello World!!" );
  }
Arguments to, or return values from, remote methods can be any data type for the Java platform, including objects, as long as those objects implement the interface java.io.Serializable. Most of the core classes in java.lang and java.util implement the Serializable interface. In RMI:
  • By default, local objects are passed by copy, which means that all data members (or fields) of an object are copied, except those marked as static or transient.
  • Remote objects are passed by reference. A reference to a remote object is actually a reference to a stub, which is a client-side proxy for the remote object. We'll create stubs later in this tutorial in the section: Use rmic to generate stubs and skeletons.

Write The Server Class

A server class is the class which has a main method that creates an instance of the remote object implementation, and binds that instance to a name in the Naming Service. The class that contains this main method could be the implementation class itself, or another class entirely.

In this example, the main method is part of HelloServer.java, which does the following:

  • Creates a Portable Object Adapter (POA) with the appropriate policies
  • Activates the POA Managers
  • Creates an instance of the servant and activates the Tie, creates an instance of a remote object
  • Publishes the object reference
  • Prepares to accept requests from the client
An explanation of each of the preceding steps follows the source for HelloServer.java:
//HelloServer.java
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.rmi.PortableRemoteObject ;
//Please note that internal Sun APIs
//may change in future releases.
import com.sun.corba.se.internal.POA.POAORB;
import org.omg.PortableServer.*;
import java.util.*;
import org.omg.CORBA.*;
import javax.rmi.CORBA.Stub;
import javax.rmi.CORBA.Util;

public class HelloServer {
  public HelloServer(String[] args) {
    try {
      Properties p = System.getProperties();
      // add runtime properties here
      //Please note that the name of the servertool
      //class may change in future releases.
      p.put("org.omg.CORBA.ORBClass",
          "com.sun.corba.se.internal.POA.POAORB");
      p.put("org.omg.CORBA.ORBSingletonClass",
          "com.sun.corba.se.internal.corba.ORBSingleton");

      ORB orb = ORB.init( args, p );

      POA rootPOA = (POA)orb.resolve_initial_references("RootPOA");

      // STEP 1: Create a POA with the appropriate policies
      Policy[] tpolicy = new Policy[3];
      tpolicy[0] = rootPOA.create_lifespan_policy(
        LifespanPolicyValue.TRANSIENT );
      tpolicy[1] = rootPOA.create_request_processing_policy(
        RequestProcessingPolicyValue.USE_ACTIVE_OBJECT_MAP_ONLY );
      tpolicy[2] = rootPOA.create_servant_retention_policy(
        ServantRetentionPolicyValue.RETAIN);
      POA tPOA = rootPOA.create_POA("MyTransientPOA", null, tpolicy);

      // STEP 2: Activate the POA Manager, otherwise all calls to the
      // servant hang because, by default, POAManager will be in the
      // HOLD state.
      tPOA.the_POAManager().activate();

      // STEP 3: Instantiate the Servant and activate the Tie, If the
      // POA policy is USE_ACTIVE_OBJECT_MAP_ONLY
      HelloImpl helloImpl = new HelloImpl();
      _HelloImpl_Tie tie = (_HelloImpl_Tie)Util.getTie( helloImpl );
      String helloId = "hello";
      byte[] id = helloId.getBytes();
      tPOA.activate_object_with_id( id, tie );

      // STEP 4: Publish the object reference using the same object id
      // used to activate the Tie object.
      Context initialNamingContext = new InitialContext();
      initialNamingContext.rebind("HelloService",
        tPOA.create_reference_with_id(id,
          tie._all_interfaces(tPOA,id)[0]) );
      System.out.println("Hello Server: Ready...");

      // STEP 5: Get ready to accept requests from the client
      orb.run();
    }
      catch (Exception e) {
        System.out.println("Problem running HelloServer: " + e);
        e.printStackTrace();
      }
  }

  public static void main(String args[]) {
    new HelloServer( args );
  }
}

Create a Portable Object Adapter (POA) with the appropriate policies

The main method of the server first needs to create a Portable Object Adapter (POA) with the appropriate policies. For example:
      Policy[] tpolicy = new Policy[3];
      tpolicy[0] = rootPOA.create_lifespan_policy(
        LifespanPolicyValue.TRANSIENT );
      tpolicy[1] = rootPOA.create_request_processing_policy(
        RequestProcessingPolicyValue.USE_ACTIVE_OBJECT_MAP_ONLY );
      tpolicy[2] = rootPOA.create_servant_retention_policy(
        ServantRetentionPolicyValue.RETAIN);
      POA tPOA = rootPOA.create_POA("MyTransientPOA", null, tpolicy);

The Portable Object Adaptor (POA) is designed to provide an object adapter that can be used with multiple ORB implementations with a minimum of rewriting needed to deal with different vendors' implementations. POA support was introduced in J2SE version 1.4.

The POA is also intended to allow persistent objects -- at least, from the client's perspective. That is, as far as the client is concerned, these objects are always alive, and maintain data values stored in them, even though physically, the server may have been restarted many times, or the implementation may be provided by many different object implementations.

The POA allows the object implementor a lot more control. Previously, the implementation of the object was responsible only for the code that is executed in response to method requests. Now, additionally, the implementor has more control over the object's identity, state, storage, and lifecycle.

In this example, the policy values include:

  • The LifespanPolicyValue can have the following values:
    • TRANSIENT - The objects implemented in the POA cannot outlive the POA instance in which they are first created.
    • PERSISTENT - The objects implemented in the POA can outlive the process in which they are first created.
  • The RequestProcessingPolicyValue can have the following values:
    • USE_ACTIVE_OBJECT_MAP_ONLY - If the object ID is not found in the Active Object Map, an OBJECT_NOT_EXIST exception is returned to the client. The RETAIN policy is also required.
    • USE_DEFAULT_SERVANT - If the object ID is not found in the Active Object Map or the NON_RETAIN policy is present, and a default servant has been registered with the POA using the set_servant operation, the request is dispatched to the default servant.
    • USE_SERVANT_MANAGER - If the object ID is not found in the Active Object Map or the NON_RETAIN policy is present, and a servant manager has been registered with the POA using the set_servant_manager operation, the servant manager is given the opportunity to locate a servant or raise an exception.
  • The ServantRetentionPolicyValue can have the following values.
    • RETAIN - to indicate that the POA will retain active servants in its Active Object Map. If no ServantRetentionPolicy is specified at POA creation, the default is RETAIN.
    • NON_RETAIN - to indicate Servants are not retained by the POA.

For more information on POA policies, refer to Chapter 11, Portable Object Adapter of the CORBA/IIOP 2.3.1 Specification at http://www.omg.org/cgi-bin/doc?formal/99-10-07

Activate the POA Managers

Each POA object has an associated POAManager object. A POA Manager may be associated with one or more POA objects. A POA Manager encapsulates the processing state of the POAs it is associated with. In this step, the POA Manager is activated. If this step is missing, all calls to the Servant would hang because, by default, the POA Manager will be in the HOLD state.

      tPOA.the_POAManager().activate();

Create an instance of a remote object and activate the Tie

The main method of the server needs to create an instance of the remote object implementation, or Servant. For example:
    HelloImpl helloImpl = new HelloImpl();
The constructor exports the remote object, which means that once created, the remote object is ready to accept incoming calls.

When using RMI-IIOP technology, your implementations use delegation (known as the Tie model) to associate your implementation with the interface. When you create an instance of your implementation, as above, you also need to create a Tie object to associate it with a CORBA interface. The next few lines of code activate the Tie, but only if the POA policy is USE_ACTIVE_OBJECT_MAP_ONLY.

      _HelloImpl_Tie tie = (_HelloImpl_Tie)Util.getTie( helloImpl );
      String helloId = "hello";
      byte[] id = helloId.getBytes();
      tPOA.activate_object_with_id( id, tie );

Publish the object reference using the same object id used to activate the Tie object

For a caller (client, peer, or client application) to be able to invoke a method on a remote object, that caller must first obtain a reference to the remote object.

Once a remote object is registered on the server, callers can look up the object by name (using a naming service), obtain a remote object reference, and then remotely invoke methods on the object. In this example, we use the Object Request Broker Daemon (orbd), which is a daemon process containing a Bootstrap Service, a Transient Naming Service, a Persistent Naming Service, and a Server Manager.

For example, the following code binds the name "HelloService" to a reference for the remote object:

      Context initialNamingContext = new InitialContext();
      initialNamingContext.rebind("HelloService",
        tPOA.create_reference_with_id(id,
          tie._all_interfaces(tPOA,id)[0]) );
      System.out.println("Hello Server: Ready...");

Note the following about the arguments to the rebind method call:

  • The first argument, "HelloService", is a java.lang.String, representing the name of the remote object to bind
  • The second argument, tPOA.create_reference_with_id(id, tie._all_interfaces(tPOA,id)[0] is the object id of the remote object to bind

Prepare to accept requests from the client

The following line of code, when called by the main thread, enables the ORB to perform work using the main thread.
      orb.run();

Write a client program that uses the remote service

The client application in this example remotely invokes the sayHello method in order to get the string "Hello World!" to display when the client application runs. Here is the code for the client application:

//HelloClient.java
import java.rmi.RemoteException;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import javax.rmi.*;
import java.util.Vector;
import javax.naming.NamingException;
import javax.naming.InitialContext;
import javax.naming.Context;

public class HelloClient {

  public static void  main( String args[] ) {
    Context ic;
    Object objref;
    HelloInterface hi;

    try {
      ic = new InitialContext();
    } catch (NamingException e) {
        System.out.println("failed to obtain context" + e);
        e.printStackTrace();
        return;
    }

    // STEP 1: Get the Object reference from the Name Service
    // using JNDI call.
    try {
      objref = ic.lookup("HelloService");
      System.out.println("Client: Obtained a ref. to Hello server.");
    } catch (NamingException e) {
        System.out.println("failed to lookup object reference");
        e.printStackTrace();
        return;
    }

    // STEP 2: Narrow the object reference to the concrete type and
    // invoke the method.
    try {
      hi = (HelloInterface) PortableRemoteObject.narrow(
        objref, HelloInterface.class);
      hi.sayHello();
    } catch (ClassCastException e) {
        System.out.println("narrow failed");
        e.printStackTrace();
        return;
      } catch( Exception e ) {
            System.err.println( "Exception " + e + "Caught" );
            e.printStackTrace( );
            return;
        }
  }
}

First, the client application gets a reference to the remote object implementation (advertised as "HelloService") from the Name Service using Java Naming and Directory Interface [TM] (JNDI) calls. Like the Naming.rebind method, the Naming.lookup method takes java.lang.String value representing the name of the object to look up. You supply Naming.lookup() the name of the object you want to look up, and it returns the object bound to that name.

  • Naming.lookup() takes care of these tasks:
    • The Name Service returns the _HelloImpl_Stub instance bound to that name
    • The lookup method receives the remote object's (HelloImpl) stub instance and loads the stub class (_HelloImpl_Stub)
    • Naming.lookup returns the stub to its caller (HelloClient)
  • The client application invokes the remote sayHello() method on the server's remote object, causing the string "It works! Hello World!!" to be displayed on the command line.

Compile Class Files

The source code for this example is now complete and the directory contains four files:
  • HelloInterface.java contains the source code for the remote interface
  • HelloImpl.java contains the source code for the remote object implementation
  • HelloServer.java contains the source code for the server
  • HelloClient.java contains the source code for the client application
In this section, you compile the remote object implementation file, HelloImpl.java, in order to create the .class files needed to run rmic. You then run the rmic compiler to create stubs and skeletons. A stub is a client-side proxy for a remote object which forwards RMI-IIOP calls to the server-side dispatcher, which in turn forwards the call to the actual remote object implementation. The last task is to compile the remaining .java source files to create .class files.

The following tasks will be completed in this section:

  1. Compile the remote object implementation
  2. Use rmic to generate stubs and skeletons
  3. Compile the source files

Compile the remote object implementation

To create stub and skeleton files, the rmic compiler must be run on the fully-qualified package names of compiled class files that contain remote object implementations. In this example, the file that contains the remote object implementations is HelloImpl.java. In order to generate the stubs and skeletons, we must first compile HelloImpl.java, as follows:

    javac -d . -classpath . HelloImpl.java

The "-d ." option indicates that the generated files should be placed in the directory from which you are running the compiler. The "-classpath ." option indicates that files on which HelloImpl.java is dependent can be found in this directory.

Use rmic to generate skeletons and stubs

To create CORBA-compatible stub and skeleton files, run the rmic compiler with the -poa -iiop option. The rmic -poa -iiop command takes one or more class names as an argument and produces class files of the form _MyImpl_Tie.class and _MyInterface_Stub.class. The remote implementation file, HelloImpl.class, is the class name to pass in this example.

For an explanation of rmic options, refer to the Solaris Operating Environment rmic manual page or the Microsoft Windows rmic manual page.

To create the stub and skeleton for the HelloImpl remote object implementation, run rmic like this:

    rmic -poa -iiop HelloImpl

The preceding command creates the following files:

  • _HelloInterface_Stub.class - the client stub
  • _HelloImpl_Tie.class - the server skeleton

Compile the source files

To compile the source files, run the javac command as follows:

    javac -d . -classpath . HelloInterface.java HelloServer.java HelloClient.java

This command creates the class files HelloInterface.class, HelloServer.class, and HelloClient.class. These are the remote interface, the server, and the client application respectively. For an explanation of javac options, you can refer to the Solaris javac manual page or the Microsoft Windows javac manual page.

Start the Naming Service, server, and client application

The following tasks will be completed in this section:
  1. Start the Naming Service
  2. Start the server
  3. Run the client application

Start the Naming Service

For this example, we will use the Object Request Broker Daemon, orbd, which includes both a Transient and a Persistent Naming Service, and is available with every download of J2SE 1.4 and higher.

For a caller (client, peer, or client application) to be able to invoke a method on a remote object, that caller must first obtain a reference to the remote object.

Once a remote object is registered on the server, callers can look up the object by name, obtain a remote object reference, and then remotely invoke methods on the object.

To start the Naming Service, run orbd from the command line. This command produces no output and is typically run in the background. For more on the orbd tool, you can refer to the orbd manual page.

For this example, on the Solaris operating system:

    orbd -ORBInitialPort 1060&

or, on the Microsoft Windows operating system:

    start orbd -ORBInitialPort 1060

You must specify a port on which to run orbd. For this example the port of 1060 is chosen because in the Solaris operating environment, a user must become root to start a process on a port under 1024.

You must stop and restart the server any time you modify a remote interface or use modified/additional remote interfaces in a remote object implementation. Otherwise, the type of the object reference bound in the Naming Service will not match the modified class.

Start the server

Open another terminal window and change to the directory containing the source files for this example. The command for running the client has been spread out below to make it easier to read, but should be typed without returns between the lines. The following command shows how to start the HelloServer server. Of course, if you used a port other than 1060 or a host other than localhost when starting the orbd tool, replace those values in the command below with the actual values used to start orbd.

    java
      -classpath .
      -Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory
      -Djava.naming.provider.url=iiop://localhost:1060
      HelloServer

For an explanation of java options, you can refer to the Solaris java manual page or the Microsoft Windows java manual page.

The output should look like this:

Hello Server: Ready ...

Run the client application

Once the Naming Service and server are running, the client application can be run. From a new terminal window, go to the source code directory, and run the client application from the command line, as shown below. The command for running the client has been spread out below to make it easier to read, but should be typed without returns between the lines. Of course, if you used a port other than 1060 or a host other than localhost when starting the orbd tool, replace those values in the command below with the actual values used to start orbd.
    java
      -classpath .
      -Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory
      -Djava.naming.provider.url=iiop://localhost:1060
      HelloClient
After running the client application, you will see output similar to the following in your terminal window or command prompt window:
Client: Obtained a ref. to Hello server.

The server window will return the following message:

It works! Hello World!!

This completes the tutorial. If you are ready to move on to more complicated applications, here are some sources that may help:

  • http://forum.java.sun.com/forum.jsp?forum=59, The Sun Developer's Forum for RMI-IIOP. You must register with the Java Developer Connection to access this site.
  • EJB clients interact with the J2EE EJB tier using the RMI-IIOP protocol. For more information on using RMI-IIOP in this way, see the Java 2 Platform, Enterprise Edition Blueprints or the EJB Tutorials.
  • The Java IDL tutorial includes an example for running the client and server on different machines. The concepts of Running the Hello World Example on Two Machines apply to this example as well.
-->


When should I use RMI-IIOP?

RMI-IIOP is for developers who program in the Java programming language and want to program to the RMI interfaces, but use IIOP as the underlying transport. RMI-IIOP provides interoperability with other CORBA objects implemented in various languages - but only if all the remote interfaces are originally defined as Java RMI interfaces. It is of particular interest to programmers using Enterprise JavaBeansTM (EJBTM), since the remote object model for EJB components is based on the RMI API.

RMI-IIOP combines the best features of Java Remote Method Invocation (RMI) with the best features of CORBA. RMI-IIOP speeds distributed application development by allowing developers to work completely in the Java programming language, writing remote interfaces in the Java programming language and implementing them simply using Java technology and the Java RMI APIs.

When using RMI-IIOP to produce technology-based distributed applications written in the Java programming language, there is no separate Interface Definition Language (IDL) or mapping to learn: the remote interfaces can be implemented in any other language that is supported by an OMG mapping and a vendor supplied ORB for that language. Similarly, clients can be written in other languages using IDL derived from the remote Java technology-based interfaces.

RMI-IIOP provides flexibility by allowing developers to pass any Java object between application components either by reference or by value.

Like CORBA, RMI-IIOP is based on open standards defined with the participation of hundreds of vendors and users in the Object Management Group. Like CORBA, RMI-IIOP uses Internet Inter-ORB Protocol (IIOP) as its communication protocol. IIOP eases legacy application and platform integration by allowing application components written in C++, Smalltalk, and other CORBA supported languages to communicate with components running on the Java platform.

What other options do I have for distributed application development?

Developers who program using the JavaTM programming language can choose several solutions for creating distributed applications programs.

  • JavaTM RMI technology - If all of your applications are written in the Java programming language, you will probably want to use Java RMI technology to enable communication between Java objects on different virtual machines and different physical machines. Using Java RMI technology without its IIOP option leverages its strengths of code portability, security, and garbage collection.
  • JavaTM IDL technology - Java IDL technology are for CORBA programmers who want to program in the Java programming language based on interfaces defined in CORBA Interface Definition Language (IDL). This is "business as usual" CORBA programming, supporting the Java platform in exactly the same way as other languages like C++ or COBOL.
  • Enterprise JavaBeansTM technology - Enterprise JavaBeansTM (EJBTM) technology is part of the Java 2 Platform, Enterprise Edition. EJB components use the Java RMI/Java IDL technology for their distributed object model, and use the Java Transaction Service (JTS) for their distributed transaction model. When Enterprise JavaBeans components are implemented using the RMI-IIOP protocol for EJB component interoperability in heterogeneous server environments, the standard mapping of the EJB architecture to CORBA enables interoperability with multivendor ORBs, other EJB servers, and CORBA clients written in programming languages other than the Java programming language. For an example application that uses an EJB server with a CORBA client, look at Enterprise JavaBeans Components and CORBA Clients.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


rmiregistry - The Java Remote Object Registry

The rmiregistry command starts a remote object registry on the specified port on the current host.

SYNOPSIS

rmiregistry [port]

DESCRIPTION

The rmiregistry command creates and starts a remote object registry on the specified port on the current host. If port is omitted, the registry is started on port 1099. The rmiregistry command produces no output and is typically run in the background. For example:

start rmiregistry

A remote object registry is a bootstrap naming service that is used by RMI servers on the same host to bind remote objects to names. Clients on local and remote hosts can then look up remote objects and make remote method invocations.

The registry is typically used to locate the first remote object on which an application needs to invoke methods. That object in turn will provide application-specific support for finding other objects.

The methods of the java.rmi.registry.LocateRegistry class are used to get a registry operating on the local host or local host and port.

The URL-based methods of the java.rmi.Naming class operate on a registry and can be used to look up a remote object on any host, and on the local host: bind a simple (string) name to a remote object, rebind a new name to a remote object (overriding the old binding), unbind a remote object, and list the URLs bound in the registry.

OPTIONS

-J
Used in conjunction with any java option, it passes the option following the -J (no spaces between the -J and the option) on to the java interpreter.

SEE ALSO

java command, java.rmi.registry.LocateRegistry and java.rmi.Naming

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Remote Method Invocation: - Contents

CONTENTS | PREV | NEXT Java Remote Method Invocation

Table of Contents

1 Introduction

1.1 Background
1.2 System Goals

2 Java Distributed Object Model

2.1 Distributed Object Applications
2.2 Definition of Terms
2.3 The Distributed and Nondistributed Models Contrasted
2.4 Overview of RMI Interfaces and Classes
2.5 Implementing a Remote Interface
2.6 Parameter Passing in Remote Method Invocation
2.7 Locating Remote Objects

3 RMI System Overview

3.1 Stubs and Skeletons
3.2 Thread Usage in Remote Method Invocations
3.3 Garbage Collection of Remote Objects
3.4 Dynamic Class Loading
3.5 RMI Through Firewalls Via Proxies

4 Client Interfaces

4.1 The Remote Interface
4.2 The RemoteException Class
4.3 The Naming Class

5 Server Interfaces

5.1 The RemoteObject Class
5.2 The RemoteServer Class
5.3 The UnicastRemoteObject Class
5.4 The Unreferenced Interface
5.5 The RMISecurityManager Class
5.6 The RMIClassLoader Class
5.7 The LoaderHandler Interface
5.8 RMI Socket Factories
5.9 The RMIFailureHandler Interface
5.10 The LogStream Class
5.11 Stub and Skeleton Compiler

6 Registry Interfaces

6.1 The Registry Interface
6.2 The LocateRegistry Class
6.3 The RegistryHandler Interface

7 Remote Object Activation

7.1 Overview
7.2 Activation Protocol
7.3 Implementation Model for an "Activatable" Remote Object
7.4 Activation Interfaces

8 Stub/Skeleton Interfaces

8.1 The RemoteStub Class
8.2 The RemoteCall Interface
8.3 The RemoteRef Interface
8.4 The ServerRef Interface
8.5 The Skeleton Interface
8.6 The Operation Class

9 Garbage Collector Interfaces

9.1 The DGC Interface
9.2 The Lease Class
9.3 The ObjID Class
9.4 The UID Class
9.5 The VMID Class

10 RMI Wire Protocol

10.1 Overview
10.2 RMI Transport Protocol
10.3 RMI's Use of Object Serialization Protocol
10.4 RMI's Use of HTTP POST Protocol
10.5 Application-Specific Values for RMI
10.6 RMI's Multiplexing Protocol

A Exceptions In RMI

A.1 Exceptions During Remote Object Export
A.2 Exceptions During RMI Call
A.3 Exceptions or Errors During Return
A.4 Naming Exceptions
A.5 Activation Exceptions
A.6 Other Exceptions

B Properties In RMI

B.1 Server Properties
B.2 Activation Properties
B.3 Other Properties

CONTENTS | PREV | NEXT
Copyright © 1997, 2010, Oracle and/or its affiliates. All rights reserved.


Uses of Interface com.sun.javadoc.RootDoc (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.javadoc.RootDoc

    • Uses of RootDoc in com.sun.javadoc

      Methods in com.sun.javadoc with parameters of type RootDoc
      Modifier and Type Method and Description
      static boolean Doclet.start(RootDoc root)
      Generate documentation here.
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.mirror.apt.RoundCompleteEvent (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.mirror.apt.RoundCompleteEvent

  • Packages that use RoundCompleteEvent
    Package Description
    com.sun.mirror.apt
    Classes used to communicate information between annotation processors and an annotation processing tool.

    • Uses of RoundCompleteEvent in com.sun.mirror.apt

      Methods in com.sun.mirror.apt with parameters of type RoundCompleteEvent
      Modifier and Type Method and Description
      void RoundCompleteListener.roundComplete(RoundCompleteEvent event)
      Deprecated.
      Invoked after all processors for a round have run to completion.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.apt.RoundCompleteListener (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.apt.RoundCompleteListener

No usage of com.sun.mirror.apt.RoundCompleteListener
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.apt.RoundState (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.apt.RoundState

  • Packages that use RoundState
    Package Description
    com.sun.mirror.apt
    Classes used to communicate information between annotation processors and an annotation processing tool.

    • Uses of RoundState in com.sun.mirror.apt

      Methods in com.sun.mirror.apt that return RoundState
      Modifier and Type Method and Description
      RoundState RoundCompleteEvent.getRoundState()
      Deprecated.
      Return round state.
      Constructors in com.sun.mirror.apt with parameters of type RoundState
      Constructor and Description
      RoundCompleteEvent(AnnotationProcessorEnvironment source, RoundState rs)
      Deprecated.
      The current AnnotationProcessorEnvironment is regarded as the source of events.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


How to Deploy RSA-Signed Applets in Java Plug-in

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

< Contents

Deploying RSA-Signed Applets in Java Plug-in

This section covers the following topics:

  • How to deploy RSA Signed Applets
  • Certificate Management
  • Disabling RSA signed applet support

How to Deploy RSA Signed Applets

To deploy RSA signed applets:

  1. Reference the JAR from the HTML page using archive, cache_archive, or cache_archive_ex format. See Applet Caching.
  2. Place the JAR file and HTML page on the web server.

When users of Java Plug-in encounter an RSA signed applet, the Plug-in will verify whether:

  1. The applet is correctly signed
  2. The RSA certificate chain and root CA are valid

If the applet is correctly signed and the RSA certificate chain and root CA are valid, the Plug-in will pop-up a security dialog telling the user and providing four options:

  1. Grant always: If selected, the applet will be granted the AllPermission permission. Any applet signed with the same certificate will be trusted automatically in the future, and no security dialog will pop up when the certificate is encountered again. This option selection can be changed from the Java Control Panel.
  2. Grant this session: If selected, the applet will be granted the AllPermission permission. Any applet signed with the same certificate will be trusted automatically within the same browser session.
  3. Deny: If selected, the applet will be treated as untrusted.
  4. View Issuer: If selected, the user can examine the attributes of each certificate in the certificate chain in the JAR file.

Once the user selects the options from the security dialog, the applet will be run in the corresponding security context. Note that all options are selected on the fly; no preconfiguration is required.

Certificate Management

The Java Control Panel provides a Certificates Panel for managing RSA signed applets. This panel contains a list of certificates that received "Grant always" permission when the Java Plug-in security dialog (pop-up) ran. Users can remove any certificate from the list, and if an applet signed by a removed certificates is encountered again, a security dialog pop-up will appear asking for permission. Users can also export and view certificates through the Java Control Panel.

Disabling RSA Signed Applet Support

RSA signed applets can be entirely disabled in Java Plug-in by specifying the usePolicy permission in the policy file. If the usePolicy permission is among the permissions granted to the given codesource (by the configured security policy), user prompting will not take place, and only permissions specified in the security policy will be granted to the codesource. By default, RSA signed applets are enabled in the Java Plug-in.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


How RSA Signed Applet Verification Works in Java Plug-in

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

< Contents

Verification of RSA Signed Applets in Java Plug-in

This section covers the following topics:

  • Introduction
  • Support for RSA Verification
  • Support for Dynamic Trust Management
  • usePolicy Permission

Introduction

This page provides an overview of how verification of RSA signed applets is implemented in Java Plug-in. For an overview of how to use RSA signed applets, see How to Deploy RSA-Signed Applets in Java Plug-in.

Support for RSA Verification

To enable verification of RSA signatures in a browser-independent way, Java Plug-in includes a Cryptographic Service Provider (CSP). The CSP supports the "MD2withRSA", "MD5withRSA", and "SHA1withRSA" digital signature algorithms. It is automatically registered with the Java Cryptographic Architecture framework as part of the static initializer of the PluginClassLoader.

Support for Dynamic Trust Management

Java SE has a fine-grained access control based on "codesource" and "protection domain". Every class that is loaded from a JAR file has a codesource, which encapsulates two pieces of information:

  • The location (URL) where the class came from. In addition, every class that is loaded by a classloader belongs to one and only one protection domain, based on its codesource (i.e., based on where the class came from and who signed it). Every protection domain has a set of permissions associated with it, based on the configured security policy. The protection domain encapsulates the codesource and the set of permissions granted to it
  • The list of principals who signed it (its certificates). Each signer principal in the codesource is represented by its X.509 public-key certificate and supporting certificate chain.

A certificate chain is a list of hierarchically ordered public-key certificates, starting at the signer's public-key certificate and ending at the certificate of a Root Certification Authority ("Root CA"). The public key of one certificate in the chain is used to verify the signature on the previous certificate in the chain. The Root CA certificate is self-signed. The assumption is that the Root CA is trusted because it is well known and widely published.

The PluginClassLoader checks the configured security policy to determine which permissions to grant to a given codesource. The codesource and the set of permissions granted to it then form a protection domain. This behavior is common to all secure classloaders (i.e., instances of java.security.SecureClassLoader).

The sun.plugin.security.PluginClassLoader extends sun.applet.AppletClassLoader, which is a subclass of java.net.URLClassLoader, which in turn extends java.security.SecureClassLoader. The PluginClassLoader does additional work: If the applet is signed, and the permissions granted to it do not include the special usePolicy permission, the PluginClassLoader extracts the signers (and their supporting certificate chains) from the applet's codesource and attempts to verify them.

If Plug-in can verify the certificate chain all the way up to its Root CA certificate, it checks if that Root CA certificate is contained in the database of trusted Root CA certificates. If so, Plug-in will display the certificate chain of the authenticated signer and ask the user whether or not to grant AllPermission to code signed by that principal. Java code that is assigned the AllPermission permission is treated the same as system code, meaning it has all the privileges that system code has. The user can then choose whether or not to grant AllPermission to code signed by that principal, and whether such permission should be granted to any code signed by that principal for all subsequent sessions or for the current session only.

For the case of unsigned applets, or signed applets whose permissions include the usePolicy, see Overview—Applet Security Basics.

usePolicy Permission

A permission named usePolicy allows system administrators to turn off the PluginClassLoader behavior. If the usePolicy permission is granted to the codesource by the configured security policy, no user prompting will take place. Only the permissions specified in the security policy will be granted to the codesource.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Signing Applets Using RSA Signed Certificates

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

< Contents

Signing Applets Using RSA Certificates

This chapter covers the following topics:

  • Introduction
  • Signing Tools
  • Getting RSA Certificates
    • Getting Certificates With Jarsigner
    • Getting Certificates With Netscape Signing Tool
  • Bundling Java Applets as JAR Files
  • Signing Java Applets
    • Signing Applets Using jarsigner
    • Signing Applets Using Netscape Signing Tool
  • Converting Old Netscape-Signed Applets
  • Microsoft Authenticode
  • Common Problems

Introduction

RSA-signed applets are supported to make deployment of signed applets easier. However, signing applets through RSA is still difficult for most novice applet developers and prevents them from taking full advantage of this Java Plug-in feature. This document provides step-by-step instructions for signing applets using RSA certificates, allowing novice applet developers to sign their applets without having to wade through the many complex security issues involved.

Signing applets requires the following :

  1. Signing tools
  2. An RSA keypair and a certificate chain for the public keys
  3. The applet and all its class files, bundled as JAR files

Signing Tools

Java Plug-in supports the format of the following tools for signing applets using RSA:

  1. jarsigner—Signing tool shipped as part of the Java SDK
  2. signtool—Signing tool provided by Netscape for signing applets in Navigator/Communicator. For more details on the sign tool and downloading it read the page at http://www.mozilla.org/projects/security/pki/nss/tools.

Getting RSA Certificates

RSA certificates may be purchased from a Certificate Authority (CA) that supports RSA, such as VeriSign and Thawte. Some CAs, such as VeriSign, implement different protocols for issuing certificates, depending on the particular signing tool you are using.

Getting Certificates With Jarsigner

Jarsigner is known to work with VeriSign and Thawte certificates and may work with Certificate Authorties. To use Jarsigner to sign applets using RSA certificates, obtain the Sun Java Signing certificate from VeriSign or the Java Code Signing certificate from Thawte—or similar certificates from other CAs. During the process of certificate enrollment, you will be asked to provide the certificate signing request (CSR). To generate the CSR, follow these steps:

  1. Use keytool to generate an RSA keypair (using the "-genkey -keyalg rsa" options). Make sure your distinguished name contains all the components mandated by VeriSign/Thawte. E.g.,
    C:\Program Files\Java\jdk1.6.0\bin\keytool -genkey -keyalg rsa -alias MyCert
Enter keystore password: *********
What is your first and last name?
[Unknown]: XXXXXXX YYY
What is the name of your organizational unit?
[Unknown]: Java Software
What is the name of your organization?
[Unknown]: Sun Microsystems
What is the name of your City or Locality?
[Unknown]: Cupertino
What is the name of your State or Province?
[Unknown]: CA
What is the two-letter country code for this unit?
[Unknown]: US
Is <CN=XXXXXXX YYY, OU=Java Software, O=Sun Microsystems,
                L=Cupertino, ST=CA, C=US> correct?
[no]: yes

Enter key password for <MyCert>
(RETURN if same as keystore password): *********
  2. Use "keytool -certreq" to generate a certification signing request. Copy the result and paste it into the VeriSign/Thawte webform. For example,
    C:\Program Files\Java\jdk1.6.0\bin\keytool -certreq -alias MyCert

Enter keystore password:  *********
-----BEGIN NEW CERTIFICATE REQUEST-----
MIIBtjCCAR8CAQAwdjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRIwE
AYDVQQHEwlDdXBlcnRpbm8xGTAXBgNVBAoTEFN1biBNaWNyb3N5c3RlbX
MxFjAUBgNVBAsTDUphdmEgU29mdHdhcmUxEzARBgNVBAMTClN0YW5sZXk
gSG8wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALTgU8PovA4y59eb
oPjY65BwCSc/zPqtOZKJlaW4WP+UhmebE+T2Mho7P5zXjGf7elo3tV5uI
3vzgGfnhgpf73EoMow8EJhly4w/YsXKqeJEqqvNogzAD+qUv7Ld6dLOv0
CO5qvpmBAO6mfaI1XAgx/4xU/6009jVQe0TgIoocB5AgMBAAGgADANBgk
qhkiG9w0BAQQFAAOBgQAWmLrkifKiUYtd4ykhBtPWSwW/IKkgyfIuNMML
dF1DH8neSnXf3ZLI32f2yXvs7u3/xn6chnTXh4HYCJoGYOAbB3WNbAoQR
i6u6TLLOvgv9pMNUo6v1qB0xly1faizjimVYBwLhOenkA3Bw7S8UIVfdv
84cO9dFUGcr/Pfrl3GtQ==
-----END NEW CERTIFICATE REQUEST-----
  3. The CA (e.g., VeriSign/Thawte) will send you a certificate reply (chain) by email. Copy the chain and store it in a file. Use "keytool -import" to import the chain into your keystore. E.g.,
    C:\Program Files\Java\jdk1.6.0\bin\keytool -import -alias MyCert -file VSSStanleyNew.cer
  4. Your RSA certificate and its supporting chain have been validated and imported into your keystore. You are now ready to use jarsigner to sign your JAR file.

Note

You must use the same alias name for all the above steps—or no alias name, in which case the alias name defaults to "mykey".

Getting Certificates With Netscape Signing Tool

Most CAs (e.g., VeriSign/Thawte) support Netscape Signing Tool. To use the Netscape Signing Tool to sign applets using RSA certificates, obtain the Netscape Object Signing certificate from Verisign or the Netscape Object Signing certificate from Thawte—or similar certificates from other CAs. During the process of enrollment, you will be asked for personal/company information, since the CA will need to verify your identity before issuing a certificate. This process may take from several hours to several days.

Once the RSA certificate is issued, it usually consists of three files:

  • cert7.db
  • key3.db
  • secmod.db

Depending on the CA, the certificate may be issued and stored on a floppy diskette, or it may be stored directly in the security modules of Netscape Navigator/Communicator. Once you have the certificate, you are ready to use the Netscape Signing Tool to sign your JAR file.

Bundling Java Applets as JAR Files

To use Jarsigner to sign applets with RSA certificates, the applets must be bundled as JAR files. The Jar tool (command jar ...), which comes wiht the Java SE SDK, can be used for that purpose. E.g.,

C:\Program Files\Java\jdk1.6.0\bin\jar cvf C:\TestApplet.jar .
added manifest
adding: TestApplet.class (in = 94208) (out= 20103)(deflated 78%)
adding: TestHelper.class (in = 16384) (out= 779)(deflated 95%)
This example creates a JAR file C:\TestApplet.jar, and it contains all the files under the current directory and its sub-directories.

After the JAR file is created, you should verify its content using the jar tool again, e.g.,

C:\Program Files\Java\jdk1.6.0\bin\jar tvf TestApplet.jar
     0 Mon Mar 06 18:02:54 PST 2000 META-INF/
    68 Mon Mar 06 18:02:54 PST 2000 META-INF/MANIFEST.MF
 94208 Wed Mar 10 11:48:52 PST 2000 TestApplet.class
 16384 Wed Mar 10 11:48:52 PST 2000 TestHelper.class
This ensures that the class files are stored with the proper path within the JAR file.

To sign an applet with an RSA certificate using the Netscape Signing Tool, the applet must be placed in a directory, e.g., C:\signdir. The Netscape Signing Tool will bundle it as JAR file after the signing process.

Signing Java Applets

Once you have the RSA certificates, the signing tool and the applet's JAR files, you are ready to sign the applets.

Signing Applets Using jarsigner

To sign applets using jarsigner, follow these steps:

  1. Use jarsigner to sign the JAR file, using the RSA credentials in your keystore that were generated in the previous steps. Make sure the same alias name is specified. E.g.,
    C:\Program Files\Java\jdk1.6.0\bin\jarsigner C:\TestApplet.jar MyCert
Enter Passphrase for keystore: ********
  2. Use "jarsigner -verify -verbose -certs" to verify the jar files
    C:\Program Files\Java\jdk1.6.0\bin\jarsigner -verify -verbose
                -certs d:\TestApplet.jar

         245 Wed Mar 10 11:48:52 PST 2000 META-INF/manifest.mf
         187 Wed Mar 10 11:48:52 PST 2000 META-INF/MYCERT.SF
         968 Wed Mar 10 11:48:52 PST 2000 META-INF/MYCERT.RSA
smk      943 Wed Mar 10 11:48:52 PST 2000 TestApplet.class
smk      163 Wed Mar 10 11:48:52 PST 2000 TestHelper.class

      X.509, CN=XXXXXXX YYY, OU=Java Software,
                O=Sun Microsystems, L=Cupertino,
                ST=CA, C=US (mycert)
      X.509, CN=Sun Microsystems, OU=Java Plug-in QA,
                O=Sun Microsystems, L=Cupertino, ST=CA, C=US
      X.509, EmailAddress=server-certs@thawte.com,
                CN=Thawte Server CA, OU=Certification
                Services Division, O=Thawte Consulting cc,
                L=Cape Town, ST=Western Cape, C=ZA

  s = signature was verified
  m = entry is listed in manifest
  k = at least one certificate was found in keystore
  i = at least one certificate was found in identity scope

jar verified.
  3. Your applet has been signed properly. You are now ready to deploy your RSA signed applet.

Signing Applets Using Netscape Signing Tool

To sign applets using signtool, follow these steps:

  1. Use "signtool -L" to determine the certificate nickname that should be used in signing. E.g.,
    C:\signtool13WINNT40\signtool -L -d a:\cert
using certificate directory: a:\cert

S Certificates
- ------------
  AT&T Certificate Services
  Thawte Personal Premium CA
  GTE CyberTrust Secure Server CA
  Verisign/RSA Commercial CA
  AT&T Directory Services
  BelSign Secure Server CA
  BelSign Class 1 CA
  GTIS/PWGSC, Canada Gov. Web CA
  Thawte Personal Freemail CA
  Thawte Server CA
  GTIS/PWGSC, Canada Gov. Secure CA
  MCI Mall CA
  VeriSign Class 3 Primary CA
  VeriSign Class 4 Primary CA
  KEYWITNESS, Canada CA
  BelSign Class 2 CA
  BelSign Object Publishing CA
* Sun Microsystems, Inc.
  VeriSign Class 3 CA - Commercial Content/Software
                        Publisher - VeriSign, Inc.
  Verisign/RSA Secure Server CA
  VeriSign Class 1 Primary CA
  BBN Certificate Services CA Root 1
  Thawte Personal Basic CA
* Sun Microsystems, Inc.'s VeriSign, Inc. ID
  CertiSign BR
  VeriSign Class 2 Primary CA
  Canada Post Corporation CA
  Integrion CA
  IBM World Registry CA
  BelSign Class 3 CA
  Uptime Group Plc. Class 1 CA
  Uptime Group Plc. Class 2 CA
  Thawte Premium Server CA
  Uptime Group Plc. Class 3 CA
  GTE CyberTrust Root CA
  Uptime Group Plc. Class 4 CA
- ------------

Certificates that can be used to sign objects
have *'s to their left.
  2. Create an empty directory. E.g.,
    mkdir signdir
  3. Put all the applet class files into it.

  4. Use "signtool -Z" to sign the applet. E.g.,
    C:\signtool13>signtool -k "Sun Microsystems, Inc.'s VeriSign, Inc. ID"
        -d a:\cert -Z c:\TestApplet.jar c:\signdir
using certificate directory: a:\cert
Generating c:\signdir/META-INF/manifest.mf file..
--> TestApplet.class
adding c:\signdir/TestApplet.class to c:\TestApplet.jar...
        (deflated 57%)
--> TestHelper.class
adding c:\signdir/TestHelper.class to c:\TestApplet.jar...
        (deflated 43%)
Generating zigbert.sf file..
adding c:\signdir/META-INF/manifest.mf to c:\TestApplet.jar...
        (deflated 44%)
adding c:\signdir/META-INF/zigbert.sf to c:\TestApplet.jar...
        (deflated 46%)
adding c:\signdir/META-INF/zigbert.rsa to c:\TestApplet.jar...
        (deflated 40%)
tree "c:\signdir" signed successfully
  5. Use "signtool -w" to verify the archive. E.g.,
    C:\signtool13>signtool -w c:\TestApplet.jar -d a:\cert
using certificate directory: a:\cert

Signer information:

nickname: Sun Microsystems, Inc.'s VeriSign, Inc. ID
subject name: C=US, ST=CA, L=Palo Alto, OU=Java Software,
        CN=Sun Microsystems, OU=Digital ID Class 3 - Netscape
Object Signing, OU="www.verisign.com/repository/RPA Incorp.
        by Ref.,LIAB.LTD(c)99", OU=VeriSign Trust Network,
        O="VeriSign, Inc."
issuer name: CN=VeriSign Class 3 CA - Commercial Content/Software
        Publisher, OU="www.verisign.com/repository/RPA Incorp.
        by Ref.,LIAB.LTD(c)98", OU=VeriSign Trust Network,
        O="VeriSign, Inc."

Your applet has been signed properly. You are now ready to deploy your RSA signed applet. See How to Deploy RSA Signed Applets for deployment information.

Converting Old Netscape-Signed Applets

Existing RSA signed applets designed for Netscape may use Netscape-specific security APIs. These Netscape-specific APIs are not supported in Java Plug-in. Instead, the Plug-in supports the standard Java security APIs in both Netscape Navigator and Internet Explorer.

To migrate Netscape-signed applets using the Netscape security APIs to run in Java Plug-in:

  1. Comment or remove all netscape.security.* related statements from the Java applet.
  2. Compile and archive the applet as a JAR file.
  3. Re-sign the JAR file using Object Signing.

This ensures that an RSA signed applet will run in both Netscape Navigator and Internet Explorer with Java Plug-in.

Microsoft Authenticode

Authenticode is a proprietary signing technology used in Microsoft Internet Explorer on Win32 for supporting signed applets in IE's JVM. Authenticode is not supported in Java Plug-in. Instead, the Java Plug-in supports use of RSA signed applets in both IE and Netscape.

Common Problems

  • If the JAR file is not signed properly, if the RSA certificate has expired, or if the RSA certificate is a self-generated, self-signed certificate, Java Plug-in may fail silently and not pop up the security dialog. The applet will be treated as unsigned.
  • The Netscape Signing Tool is very particular about JAR file format. In Netscape Signing Tool, it expects the MANIFEST file to be at the end of the JAR file, whereas Jarsigner puts it at the beginning. The standard does not mandate where the MANIFEST file should be in the JAR file. Therefore, if you create a JAR file using Jar tool, the Netscape Signing Tool may complain about "Invalid Jar File Format". On the other hand, Jarsigner is not picky; it can verify a JAR file regardless of whether its MANIFEST file is located at the beginning or the end. To avoid this problem when using Netscape Signing Tool, you should both generate and sign the JAR file through the Netscape Signing Tool.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Sample Output from Deadlock Detection Utility

^\Full thread dump Java HotSpot(TM) Client VM (1.4.1 mixed mode):

"DestroyJavaVM" prio=5 tid=0x2c788 nid=0x1 waiting on condition [0..ffbee16c]

"Thread-7" prio=5 tid=0x119570 nid=0x11 waiting for monitor entry [f1681000..f168199c]
        at Locker.run(Deadlock.java:98)
        - waiting to lock <f203fe18> (a java.lang.Object)
        - locked <f6112a88> (a java.lang.String)

"Thread-6" prio=5 tid=0x118a18 nid=0x10 waiting for monitor entry [f1781000..f178199c]
        at Locker.run(Deadlock.java:98)
        - waiting to lock <f6112a88> (a java.lang.String)
        - locked <f203fe18> (a java.lang.Object)

"Thread-5" prio=5 tid=0x117660 nid=0xf waiting on condition [f1881000..f188199c]
        at java.lang.Thread.sleep(Native Method)
        at Deadlock$3.run(Deadlock.java:55)
        - locked <f203fe10> (a java.lang.Object)
        at java.lang.Thread.run(Thread.java:536)

"Thread-4" prio=5 tid=0x116ab8 nid=0xe waiting for monitor entry [f1981000..f198199c]
        at Deadlock.jniEnter(Native Method)
        at Deadlock$2.run(Deadlock.java:41)
        at java.lang.Thread.run(Thread.java:536)

"Thread-3" prio=5 tid=0x115f10 nid=0xd runnable [f1a81000..f1a8199c]
        at Deadlock.rawEnter(Deadlock.java:76)
        at Deadlock$1.run(Deadlock.java:24)
        at java.lang.Thread.run(Thread.java:536)

"Thread-2" prio=5 tid=0x1154a8 nid=0xc waiting for monitor entry [f1b81000..f1b8199c]
        at Locker.run(Deadlock.java:98)
        - waiting to lock <f6112a60> (a java.lang.String)
        - locked <f203fe00> (a java.lang.Object)

"Thread-1" prio=5 tid=0x115270 nid=0xb waiting for monitor entry [f1c81000..f1c8199c]
        at Locker.run(Deadlock.java:98)
        - waiting to lock <f203fe00> (a java.lang.Object)
        - locked <f203fdf8> (a java.lang.Object)

"Signal Dispatcher" daemon prio=10 tid=0xbac48 nid=0x9 waiting on condition [0..0]

"Finalizer" daemon prio=8 tid=0xb5590 nid=0x6 in Object.wait() [fa381000..fa38199c]
        at java.lang.Object.wait(Native Method)
        - waiting on <f2000490> (a java.lang.ref.ReferenceQueue$Lock)
        at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:111)
        - locked <f2000490> (a java.lang.ref.ReferenceQueue$Lock)
        at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:127)
        at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:159)

"Reference Handler" daemon prio=10 tid=0xb3c40 nid=0x5 in Object.wait() [fdf81000..fdf8199c]
        at java.lang.Object.wait(Native Method)
        - waiting on <f2000380> (a java.lang.ref.Reference$Lock)
        at java.lang.Object.wait(Object.java:426)
        at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:113)
        - locked <f2000380> (a java.lang.ref.Reference$Lock)

"VM Thread" prio=5 tid=0xb2808 nid=0x4 runnable

"VM Periodic Task Thread" prio=10 tid=0xb9190 nid=0x7 waiting on condition
"Suspend Checker Thread" prio=10 tid=0xb9ae8 nid=0x8 runnable

Found one Java-level deadlock:
=============================
"Thread-7":
  waiting to lock monitor 0xb48d8 (object 0xf203fe18, a java.lang.Object),
  which is held by "Thread-6"
"Thread-6":
  waiting to lock monitor 0xb48a0 (object 0xf6112a88, a java.lang.String),
  which is held by "Thread-7"

Java stack information for the threads listed above:
===================================================
"Thread-7":
        at Locker.run(Deadlock.java:98)
        - waiting to lock <f203fe18> (a java.lang.Object)
        - locked <f6112a88> (a java.lang.String)
"Thread-6":
        at Locker.run(Deadlock.java:98)
        - waiting to lock <f6112a88> (a java.lang.String)
        - locked <f203fe18> (a java.lang.Object)

Found one Java-level deadlock:
=============================
"Thread-4":
  waiting to lock monitor 0xb4868 (object 0xf203fdf8, a java.lang.Object)
  in JNI, which is held by "Thread-1"
"Thread-1":
  waiting to lock monitor 0xb4910 (object 0xf203fe00, a java.lang.Object),
  which is held by "Thread-2"
"Thread-2":
  waiting to lock monitor 0xb4830 (object 0xf6112a60, a java.lang.String),
  which is held by "Thread-3"
"Thread-3":
  waiting to lock monitor 0x119520 (JVMDI/JVMPI raw monitor),
  which is held by "Thread-4"

Java stack information for the threads listed above:
===================================================
"Thread-4":
        at Deadlock.jniEnter(Native Method)
        at Deadlock$2.run(Deadlock.java:41)
        at java.lang.Thread.run(Thread.java:536)
"Thread-1":
        at Locker.run(Deadlock.java:98)
        - waiting to lock <f203fe00> (a java.lang.Object)
        - locked <f203fdf8> (a java.lang.Object)
"Thread-2":
        at Locker.run(Deadlock.java:98)
        - waiting to lock <f6112a60> (a java.lang.String)
        - locked <f203fe00> (a java.lang.Object)
"Thread-3":
        at Deadlock.rawEnter(Deadlock.java:76)
        at Deadlock$1.run(Deadlock.java:24)
        at java.lang.Thread.run(Thread.java:536)

Found 2 deadlocks.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java SASL API

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

The Java SASL API
Programming and Deployment Guide

  1. Introduction
    • What is SASL
    • The Java SASL API
    • When to Use SASL
  2. API Overview
    • Creating the Mechanisms
    • Passing Input to the Mechanisms
    • Using the Mechanisms
    • Using the Negotiated Security Layer
  3. How SASL Mechanisms are Installed and Selected
  4. The SunSASL Provider
    • Client Mechanisms
    • Server Mechanisms
    • Debugging and Monitoring
  5. Implementing a SASL Security Provider

Introduction

What is SASL?

Simple Authentication and Security Layer, or SASL, is an Internet standard (RFC 2222) that specifies a protocol for authentication and optional establishment of a security layer between client and server applications. SASL defines how authentication data is to be exchanged but does not itself specify the contents of that data. It is a framework into which specific authentication mechanisms that specify the contents and semantics of the authentication data can fit.

SASL is used by protocols, such as the Lightweight Directory Access Protocol, version 3 (LDAP v3), and the Internet Message Access Protocol, version 4 (IMAP v4) to enable pluggable authentication. Instead of hardwiring an authentication method into the protocol, LDAP v3 and IMAP v4 use SASL to perform authentication, thus enabling authentication via various SASL mechanisms.

There are a number of standard SASL mechanisms defined by the Internet community for various levels of security and deployment scenarios. These range from no security (e.g., anonymous authentication) to high security (e.g., Kerberos authentication) and levels in between.

The Java SASL API

The Java SASL API defines classes and interfaces for applications that use SASL mechanisms. It is defined to be mechanism-neutral: the application that uses the API need not be hardwired into using any particular SASL mechanism. The API supports both client and server applications. It allows applications to select the mechanism to use based on desired security features, such as whether they are susceptible to passive dictionary attacks or whether they accept anonymous authentication.

The Java SASL API also allows developers to use their own, custom SASL mechanisms. SASL mechanisms are installed by using the Java Cryptography Architecture (JCA).

When to Use SASL

SASL provides pluggable authentication and security layer for network applications. There are other features in the Java SE that provide similar functionality, including the Java Secure Socket Extension (JSSE), and Java Generic Security Service (Java GSS). JSSE provides a framework and an implementation for a Java language version of the SSL and TLS protocols. Java GSS is the Java language bindings for the Generic Security Service Application Programming Interface (GSS-API). The only mechanism currently supported underneath this API on Java SE is Kerberos v5.

When compared with JSSE and Java GSS, SASL is relatively lightweight and is popular among more recent protocols. It also has the advantage that several popular, lightweight (in terms infrastructure support) SASL mechanisms have been defined. Primary JSSE and Java GSS mechanisms, on the other hand, have relatively heavyweight mechanisms that require more elaborate infrastructures (Public Key Infrastructure and Kerberos, respectively).

SASL, JSSE, and Java GSS are often used together. For example, a common pattern is for an application to use JSSE for establishing a secure channel, and to use SASL for client, username/password-based authentication. There are also SASL mechanisms layered on top of GSS-API mechanisms; one popular example is a SASL GSS-API/Kerberos v5 mechanism that is used with LDAP.

Except when defining and building protocols from scratch, often the biggest factor determining which API to use is the protocol definition. For example, LDAP and IMAP are defined to use SASL, so software related to these protocols should use the Java SASL API. When building Kerberos applications and services, the API to use is Java GSS. When building applications and services that use SSL/TLS as their protocol, the API to use is JSSE. See the Java Security Documentation for further details about when to use JSSE versus Java GSS.

API Overview

SASL is a challenge-response protocol. The server issues a challenge to the client, and the client sends a response based on the challenge. This exchange continues until the server is satisfied and issues no further challenge. These challenges and responses are binary tokens of arbitrary length. The encapsulating protocol (such as LDAP or IMAP) specifies how these tokens are encoded and exchanged. For example, LDAP specifies how SASL tokens are encapsulated within LDAP bind requests and responses.

The Java SASL API is modeled according to this style of interaction and usage. It has interfaces, SaslClient and SaslServer, that represent client-side and server-side mechanisms, respectively. The application interacts with the mechanisms via byte arrays that represent the challenges and responses. The server-side mechanism iterates, issuing challenges and processing responses, until it is satisfied, while the client-side mechanism iterates, evaluating challenges and issuing responses, until the server is satisfied. The application that is using the mechanism drives each iteration. That is, it extracts the challenge or response from a protocol packet and supplies it to the mechanism, and then puts the response or challenge returned by the mechanism into a protocol packet and sends it to the peer.

Creating the Mechanisms

The client and server code that uses the SASL mechanisms are not hardwired to use specific mechanism(s). In many protocols that use SASL, the server advertises (either statically or dynamically) a list of SASL mechanisms that it supports. The client then selects one of these based on its security requirements.

The Sasl class is used for creating instances of SaslClient and SaslServer. Here is an example of how an application creates a SASL client mechanism using a list of possible SASL mechanisms.

String[] mechanisms = new String[]{"DIGEST-MD5", "PLAIN"};
SaslClient sc = Sasl.createSaslClient(mechanisms, authzid, protocol,
                serverName, props, callbackHandler);

Based on the availability of the mechanisms supported by the platform and other configuration information provided via the parameters, the Java SASL framework selects one of the listed mechanisms and return an instance of SaslClient.

The name of the selected mechanism is usually transmitted to the server via the application protocol. Upon receiving the mechanism name, the server creates a corresponding SaslServer object to process client-sent responses. Here is an example of how the server would create an instance of SaslServer.

SaslServer ss = Sasl.createSaslServer(mechanism, protocol,
                  myName, props, callbackHandler);

Passing Input to the Mechanisms

Because the Java SASL API is a general framework, it must be able to accommodate many different types of mechanisms. Each mechanism needs to be initialized with input and may need input to make progress. The API provides three means by which an application gives input to a mechanism.

  1. Common input parameters. The application uses predefined parameters to supply information that are defined by the SASL specification and commonly required by mechanisms. For SASL client mechanisms, the input parameters are authorization id, protocol id, and server name. For SASL server mechanisms, the common input parameters are prototol id and (its own fully qualified) server name.
  2. Properties parameter. The application uses the properties parameter, a mapping of property names to (possibly non-string) property values, to supply configuration information. The Java SASL API defines some standard properties, such as quality-of-protection, cipher strength, and maximum buffer size. The parameter can also be used to pass in non-standard properties that are specific to particular mechanisms.
  3. Callbacks. The application uses the callback handler parameter to supply input that cannot be predetermined or might not be common across mechanisms. When a mechanism requires input data, it uses the callback handler supplied by the application to collect the data, possibly from the end-user of the application. For example, a mechanism might require the end-user of the application to supply a name and password.

    Mechanisms can use the callbacks defined in the javax.security.auth.callback package; these are generic callbacks useful for building applications that perform authentication. Mechanisms might also need SASL-specific callbacks, such as those for collecting realm and authorization information, or even (non-standardized) mechanism-specific callbacks. The application should be able to accommodate a variety of mechanisms. Consequently, its callback handler must be able to service all of the callbacks that the mechanisms might request. This is not possible in general for arbitrary mechanisms, but is usually feasible due to the limited number of mechanisms that are typically deployed and used.

Using the Mechanisms

Once the application has created a mechanism, it uses the mechanism to obtain SASL tokens to exchange with the peer. The client typically indicates to the server via the application protocol which mechanism to use. Some protocols allows the client to accompany the request with an optional initial response for mechanisms that have an initial response. This feature can be used to lower the number of message exchanges required for authentication. Here is an example of how a client might use SaslClient for authentication.
// Get optional initial response
byte[] response =
    (sc.hasInitialResponse() ? sc.evaluateChallenge(new byte[]) : null);

String mechanism = sc.getName();

// Send selected mechanism name and optional initial response to server
send(mechanism, response);

// Read response
msg = receive();
while (!sc.isComplete() && (msg.status == CONTINUE || msg.status == SUCCESS)) {
    // Evaluate server challenge
    response = sc.evaluateChallenge(msg.contents);

    if (msg.status == SUCCESS) {
        // done; server doesn't expect any more SASL data
        if (response != null) {
           throw new IOException(
               "Protocol error: attempting to send response after completion");
        }
        break;
    } else {
        send(mechanism, response);
        msg = receive();
    }

The client application iterates through each step of the authentication by using the mechanism (sc) to evaluate the challenge gotten from the server and to get a response to send back to the server. It continues this cycle until either the mechanism or application-level protocol indicates that the authentication has completed, or if the mechanism cannot evaluate a challenge. If the mechanism cannot evaluate the challenge, it throws an exception to indicate the error and terminates the authentication. Disagreement between the mechanism and protocol about the completion state must be treated as an error because it might indicate a compromise of the authentication exchange.

Here is an example of how a server might use SaslServer.

// Read request that contains mechanism name and optional initial response
msg.receive();

// Obtain a SaslServer to perform authentication
SaslServer ss = Sasl.createSaslServer(msg.mechanism,
    protocol, myName, props, callbackHandler);

// Perform authentication steps until done
while (!ss.isComplete()) {
    try {
        // Process response
        byte[] challenge = sc.evaluateResponse(msg.contents);

        if (ss.isComplete()) {
            send(mechanism, challenge, SUCCESS);
        } else {
            send(mechanism, challenge, CONTINUE);
            msg.receive();
        }
    } catch (SaslException e) {
        send(ERROR);
        sc.dispose();
        break;
    }
}
The server application iterates through each step of the authentication by giving the client's response to the mechanism (ss) to process. If the response is incorrect, the mechanism indicates the error by throwing a SaslException so that the server can report the error and terminate the authentication. If the response is correct, the mechanism returns challenge data to be sent to the client and indicates whether the authentication is complete. Note that challenge data can accompany a "success" indication. This might be used, for example, to tell the client to finalize some negotiated state.

Using the Negotiated Security Layer

Some SASL mechanisms support only authentication while others support use of a negotiated security layer after authentication. The security layer feature is often not used when the application uses some other means, such as SSL/TLS, to communicate securely with the peer.

When a security layer has been negotiated, all subsequent communication with the peer must take place using the security layer. To determine whether a security layer has been negotiated, get the negotiated quality-of-protection (QOP) from the mechanism. Here is an example of how to determine whether a security layer has been negotiated.

String qop = (String) sc.getNegotiatedProperty(Sasl.QOP);
boolean hasSecurityLayer = (qop != null &&
    (qop.equals("auth-int") || qop.equals("auth-conf")));

A security layer has been negotiated if the Sasl.QOP property indicates that either integrity and/or confidentiality has been negotiated.

To communicate with the peer using the negotiated layer, the application first uses the wrap method to encode the data to be sent to the peer to produce a "wrapped" buffer. It then transfers a length field representing the number of octets in the wrapped buffer followed by the contents of the wrapped buffer to the peer. The peer receiving the stream of octets passes the buffer (without the length field) to unwrap to obtain the decoded bytes sent by the peer. Details of this protocol are described in RFC 2222. Here is an example of how a client application sends and receives application data using a security layer.

// Send outgoing application data to peer
byte[] outgoing = ...;
byte[] netOut = sc.wrap(outgoing, 0, outgoing.length);

send(netOut.length, netOut);   // send to peer

// Receive incoming application data from peer
byte[] netIn = receive();      // read length and ensuing bytes from peer

byte[] incoming = sc.unwrap(netIn, 0, netIn.length);

How SASL Mechanisms are Installed and Selected

SASL mechanism implementations are provided by SASL security providers. Each provider may support one or more SASL mechanisms and is registered with the Java Cryptography Architecture (JCA). By default, in J2SE 5, the SunSASL provider is automatically registered as a JCA provider. To remove it or reorder its priority as a JCA provider, change the line
security.provider.7=com.sun.security.sasl.Provider
in the Java Security Properties file ($JAVA_HOME/lib/security/java.security).

To add or remove a SASL provider, you add or remove the corresponding line in the Security Properties file. For example, if you want to add a SASL provider and have its mechanisms be chosen over the same ones implemented by the SunSASL provider, then you would add a line to the Security Properties file with a lower number.

security.provider.7=com.example.MyProvider
security.provider.8=com.sun.security.sasl.Provider

Alternatively, you can programmatically add your own provider using the java.security.Security class. For example, the following sample code registers the com.example.MyProvider to the list of available SASL security providers.

Security.addProvider(new com.example.MyProvider());
When an application requests a SASL mechanism by supplying one or more mechanism names, the SASL framework looks for registered SASL providers that support that mechanism by going through, in order, the list of registered providers. The providers must then determine whether the requested mechanism matches the selection policy properties and if so, return an implementation for the mechanism.

The selection policy properties specify the security aspects of a mechanism, such as its susceptibility to certain attacks. These are characteristics of the mechanism (definition), rather than its implementation so all providers should come to the same conclusion about a particular mechanism. For example, the PLAIN mechanism is susceptible to plaintext attacks regardless of how it is implemented. If no selection policy properties are supplied, there are no restrictions on the selected mechanism. Using these properties, an application can ensure that it does not use unsuitable mechanisms that might be deployed in the execution environment. For example, an application might use the following sample code if it does not want to allow the use of mechanisms susceptible to plaintext attacks.

Map props = new HashMap();
props.add(Sasl.POLICY_NOPLAINTEXT, "true");
SaslClient sc = Sasl.createSaslClient(mechanisms,
    authzid, protocol, serverName, props, callbackHandler);
See the Sasl class for descriptions of the selection policy properties.

The SunSASL Provider

The SunSASL provider supports the following client and server mechanisms.
  • Client Mechanisms
    • PLAIN (RFC 2595). This mechanism supports cleartext username/password authentication.
    • CRAM-MD5 (RFC 2195). This mechanism supports a hashed username/password authentication scheme.
    • DIGEST-MD5 (RFC 2831). This mechanism defines how HTTP Digest Authentication can be used as a SASL mechanism.
    • GSSAPI (RFC 2222). This mechanism uses the GSSAPI for obtaining authentication information. It supports Kerberos v5 authentication.
    • EXTERNAL (RFC 2222). This mechanism obtains authentication information from an external channel (such as TLS or IPsec).
  • Server Mechanisms
    • CRAM-MD5
    • DIGEST-MD5
    • GSSAPI (Kerberos v5)

Client Mechanisms

The SunSASL provider supports several SASL mechanisms used in popular protocols such as LDAP, IMAP, and SMTP. The following table summarizes the client mechanisms and their required input.
Client Mechanism Name | Parameters/Input | Callbacks | Configuration Properties | Selection Policy
CRAM-MD5 | authorization id (as default username) | NameCallback PasswordCallback |  | Sasl.POLICY_NOANONYMOUS Sasl.POLICY_NOPLAINTEXT
DIGEST-MD5 | authorization id protocol id server name | NameCallback PasswordCallback RealmCallback RealmChoiceCallback | Sasl.QOP Sasl.STRENGTH Sasl.MAX_BUFFER Sasl.SERVER_AUTH "javax.security.sasl.sendmaxbuffer" "com.sun.security.sasl.digest.cipher" | Sasl.POLICY_NOANONYMOUS Sasl.POLICY_NOPLAINTEXT
EXTERNAL | authorization id external channel |  |  | Sasl.POLICY_NOPLAINTEXT Sasl.POLICY_NOACTIVE Sasl.POLICY_NODICTIONARY
GSSAPI | JAAS Subject authorization id protocol id server name |  | Sasl.QOP Sasl.MAX_BUFFER Sasl.SERVER_AUTH "javax.security.sasl.sendmaxbuffer" | Sasl.POLICY_NOACTIVE Sasl.POLICY_NOANONYMOUS Sasl.POLICY_NOPLAINTEXT
PLAIN | authorization id | NameCallback PasswordCallback |  | Sasl.POLICY_NOANONYMOUS

An application that uses these mechanisms from the SunSASL provider must supply the required parameters, callbacks and properties. The properties have reasonable defaults and only need to be set if the application wants to override the defaults. Most of the parameters, callbacks, and properties are described in the API documentation. The following sections describe mechanism-specific behaviors and parameters not already covered by the API documentation.

Cram-MD5

The Cram-MD5 client mechanism uses the authorization id parameter, if supplied, as the default username in the NameCallback to solicit the application/end-user for the authentication id. The authorization id is otherwise not used by the Cram-MD5 mechanism; only the authentication id is exchanged with the server.

Digest-MD5

The Digest-MD5 mechanism is used for digest authentication and optional establishment of a security layer. It specifies the following ciphers for use with the security layer: Triple DES, DES and RC4 (128, 56, and 40 bits). The Digest-MD5 mechanism can support only ciphers that are available on the platform. For example, if the platform does not support the RC4 ciphers, then the Digest-MD5 mechanism will not use those ciphers.

The Sasl.STRENGTH property supports "high", "medium", and "low" settings; its default is "high,medium,low". The ciphers are mapped to the strength settings as follows.

Strength | Cipher | Cipher Id
high | Triple DES RC4 128 bits | 3des rc4
medium | DES RC4 56 bits | des rc4-56
low | RC4 40 bits | rc4-40

When there is more than one choice for a particular strength, the cipher selected depends on the availability of the ciphers in the underlying platform. To explicitly name the cipher to use, set the "com.sun.security.sasl.digest.cipher" property to the corresponding cipher id. Note that this property setting must be compatible with Sasl.STRENGTH and the ciphers available in the underlying platform. For example, Sasl.STRENGTH being set to "low" and "com.sun.security.sasl.digest.cipher" being set to "3des" are incompatible. The "com.sun.security.sasl.digest.cipher" property has no default.

The "javax.security.sasl.sendmaxbuffer" property specifies (the string representation of) the maximum send buffer size in bytes. The default is 65536. The actual maximum number of bytes will be the minimum of this number and the peer's maximum receive buffer size.

GSSAPI

The GSSAPI mechanism is used for Kerberos v5 authentication and optional establishment of a security layer. The mechanism expects the calling thread's Subject to contain the client's Kerberos credentials or that the credentials could be obtained by implicitly logging in to Kerberos. To obtain the client's Kerberos credentials, use the Java Authentication and Authorization Service (JAAS) to log in using the Kerberos login module. See the Java GSS-API and JAAS Tutorials for Use with Kerberos for details and examples. After using JAAS authentication to obtain the Kerberos credentials, you put the code that uses the SASL GSSAPI mechanism within doAs or doAsPrivileged.
LoginContext lc = new LoginContext("JaasSample", new TextCallbackHandler());
lc.login();
lc.getSubject().doAs(new SaslAction());

class SaslAction implements java.security.PrivilegedAction {
   public class run() {
       ...
       String[] mechanisms = new String[]{"GSSAPI"};
       SaslClient sc = Sasl.createSaslClient(mechanisms,
           authzid, protocol, serverName, props, callbackHandler);
       ...
   }
}
To obtain Kerberos credentials without doing explicit JAAS programming, see the Java GSS-API and JAAS Tutorials for Use with Kerberos. When using this approach, there is no need to wrap the code within doAs or doAsPrivileged.

The "javax.security.sasl.sendmaxbuffer" property specifies (the string representation of) the maximum send buffer size in bytes. The default is 65536. The actual maximum number of bytes will be the minimum of this number and the peer's maximum receive buffer size.

Server Mechanisms

Here is a table that summarizes the server mechanisms and their required input.
Server Mechanism Name | Parameters/Input | Callbacks | Configuration Properties | Selection Policy
CRAM-MD5 | server name | AuthorizeCallback NameCallback PasswordCallback |  | Sasl.POLICY_NOANONYMOUS Sasl.POLICY_NOPLAINTEXT
DIGEST-MD5 | protocol id server name | AuthorizeCallback NameCallback PasswordCallback RealmCallback | Sasl.QOP Sasl.STRENGTH Sasl.MAX_BUFFER "javax.security.sasl.sendmaxbuffer" "com.sun.security.sasl.digest.realm" "com.sun.security.sasl.digest.utf8" | Sasl.POLICY_NOANONYMOUS Sasl.POLICY_NOPLAINTEXT
GSSAPI | JAAS Subject protocol id server name | AuthorizeCallback | Sasl.QOP Sasl.MAX_BUFFER "javax.security.sasl.sendmaxbuffer" | Sasl.POLICY_NOACTIVE Sasl.POLICY_NOANONYMOUS Sasl.POLICY_NOPLAINTEXT

An application that uses these mechanisms from the SunSASL provider must supply the required parameters, callbacks and properties. The properties have reasonable defaults and only need to be set if the application wants to override the defaults.

All users of server mechanisms must have a callback handler that deals with the AuthorizeCallback. This is used by the mechanisms to determine whether the authenticated user is allowed to act on behalf of the requested authorization id, and also to obtain the canonicalized name of the authorized user (if canonicalization is applicable).

Most of the parameters, callbacks, and properties are described in the API documentation. The following sections describe mechanism-specific behaviors and parameters not already covered by the API documentation.

Cram-MD5

The Cram-MD5 server mechanism uses the NameCallback and PasswordCallback to obtain the password required to verify the SASL client's response. The callback handler should use the NameCallback.getDefaultName() as the key to fetch the password.

Digest-MD5

The Digest-MD5 server mechanism uses the RealmCallback, NameCallback, and PasswordCallback to obtain the password required to verify the SASL client's response. The callback handler should use
RealmCallback.getDefaultText() and NameCallback.getDefaultName() as keys to fetch the password.

The "javax.security.sasl.sendmaxbuffer" property is described in the Digest-MD5 client section.

The "com.sun.security.sasl.digest.realm" property is used to specify a list of space-separated realm names that the server supports. The list is sent to the client as part of the challenge. If this property has not been set, the default realm is the server's name (supplied as a parameter).

The "com.sun.security.sasl.digest.utf8" property is used to specify the character encoding to use. "true" means to use UTF-8 encoding; "false" means to use ISO Latin 1 (ISO-8859-1). The default is "true".

GSSAPI

The GSSAPI server mechanism has the same requirements as the GSSAPI client mechanism in terms of Kerberos credentials and the "javax.security.sasl.sendmaxbuffer" property.

Debugging and Monitoring

The SunSASL provider uses the Logging APIs to provide implementation logging output. This output can be controlled by using the logging configuration file and programmatic API (java.util.logging). The logger name used by the SunSASL provider is "javax.security.sasl". Here is a sample logging configuration file that enables the FINEST logging level for the SunSASL provider.
javax.security.sasl.level=FINEST
handlers=java.util.logging.ConsoleHandler
java.util.logging.ConsoleHandler.level=FINEST

The table below shows the mechanisms and the logging output that they generate.

Mechanism | Logging Level | Information Logged
CRAM-MD5 | FINE | Configuration properties; challenge/response messages
DIGEST-MD5 | INFO | Message discarded due to encoding problem (e.g., unmatched MACs, incorrect padding)
DIGEST-MD5 | FINE | Configuration properties; challenge/response messages
DIGEST-MD5 | FINER | More detailed information about challenge/response messages
DIGEST-MD5 | FINEST | Buffers exchanged at the security layer
GSSAPI | FINE | Configuration properties; challenge/response messages
GSSAPI | FINER | More detailed information about challenge/response messages
GSSAPI | FINEST | Buffers exchanged at the security layer

Implementing a SASL Security Provider

There are three basic steps in implementing a SASL security provider.
  1. Write a class that implements the SaslClient or SaslServer interface.
  2. Write a factory class (that implements SaslClientFactory or SaslServerFactory) that creates instances of the class.
  3. Write a JCA provider that registers the factory.

The first step involves providing an implementation for the SASL mechanism. To implement a client mechanism, you need to implement the methods declared in the SaslClient interface. Similarly, for a server mechanism, you need to implement the methods declared in the SaslServer interface. For the purposes of this discussion, suppose you are developing an implementation for the client mechanism "SAMPLE-MECH", implemented by the class, com.example.SampleMechClient. You must decide what input are needed by the mechanism and how the implementation is going to collect them. For example, if the mechanism is username/password-based, then the implementation would likely need to collect that information via the callback handler parameter.

The next step involves providing a factory class that will create instances of com.example.SampleMechClient. The factory needs to determine the characteristics of the mechanism that it supports (as described by the Sasl.POLICY_* properties) so that it can return an instance of the mechanism when the API user requests it using compatible policy properties. The factory may also check for validity of the parameters before creating the mechanism. For the purposes of this discussion, suppose the factory class is named com.example.MySampleClientFactory. Although our sample factory is responsible for only one mechanism, a single factory can be responsible for any number of mechanisms.

The final step involves creating a JCA provider. The steps for creating a JCA provider is described in detail in the document, How to Implement a Provider for the Java Cryptography Architecture. SASL client factories are registered using property names of the form

SaslClientFactory.mechName

while SASL server factories are registered using property names of the form

SaslServerFactory.mechName

mechName is the SASL mechanism's name. This is what's returned by SaslClient.getMechanismName() and SaslServer.getMechanismName(). Continuing with our example, here is how the provider would register the "SAMPLE-MECH" mechanism.

put("SaslClientFactory.SAMPLE-MECH", "com.example.MySampleClientFactory");

A single SASL provider might be responsible for many mechanisms. Therefore, it might have many invocations of put to register the relevant factories. The completed SASL provider can then be made available to applications using the instructions given previously.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JAXB RI 2.1.3 -- Schema Generator (schemagen)

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

schemagen - Java™ Architecture for XML Binding Schema Generator

Specification Version: 2.1
Implementation Version: 2.1.3

Launching schemagen

The schema generator can be launched using the appropriate schemagen shell script in the bin directory for your platform.

The current schema generator can process either Java source files or class files.

We also provide an Ant task to run the schema generator - see the instructions for using schemagen with Ant.

% schemagen.sh Foo.java Bar.java ...
Note: Writing schema1.xsd

If your java sources/classes reference other classes, they must be accessable on your system CLASSPATH environment variable, or they need to be given to the tool by using the -classpath/-cp options. Otherwise you will see errors when generating your schema.

Command Line Options

Usage: schemagen [-options ...] <java files>

Options:
    -d <path>             : specify where to place processor and javac generated class files
    -cp <path>            : specify where to find user specified files
    -classpath <path>     : specify where to find user specified files
    -encoding <encoding>  : specify encoding to be used for apt/javac invocation

    -episode <file>       : generate episode file for separate compilation
    -version              : display version information
    -help                 : display this usage message

Generated Resource Files

The current schema generator simply creates a schema file for each namespace referenced in your Java classes. There is no way to control the name of the generated schema files at this time. For that purpose, use the schema generator ant task.

See Also

  • Running the schema generator (schemagen): [command-line instructions, using the SchemaGen Ant task]
  • Java Architecture for XML Binding (JAXB)
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.source.tree.Scope (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.Scope

  • Packages that use Scope
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of Scope in com.sun.source.tree

      Methods in com.sun.source.tree that return Scope
      Modifier and Type Method and Description
      Scope Scope.getEnclosingScope()
      Returns the enclosing scope.

    • Uses of Scope in com.sun.source.util

      Methods in com.sun.source.util that return Scope
      Modifier and Type Method and Description
      abstract Scope Trees.getScope(TreePath path)
      Gets the Scope for the Tree node identified by a given TreePath.
      Methods in com.sun.source.util with parameters of type Scope
      Modifier and Type Method and Description
      abstract boolean Trees.isAccessible(Scope scope, Element member, DeclaredType type)
      Checks whether the given element is accessible as a member of the given type in a given scope.
      abstract boolean Trees.isAccessible(Scope scope, TypeElement type)
      Checks whether a given type is accessible in a given scope.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Contents | Previous | Next Java Management Extensions (JMX) Technology Tutorial

Chapter 5

Security

This chapter gives examples of how to set up the JMX technology security features, as described in the following sections:

  • Section "Simple Security" presents examples of connectors that implement straightforward security based on password authentication and file access control.
  • Section "Subject Delegation" presents examples of connectors that use the subject delegation model to perform operations on a given authenticated connection on behalf of several different identities.
  • Section "Fine-Grained Security" presents examples of connectors that implement more sophisticated security mechanisms, in which permission to perform individual operations is controlled.

Simple Security

The simplest type of security you can use with the JMX technology is based upon encryption, user name and password authentication, and file access control.

RMI Connectors With Simple Security

You can find an example of an RMI connector with simple security in the directory work_dir/jmx_examples/Security/simple.

  2. Open the work_dir/jmx_examples/Security/simple directory.

    Inside this directory you will find the following directories:

    • /server, containing the fileServer.java
    • /config, containing the security configuration files:
    • access.properties
    • keystore
    • password.properties
    • truststore
    • /mbeans, containing the following files:
    • SimpleStandardMBean.java
    • SimpleStandard.java
    • /client, containing the following files:
    • Client.java
    • ClientListener.java
  3. Open all the *.java and *.properties files in a text editor

    These files will be analyzed in the following sections.

Server.java

The Server.java class is shown in CODE EXAMPLE 5-1.

CODE EXAMPLE 5-1 RMI Connector Example (Simple Security) Class Server.java

public class Server {

  public static void main(String[] args) {
  try {
       MBeanServer mbs = MBeanServerFactory.createMBeanServer();

       HashMap env = new HashMap();

       SslRMIClientSocketFactory csf =
                  new SslRMIClientSocketFactory();
       SslRMIServerSocketFactory ssf =
                  new SslRMIServerSocketFactory();
       env.put(RMIConnectorServer.
                  RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE,csf);
       env.put(RMIConnectorServer.
                  RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE,ssf);

       env.put("jmx.remote.x.password.file",
                 "config" + File.separator + "password.properties");
       env.put("jmx.remote.x.access.file",
                 "config" + File.separator + "access.properties");

       JMXServiceURL url = new JMXServiceURL(
        "service:jmx:rmi:///jndi/rmi://localhost:9999/server");
         JMXConnectorServer cs =
            JMXConnectorServerFactory.newJMXConnectorServer(url,
                                                            env,
                                                            mbs);
       cs.start();
     } catch (Exception e) {
       e.printStackTrace();
     }
  }
}

The Server class shown in CODE EXAMPLE 5-1 creates an MBean server mbs, and populates an environment map env with a secure RMI client socket factory csf, a secure RMI server socket factory ssf, and the properties files password.properties and access.properties.

The properties file password.properties contains a username and password and is accessed using the JMX Remote API interface JMXAuthenticator. Using the property jmx.remote.x.password.file is the same as creating a password-based JMXAuthenticator and passing it into the environment map through the jmx.remote.authenticator property.

The properties file access.properties contains a username and a level of access permission that can be either readwrite or readonly. This represents the level of access this user can have to MBean server operations. This file-based access control is implemented using the JMX technology interface MBeanServerForwarder, which wraps the real MBean server inside an access controller MBean server. The access controller MBean server only forwards requests to the real MBean server after performing the appropriate checks.

Server creates a JMX service URL, named url, for an RMI connector that will operate over the default JRMP transport, and register an RMI connector stub in an RMI registry on port 9999 of the local host.

The MBean server mbs, the environment map env and the service URL url are all passed to JMXConnectorServer to create a new, secure JMX connector server named cs.

SimpleStandardMBean.java

The SimpleStandardMBean class defines the same straightforward MBean interface as was used in Chapter 3, "JMX Connectors".

SimpleStandard.java

The SimpleStandard class defines the same straightforward MBean as was used in Chapter 3, "JMX Connectors".

ClientListener.java

The ClientListener class defines the same straightforward notification listener as was used in Chapter 3, "JMX Connectors".

Client.java

The Client.java class is shown in CODE EXAMPLE 5-1.

CODE EXAMPLE 5-1 RMI Connector Example (Simple Security) Class Client.java

public class Client {

  public static void main(String[] args) {
  try {
      HashMap env = new HashMap();

      String[] credentials = new String[] { "username" , "password" };
      env.put("jmx.remote.credentials", credentials);
      JMXServiceURL url = new JMXServiceURL(
         "service:jmx:rmi:///jndi/rmi://localhost:9999/server");
      JMXConnector jmxc = JMXConnectorFactory.connect(url, env);
      MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
      String domains[] = mbsc.getDomains();
      for (int i = 0; i < domains.length; i++) {
         System.out.println("Domain[" + i + "] = " + domains[i]);
      }

      ObjectName mbeanName =
          new ObjectName("MBeans:type=SimpleStandard");
      mbsc.createMBean("SimpleStandard", mbeanName, null, null);
      // Perform MBean operations
      [...]

      mbsc.removeNotificationListener(mbeanName, listener);
      mbsc.unregisterMBean(mbeanName);
      jmxc.close();
    }  catch (Exception e) {
      e.printStackTrace();
    }
  }
}

The Client class shown in CODE EXAMPLE 5-1 populates an environment map env with a set of credentials, namely the username and password expected by the Server. These credentials are then given to an instance of JMXConnector named jmxc when the service URL of the connector stub and the environment map are passed to JMXConnectorFactory.connect(). Through jmxc, the Client connects to the MBean server started by Server, and performs MBean operations.

When the connection is established, the credentials supplied in the environment map env are sent to the server. The server then calls the authenticate() method of the JMXAuthenticator interface, passing the client credentials as parameters. The authenticate() method authenticates the client and returns a subject that contains the set of principals upon which the access control checks will be performed.

Running the RMI Connector Example With Simple Security

To run the RMI connector example with simple security, perform the following steps:

  • $ javac
      mbeans/SimpleStandard.java \
      mbeans/SimpleStandardMBean.java \
      server/Server.java \
      client/Client.java \
      client/ClientListener.java
  • Start an RMI registry on port 9999 of the local host.
  •
$ export CLASSPATH=server ; rmiregistry 9999 &
  • Start the Server.
  •
$ java -classpath server:mbeans \
     -Djavax.net.ssl.keyStore=config/keystore \
     -Djavax.net.ssl.keyStorePassword=password \
     Server &

    You will see confirmation of the creation of the MBean server and of the RMI connector.

  • Start the Client.
  •
$java -classpath client:server:mbeans \
     -Djavax.net.ssl.trustStore=config/truststore \
     -Djavax.net.ssl.trustStorePassword=trustword \
     Client

    You will see confirmation of the creation of the connector client, the various MBean operations followed by the closure of the connection.

    As you can see, all the above appears to proceed in exactly the same manner as the basic RMI connector example shown in Chapter 3, "JMX Connectors". However, if you were to open password.properties and change the password, you would see a java.lang.SecurityException when you launched the Client, and the connection would fail.

    Subject Delegation

    If your implementation requires the client end of the connection to perform different operations on behalf of multiple users or applications, using the security mechanisms demonstrated in Section "Simple Security", each different user would require one secure connection for every operation it performs. If you expect your connector clients to interact with numerous users, you can reduce the load on your system by implementing subject delegation. Subject delegation establishes a single secure connection for a user, and this connection can be used to perform related operations on behalf of any number of users. The connection itself is made by an authenticated user. If the authenticated user has been granted a SubjectDelegationPermission that allows it to act on behalf of another user, then operations can be performed over the connection on behalf of that user.

    Secure RMI Connectors With Subject Delegation

    You can find an example of a secure RMI connector that implements subject delegation in the directory work_dir/jmx_examples/Security/subject_delegation.

    2. Open the work_dir/jmx_examples/Security/subject_delegation directory

      Inside this directory you will find the following directories:

      • /server, containing the file Server.java:
      • /config, containing the security configuration files:
      • access.properties
      • java.policy
      • password.properties
      • /mbeans, containing the following files:
      • SimpleStandardMBean.java
      • SimpleStandard.java
      • /client, containing the following files:
      • Client.java
      • ClientListener.java
    3. Open all the *.java and *.properties files in a text editor

      These files will be analyzed in the following sections.

    Server.java

    The Server.java class is shown in CODE EXAMPLE 5-1:

    CODE EXAMPLE 5-1 Secure RMI Connector (Subject Delegation) Example Class Server.java

public class Server {

   public static void main(String[] args) {
     try {
          MBeanServer mbs = MBeanServerFactory.createMBeanServer();
          HashMap env = new HashMap();
          env.put("jmx.remote.x.password.file",
                  "config" + File.separator + "password.properties");
          env.put("jmx.remote.x.access.file",
                  "config" + File.separator + "access.properties");

          JMXServiceURL url = new JMXServiceURL(
             "service:jmx:rmi:///jndi/rmi://localhost:9999/server");
          JMXConnectorServer cs =
              JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
          cs.start();
     } catch (Exception e) {
          e.printStackTrace();
     }
   }
}

    CODE EXAMPLE 5-1 begins with the creation of an MBean server mbs, and the population of an environment map env with a password file and an access file, called password.properties and access.properties respectively:

    • The password file contains a username and password combination that is used to authenticate users that try to make connections.
    • The access file contains a user name and access level combination that is used to authorize access to the MBeans in the MBean server. The access level is either readwrite or readonly.

    The Server then creates a connector server named cs, and starts it in exactly the same way as in the previous RMI connector examples.

    java.policy

    The java.policy file grants to username a SubjectDelegationPermission so it can perform operations on behalf of the user delegate, an instance of JMXPrincipal created by the Client class. The java.policy file is required when launching the Server class.

    SimpleStandardMBean.java

    The SimpleStandardMBean class defines the same straightforward MBean interface as was used in the previous examples.

    SimpleStandard.java

    The SimpleStandard class defines the same straightforward MBean as was used in the previous examples.

    ClientListener.java

    The ClientListener class defines the same straightforward notification listener as was used in the previous examples.

    Client.java

    The Client.java class is shown in CODE EXAMPLE 5-1:

    CODE EXAMPLE 5-1 Secure RMI Connector (Subject Delegation) Example Class Client.java

public class Client {

  public static void main(String[] args) {
    try {
         HashMap env = new HashMap();
         String[] credentials = new String[] { "username" , "password" };
         env.put("jmx.remote.credentials", credentials);
         JMXServiceURL url = new JMXServiceURL(
            "service:jmx:rmi:///jndi/rmi://localhost:9999/server");
         JMXConnector jmxc = JMXConnectorFactory.connect(url, env);
         Subject delegationSubject =
            new Subject(true,
                Collections.singleton(new JMXPrincipal("delegate")),
                Collections.EMPTY_SET,
                Collections.EMPTY_SET);

         MBeanServerConnection mbsc =
            jmxc.getMBeanServerConnection(delegationSubject);
         String domains[] = mbsc.getDomains();
         ObjectName mbeanName =
            new ObjectName("MBeans:type=SimpleStandard");
         mbsc.createMBean("SimpleStandard", mbeanName, null, null);
         // Perform MBean operations
         //

[...]
         mbsc.removeNotificationListener(mbeanName, listener);
         mbsc.unregisterMBean(mbeanName);
         jmxc.close();
     } catch (Exception e) {
         e.printStackTrace();
     }
  }
}

    CODE EXAMPLE 5-1 begins with the creation of an environment map env that is populated with a user name username and a password password. These strings match the user name and password stored in the password.properties file that is held by the Server to authenticate users accessing the connector server.

    A JMX technology connector client jmxc is created in the same way as in the previous RMI connector examples, with the user name and password passed into the environment map env.

    The Client then creates an instance of Subject, called delegationSubject, with a Principal that is an instance of JMXPrincipal, named delegate.

    An MBean server connection, named mbsc, is created by calling the getMBeanServerConnection() method of JMXConnector, with delegationSubject passed in as a parameter. This MBean server connection therefore allows operations to be performed on the remote MBean server on behalf of the principals stored in the delegationSubject, which in this example is the JMXPrincipal named delegate.

    The example continues by creating and registering the SimpleStandard MBean in the MBean server, and performing operations on it, in exactly the same way as in the previous examples.

    Running the Secure RMI Connector Example With Subject Delegation

    To run the secure RMI connector example with subject delegation, perform the following steps:

    $ javac  mbeans/SimpleStandard.java \
  mbeans/SimpleStandardMBean.java \
  server/Server.java \
  client/Client.java \
  client/ClientListener.java
    • Start an RMI registry on port 9999 of the local host.

    • $ export CLASSPATH=server ; rmiregistry 9999 &

    • Start the Server.
    • $ java -classpath server:mbeans \
  -Djava.security.policy=config/java.policy Server &

      You will see confirmation of the creation of the MBean server, the initialization of the environment map, the creation of the RMI connector, and the registration of the connector in the MBean server.

    • Start the Client.

    • $ java -classpath client:server:mbeans Client

      You will see confirmation of the creation of the connector client, the creation of the delegation subject, the connection to the MBean server and the various MBean operations followed by the closure of the connection.

      Fine-Grained Security

      You can implement a more fine-grained level of security in your connectors by managing user access through the Java Authentication and Authorization Service (JAAS) and Java platform Standard Edition (Java SE) Security Architecture. JAAS and Java SE security is based on the use of security managers and policy files to allocate different levels of access to different users. Consequently, you can decide more precisely which users are allowed to perform which operations.

      The two examples in this section are very similar to those shown in Section "Simple Security", with the difference being that the simple, file-based access control has been replaced by policy-based access control.

      RMI Connectors With Fine-Grained Security

      You can find an example of an RMI connector with fine-grained security in the directory work_dir/jmx_examples/Security/fine_grained.

      2. Open work_dir/jmx_examples/Security/fine_grained.

        Inside this directory you will find the following directories:

        • /server, containing the fileServer.java
        • /config, containing the security configuration files:
        • java.policy
        • keystore
        • password.properties
        • truststore
        • /mbeans, containing the following files:
        • SimpleStandard.java
        • SimpleStandardMBean.java
        • /client, containing the following files:
        • ClientListener.java
        • Client.java
      3. Open all the *.java and *.properties files in a text editor.

        The files will be analyzed in the following sections.Server.java

        The Server.java class used in this example is very similar to the one used in the RMI connector example with simple security. The only difference is that there is no access.properties file to map into the environment map in the fine-grained example. Otherwise, the two classes are identical.

        java.policy

        The java.policy file grants the following permissions:

        • All permissions to the server code base, so that the connector server can create the connectors, and then perform the operations requested by remote user calls
        • MBeanTrustPermission to the mbeans code base, allowing trusted MBeans to register in the MBean server
        • Permission to perform the various MBean and MBean server operations for the user represented by a JMXPrincipal named username.

        SimpleStandardMBean.java

        The SimpleStandardMBean class defines the same straightforward MBean interface as was used in the previous examples.

        SimpleStandard.java

        The SimpleStandard class defines the same straightforward MBean as was used in the previous examples.

        ClientListener.java

        The ClientListener class defines the same straightforward notification listener as as was used in the previous examples.

        Client.java

        The Client.java class is exactly the same as the one used in the RMI connector example with simple security.

        Running the RMI Connector Example With Fine-Grained Security

        To run the RMI connector example with fine-grained security, perform the following steps:

        $ javac
      mbeans/SimpleStandard.java \
      mbeans/SimpleStandardMBean.java \
      server/Server.java \
      client/Client.java \
      client/ClientListener.java
      4. Start an RMI registry on port 9999 of the local host.

        $ export CLASSPATH=server ; rmiregistry 9999 &

      5. Start the Server.
        $ java -classpath server:mbeans \
     -Djavax.net.ssl.keyStore=config/keystore \
     -Djavax.net.ssl.keyStorePassword=password \
     -Djava.security.manager \
     -Djava.security.policy=config/java.policy \
     Server &

        You will see confirmation of the initialization of the environment map, the creation of the MBean server and of the RMI connector.

      6. Start the Client.

$ java -classpath client:server:mbeans \
     -Djavax.net.ssl.trustStore=config/truststore \
     -Djavax.net.ssl.trustStorePassword=trustword \
     Client

        You will see confirmation of the creation of the connector client, the connection to the RMI server and the various MBean operations followed by the closure of the connection.

      Contents | Previous | Next

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Long description needed.


Java Security Architecture: Contents

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

JavaTM SE Platform Security Architecture

Author: Li Gong

Version 1.2

This document gives an overview of the motivation of the major security features that are being implemented for JavaTM SE Platform Security, introduces the new classes and their usage, discusses the impact of this new architecture on existing code, and gives thoughts on writing security-sensitive code in the future.

CONTENTS | PREV | NEXT
Copyright © 1997-2002 Sun Microsystems, Inc. All Rights Reserved.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Security Architecture: -

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

1 Introduction

Since the inception of Java technology, there has been strong and growing interest around the security of the Java platform as well as new security issues raised by the deployment of Java technology.

From a technology provider's point of view, Java security includes two aspects:

  • Provide the Java platform as a secure, ready-built platform on which to run Java-enabled applications in a secure fashion.
  • Provide security tools and services implemented in the Java programming language that enable a wider range of security-sensitive applications, for example, in the enterprise world.
This document discusses issues related to the first aspect, where the customers for such technologies include vendors that bundle or embed Java technology in their products (such as browsers and operating systems).

1.1 The Original Sandbox Model

The original security model provided by the Java platform is known as the sandbox model, which existed in order to provide a very restricted environment in which to run untrusted code obtained from the open network. The essence of the sandbox model is that local code is trusted to have full access to vital system resources (such as the file system) while downloaded remote code (an applet) is not trusted and can access only the limited resources provided inside the sandbox. This sandbox model is illustrated in the figure below.

The previous context describes this graphic.

The sandbox model was deployed through the Java Development Kit (JDK), and was generally adopted by applications built with JDK 1.0, including Java-enabled web browsers.

Overall security is enforced through a number of mechanisms. First of all, the language is designed to be type-safe and easy to use. The hope is that the burden on the programmer is such that the likelihood of making subtle mistakes is lessened compared with using other programming languages such as C or C++. Language features such as automatic memory management, garbage collection, and range checking on strings and arrays are examples of how the language helps the programmer to write safe code.

Second, compilers and a bytecode verifier ensure that only legitimate Java bytecodes are executed. The bytecode verifier, together with the Java Virtual Machine, guarantees language safety at run time.

Moreover, a classloader defines a local name space, which can be used to ensure that an untrusted applet cannot interfere with the running of other programs.

Finally, access to crucial system resources is mediated by the Java Virtual Machine and is checked in advance by a SecurityManager class that restricts the actions of a piece of untrusted code to the bare minimum.

JDK 1.1 introduced the concept of a "signed applet", as illustrated by the figure below. In that release, a correctly digitally signed applet is treated as if it is trusted local code if the signature key is recognized as trusted by the end system that receives the applet. Signed applets, together with their signatures, are delivered in the JAR (Java Archive) format. In JDK 1.1, unsigned applets still run in the sandbox.

The previous context describes this graphic

1.2 Evolving the Sandbox Model

The new Java SE Platform Security Architecture, illustrated in the figure below, is introduced primarily for the following purposes.

See long description [D]

  • Fine-grained access control.
This capability existed in the JDK from the beginning, but to use it, the application writer had to do substantial programming (e.g., by subclassing and customizing the SecurityManager and ClassLoader classes). The HotJava browser 1.0 is such an application, as it allows the browser user to choose from a small number of different security levels.

However, such programming is extremely security-sensitive and requires sophisticated skills and in-depth knowledge of computer security. The new architecture will make this exercise simpler and safer.

  • Easily configurable security policy.
Once again, this capability existed previously in the JDK but was not easy to use. Moreover, writing security code is not straightforward, so it is desirable to allow application builders and users to configure security policies without having to program.
  • Easily extensible access control structure.
Up to JDK 1.1, in order to create a new access permission, you had to add a new check method to the SecurityManager class. The new architecture allows typed permissions (each representing an access to a system resource) and automatic handling of all permissions (including yet-to-be-defined permissions) of the correct type. No new method in the SecurityManager class needs to be created in most cases. (In fact, we have so far not encountered a situation where a new method must be created.)
  • Extension of security checks to all Java programs, including applications as well as applets.
There is no longer a built-in concept that all local code is trusted. Instead, local code (e.g., non-system code, application packages installed on the local file system) is subjected to the same security control as applets, although it is possible, if desired, to declare that the policy on local code (or remote code) be the most liberal, thus enabling such code to effectively run as totally trusted. The same principle applies to signed applets and any Java application.

Finally, an implicit goal is to make internal adjustment to the design of security classes (including the SecurityManager and ClassLoader classes) to reduce the risks of creating subtle security holes in future programming.

CONTENTS | PREV | NEXT
Copyright © 1997-1999 Sun Microsystems, Inc. All Rights Reserved.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Security Architecture: -

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

2 New Protection Mechanisms -- Overview of Basic Concepts

We now go over, in some detail, the new protection architecture and give a brief explanation of its functionality. We start with an overview of the basic concepts behind the new architecture. We then introduce the major new classes in a natural order, starting with permission specifications, going on to the policy and related features, followed by access control and its usage, and then covering secure class loading and resolution.

A fundamental concept and important building block of system security is the protection domain [Saltzer and Schroeder 75]. A domain can be scoped by the set of objects that are currently directly accessible by a principal, where a principal is an entity in the computer system to which permissions (and as a result, accountability) are granted. The sandbox utilized in JDK 1.0 is one example of a protection domain with a fixed boundary.

The protection domain concept serves as a convenient mechanism for grouping and isolation between units of protection. For example, it is possible (but not yet provided as a built-in feature) to separate protection domains from interacting with each other so that any permitted interaction must be either through trusted system code or explicitly allowed by the domains concerned. Note that existing object accessibility rules remain valid under the new security architecture.

Protection domains generally fall into two distinct categories: system domain and application domain. It is important that all protected external resources, such as the file system, the networking facility, and the screen and keyboard, be accessible only via system domains. The figure below illustrates the domain composition of a Java application environment.

See long description [D]

A domain conceptually encloses a set of classes whose instances are granted the same set of permissions. Protection domains are determined by the policy currently in effect. The Java application environment maintains a mapping from code (classes and instances) to their protection domains and then to their permissions, as illustrated by the figure below.

See long description [D]

A thread of execution (which is often, but not necessarily tied to, a single Java thread, which in turn is not necessarily tied to the thread concept of the underlying operation system) may occur completely within a single protection domain or may involve an application domain and also the system domain. For example, an application that prints a message out will have to interact with the system domain that is the only access point to an output stream. In this case, it is crucial that at any time the application domain does not gain additional permissions by calling the system domain. Otherwise, there can be serious security implications.

In the reverse situation where a system domain invokes a method from an application domain, such as when the AWT system domain calls an applet's paint method to display the applet, it is again crucial that at any time the effective access rights are the same as current rights enabled in the application domain.

In other words, a less "powerful" domain cannot gain additional permissions as a result of calling or being called by a more powerful domain.

This discussion of one thread involving two protection domains naturally generalizes to a thread that traverses multiple protection domains. A simple and prudent rule of thumb for calculating permissions is the following:

  • The permission set of an execution thread is considered to be the intersection of the permissions of all protection domains traversed by the execution thread.
  • When a piece of code calls the doPrivileged method (see below), the permission set of the execution thread is considered to include a permission if it is allowed by the said code's protection domain and by all protection domains that are called or entered directly or indirectly subsequently.
As you can see, the doPrivileged method enables a piece of trusted code to temporarily enable access to more resources than are available directly to the application that called it. This is necessary in some situations. For example, an application may not be allowed direct access to files that contain fonts, but the system utility to display a document must obtain those fonts, on behalf of the user. We provide the doPrivileged method for the system domain to deal with this situation, and the method is in fact available to all domains.

During execution, when access to a critical system resource (such as file I/O and network I/O) is requested, the resource-handling code directly or indirectly invokes a special AccessController class method that evaluates the request and decides if the request should be granted or denied.

Such an evaluation follows and generalizes the "rule of thumb" given above. The actual way in which the evaluation is conducted can vary between implementations. The basic principle is to examine the call history and the permissions granted to the relevant protection domains, and to return silently if the request is granted or throw a security exception if the request is denied.

Finally, each domain (system or application) may also implement additional protection of its internal resources within its own domain boundary. For example, a banking application may need to support and protect internal concepts such as checking accounts, deposits and withdrawals. Because the semantics of such protection is unlikely to be predictable or enforceable by the Java 2 SDK, the protection system at this level is best left to the system or application developers. Nevertheless, whenever appropriate, we provide helpful primitives to simplify developers' tasks. One such primitive is the SignedObject class, whose detail we will describe later.

CONTENTS | PREV | NEXT
Copyright © 1997-1999 Sun Microsystems, Inc. All Rights Reserved.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Security Architecture: -

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

3 Permissions and Security Policy

3.1 The Permission Classes

The permission classes represent access to system resources. The java.security.Permission class is an abstract class and is subclassed, as appropriate, to represent specific accesses.

As an example of a permission, the following code can be used to produce a permission to read the file named "abc" in the /tmp directory:

    perm = new java.io.FilePermission("/tmp/abc", "read");
New permissions are subclassed either from the Permission class or one of its subclasses, such as java.security.BasicPermission. Subclassed permissions (other than BasicPermission) generally belong to their own packages. Thus, FilePermission is found in the java.io package.

A crucial abstract method that needs to be implemented for each new class of permission is the implies method. Basically, "a implies b" means that if one is granted permission "a", one is naturally granted permission "b". This is important when making access control decisions.

Associated with the abstract class java.security.Permission are the abstract class named java.security.PermissionCollection and the final class java.security.Permissions.

Class java.security.PermissionCollection represents a collection (i.e., a set that allows duplicates) of Permission objects for a single category (such as file permissions), for ease of grouping. In cases where permissions can be added to the PermissionCollection object in any order, such as for file permissions, it is crucial that the PermissionCollection object ensure that the correct semantics are followed when the implies function is called.

Class java.security.Permissions represents a collection of collections of Permission objects, or in other words, a super collection of heterogeneous permissions.

Applications are free to add new categories of permissions that the system supports. How to add such application-specific permissions is discussed later in this document.

Now we describe the syntax and semantics of all built-in permissions.

3.1.1 java.security.Permission

This abstract class is the ancestor of all permissions. It defines the essential functionalities required for all permissions.

Each permission instance is typically generated by passing one or more string parameters to the constructor. In a common case with two parameters, the first parameter is usually "the name of the target" (such as the name of a file for which the permission is aimed), and the second parameter is the action (such as "read" action on a file). Generally, a set of actions can be specified together as a comma-separated composite string.

3.1.2 java.security.PermissionCollection

This class holds a homogeneous collection of permissions. In other words, each instance of the class holds only permissions of the same type.

3.1.3 java.security.Permissions

This class is designed to hold a heterogeneous collection of permissions. Basically, it is a collection of java.security.PermissionCollection objects.

3.1.4 java.security.UnresolvedPermission

Recall that the internal state of a security policy is normally expressed by the permission objects that are associated with each code source. Given the dynamic nature of Java technology, however, it is possible that when the policy is initialized the actual code that implements a particular permission class has not yet been loaded and defined in the Java application environment. For example, a referenced permission class may be in a JAR file that will later be loaded.

The UnresolvedPermission class is used to hold such "unresolved" permissions. Similarly, the class java.security.UnresolvedPermissionCollection stores a collection of UnresolvedPermission permissions.

During access control checking on a permission of a type that was previously unresolved, but whose class has since been loaded, the unresolved permission is "resolved" and the appropriate access control decision is made. That is, a new object of the appropriate class type is instantiated, if possible, based on the information in the UnresolvedPermission. This new object replaces the UnresolvedPermission, which is removed.

If the permission is still unresolvable at this time, the permission is considered invalid, as if it is never granted in a security policy.

3.1.5 java.io.FilePermission

The targets for this class can be specified in the following ways, where directory and file names are strings that cannot contain white spaces.
file
directory (same as directory/)
directory/file
directory/* (all files in this directory)
* (all files in the current directory)
directory/- (all files in the file system under this directory)
- (all files in the file system under the current directory)
"<<ALL FILES>>" (all files in the file system)
Note that "<<ALL FILES>>" is a special string denoting all files in the system. On a Unix system, this includes all files under the root directory. On an MS-DOS system, this includes all files on all drives.

The actions are: read, write, delete, and execute. Therefore, the following are valid code samples for creating file permissions:

import java.io.FilePermission;

FilePermission p = new FilePermission("myfile", "read,write");
FilePermission p = new FilePermission("/home/gong/", "read");
FilePermission p = new FilePermission("/tmp/mytmp", "read,delete");
FilePermission p = new FilePermission("/bin/*", "execute");
FilePermission p = new FilePermission("*", "read");
FilePermission p = new FilePermission("/-", "read,execute");
FilePermission p = new FilePermission("-", "read,execute");
FilePermission p = new FilePermission("<<ALL FILES>>", "read");
> The implies method in this class correctly interprets the file system. For example, FilePermission("/-", "read,execute") implies FilePermission("/home/gong/public_html/index.html", "read"), and FilePermission("bin/*", "execute") implies FilePermission("bin/emacs19.31", "execute").

Note: Most of these strings are given in platform-dependent format. For example, to represent read access to the file named "foo" in the "temp" directory on the C drive of a Windows system, you would use

FilePermission p = new FilePermission("c:\\temp\\foo", "read");
The double backslashes are necessary to represent a single backslash because the strings are processed by a tokenizer (java.io.StreamTokenizer), which allows "\" to be used as an escape string (e.g., "\n" to indicate a new line) and which thus requires two backslashes to indicate a single backslash. After the tokenizer has processed the above FilePermission target string, converting double backslashes to single backslashes, the end result is the actual path
"c:\temp\foo"
It is necessary that the strings be given in platform-dependent format until there is a universal file description language. Note also that the use of meta symbols such as "*" and "-" prevents the use of specific file names. We think this is a small limitation that can be tolerated for the moment. Finally, note that "/-" and "<<ALL FILES>>" are the same target on Unix systems in that they both refer to the entire file system. (They can refer to multiple file systems if they are all available). The two targets are potentially different on other operating systems, such as MS Windows and MacOS.

Also note that a target name that specifies just a directory, with a "read" action, as in

FilePermission p = new FilePermission("/home/gong/", "read");
means you are only giving permission to list the files in that directory, not read any of them. To allow read access to files, you must specify either an explicit file name, or an "*" or "-", as in
FilePermission p = new FilePermission("/home/gong/myfile", "read");
FilePermission p = new FilePermission("/home/gong/*", "read");
FilePermission p = new FilePermission("/home/gong/-", "read");
And finally, note that code always automatically has permission to read files from its same (URL) location, and subdirectories of that location; it does not need explicit permission to do so.

3.1.6 java.net.SocketPermission

This class represents access to a network via sockets. The target for this class can be given as "hostname:port_range", where hostname can be given in the following ways:
hostname (a single host)
IP address (a single host)
localhost (the local machine)
"" (equivalent to "localhost")
hostname.domain (a single host within the domain)
hostname.subdomain.domain
*.domain (all hosts in the domain)
*.subdomain.domain
* (all hosts)
That is, the host is expressed as a DNS name, as a numerical IP address, as "localhost" (for the local machine) or as "" (which is equivalent to specifying "localhost").

The wildcard "*" may be included once in a DNS name host specification. If it is included, it must be in the leftmost position, as in "*.sun.com".

The port_range can be given as follows:

N (a single port)
N- (all ports numbered N and above)
-N (all ports numbered N and below)
N1-N2 (all ports between N1 and N2, inclusive)
Here N, N1, and N2 are non-negative integers ranging from 0 to 65535 (2^16-1).

The actions on sockets are accept, connect, listen, and resolve (which is basically DNS lookup). Note that implicitly, the action "resolve" is implied by "accept", "connect", and "listen" -- i.e., those who can listen or accept incoming connections from or initiate out-going connections to a host should be able to look up the name of the remote host.

Below are some examples of socket permissions.

import java.net.SocketPermission;

SocketPermission p = new SocketPermission("java.sun.com","accept");
p = new SocketPermission("204.160.241.99","accept");
p = new SocketPermission("*.com","connect");
p = new SocketPermission("*.sun.com:80","accept");
p = new SocketPermission("*.sun.com:-1023","accept");
p = new SocketPermission("*.sun.com:1024-","connect");
p = new SocketPermission("java.sun.com:8000-9000",
         "connect,accept");
p = new SocketPermission("localhost:1024-",
          "accept,connect,listen");
Note that SocketPermission("java.sun.com:80,8080","accept") and SocketPermission("java.sun.com,javasun.sun.com","accept") are not valid socket permissions.

Moreover, because listen is an action that applies only to ports on the local host, whereas accept is an action that applies to ports on both the local and remote host, both actions are necessary.

3.1.7 java.security.BasicPermission

The BasicPermission class extends the Permission class. It can be used as the base class for permissions that want to follow the same naming convention as BasicPermission (see below).

The name for a BasicPermission is the name of the given permission (for example, "exitVM", "setFactory", "queuePrintJob", etc). The naming convention follows the hierarchical property naming convention. An asterisk may appear at the end of the name, following a ".", or by itself, to signify a wildcard match. For example: "java.*" or "*" is valid, "*java" or "a*b" is not valid.

The action string (inherited from Permission) is unused.Thus, BasicPermission is commonly used as the base class for "named" permissions (ones that contain a name but no actions list; you either have the named permission or you don't.) Subclasses may implement actions on top of BasicPermission, if desired.

Some of the BasicPermission subclasses are java.lang.RuntimePermission, java.security.SecurityPermission, java.util.PropertyPermission, and java.net.NetPermission.

3.1.8 java.util.PropertyPermission

The targets for this class are basically the names of Java properties as set in various property files. Examples are the "java.home" and "os.name" properties. Targets can be specified as "*" (any property), "a.*" (any property whose name has a prefix "a."), "a.b.*", and so on. Note that the wildcard can occur only once and can only be at the rightmost position.

This is one of the BasicPermission subclasses that implements actions on top of BasicPermission. The actions are read and write. Their meaning is defined as follows: "read" permission allows the getProperty method in java.lang.System to be called to get the property value, and "write" permission allows the setProperty method to be called to set the property value.

3.1.9 java.lang.RuntimePermission

The target for a RuntimePermission can be represented by any string, and there is no action associated with the targets. For example, RuntimePermission("exitVM") denotes the permission to exit the Java Virtual Machine.

The target names are:

createClassLoader
getClassLoader
setContextClassLoader
setSecurityManager
createSecurityManager
exitVM
setFactory
setIO
modifyThread
stopThread
modifyThreadGroup
getProtectionDomain
readFileDescriptor
writeFileDescriptor
loadLibrary.{library name}
accessClassInPackage.{package name}
defineClassInPackage.{package name}
accessDeclaredMembers.{class name}
queuePrintJob

3.1.10 java.awt.AWTPermission

This is in the same spirit as the RuntimePermission; it's a permission without actions. The targets for this class are:
accessClipboard
accessEventQueue
listenToAllAWTEvents
showWindowWithoutWarningBanner

3.1.11 java.net.NetPermission

This class contains the following targets and no actions:
requestPasswordAuthentication
setDefaultAuthenticator
specifyStreamHandler

3.1.12 java.lang.reflect.ReflectPermission

This is the Permission class for reflective operations. A ReflectPermission is a named permission (like RuntimePermission) and has no actions. The only name currently defined is
suppressAccessChecks
which allows suppressing the standard Java programming language access checks -- for public, default (package) access, protected, and private members -- performed by reflected objects at their point of use.

3.1.13 java.io.SerializablePermission

This class contains the following targets and no actions:
enableSubclassImplementation
enableSubstitution

3.1.14 java.security.SecurityPermission

SecurityPermissions control access to security-related objects, such as Security, Policy, Provider, Signer, and Identity objects. This class contains the following targets and no actions:
getPolicy
setPolicy
getProperty.{key}
setProperty.{key}
insertProvider.{provider name}
removeProvider.{provider name}
setSystemScope
setIdentityPublicKey
setIdentityInfo
printIdentity
addIdentityCertificate
removeIdentityCertificate
clearProviderProperties.{provider name}
putProviderProperty.{provider name}
removeProviderProperty.{provider name}
getSignerPrivateKey
setSignerKeyPair

3.1.15 java.security.AllPermission

This permission implies all permissions. It is introduced to simplify the work of system administrators who might need to perform multiple tasks that require all (or numerous) permissions. It would be inconvenient to require the security policy to iterate through all permissions. Note that AllPermission also implies new permissions that are defined in the future.

Clearly much caution is necessary when considering granting this permission.

3.1.16 javax.security.auth.AuthPermsision

AuthPermission handles authentication permissions and authentication-related object such as Subject, SubjectDomainCombiner, LoginContext, and Configuration. This class contains the following targets and no actions:
doAs
doAsPrivileged
getSubject
getSubjectFromDomainCombiner
setReadOnly
modifyPrincipals
modifyPublicCredentials
modifyPrivateCredentials
refreshCredential
destroyCredential
createLoginContext.{name}
getLoginConfiguration
setLoginConfiguration
refreshLoginConfiguration

3.1.17 Discussion of Permission Implications

Recall that permissions are often compared against each other, and to facilitate such comparisons, we require that each permission class defines an implies method that represents how the particular permission class relates to other permission classes. For example, java.io.FilePermission("/tmp/*", "read") implies java.io.FilePermission("/tmp/a.txt", "read") but does not imply any java.net.NetPermission.

There is another layer of implication that may not be immediately obvious to some readers. Suppose that one applet has been granted the permission to write to the entire file system. This presumbly allows the applet to replace the system binary, including the JVM runtime environment. This effectively means that the applet has been granted all permissions.

Another example is that if an applet is granted the runtime permission to create class loaders, it is effectively granted many more permissions, as a class loader can perform sensitive operations.

Other permissions that are "dangerous" to give out include those that allow the setting of system properties, runtime permissions for defining packages and for loading native code libraries (because the Java security architecture is not designed to and does not prevent malicious behavior at the level of native code), and of course the AllPermission.

For more information about permissions, including tables enumerating the risks of assigning specific permissions as well as a table of all the Java 2 SDK built-in methods that require permissions, see http://java.sun.com/j2se/sdk/1.2/docs/guide/security/permissions.html.

3.1.18 How To Create New Types of Permissions

It is essential that no one except Sun Microsystems should extend the permissions that are built into the Java 2 SDK, either by adding new functionality or by introducing additional target keywords into a class such as java.lang.RuntimePermission. This maintains consistency.

To create a new permission, the following steps are recommended, as shown by an example. Suppose an application developer from company ABC wants to create a customized permission to "watch TV".

First, create a new class com.abc.Permission that extends the abstract class java.security.Permission (or one of its subclasses), and another new class com.abc.TVPermission that extends the com.abc.Permission. Make sure that the implies method, among others, is correctly implemented. (Of course, com.abc.TVPermission can directly extend java.security.Permission; the intermediate com.abc.Permission is not required.)

public class com.abc.Permission extends java.security.Permission

public class com.abc.TVPermission extends com.abc.Permission
The following figure shows the subclass relationship.

Flow chart showing the logic flows from Permission to the subclass com.abc.Permission and then to com.abc.TVPermission

Second, include these new classes with the application package.

Each user that wants to allow this new type of permission for specific code does so by adding an entry in a policy file. (Details of the policy file syntax are given in a later section.) An example of a policy file entry granting code from http://java.sun.com/ permission to watch channel 5 would be:

grant codeBase  "http://java.sun.com/" {
    permission com.abc.TVPermission "channel-5", "watch";
    }
In the application's resource management code, when checking to see if a permission should be granted, call AccessController's checkPermission method using a com.abc.TVPermission object as the parameter.
   com.abc.TVPermission tvperm = new
        com.abc.TVPermission("channel-5", "watch");
   AccessController.checkPermission(tvperm);
Note that, when adding a new permission, one should create a new (permission) class and not add a new method to the security manager. (In the past, in order to enable checking of a new type of access, you had to add a new method to the SecurityManager class.)

If more elaborate TVPermissions such as "channel-1:13" or "channel-*" are allowed, then it may be necessary to implement a TVPermissionCollection object that knows how to deal with the semantics of these pseudo names.

New code should always invoke a permission check by calling the checkPermission method of the AccessController class in order to exercise the built-in access control algorithm. There is no essential need to examine whether there is a ClassLoader or a SecurityManager. On the other hand, if the algorithm should be left to the installed security manager class, then the method SecurityManager.checkPermission should be invoked instead.

3.2 java.security.CodeSource

This class extends the concept of a codebase within HTML to encapsulate not only the code location (URL) but also the certificate(s) containing public keys that should be used to verify signed code originating from that location. Note that this is not the equivalent of the CodeBase tag in HTML files. Each certificate is represented as a java.security.cert.Certificate, and each URL as a java.net.URL.

3.3 java.security.Policy

The system security policy for a Java application environment, specifying which permissions are available for code from various sources, is represented by a Policy object. More specifically, it is represented by a Policy subclass providing an implementation of the abstract methods in the Policy class.

In order for an applet (or an application running under a SecurityManager) to be allowed to perform secured actions, such as reading or writing a file, the applet (or application) must be granted permission for that particular action. The only exception is that code always automatically has permission to read files from its same CodeSource, and subdirectories of that CodeSource; it does not need explicit permission to do so.

There could be multiple instances of the Policy object, although only one is "in effect" at any time. The currently-installed Policy object can be obtained by calling the getPolicy method, and it can be changed by a call to the setPolicy method (by code with permission to reset the Policy).

The source location for the policy information utilized by the Policy object is up to the Policy implementation. The policy configuration may be stored, for example, as a flat ASCII file, as a serialized binary file of the Policy class, or as a database. There is a Policy reference implementation that obtains its information from static policy configuration files.

3.3.1 Policy File Format

In the Policy reference implementation, the policy can be specified within one or more policy configuration files. The configuration files indicate what permissions are allowed for code from specified code sources. Each configuration file must be encoded in UTF-8.

A policy configuration file essentially contains a list of entries. It may contain a "keystore" entry, and contains zero or more "grant" entries.

A keystore is a database of private keys and their associated digital certificates such as X.509 certificate chains authenticating the corresponding public keys. The keytool utility is used to create and administer keystores. The keystore specified in a policy configuration file is used to look up the public keys of the signers specified in the grant entries of the file. A keystore entry must appear in a policy configuration file if any grant entries specify signer aliases, or if any grant entries specify a principal alias (see below).

At this time, there can be only one keystore entry in the policy file (others after the first one are ignored), and it can appear anywhere outside the file's grant entries . It has the following syntax:

keystore "some_keystore_url", "keystore_type";
Here, "some_keystore_url" specifies the URL location of the keystore, and "keystore_type" specifies the keystore type. The latter is optional. If not specified, the type is assumed to be that specified by the "keystore.type" property in the security properties file.

The URL is relative to the policy file location. Thus if the policy file is specified in the security properties file as:

policy.url.1=http://foo.bar.com/blah/some.policy
and that policy file has an entry:
keystore ".keystore";
then the keystore will be loaded from:
http://foo.bar.com/blah/.keystore
The URL can also be absolute.

A keystore type defines the storage and data format of the keystore information, and the algorithms used to protect private keys in the keystore and the integrity of the keystore itself. The default type supported by Sun Microsystems is a proprietary keystore type named "JKS".

Each grant entry in a policy file essentially consists of a CodeSource and its permissions. Actually, a CodeSource consists of a URL and a set of certificates, while a policy file entry includes a URL and a list of signer names. The system creates the corresponding CodeSource after consulting the keystore to determine the certificate(s) of the specified signers.

Each grant entry in the policy file is of the following format, where the leading "grant" is a reserved word that signifies the beginning of a new entry and optional items appear in brackets. Within each entry, a leading "permission" is another reserved word that marks the beginning of a new permission in the entry. Each grant entry grants a set of permissions to a specified code source and principals.

grant [SignedBy "signer_names"] [, CodeBase "URL"]
      [, Principal [principal_class_name] "principal_name"]
      [, Principal [principal_class_name] "principal_name"] ... {
    permission permission_class_name [ "target_name" ]
               [, "action"] [, SignedBy "signer_names"];
    permission ...
};
White spaces are allowed immediately before or after any comma. The name of the permission class must be a fully qualified class name, such as java.io.FilePermission, and cannot be abbreviated (for example, to FilePermission).

Note that the action field is optional in that it can be omitted if the permission class does not require it. If it is present, then it must come immediately after the target field.

The exact meaning of a CodeBase URL value depends on the characters at the end. A CodeBase with a trailing "/" matches all class files (not JAR files) in the specified directory. A CodeBase with a trailing "/*" matches all files (both class and JAR files) contained in that directory. A CodeBase with a trailing "/-" matches all files (both class and JAR files) in the directory and recursively all files in subdirectories contained in that directory.

The CodeBase field (URL) is optional in that, if it is omitted, it signifies "any code base".

The first signer name field is a string alias that is mapped, via a separate mechanism, to a set of public keys (within certificates in the keystore) that are associated with the signers. These keys are used to verify that certain signed classes are really signed by these signers.

This signer field can be a comma-separated string containing names of multiple signers, an example of which is "Adam,Eve,Charles", which means signed by Adam and Eve and Charles (i.e., the relationship is AND, not OR).

This field is optional in that, if it is omitted, it signifies "any signer", or in other words, "It doesn't matter whether the code is signed or not".

The second signer field, inside a Permission entry, represents the alias to the keystore entry containing the public key corresponding to the private key used to sign the bytecodes that implemented the said permission class. This permission entry is effective (i.e., access control permission will be granted based on this entry) only if the bytecode implementation is verified to be correctly signed by the said alias.

A principal value specifies a class_name/principal_name pair which must be present within the executing threads principal set. The principal set is associated with the executing code by way of a Subject. The principal field is optional in that, if it is omitted, it signifies "any principals".

Note on KeyStore Alias Replacement:

If the principal class_name/principal_name pair is specified as a single quoted string, it is treated as a keystore alias. The keystore is consulted and queried (via the alias) for an X509 Certificate. If one is found, the principal_class is automatically treated as javax.security.auth.x500.X500Principal, and the principal_name is automatically treated as the subject distinguished name from the certificate. If an X509 Certificate mapping is not found, the entire grant entry is ignored.

The order between the CodeBase, SignedBy, and Principal fields does not matter.

An informal BNF grammer for the Policy file format is given below, where non-capitalized terms are terminals:

PolicyFile -> PolicyEntry | PolicyEntry; PolicyFile
PolicyEntry -> grant {PermissionEntry}; |
           grant SignerEntry {PermissionEntry} |
           grant CodebaseEntry {PermissionEntry} |
           grant PrincipalEntry {PermissionEntry} |
           grant SignerEntry, CodebaseEntry {PermissionEntry} |
           grant CodebaseEntry, SignerEntry {PermissionEntry} |
           grant SignerEntry, PrincipalEntry {PermissionEntry} |
           grant PrincipalEntry, SignerEntry {PermissionEntry} |
           grant CodebaseEntry, PrincipalEntry {PermissionEntry} |
           grant PrincipalEntry, CodebaseEntry {PermissionEntry} |
           grant SignerEntry, CodebaseEntry, PrincipalEntry {PermissionEntry} |
           grant CodebaseEntry, SignerEntry, PrincipalEntry {PermissionEntry} |
           grant SignerEntry, PrincipalEntry, CodebaseEntry {PermissionEntry} |
           grant CodebaseEntry, PrincipalEntry, SignerEntry {PermissionEntry} |
           grant PrincipalEntry, CodebaseEntry, SignerEntry {PermissionEntry} |
           grant PrincipalEntry, SignerEntry, CodebaseEntry {PermissionEntry} |
           keystore "url"
SignerEntry -> signedby (a comma-separated list of strings)
CodebaseEntry -> codebase (a string representation of a URL)
PrincipalEntry -> OnePrincipal | OnePrincipal, PrincipalEntry
OnePrincipal -> principal [ principal_class_name ] "principal_name" (a principal)
PermissionEntry -> OnePermission | OnePermission PermissionEntry
OnePermission -> permission permission_class_name
                 [ "target_name" ] [, "action_list"]
                 [, SignerEntry];
Now we give some examples. The following policy grants permission a.b.Foo to code signed by Roland:
grant signedBy "Roland" {
    permission a.b.Foo;
};
The following grants a FilePermission to all code (regardless of the signer and/or codeBase):
grant {
   permission java.io.FilePermission ".tmp", "read";
};
The following grants two permissions to code that is signed by both Li and Roland:
grant signedBy "Roland,Li" {
  permission java.io.FilePermission "/tmp/*", "read";
  permission java.util.PropertyPermission "user.*";
};
The following grants two permissions to code that is signed by Li and that comes from http://java.sun.com:
grant codeBase "http://java.sun.com/*", signedBy "Li" {
    permission java.io.FilePermission "/tmp/*", "read";
    permission java.io.SocketPermission "*", "connect";
};
The following grants two permissions to code that is signed by both Li and Roland, and only if the bytecodes implementing com.abc.TVPermission are genuinely signed by Li.
grant signedBy "Roland,Li" {
  permission java.io.FilePermission "/tmp/*", "read";
  permission com.abc.TVPermission "channel-5", "watch",
     signedBy "Li";
};
The reason for including the second signer field is to prevent spoofing when a permission class does not reside with the Java runtime installation. For example, a copy of the com.abc.TVPermission class can be downloaded as part of a remote JAR archive, and the user policy might include an entry that refers to it. Because the archive is not long-lived, the second time the com.abc.TVPermission class is downloaded, posssibly from a different web site, it is crucial that the second copy is authentic, as the presence of the permission entry in the user policy might reflect the user's confidence or belief in the first copy of the class bytecode.

The reason we chose to use digital signatures to ensure authenticity, rather than storing (a hash value of) the first copy of the bytecodes and using it to compare with the second copy, is because the author of the permission class can legitimately update the class file to reflect a new design or implementation.

Please note: The strings for a file path must be specified in a platform-dependent format; this is necessary until there is a universal file description language. The above examples have shown strings appropriate on Solaris systems. On Windows systems, when you directly specify a file path in a string, you need to include two backslashes for each actual single backslash in the path, as in

grant signedBy "Roland" {
  permission java.io.FilePermission "C:\\users\\Cathy\\*", "read";
};
This is because the strings are processed by a tokenizer (java.io.StreamTokenizer), which allows "\" to be used as an escape string (e.g., "\n" to indicate a new line) and which thus requires two backslashes to indicate a single backslash. After the tokenizer has processed the above FilePermission target string, converting double backslashes to single backslashes, the end result is the actual path
"C:\users\Cathy\*"
Finally, here are some principal-based grant entries:
grant principal javax.security.auth.x500.X500Principal "cn=Alice" {
  permission java.io.FilePermission "/home/Alice", "read, write";
};
This permits any code executing as the X500Principal, "cn=Alice", permission to read and write to "/home/Alice".

The following example shows a grant statement with both codesource and principal information.

  grant codebase "http://www.games.com",
        signedBy "Duke",
        principal javax.security.auth.x500.X500Principal "cn=Alice" {
    permission java.io.FilePermission "/tmp/games", "read, write";
  };
This allows code downloaded from "www.games.com", signed by "Duke", and executed by "cn=Alice", permission to read and write into the "/tmp/games" directory.

The following example shows a grant statement with KeyStore alias replacement:

  keystore "http://foo.bar.com/blah/.keystore";

  grant principal "alice" {
    permission java.io.FilePermission "/tmp/games", "read, write";
  };
"alice" will be replaced by javax.security.auth.x500.X500Principal "cn=Alice" assuming the X.509 certificate associated with the keystore alias, alice, has a subject distinguished name of "cn=Alice". This allows code executed by the X500Principal "cn=Alice" permission to read and write into the "/tmp/games" directory.

3.3.2 Property Expansion in Policy Files

Property expansion is possible in policy files and in the security properties file.

Property expansion is similar to expanding variables in a shell. That is, when a string like

"${some.property}"

appears in a policy file, or in the security properties file, it will be expanded to the value of the specified system property. For example,

permission java.io.FilePermission "${user.home}", "read";
will expand "${user.home}" to use the value of the "user.home" system property. If that property's value is "/home/cathy", then the above is equivalent to
permission java.io.FilePermission "/home/cathy", "read";
In order to assist in platform-independent policy files, you can also use the special notation of "${/}", which is a shortcut for "${file.separator}". This allows permission designations such as
permission java.io.FilePermission "${user.home}${/}*", "read";
If user.home is /home/cathy, and you are on Solaris, the above gets converted to:
permission java.io.FilePermission "/home/cathy/*", "read";
If on the other hand user.home is C:\users\cathy and you are on a Windows system, the above gets converted to:
permission java.io.FilePermission "C:\users\cathy\*", "read";
Also, as a special case, if you expand a property in a codebase, such as
grant codeBase "file:/${java.home}/lib/ext/"
then any file.separator characters will be automatically converted to /'s, which is desirable since codebases are URLs. Thus on a Windows system, even if java.home is set to C:\j2sdk1.2, the above would get converted to
grant codeBase "file:/C:/j2sdk1.2/lib/ext/"
Thus you don't need to use ${/} in codebase strings (and you shouldn't).

Property expansion takes place anywhere a double quoted string is allowed in the policy file. This includes the signedby, codebase, target names, and actions fields.

Whether or not property expansion is allowed is controlled by the value of the "policy.expandProperties" property in the security properties file. If the value of this property is true (the default), expansion is allowed.

Please note: You can't use nested properties; they will not work. For example,

"${user.${foo}}"
doesn't work, even if the "foo" property is set to "home". The reason is the property parser doesn't recognize nested properties; it simply looks for the first "${", and then keeps looking until it finds the first "}" and tries to interpret the result "${user.$foo}" as a property, but fails if there is no such property.

Also note: If a property can't be expanded in a grant entry, permission entry, or keystore entry, that entry is ignored. For example, if the system property "foo" is not defined and you have:

grant codeBase "${foo}" {
  permission ...;
  permission ...;
};
then all the permissions in this grant entry are ignored. If you have
grant {
  permission Foo "${foo}";
  permission Bar;
};
then only the "permission Foo..." entry is ignored. And finally, if you have
keystore "${foo}";
then the keystore entry is ignored.

One final note: On Windows systems, when you directly specify a file path in a string, you need to include two backslashes for each actual single backslash in the path, as in

"C:\\users\\cathy\\foo.bat"
This is because the strings are processed by a tokenizer (java.io.StreamTokenizer), which allows "\" to be used as an escape string (e.g., "\n" to indicate a new line) and which thus requires two backslashes to indicate a single backslash. After the tokenizer has processed the above string, converting double backslashes to single backslashes, the end result is
"C:\users\cathy\foo.bat"
Expansion of a property in a string takes place after the tokenizer has processed the string. Thus if you have the string
"${user.home}\\foo.bat"
then first the tokenizer processes the string, converting the double backslashes to a single backslash, and the result is
"${user.home}\foo.bat"
Then the ${user.home} property is expanded and the end result is
"C:\users\cathy\foo.bat"
assuming the user.home value is "C:\users\cathy". Of course, for platform independence, it would be better if the string was initially specified without any explicit slashes, i.e., using the ${/} property instead, as in
"${user.home}${/}foo.bat"

3.3.3 General Expansion in Policy Files

Generalized forms of expansion are also supported in policy files. For example, permission names may contain a string of the form: ${{protocol:protocol_data}} If such a string occurs in a permission name, then the value in protocol determines the exact type of expansion that should occur, and protocol_data is used to help perform the expansion. protocol_data may be empty, in which case the above string should simply take the form: ${{protocol}}

There are two protocols supported in the default policy file implementation:

  1. ${{self}}

    The protocol, self, denotes a replacement of the entire string, ${{self}}, with one or more principal class/name pairs. The exact replacement performed depends upon the contents of the grant clause to which the permission belongs.

    If the grant clause does not contain any principal information, the permission will be ignored (permissions containing ${{self}} in their target names are only valid in the context of a principal-based grant clause). For example, BarPermission will always be ignored in the following grant clause:

                grant codebase "www.foo.com", signedby "duke" {
                permission BarPermission "... ${{self}} ...";
            };
    If the grant clause contains principal information, ${{self}} will be replaced with that same principal information. For example, ${{self}} in BarPermission will be replaced by javax.security.auth.x500.X500Principal "cn=Duke" in the following grant clause:
                grant principal javax.security.auth.x500.X500Principal "cn=Duke" {
                permission BarPermission "... ${{self}} ...";
            };
    If there is a comma-separated list of principals in the grant clause, then ${{self}} will be replaced by the same comma-separated list or principals. In the case where both the principal class and name are wildcarded in the grant clause, ${{self}} is replaced with all the principals associated with the Subject in the current AccessControlContext.

    The following example describes a scenario involving both self and KeyStore alias replacement together:

                keystore "http://foo.bar.com/blah/.keystore";

            grant principal "duke" {
                permission BarPermission "... ${{self}} ...";
            };
    In the above example, "duke" will first be expanded into javax.security.auth.x500.X500Principal "cn=Duke" assuming the X.509 certificate associated with the KeyStore alias, "duke", has a subject distinguished name of "cn=Duke". Next, ${{self}} will be replaced with the same principal information that just got expanded in the grant clause: javax.security.auth.x500.X500Principal "cn=Duke".
  2. ${{alias:alias_name}}

    The protocol, alias, denotes a java.security.KeyStore alias substitution. The KeyStore used is the one specified in the KeyStore entry. alias_name represents an alias into the KeyStore. ${{alias:alias_name}} is replaced with javax.security.auth.x500.X500Principal "DN", where DN represents the subject distinguished name of the certificate belonging to alias_name. For example:

                keystore "http://foo.bar.com/blah/.keystore";

            grant codebase "www.foo.com" {
                permission BarPermission "... ${{alias:duke}} ...";
            };
    In the above example the X.509 certificate associated with the alias, duke, is retrieved from the KeyStore, foo.bar.com/blah/.keystore. Assuming duke's certificate specifies "o=dukeOrg, cn=duke" as the subject distinguished name, then ${{alias:duke}} is replaced with javax.security.auth.x500.X500Principal "o=dukeOrg, cn=duke".

    The permission entry is ignored under the following error conditions:

    • The keystore entry is unspecified
    • The alias_name is not provided
    • The certificate for alias_name can not be retrieved
    • The certificate retrieved is not an X.509 certificate

3.3.4 Assigning Permissions

When a principal executes a class that originated from a particular CodeSource, the security mechanism consults the policy object to determine what permissions to grant. This is done by invoking the getPermissions or implies method on the Policy object that is installed in the VM.

Clearly, a given code source in a ProtectionDomain can match the code source given in multiple entries in the policy, for example because the wildcard "*" is allowed.

The following algorithm is used to locate the appropriate set of permissions in the policy.

1. match the public keys, if code is signed.
2. if a key is not recognized in the policy, ignore the key
   if every key is ignored, treat the code as unsigned.
3. if the keys are matched, or no signer was specified {
       try to match all URLs in the policy for the keys
   }
4. if the keys are matched (or no signer was specified),
   and the URLs are matched (or no codebase was specified) {
       try to match all principals in the policy with
       the principals associated with the current executing thread.
5. if either key, URL, or principals are not matched, use built-in default
       permission, which is the original sandbox permission.
The exact meaning of a policy entry codeBase URL value depends on the characters at the end. A codeBase with a trailing "/" matches all class files (not JAR files) in the specified directory. A codeBase with a trailing "/*" matches all files (both class and JAR files) contained in that directory. A codeBase with a trailing "/-" matches all files (both class and JAR files) in the directory and recursively all files in subdirectories contained in that directory.

As an example, given "http://java.sun.com/-" in the policy, then any code base that is on this web site matches the policy entry. Matching code bases include "http://java.sun.com/j2se/sdk/" and "http://java.sun.com/people/gong/appl.jar".

If multiple entries are matched, then all the permissions given in those entries are granted. In other words, permission assignment is additive. For example, if code signed with key A gets permission X and code signed by key B gets permission Y and no particular codebase is specified, then code signed by both A and B gets permissions X and Y. Similarly, if code with codeBase "http://java.sun.com/-" is given permission X, and "http://java.sun.com/people/*" is given permission Y, and no particular signers are specified, then an applet from "http://java.sun.com/people/applet.jar" gets both X and Y.

Note that URL matching here is purely syntactic. For example, a policy can give an entry that specifies a URL "ftp://ftp.sun.com". Such an entry is useful only when one can obtain Java code directly from ftp for execution.

To specify URLs for the local file system, a file URL can be used. For example, to specify files in the /home/cathy/temp directory in a Solaris system, you'd use

"file:/home/cathy/temp/*"
To specify files in the "temp" directory on the C drive in a Windows system, use
"file:/c:/temp/*"
Note: code base URLs always use slashes (no backlashes), regardless of the platform they apply to.

You can also use an absolute path name such as

"/home/gong/bin/MyWonderfulJava"

3.3.5 Default System and User Policy Files

In the Policy reference implementation, the policy can be specified within one or more policy configuration files. The configuration files specify what permissions are allowed for code from specified code sources.

A policy file can be composed via a simple text editor, or via a graphical PolicyTool utility that is described later.

There is by default a single system-wide policy file, and a single user policy file.

The system policy file is by default located at

{java.home}/lib/security/java.policy  (Solaris)
{java.home}\lib\security\java.policy  (Windows)
Here, java.home is a system property specifying the directory into which the Java 2 SDK was installed.

The user policy file is by default located at

{user.home}/.java.policy  (Solaris)
{user.home}\.java.policy  (Windows)
Here, user.home is a system property specifying the user's home directory.

When the Policy is initialized, the system policy is loaded in first, and then the user policy is added to it. If neither policy is present, a built-in policy is used. This built-in policy is the same as the original sandbox policy.

Policy file locations are specified in the security properties file, which is located at

{java.home}/lib/security/java.security  (Solaris)
{java.home}\lib/security\java.security  (Windows)
The policy file locations are specified as the values of properties whose names are of the form
policy.url.n
Here, n is a number. You specify each such property value in a line of the following form:
policy.url.n=URL
Here, URL is a URL specification. For example, the default system and user policy files are defined in the security properties file as
policy.url.1=file:${java.home}/lib/security/java.policy
policy.url.2=file:${user.home}/.java.policy
You can actually specify a number of URLs, including ones of the form "http://", and all the designated policy files will get loaded. You can also comment out or change the second one to disable reading the default user policy file.

The algorithm starts at policy.url.1, and keeps incrementing until it does not find a URL. Thus if you have policy.url.1 and policy.url.3, policy.url.3 will never be read.

It is also possible to specify an additional or a different policy file when invoking execution of an application. This can be done via the "-Djava.security.policy" command-line argument, which sets the value of the java.security.policy property. For example, if you use

java -Djava.security.manager -Djava.security.policy=pURL SomeApp
Here, pURL is a URL specifying the location of a policy file, then the specified policy file will be loaded in addition to all the policy files that are specified in the security properties file. (The "-Djava.security.manager" argument ensures that the default security manager is installed, and thus the application is subject to policy checks, as described in "Security Management for Applets and Applications". It is not required if the application SomeApp installs a security manager.)

If you use the following, with a double equals, then just the specified policy file will be used; all others will be ignored.

java -Djava.security.manager -Djava.security.policy==pURL SomeApp
If you want to pass a policy file to the appletviewer, again use a "-Djava.security.policy" argument as follows:
appletviewer -J-Djava.security.policy=pURL  myApplet
Please note: The "-Djava.security.policy" policy file value will be ignored (for both java and appletviewer commands) if the "policy.allowSystemProperty" property in the security properties file is set to false. The default is true.

3.3.6 Customizing Policy Evaluation

The current design of the Policy class is not as comprehensive as it could be. We have given the issues much thought and are progressing cautiously, partly to ensure that we define method calls that are appropriate for the most common cases. For the meantime, an alternative policy class can be given to replace the default policy class, as long as the former is a subclass of the abstract Policy class and implements the getPermissions method (and other methods as necessary).

The Policy reference implementation can be changed by resetting the value of the "policy.provider" security property (in the security properties file) to the fully qualified name of the desired Policy implementation class. The security properties file is located in the file named

{java.home}/lib/security/java.security (Solaris)
{java.home}\lib\security\java.security (Windows)
Here, {java.home} refers to the directory where the runtime environment is installed -- either the jre directory inside the Java 2 SDK, or the top-level directory of the Java 2 Runtime Environment.

The property policy.provider specifies the name of the policy class, and the default is the following:

policy.provider=sun.security.provider.PolicyFile
To customize, you can change the property value to specify another class, as in
policy.provider=com.mycom.MyPolicy
Note that the MyPolicy class must be a subclass of java.security.Policy. It is perhaps worth emphasizing that such an override of the policy class is a temporary solution and a more comprehensive policy API will probably make this unnecessary.

3.4 java.security.GeneralSecurityException

This is a new exception class that is a subclass of java.lang.Exception. The intention is that there should be two types of exceptions associated with security and the security packages.
  • java.lang.SecurityException and its subclasses should be runtime exceptions (unchecked, not declared) that are likely to cause the execution of a program to stop.
Such an exception is thrown only when some sort of security violation is detected. For example, such an exception is thrown when some code attempts to access a file, but it does not have permission for the access. Application developers may catch these exceptions, if they want.
  • java.security.GeneralSecurityException, which is a subclass of java.lang.Exception (must be declared or caught) that is thrown in all other cases from within the security packages.
Such an exception is security related but non-vital. For example, passing in an invalid key is probably not a security violation and should be caught and dealt with by a developer.

There are currently still two exceptions within the java.security package that are subclasses from RuntimeException. We at this moment cannot change these due to backward compatibility requirements. We will revisit this issue in the future.

CONTENTS| PREV| NEXT
Copyright © 1997-2002 Sun Microsystems, Inc. All Rights Reserved.
CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Security Architecture: -

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

4 Access Control Mechanisms and Algorithms

4.1 java.security.ProtectionDomain

The ProtectionDomain class encapsulates the characteristics of a domain. Such a domain encloses a set of classes whose instances are granted a set of permissions when being executed on behalf of a given set of Principals.

A ProtectionDomain is constructed with a CodeSource, a ClassLoader, an array of Principals, and a collection of Permissions. The CodeSource encapsulates the codebase (java.net.URL) for all classes in this domain, as well as a set of certificates (of type java.security.cert.Certificate) for public keys that correspond to the private keys that signed all code in this domain. The Principals represent the user on whose behalf the code is running.

The permissions passed in at ProtectionDomain construction time represent a static set of permissions bound to the domain regardless of the Policy in force. The ProtectionDomain subsequently consults the current policy during each security check to retrieve dynamic permissions granted to the domain.

Classes from different CodeSources, or that are being executed on behalf of different principals, belong to different domains.

Today all code shipped as part of the Java 2 SDK is considered system code and run inside the unique system domain. Each applet or application runs in its appropriate domain, determined by policy.

It is possible to ensure that objects in any non-system domain cannot automatically discover objects in another non-system domain. This partition can be achieved by careful class resolution and loading, for example, using different classloaders for different domains. However, SecureClassLoader (or its subclasses) can, at its choice, load classes from different domains, thus allowing these classes to co-exist within the same name space (as partitioned by a classloader).

4.2 java.security.AccessController

The AccessController class is used for three purposes, each of which is described in further detail in sections below:
  • to decide whether an access to a critical system resource is to be allowed or denied, based on the security policy currently in effect,
  • to mark code as being "privileged", thus affecting subsequent access determinations, and
  • to obtain a "snapshot" of the current calling context so access-control decisions from a different context can be made with respect to the saved context.
Any code that controls access to system resources should invoke AccessController methods if it wishes to use the specific security model and access control algorithm utilized by these methods. If, on the other hand, the application wishes to defer the security model to that of the SecurityManager installed at runtime, then it should instead invoke corresponding methods in the SecurityManager class.

For example, the typical way to invoke access control has been the following code (taken from an earlier version of JDK):

 ClassLoader loader = this.getClass().getClassLoader();
        if (loader != null) {
                SecurityManager security = System.getSecurityManager();
            if (security != null) {
                security.checkRead("path/file");
            }
        }
Under the new architecture, the check typically should be invoked whether or not there is a classloader associated with a calling class. It could be simply, for example:
FilePermission perm = new FilePermission("path/file", "read");
AccessController.checkPermission(perm);
The AccessController checkPermission method examines the current execution context and makes the right decision as to whether or not the requested access is allowed. If it is, this check returns quietly. Otherwise, an AccessControlException (a subclass of java.lang.SecurityException) is thrown.

Note that there are (legacy) cases, for example, in some browsers, where whether there is a SecurityManager installed signifies one or the other security state that may result in different actions being taken. For backward compatibility, the checkPermission method on SecurityManager can be used.

SecurityManager security = System.getSecurityManager();
if (security != null) {
    FilePermission perm = new FilePermission("path/file", "read");
    security.checkPermission(perm);
}
We currently do not change this aspect of the SecurityManager usage, but would encourage application developers to use new techniques introduced in the Java 2 SDK in their future programming when the built-in access control algorithm is appropriate.

The default behavior of the SecurityManager checkPermission method is actually to call the AccessController checkPermission method. A different SecurityManager implementation may implement its own security management approach, possibly including the addition of further constraints used in determining whether or not an access is permitted.

4.2.1 Algorithm for Checking Permissions

Suppose access control checking occurs in a thread of computation that has a chain of multiple callers (think of this as multiple method calls that cross the protection domain boundaries), as illustrated in the next figure.

Illustration of access control

When the checkPermission method of the AccessController is invoked by the most recent caller (e.g., a method in the File class), the basic algorithm for deciding whether to allow or deny the requested access is as follows.

If any caller in the call chain does not have the requested permission, AccessControlException is thrown, unless the following is true -- a caller whose domain is granted the said permission has been marked as "privileged" (see the next section) and all parties subsequently called by this caller (directly or indirectly) all have the said permission. There are obviously two implementation strategies:
  • In an "eager evaluation" implementation, whenever a thread enters a new protection domain or exits from one, the set of effective permissions is updated dynamically.
The benefit is that checking whether a permission is allowed is simplified and can be faster in many cases. The disadvantage is that, because permission checking occurs much less frequently than cross-domain calls, a large percentage of permission updates are likely to be useless effort.
  • In a "lazy evaluation" implementation, whenever permission checking is requested, the thread state (as reflected by the current state, including the current thread's call stack or its equivalent) is examined and a decision is reached to either deny or grant the particular access requested.
One potential downside of this approach is performance penalty at permission checking time, although this penalty would have been incurred anyway in the "eager evaluation" approach (albeit at earlier times and spread out among each cross-domain call). Our implementation so far has yielded acceptable performance, so we feel that lazy evaluation is the most economical approach overall.

Therefore, the algorithm for checking permissions is currently implemented as "lazy evaluation". Suppose the current thread traversed m callers, in the order of caller 1 to caller 2 to caller m. Then caller m invoked the checkPermission method. The basic algorithm checkPermission uses to determine whether access is granted or denied is the following (see subsequent sections for refinements):

 i = m;
 while (i > 0) {
     if (caller i's domain does not have the permission)
         throw AccessControlException
     else if (caller i is marked as privileged)
         return;
     i = i - 1;
 };

4.2.2 Handling Privileges

A new, static method in the AccessController class allows code in a class instance to inform the AccessController that a body of its code is "privileged" in that it is solely responsible for requesting access to its available resources, no matter what code caused it to do so.

That is, a caller can be marked as being "privileged" when it calls the doPrivileged method. When making access control decisions, the checkPermission method stops checking if it reaches a caller that was marked as "privileged" via a doPrivileged call without a context argument (see a subsequent section for information about a context argument). If that caller's domain has the specified permission, no further checking is done and checkPermission returns quietly, indicating that the requested access is allowed. If that domain does not have the specified permission, an exception is thrown, as usual.

The normal use of the "privileged" feature is as follows:

If you don't need to return a value from within the "privileged" block, do the following:

  somemethod() {
       ...normal code here...
       AccessController.doPrivileged(new PrivilegedAction() {
           public Object run() {
               // privileged code goes here, for example:
               System.loadLibrary("awt");
               return null; // nothing to return
           }
       });
       ...normal code here...
  }
PrivilegedAction is an interface with a single method, named run, that returns an Object. The above example shows creation of an anonymous inner class implementing that interface; a concrete implementation of the run method is supplied. When the call to doPrivileged is made, an instance of the PrivilegedAction implementation is passed to it. The doPrivileged method calls the run method from the PrivilegedAction implementation after enabling privileges, and returns the run method's return value as the doPrivileged return value, which is ignored in this example.

(For more information about inner classes, see the Inner Classes Specification at http://java.sun.com/products/jdk/1.1/docs/guide/innerclasses/spec/innerclasses.doc.html or Nested Classes at http://download.oracle.com/javase/tutorial/java/javaOO/nested.html .)

If you need to return a value, you can do something like the following:

  somemethod() {
       ...normal code here...
       String user = (String) AccessController.doPrivileged(
         new PrivilegedAction() {
           public Object run() {
               return System.getProperty("user.name");
           }
         }
       );
       ...normal code here...
  }
If the action performed in your run method could throw a "checked" exception (one listed in the throws clause of a method), then you need to use the PrivilegedExceptionAction interface instead of the PrivilegedAction interface:
  somemethod() throws FileNotFoundException {
       ...normal code here...
     try {
       FileInputStream fis = (FileInputStream)
        AccessController.doPrivileged(
         new PrivilegedExceptionAction() {
           public Object run() throws FileNotFoundException {
               return new FileInputStream("someFile");
           }
         }
       );
     } catch (PrivilegedActionException e) {
       // e.getException() should be an instance of
       // FileNotFoundException,
       // as only "checked" exceptions will be "wrapped" in a
       // <code>PrivilegedActionException</code>.
       throw (FileNotFoundException) e.getException();
     }
       ...normal code here...
 }
Some important points about being privileged: Firstly, this concept only exists within a single thread. As soon as the privileged code completes, the privilege is guaranteed to be erased or revoked.

Secondly, in this example, the body of code in the run method is privileged. However, if it calls less trustworthy code that is less privileged, that code will not gain any privileges as a result; a permission is only granted if the privileged code has the permission and so do all the subsequent callers in the call chain up to the checkPermission call.

For more information about marking code as "privileged," see http://java.sun.com/j2se/sdk/1.2/docs/guide/security/doprivileged.html.

4.3 Inheritence of Access Control Context

When a thread creates a new thread, a new stack is created. If the current security context was not retained when this new thread was created, then when AccessController.checkPermission was called inside the new thread, a security decision would be made based solely upon the new thread's context, not taking into consideration that of the parent thread.

This clean stack issue would not be a security problem per se, but it would make the writing of secure code, and especially system code, more prone to subtle errors. For example, a non-expert developer might assume, quite reasonably, that a child thread (e.g., one that does not involve untrusted code) inherits the same security context from the parent thread (e.g., one that involves untrusted code). This would cause unintended security holes when accessing controlled resources from inside the new thread (and then passing the resources along to less trusted code), if the parent context was not in fact saved.

Thus, when a new thread is created, we actually ensure (via thread creation and other code) that it automatically inherits the parent thread's security context at the time of creation of the child thread, in such a way that subsequent checkPermission calls in the child thread will take into consideration the inherited parent context.

In other words, the logical thread context is expanded to include both the parent context (in the form of an AccessControlContext, described in the next section) and the current context, and the algorithm for checking permissions is expanded to the following. (Recall there are m callers up to the call to checkPermission, and see the next section for information about the AccessControlContext checkPermission method.)

 i = m;
 while (i > 0) {
     if (caller i's domain does not have the permission)
         throw AccessControlException
     else if (caller i is marked as privileged)
         return;
     i = i - 1;
 };

 // Next, check the context inherited when
 // the thread was created. Whenever a new thread is created, the
 // AccessControlContext at that time is
 // stored and associated with the new thread, as the "inherited"
 // context.

 inheritedContext.checkPermission(permission);
Note that this inheritance is transitive so that, for example, a grandchild inherits both from the parent and the grandparent. Also note that the inherited context snapshot is taken when the new child is created, and not when the child is first run. There is no public API change for the inheritance feature.

4.4 java.security.AccessControlContext

Recall that the AccessController checkPermission method performs security checks within the context of the current execution thread (including the inherited context). A difficulty arises when such a security check can only be done in a different context. That is, sometimes a security check that should be made within a given context will actually need to be done from within a different context. For example, when one thread posts an event to another thread, the second thread serving the requesting event would not have the proper context to complete access control, if the service requests access to controller resources.

To address this issue, we provide the AccessController getContext method and AccessControlContext class. The getContext method takes a "snapshot" of the current calling context, and places it in an AccessControlContext object, which it returns. A sample call is the following:

AccessControlContext acc = AccessController.getContext();
This context captures relevant information so that an access control decision can be made by checking, from within a different context, against this context information. For example, one thread can post a request event to a second thread, while also supplying this context information. AccessControlContext itself has a checkPermission method that makes access decisions based on the context it encapsulates, rather than that of the current execution thread. Thus, the second thread can perform an appropriate security check if necessary by invoking the following:
acc.checkPermission(permission);
The above method call is equivalent to performing the same security check in the context of the first thread, even though it is done in the second thread.

There are also times where one or more permissions must be checked against an access control context, but it is unclear a priori which permissions are to be checked. In these cases you can use the doPrivileged method that takes a context:

  somemethod() {
        AccessController.doPrivileged(new PrivilegedAction() {
             public Object run() {
                // Code goes here. Any permission checks from
                // this point forward require both the current
                // context and the snapshot's context to have
                // the desired permission.
             }
        }, acc);
        ...normal code here...
Now the complete algorithm utilized by the AccessController checkPermission method can be given. Suppose the current thread traversed m callers, in the order of caller 1 to caller 2 to caller m. Then caller m invoked the checkPermission method. The algorithm checkPermission uses to determine whether access is granted or denied is the following
  i = m;
  while (i > 0) {
     if (caller i's domain does not have the permission)
        throw AccessControlException
     else if (caller i is marked as privileged) {
        if (a context was specified in the call to doPrivileged)
           context.checkPermission(permission);
        return;
     }
     i = i - 1;
  };

  // Next, check the context inherited when
  // the thread was created. Whenever a new thread is created, the
  // AccessControlContext at that time is
  // stored and associated with the new thread, as the "inherited"
  // context.

  inheritedContext.checkPermission(permission);

CONTENTS | PREV | NEXT
Copyright © 1997-1999 Sun Microsystems, Inc. All Rights Reserved.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Security Architecture: -

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

5 Secure Class Loading

Dynamic class loading is an important feature of the Java Virtual Machine because it provides the Java platform with the ability to install software components at run-time. It has a number of unique characteristics. First of all, lazy loading means that classes are loaded on demand and at the last moment possible. Second, dynamic class loading maintains the type safety of the Java Virtual Machine by adding link-time checks, which replace certain run-time checks and are performed only once. Moreover, programmers can define their own class loaders that, for example, specify the remote location from which certain classes are loaded, or assign appropriate security attributes to them. Finally, class loaders can be used to provide separate name spaces for various software components. For example, a browser can load applets from different web pages using separate class loaders, thus maintaining a degree of isolation between those applet classes. In fact, these applets can contain classes of the same name -- these classes are treated as distinct types by the Java Virtual Machine.

The class loading mechanism is not only central to the dynamic nature of the Java programming language. It also plays a critical role in providing security because the class loader is responsible for locating and fetching the class file, consulting the security policy, and defining the class object with the appropriate permissions.

5.1 Class Loader Class Hierarchies

When loading a class, because there can be multiple instances of class loader objects in one Java Virtual Machine, an important question is how do we determine which class loader to use. The Java 2 SDK has introduced multiple class loader classes are introduced that have distinct properties, so another important question is what type of class loader we should use.

The root of the class loader class hierarchy is an abstract class called java.lang.ClassLoader, originally defined in JDK 1.0 and since expanded. Class java.security.SecureClassLoader, introduced in Java 2 SDK, v 1.2, is a subclass and a concrete implementation of the abstract ClassLoader class. Class java.net.URLClassLoader is a subclass of SecureClassLoader.

A utility program called Appletviewer uses a private class sun.applet.AppletClassLoader to load applets. In JDK 1.0, AppletClassLoader is a subclass and concrete implementation of ClassLoader. In Java 2 SDK, it is a subclass of URLClassLoader.

When creating a custom class loader class, one can subclass from any of the above class loader classes, depending on the particular needs of the custom class loader. Because AppletClassLoader is a private class defined in the sun.* package, it is not supported and is subject to change, so one should not subclass from it.

5.2 The Primordial Class Loader

Because each class is loaded by its class loader, and each class loader itself is a class and must be loaded by another class loader, we seem to have the obvious chicken-and-egg problem, i.e., where does the first class loader come from? There is a "primordial'' class loader that bootstraps the class loading process. The primordial class loader is generally written in a native language, such as C, and does not manifest itself within the Java context. The primordial class loader often loads classes from the local file system in a platform-dependent manner.

Some classes, such as those defined in the java.* package, are essential for the correct functioning of the Java Virtual Machine and runtime system. They are often referred to as base classes. Due to historical reasons, all such classes have a class loader that is a null. This null class loader is perhaps the only sign of the existence of a primordial class loader. In fact, it is easier to simply view the null class loader as the primordial class loader.

Given all classes in one Java application environment, we can easily form a class loading tree to reflect the class loading relationship. Each class that is not a class loader is a leaf node. Each class's parent node is its class loader, with the null class loader being the root class. Such a structure is a tree because there cannot be cycles -- a class loader cannot have loaded its own ancestor class loader.

5.3 Class Loader Delegation

When one class loader is asked to load a class, this class loader either loads the class itself or it can ask another class loader to do so. In other words, the first class loader can delegate to the second class loader. The delegation relationship is virtual in the sense that it has nothing to do with which class loader loads which other class loader. Instead, the delegation relationship is formed when class loader objects are created, and in the form of a parent-child relationship. Nevertheless, the system class loader is the delegation root ancestor of all class loaders. Care must be taken to ensure that the delegation relationship does not contain cycles. Otherwise, the delegation process may enter into an infinite loop.

5.4 Class Resolution Algorithm

The default implementation of the Java 2 SDK ClassLoader method for loading a class searches for classes in the following order:
  • Check if the class has already been loaded.
  • If the current class loader has a specified delegation parent, delegate to the parent to try to load this class. If there is no parent, delegate to the primordial class loader.
  • Call a customizable method to find the class elsewhere.
Here, the first step looks into the class loader's local cache (or its functional equivalent, such as a global cache) to see if a loaded class matches the target class. The last step provides a way to customize the mechanism for looking for classes; thus a custom class loader can override this method to specify how a class should be looked up. For example, an applet class loader can override this method to go back to the applet host and try to locate the class file and load it over the network.

If at any step a class is located, it is returned. If the class is not found using the above steps, a ClassNotFound exception is thrown.

Observe that it is critical for type safety that the same class not be loaded more than once by the same class loader. If the class is not among those already loaded, the current class loader attempts to delegate the task to the parent class loader. This can occur recursively. This ensures that the appropriate class loader is used. For example, when locating a system class, the delegation process continues until the system class loader is reached.

We have seen the delegation algorithm earlier. But, given the name of any class, which class loader do we start with in trying to load the class? The rules for determining the class loader are the following:

  • When loading the first class of an application, a new instance of the URLClassLoader is used.
  • When loading the first class of an applet, a new instance of the AppletClassLoader is used.
  • When java.lang.Class.ForName is directly called, the primordial class loader is used.
  • If the request to load a class is triggered by a reference to it from an existing class, the class loader for the existing class is asked to load the class.
Note that rules about the use of URLClassLoader and AppletClassLoader instances have exceptions and can vary depending on the particular system environment. For example, a web browser may choose to reuse an existing AppletClassLoader to load applet classes from the same web page.

Due to the power of class loaders, we severely restrict who can create class loader instances. On the other hand, it is desirable to provide a convenient mechanism for applications or applets to specify URL locations and load classes from them. We provide static methods to allow any program to create instances of the URLClassLoader class, although not other types of class loaders.

CONTENTS | PREV | NEXT
Copyright © 1997-1999 Sun Microsystems, Inc. All Rights Reserved.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Security Architecture: -

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

6 Security Management

6.1 Managing Applets and Applications

Currently, all Java 2 SDK system code invokes SecurityManager methods to check the policy currently in effect and perform access control checks. There is typically a security manager (SecurityManager implementation) installed whenever an applet is running; the appletviewer and most browsers, including those from Netscape and Microsoft, install a security manager.

A security manager is not automatically installed when an application is running. To apply the same security policy to an application found on the local file system as to downloaded applets, either the user running the application must invoke the Java Virtual Machine with the new "-Djava.security.manager" command-line argument (which sets the value of the java.security.manager property), as in

    java -Djava.security.manager  SomeApp
or the application itself must call the setSecurityManager method in the java.lang.System class to install a security manager.

It is possible to specify on the command line a particular security manager to be utilized, by following "-Djava.security.manager" with an equals and the name of the class to be used as the security manager, as in

    java -Djava.security.manager=COM.abc.MySecMgr  SomeApp
If no security manager is specified, the built-in default security manager is utilized (unless the application installs a different security manager). All of the following are equivalent and result in usage of the default security manager:
    java -Djava.security.manager  SomeApp
    java -Djava.security.manager=""  SomeApp
    java -Djava.security.manager=default  SomeApp
Java 2 SDK includes a property named java.class.path. Classes that are stored on the local file system but should not be treated as base classes (e.g., classes built into the SDK) should be on this path. Classes on this path are loaded with a secure class loader and are thus subjected to the security policy being enforced.

There is also a "-Djava.security.policy" command-line argument whose usage determines what policy files are utilized. This command-line argument is described in detail in the "Default System and User Policy Files" section. Basically, if you don't include "-Djava.security.policy" on the command line, then the policy files specified in the security properties file will be used.

You can use a "-Djava.security.policy" command-line argument to specify an additional or a different policy file when invoking execution of an application. For example, if you type the following, where pURL is a URL specifying the location of a policy file, then the specified policy file will be loaded in addition to all the policy files specified in the security properties file:

    java -Djava.security.manager -Djava.security.policy=pURL SomeApp
If you instead type the following command, using a double equals, then just the specified policy file will be used; all others will be ignored:
java -Djava.security.manager -Djava.security.policy==pURL SomeApp

6.2 SecurityManager versus AccessController

The new access control mechanism is fully backward compatible. For example, all check methods in SecurityManager are still supported, although most of their implementations are changed to call the new SecurityManager checkPermission method, whose default implementation calls the AccessController checkPermission method. Note that certain internal security checks may stay in the SecurityManager class, unless it can be parameterized.

We have not at this time revised any system code to call AccessController instead of calling SecurityManager (and checking for the existence of a classloader), because of the potential of existing third-party applications that subclass the SecurityManager and customize the check methods. In fact, we added a new method SecurityManager.checkPermission that by default simply invokes AccessController.checkPermission.

To understand the relationship between SecurityManager and AccessController, it is sufficient to note that SecurityManager represents the concept of a central point of access control, while AccessController implements a particular access control algorithm, with special features such as the doPrivileged method. By keeping SecurityManager up to date, we maintain backward compatibility (e.g., for those applications that have written their own security manager classes based on earlier versions of the JDK) and flexibility (e.g., for someone wanting to customize the security model to implement mandatory access control or multilevel security). By providing AccessController, we build in the algorithm that we believe is the most restrictive and that relieves the typical programmer from the burden of having to write extensive security code in most scenarios.

We encourage the use of AccessController in application code, while customization of a security manager (via subclassing) should be the last resort and should be done with extreme care. Moreover, a customized security manager, such as one that always checks the time of the day before invoking standard security checks, could and should utilize the algorithm provided by AccessController whenever appropriate.

6.3 Auxiliary Tools

This section briefly describes the usage of three tools that assist in the deployment of the new security features. These tools may be packaged together in the future.

More extensive documentation for the tools can be found in the

/docs/technotes/tools/solaris
and
/docs/technotes/tools/windows
subdirectories of the SDK release directory (where the directory separators are actually "\" on Windows systems).

For example, if the Java 2 SDK is installed in a directory named "/j2sdk1.2" on a Solaris system, then the keytool documentation for Solaris and Windows users, respectively, can be found in

/j2sdk1.2/docs/tooldocs/solaris/keytool.html
/j2sdk1.2/docs/tooldocs/windows/keytool.html
If the Java 2 SDK is installed in a directory named "C:\j2sdk1.2" on a Windows system, then the keytool documentation for Solaris and Windows users, respectively, can be found in
C:\j2sdk1.2\docs\tooldocs\solaris\keytool.html
C:\j2sdk1.2\docs\tooldocs\windows\keytool.html

6.3.1 The Key and Certificate Management Tool

keytool is a key and certificate management utility. It enables users to administer their own public/private key pairs and associated certificates for use in self-authentication (where the user authenticates himself/herself to other users/services) or data integrity and authentication services, using digital signatures. The authentication information includes both a sequence (chain) of X.509 certificates, and an associated private key, which can be referenced by a so-called "alias". This tool also manages certificates (that are "trusted" by the user), which are stored in the same database as the authentication information, and can be referenced by an "alias".

keytool stores the keys and certificates in a so-called keystore. The default keystore implementation implements the keystore as a file. It protects private keys with a password.

The chains of X.509 certificates are provided by organizations called Certification Authorities, or CAs. Identities (including CAs) use their private keys to authenticate their association with objects (such as with channels which are secured using SSL), with archives of code they signed, or (for CAs) with X.509 certificates they have issued. As a bootstrapping tool, certificates generated using the -genkey command may be used until a Certification Authority returns a certificate chain.

The private keys in this database are always stored in encrypted form, to make it difficult to disclose these private keys inappropriately. A password is required to access or modify the database. These private keys are encrypted using the "password", which should be several words long. If the password is lost, those authentication keys cannot be recovered.

In fact, each private key in the keystore can be protected using its own individual password, which may or may not be the same as the password that protects the keystore's overall integrity.

This tool is (currently) intended to be used from the command line, where one simply types "keytool" as a shell prompt. keytool is a script that executes the appropriate Java classes and is built together with the SDK.

The command line options for each command may be provided in any order. Typing an incorrect option or typing "keytool -help" will cause the tool's usage to be summarized on the output device (such as a shell window), as given below.

% keytool -help
KeyTool usage:

-certreq     [-v] [-alias <alias>] [-sigalg <sigalg>]
             [-file <certreq_file>] [-keypass <keypass>]
             [-keystore <keystore>] [-storepass <storepass>]
             [-storetype <i>storetype</i>]

-delete      [-v] -alias <alias>
             [-keystore <keystore>] [-storepass <storepass>]
             [-storetype <i>storetype</i>]

-export      [-v] [rfc] [-alias <alias>] [-file <cert_file>]
             [-keystore <keystore>] [-storepass <storepass>]
             [-storetype <i>storetype</i>]

-genkey      [-v] [-alias <alias>] [-keyalg <keyalg>]
             [-keysize <keysize>] [-sigalg <sigalg>]
             [-dname <distinguished_name>] [-validity <valDays>]
             [-keypass <keypass>] [-keystore <keystore>]
             [-storepass <storepass>]
             [-storetype <i>storetype</i>]

-help

-identitydb  [-v] [-file <idb_file>] [-keystore <keystore>]
             [-storepass <storepass>]
             [-storetype <i>storetype</i>]

-import      [-v] [-noprompt] [-alias <alias>]
             [-file <cert_file>] [-keypass <keypass>]
             [-keystore <keystore>] [-storepass <storepass>]
             [-storetype <i>storetype</i>]

-keyclone    [-v] [-alias <alias>] -dest <dest_alias>
             [-keypass <keypass>] [-new <new_keypass>]
             [-keystore <keystore>] [-storepass <storepass>]
             [-storetype <i>storetype</i>]

-keypasswd   [-v] [-alias <alias>]
             [-keypass <old_keypass>] [-new <new_keypass>]
             [-keystore <keystore>] [-storepass <storepass>]
             [-storetype <i>storetype</i>]

-list        [-v | -rfc] [-alias <alias>]
             [-keystore <keystore>] [-storepass <storepass>]
             [-storetype <i>storetype</i>]

-printcert   [-v] [-file <cert_file>]

-selfcert    [-v] [-alias <alias>] [-sigalg <sigalg>]
             [-dname <distinguished_name>] [-validity <valDays>]
             [-keypass <keypass>] [-keystore <keystore>]
             [-storepass <storepass>]
             [-storetype <i>storetype</i>]

-storepasswd  [-v] [-new <new_storepass>]
             [-keystore <keystore>] [-storepass <storepass>]
              [-storetype <i>storetype</i>]

6.3.2 PolicyTool

The PolicyTool is a graphical user interface (illustrated below with a screen shot) that assists a user (such as a system administrator) in specifying, generating, editing, exporting, or importing a security policy. The tool is invoked from the command line as policytool. This again is a script built with the SDK that invokes the appropriate (non-public) implementation classes.

See the PolicyTool documentation for usage information and examples with up-to-date screen shots. The documentation can be found in the policytool.html file in the

/docs/technotes/tools/solaris/
or
/docs/technotes/tools/windows/
directory in the directory in which the SDK was installed (where the file separators are actually backslashes on Windows systems).

screenshot od PolicyTool window

6.3.3 The JAR Signing and Verification Tool

The jarsigner tool can be used to digitally sign Java archives (JAR files), and to verify such signatures. This tool, like the PolicyTool, depends on the keystore that is managed by the keytool. Its usage is quickly summarized below.
% jarsigner
Usage: jarsigner [options] jar-file alias
       jarsigner -verify [options] jar-file
  [-keystore <url>]         keystore file location
  [-storepass <password>]   password for keystore integrity
  [-keypass <password>]     password for private key (if different)
  [-sigfile <file>]         name of .SF/.DSA file
  [-signedjar <file>]       name of signed JAR file
  [-verify]                 verify a signed JAR file
  [-verbose]                verbose output when signing/verifying
  [-certs]          display certificates when verbose and verifying
  [-internalsf]             include .SF file inside signature block
  [-sectionsonly]           don't compute hash of entire manifest
Again, this tool is a script built with the SDK. Note that it is expected that this tool and the existing jar tool script may be merged in the near future to form a single command-line primitive to create JARs, either signed or unsigned.
CONTENTS | PREV | NEXT
Copyright © 1997-1999 Sun Microsystems, Inc. All Rights Reserved.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Security Architecture: -

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

7 GuardedObject and SignedObject

7.1 java.security.GuardedObject and java.security.Guard

Recall that the class AccessControlContext is useful when an access control decision has to be made in a different context. There is another such scenario, where the supplier of a resource is not in the same thread as the comsumer of that resource, and the consumer thread cannot provide the supplier thread the access control context information (because the context is security-sensitive, or the context is too large to pass, or for other reasons). For this case, we provide a class called GuardedObject to protect access to the resource, illustrated in the figure below.

Illustration of previous context

The basic idea is that the supplier of the resource can create an object representing the resource, create a GuardedObject that embeds the resource object inside, and then provide the GuardedObject to the consumer. In creating the GuardedObject, the supplier also specifies a Guard object such that anyone (including the consumer) can only obtain the resource object if certain (security) checks inside the Guard are satisfied.

Guard is an interface, so any object can choose to become a Guard. The only method in this interface is called checkGuard. It takes an Object argument and it performs certain (security) checks. The Permission class in java.security implements the Guard interface.

For example, suppose a system thread is asked to open a file /a/b/c.txt for read access, but the system thread does not know who the requestor is or under what circumstances the request is made. Therefore, the correct access control decision cannot be made at the server side. The system thread can use GuardedObject to delay the access control checking, as follows.

FileInputStream f = new FileInputStream("/a/b/c.txt");
FilePermission p = new FilePermission("/a/b/c.txt", "read");
GuardedObject g = new GuardedObject(f, p);
Now the system thread can pass g to the consumer thread. For that thread to obtain the file input stream, it has to call
FileInputStream fis = (FileInputStream) g.getObject();
This method in turn invokes the checkGuard method on the Guard object p, and because p is a Permission, its checkGuard method is in fact:
SecurityManager sm = System.getSecurityManager();
if (sm != null) sm.checkPermission(this);
This ensures that a proper access control check takes place within the consumer context. In fact, one can replace often-used hash tables and access control lists in many cases and simply store a hash table of GuardedObjects.

This basic pattern of GuardedObject and Guard is very general, and we expect that by extending the basic Guard and GuardedObject classes, developers can easily obtain quite powerful access control tools. For example, per-method invocation can be achieved with an appropriate Guard for each method, and a Guard can check the time of the day, the signer or other identification of the caller, or any other relevant information.

Note that certain typing information is lost because GuardedObject returns an Object. GuardedObject is intended to be used between cooperating parties so that the receiving party should know what type of object to expect (and to cast for). In fact, we envision that most usage of GuardedObject involves subclassing it (say to form a GuardedFileInputStream class), thus encapsulating typing information, and casting can happen suitably in the subclass.

7.2 java.security.SignedObject

This class is an essential building block for other security primitives. SignedObject contains another Serializable object, the (to-be-)signed object and its signature. If the signature is not null, it contains a valid digital signature of the signed object. This is illustrated in the figure below.

The previous context describes this graphic

The underlying signing algorithm is set through a Signature object as a parameter to the sign method call, and the algorithm can be, among others, the NIST standard DSA, using DSA and SHA-1. The algorithm is specified using the same convention for signatures, such as "SHA/DSA".

The signed object is a "deep copy" (in serialized form) of an original object. Once the copy is made, further manipulation of the original object has no side effect on the copy. A signed object is immutable.

A typical example of creating a signed object is the following:

Signature signingEngine =
    Signature.getInstance(algorithm,provider);
SignedObject so =
    new SignedObject(myobject, signingKey, signingEngine);
A typical example of verification is the following (having received SignedObject so), where the first line is not needed if the name of the algorithm is known:
String algorithm = so.getAlgorithm();
Signature verificationEngine =
    Signature.getInstance(algorithm, provider);
so.verify(verificationEngine);
Potential applications of SignedObject include:
  • It can be used internally to any Java application environment as an unforgeable authorization token -- one that can be passed around without the fear that the token can be maliciously modified without being detected.
  • It can be used to sign and serialize data/object for storage outside the Java runtime (e.g., storing critical access control data on disk).
  • Nested SignedObjects can be used to construct a logical sequence of signatures, resembling a chain of authorization and delegation.
It is intended that this class can be subclassed in the future to allow multiple signatures on the same signed object. In that case, existing method calls in this base class will be fully compatible in semantics. In particular, any get method will return the unique value if there is only one signature, and will return an arbitrary one from the set of signatures if there is more than one signature.
CONTENTS | PREV | NEXT
Copyright © 1997-1999 Sun Microsystems, Inc. All Rights Reserved.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Security Architecture: -

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

8 Discussion and Future Directions

8.1 Resource Consumption Management

Resource consumption management is relatively easy to implement in some cases (e.g., to limit the number of windows any application can pop up at any one time), while it can be quite hard to implement efficiently in other cases (e.g., to limit memory or file system usage). We plan to coherently address such issues in the future.

8.2 Arbitrary Grouping of Permissions

Sometimes it is convenient to group a number of permissions together and use a short-hand name to refer to them. For example, if we would like to have a permission called "SuperPermission" to include (and imply) both FilePermission("-", "read,write") and SocketPermission("*", "connect,accept"), technically we can use the class Permissions or a similar class to implement this super permission by using the add methods to add the required permissions. And such grouping can be arbitrarily complicated.

The more difficult issues are the following. First, to understand what actual permissions one is granting when giving out such a super permission, either a fixed and named permission class is created to denote a statically specified group of permissions, or the member permissions need to be spelled out in the policy file. Second, processing the policy (file) can become more complicated because the grouped permissions may need to be expanded. Moreover, nesting of grouped permission increases complexity even more.

8.3 Object-Level Protection

Given the object-oriented nature of the Java programming language, it is conceivable that developers will benefit from a set of appropriate object-level protection mechanisms that (1) goes beyond the natural protection provided by the Java programming language and that (2) supplements the thread-based access control mechanism.

One such mechanism is SignedObject. Parallel to this primitive, we will provide SealedObject that uses encryption to hide the content of an object. (Due to current U.S. export control regulations on the use of encryption, the SealedObject class will likely be provided separate from the SDK.)

GuardedObject is a general way to enforce access control at a per class/object per method level. This method, however, should be used only selectively, partly because this type of control can be difficult to administer at a high level.

8.4 Subdividing Protection Domains

A potentially useful concept not currently implemented is that of "subdomains." A subdomain is one that is enclosed in another. A subdomain would not have more permissions or privileges than the domain of which it is a subpart. A domain could be created, for example, to selectively further limit what a program can do.

Often a domain is thought of as supporting inheritance: a subdomain would automatically inherit the parent domain's security attributes, except in certain cases where the parent further restricts the subdomain explicitly. Relaxing a subdomain by right amplification is a possibility with the notion of trusted code.

For convenience, we can think of the system domain as a single, big collection of all system code. For better protection, though, system code should be run in multiple system domains, where each domain protects a particular type of resource and is given a special set of rights. For example, if file system code and network system code run in separate domains, where the former has no rights to the networking resources and the latter has no rights to the file system resources, the risks and consequence of an error or security flaw in one system domain is more likely to be confined within its boundary.

8.5 Running Applets with Signed Content

The JAR and Manifest specifications on code signing allow a very flexible format. Classes within the same archive can be signed with different keys, and a class can be unsigned, signed with one key, or signed with multiple keys. Other resources within the archive, such as audio clips and graphic images, can also be signed or unsigned, just like classes can.

This flexibility brings about the issue of interpretation. The following questions need to be answered, especially when keys are treated differently:

1. Should images and audios be required to be signed with the
   same key if any class in the archive is signed?
2. If images and audios are signed with different keys, can
   they be placed in the same appletviewer (or browser page),
   or should they be sent to different viewers for processing?
These questions are not easy to answer, and require consistency across platforms and products to be the most effective. Our intermediate approach is to provide a simple answer -- all images and audio clips are forwarded to be processed within the same applet classloader, whether they are signed or not. This temporary solution will be improved once a consensus is reached.

Moreover, if a digital signature cannot be verified because the bytecode content of a class file does not match the signed hash value in the JAR, a security exception is thrown, as the original intention of the JAR author is clearly altered. Previously, there was a suggestion to run such code as untrusted. This idea is undesirable because the applet classloader allows the loading of code signed by multiple parties. This means that accepting a partially modified JAR file would allow an untrusted piece of code to run together with and access other code through the same classloader.

CONTENTS | PREV | NEXT
Copyright © 1997-1999 Sun Microsystems, Inc. All Rights Reserved.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Security Architecture: -

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

9 Summary

This document gives an overview of the motivation and the new security architecture of the major security features that are implemented for the Java SE Platform.

Please send comments and feedback to java-security@sun.com (which is archived on the web at http://java.sun.com/security/hypermail/java-security-archive/index.html). Messages of a more confidential nature should be sent to the author directly (li.gong@sun.com).

CONTENTS | PREV | NEXT
Copyright © 1997-1999 Sun Microsystems, Inc. All Rights Reserved.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Security Architecture: -

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

10 Acknowledgments

The design and implementation of new security features in Java 2 SDK is the work of primarily members of the JavaSoft security group. Other (past and present) members of the JavaSoft community provided invaluable insight, detailed reviews, and much needed technical assistance. Significant contributors, in alphabetical order, include but are not limited to: Gigi Ankeny, Josh Bloch, Satya Dodda, Charlie Lai, Sheng Liang, Jan Luehe, Marianne Mueller, Jeff Nisewanger, Hemma Prafullchandra, Roger Riggs, Nakul Saraiya, Bill Shannon, Roland Schemers, and Vijay Srinivasan.

This work is not possible without strong support from JavaSoft management (our thanks go to Dick Neiss, Jon Kannegaard, and Alan Baratz), and the testing and documentation groups (especially Mary Dageforde). We are grateful for technical guidance from James Gosling, Graham Hamilton, and Jim Mitchell.

We received numerous suggestions from our corporate partners and licensees, whom we could not fully list here.

CONTENTS | PREV | NEXT
Copyright © 1997-1999 Sun Microsystems, Inc. All Rights Reserved.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Security Architecture: -

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
bgcolor="#FFFFFF">
CONTENTS | PREV | NEXT

11 References

M. Gasser. Building a Secure Computer System. Van Nostrand Reinhold Co., New York, 1988.

L. Gong, "Java Security: Present and Near Future". IEEE Micro, 17(3):14--19, May/June 1997.

L. Gong, T.M.A. Lomas, R.M. Needham, and J.H. Saltzer, "Protecting Poorly Chosen Secrets from Guessing Attacks". IEEE Journal on Selected Areas in Communications, 11(5):648--656, June, 1993.

J. Gosling, Bill Joy, and Guy Steele. The Java Language Specification. Addison-Wesley, Menlo Park, California, August 1996.

A.K. Jones. Protection in Programmed Systems. Ph.D. dissertation, Carnegie-Mellon University, Pittsburgh, PA 15213, June 1973.

B.W. Lampson. Protection. In Proceedings of the 5th Princeton Symposium on Information Sciences and Systems, Princeton University, March 1971. Reprinted in ACM Operating Systems Review, 8(1):18--24, January, 1974.

T. Lindholm and F. Yellin. The Java Virtual Machine Specification. Addison-Wesley, Menlo Park, California, 1997.

P.G. Neumann. Computer-Related Risks. Addison-Wesley, Menlo Park, California, 1995.

U.S. General Accounting Office. Information Security: Computer Attacks at Department of Defense Pose Increasing Risks. Technical Report GAO/AIMD-96-84, Washington, D.C. 20548, May 1996.

J.H. Saltzer. Protection and the Control of Information Sharing in Multics. Communications of the ACM, 17(7):388--402, July 1974.

J.H. Saltzer and M.D. Schroeder. The Protection of Information in Computer Systems}. Proceedings of the IEEE, 63(9):1278--1308, September 1975.

M.D. Schroeder. Cooperation of Mutually Suspicious Subsystems in a Computer Utility. Ph.D. dissertation, Massachusetts Institute of Technology, Cambridge, MA 02139, September 1972.

W.A. Wulf, R. Levin, and S.P. Harbison. HYDRA/C.mmp -- An Experimental Computer System. McGraw-Hill, 1981.

CONTENTS | PREV | NEXT
Copyright © 1997-1999 Sun Microsystems, Inc. All Rights Reserved.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Security Architecture: -

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

12 Revision History

Various drafts on Java 2 Security Architecture, under different disguises, existed since August of 1996.

Java SE Platform Security Architecture Specification v0.1 was drafted on March 12, 1997.

Revision 0.2 on March 27, 1997

Revision 0.3 on March 31, 1997

Revision 0.4 on June 3, 1997. Reflected changes in design and implementation based on comments and feedbacks of revision 0.3. Introduced SignedObject.

Revision 0.5 on July 10, 1997. Major reorganization. It now includes a detailed syntax and semantics for policy and permissions. The class java.lang.SecurityManager is changed from abstract to concrete, with a default implementation.

Revision 0.6 on September 3, 1997. Reorganized sections under clearer headings. Syntactical changes to policy file format, including adding an optional signer field to each permission entry. Introduced GuardedObject class and Guard interface. The Permission class is now Serializable and implements the Guard interface. Added a new AccessControlContext class that helps cross-thread access control decision making. Gave descriptions of keytool, policytool, and jarsigner. Revised Acknowledgements.

Revision 0.7 on October 1, 1997. Added description of a feature that automatically makes a new thread, at its creation time, inherit the parent thread's security context so that access control checking in the new child thread considers both the first current context and also the inherited context.

Revision 0.8 on March 9, 1998. The previously package private class java.security.ProtectionDomain is now made public, and suitable get, set, and define methods to use this class are added in java.lang.Class and java.security.SecureClassLoader. The class java.security.SignedObject is now immutable. Introduced a new class java.security.UnresolvedPermission. Added new method SecurityManager.checkPermission that, by default, invokes AccessController.checkPermission. Syntax change for FilePermission in the case of "*", "-", and introduced "<<ALL FILES>>". Other minor additions and changes, including two new options for jarsigner. Revised Acknowledgements.

Revision 0.9 on June 10, 1998. Some permission names have been modified to make permission naming clearer and more consistent. Added sections for Permission classes not previously documented herein. The evaluate method in Policy has been renamed getPermissions. Class.setProtectionDomain no longer exists. Corrected "file:" URL examples. The "-usepolicy" command-line argument for the "java" command has been replaced by "-Djava.security.manager" and "-Djava.security.policy". Updated command lists for the keytool and jarsigner tools. The AccessController beginPrivileged and endPrivileged methods have been replaced by the doPrivileged method.

Revision 1.0 on October 2, 1998. Updated description of the class loading mechanism with a new chapter. Rearranged some chapters and sections.

Revision 1.1 on December 20, 2000. Updated the document to reflect the new Policy and ProtectionDomain updates to support dynamic policies. Also added updates for the integration of the Java Authentication and Authorization Service (JAAS) into the core SDK. New policy syntax was described and examples were added.

Revision 1.2 (the current version) on March 22, 2002. Added notes on KeyStore Alias Replacement including an example of a grant statement with KeyStore alias replacement. Added new section 3.3 explaining generalized expansion in policy files including examples.

CONTENTS | PREV | NEXT
Copyright © 1997-1999 Sun Microsystems, Inc. All Rights Reserved.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Security Architecture: -

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

Table of Contents

1 Introduction
1.1 The Original Sandbox Model
1.2 Evolving the Sandbox Model

2 New Protection Mechanisms -- Overview of Basic Concepts

3 Permissions and Security Policy
3.1 The Permission Classes
3.1.1 java.security.Permission
3.1.2 java.security.PermissionCollection
3.1.3 java.security.Permissions
3.1.4 java.security.UnresolvedPermission
3.1.5 java.io.FilePermission
3.1.6 java.net.SocketPermission
3.1.7 java.security.BasicPermission
3.1.8 java.util.PropertyPermission
3.1.9 java.lang.RuntimePermission
3.1.10 java.awt.AWTPermission
3.1.11 java.net.NetPermission
3.1.12 java.lang.reflect.ReflectPermission
3.1.13 java.io.SerializablePermission
3.1.14 java.security.SecurityPermission
3.1.15 java.security.AllPermission
3.1.16 javax.security.auth.AuthPermission
3.1.17 Discussion of Permission Implications
3.1.18 How To Create New Types of Permissions
3.2 java.security.CodeSource
3.3 java.security.Policy
3.3.1 Policy File Format
3.3.2 Property Expansion in Policy Files
3.3.3 General Expansion in Policy Files
3.3.4 Assigning Permissions
3.3.5 Default System and User Policy Files
3.3.6 Customizing Policy Evaluation
3.4 java.security.GeneralSecurityException

4 Access Control Mechanisms and Algorithms
4.1 java.security.ProtectionDomain
4.2 java.security.AccessController
4.2.1 Algorithm for Checking Permissions
4.2.2 Handling Privileges
4.3 Inheritence of Access Control Context
4.4 java.security.AccessControlContext

5 Secure Class Loading
5.1 Class Loader Class Hierarchies
5.2 The Primordial Class Loader
5.3 Class Loader Delegation
5.4 Class Resolution Algorithm

6 Security Management
6.1 Managing Applets and Applications
6.2 SecurityManager versus AccessController
6.3 Auxiliary Tools
6.3.1 The Key and Certificate Management Tool
6.3.2 PolicyTool
6.3.3 The JAR Signing and Verification Tool

7 GuardedObject and SignedObject
7.1 java.security.GuardedObject and java.security.Guard
7.2 java.security.SignedObject

8 Discussion and Future Directions
8.1 Resource Consumption Management
8.2 Arbitrary Grouping of Permissions
8.3 Object-Level Protection
8.4 Subdividing Protection Domains
8.5 Running Applets with Signed Content

9 Summary

10 Acknowledgments

11 References

12 Revision History

CONTENTS | PREV | NEXT
Copyright © 1997-2002 Sun Microsystems, Inc. All Rights Reserved.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Additional Security Information For Microsoft Windows - Java SE Monitoring and Management Guide

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
previous Previous Contents
Appendix A

Additional Security Information For Microsoft Windows

How to Secure a Password File on Microsoft Windows Systems

For remote monitoring and management, password and access files are used to control security. How to set the file permissions for a password file is described for Solaris and Linux platforms in Using Password and Access Files in Chapter 2, Monitoring and Management Using JMX Technology.

This appendix describes how to set the file permissions of the password file on a Windows system using a New Technology File System (NTFS) so that only the owner has read and write permissions on this file. If the file system is a File Allocation Table (FAT) 32 system, then security is not supported for this file system and the password file cannot be secured.

Securing a password file is done differently in the different versions of Windows XP. Solutions for both Windows XP Professional Edition and Windows XP Home Edition are provided in this appendix.

procedure graphic To Secure a Password File on Windows XP Professional Edition

The procedure given below will not work if you are running Windows XP Home Edition, which does not allow you to change file permissions graphically. A solution is given in To Secure a Password File on Windows XP Home Edition below.

Note - The solution using the cacls command described in To Secure a Password File on Windows XP Home Edition can also be used on Windows XP Professional Edition, as a command-line alternative to using the graphical interfaces.

  1. In Windows Explorer, navigate to the directory containing the jmxremote.password file.
  2. Right-click on the jmxremote.password file and select the Properties option.
    Displaying the jmxremote.password file properties
  3. Select the Security tab
    Displaying the jmxremote.password file's security properties

    If you are using Windows XP Professional Edition and the computer is not part of a domain, then the Security tab will not be automatically visible. To reveal the Security tab, you must perform the following steps.

    1. Open Windows Explorer, and choose Folder Options from the Tools menu.
    2. Select the View tab and scroll to the bottom of the Advanced Settings and clear the Use Simple File Sharing check box.
      Displaying the Security tab in Windows XP.
    3. Click OK to apply the change.
    4. Restart Windows Explorer.

      The Security tab will now be visible

  4. Select the Advanced button in the Security tab.
    Displaying advanced security properties.
  5. Select the Owner tab to check if the file owner matches the user under which the Java VM is running.
    Checking who owns the password file.
  6. Select the Permissions tab to set the permissions.

    If there are permission entries inherited from a parent directory that allow users or groups other than the owner access to the file, then clear the "Inherit from parent the permission entries that apply to child objects" checkbox.

    Blocking inheritance of file permissions from parent objects.
  7. A dialog box will ask if the inherited permissions should be copied from the parent or removed. Press the Copy button.
    Copying permissions from the parent.
  8. Remove all permission entries that grant access to users or groups other than the file owner.

    Do this by clicking the user or group and pressing the Remove button for all users and groups except the file owner.

    Removing permissions from all users but the owner.

    Now there should be a single permission entry which grants Full Control to the owner.

  9. Press OK to apply the file security change.

    The password file is now secure and can only be accessed by the owner.

  10. Press OK in the jmxremote.password Properties dialog.

procedure graphic To Secure a Password File on Windows XP Home Edition

As stated above, Windows XP Home Edition does not allow you to set file permissions graphically. However, you can set permissions using the cacls command.

  1. Open a command prompt window.
  2. Run the following command
    C:\MyPasswordFile>cacls jmxremote.password

    This command displays the access control list (ACL) of the jmxremote.password file.

  3. Set the access rights so that only your username has read access.

    When no users have been configured on the machine the default username is usually Owner, or a localized translation of Owner.

    C:\MyPasswordFile>cacls jmxremote.password /P Owner:R

    This command grants access to the user Owner with read-only permission, where Owner is the owner of the jmxremote.password file.

  4. Display the ACL again.
    C:\MyPasswordFile>cacls jmxremote.password

    This time, you will see that only the Owner has access to the password file.

    Changing file permissions in Windows XP.
previous Previous Contents
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Summary of Security Tools

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Summary of Tools for Java Platform Security

Last Modified: 28 July, 2006

Below is a summary of the following security tools, with links to the more detailed documentation: keytool, jar, jarsigner, Policy Tool, kinit, klist, and ktab. All of these tools are command-line tools with the exception of Policy Tool, which has a graphical user interface.

The Tools

keytool (Solaris or Linux) (Windows)

Use keytool to manage your keystore, for example to

  • create public/private key pairs
  • issue certificate requests (which you send to the appropriate Certification Authority)
  • import certificate replies (obtained from the Certification Authority you contacted)
  • designate public keys belonging to other parties as trusted
  • copy entries between two keystores

Keys and certificates are used to digitally sign your applications and applets (see jarsigner below). A keystore is a protected database that holds keys and certificates for an enterprise. Access to a keystore is guarded by a password (defined at the time the keystore is created, by the person who creates the keystore, and changeable only when providing the current password). In addition, each private key in a keystore can be guarded by its own password.

jar (Solaris or Linux) (Windows)

Use the jar tool to create JAR files.

The Java ARchive (JAR) file format enables you to bundle multiple files into a single archive file. Typically a JAR file will contain the class files and auxiliary resources associated with applets and applications. When you want to "digitally sign" code, you use the jar tool to place it in a JAR file and the jarsigner tool to sign the JAR file (after generating or importing appropriate keys into your keystore using keytool).

jarsigner (Solaris or Linux) (Windows)

Use the jarsigner tool to sign JAR files, or to verify signatures on signed JAR files.

The jarsigner tool accesses a keystore that is created and managed by keytool, when it needs to find the private key and its associated certificate chain to use when signing a JAR file. Since accesses to the keystore and to private keys are protected by passwords, only people who know the passwords will be able to access the key and use it to sign a JAR file. The jarsigner tool prompts for needed passwords.

Policy Tool (Solaris or Linux) (Windows)

Use the Policy Tool (invoked by using the policytool command) to create and modify the external policy configuration files that define your installation's security policy.

The policy is described in the Security Architecture Specification. Further information is provided in Default Policy Implementation and Policy File Syntax.

This tool has a graphical user interface, so you select buttons and other options rather than type in commands as for the other tools. Please read the Policy Tool Users Guide for details.

kinit (Windows)

kinit is used to obtain and cache Kerberos ticket-granting tickets. This tool is similar in functionality to the kinit tool commonly found in other Kerberos implementations, such as SEAM and MIT Reference implementations.

The user must be registered as a principal with the Key Distribution Center (KDC) prior to running kinit.

Solaris - Equivalent functionality is available for Solaris users via the kinit tool that is part of the Solaris operating environment.

Linux - Equivalent functionality is available for Linux users via the kinit tool in any Kerberos 5 installation.

klist (Windows)

klist is a command-line tool that allows the user to view entries in the local credentials cache and key table.

Solaris - Equivalent functionality is available for Solaris users via the klist tool that is part of the Solaris operating environment.

Linux - Equivalent functionality is available for Linux users via the klist tool in any Kerberos 5 installation.

ktab (Windows)

ktab is a command-line tool that allows the user to manage the principal names and service keys stored in a local key table. Principal and key pairs listed in the keytab allow services running on a host to authenticate themselves to the Key Distribution Center (KDC). Before a server can be setup to use Kerberos, the user must setup a keytab on the host running the server. Note that any updates made to the keytab using ktab do not affect the Kerberos database. If you change the keys in the keytab, you must also make the corresponding changes to the Kerberos database. Also note that the command line options are not case-sensitive.

Solaris - Equivalent functionality is available for Solaris users via the ktutil or kadmin tool that is part of Solaris operating environment.

Linux - Equivalent functionality is available for Linux users via the ktutil or kadmin tool in any Kerberos 5 installation.

Examples of Use of the Tools

Examples of the use of several of these security tools can be found in the Java Platform Security trail of the Java Tutorials.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.javadoc.SeeTag (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.javadoc.SeeTag

    • Uses of SeeTag in com.sun.javadoc

      Methods in com.sun.javadoc that return SeeTag
      Modifier and Type Method and Description
      SeeTag[] Doc.seeTags()
      Return the see also tags in this Doc item.
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Java Object Serialization Specification: 1 - System Architecture

CONTENTS | PREV | NEXT Java Object Serialization Specification
version 6.0

System Architecture

CHAPTER 1

Topics:

  • Overview
  • Writing to an Object Stream
  • Reading from an Object Stream
  • Object Streams as Containers
  • Defining Serializable Fields for a Class
  • Documenting Serializable Fields and Data for a Class
  • Accessing Serializable Fields of a Class
  • The ObjectOutput Interface
  • The ObjectInput Interface
  • The Serializable Interface
  • The Externalizable Interface
  • Serialization of Enum Constants
  • Protecting Sensitive Information

1.1 Overview

The ability to store and retrieve JavaTM objects is essential to building all but the most transient applications. The key to storing and retrieving objects in a serialized form is representing the state of objects sufficient to reconstruct the object(s). Objects to be saved in the stream may support either the Serializable or the Externalizable interface. For JavaTM objects, the serialized form must be able to identify and verify the JavaTM class from which the contents of the object were saved and to restore the contents to a new instance. For serializable objects, the stream includes sufficient information to restore the fields in the stream to a compatible version of the class. For Externalizable objects, the class is solely responsible for the external format of its contents.

Objects to be stored and retrieved frequently refer to other objects. Those other objects must be stored and retrieved at the same time to maintain the relationships between the objects. When an object is stored, all of the objects that are reachable from that object are stored as well.

The goals for serializing JavaTM objects are to:

  • Have a simple yet extensible mechanism.
  • Maintain the JavaTM object type and safety properties in the serialized form.
  • Be extensible to support marshaling and unmarshaling as needed for remote objects.
  • Be extensible to support simple persistence of JavaTM objects.
  • Require per class implementation only for customization.
  • Allow the object to define its external format.

1.2 Writing to an Object Stream

Writing objects and primitives to a stream is a straightforward process. For example:

// Serialize today's date to a file.
    FileOutputStream f = new FileOutputStream("tmp");
    ObjectOutput s = new ObjectOutputStream(f);
    s.writeObject("Today");
    s.writeObject(new Date());
    s.flush();
First an OutputStream, in this case a FileOutputStream, is needed to receive the bytes. Then an ObjectOutputStream is created that writes to the FileOutputStream. Next, the string "Today" and a Date object are written to the stream. More generally, objects are written with the writeObject method and primitives are written to the stream with the methods of DataOutput.

The writeObject method (see Section 2.3, "The writeObject Method") serializes the specified object and traverses its references to other objects in the object graph recursively to create a complete serialized representation of the graph. Within a stream, the first reference to any object results in the object being serialized or externalized and the assignment of a handle for that object. Subsequent references to that object are encoded as the handle. Using object handles preserves sharing and circular references that occur naturally in object graphs. Subsequent references to an object use only the handle allowing a very compact representation.

Special handling is required for arrays, enum constants, and objects of type Class, ObjectStreamClass, and String. Other objects must implement either the Serializable or the Externalizable interface to be saved in or restored from a stream.

Primitive data types are written to the stream with the methods in the DataOutput interface, such as writeInt, writeFloat, or writeUTF. Individual bytes and arrays of bytes are written with the methods of OutputStream. Except for serializable fields, primitive data is written to the stream in block-data records, with each record prefixed by a marker and an indication of the number of bytes in the record.

ObjectOutputStream can be extended to customize the information about classes in the stream or to replace objects to be serialized. Refer to the annotateClass and replaceObject method descriptions for details.

1.3 Reading from an Object Stream

Reading an object from a stream, like writing, is straightforward:

// Deserialize a string and date from a file.
    FileInputStream in = new FileInputStream("tmp");
    ObjectInputStream s = new ObjectInputStream(in);
    String today = (String)s.readObject();
    Date date = (Date)s.readObject();
First an InputStream, in this case a FileInputStream, is needed as the source stream. Then an ObjectInputStream is created that reads from the InputStream. Next, the string "Today" and a Date object are read from the stream. Generally, objects are read with the readObject method and primitives are read from the stream with the methods of DataInput.

The readObject method deserializes the next object in the stream and traverses its references to other objects recursively to create the complete graph of objects serialized.

Primitive data types are read from the stream with the methods in the DataInput interface, such as readInt, readFloat, or readUTF. Individual bytes and arrays of bytes are read with the methods of InputStream. Except for serializable fields, primitive data is read from block-data records.

ObjectInputStream can be extended to utilize customized information in the stream about classes or to replace objects that have been deserialized. Refer to the resolveClass and resolveObject method descriptions for details.

1.4 Object Streams as Containers

Object Serialization produces and consumes a stream of bytes that contain one or more primitives and objects. The objects written to the stream, in turn, refer to other objects, which are also represented in the stream. Object Serialization produces just one stream format that encodes and stores the contained objects.

Each object that acts as a container implements an interface which allows primitives and objects to be stored in or retrieved from it. These interfaces are the ObjectOutput and ObjectInput interfaces which:

  • Provide a stream to write to and to read from
  • Handle requests to write primitive types and objects to the stream
  • Handle requests to read primitive types and objects from the stream
Each object which is to be stored in a stream must explicitly allow itself to be stored and must implement the protocols needed to save and restore its state. Object Serialization defines two such protocols. The protocols allow the container to ask the object to write and read its state.

To be stored in an Object Stream, each object must implement either the Serializable or the Externalizable interface:

  • For a Serializable class, Object Serialization can automatically save and restore fields of each class of an object and automatically handle classes that evolve by adding fields or supertypes. A serializable class can declare which of its fields are saved or restored, and write and read optional values and objects.
  • For an Externalizable class, Object Serialization delegates to the class complete control over its external format and how the state of the supertype(s) is saved and restored.

1.5 Defining Serializable Fields for a Class

The serializable fields of a class can be defined two different ways. Default serializable fields of a class are defined to be the non-transient and non-static fields. This default computation can be overridden by declaring a special field in the Serializable class, serialPersistentFields. This field must be initialized with an array of ObjectStreamField objects that list the names and types of the serializable fields. The modifiers for the field are required to be private, static, and final. If the field's value is null or is otherwise not an instance of ObjectStreamField[], or if the field does not have the required modifiers, then the behavior is as if the field were not declared at all.

For example, the following declaration duplicates the default behavior.

class List implements Serializable {
    List next;

    private static final ObjectStreamField[] serialPersistentFields
                 = {new ObjectStreamField("next", List.class)};

}
By using serialPersistentFields to define the Serializable fields for a class, there no longer is a limitation that a serializable field must be a field within the current definition of the Serializable class. The writeObject and readObject methods of the Serializable class can map the current implementation of the class to the serializable fields of the class using the interface that is described in Section 1.7, "Accessing Serializable Fields of a Class." Therefore, the fields for a Serializable class can change in a later release, as long as it maintains the mapping back to its Serializable fields that must remain compatible across release boundaries.
Note - There is, however, a limitation to the use of this mechanism to specify serializable fields for inner classes. Inner classes can only contain final static fields that are initialized to constants or expressions built up from constants. Consequently, it is not possible to set serialPersistentFields for an inner class (though it is possible to set it for static member classes). For other restrictions pertaining to serialization of inner class instances, see section Section 1.10, "The Serializable Interface".

1.6 Documenting Serializable Fields and Data for a Class

It is important to document the serializable state of a class to enable interoperability with alternative implementations of a Serializable class and to document class evolution. Documenting a serializable field gives one a final opportunity to review whether or not the field should be serializable. The serialization javadoc tags, @serial, @serialField, and @serialData, provide a way to document the serialized form for a Serializable class within the source code.
  • The @serial tag should be placed in the javadoc comment for a default serializable field. The syntax is as follows: @serial field-description The optional field-description describes the meaning of the field and its acceptable values. The field-description can span multiple lines. When a field is added after the initial release, a @since tag indicates the version the field was added. The field-description for @serial provides serialization-specific documentation and is appended to the javadoc comment for the field within the serialized form documentation.
  • The @serialField tag is used to document an ObjectStreamField component of a serialPersistentFields array. One of these tags should be used for each ObjectStreamField component. The syntax is as follows: @serialField field-name field-type field-description
  • The @serialData tag describes the sequences and types of data written or read. The tag describes the sequence and type of optional data written by writeObject or all data written by the Externalizable.writeExternal method. The syntax is as follows: @serialData data-description
The javadoc application recognizes the serialization javadoc tags and generates a specification for each Serializable and Externalizable class. See Section C.1, "Example Alternate Implementation of java.io.File" for an example that uses these tags.

When a class is declared Serializable, the serializable state of the object is defined by serializable fields (by name and type) plus optional data. Optional data can only be written explicitly by the writeObject method of a Serializable class. Optional data can be read by the Serializable class' readObject method or serialization will skip unread optional data.

When a class is declared Externalizable, the data that is written to the stream by the class itself defines the serialized state. The class must specify the order, types, and meaning of each datum that is written to the stream. The class must handle its own evolution, so that it can continue to read data written by and write data that can be read by previous versions. The class must coordinate with the superclass when saving and restoring data. The location of the superclasses data in the stream must be specified.

The designer of a Serializable class must ensure that the information saved for the class is appropriate for persistence and follows the serialization-specified rules for interoperability and evolution. Class evolution is explained in greater detail in Chapter 5, "Versioning of Serializable Objects."

1.7 Accessing Serializable Fields of a Class

Serialization provides two mechanisms for accessing the serializable fields in a stream:
  • The default mechanism requires no customization
  • The Serializable Fields API allows a class to explicitly access/set the serializable fields by name and type
The default mechanism is used automatically when reading or writing objects that implement the Serializable interface and do no further customization. The serializable fields are mapped to the corresponding fields of the class and values are either written to the stream from those fields or are read in and assigned respectively. If the class provides writeObject and readObject methods, the default mechanism can be invoked by calling defaultWriteObject and defaultReadObject. When the writeObject and readObject methods are implemented, the class has an opportunity to modify the serializable field values before they are written or after they are read.

When the default mechanism cannot be used, the serializable class can use the putFields method of ObjectOutputStream to put the values for the serializable fields into the stream. The writeFields method of ObjectOutputStream puts the values in the correct order, then writes them to the stream using the existing protocol for serialization. Correspondingly, the readFields method of ObjectInputStream reads the values from the stream and makes them available to the class by name in any order. See Section 2.2, "The ObjectOutputStream.PutField Class" and Section 3.2, "The ObjectInputStream.GetField Class." for a detailed description of the Serializable Fields API.

1.8 The ObjectOutput Interface

The ObjectOutput interface provides an abstract, stream-based interface to object storage. It extends the DataOutput interface so those methods can be used for writing primitive data types. Objects that implement this interface can be used to store primitives and objects.

package java.io;

public interface ObjectOutput extends DataOutput
{
    public void writeObject(Object obj) throws IOException;
    public void write(int b) throws IOException;
    public void write(byte b[]) throws IOException;
     public void write(byte b[], int off, int len) throws IOException;
    public void flush() throws IOException;
    public void close() throws IOException;
}
The writeObject method is used to write an object. The exceptions thrown reflect errors while accessing the object or its fields, or exceptions that occur in writing to storage. If any exception is thrown, the underlying storage may be corrupted. If this occurs, refer to the object that is implementing this interface for more information.

1.9 The ObjectInput Interface

The ObjectInput interface provides an abstract stream based interface to object retrieval. It extends the DataInput interface so those methods for reading primitive data types are accessible in this interface.

package java.io;

public interface ObjectInput extends DataInput
{
    public Object readObject()
        throws ClassNotFoundException, IOException;
    public int read() throws IOException;
    public int read(byte b[]) throws IOException;
    public int read(byte b[], int off, int len) throws IOException;
    public long skip(long n) throws IOException;
    public int available() throws IOException;
    public void close() throws IOException;
}
The readObject method is used to read and return an object. The exceptions thrown reflect errors while accessing the objects or its fields or exceptions that occur in reading from the storage. If any exception is thrown, the underlying storage may be corrupted. If this occurs, refer to the object implementing this interface for additional information.

1.10 The Serializable Interface

Object Serialization produces a stream with information about the JavaTM classes for the objects which are being saved. For serializable objects, sufficient information is kept to restore those objects even if a different (but compatible) version of the implementation of the class is present. The Serializable interface is defined to identify classes which implement the serializable protocol:

package java.io;

public interface Serializable {};
A Serializable class must do the following:
  • Implement the java.io.Serializable interface
  • Identify the fields that should be serializable
(Use the serialPersistentFields member to explicitly declare them serializable or use the transient keyword to denote nonserializable fields.)
  • Have access to the no-arg constructor of its first nonserializable superclass
The class can optionally define the following methods:
  • A writeObject method to control what information is saved or to append additional information to the stream
  • A readObject method either to read the information written by the corresponding writeObject method or to update the state of the object after it has been restored
  • A writeReplace method to allow a class to nominate a replacement object to be written to the stream
(See Section 2.5, "The writeReplace Method" for additional information.)
  • A readResolve method to allow a class to designate a replacement object for the object just read from the stream
(See Section 3.7, "The readResolve Method" for additional information.)
ObjectOutputStream and ObjectInputStream allow the serializable classes on which they operate to evolve (allow changes to the classes that are compatible with the earlier versions of the classes). See Section 5.5, "Compatible JavaTM Type Evolution" for information about the mechanism which is used to allow compatible changes.
Note - Serialization of inner classes (i.e., nested classes that are not static member classes), including local and anonymous classes, is strongly discouraged for several reasons. Because inner classes declared in non-static contexts contain implicit non-transient references to enclosing class instances, serializing such an inner class instance will result in serialization of its associated outer class instance as well. Synthetic fields generated by javac (or other JavaTM compilers) to implement inner classes are implementation dependent and may vary between compilers; differences in such fields can disrupt compatibility as well as result in conflicting default serialVersionUID values. The names assigned to local and anonymous inner classes are also implementation dependent and may differ between compilers. Since inner classes cannot declare static members other than compile-time constant fields, they cannot use the serialPersistentFields mechanism to designate serializable fields. Finally, because inner classes associated with outer instances do not have zero-argument constructors (constructors of such inner classes implicitly accept the enclosing instance as a prepended parameter), they cannot implement Externalizable. None of the issues listed above, however, apply to static member classes.

1.11 The Externalizable Interface

For Externalizable objects, only the identity of the class of the object is saved by the container; the class must save and restore the contents. The Externalizable interface is defined as follows:

package java.io;

public interface Externalizable extends Serializable
{
    public void writeExternal(ObjectOutput out)
        throws IOException;

    public void readExternal(ObjectInput in)
        throws IOException, java.lang.ClassNotFoundException;
}
The class of an Externalizable object must do the following:
  • Implement the java.io.Externalizable interface
  • Implement a writeExternal method to save the state of the object
(It must explicitly coordinate with its supertype to save its state.)
  • Implement a readExternal method to read the data written by the writeExternal method from the stream and restore the state of the object
(It must explicitly coordinate with the supertype to save its state.)
  • Have the writeExternal and readExternal methods be solely responsible for the format, if an externally defined format is written
Note - The writeExternal and readExternal methods are public and raise the risk that a client may be able to write or read information in the object other than by using its methods and fields. These methods must be used only when the information held by the object is not sensitive or when exposing it does not present a security risk.
  • Have a public no-arg constructor
Note - Inner classes associated with enclosing instances cannot have no-arg constructors, since constructors of such classes implicitly accept the enclosing instance as a prepended parameter. Consequently the Externalizable interface mechanism cannot be used for inner classes and they should implement the Serializable interface, if they must be serialized. Several limitations exist for serializable inner classes as well, however; see Section 1.10, "The Serializable Interface", for a full enumeration.
An Externalizable class can optionally define the following methods:
  • A writeReplace method to allow a class to nominate a replacement object to be written to the stream
(See Section 2.5, "The writeReplace Method" for additional information.)
  • A readResolve method to allow a class to designate a replacement object for the object just read from the stream
(See Section 3.7, "The readResolve Method" for additional information.)

1.12 Serialization of Enum Constants

Enum constants are serialized differently than ordinary serializable or externalizable objects. The serialized form of an enum constant consists solely of its name; field values of the constant are not present in the form. To serialize an enum constant, ObjectOutputStream writes the value returned by the enum constant's name method. To deserialize an enum constant, ObjectInputStream reads the constant name from the stream; the deserialized constant is then obtained by calling the java.lang.Enum.valueOf method, passing the constant's enum type along with the received constant name as arguments. Like other serializable or externalizable objects, enum constants can function as the targets of back references appearing subsequently in the serialization stream.

The process by which enum constants are serialized cannot be customized: any class-specific writeObject, readObject, readObjectNoData, writeReplace, and readResolve methods defined by enum types are ignored during serialization and deserialization. Similarly, any serialPersistentFields or serialVersionUID field declarations are also ignored--all enum types have a fixed serialVersionUID of 0L. Documenting serializable fields and data for enum types is unnecessary, since there is no variation in the type of data sent.

1.13 Protecting Sensitive Information

When developing a class that provides controlled access to resources, care must be taken to protect sensitive information and functions. During deserialization, the private state of the object is restored. For example, a file descriptor contains a handle that provides access to an operating system resource. Being able to forge a file descriptor would allow some forms of illegal access, since restoring state is done from a stream. Therefore, the serializing runtime must take the conservative approach and not trust the stream to contain only valid representations of objects. To avoid compromising a class, the sensitive state of an object must not be restored from the stream, or it must be reverified by the class. Several techniques are available to protect sensitive data in classes.

The easiest technique is to mark fields that contain sensitive data as private transient. Transient fields are not persistent and will not be saved by any persistence mechanism. Marking the field will prevent the state from appearing in the stream and from being restored during deserialization. Since writing and reading (of private fields) cannot be superseded outside of the class, the transient fields of the class are safe.

Particularly sensitive classes should not be serialized at all. To accomplish this, the object should not implement either the Serializable or the Externalizable interface.

Some classes may find it beneficial to allow writing and reading but specifically handle and revalidate the state as it is deserialized. The class should implement writeObject and readObject methods to save and restore only the appropriate state. If access should be denied, throwing a NotSerializableException will prevent further access.

CONTENTS | PREV | NEXT
Copyright © 2005, 2010, Oracle and/or its affiliates. All rights reserved.


Uses of Interface com.sun.javadoc.SerialFieldTag (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.javadoc.SerialFieldTag

    • Uses of SerialFieldTag in com.sun.javadoc

      Methods in com.sun.javadoc that return SerialFieldTag
      Modifier and Type Method and Description
      SerialFieldTag[] FieldDoc.serialFieldTags()
      Return the serialField tags in this FieldDoc item.
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Java Object Serialization Specification: Contents

CONTENTS | PREV | NEXT
Java Object Serialization Specification

Table of Contents

1 System Architecture
1.1 Overview
1.2 Writing to an Object Stream
1.3 Reading from an Object Stream
1.4 Object Streams as Containers
1.5 Defining Serializable Fields for a Class
1.6 Documenting Serializable Fields and Data for a Class
1.7 Accessing Serializable Fields of a Class
1.8 The ObjectOutput Interface
1.9 The ObjectInput Interface
1.10 The Serializable Interface
1.11 The Externalizable Interface
1.12 Serialization of Enum Constants
1.13 Protecting Sensitive Information

2 Object Output Classes
2.1 The ObjectOutputStream Class
2.2 The ObjectOutputStream.PutField Class
2.3 The writeObject Method
2.4 The writeExternal Method
2.5 The writeReplace Method
2.6 The useProtocolVersion Method

3 Object Input Classes
3.1 The ObjectInputStream Class
3.2 The ObjectInputStream.GetField Class
3.3 The ObjectInputValidation Interface
3.4 The readObject Method
3.5 The readObjectNoData Method
3.6 The readExternal Method
3.7 The readResolve Method

4 Class Descriptors
4.1 The ObjectStreamClass Class
4.2 Dynamic Proxy Class Descriptors
4.3 Serialized Form
4.4 The ObjectStreamField Class
4.5 Inspecting Serializable Classes
4.6 Stream Unique Identifiers

5 Versioning of Serializable Objects
5.1 Overview
5.2 Goals
5.3 Assumptions
5.4 Who's Responsible for Versioning of Streams
5.5 Compatible JavaTM Type Evolution
5.6 Type Changes Affecting Serialization
5.6.1 Incompatible Changes
5.6.2 Compatible Changes

6 Object Serialization Stream Protocol
6.1 Overview
6.2 Stream Elements
6.3 Stream Protocol Versions
6.4 Grammar for the Stream Format
6.4.1 Rules of the Grammar
6.4.2 Terminal Symbols and Constants

A Security in Object Serialization
A.1 Overview
A.2 Design Goals
A.3 Security Issues
A.4 Preventing Serialization of Sensitive Data
A.5 Writing Class-Specific Serializing Methods
A.6 Guarding Unshared Deserialized Objects
A.7 Preventing Overwriting of Externalizable Objects
A.8 Encrypting a Bytestream

B Exceptions In Object Serialization

C Example of Serializable Fields
C.1 Example Alternate Implementation of java.io.File
CONTENTS | PREV | NEXT
Copyright © 2005, 2010, Oracle and/or its affiliates. All rights reserved.


serialver - The Serial Version Command

The serialver command returns the serialVersionUID.

SYNOPSIS

serialver [ options ]

DESCRIPTION

serialver returns the serialVersionUID for one or more classes in a form suitable for copying into an evolving class. When invoked with no arguments it prints a usage line.

OPTIONS

-show
Displays a simple user interface. Enter the full class name and press either the Enter key or the Show button to display the serialVersionUID.

SEE ALSO

java.io.ObjectStreamClass

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL: Using Servant Activators

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Using Servant Activators

What is a Servant Activator?

When creating a new POA, the application developer may declare specific policy choices for the new POA and provide a different adapter activator and servant manager (these are callback objects used by the POA to activate POAs on demand and activate servants). Creating new POAs also allows the application developer to partition the name space of objects, as Object Ids are interpreted relative to a POA. Finally, by creating new POAs, the developer can independently control request processing for multiple sets of objects.

A Servant Activator is a type of Servant Manager. Servant Managers are optional. You would use a servant manager to allow the POA to activate servants on demand when a request for an inactive object is received. If your server loads all objects when it starts up, you do not need a servant manager.

A servant manager is a callback object that the application developer can associate with a POA. The ORB will invoke operations on servant managers to activate servants on demand, and to deactivate servants. Servant managers are responsible for managing the association of an object reference (as characterized by its Object Id value) with a particular servant, and for determining whether an object reference exists or not. Each servant manager type contains two operations, the first called to find and return a servant and the second to deactivate a servant. The operations differ according to the amount of information usable for their situation.

To use servant managers, the USE_SERVANT_MANAGER policy must be set. Once set, the type of servant manager used in a particular situation depends on other policies in the POA. The two types of servant managers are:

  • ServantActivator

    When the POA has the RETAIN policy, it uses servant managers that are ServantActivators. A ServantActivator always results in an entry in the Active Object Map. The servant is then used until it is deactivated. A servant can be deactivated by destroying the POA, the POA Manager, or the ORB, or by an explicit deactivate call.

    • This document includes an example that uses Servant Activators, see An Example Using Servant Activators.
  • ServantLocator

    When the POA has the NON_RETAIN policy, it uses servant managers that are ServantLocators. Because the POA knows that the servant returned by this servant manager will be used only for a single request, it can supply extra information to the servant manager's operations and the servant manager's pair of operations may be able to cooperate to do something different than a ServantActivator. When the POA uses the ServantLocator interface, immediately after performing the operation invocation on the servant returned by preinvoke, the POA will invoke postinvoke on the servant manager, passing the ObjectId value and the Servant value as parameters (among others). This feature may be used to force every request for objects associated with a POA to be mediated by the servant manager.

    • For an example that uses Servant Locators see Using Servant Locators.

An Example Using Servant Activators

The following example code shows an application that uses Servant Activators to enable the POA to activate transient objects. This application builds on the "Hello World" example. The following files are included for your information:

  • Client.java
  • Server.java
  • Hello.idl
  • HelloImpl.java
  • Makefile
  • runSample

Client.java

import org.omg.CORBA.ORB;
import org.omg.CosNaming.*;

public class Client {
    public Client(String[] args) {
        try {
            ORB orb = ORB.init(args, System.getProperties());
            NamingContext rootContext = NamingContextHelper.narrow(
                orb.resolve_initial_references("NameService"));

            // Resolves for remote object reference of HelloServer
            NameComponent name[] = {new NameComponent("HelloServer", "")};
            Hello helloRef = HelloHelper.narrow(rootContext.resolve(name));
            System.out.println("\nClient: Obtained the remote object " +
                               "reference");

            // Invokes the remote sayHello() method
            System.out.println("Client: Invoking the remote operation ...");
            System.out.println(helloRef.sayHello());
        } catch (Exception e) {
            System.err.println("\nClient: Caught exception - " + e);
            e.printStackTrace();
        }
    }

    public static void main(String [] args) {
        Client servantActivatorClient = new Client(args);
    }
}

Server.java

import org.omg.CORBA.*;
import org.omg.PortableServer.*;
import org.omg.CosNaming.*;

public class Server {
    public Server(String[] args) {
        try {
            ORB orb = ORB.init(args, System.getProperties());
            POA rootPoa = (POA) orb.resolve_initial_references("RootPOA");
            rootPoa.the_POAManager().activate();
            System.out.println("\nServer: Obtained from ORB and activated " +
                               "the " + rootPoa.the_name());

            Policy poaPolicy[] = new Policy[2];
            poaPolicy[0] = rootPoa.create_servant_retention_policy(
                ServantRetentionPolicyValue.RETAIN);
            poaPolicy[1] = rootPoa.create_request_processing_policy(
                RequestProcessingPolicyValue.USE_SERVANT_MANAGER);
            System.out.println("Server: Set POA policy as RETAIN and " +
                               "USE_SERVANT_MANAGER");

            POA poa1 = rootPoa.create_POA("HelloPoa", null, poaPolicy);
            poa1.the_POAManager().activate();
            System.out.println("Server: Created and activated child POA " +
                               "\"" + poa1.the_name() + "\"");

            poa1.set_servant_manager(new PoaServantActivator());
            System.out.println("Server: Associated the servant manager of " +
                               "type servant activator with \"" +
                               poa1.the_name() + "\"");

            // This create_reference operation does not cause an activation,
            // the resulting object reference will be exported and passed to
            // client, so that subsequent requests on the reference will cause
            // the appropriate servant manager to be invoked
            org.omg.CORBA.Object objectRef = poa1.create_reference(
                HelloHelper.id());
            System.out.println("Server: Created a CORBA object reference " +
                               "from id \"" + HelloHelper.id() + "\"");

            NamingContext rootContext = NamingContextHelper.narrow(
                orb.resolve_initial_references("NameService"));
            NameComponent name[] = {new NameComponent("HelloServer", "")};
            rootContext.rebind(name, objectRef);
            System.out.println("Server: Exported the CORBA object reference " +
                               "to NameService");

            System.out.println("Server: Ready and waiting for requests ...");
            orb.run();
        } catch (Exception e) {
            System.err.println("\nServer: Caught exception - " + e);
            e.printStackTrace();
        }
    }

    public static void main(String [] args) {
        Server serverServantActivator = new Server(args) ;
    }
}

class PoaServantActivator extends LocalObject implements ServantActivator {
    // The incarnate operation is invoked by the POA whenever the POA receives
    // a request for an object that is not currently active, assuming the POA
    // has the RETAIN and USE_SERVANT_MANAGER policies
    public Servant incarnate(byte[] oid, POA adapter) throws ForwardRequest {
        try {
            HelloImpl servantObj = new HelloImpl();
            System.out.println("PoaServantActivator.incarnate(): Created \"" +
                               servantObj.getClass().getName() + "\" " +
                               "servant object for \"" + adapter.the_name() +
                               "\"");
            return servantObj;
        } catch (Exception e) {
            System.err.println("incarnate: Caught exception - " + e);
        }
        return null;
    }

    public void etherealize(byte[] oid, POA adapter, Servant serv,
                            boolean cleanup_in_progress,
                            boolean remaining_activations) {
    }
}

Hello.idl

interface Hello {
    string sayHello();
};

HelloImpl.java

public class HelloImpl extends HelloPOA {

    public String sayHello() {
        return "Hello :)";
    }

}

Makefile

IDLJ=${JAVA_HOME}/bin/idlj
JAVAC=${JAVA_HOME}/bin/javac
JAVA=${JAVA_HOME}/bin/java

CLASSFILES=./classes_dir
IDLJFLAGS=-fall -verbose -td ${CLASSFILES}
JFLAGS=-g -d $(CLASSFILES) -classpath $(CLASSFILES)
JAVAFLAGS=-cp $(CLASSFILES) -Dorg.omg.CORBA.ORBInitialHost=localhost \
          -Dorg.omg.CORBA.ORBInitialPort=1950
ORBD_FLAGS=-port 1949 -ORBInitialHost ${SERVER_HOSTNAME} \
           -ORBInitialPort 1950 -ORBDebug
ORBD=${JAVA_HOME}/bin/orbd $(ORBD_FLAGS) orbd

client = Client.java

server = HelloImpl.java \
         Server.java

all: clean build run

clean:
        @echo ""
        @echo "*** Clean up old files and directories ***"
        -$(RM) $(CLASSFILES)
        -$(RM) ./orb.db
        -$(RM) ./kill_started_processes.sh

build: stubs client_server

stubs: Hello.idl
        @echo ""
        @echo "*** Generate stubs and helpers ***"
        @-$(MKDIR) $(CLASSFILES)
        $(IDLJ) $(IDLJFLAGS) Hello.idl

client_server: $(client) $(server)
        @echo ""
        @echo "*** Compile client, server and implementation ***"
        $(JAVAC) $(JFLAGS) $(client) $(server)

run: run_orbd run_server run_client terminate_servers

run_orbd:
        @echo ""
        @echo "*** Start the orbd ***"
        $(ORBD) & \
        echo "kill -9 $$!" > ./kill_started_processes.sh; \
        if [ $(OS) = "WinNT" ] ; then \
            tpid=`ps -o pid,ppid,comm | grep $$! | grep -v "sh" | cut -c1-6` ; \
            echo "kill -9 $$tpid" >> ./kill_started_processes.sh ; \
        fi ; \
        $(SLEEP) $(SLEEP_LONG)

run_server: run_orbd
        @echo ""
        @echo "*** Start the Server ***"
        $(JAVA) $(JAVAFLAGS) Server & \
        echo "kill -9 $$!" >> ./kill_started_processes.sh; \
        if [ $(OS) = "WinNT" ] ; then \
        tpid=`ps -o pid,ppid,comm | grep $$! | grep -v "sh" | cut -c1-6` ; \
        echo "kill -9 $$tpid" >> ./kill_started_processes.sh ; \
        fi ; \
        $(SLEEP) $(SLEEP_NORMAL)

run_client:
        @echo ""
        @echo "*** Start the Client ***"
        $(JAVA) $(JAVAFLAGS) Client

terminate_servers:
        @echo ""
        @echo "*** Terminate the Server and orbd ***"
        @$(SLEEP) $(SLEEP_SHORT)
        @if [ -f ./kill_started_processes.sh ]; then \
                $(CHMOD) u+x ./kill_started_processes.sh; \
                ./kill_started_processes.sh; \
                $(SLEEP) $(SLEEP_SHORT) ; \
        fi

runSample

#!/bin/ksh

if [ `uname` = "SunOS" ] ; then
    OS="Solaris_sparc"
    JAVA_HOME=/path_to_your_java_installation
    SEP=:
    SLEEP=/bin/sleep
    RM="/bin/rm -rf"
    CHMOD=/bin/chmod
    MKDIR=/bin/mkdir
    SLEEP_SHORT=2
    SLEEP_NORMAL=5
    SLEEP_LONG=7
elif [ `uname` = "Windows_NT" ] ; then
    OS="WinNT"
    if [ ! -d "y:/path_to_your_java_installation" ] ; then
        echo; echo "Please map drive y: to \\\\\your_Java_drive before runSample"
        exit 1
    fi
    JAVA_HOME="y:/path_to_your_java_installation"
    SEP=";"
    SLEEP=sleep
    RM="rm -rf"
    CHMOD=chmod
    MKDIR="mkdir -p"
    SLEEP_SHORT=5
    SLEEP_NORMAL=10
    SLEEP_LONG=15
fi

while [ $# -gt 0 ] ; do
   case $1 in
   -host ) SERVER_HOSTNAME=$2 ;
           shift;;
   * ) TARGET=$* ;
       break ;;
   esac
   shift
done

DEFAULT_HOSTNAME=localhost
SERVER_HOSTNAME=${HOSTNAME-$DEFAULT_HOSTNAME}

make ${TARGET} \
   "OS=${OS}" \
   "JAVA_HOME=${JAVA_HOME}" \
   "SERVER_HOSTNAME=${SERVER_HOSTNAME}" \
   "SLEEP=${SLEEP}" \
   "RM=${RM}" \
   "CHMOD=${CHMOD}" \
   "MKDIR=${MKDIR}" \
   "SLEEP_SHORT=${SLEEP_SHORT}" \
   "SLEEP_NORMAL=${SLEEP_NORMAL}" \
   "SLEEP_LONG=${SLEEP_LONG}"

Running the Example Servant Activator Example

To run this example,

  1. Create the files using the code shown above.
  2. Run the example as shown in runSample.

You will see output generated to the terminal window similar to that below:

*** Clean up old files and directories ***
/bin/rm -rf ./classes_dir
/bin/rm -rf ./orb.db
/bin/rm -rf ./kill_started_processes.sh

*** Generate stubs and helpers ***
/path_to_your_java_installation/bin/idlj -fall -verbose -td ./classes_dir Hello.idl
Parsing Hello.idl
done  - Hello.idl

Generating Hello
done   -   Hello

*** Compile client, server and implementation ***
/path_to_your_java_installation/bin/javac -g -d ./classes_dir -classpath
./classes_dir Client.java HelloImpl.java Server.java

*** Start the orbd ***
/path_to_your_java_installation/bin/orbd -port 1949 -ORBInitialHost localhost
-ORBInitialPort 1950 -ORBDebug orbd & \
echo "kill -9 $!" > ./kill_started_processes.sh; \
if [ Solaris_sparc = "WinNT" ] ; then \
    tpid=`ps -o pid,ppid,comm | grep $! | grep -v "sh" | cut -c1-6` ; \
    echo "kill -9 $tpid" >> ./kill_started_processes.sh ; \
fi ; \
/bin/sleep 7
ORBD begins initialization.
ORBD is ready.
ORBD serverid: 1
activation dbdir: /path_to_your_sample_file/ServantActivator/./orb.db
activation port: 1949
activation Server Polling Time: 1000 milli-seconds
activation Server Startup Delay: 1000 milli-seconds

*** Start the Server ***
/path_to_your_java_installation/bin/java -cp ./classes_dir
-Dorg.omg.CORBA.ORBInitialHost=localhost -Dorg.omg.CORBA.ORBInitialPort=1950 Server & \
echo "kill -9 $!" >> ./kill_started_processes.sh; \
if [ Solaris_sparc = "WinNT" ] ; then \
tpid=`ps -o pid,ppid,comm | grep $! | grep -v "sh" | cut -c1-6` ; \
echo "kill -9 $tpid" >> ./kill_started_processes.sh ; \
fi ; \
/bin/sleep 5

Server: Obtained from ORB and activated the RootPOA
Server: Set POA policy as RETAIN and USE_SERVANT_MANAGER
Server: Created and activated child POA "HelloPoa"
Server: Associated the servant manager of type servant activator with "HelloPoa"
Server: Created a CORBA object reference from id "IDL:Hello:1.0"
Server: Exported the CORBA object reference to NameService
Server: Ready and waiting for requests ...

*** Start the Client ***
/path_to_your_java_installation/bin/java -cp ./classes_dir
-Dorg.omg.CORBA.ORBInitialHost=localhost -Dorg.omg.CORBA.ORBInitialPort=1950 Client

Client: Obtained the remote object reference
Client: Invoking the remote operation ...
PoaServantActivator.incarnate(): Created "HelloImpl" servant object for "HelloPoa"
Hello :)

*** Terminate the Server and orbd ***

Further Information

For more information on Servant Activators, see the section on Servant Managers, in section 11.3.4 of the CORBA 2.3.1 Specification.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL: Using Servant Locators

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Using Servant Locators

What is a Servant Locator?

When creating a new POA, the application developer may declare specific policy choices for the new POA and provide a different adapter activator and servant manager (these are callback objects used by the POA to activate POAs on demand and activate servants). Creating new POAs also allows the application developer to partition the name space of objects, as Object Ids are interpreted relative to a POA. Finally, by creating new POAs, the developer can independently control request processing for multiple sets of objects.

A Servant Activator is a type of Servant Manager. Servant Managers are optional. You would use a servant manager to allow the POA to activate servants on demand when a request for an inactive object is received. If your server loads all objects when it starts up, you do not need a servant manager.

A servant manager is a callback object that the application developer can associate with a POA. The ORB will invoke operations on servant managers to activate servants on demand, and to deactivate servants. Servant managers are responsible for managing the association of an object reference (as characterized by its Object Id value) with a particular servant, and for determining whether an object reference exists or not. Each servant manager type contains two operations, the first called to find and return a servant and the second to deactivate a servant. The operations differ according to the amount of information usable for their situation.

To use servant managers, the USE_SERVANT_MANAGER policy must be set. Once set, the type of servant manager used in a particular situation depends on other policies in the POA. The two types of servant managers are:

  • ServantActivator

    When the POA has the RETAIN policy, it uses servant managers that are ServantActivators. A ServantActivator always results in an entry in the Active Object Map. The servant is then used until it is deactivated. A servant can be deactivated by destroying the POA, the POA Manager, or the ORB, or by an explicit deactivate call.

    • For an example that uses Servant Activators, see Using Servant Activators.
  • ServantLocator

    When the POA has the NON_RETAIN policy, it uses servant managers that are ServantLocators. Because the POA knows that the servant returned by this servant manager will be used only for a single request, it can supply extra information to the servant manager's operations and the servant manager's pair of operations may be able to cooperate to do something different than a ServantActivator. When the POA uses the ServantLocator interface, immediately after performing the operation invocation on the servant returned by preinvoke, the POA will invoke postinvoke on the servant manager, passing the ObjectId value and the Servant value as parameters (among others). This feature may be used to force every request for objects associated with a POA to be mediated by the servant manager.

    • This document includes an example that uses Servant Locators, see An Example Using Servant Locators.

An Example Using Servant Locators

The following example code shows an application that uses Servant Locators to enable the POA to activate transient objects. This application builds on the "Hello World" example. The following files are included for your information:

  • Client.java
  • Server.java
  • Hello.idl
  • HelloImpl.java
  • Makefile
  • runSample

Client.java

import org.omg.CORBA.ORB;
import org.omg.CosNaming.*;

public class Client {
    public Client(String[] args) {
        try {
            ORB orb = ORB.init(args, System.getProperties());
            NamingContext rootContext = NamingContextHelper.narrow(
                orb.resolve_initial_references("NameService"));

            // Resolves for remote object reference of HelloServer
            NameComponent name[] = {new NameComponent("HelloServer", "")};
            Hello helloRef = HelloHelper.narrow(rootContext.resolve(name));
            System.out.println("\nClient: Obtained the remote object " +
                               "reference");

            // Invokes the remote sayHello() method
            System.out.println("Client: Invoking the remote operation ...");
            System.out.println(helloRef.sayHello());
        } catch (Exception e) {
            System.err.println("\nClient: Caught exception - " + e);
            e.printStackTrace();
        }
    }

    public static void main(String [] args) {
        Client servantLocatorClient = new Client(args);
    }
}

Server.java

import org.omg.CORBA.*;
import org.omg.PortableServer.*;
import org.omg.PortableServer.ServantLocatorPackage.*;
import org.omg.CosNaming.*;

public class Server {
    public Server(String[] args) {
        try {
            ORB orb = ORB.init(args, System.getProperties());
            POA rootPoa = (POA) orb.resolve_initial_references("RootPOA");
            rootPoa.the_POAManager().activate();
            System.out.println("\nServer: Obtained from ORB and activated " +
                               "the " + rootPoa.the_name());

            Policy poaPolicy[] = new Policy[2];
            poaPolicy[0] = rootPoa.create_servant_retention_policy(
                ServantRetentionPolicyValue.NON_RETAIN);
            poaPolicy[1] = rootPoa.create_request_processing_policy(
                RequestProcessingPolicyValue.USE_SERVANT_MANAGER);
            System.out.println("Server: Set POA policy as NON_RETAIN and " +
                               "USE_SERVANT_MANAGER");

            POA poa1 = rootPoa.create_POA("HelloPoa", null, poaPolicy);
            poa1.the_POAManager().activate();
            System.out.println("Server: Created and activated child POA " +
                               "\"" + poa1.the_name() + "\"");

            poa1.set_servant_manager(new PoaServantLocator());
            System.out.println("Server: Associated the servant manager of " +
                               "type servant locator with \"" +
                               poa1.the_name() + "\"");

            // This create_reference operation does not cause an activation,
            // the resulting object reference will be exported and passed to
            // client, so that subsequent requests on the reference will cause
            // the appropriate servant manager to be invoked
            org.omg.CORBA.Object objectRef = poa1.create_reference(
                HelloHelper.id());
            System.out.println("Server: Created a CORBA object reference " +
                               "from id \"" + HelloHelper.id() + "\"");

            NamingContext rootContext = NamingContextHelper.narrow(
                orb.resolve_initial_references("NameService"));
            NameComponent name[] = {new NameComponent("HelloServer", "")};
            rootContext.rebind(name, objectRef);
            System.out.println("Server: Exported the CORBA object reference " +
                               "to NameService");

            System.out.println("Server: Ready and waiting for requests ...");
            orb.run();
        } catch (Exception e) {
            System.err.println("\nServer: Caught exception - " + e);
            e.printStackTrace();
        }
    }

    public static void main(String [] args) {
        Server serverServantLocator = new Server(args) ;
    }
}

class PoaServantLocator extends LocalObject implements ServantLocator {
    public Servant preinvoke(byte[] oid, POA adapter,
                             String operation,
                             CookieHolder the_cookie) throws ForwardRequest {
        try {
            HelloImpl servantObj = new HelloImpl();
            System.out.println("PoaServantLocator.preinvoke(): Created \"" +
                               servantObj.getClass().getName() + "\" " +
                               "servant object for \"" + adapter.the_name() +
                               "\"");
            return servantObj;
        } catch (Exception e) {
            System.err.println("preinvoke: Caught exception - " + e);
        }
        return null;
    }

    public void postinvoke(byte[] oid, POA adapter,
                           String operation,
                           java.lang.Object the_cookie,
                           Servant the_servant) {
        try {
            System.out.println("PoaServantLocator.postinvoke(): For \"" +
                               adapter.the_name() + "\" adapter of servant " +
                               "object type \"" +
                               the_servant.getClass().getName() + "\"");
        } catch (Exception e) {
            System.err.println("postinvoke: Caught exception - " + e);
        }
    }
}

Hello.idl

interface Hello {
    string sayHello();
};

HelloImpl.java

public class HelloImpl extends HelloPOA {

    public String sayHello() {
        return "Hello :)";
    }

}

Makefile

IDLJ=${JAVA_HOME}/bin/idlj
JAVAC=${JAVA_HOME}/bin/javac
JAVA=${JAVA_HOME}/bin/java

CLASSFILES=./classes_dir
IDLJFLAGS=-fall -verbose -td ${CLASSFILES}
JFLAGS=-g -d $(CLASSFILES) -classpath $(CLASSFILES)
JAVAFLAGS=-cp $(CLASSFILES) -Dorg.omg.CORBA.ORBInitialHost=localhost \
          -Dorg.omg.CORBA.ORBInitialPort=1950
ORBD_FLAGS=-port 1949 -ORBInitialHost ${SERVER_HOSTNAME} \
           -ORBInitialPort 1950 -ORBDebug
ORBD=${JAVA_HOME}/bin/orbd $(ORBD_FLAGS) orbd

client = Client.java

server = HelloImpl.java \
         Server.java

all: clean build run

clean:
        @echo ""
        @echo "*** Clean up old files and directories ***"
        -$(RM) $(CLASSFILES)
        -$(RM) ./orb.db
        -$(RM) ./kill_started_processes.sh

build: stubs client_server

stubs: Hello.idl
        @echo ""
        @echo "*** Generate stubs and helpers ***"
        @-$(MKDIR) $(CLASSFILES)
        $(IDLJ) $(IDLJFLAGS) Hello.idl

client_server: $(client) $(server)
        @echo ""
        @echo "*** Compile client, server and implementation ***"
        $(JAVAC) $(JFLAGS) $(client) $(server)

run: run_orbd run_server run_client terminate_servers

run_orbd:
        @echo ""
        @echo "*** Start the orbd ***"
        $(ORBD) & \
        echo "kill -9 $$!" > ./kill_started_processes.sh; \
        if [ $(OS) = "WinNT" ] ; then \
            tpid=`ps -o pid,ppid,comm | grep $$! | grep -v "sh" | cut -c1-6` ; \
            echo "kill -9 $$tpid" >> ./kill_started_processes.sh ; \
        fi ; \
        $(SLEEP) $(SLEEP_LONG)

run_server: run_orbd
        @echo ""
        @echo "*** Start the Server ***"
        $(JAVA) $(JAVAFLAGS) Server & \
        echo "kill -9 $$!" >> ./kill_started_processes.sh; \
        if [ $(OS) = "WinNT" ] ; then \
        tpid=`ps -o pid,ppid,comm | grep $$! | grep -v "sh" | cut -c1-6` ; \
        echo "kill -9 $$tpid" >> ./kill_started_processes.sh ; \
        fi ; \
        $(SLEEP) $(SLEEP_NORMAL)

run_client:
        @echo ""
        @echo "*** Start the Client ***"
        $(JAVA) $(JAVAFLAGS) Client

terminate_servers:
        @echo ""
        @echo "*** Terminate the Server and orbd ***"
        @$(SLEEP) $(SLEEP_SHORT)
        @if [ -f ./kill_started_processes.sh ]; then \
                $(CHMOD) u+x ./kill_started_processes.sh; \
                ./kill_started_processes.sh; \
                $(SLEEP) $(SLEEP_SHORT) ; \
        fi

runSample

#!/bin/ksh

if [ `uname` = "SunOS" ] ; then
    OS="Solaris_sparc"
    JAVA_HOME=/path_to_your_java_installation
    SEP=:
    SLEEP=/bin/sleep
    RM="/bin/rm -rf"
    CHMOD=/bin/chmod
    MKDIR=/bin/mkdir
    SLEEP_SHORT=2
    SLEEP_NORMAL=5
    SLEEP_LONG=7
elif [ `uname` = "Windows_NT" ] ; then
    OS="WinNT"
    if [ ! -d "y:/path_to_your_java_installation" ] ; then
        echo; echo "Please map drive y: to \\\\\path_to_your_java_installation before
runSample"
        exit 1
    fi
    JAVA_HOME="y:/path_to_your_java_installation"
    SEP=";"
    SLEEP=sleep
    RM="rm -rf"
    CHMOD=chmod
    MKDIR="mkdir -p"
    SLEEP_SHORT=5
    SLEEP_NORMAL=10
    SLEEP_LONG=15
fi

while [ $# -gt 0 ] ; do
   case $1 in
   -host ) SERVER_HOSTNAME=$2 ;
           shift;;
   * ) TARGET=$* ;
       break ;;
   esac
   shift
done

DEFAULT_HOSTNAME=localhost
SERVER_HOSTNAME=${HOSTNAME-$DEFAULT_HOSTNAME}

make ${TARGET} \
   "OS=${OS}" \
   "JAVA_HOME=${JAVA_HOME}" \
   "SERVER_HOSTNAME=${SERVER_HOSTNAME}" \
   "SLEEP=${SLEEP}" \
   "RM=${RM}" \
   "CHMOD=${CHMOD}" \
   "MKDIR=${MKDIR}" \
   "SLEEP_SHORT=${SLEEP_SHORT}" \
   "SLEEP_NORMAL=${SLEEP_NORMAL}" \
   "SLEEP_LONG=${SLEEP_LONG}"

Running the Example Servant Activator Example

To run this example,

  1. Create the files using the code shown above.
  2. Run the example as shown in runSample.

You will see output generated to the terminal window similar to that below:

*** Clean up old files and directories ***
/bin/rm -rf ./classes_dir
/bin/rm -rf ./orb.db
/bin/rm -rf ./kill_started_processes.sh

*** Generate stubs and helpers ***
/path_to_your_java_installation/bin/idlj -fall -verbose -td ./classes_dir Hello.idl
Parsing Hello.idl
done  - Hello.idl

Generating Hello
done   -   Hello

*** Compile client, server and implementation ***
/path_to_your_java_installation/bin/javac -g -d ./classes_dir -classpath ./classes_dir
Client.java HelloImpl.java Server.java

*** Start the orbd ***
/path_to_your_java_installation/bin/orbd -port 1949 -ORBInitialHost localhost -ORBInitialPort
1950 -ORBDebug orbd & \
echo "kill -9 $!" > ./kill_started_processes.sh; \
if [ Solaris_sparc = "WinNT" ] ; then \
    tpid=`ps -o pid,ppid,comm | grep $! | grep -v "sh" | cut -c1-6` ; \
    echo "kill -9 $tpid" >> ./kill_started_processes.sh ; \
fi ; \
/bin/sleep 7
ORBD begins initialization.
ORBD is ready.
ORBD serverid: 1
activation dbdir: /home/dcarson1/samples/POA_samples/ServantLocator/./orb.db
activation port: 1949
activation Server Polling Time: 1000 milli-seconds
activation Server Startup Delay: 1000 milli-seconds

*** Start the Server ***
/path_to_your_java_installation/bin/java -cp ./classes_dir
-Dorg.omg.CORBA.ORBInitialHost=localhost -Dorg.omg.CORBA.ORBInitialPort=1950 Server & \
echo "kill -9 $!" >> ./kill_started_processes.sh; \
if [ Solaris_sparc = "WinNT" ] ; then \
tpid=`ps -o pid,ppid,comm | grep $! | grep -v "sh" | cut -c1-6` ; \
echo "kill -9 $tpid" >> ./kill_started_processes.sh ; \
fi ; \
/bin/sleep 5

Server: Obtained from ORB and activated the RootPOA
Server: Set POA policy as NON_RETAIN and USE_SERVANT_MANAGER
Server: Created and activated child POA "HelloPoa"
Server: Associated the servant manager of type servant locator with "HelloPoa"
Server: Created a CORBA object reference from id "IDL:Hello:1.0"
Server: Exported the CORBA object reference to NameService
Server: Ready and waiting for requests ...

*** Start the Client ***
/path_to_your_java_installation/bin/java -cp ./classes_dir
-Dorg.omg.CORBA.ORBInitialHost=localhost -Dorg.omg.CORBA.ORBInitialPort=1950 Client

Client: Obtained the remote object reference
Client: Invoking the remote operation ...
PoaServantLocator.preinvoke(): Created "HelloImpl" servant object for "HelloPoa"
PoaServantLocator.postinvoke(): For "HelloPoa" adapter of servant object type "HelloImpl"
Hello :)

*** Terminate the Server and orbd ***

Further Information

For more information on Servant Locators, see the section on Servant Managers in section 11.3.4 of the CORBA 2.3.1 Specification.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Server-Class Machine Detection

Starting with J2SE 5.0, when an application starts up, the launcher can attempt to detect whether the application is running on a "server-class" machine and, if so, use the Java HotSpot Server Virtual Machine (server VM) instead of the Java HotSpot Client Virtual Machine (client VM). The aim is to improve performance even if no one configures the VM to reflect the application it's running. In general, the server VM starts up more slowly than the client VM, but over time runs more quickly.

Note: For Java SE 6, the definition of a server-class machine is one with at least 2 CPUs and at least 2GB of physical memory.

In Java SE 6, server-class detection occurs if neither -server nor -client is specified when launching the application on an i586 or Sparc 32-bit machine running Solaris or Linux. As the following table shows, the i586 Microsoft Windows platform uses the client VM by default. The remaining Sun-supported platforms use only the server VM.

Architecture | OS | Default client VM | if server-class, server VM; otherwise, client VM | Default server VM
SPARC 32-bit | Solaris |  | X |
i586 | Solaris |  | X |
i586 | Linux |  | X |
i586 | Microsoft Windows | X |  |
SPARC 64-bit | Solaris | — |  | X
AMD64 | Solaris | — |  | X
AMD64 | Linux | — |  | X
AMD64 | Microsoft Windows | — |  | X
Legend: X = default VM — = client VM not provided for this platform

For details of using command-line options for launching applications, see the java tool documentation for Solaris and Linux, or Microsoft Windows.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


servertool - The Java™ IDL Server Tool

servertool provides a command-line interface for application programmers to register, unregister, startup, and shutdown a persistent server.

SYNOPSIS

servertool -ORBInitialPort nameserverport options [ commands ]

If you did not enter a command when starting servertool, the command-line tool displays with a servertool > prompt. Enter commands at the servertool > prompt.

If you enter a command when starting servertool, the Java IDL Server Tool starts, runs the command, and exits.

The -ORBInitialPort nameserverport option is required. The value for nameserverport must specify the port on which orbd is running and listening for incoming requests. When using Solaris software, you must become root to start a process on a port under 1024. For this reason, we recommend that you use a port number greater than or equal to 1024 for the nameserverport.

DESCRIPTION

The servertool provides the command-line interface for the application programmers to register, unregister, startup, and shutdown a persistent server. Other commands are provided to obtain various statistical information about the server.

OPTIONS

-ORBInitialHost nameserverhost
Specifies the host machine on which the name server is running and listening for incoming requests. The nameserverhost defaults to localhost if this option is not specified. If orbd and servertool are running on different machines, you must specify the name or IP address of the host on which orbd is running.

-J option
Pass option to the Java virtual machine, where option is one of the options described on the reference page for the java application launcher. For example, -J-Xms48m sets the startup memory to 48 megabytes. It is a common convention for -J to pass options to the underlying virtual machine.

COMMANDS

register -server <server class name> -classpath <classpath to server> [ -applicationName <application name> -args <args to server> -vmargs <flags to be passed to Java VM> ]
Register a new persistent server with the Object Request Broker Daemon (ORBD). If the server is not already registered, it is registered and activated. This command causes an install method to be invoked in the main class of the server identified by the -server option. The install method must be public static void install(org.omg.CORBA.ORB). The install method is optional and enables the developer to provide their own server installation behavior (for example, creating database schema).

unregister -serverid <server id > | -applicationName <application name>
Unregister a server from the ORBD by using either its server id or its application name. This command causes an uninstall method to be invoked in the main class of the server identified by the -server option. The uninstall method must be public static void uninstall(org.omg.CORBA.ORB). The uninstall method is optional and enables the developer to provide their own server uninstall behavior (for example, undoing the behavior of the install method).

getserverid -applicationName <application name>
Return the server id that corresponds with an application.

list
List information about all persistent servers registered with the ORBD.

listappnames
List the application names for all servers currently registered with the ORBD.

listactive
List information about all persistent servers that have been launched by the ORBD and are currently running.

locate -serverid <server id > | -applicationName <application name> [-endpointType <endpointType> ]
Locate the endpoints (ports) of a specific type for all ORBs created by a registered server. If a server is not already running, it is activated. If an endpoint type is not specified, then the plain/non-protected endpoint associated with each ORB in a server is returned.

locateperorb -serverid <server id > | -applicationName <application name> [-orbid <ORB name> ]
Locate all the endpoints (ports) registered by a specific ORB of registered server. If a server is not already running, then it is activated. If an orbid is not specified, the default value of "" is assigned to the orbid. If any ORBs are created with an orbid of empty string, all ports registered by it are returned.

orblist -serverid <server id > | -applicationName <application name>
Lists the ORBId of the ORBs defined on a server. An ORBId is the string name for the ORB created by the server. If the server is not already running, it is activated.

shutdown -serverid <server id > | -applicationName <application name>
Shutdown an active server that is registered with ORBD. During execution of this command, the shutdown() method defined in the class specified by either the -serverid or -applicationName parameter is also invoked to shutdown the server process appropriately.

startup -serverid <server id > | -applicationName <application name>
Startup or activate a server that is registered with ORBD. If the server is not running, this command launches the server. If the server is already running, an error message is returned to the user.

help
List all the commands available to the server through the server tool.

quit
Exit the server tool.

SEE ALSO

orbd

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


ServiceManager (JNLP API Reference 1.7.0)

  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method
javax.jnlp

Class ServiceManager

  • java.lang.Object
    • javax.jnlp.ServiceManager

  • public final class ServiceManager
extends java.lang.Object
    The ServiceManager provides static methods to lookup JNLP services. This class is abstract and final and cannot be instantiated.

    Requests are delegated to a ServiceManagerStub object. This object must be set by the JNLP Client on startup using the setServiceManagerStub method.

    Since:
    1.0
    See Also:
    ServiceManagerStub

    • Method Summary

      Methods
      Modifier and Type Method and Description
      static java.lang.String[] getServiceNames()
      Returns the names of all services implemented by the JNLP Client.
      static java.lang.Object lookup(java.lang.String name)
      Asks the JNLP Client for a service with a given name.
      static void setServiceManagerStub(ServiceManagerStub stub)
      Sets the object that all lookup and getServiceNames requests are delegated to.

      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

    • Method Detail

      • lookup

        public static java.lang.Object lookup(java.lang.String name)
                               throws UnavailableServiceException
        Asks the JNLP Client for a service with a given name. The lookup must be idempotent, that is return the same object for each invocation with the same name.
        Parameters:
        name - Name of service to lookup.
        Returns:
        An object implementing the service. null will never be returned. Instead an exception will be thrown.
        Throws:
        UnavailableServiceException - if the service is not available, or if name is null.
        UnavailableServiceException

      • getServiceNames

        public static java.lang.String[] getServiceNames()
        Returns the names of all services implemented by the JNLP Client.

      • setServiceManagerStub

        public static void setServiceManagerStub(ServiceManagerStub stub)
        Sets the object that all lookup and getServiceNames requests are delegated to. The setServiceManagerStub call is ignored if the stub has already been set.

        This method should be called exactly once by the JNLP Client, and never be called by a launched application.

        Parameters:
        stub - The ServiceManagerStub object to delegate to
  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.


ServiceManagerStub (JNLP API Reference 1.7.0)

  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method
javax.jnlp

Interface ServiceManagerStub

  • public interface ServiceManagerStub
    A ServiceManagerStub object implements the particular lookup of JNLP services by the JNLP Client. The object is registered with the ServiceManager using the ServiceManager.setServiceManagerStub(javax.jnlp.ServiceManagerStub) method.
    Since:
    1.0
    See Also:
    ServiceManager

    • Method Summary

      Methods
      Modifier and Type Method and Description
      java.lang.String[] getServiceNames()
      See description for ServiceManager.getServiceNames()
      java.lang.Object lookup(java.lang.String name)
      See description for ServiceManager.lookup(java.lang.String)

    • Method Detail

      • lookup

        java.lang.Object lookup(java.lang.String name)
                        throws UnavailableServiceException
        See description for ServiceManager.lookup(java.lang.String)
        Throws:
        UnavailableServiceException

      • getServiceNames

        java.lang.String[] getServiceNames()
        See description for ServiceManager.getServiceNames()
  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.


Using Activation: the Setup Program

This tutorial describes how to write a program that registers an activation descriptor for a remote object with the JavaTM Remote Method Invocation (Java RMI) activation system daemon (rmid) and then binds a stub for that remote object in an rmiregistry so that clients can look it up.

This tutorial has the following steps:

  • Implement the Setup program
  • Compile the source file
  • Start rmid, rmiregistry, and the Setup program
The files needed for this tutorial are:
  • Setup.java - main Setup program
  • setup.policy - security policy file for the Setup program
  • rmid.policy - security policy file for rmid
  • group.policy - security policy file for the activation group

Implement the Setup program

The Setup program, implemented by the class examples.activation.Setup, registers an activation descriptor with rmid to enable future activation of the object specified by that activation descriptor. This program does not create an instance of a remote object, but instead registers a remote object's stub with an rmiregistry so that clients can look it up. This Setup program must be run prior to running any of the clients described in the other activation tutorials.

The Setup program uses a number of system properties to customize the information that is registered with rmid and rmiregistry. The program also takes a single command-line argument that specifies the package-qualified name of the implementation class for the activatable remote object being registered. The Setup program is run as follows:

java -cp classpath \
     -Djava.security.policy=setup.policy        \
     -Djava.rmi.server.codebase=codebase         \
     -Dexamples.activation.setup.codebase=setupCodebase  \
     -Dexamples.activation.impl.codebase=implCodebase \
     -Dexamples.activation.name=name             \
     [-Dexamples.activation.file=filename]       \
     [-Dexamples.activation.policy=group.policy] \
     examples.activation.Setup implClass

where:

  • classpath is a class path that includes the Setup program and the implementation classes
  • setup.policy is the security policy file for the Setup program
  • codebase is the location (URL) of the remote interface class(es)
  • setupCodebase is the location (URL) the Setup program class (used in granting permissions to the Setup program in the setup.policy file)
  • implCodebase is the location (URL) of the implementation class(es), used in the activation descriptor and also used in the group policy file as the codebase to grant permissions to
  • name is the name for the object's stub to be bound in the registry
  • file (optional) is the name of a file containing the object's persistent state which is registered as the data in the object's activation descriptor (no default)
  • group.policy (optional) is the security policy file for the activation group (defaults to group.policy), and
  • implClass is the fully-qualified name of the
  • implementation class.

The following is an example policy file for the Setup program:

  grant codeBase "${examples.activation.setup.codebase}" {

    // permissions to read system properties required by setup program
    permission java.util.PropertyPermission "examples.activation.impl.codebase","read";
    permission java.util.PropertyPermission "examples.activation.policy","read";
    permission java.util.PropertyPermission "examples.activation.file","read";
    permission java.util.PropertyPermission "examples.activation.name","read";

    // permission to connect to the activation system and the registry
    permission java.net.SocketPermission "*:1098-1099","connect";
};

The codebase to which permissions are granted is a URL specifying the location of the Setup program's implementation class(es). This URL is the value of the examples.activation.setup.codebase system property, which is defined when the Setup program is run. The Setup program needs the following permissions:

  • java.util.PropertyPermission - to read various system properties required by the Setup program
  • java.net.SocketPermission - to connect to the activation system (port 1098) to register an activation descriptor, and to connect to the registry (port 1099) to bind the activatable object's stub to a name

There are several steps to writing this Setup program:

  • Construct an activation group descriptor
  • Register the group descriptor
  • Construct an activation descriptor
  • Register the activation descriptor, and finally,
  • Bind the remote object's stub in an rmiregistry

The Setup class has a static main method that performs all of the above steps. But before doing so, the main method sets a SecurityManager and obtains the single command line argument that specifies the package-qualified name of the implementation class for the activatable remote object. The rest of the steps are described below. See Setup.java for the full source code.

Construct an activation group descriptor

Before an application registers information about a particular activatable remote object, it first needs to register information about the activation group that the object will be contained in. An activation group is a container virtual machine (VM) for a set of activatable objects. Each activation group manages the execution of one or more activatable objects. An activation group descriptor contains information that the activation system needs to start an activation group's VM. An application can register an activation group descriptor with the activation system rmid to obtain an activation group ID to use for the activatable object, or the application can use an activation group ID obtained from a previous group registration.

The activation group descriptor, an instance of the class java.rmi.activation.ActivationGroupDesc, can be constructed in several ways. This tutorial uses the two parameter constructor ActivationGroupDesc(Properties,CommandEnvironment). The Properties map contains overrides for system properties in the activation group VM. For this tutorial, an activation group VM needs the following system properties defined:

  • java.security.policy - the group's security policy file
  • java.class.path - a dummy class path to prevent an activation group from loading implementation classes from the local class path
  • examples.activation.impl.codebase - the location of the implementation classes, which the group's policy file uses to grant permissions to
  • examples.activation.file - a file containg the object's persistent state

The java.security.policy property is specified by the examples.activation.policy system property, and defaults to the file named group.policy which will, in practice, be in the working directory where rmid is run. The java.class.path property is defined as no_classpath. The examples.activation.impl.codebase and examples.activation.file properties are specified by their current values (respectively), defined when the Setup program runs.

The group descriptor is constructed as follows:

String policy =
    System.getProperty("examples.activation.policy", "group.policy");
String implCodebase =
    System.getProperty("examples.activation.impl.codebase");
String filename =
    System.getProperty("examples.activation.file", "");

Properties props = new Properties();
props.put("java.security.policy", policy);
props.put("java.class.path", "no_classpath");
props.put("examples.activation.impl.codebase", implCodebase);
if (filename != null && !filename.equals("")) {
    props.put("examples.activation.file", filename);
}

ActivationGroupDesc groupDesc = new ActivationGroupDesc(props, null);

The following is an example group.policy file that grants the appropriate permissions for the activation examples:

grant codeBase "${examples.activation.impl.codebase}" {

    // permission to read and write object's file
    permission java.io.FilePermission "${examples.activation.file}","read,write";

    // permission to listen on an anonymous port
    permission java.net.SocketPermission "*:1024-","accept";
};

The codebase to which permissions are granted is a URL specifying the location of the activatable object's implementation classes. This URL is the value of the examples.activation.impl.codebase system property, which will be defined in the activation group's VM. An activatable object in the group needs two permissions:

  • java.io.FilePermission - to read and write the file containing the activatable object's persistent state
  • java.net.SocketPermission - to export the activatable object to accept connections an anonymous port

Register the group descriptor

Next, the Setup program must register the activation group descriptor with the activation system to obtain the group's ID, an instance of the class java.rmi.activation.ActivationGroupID. The class java.rmi.activation.ActivationGroup has a static method getSystem for obtaining the stub for the activation system. The Setup program calls the activation system's remote method registerGroup, passing the group descriptor created above, to register the activation group:
ActivationGroupID groupID =
    ActivationGroup.getSystem().registerGroup(groupDesc);

Construct an activation descriptor

Once the activation group ID is obtained, the Setup program can register the activation descriptor. The activation descriptor has four basic pieces of information:

  • the activation group ID for the group that the object will be contained in
  • the implementation's class name
  • the location (URL) specifying where the implementation's classes can be loaded from
  • a marshalled object containing initialization information for the object

In this example, the activation group ID is the one obtained above; the implementation's class name is the class name, implClass, supplied as the command-line argument to the Setup program; the location (URL) is specified by the system property examples.activation.impl.codebase; and, the initialization data (which is optional) is a filename specified by the system property examples.activation.file.

The activation descriptor is constructed as follows:

MarshalledObject data = null;
if (filename != null && !filename.equals("")) {
    data = new MarshalledObject(filename);
}

ActivationDesc desc =
    new ActivationDesc(groupID, implClass, implCodebase, data);

Register the activation descriptor

Next, the Setup program must register the activation descriptor with the activation system. The class Activatable has a static convenience method, register, that registers an activation descriptor with the activation system and returns a stub for the activatable object specified by the descriptor.

Remote stub = Activatable.register(desc);

Note: The register method attempts to load a stub class for the implementation class in order to create a stub instance. If your activatable object needs to support pre-5.0 clients, you will need use rmic to pregenerate a stub class for the implementation class. If your activatable object does not need to support pre-5.0 clients, then there is no need to pregenerate a stub class for the implementation class. If the register method is unable to load a pregenerated stub class, it will use an instance of a dynamically-generated proxy class that implements all the interfaces of the implementation class. In the latter case the register method needs load the implementation class in order to determine the remote interfaces that the implementation class implements. So, the register method has a slight behavioral difference, depending on whether a pregenerated or dynamically-generated stub class is used.

Bind the remote object's stub in a rmiregistry

Finally, the remote object's stub is bound to a name in the registry running on the default port of 1099. The name is specified by the system property examples.activation.name.

String name = System.getProperty("examples.activation.name");
LocateRegistry.getRegistry().rebind(name, stub);

Compile the source file

The source file for this example can be compiled as follows:

javac -d setupDir Setup.java
where setupDir is the root destination directory to put the class files in.

Start rmid, rmiregistry, and the Setup program

To run this the Setup program, you will need to do the following:

  • Start rmid
  • Start rmiregistry
  • Run the Setup program

Start rmid

To start rmid, run the rmid command on the server's host. This command should produce no output if it is run with a security policy file as specified below. For more information, see the tools documentation for rmid [Solaris, Windows].

For example, in the Solaris Operating System:

rmid -J-Djava.security.policy=rmid.policy \
     -J-Dexamples.activation.policy=group.policy &

Or, on Windows platforms:

start rmid -J-Djava.security.policy=rmid.policy \
           -J-Dexamples.activation.policy=group.policy

where:

  • rmid.policy is the security policy file for rmid
  • group.policy is the group policy file, used in rmid's policy file

The security policy file for rmid grants permissions for rmid to execute specific commands and to use specific command-line options in starting activation group VMs. For example, a user might grant specific permissions to start an activation group VM with one or more system properties or other java command-line options. This example allows rmid to start activation group VMs that define the system properties java.security.policy, java.class.path, examples.activation.impl.codebase, and examples.activation.file. The following example security policy file grants permission to start an activation group VM with these specific properties defined:

grant {
    // allow activation groups to use certain system properties
    permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=${examples.activation.policy}";
    permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.class.path=no_classpath";
    permission com.sun.rmi.rmid.ExecOptionPermission "-Dexamples.activation.impl.codebase=*";
    permission com.sun.rmi.rmid.ExecOptionPermission "-Dexamples.activation.file=*";
};

The first ExecOptionPermission permission grant restricts the java.security.policy system property to be the file specified by the system property examples.activation.policy, defined when rmid is run. The next permission grant allows a group to define the system property java.class.path as no_classpath, a dummy class path that prevents the group from having a valid class path. The next permission grant allows the group to define the system property examples.activation.impl.codebase to be any value. The final permission grant allows the examples.activation.file system property to be any value.

Start rmiregistry

To start the registry, run the rmiregistry command on the server's host. This command produces no output (when successful) and is typically run in the background. For more information, see the tools documentation for rmiregistry [Solaris, Windows].

For example, in the Solaris Operating System:

rmiregistry &

Or, on Windows platforms:

start rmiregistry

By default, the registry runs on TCP port 1099. To start a registry on a different port, specify the port number from the command line. For example, to start the registry on port 2001 on a Windows platform:

start rmiregistry 2001

Note: Make sure that rmiregistry does not have any implementation classes in its class path to prevent it from loading any classes from its local class path.

If the registry will be running on a port other than 1099, you'll need to specify the port number in the calls to LocateRegistry.getRegistry in the Setup program, as well as any clients that access this registry. For example, if the registry is running on port 2001 in this example, the call to getRegistry would be:

Registry registry = LocateRegistry.getRegistry(2001);

Also note that if you use a registry port other than 1099, you will also need to modify the Setup and client program's policy files to grant permission to connect to the registry's port.

Run the Setup program

To start the Setup program, run the Setup class using the java command as follows:

java -cp setupDir:implDir \
     -Djava.security.policy=setup.policy        \
     -Djava.rmi.server.codebase=codebase         \
     -Dexamples.activation.setup.codebase=setupCodebase       \
     -Dexamples.activation.impl.codebase=implCodebase \
     -Dexamples.activation.name=name             \
     [-Dexamples.activation.file=file]       \
     [-Dexamples.activation.policy=group.policy] \
     examples.activation.Setup implClass

where:

  • setupDir is the root directory for the Setup program's class
  • implDir is the root directory for the implementation's classes
  • setup.policy is the security policy file for the Setup program
  • codebase is the location (URL) of the remote interface class(es)
  • setupCodebase is the location (URL) the Setup program class (used in granting permissions to the Setup program in the setup.policy file)
  • implCodebase is the location (URL) of the implementation class(es), used in the activation descriptor and also used in the group policy file as the codebase to grant permissions to
  • name is the name for the object's stub to be bound in the registry
  • file (optional) is the name of a file containing the object's persistent state which is registered as the data in the object's activation descriptor (no default)
  • group.policy (optional) is the security policy file for the activation group (defaults to group.policy), and
  • implClass is the fully-qualified name of the implementation class.

Note: If you use file URLs for any of the codebases listed above, make sure that each file URL has a trailing slash, or the codebase will be invalid.

The output from the Setup program should look like this:

Activation group descriptor registered.
Activation descriptor registered.
Stub bound in registry.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.ShortType (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.ShortType

No usage of com.sun.jdi.ShortType
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.ShortValue (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.ShortValue

  • Packages that use ShortValue
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of ShortValue in com.sun.jdi

      Methods in com.sun.jdi that return ShortValue
      Modifier and Type Method and Description
      ShortValue VirtualMachine.mirrorOf(short value)
      Creates a ShortValue for the given value.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Signal Chaining

The Java 2 SDK, Standard Edition, (JDK) v1.4 contains a new signal-chaining facility. Signal-chaining enables the Java Platform to better interoperate with native code that installs its own signal handlers. The facility works on both Solaris and Linux platforms.

The signal-chaining facility was introduced to remedy a problem with signal handling in previous versions of the Java HotSpot VM. Prior to version 1.4, the Java HotSpot VM would not allow application-installed signal handlers for certain signals including, for example, SIGBUS, SIGSEGV, SIGILL, etc, since those signal handlers could conflict with the signal handlers used internally by the Java HotSpot VM.

The signal-chaining facility offers the following:

  • Support for pre-installed signal handlers when the HotSpot VM is created.
  • Support for signal handler installation after the HotSpot VM is created, inside JNI code or from another native thread.

Pre-installed signal handlers (A) are supported by means of saving existing signal handlers, for signals that are used by the VM, when the VM is first created. Later, when any of these signals are raised and found not to be targeted at the Java HotSpot VM, the pre-installed handlers are invoked. In other words, pre-installed handlers are "chained" behind the VM handlers for these signals.

The signal-chaining facility also allows an application to link and load a shared library libjsig.so before libc/libthread/libpthread. This library ensures that calls such as signal(), sigset(), and sigaction() are intercepted so that they do not actually replace the Java HotSpot VM's signal handlers if the handlers conflict with those already installed by the Java HotSpot VM (B). Instead, these calls save the new signal handlers, or "chain" them behind the VM-installed handlers. Later, when any of these signals are raised and found not to be targeted at the Java HotSpot VM, the pre-installed handlers are invoked. libjsig.so is not needed if (B) is not required.

To use libjsig.so, either link it with the application that creates/embeds a HotSpot VM, for example:

cc -L <libjvm.so dir> -ljsig -ljvm java_application.c
or use LD_PRELOAD environment variable, for example:
export LD_PRELOAD=<libjvm.so dir>/libjsig.so; java_application (ksh)

setenv LD_PRELOAD <libjvm.so dir>/libjsig.so; java_application (csh)
The interposed signal()/sigset()/sigaction() return the saved signal handlers, not the signal handlers installed by the Java HotSpot VM which are seen by the OS.

The signal-chaining facility was introduced to address Request for Enhancement number 4381843.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JDI Type Signatures
Type Signature | Java Type
Z | boolean
B | byte
C | char
S | short
I | int
J | long
F | float
D | double
L fully-qualified-class ; | fully-qualified-class
[ type | type[]
( arg-types ) ret-type | method type (including constructors)

For example, the Java method:

    long f (int n, String s, int[] arr);
has the following type signature:

    (ILjava/lang/String;[I)J


Uses of Class com.sun.mirror.util.SimpleDeclarationVisitor (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.mirror.util.SimpleDeclarationVisitor

No usage of com.sun.mirror.util.SimpleDeclarationVisitor
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


SimplePlayerApplet.java Source Code

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
/*
 * @(#)SimplePlayerApplet.java  1.2 01/03/13

 *
 * Copyright (c) 1996, 2001, Oracle and/or its affiliates. All rights reserved.
 *
 * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
 * modify and redistribute this software in source and binary code form,
 * provided that i) this copyright notice and license appear on all copies of
 * the software; and ii) Licensee does not utilize the software in a manner
 * which is disparaging to Sun.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
 * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
 * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
 * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
 * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
 * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
 * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
 * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 *
 * This software is not designed or intended for use in on-line control of
 * aircraft, air traffic, aircraft navigation or aircraft communications; or in
 * the design, construction, operation or maintenance of any nuclear
 * facility. Licensee represents and warrants that it will not use or
 * redistribute the Software for such purposes.
 */

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.lang.String;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.IOException;
import java.util.Properties;
import javax.media.*;
//import com.sun.media.util.JMFSecurity;

/**
  * This is a Java Applet that demonstrates how to create a simple
  * media player with a media event listener. It will play the
  * media clip right away and continuously loop.
  *
  *<!-- Sample HTML
  * <applet code=SimplePlayerApplet width=320 height=300>
  * <param name=file value="sun.avi">
  * </applet>
  * -->
  */
public class SimplePlayerApplet extends Applet implements ControllerListener {

    // media Player
    Player player = null;
    // component in which video is playing
    Component visualComponent = null;
    // controls gain, position, start, stop
    Component controlComponent = null;
    // displays progress during download
    Component progressBar = null;
    boolean firstTime = true;
    long CachingSize = 0L;
    Panel panel = null;
    int controlPanelHeight = 0;
    int videoWidth = 0;
    int videoHeight = 0;

    /**
     * Read the applet file parameter and create the media
     * player.
     */
    public void init() {
        //$ System.out.println("Applet.init() is called");
        setLayout(null);
        setBackground(Color.white);
        panel = new Panel();
        panel.setLayout( null );
        add(panel);
        panel.setBounds(0, 0, 320, 240);

        // input file name from html param
        String mediaFile = null;
        // URL for our media file
        MediaLocator mrl = null;
        URL url = null;

        // Get the media filename info.
        // The applet tag should contain the path to the
        // source media file, relative to the html page.

        if ((mediaFile = getParameter("FILE")) == null)
            Fatal("Invalid media file parameter");

        try {
            url = new URL(getDocumentBase(), mediaFile);
            mediaFile = url.toExternalForm();
        } catch (MalformedURLException mue) {
        }

        try {
            // Create a media locator from the file name
            if ((mrl = new MediaLocator(mediaFile)) == null)
                Fatal("Can't build URL for " + mediaFile);

            /*
            try {
                JMFSecurity.enablePrivilege.invoke(JMFSecurity.privilegeManager,
                                                   JMFSecurity.writePropArgs);
                JMFSecurity.enablePrivilege.invoke(JMFSecurity.privilegeManager,
                                                   JMFSecurity.readPropArgs);
                JMFSecurity.enablePrivilege.invoke(JMFSecurity.privilegeManager,
                                                   JMFSecurity.connectArgs);
            } catch (Exception e) {}
            */

            // Create an instance of a player for this media
            try {
                player = Manager.createPlayer(mrl);
            } catch (NoPlayerException e) {
                System.out.println(e);
                Fatal("Could not create player for " + mrl);
            }

            // Add ourselves as a listener for a player's events
            player.addControllerListener(this);

        } catch (MalformedURLException e) {
            Fatal("Invalid media file URL!");
        } catch (IOException e) {
            Fatal("IO exception creating player for " + mrl);
        }

        // This applet assumes that its start() calls
        // player.start(). This causes the player to become
        // realized. Once realized, the applet will get
        // the visual and control panel components and add
        // them to the Applet. These components are not added
        // during init() because they are long operations that
        // would make us appear unresposive to the user.
    }

    /**
     * Start media file playback. This function is called the
     * first time that the Applet runs and every
     * time the user re-enters the page.
     */

    public void start() {
        //$ System.out.println("Applet.start() is called");
        // Call start() to prefetch and start the player.
        if (player != null)
            player.start();
    }

    /**
     * Stop media file playback and release resource before
     * leaving the page.
     */
    public void stop() {
        //$ System.out.println("Applet.stop() is called");
        if (player != null) {
            player.stop();
            player.deallocate();
        }
    }

    public void destroy() {
        //$ System.out.println("Applet.destroy() is called");
        player.close();
    }

    /**
     * This controllerUpdate function must be defined in order to
     * implement a ControllerListener interface. This
     * function will be called whenever there is a media event
     */
    public synchronized void controllerUpdate(ControllerEvent event) {
        // If we're getting messages from a dead player,
        // just leave
        if (player == null)
            return;

        // When the player is Realized, get the visual
        // and control components and add them to the Applet
        if (event instanceof RealizeCompleteEvent) {
            if (progressBar != null) {
                panel.remove(progressBar);
                progressBar = null;
            }

            int width = 320;
            int height = 0;
            if (controlComponent == null)
                if (( controlComponent =
                      player.getControlPanelComponent()) != null) {

                    controlPanelHeight = controlComponent.getPreferredSize().height;
                    panel.add(controlComponent);
                    height += controlPanelHeight;
                }
            if (visualComponent == null)
                if (( visualComponent =
                      player.getVisualComponent())!= null) {
                    panel.add(visualComponent);
                    Dimension videoSize = visualComponent.getPreferredSize();
                    videoWidth = videoSize.width;
                    videoHeight = videoSize.height;
                    width = videoWidth;
                    height += videoHeight;
                    visualComponent.setBounds(0, 0, videoWidth, videoHeight);
                }

            panel.setBounds(0, 0, width, height);
            if (controlComponent != null) {
                controlComponent.setBounds(0, videoHeight,
                                           width, controlPanelHeight);
                controlComponent.invalidate();
            }

        } else if (event instanceof CachingControlEvent) {
            if (player.getState() > Controller.Realizing)
                return;
            // Put a progress bar up when downloading starts,
            // take it down when downloading ends.
            CachingControlEvent e = (CachingControlEvent) event;
            CachingControl cc = e.getCachingControl();

            // Add the bar if not already there ...
            if (progressBar == null) {
                if ((progressBar = cc.getControlComponent()) != null) {
                    panel.add(progressBar);
                    panel.setSize(progressBar.getPreferredSize());
                    validate();
                }
            }
        } else if (event instanceof EndOfMediaEvent) {
            // We've reached the end of the media; rewind and
            // start over
            player.setMediaTime(new Time(0));
            player.start();
        } else if (event instanceof ControllerErrorEvent) {
            // Tell TypicalPlayerApplet.start() to call it a day
            player = null;
            Fatal(((ControllerErrorEvent)event).getMessage());
        } else if (event instanceof ControllerClosedEvent) {
            panel.removeAll();
        }
    }

    void Fatal (String s) {
        // Applications will make various choices about what
        // to do here. We print a message
        System.err.println("FATAL ERROR: " + s);
        throw new Error(s); // Invoke the uncaught exception
                            // handler System.exit() is another
                            // choice.

    }
}
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.source.util.SimpleTreeVisitor (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.source.util.SimpleTreeVisitor

No usage of com.sun.source.util.SimpleTreeVisitor
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.mirror.util.SimpleTypeVisitor (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.mirror.util.SimpleTypeVisitor

No usage of com.sun.mirror.util.SimpleTypeVisitor
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Single Sign-on Using Kerberos in Java

Mayank Upadhyay
Ram Marti

ABSTRACT

A significant enhancement to the Java security architecture is the capability to achieve single sign-on using Kerberos Version 5 in the next release of Java Standard Edition (J2SE). A single sign-on solution lets users authenticate themselves just once to access information on any of several systems. This is done using JAAS for authentication and authorization and Java GSS-API to establish a secure context for communication with a peer application. Our focus is on Kerberos V5 as the underlying security mechanism for single sign-on, although other security mechanisms may be added in the future.

INTRODUCTION

With the increasing use of distributed systems users need to access resources that are often remote. Traditionally users have had to sign-on to multiple systems, each of which may involve different usernames and authentication techniques. In contrast, with single sign-on, the user needs to authenticate only once and the authenticated identity is securely carried across the network to access resources on behalf of the user.

In this paper we discuss how to use single sign-on based on the Kerberos V5 protocol. We use the Java Authentication and Authorization Service (JAAS) to authenticate a principal to Kerberos and obtain credentials that prove its identity. We show how Sun's implementation of a Kerberos login module can be made to read credentials from an existing cache on platforms that contain native Kerberos support. We then use the Java Generic Security Service API (Java GSS-API) to authenticate to a remote peer using the previously obtained Kerberos credentials. We also show how to delegate Kerberos credentials for single sign-on in a multi-tier environment.

KERBEROS V5

Kerberos V5 is a trusted third party network authentication protocol designed to provide strong authentication using secret key cryptography. When using Kerberos V5, the user's password is never sent across the network, not even in encrypted form, except during Kerberos V5 administration. Kerberos was developed in the mid-1980's as part of MIT's Project Athena. A full description of the Kerberos V5 protocol is beyond the scope of this paper. For more information on the Kerberos V5 protocol please refer to [1] and [2]

Kerberos V5 is a mature protocol and has been widely deployed. It is available on Solaris as SEAM and on Windows 2000 and several other platforms. A free reference implementation in C is available from MIT. For these reasons we have selected Kerberos V5 as the underlying technology for single sign-on in J2SE.

JAVA AUTHENTICATION AND AUTHORIZATION SERVICE (JAAS)

Until recently the Java 2 security architecture solely determined privileges by the origin of the code and the public key certificates matching the code signers. However, in a multi-user environment it is desirable to further specify privileges based on the authenticated identity of the user running the code.

JAAS supplies such a capability. JAAS is a pluggable framework and programming interface specifically targeted for authentication and access control based on the authenticated identities.

Authentication and Authorization

The JAAS framework can be divided into two components: an authentication component and an authorization component.

The JAAS authentication component provides the ability to reliably and securely determine who is currently executing Java code, regardless of whether the code is running as an application, an applet, a bean, or a servlet.

The JAAS authorization component supplements the existing Java security framework by providing the means to restrict the executing Java code from performing sensitive tasks, depending on its codesource and depending on who is executing the code.

Pluggable and Stackable Framework

JAAS authentication framework is based on Pluggable Authentication Module (PAM)[3, 4]. JAAS authentication is performed in a pluggable fashion allowing system administrators to add appropriate authentication modules. This permits Java applications to remain independent of underlying authentication technologies, and new or updated authentication technologies can be seamlessly configured without requiring modifications to the application itself.

JAAS authentication framework also supports the stacking of authentication modules. Multiple modules can be specified and they are invoked by the JAAS framework in the order they were specified. The success of the overall authentication depends on the results of the individual authentication modules.

Subject

JAAS uses the term Subject to refer to any entity that is the source of a request to access resources. A Subject may be a user or a service. Since an entity may have many names or principals JAAS uses Subject as an extra layer of abstraction that handles multiple names per entity.Thus a Subject is comprised of a set of principals. There are no restrictions on principal names.

A Subject is only populated with authenticated principals. Authentication typically involves the user providing proof of identity, such as a password.

A Subject may also have security related attributes, which are referred to as credentials. The credentials can be public or private. Sensitive credentials such as private cryptographic keys are stored in the private credentials set of the Subject.

The Subject class has methods to retrieve the principals, public credentials and private credentials associated with it.

Please note that different permissions may be required for operations on these classes. For example AuthPermission("modifyPrincipals") may be required to modify the principal set of the Subject. Similar permissions are required to modify the public credentials, private credentials and to get the current Subject.

doAs and doAsPrivileged

Java 2 enforces runtime access controls via java.lang.SecurityManager. The SecurityManager is consulted anytime sensitive operations are attempted. The SecurityManager delegates this responsibility to java.security.AccessController. The AccessController obtains a current image of the AccessControlContext and verifies that it has sufficient permission to do the operation requested.

JAAS provides two methods doAs and doAsPrivileged that can be used to associate an authenticated Subject with the AccessControlContext dynamically.

The doAs method associates the Subject with the current thread's access control context and subsequent access control checks are made on the basis of the code being executed and the Subject executing it.

public static Object doAs(final Subject subject,
                          final  PrivilegedAction action)

public static Object doAs(final Subject subject,
                          final  PrivilegedExceptionAction action)
    throws  PrivilegedActionException;

Both forms of the doAs method first associate the specified subject with the current Thread's AccessControlContext, and then execute the action. This achieves the effect of having the action run as the Subject. The first method can throw runtime exceptions but normal execution has it returning an Object from the run() method of its action argument. The second method behaves similarly except that it can throw a checked PrivilegedActionException from its run() method. An AuthPermission("doAs") is required to call the doAs methods.

The following methods also execute code as a particular Subject:

public static Object doAsPrivileged(final Subject subject,
                                    final  PrivilegedAction action,
                                    final  AccessControlContext  acc);

public static Object doAsPrivileged(final Subject subject,
                                    final PrivilegedExceptionAction action,
                                    final  AccessControlContext acc)
   throws PrivilegedActionException;

The doAsPrivileged method behaves exactly as doAs, except that it allows the caller to specify an access control context. Thus it effectively throws away the current AccessControlContext and authorization decisions will be based on the AccessControlContext passed in.

Since the AccessControlContext is set on a per thread basis, different threads within the JVM can assume different identities. The Subject associated with a specific AccessControlContext can be retrieved by using the following method:

public static Subject getSubject(final AccessControlContext acc);

LoginContext

The LoginContext class provides the basic methods used to authenticate Subjects. It also allows an application to be independent of the underlying authentication technologies. The LoginContext consults a configuration that determines the authentication services or LoginModules configured for a particular application. If the application does not have a specific entry, it defaults to the entry identified as "other".

To support the stackable nature of LoginModules, LoginContext performs authentication in two phases. In the first phase or login phase, it invokes each configured LoginModule to attempt the authentication. If all the necessary LoginModules succeed, then LoginContext enters the second phase where it invokes each LoginModule again to formally commit the authentication process. During this phase the Subject is populated with the authenticated principals and their credentials. If either of the phase fails, then the LoginContext invokes each configured module to abort the entire authentication attempt. Each LoginModule then cleans up any relevant state associated with the authentication attempt.

LoginContext has four constructors that can be used to instantiate it. All of them require the configuration entry name to be passed. In addition the Subject and/or a CallbackHandler can also be passed to the constructors.

Callbacks

The login modules invoked by JAAS must be able to garner information from the caller for authentication. For example the Kerberos login module may require users to enter their Kerberos password for authentication.

The LoginContext allows the application to specify a callbackhandler that the underlying login modules use to interact with users. There are two callback handlers available in Merlin (J2SE 1.4) - one based on the command line and another based on a GUI.

LoginModules

Sun provides an implementation of the UnixLoginModule, NTLoginModule, JNDILoginModule, KeyStoreLoginModule and Krb5LoginModule in Merlin. A smart card based JAAS login module is available from GemPlus [5].

The Kerberos Login Module

The class com.sun.security.auth.module.Krb5LoginModule is Sun's implementation of a login module for the Kerberos version 5 protocol. Upon successful authentication the Ticket Granting Ticket (TGT) is stored in the Subject's private credentials set and the Kerberos principal is stored in the Subject's principal set.

Based on certain configurable options, Krb5LoginModule can also use an existing credentials cache, such as a native cache in the operating system, to acquire the TGT and/or use a keytab file containing the secret key to implicitly authenticate a principal. Both the Solaris and Windows 2000 platforms contain a credentials cache that Krb5LoginModule can use for fetching the TGT. Solaris also contains a system wide keytab file that Krb5LoginModule can use for fetching the secret key. On all platforms, Krb5LoginModule supports options to set the file path to a ticket cache or keytab file of choice. This is useful when third-party Kerberos support is installed and Java integration is desired. Please consult the documentation for Krb5LoginModule to learn about these options. In the absence of a native cache or keytab, the user will be prompted for the password and the TGT obtained from the KDC.

Figure 1 provides a sample JAAS login configuration entry for a client application. In this example, Krb5LoginModule will use the native ticket cache to get the TGT available in it. The authenticated identity will be the identity of the Kerberos principal that the TGT belongs to.

SampleClient {
    com.sun.security.auth.module.Krb5LoginModule required useTicketCache=true
};
             Figure 1. Sample client  configuration entry

Figure 2 provides a sample login configuration entry for a server application. With this configuration, the secret key from the keytab is used to authenticate the principal "nfs/bar.foo.com" and both the TGT obtained from the Kerberos KDC and the secret key are stored in the Subject's private credentials set. The stored key may be used later to validate a service ticket sent by a client (See the section on Java GSS-API.)

SampleServer {
     com.sun.security.auth.module.Krb5LoginModule
         required useKeyTab=true storeKey=true principal="nfs/bar.foo.com"
};

             Figure 2. Sample server configuration entry

In the client code example shown in Figure 3, the configuration entry "SampleClient" will be used by the LoginContext. The TextCallbackHandler class will be used to prompt the user for the Kerberos password. Once the user has logged in, the Subject will be populated with the Kerberos Principal name and the TGT. Thereafter the user can execute code using Subject.doAs passing in the Subject obtained from the LoginContext.

LoginContext lc = null;

try {
        lc = new LoginContext("SampleClient", new TextCallbackHandler());
        // attempt authentication
        lc.login();
} catch (LoginException le) {
    ...
}

 // Now try to execute ClientAction as the authenticated Subject

 Subject mySubject = lc.getSubject();
 PrivilegedAction action = new ClientAction();
 Subject.doAs(mySubject, action);

            Figure 3. Sample client code

ClientAction could be an action that is allowed only for authenticated Kerberos client Principals with a specific value.

Figure 4 shows server side sample code. It is similar to the client code shown in Figure 4 except for the application entry name and the PrivilegedAction.

LoginContext lc = null;

try {
        lc = new LoginContext("SampleServer", new TextCallbackHandler());
        // attempt authentication
        lc.login();
} catch (LoginException le) {
   ...
}

// Now try to execute ServerAction as the authenticated Subject

Subject mySubject = lc.getSubject();
PrivilegedAction action = new ServerAction();
Subject.doAs(mySubject, action);

            Figure 4. Sample server code

Kerberos Classes

To enable other vendors to provide their own Kerberos login module implementation that can be used with Java GSS-API, three standard Kerberos classes have been introduced in the javax.security.auth.kerberos package. These are KerberosPrincipal for Kerberos principals, KerberosKey for the long-term Kerberos secret key and KerberosTicket for Kerberos tickets. All implementations of the Kerberos login module must use these classes to store principals, keys and tickets in the Subject.

Authorization

Upon successful authentication of a Subject, access controls can be enforced based upon the principals associated with the authenticated Subject. The JAAS principal based access controls augment the CodeSource access controls of Java 2. Permissions granted to a Subject are configured in Policy, which is an abstract class for representing the system wide access control policy. Sun provides a file based implementation of the Policy class. The Policy class is provider based so that others can provide their own policy implementation.

JAVA GENERIC SECURITY SERVICE APPLICATION PROGRAM INTERFACE (Java GSS-API)

Generic Security Service API (GSS-API)

Enterprise applications often have varying security requirements and deploy a range of underlying technologies to achieve this. In such a scenario how do we develop a client-server application so that it can easily migrate from one technology to another? The GSS-API was designed in the Common Authentication Technology working group of the IETF to solve this problem by providing a uniform application programming interface for peer to peer authentication and secure communication that insulates the caller from the details of the underlying technology.

The API, described in a language independent form in RFC 2743 [6], accommodates the following security services: authentication, message confidentiality and integrity, sequencing of protected messages, replay detection, and credential delegation. The underlying security technology or "security mechanism" being used, has a choice of supporting one or more of these features beyond the essential one way authentication 1. There are mainly two standard security mechanisms that the IETF has defined: Kerberos V5 [6] and the Simple Public Key Mechanism (SPKM) [8].

The API is designed such that an implementation may support multiple mechanisms simultaneously, giving the application the ability to choose one at runtime. Mechanisms are identified by means of unique object identifier's (OID's) that are registered with the IANA. For instance, the Kerberos V5 mechanism is identified by the OID {iso(1) member-body(2) United States(840) mit(113554) infosys(1) gssapi(2) krb5(2)}.

Another important feature of the API is that it is token based. i.e., Calls to the API generate opaque octets that the application must transport to its peer. This enables the API to be transport independent.

Multi-mechanism GSS-API

Figure 5. A multi-mechanism GSS-API implementation

Java GSS-API

The Java API for the Generic Security Service was also defined at the IETF and is documented in RFC 2853 [10]. Sun is pursuing the standardization of this API under the Java Community Process (JCP) [11] and plans to deliver a reference implementation with Merlin. Because the JCP is merely endorsing this externally defined API, the IETF assigned package namespace "org.ietf.jgss" will be retained in Merlin.

Sun's implementation of Java GSS-API, will initially ship with support for the Kerberos V5 mechanism only. Kerberos V5 mechanism support is mandatory for all Java GSS-API implementations in Java SE, although they are free to support additional mechanisms. In a future release, a Service Provider Interface (SPI) will be added so that new mechanisms can be configured statically or even at runtime. Even now the reference implementation in Merlin will be modular and support a private provider SPI that will be converted to public when standardized.

The Java GSS-API framework itself is quite thin, and all security related functionality is delegated to components obtained from the underlying mechanisms. The GSSManager class is aware of all mechanism providers installed and is responsible for invoking them to obtain these components.

The implementation of the default GSSManager that will ship with Java SE is obtained as follows:

GSSManager manager = GSSManager.getInstance();

The GSSManager can be used to configure new providers and to list all mechanisms already present. The GSSManager also serves as a factory class for three important interfaces: GSSName, GSSCredential, and GSSContext. These interfaces are described below with the methods to instantiate their implementations. For a complete API specification, readers are referred to [9] and [11].

Most calls to Java GSS-API throw a GSSException that encapsulate problems that occur both within the GSS-API framework, and within the mechanism providers.

The GSSName Interface

This interface represents an entity for the purposes of Java GSS-API. An implementation of this interface is instantiated as follows:

GSSName GSSManager.createName(String name, Oid nameType)
    throws GSSException

For Example:

GSSName clientName = manager.createName("duke", GSSName.NT_USER_NAME);

This call returns a GSSName that represents the user principal "duke" at a mechanism independent level. Internally, it is assumed that each supported mechanism will map the generic representation of the user to a more mechanism specific form. For instance a Kerberos V5 mechanism provider might map this name to duke@FOO.COM where FOO.COM is the local Kerberos realm. Similarly, a public key based mechanism provider might map this name to an X.509 Distinguished Name.

If we were referring to a principal that was not a user, but some sort of service, we would indicate that to the Java GSS-API call so that the mechanism knows to interpret it differently.

Example:

GSSName serverName = manager.createName("nfs@bar.foo.com",
                                         GSSName.NT_HOSTBASED_SERVICE);

The Kerberos V5 mechanism would map this name to the Kerberos specific form nfs/bar.foo.com@FOO.COM where FOO.COM is the realm of the principal. This principal represents the service nfs running on the host machine bar.foo.com.

Sun's implementation of the GSSName interface is a container class. The container class lazily asks the individual providers to perform their mapping when their mechanism is used and then stores each mapped element in a set of principals. In this respect an implementation of GSSName is similar to the principal set stored in a Subject. It may even contain the same elements that are in a Subject's principal set, but its use is restricted to the context of Java GSS-API.

The name element stored by the Sun Kerberos V5 provider is an instance of a subclass of javax.security.auth.kerberos.KerberosPrincipal.

The GSSCredential Interface

This interface encapsulates the credentials owned by one entity. Like the GSSName, this interface too is a multi-mechanism container.

Its implementation is instantiated as follows:

GSSCredential createCredential(GSSName name,
                               int lifetime,
                               Oid[] desiredMechs,
                               int usage)

    throws GSSException

Here is an example of this call on the client side:

GSSCredential clientCreds =
               manager.createCredential(clientName,
                                        8*3600,
                                        desiredMechs,
                                        GSSCredential.INITIATE_ONLY);

The GSSManager invokes the providers of the mechanisms listed in the desiredMechs for credentials that belong to the GSSName clientName. Additionally, it imposes the restriction that the credential must be the kind that can initiate outbound requests (i.e., a client credential), and requests a lifetime of 8 hours for it. The returned object contains elements from a subset of desiredMechs that had some credential available to satisfy this criteria. The element stored by the Kerberos V5 mechanism is an instance of a subclass of javax.security.auth.kerberos.KerberosTicket containing a TGT that belongs to the user.

Credential acquisition on the server side occurs as follows:

GSSCredential serverCreds =
          manager.createCredential(serverName,
                                   GSSCredential.INDEFINITE_LIFETIME,
                                   desiredMechs,
                                   GSSCredential.ACCEPT_ONLY);

The behavior is similar to the client case, except that the kind of credential requested is one that can accept incoming requests (i.e., a server credential). Moreover, servers are typically long lived and like to request a longer lifetime for the credentials such as the INDEFINITE_LIFETIME shown here. The Kerberos V5 mechanism element stored is an instance of a subclass of javax.security.auth.kerberos.KerberosKey containing the secret key of the server.

This step can be an expensive one, and applications generally acquire a reference at initialization time to all the credentials they expect to use during their lifetime.

The GSSContext Interface

The GSSContext is an interface whose implementation provides security services to the two peers.

On the client side a GSSContext implementation is obtained with the following API call:

GSSContext GSSManager.createContext(GSSName peer,
                                    Oid mech,
                                    GSSCredential clientCreds,
                                    int lifetime)
    throws GSSException

This returns an initialized security context that is aware of the peer that it must communicate with and the mechanism that it must use to do so. The client's credentials are necessary to authenticate to the peer.

On the server side the GSSContext is obtained as follows:

GSSContext GSSManager.createContext(GSSCredential serverCreds)
    throws GSSException

This returns an initialized security context on the acceptor's side. At this point it does not know the name of the peer (client) that will send a context establishment request or even the underlying mechanism that will be used. However, if the incoming request is not for service principal represented by the credentials serverCreds, or the underlying mechanism requested by the client side does not have a credential element in serverCreds, then the request will fail.

Before the GSSContext can be used for its security services it has to be established with an exchange of tokens between the two peers. Each call to the context establishment methods will generate an opaque token that the application must somehow send to its peer using a communication channel of its choice.

The client uses the following API call to establish the context:

byte[] GSSContext.initSecContext(byte[] inToken,
                                 int offset,
                                 int len)

   throws GSSException

The server uses the following call:

byte[] acceptSecContext(byte[] inToken,
                        int offset,
                        int len)

   throws GSSException

These two methods are complementary and the input accepted by one is the output generated by the other. The first token is generated when the client calls initSecContext for the first time. The arguments to this method are ignored during that call. The last token generated depends on the particulars of the security mechanism being used and the properties of the context being established.

The number of round trips of GSS-API tokens required to authenticate the peers varies from mechanism to mechanism and also varies with characteristics such as whether mutual authentication or one-way authentication is desired. Thus each side of the application must continue to call the context establishment methods in a loop until the process is complete.

In the case of the Kerberos V5 mechanism, there is no more than one round trip of tokens during context establishment. The client first sends a token generated by its initSecContext() containing the Kerberos AP-REQ message [2]. In order to generate the AP-REQ message, the Kerberos provider obtains a service ticket for the target server using the client's TGT. The service ticket is encrypted with the server's long-term secret key and is encapsulated as part of the AP-REQ message. After the server receives this token, it is passed to the acceptSecContext() method which decrypts the service ticket and authenticates the client. If mutual authentication was not requested, both the client and server side contexts would be established, and the server side acceptSecContext() would generate no output.

However, if mutual authentication were enabled, then the server's acceptSecContext() would generate an output token containing the Kerberos AP-REP [2] message. This token would need to be sent back to the client for processing by its initSecContext(), before the client side context is established.

Note that when a GSSContext is initialized on the client side, it is clear what underlying mechanism needs to be used. The Java GSS-API framework can obtain a context implementation from the appropriate mechanism provider. Thereafter, all calls made to the GSSContext object are delegated to the mechanism's context implementation. On the server side, the mechanism to use is not decided until the first token from the client side arrives.

Here is a class showing how the client side of an application would be coded. This is the ClientAction class that was executed using the doAs method in Figure 3:

class ClientAction implements PrivilegedAction {

    public Object run() {
        ...
        ...
        try {
            GSSManager manager = GSSManager.getInstance();
            GSSName clientName =
                manager.createName("duke", GSSName.NT_USER_NAME);
            GSSCredential clientCreds =
                manager.createCredential(clientName,
                                          8*3600,
                                          desiredMechs,
                                          GSSCredential.INITIATE_ONLY);
            GSSName peerName =
                manager.createName("nfs@bar.foo.com",
                                    GSSName.NT_HOSTBASED_SERVICE);
            GSSContext secContext =
                manager.createContext(peerName,
                                      krb5Oid,
                                      clientCreds,
                                      GSSContext.DEFAULT_LIFETIME);
            secContext.requestMutualAuth(true);

            // The first input token is ignored
            byte[] inToken = new byte[0];

            byte[] outToken = null;

            boolean established = false;

           // Loop while the context is still not established
           while (!established) {
               outToken =
                   secContext.initSecContext(inToken, 0, inToken.length);

               // Send a token to the peer if one was generated
               if (outToken != null)
                  sendToken(outToken);

               if (!secContext.isEstablished()) {
                  inToken = readToken();
               else
                  established = true;
            }
        } catch (GSSException e) {
             ....
        }
        ...
        ...
    }
}

        Figure 6. Sample client using Java GSS-API

The corresponding section of code on the server side running the ServerAction class from Figure 5 is as follows:

class ServerAction implelemts PrivilegedAction {

    public Object run() {
        ...
        ...
        try {
            GSSManager manager = GSSManager.getInstance();
            GSSName serverName =
                manager.createName("nfs@bar.foo.com",
                                    GSSName.NT_HOSTBASED_SERVICE);
            GSSCredential serverCreds =
             manager.createCredential(serverName,
                                       GSSCredential.INDEFINITE_LIFETIME,
                                       desiredMechs,
                                       GSSCredential.ACCEPT_ONLY);
            GSSContext secContext = manager.createContext(serverCreds);

            byte[] inToken = null;
            byte[] outToken = null;

            // Loop while the context is still not established
            while (!secContext.isEstablished()) {
                 inToken = readToken();
                 outToken =
                     secContext.acceptSecContext(inToken, 0, inToken.length);

                  // Send a token to the peer if one was generated
                  if (outToken != null)
                      sendToken(outToken);
            }
        } catch (GSSException e) {
          ...
        }
        ...
        ...
   }
}

             Figure 7. Sample server using Java GSS-API

Message Protection

Once the security context is established, it can be used for message protection. Java GSS-API provides both message integrity and message confidentiality. The two calls that enable this are as follows:

byte[] GSSContext.wrap(byte[] clearText,
                       int offset,
                       int len,
                       MessageProp properties)
    throws GSSException
and
byte[] unwrap(byte[] inToken,
              int offset,
              int len,
              MessageProp properties)
    throws GSSException

The wrap method is used to encapsulate a cleartext message in a token such that it is integrity protected. Optionally, the message can also be encrypted by requesting this through a properties object. The wrap method returns an opaque token that the caller sends to its peer. The original cleartext is returned by the peer's unwrap method when the token is passed to it. The properties object on the unwrap side returns information about whether the message was simply integrity protected or whether it was encrypted as well. It also contains sequencing and duplicate token warnings.

Credential Delegation

Java GSS-API allows the client to securely delegate its credentials to the server, such that the server can initiate other security contexts on behalf of the client. This feature is useful for single sign-on in a multi-tier environment.

Credential delegation in a multi-tier environment

Figure 8. Credential Delegation

The client requests credential delegation prior to making the first call to initSecContext():

void GSSContext.requestCredDeleg(boolean state)
    throws GSSException
by setting state to true.

The server receives the delegated credential after context establishment:

GSSCredential GSSContext.getDelegCred() throws GSSException

The server can then pass this GSSCredential to GSSManager.createContext() pretending to be the client.

In the case of the Kerberos V5 mechanism, the delegated credential is a forwarded TGT that is encapsulated as part of the first token sent from the client to the server. Using this TGT, the server can obtain a service ticket on behalf of the client for any other service.

DEFAULT CREDENTIAL ACQUISITION MODEL

Previously we discussed how an application uses the GSSManager.createCredential() method to populate a GSSCredential object with mechanism specific credentials.The next two sub-sections will focus on how Java GSS-API mechanisms obtain these credentials. The mechanisms do not themselves perform a user login. Instead, the login is performed prior to using Java GSS-API and the credentials are assumed to be stored in some cache that the mechanism provider is aware of. The GSSManager.createCredential() method merely obtains references to those credentials and returns them in a GSS-centric container, the GSSCredential.

In the Java 2 platform we impose the restriction that the credentials cache that Java GSS-API mechanism providers use to obtain these elements must exclusively be the public and private credential sets in the Subject that is on the current access control context.

This model has the advantage that credential management is simple and predictable from the application's point of view. An application, given the right permissions, can purge the credentials in the Subject or renew them using standard Java API's. If it purged the credentials, it would be sure that the Java GSS-API mechanism would fail, or if it renewed a time based credential it would be sure that the mechanism would succeed.

Here is the sequence of events relevant to credential acquisition when the Kerberos V5 mechanism is used by the client application in Figures 3 and 6:

  1. The application invokes a JAAS login, which in turn invokes the configured Krb5LoginModule
  2. Krb5LoginModule obtains a TGT (KerberosTicket) for the user either from the KDC or from an existing ticket cache, and stores this TGT in the private credentials set of a Subject
  3. The application retrieves the populated Subject, then calls Subject.doAs/doAsPrivileged which places this Subject on the access control context of the thread executing ClientAction
  4. ClientAction calls the GSSManager.createCredential method, passing it the Kerberos V5 OID in desiredMechs.
  5. GSSManager.createCredential invokes the Kerberos V5 GSS-API provider, asking for a Kerberos credential for initiating security contexts.
  6. The Kerberos provider obtains the Subject from the current access control context, and searches through its private credential set for a valid KerberosTicket that represents the TGT for the user.
  7. The KerberosTicket is returned to the GSSManager which stores it in a GSSCredential container instance to be returned to the caller.

On the server side, when the Kerberos login is successful in step 2, Krb5LoginModule stores the KerberosKey for the server in the Subject in addition to the KerberosTicket. Later on the KerberosKey is retrieved in steps 5 through 7 and used to decrypt the service ticket that the client sends.

EXCEPTIONS TO THE MODEL

The default credential acquisition model for Java GSS-API requires credentials to be present in the current Subject. Typically, the credentials are placed there after a JAAS login by the application.

There might be cases where an application wishes to use Kerberos credentials from outside the Subject. It is recommended that such credentials be read as part of the initial JAAS login, either by configuring Krb5LoginModule to read them, or by writing a custom login module that reads them. However, some applications might have constrains that either prevent them from using JAAS prior to calling Java GSS-API, or force them to use some Kerberos mechanism provider that does not retrieve credentials from the current Subject.

In order to accommodate such cases while still retaining the standard model for others, the system property javax.security.auth.useSubjectCredsOnly was added. This system property serves as a boolean where a value of true requires that the standard credential acquisition model be followed, and a value of false permits the provider to use any cache of it choice. The default value of this property (when it is not set) will be assumed to be true.

If there is no valid Kerberos credential in the current Subject, and this property is true, then the Kerberos mechanism throws a GSSException. Setting this property to false does not necessarily mean that the provider has to use a cache other than the current Subject, it only gives the provider the latitude to do so if it wishes.

The Sun provider for the Kerberos V5 GSS-API mechanism always obtains credentials from a Subject. If there are no valid credentials in the current Subject, and this property is set to false, then the provider attempts to obtain new credentials from a temporary Subject by invoking a JAAS login itself. It uses the text callback handler for input/output with the user, and the JAAS configuration entry identified by"other" for the list of modules and options to use 2. It assumes that one of these modules will be a Kerberos login module. It is possible to configure the modules listed under "other" to read a pre-existing cache so that the user is not unexpectedly prompted for a password in the middle of a Java GSS-API call. The new Subject that is populated by this login is discarded by the Kerberos GSS-API mechanism just as soon as the required credentials are retrieved from it.

WEB-BROWSER INTEGRATION

An important class of applications that should be able to capitalize on Java single sign-on are applets. For this discussion we assume that the browser JRE has all the required packages or the Java plugin is used with a Merlin JRE installed by the user.

One complication in using applets arises mostly out of the fact that before an applet can use Java GSS-API, it must perform a JAAS login. The main problems with this are (a) an increase in the effort required on the part of the applet developer (b)unnecessary repeated login by the same user each time he or she starts an applet.

A good model to solve this problem would be to have the browser (or the Java plugin) perform a JAAS login once at startup. This would provide a Subject that could always be associated with the access control context whenever any Java code was run. As a result, the applet code would not need to perform a JAAS login prior to using Java GSS-API, and the user login would occur just once.

In the absence of this login functionality in the browser (or Java plugin), applets can still avoid having to perform a JAAS login themselves. To do so, the applets would have to set the javax.security.auth.useSubjectCredsOnly system property to false and use a GSS-API mechanism provider that is capable of obtaining credentials from sources other than current Subject. When using a Sun JRE with a Sun Kerberos GSS-API provider, expect the mechanism to perform a JAAS login to obtain new credentials as explained in the previous section. The applet deployer would only need to ensure that the appropriate modules and options are listed in the entry "other" in the JAAS configuration used by the JRE. This saves the applet developer from calling into JAAS API's directly, but it does not stop the repeated JAAS login that might happen with each applet the user runs. However, by configuring the login modules to read a pre-existing native cache, the deployer can both hide the login from the user, and minimize the overhead in the multiple logins. (See how this is done for the JAAS configuration entry "SampleClient" in Figure 1.)

SECURITY RISKS

The convenience of single sign-on also introduces new risks. What happens if a malicious user gains access to your unattended desktop from where he or she can start applets as you? What happens if malicious applets sign on as you to services that they are not supposed to?

For the former, we have no solution but to caution you against leaving your workstation unlocked! For the latter, we have many authorizations checks in place.

To illustrate some details of the permissions model consider an example where your browser has performed a JAAS login at startup time and associated a Subject with all applets that run in it.

The Subject is protected from rogue applets by means of the javax.security.auth.AuthPermission class. This permission is checked whenever code tries to obtain a reference to the Subject associated with any access control context.

Even if an applet were given access to a Subject, it needs a javax.security.auth.PrivateCredentialPermission to actually read the sensitive private credentials stored in it.

Other kinds of checks are to be done by Java GSS-API mechanism providers as they read credentials and establish security contexts on behalf of the credential's owner. In order to support the Kerberos V5 mechanism, two new permission classes have been added with the package javax.security.auth.kerberos:

ServicePermission(String servicePrinicipal, String action)
DelegationPermission(String principals)

As new GSS-API mechanisms are standardized for Java SE, more packages will be added that contain relevant permission classes for providers of those mechanisms.

The Kerberos GSS-API mechanism permission checks take place at the following points in the program's execution:

Credential Acquisition

The GSSManager.createCredential() method obtains mechanism specific credential elements from a cache such as the current Subject and stores them in a GSSCredential container. Allowing applets to acquire GSSCredential freely, even if they cannot use them to do much, is undesirable. Doing so leaks information about the existence of user and service principals. Thus, before an application can acquire a GSSCredential with any Kerberos credential elements in it, a ServicePermission check is made.

On the client side, a successful GSSCredential acquisition implies that a TGT has been accessed from a cache. Thus the following ServicePermission is checked:

ServicePermission("krbtgt/FOO.COM@FOO.COM", "initiate");

The service principal krbtgt/FOO.COM@FOO.COM represents the ticket granting service (TGS) in the Kerberos realm FOO.COM, and the action "initiate" suggests that a ticket to this service is being accessed. The TGS service principal will always be used in this permission check at the time of client side credential acquisition.

On the server side, a successful GSSCredential acquisition implies that a secret key has been accessed from a cache. Thus the following ServicePermission is checked:

ServicePermission("nfs/bar.foo.com@FOO.COM", "accept");

Here the service principal nfs/bar.foo.com represents the Kerberos service principal and the action "accept" suggests that the secret key for this service is being requested.

Context Establishment

An applet that has permissions to contact a particular server, say the LDAP server, must not instead contact a different server such as the FTP server. Of course, the applet might be restricted from doing so with the help of SocketPermission. However, it is possible to use ServicePermission to restrict it from authenticating using your identity, even if the network connection was permitted.

When the Kerberos mechanism provider is about to initiate context establishment it checks the ServicePermission:

ServicePermission("ftp@FOO.COM", "initiate");

This check prevents unauthorized code from obtaining and using a Kerberos service ticket for the principal ftp@FOO.COM.

Providing limited access to specific service principals using this permission is still dangerous. Downloaded code is allowed to communicate back with the host it originated from. A malicious applet could send back the initial GSS-API output token that contains a KerberosTicket encrypted in the target service principal's long-term secret key, thus exposing it to an offline dictionary attack. For this reason it is not advisable to grant any "initiate" ServicePermission to code downloaded from untrusted sites.

On the server side, the permission to use the secret key to accept incoming security context establishment requests is already checked during credential acquisition. Hence, no checks are made in the context establishment stage.

Credential Delegation

An applet that has permission to establish a security context with a server on your behalf also has the ability to request that your credentials be delegated to that server. But not all servers are trusted to the extent that your credentials can be delegated to them. Thus, before a Kerberos provider obtains a delegated credential to send to the peer, it checks the following permission:

DelegationPermission(" \"ftp@FOO.COM\" \"krbtgt/FOO.COM@FOO.COM\" ");

This permission allows the Kerberos service principal ftp@FOO.COM to receive a forwarded TGT (represented by the ticket granting service krbtgt/FOO.COM@FOO.COM)3.

CONCLUSIONS

In this paper we have presented a framework to enable single sign-on in Java. This requires sharing of credentials between JAAS which does the initial authentication to obtain credentials, and Java GSS-API which uses those credentials to communicate securely over the wire. We have focused on Kerberos V5 as the underlying security mechanism, but JAAS's stackable architecture and Java GSS-API's multi-mechanism nature allow us to use any number of different mechanisms simultaneously.

The Kerberos login module for JAAS is capable of reading native caches so that users do not have to authenticate themselves beyond desktop login on platforms that support Kerberos. Moreover, the Kerberos V5 mechanism for Java GSS-API allows credentials to be delegated which enables single sign-on in multi-tier environments.

Finally, a number of permissions checks are shown to prevent the unauthorized use of the single-sign on features provided by Kerberos.

ACKNOWLEDGMENTS

We thank Gary Ellison, Charlie Lai, and Jeff Nisewanger for their contribution at each stage of the Kerberos single sign-on project. JAAS 1.0 was implemented by Charlie as an optional package for Kestrel (J2SE 1.3). Gary has been instrumental in designing the permissions model for the Kerberos Java GSS-API mechanism. We are grateful to Bob Scheifler for his feedback on integrating JAAS 1.0 into Merlin and to Tim Blackman for the KeyStoreLoginModule and CallbackHandler implementations. We also thank Bruce Rich, Tony Nadalin, Thomas Owusu and Yanni Zhang for their comments and suggestions. We thank Mary Dageforde for the documentation and tutorials. Sriramulu Lakkaraju, Stuart Ke and Shital Shisode contributed tests for the projects. Maxine Erlund provided management support for the project.

REFERENCES

  1. Neuman, Clifford and Tso, Theodore (1994). Kerberos: An Authentication Service for Computer Networks, IEEE Communications, volume 39 pages 33-38
  2. J.Kohl and C.Neuman. The Kerberos Network Authentication Service (V5) Internet Engineering Task Force, September 1993 Request for Comments 1510
  3. V. Samar and C. Lai. Making Login Services Independent from Authentication Technologies. In Proceedings of the SunSoft Developer's Conference, March 1996.
  4. X/Open Single Sign-On Service (XSSO) - Pluggable Authentication. Preliminary Specification P702, The Open Group, June 1997. http://www.opengroup.org
  5. A Smart Card Login Module for Java Authentication and Authorization Service. http://www.gemplus.com/techno/smartjaas/index.html
  6. J. Linn. Generic Security Service Application Program Interface,Version 2. Internet Engineering Task Force, January 2000 Request for Comments 2743
  7. J. Linn. The Kerberos Version 5 GSS-API Mechanism. Internet Engineering Task Force, June 1996 Request for Comments 1964
  8. C.Adams. The Simple Public-Key GSS-API Mechanism (SPKM). Internet Engineering Task Force, October 1996 Request for Comments 2025
  9. J. Kabat and M.Upadhyay. Generic Security Service API Version 2: Java Bindings. Internet Engineering Task Force, January 1997 Request for Comments 2853
  10. JSR 000072 Generic Security Services API http://java.sun.com/aboutJava/communityprocess/final-draft/jsr072/index.html
  11. Java 2 Platform, Standard Edition, v 1.4 API Specification. http://java.sun.com/j2se/1.4.2/docs/api/overview-summary.html

1 The GSS-API Kerberos mechanism performs client authentication at the minimum.

2 Actually it first tries to use the JAAS configuration entry"com.sun.security.jgss.initiate" for the client and "com.sun.security.jgss.accept" for the server and falls back on the entry for "other", if these entries are missing. This gives system administrators some additional control over its behavior.

3 The use of two principal names in this permission allows for finer grained delegation such as proxy tickets for specific services unlike a carte blanche forwarded TGT. Even though the GSS-API does not allow for proxy tickets, another API such as JSSE might support this idea at some point in the future.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


SingleInstanceListener (JNLP API Reference 1.7.0)

  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method
javax.jnlp

Interface SingleInstanceListener

  • public interface SingleInstanceListener
    SingleInstanceListener is a interface which should be implemented by a JNLP application if they wish to support single instance behaviour.
    Since:
    1.5

    • Method Summary

      Methods
      Modifier and Type Method and Description
      void newActivation(java.lang.String[] params)
      This method should be implemented by the application to handle the single instance behaviour - how should the application handle the arguments when another instance of the application is invoked with params.

    • Method Detail

      • newActivation

        void newActivation(java.lang.String[] params)
        This method should be implemented by the application to handle the single instance behaviour - how should the application handle the arguments when another instance of the application is invoked with params.
        Parameters:
        params - Array of parameters for the application main (arguments supplied in the jnlp file)
  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.


SingleInstanceService (JNLP API Reference 1.7.0)

  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method
javax.jnlp

Interface SingleInstanceService

  • public interface SingleInstanceService
    SingleInstanceService allow applications launched under Java Web Start to register themselves as singletons, and to be passed in new parameter sets when user attempts to launch new instances of them.
    Since:
    1.5

    • Method Summary

      Methods
      Modifier and Type Method and Description
      void addSingleInstanceListener(SingleInstanceListener sil)
      Adds the specified SingleInstanceListener to handle how the application/applet should behave when another instance of the same application/applet is invoked.
      void removeSingleInstanceListener(SingleInstanceListener sil)
      Removes the specified SingleInstanceListener.

    • Method Detail

      • addSingleInstanceListener

        void addSingleInstanceListener(SingleInstanceListener sil)
        Adds the specified SingleInstanceListener to handle how the application/applet should behave when another instance of the same application/applet is invoked. If SingleInstanceListener sil is null, no exception is thrown and no action is performed.
        Parameters:
        sil - the SingleInstanceListener object to be added

      • removeSingleInstanceListener

        void removeSingleInstanceListener(SingleInstanceListener sil)
        Removes the specified SingleInstanceListener. This method performs no function, nor does it throw an exception, if the listener specified by the argument was not previously added to the application/applet. If listener sil is null, no exception is thrown and no action is performed. It is recommended that if an application/applet registered any SingleInstanceListener(s), it should call this method to remove all listeners upon exit of the application/applet.
        Parameters:
        sil - the SingleInstanceListener object to be removed
  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.


Legal Notices

See Legal Notices

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Security Managers and the Java SE JDK

Introduction
Security Model Evolution
Security Manager Evolution
Security Manager Methods
Security Managers in JDK 1.1
Security Managers in the Java SE JDK
Installing java.lang.SecurityManager as the Default Security Manager
Changes to Methods For Class Loaders And Class Loader Depth
How to Port 1.1-Style Security Managers
SecurityManager Method Changes and Override Advice

Introduction

This document describes changes made to the security manager in the JDK that allow it to be used as-is as the default security manager in applications.

Security Model Evolution

In JDK 1.1, local applications and correctly digitally signed applets were generally trusted to have full access to vital system resources, such as the file system, while unsigned applets were not trusted and could access only limited resources. A security manager was responsible for determining which resource accesses were allowed.

The Java SE JDK security architecture is policy-based, and allows for fine-grained access control. When code is loaded, it is assigned "permissions" based on the security policy currently in effect. Each permission specifies a permitted access to a particular resource, such as "read" and "write" access to a specified file or directory, or "connect" access to a given host and port. The policy, specifying which permissions are available for code from various signers/locations, can be initialized from an external configurable policy file. Unless a permission is explicitly granted to code, it cannot access the resource that is guarded by that permission. These new concepts of permission and policy enable the JDK to offer fine-grain, highly configurable, flexible, and extensible access control. Such access control can now not only be specified for applets, but also for all Java code, including applications, beans, and servlets.

For more information on the Java security architecture, please see the security documentaton.

Security Manager Evolution

Security Manager Methods

The SecurityManager class contains many methods with names that begin with the word check. Examples are checkRead and checkConnect. Various methods in the Java libraries call a check method before performing each potentially security-sensitive operation. The security manager is thereby given an opportunity to prevent completion of the operation by throwing an exception. A security manager routine simply returns if the operation is permitted, but throws a SecurityException if the operation is not permitted. The only exception to this convention is checkTopLevelWindow, which returns a boolean value.

The other main type of methods contained in the SecurityManager class are those related to class loader existence and depth:

  • currentClassLoader
  • currentLoadedClass
  • inClassLoader
  • classLoaderDepth

Security Managers in JDK 1.1

In JDK 1.1, the class java.lang.SecurityManager was an abstract class. The default implementations of the security manager check methods threw exceptions. The class loader and depth-related classes were appropriately implemented, often in native code.

Any application (such as a browser) that wanted to install a security manager had to write their own, providing appropriate concrete implementations of the methods that threw exceptions by default -- primarily the check methods.

Security managers based on the JDK 1.1 applet security manager model typically based access control decisions on two things:

  1. Whether or not a class with a class loader (i.e., an applet in JDK 1.1) was on the stack.
  2. The class loader depth -- how far down the stack was the most recent occurrence of a method from a class defined using a class loader.

These types of decisions were made by calling the SecurityManager methods related to class loader existence and depth. For example, a typical 1.1-style security manager might have a checkExit method like the following:

     public void checkExit(int status) {
       if (inClassLoader()) {
        throw new SecurityException(..);
       }
     }

Such a checkExit method would not allow Runtime.exit to be called when any class defined with a class loader (an applet) was on the stack. This is an example of the first case, checking whether or not a class with a class loader is on the stack. An example of the second case (class loader depth) would be something like:

      public void checkCreateClassLoader() {
         if (classLoaderDepth() == 2) {
            throw new SecurityException();
         }
      }

This method is saying that the class loader depth can't be 2. That is, the method that called the method that called checkCreateClassLoader must not be in a class defined with a class loader. For example, the constructor for java.lang.ClassLoader calls checkCreateClassLoader, which means the method that calls the constructor for java.lang.ClassLoader must not have a class loader. This means applets can't directly create class loaders.

Note that there is a big difference between the two methods, even though both attempt to prevent applets from performing actions. In the first case, checkExit will throw an exception if an applet is anywhere on the stack. That means even built-in JDK code can't exit the VM if it was called from an applet. In the second case, JDK code is allowed to create a class loader, even if it was called by an applet. That is because the depth of a class with a class loader is used, and not the fact that there is one.

Security Managers in the Java SE JDK

In the JDK, the class java.lang.SecurityManager had a number of changes made to it in order to allow it to be used as the default security manager for applications. In particular:
  • It is no longer an abstract class, and can thus be installed as-is.
  • Most check methods call a new checkPermission method, which by default calls the method of the same name (checkPermission) in the new AccessController class. Those methods that don't call checkPermission have reasonable defaults.
  • Methods used in JDK 1.1 to determine if a class loader is on the stack and/or to calculate class loader depth have been modified in the JDK to ignore system class loaders and security contexts that have been granted java.security.AllPermission.

Installing java.lang.SecurityManager as the Default Security Manager

Since java.lang.SecurityManager is no longer abstract, you can install and use it as the default security manager. You can do this by setting a system property when launching the VM:

    java -Djava.security.manager YourApp
Alternatively, your application can install it directly via the following line of code:
    System.setSecurityManager(new SecurityManager());
You can customize the behavior of the default security manager by modifying policy files. See the security guide on policy files for more information.

Changes to Methods For Class Loaders And Class Loader Depth

In the JDK, the SecurityManager methods related to class loaders and class loader depth are not called by any of the check methods, and they are deprecated. They should not be used by any new security managers, and it is recommended that their use be eliminated from existing security managers as well. However, they are left in for backward compatibility and they have been modified in an attempt to enable old 1.1-style security managers to still work under the JDK, without modification.

These methods are:

  • currentClassLoader
  • currentLoadedClass
  • inClassLoader
  • classLoaderDepth

Modification of Class Loader/Depth-related Methods

The class loader/depth related methods have all been modified in three ways:

  1. These methods skip system class loaders. A system class loader is defined as being a class loader that is equal to the system class loader (as returned by ClassLoader.getSystemClassLoader) or one of its ancestors.

    Since classes loaded by the system class loader include application classes (loaded off of CLASSPATH), extension classes, and the built-in JDK classes, this modification enables these methods to ignore such code.

    Note that if you run an application that installs a custom security manager, and that security manager is loaded off of CLASSPATH in the JDK, it will have a system class loader associated with it. (Application classes did not have a class loader in JDK 1.1.) If you were to call a method like classLoaderDepth from within the custom security manager, and that method were not modified to ignore classes loaded by a system class loader, it would always return 0, which would not be very useful. Similarly, if class loader methods weren't changed to skip system classes and a custom security manager was loaded off of CLASSPATH, then this might also open up security holes in cases where the security manager is making decisions based on, for example, disallowing an operation if "classLoaderDepth() == 2". (It should really be "classLoaderDepth() <= 2".)

  2. These methods stop checking after they reach a method on the stack that has been marked as "privileged." (See java.security.AccessController.doPrivileged() and API for Privileged Blocks.)
  3. These methods treat security contexts that have been granted AllPermission as if there is no class loader on the stack.

As an example of the use of the first two modifications, note that there are now places in the JDK that open files, etc., after a security manager has been installed. Some 1.1-style security managers have a checkRead method that looks like the following:

       public void checkRead(String file) {
         if (inClassLoader()) {
          throw new SecurityException(..);
         }
       }

Without JDK code modifications, such a check run in the JDK would cause a security exception to be thrown when the JDK itself tries to read a file and there is a class with a non-system class loader on the stack. With the new security model, all such JDK code that tries to perform an operation that its caller might not be allowed to do has a doPrivileged block around it. Since inClassLoader just examines the stack up to and including the frame containing the "privileged" code, and the code at the top of the stack is JDK code, which is loaded by the system class loader or one of its ancestors, the inClassLoader method will return false, allowing the read to occur.

Maintenance of Class Loader Depths

As noted previously, security managers based on the 1.1 applet security manager based some of their access control decisions on class loader depth. As an example, the checkCreateClassLoader method previously presented is repeated here:

       public void checkCreateClassLoader() {
          if (classLoaderDepth() == 2) {
             throw new SecurityException();
          }
       }
In the JDK we have attempted to maintain the stack depth as used in 1.1-style security managers. For example, the constructor for java.security.SecureClassLoader has an explicit call to SecurityManager.checkCreateClassLoader even though the constructor for its super class (ClassLoader) also does. If the check was not placed in the constructor for SecureClassLoader, then a 1.1-style security manager would allow untrusted code to extend SecureClassLoader and construct class loaders, as the class loader depth would always be greater than 2.

How to Port 1.1-Style Security Managers

First and foremost, we highly recommend analyzing all your custom security manager methods before running your security manager under the JDK. Failure to do so could result in a security hole or prevent the proper operation of the JDK. This is due to the fragile nature of 1.1-style security managers.

Where possible, you should just use the default implementation of the 1.2 SecurityManager. This helps give users and administrators consistent behavior. If this is not possible, then you should at least try to call super.checkXXX in your checkXXX method before throwing a security exception. Doing so will allow the access controller algorithm to be used, and will allow the JDK itself to function correctly.

In the JDK, any existing code that used to call any of the SecurityManager check methods continues to do so. For new code that requires a security check, calls are made to SecurityManager.checkPermission instead of adding a new SecurityManager check method. For example, the new java.lang.System.setProperty method calls checkPermission with a java.util.PropertyPermission permission.

When extending the SecurityManager class and overriding existing methods, some care should be taken. For example, if you override the checkRead(String file) method so it always throws a security exception, then the JDK itself may fail to operate properly. That is, if some JDK code needs to open a file (to read a properties file, load a JAR file, etc.) then throwing a security exception for every read attempt would cause such opens to always fail.

In general, you should only override the default methods if you intend to loosen security, not to make it stronger. If you want to tighten security, you should modify the default policy files and/or install a custom java.security.Policy object. See the security guide on policy files for more information.

In general, when overriding security manager methods you should place a call to the super.checkXXX method at the point where your overridden checkXXX method would throw an exception. For example:

      public class MySecurityManager extends SecurityManager {

        public void checkRead(String file) {
          if (someCustomSecurityCheckFails()) {
             super.checkRead(file);
          }
        }
      }
If your custom security check fails, then super.checkRead gets called. The default implementation of checkRead invokes checkPermission, which by default consults the AccessController. By invoking the AccessController, system code that has done an AccessController.doPrivileged before trying to read a file will succeed in reading that file. All other code will be subjected to the current policy in effect, and an access control exception will be thrown if access to that file has not been granted.

Note, there are some checkXXX methods in which you should not call super.checkXXX methods when overriding them. That is because the default implementation of these methods may not be as strict as the policy you are implementing in the overridden method. For example, the default checkAccess(ThreadGroup g) method only protects the system thread group. If you intend to protect threads in distinct thread groups from each other (for example applet thread groups), then you would not want to call super.checkAccess at the point you would normally throw a security exception, as that would defeat the purpose of your customized check. Instead, you could place a call to super.checkAccess as the first statement in your overridden method.

For example:

      public class AppletSecurityManager extends SecurityManager {

        public void checkAccess(ThreadGroup g) {
          // a call to super will throw an exception if someone
          // is trying to modify the system thread group
          super.checkAccess(g);
          ...
          // now perform checks based on which applet thread group
          // the current caller is in to see if they can modify thread group g.
          ...
      }

We describe how to override each method in the following section.

SecurityManager Method Changes and Override Advice

This section lists changes made to java.lang.SecurityManager methods in the JDK and provides suggestions regarding any overrides you may wish to make. Please see the Java documentation for the SecurityManager class for more information on these methods.

protected boolean inCheck

This field has been deprecated, and any uses of this field within the JDK itself have been removed. Instead of using inCheck, you should use checkPermission along with doPrivileged.

public boolean getInCheck();

This method has also been deprecated.

public SecurityManager();

The constructor has been modified to allow multiple SecurityManagers to be created, assuming the caller has the RuntimePermission("createSecurityManager") permission.

protected native Class[] getClassContext();

No changes. This call can be used to emulate the 1.1 behavior of the methods that have been changed in the JDK ( currentClassLoader, currentLoadedClass, classLoaderDepth, inClassLoader).

protected ClassLoader currentClassLoader();

The typical use of this method in JDK 1.1-style security managers was to see if there was a class loader on the stack, and if not, treat the code as "trusted" and allow it to do anything. This method has been modified in the JDK to allow trusted JDK code (actually any code granted java.security.AllPermission) that calls doPrivileged to be treated as trusted by 1.1-style security managers. It has also been modified to skip system class loaders. A system class loader is defined as being a class loader that is equal to the system class loader (as returned by ClassLoader.getSystemClassLoader) or one of its ancestors.

This method will return null in the following three cases:

  1. All methods on the execution stack are from classes defined using the system class loader or one of its ancestors.
  2. All methods on the execution stack up to the first "privileged" caller (see java.security.AccessController.doPrivileged) are from classes defined using the system class loader or one of its ancestors.
  3. A call to checkPermission with java.security.AllPermission does not result in a SecurityException.

This method has been deprecated. Use checkPermission instead.

protected Class currentLoadedClass();

This method has been modified in the same fashion as currentClassLoader, and will return null if the current security context has been granted AllPermission or all the methods on the stack (up to the first privileged caller, if any) are from classes defined using the system class loader or one of its ancestors.

This method has been deprecated. Use checkPermission instead.

protected int classDepth(String name);

No changes in behavior. This method has been deprecated. Use checkPermission instead.

protected int classLoaderDepth();

This method has been modified in the same fashion as currentClassLoader, and will return -1 if the current security context has been granted AllPermission or all the methods on the stack (up to the first privileged caller, if any) are from classes defined using the system class loader or one of its ancestors.

This method has been deprecated. Use checkPermission instead.

protected boolean inClass(String name);

No changes in behavior. This method has been deprecated. Use checkPermission instead.

protected boolean inClassLoader();

This method returns true if currentClassLoader returns a non-null class loader, so it follows the same semantics that currentClassLoader does.

This method has been deprecated. Use checkPermission instead.

public Object getSecurityContext();

This method returns a java.security.AccessControlContext object that is created with a call to java.security.AccessController.getContext. In JDK1.1 it returned null by default.

public void checkPermission(Permission perm);

This method is new in the JDK. It calls java.security.AccessController.checkPermission with the given permission. Internally, the JDK always calls SecurityManager.checkPermission instead of calling the AccessController directly. This allows people to override this method to provide additional functionality such as auditing and/or GUI dialogs.

public void checkPermission(Permission perm, Object context);

This method is new in the JDK. If context is an instance of AccessControlContext then the AccessControlContext.checkPermission method will be invoked on the given context with the specified permission.

If context is not an instance of AccessControlContext then a SecurityException is thrown.

public void checkCreateClassLoader();

This method has been modified to call checkPermission with the RuntimePermission("createClassLoader") permission.

If this method is overridden, then a call to super.checkCreateClassLoader should be made at the point the overridden method would normally throw an exception. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkCreateClassLoader() {
      if (someCustomSecurityCheckFails()) {
        super.checkCreateClassLoader();
      }
    }
  }

public void checkAccess(Thread t);

If the thread argument is a system thread (belongs to the thread group with a null parent) then this method calls checkPermission with the RuntimePermission("modifyThread") permission.

Applications that want a stricter policy should override this method.

If this method is overridden, then super.checkAccess should be called by the first statement in the overridden method, or the equivalent security check should be placed in the overridden method.

If this method is overridden, the method that overrides it should additionally check to see if the calling thread has the RuntimePermission("modifyThread") permission, and if so, return silently. This is to ensure that code granted that permission (such as the JDK itself) is allowed to manipulate any thread.

For example:

  public class MySecurityManager extends SecurityManager {

    public void checkAccess(Thread t) {
      // a call to super will throw an exception if someone
      // is trying to modify a system thread
      super.checkAccess(t);
      ...
      if (someCustomSecurityCheckForOtherThreadsFails()) {
        // if the check fails, instead of throwing an exception,
        // call checkPermission, which will throw an exception
        // if need be
        checkPermission(new RuntimePermission("modifyThread"));
      }
      ...
    }
  }

public void checkAccess(ThreadGroup g);

If the thread group argument is the system thread group (has a null parent) then this method calls checkPermission with the RuntimePermission("modifyThreadGroup") permission.

Applications that want a stricter policy should override this method.

If this method is overridden, then super.checkAccess should be called by the first statement in the overridden method, or the equivalent security check should be placed in the overridden method.

If this method is overridden, the method that overrides it should additionally check to see if the caller has the RuntimePermission("modifyThreadGroup") permission, and if so, return silently. This is to ensure that code granted that permission (such as the JDK itself) is allowed to manipulate any thread group.

For example:

  public class MySecurityManager extends SecurityManager {

    public void checkAccess(ThreadGroup g) {
      // a call to super will throw an exception if someone
      // is trying to modify the system thread group
      super.checkAccess(g);
      ...
      if (someCustomSecurityCheckForOtherThreadGroupsFails()) {
        // if the check fails, instead of throwing an exception,
        // call checkPermission, which will throw an exception
        // if need be
        checkPermission(new RuntimePermission("modifyThreadGroup"));
      }
      ...
    }
  }

public void checkExit(int status);

This method has been modified to call checkPermission with the RuntimePermission("exitVM") permission.

If this method is overridden, then a call to super.checkExit should be made at the point the overridden method would normally throw an exception. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkExit(int status) {
      if (someCustomSecurityCheckFails()) {
        super.checkExit(status);
      }
    }
  }

public void checkExec(String cmd);

This method has been modified to call checkPermission with a FilePermission. If the cmd is an absolute path (see java.io.File.isAbsolute) then it is passed as-is as the target for the FilePermission. If cmd is not absolute, then the special target "<<ALL FILES>>" is used. This target is used because it is difficult to determine the actual path of the command that will be executed on an individual platform due to things such as environment variables, etc.

If this method is overridden, then a call to super.checkExec should be made at the point the overridden method would normally throw an exception. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkExec(String cmd) {
      if (someCustomSecurityCheckFails()) {
        super.checkExec(cmd);
      }
    }
  }

public void checkLink(String lib);

This method has been modified to call checkPermission with the RuntimePermission("loadLibrary."+lib) permission.

If this method is overridden, then a call to super.checkLink should be made at the point the overridden method would normally throw an exception. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkLink(String lib) {
      if (someCustomSecurityCheckFails()) {
        super.checkLink(lib);
      }
    }
  }

public void checkRead(FileDescriptor fd);

This method has been modified to call checkPermission with the RuntimePermission("readFileDescriptor") permission.

If this method is overridden, then a call to super.checkRead should be made at the point the overridden method would normally throw an exception. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkRead(FileDescriptor fd) {
      if (someCustomSecurityCheckFails()) {
        super.checkRead(fd);
      }
    }
  }

public void checkRead(String file);

This method has been modified to call checkPermission with the FilePermission(file,"read") permission.

If this method is overridden, then a call to super.checkRead should be made at the point the overridden method would normally throw an exception. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkRead(String file) {
      if (someCustomSecurityCheckFails()) {
        super.checkRead(file);
      }
    }
  }

public void checkRead(String file, Object context);

This method has been modified. If context is an instance of AccessControlContext then the AccessControlContext.checkPermission method will be invoked on the given context with the FilePermission(file,"read") permission.

If context is not an instance of AccessControlContext then a SecurityException is thrown.

If this method is overridden, then a call to super.checkRead should be made at the point the overridden method would normally throw an exception. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkRead(String file, Object context) {
      if (someCustomSecurityCheckFails()) {
        super.checkRead(file, context);
      }
    }
  }

public void checkWrite(FileDescriptor fd);

This method has been modified to call checkPermission with the RuntimePermission("writeFileDescriptor") permission.

If this method is overridden, then a call to super.checkWrite should be made at the point the overridden method would normally throw an exception. For Example:

  public class MySecurityManager extends SecurityManager {

    public void checkWrite(FileDescriptor fd) {
      if (someCustomSecurityCheckFails()) {
        super.checkWrite(fd);
      }
    }
  }

public void checkWrite(String file);

This method has been modified to call checkPermission with the FilePermission(file,"write") permission.

If this method is overridden, then a call to super.checkWrite should be made at the point the overridden method would normally throw an exception. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkWrite(String file) {
      if (someCustomSecurityCheckFails()) {
        super.checkWrite(file);
      }
    }
  }

public void checkDelete(String file);

This method has been modified to call checkPermission with the FilePermission(file,"delete") permission.

If this method is overridden, then a call to super.checkDelete should be made at the point the overridden method would normally throw an exception. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkDelete(String file) {
      if (someCustomSecurityCheckFails()) {
        super.checkDelete(file);
      }
    }
  }

public void checkConnect(String host, int port);

This method has been modified to call checkPermission with the SocketPermission(host+":"+port,"connect") permission if the port is not equal to -1. If the port is equal to -1, then it calls checkPermission with the SocketPermission(host,"resolve") permission.

This behavior is consistent with JDK 1.1, where a port equal to -1 indicates that an IP address lookup is being performed.

If this method is overridden, then a call to super.checkConnect should be made at the point the overridden method would normally throw an exception. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkConnect(String host, int port) {
      if (someCustomSecurityCheckFails()) {
        super.checkConnect(host, port);
      }
    }
  }

public void checkConnect(String host, int port, Object context);

This method has been modified. If context is an instance of AccessControlContext then the AccessControlContext.checkPermission method will be invoked on the given context with the SocketPermission(host+":"+port,"connect") permission if the port is not equal to -1. If the port is equal to -1, then it calls checkPermission with the SocketPermission(host,"resolve") permission.

If context is not an instance of AccessControlContext then a SecurityException is thrown.

If this method is overridden, then a call to super.checkConnect should be made at the point the overridden method would normally throw an exception. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkConnect(String host, int port, Object context) {
      if (someCustomSecurityCheckFails()) {
        super.checkConnect(host, port, context);
      }
    }
  }

public void checkListen(int port)

This method has been modified. If port is not 0, it calls checkPermission with the SocketPermission("localhost:"+port,"listen"). If port is zero, it calls checkPermission with SocketPermission("localhost:1024-","listen").

If this method is overridden, then a call to super.checkListen should be made at the point the overridden method would normally throw an exception. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkListen(int port) {
      if (someCustomSecurityCheckFails()) {
        super.checkListen(port);
      }
    }
  }

public void checkAccept(String host, int port);

This method has been modified to call checkPermission with the SocketPermission(host+":"+port,"accept") permission.

If this method is overridden, then a call to super.checkAccept should be made at the point the overridden method would normally throw an exception. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkAccept(String host, int port) {
      if (someCustomSecurityCheckFails()) {
        super.checkAccept(host, port);
      }
    }
  }

public void checkMulticast(InetAddress maddr);

This method has been modified to call checkPermission with the SocketPermission(maddr.getHostAddress(),"accept,connect") permission.

If this method is overridden, then a call to super.checkMulticast should be made at the point the overridden method would normally throw an exception. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkMultiCast(InetAddress maddr) {
      if (someCustomSecurityCheckFails()) {
        super.checkMultiCast(maddr);
      }
    }
  }

public void checkMulticast(InetAddress maddr, byte ttl);

This method has been modified to call checkPermission with the SocketPermission(maddr.getHostAddress(),"accept,connect") permission.

If this method is overridden, then a call to super.checkMulticast should be made at the point the overridden method would normally throw an exception. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkMultiCast(InetAddress maddr, byte ttl) {
      if (someCustomSecurityCheckFails()) {
        super.checkMultiCast(maddr, ttl);
      }
    }
  }

public void checkPropertiesAccess();

This method has been modified to call checkPermission with the PropertyPermission("*", "read,write") permission.

If this method is overridden, then a call to super.checkPropertiesAccess should be made at the point the overridden method would normally throw an exception. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkPropertiesAccess() {
      if (someCustomSecurityCheckFails()) {
        super.checkPropertiesAccess();
      }
    }
  }

public void checkPropertyAccess(String key);

This method has been modified to call checkPermission with the PropertyPermission(key, "read") permission.

If this method is overridden, then a call to super.checkPropertyAccess should be made at the point the overridden method would normally throw an exception. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkPropertyAccess(String key) {
      if (someCustomSecurityCheckFails()) {
        super.checkPropertiesAccess(key);
      }
    }
  }

public boolean checkTopLevelWindow(Object window);

This method has been modified to call checkPermission with the AWTPermission("showWindowWithoutWarningBanner") permission, and returns true if an SecurityException is not thrown, otherwise it returns false.

If this method is overridden, then a call to super.checkTopLevelWindow should be made at the point the overridden method would normally return false, and the value of super.checkTopLevelWindow should be returned. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkTopLevelWindow(Object window) {
      if (someCustomSecurityCheckFails()) {
        return super.checkTopLevelWindow(window);
      } else {
        return true;
      }
    }
  }

public void checkPrintJobAccess();

This method has been modified to call checkPermission with the RuntimePermission("queuePrintJob") permission.

If this method is overridden, then a call to super.checkPrintJobAccess should be made at the point the overridden method would normally throw an exception. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkPrintJobAccess() {
      if (someCustomSecurityCheckFails()) {
        super.checkPrintJobAccess();
      }
    }
  }

public void checkSystemClipboardAccess();

This method has been modified to call checkPermission with the AWTPermission("accessClipboard") permission.

If this method is overridden, then a call to super.checkSystemClipboardAccess should be made at the point the overridden method would normally throw an exception. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkSystemClipboardAccess() {
      if (someCustomSecurityCheckFails()) {
        super.checkSystemClipboardAccess();
      }
    }
  }

public void checkAwtEventQueueAccess();

This method has been modified to call checkPermission with the AWTPermission("accessEventQueue") permission.

If this method is overridden, then a call to super.checkAwtEventQueueAccess should be made at the point the overridden method would normally throw an exception. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkAwtEventQueueAccess() {
      if (someCustomSecurityCheckFails()) {
        super.checkAwtEventQueueAccess();
      }
    }
  }

public void checkPackageAccess(String pkg);

This method has been modified. It first gets a list of restricted packages by obtaining a comma-separated list from a call to java.security.Security.getProperty("package.access"), and checks to see if pkg starts with or equals any of the restricted packages. If it does, then checkPermission gets called with the RuntimePermission("accessClassInPackage."+pkg) permission.

If this method is overridden, then super.checkPackageAccess should be called as the first line in the overridden method. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkPackageAccess(String pkg) {
      super.checkPackageAccess(pkg);
      ...
      someCustomSecurityCheck();
      ...
    }
  }

public void checkPackageDefinition(String pkg);

This method has been modified. It first gets a list of restricted packages by obtaining a comma-separated list from a call to java.security.Security.getProperty("package.definition"), and checks to see if pkg starts with or equals any of the restricted packages. If it does, then checkPermission gets called with the RuntimePermission("defineClassInPackage."+pkg) permission.

If this method is overridden, then super.checkPackageDefinition should be called as the first line in the overridden method. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkPackageDefinition(String pkg) {
      super.checkPackageDefinition(pkg);
      ...
      someCustomSecurityCheck();
      ...
    }
  }

public void checkSetFactory();

This method has been modified to call checkPermission with the RuntimePermission("setFactory") permission.

If this method is overridden, then a call to super.checkSetFactory should be made at the point the overridden method would normally throw an exception. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkSetFactory() {
      if (someCustomSecurityCheckFails()) {
        super.checkSetFactory();
      }
    }
  }

public void checkMemberAccess(Class clazz, int which);

This method has been modified. The default policy is to allow access to PUBLIC members, as well as access to classes that have the same class loader as the caller. In all other cases call checkPermission with the RuntimePermission("accessDeclaredMembers") permission.

If this method is overridden, then a call to super.checkMemberAccess cannot be made, as the default implementation of checkMemberAccess relies on the code being checked being at a stack depth of 4. For example:

     someCaller[3]
     java.lang.Class.someReflectionAPI [2]
     java.lang.Class.checkMemberAccess [1]
     SecurityManager.checkMemberAccess [0]
In order to emulate this behavior, you would need to call getClassContext, and examine the class loader of the class at index 3, just as the default checkMemberAccess method does:
  if (which != Member.PUBLIC) {
    Class stack[] = getClassContext();
    /*
     * stack depth of 4 should be the caller of one of the
     * methods in java.lang.Class that invoke checkMember
     * access. The stack should look like:
     *
     * someCaller [3]
     * java.lang.Class.someReflectionAPI  [2]
     * java.lang.Class.checkMemberAccess [1]
     * MySecurityManager.checkMemberAccess [0]
     *
     */
    if ((stack.length<4) ||
      (stack[3].getClassLoader() != clazz.getClassLoader())) {
      if (checkMemberAccessPermission == null)
        checkMemberAccessPermission =
          new RuntimePermission("accessDeclaredMembers");
      checkPermission(checkMemberAccessPermission);
    }
  }

This is the only security manager method in the JDK that is still based on a caller's depth. This is to allow a caller to reflect on classes from the same class loader it came from.

public void checkSecurityAccess(String target);

This method has been modified to create a SecurityPermission object for the given permission target name and calls checkPermission with it.

If this method is overridden, then a call to super.checkSecurityAccess should be made at the point the overridden method would normally throw an exception. For example:

  public class MySecurityManager extends SecurityManager {

    public void checkSecurityAccess(String target) {
      if (someCustomSecurityCheckFails()) {
        super.checkSecurityAccess(target);
      }
    }
  }

public ThreadGroup getThreadGroup();

This method has not been changed.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java VisualVM

Working with Snapshots

Java VisualVM enables you to take snapshots of application data and save the snapshots to your local system. Snapshots are a convenient way to capture data about an application because after a snapshot is saved it can be opened and viewed at any time. The target application does not need to be running to view the snapshot. Snapshots can also be sent and viewed by other people.

Snapshot Types

Snapshots are basically archives of data captured at a point in time that can then be opened in Java VisualVM. You can take and save the following types of snapshots:

Profiler Snapshots

Profiler snapshots capture profiling data at the moment the snapshot is taken. You can take a profiler snapshot at any time during a profiling session. When you take a profiler snapshot, a node representing the snapshot appears below the application node in the Applications window and a temporary snapshot file is written to your local system in the Java VisualVM userdir.

Java VisualVM can take the following types of profiler snapshots

  • Memory Snapshot. A memory snapshot captures profiling data on allocated objects. You can take a memory snapshot when you are using the profiler to analyze memory usage.
  • CPU Snapshot. A CPU snapshot captures data on the performance of the application. You can take a CPU snapshot when you are using the profiler to analyze application performance.

Screenshot of memory profiling snapshot

screenshot of memory profiling snapshot

Screenshot of CPU profiling snapshot

screenshot of CPU profiling snapshot

If you want to view a profiler snapshot later, the snapshot must be explicitly saved to your local system, either as a profiler snapshot or archived in an application snapshot.

Taking Profiler Snapshots

You can take a profiler snapshot during a profiling session. When you take a memory or CPU snapshot, the snapshot opens in the application's tab in the main window.

To take a snapshot, do one of the following:

  • Click the Take Snapshot of Collected Results button in the Profiler tab
  • Right-click the application node and choose Profiler Snapshot.

The snapshot toolbar enables you to do the following:

  • Save Snapshot to Custom File. Click to save snapshot as Snapshot file (.nps to your local system).
  • Save Current View to Image. Click to save snapshot as an image (.png to your local system)
  • Find in Results. Click to find a search term in the profiling results.
  • Find Next Occurence. Click to find next occurrence of search term
  • Find Previous Occurence. Click to find previous occurrence of search term

Application Snapshots

An application snapshot captures the collected heap dumps, thread dumps and profiler snapshots of an application at the moment the snapshot is taken. An application snapshot also captures general information about the Java Virtual Machine (JVM).

You take an application snapshot by right-clicking an application node in the Applications window and choosing Application Snapshot from the popup menu. Application snapshots are persisted between Java VisualVM sessions.

When you take an application snapshot:

  • An application snapshot node appears under the Snapshots node in the Applications window
  • Application data is saved in a folder in the the repository/snapshots folder in the Java VisualVM user dir

Application snapshots are listed under the Snapshots node in the Applications window. Expand the application snapshot node to view the contents of the snapshot.

screenshot of Applications window showing application snapshots

After you take an application snapshot, you can view and modify the contents by expanding the application snapshot node in the Applications window. You can right-click an application snapshot node or any of the items listed under the application snapshot node to open the popup menu where you can choose to open, save, rename and delete the item. You can then save the application snapshot as a single application snapshot archive (.apps) to your local system.

The Overview tab of an application snapshot captures data about the JVM software.

screenshot of Overview tab of an application snapshot
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


SNMP Monitoring and Management - Java SE Monitoring and Management Guide

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
previous Previous Contents Next next
Chapter 5

SNMP Monitoring and Management

The Simple Network Management Protocol (SNMP) is an industry standard for network management. Objects managed by SNMP are arranged in management information bases (MIBs). The SNMP agent publishes the standard MIB for the Java virtual machine (Java VM) instrumentation. The standard MIB for monitoring and management of the Java VM is available for download at http://java.sun.com/javase/6/docs/jre/api/management/JVM-MANAGEMENT-MIB.mib.

Enabling the SNMP Agent

To monitor a Java VM with SNMP you must first enable an SNMP agent when you start the Java VM. You can enable the SNMP agent for either a single-user environment or a multiple-user environment. Then, you can monitor the Java VM with an SNMP-compliant tool.

For general information on setting system properties when you start the Java VM, see Setting System Properties in Chapter 2, Monitoring and Management Using JMX Technology. How to enable the SNMP agent in single and multiple-user environments is described below. The process is the same for both environments, but the actions performed are slightly different.

Access Control List File

An Access Control List (ACL) template file is provided with the Java Platform, Standard Edition (Java SE platform) in JRE_HOME/lib/management/snmp.acl.template, where JRE_HOME is the directory in which the Java Runtime Environment (JRE) implementation is installed. You will copy this file to either JRE_HOME/lib/management/snmp.acl or to your home directory, depending on whether you are operating in a single or a multiple-user environment. Ensure that only you have read permissions, since the file contains non-encrypted SNMP community strings. For security reasons, the system checks that only the owner has read permissions on the file and exits with an error if this is not the case. Thus, in a multiple-user environment, you should put this file in private location, such as your home directory.

Example 5-1 shows some possible entries in an ACL file.

Example 5-1 Sample ACL Entries
#The communities public and private are allowed access from the local host.
acl = {
        {
          communities = public, private
          access = read-only
          managers = localhost
        }
      }
# Traps are sent to localhost only
trap = {
          {
            trap-community = public
            hosts = localhost
          }
        }

procedure graphic To Enable the SNMP Agent in a Single-user Environment

  1. Set the following system property when you start the Java VM.
    com.sun.management.snmp.port=portNum

    In the property above, portNum is the port number to use for monitoring. Setting this property starts an SNMP agent that listens on the specified port number for incoming SNMP requests.

  2. Create an ACL File.

    Copy the ACL template file from JRE_HOME/lib/management/snmp.acl.template to JRE_HOME/lib/management/snmp.acl.

  3. Set the permissions on the ACL file.

    Make sure the ACL file is readable by only the owner, and add community strings as needed.

procedure graphic To Enable the SNMP Agent in a Multiple-user Environment

  1. Set the following system properties when you start the Java VM.
    com.sun.management.snmp.port=portNum
com.sun.management.snmp.acl.file=ACLFilePath

    Where ACLFilePath is the path to the ACL file.

  2. Create an ACL File.

    Copy the ACL template file from JRE_HOME/lib/management/snmp.acl.template to a file named snmp.acl in your home directory.

  3. Set the permissions on the ACL file.

    Make sure the ACL file is readable by only the owner, and add community strings as needed.

SNMP Monitoring and Management Properties

You can set SNMP monitoring and management properties in a configuration file or on the command line. Properties specified on the command line override properties in a configuration file. The default location for the configuration file is JRE_HOME/lib/management/management.properties. The Java VM reads this file if the command-line property com.sun.management.snmp.port is set.

You can specify a different location for the configuration file with the following command-line option.

com.sun.management.config.file=ConfigFilePath

In the property above, ConfigFilePath is the path to the configuration file.

You must specify all system properties when you start the Java VM. After the Java VM has started, any changes to system properties (for example, via the setProperty method), to the password file, to the ACL file, or to the configuration file will have no effect.

Table 5-1 describes all the SNMP management properties.

Table 5-1 SNMP monitoring and management Properties

Property Name | Description | Default
com.sun.management.snmp.trap | Remote port to which the SNMP agent sends traps. | 162
com.sun.management.snmp. interface | Optional. The local host InetAddress, to force the SNMP agent to bind to the given InetAddress. This is for multi-home hosts if one wants to listen to a specific subnet only. | Not applicable
com.sun.management.snmp.acl | Enables or disables SNMP ACL checks. | true
com.sun.management.snmp. acl.file | Path to a valid ACL file. After the Java VM has started, modifying the ACL file has no effect. | JRE_HOME/lib/management/snmp.acl

Configuration Errors

If any errors occur during start up of the SNMP agent, the Java VM will throw an exception and exit. Configuration errors include the following.

  • Failure to bind to the port number.

  • The password file is readable by anyone other than the owner.

  • Invalid SNMP ACL file.

If your application runs a security manager, then additional permissions are required in the security permissions file.
previous Previous Contents Next next
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


New SocketExceptions in JDK1.1

Previously, all network errors in java raised a SocketException, which didn't provide enough information to decipher what went wrong. Was the connection refused by the remote machine (no one listening on that port)? Or was the host unreachable (connect attempt timed out)? JDK 1.1 adds three new classes that provide a finer granularity of reported errors:

  • java.net.BindException

    The local port is in use, or the requested bind address couldn't be assigned locally.
            public class BindException extends SocketException {
        ...
        }

  • java.net.ConnectException

    This exception is raised when a connection is refused at the remote host (i.e., no process is listening on that port).
            public class ConnectException extends SocketException {
        ...
        }

  • java.net.NoRouteToHostException

    The connect attempt timed out, or the remote host is otherwise unreachable.
            public class NoRouteToHostException extends SocketException {
        ...
        }

Simple Usage Examples:

  • On the Client Side:
    import java.net.*;
        ...
        Socket s = null;
        try {
           s = new Socket("foo.org", 80);
        } catch (UnknownHostException e) {
           // check spelling of hostname
        } catch (ConnectException e) {
           // connection refused - is server down? Try another port.
        } catch (NoRouteToHostException e) {
           // The connect attempt timed out.  Try connecting through a proxy
        } catch (IOException e) {
           // another error occurred
        }
  • On the Server Side:
    import java.net.*;
        ...
        ServerSocket ss = null;
        try {
            /* try to bind to local address 129.144.175.156 */
            InetAddress in = InetAddress.getByName("129.144.175.156");
            int port = 8000;
            int backlog = 5;
            ss = new ServerSocket(port, backlog, in);
        } catch (BindException e) {
            // port 8000 in use, or can't bind to 129.144.175.156 as a local address
        } catch (SocketException e) {
            // another error occurred
        }
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Socket Options in Java

The C way

Programming in C, one sets options by using a system call along the lines of:
        setsockopt(int fd, int level, int optval, void *optdata,
                   int optdatalen);

        fd = already opened (possibly connected) socket fd;
        level = level in the protocol stack (IP, UDP, TCP) where
                the option applies;
        optval = the option, a CONSTANT;
        optdata = ptr to option dependent struct of parameters relevant
                 only to a particular option;

In java

The C way of setting options lacks the type-safety of object-oriented programming. The option one wishes to set/get is identified by an int, and the value to set/get into is an opaque void*. It is all too easy to pass the wrong option identifier, the wrong type object in the void* parameter, or the wrong for that parameter. Worse still, the code for these errors will typically compile, and the error will only be manifested at runtime.

Java now provides a type-safe way to set options. Each socket class has a get/set method for each option it supports, taking and returning the appropriate type. The options supported, for which socket classes and their meaning in brief:

  • TCP_NODELAY
    • Disable Nagle's algorithm.
    • Valid for (client) Sockets.
  • SO_LINGER
    • Specify a linger-on-close timeout.
    • Valid for (client) Sockets.
  • SO_TIMEOUT
    • Specify a timeout on blocking socket operations. (Don't block forever!
    • Valid for all sockets: Socket, ServerSocket, DatagramSocket.
  • SO_BINDADDR
    • Fetch the local address binding of a socket.
    • Valid for Socket, ServerSocket, DatagramSocket.
  • SO_REUSEADDR
    • Enable reuse address for a socket.
    • Valid for Socket, ServerSocket, DatagramSocket.
  • SO_BROADCAST
    • Enables a socket to send broadcast messages.
    • Valid for DatagramSocket.
  • SO_SNDBUF
    • Set a hint the size of the underlying buffers for outgoing network I/O.
    • Valid for all sockets: Socket, ServerSocket, DatagramSocket.
  • SO_RCVBUF
    • Get the size of the buffer actually used by the platform when receiving in data on this socket.
    • Valid for all sockets: Socket, ServerSocket, DatagramSocket.
  • SO_KEEPALIVE
    • Turn on socket keepalive.
    • Valid for Socket.
  • SO_OOBINLINE
    • Enable inline reception of TCP urgent data.
    • Valid for Socket.
  • IP_MULTICAST_IF
    • Specify the outgoing interface for multicast packets (on multihomed hosts).
    • Valid for MulticastSockets.
  • IP_MULTICAST_LOOP
    • Enables or disables local loopback of multicast datagrams.
    • Valid for MulticastSocket.
  • IP_TOS
    • Sets the type-of-service or traffic class field in the IP header for a TCP or UDP socket.
    • Valid for Socket, DatagramSocket

Fell by the wayside...

Some possible BSD options that are not supported in java:
  • RAW/ICMP SOCKETS:
    The main argument in favor of this one seemed to be so people could write "ping" in java. Security nightmare. Must be root on UNIX machines.

The implementation details...

...that you don't need to know, unless you subclass SocketImpl/DatagramSocketImpl. Every *Socket object has an underlying SocketImpl/DatagramSocketImpl that interfaces to native code. The Impl classes implement two methods to support options:
        void setOption(int optID, Object val) throws SocketException;
        Object getOption(int optID) throws SocketException;
that look much like C. These methods act as glue to the native methods, and ensure type safety before native methods are invoked.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.security.auth.module.SolarisLoginModule (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.module.SolarisLoginModule

No usage of com.sun.security.auth.module.SolarisLoginModule
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.auth.SolarisNumericGroupPrincipal (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.SolarisNumericGroupPrincipal

No usage of com.sun.security.auth.SolarisNumericGroupPrincipal
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.auth.SolarisNumericUserPrincipal (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.SolarisNumericUserPrincipal

No usage of com.sun.security.auth.SolarisNumericUserPrincipal
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.auth.SolarisPrincipal (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.SolarisPrincipal

No usage of com.sun.security.auth.SolarisPrincipal
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.auth.module.SolarisSystem (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.module.SolarisSystem

No usage of com.sun.security.auth.module.SolarisSystem
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.util.SourcePosition (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.util.SourcePosition

  • Packages that use SourcePosition
    Package Description
    com.sun.mirror.apt
    Classes used to communicate information between annotation processors and an annotation processing tool.
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.

    • Uses of SourcePosition in com.sun.mirror.apt

      Methods in com.sun.mirror.apt with parameters of type SourcePosition
      Modifier and Type Method and Description
      void Messager.printError(SourcePosition pos, String msg)
      Deprecated.
      Prints an error message.
      void Messager.printNotice(SourcePosition pos, String msg)
      Deprecated.
      Prints a notice.
      void Messager.printWarning(SourcePosition pos, String msg)
      Deprecated.
      Prints a warning message.

    • Uses of SourcePosition in com.sun.mirror.declaration

      Methods in com.sun.mirror.declaration that return SourcePosition
      Modifier and Type Method and Description
      SourcePosition Declaration.getPosition()
      Deprecated.
      Returns the source position of the beginning of this declaration.
      SourcePosition AnnotationValue.getPosition()
      Deprecated.
      Returns the source position of the beginning of this annotation value.
      SourcePosition AnnotationMirror.getPosition()
      Deprecated.
      Returns the source position of the beginning of this annotation.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.util.SourcePositions (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.util.SourcePositions

  • Packages that use SourcePositions
    Package Description
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of SourcePositions in com.sun.source.util

      Methods in com.sun.source.util that return SourcePositions
      Modifier and Type Method and Description
      abstract SourcePositions Trees.getSourcePositions()
      Gets a utility object for obtaining source positions.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Substitution by Serializable Classes

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Serialization and the writeReplace/readResolve Methods

Source Files

The following source file is provided:

Substitute.java

Additional Information

Running the Example
Abstract
List of Examples
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java 2D API Specification

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java 2DTM API Specification

The following list contains all of the packages and classes included in the Java 2D API. Each item in the list is linked to its API documentation.
  • java.awt.color
    Provides classes for color spaces and color profiles based on the ICC Profile Format Specification.
  • java.awt.font
    Provides classes and interfaces relating to fonts and support for representing Type 1, Type 1 Multiple Master, OpenType, and TrueType fonts.
  • java.awt.geom
    Provides classes for defining and performing operations on two-dimensional geometric objects.
  • java.awt.image
    Provides classes for creating and modifying images, as well as image producers, consumers and filters for configuring image processing.
  • java.awt.print
    Provides classes and interfaces for printing two-dimensional objects and includes support for specifying document types, controlling page setup and page formats, and managing job control dialogs.
  • javax.print
    Provides the principal classes and interfaces for the Java Print Service API.
  • java.awt.image.renderable
    Provides classes and interfaces for producing rendering-independent images.

The java.awt package also includes classes that are part of the Java 2D API:

  • java.awt - Contains classes for generating user interfaces and painting graphics and images. The following java.awt classes are part of the Java 2D API.
    • java.awt.AlphaComposite
    • java.awt.BasicStroke
    • java.awt.Color
    • java.awt.Composite
    • java.awt.CompositeContext
    • java.awt.Font
    • java.awt.FontMetrics
    • java.awt.GradientPaint
    • java.awt.Graphics
    • java.awt.Graphics2D
    • java.awt.GraphicsConfigTemplate
    • java.awt.GraphicsConfiguration
    • java.awt.GraphicsDevice
    • java.awt.GraphicsEnvironment
    • java.awt.Image
    • java.awt.ImageCapabilities
    • java.awt.MediaTracker
    • java.awt.PageAttributes and its nested classes
    • java.awt.Paint
    • java.awt.PaintContext
    • java.awt.Point
    • java.awt.Polygon
    • java.awt.Rectangle
    • java.awt.RenderingHints and its nested class
    • java.awt.Shape
    • java.awt.Stroke
    • java.awt.TexturePaint
    • java.awt.Toolkit
    • java.awt.Transparency

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Special Applet Attributes

Applets have default attributes associated with them. Special attributes like image and boxmessage can be associated with applets and used for customizing the applet window during downloading of an applet. JavaBeans component can also be customized using these special attributes. This section discusses the following :

  • Default Appearance of Applets
  • Special Attributes of Applets
  • Applet Attribute Precedence
  • Troubleshooting Scenario

Default Appearance of Applets

The def ault appearence of a Applet when no special attributes are used is as follows:

  • The Java logo is centered in the applet's space.
  • There is a white glow (circle with hazy edge) encircling the Java brand.
  • The rotating burst animation shows that activity is occuring.
  • The progress bar is located below the bottom edge of the Java brand graphic to show the progress as the applet is downloaded.
  • Depending on the size of the applet's viewing area the default appearance will vary.
  • The design of animation will scale to accomodate different "width-by-height" combinations.
  • When the mouse is moved over the applet's area during the loading period, the cursor changes to the normal hypertext cursor indicating that this element is an interactive part of the web page.
  • Clicking/selecting anywhere within the Gray Box will spawn a new browser window pointing to the www.java.com web page.

Special Attributes of Applets

image

The image attribute allows you to replace the default animation with a custom graphic. The format with the standard APPLET element is:

<APPLET ...>
<PARAM name="image" value="my_image.gif">
</APPLET>

See Using OBJECT, EMBED and APPLET Tags in Java Plug-in for how this would be mapped to the OBJECT or the EMBED tags.

If a custom graphic is specified, it should be the same size as the area of the applet window. If these sizes do not match, the graphic will be placed in the upper left corner of the area specified for applet. If it is larger than the applet window, part of it will get chopped off. If it is smaller than the applet window, white, or whatever color is specified for boxbgcolor, will appear around it.

The image can be either a GIF or JPEG, and it should reside in the same directory where other resources for the applet reside; i.e., if the applet uses the codebase attribute, then this image should be in the codebase directory.

Note: The image file should not be in a packaged jar file with other applet resources, since the image needs to be displayed while downloading resources.

The status bar of the browser will display "Loading Java Applet ..." when the mouse is pointed at the applet window.

boxmessage

With the boxmessage attribute you can customize the text displayed in the status bar of the browser. This attribute will be in effect when image attribute is used. The format for using this with the standard APPLET element is:

<APPLET ...>
<PARAM name="boxmessage" value="<your custom message goes here>">
</APPLET>

boxbgcolor, boxfgcolor

These attributes can be used to customize colors in the applet window.

These attributes will be in effect when the image attribute is used. Custom colors cannot be specified for the default appearance of the applet viewing area.

By default the applet window background color is white. The attribute boxbgcolor can be used to specify a different background color. The format for use with the standard APPLET element is:

<APPLET ...>
<PARAM name="boxbgcolor" value="<value>">
</APPLET>

where <value> may be:

  • any Color from java.awt.Color;
  • r,g,b where r, g, and b are integers in the range of 0-255 that would render an opaque standard RGB (sRGB) color in the Color constructor Color(int r, int g, int b);
  • standard HTML colors: silver, green, maroon, purple, navy, teal, and olive; or
  • hexadecimal color format

Examples of each item above:
value="cyan",
value="111,222,145",
value="silver",
value="#33FF33"

By default the applet window foreground color is black. The attribute boxfgcolor can be used to specify a different foreground color. The color values are the same as described above. The format for use with the standard APPLET element is:

<APPLET ...>
<PARAM name="boxfgcolor" value="<value>">
</APPLET>

Applet Attribute Precedence

The order of precedence for these attributes in applets is as follows:

1) If no parameters are provided, the default appearance described above is used.
2) If a custom graphic is specified via the image attribute, then the custom graphic will appear as described above under image.
3) If custom text is provided via the boxmessage attribute, then custom text will be displayed as described above under boxmessage.

With any combination of image and boxmessage attributes, custom colors can always be provided via the boxbgcolor and boxfgcolor attributes.

Troubleshooting Scenario

If an applet fails to load the following actions are performed:

  • The applet window displays error information.
  • The applet window has a single pixel border using white for the foreground color, and a small "broken" graphic will occupy the upper left corner.

The user can click in the applet window to get a popup menu to open one of the following options:

  • Open the Java Console
  • Open a window with information about the Java VM and Java Plug-in.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Improvements to Program Execution Speed

Enhancements in JDK 6

Descriptions of the many performance enhancements in JDK 6 can be found on the performance web site in the Java SE 6 Performance Whitepaper .

Enhancements in JDK 5.0

The following are some of the enhancements made for improved program execution speed in JDK 5.0.
  • Garbage collection ergonomics - Provides for the automatic detection and choice of the client or server runtime compiler, which enhances performance on server-class machines. See "Server-Class Machine Detection" and "Garbage Collection Ergonomics" at Java Virtual Machines for more information.
  • StringBuilder class - The addition of a new class StringBuilder that works essentially as an unsynchronized StringBuffer for performance enhancement. You should replace all StringBuffer uses with StringBuilder unless you need the synchronization (which you almost certainly don't). StringBuilder is almost always faster than StringBuffer.
  • Java 2D™ technology - These Java 2D performance enhancements have spin-off performance benefits in other areas of functionality such as Swing/JFC. Examples include improved acceleration for BufferedImage objects, support for hardware-accelerated rendering using OpenGL, and improved text-rendering performance. See New Java 2D Features for more information.
  • Image I/O - Performance and memory usage improvements have been made when reading and writing JPEG images. See "Improved Performance" at Image I/O Features.

Enhancements in J2SDK 1.4

The following are some of the enhancements made for improved program execution speed in J2SDK 1.4.
  • Java 2D™ technology - These Java 2D performance enhancements have spin-off performance benefits in other areas of functionality such as Swing/JFC. One example of performance improvement in J2SDK 1.4 is that remote X display on Solaris is greatly improved. See New Java 2D Features for more information on Java 2D enhancements, including performance enhancements.
  • java.nio - The New I/O API provides for improved performance in the areas of buffer management, scalable network and file I/O, character-set support, and regular-expression matching. The New I/O APIs supplement the I/O facilities in the java.io package. For more information, see I/O APIs.
  • Reflection - Beginning with J2SDK 1.4.0, certain reflective operations, specifically java.lang.reflect.Field, java.lang.reflect.Method.invoke(), java.lang.reflect.Constructor.newInstance(), and Class.newInstance(), have been rewritten for higher performance. Reflective invocations and instantiations are several times faster than in previous releases.
  • Networking - The networking functionality in J2SDK 1.4 has improved performance for Http streaming.
  • java.math - New static method probablePrime has been added to class BigInteger for generating prime numbers. Previously, the sole means of generating a prime BigInteger required the caller to provide a 'certainty' (the log of the probability of compositeness that the caller was willing to tolerate). However, providing an unreasonable value for the certainty could lead to poor performance (if the certainty was too high) or serious bugs (if it was too low). The new prime-generation method provides an efficient algorithm for generating primes using an automatically determined, appropriate value for the certainty based on a draft ANSI specification (X9-80).
  • Hotspot - The Java HotSpot[TM] virtual machine now uses "full-speed debugging". In the previous version of HotSpot, when debugging was enabled, the program executed using only the interpreter. Now, the full performance advantage of HotSpot Technology is available to programs running with debugging enabled. The improved performance allows long running programs to be more easily debugged. It also allows testing to proceed at full speed and the launch of a debugger to occur on an exception.

Enhancements in J2SDK 1.3

The following are some of the changes made to improve the program execution speed and general runtime performance in previous release J2SDK 1.3. These enhancements have been carried forward into J2SDK 1.4.

Links to relevant bug reports on the Bug Database web site are provided were applicable for further information.

  • Improved Performance for readUTF and writeUTF - The implementations of the readUTF and writeUTF methods of DataInputStream and DataInputStream have been modified to improve performance. This is a fix for bug number 4219771 on the Bug Database web site.
  • Improved Performance of JScrollPane Painting - The implementation of JScrollPane has been improved so that it does not cause excessive painting and screen flashing when double buffering is not used.
  • Improved JTable Performance - The performance of the JTable's column-handling functionality has been improved. Previously, the performance of the operations of adding columns or recalculating column widths did not scale well as the number of columns became large. The implementation has been changed to improve scalability. This is a fix for bug number 4223642 on the Bug Database web site.
  • Paint Coalescing - Painting performance has been enhanced through the implementation of an improved paint coalescing algorithm. Areas that require repainting are coalesced into a single, non-rectangular repaint area as they are posted to the event queue. This has the effect batching repaints, executing multiple repaints simultaneously in a manner more efficient than in previous releases.
  • Frame Resizing - Resizing of top-level frames has been improved.
  • Internal Frame Blitting - By using Graphics.copyArea calls, Swing's DefaultDesktopManager now needs to redraw far less when frames are dragged.
  • Performance Enhancements in BigIntenger - Class java.math.BigInteger has been reimplemented in pure Java programming-language code. Previously, BigInteger's implementation was based on the Plumb C library. The new implementation performs all standard operations much faster than the old implementation. The speed-up realized in the new implemenation can be as much as 5x or more, depending on the operation being performed.
  • Provision for Better-Performing Numeric Operations - The Java 2 Platform now contains two classes which provide API for performing general numeric operations.
    • java.lang.StrictMath - Class java.lang.StrictMath is a renaming of class java.lang.Math from previous versions of the Java platform, but otherwise retains the previous specification of Math. In particular, it is defined to return bit-for-bit reproducible results in all implementations.
    • java.lang.Math - Class java.lang.Math provides the same set of API as does class StrictMath. However, unlike some of the numeric functions of class StrictMath, all implementations of the equivalent functions of class Math are not defined to return the bit-for-bit same results, but can vary within specified constraints. This relaxation permits better-performing implementations where strict reproducibility is not required.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Appendix A: Service Provider Example

This appendix contains a simple service provider. It implements a flat namespace (with no federation support). It shows how to produce a context implementation by providing all the methods in the Context interface.

An instance of this context is bound directly as the initial context. This example provides the corresponding InitialContextFactory definition.

A.1 Simple Flat Context

A.1.1 Context Implementation

/*
 * @(#)FlatCtx.java     1.3 99/07/26
 *
 * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
package examples.spi.flat;

import javax.naming.*;
import java.util.*;

/**
 * A sample service provider that implements a flat namespace in memory.
 */

class FlatCtx implements Context {
    Hashtable myEnv;
    private Hashtable bindings = new Hashtable(11);
    static NameParser myParser = new FlatNameParser();

    FlatCtx(Hashtable environment) {
        myEnv = (environment != null)
            ? (Hashtable)(environment.clone())
            : null;
    }

    public Object lookup(String name) throws NamingException {
        if (name.equals("")) {
            // Asking to look up this context itself.  Create and return
            // a new instance with its own independent environment.
            return (new FlatCtx(myEnv));
        }
        Object answer = bindings.get(name);
        if (answer == null) {
            throw new NameNotFoundException(name + " not found");
        }
        return answer;
    }

    public Object lookup(Name name) throws NamingException {
        // Flat namespace; no federation; just call string version
        return lookup(name.toString());
    }

    public void bind(String name, Object obj) throws NamingException {
        if (name.equals("")) {
            throw new InvalidNameException("Cannot bind empty name");
        }
        if (bindings.get(name) != null) {
            throw new NameAlreadyBoundException(
                    "Use rebind to override");
        }
        bindings.put(name, obj);
    }

    public void bind(Name name, Object obj) throws NamingException {
        // Flat namespace; no federation; just call string version
        bind(name.toString(), obj);
    }

    public void rebind(String name, Object obj) throws NamingException {
        if (name.equals("")) {
            throw new InvalidNameException("Cannot bind empty name");
        }
        bindings.put(name, obj);
    }

    public void rebind(Name name, Object obj) throws NamingException {
        // Flat namespace; no federation; just call string version
        rebind(name.toString(), obj);
    }

    public void unbind(String name) throws NamingException {
        if (name.equals("")) {
            throw new InvalidNameException("Cannot unbind empty name");
        }
        bindings.remove(name);
    }

    public void unbind(Name name) throws NamingException {
        // Flat namespace; no federation; just call string version
        unbind(name.toString());
    }

    public void rename(String oldname, String newname)
            throws NamingException {
        if (oldname.equals("") || newname.equals("")) {
            throw new InvalidNameException("Cannot rename empty name");
        }

        // Check if new name exists
        if (bindings.get(newname) != null) {
            throw new NameAlreadyBoundException(newname +
                                                " is already bound");
        }

        // Check if old name is bound
        Object oldBinding = bindings.remove(oldname);
        if (oldBinding == null) {
            throw new NameNotFoundException(oldname + " not bound");
        }

        bindings.put(newname, oldBinding);
    }

    public void rename(Name oldname, Name newname)
            throws NamingException {
        // Flat namespace; no federation; just call string version
        rename(oldname.toString(), newname.toString());
    }

    public NamingEnumeration list(String name)
            throws NamingException {
        if (name.equals("")) {
            // listing this context
            return new FlatNames(bindings.keys());
        }

        // Perhaps `name' names a context
        Object target = lookup(name);
        if (target instanceof Context) {
            return ((Context)target).list("");
        }
        throw new NotContextException(name + " cannot be listed");
    }

    public NamingEnumeration list(Name name)
            throws NamingException {
        // Flat namespace; no federation; just call string version
        return list(name.toString());
    }

    public NamingEnumeration listBindings(String name)
            throws NamingException {
        if (name.equals("")) {
            // listing this context
            return new FlatBindings(bindings.keys());
        }

        // Perhaps `name' names a context
        Object target = lookup(name);
        if (target instanceof Context) {
            return ((Context)target).listBindings("");
        }
        throw new NotContextException(name + " cannot be listed");
    }

    public NamingEnumeration listBindings(Name name)
            throws NamingException {
        // Flat namespace; no federation; just call string version
        return listBindings(name.toString());
    }

    public void destroySubcontext(String name) throws NamingException {
        throw new OperationNotSupportedException(
                "FlatCtx does not support subcontexts");
    }

    public void destroySubcontext(Name name) throws NamingException {
        // Flat namespace; no federation; just call string version
        destroySubcontext(name.toString());
    }

    public Context createSubcontext(String name)
            throws NamingException {
        throw new OperationNotSupportedException(
                "FlatCtx does not support subcontexts");
    }

    public Context createSubcontext(Name name) throws NamingException {
        // Flat namespace; no federation; just call string version
        return createSubcontext(name.toString());
    }

    public Object lookupLink(String name) throws NamingException {
        // This flat context does not treat links specially
        return lookup(name);
    }

    public Object lookupLink(Name name) throws NamingException {
        // Flat namespace; no federation; just call string version
        return lookupLink(name.toString());
    }

    public NameParser getNameParser(String name)
            throws NamingException {
        return myParser;
    }

    public NameParser getNameParser(Name name) throws NamingException {
        // Flat namespace; no federation; just call string version
        return getNameParser(name.toString());
    }

    public String composeName(String name, String prefix)
            throws NamingException {
        Name result = composeName(new CompositeName(name),
                                  new CompositeName(prefix));
        return result.toString();
    }

    public Name composeName(Name name, Name prefix)
            throws NamingException {
        Name result = (Name)(prefix.clone());
        result.addAll(name);
        return result;
    }

    public Object addToEnvironment(String propName, Object propVal)
            throws NamingException {
        if (myEnv == null) {
            myEnv = new Hashtable(5, 0.75f);
        }
        return myEnv.put(propName, propVal);
    }

    public Object removeFromEnvironment(String propName)
            throws NamingException {
        if (myEnv == null)
            return null;

        return myEnv.remove(propName);
    }

    public Hashtable getEnvironment() throws NamingException {
        if (myEnv == null) {
            // Must return non-null
            return new Hashtable(3, 0.75f);
        } else {
            return (Hashtable)myEnv.clone();
        }
    }

    public String getNameInNamespace() throws NamingException {
        return "";
    }

    public void close() throws NamingException {
        myEnv = null;
        bindings = null;
    }

    // Class for enumerating name/class pairs
    class FlatNames implements NamingEnumeration {
        Enumeration names;

        FlatNames (Enumeration names) {
            this.names = names;
        }

        public boolean hasMoreElements() {
            return names.hasMoreElements();
        }

        public boolean hasMore() throws NamingException {
            return hasMoreElements();
        }

        public Object nextElement() {
            String name = (String)names.nextElement();
            String className = bindings.get(name).getClass().getName();
            return new NameClassPair(name, className);
        }

        public Object next() throws NamingException {
            return nextElement();
        }
        public void close() {
        }
    }

    // Class for enumerating bindings
    class FlatBindings implements NamingEnumeration {
        Enumeration names;

        FlatBindings (Enumeration names) {
            this.names = names;
        }

        public boolean hasMoreElements() {
            return names.hasMoreElements();
        }

        public boolean hasMore() throws NamingException {
            return hasMoreElements();
        }

        public Object nextElement() {
            String name = (String)names.nextElement();
            return new Binding(name, bindings.get(name));
        }

        public Object next() throws NamingException {
            return nextElement();
        }
        public void close() {
        }
    }
};

A.1.2 Name Parser

/*
 * @(#)FlatNameParser.java      1.3 99/07/26
 *
 * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
package examples.spi.flat;

import javax.naming.NameParser;
import javax.naming.Name;
import javax.naming.CompoundName;
import javax.naming.NamingException;
import java.util.Properties;

class FlatNameParser implements NameParser {

    static Properties syntax = new Properties();
    static {
        syntax.put("jndi.syntax.direction", "flat");
        syntax.put("jndi.syntax.ignorecase", "false");
    }
    public Name parse(String name) throws NamingException {
        return new CompoundName(name, syntax);
    }
}

A.1.3 Initial Context Factory

/*
 * @(#)FlatInitCtxFactory.java  1.3 99/07/26
 *
 * Copyright (c) 1997, 1999, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
package examples.spi.flat;

import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.spi.InitialContextFactory;

public class FlatInitCtxFactory implements InitialContextFactory {

    public Context getInitialContext(Hashtable env) {
        return new FlatCtx(env);
    }
}

[Top] [Prev] [Next] [Bottom]
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Input Method Engine SPI Reference

The following classes are part of the input method engine SPI:

  • java.awt.im.spi
    • Package Specification
    • java.awt.im.spi.InputMethod
    • java.awt.im.spi.InputMethodDescriptor
    • java.awt.im.spi.InputMethodContext
  • java.awt.im
    • java.awt.im.InputMethodHighlight
    • java.awt.im.InputMethodRequests
    • java.awt.im.InputSubset
  • java.awt.event
    • java.awt.event.InputMethodEvent

    In addition, the following classes and members in other frameworks support the input method engine SPI:

  • java.awt.font
    • java.awt.font.TextAttribute
      • INPUT_METHOD_UNDERLINE
      • UNDERLINE_LOW_ONE_PIXEL
      • UNDERLINE_LOW_TWO_PIXEL
      • UNDERLINE_LOW_DOTTED
      • UNDERLINE_LOW_GRAY
      • UNDERLINE_LOW_DASHED
  • java.lang
    • java.lang.Character.Subset
  • java.text
    • java.text.Annotation
    • java.text.AttributedCharacterIterator
    • java.text.AttributedCharacterIterator.Attribute
    • java.text.AttributedString
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Input Method Engine SPI Tutorial

Contents

  1. Introduction
  2. Describing the Input Method
  3. Communicating with the Client Component
  4. Using Input Method Windows
  5. Implementing Composition
  6. Providing Engine-Specific Functionality
  7. Packaging the Input Method
  8. Sample Code

1. Introduction

The input method engine SPI enables the development of input methods in the Java programming language that can be used with any Java 2 runtime environment. As far as the input method framework is concerned, an input method consists of two classes implementing the InputMethodDescriptor and InputMethod interfaces, packaged with some additional information as an extension and installed into a Java runtime. The specifications for the java.awt.im.spi package, and the InputMethodDescriptor and InputMethod interfaces provide the core information that's needed to implement an input method. This tutorial provides additional information that makes this task a little easier and helps avoid compatibility problems between different implementations of the Java 2 platform.

2. Describing the Input Method

Before the input method framework can start using an input method, it needs to know about its capabilities. The necessary information is provided by the input method's implementation of the InputMethodDescriptor class. This information is used in selecting input methods.

The list of available locales returned by getAvailableLocales should only return languages that the input method is really designed for. For example, a Chinese Pinyin input method that produces simplified Chinese characters should only return SIMPLIFIED_CHINESE, even if it has a mode that simply lets key events pass through and thus also makes it possible to write English or Malay. The InputMethod.setLocale method on the other hand may return true for a larger set of languages. The reason is that getAvailableLocales is used to decide whether to load and switch to an input method, which is only worthwhile if the input method handles the language well, while setLocale is used to decide whether to switch away from an input method, which is only worthwhile if the input method doesn't handle the language at all.

3. Communicating with the Client Component

When an input method instance is created, it receives an InputMethodContext instance through setInputMethodContext. This instance provides it with all the functionality that it needs to communicate with the input method framework, the client component, or the composition window. It lets the input method send information about composed and committed text using the dispatchInputMethodEvent method. And it lets the input method request information from the client component using the methods it inherits from the InputMethodRequests interface.

The input method framework provides the input method with an environment that makes it seem like it is always communicating with an active client component using the on-the-spot input style. If the actual client component is not an active client, or if a different input style is used, then the framework redirects events and requests as needed.

The input method should never try to access the client component directly, as doing so would conflict with the framework's switching and redirection functionality. Instead, the input method should always use the methods provided by its input method context.

4. Using Input Method Windows

Input methods may use a number of different windows to communicate with the user. Windows commonly used by input methods include:

  • a look-up window, which shows several possible interpretations of the user's input and lets the user choose the correct one.
  • a status window, which provides the user with information about the current state of the input method, such as the selected language or target character set.
  • a control panel (often combined with the status window), which lets the user change the input method's state, such as selecting a different language or target character set.
  • a preferences window, which lets the user tailor the input method to his or her needs.
  • a dictionary editor window, which lets the user add or correct conversions.

Note: On some other platforms, input methods may also provide a composition window, which shows the composed text. In the Java input method framework, composed text is always displayed by the client component or the input method framework, never by the input method.

It is useful to consider three groups of windows:

  • transient windows: these windows pop up for short times during a composition operation. Their functionality is tied to a specific composition. Opening, closing, positioning, and sizing are usually automatic since any user interaction with the windows themselves would distract from the composition. In particular, transient windows are always closed when the composition operation ends or is interrupted. Examples: look-up window.
  • persistent windows: these windows tend to stay around for extended periods of time, possibly for as long as the user is using the input method. Their functionality may be tied to the currently active instance of the input method, or to the input method class. Usually the user can actively open, close, position, and possibly resize these windows, although they are always automatically closed when switching to a different input method, and in some cases they're automatically positioned relative to the window containing the current client component. Examples: status window, control panel.
  • document windows: these are just regular windows. Their functionality is not tied to composition. The user fully controls opening, closing, positioning, and possibly sizing of these windows. Examples: dictionary editor window.

Here's how these window groups can be handled by input methods written for the Java 2 platform:

  • transient windows are created using InputMethodContext.createInputMethodWindow, typically with attachToInputContext set to true. They are opened either in the input method's implementation of activate, or later when needed to respond to user input. They are closed in the input method's implementations of deactivate or hideWindows, or earlier if they are no longer needed.
  • persistent windows are created using InputMethodContext.createInputMethodWindow, with attachToInputContext set to false. They are typically opened in the input method's implementation of activate and closed in the input method's implementation of hideWindows.
  • document windows are created as regular AWT windows, and opening and closing them is usually under user control.

Note that the focus behavior of a window created by createInputMethodWindow is implementation dependent. It may never get the focus, it may get the focus when initially made visible, or it may get the focus when the user clicks into it. An input method must be able to handle either case.

To position windows (such as the look-up window) automatically relative to the composed text, the input method can use the input method context's getTextLocation method. To position windows (such as a status window) automatically relative to the window containing the current client component, the input method can register for notifications about that window's location and state using the input method context's enableClientWindowNotification method; it then has to implement the notifyClientWindowChange method to receive notifications.

Input methods must call Window.dispose for all windows they create when they are no longer needed. This ensures that the JVM exits when the application terminates all non-daemon threads it started. Please refer to AWT Threading Issues for more information.

5. Implementing Composition

The main task of an input method is interpreting user actions in composing text input. The user actions may be typing on the keyboard, using the mouse, handwriting, or speaking.

The activate and deactivate methods indicate to the input method whether a client component has the focus and therefore is the target of text input. Typically input methods only process events to compose text while they're active.

When an input method is active, certain types of events are dispatched to the input method using the dispatchEvent method before they are processed by the client component. The input method decides for each event whether it wants to handle it. If it does, it marks the event as consumed so that it is not processed by the client component.

Note: For key events, input methods should use only KEY_TYPED events to obtain information about characters being entered, and use KEY_PRESSED or KEY_RELEASED events only to obtain information about function keys that don't result in KEY_TYPED events. The mapping from key-presses to characters depends on platforms, hardware, locales, and possibly other factors, and is best left to the underlying operating system.

As text is being composed and committed, the input method needs to inform the client component about all changes so that the client component can redraw the text. The input method does this by using InputMethodContext.dispatchInputMethodEvent to construct and dispatch input method events to the client component. Depending on the current event flow model, the input method framework may redirect the events to its composition window. Dispatching input method events is the only way for Java input methods to have composed text displayed.

Composed text is usually marked up with highlight styles that indicate the current state of the conversion. This is accomplished by adding attributes to the text using the TextAttribute.INPUT_METHOD_HIGHLIGHT key and instances of InputMethodHighlight as values. Normally input methods only define abstract highlights (using the state and selected properties of the input method highlight) and leave the mapping to concrete styles to the rendering system. However, if desired, input methods can add concrete style information to the highlight using the style property. It is a good idea to design the concrete styles as variations of the styles provided returned by Toolkit.mapInputMethodHighlight.

Both the client component and the input method framework may recognize situations where the current composition needs to be ended and all composed text either committed or cancelled. They inform the input method about this need using the endComposition method. Note that endComposition may be called while the input method is not active.

Client components can influence composition using several methods. The InputContext.setCharacterSubsets method lets them restrict the subset of the Unicode character set that the input method is allowed to input. Input methods should generally not create characters outside of the specified subsets, and may switch to a different input mode that particularly supports the specified character subsets. The InputContext.setCompositionEnabled and isCompositionEnabled methods let them control and examine whether the current input method is enabled for composition. The InputContext.reconvert method lets them initiate reconversion.

6. Providing Engine-Specific Functionality

Some input methods may want to provide functionality to client components that can not be made available through the input method framework API. This is possible through input method control objects. The input method developer must publish an interface for these objects, and return instances through InputMethod.getControlObject. Client components that want to take advantage of the additional functionality can then call InputContext.getInputMethodControlObject, check whether the returned object is an instance of a known control object class, and if it is, call its methods.

7. Packaging the Input Method

Input methods are packaged as installed extensions with specific content as described in the "Packaging Input Methods" section of the SPI specification. One important aspect to consider is that all extensions installed in a Java application environment share the same name space. To avoid name collisions, input methods should follow the package naming conventions as described in the Java Language Specification. Similar conventions should be applied to naming non-class files that are packaged in the input method JAR file, such as dictionaries.

8. Sample Code

City Input Method is a simple input method that shows how to use the interfaces provided by the input method engine SPI.

  • City Input Method documentation - tells you how to install and use this input method.
  • City Input Method - a jar file containing the input method. Some browsers will automatically offer to download this file; others will show its contents in a window (not a pretty sight), and you then have to use the Save command to write it into a file. See the documentation for installation instructions.
  • CityInputMethodDescriptor.java - the InputMethodDescriptor implementation for this input method.
  • CityInputMethod.java - the InputMethod implementation for this input method.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
[Top] [Prev] [Next] [Bottom]

Java Naming and Directory Interface TM
Service Provider Interface
(JNDI SPI)

Please send technical comments to

jndi@java.sun.com

Please send product and business questions to

jndi-business@java.sun.com.

JNDI 1.2/JavaTM 2 Platform, Standard Edition, v 1.3
July 14, 1999

[Top] [Prev] [Next] [Bottom]
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JSpinner - A Simple Sequence Container

This document describes the new Swing component, JSpinner.

One of the most commonly requested new Swing components is a spinner - a single line input field that lets the user select an number or an object value from an ordered set. Spinners typically provide a pair of tiny arrow buttons for stepping through the possible values, the up/down arrow keys also cycle through the values. The user may also be allowed to type a (legal) value directly into the spinner. Although combo boxes provide similar functionality, spinners are sometimes preferred because they don't require a drop down list that can obscure important data.

The bugtraq report that corresponds to this change is: 4290529.

A Short Catalog of Spinners

Spinners are common in modern GUIs. Here are some examples from some popular look and feels and from OpenWindows:

Windows spinner | CDE/Motif spinner | JLF spinner | Mac Aqua spinner | OpenWindows spinner
Windows | CDE/Motif | JLF | Mac Aqua | OpenWindows

All of the spinners deliver very simple behavior: clicking on the arrow buttons changes the fields value and, when the spinner has the focus, the keyboard up and down arrow keys do the same. In some applications the spinners up or down arrow button is disabled when the upper or lower limit of the spinner has been reached, in other cases the spinner just resets its value to the opposite extreme.

JSpinner, SpinnerModel, SpinnerListModel

The JSpinner class is a simple Swing container that manages three children: two arrow buttons and a single component, called the editor that displays the spinner's value. The value displayed by the spinner is encapsulated by model of a sequence of objects called a SpinnerModel.

public interface SpinnerModel {
    Object getValue();
    void setValue(Object);
    Object getNextValue();
    Object getPreviousValue();
    void addChangeListener(ChangeListener x);
    void removeChangeListener(ChangeListener x);}

The SpinnerModel interface is similar to ListModel - they both represent a sequence a values - however there are some important differences:

  • The model doesn't support random access to sequence elements. Only three sequence values are accessible at a time: current, next and previous.
  • The number of sequence elements isn't necessarily bounded so there's no sequence length returning size method.
  • The model's value property is read/write, unlike the elements of a ListModels sequence, which are read-only. This difference reflects the different roles of JList and JSpinner. The former was designed to simplify selecting one or more items from a list and the latter for entering a single value directly.

The relationship between the JSpinner and its model is simple. The editor component monitors the model with a ChangeListener and always displays the object returned by SpinnerModel.getValue(). The up and down arrow buttons update the value by calling setValue(getNextValue()) or setValue(getPreviousValue()) respectively. The getNextValue and getPreviousValue methods return null when the end or the beginning of the sequence has been reached, so the arrow button actions have to check for null before updating the models value. If the editor is a writable field of some kind, it's responsible for honoring the constraints defined by the model or handling the IllegalArgumentException thrown by setValue for invalid values.

The SpinnerListModel provides support for two common mutable sequence types: java.util.List, and an array of objects. For example to create a JSpinner that lets the user choose a day of the week in the default locale one could write:

    String[] days = new DateFormatSymbols().getWeekdays();
    SpinnerModel model = new SpinnerListModel(days);
    JSpinner spinner = new JSpinner(model);

In addition to initializing the model property of the spinner, these constructors create an editor component that displays the SpinnerModel's value and can be used to change it. The protected JSpinner.createEditor method is used for this and, by default, it creates a JFormattedTextField that has been configured to display the model.

To find or initialize a spinners current value one can either use the models value property or use the convenience JSpinner value property which just delegates to the model. For example, using the spinner configured in the example above, the following two statements are equivalent:

    String selectedDay = spinner.getModel().getValue().toString();
    String selectedDay = spinner.getValue().toString();

Setting the spinner's value is similar. Attempts to set the SpinnerModel value to an object that the model doesn't support cause an IllegalArgumentException to be thrown.

Dates and numbers are two of the most common applications for a spinner component. To simplify spinning these types, two additional SpinnerModel implementation classes are provided: SpinnerDateModel and SpinnerNumberModel.

SpinnerDateModel

One of the most common uses of a spinner is to compactly present an editable date. Here's a simple example of creating a JSpinner that allows the user to enter a (fully localized) date:

    SpinnerDateModel model = new SpinnerDateModel();
    JSpinner spinner = new JSpinner(model);
    Date value = model.getDate();

In this example, the JSpinner constructor has created a JFormattedTextField editor that's configured for editing dates and it has added a ChangeListener to the SpinnerDateModel to keep the editor and the model in sync.

Here's the SpinnerDateModel API. We've added three new read/write properties: start, end, and stepSize and a read-only date property that returns the models value cast to a Date.

public class SpinnerDateModel extends AbstractSpinnerModel {
    public SpinnerDateModel(Date value, Comparable start, Comparable end, int stepSize)
    public SpinnerDateModel()
    public void setStart(Comparable start)
    public Comparable getStart()
    public void setEnd(Comparable end)
    public Comparable getEnd()
    public Object getNextValue()
    public Object getPreviousValue()
    public Date getDate()
    public Object getValue()
    public void setValue(Object value)}

The startDate and endDate properties can be null to indicate that there is no lower or upper limit. The no-arguments SpinnerDateModel constructor initializes both the start and end date to null, the initial value of the model is the current date.

The value of the stepSize property must be one of the java.util.Calendar constants that specify a field within a Calendar. The getNextValue and getPreviousValue methods change the date forward or backwards by this amount. For example, if stepSize is Calendar.DAY_OF_WEEK, then nextValue produces a Date that's 24 hours after the current value, and previousValue produces a Date that's 24 hours earlier.

The legal values for stepSize are:

  • Calendar.ERA
  • Calendar.YEAR
  • Calendar.MONTH
  • Calendar.WEEK_OF_YEAR
  • Calendar.WEEK_OF_MONTH
  • Calendar.DAY_OF_MONTH
  • Calendar.DAY_OF_YEAR
  • Calendar.DAY_OF_WEEK
  • Calendar.DAY_OF_WEEK_IN_MONTH
  • Calendar.AM_PM
  • Calendar.HOUR
  • Calendar.HOUR_OF_DAY
  • Calendar.MINUTE
  • Calendar.SECOND
  • Calendar.MILLISECOND

The default SpinnerDateModel editor adjusts the stepSize property based on the text cursor position. For example if the cursor moves into the editor's month subfield then the incrementSize would be changed to Calendar.DAY_OF_MONTH.

SpinnerNumberModel

Spinners are often used to present editable integers and real numbers that represent everything from temperature to stock prices. The SpinnerNumberModel provides basic support for all of the basic Java Number types, from Byte to Double.

To create a spinner that allows the user to pick a real multiple of 1/8 between 0.0 and 1000.0, with an initial value of 500.0, one could write:

    SpinnerNumberModel model = new SpinnerNumberModel(500.0, 0.0, 1000.0, 0.625);
    JSpinner spinner = new JSpinner(model);
    double value = model.getNumber().doubleValue();

In this example, the JSpinner constructor has created a JFormattedTextField editor that's configured for editing real numbers and it has added a ChangeListener to the SpinnerNumberModel to keep the editor and the model in sync.

Here's a summary of the SpinnerNumberModel API. We've added three new read/write properties: minimum, maximum, and stepSize and a read-only number property that returns the models value cast to a Number.

public class SpinnerNumberModel extends AbstractSpinnerModel {
    public SpinnerNumberModel(Number value, Comparable minimum, Comparable maximum, Number stepSize)
    public SpinnerNumberModel(int value, int minimum, int maximum, int stepSize)
    public SpinnerNumberModel(double value, double minimum, double maximum, double stepSize)
    public SpinnerNumberModel()
    public void setMinimum(Comparable minimum)
    public Comparable getMinimum()
    public void setMaximum(Comparable maximum)
    public Comparable getMaximum()
    public void setStepSize(Number stepSize)
    public Number getStepSize()
    public Object getNextValue()
    public Object getPreviousValue()
    public Number getNumber()
    public Object getValue()
    public void setValue(Object value)}

As with the SpinnerDateModel, the minimum and maximum properties can be null to indicate that there is no lower or upper limit. The stepSize property just specifies how much to add or subtract from the value to compute the nextValue or the previousValue.

Summary of the Spinner APIs

Support for spinners added six classes and one interface (SpinnerModel) to the javax.swing package:

  • JSpinner
  • SpinnerListModel
  • AbstractSpinnerModel
  • SpinnerDateModel
  • SpinnerModel
  • SpinnerNumberModel

Additionally, SpinnerUI has been added to the javax.swing.plaf package and BasicSpinnerUI to the javax.swing.plaf.basic package:

  • SpinnerUI
  • BasicSpinnerUI
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Using Java RMI with SSL

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Using Java™ RMI with SSL

Many have asked how a Java™ Remote Method Invocation (Java RMI) application can make remote invocations over secure SSL connections. Below are some questions and answers about using Java RMI with SSL.

Q1: Is it possible to use Java RMI with SSL?

A1: Yes, it is possible, with the use of custom socket factories. An application can export a remote object to use custom socket factories that create sockets of a desired type (for example, SSL sockets). Using this technique, an application can use SSL socket communication instead of the default socket communication. For further details on using custom socket factories, see the tutorial: Using Custom Socket Factories with Java RMI.

Q2: Where can I find a pure Java programming language implementation of SSL?

A2: The JDK includes the Java Secure Socket Extension (JSSE) API which provides an implementation of SSL sockets. See the JSSE Reference Guide for more detailed information on the features and benefits of JSSE.

Q3: Where can I find an example using Java RMI with SSL?

A3: There is an example bundled with the JSSE code examples that illustrates how to use SSL-based connections for calls to a remote object. This is achieved by exporting a remote object to use custom socket factories that create SSL sockets. Beginning with the J2SE 5.0 release, the JDK provides some standard SSL-based custom socket factory classes; see the javax.rmi.ssl package for more details.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.StackFrame (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.StackFrame

  • Packages that use StackFrame
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of StackFrame in com.sun.jdi

      Methods in com.sun.jdi that return StackFrame
      Modifier and Type Method and Description
      StackFrame ThreadReference.frame(int index)
      Returns the StackFrame at the given index in the thread's current call stack.
      Methods in com.sun.jdi that return types with arguments of type StackFrame
      Modifier and Type Method and Description
      List<StackFrame> ThreadReference.frames()
      Returns a List containing each StackFrame in the thread's current call stack.
      List<StackFrame> ThreadReference.frames(int start, int length)
      Returns a List containing a range of StackFrame mirrors from the thread's current call stack.
      Methods in com.sun.jdi with parameters of type StackFrame
      Modifier and Type Method and Description
      boolean LocalVariable.isVisible(StackFrame frame)
      Determines whether this variable can be accessed from the given StackFrame.
      void ThreadReference.popFrames(StackFrame frame)
      Pop stack frames.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Doclet Overview

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

The Standard Doclet

Contents

  • What the Standard Doclet Is
  • Running the Standard Doclet from the Command Line
  • Running the Standard Doclet Programmatically
  • The Source for the Standard Doclet

What the Standard Doclet Is

The standard doclet is the doclet provided by Sun™ that produces Javadoc's default HTML-formatted API output. The API documentation for the Java™ platform in this JDK documentation is an example of the standard doclet's output. Javadoc uses the standard doclet if no other doclet is specified using Javadoc's -doclet option on the command line.

Running the Standard Doclet from the Command Line

The standard doclet is invoked by default when no other doclet is specified with the -doclet tag on the command line. For example, running
% javadoc myPackage
will use the standard doclet to produce the default-style HTML API documentation for myPackage. Running javadoc without the -doclet option is equivalent to running javadoc using the -doclet option to invoke the standard doclet. That is, the above command is equivalent to
% javadoc -docletpath /home/user/jdk1.5.0/lib/tools.jar \
  -doclet com.sun.tools.doclets.standard.Standard \
  myPackage
or
% javadoc -docletpath /home/user/jdk1.5.0/lib/tools.jar \
  -doclet com.sun.tools.doclets.formats.html.HtmlDoclet \
  myPackage
Both of these approaches are equivalent.

Running the Standard Doclet Programmatically

The Javadoc tool has a programmatic interface with public methods for invoking the Javadoc tool from another program written in the Java language. These methods are located in class com.sun.tools.javadoc.Main in lib/tools.jar. An example is given below.

The disadvantages of calling main are: (1) It can only be called once per run -- for 1.2.x or 1.3.x, use java.lang.Runtime.exec("javadoc ...") if more than one call is needed, (2) it exits using System.exit(), which exits the entire program, and (3) an exit code is not returned.

public static void main(java.lang.String[] args)
Command line interface.
Parameters:
args - The command line parameters.
The execute method overcomes all the disadvantages of main.
public static int execute(java.lang.String[] args)
Programmatic interface.
Parameters:
args - The command line parameters.
Returns:
The return code.
public static int execute(java.lang.String programName,
                          java.lang.String[] args)
Programmatic interface.
Parameters:
programName - Name of the program (for error messages).
args - The command line parameters.
Returns:
The return code.
public static int execute(java.lang.String programName,
                          java.lang.String defaultDocletClassName,
                          java.lang.String[] args)
Programmatic interface.
Parameters:
programName - Name of the program (for error messages).
defaultDocletClassName - Fully qualified class name.
args - The command line parameters.
Returns:
The return code.
public static int execute(java.lang.String programName,
                          java.io.PrintWriter errWriter,
                          java.io.PrintWriter warnWriter,
                          java.io.PrintWriter noticeWriter,
                          java.lang.String defaultDocletClassName,
                          java.lang.String[] args)
Programmatic interface.
Parameters:
programName - Name of the program (for error messages).
errWriter - PrintWriter to receive error messages.
warnWriter - PrintWriter to receive error messages.
noticeWriter - PrintWriter to receive error messages.
defaultDocletClassName - Fully qualified class name.
args - The command line parameters.
Returns:
The return code.

Example

With classpath set to lib/tools.jar in the Java SE, pass in each option and argument as a separate string:

com.sun.tools.javadoc.Main.execute(new String[] {"-d", "docs", "-sourcepath", "/home/usr/src", "p1", "p2"});

The Source for the Standard Doclet

You can download the source code for the standard doclet as part of the Java SE at:
  • Java SE Source Code Release
    (Note: There is a delay between when the JDK is first available and the source code release is available.)
The source files are located in the directory src/share/classes/com/sun/tools/doclets.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Standard Algorithm Name Documentation

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java™ Cryptography Architecture
Standard Algorithm Name Documentation

for Java Platform Standard Edition 7

  • Standard Names
    • AlgorithmParameterGenerator Algorithms
    • AlgorithmParameters Algorithms
    • CertificateFactory Types
    • CertPathBuilder Algorithms
    • CertPath Encodings
    • CertPathValidator Algorithms
    • CertStore Types
    • Cipher (Encryption) Algorithms
    • Configuration Types
    • Exemption Mechanisms
    • GSSAPI Mechanisms
    • KeyAgreement Algorithms
    • KeyFactory Algorithms
    • KeyGenerator Algorithms
    • KeyManagerFactory Algorithms
    • KeyPairGenerator Algorithms
    • KeyStore Types
    • Mac Algorithms
    • MessageDigest Algorithms
    • Policy Types
    • SaslClient Mechanisms
    • SaslServer Mechanisms
    • SecretKeyFactory Algorithms
    • SecureRandom Number Generation (RNG) Algorithms
    • Service Attributes
    • Signature Algorithms
    • SSLContext Algorithms
    • TrustManagerFactory Algorithms
    • XML Signature (XMLSignatureFactory/KeyInfoFactory/TransformService) Mechanisms
    • XML Signature Transform (TransformService) Algorithms
    • JSSE Cipher Suite Names
    • Additional JSSE Standard Names
  • Algorithms
    • Specification Template
    • Algorithm Specifications
  • Implementation Requirements

Note: The Sun Provider Documentation contains specific provider and algorithm information.

Standard Names

The JDK Security API requires and uses a set of standard names for algorithms, certificate and keystore types. This specification establishes the following names as standard names.

In some cases naming conventions are given for forming names that are not explicitly listed, to facilitate name consistency across provider implementations. Items in angle brackets (such as <digest> and <encryption>) are placeholders to be replaced by a specific message digest, encryption algorithm, or other name.

Note: Standard names are not case-sensitive.

This document includes corresponding lists of standard names relevant to the following security subareas:

  • Java PKI Programmer's Guide
  • JSSE Reference Guide
  • For standard name specifications, See Algorithms.
  • Cryptography Architecture
  • Single Sign-on Using Kerberos in Java
  • The Java SASL API Programming and Deployment Guide
  • The XML Digital Signature API Specification

AlgorithmParameterGenerator Algorithms

The algorithm names in this section can be specified when generating an instance of AlgorithmParameterGenerator.

Algorithm Name | Description
DiffieHellman | Parameters for use with the Diffie-Hellman algorithm.
DSA | Parameters for use with the Digital Signature Algorithm.

AlgorithmParameters Algorithms

The algorithm names in this section can be specified when generating an instance of AlgorithmParameters.

Algorithm Name | Description
AES | Parameters for use with the AES algorithm.
Blowfish | Parameters for use with the Blowfish algorithm.
DES | Parameters for use with the DES algorithm.
DESede | Parameters for use with the DESede algorithm.
DiffieHellman | Parameters for use with the DiffieHellman algorithm.
DSA | Parameters for use with the Digital Signature Algorithm.
OAEP | Parameters for use with the OAEP algorithm.
PBEWith<digest>And<encryption> | Parameters for use with the PBEWith<digest>And<encryption> algorithm. Examples: PBEWithMD5AndDES, and PBEWithHmacSHA1AndDESede.
PBE | Parameters for use with the PBE algorithm. This name should not be used, in preference to the more specific PBE-algorithm names previously listed.
RC2 | Parameters for use with the RC2 algorithm.

CertificateFactory Types

The type in this section can be specified when generating an instance of CertificateFactory.

Type | Description
X.509 | The certificate type defined in X.509, also available via RFC 3280

CertPathBuilder Algorithms

The algorithm in this section can be specified when generating an instance of CertPathBuilder.

Algorithm Name | Description
PKIX | The PKIX certification path validation algorithm as defined in the ValidationAlgorithm service attribute. The output of CertPathBuilder instances implementing this algorithm is a certification path validated against the PKIX validation algorithm.

CertPath Encodings

The following encodings may be passed to the getEncoded method of CertPath or the generateCertPath(InputStream inStream, String encoding) method of CertificateFactory.

Encoding | Description
PKCS7 | A PKCS#7 SignedData object, with the only significant field being certificates. In particular, the signature and the contents are ignored. If no certificates are present, a zero-length CertPath is assumed. Warning: PKCS#7 does not maintain the order of certificates in a certification path. This means that if a CertPath is converted to PKCS#7 encoded bytes and then converted back, the order of the certificates may change, potentially rendering the CertPath invalid. Users should be aware of this behavior. See RSA Security for details on PKCS7.
PkiPath an ASN.1 DER encoded sequence of certificates, defined as follows:
    PkiPath ::= SEQUENCE OF Certificate
Within the sequence, the order of certificates is such that the subject of the first certificate is the issuer of the second certificate, and so on. Each certificate in PkiPath shall be unique. No certificate may appear more than once in a value of Certificate in PkiPath. The PkiPath format is defined in defect report 279 against X.509 (2000) and is incorporated into Technical Corrigendum 1 (DTC 2) for the ITU-T Recommendation X.509 (2000). See the ITU website for details.

CertPathValidator Algorithms

The algorithm in this section can be specified when generating an instance of CertPathValidator.

Algorithm Name | Description
PKIX | The PKIX certification path validation algorithm as defined in the ValidationAlgorithm service attribute.

CertStore Types

The type in this section can be specified when generating an instance of CertStore.

Type | Description
Collection | A CertStore implementation that retrieves certificates and CRLs from a Collection. This type of CertStore is particularly useful in applications where certificates or CRLs are received in a bag or some sort of attachment, such as with a signed email message or in an SSL negotiation.
LDAP | A CertStore implementation that fetches certificates and CRLs from an LDAP directory using the schema defined in the LDAPSchema service attribute.

Cipher (Encryption) Algorithms

Cipher Algorithm Names

The following names can be specified as the algorithm component in a transformation when requesting an instance of Cipher.

Algorithm Name | Description
AES | Advanced Encryption Standard as specified by NIST in FIPS 197. Also known as the Rijndael algorithm by Joan Daemen and Vincent Rijmen, AES is a 128-bit block cipher supporting keys of 128, 192, and 256 bits.
AESWrap | The AES key wrapping algorithm as described in RFC 3394.
ARCFOUR | A stream cipher believed to be fully interoperable with the RC4 cipher developed by Ron Rivest. For more information, see K. Kaukonen and R. Thayer, "A Stream Cipher Encryption Algorithm 'Arcfour'", Internet Draft (expired), draft-kaukonen-cipher-arcfour-03.txt.
Blowfish | The Blowfish block cipher designed by Bruce Schneier.
DES | The Digital Encryption Standard as described in FIPS PUB 46-3.
DESede | Triple DES Encryption (also known as DES-EDE, 3DES, or Triple-DES). Data is encrypted using the DES algorithm three separate times. It is first encrypted using the first subkey, then decrypted with the second subkey, and encrypted with the third subkey.
DESedeWrap | The DESede key wrapping algorithm as described in RFC 3217 .
ECIES | Elliptic Curve Integrated Encryption Scheme
PBEWith<digest>And<encryption> PBEWith<prf>And<encryption> The password-based encryption algorithm found in (PKCS5), using the specified message digest (<digest>) or pseudo-random function (<prf>) and encryption algorithm (<encryption>). Examples:
  • PBEWithMD5AndDES: The password-based encryption algorithm as defined in RSA Laboratories, "PKCS #5: Password-Based Encryption Standard," version 1.5, Nov 1993. Note that this algorithm implies CBC as the cipher mode and PKCS5Padding as the padding scheme and cannot be used with any other cipher modes or padding schemes.
  • PBEWithHmacSHA1AndDESede: The password-based encryption algorithm as defined in RSA Laboratories, "PKCS #5: Password-Based Cryptography Standard," version 2.0, March 1999.
RC2 | Variable-key-size encryption algorithms developed by Ron Rivest for RSA Data Security, Inc.
RC4 | Variable-key-size encryption algorithms developed by Ron Rivest for RSA Data Security, Inc. (See note prior for ARCFOUR.)
RC5 | Variable-key-size encryption algorithms developed by Ron Rivest for RSA Data Security, Inc.
RSA | The RSA encryption algorithm as defined in PKCS #1

Cipher Algorithm Modes

The following names can be specified as the mode component in a transformation when requesting an instance of Cipher.

Algorithm Name | Description
NONE | No mode.
CBC | Cipher Block Chaining Mode, as defined in FIPS PUB 81.
CFB, CFBx | Cipher Feedback Mode, as defined in FIPS PUB 81. Using modes such as CFB and OFB, block ciphers can encrypt data in units smaller than the cipher's actual block size. When requesting such a mode, you may optionally specify the number of bits to be processed at a time by appending this number to the mode name as shown in the "DES/CFB8/NoPadding" and "DES/OFB32/PKCS5Padding" transformations. If no such number is specified, a provider-specific default is used. (For example, the SunJCE provider uses a default of 64 bits for DES.) Thus, block ciphers can be turned into byte-oriented stream ciphers by using an 8-bit mode such as CFB8 or OFB8.
CTR | A simplification of OFB, Counter mode updates the input block as a counter.
CTS | Cipher Text Stealing, as described in Bruce Schneier's book Applied Cryptography-Second Edition, John Wiley and Sons, 1996.
ECB | Electronic Codebook Mode, as defined in FIPS PUB 81.
OFB, OFBx | Output Feedback Mode, as defined in FIPS PUB 81. Using modes such as CFB and OFB, block ciphers can encrypt data in units smaller than the cipher's actual block size. When requesting such a mode, you may optionally specify the number of bits to be processed at a time by appending this number to the mode name as shown in the "DES/CFB8/NoPadding" and "DES/OFB32/PKCS5Padding" transformations. If no such number is specified, a provider-specific default is used. (For example, the SunJCE provider uses a default of 64 bits for DES.) Thus, block ciphers can be turned into byte-oriented stream ciphers by using an 8-bit mode such as CFB8 or OFB8.
PCBC | Propagating Cipher Block Chaining, as defined by Kerberos V4.

Cipher Algorithm Padding

The following names can be specified as the padding component in a transformation when requesting an instance of Cipher.

Algorithm Name | Description
NoPadding | No padding.
ISO10126Padding | This padding for block ciphers is described in 5.2 Block Encryption Algorithms in the W3C's "XML Encryption Syntax and Processing" document.
OAEPPadding, OAEPWith<digest>And<mgf>Padding Optimal Asymmetric Encryption Padding scheme defined in PKCS1, where <digest> should be replaced by the message digest and <mgf> by the mask generation function. Examples: OAEPWithMD5AndMGF1Padding and OAEPWithSHA-512AndMGF1Padding.

If OAEPPadding is used, Cipher objects are initialized with a javax.crypto.spec.OAEPParameterSpec object to supply values needed for OAEPPadding.
PKCS1Padding | The padding scheme described in PKCS #1, used with the RSA algorithm.
PKCS5Padding | The padding scheme described in RSA Laboratories, "PKCS #5: Password-Based Encryption Standard," version 1.5, November 1993.
SSL3Padding The padding scheme defined in the SSL Protocol Version 3.0, November 18, 1996, section 5.2.3.2 (CBC block cipher):
    block-ciphered struct {
        opaque content[SSLCompressed.length];
        opaque MAC[CipherSpec.hash_size];
        uint8 padding[
            GenericBlockCipher.padding_length];
        uint8 padding_length;
    } GenericBlockCipher;
The size of an instance of a GenericBlockCipher must be a multiple of the block cipher's block length.

The padding length, which is always present, contributes to the padding, which implies that if:
    sizeof(content) + sizeof(MAC) % block_length = 0,
padding has to be (block_length - 1) bytes long, because of the existence of padding_length.

This makes the padding scheme similar (but not quite) to PKCS5Padding, where the padding length is encoded in the padding (and ranges from 1 to block_length). With the SSL scheme, the sizeof(padding) is encoded in the always present padding_length and therefore ranges from 0 to block_length-1.

Configuration Types

The type in this section can be specified when generating an instance of javax.security.auth.login.Configuration.

Type | Description
JavaLoginConfig | The default Configuration implementation from the SUN provider, as described in the ConfigFile class specification. This type accepts java.security.URIParameter as a valid Configuration.Parameter type. If this parameter is not specified, then the configuration information is loaded from the sources described in the ConfigFile class specification. If this parameter is specified, the configuration information is loaded solely from the specified URI.

Exemption Mechanisms

The following exemption mechanism names can be specified in the permission policy file that accompanies an application considered "exempt" from cryptographic restrictions.

Algorithm Name | Description
KeyEscrow | An encryption system with a backup decryption capability that allows authorized persons (users, officers of an organization, and government officials), under certain prescribed conditions, to decrypt ciphertext with the help of information supplied by one or more trusted parties who hold special data recovery keys.
KeyRecovery | A method of obtaining the secret key used to lock encrypted data. One use is as a means of providing fail-safe access to a corporation's own encrypted information in times of disaster.
KeyWeakening | A method in which a part of the key can be escrowed or recovered.

GSSAPI Mechanisms

The following mechanisms can be specified when using GSSAPI. Note that Object Identifiers (OIDs) are specified instead of names to be consistent with the GSSAPI standard.

Mechanism OID | Description
1.2.840.113554.1.2.2 | The Kerberos v5 GSS-API mechanism defined in RFC 4121.
1.3.6.1.5.5.2 | The Simple and Protected GSS-API Negotiation (SPNEGO) mechanism defined in RFC 4178.

KeyAgreement Algorithms

The following algorithm names can be specified when requesting an instance of KeyAgreement.

Algorithm Name | Description
DiffieHellman | Diffie-Hellman Key Agreement as defined in PKCS #3: Diffie-Hellman Key-Agreement Standard, RSA Laboratories, version 1.4, November 1993.
ECDH | Elliptic Curve Diffie-Hellman as defined in ANSI X9.63 and as described in RFC 3278: "Use of Elliptic Curve Cryptography (ECC) Algorithms in Cryptographic Message Syntax (CMS)."
ECMQV | Elliptic Curve Menezes-Qu-Vanstone as defined in "Elliptic Curve Cryptography" from www.secg.org.

KeyFactory Algorithms

(Except as noted, these classes create keys for which Key.getAlgorithm() returns the standard algorithm name.)

The algorithm names in this section can be specified when generating an instance of KeyFactory.

Algorithm Name | Description
DiffieHellman | Keys for the Diffie-Hellman KeyAgreement algorithm. Note: key.getAlgorithm() will return "DH" instead of "DiffieHellman".
DSA | Keys for the Digital Signature Algorithm.
RSA | Keys for the RSA algorithm (Signature/Cipher).
EC | Keys for the Elliptic Curve algorithm.

KeyGenerator Algorithms

The following algorithm names can be specified when requesting an instance of KeyGenerator.

Algorithm Name | Description
AES | Key generator for use with the AES algorithm.
ARCFOUR | Key generator for use with the ARCFOUR (RC4) algorithm.
Blowfish | Key generator for use with the Blowfish algorithm.
DES | Key generator for use with the DES algorithm.
DESede | Key generator for use with the DESede (triple-DES) algorithm.
HmacMD5 | Key generator for use with the HmacMD5 algorithm.
HmacSHA1 HmacSHA256 HmacSHA384 HmacSHA512 | Keys generator for use with the various flavors of the HmacSHA algorithms.
RC2 | Key generator for use with the RC2 algorithm.

KeyManagerFactory Algorithms

The algorithm name in this section can be specified when generating an instance of KeyManagerFactory.

Algorithm Name | Description
PKIX | A factory for X509ExtendedKeyManagers that manage X.509 certificate-based key pairs for local side authentication according to the rules defined by the IETF PKIX working group in RFC 3280 or its successor. The KeyManagerFactory must support initialization using the class javax.net.ssl.KeyStoreBuilderParameters.

KeyPairGenerator Algorithms

(Except as noted, these classes create keys for which Key.getAlgorithm() returns the standard algorithm name.)

The algorithm names in this section can be specified when generating an instance of KeyPairGenerator.

Algorithm Name | Description
DiffieHellman | Generates keypairs for the Diffie-Hellman KeyAgreement algorithm. Note: key.getAlgorithm() will return "DH" instead of "DiffieHellman".
DSA | Generates keypairs for the Digital Signature Algorithm.
RSA | Generates keypairs for the RSA algorithm (Signature/Cipher).
EC | Generates keypairs for the Elliptic Curve algorithm.

KeyStore Types

The types in this section can be specified when generating an instance of KeyStore.

Type | Description
jceks | The proprietary keystore implementation provided by the SunJCE provider.
jks | The proprietary keystore implementation provided by the SUN provider.
pkcs12 | The transfer syntax for personal identity information as defined in PKCS #12.

Mac Algorithms

The following algorithm names can be specified when requesting an instance of Mac.

Algorithm Name | Description
HmacMD5 | The HMAC-MD5 keyed-hashing algorithm as defined in RFC 2104 "HMAC: Keyed-Hashing for Message Authentication" (February 1997).
HmacSHA1 HmacSHA256 HmacSHA384 HmacSHA512 | The HmacSHA* algorithms as defined in RFC 2104 "HMAC: Keyed-Hashing for Message Authentication" (February 1997) with SHA-* as the message digest algorithm.
PBEWith<mac> | Mac for use with the PKCS #5 v 2.0 password-based message authentication standard, where <mac> is a Message Authentication Code algorithm name. Example: PBEWithHmacSHA1.

MessageDigest Algorithms

The algorithm names in this section can be specified when generating an instance of MessageDigest.

Algorithm Name | Description
MD2 | The MD2 message digest algorithm as defined in RFC 1319.
MD5 | The MD5 message digest algorithm as defined in RFC 1321.
SHA-1 SHA-256 SHA-384 SHA-512 | Hash algorithms defined in the FIPS PUB 180-2. SHA-256 is a 256-bit hash function intended to provide 128 bits of security against collision attacks, while SHA-512 is a 512-bit hash function intended to provide 256 bits of security. A 384-bit hash may be obtained by truncating the SHA-512 output.

Policy Types

The type in this section can be specified when generating an instance of Policy.

Type | Description
JavaPolicy | The default Policy implementation from the SUN provider, as described in the PolicyFile guide. This type accepts java.security.URIParameter as a valid Policy.Parameter type. If this parameter is not specified, then the policy information is loaded from the sources described in the Default Policy File Locations section of the PolicyFile guide. If this parameter is specified, the policy information is loaded solely from the specified URI.

SaslClient Mechanisms

The mechanisms in this section can be specified when generating an instance of SaslClient.

Mechanism | Description
CRAM-MD5 | See RFC 2195. This mechanism supports a hashed username/password authentication scheme.
DIGEST-MD5 | See RFC 2831. This mechanism defines how HTTP Digest Authentication can be used as a SASL mechanism.
EXTERNAL | See RFC 2222. This mechanism obtains authentication information from an external channel (such as TLS or IPsec).
GSSAPI | See RFC 2222. This mechanism uses the GSSAPI for obtaining authentication information. It supports Kerberos v5 authentication.
PLAIN | See RFC 2595. This mechanism supports cleartext user name/password authentication.

SaslServer Mechanisms

The mechanisms in this section can be specified when generating an instance of SaslServer.

Mechanism | Description
CRAM-MD5 | See RFC 2195. This mechanism supports a hashed user name/password authentication scheme.
DIGEST-MD5 | See RFC 2831. This mechanism defines how HTTP Digest Authentication can be used as a SASL mechanism.
GSSAPI | See RFC 2222. This mechanism uses the GSSAPI for obtaining authentication information. It supports Kerberos v5 authentication.

SecretKeyFactory Algorithms

The following algorithm names can be specified when requesting an instance of SecretKeyFactory.

Algorithm Name | Description
AES | Constructs secret keys for use with the AES algorithm.
ARCFOUR | Constructs secret keys for use with the ARCFOUR algorithm.
DES | Constructs secrets keys for use with the DES algorithm.
DESede | Constructs secrets keys for use with the DESede (Triple-DES) algorithm.
PBEWith<digest>And<encryption>
PBEWith<prf>And<encryption> 		Secret-key factory for use with PKCS5 password-based encryption, where <digest> is a message digest, <prf> is a pseudo-random function, and <encryption> is an encryption algorithm.

Examples:

  • PBEWithMD5AndDES (PKCS5, v 1.5),
  • PBEWithHmacSHA1AndDESede (PKCS5, v 2.0), and
Note: These all use only the low order 8 bits of each password character.
PBKDF2WithHmacSHA1 | Constructs secret keys using the Password-Based Key Derivation Function function found in PKCS #5 v2.0.

SecureRandom Number Generation (RNG) Algorithms

The algorithm name in this section can be specified when generating an instance of SecureRandom.

Algorithm Name | Description
SHA1PRNG | The name of the pseudo-random number generation (PRNG) algorithm supplied by the SUN provider. This algorithm uses SHA-1 as the foundation of the PRNG. It computes the SHA-1 hash over a true-random seed value concatenated with a 64-bit counter which is incremented by 1 for each operation. From the 160-bit SHA-1 output, only 64 bits are used.

Service Attributes

A cryptographic service is always associated with a particular algorithm or type. For example, a digital signature service is always associated with a particular algorithm (for example, DSA), and a CertificateFactory service is always associated with a particular certificate type (for example, X.509).

The attributes in this section are for cryptographic services. The service attributes can be used as filters for selecting providers.

Both the attribute name and value are case-insensitive.

Attribute | Description
KeySize | The maximum key size that the provider supports for the cryptographic service.
ImplementedIn | Whether the implementation for the cryptographic service is done by software or hardware. The value of this attribute is "software" or "hardware".
ValidationAlgorithm | The name of the specification that defines the certification path validation algorithm that an implementation of CertPathBuilder or CertPathValidator supports. RFCs should be specified as "RFC#" (ex: "RFC3280") and Internet Drafts as the name of the draft (ex: "draft-ietf-pkix-rfc2560bis-01.txt"). Values for this attribute that are specified as selection criteria to the Security.getProviders method will be compared using the String.equalsIgnoreCase method. All PKIX implementations of CertPathBuilder and CertPathValidator should provide a value for this attribute.
LDAPSchema | The name of the specification that defines the LDAP schema that an implementation of an LDAP CertStore uses to retrieve certificates and CRLs. The format and semantics of this attribute is the same as described for the ValidationAlgorithm attribute. All LDAP implementations of CertStore should provide a value for this attribute.

For example:

   map.put("KeyPairGenerator.DSA",
            "sun.security.provider.DSAKeyPairGenerator");
        map.put("KeyPairGenerator.DSA KeySize", "1024");
        map.put("KeyPairGenerator.DSA ImplementedIn", "Software");

Signature Algorithms

The algorithm names in this section can be specified when generating an instance of Signature.

Algorithm Name | Description
NONEwithRSA | The RSA signature algorithm, which does not use a digesting algorithm (for example, MD5/SHA1) before performing the RSA operation. For more information about the RSA Signature algorithms, see PKCS #1.
MD2withRSA MD5withRSA | The MD2/MD5 with RSA Encryption signature algorithm, which uses the MD2/MD5 digest algorithm and RSA to create and verify RSA digital signatures as defined in PKCS #1.
SHA1withRSA SHA256withRSA SHA384withRSA SHA512withRSA | The signature algorithm with SHA-* and the RSA encryption algorithm as defined in the OSI Interoperability Workshop, using the padding conventions described in PKCS #1.
NONEwithDSA | The Digital Signature Algorithm as defined in FIPS PUB 186-2. The data must be exactly 20 bytes in length. This algorithm is also known as rawDSA.
SHA1withDSA | The DSA with SHA-1 signature algorithm, which uses the SHA-1 digest algorithm and DSA to create and verify DSA digital signatures as defined in FIPS PUB 186.
NONEwithECDSA SHA1withECDSA SHA256withECDSA SHA384withECDSA SHA512withECDSA (ECDSA) | The ECDSA signature algorithms as defined in ANSI X9.62. Note:"ECDSA" is an ambiguous name for the "SHA1withECDSA" algorithm and should not be used. The formal name "SHA1withECDSA" should be used instead.
<digest>with<encryption> | Use this to form a name for a signature algorithm with a particular message digest (such as MD2 or MD5) and algorithm (such as RSA or DSA), just as was done for the explicitly defined standard names in this section (MD2withRSA, and so on). For the new signature schemes defined in PKCS #1 v 2.0, for which the <digest>with<encryption> form is insufficient, <digest>with<encryption>and<mgf> can be used to form a name. Here, <mgf> should be replaced by a mask generation function such as MGF1. Example: MD5withRSAandMGF1.

SSLContext Algorithms

The algorithm names in this section can be specified when generating an instance of SSLContext.

Algorithm Name | Description
SSL | Supports some version of SSL; may support other versions
SSLv2 | Supports SSL version 2 or later; may support other versions
SSLv3 | Supports SSL version 3; may support other versions
TLS | Supports some version of TLS; may support other versions
TLSv1 | Supports RFC 2246: TLS version 1.0 ; may support other versions
TLSv1.1 | Supports RFC 4346: TLS version 1.1 ; may support other versions
TLSv1.2 | Supports RFC 5246: TLS version 1.2 ; may support other versions

TrustManagerFactory Algorithms

The algorithm name in this section can be specified when generating an instance of TrustManagerFactory.

Algorithm Name | Description
PKIX | A factory for X509ExtendedTrustManager objects that validate certificate chains according to the rules defined by the IETF PKIX working group in RFC 3280 or its successor. The TrustManagerFactory must support initialization using the class javax.net.ssl.CertPathTrustManagerParameters.

XML Signature (XMLSignatureFactory/KeyInfoFactory/TransformService) Mechanisms

The mechanism in this section can be specified when generating an instance of XMLSignatureFactory, KeyInfoFactory, or TransformService. The mechanism identifies the XML processing mechanism that an implementation uses internally to parse and generate XML signature and KeyInfo structures. Also, note that each TransformService instance supports a specific transform algorithm in addition to a mechanism. The standard names for the transform algorithms are defined in the next section.

Mechanism | Description
DOM | The Document Object Model. See DOM Mechanism Requirements for additional requirements for DOM implementations.

XML Signature Transform (TransformService) Algorithms

The algorithms in this section can be specified when generating an instance of TransformService. Note that URIs are specified instead of names to be consistent with the XML Signature standard. API constants have been defined for each of these URIs, and these are listed in parentheses after each URI in the table that follows.

Algorithm URI | Description
http://www.w3.org/TR/2001/REC-xml-c14n-20010315 (CanonicalizationMethod.INCLUSIVE) | The Canonical XML (without comments) canonicalization algorithm.
http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments (CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS) | The Canonical XML with comments canonicalization algorithm.
http://www.w3.org/2001/10/xml-exc-c14n# (CanonicalizationMethod.EXCLUSIVE) | The Exclusive Canonical XML (without comments) canonicalization algorithm.
http://www.w3.org/2001/10/xml-exc-c14n#WithComments (CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS) | The Exclusive Canonical XML with comments canonicalization algorithm.
http://www.w3.org/2000/09/xmldsig#base64 (Transform.BASE64) | The Base64 transform algorithm.
http://www.w3.org/2000/09/xmldsig#enveloped-signature (Transform.ENVELOPED) | The Enveloped Signature transform algorithm.
http://www.w3.org/TR/1999/REC-xpath-19991116 (Transform.XPATH) | The XPath transform algorithm.
http://www.w3.org/2002/06/xmldsig-filter2 (Transform.XPATH2) | The XPath Filter 2 transform algorithm.
http://www.w3.org/TR/1999/REC-xslt-19991116 (Transform.XSLT) | The XSLT transform algorithm.

JSSE Cipher Suite Names

The following list contains the standard JSSE cipher suite names. Over time, various groups have added additional cipher suites to the SSL/TLS namespace. Some JSSE cipher suite names were defined before TLSv1.0 was finalized, and were therefore given the SSL_ prefix. The names mentioned in the TLS RFCs prefixed with TLS_ are functionally equivalent to the JSSE cipher suites prefixed with SSL_.

SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA
SSL_DH_anon_EXPORT_WITH_RC4_40_MD5
SSL_DH_anon_WITH_3DES_EDE_CBC_SHA
TLS_DH_anon_WITH_AES_128_CBC_SHA
TLS_DH_anon_WITH_AES_128_CBC_SHA256
TLS_DH_anon_WITH_AES_128_GCM_SHA256
TLS_DH_anon_WITH_AES_256_CBC_SHA
TLS_DH_anon_WITH_AES_256_CBC_SHA256
TLS_DH_anon_WITH_AES_256_GCM_SHA384
TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA
TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256
TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA
TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256
SSL_DH_anon_WITH_DES_CBC_SHA
SSL_DH_anon_WITH_RC4_128_MD5
TLS_DH_anon_WITH_SEED_CBC_SHA
SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA
SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA
TLS_DH_DSS_WITH_AES_128_CBC_SHA
TLS_DH_DSS_WITH_AES_128_CBC_SHA256
TLS_DH_DSS_WITH_AES_128_GCM_SHA256
TLS_DH_DSS_WITH_AES_256_CBC_SHA
TLS_DH_DSS_WITH_AES_256_CBC_SHA256
TLS_DH_DSS_WITH_AES_256_GCM_SHA384
TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA
TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256
TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA
TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256
SSL_DH_DSS_WITH_DES_CBC_SHA
TLS_DH_DSS_WITH_SEED_CBC_SHA
SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA
SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA
TLS_DH_RSA_WITH_AES_128_CBC_SHA
TLS_DH_RSA_WITH_AES_128_CBC_SHA256
TLS_DH_RSA_WITH_AES_128_GCM_SHA256
TLS_DH_RSA_WITH_AES_256_CBC_SHA
TLS_DH_RSA_WITH_AES_256_CBC_SHA256
TLS_DH_RSA_WITH_AES_256_GCM_SHA384
TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA
TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256
TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA
TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256
SSL_DH_RSA_WITH_DES_CBC_SHA
TLS_DH_RSA_WITH_SEED_CBC_SHA
SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA
SSL_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA
SSL_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA
SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA
TLS_DHE_DSS_WITH_AES_128_CBC_SHA
TLS_DHE_DSS_WITH_AES_128_CBC_SHA256
TLS_DHE_DSS_WITH_AES_128_GCM_SHA256
TLS_DHE_DSS_WITH_AES_256_CBC_SHA
TLS_DHE_DSS_WITH_AES_256_CBC_SHA256
TLS_DHE_DSS_WITH_AES_256_GCM_SHA384
TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA
TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256
TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA
TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256
SSL_DHE_DSS_WITH_DES_CBC_SHA
SSL_DHE_DSS_WITH_RC4_128_SHA
TLS_DHE_DSS_WITH_SEED_CBC_SHA
TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA
TLS_DHE_PSK_WITH_AES_128_CBC_SHA
TLS_DHE_PSK_WITH_AES_128_CBC_SHA256
TLS_DHE_PSK_WITH_AES_128_GCM_SHA256
TLS_DHE_PSK_WITH_AES_256_CBC_SHA
TLS_DHE_PSK_WITH_AES_256_CBC_SHA384
TLS_DHE_PSK_WITH_AES_256_GCM_SHA384
TLS_DHE_PSK_WITH_NULL_SHA
TLS_DHE_PSK_WITH_NULL_SHA256
TLS_DHE_PSK_WITH_NULL_SHA384
TLS_DHE_PSK_WITH_RC4_128_SHA
SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA
TLS_DHE_RSA_WITH_AES_128_CBC_SHA
TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
TLS_DHE_RSA_WITH_AES_256_CBC_SHA
TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256
TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256
SSL_DHE_RSA_WITH_DES_CBC_SHA
TLS_DHE_RSA_WITH_SEED_CBC_SHA
TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA
TLS_ECDH_anon_WITH_AES_128_CBC_SHA
TLS_ECDH_anon_WITH_AES_256_CBC_SHA
TLS_ECDH_anon_WITH_NULL_SHA
TLS_ECDH_anon_WITH_RC4_128_SHA
TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
TLS_ECDH_ECDSA_WITH_NULL_SHA
TLS_ECDH_ECDSA_WITH_RC4_128_SHA
TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
TLS_ECDH_RSA_WITH_NULL_SHA
TLS_ECDH_RSA_WITH_RC4_128_SHA
TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
TLS_ECDHE_ECDSA_WITH_NULL_SHA
TLS_ECDHE_ECDSA_WITH_RC4_128_SHA
TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA
TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA
TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA
TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384
TLS_ECDHE_PSK_WITH_NULL_SHA
TLS_ECDHE_PSK_WITH_NULL_SHA256
TLS_ECDHE_PSK_WITH_NULL_SHA384
TLS_ECDHE_PSK_WITH_RC4_128_SHA
TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
TLS_ECDHE_RSA_WITH_NULL_SHA
TLS_ECDHE_RSA_WITH_RC4_128_SHA
TLS_EMPTY_RENEGOTIATION_INFO_SCSV*
SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA
SSL_FORTEZZA_DMS_WITH_NULL_SHA
TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5
TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA
TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5
TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA
TLS_KRB5_EXPORT_WITH_RC4_40_MD5
TLS_KRB5_EXPORT_WITH_RC4_40_SHA
TLS_KRB5_WITH_3DES_EDE_CBC_MD5
TLS_KRB5_WITH_3DES_EDE_CBC_SHA
TLS_KRB5_WITH_DES_CBC_MD5
TLS_KRB5_WITH_DES_CBC_SHA
TLS_KRB5_WITH_IDEA_CBC_MD5
TLS_KRB5_WITH_IDEA_CBC_SHA
TLS_KRB5_WITH_RC4_128_MD5
TLS_KRB5_WITH_RC4_128_SHA
TLS_PSK_WITH_3DES_EDE_CBC_SHA
TLS_PSK_WITH_AES_128_CBC_SHA
TLS_PSK_WITH_AES_128_CBC_SHA256
TLS_PSK_WITH_AES_128_GCM_SHA256
TLS_PSK_WITH_AES_256_CBC_SHA
TLS_PSK_WITH_AES_256_CBC_SHA384
TLS_PSK_WITH_AES_256_GCM_SHA384
TLS_PSK_WITH_NULL_SHA
TLS_PSK_WITH_NULL_SHA256
TLS_PSK_WITH_NULL_SHA384
TLS_PSK_WITH_RC4_128_SHA
SSL_RSA_EXPORT_WITH_DES40_CBC_SHA
SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5
SSL_RSA_EXPORT_WITH_RC4_40_MD5
SSL_RSA_EXPORT1024_WITH_DES_CBC_SHA
SSL_RSA_EXPORT1024_WITH_RC4_56_SHA
SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA
SSL_RSA_FIPS_WITH_DES_CBC_SHA
TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA
TLS_RSA_PSK_WITH_AES_128_CBC_SHA
TLS_RSA_PSK_WITH_AES_128_CBC_SHA256
TLS_RSA_PSK_WITH_AES_128_GCM_SHA256
TLS_RSA_PSK_WITH_AES_256_CBC_SHA
TLS_RSA_PSK_WITH_AES_256_CBC_SHA384
TLS_RSA_PSK_WITH_AES_256_GCM_SHA384
TLS_RSA_PSK_WITH_NULL_SHA
TLS_RSA_PSK_WITH_NULL_SHA256
TLS_RSA_PSK_WITH_NULL_SHA384
TLS_RSA_PSK_WITH_RC4_128_SHA
SSL_RSA_WITH_3DES_EDE_CBC_SHA
TLS_RSA_WITH_AES_128_CBC_SHA
TLS_RSA_WITH_AES_128_CBC_SHA256
TLS_RSA_WITH_AES_128_GCM_SHA256
TLS_RSA_WITH_AES_256_CBC_SHA
TLS_RSA_WITH_AES_256_CBC_SHA256
TLS_RSA_WITH_AES_256_GCM_SHA384
TLS_RSA_WITH_CAMELLIA_128_CBC_SHA
TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256
TLS_RSA_WITH_CAMELLIA_256_CBC_SHA
TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256
SSL_RSA_WITH_DES_CBC_SHA
SSL_RSA_WITH_IDEA_CBC_SHA
SSL_RSA_WITH_NULL_MD5
SSL_RSA_WITH_NULL_SHA
TLS_RSA_WITH_NULL_SHA256
SSL_RSA_WITH_RC4_128_MD5
SSL_RSA_WITH_RC4_128_SHA
TLS_RSA_WITH_SEED_CBC_SHA
TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA
TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA
TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA
TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA
TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA
TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA
TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA
TLS_SRP_SHA_WITH_AES_128_CBC_SHA
TLS_SRP_SHA_WITH_AES_256_CBC_SHA

* TLS_EMPTY_RENEGOTIATION_INFO_SCSV is a new pseudo-cipher suite to support RFC 5746. Read the Transport Layer Security (TLS) Renegotiation Issue section of the JSEE Reference Guide for more information.

Additional JSSE Standard Names

The keyType parameter passed to the chooseClientAlias, chooseServerAlias, getClientAliases, and getServerAliases methods of X509KeyManager specifies the public key types. Each row of the table that follows lists the standard name that should be used for keyType, given the specified certificate type.

Name | Certificate Type
RSA | RSA
DSA | DSA
DH_RSA | Diffie-Hellman with RSA signature
DH_DSA | Diffie-Hellman with DSA signature
EC | Elliptic Curve
EC_EC | Elliptic Curve with ECDSA signature
EC_RSA | Elliptic Curve with RSA signature

The protocols parameter passed to the setEnabledProtocols method of SSLSocket specifies the protocol versions to be enabled for use on the connection. The table that follows lists the standard names that can be passed to setEnabledProtocols or that may be returned by the SSLSocket getSupportedProtocols and getEnabledProtocols methods.

Name | Protocol
SSLv2 | SSL version 2 protocol
SSLv3 | SSL version 3 protocol
TLSv1 | TLS version 1.0 protocol (defined in RFC 2246)
TLSv1.1 | TLS version 1.1 protocol (defined in RFC 4346)
TLSv1.2 | TLS version 1.2 protocol (defined in RFC 5246)
SSLv2Hello | Currently, the SSLv3, TLSv1, and TLSv1.1 protocols allow you to send SSLv3, TLSv1, and TLSv1.1 hellos encapsulated in an SSLv2 format hello. For more details on the reasons for allowing this compatibility in these protocols, see Appendix E in the appropriate RFCs (previously listed). Note that some SSL/TLS servers do not support the v2 hello format and require that client hellos conform to the SSLv3 or TLSv1 client hello formats. The SSLv2Hello option controls the SSLv2 encapsulation. If SSLv2Hello is disabled on the client, then all outgoing messages will conform to the SSLv3/TLSv1 client hello format. If SSLv2Hello is disabled on the server, then all incoming messages must conform to the SSLv3/TLSv1 client hello format.

The authType parameter passed to the checkClientTrusted and checkServerTrusted methods of X509TrustManager indicates the authentication type. The table that follows specifies what standard names should be used for the client or server certificate chains.

Client or Server Certificate Chain | Authentication Type Standard Name
Client | Determined by the actual certificate used. For instance, if RSAPublicKey is used, the authType should be "RSA".
Server | The key exchange algorithm portion of the cipher suites represented as a String, such as "RSA" or "DHE_DSS". Note: For some exportable cipher suites, the key exchange algorithm is determined at runtime during the handshake. For instance, for TLS_RSA_EXPORT_WITH_RC4_40_MD5, the authType should be "RSA_EXPORT" when an ephemeral RSA key is used for the key exchange, and "RSA" when the key from the server certificate is used. Or it can take the value "UNKNOWN".

The Java SE 7 release supports endpoint identification algorithms for TLS 1.2. The algorithm name can be passed to the setEndpointIdentificationAlgorithm() method of javax.net.ssl.SSLParameters. The following table shows the currently recognized names.

Endpoint Identification Algorithm Name | Specification
HTTPS | http://www.ietf.org/rfc/rfc2818.txt
LDAPS | http://www.ietf.org/rfc/rfc2830.txt

Algorithms

This section specifies details concerning some of the algorithms defined in this document. Any provider supplying an implementation of the listed algorithms must comply with the specifications in this section.

To add a new algorithm not specified here, you should first survey other people or companies supplying provider packages to see if they have already added that algorithm, and, if so, use the definitions they published, if available. Otherwise, you should create and make available a template, similar to those found in this section, with the specifications for the algorithm you provide.

Specification Template

The following table shows the fields of the algorithm specifications.

Field | Description
Name | The name by which the algorithm is known. This is the name passed to the getInstance method (when requesting the algorithm), and returned by the getAlgorithm method to determine the name of an existing algorithm object. These methods are in the relevant engine classes: Signature, MessageDigest, KeyPairGenerator, and AlgorithmParameterGenerator .
Type | The type of algorithm: Signature, MessageDigest, KeyPairGenerator, or ParameterGenerator.
Description | General notes about the algorithm, including any standards implemented by the algorithm, applicable patents, and so on.
KeyPair Algorithm (optional) | The keypair algorithm for this algorithm.
Keysize (optional) | For a keyed algorithm or key generation algorithm: the valid keysizes.
Size (optional) | For an algorithm parameter generation algorithm: the valid "sizes" for algorithm parameter generation.
Parameter Defaults (optional) | For a key generation algorithm: the default parameter values.
Signature Format (optional) | For a Signature algorithm, the format of the signature, that is, the input and output of the verify and sign methods, respectively.

Algorithm Specifications

SHA-1 Message Digest Algorithm

Field | Description
Name | SHA-1
Type | MessageDigest
Description | The message digest algorithm as defined in NIST's FIPS 180-2. The output of this algorithm is a 160-bit digest.

MD2 Message Digest Algorithm

Field | Description
Name | MD2
Type | MessageDigest
Description | The message digest algorithm as defined in RFC 1319. The output of this algorithm is a 128-bit (16 byte) digest.

MD5 Message Digest Algorithm

Field | Description
Name | MD5
Type | MessageDigest
Description | The message digest algorithm as defined in RFC 1321. The output of this algorithm is a 128-bit (16 byte) digest.

The Digital Signature Algorithm

Field | Description
Name | SHA1withDSA
Type | Signature
Description | This algorithm is the signature algorithm described in NIST FIPS 186, using DSA with the SHA-1 message digest algorithm.
KeyPair Algorithm | DSA
Signature Format | ASN.1 sequence of two INTEGER values: r and s, in that order: SEQUENCE ::= { r INTEGER, s INTEGER }

RSA-based Signature Algorithms, with MD2, MD5 or SHA-1

Field | Description
Names | MD2withRSA, MD5withRSA and SHA1withRSA
Type | Signature
Description | These are the signature algorithms that use the MD2, MD5, and SHA-1 message digest algorithms (respectively) with RSA encryption.
KeyPair Algorithm | RSA
Signature Format | DER-encoded PKCS1 block as defined in RSA Laboratories, PKCS #1. The data encrypted is the digest of the data signed.

DSA KeyPair Generation Algorithm

Field | Description
Name | DSA
Type | KeyPairGenerator
Description | This algorithm is the key pair generation algorithm described NIST FIPS 186 for DSA.
Keysize | The length, in bits, of the modulus p. This must range from 512 to 1024, and must be a multiple of 64. The default keysize is 1024.
Parameter Defaults

The following default parameter values are used for keysizes of 512, 768, and 1024 bits:

512-bit Key Parameters

SEED = b869c82b 35d70e1b 1ff91b28 e37a62ec dc34409b
counter = 123
p = fca682ce 8e12caba 26efccf7 110e526d b078b05e decbcd1e b4a208f3
    ae1617ae 01f35b91 a47e6df6 3413c5e1 2ed0899b cd132acd 50d99151
    bdc43ee7 37592e17
q = 962eddcc 369cba8e bb260ee6 b6a126d9 346e38c5

g = 678471b2 7a9cf44e e91a49c5 147db1a9 aaf244f0 5a434d64 86931d2d
    14271b9e 35030b71 fd73da17 9069b32e 2935630e 1c206235 4d0da20a
    6c416e50 be794ca4

768-bit key parameters

SEED = 77d0f8c4 dad15eb8 c4f2f8d6 726cefd9 6d5bb399
counter = 263
p = e9e64259 9d355f37 c97ffd35 67120b8e 25c9cd43 e927b3a9 670fbec5
    d8901419 22d2c3b3 ad248009 3799869d 1e846aab 49fab0ad 26d2ce6a
    22219d47 0bce7d77 7d4a21fb e9c270b5 7f607002 f3cef839 3694cf45
    ee3688c1 1a8c56ab 127a3daf
q = 9cdbd84c 9f1ac2f3 8d0f80f4 2ab952e7 338bf511
g = 30470ad5 a005fb14 ce2d9dcd 87e38bc7 d1b1c5fa cbaecbe9 5f190aa7
    a31d23c4 dbbcbe06 17454440 1a5b2c02 0965d8c2 bd2171d3 66844577
    1f74ba08 4d2029d8 3c1c1585 47f3a9f1 a2715be2 3d51ae4d 3e5a1f6a
    7064f316 933a346d 3f529252

1024-bit key parameters

SEED = 8d515589 4229d5e6 89ee01e6 018a237e 2cae64cd
counter = 92
p = fd7f5381 1d751229 52df4a9c 2eece4e7 f611b752 3cef4400 c31e3f80
    b6512669 455d4022 51fb593d 8d58fabf c5f5ba30 f6cb9b55 6cd7813b
    801d346f f26660b7 6b9950a5 a49f9fe8 047b1022 c24fbba9 d7feb7c6
    1bf83b57 e7c6a8a6 150f04fb 83f6d3c5 1ec30235 54135a16 9132f675
    f3ae2b61 d72aeff2 2203199d d14801c7
q = 9760508f 15230bcc b292b982 a2eb840b f0581cf5

g = f7e1a085 d69b3dde cbbcab5c 36b857b9 7994afbb fa3aea82 f9574c0b
    3d078267 5159578e bad4594f e6710710 8180b449 167123e8 4c281613
    b7cf0932 8cc8a6e1 3c167a8b 547c8d28 e0a3ae1e 2bb3a675 916ea37f
    0bfa2135 62f1fb62 7a01243b cca4f1be a8519089 a883dfe1 5ae59f06
    928b665e 807b5525 64014c3b fecf492a

RSA KeyPair Generation Algorithm

Field | Description
Names | RSA
Type | KeyPairGenerator
Description | This algorithm is the key pair generation algorithm described in PKCS #1.
Strength | Any integer that is a multiple of 8, greater than or equal to 512.

DSA Parameter Generation Algorithm

Field | Description
Names | DSA
Type | ParameterGenerator
Description | This algorithm is the parameter generation algorithm described in NIST FIPS 186 for DSA.
Strength | The length, in bits, of the modulus p. This must range from 512 to 1024, and must be a multiple of 64. The default size is 1024.

Implementation Requirements

This section defines the security algorithm requirements for Java SE 7 implementations. These requirements are intended to improve the interoperability of Java SE 7 implementations and applications that use these algorithms.

Note that the requirements in this section are not a measure of the strength or security of the algorithm. For example, recent advances in cryptanalysis have found weaknesses in the strength of the MD5 MessageDigest algorithm. It is your responsibility to determine whether the algorithm meets the security requirements of your application.

Every implementation of the Java SE 7 platform must support the specified algorithms in the table that follows. These requirements do not apply to 3rd party providers. Consult the release documentation for your implementation to see if any other algorithms are supported.

Class | Algorithm Name(s)
AlgorithmParameterGenerator Implementations must support the key sizes in parentheses. | DiffieHellman (1024) DSA (1024)
AlgorithmParameters | AES DES DESede DiffieHellman DSA
CertificateFactory | X.509
CertPath Encodings | PKCS7 PkiPath
CertPathBuilder | PKIX
CertPathValidator | PKIX
CertStore | Collection
Cipher The algorithms are specified as transformations. Implementations must support the key sizes in parentheses. | AES/CBC/NoPadding (128) AES/CBC/PKCS5Padding (128) AES/ECB/NoPadding (128) AES/ECB/PKCS5Padding (128) DES/CBC/NoPadding (56) DES/CBC/PKCS5Padding (56) DES/ECB/NoPadding (56) DES/ECB/PKCS5Padding (56) DESede/CBC/NoPadding (168) DESede/CBC/PKCS5Padding (168) DESede/ECB/NoPadding (168) DESede/ECB/PKCS5Padding (168) RSA/ECB/PKCS1Padding (1024, 2048) RSA/ECB/OAEPWithSHA-1AndMGF1Padding (1024, 2048) RSA/ECB/OAEPWithSHA-256AndMGF1Padding (1024, 2048)
Configuration [1] |
KeyAgreement | DiffieHellman
KeyFactory | DiffieHellman DSA RSA
KeyGenerator Implementations must support the key sizes in parentheses. | AES (128) DES (56) DESede (168) HmacSHA1 HmacSHA256
KeyPairGenerator Implementations must support the key sizes in parentheses. | DiffieHellman (1024) DSA (1024) RSA (1024, 2048)
KeyStore | PKCS12
Mac | HmacMD5 HmacSHA1 HmacSHA256
MessageDigest | MD5 SHA-1 SHA-256
Policy [1] |
SecretKeyFactory | DES DESede
SecureRandom [1] |
Signature | SHA1withDSA SHA1withRSA SHA256withRSA
SSLContext | TLSv1 [2]

[1] No specific Configuration type, Policy type or SecureRandom algorithm is required; however, an implementation-specific default must be provided.

[2] A TLSv1 implementation must support the cipher suite TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA as defined in RFC 2246 and the special signaling cipher suite TLS_EMPTY_RENEGOTIATION_INFO_SCSV for safe renegotiation as defined in RFC 5746.

XML Signature Algorithms

Every implementation of the Java SE 7 platform must support the specified XML Signature algorithms in the table that follows. These requirements do not apply to 3rd party providers. Consult the release documentation for your implementation to see if any other algorithms are supported.

Class | Algorithm Name(s)
TransformService | http://www.w3.org/2001/10/xml-exc-c14n# (CanonicalizationMethod.EXCLUSIVE) http://www.w3.org/TR/2001/REC-xml-c14n-20010315 (CanonicalizationMethod.INCLUSIVE) http://www.w3.org/2000/09/xmldsig#base64 (Transform.BASE64) http://www.w3.org/2000/09/xmldsig#enveloped-signature (Transform.ENVELOPED)
XMLSignatureFactory | DOM
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.source.tree.StatementTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.StatementTree

  • Packages that use StatementTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).

    • Uses of StatementTree in com.sun.source.tree

      Subinterfaces of StatementTree in com.sun.source.tree
      Modifier and Type Interface and Description
      interface  AssertTree
      A tree node for an 'assert' statement.
      interface  BlockTree
      A tree node for a statement block.
      interface  BreakTree
      A tree node for a 'break' statement.
      interface  ClassTree
      A tree node for a class, interface, enum, or annotation type declaration.
      interface  ContinueTree
      A tree node for a 'continue' statement.
      interface  DoWhileLoopTree
      A tree node for a 'do' statement.
      interface  EmptyStatementTree
      A tree node for an empty (skip) statement.
      interface  EnhancedForLoopTree
      A tree node for an "enhanced" 'for' loop statement.
      interface  ExpressionStatementTree
      A tree node for an expression statement.
      interface  ForLoopTree
      A tree node for a basic 'for' loop statement.
      interface  IfTree
      A tree node for an 'if' statement.
      interface  LabeledStatementTree
      A tree node for a labeled statement.
      interface  ReturnTree
      A tree node for a 'return' statement.
      interface  SwitchTree
      A tree node for a 'switch' statement.
      interface  SynchronizedTree
      A tree node for a 'synchronized' statement.
      interface  ThrowTree
      A tree node for a 'throw' statement.
      interface  TryTree
      A tree node for a 'try' statement.
      interface  VariableTree
      A tree node for a variable declaration.
      interface  WhileLoopTree
      A tree node for a 'while' loop statement.
      Methods in com.sun.source.tree that return StatementTree
      Modifier and Type | Method and Description
      StatementTree | IfTree.getElseStatement()
      StatementTree | WhileLoopTree.getStatement()
      StatementTree | LabeledStatementTree.getStatement()
      StatementTree | ForLoopTree.getStatement()
      StatementTree | EnhancedForLoopTree.getStatement()
      StatementTree | DoWhileLoopTree.getStatement()
      StatementTree | IfTree.getThenStatement()
      Methods in com.sun.source.tree that return types with arguments of type StatementTree
      Modifier and Type | Method and Description
      List<? extends StatementTree> | ForLoopTree.getInitializer()
      List<? extends StatementTree> | CaseTree.getStatements()
      List<? extends StatementTree> | BlockTree.getStatements()
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Static Import

In order to access static members, it is necessary to qualify references with the class they came from. For example, one must say:
double r = Math.cos(Math.PI * theta);
In order to get around this, people sometimes put static members into an interface and inherit from that interface. This is a bad idea. In fact, it's such a bad idea that there's a name for it: the Constant Interface Antipattern (see Effective Java Item 17). The problem is that a class's use of the static members of another class is a mere implementation detail. When a class implements an interface, it becomes part of the class's public API. Implementation details should not leak into public APIs.

The static import construct allows unqualified access to static members without inheriting from the type containing the static members. Instead, the program imports the members, either individually:

import static java.lang.Math.PI;
or en masse:
import static java.lang.Math.*;
Once the static members have been imported, they may be used without qualification:
double r = cos(PI * theta);
The static import declaration is analogous to the normal import declaration. Where the normal import declaration imports classes from packages, allowing them to be used without package qualification, the static import declaration imports static members from classes, allowing them to be used without class qualification.

So when should you use static import? Very sparingly! Only use it when you'd otherwise be tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface Antipattern). In other words, use it when you require frequent access to static members from one or two classes. If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from. Importing all of the static members from a class can be particularly harmful to readability; if you need only one or two members, import them individually. Used appropriately, static import can make your program more readable, by removing the boilerplate of repetition of class names.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.event.StepEvent (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.event.StepEvent

No usage of com.sun.jdi.event.StepEvent
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.request.StepRequest (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.request.StepRequest

  • Packages that use StepRequest
    Package Description
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of StepRequest in com.sun.jdi.request

      Methods in com.sun.jdi.request that return StepRequest
      Modifier and Type Method and Description
      StepRequest EventRequestManager.createStepRequest(ThreadReference thread, int size, int depth)
      Creates a new disabled StepRequest.
      Methods in com.sun.jdi.request that return types with arguments of type StepRequest
      Modifier and Type Method and Description
      List<StepRequest> EventRequestManager.stepRequests()
      Return an unmodifiable list of the enabled and disabled step requests.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.StringReference (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.StringReference

  • Packages that use StringReference
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of StringReference in com.sun.jdi

      Methods in com.sun.jdi that return StringReference
      Modifier and Type Method and Description
      StringReference VirtualMachine.mirrorOf(String value)
      Creates a string in this virtual machine.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Strings in switch Statements

In the JDK 7 release, you can use a String object in the expression of a switch statement:

public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
     String typeOfDay;
     switch (dayOfWeekArg) {
         case "Monday":
             typeOfDay = "Start of work week";
             break;
         case "Tuesday":
         case "Wednesday":
         case "Thursday":
             typeOfDay = "Midweek";
             break;
         case "Friday":
             typeOfDay = "End of work week";
             break;
         case "Saturday":
         case "Sunday":
             typeOfDay = "Weekend";
             break;
         default:
             throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
     }
     return typeOfDay;
}

The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String.equals method; consequently, the comparison of String objects in switch statements is case sensitive. The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface org.w3c.dom.stylesheets.StyleSheet (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.stylesheets.StyleSheet

  • Packages that use StyleSheet
    Package Description
    org.w3c.dom.css
    org.w3c.dom.stylesheets

    • Uses of StyleSheet in org.w3c.dom.css

      Subinterfaces of StyleSheet in org.w3c.dom.css
      Modifier and Type Interface and Description
      interface  CSSStyleSheet
      The CSSStyleSheet interface is a concrete interface used to represent a CSS style sheet i.e., a style sheet whose content type is "text/css".

    • Uses of StyleSheet in org.w3c.dom.stylesheets

      Methods in org.w3c.dom.stylesheets that return StyleSheet
      Modifier and Type Method and Description
      StyleSheet StyleSheet.getParentStyleSheet()
      For style sheet languages that support the concept of style sheet inclusion, this attribute represents the including style sheet, if one exists.
      StyleSheet LinkStyle.getSheet()
      The style sheet.
      StyleSheet StyleSheetList.item(int index)
      Used to retrieve a style sheet by ordinal index.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.stylesheets.StyleSheetList (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.stylesheets.StyleSheetList

  • Packages that use StyleSheetList
    Package Description
    org.w3c.dom.stylesheets

    • Uses of StyleSheetList in org.w3c.dom.stylesheets

      Methods in org.w3c.dom.stylesheets that return StyleSheetList
      Modifier and Type Method and Description
      StyleSheetList DocumentStyle.getStyleSheets()
      A list containing all the style sheets explicitly linked into or embedded in a document.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Subscribing/Unsubscribing to the RMI-USERS List

To subscribe:
  • Send email to: listserv@java.sun.com
  • In the body of the message, type: subscribe RMI-USERS

    After subscribing, you can choose to receive all of the RMI-USERS daily email batched into just a few email messages:

    • Send email to: listserv@java.sun.com
    • In the body of the message, type: set RMI-USERS digest

    If you decide at a later time that you'd rather receive all of the email messages individually:

    • Send email to: listserv@java.sun.com
    • In the body of the message, type: set RMI-USERS nodigest
To unsubscribe:
  • Send email to: listserv@java.sun.com
  • In the body of the message, type: signoff RMI-USERS

If you'd like to check out the RMI-USERS email archives, they can be found here.

You may also want to take a look at the answers to Frequently Asked Questions about Java RMI and Object Serialization.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Cryptography Architecture Oracle Providers Documentation

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java™ Cryptography Architecture
Oracle Providers Documentation

for JavaTM Platform Standard Edition 7

Introduction
Import Limits on Cryptographic Algorithms
The SunPKCS11 Provider
The SUN Provider
The SunRsaSign Provider
The SunJSSE Provider
The SunJCE Provider
The SunJGSS Provider
The SunSASL Provider
The XMLDSig Provider
The SunPCSC Provider
The SunMSCAPI Provider
The SunEC Provider

Note: The Standard Names Documentation contains more information about the standard names used in this document.

Introduction

The Java platform defines a set of APIs spanning major security areas, including cryptography, public key infrastructure, authentication, secure communication, and access control. These APIs allow developers to easily integrate security mechanisms into their application code. The Java Cryptography Architecture (JCA) and its Provider Architecture is a core concept of the Java Development Kit (JDK). It is assumed readers have a solid understanding of this architecture.

This document describes the technical details of the providers shipped as part of Oracle's Java Environment.

Reminder: Cryptographic implementations in the JDK are distributed through several different providers ("Sun", "SunJSSE", "SunJCE", "SunRsaSign") for both historical reasons and by the types of services provided. General purpose applications SHOULD NOT request cryptographic services from specific providers. That is:
    getInstance("...", "SunJCE");  // not recommended
        vs.
    getInstance("...");            // recommended
Otherwise, applications are tied to specific providers that may not be available on other Java implementations. They also might not be able to take advantage of available optimized providers (for example, hardware accelerators via PKCS11 or native OS implementations such as Microsoft's MSCAPI) that have a higher preference order than the specific requested provider.

Import Limits on Cryptographic Algorithms

Due to import regulations in some countries, the Oracle implementation provides a default cryptographic jurisdiction policy file that limits the strength of cryptographic algorithms. Here are the maximum key sizes allowed by this "strong" version of the jurisdiction policy files:

Algorithm | Maximum Keysize
DES | 64
DESede | *
RC2 | 128
RC4 | 128
RC5 | 128
RSA | *
all others | 128

If stronger algorithms are needed (for example, AES with 256-bit keys), the JCE Unlimited Strength Jurisdiction Policy Files must be obtained and installed in the JDK/JRE.

It is the user's responsibility to verify that this action is permissible under local regulations.

The SunPKCS11 Provider

The Cryptographic Token Interface Standard ( PKCS#11) provides native programming interfaces to cryptographic mechanisms, such as hardware cryptographic accelerators and Smart Cards. When properly configured, the SunPKCS11 provider enables applications to use the standard JCA/JCE APIs to access native PKCS#11 libraries. The SunPKCS11 provider itself does not contain cryptographic functionality, it is simply a conduit between the Java environment and the native PKCS11 providers. The Java PKCS#11 Reference Guide has a much more detailed treatment of this provider.

The SUN Provider

JDK 1.1 introduced the Provider architecture. The first JDK provider was named SUN, and contained two types of cryptographic services (MessageDigests and Signatures). In later releases, other mechanisms were added (SecureRandom number generators, KeyPairGenerators, KeyFactorys, and so on.).

United States export regulations in effect at the time placed significant restrictions on the type of cryptographic functionality that could be made available internationally in the JDK. For this reason, the SUN provider has historically contained cryptographic engines that did not directly encrypt or decrypt data.

The following algorithms are available in the SUN provider:

Engine | Algorithm Names
AlgorithmParameterGenerator | DSA
AlgorithmParameters | DSA
CertificateFactory | X.509
CertPathBuilder | PKIX
CertPathValidator | PKIX
CertStore | Collection LDAP
Configuration | JavaLoginConfig
KeyFactory | DSA
KeyPairGenerator | DSA
KeyStore | JKS
MessageDigest | MD2 MD5 SHA-1 SHA-256 SHA-384 SHA-512
Policy | JavaPolicy
SecureRandom | SHA1PRNG
Signature | NONEwithDSA SHA1withDSA

Keysize Restrictions

The SUN provider uses the following default keysizes (in bits) and enforces the following restrictions:

KeyPairGenerator

Alg. Name | Default Keysize | Restrictions/Comments
DSA | 1024 | Keysize must be a multiple of 64, ranging from 512 to 1024 (inclusive).

AlgorithmParameterGenerator

Alg. Name | Default Keysize | Restrictions/Comments
DSA | 1024 | Keysize must be a multiple of 64, ranging from 512 to 1024 (inclusive).

CertificateFactory/CertPathBuilder/ CertPathValidator/CertStore Implementations

Additional details on the SUN provider implementations for CertificateFactory, CertPathBuilder, CertPathValidator and CertStore are documented in Appendix B of the PKI Programmer's Guide.

The SunRsaSign Provider

The SunRsaSign provider was introduced in JDK 1.3 as an enhanced replacement for the RSA signatures in the SunJSSE provider.

The following algorithms are available in the SunRsaSign provider:

Engine | Algorithm Names
KeyFactory | RSA
KeyPairGenerator | RSA
Signature | MD2withRSA MD5withRSA SHA1withRSA SHA256withRSA SHA384withRSA SHA512withRSA

Keysize Restrictions

The SunRsaSign provider uses the following default keysize (in bits) and enforces the following restriction:

KeyPairGenerator

Alg. Name | Default Keysize | Restrictions/Comments
RSA | 1024 | Keysize must range between 512 and 65536 bits, the latter of which is unnecessarily large.

The SunJSSE Provider

The Java Secure Socket Extension (JSSE) was originally released as a separate "Optional Package" (also briefly known as a "Standard Extension"), and was available for JDK 1.2.n and 1.3.n. The SunJSSE provider was introduced as part of this release.

In earlier JDK releases, there were no RSA signature providers available in the JDK, therefore SunJSSE had to provide its own RSA implementation in order to use commonly available RSA-based certificates. JDK 5 introduced the SunRsaSign provider, which provides all the functionality (and more) of the SunJSSE provider. Applications targeted at JDK 5.0 and later should request instances of the SunRsaSign provider instead. For backward compatibility, the RSA algorithms are still available through this provider, but are actually implemented in the SunRsaSign provider.

Algorithms

The following algorithms are available in the SunJSSE provider:

Engine Algorithm Name(s)
KeyFactory
RSA
KeyManagerFactory
SunX509: A factory for X509ExtendedKeyManager instances that manage X.509 certificate-based key pairs for local side authentication according to the rules defined by the IETF PKIX working group in RFC 3280 or its successor. This KeyManagerFactory supports initialization using a Keystore object, but does not currently support initialization using the class javax.net.ssl.ManagerFactoryParameters.

PKIX: A factory for X509ExtendedKeyManager instances that manage X.509 certificate-based key pairs for local side authentication according to the rules defined by the IETF PKIX working group in RFC 3280 or its successor. This KeyManagerFactory currently supports initialization using a KeyStore object or javax.net.ssl.KeyStoreBuilderParameters.
KeyPairGenerator
RSA
KeyStore
PKCS12
Signature
MD2withRSA
MD5withRSA
SHA1withRSA
SSLContext
SSLv3
TLSv1
TLSv1.1
TLSv1.2
TrustManagerFactory
SunX509: A factory for X509ExtendedTrustManager instances that validate certificate chains according to the rules defined by the IETF PKIX working group in RFC 3280 or its successor. This TrustManagerFactory supports initialization using a Keystore object, but does not currently support initialization using the class javax.net.ssl.ManagerFactoryParameters.

PKIX: A factory for X509ExtendedTrustManager instances that validate certificate chains according to the rules defined by the IETF PKIX working group in RFC 3280 or its successor. This TrustManagerFactory currently supports initialization using a KeyStore object or javax.net.ssl.CertPathTrustManagerParameters.

Protocols

The SunJSSE supports the following protocol parameters:

Protocol | Enabled by Default for Client | Enabled by Default for Server
SSLv3 | Yes | Yes
TLSv1 | Yes | Yes
TLSv1.1 | No | Yes
TLSv1.2 | No | Yes
SSLv2Hello | No | No

Although SunJSSE in the Java SE 7 release supports TLS 1.1 and TLS 1.2, neither version is enabled by default for client connections. Some servers do not implement forward compatibility correctly and refuse to talk to TLS 1.1 or TLS 1.2 clients. For interoperability, SunJSSE does not enable TLS 1.1 or TLS 1.2 by default for client connections.

Server connections have no such interoperability problem. TLS 1.1 and TLS 1.2 are enabled by default for server connections.

The SSLv3, TLSv1, and TLSv1.1 protocols allow you to send SSLv3, TLSv1, and TLSv1.1 hellos encapsulated in an SSLv2 format hello. In the Java SE 7 release, this support is still present but is disabled by default.

Cipher Suites

SunJSSE supports a large number of cipher suites. The two tables that follow show the cipher suites supported by SunJSSE in preference order and the release in which they were introduced.

The first table lists the cipher suites that are enable by default. The second table shows cipher suites that are supported by SunJSSE but disabled by default.

Default Enabled Cipher Suites
Cipher Suite | J2SE v1.4 | J2SE v1.4.1, v1.4.2 | J2SE 5.0 | Java SE 6 | Java SE 7
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 |  |  |  |  | X1
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 |  |  |  |  | X1
TLS_RSA_WITH_AES_256_CBC_SHA256 |  |  |  |  | X1
TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 |  |  |  |  | X1
TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 |  |  |  |  | X1
TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 |  |  |  |  | X1
TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 |  |  |  |  | X1
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA |  |  |  | X | X
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA |  |  |  | X | X
TLS_RSA_WITH_AES_256_CBC_SHA |  | X | X | X | X
TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA |  |  |  | X | X
TLS_ECDH_RSA_WITH_AES_256_CBC_SHA |  |  |  | X | X
TLS_DHE_RSA_WITH_AES_256_CBC_SHA |  | X | X | X | X
TLS_DHE_DSS_WITH_AES_256_CBC_SHA |  | X | X | X | X
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 |  |  |  |  | X1
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 |  |  |  |  | X1
TLS_RSA_WITH_AES_128_CBC_SHA256 |  |  |  |  | X1
TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 |  |  |  |  | X1
TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 |  |  |  |  | X1
TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 |  |  |  |  | X1
TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 |  |  |  |  | X1
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA |  |  |  | X | X
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA |  |  |  | X | X
TLS_RSA_WITH_AES_128_CBC_SHA |  | X | X | X | X
TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA |  |  |  | X | X
TLS_ECDH_RSA_WITH_AES_128_CBC_SHA |  |  |  | X | X
TLS_DHE_RSA_WITH_AES_128_CBC_SHA |  | X | X | X | X
TLS_DHE_DSS_WITH_AES_128_CBC_SHA |  | X | X | X | X
TLS_ECDHE_ECDSA_WITH_RC4_128_SHA |  |  |  | X | X
TLS_ECDHE_RSA_WITH_RC4_128_SHA |  |  |  | X | X
SSL_RSA_WITH_RC4_128_SHA | X | X | X | X | X
TLS_ECDH_ECDSA_WITH_RC4_128_SHA |  |  |  | X | X
TLS_ECDH_RSA_WITH_RC4_128_SHA |  |  |  | X | X
TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA |  |  |  | X | X
TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA |  |  |  | X | X
SSL_RSA_WITH_3DES_EDE_CBC_SHA | X | X | X | X | X
TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA |  |  |  | X | X
TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA |  |  |  | X | X
SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA |  | X | X | X | X
SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA | X | X | X | X | X
SSL_RSA_WITH_RC4_128_MD5 | X | X | X | X | X
TLS_EMPTY_RENEGOTIATION_INFO_SCSV 2 |  | 1.4.2u28+ | u26+ | u22+ | X

1 Cipher suites with SHA384 and SHA256 are available only for TLS 1.2 or later.

2 TLS_EMPTY_RENEGOTIATION_INFO_SCSV is a new pseudo-cipher suite to support RFC 5746. See the Transport Layer Security (TLS) Renegotiation Issue section of the JSEE Reference Guide for more information.

Default Disabled Cipher Suites
Cipher Suite | J2SE v1.4 | J2SE v1.4.1, v1.4.2 | J2SE 5.0 | Java SE 6 | Java SE 7
TLS_DH_anon_WITH_AES_256_CBC_SHA256 |  |  |  |  | X
TLS_ECDH_anon_WITH_AES_256_CBC_SHA |  |  |  | X | X
TLS_DH_anon_WITH_AES_256_CBC_SHA |  | X | X | X | X
TLS_DH_anon_WITH_AES_128_CBC_SHA256 |  |  |  |  | X
TLS_ECDH_anon_WITH_AES_128_CBC_SHA |  |  |  | X | X
TLS_DH_anon_WITH_AES_128_CBC_SHA |  | X | X | X | X
TLS_ECDH_anon_WITH_RC4_128_SHA |  |  |  | X | X
SSL_DH_anon_WITH_RC4_128_MD5 | X | X | X | X | X
TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA |  |  |  | X | X
SSL_DH_anon_WITH_3DES_EDE_CBC_SHA | X | X | X | X | X
TLS_RSA_WITH_NULL_SHA256 |  |  |  |  | X
TLS_ECDHE_ECDSA_WITH_NULL_SHA |  |  |  | X | X
TLS_ECDHE_RSA_WITH_NULL_SHA |  |  |  | X | X
SSL_RSA_WITH_NULL_SHA | X | X | X | X | X
TLS_ECDH_ECDSA_WITH_NULL_SHA |  |  |  | X | X
TLS_ECDH_RSA_WITH_NULL_SHA |  |  |  | X | X
TLS_ECDH_anon_WITH_NULL_SHA |  |  |  | X | X
SSL_RSA_WITH_NULL_MD5 | X | X | X | X | X
SSL_RSA_WITH_DES_CBC_SHA | X | X | X | X | X1
SSL_DHE_RSA_WITH_DES_CBC_SHA |  | X | X | X | X1
SSL_DHE_DSS_WITH_DES_CBC_SHA | X | X | X | X | X1
SSL_DH_anon_WITH_DES_CBC_SHA | X | X | X | X | X1
SSL_RSA_EXPORT_WITH_RC4_40_MD5 | X | X | X | X | X2
SSL_DH_anon_EXPORT_WITH_RC4_40_MD5 | X | X | X | X | X2
SSL_RSA_EXPORT_WITH_DES40_CBC_SHA |  | X | X | X | X2
SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA |  | X | X | X | X2
SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA | X | X | X | X | X2
SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA | X | X | X | X | X2
TLS_KRB5_WITH_RC4_128_SHA |  |  | X | X | X
TLS_KRB5_WITH_RC4_128_MD5 |  |  | X | X | X
TLS_KRB5_WITH_3DES_EDE_CBC_SHA |  |  | X | X | X
TLS_KRB5_WITH_3DES_EDE_CBC_MD5 |  |  | X | X | X
TLS_KRB5_WITH_DES_CBC_SHA |  |  | X | X | X1
TLS_KRB5_WITH_DES_CBC_MD5 |  |  | X | X | X1
TLS_KRB5_EXPORT_WITH_RC4_40_SHA |  |  | X | X | X2
TLS_KRB5_EXPORT_WITH_RC4_40_MD5 |  |  | X | X | X2
TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA |  |  | X | X | X2
TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5 |  |  | X | X | X2

1 RFC 5246 TLS 1.2 forbids the use of these suites. These can be used in the SSLv3/TLS1.0/TLS1.1 protocols, but cannot be used in TLS 1.2 and later.

2 RFC 4346 TLS 1.1 forbids the use of these suites. These can be used in the SSLv3/TLS1.0 protocols, but cannot be used in TLS 1.1 and later.

Cipher suites that use AES_256 require installation of the JCE Unlimited Strength Jurisdiction Policy Files. See Import Limits on Cryptographic Algorithms.

Cipher suites that use Elliptic Curve Cryptography (ECDSA, ECDH, ECDHE, ECDH_anon) require a JCE cryptographic provider that meets the following requirements:

  • The provider must implement ECC as defined by the classes and interfaces in the packages java.security.spec and java.security.interfaces. The getAlgorithm() method of elliptic curve key objects must return the string "EC".

  • The provider must support the Signature algorithms SHA1withECDSA and NONEwithECDSA, the KeyAgreement algorithm ECDH, and a KeyPairGenerator and a KeyFactory for algorithm EC. If one of these algorithms is missing, SunJSSE will not allow EC cipher suites to be used.

  • The provider must support all the SECG curves referenced in RFC 4492 specification, section 5.1.1 (see also appendix A). In certificates, points should be encoded using the uncompressed form and curves should be encoded using the namedCurve choice, that is, using an object identifier.

If these requirements are not met, EC cipher suites may not be negotiated correctly.

Tighter Checking of EncryptedPreMasterSecret Version Numbers

Prior to the Java SE 7 release, the SSL/TLS implementation did not check the version number in PreMasterSecret, and the SSL/TLS client did not send the correct version number by default. Unless the system property com.sun.net.ssl.rsaPreMasterSecretFix is set to true, the TLS client sends the active negotiated version, but not the expected maximum version supported by the client.

For compatibility, this behavior is preserved for SSL version 3.0 and TLS version 1.0. However, for TLS version 1.1 or later, the implementation tightens checking the PreMasterSecret version numbers as required by RFC 5246. Clients always send the correct version number, and servers check the version number strictly. The system property, com.sun.net.ssl.rsaPreMasterSecretFix, is not used in TLS 1.1 or later.

The SunJCE Provider

As described briefly in The SUN Provider, US export regulations at the time restricted the type of cryptographic functionality that could be made available in the JDK. A separate API and reference implementation was developed that allowed applications to encrypt/decrypt data. The Java Cryptographic Extension (JCE) was released as a separate "Optional Package" (also briefly known as a "Standard Extension"), and was available for JDK 1.2.x and 1.3.x. During the development of JDK 1.4, regulations were relaxed enough that JCE (and SunJSSE) could be bundled as part of the JDK.

The following algorithms are available in the SunJCE provider:

Engine | Algorithm Names
AlgorithmParameterGenerator | DiffieHellman
AlgorithmParameters | AES Blowfish DES DESede DiffieHellman OAEP PBEWithMD5AndDES PBEWithMD5AndTripleDES PBEWithSHA1AndDESede PBEWithSHA1AndRC2_40 RC2
Cipher | See the Cipher table.
KeyAgreement | DiffieHellman
KeyFactory | DiffieHellman
KeyGenerator | AES ARCFOUR Blowfish DES DESede HmacMD5 HmacSHA1 HmacSHA256 HmacSHA384 HmacSHA512 RC2
KeyPairGenerator | DiffieHellman
KeyStore | JCEKS
Mac | HmacMD5 HmacSHA1 HmacSHA256 HmacSHA384 HmacSHA512
SecretKeyFactory | DES DESede PBEWithMD5AndDES PBEWithMD5AndTripleDES PBEWithSHA1AndDESede PBEWithSHA1AndRC2_40 PBKDF2WithHmacSHA1

The following table lists cipher algorithms available in the SunJCE provider.

Algorithm Name | Modes | Paddings
AES | ECB, CBC, PCBC, CTR, CTS, CFB, CFB8..CFB128, OFB, OFB8..OFB128 | NOPADDING, PKCS5PADDING, ISO10126PADDING
AESWrap | ECB | NOPADDING
ARCFOUR | ECB | NOPADDING
Blowfish, DES, DESede, RC2 | ECB, CBC, PCBC, CTR, CTS, CFB, CFB8..CFB64, OFB, OFB8..OFB64 | NOPADDING, PKCS5PADDING, ISO10126PADDING
DESedeWrap | CBC | NOPADDING
PBEWithMD5AndDES, PBEWithMD5AndTripleDES1 PBEWithSHA1AndDESede, PBEWithSHA1AndRC2_40 | CBC | PKCS5Padding
RSA | ECB | NOPADDING, PKCS1PADDING, OAEPWITHMD5ANDMGF1PADDING, OAEPWITHSHA1ANDMGF1PADDING, OAEPWITHSHA-1ANDMGF1PADDING, OAEPWITHSHA-256ANDMGF1PADDING, OAEPWITHSHA-384ANDMGF1PADDING, OAEPWITHSHA-512ANDMGF1PADDING

1 PBEWithMD5AndTripleDES is a proprietary algorithm that has not been standardized.

Keysize Restrictions

The SunJCE provider uses the following default keysizes (in bits) and enforces the following restrictions:

KeyGenerator

Algorithm Name | Default Keysize | Restrictions/Comments
AES | 128 | Keysize must be equal to 128, 192, or 256.
ARCFOUR (RC4) | 128 | Keysize must range between 40 and 1024 (inclusive).
Blowfish | 128 | Keysize must be a multiple of 8, ranging from 32 to 448 (inclusive).
DES | 56 | Keysize must be equal to 56.
DESede (Triple DES) 168 Keysize must be equal to 112 or 168.

A keysize of 112 will generate a Triple DES key with 2 intermediate keys, and a keysize of 168 will generate a Triple DES key with 3 intermediate keys.

Due to the "Meet-In-The-Middle" problem, even though 112 or 168 bits of key material are used, the effective keysize is 80 or 112 bits respectively.
HmacMD5 | 512 | No keysize restriction.
HmacSHA1 | 512 | No keysize restriction.
HmacSHA256 | 256 | No keysize restriction.
HmacSHA384 | 384 | No keysize restriction.
HmacSHA512 | 512 | No keysize restriction.
RC2 | 128 | Keysize must range between 40 and 1024 (inclusive).

NOTE: The various Password-Based Encryption (PBE) algorithms use various algorithms to generate key data, and ultimately depends on the targeted Cipher algorithm. For example, "PBEWithMD5AndDES" will always generate 56-bit keys.

KeyPairGenerator

Algorithm Name | Default Keysize | Restrictions/Comments
Diffie-Hellman (DH) | 1024 | Keysize must be a multiple of 64, ranging from 512 to 1024 (inclusive).

AlgorithmParameterGenerator

Alg. Name | Default Keysize | Restrictions/Comments
Diffie-Hellman (DH) | 1024 | Keysize must be a multiple of 64, ranging from 512 to 1024 (inclusive).
DSA | 1024 | Keysize must be a multiple of 64, ranging from 512 to 1024 (inclusive).

The SunJGSS Provider

The following algorithms are available in the SunJGSS provider:

OID | Name
1.2.840.113554.1.2.2 | Kerberos v5
1.3.6.1.5.5.2 | SPNEGO

The SunSASL Provider

The following algorithms are available in the SunSASL provider:

Engine | Algorithm Names
SaslClient | CRAM-MD5 DIGEST-MD5 EXTERNAL GSSAPI PLAIN
SaslServer | CRAM-MD5 DIGEST-MD5 GSSAPI

The XMLDSig Provider

The following algorithms are available in the XMLDSig provider:

Engine | Algorithm Names
KeyInfoFactory | DOM
TransformService | http://www.w3.org/TR/2001/REC-xml-c14n-20010315 - (CanonicalizationMethod.INCLUSIVE) http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments - (CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS) http://www.w3.org/2001/10/xml-exc-c14n# - (CanonicalizationMethod.EXCLUSIVE) http://www.w3.org/2001/10/xml-exc-c14n#WithComments - (CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS) http://www.w3.org/2000/09/xmldsig#base64 - (Transform.BASE64) http://www.w3.org/2000/09/xmldsig#enveloped-signature - (Transform.ENVELOPED) http://www.w3.org/TR/1999/REC-xpath-19991116 - (Transform.XPATH) http://www.w3.org/2002/06/xmldsig-filter2 - (Transform.XPATH2) http://www.w3.org/TR/1999/REC-xslt-19991116 - (Transform.XSLT)
XMLSignatureFactory | DOM

The SunPCSC Provider

The SunPCSC provider enables applications to use the Java Smart Card I/O API to interact with the PC/SC Smart Card stack of the underlying operating system. On some operating systems, it may be necessary to enable and configure the PC/SC stack before it is usable. Consult your operating system documentation for details.

On Solaris and Linux platforms, SunPCSC accesses the PC/SC stack via the libpcsclite.so library. It looks for this library in the directories /usr/$LIBISA and /usr/local/$LIBISA, where $LIBISA is expanded to lib on 32-bit platforms, lib/64 on 64-bit Solaris platforms, and lib64 on 64-bit Linux platforms. The system property sun.security.smartcardio.library may also be set to the full filename of an alternate libpcsclite.so implementation. On Windows platforms, SunPCSC always calls into winscard.dll and no Java-level configuration is necessary or possible.

If PC/SC is available on the host platform, the SunPCSC implementation can be obtained via TerminalFactory.getDefault() and TerminalFactory.getInstance("PC/SC"). If PC/SC is not available or not correctly configured, a getInstance() call will fail with a NoSuchAlgorithmException and getDefault() will return a JRE built-in implementation that does not support any terminals.

The following algorithms are available in the SunPCSC provider:

Engine | Algorithm Names
TerminalFactory | PC/SC

The SunMSCAPI Provider

The SunMSCAPI provider enables applications to use the standard JCA/JCE APIs to access the native cryptographic libraries, certificates stores and key containers on the Microsoft Windows platform. The SunMSCAPI provider itself does not contain cryptographic functionality, it is simply a conduit between the Java environment and the native cryptographic services on Windows.

The following algorithms are available in the SunMSCAPI provider:

Engine | Algorithm Names
Cipher | RSA RSA/ECB/PKCS1Padding only
KeyPairGenerator | RSA
KeyStore Windows-MY

The keystore type that identifies the native Microsoft Windows MY keystore. It contains the user's personal certificates and associated private keys.

Windows-ROOT

The keystore type that identifies the native Microsoft Windows ROOT keystore. It contains the certificates of Root certificate authorities and other self-signed trusted certificates.
SecureRandom Windows-PRNG

The name of the native pseudo-random number generation (PRNG) algorithm.
Signature MD2withRSA
MD5withRSA
SHA1withRSA

Keysize Restrictions

The SunMSCAPI provider uses the following default keysizes (in bits) and enforce the following restrictions:

KeyGenerator

Alg. Name | Default Keysize | Restrictions/Comments
RSA | 1024 | Keysize ranges from 384 bits to 16,384 bits (depending on the underlying Microsoft Windows cryptographic service provider).

The SunEC Provider

The SunEC provider implements Elliptical Curve Cryptography (ECC). ECC is emerging as an attractive public-key cryptosystem for mobile/wireless and other environments. Compared to traditional cryptosystems like RSA, ECC offers equivalent security with smaller key sizes, which results in faster computations, lower power consumption, as well as memory and bandwidth savings.

Applications can now use the standard JCA/JCE APIs to access ECC functionality without the dependency on external ECC libraries(via SunPKCS11), as was the case in the JDK 6 release.

The following algorithms are available in the SunEC provider:

Engine | Algorithm Name(s)
AlgorithmParameters | EC
KeyAgreement | ECDH
KeyFactory | EC
KeyPairGenerator | EC
Signature | NONEwithECDSA SHA1withECDSA SHA256withECDSA SHA384withECDSA SHA512withECDSA

Keysize Restrictions

The SunEC provider uses the following default keysizes (in bits) and enforces the following restrictions:

KeyPairGenerator

Alg. Name | Default Keysize | Restrictions/Comments
EC | 256 | Keysize must range from 112 to 571 (inclusive).
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


sun.rmi Properties

WARNING: The properties described here are not supported, can change at any time, and only exist in certain implementations of JavaTM Remote Method Invocation (Java RMI) from Sun Microsystems. These properties are not part of the Java RMI public API. To see a list of the properties that are part of the public API, please refer to the page, java.rmi Properties.

Please Note: Unless otherwise stated, any output from these properties is sent to System.err.

Each of the properties that have names ending in ".logLevel" have possible values of "SILENT", "BRIEF", and "VERBOSE". These values are case insensitive and may be abbreviated as a string containing the first n letters, where n is greater than or equal to 1. If not specified, these properties have a default value of "SILENT". A value of "BRIEF" causes the corresponding Logger to be set to the level Level.FINE, and a value of "VERBOSE" causes the corresponding Logger to be set to the level Level.FINER. Use of the logging configuration file is now preferred over the use of these sun.rmi.* system properties for logging.

Logging messages are sent to System.err. For instance, if a property is said to send output to the "transport" log, this means that logging messages are sent to a LogStream returned by java.rmi.server.LogStream.log("transport"), which sends messages to System.err, unless you've set it to something else.

Properties that can be set on rmid

sun.rmi.activation.execPolicy (1.3 and later)
The value of this property controls the policy that rmid uses to determine whether or not the information in an ActivationGroupDesc may be used to launch a virtual machine for an activation group. The possible values for the property are default, none, or the fully qualified name of a class that implements a method named checkExecCommand that is called to verify ActivationGroupDesc information. For details, see the tools documentation for rmid [Solaris and Linux] [Windows].
sun.rmi.activation.execTimeout (1.2 and later)
The value of this property represents the time (in milliseconds) that the activation system will wait for a spawned activation group to start up. Setting this property gives you the ability to shorten or lengthen the maximum time that rmid will wait for an activation group to start up. The default value is 30000 milliseconds (30 seconds).
sun.rmi.activation.groupThrottle (5.0 and later)
The value of this property represents the maximum number of activation group VMs that rmid will allow to be in the "spawning but not yet active" state simultaneously. If more VMs need to be started, they will queue up until one of the current spawn attempts either succeeds or times out. Note that this property does not limit the maximum number of active VMs; it is intended to smooth out sudden spikes of activity to avoid reaching operating system limits. While setting the value of this property to a lower number may result in a longer start-up time for rmid, and setting the value to a higher number could shorten the start-up time, setting this value too high can crash rmid, because your system may run out of resources. The default value is 3. In previous releases, this property was named sun.rmi.rmid.maxstartgroup which is no longer supported.
sun.rmi.activation.groupTimeout (5.0 and later)
The value of this property represents the time (in milliseconds) that rmid will wait after destroying an activation group's process before creating a new incarnation of the activation group. The default value is 60000 milliseconds (60 seconds).
sun.rmi.activation.snapshotInterval (1.2 and later)
This property controls the number of updates for which the activation system will wait before it serializes a snapshot of its state to the rmid log file on disk. An "update" refers to a persistent change in the state of the activation system (for example, the registration of an Activatable object) since the last snapshot was taken. Changing the value of this property can be used to make rmid re-start more quickly (by taking snapshots of the log more often) or to make rmid more efficient (by taking snapshots of the log less often). The value of this property is a positive integer value. The default value is 200.
sun.rmi.log.debug (1.2 and later)
If this value is true, details of rmid's logging activity are sent to System.err.
sun.rmi.server.activation.debugExec (1.2 and later)
If this value is true, the activation system will print out debugging information to the command line that is used for spawning activation groups. By default, the value is false, so debugging information is not printed.

Properties that are useful to set on VMs that export remote objects

sun.rmi.dgc.ackTimeout (1.4 and later)
The value of this property represents the length of time (in milliseconds) that the server-side Java RMI runtime will strongly refer to a remote object (or a reference to a remote object) that has been returned from the current virtual machine as part of the result of a remote method call, until it receives positive acknowledgment from the client that the remote reference has been fully received and processed. This timeout only applies to failure situations (in which the client fails to send the acknowledgment). Setting the value too low can increase the risk of a remote object being prematurely garbage collected when the only known reference to the remote object is the one in transit as part of the remote method call result. The maximum value is Long.MAX_VALUE. The default value is 300000 (five minutes).
sun.rmi.dgc.checkInterval (1.1 and later)
The value of this property represents (in milliseconds) how often the Java RMI runtime checks for expired DGC leases. The default value is half the value of the java.rmi.dgc.leaseValue property.
sun.rmi.dgc.logLevel (1.1 and later)
This property controls the logging of incoming and outgoing calls related to DGC lease granting, renewing, and expiration. It sends output to the "dgc" log.
sun.rmi.dgc.server.gcInterval (1.2 and later)
When it is necessary to ensure that unreachable remote objects are unexported and garbage collected in a timely fashion, the value of this property represents the maximum interval (in milliseconds) that the Java RMI runtime will allow between garbage collections of the local heap. The default value is 3600000 milliseconds (one hour).
sun.rmi.loader.logLevel (1.2 and later)
This property controls the logging of each class name and codebase, whenever the Java RMI runtime attempts to load a class as a result of unmarshalling either an argument or return value. This property sends output to the "loader" log.

sun.rmi.server.exceptionTrace (1.2 and later)
This property controls the output of server-side stack traces from exceptions and errors that are thrown by dispatched, incoming remote calls. If this value is true, exception stack traces will be printed. By default (false), exception and error stack traces are not printed.

sun.rmi.server.suppressStackTraces (1.4 and later)
If this value is true, the server-side Java RMI runtime implementation will clear the stack traces of all exceptions thrown from the current virtual machine as the result of remote calls. This property is useful for certain server applications that may wish to prevent any server-side stack trace data from accompanying an exception to be marshalled out as the result of an incoming remote call (as part of the exception's default serialized form in J2SE 1.4), perhaps for reasons of performance or confidentiality.
sun.rmi.transport.logLevel (1.1 and later)
This property controls detailed logging throughout the transport layer. It sends output to the "transport" log.
sun.rmi.transport.tcp.localHostNameTimeOut (1.1.7 and later)
The value of this property represents the time (in milliseconds) that the Java RMI runtime will wait to obtain a fully qualified domain name for the local host. The default value is 10000 milliseconds (10 seconds).
sun.rmi.transport.tcp.logLevel (1.1 and later)
This property provides detailed logging for the TCP-specific transport sub-layer. It sends output to the "tcp" log.

sun.rmi.transport.tcp.readTimeout (1.2.2 and later)
The value of this property represents the time (in milliseconds) used as an idle timeout for incoming TCP connections the Java RMI runtime uses. The value is passed to java.net.Socket.setSoTimeout. This property is used only for cases where a client has not dropped an unused connection as it should (see sun.rmi.transport.connectionTimeout). The default value is 2*3600*1000 milliseconds (two hours).
sun.rmi.transport.tcp.maxConnectionThreads (6 and later)
The value of this property controls the maximum size of the pool of threads used to handle incoming connections, and thus it places an upper bound on the number of incoming remote method invocations that can execute concurrently. Setting this property to a lower value may improve the throughput of a Java RMI server application under heavy load, but setting it too low may (depending on the nature of the application's remote invocation patterns) lead to deadlock or starvation. The default value is the maximum, Integer.MAX_VALUE, which effectively means no limit.
sun.rmi.transport.tcp.threadKeepAliveTime (6 and later)
The value of this property controls the amount of time that a thread in the pool of threads used to handle incoming connections will remain idle before terminating. The default value is 60000 milliseconds (one minute).

Properties that are useful to set on VMs that make remote method calls

sun.rmi.client.logCalls (1.4 and later)
If the value of this property is true, the sun.rmi.client.call logger will be set to the level Level.FINER. Remote calls are logged at the level Level.FINER, and exceptions from remote calls are logged at the level Level.FINE.
sun.rmi.dgc.cleanInterval (1.1 and later)
The value of this property represents the maximum length of time (in milliseconds) that the Java RMI runtime will wait before retrying a failed DGC "clean" call. The default value is 180000 milliseconds (three minutes).
sun.rmi.dgc.client.gcInterval (1.2 and later)
When it is necessary to ensure that DGC clean calls for unreachable remote references are delivered in a timely fashion, the value of this property represents the maximum interval (in milliseconds) that the Java RMI runtime will allow between garbage collections of the local heap. The default value is 3600000 milliseconds (one hour).
sun.rmi.loader.logLevel (1.2 and later)
This property controls the logging of each class name and codebase, whenever the Java RMI runtime attempts to load a class as a result of unmarshalling either an argument or return value. This property sends output to the "loader" log.
sun.rmi.server.logLevel (1.1 and later)
This property controls the logging of information related to outgoing calls, including some connection-reuse information. It sends output to the "transport" log.

sun.rmi.transport.connectionTimeout (1.1.6 and later)
The value of this property represents the period (in milliseconds) for which socket connections may reside in an "unused" state, before the Java RMI runtime will allow those connections to be freed (closed). The default value is 15000 milliseconds (15 seconds). See also sun.rmi.transport.tcp.readTimeout.
sun.rmi.transport.logLevel (1.1 and later)
This property controls detailed logging throughout the transport layer. It sends output to the "transport" log.
sun.rmi.transport.proxy.connectTimeout (1.1 and later)
The value of this property represents the maximum length of time (in milliseconds) that the Java RMI runtime will wait for a connection attempt (createSocket) to complete, before attempting to contact the server using HTTP. This property is only used when the http.proxyHost property is set and the value of java.rmi.server.disableHttp is false. The default value is 15000 milliseconds (15 seconds).

sun.rmi.transport.proxy.eagerHttpFallback (1.4.1 and later)
If this value is true and the java.rmi.server.disableHttp system property is not set, then the default global RMISocketFactory will fall back to HTTP tunneling when any java.net.SocketException is thrown from an initial (direct) connection attempt, as opposed to the default behavior of falling back to HTTP tunneling only if an initial connection attempt throws a java.net.UnknownHostException or java.net.NoRouteToHostException.

This setting can be useful when dealing with firewalls that deny (instead of ignore) connection attempts to unauthorized ports, resulting in java.net.ConnectionExceptions inside the client's default global RMISocketFactory. If this system property is not enabled, then such ConnectionExceptions will not trigger HTTP fallback, since they are neither UnknownHostExceptions nor NoRouteToHostExceptions. However, if this system property is enabled, then the ConnectionExceptions will cause HTTP fallback to occur, because ConnectionException is a subclass of SocketException.

sun.rmi.transport.proxy.logLevel (1.1 and later)
This property controls the logging of events (createSocket and createServerSocket) when the default RMISocketFactory class is used. This type of logging is likely to be useful for applications that use Java RMI over HTTP. Events in custom socket factories are not logged by this property. It sends some messages to the "proxy" log, and others to the "transport" log.
sun.rmi.transport.tcp.handshakeTimeout (1.4 and later)
The value of this property represents the length of time (in milliseconds) that the client-side Java RMI runtime will use as a socket read timeout when reading initial handshake data (protocol acknowledgment) when establishing a new JRMP connection. This property is used to configure how long the Java RMI runtime will wait before deciding that a TCP connection accepted by a remote server cannot actually be used, either because the entity listening on the remote host's port is not actually a Java RMI server, or because the server is somehow not functioning correctly. The maximum value is Integer.MAX_VALUE, and a value of zero indicates an infinite timeout. The default value is 60000 (one minute).
sun.rmi.transport.tcp.responseTimeout (1.4 and later)
The value of this property represents the length of time (in milliseconds) that the client-side Java RMI runtime will use as a socket read timeout on an established JRMP connection when reading response data for a remote method invocation. Therefore, this property can be used to impose a timeout on waiting for the results of remote invocations; if this timeout expires, the associated invocation will fail with a java.rmi.RemoteException. Setting this property should be done with due consideration, however, because it effectively places an upper bound on the allowed duration of any successful outgoing remote invocation. The maximum value is Integer.MAX_VALUE, and a value of zero indicates an infinite timeout. The default value is zero (no timeout).
sun.rmi.transport.tcp.logLevel (1.1 and later)
This property provides detailed logging for the TCP-specific transport sub-layer. It sends output to the "tcp" log.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Swing Changes and New Features

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Swing Changes and New Features for Java™ 2 SDK, Standard Edition, v 1.4

Changes Specific to releases 1.4.1 and 1.4.2

This document contains information relevant to all 1.4.* releases. For information specific to 1.4.1 and 1.4.2, see Swing Changes Since Java 2 SDK, Standard Edition, v 1.4.

Major Changes

Certain features, typically ones that have a large impact on Swing, have been extensively written up in separate documents. The following link to these documents:

  • Windows XP look and feel
  • GTK+ look and feel
  • Support for indeterminate progress bars
  • JTabbedPane with scrollable tabs
  • JSpinner
  • JFormattedTextField
  • Popup and PopupFactory
  • New Focus Model Specification and Javadoc
  • Windows look and feel update.
  • The new Drag and Drop architecture.

Minor Changes

Each section contains changes for a set of related classes. Most of the sections are focused on the classes that are part of a single Swing component like JEditorPane or JTable. Each API change is associated with a link to a report on the Bug Database , where you'll find the original bug or RFE ("request for enhancement") that motivated the change. In this document you'll also find the following information for each API change:

  • The method signatures with a link to the Javadoc for new methods or methods whose semantics have changed.
  • A brief description of the overall change and how to take advantage of it. You'll probably find this same material in the evaluation section of the bug/rfe report.
  • If the API change corrects a long standing bug or provides a missing feature - suggestions about how to migrate typical workarounds or extensions to the new feature.
  • Nearly all changes (even bugfixes!) introduce some kind of incompatibility. We've done our best to predict these incompatibilities and provide advice about how to avoid them.

Sections

  • Box
  • JButton
  • JComboBox
  • JFileChooser
  • JInternalFrame
  • JList
  • JOptionPane
  • JPopupMenu
  • JPanel
  • JRootPane
  • JScrollBar
  • JScrollPane
  • JTabbedPane
  • JTable
  • JTextComponent
  • JTree
  • RepaintManager
  • SpringLayout
  • Miscellaneous
  • Known Bugs

Box

Box now descends from JComponent

The bugtraq report that corresponds to this change is: 4304100.

Historically, the superclass for Box has been Component. Since Box did not descend from JComponent, you could not use it like a normal Swing component, for example, you couldn't set the borders, or issue revalidate. Not only this, but changing visibility, or other similiar visual properties, on a standard Swing component typically triggers a repaint or revalidate, but Box did not conform to this behavior. As of this release, Box and Box.Filler now descend from the JComponent superclass and therefore behave more like standard Swing components.

BoxLayout Now Supports Right-to-Left and Bottom-to-Top Component Orientations

The bugtraq report that corresponds to this change is: 4140833.

BoxLayout did not consider the ComponentOrientation of the Container it is laying out. Other AWT layout managers were made to do this when the ComponentOrientation feature was added in JDK 1.2. Adding this feature to BoxLayout makes it useful for programs that support Middle East locales. Because BoxLayout is also used internally by other Swing components, such as JOptionPane, JToolBar and JMenuBar, adding this feature is also necessary for these components to support ComponentOrientation.

To support this functionality, the constants LINE_AXIS and PAGE_AXIS, and the constructor, BoxLayout(Container, int), were added to BoxLayout.

There were also changes to several methods in SizeRequirements:

  • calculateTiledPositions(int,SizeRequirements,SizeRequirements[],int[],int[],boolean)
  • calculateTiledPositions(int,SizeRequirements,SizeRequirements[],int[],int[])
  • calculateAlignedPositions(int,SizeRequirements,SizeRequirements[],int[],int[],boolean)
  • calculateAlignedPositions(int,SizeRequirements,SizeRequirements[],int[],int[])

JButton

Default Button Follows the Focus on Windows LAF

The bugtraq report that corresponds to this change is: 4659800.

With this bug, introduced in 1.4.0, the default button did not always follow the focus. This has been fixed in 1.4.1.

New Control of Highlighted Characters

The bugtraq report that corresponds to this change is: 4138746.

AbstractButton and JLabel both allow the developer to set a character, called the mnemonic, that can be used to perform an action when typed at the keyboard. The javadoc for these methods states that the first case-insensitive occurrence of the character is decorated. While this suits most developers, often times a different occurrence of the character needs to be highlighted. For example: in Notepad, 'a' is the accelerator for Save As, but the second 'a' is decorated. Developers need a way to be able to specify this.

This is solved with the new AbstractButton.setDisplayedMnemonicIndex and JLabel.setDisplayedMnemonicIndex methods. Once you have specified a mnemonic, via the setMnemonic or setDisplayedMnemonic methods, you can then change the character that is highlighted via the setDisplayedMnemonicIndex method. There are also new AbstractButton.getDisplayedMnemonicIndex and JLabel.getDisplayedMnemonicIndex methods. Finally, drawStringUnderlineCharAt has been added to javax.swing.plaf.basic.BasicGraphicsUtils.

AbstractButton.configurePropertiesFromAction Now Honors ACTION_COMMAND_KEY Property

The bugtraq report that corresponds to this change is: 4457940.

Previously, the AbstractButton methods configurePropertiesFromAction(Action) and configurePropertiesFromAction(Action, String[]) did not honor the ACTION_COMMAND_KEY property. That has now been addressed. This affects the javadoc for the configurePropertiesFromAction methods in the following subclasses of AbstractButton:

  • JButton.configurePropertiesFromAction(Action)
  • JMenu.configurePropertiesFromAction(Action)
  • JCheckBox.configurePropertiesFromAction(Action)
  • JRadioButton.configurePropertiesFromAction(Action)

JComboBox

PopupMenuListener Added to JComboBox

The bugtraq report that corresponds to this change is: 4287690.

Many developers have requested support for listeners to be notified when a combo box's drop down menu is popped up, dismissed, or canceled. Applications could use these listeners to lazily populate the combo box's model with items.

This feature wasn't provided in earlier versions of Swing because there was some, probably academic, concern about supporting a listener for a feature (the drop down menu) that some look and feel implementations might not provide. All of the look and feels that are shipped with Java, and all of the ones we've come across, do use a drop down menu to show all of the combo box items. Some developers have resorted to non-portable hacks to get the menu state change notifications.

For this release, we added a PopupMenuListener to JComboBox. So long as the underlying look and feel supports an item menu, this listener can be used to perform actions before and after the combo box menu appears. Several new JComboBox methods were required to support this feature:

    public void addPopupMenuListener(PopupMenuListener l)
    public void removePopupMenuListener(PopupMenuListener l)
    public void firePopupMenuWillBecomeVisible()
    public void firePopupMenuWillBecomeInvisible()
    public void firePopupMenuCanceled()

JComboBox Now Supports Prototype Cell for Lists

The bugtraq report that corresponds to this change is: 4231298.

JComboBox previously configured a renderer for every item it displayed. For large lists this could take quite a while. Instead, developers needed the ability to specify a prototype that all cells match, so that the prototype is only checked once instead of every cell. For this release, getPrototypeDisplayValue and setPrototypeDisplayValue have been added to JComboBox.

Javadoc for JComboBox and Related Classes Has Improved Documentation

The bugtraq report that corresponds to this change is 4394300.

Previously, public API for JComboBox and its UI delegates contained javadoc which described the details of its implementation. Refactoring and bug fixing over the course of its history had made this javadoc out of date. The javadoc has been checked and revised so that it describes the behavior of the method rather than the implementation details. Also, some of the javadoc for "protected" methods and fields which should really have been private have been removed so that overriding or calling these methods are not encouraged.

The doc has been changed for JComboBox, ComboBoxModel, MutableComboBoxModel, javax.swing.plaf.basic.BasicComboBoxUI, javax.swing.plaf.basic.ComboPopup, and javax.swing.plaf.basic.BasicComboPopup.

JFileChooser

JFileChooser Windows Look and Feel Improved

The bugtraq report that corresponds to this change is 4290709.

Although Swing's JFileChooser closely resembles the Microsoft Windows common file dialog under the Windows look and feel, there are several deficiencies for which we have received complaints. In particular, the Microsoft Windows aesthetics guide mentions the following:

If you cannot use the [common] Open and Save As dialog boxes, you should incorporate the following features into your open and save dialog boxes to ensure that they are consistent with the shell, the Windows accessories, and other applications:

  • Support the same namespace hierarchy as the shell; that is, Desktop should be at the root of the hierarchy, followed by all folders and objects on the desktop, including My Computer, My Network, and so on. [...]
  • Support shortcuts (also known as shell links). [...]
  • Display filenames with the corresponding icons and filename extensions removed, as the shell does.
  • Allow the user to browse the network hierarchy directly.
  • Make sure that all of your dialog boxes (not just your open and save dialog boxes) use only nonbold fonts. [...]

The first four points are not possible in Swing without additional API support from the AWT. The AWT common file dialog is also currently an unacceptable solution for the following reasons:

  • It cannot be embedded into a frame or dialog like JFileChooser.
  • Filename filter is not implemented and is difficult to implement on Windows.

The new functionality is accomplished by adding the following public methods to the javax.swing.filechooser.FileSystemView class, providing file and directory information beyond the scope of the File class:

    public boolean isTraversable(File f)
    public String getSystemDisplayName(File f)
    public String getSystemTypeDescription
    public Icon getSystemIcon(File f)
    public boolean isParent(File folder, File file)
    public File getChild(File parent, String filename)
    public boolean isFileSystem(File f)
    public boolean isFileSystemRoot(File dir)
    public boolean isDrive(File dir)
    public boolean isFloppyDrive(File dir)
    public boolean isComputerNode(File dir)
    public File createFileSystemRoot(File f)
    public File[] getRoots()

The isTraversable method has been removed from javax.swing.plaf.basic.BasicFileChooserUI.BasicFileView so that the superclass's implementation is used.

createListSelectionListener has been added to javax.swing.plaf.metal.MetalFileChooserUI.

Also, javax.swing.plaf.basic.BasicDirectoryModel has the following changes:

    public void intervalAdded(ListDataEvent e)
    public void intervalRemoved(ListDataEvent e)
    public void renameFile(File oldFile, File newFile)

New Ability to Specify Characteristics of Open Directory Button in JFileChooser

The bugtraq report that corresponds to this change is 4318785.

Look and feels need the ability to specify the text, tooltip text, and mnemonic for the button used to open a directory in JFileChooser.

To support this, several constants and methods were added to plaf.basic.BasicFileChooserUI:

    protected int directoryOpenButtonMnemonic = 0;
    protected String directoryOpenButtonText = null
    protected String directoryOpenButtonToolTipText = null
    protected boolean isDirectorySelected()
    protected void setDirectorySelected(boolean b)
    protected File getDirectory()
    protected void setDirectory(File f)

Multiple File Selection Supported

The bugtraq report that corresponds to this change is 4218431.

Multiple file selection was added to JFileChooser in the 1.4 release, but the javadoc for setMultiSelectionEnabled wasn't updated until the 1.4.1 release.

JInternalFrame

JInternalFrame Now Truncates Titles That are Too Long

The bugtraq report that corresponds to this change is 4134077.

Previously, the title of an internal frame would not be clipped if it was too long. This would lead to the title displaying over parts of the icons, as well no visual feedback to the user that the title had been clipped. To solve this, BasicInternalFrameTitlePane.getTitle was added.

JInternalFrame Titles in Windows Look and Feel May Now be Rendered with a Gradient

The bugtraq report that corresponds to this change is: 4389209.

To implement this correctly, we needed to create a class, com.sun.java.swing.plaf.windows.WindowsInternalFrameTitlePane, which extended javax.swing.plaf.basic.BasicInternalFrameTitlePane, but overrode the paint routine to render the gradient when appropriate. The best way to get code-reuse was to break out the portion of the paint method which paints just the background and override just that in WindowsInternalFrameTitlePane. The method paintTitleBackground was added to javax.swing.plaf.basic.BasicInternalFrameTitlePane.

JTextComponent

New Support for Tooltips for Images in JEditorPane

The bugtraq report that corresponds to this change is: 4252169.

In previous releases it was not possible for ImageView (the View responsible for rendering images in a JEditorPane) to show tooltip text because there was no way for a View to influence the tooltip text that is displayed for a JTextComponent. In this release, if the JTextComponent doesn't have a tooltip, then the view under the mouse is asked to provide one. If that View corresponds to an HTML element with an ALT attribute, then the tooltip text is the value of that attribute.

To make it possible for Views to affect the tooltip text, a number of methods were needed. getToolTipText was added to javax.swing.plaf.TextUI so that it is possible to get the tooltip text for a particular location. JTextComponent's getToolTipText method then forwards to the TextUI, assuming a tooltip was not set on the JTextComponent.

getToolTipText was also added to javax.swing.text.View. The default implementation of View.getToolTipText will forward the request to the View's child at the given location. To make it easy to determine the child at a particular location, getViewIndex was added to View.

The View implementation invokes getViewIndex and then getToolTipText on the child View. ImageView then overrides getToolTipText and returns the value from the ALT attribute of its AttributeSet.

ImageView Class is Now Public

The bugtraq report that corresponds to this change is: 4233811.

The package private class javax.swing.text.html.ImageView is now public so that it can be extended.

New HyperlinkEvent Read-Only elementOffset Property

The bugtraq report that corresponds to this change is: 4182124.

The HTML package exposes a way for developers to determine when the mouse moves over a link via the HyperlinkEvent and HyperlinkListener classes. Often times developers need a way to extract information from the document when the HyperlinkListener is notified. There was previously no way for a developer to determine the position in the document a HyperlinkEvent represents. To remedy this the constructor HyperlinkEvent(Object, EventType, URL, String, Element) and the method getSourceElement were added to HyperlinkEvent.

HTMLFrameHyperlinkEvent extends HyperlinkEvent, which already defines the method getSourceElement. Since the superclass now defines this method, the getSourceElement javadoc was removed from HTMLFrameHyperlinkEvent (the method is now inherited):

HTML Parser Change: Whitespace Reporting

The bugtraq report that corresponds to this change is: 4241788.

The semantics of the HTML parser ( javax.swing.text.html.parser.Parser) have slightly changed to better match that of the browser (NetscapeTM and Internet Explorer). While no API was changed, those using the parser may notice a slight difference in the reporting of whitespace. Here is how things have changed: if strict (an instance variable of javax.swing.text.html.parser.Parser) == false (the default) an instance variable is used to try and mimic the behavior of Netscape and Explorer.

The problematic scenarios are:

'<b>blah <i> <strike> foo'

which can be treated as:

'<b>blah <i><strike>foo'

as well as:

'<p><a href="xx"> <em>Using</em></a></p>'

which appears to be treated as:

'<p><a href="xx"><em>Using</em></a></p>'

When a tag that breaks flow, or trailing whitespace is encountered an instance variable is set to true. From then on, all whitespace is ignored. The instance variable is set back to false the first time a non whitespace character is encountered.

Improved Support for Writing HTML Forms

The bugtraq report that corresponds to this change is: 4200439.

The HTML support provided in the J2SETM has never correctly supported writing out form elements. This was due, in large part, to the way that forms were modeled. To better match the document object model (see DOM at www.w3.org) we have changed how the forms are modeled internally. Previously, any attributes of a form would be stored in the attributeSet of all of the children character elements. As of this release, an element is created to represent the form, better matching that of the HTML file itself. This allows for better modeling of the form, as well as consistent writing of the form.

This affects developers that relied on forms being handled loosely. As an example, we would previously treat the following invalid HTML:

<table>
<form>
</table>
</form>

as:

<form>
<table>
</table>
</form>

With this release, we instead treat it as:

<table>
<form>
</form>
</table>

Static DefaultPainter in javax.swing.text.DefaultHighlighter Class is Now Final

The bugtraq report that corresponds to this change is: 4328938.

Prior to this release, the static field DefaultPainter of javax.swing.text.DefaultHighlighter was not final. This was a potential security problem. For this release, it is now Final.

PlainDocument Constructor is Now Public

The bugtraq report that corresponds to this change is: 4220001.

Prior to this release, the PlainDocument(AbstractDocument.Content) constructor was protected. This meant that developers wishing to use the constructor had to subclass. This constructor was intended to be public, and is now public in this release.

JEditorPane.scrollToReference Method is Now Public

The bugtraq report that corresponds to this change is: 4304676.

JEditorPane.scrollToReference was protected for no good reason. This method is intended to be useful without having to subclass, as such it has been made public in this release.

Document.getText Method Now Allows for Partial Returns

The bugtraq report that corresponds to this change is: 4156650.

For efficiently accessing the content of a text document, Document defines the method getText(int, int, Segment). Unfortunately, there has been no way for the caller to determine if the receiver could efficiently satisfy the request. For example, GapContent could efficiently implement the request as long as the request didn't span the last edited spot of the document (the gap). To facilitate efficient access of the content, the methods setPartialReturn and isPartialReturn have been added to Segment. The current semantics of Document.getText still hold, but for more efficient use callers should invoke segment.setPartialReturn(true) and be prepared to get back a portion of the document at a time.

JEditorPane Now Provides HTML Accessibility Support

The bugtraq report that corresponds to this change is: 4303259.

Assistive technologies for people with disabilities require programmatic access to the contents of JEditorPane using the Accessibility API. Previously, the only access was to hypertext links. This API change provided accessibility to all HTML components using the Accessibility API.

javax.swing.text.html.HTMLEditorKit now implements javax.accessibility.Accessible.

JEditorPane now implements getAccessibleContext().

Further Support for New AbstractDocument.replace Method

The bugtraq report that corresponds to this change is: 4458513.

As part of RFE 4431047, a replace method was added to AbstractDocument. In order to allow this method to call remove and insertString (the only methods defined in the interface for mutating a Document), the restrictions on when writeLock may be invoked have been relaxed. This allows replace to be compatible with old versions of AbstractDocument that only override remove and insertString.

JOptionPane

New showInputDialog Methods

The bugtraq report that corresponds to this change is: 4226644.

Prior to this release, if programs wished to display a simple input dialog containing a textfield with a default string, they had to invoke the complex JOptionPane.showInputDialog method which requires seven parameters. Two new methods, showInputDialog(Object, Object), and showInputDialog(Component, Object, Object), make it more convenient to create and display simple input dialogs.

JOptionPane Now Supports ComponentOrientation

The bugtraq report that corresponds to this change is: 4265463.

JOptionPane needed to support right-to-left layout. This was a bug fix and no actual API was required, however, the class spec for JOptionPane and javax.swing.plaf.basic.BasicOptionPane have been updated.

JOptionPane now uses Non-Resizable Dialogs

The bugtraq report that corresponds to this change is: 4829588.

As of release 1.4.0, JOptionPane is changed to use non-resizable dialogs. As a result, the dialogs displayed by many JOptionPane methods have slightly changed. The first two changes are desirable:

  • The dialogs are, obviously, no longer resizable.
  • The dialogs no longer show the system menu icon (that typically appears in the upper-left corner of the dialog on a left-to-right system).
A side effect of this change appears in the handling of extra-long text. Previously, long text was clipped, showing "..." at the end, as the dialog was restricted to the size of the screen. Now, extra-long text can cause the dialog to be sized larger than the screen in order to accomodate all of the text. Keep watching bug 4829588 to see how this undesirable behavior is resolved.

JPopupMenu

JPopupMenu and Focus

As of this release, showing a JPopupMenu causes focus to transfer to the parent JRootPane. This was done so that JPopupMenus would support keyboard traversal ( 4212563). This may cause problems for applications that are doing validation on focus lost. If this affects you, it is recommended that in the focusLost notification you check the temporary property of the FocusEvent and, if true, do nothing. In situations where you don't want JPopupMenu to grab focus, there is unfortunately no way to disable this in the current release. In release 1.4.1 the decision to transfer focus is based on the focusability of the JPopupMenu. Refer to bug 4632782 for details.

JPopupMenu Now Supports Key Bindings

The bugtraq report that corresponds to this change is: 4212563.

Previously, JPopupMenu didn't support key bindings. The arrow keys, mnemonics, the enter key, and escape did not work with a JPopupMenu unless it was used as part of a compound component (like a JMenu or a JComboBox).

This behavior can be traced to the fact that JPopupMenu did not always gain focus, and could therefore not get KeyEvents. It was previously not possible for light weight toolkits, such as Swing, to request focus and indicate that the focus change was temporary. The new focus architecture solved this problem, and Swing can now request a temporary focus change. Fixing this bug required making the JPopupMenu get focus so that the key bindings can be processed. Consumers that had previously not expected focus changes need to update their code to check the temporary property of the FocusEvents.

JPopupMenu.setVisible(true) Now Throws HeadlessException in Headless Mode

The bugtraq report that corresponds to this change is: 4401222.

When the new headless mode was introduced, JPopupMenu.setVisible(true) was implemented to throw NullPointerException when called in headless mode. It has now been fixed to throw HeadlessException instead, to indicate that this operation cannot be performed in headless mode.

JPanel

New setUI, getUI Methods

The bugtraq report that corresponds to this change is: 4226238.

The setUI/getUI methods were not implemented for JPanel, even though its look and feel is defined by pluggable look and feel (plaf). See javax.swing.plaf.basic.BasicPanelUI.java, for example.

JTabbedPane

JTabbedPane and Focus

The new focus specification states that focus requests on components that are not showing will fail. This can have subtle side effects. One such side effect is that requesting focus from a ChangeListener associated with a JTabbedPane may fail. At the same time, the ChangeListener is notified that the component is not currently visible and therefore the focus request fails in the same situation that it probably worked under the previous release. If you are running into this situation with JTabbedPane it is suggested you make the component visible before requesting focus. Other situations may require different approaches.

New indexAtLocation Method in JTabbedPane

The bugtraq report that corresponds to this change is: 4241787.

Prior to this change, there was no way for client programs to convert a coordinate location to a particular tab in a tabbedpane. This made it difficult to implement special event handling on a JTabbedPane (like popping up a menu over a tab).

The method indexAtLocation has been added to JTabbedPane.

New Mnemonic Support for Accessing Tabs in JTabbedPane

The bugtraq report that corresponds to this change is: 4284674.

The panes of a JTabbedPane did not previously allow for mnemonics. To facilitate this, the methods getDisplayedMnemonicIndexAt and setDisplayedMnemonicIndexAt have been added.

Exceptions Thrown by JTabbedPane Now Consistent

The bugtraq report that corresponds to this change is: 4287053.

The JTabbedPane class is a container that has many methods which take an integer index as a parameter. Unfortunately, these methods weren't inconsistent with their approach to throwing exceptions (some methods check/throw, some don't). Additionally, the javadoc was in error - it stated that an IllegalParameterException was thrown when in fact an ArrayIndexOutOfBoundsException was thrown (by the underlying Vector).

Any method which takes an index that must be in the valid range from 0 to tabCount-1 now documents that it throws an IndexOutOfBoundsException (note: the underlying code continues to throw ArrayIndexOutOfBoundsException for compatibility reasons).

The following doc change:

    * @exception IndexOutOfBoundsException if index is out of range
    *       (index < 0 || index >= tab count)
will be applied to the following JTabbedPane methods:
    public String getTitleAt(int index)
    public Icon getIconAt(int index)
    public Icon getDisabledIconAt(int index)
    public String getToolTipTextAt(int index)
    public Color getBackgroundAt(int index)
    public Color getForegroundAt(int index)
    public boolean isEnabledAt(int index)
    public Component getComponentAt(int index)
    public int getDisplayedMnemonicIndexAt(int index)
    public Rectangle getBoundsAt(int index)
    public void setTitleAt(int index, String title)
    public void setIconAt(int index, Icon icon)
    public void setDisabledIconAt(int index, Icon icon)
    public void setToolTipTextAt(int index, String toolTipText)
    public void setForegroundAt(int index, Color foreground)
    public void setBackgroundAt(int index, Color background)
    public void setEnabledAt(int index, boolean enabled)
    public void setComponentAt(int index, Component component)
    public void setDisplayedMnemonicIndexAt(int tabIndex, int mnemonicIndex)

The same exception handling will be added to the following methods which previously did nothing:

    public void setSelectedIndex(int index)
    public void remove(int index)

JTable

DefaultTableModel.moveRow Specification Clarified

The bugtraq report that corresponds to this change is: 4144295.

In JDK 1.3, the moveRow method in DefaultTableModel was documented in such a way that it did not clearly define whether the row at startIndex or the row at endIndex row would end up at toIndex. By inference from the examples, it appears that the startIndex should end up at toIndex when moving rows downward and the endIndex should end up at toIndex when moving rows upward.

That said, the implementation of moveRow had a bug such that whenever the number of rows being moved was more than one - the rows would end up in somewhat arbitrary positions and would not even be contiguous after the move. Bug 4144295 noted that the implementation did not even perform the example in its specification: the moveRow(1, 3, 5) example in practice left the vector in the following state:

a|C|e|B|D|f|g|h|i|j|k
The new implementation makes the observation that this operation is a simple rotation of elements between bounds that can be calculated from the inputs.

Since the previous implementation did not work we have taken the opportunity to simplify the definition to one where the startIndex is always moved to the toIndex, with all other elements appearing after toIndex in the same order that they were originally. Note that this performs the same operation as the previous implementation in the only case where it worked - when a single row was being moved.

The new implementation does not throw an exception when endIndex is less than startIndex - it does nothing instead having satisfied the implied contract to move all rows, r, where startIndex <= r <= endIndex.

Typing into a JTable Now Transfers Focus to the Cell

The bugtraq report that corresponds to this change is: 4274963.

The Excel application automatically gives focus to underlying editors when a user presses an alphanumeric key. We have received over 200 JDC votes requesting that we offer this behavior in JTable. While we can't change the default behavior for reasons of backwards compatibility, in this release we have added the new property, surrendersFocusOnKeystroke, to address this request. The new methods setSurrendersFocusOnKeystroke and getSurrendersFocusOnKeystrok support this feature. The default behavior remains unchanged.

DefaultTableModel Now Allows a Null For Name Argument

The bugtraq report that corresponds to this change is: 4474094.

The methods DefaultTableModel.addColumn(Object) and DefaultTableModel.addColumn(Object, Vector) did not previously allow null for the name argument - they threw an IllegalArgumentException. As it is possible to set the column name to null via other means (using constructors, or directly manipulating the field), the addColumn methods now also allows a null value.

JTree

DefaultTreeModel Now Allows a Null Root

The bugtraq report that corresponds to this change is: 4264897.

DefaultTreeModel now allows a null root node . Previously, the javadoc for TreeModel specified that a null root was valid, but DefaultTreeModel would not allow one. DefaultTreeModel now allows setting a null root, as well as a null root in the constructor. The javadoc for setRoot has been revised to reflect the change.

Added First Letter Navigation to JTree

The bugtraq report that corresponds to this change is: 4284709.

Often times users wish to navigate to cells in a JTree using alphanumeric keys. To facilitate this, a method named getNextMatch has been added to JTree. BasicTreeUI installs a KeyListener that invokes this method as keys are typed on the keyboard.

JList

ListDataEvent.toString Now Provides Useful Information

The bugtraq report that corresponds to this change is: 4134085.

Developers often rely on the toString method for useful debugging information. Unfortunately ListDataEvent's toString method did not really provide anything useful. For this release, it has been changed to return something useful.

JList Now Supports First Letter Key Navigation

The bugtraq report that corresponds to this change is: 4284709.

Often times users wish to navigate to cells in a JList using alphanumeric keys. To facilitate this, getNextMatch was added to JList. BasicListUI will then install a KeyListener that will invoke this method as keys are typed to update the selection.

JList Items May Now be Arranged Horizontally

The bugtraq report that corresponds to this change is: 4460016.

JList previously only allowed laying out its cells vertically, that is:

1
2
3
4

Numerous users have asked for the ability to lay out the list horizontally, something like:

1  3
2  4
or
1  2
3  4

To achieve this, three constants are added to JList, VERTICAL, VERTICAL_WRAP, and HORIZONTAL_WRAP. The methods getLayoutOrientation and setLayoutOrientation are also added to JList. The javadoc for the JList methods getScrollableTracksViewportHeight, getScrollableTracksViewportWidth, getScrollableBlockIncrement, and getPreferredScrollableViewportSize are updated accordingly. Likewise, the javadoc for getPreferredSize in javax.swing.plaf.basic.BasicListUI is updated.

Miscellaneous

Two default settings in Metal look and feel have changed

Two default settings have changed in the Metal look and feel:

  • The foreground color for JLabel has changed from dark blue to black.
  • The font for DefaultListCellRenderer has changed from normal to bold.

JColorChooser.setPreviewPanel doesn't remove the old one

The bugtraq report that corresponds to this change is: 4759306.

When calling this method the default PreviewPanel was not removed from the colorChooser, though the new panel was added. This resulted in strange artifacts. This has been fixed in release 1.4.2.

Deadlock in JColorChooser Fixed

The bugtraq report that corresponds to this change is: 4668511.

This bug when encountered in 1.4.0, caused a deadlock that would hang the entire application. This has been fixed in 1.4.1.

JFrame.setDefaultCloseOperation Can Now Throw SecurityException

As of release 1.4.1, the setDefaultCloseOperation method in JFrame may now throw SecurityException.

Metal Can Now Pick up Font Sizes from the Desktop on Microsoft Windows

The bugtraq reports that correspond to this change are: 4419964 and 4668963.

Prior to this release, the DefaultMetalTheme ignored the font size information from the Windows desktop. As of release 1.4.1, DefaultMetalTheme can use the font sizes specified in the Windows desktop. This can be disabled using the system property swing.useSystemFontSettings. An additional part of this bug is that our Windows look and feel was picking up the wrong fonts for a handful of components; this has been fixed.

Some Locales Will Honor Font Size Only from the Desktop on Windows

The bugtraq report that corresponds to this change is: 4615396.

On Microsoft Windows, with the WindowsLookAndFeel, in certain locales we only honor font size from the desktop. This has been addressed in 1.4.1.

Document Which Properties a Look and Feel May Ignore

The bugtraq report that corresponds to this change is: 4420209.

Some look and feel implementations may ignore certain properties which affect the look and feel. With this release, the documentation for certain methods has been modified to indicate that these properties may be ignored by some look and feels. Also, the class spec for UIManager and the documentation for the javax.swing.plaf.metal package were modified to specify that the Java look and feel is the default look and feel. This modification affects only documentation.

The affected methods are:

  • javax.swing.AbstractButton
    • public boolean isFocusPainted()
    • public void setFocusPainted(boolean b)
    • public boolean isRolloverEnabled()
    • public void setRolloverEnabled(boolean b)
  • javax.swing.JButton
    • public boolean isDefaultButton()
    • public boolean isDefaultCapable()
    • public void setDefaultCapable(boolean defaultCapable)
  • javax.swing.JCheckBox
    • public boolean isBorderPaintedFlat()
    • public void setBorderPaintedFlat(boolean b)
  • javax.swing.JColorChooser
    • public boolean getDragEnabled()
    • public void setDragEnabled(boolean b)
  • javax.swing.JComboBox
    • public boolean isLightWeightPopupEnabled()
    • public void setLightWeightPopupEnabled(boolean aFlag)
  • javax.swing.JFileChooser
    • public boolean getDragEnabled()
    • public void setDragEnabled(boolean b)
    • public boolean getControlButtonsAreShown()
    • public void setControlButtonsAreShown(boolean b)
  • javax.swing.JInternalFrame
    • public boolean isIconifiable()
    • public void setIconifiable(boolean b)
  • javax.swing.JList
    • public boolean getDragEnabled()
    • public void setDragEnabled(boolean b)
  • javax.swing.JPopupMenu
    • public boolean isLightWeightPopupEnabled()
    • public void setLightWeightPopupEnabled(boolean aFlag)
  • javax.swing.JProgressBar
    • public boolean isStringPainted()
    • public void setStringPainted(boolean b)
    • public boolean isIndeterminate()
    • public void setIndeterminate(boolean newValue)
  • javax.swing.JSplitPane
    • public boolean isOneTouchExpandable()
    • public void setOneTouchExpandable(boolean newValue)
    • public boolean isContinuousLayout()
    • public void setContinuousLayout(boolean newContinuousLayout)
  • javax.swing.JTable
    • public boolean getDragEnabled()
    • public void setDragEnabled(boolean b)
  • javax.swing.text.JTextComponent
    • public boolean getDragEnabled()
    • public void setDragEnabled(boolean b)
  • javax.swing.JToolBar
    • public boolean isFloatable()
    • public void setFloatable(boolean b)
  • javax.swing.JTree
    • public boolean getDragEnabled()
    • public void setDragEnabled(boolean b)
    • public boolean getShowsRootHandles()
    • public void setShowsRootHandles(boolean newValue)
    • public boolean getScrollsOnExpand()
    • public void setScrollsOnExpand(boolean newValue)

SwingConstants Now Define NEXT and PREVIOUS

The bugtraq report that corresponds to this change is: 4175466.

SwingConstants defines constants that are used throughout Swing. A common UI operation is to locate the next/previous item in a sequence; as such, SwingConstants now defines constants for NEXT and PREVIOUS.

New Way to Process Bindings for Swing Components from a non-Swing Component

The bugtraq report that corresponds to this change is: 4344900.

Swing has an elaborate infrastructure to support associating actions with particular key strokes. This means that when the user types a character the action executes. The processing of these events is triggered from within JComponent.processKeyEvent (processKeyEvent is overridden from java.awt.Component). As the processing of these actions occurs within JComponent, there was previously no way for developers to process bindings from within non-JComponent subclasses that get focus. To facilitate this, a processKeyBindings method was added to SwingUtilities.

Auditory Feedback for Swing Components

The bugtraq report that corresponds to this change is: 4290988.

Note: Due to a handful of bugs in the sound package we default to playing no sounds. If you would like to turn on sounds, you can do the following:

    UIManager.put("AuditoryCues.playList",
        UIManager.get("AuditoryCues.allAuditoryCues"));

Previously, Swing components did not provide the same auditory feedback as native components on many platforms. MALF2, a set of modifications to Swing's PLAFs, is primarily intended for use as an output-only, non-speech audio user feedback mechanism. The MALF2 project is important from the perspective of Swing/JFC and the Java platform's goal of tight user interface integration with the underlying platform. The MALF2 project ensures that a user's experience with a native application and a Swing/JFC application is identical with regard to the auditory user feedback.

The implementation centers around adding API to BasicLookAndFeel to support loading an ActionMap containing Actions that play sounds. Various BasicComponentUI implementations then invoke actionPerformed on the Action at the appropriate time to play the sound. For example, BasicMenuItemUI uses doClick to perform the action. While BasicLookAndFeel plays sounds using the Java Sound API, subclasses can use an alternative method. For example, WindowsLookAndFeel maps the Strings to Runnables by way of Toolkit.getDefaultToolkit().getDesktopProperty(), to provide integration with the sounds provided by Windows.

The ActionMap containing the sounds can be accessed via BasicLookAndFeel.getAudioActionMap. When getAudioActionMap is first invoked, it performs the following:

  1. The default entry auditoryCues.cueList (an Object[]) is used to determine a list of sounds to load.
  2. Each entry in the array is passed to createAudioAction to obtain the Action responsible for playing the sound.
  3. The Object passed into BasicLookAndFeel.createAudioAction is used to look up a path to a sound file from the defaults table that can be loaded by Java Sound.
  4. When one of the BasicComponentUIs classes wishes to play a sound, it invokes BasicLookAndFeel.playSound, passing in the Action.
  5. BasicLookAndFeel.playSound invokes actionPerformed on the Action if the name of the Action is contained in the defaults entry AuditoryCues.playList.

This architecture allows the developer numerous ways to customize the sounds that are played:

  • The sounds associated with a particular JComponent can be manipulated by changing the Action in the ActionMap associated with the JComponent, eg:
    ActionMap map = menuItem.getActionMap();
map.put("MenuItem.commandSound", differentActionToPlaySound);
  • The sounds used by all Components of a particular type can be changed by manipulating the defaults table, eg:
    UIManager.put("MenuItem.commandSound", "pathToNewSoundFild");
  • Developers creating a custom look and feel may override one of the BasicLookAndFeel methods to load the sounds in an alternative manner, or perhaps play the sounds in a different way.

Alternatively, the set of sounds to be played can be manipulated by way of the defaults entry AuditoryCues.playList. This Object array contains the keys in the defaults table indicating which sounds to play. MetalLookAndFeel defines this to be:

new Object[]  {"OptionPane.errorSound",
          "OptionPane.informationSound",
          "OptionPane.questionSound",
          "OptionPane.warningSound" }
This has the effect of turning on only the sounds that JOptionPane supports.

JMenu Updated to Work with New Focus Architecture

The bugtraq report that corresponds to this change is: 4371580.

The new focus architecture introduced via RFE 4290675 allows for developers to request a temporary focus change. The request is done through the protected Component methods requestFocus(boolean) or requestFocusInWindow(boolean). These two methods are protected as they are not meant for general use, but only for implementors of lightweight toolkits, such as Swing. Swing is architected in such a way that code in different packages needs to temporarily request focus; as such, the parent class of all Swing Components, JComponent, needs to expose requestFocus(boolean) and requestFocusInWindow as public.

New Support for Changing ComponentOrientation in Tree of Components

The bugtraq report that corresponds to this change is: 4337186.

With the bulk of the Swing components paying attention to their ComponentOrientation property, we now need two features to make it easier to manage the ComponentOrientation settings of an entire hierarchy of components. It should be easy to set entire hierarchies of components to a consistent ComponentOrientation setting using the new SwingUtilities method applyComponentOrientation(Component c, ComponentOrientation o).

New Access to Desktop Properties

The bugtraq report that corresponds to this change is: 4290973.

As part of the Windows look and feel update, a method was added to LookAndFeel, getDesktopPropertyValue, to facilitate accessing desktop properties.

New Method to Offset Rectangle by Component's Insets

This was actually added as part of the update to JProgressBar to support an indeterminate state. The bugtraq report that corresponds to this change is: 4290717.

The new method is calculateInnerArea(Component, Rectangle) has been added to SwingUtilities.

New API for Mouse Wheels

The bugtraq report that corresponds to this change is: 4356268.

Wheel mice, with a scroll wheel as a middle mouse button, are increasingly popular. This proposal provides for built-in Java support for scrolling via the mouse wheel, as well as a new wheel event listener so developers can customize mouse wheel behavior.

A new class, MouseWheelListener, and a new interface, MouseWheelEvent, have been added. The constant, MOUSE_WHEEL_EVENT_MASK has been added to AWTEvent. AWTEventMulticaster has three new methods: mouseWheelMoved, add, and remove. Component has two new methods: addMouseWheelListener, and removeMouseWheelListener. ScrollPane also has two new methods: setWheelScrollingEnabled and isWheelScrollingEnabled. Finally, Robot has the new method mouseWheel.

JFrame, JDialog, and JApplet No Longer Override processKeyEvent

The bugtraq report that corresponds to this change is: 4462408.

Swing supports the option of registering key bindings on JComponents. In previous releases it was necessary for Swing top level components ( JFrame, JDialog, and JApplet) to override processKeyEvent (defined in java.awt.Component) to activate these bindings if the focus was ever on one of these top level components. With the addition of java.awt.KeyEventPostProcessor and Swing taking advantage of this ( RFE 4389332), it is no longer necessary for these methods to be overridden in the Swing top level components. As of this release, these methods have been removed at the top level and are now inherited.

Document Headless Exceptions for JWindow Constructors

The bugtraq report that corresponds to this change is: 4483258.

Though the headless mode was added to this release, two JWindow constructors did not indicate that HeadlessException may be thrown. This has been fixed in the doc for Window(Window, GraphicsConfiguration) and JWindow(GraphicsConfiguration).

Known Input Verifier Bug

The bugtraq report that corresponds to this change is: 4532517.

We've recently found an input verifier bug that has been causing problems for some of our users. Under 1.4, the shouldYieldFocus method does not allow side-effects such as popping up an OptionPane.

We do have the following workaround:

    public boolean shouldYieldFocus(JComponent input) {
      if (verify(input)) {
        return true;
      }

      // According to the documentation, should yield focus is allowed to cause
      // side effects.  So temporarily remove the input verifier on the text
      // field.
      input.setInputVerifier(null);
      System.out.println("Removed input verifier");

      // Pop up the message dialog.
      String message = "Roll over the 'JButton1' with mouse pointer "
        + "after closing this dialog.\nIt sometimes behaves correctly "
        + "for the first time\n but repeating action brings incorrect "
        + "behaviour of button.";
      JOptionPane.showMessageDialog(null, message , "invalid value",
        JOptionPane.WARNING_MESSAGE);
      System.out.println("Showed message.");

      // Reinstall the input verifier.
      input.setInputVerifier(this);
      System.out.println("Reinstalled input verifier");

      // Tell whomever called us that we don't want to yield focus.
      return false;
    }

Known Bugs

Focus Bug When Simultaneously Running Windows and a Remote Display Application

In certain circumstances showing a heavy weight Window that is not focusable causes focus to be lost. This specifically happens when running flavors of Windows and a remote display application, such as Reflection-X, at the same time. Note that this bug was filed against release 1.4, but is fixed in 1.4.1. Refer to bug 4628933 for details.

JRootPane

New Multi Implementation of RootPaneUI

The bugtraq report that corresponds to this change is: 4338458.

The classes in javax.swing.plaf.multi are used to multiplex between multiple look and feels. This is typically used by assistive technologies that use an auxiliary look and feel to provide additional information, such as auditory information. There is currently no implementation in multi for RootPaneUI which makes using an auxiliary look and feel problematic.

The new class javax.swing.plaf.multi.MultiRootPaneUI has been added.

Support for Look and Feels to Provide Window Decorations

The bugtraq report that corresponds to this change is: 4290471.

AWT recently provided API such that Windows may be undecorated. That is, when undecorated is true, the Window will not render any widgets for closing, moving, or resizing. As such, Swing has made it possible for the look and feel to render decorations for Windows.

This feature is primarily supported in javax.swing.JRootPane, but we encourage developers to use the switches provided in javax.swing.JFrame and javax.swing.JDialog.

The following changes were made to JRootPane:

    public static final int NONE;
    public static final int FRAME;
    public static final int PLAIN_DIALOG;
    public static final int INFORMATION_DIALOG;
    public static final int ERROR_DIALOG;
    public static final int COLOR_CHOOSER_DIALOG;
    public static final int FILE_CHOOSER_DIALOG;
    public static final int QUESTION_DIALOG;
    public static final int WARNING_DIALOG;

    public void setWindowDecorationStyle(int style)
    public int getWindowDecorationStyle()

Not all look and feels support the window decoration style; the method getSupportsWindowDecorations has been added to javax.swing.LookAndFeel to provide a way for look and feels to indicate whether they support this behavior.

The methods, isDefaultLookAndFeelDecorated(), and setDefaultLookAndFeelDecorated have been added to JFrame.

The methods, isDefaultLookAndFeelDecorated(), and setDefaultLookAndFeelDecorated have also been added to JDialog.

JScrollBar

JScrollBar Now Overrides setUI

The bugtraq report that corresponds to this change is: 4213298.

JScrollBar did not previously override the setUI method. For this release, it has been changed to conform to this behavior.

JScrollPane

JScrollPane Supports New MouseWheelListener

This was implemented as part of the mouse wheel support. This section only documents the changes to JScrollPane, for details of the other changes refer to this section. The bugtraq report that corresponds to this change is: 4356268.

The methods isWheelScrollingEnabled and setWheelScrollingEnabled were added to JScrollPane.

A new protected inner class, MouseWheelHandler, was added to javax.swing.plaf.basic.BasicScrollPaneUI. The relevant method in this inner class is mouseWheelMoved. Finally, the new method createMouseWheelListener has been added to BasicScrollPaneUI.

RepaintManager

New VolatileImage Support

The bugtraq report that corresponds to this change is: 4363288.

The Java 2D team has implemented a new VolatileImage mechanism that has the ability to take advantage of hardware acceleration for Image graphics and blit-to-screen operations.

By default, Swing uses double-buffering to paint the contents of GUI components (by rendering into an offscreen image and then copying that image to the screen) and has been changed to take advantage of the new VolatileImage support.

The double buffer that Swing uses to do painting is obtained from the RepaintManager by using the method getOffscreenBuffer. Since a VolatileImage object requires special handling (to test for failure conditions), we could not simply change this method to return a VolatileImage since there may be existing code out there that invokes this method and does not implement this additional handling. Therefore, we have added a method, getVolatileOffscreenBuffer, to javax.swing.RepaintManager to specifically return a VolatileImage object.

SpringLayout

New SpringLayout Class

The bugtraq report that corresponds to this change is: 4290203.

This release introduces the new layout manager, SpringLayout.

See How to Use SpringLayout in The Java Tutorial for examples of using SpringLayout.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.source.tree.SwitchTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.SwitchTree

  • Packages that use SwitchTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of SwitchTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type SwitchTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitSwitch(SwitchTree node, P p)

    • Uses of SwitchTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type SwitchTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitSwitch(SwitchTree node, P p)
      R | SimpleTreeVisitor.visitSwitch(SwitchTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.SynchronizedTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.SynchronizedTree

  • Packages that use SynchronizedTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of SynchronizedTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type SynchronizedTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitSynchronized(SynchronizedTree node, P p)

    • Uses of SynchronizedTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type SynchronizedTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitSynchronized(SynchronizedTree node, P p)
      R | SimpleTreeVisitor.visitSynchronized(SynchronizedTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


JNLP File Syntax

This chapter covers the following topics:

  • Introduction
  • Example
  • JNLP Elements
    • jnlp Element
    • information Element
    • security Element
    • update Element
    • resources Element
    • application-desc Element
    • applet-desc Element
    • component-desc Element
    • installer-desc Element

Introduction

The format used in this release is that specified in the Java Network Launching Protocol & API Specification (JSR-56) version 6.0. This document describes the most commonly used elements of a JNLP file. For a complete description of the format, refer to the specification.

JNLP File Contents

Element

Attributes

Description

Since

Required

jnlp

This is the main xml element for a jnlp file. Everything is contained within the jnlp element.

1.0

yes

spec

The spec attribute can be 1.0, 1.5.0, or 6.0 or can use the wildcards such as 1.0+. It denoted the minimum version of the JNLP Specification that this jnlp file can work woth.

1.0

codebase

The codebase attribute specifies the base location for all relative URLs specified in href attributes in the JNLP file.

1.0

href

The href specifies the URL of the JNLP file itself.

1.0

version

The version of the application being launched, as well as the version of the JNLP file itself.

1.0

information

The information element contains other elements that describe the application and it's source.

1.0

yes

os

Specifies the operating systems for which this information element should be considered.

1.5.0

arch

Specifies the architecture for which this information element should be considered

1.5.0

platform

Specifies the platform for which this information element should be considered.

1.5.0

locale

Specifies the locale for which this information element should be considered.

1.5.0

title

The title element specifies the title of the application.

1.0

yes

vendor

The vendor element specifies the provider of the application.

1.0

yes

homepage

The homepage of the application.

1.0

href

A URL pointing to where more information on this application can be found.

1.0

yes

description

A short statement describing the application.

1.0

kind

An indicator as to what type of description this is, legal values are one-line, short, and tooltip.

1.0

icon

Describes an icon that can be used to identify the application to the user.

1.0

href

A URL pointing to the icon file, may be in one of the following formats: gif, jpg, png, ico.

1.0

yes

kind

Indicates the suggested use of the icon, can be: default, selected, disabled, rollover, splash, or shortcut.

1.0

width

Can be used to indicate the resolution of the image.

1.0

height

Can be used to indicate the resolution of the image.

1.0

depth

Can be used to indicate the resolution of the image.

1.0

offline-allowed

Indicates that this application can operate when the client system is disconnected from the network.

1.0

shortcut

The shortcut element can be used to indicate an application's preferences for desktop integration.

1.5.0

online

Can be used to describe the application's preference for creating a shortcut to run online or offline.

1.5.0

install

The optional install attribute can be used in a shortcut element to describe the application's preference for being considered "installed". If the value is "true" the application prefers to be considered installed. The default value of the install attribute is "false".

7.0

desktop

Can be used to indicate an application's preference for putting a shortcut on the users desktop.

1.5.0

menu

Can be used to indicate an application's preference for putting a menu item in the users start menus.

1.5.0

sub-menu

Can be used to indicate an application's preference for where to place the menu item.

1.5.0

association

Can be used to hint to the JNLP client that it wishes to be registered with the operating system as the primary handler of certain extensions and a certain mime-type.

1.5.0

extensions

Contains a list of file extensions (separated by spaces) that the application requests it be registered to handle.

1.5.0

mime-type

Contains the mime-type that the application requests it be registered to handle.

1.5.0

related-content

Describes an additional piece of related content that may be integrated with the application.

1.5.0

href

A URL pointing to the related content.

1.5.0

yes

update

The update element is used to indicate the preferences for how application updates should be handled by the JNLP Client.

6.0

check

Indicates the preference for when the JNLP Client should check for updates. It can be always, timeout, or background..

6.0

policy

Indicates the preference for how the JNLP Client should handle an application update when it is known an update is available before the application is launched. It can be always, prompt-update, or prompt-run.

6.0

1.0

security

This element can be used to request enhanced permissions.

1.0

all-permissions

Requests that the application be run with all permissions.

1.0

j2ee-application-client-permissions

Requests that the application be run with a permission set that meets the security specifications of the J2EE Application Client environment.

1.0

1.0

resources

Describes all the resources that are needed for an application.

1.0

yes

os

Specifies the operating system for which the resources element should be considered.

1.0

arch

Specifies the architecture for which the resources element should be considered.

1.0

locale

Specifies that the locales for which the resources element should be considered.

java (or j2se)

Specifies what version(s) of Java to run the application with.

6.0 (java)

version

Describes an ordered list of version ranges to use.

1.0

yes

href

The URL denoting the supplier of this version of java, and where it may be downloaded from.

1.0

java-vm-args

Indicates an additional set of standard and non-standard virtual machine arguments that the application would prefer the JNLP Client to use when launching Java.

1.0

initial-heap-size

Indicates the initial size of the Java heap.

1.0

max-heap-size

Indicates the maximum size of the Java heap.

1.0

jar

Specifies a JAR file that is part of the application's classpath.

1.0

yes

href

The URL of the jar file.

1.0

yes

version

The requested version of the jar file. Requires using the version-based download protocol

1.0

main

Indicates if this jar contains the class containing the main method of the application.

1.0

download

Can be used to indicate this jar may be downloaded eagerly, lazily, or for progress indication.

1.0 (6.0.18)

size

Indicates the downloadable size of the jar file in bytes.

1.0

part

Can be used to group resources together so they will be downloaded at the same time.

1.0

nativelib

Specifies a JAR file that contains native libraries in it's root directory.

1.0

href

The URL of the jar file.

1.0

yes

version

The requested version of the jar file. Requires using the version-based download protocol

1.0

download

Can be used to indicate this jar may be downloaded lazily.

1.0

size

Indicates the downloadable size of the jar file in bytes.

1.0

part

Can be used to group resources together so they will be downloaded at the same time.

1.0

extension

Contains pointer to an additional component-desc or installer-desc to be used with this application.

1.0

href

The URL to the additional extension jnlp file.

1.0

yes

version

The version of the additional extension jnlp file.

1.0

name

The name of the additional extension jnlp file

1.0

ext-download

Can be used in an extension element to denote the parts contained in a component-extension.

1.0

ext-part

Describes the name of a part that can be expected to be found in the extension.

1.0

yes

download

Can be used to indicate this extension may be downloaded eagerly or lazily.

1.0

part

Denotes the name of a part in this jnlp file to include the extension in.

1.0

package

Can be used to indicate to the JNLP Client which packages are implemented in which JAR files.

1.0

name

Package name contained in the jar files of the given part.

1.0

yes

part

Part name containing the jar files that include the given package name.

1.0

yes

recursive

Can be used to indicated that all package names beginning with the given name, can be found in the given part.

1.0

property

Defines a system property that will be available through the System.getProperty and System.getProperties methods.

1.0

name

Name of the system property.

1.0

yes

value

Value it will be set to.

1.0

yes

1.0

Note: A jnlp file must contain one of application-desc, applet-desc, component-desc, or installer-desc

1.0

yes

application-desc

Denotes this is the jnlp file for an application.

1.0

main-class

The name of the class containing the public static void main(String[]) method of the application.

1.0

yes

progress-class

The name of the class containing the implementation of DownloadServiceListener, that may be used to indicate download progress.

6.0.18

argument

Each argument contains (in order) an additional argument to be passed to main.

1.0

applet-desc

Denotes this is the jnlp file for an applet.

1.0

main-class

This is the name of the main Applet class.

1.0

yes

documentbase

The document base for the Applet as a URL.

1.0

name

Name of the Applet.

1.0

yes

width

The width of the applet in pixels.

1.0

yes

height

The height of the applet in pixels

1.0

yes

progress-class

The name of the class containing the implementation of DownloadServiceListener, that may be used to indicate download progress.

6.0.18

param

A set of parameters that can be passed into the applet.

1.0

name

The name of this parameter

1.0

yes

value

The value of this parameter

1.0

yes

component-desc

Denotes this is the jnlp file for a component extension.

1.0

progress-class

The name of the class containing the implementation of DownloadServiceListener, that may be used to indicate download progress.

6.0.18

installer-desc

Denotes this is the jnlp file for an installed extension.

1.0

main-class

The name of the class containing the public static void main(String[]) method of the installer.

1.0

yes

The JNLP file is an XML document. The following shows a complete example of a JNLP file.

Example

<?xml version="1.0" encoding="utf-8"?>
<!-- JNLP File for SwingSet2 Demo Application -->
<jnlp
  spec="6.0+"
  codebase="http://my_company.com/jaws/apps"
  href="swingset2.jnlp">
  <information>
    <title>SwingSet2 Demo Application</title>
    <vendor>Sun Microsystems, Inc.</vendor>
    <homepage href="docs/help.html"/>
    <description>SwingSet2 Demo Application</description>
    <description kind="short">A demo of the capabilities
    of the Swing Graphical User Interface.</description>
    <icon href="images/swingset2.jpg"/>
    <icon kind="splash" href="images/splash.gif"/>
    <offline-allowed/>
    <association mime-type="application-x/swingset2-file"  extensions="swingset2"/>
    <shortcut online="false" install="false">
      <desktop/>
      <menu submenu="My Corporation Apps"/>
    </shortcut>
  </information>
  <information os="linux">
    <title> SwingSet2 Demo on Linux </title>
    <homepage href="docs/linuxhelp.html">
  </information>
  <security>
      <all-permissions/>
  </security>
  <resources>
    <j2se version="1.6+" java-vm-args="-esa -Xnoclassgc"/>
    <jar href="lib/SwingSet2.jar"/>
  </resources>
  <application-desc main-class="SwingSet2"/>
</jnlp>

The example shows the basic outline of the document. The root element is jnlp, which has four subelements: information, security, resources, and application-desc. In addition, Java Web Start also supports launching applets by using the applet-desc element. The elements are described in more detail below.

JNLP Elements

jnlp Element

spec attribute: This attribute must be 1.0 or higher to work with this release. The default value is "1.0+". Thus, it can typically be omited. Note that this version supports both spec version 1.0, version 1.5, and version 6.0, whereas previous versions support only 1.0 and 1.5. A jnlp file specifying spec="6.0+" will work with this version, but not previous versions of Java Web Start.

codebase attribute: All relative URLs specified in href attributes in the JNLP file are using this URL as a base.

href attribute: This is a URL pointing to the location of the JNLP file itself.

information Element

os attribute: This attribute contains a list of operating system names for this element. Read the discussion of the resources element later for a full discussion of the os attribute.

title element: The name of the application.

vendor element: The name of the vendor of the application.

homepage element: Contains a single attribute, href, which is a URL locating the home page for the Application. It is used by the Java Application Cache Viewer to point the user to a Web page where more information about the application can be found.

description element: A short statement about the application. Description elements are optional. The kind attribute defines how the description should be used. It can have one of the following values:

  • one-line: If a reference to the application is going to appear on one row in a list or a table, this description will be used.
  • short: If a reference to the application is going to be displayed in a situation where there is room for a paragraph, this description is used.
  • tooltip: If a reference to the application is going to appear in a tooltip, this description is used.

Only one description element of each kind can be specified. A description element without a kind is used as a default value. Thus, if Java Web Start needs a description of kind short, and it is not specified in the JNLP file, then the text from the description without an attribute is used.

All descriptions contain plain text. No formatting, such as with HTML tags, is supported.

icon element: Contains an HTTP URL to an image file in either GIF or JPEG format. The icons are used to represents the application

  • during launch when Java Web Start presents the application to the user;
  • in the Java Application Cache Viewer;
  • in desktop shortcuts.

A 64x64 icon is shown during download; in the Java Application Cache Viewer and in desktop shortcuts a 32x32 icon is used. Java Web Start automatically resizes an icon to the appropriate size.

Optional width and height attributes can be used to indicate the size of the images.

The optional kind="splash" attribute may be used in an icon element to indicate that the image is to be used as a "splash" screen during the launch of an application. If the JNLP file does not contain an icon element with kind="splash" attribute, Java Web Start will construct a splash screen using other items from the information Element.

If the JNLP file does not contain any icon images, the splash image will consist of the application's title and vendor, as taken from the JNLP file.

The first time an application is launched following the addition or modification of the icon element in the JNLP file, the old splash image will still be displayed. The new splash image will appear on the second and subsequent launches of the application.

offline-allowed element: The optional offline-allowed element indicates if the application can be launched offline.

If offline-allowed is specified, then the application can be launched offline by the Java Application Cache Viewer, and shortcuts can be created which launch the application offline.

If an application is launched offline, it will not check for updates and the API call BasicService.isOffline() will return true.

The offline-allowed element also controls how Java Web Start checks for an update to an application. If the element is not specified—i.e., the application is required to be online to run—Java Web Start will always check for an updated version before launching the application. And if an update is found, the new application will be downloaded and launched. Thus, it is guaranteed that the user always runs the latest version of the application. The application, however, must be run online.

If offline-allowed is specified, Java Web Start will also check to see if an update is available. However, if the application is already downloaded the check will timeout after a few seconds, in which case the cached application will be launched instead. Given a reasonably fast server connection, the latest version of the application will usually be run, but it is not guaranteed. The application, however, can be run offline.

shortcut element: The optional shortcut element can be used to indicate an application's preferences for desktop integration. The shortcut element and its sub-elements provide hints that the JNLP Client may or may not use. The shortcut element can contain the optional online and install attributes, and the two optional sub-elements, desktop and menu.

association element: The optional association element is a hint to the JNLP client that it wishes to be registered with the operating system as the primary handler of certain extensions and a certain mime-type. The association element must have the extensions and mime-type attributes.

related-content element: The optional related-content element describes an additional piece of related content, such as a readme file, help pages, or links to registration pages, as a hint to a JNLP Client. The application is asking that this content be included in its desktop integration. The related-content element has a mandatory href and title attribute. It can contain any of the following two sub-elements:

  • description element: A short description of the related content.
  • icon element: The icon can be used by the JNLP Client to identify the related content to the user.

security Element

Each application is, by default, run in a restricted execution environment, similar to the Applet sandbox. The security element can be used to request unrestricted access.

If the all-permissions element is specified, the application will have full access to the client machine and local network. If an application requests full access, then all JAR files must be signed. The user will be prompted to accept the certificate the first time the application is launched.

update Element

The update element is used to indicate the preferences for how application updates should be handled by Java Web Start.

The update element can contain the following two optional attributes:

check attribute: The check attribute indicates the preference for when the JNLP Client should check for updates, and can have one of the three values: "always", "timeout", and "background"

A value of "always" means to always check for updates before launching the application.

A value of "timeout" (default) means to check for updates until timeout before launching the application. If the update check is not completed before the timeout, the application is launched, and the update check will continue in the background.

A value of "background" means to launch the application while checking for updates in the background.

policy attribute: The policy attribute indicates the preference for how the JNLP Client should handle an application update when it is known an update is available before the application is launched, and can have one of the following three values: "always", "prompt-update", and "prompt-run"

A value of "always" (default) means to always download updates without any prompt.

A value of "prompt-update" means to ask the user if he/she wants to download and run the updated version, or launch the cached version.

A value of "prompt-run" means to ask the user if he/she wants to download and run the updated version, or cancel and abort running the application.

For example:

<update check="always" policy="prompt-update">

resources Element

The resources element is used to specify all the resources, such as Java class files, native libraries, and system properties, that are part of the application. A resource definition can be restricted to a specific operating system, architecture, or locale using the os, arch, and locale attributes.

The os attribute contains a list of operating system names for a resource. For example, you could use multiple resources definitions, with different os attributes, to supply a native library for multiple operating systems.

The os attribute contains a list of operating system names separated by spaces. At runtime, the os values are compared with the beginning of the os.name system property to find a match. For example, an os attribute value of "Windows" matches both "Windows Vista" and "Windows 7" operating systems.

If you wish to list an operating system whose name contains a space, use a backslash to indicate that the space is part of the operating system name. The following example will specifically match "Windows Vista" and "Windows 7":

    <resources os="Windows\ Vista Windows\ 7">
      <jar href="hello.jar"/>
    </resources>

The resources element has six different possible subelements: jar, nativelib, j2se, property, package, and extension. The package and extension elements are not discussed in this developer's guide. See the Java Network Launching Protocol & API Specification (JSR-56) version 6.0 for details.

A jar element specifies a JAR file that is part of the application's classpath. For example:

      <jar href="myjar.jar"/>

The jar file will be loaded into the JVM using a ClassLoader object. The jar file will typically contain Java classes that contain the code for the particular application, but can also contain other resources, such as icons and configuration files, that are available through the getResource mechanism.

A nativelib element specifies a JAR file that contains native libraries. For example:

      <nativelib href="lib/windows/corelib.jar"/>

The JNLP client must ensure that each file entry in the root directory of the JAR file (i.e., /) can be loaded into the running process using the System.loadLibrary method. Each entry must contain a platform-dependent shared library with the correct naming convention, e.g., *.dll on Windows or lib*.so on Solaris/Linux. The application is responsible for doing the actual call to System.loadLibrary.

Native libraries would typically be included in a resources element that is geared toward a particular operating system and architecture. For example:

    <resources os="SunOS" arch="sparc">
      <nativelib href="lib/solaris/corelibs.jar"/>
    </resources>

By default, jar and nativelib resources will be downloaded eagerly, i.e., they are downloaded and available locally to the JVM running the application before the application is launched. The jar and nativelib elements also allow a resource to be specified as lazy. This means the resource does not have to be downloaded onto the client system before the application is launched.

The download attribute is used to control whether a resource is downloaded eagerly, lazily, or contains a custom progress implementation. For example:

    <jar href="sound.jar"
download="lazy"/>
<nativelib
href="native-sound.jar"
download="eager"/>
<jar href="progress.jar"
download="progress"/>

A jar denoted with download="progress" will be downloaded eagerly, and may be used to indicate progress while downloading other resources.

The j2se element specifies what Java(TM) Platform Standard Edition Runtime Environment (JRE) versions an application is supported on, as well as standard parameters to the Java Virtual Machine. If several JREs are specified, this indicates a prioritized list of the supported JREs, with the most preferred version first. For example:

       <j2se
version="1.3" initial-heap-size="64m"
max-heap-size="128m"/>
<j2se
version="1.4.2+"
href="http://java.sun.com/products/autodl/j2se"
java-vm-args="-esa -Xnoclassgc"/>

The version attribute refers, by default, to a platform version (specification version) of the Java(TM) Platform Standard Edition. Currently defined platform versions are 1.2, 1.3, 1.4, 1.5 and 1.6. (A platform version will not normally contain a micro version number; e.g., 1.4.2.)

Exact product versions (implementation versions) may also be specified. by including the href attribute. For example, 1.3.1_07, 1.4.2, or 1.5.0-beta2 by Sun Microsystems, Inc. For example,

<j2se version="1.4.2" href="http://java.sun.com/products/autodl/j2se"/

or

<j2se version="1.4.2_04" href="http://java.sun.com/products/autodl/j2se"/>

If a platform version is specified (i.e., no href attribute is provided), Java Web Start will not consider an installed non-FCS (i.e., milestone) JRE as a match. E.g., a request of the form

<j2se version="1.4+"/>

would not consider an installed 1.4.1-ea or 1.4.2-beta JRE as a match for the request. Starting with 1.3.0, a JRE from Sun Microsystems, Inc., is by convention a non-FCS (milestone) JRE if there is a dash (-) in the version string.

The java-vm-args attribute of the j2se element specifies a preferred set of virtual machine arguments to use when launching java.

<j2se version="1.4+" java-vm-args="-ea -Xincgc"/>

The following java-vm-args are supported by this version:

 -d32,                                                          /* use a 32-bit data model if available (unix platforms only) */
 -client,                                                       /* to select the client VM */
 -server,                                                       /* to select the server VM */
 -verbose,                                                      /* enable verbose output */
 -version,                                                      /* print product version and exit */
 -showversion,                                                  /* print product version and continue */
 -help,                                                         /* print this help message */
 -X,                                                            /* print help on non-standard options */
 -ea,                                                           /* enable assertions */
 -enableassertions,                                             /* enable assertions */
 -da,                                                           /* disable assertions */
 -disableassertions,                                            /* disable assertions */
 -esa,                                                          /* enable system assertions */
 -enablesystemassertions,                                       /* enable system assertions */
 -dsa,                                                          /* disable system assertione */
 -disablesystemassertions,                                      /* disable system assertione */
 -Xmixed,                                                       /* mixed mode execution (default) */
 -Xint,                                                         /* interpreted mode execution only */
 -Xnoclassgc,                                                   /* disable class garbage collection */
 -Xincgc,                                                       /* enable incremental garbage collection */
 -Xbatch,                                                       /* disable background compilation */
 -Xprof,                                                        /* output cpu profiling data */
 -Xdebug,                                                       /* enable remote debugging */
 -Xfuture,                                                      /* enable strictest checks, anticipating future default */
 -Xrs,                                                          /* reduce use of OS signals by Java/VM (see documentation) */
 -XX:+ForceTimeHighResolution,                                  /* use high resolution timer */
 -XX:-ForceTimeHighResolution,                                  /* use low resolution (default) */

Plus any argument starting with one of the following:

-ea,                          /* enable assertions for classes */
-enableassertions,            /* enable assertions for classes */
-da,                          /* disable assertions for classes */
-disableassertions,           /* disable assertions for classes */
-verbose,                     /* enable verbose output */
-Xms,                         /* set initial Java heap size */
-Xmx,                         /* set maximum Java heap size */
-Xss,                         /* set java thread stack size */
-XX:NewRatio,                 /* set Ratio of new/old gen sizes */
-XX:NewSize,                  /* set initial size of new generation */
-XX:MaxNewSize,               /* set max size of new generation */
-XX:PermSize,                 /* set initial size of permanent gen */
-XX:MaxPermSize,              /* set max size of permanent gen */
-XX:MaxHeapFreeRatio,         /* heap free percentage (default 70) */
-XX:MinHeapFreeRatio,         /* heap free percentage (default 40) */
-XX:UseSerialGC,              /* use serial garbage collection */
-XX:ThreadStackSize,          /* thread stack size (in KB) */
-XX:MaxInlineSize,            /* set max num of bytecodes to inline */
-XX:ReservedCodeCacheSize,    /* Reserved code cache size (bytes) */
-XX:MaxDirectMemorySize,

The property element defines a system property that will be available through the System.getProperty and System.setProperties methods. It has two required attributes: name and value. For example:

<property name="key" value="overwritten"/>

Properties set in the jnlp file will normally be set by Java Web Start after the VM is started but before the application is invoked. Some properties are considered "secure" properties and can be passed as -Dkey=value arguments on the java invocation command line.

The following properties, as well as properties beginning with either "javaws." or "jnlp.", are considered "secure" and will be passed to the VM in this way:

    sun.java2d.noddraw,
    swing.useSystemFontSettings,
    swing.metalTheme,
    http.agent,
    http.keepAlive,
    sun.awt.noerasebackground,
    sun.java2d.opengl,
    sun.java2d.d3d,
    java.awt.syncLWRequests,
    java.awt.Window.locationByPlatform,
    sun.awt.erasebackgroundonresize,
    swing.noxp,
    swing.boldMetal,
    awt.useSystemAAFontSettings,
    sun.java2d.dpiaware,
    sun.awt.disableMixing

For an untrusted application, system properties set in the JNLP file will only be set by Java Web Start if they are considered secure.

For information about properties that affect the behavior of Java Web Start applications, see Properties That Affect the Behavior of Rich Internet Applications.

application-desc Element

The application element indicates that the JNLP file is launching an application (as opposed to an applet). The application element has an optional attribute, main-class, which can be used to specify the name of the application's main class, i.e., the class that contains the public static void main(String argv[]) method where execution must begin.

The main-class attribute can be omitted if the first JAR file specified in the JNLP file contains a manifest file containing the main class.

Arguments can be specified to the application by including one or more nested argument elements. For example:

  <application-desc main-class="Main">
    <argument>arg1</argument>
    <argument>arg2</argument>
  </application-desc>

The (optional) progress-class attribute can be used to indicate that the class of this name implements the javax.jnlp.DownloadServiceListener interface. This class may be loaded first and used to indicate the progress of other resources being downloaded and verified.

applet-desc Element

Java Web Start has support for launching Java applets. This support provides easy migration of existing code to Java Web Start.

An applet is launched using the applet-desc element instead of the application-desc element. For example:

  <applet-desc
documentBase="http://..."
name="TimePilot"
main-class="TimePilot.TimePilotApp"
width="527"
height="428">
<param name="key1"
value="value1"/>
<param name="key2"
value="value2"/>
</applet-desc>

The JAR files that make up the applet are described using the resources element as for applications. The documentBase must be provided explicitly since a JNLP file is not embedded in an HTML page. The rest of the attributes correspond to the respective HTML applet tag elements.

The main-class attribute is used instead of the code attribute. The main-class attribute is assigned the name of the Applet class (without the .class extension). This attribute can be omitted if the Applet class can be found from the Main-Class manifest entry in the main JAR file.

The (optional) progress-class attribute can be used to indicate that the class of this name implements the javax.jnlp.DownloadServiceListener interface. This class may be loaded first and used to indicate the progress of other resources being downloaded and verified.

Note: Applets must be packaged in JAR files in order to work with Java Web Start.

component-desc Element

The component-desc element denotes that this jnlp file is not an application or an applet but an extension that can be used as a resource in an application, applet or another extension.

A component extension is typically used to factor out a set of resources that are shared between multiple applications or that have separate security needs.

The (optional) progress-class attribute can be used to indicate that the class of this name implements the javax.jnlp.DownloadServiceListener interface. This class may be loaded first and used to indicate the progress of other resources being downloaded and verified.

installer-desc Element

The installer-desc element denotes that this jnlp file is an installer extension that defines an application that will be run only once, the first time this extension jnlp file is used in an application, applet or another extension.

An installer extension is typically used to install platform specific native code that requires a more complicated setup than simply loading a native library into the VM.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JTabbedPane: Scrollable Tabs

Previously with JTabbedPane, if all the tabs did not fit within a single tab run, the JTabbedPane wrapped tabs onto multiple runs. There have been many requests to provide an alternative scheme, where the JTabbedPane would instead display a single, scrollable run of tabs. This document describes the new API for providing such scrollable tab support in JTabbedPane for the 1.4 release. The bugtraq report that corresponds to this change is: 4093898.

  • The Too-Many-Tabs Dilemma
  • New JTabbedPane API
  • Compatibility

The Too-Many-Tabs Dilemma

Wrapping tabs onto multiple lines provides the benefit of always allowing the user to view all possible tab selections at a given time:

Graphic with two rows of tabs. The first row has five, the second row has four.

However, the problem with multiple runs is in handling the case where the user selects a tab in a run which is not adjacent to the panel display area. For the Windows and Motif look and feel implementations, this action will cause the runs to rotate such that the run containing the selected tab is placed adjacent to the panel display area.

Graphic with selected tab adjacent to panel display area

This behavior can be extremely disorienting to the user because it constantly re-arranges the tabs, eliminating predictability in the UI. The Metal look and feel solved this problem by always leaving the runs fixed, even if the selected tab is not adjacent to the panel display area:

Graphic with selected tab is denoted by different color

Unfortunately the downside of the Metal solution is that it visually departs from the 'tabbed folder' metaphor (the selected tab is not 'attached' to its content). In fact, Chapter 7 of the Java Look and Feel Guidelines recommends against creating tabbed panes with multiple runs:

"If your tabbed pane requires multiple rows of tabs, consider dividing the content among several dialog boxes or components. Multiple rows of tabs can be confusing."

While constraining tabs in a tabbed pane to a number which will fit within a single run is an important UI guideline, there are circumstances where a proliferation of tabs cannot be avoided. This is often the case if the tabs are created dynamically by the application at runtime (perhaps driven off the content of a database).

An alternate solution for handling the tab proliferation case is to constrain the tabbed pane to a single, scrollable run of tabs:

Graphic with a single row of tabs that does not include all the possible choices

Naturally, this solution has its own set of usability problems, the most obvious of which is that the user can no longer view all possible selections at one time. However, this scrollable-tab behavior is becoming increasingly common in user interfaces and therefore Swing now supports it as an option.

New JTabbedPane API

To allow programs to define which tab layout behavior they require, we now provide a "tabLayoutPolicy" bound property on JTabbedPane:

    public void setTabLayoutPolicy(int layoutPolicy)

    public boolean getTabLayoutPolicy()

Additionally, constants for the supported policy values have been added to JTabbedPane:

    public static final int WRAP_TAB_LAYOUT = 0;

    public static final int SCROLL_TAB_LAYOUT = 1;

Compatibility

This feature had no impact on compatibility, as the default value for the tabLayoutPolicy property is WRAP_TAB_LAYOUT which matches the previous layout behavior of the tabbed pane.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.javadoc.Tag (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.javadoc.Tag

    • Uses of Tag in com.sun.javadoc

      Subinterfaces of Tag in com.sun.javadoc
      Modifier and Type Interface and Description
      interface  ParamTag
      Represents an @param documentation tag.
      interface  SeeTag
      Represents a user-defined cross-reference to related documentation.
      interface  SerialFieldTag
      Documents a Serializable field defined by an ObjectStreamField.
      interface  ThrowsTag
      Represents a @throws or @exception documentation tag.
      Methods in com.sun.javadoc that return Tag
      Modifier and Type Method and Description
      Tag[] Tag.firstSentenceTags()
      Return the first sentence of the comment as an array of tags.
      Tag[] Doc.firstSentenceTags()
      Return the first sentence of the comment as an array of tags.
      Tag[] Tag.inlineTags()
      For a documentation comment with embedded {@link} tags, return an array of Tag objects.
      Tag[] Doc.inlineTags()
      Return comment as an array of tags.
      Tag[] Doc.tags()
      Return all tags in this Doc item.
      Tag[] Doc.tags(String tagname)
      Return tags of the specified kind in this Doc item.
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Taglet

com.sun.tools.doclets

Interface Taglet

  • public interface Taglet
    The interface for a custom tag used by Doclets. A custom tag must implement this interface. To be loaded and used by doclets at run-time, the taglet must have a static method called register that accepts a Map as an argument with the following signature:
       public void register(Map map)
    This method should add an instance of the custom taglet to the map with the name of the taglet as the key. If overriding a taglet, to avoid a name conflict, the overridden taglet must be deleted from the map before an instance of the new taglet is added to the map.

    It is recommended that the taglet throw an exception when it fails to register itself. The exception that it throws is up to the user.

    Here are two sample taglets:

    • ToDoTaglet.java - Standalone taglet
    • UnderlineTaglet.java - Inline taglet

    For more information on how to create your own Taglets, please see the Taglet Overview.

    Since:
    1.4

    • Method Summary

      Methods
      Modifier and Type Method and Description
      String getName()
      Return the name of this custom tag.
      boolean inConstructor()
      Return true if this Taglet is used in constructor documentation.
      boolean inField()
      Return true if this Taglet is used in field documentation.
      boolean inMethod()
      Return true if this Taglet is used in method documentation.
      boolean inOverview()
      Return true if this Taglet is used in overview documentation.
      boolean inPackage()
      Return true if this Taglet is used in package documentation.
      boolean inType()
      Return true if this Taglet is used in type documentation (classes or interfaces).
      boolean isInlineTag()
      Return true if this Taglet is an inline tag.
      String toString(com.sun.javadoc.Tag tag)
      Given the Tag representation of this custom tag, return its string representation, which is output to the generated page.
      String toString(com.sun.javadoc.Tag[] tags)
      Given an array of Tags representing this custom tag, return its string representation, which is output to the generated page.

    • Method Detail

      • inField

        boolean inField()
        Return true if this Taglet is used in field documentation. Set to false for inline tags.
        Returns:
        true if this Taglet is used in field documentation and false otherwise.

      • inConstructor

        boolean inConstructor()
        Return true if this Taglet is used in constructor documentation. Set to false for inline tags.
        Returns:
        true if this Taglet is used in constructor documentation and false otherwise.

      • inMethod

        boolean inMethod()
        Return true if this Taglet is used in method documentation. Set to false for inline tags.
        Returns:
        true if this Taglet is used in method documentation and false otherwise.

      • inOverview

        boolean inOverview()
        Return true if this Taglet is used in overview documentation. Set to false for inline tags.
        Returns:
        true if this Taglet is used in method documentation and false otherwise.

      • inPackage

        boolean inPackage()
        Return true if this Taglet is used in package documentation. Set to false for inline tags.
        Returns:
        true if this Taglet is used in package documentation and false otherwise.

      • inType

        boolean inType()
        Return true if this Taglet is used in type documentation (classes or interfaces). Set to false for inline tags.
        Returns:
        true if this Taglet is used in type documentation and false otherwise.

      • isInlineTag

        boolean isInlineTag()
        Return true if this Taglet is an inline tag. Return false otherwise.
        Returns:
        true if this Taglet is an inline tag and false otherwise.

      • getName

        String getName()
        Return the name of this custom tag.
        Returns:
        the name of this custom tag.

      • toString

        String toString(com.sun.javadoc.Tag tag)
        Given the Tag representation of this custom tag, return its string representation, which is output to the generated page.
        Parameters:
        tag - the Tag representation of this custom tag.
        Returns:
        the string representation of this Tag.

      • toString

        String toString(com.sun.javadoc.Tag[] tags)
        Given an array of Tags representing this custom tag, return its string representation, which is output to the generated page. This method should return null if this taglet represents an inline tag.
        Parameters:
        tags - the array of Tags representing of this custom tag.
        Returns:
        the string representation of this Tag.

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.source.util.TaskEvent (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.source.util.TaskEvent

  • Packages that use TaskEvent
    Package Description
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of TaskEvent in com.sun.source.util

      Methods in com.sun.source.util with parameters of type TaskEvent
      Modifier and Type | Method and Description
      void | TaskListener.finished(TaskEvent e)
      void | TaskListener.started(TaskEvent e)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.source.util.TaskEvent.Kind (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.source.util.TaskEvent.Kind

  • Packages that use TaskEvent.Kind
    Package Description
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of TaskEvent.Kind in com.sun.source.util

      Methods in com.sun.source.util that return TaskEvent.Kind
      Modifier and Type | Method and Description
      TaskEvent.Kind | TaskEvent.getKind()
      static TaskEvent.Kind TaskEvent.Kind.valueOf(String name)
      Returns the enum constant of this type with the specified name.
      static TaskEvent.Kind[] TaskEvent.Kind.values()
      Returns an array containing the constants of this enum type, in the order they are declared.
      Constructors in com.sun.source.util with parameters of type TaskEvent.Kind
      Constructor and Description
      TaskEvent(TaskEvent.Kind kind)
      TaskEvent(TaskEvent.Kind kind, CompilationUnitTree unit)
      TaskEvent(TaskEvent.Kind kind, CompilationUnitTree unit, TypeElement clazz)
      TaskEvent(TaskEvent.Kind kind, JavaFileObject sourceFile)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.util.TaskListener (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.util.TaskListener

  • Packages that use TaskListener
    Package Description
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of TaskListener in com.sun.source.util

      Methods in com.sun.source.util with parameters of type TaskListener
      Modifier and Type Method and Description
      abstract void JavacTask.setTaskListener(TaskListener taskListener)
      The specified listener will receive events describing the progress of this compilation task.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class javax.smartcardio.TerminalFactory (Java Smart Card I/O b138)

  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
javax.smartcardio.TerminalFactory

    • Uses of TerminalFactory in javax.smartcardio

      Methods in javax.smartcardio that return TerminalFactory
      Modifier and Type Method and Description
      static TerminalFactory TerminalFactory.getDefault()
      Returns the default TerminalFactory instance.
      static TerminalFactory TerminalFactory.getInstance(String type, Object params)
      Returns a TerminalFactory of the specified type that is initialized with the specified parameters.
      static TerminalFactory TerminalFactory.getInstance(String type, Object params, Provider provider)
      Returns a TerminalFactory of the specified type that is initialized with the specified parameters.
      static TerminalFactory TerminalFactory.getInstance(String type, Object params, String provider)
      Returns a TerminalFactory of the specified type that is initialized with the specified parameters.
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class javax.smartcardio.TerminalFactorySpi (Java Smart Card I/O b138)

  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
javax.smartcardio.TerminalFactorySpi

No usage of javax.smartcardio.TerminalFactorySpi
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Java Smart Card I/O
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.Text (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.Text

  • Packages that use Text
    Package Description
    org.w3c.dom
    Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.

    • Uses of Text in org.w3c.dom

      Subinterfaces of Text in org.w3c.dom
      Modifier and Type Interface and Description
      interface  CDATASection
      CDATA sections are used to escape blocks of text containing characters that would otherwise be regarded as markup.
      Methods in org.w3c.dom that return Text
      Modifier and Type Method and Description
      Text Document.createTextNode(String data)
      Creates a Text node given the specified string.
      Text Text.replaceWholeText(String content)
      Replaces the text of the current node and all logically-adjacent text nodes with the specified text.
      Text Text.splitText(int offset)
      Breaks this node into two nodes at the specified offset, keeping both in the tree as siblings.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.auth.callback.TextCallbackHandler (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.callback.TextCallbackHandler

No usage of com.sun.security.auth.callback.TextCallbackHandler
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Thread Priority on Solaris

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Thread Priority on the Solaris Platform

This document discusses how the Java virtual machine (JVM) maps priorities for threads executing in the JVM (Java threads) onto native thread priorities on Solaris. It covers both current and past implementations of Solaris threads and the JVM.

  • Background Information: Java Threads
  • Background Information: Solaris Threads
    • Libthread Variants: T1 and T2
    • Native LWP Priorities
    • Summary
  • Historical Thread Priority Implementations
    • Before JRE 1.4.2
    • JRE 1.4.2
    • JRE 5.0
  • Miscellany
  • General Scheduling Issues: Priority, Yielding, and Monitor Fairness

Background Information: Java Threads

The JVM defines a range of ten logical priorities for Java threads, including:

java.lang.Thread.MIN_PRIORITY  = 1
java.lang.Thread.NORM_PRIORITY = 5
java.lang.Thread.MAX_PRIORITY  = 10

These values [1..10] are passed into Thread.setPriority(int) to assign priorities to Java threads. The default priority of a Java thread is NORM_PRIORITY. (A Java thread that doesn't explicitly call setPriority runs at NORM_PRIORITY.) A JVM is free to implement priorities in any way it chooses, including ignoring the value.

The Java HotSpot virtual machine currently associates each Java thread with a unique native thread. The relationship between the Java thread and the native thread is stable and persists for the lifetime of the Java thread.

Background Information: Solaris

Libthread Variants: T1 and T2

Prior to Solaris 9 the default libthread was the so-called T1 libthread. T1 provided an M:N threading model where M native threads were multiplexed on top of N kernel threads (LWPs). The relationship between native threads and LWPs was fluid and dynamic and could change even while a thread was running and without the knowledge of the thread. Solaris provided the priocntl() system call to change the dispatching priority of an LWP, but because the relationship between LWPs and native threads was unstable so there was no reliable way to change to change the dispatching priority of a native thread. (The JVM could change the priority of the LWP on which a Java thread was currently running, but the thread could switch to another LWP without the JVM's knowledge).

T2, the default libthread in Solaris 9 and better, implements a much more simple and robust 1:1 threading model. Each native thread is assigned to a unique LWP, and that relationship is stable for the lifetime of the native thread.

Both T1 and T2 expose a thr_setprio() API that applications use to set a thread's process-local priority. The value assigned by thr_setprio() is a process-local attribute and is not visible to the kernel scheduler. The thr_setprio()-priority controls the placement and ordering of threads on user-level process-local sleep queues, such as the queue of threads associated with a contended process-local mutex. In HotSpot most mutexes are uncontended and condvars have usually have either 0 or 1 threads. As such, the ordering imposed by thr_setprio()-priority has very little effect on most Java threads. The thr_setprio() function supports priority values in the range 0 through 127, inclusive, with 127 representing the highest priority.

T1 also uses thread priority to implement rudimentary user-mode preemption. T1 maintains an invariant that the thr_setprio()-priority of any thread on the local ready queue must be less than or equal to the priority of any unbound thread that's currently running and associated with an LWP. If the invariant is threatened, T1 preempts the lowest priority executing thread to "steal" its LWP in order to reestablish the invariant.

Preemption can occur in these cases:

  • When a running native thread lowers its own priority
  • When a running native thread increases the priority of a ready thread
  • When a native thread becomes ready, and its priority is higher than any "running" native thread. This could happen, for example, when a Java thread exits a monitor or calls notify and the JVM is using user-level Solaris synchronization primitives.

An early version of T2, referred to as the alternate libthread, appeared in Solaris 8.

For additional information about T1, T2, and LWPs refer to the following:

  • http://developers.sun.com/solaris/articles/alt_thread_lib.html
  • http://wwws.sun.com/software/whitepapers/solaris9/multithread.pdf

Native LWP Priorities

In Solaris an LWP's priority influences how many CPU cycles a thread receives relative to other threads. The Solaris scheduler uses priority (among other factors) to determine if one thread should preempt another thread, how often a thread runs, and how long a thread runs. Native LWP priorities are assigned by the priocntl() system call.

Summary

To recap, we have Java threads, with priorities set by the Thread.setPriority method. Java threads run on native threads. The thr_setprio() function is used to change the priority of native threads. Native threads run on LWPs. The priocntl() system call is used to change the priority of LWPs.

Historical Thread Priority Implementations

Before 1.4.2

In releases earlier than 1.4.2, when a Java thread called the Thread.setPriority method or when a thread was created, HotSpot would call thr_setprio() to map the Java priority to an native priority. Calling thr_setprio() had very little effect on the execution behavior of a Java thread. The JVM did not call priocntl() to adjust the priority of the underlying LWP. This was a conscious design decision because in the 1.4.2 time frame the only libthread available on Solaris was the older T1 libthread.

Note: The JVM could have forced native threads to be bound 1:1 to LWPs under T1 by specifying THR_BOUND when threads are created. THR_BOUND is not sufficient, however, as threads that attach to the JVM might not be THR_BOUND and the primordial thread is not THR_BOUND. Given that there's no way in Solaris to force a thread to be bound after it's been created, the HotSpot implementors decided that it was prudent not to change LWP priority when a Java thread called setPriority()

1.4.2

In 1.4.2 HotSpot was able to determine at startup time if it was running under T1 or T2. If the JVM started under T1 the effect of priorities would be precisely the same as in earlier releases.

Under T2, however, 1.4.2 translated calls to the Thread.setPriority method into calls to both thr_setprio() (to change the native process-local priority) and to priocntl() (to change the dispatching priority of the underlying LWP). The JVM called priocntl() only for threads that are running in the TS (timeshare), IA (interactive), and RT (real-time) scheduling classes. Refer to the Solaris priocntl(2) man page for a description of scheduling classes. If a Java thread was not in the TS, IA, or RT scheduling classes the JVM would not attempt to set the priority of the underlying LWP with priocntl().

Unfortunately the default priority of native threads in the TS and IA scheduling classes is the highest possible priority. The default logical priority for Java threads is NORM_PRIORITY, which is midway in domain of Java thread priorities. When the JVM maps NORM_PRIORITY to native and LWP priorities, the outcome is a value that is less then the default native priority. Let's say we have a 2-CPU system running a JVM, and that JVM has two Java threads, both at NORM_PRIORITY. Assume that the threads are in the IA or TS scheduling class, as is commonly the case. When the Java threads are created, the JVM calls priocntl() to map NORM_PRIORITY to the middle of the TS or IA priority bands. Furthermore, assume that 2 native "C" threads in another process are running/ready concurrently with the Java threads. Both the native C threads and the Java threads are CPU-bound and spin, computing. The native threads will run at the highest priority in the TS or IA scheduling class, and the JVM threads will run at the middle priority. Since all four threads are competing for CPU cycles, the native threads will receive relatively more CPU cycles and the Java threads will, in a sense, be disadvantaged. This effect occurs only when Java threads compete with normal threads and the system is entirely saturated.

Conversely, a benefit of using lower relative priorities is that in the TS and IA scheduling classes a thread running at lower priorities receives a longer quantum, assuming that it's not preempted mid-quantum by higher priority threads that become ready. A longer quantum is often beneficial for threads in server applications as the context switch rate from preemption decreases. A thread is permitted to run on a CPU for a longer period and the cache-reload transient (the period immediately after a thread is scheduled on to a CPU: when a thread incurs a high cache miss rate as it repopulates the CPU's data caches and displaces the previous thread's data) is amortized over a longer quantum.

JRE 5.0

JRE 5.0 provides the same priority mapping as 1.4.2 except that Java priorities in the range [10...5] are all mapped to the highest possible TS or IA priority, while priorities in the range [1..4] are mapped to correspondingly lower native TS or IA priorities. The advantage of this change is that Java threads at NORM_PRIORITY can now compete as expected with native threads. If neither the Java threads nor the native threads have explicitly set priorities (which is commonly the case), both classes of thread will compete on an equal footing, running at the highest priority in the TS or IA scheduling class.

Assuming that Java threads don't explicitly set their priority with setPriority(), this change restores the behavior and effective LWP priority of Java threads that was used prior to 1.4.2. The disadvantage to this implementation is that Java priorities from 5 to 10 are not differentiated. A Java thread at logical priority 8 maps to the same LWP priority as a Java thread at priority 9, for instance.

Miscellany

The following statements apply to all versions of HotSpot:

  • The JVM never changes the scheduling class of an LWP.
  • Calling the Thread.setPriority method may be an expensive operation. Frivolous priority adjustments can reduce performance.
  • If a foreign thread attaches to a JVM, the JVM sets that thread's priority to NORM_PRIORITY. This, in turn, changes the thread's native priority and potentially changes the priority of the LWP on which the native thread is running. Specifically, if a native thread adjusts its priority and then attaches to a JVM, the JVM overwrites the previous priority settings of the thread. The JVM does not "undo" or restore a native thread's priority if the thread detaches.

General Scheduling Issues: Priority, Yielding, and Monitor Fairness

The Thread.setPriority and Thread.yield methods are advisory. They constitute hints from the application to the JVM. Properly written, robust, platform-independent code can use setPriority() and yield() to optimize the performance of the application, but should not depend on these attributes for correctness. Likewise, no assumptions should be made about the order in which threads are granted ownership of a monitor or the order in which threads wake in response to the notify or notifyAll method. An excellent reference for these topics is Chapter 9, "Threads," in Joshua Bloch's book Effective Java Programming Language Guide.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.event.ThreadDeathEvent (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.event.ThreadDeathEvent

No usage of com.sun.jdi.event.ThreadDeathEvent
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.request.ThreadDeathRequest (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.request.ThreadDeathRequest

  • Packages that use ThreadDeathRequest
    Package Description
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of ThreadDeathRequest in com.sun.jdi.request

      Methods in com.sun.jdi.request that return ThreadDeathRequest
      Modifier and Type Method and Description
      ThreadDeathRequest EventRequestManager.createThreadDeathRequest()
      Creates a new disabled ThreadDeathRequest.
      Methods in com.sun.jdi.request that return types with arguments of type ThreadDeathRequest
      Modifier and Type Method and Description
      List<ThreadDeathRequest> EventRequestManager.threadDeathRequests()
      Return an unmodifiable list of the enabled and disabled thread death requests.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.ThreadGroupReference (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.ThreadGroupReference

  • Packages that use ThreadGroupReference
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of ThreadGroupReference in com.sun.jdi

      Methods in com.sun.jdi that return ThreadGroupReference
      Modifier and Type Method and Description
      ThreadGroupReference ThreadGroupReference.parent()
      Returns the parent of this thread group.
      ThreadGroupReference ThreadReference.threadGroup()
      Returns this thread's thread group.
      Methods in com.sun.jdi that return types with arguments of type ThreadGroupReference
      Modifier and Type Method and Description
      List<ThreadGroupReference> ThreadGroupReference.threadGroups()
      Returns a List containing each active ThreadGroupReference in this thread group.
      List<ThreadGroupReference> VirtualMachine.topLevelThreadGroups()
      Returns each thread group which does not have a parent.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.management.ThreadMXBean (Monitoring and Management Interface for the Java Platform b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Monitoring and Management Interface for the Java Platform
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.management.ThreadMXBean

No usage of com.sun.management.ThreadMXBean
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Monitoring and Management Interface for the Java Platform
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2003, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Java Thread Primitive Deprecation

Why is Thread.stop deprecated?

Because it is inherently unsafe. Stopping a thread causes it to unlock all the monitors that it has locked. (The monitors are unlocked as the ThreadDeath exception propagates up the stack.) If any of the objects previously protected by these monitors were in an inconsistent state, other threads may now view these objects in an inconsistent state. Such objects are said to be damaged. When threads operate on damaged objects, arbitrary behavior can result. This behavior may be subtle and difficult to detect, or it may be pronounced. Unlike other unchecked exceptions, ThreadDeath kills threads silently; thus, the user has no warning that his program may be corrupted. The corruption can manifest itself at any time after the actual damage occurs, even hours or days in the future.

Couldn't I just catch the ThreadDeath exception and fix the damaged object?

In theory, perhaps, but it would vastly complicate the task of writing correct multithreaded code. The task would be nearly insurmountable for two reasons:

  1. A thread can throw a ThreadDeath exception almost anywhere. All synchronized methods and blocks would have to be studied in great detail, with this in mind.
  2. A thread can throw a second ThreadDeath exception while cleaning up from the first (in the catch or finally clause). Cleanup would have to repeated till it succeeded. The code to ensure this would be quite complex.
In sum, it just isn't practical.

What about Thread.stop(Throwable)?

In addition to all of the problems noted above, this method may be used to generate exceptions that its target thread is unprepared to handle (including checked exceptions that the thread could not possibly throw, were it not for this method). For example, the following method is behaviorally identical to Java's throw operation, but circumvents the compiler's attempts to guarantee that the calling method has declared all of the checked exceptions that it may throw:

    static void sneakyThrow(Throwable t) {
        Thread.currentThread().stop(t);
    }

What should I use instead of Thread.stop?

Most uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. To ensure prompt communication of the stop-request, the variable must be volatile (or access to the variable must be synchronized).

For example, suppose your applet contains the following start, stop and run methods:

    private Thread blinker;

    public void start() {
        blinker = new Thread(this);
        blinker.start();
    }

    public void stop() {
        blinker.stop();  // UNSAFE!
    }

    public void run() {
        while (true) {
            try {
                Thread.sleep(interval);
            } catch (InterruptedException e){
            }
            repaint();
        }
    }
You can avoid the use of Thread.stop by replacing the applet's stop and run methods with:
    private volatile Thread blinker;

    public void stop() {
        blinker = null;
    }

    public void run() {
        Thread thisThread = Thread.currentThread();
        while (blinker == thisThread) {
            try {
                Thread.sleep(interval);
            } catch (InterruptedException e){
            }
            repaint();
        }
    }

How do I stop a thread that waits for long periods (e.g., for input)?

That's what the Thread.interrupt method is for. The same "state based" signaling mechanism shown above can be used, but the state change (blinker = null, in the previous example) can be followed by a call to Thread.interrupt, to interrupt the wait:

    public void stop() {
        Thread moribund = waiter;
        waiter = null;
        moribund.interrupt();
    }
For this technique to work, it's critical that any method that catches an interrupt exception and is not prepared to deal with it immediately reasserts the exception. We say reasserts rather than rethrows, because it is not always possible to rethrow the exception. If the method that catches the InterruptedException is not declared to throw this (checked) exception, then it should "reinterrupt itself" with the following incantation:
    Thread.currentThread().interrupt();
This ensures that the Thread will reraise the InterruptedException as soon as it is able.

What if a thread doesn't respond to Thread.interrupt?

In some cases, you can use application specific tricks. For example, if a thread is waiting on a known socket, you can close the socket to cause the thread to return immediately. Unfortunately, there really isn't any technique that works in general. It should be noted that in all situations where a waiting thread doesn't respond to Thread.interrupt, it wouldn't respond to Thread.stop either. Such cases include deliberate denial-of-service attacks, and I/O operations for which thread.stop and thread.interrupt do not work properly.

Why are Thread.suspend and Thread.resume deprecated?

Thread.suspend is inherently deadlock-prone. If the target thread holds a lock on the monitor protecting a critical system resource when it is suspended, no thread can access this resource until the target thread is resumed. If the thread that would resume the target thread attempts to lock this monitor prior to calling resume, deadlock results. Such deadlocks typically manifest themselves as "frozen" processes.

What should I use instead of Thread.suspend and Thread.resume?

As with Thread.stop, the prudent approach is to have the "target thread" poll a variable indicating the desired state of the thread (active or suspended). When the desired state is suspended, the thread waits using Object.wait. When the thread is resumed, the target thread is notified using Object.notify.

For example, suppose your applet contains the following mousePressed event handler, which toggles the state of a thread called blinker:

    private boolean threadSuspended;

    Public void mousePressed(MouseEvent e) {
        e.consume();

        if (threadSuspended)
            blinker.resume();
        else
            blinker.suspend();  // DEADLOCK-PRONE!

        threadSuspended = !threadSuspended;
    }
You can avoid the use of Thread.suspend and Thread.resume by replacing the event handler above with:
    public synchronized void mousePressed(MouseEvent e) {
        e.consume();

        threadSuspended = !threadSuspended;

        if (!threadSuspended)
            notify();
    }
and adding the following code to the "run loop":
                synchronized(this) {
                    while (threadSuspended)
                        wait();
                }
The wait method throws the InterruptedException, so it must be inside a try ... catch clause. It's fine to put it in the same clause as the sleep. The check should follow (rather than precede) the sleep so the window is immediately repainted when the thread is "resumed." The resulting run method follows:
    public void run() {
        while (true) {
            try {
                Thread.sleep(interval);

                synchronized(this) {
                    while (threadSuspended)
                        wait();
                }
            } catch (InterruptedException e){
            }
            repaint();
        }
    }
Note that the notify in the mousePressed method and the wait in the run method are inside synchronized blocks. This is required by the language, and ensures that wait and notify are properly serialized. In practical terms, this eliminates race conditions that could cause the "suspended" thread to miss a notify and remain suspended indefinitely.

While the cost of synchronization in Java is decreasing as the platform matures, it will never be free. A simple trick can be used to remove the synchronization that we've added to each iteration of the "run loop." The synchronized block that was added is replaced by a slightly more complex piece of code that enters a synchronized block only if the thread has actually been suspended:

                if (threadSuspended) {
                    synchronized(this) {
                        while (threadSuspended)
                            wait();
                    }
                }

In the absence of explicit synchronization, threadSuspended must be made volatile to ensure prompt communication of the suspend-request.

The resulting run method is:
    private volatile boolean threadSuspended;

    public void run() {
        while (true) {
            try {
                Thread.sleep(interval);

                if (threadSuspended) {
                    synchronized(this) {
                        while (threadSuspended)
                            wait();
                    }
                }
            } catch (InterruptedException e){
            }
            repaint();
        }
    }

Can I combine the two techniques to produce a thread that may be safely "stopped" or "suspended"?

Yes, it's reasonably straightforward. The one subtlety is that the target thread may already be suspended at the time that another thread tries to stop it. If the stop method merely sets the state variable (blinker) to null, the target thread will remain suspended (waiting on the monitor), rather than exiting gracefully as it should. If the applet is restarted, multiple threads could end up waiting on the monitor at the same time, resulting in erratic behavior.

To rectify this situation, the stop method must ensure that the target thread resumes immediately if it is suspended. Once the target thread resumes, it must recognize immediately that it has been stopped, and exit gracefully. Here's how the resulting run and stop methods look:

    public void run() {
        Thread thisThread = Thread.currentThread();
        while (blinker == thisThread) {
            try {
                Thread.sleep(interval);

                synchronized(this) {
                    while (threadSuspended && blinker==thisThread)
                        wait();
                }
            } catch (InterruptedException e){
            }
            repaint();
        }
    }

    public synchronized void stop() {
        blinker = null;
        notify();
    }
If the stop method calls Thread.interrupt, as described above, it needn't call notify as well, but it still must be synchronized. This ensures that the target thread won't miss an interrupt due to a race condition.

What about Thread.destroy?

Thread.destroy was never implemented and has been deprecated. If it were implemented, it would be deadlock-prone in the manner of Thread.suspend. (In fact, it is roughly equivalent to Thread.suspend without the possibility of a subsequent Thread.resume.)

Why is Runtime.runFinalizersOnExit deprecated?

Because it is inherently unsafe. It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock. While this problem could be prevented if the class whose objects are being finalized were coded to "defend against" this call, most programmers do not defend against it. They assume that an object is dead at the time that its finalizer is called.

Further, the call is not "thread-safe" in the sense that it sets a VM-global flag. This forces every class with a finalizer to defend against the finalization of live objects!

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.ThreadReference (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.ThreadReference

  • Packages that use ThreadReference
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.
    com.sun.jdi.event
    This package defines JDI events and event processing.
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of ThreadReference in com.sun.jdi

      Methods in com.sun.jdi that return ThreadReference
      Modifier and Type Method and Description
      ThreadReference ObjectReference.owningThread()
      Returns an ThreadReference for the thread, if any, which currently owns this object's monitor.
      ThreadReference MonitorInfo.thread()
      Returns a ThreadReference object for the thread that owns the monitor.
      ThreadReference StackFrame.thread()
      Returns the thread under which this frame's method is running.
      Methods in com.sun.jdi that return types with arguments of type ThreadReference
      Modifier and Type Method and Description
      List<ThreadReference> VirtualMachine.allThreads()
      Returns a list of the currently running threads.
      List<ThreadReference> ThreadGroupReference.threads()
      Returns a List containing a ThreadReference for each live thread in this thread group.
      List<ThreadReference> ObjectReference.waitingThreads()
      Returns a List containing a ThreadReference for each thread currently waiting for this object's monitor.
      Methods in com.sun.jdi with parameters of type ThreadReference
      Modifier and Type Method and Description
      Value ClassType.invokeMethod(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Invokes the specified static Method in the target VM.
      Value ObjectReference.invokeMethod(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Invokes the specified Method on this object in the target VM.
      ObjectReference ClassType.newInstance(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Constructs a new instance of this type, using the given constructor Method in the target VM.

    • Uses of ThreadReference in com.sun.jdi.event

      Methods in com.sun.jdi.event that return ThreadReference
      Modifier and Type Method and Description
      ThreadReference VMStartEvent.thread()
      Returns the initial thread of the VM which has started.
      ThreadReference ThreadStartEvent.thread()
      Returns the thread which has started.
      ThreadReference ThreadDeathEvent.thread()
      Returns the thread which is terminating.
      ThreadReference MonitorWaitedEvent.thread()
      Returns the thread in which this event has occurred.
      ThreadReference MonitorWaitEvent.thread()
      Returns the thread in which monitor wait event has occurred.
      ThreadReference MonitorContendedEnteredEvent.thread()
      Returns the thread in which this event has occurred.
      ThreadReference MonitorContendedEnterEvent.thread()
      Returns the thread in which this event has occurred.
      ThreadReference ClassPrepareEvent.thread()
      Returns the thread in which this event has occurred.
      ThreadReference LocatableEvent.thread()
      Returns the thread in which this event has occurred.

    • Uses of ThreadReference in com.sun.jdi.request

      Methods in com.sun.jdi.request that return ThreadReference
      Modifier and Type | Method and Description
      ThreadReference | StepRequest.thread()
      Methods in com.sun.jdi.request with parameters of type ThreadReference
      Modifier and Type Method and Description
      void WatchpointRequest.addThreadFilter(ThreadReference thread)
      Restricts the events generated by this request to those in the given thread.
      void BreakpointRequest.addThreadFilter(ThreadReference thread)
      Restricts the events generated by this request to those in the given thread.
      void MonitorWaitedRequest.addThreadFilter(ThreadReference thread)
      Restricts the events generated by this request to those in the given thread.
      void MonitorWaitRequest.addThreadFilter(ThreadReference thread)
      Restricts the events generated by this request to those in the given thread.
      void MonitorContendedEnteredRequest.addThreadFilter(ThreadReference thread)
      Restricts the events generated by this request to those in the given thread.
      void MonitorContendedEnterRequest.addThreadFilter(ThreadReference thread)
      Restricts the events generated by this request to those in the given thread.
      void MethodExitRequest.addThreadFilter(ThreadReference thread)
      Restricts the events generated by this request to those in the given thread.
      void MethodEntryRequest.addThreadFilter(ThreadReference thread)
      Restricts the events generated by this request to those in the given thread.
      void ExceptionRequest.addThreadFilter(ThreadReference thread)
      Restricts the events generated by this request to those in the given thread.
      void ThreadDeathRequest.addThreadFilter(ThreadReference thread)
      Restricts the events generated by this request to those in the given thread.
      void ThreadStartRequest.addThreadFilter(ThreadReference thread)
      Restricts the events generated by this request to those in the given thread.
      StepRequest EventRequestManager.createStepRequest(ThreadReference thread, int size, int depth)
      Creates a new disabled StepRequest.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Java VisualVM

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java VisualVM - Monitoring Application Threads

Java VisualVM presents data for local and remote applications in a tab specific for that application. Application tabs are displayed in the main window to the right of the Applications window. You can have multiple application tabs open at one time. Each application tab contains sub-tabs that display different types of information about the application.

Monitoring Thread Activity

Java VisualVM displays real-time, high-level data on thread activity in the Threads tab.
Note: The information displayed in the Threads tab is based on Java Management Extensions (JMX). The Threads tab is visible if Java VisualVM can make a JMX technology-based connection (JMX connection) with the target application and retrieve JMX instrumentation from the Java Virtual Machine (JVM). If the target application is a local application running on Java Development Kit (JDK) version 1.6, the JMX connection is made automatically. If the target application is not running on JDK version 1.6, you may need to explicitly establish a JMX connection with the JVM software. For more on establishing a JMX connection, see the following document:

  • Connecting to JMX Agents Explicitly

By default the Threads tab displays a timeline of current thread activity. You can click a thread in the timeline to view details about that thread in the Details tab.

Timeline Tab

This tab displays a timeline with real-time thread states. Use the buttons in the Timeline toolbar to zoom in/out on the current view and to switch to the Scale to Fit mode. The drop-down list enables you to select which threads are displayed. You can choose to view all threads, live threads or finished threads. You can also select a single thread or multiple threads to display a subset of the threads. You can double-click on a thread timeline to open that thread in the Details tab.

A timeline for each thread provides a quick overview of the thread's activity.

screenshot of timeline in Threads tab

Details Tab

The Details tab displays more detailed information about individual threads. Using the drop-down list, you can select to display all threads, all live threads or all finished threads. You can also choose to display only the details of threads selected in the Timeline view. For each thread, the name, classname and current status (alive/finished) are displayed. A short description of the thread is also provided.

Each thread displayed in the Details tab has the following tabs:

  • General. This tab displays thread states statistics.
  • Details. This tab contains full listings of thread states with timestamps.

A timeline for each thread provides a quick overview of the thread's activity.

screenshot of timeline in Threads tab

Taking a Thread Dump

You can use Java VisualVM to take a thread dump (stack trace) while a local application is running. Taking a thread dump does not stop the application. When you print the thread dump you get a printout of the thread stack that includes thread states for the Java threads.

When you print a thread dump in Java VisualVM, the tool prints a stack trace of the active threads of the application. Using Java VisualVM to take a thread dump can be very convenient in cases where you do not have a command-line console for the application. You can use a stack trace to help diagnose a number of issues such as deadlocks or when an application hangs.

Screenshot of thread dump (stack trace) in thread dump sub-tab.

screenshot of timeline in Threads tab
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.event.ThreadStartEvent (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.event.ThreadStartEvent

No usage of com.sun.jdi.event.ThreadStartEvent
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.request.ThreadStartRequest (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.request.ThreadStartRequest

  • Packages that use ThreadStartRequest
    Package Description
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of ThreadStartRequest in com.sun.jdi.request

      Methods in com.sun.jdi.request that return ThreadStartRequest
      Modifier and Type Method and Description
      ThreadStartRequest EventRequestManager.createThreadStartRequest()
      Creates a new disabled ThreadStartRequest.
      Methods in com.sun.jdi.request that return types with arguments of type ThreadStartRequest
      Modifier and Type Method and Description
      List<ThreadStartRequest> EventRequestManager.threadStartRequests()
      Return an unmodifiable list of the enabled and disabled thread start requests.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.javadoc.ThrowsTag (Doclet API b138)

  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.javadoc.ThrowsTag

    • Uses of ThrowsTag in com.sun.javadoc

      Methods in com.sun.javadoc that return ThrowsTag
      Modifier and Type Method and Description
      ThrowsTag[] ExecutableMemberDoc.throwsTags()
      Return the throws tags in this method.
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Doclet API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.ThrowTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.ThrowTree

  • Packages that use ThrowTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of ThrowTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type ThrowTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitThrow(ThrowTree node, P p)

    • Uses of ThrowTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type ThrowTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitThrow(ThrowTree node, P p)
      R | SimpleTreeVisitor.visitThrow(ThrowTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Signature Time Stamp Support

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Signature Timestamp Support

Introduction

This document describes the enhancements that have been added in J2SE 5.0 to support signature timestamps. Please send feedback, especially those related to these new features, to java-security@sun.com.

Prior to J2SE 5.0, the signature generated by jarsigner contained no information about w hen the signature was generated. With no other information available, systems/deployers (including users of the Java Plug-in) often based their validity assessment of a signed JAR file on the validity of the signing certificate. When the signing certificate expires, systems/deployers conclude that the signature, and hence, the JAR file, has expired. Because signing certificates typically expire annually, this caused customers significant problems by forcing them to re-sign deployed JAR files annually.

Starting in J2SE 5.0, jarsigner can generate signatures that include a timestamp, thus enabling systems/deployer (including Java Plug-in) to check whether the JAR file was signed while the signing certificate was still valid. In addition, APIs were added in J2SE 5.0 to allow applications to obtain the timestamp information.

The following time-of-signing enhancements and additions are supported in version 5.0 of the JavaSE platform:

  • Jarsigner Enhancements
  • Java Plug-in Enhancements
  • API Enhancements

Jarsigner Enhancements

The jarsigner tool can now generate and store a signature timestamp when signing a JAR file. In addition, jarsigner supports alternative signing mechanisms. This behavior is optional and is controlled by the user at the time of signing through the options described below.

Jarsigner Timestamp Options

The following options were added to the jarsigner tool to support signature timestamps:

-tsa url

If "-tsa http://example.tsa.url" appears on the command line when signing a JAR file then a timestamp is generated for the signature. The URL, http://example.tsa.url, identifies the location of the Time Stamping Authority (TSA). It overrides any URL found via the -tsacert option. The -tsa option does not require the TSA's public key certificate to be present in the keystore.

To generate the timestamp, jarsigner communicates with the TSA using the Time-Stamp Protocol (TSP) defined in RFC 3161. If successful, the timestamp token returned by the TSA is stored along with the signature in the signature block file.

-tsacert alias

If "-tsacert alias" appears on the command line when signing a JAR file then a timestamp is generated for the signature. The alias identifies the TSA's public key certificate in the keystore that is currently in effect. The entry's certificate is examined for a Subject Information Access extension that contains a URL identifying the location of the TSA.

The TSA's public key certificate must be present in the keystore when using -tsacert.

Alternative Signing Options

Specifying an Alternative Signing Mechanism

-altsigner class Specifies that an alternative signing mechanism be used. The fully-qualified class name identifies a class file that extends the com.sun.jarsigner.ContentSigner abstract class. The path to this class file is defined by the -altsignerpath option. If the -altsigner option is used, jarsigner uses the signing mechanism provided by the specified class. Otherwise, jarsigner uses its default signing mechanism.

For example, to use the signing mechanism provided by a class named com.sun.sun.jarsigner.AuthSigner, use the jarsigner option "-altsigner com.sun.jarsigner.AuthSigner"

Specifying Path to Alternative Signing Mechanism

-altsignerpath classpathlist Specifies the path to the class file (the class file name is specified with the -altsigner option described above) and any JAR files it depends on. If the class file is in a JAR file, then this specifies the path to that JAR file, as shown in the example below.

An absolute path or a path relative to the current directory may be specified. If classpathlist contains multiple paths or JAR files, they should be separated with a colon (:) on Solaris and a semi-colon (;) on Windows. This option is not necessary if the class is already in the search path.

Example of specifying the path to a jar file that contains the class file:

-altsignerpath /home/user/lib/authsigner.jar

Note that the JAR file name is included.

Example of specifying the path to the jar file that contains the class file:

-altsignerpath /home/user/classes/com/sun/tools/jarsigner/

Note that the JAR file name is omitted.

Java Plug-in Enhancements

In J2SE 5.0, the Java Plug-in was enhanced to check signature timestamps (if available) when validating JAR files. The Java Plug-in will no longer present a dialog when it encounters an expired or revoked certificate when validating a signed jar, provided that the signature timestamp confirms that the signature was generated prior to the expiration or revocation date.

The TSA's certificate must be available from the Plug-in's keystore or certificate stores when the Plug-in is validating a JAR file containing a signature timestamp.

The Plugin reverts to 1.4.x behavior if the signature does not contain a timestamp.

API Enhancements

The security and JAR APIs were enhanced to enable applications to access timestamp information.

Two new classes were added to the java.security package. These classes are CodeSigner, which maintains information associated with a signer, and Timestamp, which represents information associated with a signature timestamp.

New methods were added to the java.security.CodeSource class and java.util.jar.JarEntry class to allow access to this new, optional information.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Image I/O API Guide

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
CONTENTS | PREV | NEXT

JavaTM Image I/O API Guide

Phil Race, Dan Rice, Raúl Vera

April 2001

CONTENTS | PREV | NEXT
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java IDL: Transient Naming Service -

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java IDL: Transient Naming Service - tnameserv

This document discusses using the Java IDL Transient Naming Service, tnameserv. Java IDL also includes the Object Request Broker Daemon (ORBD). ORBD is a daemon process containing a Bootstrap Service, a Transient Naming Service, a Persistent Naming Service, and a Server Manager. The Java IDL tutorials all use ORBD, however, you can substitute tnameserv for orbd in any of the examples that use a Transient Naming Service. For documentation on the orbd tool, link to its man page or the Java IDL Naming Service Included with ORBD topic.

Topics in this section include:

  • Java IDL Transient Naming Service
  • Starting the Java IDL Transient Naming Service
  • Stopping the Java IDL Transient Naming Service
  • Sample Client: Adding Objects to the Namespace
  • Sample Client: Browsing the Namespace

Java IDL Transient Naming Service

The CORBA COS (Common Object Services) Naming Service provides a tree-like directory for object references much like a filesystem provides a directory structure for files. The Transient Naming Service provided with Java IDL, tnameserv, is a simple implementation of the COS Naming Service specification.

Object references are stored in the namespace by name and each object reference-name pair is called a name binding. Name bindings may be organized under naming contexts. Naming contexts are themselves name bindings and serve the same organizational function as a file system subdirectory. All bindings are stored under the initial naming context. The initial naming context is the only persistent binding in the namespace; the rest of the namespace is lost if the Java IDL naming service process halts and restarts.

For an applet or application to use COS naming, its ORB must know the port of a host running a naming service or have access to a stringified initial naming context for that naming service. The naming service can either be the Java IDL naming service or another COS-compliant naming service.

Starting the Java IDL Transient Naming Service

You must start the Java IDL naming service before an application or applet that uses its naming service. Installation of the Java IDL product creates a script (Solaris: tnameserv) or executable file (Windows NT: tnameserv.exe) that starts the Java IDL naming service. Start the naming service so it runs in the background.

If you do not specify otherwise, the Java IDL naming service listens on port 900 for the bootstrap protocol used to implement the ORB resolve_initial_references() and list_initial_references() methods, as follows:

    tnameserv -ORBInitialPort nameserverport&

If you do not specify the name server port, port 900 is used by default. When running Solaris software, you must become root to start a process on a port under 1024. For this reason, we recommend that you use a port number greater than or equal to 1024. To specify a different port, for example, 1050, and to run the naming service in the background, from a UNIX command shell, enter:

    tnameserv -ORBInitialPort 1050&

From an MS-DOS system prompt (Windows), enter:

    start tnameserv -ORBInitialPort 1050

Clients of the name server must be made aware of the new port number. Do this by setting the org.omg.CORBA.ORBInitialPort property to the new port number when creating the ORB object.

Running the server and client on different hosts

In most of the Java IDL and RMI-IIOP tutorials, the Naming Service, Server, and Client are all running on the development machine. In real world deployment, it is likely that the client and server will run on different host machines than the Naming Service.

For the client and server to find the Naming Service, they must be made aware of the port number and host on which the naming service is running. Do this by setting the org.omg.CORBA.ORBInitialPort and org.omg.CORBA.ORBInitialHost properties in the client and server files to the machine name and port number on which the Naming Service is running. An example of this is shown in The Hello World Example Using RMI-IIOP. You could also use the command line options -ORBInitialPort nameserverport# and -ORBInitialHost nameserverhostname to tell the client and server where to find the Naming Service. Java IDL: Running the Hello World Example on TWO Machines shows one way of doing this using the command line option.

For example, suppose the Transient Naming Service, tnameserv is running on port 1050 on host nameserverhost. The client is running on host clienthost and the server is running on host serverhost.

  • Start tnameserv on the host nameserverhost, as follows:
         tnameserv -ORBInitialPort 1050
  • Start the server on the serverhost, as follows:
         java Server -ORBInitialPort 1050 -ORBInitialHost nameserverhost
  • Start the client on the clienthost, as follows:
         java Client -ORBInitialPort 1050 -ORBInitialHost nameserverhost

The -J option

This command-line option is available for use with tnameserve:
-J option
Pass option to the Java virtual machine, where option is one of the options described on the reference page for the java application launcher. For example, -J-Xms48m sets the startup memory to 48 megabytes. It is a common convention for -J to pass options to the underlying virtual machine.

Stopping the Java IDL Transient Naming Service

To stop the Java IDL naming service, use the relevant operating system command, such as kill for a Unix process, or Ctrl-C for a Windows process. The naming service will continue to wait for invocations until it is explicitly shutdown. Note that names registered with the Java IDL naming service disappear when the service is terminated.

Sample Client: Adding Objects to the Namespace

The following sample program illustrates how to add names to the namespace. It is a self-contained Transient Naming Service client that creates the following simple tree.

                  Initial
               Naming Context
                  /      \
                 /        \
              plans     Personal
                         /   \
                        /     \
                   calendar  schedule

In this example, plans is an object reference and Personal is a naming context that contains two object references: calendar and schedule.

import java.util.Properties;
import org.omg.CORBA.*;
import org.omg.CosNaming.*;

public class NameClient
{
   public static void main(String args[])
   {
      try {
In the above section, Starting the Java IDL Transient Naming Service, the nameserver was started on port 1050. The following code ensures that the client program is aware of this port number.
        Properties props = new Properties();
        props.put("org.omg.CORBA.ORBInitialPort", "1050");
        ORB orb = ORB.init(args, props);
This code obtains the initial naming context and assigns it to ctx. The second line copies ctx into a dummy object reference objref that we'll attach to various names and add into the namespace.
        NamingContext ctx =
NamingContextHelper.narrow(orb.resolve_initial_references("NameService"));
        NamingContext objref = ctx;
This code creates a name "plans" of type "text" and binds it to our dummy object reference. "plans" is then added under the initial naming context using rebind. The rebind method allows us to run this program over and over again without getting the exceptions we'd get from using bind.
        NameComponent nc1 = new NameComponent("plans", "text");
        NameComponent[] name1 = {nc1};
        ctx.rebind(name1, objref);
        System.out.println("plans rebind sucessful!");
This code creates a naming context called "Personal" of type "directory". The resulting object reference, ctx2, is bound to the name and added under the initial naming context.
        NameComponent nc2 = new NameComponent("Personal", "directory");
        NameComponent[] name2 = {nc2};
        NamingContext ctx2 = ctx.bind_new_context(name2);
        System.out.println("new naming context added..");
The remainder of the code binds the dummy object reference using the names "schedule" and "calendar" under the "Personal" naming context (ctx2).
        NameComponent nc3 = new NameComponent("schedule", "text");
        NameComponent[] name3 = {nc3};
        ctx2.rebind(name3, objref);
        System.out.println("schedule rebind sucessful!");

        NameComponent nc4 = new NameComponent("calender", "text");
        NameComponent[] name4 = {nc4};
        ctx2.rebind(name4, objref);
        System.out.println("calender rebind sucessful!");

    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
  }
}

Sample Client: Browsing the Namespace

The following sample program illustrates how to browse the namespace.

import java.util.Properties;
import org.omg.CORBA.*;
import org.omg.CosNaming.*;

public class NameClientList
{
   public static void main(String args[])
   {
      try {
In the above section, Starting the Java IDL Transient Naming Service, the nameserver was started on port 1050. The following code ensures that the client program is aware of this port number.

        Properties props = new Properties();
        props.put("org.omg.CORBA.ORBInitialPort", "1050");
        ORB orb = ORB.init(args, props);
The following code obtains the intial naming context.
        NamingContext nc =
NamingContextHelper.narrow(orb.resolve_initial_references("NameService"));
The list method lists the bindings in the naming context. In this case, up to 1000 bindings from the initial naming context will be returned in the BindingListHolder; any remaining bindings are returned in the BindingIteratorHolder.
        BindingListHolder bl = new BindingListHolder();
        BindingIteratorHolder blIt= new BindingIteratorHolder();
        nc.list(1000, bl, blIt);
This code gets the array of bindings out of the returned BindingListHolder. If there are no bindings, the program ends.
        Binding bindings[] = bl.value;
        if (bindings.length == 0) return;
The remainder of the code loops through the bindings and prints the names out.
        for (int i=0; i < bindings.length; i++) {

            // get the object reference for each binding
            org.omg.CORBA.Object obj = nc.resolve(bindings[i].binding_name);
            String objStr = orb.object_to_string(obj);
            int lastIx = bindings[i].binding_name.length-1;

            // check to see if this is a naming context
            if (bindings[i].binding_type == BindingType.ncontext) {
              System.out.println( "Context: " +
bindings[i].binding_name[lastIx].id);
            } else {
                System.out.println("Object: " +
bindings[i].binding_name[lastIx].id);
            }
        }

       } catch (Exception e) {
        e.printStackTrace(System.err);
       }
   }
}
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java SE Monitoring and Management Guide

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Java SE Monitoring and Management Guide

October 2006
++

- Document Information

Preface

+ 1. Overview of Java SE Monitoring and Management

+ 2. Monitoring and Management Using JMX Technology

+ 3. Using JConsole

+ 4. Using the Platform MBean Server and Platform MXBeans

+ 5. SNMP Monitoring and Management

+ A. Additional Security Information For Microsoft Windows
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


- Java SE Monitoring and Management Guide

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Java SE Monitoring and Management Guide

October 2006
++

+ Document Information

Preface

- 1. Overview of Java SE Monitoring and Management

Key Monitoring and Management Features

Java VM Instrumentation

Monitoring and Management API

Monitoring and Management Tools

Java Management Extensions (JMX) Technology

What are MBeans?

MBean Server

Creating and Registering MBeans

Instrumenting Applications

Platform MXBeans

Platform MBean Server

+ 2. Monitoring and Management Using JMX Technology

+ 3. Using JConsole

+ 4. Using the Platform MBean Server and Platform MXBeans

+ 5. SNMP Monitoring and Management

+ A. Additional Security Information For Microsoft Windows
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


- Java SE Monitoring and Management Guide

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Java SE Monitoring and Management Guide

October 2006
++

+ Document Information

Preface

+ 1. Overview of Java SE Monitoring and Management

- 2. Monitoring and Management Using JMX Technology

Setting System Properties

Enabling the Out-of-the-Box Management

Local Monitoring and Management

Local Monitoring and Management Using JConsole

Remote Monitoring and Management

Using Password Authentication

Disabling Password Authentication

Using SSL

Enabling RMI Registry Authentication

Enabling SSL Client Authentication

Disabling SSL

Disabling Security

Remote Monitoring with JConsole

Remote Monitoring with JConsole with SSL Disabled

Remote Monitoring with JConsole with SSL Enabled

Using Password and Access Files

Password Files

Access Files

Out-of-the-Box Monitoring and Management Properties

Configuration Errors

Connecting to the JMX Agent Programmatically

Setting up Monitoring and Management Programmatically

Mimicking Out-of-the-Box Management Using the JMX Remote API

Example of Mimicking Out-of-the-Box Management

Monitoring Applications through a Firewall

Using an Agent Class to Instrument an Application

+ 3. Using JConsole

+ 4. Using the Platform MBean Server and Platform MXBeans

+ 5. SNMP Monitoring and Management

+ A. Additional Security Information For Microsoft Windows
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


- Java SE Monitoring and Management Guide

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Java SE Monitoring and Management Guide

October 2006
++

+ Document Information

Preface

+ 1. Overview of Java SE Monitoring and Management

+ 2. Monitoring and Management Using JMX Technology

- 3. Using JConsole

Starting JConsole

Command Syntax

Setting up Local Monitoring

Setting up Remote Monitoring

Setting up Secure Remote Monitoring

Connecting to a JMX Agent

Dynamic Attach

Connecting JConsole to a Local Process

Connecting JConsole to a Remote Process

Connecting Using a JMX Service URL

Presenting the JConsole Tabs

Viewing Overview Information

Saving Chart Data

Monitoring Memory Consumption

Heap and Non-Heap Memory

Memory Pools and Memory Managers

Garbage Collection

Monitoring Thread Use

Detecting Deadlocked Threads

Monitoring Class Loading

Viewing VM Information

Monitoring and Managing MBeans

Constructing the MBean Tree

MBean Attributes

MBean Operations

MBean Notifications

HotSpot Diagnostic MXBean

Creating Custom Tabs

+ 4. Using the Platform MBean Server and Platform MXBeans

+ 5. SNMP Monitoring and Management

+ A. Additional Security Information For Microsoft Windows
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


- Java SE Monitoring and Management Guide

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Java SE Monitoring and Management Guide

October 2006
++

+ Document Information

Preface

+ 1. Overview of Java SE Monitoring and Management

+ 2. Monitoring and Management Using JMX Technology

+ 3. Using JConsole

- 4. Using the Platform MBean Server and Platform MXBeans

Using the Platform MBean Server

Accessing Platform MXBeans

Accessing Platform MXBeans via the ManagementFactory Class

Accessing Platform MXBeans via an MXBean Proxy

Accessing Platform MXBeans via the MBeanServerConnection Class

Using Sun Microsystems' Platform Extension

Accessing MXBean Attributes Directly

Accessing MXBean Attributes via MBeanServerConnection

Monitoring Thread Contention and CPU Time

Managing the Operating System

Logging Management

Detecting Low Memory

Memory Thresholds

Usage Threshold

Collection Usage Threshold

Memory MXBean

Memory Pool MXBean

Polling

Threshold Notifications

+ 5. SNMP Monitoring and Management

+ A. Additional Security Information For Microsoft Windows
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


- Java SE Monitoring and Management Guide

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Java SE Monitoring and Management Guide

October 2006
++

+ Document Information

Preface

+ 1. Overview of Java SE Monitoring and Management

+ 2. Monitoring and Management Using JMX Technology

+ 3. Using JConsole

+ 4. Using the Platform MBean Server and Platform MXBeans

- 5. SNMP Monitoring and Management

Enabling the SNMP Agent

Access Control List File

To Enable the SNMP Agent in a Single-user Environment

To Enable the SNMP Agent in a Multiple-user Environment

SNMP Monitoring and Management Properties

Configuration Errors

+ A. Additional Security Information For Microsoft Windows
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


- Java SE Monitoring and Management Guide

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Java SE Monitoring and Management Guide

October 2006
++

+ Document Information

Preface

+ 1. Overview of Java SE Monitoring and Management

+ 2. Monitoring and Management Using JMX Technology

+ 3. Using JConsole

+ 4. Using the Platform MBean Server and Platform MXBeans

+ 5. SNMP Monitoring and Management

- A. Additional Security Information For Microsoft Windows

How to Secure a Password File on Microsoft Windows Systems

To Secure a Password File on Windows XP Professional Edition

To Secure a Password File on Windows XP Home Edition
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java SE Monitoring and Management Guide

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search
Java SE Monitoring and Management Guide

October 2006
--

Document Information

Preface

1. Overview of Java SE Monitoring and Management

Key Monitoring and Management Features

Java VM Instrumentation

Monitoring and Management API

Monitoring and Management Tools

Java Management Extensions (JMX) Technology

What are MBeans?

MBean Server

Creating and Registering MBeans

Instrumenting Applications

Platform MXBeans

Platform MBean Server

2. Monitoring and Management Using JMX Technology

Setting System Properties

Enabling the Out-of-the-Box Management

Local Monitoring and Management

Local Monitoring and Management Using JConsole

Remote Monitoring and Management

Using Password Authentication

Disabling Password Authentication

Using SSL

Enabling RMI Registry Authentication

Enabling SSL Client Authentication

Disabling SSL

Disabling Security

Remote Monitoring with JConsole

Remote Monitoring with JConsole with SSL Disabled

Remote Monitoring with JConsole with SSL Enabled

Using Password and Access Files

Password Files

Access Files

Out-of-the-Box Monitoring and Management Properties

Configuration Errors

Connecting to the JMX Agent Programmatically

Setting up Monitoring and Management Programmatically

Mimicking Out-of-the-Box Management Using the JMX Remote API

Example of Mimicking Out-of-the-Box Management

Monitoring Applications through a Firewall

Using an Agent Class to Instrument an Application

3. Using JConsole

Starting JConsole

Command Syntax

Setting up Local Monitoring

Setting up Remote Monitoring

Setting up Secure Remote Monitoring

Connecting to a JMX Agent

Dynamic Attach

Connecting JConsole to a Local Process

Connecting JConsole to a Remote Process

Connecting Using a JMX Service URL

Presenting the JConsole Tabs

Viewing Overview Information

Saving Chart Data

Monitoring Memory Consumption

Heap and Non-Heap Memory

Memory Pools and Memory Managers

Garbage Collection

Monitoring Thread Use

Detecting Deadlocked Threads

Monitoring Class Loading

Viewing VM Information

Monitoring and Managing MBeans

Constructing the MBean Tree

MBean Attributes

MBean Operations

MBean Notifications

HotSpot Diagnostic MXBean

Creating Custom Tabs

4. Using the Platform MBean Server and Platform MXBeans

Using the Platform MBean Server

Accessing Platform MXBeans

Accessing Platform MXBeans via the ManagementFactory Class

Accessing Platform MXBeans via an MXBean Proxy

Accessing Platform MXBeans via the MBeanServerConnection Class

Using Sun Microsystems' Platform Extension

Accessing MXBean Attributes Directly

Accessing MXBean Attributes via MBeanServerConnection

Monitoring Thread Contention and CPU Time

Managing the Operating System

Logging Management

Detecting Low Memory

Memory Thresholds

Usage Threshold

Collection Usage Threshold

Memory MXBean

Memory Pool MXBean

Polling

Threshold Notifications

5. SNMP Monitoring and Management

Enabling the SNMP Agent

Access Control List File

To Enable the SNMP Agent in a Single-user Environment

To Enable the SNMP Agent in a Multiple-user Environment

SNMP Monitoring and Management Properties

Configuration Errors

A. Additional Security Information For Microsoft Windows

How to Secure a Password File on Microsoft Windows Systems

To Secure a Password File on Windows XP Professional Edition

To Secure a Password File on Windows XP Home Edition
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Substitution by Serializable Classes

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Serialization and the writeReplace/readResolve Methods

Running the Example

Complete the following procedure to compile and run the example:

  1. From yourbasedir/objectserialization/ReplaceableInterface, compile the file Substitute.java using JDK™ 1.2 or higher:
      javac Substitute.java
  2. Run the compiled file:
      java Substitute

Additional Information

Abstract
Sources
List of Examples
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java Platform Debugger Architecture

Trace runs the Java language program passed as an argument and generates a trace of its execution. Trace is a simple command line tool that uses the Java Debug Interface (JDI). Programs need not be compiled for debugging since this information is not used.

Trace can be invoked as follows:

        java Trace options class args
Your classpath must include the Java 2 SDK's lib/tools.jar file which contains the JDI Library (see set-up), the path to the compiled trace class files, and the path for the application being traced.

Available options are:

  -output filename
        Set destination for output trace. By default output
        goes to the terminal.

  -all
        Include system classes in output.  By default
        java.*, javax.*, sun.* and com.sun.* events are
        not diplayed.

  -fields
        Also show assignments into fields.

  -help
        Print a help message

class is the program to trace. args are the arguments to class.

Source for trace

Full source code for trace is included in the trace directory of examples.jar. Source code of these example application is included to provide concrete examples for debugger developers. Example code may be used, modified and redistributed by debugger developers providing they adhere to the terms in the copyright notice.

Building trace

To completely rebuild the trace classes from the provided source files in the trace directory, you need only to compile them. No special options are required, aside from those which set your classpath to include the JDI Library in lib/tools.jar.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Tracing and Logging

See Tracing and Logging in the Java Deployment Guide.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Transitioning to 1.5 Doclet API

Introduction Notes

It is assumed that the doclet developer has read the documentation on new 1.5 language features and is aware of the doclet changes required to support the new features. This document only assists the developer in making those changes. It does not define all the new language features in 1.5.

Indicate That Your Doclet Supports 1.5 Source

Class com.sun.javadoc.Doclet has a new method that allows doclets to indicate which version of Java Programming Language is supported:

Doclet.languageVersion()

By default, this method returns LanguageVersion.JAVA_1_1. You should override this method and return LanguageVersion.JAVA_1_5.

Ensure That Your Doclet Handles Primitives Properly

Given a Type, most doclets distinguish between classes and primitives by using the following check:
   // If true, Type must be a primitive
   Type.asClassDoc() == null
In 1.5, this no longer works because there are other non-classdoc types besides primitives. For example, the asClassDoc method would return null for annotation types as well. You should find all occurances of ?Type.asClassDoc() == null? and replace it with Type.isPrimitive().

Use ClassDoc.superclassType() Instead of ClassDoc.superclass()

ClassDoc.superclass() cannot accommodate certain generic type constructs. The superclassType() method should be used instead.

Use ClassDoc.interfaceTypes() Instead of ClassDoc.interfaces()

ClassDoc.interfaces() cannot accommodate certain generic type constructs. The interfaceTypes() method should be used instead.

Type Parameters

When processing ClassDocs and ExecutableMemberDocs, call method typeParameters() to retrieve the formal type parameters. Each parameter can be processed in a similar way that regular types are processes. The only difference is that type parameters have bounds that need to be documented. The bounds are retrieved by calling TypeVariable.bounds().

Here is the interface that represents a type variable:

com.sun.javadoc.TypeVariable

Here is the algorithm that the standard doclet uses to process type parameters:

if (type.asTypeVariable()!= null) {
    Doc owner = type.asTypeVariable().owner();
    if (owner instanceof ClassDoc) {
        // Generate Link to type Parameter
    } else {
        // No need to link method type parameters.
        // Append the name of the type parameter
    }

    Type[] bounds = type.asTypeVariable().bounds();
    if (! linkInfo.excludeTypeBounds) {
        for (int i = 0; i < bounds.length; i++) {
            // If i greater than 0, append " & ".  Otherwise, append " extends "
            // Generate a link to the bound
        }
    }
}

Param Tags For Type Parameters

A doclet retrieves @param tags from constructors and methods by calling ExecutableMemberDoc.paramTags(). Since classes, constructors and methods can have type parameters, the @param tag may be used to document these type parameters. They are distinguished by having angle brackets around the names. For example:
/**
 * @param <E> the type parameter for this class.
 */
public class Foo<E>
To retrieve these type parameter @param tags, call ClassDoc. typeParamTags() or ExecutableMemberDoc.typeParamTags().

Type parameter tags can be distinguished from regular parameter tags by calling ParamTag.isTypeParameter().

Annotation Types

An annotation type is distinguished from classes and interfaces by calling the isAnnotationType() method. Here is the interface that represents an annotation type:

com.sun.javadoc.AnnotationTypeDoc

Retrieve the annotation type elements by calling method elements(). There are two types of elements:

  • An optional element. If the user does not specify a value for this element, it is set to a specified default value.
  • A required element. The user must specify a value for this element when using the annotation.
There is no way to retrieve an exactly list of optional and required elements from the doclet API. The doclet must manually interate through the array of elements and check the default value is null. If it is null, the element is required.

Annotation Type Usage

When processing a ProgramElementDoc, the annotation() method should be called to retrieve the annotations used. Here is the interface that encapsulates annoation usage information:

com.sun.javadoc.AnnotationDesc

Iterate through the list of AnnotationDesc objects and process each one. Here is the algorithm that the standard doclet uses to process AnnotationDesc objects:

for (int i = 0; i < descList.length; i++) {
    AnnotationTypeDoc annotationDoc = descList[i].annotationType();
    if (/**annotationDoc does not have @documented annotation**/){
        // ONLY document annotations if they have @documented.
        continue;
    }
    // Generate a link to the annotation.  Start with the ?@? character>
    AnnotationDesc.ElementValuePair[] pairs =
        descList[i].elementValues();
    if (pairs.length > 0) {
        // Append '(' to indicate start of element list>
        for (int j = 0; j < pairs.length; j++) {
              if (j > 0) {
                // Append ',' to separate previous element from the next>
            }
            // Generate a link to the annotation element>
            // Append '=' to separate element name from value>
            AnnotationValue annotationValue = pairs[j].value();
            List annotationTypeValues = new ArrayList();
            if (annotationValue.value() instanceof
                     AnnotationValue[]) {
                 AnnotationValue[] annotationArray =
                 (AnnotationValue[]) annotationValue.value();
                 for (int k = 0; k < annotationArray.length; k++) {
                    annotationTypeValues.add(annotationArray[k]);
                 }
           } else {
               annotationTypeValues.add(annotationValue);
           }
           // Append '{' if this is an array of values
           for (Iterator iter =
               annotationTypeValues.iterator();
               iter.hasNext(); ) {
               // Append string representation of value
               // Append ?,? if there is more to append
           }
           // Append '}' if this is an array of values
       }
       // Append ')' if this is an array of values
    }
}
Here is a sample of this output:

java.lang.annotation.Target

An annotation value can be any of the following:

  • Type
  • Array Type
  • Primitive
  • Nested Annotation
  • MemberDoc
  • String
Here is the algorithm that the standard doclet uses to convert an annotation to a string:
if (annotationValue.value() instanceof Type) {
    Type type = (Type) annotationValue.value();
    if (type.asClassDoc() != null) {
        LinkInfoImpl linkInfo = new LinkInfoImpl(
           LinkInfoImpl.CONTEXT_ANNOTATION, type);
        linkInfo.label = (type.asClassDoc().isIncluded() ?
            type.typeName() :
            type.qualifiedTypeName()) + type.dimension() + ".class ";
        return getLink(linkInfo);
    } else {
        return type.typeName() + type.dimension() + ".class";
    }
} else if (annotationValue.value() instanceof AnnotationDesc) {
    // Handle nested annotations using recursion.
    List list = getAnnotations(
        new AnnotationDesc[]{(AnnotationDesc) annotationValue.value()},
            false);
    StringBuffer buf = new StringBuffer();
    for (Iterator iter = list.iterator(); iter.hasNext(); ) {
        buf.append(iter.next());
    }
    return buf.toString();
} else if (annotationValue.value() instanceof MemberDoc) {
    // Simply link to the member being references in the annotation.
    return getDocLink(LinkInfoImpl.CONTEXT_ANNOTATION,
        (MemberDoc) annotationValue.value(),
        ((MemberDoc) annotationValue.value()).name(), false);
} else {
    return annotationValue.toString();
}

Enums

An enum is distinguished from classes and interfaces by calling the isEnum() method. To retrieve the list of enum constants to be documented, call the enumConstants() method. The enum constants are returned as an array of FieldDoc objects. An enum constant can be distinguished from a regular field by calling isEnumConstant().

Here is a sample of Enum documentation:

java.lang.management.MemoryType.html

Varable Arguments

When processing an ExecutableMemberDoc, call isVarArg() to determine if the last constructor/method parameter is a var arg. If it is, the last parameter requires special handling. Here is the extra code that the standard doclet executes for var args:
if (isVarArg) {
    if (type.dimension().length() > 2) {
        // Doclet API returns var args as array.
        // Strip out the first [] from the var arg.
        // Append type.dimension().substring(2)
    }
    // Append "..."
} else {
    // Append type.dimension()
}
This code should be inserted in the place where you normally document array dimensions. Please note the comment that var args are returned as arrays by the doclet API. We strip out the first ?[]? because it is just a part of the internal representation of the var arg and should not appear in the documetation.

Wild Cards

Here is the interface that represents the wild card type:

com.sun.javadoc.WildcardType

When a wild card is encountered, iterate through the lists of extends and super bounds. Process each bound the same way you would process a regular type. Here is the algorithm the standard doclet uses to process wild cards:

if (type.asWildcardType() != null) {
    WildcardType wildcardType = type.asWildcardType();
    Type[] extendsBounds = wildcardType.extendsBounds();
    for (int i = 0; i < extendsBounds.length; i++) {
        // If i greater than 0, append " , ".  Otherwise, append " extends "
        // Generate link to extendsBounds[i])
    }
    Type[] superBounds = wildcardType.superBounds();
    for (int i = 0; i < superBounds.length; i++) {
        // If i greater than 0, append " , ".  Otherwise, append " super "
        // Generate link to superBounds[i])
    }
}
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.connect.Transport (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.connect.Transport

  • Packages that use Transport
    Package Description
    com.sun.jdi.connect
    This package defines connections between the virtual machine using the JDI and the target virtual machine.

    • Uses of Transport in com.sun.jdi.connect

      Methods in com.sun.jdi.connect that return Transport
      Modifier and Type Method and Description
      Transport Connector.transport()
      Returns the transport mechanism used by this connector to establish connections with a target VM.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.jdi.connect.spi.TransportService (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.connect.spi.TransportService

No usage of com.sun.jdi.connect.spi.TransportService
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.jdi.connect.spi.TransportService.Capabilities (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.connect.spi.TransportService.Capabilities

  • Packages that use TransportService.Capabilities
    Package Description
    com.sun.jdi.connect.spi
    This package comprises the interfaces and classes used to develop new TransportService implementations.

    • Uses of TransportService.Capabilities in com.sun.jdi.connect.spi

      Methods in com.sun.jdi.connect.spi that return TransportService.Capabilities
      Modifier and Type Method and Description
      abstract TransportService.Capabilities TransportService.capabilities()
      Returns the capabilities of the transport service.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.jdi.connect.spi.TransportService.ListenKey (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.connect.spi.TransportService.ListenKey

  • Packages that use TransportService.ListenKey
    Package Description
    com.sun.jdi.connect.spi
    This package comprises the interfaces and classes used to develop new TransportService implementations.

    • Uses of TransportService.ListenKey in com.sun.jdi.connect.spi

      Methods in com.sun.jdi.connect.spi that return TransportService.ListenKey
      Modifier and Type Method and Description
      abstract TransportService.ListenKey TransportService.startListening()
      Listens on an address choosen by the transport service.
      abstract TransportService.ListenKey TransportService.startListening(String address)
      Listens on the specified address for inbound connections.
      Methods in com.sun.jdi.connect.spi with parameters of type TransportService.ListenKey
      Modifier and Type Method and Description
      abstract Connection TransportService.accept(TransportService.ListenKey listenKey, long acceptTimeout, long handshakeTimeout)
      Accept a connection from a target VM.
      abstract void TransportService.stopListening(TransportService.ListenKey listenKey)
      Stop listening for inbound connections.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.jdi.connect.TransportTimeoutException (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.connect.TransportTimeoutException

No usage of com.sun.jdi.connect.TransportTimeoutException
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.Tree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.Tree

  • Packages that use Tree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of Tree in com.sun.source.tree

      Subinterfaces of Tree in com.sun.source.tree
      Modifier and Type Interface and Description
      interface  AnnotationTree
      A tree node for an annotation.
      interface  ArrayAccessTree
      A tree node for an array access expression.
      interface  ArrayTypeTree
      A tree node for an array type.
      interface  AssertTree
      A tree node for an 'assert' statement.
      interface  AssignmentTree
      A tree node for an assignment expression.
      interface  BinaryTree
      A tree node for a binary expression.
      interface  BlockTree
      A tree node for a statement block.
      interface  BreakTree
      A tree node for a 'break' statement.
      interface  CaseTree
      A tree node for a 'case' in a 'switch' statement.
      interface  CatchTree
      A tree node for a 'catch' block in a 'try' statement.
      interface  ClassTree
      A tree node for a class, interface, enum, or annotation type declaration.
      interface  CompilationUnitTree
      Represents the abstract syntax tree for compilation units (source files) and package declarations (package-info.java).
      interface  CompoundAssignmentTree
      A tree node for compound assignment operator.
      interface  ConditionalExpressionTree
      A tree node for the conditional operator ? :.
      interface  ContinueTree
      A tree node for a 'continue' statement.
      interface  DisjunctiveTypeTree
      A tree node for a disjunctive type expression in a multicatch var declaration.
      interface  DoWhileLoopTree
      A tree node for a 'do' statement.
      interface  EmptyStatementTree
      A tree node for an empty (skip) statement.
      interface  EnhancedForLoopTree
      A tree node for an "enhanced" 'for' loop statement.
      interface  ErroneousTree
      A tree node to stand in for a malformed expression.
      interface  ExpressionStatementTree
      A tree node for an expression statement.
      interface  ExpressionTree
      A tree node used as the base class for the different types of expressions.
      interface  ForLoopTree
      A tree node for a basic 'for' loop statement.
      interface  IdentifierTree
      A tree node for an identifier expression.
      interface  IfTree
      A tree node for an 'if' statement.
      interface  ImportTree
      A tree node for an import statement.
      interface  InstanceOfTree
      A tree node for an 'instanceof' expression.
      interface  LabeledStatementTree
      A tree node for a labeled statement.
      interface  LiteralTree
      A tree node for a literal expression.
      interface  MemberSelectTree
      A tree node for a member access expression.
      interface  MethodInvocationTree
      A tree node for a method invocation expression.
      interface  MethodTree
      A tree node for a method or annotation type element declaration.
      interface  ModifiersTree
      A tree node for the modifiers, including annotations, for a declaration.
      interface  NewArrayTree
      A tree node for an expression to create a new instance of an array.
      interface  NewClassTree
      A tree node to declare a new instance of a class.
      interface  ParameterizedTypeTree
      A tree node for a type expression involving type parameters.
      interface  ParenthesizedTree
      A tree node for a parenthesized expression.
      interface  PrimitiveTypeTree
      A tree node for a primitive type.
      interface  ReturnTree
      A tree node for a 'return' statement.
      interface  StatementTree
      A tree node used as the base class for the different kinds of statements.
      interface  SwitchTree
      A tree node for a 'switch' statement.
      interface  SynchronizedTree
      A tree node for a 'synchronized' statement.
      interface  ThrowTree
      A tree node for a 'throw' statement.
      interface  TryTree
      A tree node for a 'try' statement.
      interface  TypeCastTree
      A tree node for a type cast expression.
      interface  TypeParameterTree
      A tree node for a type parameter.
      interface  UnaryTree
      A tree node for postfix and unary expressions.
      interface  VariableTree
      A tree node for a variable declaration.
      interface  WhileLoopTree
      A tree node for a 'while' loop statement.
      interface  WildcardTree
      A tree node for a wildcard type argument.
      Methods in com.sun.source.tree that return Tree
      Modifier and Type | Method and Description
      Tree | AnnotationTree.getAnnotationType()
      Tree | WildcardTree.getBound()
      Tree | MethodTree.getDefaultValue()
      Tree | ClassTree.getExtendsClause()
      Tree | ImportTree.getQualifiedIdentifier()
      Tree | MethodTree.getReturnType()
      Tree | VariableTree.getType()
      Tree | TypeCastTree.getType()
      Tree | ParameterizedTypeTree.getType()
      Tree | NewArrayTree.getType()
      Tree | InstanceOfTree.getType()
      Tree | ArrayTypeTree.getType()
      Methods in com.sun.source.tree that return types with arguments of type Tree
      Modifier and Type | Method and Description
      Class<? extends Tree> | Tree.Kind.asInterface()
      List<? extends Tree> | TypeParameterTree.getBounds()
      List<? extends Tree> | ErroneousTree.getErrorTrees()
      List<? extends Tree> | ClassTree.getImplementsClause()
      List<? extends Tree> | ClassTree.getMembers()
      List<? extends Tree> | TryTree.getResources()
      List<? extends Tree> | DisjunctiveTypeTree.getTypeAlternatives()
      List<? extends Tree> | ParameterizedTypeTree.getTypeArguments()
      List<? extends Tree> | NewClassTree.getTypeArguments()
      List<? extends Tree> | MethodInvocationTree.getTypeArguments()
      List<? extends Tree> | CompilationUnitTree.getTypeDecls()
      Methods in com.sun.source.tree with parameters of type Tree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitOther(Tree node, P p)

    • Uses of Tree in com.sun.source.util

      Methods in com.sun.source.util that return Tree
      Modifier and Type Method and Description
      Tree TreePath.getLeaf()
      Get the leaf node for this path.
      abstract Tree Trees.getTree(Element element)
      Gets the Tree node for a given Element.
      abstract Tree Trees.getTree(Element e, AnnotationMirror a)
      Gets the Tree node for an AnnotationMirror on a given Element.
      abstract Tree Trees.getTree(Element e, AnnotationMirror a, AnnotationValue v)
      Gets the Tree node for an AnnotationValue for an AnnotationMirror on a given Element.
      Methods in com.sun.source.util that return types with arguments of type Tree
      Modifier and Type | Method and Description
      Iterator<Tree> | TreePath.iterator()
      Methods in com.sun.source.util with parameters of type Tree
      Modifier and Type | Method and Description
      protected R | SimpleTreeVisitor.defaultAction(Tree node, P p)
      long SourcePositions.getEndPosition(CompilationUnitTree file, Tree tree)
      Gets the ending position of tree within file.
      abstract TreePath Trees.getPath(CompilationUnitTree unit, Tree node)
      Gets the path to tree node within the specified compilation unit.
      static TreePath TreePath.getPath(CompilationUnitTree unit, Tree target)
      Gets a tree path for a tree node within a compilation unit.
      static TreePath TreePath.getPath(TreePath path, Tree target)
      Gets a tree path for a tree node within a subtree identified by a TreePath object.
      long SourcePositions.getStartPosition(CompilationUnitTree file, Tree tree)
      Gets the starting position of tree within file.
      abstract void Trees.printMessage(Diagnostic.Kind kind, CharSequence msg, Tree t, CompilationUnitTree root)
      Prints a message of the specified kind at the location of the tree within the provided compilation unit
      R TreeScanner.scan(Tree node, P p)
      Scan a single node.
      R TreePathScanner.scan(Tree tree, P p)
      Scan a single node.
      R | SimpleTreeVisitor.visit(Tree node, P p)
      R | TreeScanner.visitOther(Tree node, P p)
      R | SimpleTreeVisitor.visitOther(Tree node, P p)
      Method parameters in com.sun.source.util with type arguments of type Tree
      Modifier and Type | Method and Description
      abstract TypeMirror JavacTask.getTypeMirror(Iterable<? extends Tree> path)
      Get a type mirror of the tree node determined by the specified path.
      R TreeScanner.scan(Iterable<? extends Tree> nodes, P p)
      Scan a list of nodes.
      R | SimpleTreeVisitor.visit(Iterable<? extends Tree> nodes, P p)
      Constructors in com.sun.source.util with parameters of type Tree
      Constructor and Description
      TreePath(TreePath p, Tree t)
      Creates a TreePath for a child node.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.source.tree.Tree.Kind (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.source.tree.Tree.Kind

  • Packages that use Tree.Kind
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).

    • Uses of Tree.Kind in com.sun.source.tree

      Methods in com.sun.source.tree that return Tree.Kind
      Modifier and Type Method and Description
      Tree.Kind Tree.getKind()
      Gets the kind of this tree.
      static Tree.Kind Tree.Kind.valueOf(String name)
      Returns the enum constant of this type with the specified name.
      static Tree.Kind[] Tree.Kind.values()
      Returns an array containing the constants of this enum type, in the order they are declared.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.source.util.TreePath (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.source.util.TreePath

  • Packages that use TreePath
    Package Description
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of TreePath in com.sun.source.util

      Methods in com.sun.source.util that return TreePath
      Modifier and Type Method and Description
      TreePath TreePathScanner.getCurrentPath()
      Get the current path for the node, as built up by the currently active set of scan calls.
      TreePath TreePath.getParentPath()
      Get the path for the enclosing node, or null if there is no enclosing node.
      abstract TreePath Trees.getPath(CompilationUnitTree unit, Tree node)
      Gets the path to tree node within the specified compilation unit.
      static TreePath TreePath.getPath(CompilationUnitTree unit, Tree target)
      Gets a tree path for a tree node within a compilation unit.
      abstract TreePath Trees.getPath(Element e)
      Gets the TreePath node for a given Element.
      abstract TreePath Trees.getPath(Element e, AnnotationMirror a)
      Gets the TreePath node for an AnnotationMirror on a given Element.
      abstract TreePath Trees.getPath(Element e, AnnotationMirror a, AnnotationValue v)
      Gets the TreePath node for an AnnotationValue for an AnnotationMirror on a given Element.
      static TreePath TreePath.getPath(TreePath path, Tree target)
      Gets a tree path for a tree node within a subtree identified by a TreePath object.
      Methods in com.sun.source.util with parameters of type TreePath
      Modifier and Type Method and Description
      abstract String Trees.getDocComment(TreePath path)
      Gets the doc comment, if any, for the Tree node identified by a given TreePath.
      abstract Element Trees.getElement(TreePath path)
      Gets the Element for the Tree node identified by a given TreePath.
      static TreePath TreePath.getPath(TreePath path, Tree target)
      Gets a tree path for a tree node within a subtree identified by a TreePath object.
      abstract Scope Trees.getScope(TreePath path)
      Gets the Scope for the Tree node identified by a given TreePath.
      abstract TypeMirror Trees.getTypeMirror(TreePath path)
      Gets the TypeMirror for the Tree node identified by a given TreePath.
      R TreePathScanner.scan(TreePath path, P p)
      Scan a tree from a position identified by a TreePath.
      Constructors in com.sun.source.util with parameters of type TreePath
      Constructor and Description
      TreePath(TreePath p, Tree t)
      Creates a TreePath for a child node.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.source.util.TreePathScanner (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.source.util.TreePathScanner

No usage of com.sun.source.util.TreePathScanner
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.source.util.Trees (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.source.util.Trees

  • Packages that use Trees
    Package Description
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of Trees in com.sun.source.util

      Methods in com.sun.source.util that return Trees
      Modifier and Type Method and Description
      static Trees Trees.instance(JavaCompiler.CompilationTask task)
      Gets a Trees object for a given CompilationTask.
      static Trees Trees.instance(ProcessingEnvironment env)
      Gets a Trees object for a given ProcessingEnvironment.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.source.util.TreeScanner (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.source.util.TreeScanner

  • Packages that use TreeScanner
    Package Description
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of TreeScanner in com.sun.source.util

      Subclasses of TreeScanner in com.sun.source.util
      Modifier and Type Class and Description
      class  TreePathScanner<R,P>
      A TreeVisitor that visits all the child tree nodes, and provides support for maintaining a path for the parent nodes.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.TreeVisitor (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.TreeVisitor

  • Packages that use TreeVisitor
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of TreeVisitor in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type TreeVisitor
      Modifier and Type Method and Description
      <R,D> R Tree.accept(TreeVisitor<R,D> visitor, D data)
      Accept method used to implement the visitor pattern.

    • Uses of TreeVisitor in com.sun.source.util

      Classes in com.sun.source.util that implement TreeVisitor
      Modifier and Type Class and Description
      class  SimpleTreeVisitor<R,P>
      A simple visitor for tree nodes.
      class  TreePathScanner<R,P>
      A TreeVisitor that visits all the child tree nodes, and provides support for maintaining a path for the parent nodes.
      class  TreeScanner<R,P>
      A TreeVisitor that visits all the child tree nodes.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.traversal.TreeWalker (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.traversal.TreeWalker

  • Packages that use TreeWalker
    Package Description
    org.w3c.dom.traversal

    • Uses of TreeWalker in org.w3c.dom.traversal

      Methods in org.w3c.dom.traversal that return TreeWalker
      Modifier and Type Method and Description
      TreeWalker DocumentTraversal.createTreeWalker(Node root, int whatToShow, NodeFilter filter, boolean entityReferenceExpansion)
      Create a new TreeWalker over the subtree rooted at the specified node.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Troubleshooting

This section includes the following topics:

  • General Troubleshooting Issues
  • Troubleshooting Installation Issues
  • Troubleshooting Security Issues

General Troubleshooting Issues

Q. Why do I get a javax.net.ssl.SSLException (or hang or disconnect) when accessing an applet from an HTTPS site.

A. In some SSL/TLS servers you will encounter this problem if a client message is received in a format it doesn't understand or with a protocol version number that it doesn't support. The problem is on the server side. There may be several aspects of the SSL/TLS protocol that are not implemented correctly. If the server only speaks SSLv3, when a client sends a TLSv1 (aka SSLv3.1) hello the server is supposed to respond with a SSLv3 server hello (aka SSLv3.0). But the server is not doing so; hence, you get the exception (SSLException).

In Java Plug-in 1.3.x the browser's implementation of SSL was used. Netscape 4.x and Internet Explorer provide only an SSLv3.0 implementation. The problem will not be seen because in this version of Plug-in only SSLv3.0 is used.

In Java Plug-in 1.4.0 the JSSE implementation of TLS/SSL was used. By default, JSSE enables the TLSv1, SSLv3, and SSLv2Hello protocols. In this version of Plug-in TLSv1 will be used, and this problem may be seen on servers with incorrect protocol implementations.

Below are some ways to work around this problem. Turn off the TLSv1 protocol and use only SSLv3.

1. In the Java Plug-in Control Panel (Advanced tab) specify:

-Dhttps.protocols="SSLv3,SSLv2Hello"

2. Set the system property:

System.setProperty("https.protocols", "SSLv3");

3. If you have access to the socket, you can do this:

socket.setEnabledProtocols("SSLv3");

In Java Plug-in 1.4.1 the SSLv3 and SSLv2Hello protocols are used by default. Because most browsers use SSLv3 by default and most web servers support it—and to avoid seeing the above problem—the change was made to this version of the Plug-in. Users that need to use TLSv1 should set the https.protocols settings.

Q: Is there a way, other than restarting the browser, to force the JVM to check the server for modified JAR files for a page with an applet?

A: Modified jar files will be downloaded from the server when a page with an applet is refreshed or revisited if you first do this: type "x" in the Java Console to clear the Classloader cache.

Q: When trying to play a game on http://games.yahoo.com I get a ControlAccessException. What is the problem and is there a workaround?

A: The problem is that the game applet needs permission to connect to one or more servers, and it is being denied permission for security reasons. The workaround is this: Add the following to your java.policy file:

grant codeBase "http://download.yahoo.com/games/clients/" {
      permission java.net.SocketPermission "*","connect";};

java.policy is located in <JRE installation directory>/Java/j2re1.4.0/lib/security/.

Q: How do I get Nescape to find my plugin when I've downloaded and installed the Java SE, which includes Java Plug-in?

A: Set the NPX_PLUGIN_PATH envirronement variable to the location of the Java Plug-in (the directory in which the javaplugin.so file is located):

NPX_PLUGIN_PATH=$JAVAHOME/jre/plugin/sparc/ns4 for Netscape 4
NPX_PLUGIN_PATH=$JAVAHOME/jre/plugin/sparc/ns6 for Netscape 6

Q: I can't get Java Plug-in software to install in an intranet environment when I place it on our Netscape Enterprise 3.0 SuiteSpot web server. Why not?

A: We have reports that the Netscape Enterprise 3.0 SuiteSpot Webserver is unable, at least in some circumstances, to serve up .exe files. One apparent workaround has been to configure the HTML so that the Java Plug-in product is installed by a Visigenic Orb Gatekeeper, which also functions as a web server.

Q: I'm having trouble debugging with Java Plug-in Software. Do you have any tips?

A: In some circumstances, Java Plug-in Software will use a different debug connection address than expected. This occurs when Java Plug-in Software is loaded into the Explorer.exe process running in one of the following configurations:

  • Windows 95/NT running Active Desktop with IE4 or later
  • Windows 98/ME/2000

Java Plug-in Software is loaded into the Explorer.exe process when an HTML page containing the OBJECT tag is viewed in the following ways:

  • via preview in an Explorer folder, if the desktop settings allow web content to be viewed in folders (in other words, if the View->As Web Page menu option is checked)
  • via Internet Explorer, if the Microsoft Internet settings for "Launch browser windows in a separate process" or "Browse in a new process" are not set
  • via a web page shown on the Active Desktop

This can cause problems when debugging Java applets, since no two processes should use the same debug connection address. (See How to Debug Applets in Java Plug-in in Debugging Support regarding setting of the connection address.). If the Explorer.exe process has already claimed the debug connection address, and the Netscape.exe or Iexplorer.exe tries to use it, debugging problems may result.

Java Plug-in Software avoids this complication when loaded into the Explorer.exe process by prepending the debug connection address specified in the Control Panel with the string Explorer.

For example, if the default connection address set at the time of Java Plug-in Software installation is 2502, when running under Explorer.exe it is actually set to Explorer:2502.

When running JDB from the Java SDK you should specify

jdb -attach Explorer:2502

to attach to the JVM loaded into the Explorer.exe process.

Q: My applet is no longer scriptable in Internet Explorer with Java Plug-in. Why?

A: With Java Plug-in Software 1.3 a scriptable tag must be included and given a value of "true" in order for an applet to be scriptable. See the Using OBJECT, EMBED and APPLET Tags in Java Plug-in for more information.

Q: Why am I having problems using some standard extensions/optional packages?

A: Only extensions installed in the <jre>\lib\ext directory will be added to the classpath. Extensions installed in directories pointed to by the java.ext.dirs system property will not be added.

Q: Java Plug-in used to work with my Navigator 4.0.x browser. But when I upgraded to Navigator 4.5 and re-installed Java Plug-in, it does not work with Navigator 4.5. Why?

A: It has been reported that Navigator 4.5 may not install the user profile properly during installation. As a result, Java Plug-in Software may not read the correct user profile setting. To make sure the user profile setting is correct, check the following:

  • HKEY_LOCAL_MACHINE\Software\Netscape\Netscape Navigator\Users\CurrentUser
  • HKEY_LOCAL_MACHINE\Software\Netscape\Netscape Navigator\Users\<UserName>\DirRoot
Make sure that these two registry keys exist and <DirRoot> points to an existing user profile. If any of the registry keys are missing or incomplete, use the User Profile Manager tool to recreate your profile.

Q: We are trying to use Java 3D with Java Plug-in but it doesn't work at all. Why?

A: Java 3D comes with various packages. Installing it incorrectly may inadvertently disable Java Plug-in or cause it to fail. Follow these general instructions for using Java 3D and Java Plug-in Software:

  1. Install Java Plug-in first.
  2. Install Java 3D in a new directory. Do not install it over the existing Java SDK, Standard Edition/JRE. See this page for installation instructions.
  3. Install a version of the SDK/JRE that is appropriate for Java 3D if one is not already installed on your computer.
  4. In the Java Plug-in Control Panel, select the appropriate version of the SDK/JRE..
The Java 3D demos should now run within Java Plug-in.

Q: Some web/proxy servers require users to login for authentication. When I used the browser to access this server with Java Plug-in, two login dialog boxes appeared. Why?

A: Normally Java Plug-in will download the applets using its own connection. If the web/proxy server requires login, the browser will first encounter the request and bring up a login dialog box. After the HTML page is downloaded, Java Plug-in will try to download the class or jar files for the applet. However, since Java Plug-in has no access to the login information that the browser previously obtained, it will bring up its own login dialog box.

Q: When I tried to deploy Java Plug-in in the intranet and put the binaries on the internal web server, IE doesn't download and install Java Plug-in Software when it encounters the converted page. What's going on?

A: You may want to check that the CODEBASE in the OBJECT tag actually has the correct URL for Java Plug-in. Also, turning off execute privileges on the directory in which you put the Java Plug-in Software executable may help.

Q: I am experiencing problems getting an applet to render using Java Plug-in Software. What is the cause of this?

A: While this may be due to a variety of circumstances unique to your operating environment, a frequent cause of this problem is a security exception.

Problem: Your network does not support DNS (Domain Name Service). In order to perform certain security checks, the applet SecurityManager needs to be able to find the IP address from which your applet was downloaded. If DNS is not available, these security checks may fail.

Workaround: When visiting the target web page, specify an IP address rather than a hostname in the URL. For example, use "http://123.45.35.128/fred.html".

Q: I changed my browser setting while Java Plug-in Software was running, but it still uses the old settings after the change. Why?

A: The browser settings are read in by Java Plug-in when it is started. These settings are valid throughout the lifetime of the browser session. To make Java Plug-in read in the new settings, restart your browser. If you are running Active Desktop with Java Plug-in, you need to restart the computer.

Q: When I loaded my applet, it said "noninit" or "applet not initialized" in the browser's status bar. How can I identify the cause of the problem?

A: Follow these steps:

  1. Look at the error message in the Java Console.
  2. If you are accessing the applet through the network, make sure the proxy info shown in the Java Console is correct.
  3. Make sure all the class/JAR files are in the right directory.
  4. Make sure the converted HTML page is correct.
  5. Try the unconverted page with AppletViewer on the same machine. If it works, check 3, 4, and 5 again.

Q: When I try to use the AppletClassLoader with Java Plug-in Software, it crashes with a null pointer exception in IE4 but works fine in Netscape. Why does this happen? Is there a way to make it work correctly in IE4?

A: Java Plug-in Software in IE4 tries to load <YourAppletName>BeanInfo.class even if your applet is not a bean. There is a bug in Java SDK, Standard Edition v 1.3 in the AppletClassLoader that occurs when trying to load nonexistent classes. To prevent this problem, create an empty <YourAppletName>BeanInfo.class.

Q: Why does Java Plug-in Software sometimes crash Internet Explorer but not Netscape Navigator?

A: In certain circumstances, bad HTML will cause the browser to crash. One example is the absence of an </XMP> tag. Please make sure your HTML is correct.

Another possibility is that the plug-in was disabled using the Control Panel before you accessed a Plug-in-enabled page. Please check your settings to make sure the Plug-in is enabled.

Q: My applet used to create a top-level frame that would remain visible through page switches. When I upgraded to Java Plug-in this no longer occurs. Why?

A: In Java Plug-in Software, applets are stopped and destroyed during page switches. All the visible components should be destroyed as well. There has been an enhancement in Java SDK that makes sure that all of the resources of the applet are properly released, including the top-level frame.

Troubleshooting Installation Issues

Q: I am trying to install the Java Plug-in on a network drive. However, it doesn't install. Why?

A: If your network drive is protected or read-only, you will not be able to install the Java Plug-in. Contact your system administrator for more details.

Q: I am trying to install Java Plug-in. However, whenever the install program tries to install the Java Plug-in for Netscape Navigator, it displays an error. My Navigator is on a network drive. Is there a way to fix this?

A: If your Navigator is installed on a network drive, you may not have permission to install the plugin DLL on the Navigator Plugins directory. Contact your system administrator for more details.

Q: I'm having trouble installing the Java Plug-in on my Microsoft Windows machine. I see the error: "An application error has occurred and an application error log is being generated. Exception: access violation ..." What might be the problem?

A: The Microsoft Window installation (using Installshield's installer) may not work if you have Quarterdeck's Cleansweep product running in the background.

Q: When I reboot after I uninstalling Java Plug-in software, I get a dialog box warning that a .cpl file has been removed. What is this?

A: If the Java Plug-in Control Panel is open while you are uninstalling the plug-in, plugincpl.cpl will not be removed as it is locked when the Control Panel folder is open.

Q: When I uninstall Java Plug-in, the Microsoft Window Plugin for Netscape seems to stay on the machine. How can I remove that?

A: Delete the NPJPI<modified version number>.dll from the Netscape Plugins directory. For example, for Java Plug-in 1.4.0, delete NPJPI140.dll from the Plugins directory.

Troubleshooting Security Issues

Q: I have some security-related issues in my applet. How do I debug it?

A: You can enable the java.security.debug property to enable trace messages from the security system. Please see java.security.debug Property in the chapter called Debugging Support for more information.

Q: When downloading applets from the Internet, an AccessControlExcpetion is thrown. However, when the applet is located on the intranet, it works. Why?

A: To prevent DNS spoofing, a security check in Java Plug-in requires the host name to be resolved into an IP address before any connection is made from the applet. However, the side-effect of this security check is to require the intranet DNS server to be able to resolve any external host name from the Internet. For some customers, this is not the way their DNS servers are setup within the enterprise, and it causes Java Plug-in to fail. To resolve this issue, there are several options:

  1. Modify the HTML page of the applet, so the codebase and document base of the applet contains IP addresses instead of host names. This will avoid Java Plug-in performing a DNS lookup for the host name.
  2. Set trustProxy to true in Java Plug-in. By setting this property, Java Plug-in will trust the proxy to perform a proper DNS lookup and return information to Java Plug-in from trusted hosts. For intranet customers whose proxy servers are setup internally and can be trusted, this property may be used. This property may be specified as -DtrustProxy=true in the Java Plug-in Control Panel.

    Note that this property should be set by administrator, as setting this property improperly with an untrusted proxy server may expose the client machines to DNS spoofing. This property is similar to the security.lower_java_network_security_by_trusting_proxies property supported by Netscape Navigator's JVM.

Q: I keep getting a ClassFormatError exception when my webpage is loaded with HTTPS in Netscape Navigator. Why?

A: This is caused by an applet specifying a nonexistent .jar or .class file in the EMBED tag. Due to limitation of what information can be returned via HTTPS in Navigator, the web server's "File Not Found" HTML page is returned instead of the appropriate status. This HTML page is treated as a .class file and that causes the exception.

Q: I tried to run an RSA signed applet with Java Plug-in, but it is being treated as an untrusted applet. What is the problem?

A: There are several possibilities:

  • Your applet is not signed properly. Use the Netscape's signtool or Sun's jarsigner to verify it.
  • Your RSA certificate and its certificate chain may have expired.
Please see our How to Sign Applets Using RSA-Signed Certificates for details.

Q: Why do I get a yellow banner across my applet frame when using Java Plug-in?

A: When an applet creates a free-standing Frame, Java Plug-in adds a yellow warning banner so users will know they are dealing with an untrusted applet window.

Q: Can I disable the yellow warning banner on frames?

A: The yellow warning banner is an important security feature. It cannot be disabled by untrusted applets.

If you use a signed applet, where the signing key is trusted by the end user, then the warning banner will not be shown.

Q: How do I prevent the warning banner from covering my GUI state?

A: See the same question in the Developer FAQ.

Q: Why does InetAddress.getLocalHost().getHostName() return "localhost"?

A: See the same question in the Developer FAQ.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


The try-with-resources Statement

The try-with-resources statement is a try statement that declares one or more resources. A resource is as an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements the java.lang.AutoCloseable interface can be used as a resource.

The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:

static String readFirstLineFromFile(String path) throws IOException {
  try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    return br.readLine();
  }
}

In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:

static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
  BufferedReader br = new BufferedReader(new FileReader(path));
  try {
    return br.readLine();
  } finally {
    if (br != null) br.close();
  }
}

However, in this example, if the methods readLine and close both throw exceptions, then the method readFirstLineFromFileWithFinallyBlock throws the exception thrown from the finally block; the exception thrown from the try block is suppressed. In contrast, in the example readFirstLineFromFile, if exceptions are thrown from both the try block and the try-with-resources statement, then the method readFirstLineFromFile throws the exception thrown from the try block; the exception thrown from the try-with-resources block is suppressed. In Java SE 7 and later, you can retrieve suppressed exceptions; see the section Suppressed Exceptions for more information.

You may declare one or more resources in a try-with-resources statement. The following example retrieves the names of the files packaged in the zip file zipFileName and creates a text file that contains the names of these files:

  public static void writeToFileZipFileContents(String zipFileName, String outputFileName)
    throws java.io.IOException {

    java.nio.charset.Charset charset = java.nio.charset.Charset.forName("US-ASCII");
    java.nio.file.Path outputFilePath = java.nio.file.Paths.get(outputFileName);

    // Open zip file and create output file with try-with-resources statement

    try (
      java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
      java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
    ) {

      // Enumerate each entry

      for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) {

        // Get the entry name and write it to the output file

        String newLine = System.getProperty("line.separator");
        String zipEntryName = ((java.util.zip.ZipEntry)entries.nextElement()).getName() + newLine;
        writer.write(zipEntryName, 0, zipEntryName.length());
      }
    }
  }

In this example, the try-with-resources statement contains two declarations that are separated by a semicolon: ZipFile and BufferedWriter. When the block of code that directly follows it terminates, either normally or because of an exception, the close methods of the BufferedWriter and ZipFile objects are automatically called in this order. Note that the close methods of resources are called in the opposite order of their creation.

The following example uses a try-with-resources statement to automatically close a java.sql.Statement object:

  public static void viewTable(Connection con) throws SQLException {

    String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";

    try (Statement stmt = con.createStatement()) {

      ResultSet rs = stmt.executeQuery(query);

      while (rs.next()) {
        String coffeeName = rs.getString("COF_NAME");
        int supplierID = rs.getInt("SUP_ID");
        float price = rs.getFloat("PRICE");
        int sales = rs.getInt("SALES");
        int total = rs.getInt("TOTAL");
        System.out.println(coffeeName + ", " + supplierID + ", " + price +
                           ", " + sales + ", " + total);
      }

    } catch (SQLException e) {
      JDBCTutorialUtilities.printSQLException(e);
    }
  }

The resource java.sql.Statement used in this example is part of the JDBC 4.1 and later API.

Note: A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

Suppressed Exceptions

An exception can be thrown from the block of code associated with the try-with-resources statement. In the example writeToFileZipFileContents, an exception can be thrown from the try block, and up to two exceptions can be thrown from the try-with-resources statement when it tries to close the ZipFile and BufferedWriter objects. If an exception is thrown from the try block and one or more exceptions are thrown from the try-with-resources statement, then those exceptions thrown from the try-with-resources statement are suppressed, and the exception thrown by the block is the one that is thrown by the writeToFileZipFileContents method. You can retrieve these suppressed exceptions by calling the Throwable.getSuppressed method from the exception thrown by the try block.

Classes That Implement the AutoCloseable Interface

See the Javadoc of the AutoCloseable interface for a list of classes that implement this interface. The Closeable interface extends the AutoCloseable interface. The close method of the Closeable interface throws exceptions of type IOException while the close method of the AutoCloseable interface throws exceptions of type Exception. Consequently, subclasses of the AutoCloseable interface can override this behavior of the close method to throw specialized exceptions, such as IOException, or no exception at all.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.source.tree.TryTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.TryTree

  • Packages that use TryTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of TryTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type TryTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitTry(TryTree node, P p)

    • Uses of TryTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type TryTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitTry(TryTree node, P p)
      R | SimpleTreeVisitor.visitTry(TryTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Tutorial: Getting Started Using RMI-IIOP

This tutorial shows you the steps to follow to create a distributed version of the classic "Hello World" program using Java Remote Method Invocation (RMI) over Internet Inter-ORB Protocol (IIOP). RMI-IIOP adds CORBA (Common Object Request Broker Architecture) capability to Java RMI, providing standards-based interoperability and connectivity to many other programming languages and platforms. RMI-IIOP enables distributed Web-enabled Java applications to transparently invoke operations on remote network services using the industry standard IIOP defined by the Object Management Group. Runtime components include a Java ORB for distributed computing using IIOP communication.

RMI-IIOP is for Java programmers who want to program to the RMI interfaces, but use IIOP as the underlying transport. RMI-IIOP provides interoperability with other CORBA objects implemented in various languages - but only if all the remote interfaces are originally defined as Java RMI interfaces. It is of particular interest to programmers using Enterprise JavaBeans (EJB), since the remote object model for EJBs is RMI-based.

Other options for creating distributed applications are:

  • Java Interface Definition Language (IDL)

    Java IDL is for CORBA programmers who want to program in the Java programming language based on interfaces defined in CORBA Interface Definition Language (IDL). This is "business as usual" CORBA programming, supporting Java in exactly the same way as other languages like C++ or COBOL.

  • Java Remote Method Invocation (RMI).

    The Java RMI system allows an object running in one Java Virtual Machine (VM) to invoke methods on an object running in another Java VM. RMI provides for remote communication between programs written in the Java programming language via the Java Remote Method Protocol (JRMP).

Tutorial: The Hello World Application

The distributed Hello World example uses a client application to make a remote method call via IIOP to a server running on the host from which the client was downloaded. When the client runs, "Hello from MARS!" is displayed.

This tutorial is organized as follows:

  1. The steps to write the source files
  2. The steps to compile the example
  3. The steps to run the example

step icon Each step in the tutorial is indicated by this symbol.

Write or Download the Source Files

There are three tasks to complete in this section:

  1. Define the functions of the remote class as an interface written in the Java programming language
  2. Write the implementation class
  3. Write the server class
  4. Write a client program that uses the remote service
The source files used in this tutorial are:
  • HelloInterface.java - a remote interface
  • HelloImpl.java - a remote object implementation that implements HelloInterface
  • HelloServer.java - an RMI server that creates an instance of the remote object implementation and binds that instance to a name in the Naming Service
  • HelloClient.java - a client application that invokes the remote method, sayHello()

Follow the steps below to create the source files or download and unzip HelloRMIIIOP.zip.

Define the functions of the remote class as an interface written in the Java programming language

In the Java programming language, a remote object is an instance of a class that implements a Remote interface. Your remote interface will declare each of the methods that you would like to call from other machines. Remote interfaces have the following characteristics:
  • The remote interface must be declared public. Otherwise, a client will get an error when attempting to load a remote object that implements the remote interface, unless that client is in the same package as the remote interface.
  • The remote interface extends the java.rmi.Remote interface.
  • Each method must declare java.rmi.RemoteException (or a superclass of RemoteException) in its throws clause, in addition to any application-specific exceptions.
  • The data type of any remote object that is passed as an argument or return value (either directly or embedded within a local object) must be declared as the remote interface type (for example, HelloInterface) not the implementation class (HelloImpl).

For this example, create all of the source files in the same directory, for example, $HOME/mysrc/helloWorld.

step icon Create the file HelloInterface.java. The following code is the interface definition for the remote interface, HelloInterface, which contains just one method, sayHello:

//HelloInterface.java
import java.rmi.Remote;

public interface HelloInterface extends java.rmi.Remote {
   public void sayHello( String from ) throws java.rmi.RemoteException;
}
Because remote method invocations can fail in very different ways from local method invocations (due to network-related communication problems and server problems), remote methods will report communication failures by throwing a java.rmi.RemoteException. If you want more information on failure and recovery in distributed systems, you may wish to read A Note on Distributed Computing.

Write The Implementation Class

At a minimum, a remote object implementation class, HelloImpl.java must:

  • Declare that it implements at least one remote interface
  • Define the constructor for the remote object
  • Provide implementations for the methods that can be invoked remotely

step icon Create the file HelloImpl.java. The code for this file follows. An explanation of each of the preceding steps follows the source code:

//HelloImpl.java
import javax.rmi.PortableRemoteObject;

public class HelloImpl extends PortableRemoteObject implements HelloInterface {
   public HelloImpl() throws java.rmi.RemoteException {
       super();     // invoke rmi linking and remote object initialization
   }

   public void sayHello( String from ) throws java.rmi.RemoteException {
       System.out.println( "Hello from " + from + "!!" );
       System.out.flush();
   }
}

Implement a remote interface

In the Java programming language, when a class declares that it implements an interface, a contract is formed between the class and the compiler. By entering into this contract, the class is promising that it will provide method bodies, or definitions, for each of the method signatures declared in that interface. Interface methods are implicitly public and abstract, so if the implementation class doesn't fulfill its contract, it becomes by definition an abstract class, and the compiler will point out this fact if the class was not declared abstract.

The implementation class in this example is HelloImpl. The implementation class declares which remote interface(s) it is implementing. Here is the HelloImpl class declaration:

  public class HelloImpl extends PortableRemoteObject
    implements HelloInterface{
As a convenience, the implementation class can extend a remote class, which in this example is javax.rmi.PortableRemoteObject. By extending PortableRemoteObject, the HelloImpl class can be used to create a remote object that uses IIOP-based transport for communication.

Define the constructor for the remote object

The constructor for a remote class provides the same functionality as the constructor for a non-remote class: it initializes the variables of each newly created instance of the class, and returns an instance of the class to the program which called the constructor.

In addition, the remote object instance will need to be "exported". Exporting a remote object makes it available to accept incoming remote method requests, by listening for incoming calls to the remote object on an anonymous port. When you extend javax.rmi.PortableRemoteObject, your class will be exported automatically upon creation.

Because the object export could potentially throw a java.rmi.RemoteException, you must define a constructor that throws a RemoteException, even if the constructor does nothing else. If you forget the constructor, javac will produce the following error message:

        HelloImpl.java:3: unreported exception java.rmi.RemoteException; must be
        caught or declared to be thrown.

        public class HelloImpl extends PortableRemoteObject implements HelloInterface{
               ^
        1 error
To review: The implementation class for a remote object needs to:
  • Implement a remote interface
  • Export the object so that it can accept incoming remote method calls
  • Declare its constructor(s) to throw at least a java.rmi.RemoteException
Here is the constructor for the HelloImpl class:
  public HelloImpl() throws java.rmi.RemoteException {
    super();
  }
Note the following:
  • The super method call invokes the no-argument constructor of javax.rmi.PortableRemoteObject, which exports the remote object.
  • The constructor must throw java.rmi.RemoteException, because RMI's attempt to export a remote object during construction might fail if communication resources are not available.

Although the call to the superclass's no-argument constructor, super(), occurs by default (even if omitted), it is included in this example to make clear the fact that the superclass will be constructed before the class.

Provide an implementation for each remote method

The implementation class for a remote object contains the code that implements each of the remote methods specified in the remote interface. For example, here is the implementation for the sayHello() method, which returns the string "Hello from MARS!!" to the caller:
   public void sayHello( String from ) throws java.rmi.RemoteException {
       System.out.println( "Hello from " + from + "!!");
       System.out.flush();
   }
Arguments to, or return values from, remote methods can be any data type for the Java platform, including objects, as long as those objects implement the interface java.io.Serializable. Most of the core classes in java.lang and java.util implement the Serializable interface. In RMI:
  • By default, local objects are passed by copy, which means that all data members (or fields) of an object are copied, except those marked as static or transient. Please refer to the Java Object Serialization Specification for information on how to alter the default serialization behavior.
  • Remote objects are passed by reference. A reference to a remote object is actually a reference to a stub, which is a client-side proxy for the remote object. Stubs are described fully in the Java Remote Method Invocation Specification. We'll create them later in this tutorial in the section: Use rmic to generate stubs and skeletons.

Write The Server Class

A server class is the class which has a main method that creates an instance of the remote object implementation, and binds that instance to a name in the Naming Service. The class that contains this main method could be the implementation class itself, or another class entirely.

In this example, the main method is part of HelloServer.java, which does the following:

  • Creates an instance of the servant
  • Publishes the object reference

step icon Create the file HelloServer.java. The source code for this file follows. An explanation of each of the preceding steps follows the source code:

//HelloServer.java
import javax.naming.InitialContext;
import javax.naming.Context;

public class HelloServer {
    public static void main(String[] args) {
        try {
            // Step 1: Instantiate the Hello servant
            HelloImpl helloRef = new HelloImpl();

            // Step 2: Publish the reference in the Naming Service
            // using JNDI API
            Context initialNamingContext = new InitialContext();
            initialNamingContext.rebind("HelloService", helloRef );

            System.out.println("Hello Server: Ready...");

         } catch (Exception e) {
            System.out.println("Trouble: " + e);
            e.printStackTrace();
         }
     }
}

Create an instance of a remote object

The main method of the server needs to create an instance of the remote object implementation, or Servant. For example:
    HelloImpl helloRef = new HelloImpl();
The constructor exports the remote object, which means that once created, the remote object is ready to accept incoming calls.

Publish the object reference

For a caller (client, peer, or client application) to be able to invoke a method on a remote object, that caller must first obtain a reference to the remote object.

Once a remote object is registered on the server, callers can look up the object by name (using a naming service), obtain a remote object reference, and then remotely invoke methods on the object. In this example, we use the Naming Service that is part of the Object Request Broker Daemon (orbd).

For example, the following code binds the name "HelloService" to a reference for the remote object:

            // Step 2: Publish the reference in the Naming Service
            // using JNDI API
            Context initialNamingContext = new InitialContext();
            initialNamingContext.rebind("HelloService", helloRef );

Note the following about the arguments to the rebind method call:

  • The first argument, "HelloService", is a java.lang.String, representing the name of the remote object to bind
  • The second argument, helloRef is the object id of the remote object to bind

Write a client program that uses the remote service

The client application in this example remotely invokes the sayHello method in order to get the string "Hello from MARS!!" to display when the client application runs.

step icon Create the file HelloClient.java. Here is the source code for the client application:

//HelloClient.java
import java.rmi.RemoteException;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import javax.rmi.*;
import java.util.Vector;
import javax.naming.NamingException;
import javax.naming.InitialContext;
import javax.naming.Context;

public class HelloClient {

    public static void  main( String args[] ) {
        Context ic;
        Object objref;
        HelloInterface hi;

        try {
            ic = new InitialContext();

        // STEP 1: Get the Object reference from the Name Service
        // using JNDI call.
            objref = ic.lookup("HelloService");
            System.out.println("Client: Obtained a ref. to Hello server.");

        // STEP 2: Narrow the object reference to the concrete type and
        // invoke the method.
            hi = (HelloInterface) PortableRemoteObject.narrow(
                objref, HelloInterface.class);
            hi.sayHello( " MARS " );

        } catch( Exception e ) {
            System.err.println( "Exception " + e + "Caught" );
            e.printStackTrace( );
            return;
        }
    }
}

First, the client application gets a reference to the remote object implementation (advertised as "HelloService") from the Naming Service using Java Naming and Directory Interface [TM] (JNDI) calls. Like the Naming.rebind method, the Naming.lookup method takes java.lang.String value representing the name of the object to look up. You supply Naming.lookup() the name of the object you want to look up, and it returns the object bound to that name. Naming.lookup() returns the stub for the remote implementation of the Hello interface to its caller (HelloClient).

  • The client application invokes the remote sayHello() method on the server's remote object, causing the string "Hello from MARS!!" to be displayed on the command line.

Compile the Example

The source code for this example is now complete and the directory contains four files:
  • HelloInterface.java contains the source code for the remote interface
  • HelloImpl.java contains the source code for the remote object implementation
  • HelloServer.java contains the source code for the server
  • HelloClient.java contains the source code for the client application
In this section, you compile the remote object implementation file, HelloImpl.java, in order to create the .class files needed to run rmic. You then run the rmic compiler to create stubs and skeletons. A stub is a client-side proxy for a remote object which forwards RMI-IIOP calls to the server-side dispatcher, which in turn forwards the call to the actual remote object implementation. The last task is to compile the remaining .java source files to create .class files.

The following tasks will be completed in this section:

  1. Compile the remote object implementation
  2. Use rmic to generate stubs and skeletons
  3. Compile the source files

Compile the remote object implementation

To create stub and skeleton files, the rmic compiler must be run on the fully-qualified package names of compiled class files that contain remote object implementations. In this example, the file that contains the remote object implementations is HelloImpl.java. To generate the stubs and skeletons:

step icon Compile HelloImpl.java, as follows:

    javac -d . -classpath . HelloImpl.java

The "-d ." option indicates that the generated files should be placed in the directory from which you are running the compiler. The "-classpath ." option indicates that files on which HelloImpl.java is dependent can be found in this directory.

Use rmic to generate skeletons and stubs

To create CORBA-compatible stub and skeleton files, run the rmic compiler with the -iiop option. The rmic -iiop command takes one or more class names as an argument and produces class files of the form _HelloImpl_Tie.class and _HelloInterface_Stub.class. The remote implementation file, HelloImpl.class, is the class name to pass in this example.

For an explanation of rmic options, you can refer to the Solaris rmic manual page or the Windows rmic manual page.

step icon To create the stub and skeleton for the HelloImpl remote object implementation, run rmic like this:

    rmic -iiop HelloImpl

The preceding command creates the following files:

  • _HelloInterface_Stub.class - the client stub
  • _HelloImpl_Tie.class - the server skeleton

Compile the source files

step icon Compile the source files as follows:

    javac -d . -classpath . HelloInterface.java HelloServer.java HelloClient.java

This command creates the class files HelloInterface.class, HelloServer.class, and HelloClient.class. These are the remote interface, the server, and the client application respectively. For an explanation of javac options, you can refer to the Solaris javac manual page or the Windows javac manual page.

Run the Example

The following tasks will be completed in this section:
  1. Start the Naming Service
  2. Start the server
  3. Run the client application

Start the Naming Service

For this example, we will use the Object Request Broker Daemon, orbd, which includes both a Transient and a Persistent Naming Service, and is available with every download of J2SE 1.4 and higher.

For a caller (client, peer, or client application) to be able to invoke a method on a remote object, that caller must first obtain a reference to the remote object.

Once a remote object is registered on the server, callers can look up the object by name, obtain a remote object reference, and then remotely invoke methods on the object.

step icon Start the Naming Service by running orbd from the command line.

For this example, on the Solaris operating system:

    orbd -ORBInitialPort 1050&

or, on the Windows operating system:

    start orbd -ORBInitialPort 1050

You must specify a port on which to run orbd. For this example the port of 1050 is chosen because in the Solaris operating environment, a user must become root to start a process on a port under 1024. For more on the orbd tool, you can refer to the orbd manual page.

You must stop and restart the server any time you modify a remote interface or use modified/additional remote interfaces in a remote object implementation. Otherwise, the type of the object reference bound in the Naming Service will not match the modified class.

Start the server

Open another terminal window and change to the directory containing the source files for this example. The command for running the client has been spread out below to make it easier to read, but should be typed without returns between the lines. The following command shows how to start the HelloServer server. If you used a port other than 1050 or a host other than localhost when starting the orbd tool, replace those values in the command below with the actual values used to start orbd.

step icon Start the Hello server, as follows:

    java
      -classpath .
      -Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory
      -Djava.naming.provider.url=iiop://localhost:1050
      HelloServer

For an explanation of java options, you can refer to the Solaris java manual page or the Windows java manual page.

The output should look like this:

Hello Server: Ready ...

Run the client application

Once the Naming Service and server are running, the client application can be run. From a new terminal window, go to the source code directory, and run the client application from the command line, as shown below. The command for running the client has been spread out below to make it easier to read, but should be typed without returns between the lines. If you used a port other than 1050 or a host other than localhost when starting the orbd tool, replace those values in the command below with the actual values used to start orbd.

step icon Start the client application, as follows:

    java
      -classpath .
      -Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory
      -Djava.naming.provider.url=iiop://localhost:1050
      HelloClient
After running the client application, you will see output similar to the following on your display in the client window:
Client: Obtained a ref. to Hello server.

The following message will display in the server window:

Hello from  MARS

ORBD and the Hello server will continue to run until they are explicitly stopped. On Solaris, you can stop these processes using the pkill orbd and pkill HelloServer commands from a terminal window. On Windows, you can type Ctrl+C in a prompt window to kill the process.

This completes the basic RMI-IIOP tutorial. If you are ready to move on to more complicated applications, here are some sources that may help:

  • http://forum.java.sun.com/forum.jsp?forum=59, The Sun Developer's Forum for RMI-IIOP. You must register with the Java Developer Connection to access this site.
  • EJB clients interact with the J2EE EJB tier using the RMI-IIOP protocol. For more information on using RMI-IIOP in this way, see the Java 2 Platform, Enterprise Edition Blueprints or the EJB Tutorials.
  • Another RMI-IIOP tutorial includes support for the Portable Object Adapter (POA). POA support for RMI-IIOP is non-standard.
  • The Java IDL tutorial includes an example for running the client and server on different machines. The concepts of Running the Hello World Example on Two Machines apply to this example as well.
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Contents

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Java Management Extensions (JMX) Technology Tutorial

Java Management Extensions (JMX)
Java Platform, Standard Edition version 7

August, 2008
Contents | Previous | Next

Contents

Preface

1. Getting Started

Platform Information

Examples Directory

Working Directory

2. Essentials of the JMX API

Standard MBeans

MBean Interface

MBean Implementation

Managing a Resource

Running the Standard MBean Example

Sending Notifications

NotificationBroadcaster Interface

Running the MBean Notification Example

Introducing MXBeans

QueueSamplerMXBean Interface

QueueSampler Class

QueueSample Class

Creating and Registering the MXBean in the MBean Server

Running the MXBean Example

MBean Descriptors

DescriptorKey Annotations

Using MBean Descriptors

Running the MBean Descriptors Example

3. JMX Connectors

Accessing Standard and Dynamic MBeans via the RMI Connector

Analyzing the Example Classes

Server.java

SimpleStandardMBean.java

SimpleStandard.java

SimpleDynamic.java

ClientListener.java

Client.java

Running the MBean Example

4. Lookup Services

Initial Configuration

External RMI Registry

External CORBA Naming Service

External LDAP Registry

Service Location Protocol (SLP) Lookup Service

Analyzing the Example Classes

Server.java

Client.java

Running the SLP Lookup Service Example

Setting up the SLP Lookup Service Example

Running the SLP Lookup Service Example

Jini Lookup Service

Analyzing the Example Classes

Server.java

Client.java

java.policy

jini.properties.template

Running the Jini Lookup Service Example

Setting up the Jini Lookup Service Example

Running the Jini Lookup Service Example

Java Naming and Directory Interface (JNDI) / LDAP Lookup Service

Analyzing the Example Classes

Server.java

Client.java

jmx-schema.txt

60jmx-schema.ldif

Running the JNDI/LDAP Lookup Service Example

Setting up the JNDI/LDAP Lookup Service Example

Running the JNDI/LDAP Lookup Service Example With an RMI Connector

5. Security

Simple Security

RMI Connectors With Simple Security

Server.java

SimpleStandardMBean.java

SimpleStandard.java

ClientListener.java

Client.java

Running the RMI Connector Example With Simple Security

Subject Delegation

Secure RMI Connectors With Subject Delegation

Server.java

java.policy

SimpleStandardMBean.java

SimpleStandard.java

ClientListener.java

Client.java

Running the Secure RMI Connector Example With Subject Delegation

Fine-Grained Security

RMI Connectors With Fine-Grained Security

The files will be analyzed in the following sections.Server.java

java.policy

SimpleStandardMBean.java

SimpleStandard.java

ClientListener.java

Client.java

Running the RMI Connector Example With Fine-Grained Security

Contents | Previous | Next

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.Type (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.Type

  • Packages that use Type
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of Type in com.sun.jdi

      Subinterfaces of Type in com.sun.jdi
      Modifier and Type Interface and Description
      interface  ArrayType
      Provides access to the class of an array and the type of its components in the target VM.
      interface  BooleanType
      The type of all primitive boolean values accessed in the target VM.
      interface  ByteType
      The type of all primitive byte values accessed in the target VM.
      interface  CharType
      The type of all primitive char values accessed in the target VM.
      interface  ClassType
      A mirror of a class in the target VM.
      interface  DoubleType
      The type of all primitive double values accessed in the target VM.
      interface  FloatType
      The type of all primitive float values accessed in the target VM.
      interface  IntegerType
      The type of all primitive int values accessed in the target VM.
      interface  InterfaceType
      A mirror of an interface in the target VM.
      interface  LongType
      The type of all primitive long values accessed in the target VM.
      interface  PrimitiveType
      The type associated with non-object values in a target VM.
      interface  ReferenceType
      The type of an object in a target VM.
      interface  ShortType
      The type of all primitive short values accessed in the target VM.
      interface  VoidType
      The type of all primitive void values accessed in the target VM.
      Methods in com.sun.jdi that return Type
      Modifier and Type Method and Description
      Type ArrayType.componentType()
      Returns the component type of this array, as specified in the array declaration.
      Type Method.returnType()
      Returns the return type, as specified in the declaration of this method.
      Type LocalVariable.type()
      Returns the type of this variable.
      Type Field.type()
      Returns the type of this field.
      Type Value.type()
      Returns the run-time type of this value.
      Methods in com.sun.jdi that return types with arguments of type Type
      Modifier and Type Method and Description
      List<Type> Method.argumentTypes()
      Returns a list containing the type of each formal parameter of this method.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Type Inference for Generic Instance Creation

You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond operator.

For example, consider the following variable declaration:

Map<String, List<String>> myMap = new HashMap<String, List<String>>();

In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters (<>):

Map<String, List<String>> myMap = new HashMap<>();

Note that to take advantage of automatic type inference during generic class instantiation, you must specify the diamond operator. In the following example, the compiler generates an unchecked conversion warning because the HashMap() constructor refers to the HashMap raw type, not the Map<String, List<String>> type:

Map<String, List<String>> myMap = new HashMap(); // unchecked conversion warning

Java SE 7 supports limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context. For example, the following example does not compile:

List<String> list = new ArrayList<>();
list.add("A");

  // The following statement should fail since addAll expects
  // Collection<? extends String>

list.addAll(new ArrayList<>());

Note that the diamond operator often works in method calls; however, it is suggested that you use this operator primarily for variable declarations.

In comparison, the following example compiles:

// The following statements compile:

List<? extends String> list2 = new ArrayList<>();
list.addAll(list2);

Type Inference and Generic Constructors of Generic and Non-Generic Classes

Note that constructors can be generic (in other words, declare their own formal type parameters) in both generic and non-generic classes. Consider the following example:

class MyClass<X> {
  <T> MyClass(T t) {
    // ...
  }
}

Consider the following instantiation of the class MyClass, which is valid in Java SE 7 and prior releases:

new MyClass<Integer>("")

This statement creates an instance of the parameterized type MyClass<Integer>; the statement explicitly specifies the type Integer for the formal type parameter, X, of the generic class MyClass<X>. Note that the constructor for this generic class contains a formal type parameter, T. The compiler infers the type String for the formal type parameter, T, of the constructor of this generic class (because the actual parameter of this constructor is a String object).

Compilers from releases prior to Java SE 7 are able to infer the actual type parameters of generic constructors, similar to generic methods. However, the compiler in Java SE 7 can infer the actual type parameters of the generic class being instantiated if you use the diamond operator (<>). Consider the following examples, which are valid for Java SE 7 and later:

  • MyClass<Integer> myObject = new MyClass<>("");

    In this example, the compiler infers the type Integer for the formal type parameter, X, of the generic class MyClass<X>. It infers the type String for the formal type parameter, T, of the constructor of this generic class.

  • MyClass<Integer> myObject = new <String`> MyClass<>("");

    In this example, the compiler infers the type Integer for the formal type parameter, X, of the generic class MyClass<X>. The statement explicitly specifies the type String for the formal type parameter, T, of the constructor of this generic class.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.source.tree.TypeCastTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.TypeCastTree

  • Packages that use TypeCastTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of TypeCastTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type TypeCastTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitTypeCast(TypeCastTree node, P p)

    • Uses of TypeCastTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type TypeCastTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitTypeCast(TypeCastTree node, P p)
      R | SimpleTreeVisitor.visitTypeCast(TypeCastTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.TypeComponent (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.TypeComponent

  • Packages that use TypeComponent
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of TypeComponent in com.sun.jdi

      Subinterfaces of TypeComponent in com.sun.jdi
      Modifier and Type Interface and Description
      interface  Field
      A class or instance variable in the target VM.
      interface  Method
      A static or instance method in the target VM.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.declaration.TypeDeclaration (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.declaration.TypeDeclaration

  • Packages that use TypeDeclaration
    Package Description
    com.sun.mirror.apt
    Classes used to communicate information between annotation processors and an annotation processing tool.
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.
    com.sun.mirror.type
    Interfaces used to model types.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of TypeDeclaration in com.sun.mirror.apt

      Methods in com.sun.mirror.apt that return TypeDeclaration
      Modifier and Type Method and Description
      TypeDeclaration AnnotationProcessorEnvironment.getTypeDeclaration(String name)
      Deprecated.
      Returns the declaration of a type given its fully qualified name.
      Methods in com.sun.mirror.apt that return types with arguments of type TypeDeclaration
      Modifier and Type Method and Description
      Collection<TypeDeclaration> AnnotationProcessorEnvironment.getSpecifiedTypeDeclarations()
      Deprecated.
      Returns the declarations of the types specified when the annotation processing tool was invoked.
      Collection<TypeDeclaration> AnnotationProcessorEnvironment.getTypeDeclarations()
      Deprecated.
      A convenience method that returns the declarations of the types included in this invocation of the annotation processing tool.

    • Uses of TypeDeclaration in com.sun.mirror.declaration

      Subinterfaces of TypeDeclaration in com.sun.mirror.declaration
      Modifier and Type Interface and Description
      interface  AnnotationTypeDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in TypeElement.
      interface  ClassDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in TypeElement.
      interface  EnumDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in TypeElement.
      interface  InterfaceDeclaration
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in TypeElement.
      Methods in com.sun.mirror.declaration that return TypeDeclaration
      Modifier and Type Method and Description
      TypeDeclaration MemberDeclaration.getDeclaringType()
      Deprecated.
      Returns the type declaration within which this member or constructor is declared.
      Methods in com.sun.mirror.declaration that return types with arguments of type TypeDeclaration
      Modifier and Type Method and Description
      Collection<TypeDeclaration> TypeDeclaration.getNestedTypes()
      Deprecated.
      Returns the declarations of the nested classes and interfaces that are directly declared by this class or interface.

    • Uses of TypeDeclaration in com.sun.mirror.type

      Methods in com.sun.mirror.type that return TypeDeclaration
      Modifier and Type Method and Description
      TypeDeclaration DeclaredType.getDeclaration()
      Deprecated.
      Returns the declaration of this type.

    • Uses of TypeDeclaration in com.sun.mirror.util

      Methods in com.sun.mirror.util with parameters of type TypeDeclaration
      Modifier and Type Method and Description
      DeclaredType Types.getDeclaredType(DeclaredType containing, TypeDeclaration decl, TypeMirror... typeArgs)
      Deprecated.
      Returns the type corresponding to a type declaration and actual arguments, given a containing type of which it is a member.
      DeclaredType Types.getDeclaredType(TypeDeclaration decl, TypeMirror... typeArgs)
      Deprecated.
      Returns the type corresponding to a type declaration and actual type arguments.
      void SimpleDeclarationVisitor.visitTypeDeclaration(TypeDeclaration d)
      Deprecated.
      Visits a type declaration.
      void DeclarationVisitor.visitTypeDeclaration(TypeDeclaration d)
      Deprecated.
      Visits a type declaration.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.TypeInfo (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.TypeInfo

  • Packages that use TypeInfo
    Package Description
    org.w3c.dom
    Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.

    • Uses of TypeInfo in org.w3c.dom

      Methods in org.w3c.dom that return TypeInfo
      Modifier and Type Method and Description
      TypeInfo Element.getSchemaTypeInfo()
      The type information associated with this element.
      TypeInfo Attr.getSchemaTypeInfo()
      The type information associated with this attribute.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.type.TypeMirror (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.type.TypeMirror

  • Packages that use TypeMirror
    Package Description
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.
    com.sun.mirror.type
    Interfaces used to model types.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of TypeMirror in com.sun.mirror.declaration

      Methods in com.sun.mirror.declaration that return TypeMirror
      Modifier and Type Method and Description
      TypeMirror MethodDeclaration.getReturnType()
      Deprecated.
      Returns the formal return type of this method.
      TypeMirror ParameterDeclaration.getType()
      Deprecated.
      Returns the type of this parameter.
      TypeMirror FieldDeclaration.getType()
      Deprecated.
      Returns the type of this field.

    • Uses of TypeMirror in com.sun.mirror.type

      Subinterfaces of TypeMirror in com.sun.mirror.type
      Modifier and Type Interface and Description
      interface  AnnotationType
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in DeclaredType.
      interface  ArrayType
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is ArrayType.
      interface  ClassType
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in DeclaredType.
      interface  DeclaredType
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in DeclaredType.
      interface  EnumType
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in DeclaredType.
      interface  InterfaceType
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in DeclaredType.
      interface  PrimitiveType
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is PrimitiveType.
      interface  ReferenceType
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is ReferenceType.
      interface  TypeVariable
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is TypeVariable.
      interface  VoidType
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is included in NoType.
      interface  WildcardType
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this interface is WildcardType.
      Methods in com.sun.mirror.type that return TypeMirror
      Modifier and Type Method and Description
      TypeMirror ArrayType.getComponentType()
      Deprecated.
      Returns the component type of this array type.
      TypeMirror MirroredTypeException.getTypeMirror()
      Deprecated.
      Returns the type mirror corresponding to the type being accessed.
      Methods in com.sun.mirror.type that return types with arguments of type TypeMirror
      Modifier and Type Method and Description
      Collection<TypeMirror> DeclaredType.getActualTypeArguments()
      Deprecated.
      Returns (in order) the actual type arguments of this type.
      Collection<TypeMirror> MirroredTypesException.getTypeMirrors()
      Deprecated.
      Returns the type mirrors corresponding to the types being accessed.
      Constructors in com.sun.mirror.type with parameters of type TypeMirror
      Constructor and Description
      MirroredTypeException(TypeMirror type)
      Deprecated.
      Constructs a new MirroredTypeException for the specified type.
      Constructor parameters in com.sun.mirror.type with type arguments of type TypeMirror
      Constructor and Description
      MirroredTypesException(Collection<TypeMirror> types)
      Deprecated.
      Constructs a new MirroredTypesException for the specified types.

    • Uses of TypeMirror in com.sun.mirror.util

      Methods in com.sun.mirror.util that return TypeMirror
      Modifier and Type Method and Description
      TypeMirror Types.getErasure(TypeMirror t)
      Deprecated.
      Returns the erasure of a type.
      Methods in com.sun.mirror.util with parameters of type TypeMirror
      Modifier and Type Method and Description
      ArrayType Types.getArrayType(TypeMirror componentType)
      Deprecated.
      Returns an array type with the specified component type.
      DeclaredType Types.getDeclaredType(DeclaredType containing, TypeDeclaration decl, TypeMirror... typeArgs)
      Deprecated.
      Returns the type corresponding to a type declaration and actual arguments, given a containing type of which it is a member.
      DeclaredType Types.getDeclaredType(TypeDeclaration decl, TypeMirror... typeArgs)
      Deprecated.
      Returns the type corresponding to a type declaration and actual type arguments.
      TypeMirror Types.getErasure(TypeMirror t)
      Deprecated.
      Returns the erasure of a type.
      boolean Types.isAssignable(TypeMirror t1, TypeMirror t2)
      Deprecated.
      Tests whether one type is assignable to another.
      boolean Types.isSubtype(TypeMirror t1, TypeMirror t2)
      Deprecated.
      Tests whether one type is a subtype of the another.
      void TypeVisitor.visitTypeMirror(TypeMirror t)
      Deprecated.
      Visits a type mirror.
      void SimpleTypeVisitor.visitTypeMirror(TypeMirror t)
      Deprecated.
      Visits a type mirror.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.declaration.TypeParameterDeclaration (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.declaration.TypeParameterDeclaration

  • Packages that use TypeParameterDeclaration
    Package Description
    com.sun.mirror.declaration
    Interfaces used to model program element declarations.
    com.sun.mirror.type
    Interfaces used to model types.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of TypeParameterDeclaration in com.sun.mirror.declaration

      Methods in com.sun.mirror.declaration that return types with arguments of type TypeParameterDeclaration
      Modifier and Type Method and Description
      Collection<TypeParameterDeclaration> TypeDeclaration.getFormalTypeParameters()
      Deprecated.
      Returns the formal type parameters of this class or interface.
      Collection<TypeParameterDeclaration> ExecutableDeclaration.getFormalTypeParameters()
      Deprecated.
      Returns the formal type parameters of this method or constructor.

    • Uses of TypeParameterDeclaration in com.sun.mirror.type

      Methods in com.sun.mirror.type that return TypeParameterDeclaration
      Modifier and Type Method and Description
      TypeParameterDeclaration TypeVariable.getDeclaration()
      Deprecated.
      Returns the type parameter that declared this type variable.

    • Uses of TypeParameterDeclaration in com.sun.mirror.util

      Methods in com.sun.mirror.util with parameters of type TypeParameterDeclaration
      Modifier and Type Method and Description
      TypeVariable Types.getTypeVariable(TypeParameterDeclaration tparam)
      Deprecated.
      Returns the type variable declared by a type parameter.
      void SimpleDeclarationVisitor.visitTypeParameterDeclaration(TypeParameterDeclaration d)
      Deprecated.
      Visits a type parameter declaration.
      void DeclarationVisitor.visitTypeParameterDeclaration(TypeParameterDeclaration d)
      Deprecated.
      Visits a type parameter declaration.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.TypeParameterTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.TypeParameterTree

  • Packages that use TypeParameterTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of TypeParameterTree in com.sun.source.tree

      Methods in com.sun.source.tree that return types with arguments of type TypeParameterTree
      Modifier and Type | Method and Description
      List<? extends TypeParameterTree> | MethodTree.getTypeParameters()
      List<? extends TypeParameterTree> | ClassTree.getTypeParameters()
      Methods in com.sun.source.tree with parameters of type TypeParameterTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitTypeParameter(TypeParameterTree node, P p)

    • Uses of TypeParameterTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type TypeParameterTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitTypeParameter(TypeParameterTree node, P p)
      R | SimpleTreeVisitor.visitTypeParameter(TypeParameterTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.util.Types (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.util.Types

  • Packages that use Types
    Package Description
    com.sun.mirror.apt
    Classes used to communicate information between annotation processors and an annotation processing tool.

    • Uses of Types in com.sun.mirror.apt

      Methods in com.sun.mirror.apt that return Types
      Modifier and Type Method and Description
      Types AnnotationProcessorEnvironment.getTypeUtils()
      Deprecated.
      Returns an implementation of some utility methods for operating on types.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.type.TypeVariable (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.type.TypeVariable

  • Packages that use TypeVariable
    Package Description
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of TypeVariable in com.sun.mirror.util

      Methods in com.sun.mirror.util that return TypeVariable
      Modifier and Type Method and Description
      TypeVariable Types.getTypeVariable(TypeParameterDeclaration tparam)
      Deprecated.
      Returns the type variable declared by a type parameter.
      Methods in com.sun.mirror.util with parameters of type TypeVariable
      Modifier and Type Method and Description
      void TypeVisitor.visitTypeVariable(TypeVariable t)
      Deprecated.
      Visits a type variable.
      void SimpleTypeVisitor.visitTypeVariable(TypeVariable t)
      Deprecated.
      Visits a type variable.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.util.TypeVisitor (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.util.TypeVisitor

  • Packages that use TypeVisitor
    Package Description
    com.sun.mirror.type
    Interfaces used to model types.
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of TypeVisitor in com.sun.mirror.type

      Methods in com.sun.mirror.type with parameters of type TypeVisitor
      Modifier and Type Method and Description
      void TypeMirror.accept(TypeVisitor v)
      Deprecated.
      Applies a visitor to this type.

    • Uses of TypeVisitor in com.sun.mirror.util

      Classes in com.sun.mirror.util that implement TypeVisitor
      Modifier and Type Class and Description
      class  SimpleTypeVisitor
      Deprecated.
      All components of this API have been superseded by the standardized annotation processing API. The replacement for the functionality of this class is SimpleTypeVisitor6.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface org.w3c.dom.events.UIEvent (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.events.UIEvent

  • Packages that use UIEvent
    Package Description
    org.w3c.dom.events

    • Uses of UIEvent in org.w3c.dom.events

      Subinterfaces of UIEvent in org.w3c.dom.events
      Modifier and Type Interface and Description
      interface  MouseEvent
      The MouseEvent interface provides specific contextual information associated with Mouse events.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.UnaryTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.UnaryTree

  • Packages that use UnaryTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of UnaryTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type UnaryTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitUnary(UnaryTree node, P p)

    • Uses of UnaryTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type UnaryTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitUnary(UnaryTree node, P p)
      R | SimpleTreeVisitor.visitUnary(UnaryTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


UnavailableServiceException (JNLP API Reference 1.7.0)

  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method
javax.jnlp

Class UnavailableServiceException

  • java.lang.Object
    • java.lang.Throwable
      • java.lang.Exception
        • javax.jnlp.UnavailableServiceException
  • All Implemented Interfaces:
    java.io.Serializable

    public class UnavailableServiceException
extends java.lang.Exception
    The UnavailableServiceException is thrown by the ServiceManager when a non-existing or unavailable service is looked up.
    Since:
    1.0
    See Also:
    ServiceManager, Serialized Form

    • Constructor Summary

      Constructors
      Constructor and Description
      UnavailableServiceException()
      Constructs an UnavailableServiceException with null as its error detail message.
      UnavailableServiceException(java.lang.String msg)
      Constructs an UnavailableServiceException with the specified detail message.

    • Method Summary

      • Methods inherited from class java.lang.Throwable

        addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

    • Constructor Detail

      • UnavailableServiceException

        public UnavailableServiceException()
        Constructs an UnavailableServiceException with null as its error detail message.

      • UnavailableServiceException

        public UnavailableServiceException(java.lang.String msg)
        Constructs an UnavailableServiceException with the specified detail message. The error message string s can later be retrieved by the Throwable.getMessage() method of class java.lang.Throwable.
        Parameters:
        msg - the detail message.
  • Package
  • Class
  • Tree
  • Index
  • Prev Class
  • Next Class
  • Frames
  • No Frames
  • All Classes
  • Summary:
  • Nested |
  • Field |
  • Constr |
  • Method
  • Detail:
  • Field |
  • Constr |
  • Method

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.


Underscores in Numeric Literals

In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, for example, to separate groups of digits in numeric literals, which can improve the readability of your code.

For instance, if your code contains numbers with many digits, you can use an underscore character to separate digits in groups of three, similar to how you would use a punctuation mark like a comma, or a space, as a separator.

The following example shows other ways you can use the underscore in numeric literals:

long creditCardNumber = 1234_5678_9012_3456L;
long socialSecurityNumber = 999_99_9999L;
float pi = 	3.14_15F;
long hexBytes = 0xFF_EC_DE_5E;
long hexWords = 0xCAFE_BABE;
long maxLong = 0x7fff_ffff_ffff_ffffL;
byte nybbles = 0b0010_0101;
long bytes = 0b11010010_01101001_10010100_10010010;

You can place underscores only between digits; you cannot place underscores in the following places:

  • At the beginning or end of a number
  • Adjacent to a decimal point in a floating point literal
  • Prior to an F or L suffix
  • In positions where a string of digits is expected

The following examples demonstrate valid and invalid underscore placements (which are highlighted) in numeric literals:

float pi1 = 3_.1415F;      // Invalid; cannot put underscores adjacent to a decimal point
float pi2 = 3._1415F;      // Invalid; cannot put underscores adjacent to a decimal point
long socialSecurityNumber1
  = 999_99_9999_L;         // Invalid; cannot put underscores prior to an L suffix

int x1 = _52;              // This is an identifier, not a numeric literal
int x2 = 5_2;              // OK (decimal literal)
int x3 = 52_;              // Invalid; cannot put underscores at the end of a literal
int x4 = 5_______2;        // OK (decimal literal)

int x5 = 0_x52;            // Invalid; cannot put underscores in the 0x radix prefix
int x6 = 0x_52;            // Invalid; cannot put underscores at the beginning of a number
int x7 = 0x5_2;            // OK (hexadecimal literal)
int x8 = 0x52_;            // Invalid; cannot put underscores at the end of a number

int x9 = 0_52;             // OK (octal literal)
int x10 = 05_2;            // OK (octal literal)
int x11 = 052_;            // Invalid; cannot put underscores at the end of a number
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.security.auth.module.UnixLoginModule (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.module.UnixLoginModule

No usage of com.sun.security.auth.module.UnixLoginModule
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.auth.UnixNumericGroupPrincipal (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.UnixNumericGroupPrincipal

No usage of com.sun.security.auth.UnixNumericGroupPrincipal
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.auth.UnixNumericUserPrincipal (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.UnixNumericUserPrincipal

No usage of com.sun.security.auth.UnixNumericUserPrincipal
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.management.UnixOperatingSystemMXBean (Monitoring and Management Interface for the Java Platform b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Monitoring and Management Interface for the Java Platform
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.management.UnixOperatingSystemMXBean

No usage of com.sun.management.UnixOperatingSystemMXBean
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Monitoring and Management Interface for the Java Platform
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2003, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.auth.UnixPrincipal (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.UnixPrincipal

No usage of com.sun.security.auth.UnixPrincipal
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.auth.module.UnixSystem (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.module.UnixSystem

No usage of com.sun.security.auth.module.UnixSystem
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


unpack200 - JAR Unpacking tool

  • Synopsis
  • Description
  • Options
  • Exit Status
  • See Also
  • Notes

SYNOPSIS

unpack200 [ options ] input-file JAR-file

Options may be in any order. The last option on the command line supersedes all previously specified options.

input-file
Name of the input file, which can be a pack200 gzip file or a pack200 file. The input could also be JAR file produced by pack200(1) with an effort of 0. In this case the contents of the input file will be copied to the output JAR file with the Pack200 marker.
JAR-file
Name of the output JAR file.

DESCRIPTION

unpack200 is a native implementation that transforms a packed file produced by pack200(1) into a JAR file. Typical usage:

% unpack200 myarchive.pack.gz myarchive.jar

In this example, the myarchive.jar is produced from myarchive.pack.gz using the default unpack200 settings.

OPTIONS

-Hvalue --deflate-hint=value

Sets the deflation to be true, false, or keep on all entries within a JAR file. The default mode is keep. If true or false, overrides the default behavior and sets the deflation mode on all entries within the output JAR file.

-r --remove-pack-file

Removes the input packed file.

-v --verbose

Outputs minimal messages. Multiple specification of this option will output more verbose messages.

-q --quiet

Specifies quiet operation with no messages.

-lfilename --log-file=filename

Specifies a log file to output messages.

-? -h --help

Prints help information about this command.

-V --version

Prints version information about this command.

-Joption

Passes option to the Java launcher called by unpack200.

EXIT STATUS

The following exit values are returned:

 0 if successful completion;

>0 if an error occurred.

SEE ALSO

  • pack200 - JAR Packing Tool
  • Java SE Documentation
  • Java Deployment Guide - Pack200
  • jar - Java Archive Tool
  • jarsigner - JAR Signer tool
  • attributes(5) man page

NOTES

This command should not be confused with unpack(1). They are distinctly separate products.

The Java SE API Specification provided with the JDK is the superseding authority, in case of discrepancies.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface org.w3c.dom.UserDataHandler (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.UserDataHandler

  • Packages that use UserDataHandler
    Package Description
    org.w3c.dom
    Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing.

    • Uses of UserDataHandler in org.w3c.dom

      Methods in org.w3c.dom with parameters of type UserDataHandler
      Modifier and Type Method and Description
      Object Node.setUserData(String key, Object data, UserDataHandler handler)
      Associate an object to a key on this node.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.security.auth.UserPrincipal (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.UserPrincipal

No usage of com.sun.security.auth.UserPrincipal
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Using applet, object and embed Tags

This chapter includes the following topics:

  • Introduction
  • General Considerations
  • Using the applet tag
  • Using the object tag
  • Using the embed tag
  • Deploying Applets in a Mixed-Browser Environment

Introduction

This chapter explains to HTML authors how and when to use the applet, object, and embed tags to add Java applets to Web pages. In addition, this chapter provides guidelines for deploying applets on the Internet and Intranets, and for use with different browsers.

General Considerations

How you deploy an applet depends on whether users access the Web page through the Internet or an Intranet, and the type of browser they use. Note this information about your users, then follow the general guidelines below.

Deploying Applets on the Internet Versus an Intranet

When deploying applets:

  • Use the applet tag if the Web page is accessed through the Internet.

  • Use the object or embed tag if the Web page is accessed through an Intranet.

Deploying Applets for Specific Browsers

When deploying applets:

  • For Internet Explorer only, use the object tag.

  • For the Mozilla family of browsers only, use the embed tag.

If you must deploy an applet in a mixed-browser environment, follow the guidelines in the section Deploying Applets in a Mixed-Browser Environment.

Using the applet tag

You use the applet tag to deploy applets to a multi-browser environment.

For complete details on the applet tag, read the W3 HTML specification.

Note: The HTML specification states that the applet tag is deprecated, and that you should use the object tag instead. However, the specification is vague about how browsers should implement the object tag to support Java applets, and browser support is currently inconsistent. Sun therefore recommends that you continue to use the applet tag as a consistent way to deploy Java applets across browsers on all platforms.

Following is an example of the applet tag:

    <applet code=Applet1.class width="200" height="200">
    Your browser does not support the <code>applet</code> tag.
    </applet>

For both Internet Explorer and the Mozilla family of browsers, if Java Plug-in is installed (version 1.3.1_01a or later) then the highest installed version of Java Plug-in is invoked to run the applet.

Note

You cannot use the applet tag to automatically download a JRE if one is not installed locally.

Using the object tag

You use the object tag to deploy applets that are to be used only with Internet Explorer. For complete details on the object tag, read the W3 HTML specification. Following is an example of the object tag:

<OBJECT
  classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
  width="200" height="200">
  <PARAM name="code" value="Applet1.class">
</OBJECT>

The classid Attribute

The classid attribute identifies which minimum version of Java Plug-in to use.

The example shown below is the most commonly used form of the classid attribute. This example instructs Internet Explorer to use the highest installed version of Java Plug-in.

classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"

Following is an alternative form of the classid attribute:

classid="clsid:CAFEEFAC-xxxx-yyyy-zzzz-ABCDEFFEDCBA"

In this form, "xxxx", "yyyy", and "zzzz" are four-digit numbers that identify the minimum version of Java Plug-in to be used. For example, to use Java Plug-in version 1.6, you specify:

classid="clsid:CAFEEFAC-0016-0000-0000-ABCDEFFEDCBA"

The codebase Attribute

You use the optional codebase attribute to specify if and how to download the JRE.

The codebase attribute has two forms:

  • codebase=<URL>

    With this form, if the JRE specified by the classid attribute is not installed locally, then the user is prompted to download the JRE from the URL specified.
  • codebase=<URL>#Version=major,minor,micro,update

    With this form, if the version of the JRE specified in the codebase attribute is greater than the version of the JRE specified by the classid attribute, then the user is prompted to download the JRE from the URL specified.

Following is an example of how to use the codebase attribute to set up automatic downloads from the Sun Java Web site:

<object
  classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
  width="200" height="200"
  codebase="http://java.sun.com/products/plugin/autodl/
jinstall-1_5_0-windows-i586.cab#Version=1,5,0,0">
  <param name="code" value="Applet1.class">
</object>

Note: In this example the codebase=http://java.sun.com ... line is broken for readability. In the actual HTML file it would be one long line.

Sun has packaged each version of the JRE installer in Microsoft cabinet (.cab) file format. You can view a list of these releases and the corresponding .cab file names.

Using the embed tag

You use the embed tag to deploy applets that are to be used only with the Mozilla family of browsers.

Following is an example of the embed tag:

<embed code="Applet1.class"
  width="200" height="200"
  type="application/x-java-applet;version=1.6"
  pluginspage="http://java.sun.com/javase/downloads/ea.jsp"/>

The type attribute can have one of two forms:

  • type="application/x-java-applet;version=1.6"

    With this form, the highest installed JRE that supports the MIME type i.e. application/x-java-applet;version=1.6 is invoked to run the applet. If a JRE with a version number equal to or greater than the version number specified is installed locally, then that JRE is invoked. Otherwise the user is directed to the URL specified as the value of the pluginspage attribute.
  • type="application/x-java-applet;jpi-version=1.5.0_07

    With this form, a JRE with at least the specified update version given by the value of jpi-version (in this example, 1.5.0_07) is invoked to run the applet. Otherwise the user is directed to the URL specified as the value of the pluginspage attribute.

Deploying Applets in a Mixed-Browser Environment

You can deploy applets for users of both Internet Explorer and the Mozilla family of browsers in one of two ways:

  • Using pure HTML

  • Using JavaScript

Deploying Applets Using Pure HTML

When using a pure HTML approach to deploy applets in a mixed-browser environment, note the following:

  • Internet Explorer

    • Recognizes the object tag
    • Ignores the contents of the comment tag
  • Mozilla browsers
    • Ignore an object tag with the classid attribute
    • Interpret the contents of the comment tag

Consider the following example code from an HTML page:

<object
  classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
  <param name="code" value="Applet1.class">
    <comment>
      <embed code="Applet1.class"
        type="application/x-java-applet;version=1.6">
        <noembed>
          No Java Support.
        </noembed>
      </embed>
    </comment>
  </object>

Deploying Applets Using JavaScript

Instead of using the pure HTML approach described above, you can use JavaScript to deploy applets in a mixed-browser environment.

Through JavaScript, you:

  1. Detect the user's browser through the appName variable.

  2. Use the document.write() method to write a tag based on the value of the appName variable:

  1. If the browser name equals "Mozilla", write the embed tag.

  2. If the browser name equals "Microsoft Internet Explorer", write the object tag.

In the following example, the document.write() method outputs either an embed or object tag for each user “on the fly”:

<html>
<script language="Javascript">

  var _app = navigator.appName;

  if (_app == 'Mozilla') {
    document.write('<embed code="Applet1.class"',
                   'width="200"',
                   'height="200"',
                   'type="application/x-java-applet;version=1.5.0">');
    }
  else if (_app == 'Microsoft Internet Explorer') {
    document.write('<OBJECT ',
                   'classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"',
                   'width="200"',
                   'height="200">',
                   '<PARAM name="code" value="Applet1.class">',
                   '</OBJECT>');
    }
  else {
    document.write('<p>Sorry, unsupported browser.</p>');
    }

</script>
</html>
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.Value (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.Value

  • Packages that use Value
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.
    com.sun.jdi.event
    This package defines JDI events and event processing.

    • Uses of Value in com.sun.jdi

      Subinterfaces of Value in com.sun.jdi
      Modifier and Type Interface and Description
      interface  ArrayReference
      Provides access to an array object and its components in the target VM.
      interface  BooleanValue
      Provides access to a primitive boolean value in the target VM.
      interface  ByteValue
      Provides access to a primitive byte value in the target VM.
      interface  CharValue
      Provides access to a primitive char value in the target VM.
      interface  ClassLoaderReference
      A class loader object from the target VM.
      interface  ClassObjectReference
      An instance of java.lang.Class from the target VM.
      interface  DoubleValue
      Provides access to a primitive double value in the target VM.
      interface  FloatValue
      Provides access to a primitive float value in the target VM.
      interface  IntegerValue
      Provides access to a primitive int value in the target VM.
      interface  LongValue
      Provides access to a primitive long value in the target VM.
      interface  ObjectReference
      An object that currently exists in the target VM.
      interface  PrimitiveValue
      The value assigned to a field or variable of primitive type in a target VM.
      interface  ShortValue
      Provides access to a primitive short value in the target VM.
      interface  StringReference
      A string object from the target VM.
      interface  ThreadGroupReference
      A thread group object from the target VM.
      interface  ThreadReference
      A thread object from the target VM.
      interface  VoidValue
      Provides access to a primitive void value in the target VM.
      Methods in com.sun.jdi that return Value
      Modifier and Type Method and Description
      Value ReferenceType.getValue(Field field)
      Gets the Value of a given static Field in this type.
      Value ObjectReference.getValue(Field sig)
      Gets the value of a given instance or static field in this object.
      Value ArrayReference.getValue(int index)
      Returns an array component value.
      Value StackFrame.getValue(LocalVariable variable)
      Gets the Value of a LocalVariable in this frame.
      Value ClassType.invokeMethod(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Invokes the specified static Method in the target VM.
      Value ObjectReference.invokeMethod(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Invokes the specified Method on this object in the target VM.
      Methods in com.sun.jdi that return types with arguments of type Value
      Modifier and Type Method and Description
      List<Value> StackFrame.getArgumentValues()
      Returns the values of all arguments in this frame.
      List<Value> ArrayReference.getValues()
      Returns all of the components in this array.
      List<Value> ArrayReference.getValues(int index, int length)
      Returns a range of array components.
      Map<Field,Value> ReferenceType.getValues(List<? extends Field> fields)
      Returns a map containing the Value of each static Field in the given list.
      Map<Field,Value> ObjectReference.getValues(List<? extends Field> fields)
      Gets the value of multiple instance and/or static fields in this object.
      Map<LocalVariable,Value> StackFrame.getValues(List<? extends LocalVariable> variables)
      Returns the values of multiple local variables in this frame.
      Methods in com.sun.jdi with parameters of type Value
      Modifier and Type Method and Description
      void ThreadReference.forceEarlyReturn(Value value)
      Force a method to return before it reaches a return statement.
      void ClassType.setValue(Field field, Value value)
      Assigns a value to a static field.
      void ObjectReference.setValue(Field field, Value value)
      Sets the value of a given instance or static field in this object.
      void ArrayReference.setValue(int index, Value value)
      Replaces an array component with another value.
      void StackFrame.setValue(LocalVariable variable, Value value)
      Sets the Value of a LocalVariable in this frame.
      Method parameters in com.sun.jdi with type arguments of type Value
      Modifier and Type Method and Description
      Value ClassType.invokeMethod(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Invokes the specified static Method in the target VM.
      Value ObjectReference.invokeMethod(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Invokes the specified Method on this object in the target VM.
      ObjectReference ClassType.newInstance(ThreadReference thread, Method method, List<? extends Value> arguments, int options)
      Constructs a new instance of this type, using the given constructor Method in the target VM.
      void ArrayReference.setValues(int index, List<? extends Value> values, int srcIndex, int length)
      Replaces a range of array components with other values.
      void ArrayReference.setValues(List<? extends Value> values)
      Replaces all array components with other values.

    • Uses of Value in com.sun.jdi.event

      Methods in com.sun.jdi.event that return Value
      Modifier and Type Method and Description
      Value MethodExitEvent.returnValue()
      Returns the value that the method will return.
      Value WatchpointEvent.valueCurrent()
      Current value of the field.
      Value ModificationWatchpointEvent.valueToBe()
      Value that will be assigned to the field when the instruction completes.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Varargs

In past releases, a method that took an arbitrary number of values required you to create an array and put the values into the array prior to invoking the method. For example, here is how one used the MessageFormat class to format a message:
Object[] arguments = {
    new Integer(7),
    new Date(),
    "a disturbance in the Force"
};

String result = MessageFormat.format(
    "At {1,time} on {1,date}, there was {2} on planet "
     + "{0,number,integer}.", arguments);

It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process. Furthermore, it is upward compatible with preexisting APIs. So, for example, the MessageFormat.format method now has this declaration:

    public static String format(String pattern,
                                Object... arguments);

The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments. Varargs can be used only in the final argument position. Given the new varargs declaration for MessageFormat.format, the above invocation may be replaced by the following shorter and sweeter invocation:

String result = MessageFormat.format(
    "At {1,time} on {1,date}, there was {2} on planet "
    + "{0,number,integer}.",
    7, new Date(), "a disturbance in the Force");

There is a strong synergy between autoboxing and varargs, which is illustrated in the following program using reflection:

// Simple test framework
public class Test {
    public static void main(String[] args) {
        int passed = 0;
        int failed = 0;
        for (String className : args) {
            try {
                Class c = Class.forName(className);
                c.getMethod("test").invoke(c.newInstance());
                passed++;
            } catch (Exception ex) {
                System.out.printf("%s failed: %s%n", className, ex);
                failed++;
            }
        }
        System.out.printf("passed=%d; failed=%d%n", passed, failed);
    }
}

This little program is a complete, if minimal, test framework. It takes a list of class names on the command line. For each class name, it instantiates the class using its parameterless constructor and invokes a parameterless method called test. If the instantiation or invocation throws an exception, the test is deemed to have failed. The program prints each failure, followed by a summary of the test results. The reflective instantiation and invocation no longer require explicit array creation, because the getMethod and invoke methods accept a variable argument list. The program also uses the new printf facility, which relies on varargs. The program reads much more naturally than it would without varargs.

So when should you use varargs? As a client, you should take advantage of them whenever the API offers them. Important uses in core APIs include reflection, message formatting, and the new printf facility. As an API designer, you should use them sparingly, only when the benefit is truly compelling. Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.source.tree.VariableTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.VariableTree

  • Packages that use VariableTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of VariableTree in com.sun.source.tree

      Methods in com.sun.source.tree that return VariableTree
      Modifier and Type | Method and Description
      VariableTree | CatchTree.getParameter()
      VariableTree | EnhancedForLoopTree.getVariable()
      Methods in com.sun.source.tree that return types with arguments of type VariableTree
      Modifier and Type | Method and Description
      List<? extends VariableTree> | MethodTree.getParameters()
      Methods in com.sun.source.tree with parameters of type VariableTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitVariable(VariableTree node, P p)

    • Uses of VariableTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type VariableTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitVariable(VariableTree node, P p)
      R | SimpleTreeVisitor.visitVariable(VariableTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Multi-Version Support

This chapter includes the following topics:

  • Unique CLSID
  • Unique MIME Type and dll
  • Unique Java Plug-in Registry Key
  • Unique Java Plug-in Property File
  • Unique Java Plug-in Trace and Log Files
  • Unique Java Control Panel
  • Unique Registry Keys for JRE/JDK
  • Multi-version Support in Browser Sessions

Every new or patch release of Java Plug-in uniquely identifies registry keys, CLSID, MIME type and other resources.This allows multiple JRE versions to be deployed in the same environment.

Unique CLSID

There is a unique CLSID for every new or patch version of Java Plug-in. (CLSID is used in the OBJECT tag with Internet Explorer running on Windows.) If you want a minimum version of Java Plug-in to be used, then specify this unique CLSID in the OBJECT tag. The CLSID is stored in the registry in:

HKEY_CLASSES_ROOT\CLSID\

In general the CLSID looks as follows:

CAFEEFAC-<major version>-<minor version>-<patch version>-ABCDEFFEDCBA

where major version, minor version and patch version are all 4-digit hexadecimal numbers.

Examples:

For example, the CLSID for Java Plug-in 6 is as follows:

clsid:CAFEEFAC-0016-0000-0000-ABCDEFFEDCBA

and you would find this in the registry:

HKEY_CLASSES_ROOT\CLSID\CAFEEFAC-0016-0000-0000-ABCDEFFEDCBA

Note that CLSID is also stored in:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Code Store Database\Distribution Units\

Unique MIME Type and dll

There is a unique MIME type and NP*.dll for every new or patch version of Java Plug-in. MIME type identifies the type or version of the Java executable to be loaded and initialized by Java Plug-in. It is specified with the element type in the EMBED tag with supported Mozilla browsers and with <PARAM name="type"> in the OBJECT tag for Internet Explorer. If you want to use a minimum version of Java Plug-in with supported Mozilla browsers, specify the unique MIME type in the EMBED tag.

Note

MIME type will be supported by an NP*.dll with a unique name for every new or patch version. Thus, installing different version of Java Plug-in does not overwrite other .dll files in supported Mozilla browsers Plugins directory.

In general MIME types look like this:

application/x-java-applet;jpi-version=<version><version>

where version includes the major, minor and patch version numbers.

MIME types are supported in the file

NPJPI<modified version number>.dll

Example:

For Java Plug-in 1.6.0, the unique MIME type would be:

application/x-java-applet;jpi-version=1.6.0

and it would be supported in the file:

NPJPI160.dll

in supported Mozillas Plugins directory.

Unique Java Plug-in Registry Key

There is a unique Java Plug-in registry key for every new or patch version of Java Plug-in. The main Java Plug-in registry key is as follows:

HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Plug-in\<version number>

where the <version number> includes the major, minor and the patch version numbers.

Example:

For Java Plug-in 1.6.0 you will find the following in your registry:

HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Plug-in\1.6.0

Unique Java Plug-in Property File

The property file is now named deployment.properties. It is located in the following directory:

<User Application Data Folder>\Sun\Java\Deployment

where <User Application Data Folder> is an application data folder specific to the user.

As an example, for a user testuser on a Windows XP system, the value of <User Application Data Folder> would be C:\Documents and Settings\testuser\Application Data

The deployment.properties file is used by version 1.6.0. The value of <User Application Data Folder> is obtained from the Win32 API function call SHGetFolderPath() with CSIDL_APPDATA.

Unique Java Plug-in Trace and Log Files

The default location for trace and log files is <User Application Data Folder>\Sun\Java\Deployment\log

where <User Application Data Folder> is as defined above.

The property javaplugin.outputfiles.path can be used to override the default location for the trace and log files. For more information refer to the tracing and logging section in the Deployment Guide .

Unique Java Control Panel

There is a unique Java Control Panel for every new or patch release. In 1.6.0, the filename for the Control Panel is javacpl.exe.

Only the latest installed version of the Java Control Panel is available from the Windows Control Panel.

Unique Registry Keys for JRE/JDK

There are unique registry keys for every new or patch release of the JRE/JDK. These registry keys are located as follows:

HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment\<version number>
HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Development Kit\<version number>

where the <version number> includes the major, minor and the patch version numbers; e.g., 1.6.0

These keys allow Java Plug-in to locate the proper version of the JRE.

Multi Version Support in Browser Sessions

Mutliple JRE versions can be installed on Windows platform. With multiple JRE's applets using MIME type jpi-version will work with Mozilla browsers only if you enable the following options:

  • To enable the Mozilla Family option for JRE 6, open Java Control Panel and click Advanced > Default Java for browsers > Mozilla family
  • To enable the Mozilla and Netscape option for JRE 1.5.0 or earlier, open Java Control Panel and click Advanced > <Applet> tag support > Mozilla and Netscape

To invoke Java Control Panel for a specific version of the JRE browse to the <JRE_HOME>/bin directory of that version and run javacpl.exe.

Note

Multiple versions of the JRE can be run in different browser sessions. However, multiple versions cannot be run in the same browser session. Should this be attempted, the user is warned and the attempt will fail.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Versions Formats

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

Appendix 2: Specification-Version and Implementation-Version Formats

Specification-Version and Implementation-Version follow these rules for Sun products, and third-party products must follow the same rules for Java Plug-in to make reliable decisions about whether an extension is up-to-date or not:

The Specification-Version string will be of the form:

n1.n2[.n3]

where n1, n2, and n3 are integers, n1.n2 is the major version number, and optional n3 is the minor version number (also referred to as the maintenance version number).

The Implementation-Version will be of the same form initially but may:

  • append with a preceding underscore("_") n4n5 to indicate a patch version number (also referred to as the update version number)
  • or append with a hyphen ("-") a milestone name (ea , alpha, beta, rc ...), which may also include a trailing integer number (ea1, beta2, rc1 ...).

Both patch version number and milestone name may not be used together in the Implemenation-Version string.

The general form is as follows:

n1.n2[.n3][_<patch_number>|-<milestone_name>]

Integers (n1,n2, n3 ...), letters, dots, hyphens, and underscores , may be used in the version format as described above; no other characters ("*", "+" ...) are allowed.

Note that the Specification-Version and Implementation-Version numbers are in theory independent, though in practice they are often in sync with each other.

Examples:

Specification-Version examples: 1.3, 1.4

Implementation-Version examples: 1.3.1, 1.4.0_02, 1.4.0-beta3

While these are the rules, it is always a good idea when using a third-party extension JAR to examine its MANIFEST.MF file to see what actual values are in it. If it does not follow these rules, you may need to change your applet JAR MANIFEST.MF accordingly or alter the extension JAR.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Versions Formats

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

< Contents

Appendix 4: Specification-Version and Implemenation-Version Formats

Specification-Version and Implementation-Version follow these rules for Sun products, and third-party products must follow the same rules for Java Plug-in to make reliable decisions about whether an extension is up-to-date or not:

The Specification-Version string will be of the form:

n1.n2[.n3]

where n1, n2, and n3 are integers, n1.n2 is the major version number, and optional n3 is the minor version number (also referred to as the maintenance version number).

The Implementation-Version will be of the same form initially but may:

  • append with a preceding underscore("_") n4n5 to indicate a patch version number (also referred to as the update version number)
  • or append with a hyphen ("-") a milestone name (ea , alpha, beta, rc ...), which may also include a trailing integer number (ea1, beta2, rc1 ...).

Both patch version number and milestone name may not be used together in the Implemenation-Version string.

The general form is as follows:

n1.n2[.n3][_<patch_number>|-<milestone_name>]

Integers (n1,n2, n3 ...), letters, dots, hyphens, and underscores , may be used in the version format as described above; no other characters ("*", "+" ...) are allowed.

Note that the Specification-Version and Implementation-Version numbers are in theory independent, though in practice they are often in sync with each other.

Examples:

Specification-Version examples: 1.3, 1.4

Implementation-Version examples: 1.3.1, 1.4.0_02, 1.4.0-beta3

While these are the rules, it is always a good idea when using a third-party extension JAR to examine its MANIFEST.MF file to see what actual values are in it. If it does not follow these rules, you may need to change your applet JAR MANIFEST.MF accordingly or alter the extension JAR.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java™ Product Versioning Specification

Author: Roger.Riggs@East.Sun.COM

Date: 11/8/02

Evolution in open distributed systems must be managed carefully because correct operation depends on a great number of dependencies between packages. The impact of changes within a distributed system has a significant impact on users, support organizations, web administrators, and developers. Packages within a distributed system must operate correctly given only partial knowledge about the state of the whole system. The difficulty is increased because the packages of the system must be able to evolve at different rates. Evolution in such a system is made possible by explicitly managing the dependencies between the packages using techniques of object oriented design to govern how individual packages evolve. The Java language defines packages that are a natural for the consistent unit of update, they expose only public interfaces and consume only public interfaces of other classes.

Contents | Previous | Next
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java™ Product Versioning

Chapter 1

1.1 Introduction

In any system support must be provided for the system to evolve over time. Most existing systems have conventions and mechanisms that specify how change is accommodated. These systems have been based on the model where software programs are installed on a computer. Typically, developers have been able to specify what versions of other packages are required and the installation process has helped verify and configure the system.

In open distributed systems the static assumptions of existing systems does not work and evolution is more difficult because it is not possible to control how or when the packages change and correct operation depends on a greater number of dependencies between packages. What is needed is an updated set of conventions and mechanisms that specify how the packages of a system should evolve so that the goal of an open reliable scalable distributed system can be achieved.

This document specifies:

  • how classes, resources, and files that make up a Java package are versioned. Packages define the consistent unit that can be developed, packaged, verified, updated, and distributed. Per package manifest information identifies the contents of the package;
  • products are distributed by putting packages into archive files. Archives include a manifest to identify the product version and packages it contains;
  • the standards and conventions used by developers and administrators to build and deploy products that operate reliably as their packages and the packages they depend on are upgraded.

1.2 Requirements

The impact of changes within a distributed system has a significant impact on end users, support organizations, web administrators, and developers.

  • End Users
  • Product Support Organizations
  • Webmasters and Administrators
  • Product Developers

Each of these groups has different requirements on products deployed on the net that evolve over time.

Users

For users there is a need to build confidence that Java based products will be reliable and compatible over time. The reluctance to upgrade needs be addressed by building confidence in the Write Once Run Anywhere philosophy. With Java it should no longer be the norm that users will complain “if I upgrade it will break something” or “I won't be able to read/write data others can use”.

  • They need to know that upgrading will not break either other programs or will obsolete existing data or produce data unusable by others.
  • At the simplest level users want to know if the features they need are in the product version they have and what version to ask for to get particular features.
  • More knowledgeable users keep track of what bugs are in what product version so they can work around them or avoid them.

Product support

Product organizations rely on being able to easily and correctly identify the product that is being used, the environment in which it is being used, and the integrity of the product packaging.

  • Databases of known problems and solutions are indexed by product identification information.
  • The interoperation of products and packages can introduce new kinds of problems and require all of the packages in a system to be identified. Problems can originate from public interfaces that are under-specified, implementations that do not conform to the specification, or clients that use implementation specific details that are not part of the specification.

Webmasters and Administrators

Webmasters, administrators, and service providers need to deploy applications for their clients via the web or network filesystems in a way that is reliable and supportable.

  • The staff of these organizations must be able to support their sites, identifying problems with individual packages and interactions between packages.
  • Site configuration must be able to support the scaling up of sites with automated site management tools.
  • Installing updating packages must not present a risk to the correction operation of existing packages or active users.

Product Developers

Product developers need to know how to write and deploy applications and libraries that satisfy the requirements of the users, administrators and support personnel. The must be able to make products and packages that:

  • can operate correctly in the open dynamic environment of the web,
  • can be upgraded without breaking compatibility with clients,
  • can take advantage of upgrades in the packages they rely upon,
  • can take advantage of dynamic extensions of their packages,
  • can identify the packages they rely on for reporting of problems,
  • are packaged to support the needs of users, webmasters and support organizations,
  • can have known packages and combinations that satisfy the auditing and security requirements appropriate for the application and organization.

1.3 Problems of Evolution in Distributed Systems

In open distributed systems many problems can occur when the packages evolve and are updated independently. If the specified behavior inherent in the use of public interfaces are not maintained the system may fail in unexpected ways. Open systems are made up of many packages from different companies and organizations. These organizations operate asynchronously, introducing and upgrading their products on their own schedules. The distribution of those upgraded products takes time and adoption is not universal.

In Java, the components of local and distributed systems rely on the public interfaces and contracts for the behavior of other packages. Those packages will themselves evolve over time. In order for a package to operate correctly the packages it depends on must continue to provide the expected behavior even though they have been updated.

In distributed systems only partial consistency is possible, since it is impossible to have knowledge of the entire state of the system. Each process and package of the system has its own partial view of the current state of the system, accumulated incrementally by requesting information from other parts of the distributed system. Each piece of information whether from an applet that was started, a class that was loaded, a remote method invoked, or a web page retrieved must be treated carefully so that it can be used consistently with the rest of that partial view.

Many kinds of errors could result from inconsistencies in the classes that are loaded, including class verification errors, classes could compute incorrectly but without recognizable errors, or user requested functions could exhibit arbitrary failures.

Typical problems include:

  • If an applet is running and has loaded only some of its classes when the web server is updated with a new version. When the applet incrementally loads more classes they may be inconsistent with the classes already loaded.
  • If an application is using libraries from multiple websites and has loaded only some of the classes it needs, the libraries might be updated raising the potential of incompatibilities that the applet or user is left to detect.
  • If an application or applet is running and makes a RMI call that returns an object for which the class needs to be loaded. The class that is loaded could be inconsistent with respect to the other classes already loaded.
  • If an application or applet is running and makes a RMI call that returns an object that is for a newer or older version of the class.
  • Bugs may exist in a library, if the clients have worked around the bug a cascade of problems may be introduced when the bug is fixed.

These problems cannot be prevented or solved directly because they arise out of inconsistencies between dynamically loaded packages that are not under the control of a single system administrator and so cannot be addressed by current configuration management techniques.

1.4 Design for Evolution

The key to dealing with these problems and meeting the requirements stated above is the careful design of the packages and packaging of the system so that they may be updated, distributed, and loaded in consistent units. Typical to mass produced products is the notion of the field replacable unit. It is the smallest unit of a product that can be identified with a specification, a supplier, can be distributed and redistributed, and can be replaced if faulty. This same model is used for software distribution, products have a name, a version number, adhere to one or more specifications, are distributed on the network or cdrom and its problems can be reported to support organizations. These packages are the smallest unit that can be distributed, used, validated and replaced or upgraded when necessary. Packages can be assembled with other packages and each package can still be identified, verified, and distributed.

The Java language based package mechanism fits well with the idea of a replacable unit. Java packages expose only public interfaces and use only the public interfaces of other packages. The Java Language Specification define the approaches for compatible evolution of packages.

1.4.1 Java Language Specification on Backwards Compatibility

The Java Language Specification lays the groundwork for developing packages that can be expected to evolve gracefully over time. It defines how classes can change and still be backward compatible with other classes previously compiled and distributed. Essential to robust evolution is the stability of the public, protected, and package interfaces and behavior as the implementations evolve. It defines “compatible” changes as those changes that do not change existing interfaces or behavior. Thus, if a class defines a method, and the method had a particular behavior, that same contract must be supported by the all later evolutions of the class. Detailed rules are given in Chapter 13 of the Java Language Specification. One additional incompatible change has been added; it is incompatible to add methods to a public interface.

Incompatible changes are not permitted, but new or similar functionality can always be added in new or existing interfaces or classes.

By choosing the Java package as the unit of update the package and private methods of the classes may change allowing flexibility in the implementation of the package while the public and protected classes and methods maintain the external interfaces and semantics.

1.4.2 Object Serialization Specification on Backwards Compatibility

Robust persistent storage and robust communication between the components is important to distributed systems. Components must be able to maintain persistent storage as they evolve, being able to evolve classes and yet have them read data previously written to storage. Components in a distributed system evolve at different rates and must still be able to reliably communicate.

Adhering to the compatibility requirements of object serialization allows newer and older versions to communicate in a predictable and consistent way. The details are in Chapter 5 of the Java™ Object Serialization Specification.

1.5 Package Version Specification

There are several categories of artifacts that need to be identified including specifications, implementation, the Java Virtual Machine and Java Runtime Environment.

1.5.1 Specification Versioning

Open systems are based on the idea that a specification may have multiple implementations. Specifications evolve under the auspices of an organization or company. It is highly undesirable if a specification has multiple incompatible versions. Each version of a specification or implementation must evolve only into a single subsequent version. The philosophy of requiring specifications to be backward compatible allows specifications to be identified as supersets of the previous specification. Since there is a single sequence of version specifications they can meaningfully be identified by version numbers with specific semantics that imply the ordering. Specification version numbers use a Dewey decimal notation consisting of numbers seperated by periods.

A specification is identified by the:

  • Owner of the specification
  • Name of the Specification
  • Version number - major.minor.micro; major version numbers identify significant functional changes, minor version numbers identify smaller extensions to the functionality, micro versions are even finer grained versions. These version numbers are ordered with larger numbers specifying additions to the specification.

1.5.2 Virtual Machine Versioning

An implementation of the Java Virtual Machine should be identify both the specification and the implementation. These properties should be added to those already available using java.lang.System.getProperties.

  • java-vm.specification.version i.e. 1.2
  • java-vm.specification.vendor i.e. Sun Microsystems Inc.
  • java-vm.specification.name i.e. Java™ Virtual Machine Specification
  • java-vm.version i.e. Solaris 5.5 Native 1.0 build32
  • java-vm.vendor i.e. Sun Microsystems Inc.
  • java-vm.name i.e. Solaris 5.x JVM

These properties are accessed using the method java.lang.System.getProperty and each returns a string.

1.5.3 Version Identification of the Java Runtime

The requirement to identify the Java Runtime is already partially met via the properties specified by the Java Language Specification, section 20.18.7 using java.lang.System.getProperties.

  • java.version i.e. Solaris 1.2
  • java.vendor i.e. Sun Microsystems Inc.

Currently these identify the implementation of the Java runtime and the core classes that are available. These properties do not identify the Java Language Specification version that this JDK implements.

Additional properties are needed to identify the version of the Java Runtime Environment specification that this implementation adhere’s to. The properties are:

  • java.specification.version i.e. 1.1
  • java.specification.name i.e. Java™ Language Specification
  • java.specification.vendor i.e. Sun Microsystems Inc.

These properties are accessed using the method java.lang.System.getProperty and return their values as strings.

1.5.4 Package Versioning

Each Java package is made up of class files plus optional resource files. The information needed to identify the contents of the package is stored with the package contents.

This specification applies to all packages regardless of whether they are developed as a core package distributed with a Java Runtime, a standard extension, an applet or application package.

Unlike version numbers for specifications version information for implementations cannot be used to identify the package as being backward compatible with earlier versions. Package version numbers are present to identify differences between the specification and the implementation, i.e. bugs. New versions of implementations are specifically produced to remove (bad or incorrect) behavior and thus are intended not to be backward compatible. Thus package version strings can have any unique value and can only be compared for equality. For a complete explanation of the rationale, see Section 1.5.10 "Rationale for limiting Implementation version numbers to identity”.

The following attribute names are defined for a package. The value of each attribute is a string:

  • Package-Title Title of the package
  • Package-Version Version number
  • Package-Vendor Vendors company or organization
  • Specification-Title Title of the specification
  • Specification-Version Version number
  • Specification-Vendor Vendors company or organization

These attributes are stored in the manifest and retrieved by programs using the java.lang.Package API described below.

1.5.5 API to Package Version Information

The java.lang.Package class provides a object to locate and access information about the package.

Package objects are created explicitly by class loaders and should be created before the first class in the package is defined. The attributes of each package are stored in the manifest and are retrieved by the classloader.

package java.lang;
public class Package {

        // Return the name of this package.
        public String getName();

        // Return the title of the specification of this package.
        public String getSpecificationTitle();

        // Return the version of the specification of this package.
        public String getSpecificationVersion();

        // Return the vendor of the specification of this package.
        public String getSpecificationVendor();

        // Return the title of the implementation of this package.
        public String getImplementationTitle();

        // Return the version of the implementation of this package.
        public String getImplementationVersion();

        // Return the vendor of the implementation of this package.
        public String getImplementationVendor();

        // Is this package is compatible with the requested version
        public boolean isCompatibleWith(String desired);

        // Get the Package for the named class
        public static Package getPackage(String classname);

        // Return the packages for currently loaded classes.
        public static Package[] getAllPackages();

        // Return true if this package is equal to another object.
        public boolean equals(Object obj);

        // Return the hashcode for this object
        public int hashCode();

        // Return the string describing this package.
        public String toString();
}

The getName method returns this package’s name, for example, java.lang.

The getSpecificationTitle method return this packages specification title if it is known and null otherwise.

The getSpecificationVersion method return this the version number of the specification this package implements. Null is returned if the version is not known.

The getSpecificationVendor returns the organization, group or vendor that owns the specification.

The getImplementationTitle method return this packages implementation title if it is known and null otherwise.

The getImplementationVersion method return this the version number of the implementation this package implements. Null is returned if the version is not known.

The getImplementationVendor returns the organization, group or vendor that owns this implementation.

The isCompatibleWith method returns true if this package’s specification version number is compatible with the desired version number. True is returned if this packages specification version number is greater than the supplied version string. A version string is a series of positive numbers separated by periods. The numbers are compared component by component from left to right. If any number is greater than the corresponding number of the supplied string the method returns true. If the number is less than it returns false. If the corresponding numbers are equal the next number is examined.

The getPackage method locates the package for the class by name. The current class loader is consulted to map the package name to the package object in that class loader. It returns the package object containing the attributes for the package. Null is returned if the package information has not yet been loaded or if no package information was defined by the classloader.

The getAllPackages method will return an array of the packages known to the current classloader. It includes the packages of both the system and classloaded classes. It does not identify all packages available to be loaded by the classloader. It only identifies those packages for which the classloader has provided information.

The equals method returns true if this package has the same name and classloader as the object passed in.

The hashCode method returns a hashcode consistent with definition of equals as required by the Java Language Specification.

The toString method returns a string consisting of “package” and the package name. If available the specification title and specification version number are appended to the string.

1.5.6 java.lang.Class Additions

A method has been added to java.lang.Class to get the package for this class.

package java.lang;
public class Class {
        ...
        public Package getPackage();
        ...
}

1.5.7 java.lang.ClassLoader Additions

In order to support Packages the classloader is extended to keep track of the mapping from classes to packages and to allow classloaders to define the Package instances for the classes they load. The additional methods are defined to allow subclasses to define packages in this classloader to allow the Package implementation to get information about packages defined by this classloader.

The java.lang.Package implementation needs to identify the current classloader in order to call it from system code.

package java.lang;
public class ClassLoader {
        ...
        // Return the non-null classloader of callers
        public static ClassLoader currentClassLoader();
        // Define a Package
        protected Package(String pkgname,
                        String spectitle, String specversion,
                        String specvendor,      String impltitle,
                        String implversion, String implvendor);
        ...
}

The currentClassLoader method is used to find the current ClassLoader even if called from a system class. When called from a classloader loaded class it will return the equivalent of this.getClass().getClassLoader(). It’s behavior is identical to the current SecurityManager.currentClassLoader method but is public.

The protected access definePackage method is used by subclasses to define the packages of the classes it is loading. Packages with a given name may only be defined once and must be defined before the first class of that package is loaded. The classloader should supply the versioning attributes from the manifest if they are available.

1.5.8 JAR Manifest Format

The current manifest format is extended to allow the specification of the attributes for package versioning information. A manifest entry should be created for each Java package. The name of the entry will be the directory within the archive that contains the package’s class and resource files. For example:

Manifest-version: 1.0

Name: java/util/
Specification-Title: “Java Utility Classes”
Specification-Version: “1.2”
Specification-Vendor: “Sun Microsystems Inc.”.
Package-Title: “java.util”
Package-Version: “build57”
Package-Vendor: “Sun Microsystems. Inc.”

These attributes can be inserted in the manifest by creating a prototype manifest file and using the “-m” switch of the jar tool to merge them into the manifest when it is built. JarTool will be extended to browse and set the versioning attributes in the manifest.

1.5.9 How Users Know What is Running

Users need to be able to report the identities of the packages in use when bugs occur. It’s up to the application, applet or browser to expose the available information to the user on demand or when an error occurs. API’s are available to allow the following to be reported:

  • What are the packages loaded?
    The package.getAllPackages method will return the active packages.
  • What are the package versions?
    The java.lang.Package methods allow the attributes for names and versions to be examined as listed in Section 1.5.4 "Package Versioning”.
  • What version of the Java Runtime is active?
    The System.getProperties method can be used to get the properties of this virtual machine listed in Section 1.5.3 "Version Identification of the Java Runtime”.
  • What version of the Java VM is active?
    The System.getProperties method can be used to get the properties of this virtual machine listed in Section 1.5.2 "Virtual Machine Versioning”.

1.5.10 Rationale for limiting Implementation version numbers to identity

Implementations evolve independently over time to fix bugs, improve performance or add new functions called for by later revisions of the specifications. Packages implement specifications and must identify which version of each specification they implement. Interactions occur between packages only through their public and protected interfaces and classes. It is the public api and behavior that must remain stable over time so that changes can be allowed in the implementation of one package without affecting the behavior of another package.

If the classes of a package always faithfully implemented the specification it would be sufficient just to identify the specification. Since in the real world this rarely happens packages need to identify themselves so that bugs can be reported against the packages that may have contributed to the problem.

There is a significant tendency to try to attach some significance to version identifiers of implementations. If the purpose is to allow the tracking of bugs then a unique number is sufficient. It is also sufficient for a client package to workaround a bug in a particular version of a vendors package since that version can be tested for and the bug avoided.

However, many additional problems can occur when one package attempts to work around bugs in other packages. They need to identify behavior that is not part of the specification and may try to use behavior that is only part of one implementation. Such implementation specific behavior cannot be relied upon to be in any particular version other than the one(s) seen and tested by the developer.

A bug first appears in some version of a vendors package and may or may not continue to be a problem in subsequent versions. If the client of the buggy package uses a work around based on version numbers it could correctly work around the bug in the specific version. Now, if the buggy package was fixed, how would the client package know whether the bug was fixed or not. If it assumed that higher versions still contained the bug it would still try to work around the bug. The work around itself might not work correctly with the non-buggy package. This could cause a cascade of bugs caused by fixing a bug. Only the developer, through testing with a new version, can determine whether or not the workaround for a bug is still necessary or whether it will cause problems with the correctly behaving package. The developer only knows that the bug exists in a particular individual versions.

1.6 Documenting How to Develop

This section should discuss each aspect of product development and distributions giving direction on how to achieve a robust evolvable product.

  • Read the Java Language Specification, be backward compatible
  • Read Serialization Specification, be backward compatible
  • Develop on a platform that includes all of the functionality required.
  • Test for new functionality not included in each previous version of the platform specification and fall back or put up sensible messages
  • Author the package and product versioning information and create the necessary files
  • Depending on the archive model the entire contents will need to be signed and the manifests be created
  • Test on oldest platform
  • Distribute only in archives with manifests to insure consistency and integrity
  • Update only whole java packages or whole archive files

Contents | Previous | Next
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

JavaTM Product Versioning Specification
Contents | Previous | Next

Contents

Java™ Product Versioning Specification

Introduction

Requirements

Users

Product support

Webmasters and Administrators

Product Developers

Problems of Evolution in Distributed Systems

Design for Evolution

Java Language Specification on Backwards Compatibility

Object Serialization Specification on Backwards Compatibility

Package Version Specification

Specification Versioning

Virtual Machine Versioning

Version Identification of the Java Runtime

Package Versioning

API to Package Version Information

java.lang.Class Additions

java.lang.ClassLoader Additions

JAR Manifest Format

How Users Know What is Running

Rationale for limiting Implementation version numbers to identity

Documenting How to Develop

Contents | Previous | Next
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface org.w3c.dom.css.ViewCSS (Common DOM API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
org.w3c.dom.css.ViewCSS

No usage of org.w3c.dom.css.ViewCSS
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Common DOM API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Submit a bug or feature
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 2005, 2011, Oracle and/or its affiliates. 500 Oracle Parkway
Redwood Shores, CA 94065 USA. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.tools.attach.VirtualMachine (Attach API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Attach API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.tools.attach.VirtualMachine

  • Packages that use VirtualMachine
    Package Description
    com.sun.tools.attach
    Provides the API to attach to a JavaTM virtual machine.
    com.sun.tools.attach.spi
    Provider classes for the com.sun.tools.attach package.

    • Uses of VirtualMachine in com.sun.tools.attach

      Methods in com.sun.tools.attach that return VirtualMachine
      Modifier and Type Method and Description
      static VirtualMachine VirtualMachine.attach(String id)
      Attaches to a Java virtual machine.
      static VirtualMachine VirtualMachine.attach(VirtualMachineDescriptor vmd)
      Attaches to a Java virtual machine.

    • Uses of VirtualMachine in com.sun.tools.attach.spi

      Methods in com.sun.tools.attach.spi that return VirtualMachine
      Modifier and Type Method and Description
      abstract VirtualMachine AttachProvider.attachVirtualMachine(String id)
      Attaches to a Java virtual machine.
      VirtualMachine AttachProvider.attachVirtualMachine(VirtualMachineDescriptor vmd)
      Attaches to a Java virtual machine.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Attach API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.tools.attach.VirtualMachineDescriptor (Attach API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Attach API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.tools.attach.VirtualMachineDescriptor

  • Packages that use VirtualMachineDescriptor
    Package Description
    com.sun.tools.attach
    Provides the API to attach to a JavaTM virtual machine.
    com.sun.tools.attach.spi
    Provider classes for the com.sun.tools.attach package.

    • Uses of VirtualMachineDescriptor in com.sun.tools.attach

      Methods in com.sun.tools.attach that return types with arguments of type VirtualMachineDescriptor
      Modifier and Type Method and Description
      static List<VirtualMachineDescriptor> VirtualMachine.list()
      Return a list of Java virtual machines.
      Methods in com.sun.tools.attach with parameters of type VirtualMachineDescriptor
      Modifier and Type Method and Description
      static VirtualMachine VirtualMachine.attach(VirtualMachineDescriptor vmd)
      Attaches to a Java virtual machine.

    • Uses of VirtualMachineDescriptor in com.sun.tools.attach.spi

      Methods in com.sun.tools.attach.spi that return types with arguments of type VirtualMachineDescriptor
      Modifier and Type Method and Description
      abstract List<VirtualMachineDescriptor> AttachProvider.listVirtualMachines()
      Lists the Java virtual machines known to this provider.
      Methods in com.sun.tools.attach.spi with parameters of type VirtualMachineDescriptor
      Modifier and Type Method and Description
      VirtualMachine AttachProvider.attachVirtualMachine(VirtualMachineDescriptor vmd)
      Attaches to a Java virtual machine.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Attach API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.VirtualMachineManager (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.VirtualMachineManager

  • Packages that use VirtualMachineManager
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of VirtualMachineManager in com.sun.jdi

      Methods in com.sun.jdi that return VirtualMachineManager
      Modifier and Type Method and Description
      static VirtualMachineManager Bootstrap.virtualMachineManager()
      Returns the virtual machine manager.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.jdi.VMCannotBeModifiedException (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.VMCannotBeModifiedException

No usage of com.sun.jdi.VMCannotBeModifiedException
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.event.VMDeathEvent (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.event.VMDeathEvent

No usage of com.sun.jdi.event.VMDeathEvent
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.request.VMDeathRequest (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.request.VMDeathRequest

  • Packages that use VMDeathRequest
    Package Description
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of VMDeathRequest in com.sun.jdi.request

      Methods in com.sun.jdi.request that return VMDeathRequest
      Modifier and Type Method and Description
      VMDeathRequest EventRequestManager.createVMDeathRequest()
      Creates a new disabled VMDeathRequest.
      Methods in com.sun.jdi.request that return types with arguments of type VMDeathRequest
      Modifier and Type Method and Description
      List<VMDeathRequest> EventRequestManager.vmDeathRequests()
      Return an unmodifiable list of the enabled and disabled VM death requests.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.jdi.VMDisconnectedException (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.VMDisconnectedException

No usage of com.sun.jdi.VMDisconnectedException
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.event.VMDisconnectEvent (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.event.VMDisconnectEvent

No usage of com.sun.jdi.event.VMDisconnectEvent
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.jdi.VMMismatchException (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.VMMismatchException

No usage of com.sun.jdi.VMMismatchException
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.management.VMOption (Monitoring and Management Interface for the Java Platform b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Monitoring and Management Interface for the Java Platform
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.management.VMOption

    • Uses of VMOption in com.sun.management

      Methods in com.sun.management that return VMOption
      Modifier and Type Method and Description
      static VMOption VMOption.from(CompositeData cd)
      Returns a VMOption object represented by the given CompositeData.
      VMOption HotSpotDiagnosticMXBean.getVMOption(String name)
      Returns a VMOption object for a VM option of the given name.
      Methods in com.sun.management that return types with arguments of type VMOption
      Modifier and Type Method and Description
      List<VMOption> HotSpotDiagnosticMXBean.getDiagnosticOptions()
      Returns a list of VMOption objects for all diagnostic options.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Monitoring and Management Interface for the Java Platform
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2003, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.management.VMOption.Origin (Monitoring and Management Interface for the Java Platform b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Monitoring and Management Interface for the Java Platform
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.management.VMOption.Origin

    • Uses of VMOption.Origin in com.sun.management

      Methods in com.sun.management that return VMOption.Origin
      Modifier and Type Method and Description
      VMOption.Origin VMOption.getOrigin()
      Returns the origin of the value of this VM option.
      static VMOption.Origin VMOption.Origin.valueOf(String name)
      Returns the enum constant of this type with the specified name.
      static VMOption.Origin[] VMOption.Origin.values()
      Returns an array containing the constants of this enum type, in the order they are declared.
      Constructors in com.sun.management with parameters of type VMOption.Origin
      Constructor and Description
      VMOption(String name, String value, boolean writeable, VMOption.Origin origin)
      Constructs a VMOption.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Index
  • Help
Monitoring and Management Interface for the Java Platform
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2003, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.jdi.VMOutOfMemoryException (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.VMOutOfMemoryException

No usage of com.sun.jdi.VMOutOfMemoryException
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.event.VMStartEvent (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.event.VMStartEvent

No usage of com.sun.jdi.event.VMStartEvent
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Class com.sun.jdi.connect.VMStartException (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.jdi.connect.VMStartException

  • Packages that use VMStartException
    Package Description
    com.sun.jdi.connect
    This package defines connections between the virtual machine using the JDI and the target virtual machine.

    • Uses of VMStartException in com.sun.jdi.connect

      Methods in com.sun.jdi.connect that throw VMStartException
      Modifier and Type Method and Description
      VirtualMachine LaunchingConnector.launch(Map<String,? extends Connector.Argument> arguments)
      Launches an application and connects to its VM.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.type.VoidType (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.type.VoidType

  • Packages that use VoidType
    Package Description
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of VoidType in com.sun.mirror.util

      Methods in com.sun.mirror.util that return VoidType
      Modifier and Type Method and Description
      VoidType Types.getVoidType()
      Deprecated.
      Returns the pseudo-type representing the type of void.
      Methods in com.sun.mirror.util with parameters of type VoidType
      Modifier and Type Method and Description
      void TypeVisitor.visitVoidType(VoidType t)
      Deprecated.
      Visits a void type.
      void SimpleTypeVisitor.visitVoidType(VoidType t)
      Deprecated.
      Visits a void type.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.VoidValue (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.VoidValue

  • Packages that use VoidValue
    Package Description
    com.sun.jdi
    This is the core package of the Java Debug Interface (JDI), it defines mirrors for values, types, and the target VirtualMachine itself - as well bootstrapping facilities.

    • Uses of VoidValue in com.sun.jdi

      Methods in com.sun.jdi that return VoidValue
      Modifier and Type Method and Description
      VoidValue VirtualMachine.mirrorOfVoid()
      Creates a VoidValue.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Windows Look&Feel Bugs

4146858: Wrong DefaultButton behavior in Windows & Motif L&Fs
4166803: Focus set incorrectly on JInternalFrames
4172991: Microsoft Windows PLAF: Alt key for menus doesn't work
4183333: Please provide different WindowsLookAndFeel Border for JPopupMenu
4196518: Windows L&F JInternalFrame menus Disabled system menu items should get focus
4199085: JButtons are too tall and too narrow in Windows look and feel.
4199382: Swing Menus - text/icon/checkmark alignment schemes severely broken
4201986: Swing Tooltips not honoring desktop setting for tooltip font
4249732: JComboBox (Windows L&F) does not resemble native Windows combo
4252279: JFileChooser behavior under the windows look and feel on a "new folder"
4253171: white JTabbedPane on a white JPanel in windows L&F does not paint correctly
4264764: JButton has wrong margin in a JToolBar with Windows LAF
4268204: Windows Look&Feel doesn't look and feel like Windows
4268306: JToolBar uses wrong interior padding w/ Windows LF
4302970: WindowsDesktopManager does not look and feel like Windows
4337049: Background color on JComboBox also changes color of drop down button

Note: There may be additional Windows look&feel bugs not on this list because they have not yet been tagged with the "w2k" keyword.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Windows Desktop Property Support

This feature involves two areas:

  • Honor More User Preferences
    • Color Properties
    • Geometry Properties
    • Font Properties
    • Visual Effect Properties
    • Audio Feedback Properties
    • Input Properties
  • Respond to Dynamic Changes

Honor More User Preferences

On the Windows platform, users may customize their GUIs via the"Properties" option off the desktop's popup menu. In order to ensure the Swing Windows Look and Feel properly implements the user's visual and behavioral preferences, it must obtain the values of these UI properties from the system registry. The values for these properties will be retrievable from the getDesktopProperty() method on java.awt.Toolkit.

Most of the properties accessible via this method are specific to the Windows platform and hence have a "win." prefix. The list of supported Windows property names can be obtained programmaticallyby querying the "win.propNames" property:

     String propnames[] = (String[])Toolkit.getDefaultToolkit().getDesktopProperty("win.propNames");
     System.out.println("Supported windows property names:");
         for(int i = 0; i < propnames.length; i++) {
             System.out.println(propnames[i]);
         }

Properties which are supported on all platforms begin with an "awt." prefix.

Programs do not need to access these properties directly; the Windows look and feel will automatically read and interpret these properties to provide proper visuals and behavior for the components.

Color Properties

User Preference | Java Property Name | Type
3D Object Background | "win.3d.backgroundColor" | java.awt.Color
3D Object Highlight | "win.3d.highlightColor" | java.awt.Color
3D Object Light Highlight | "win.3d.lightColor" | java.awt.Color
3D Object Shadow | "win.3d.shadowColor" | java.awt.Color
Active Title Bar color1 | "win.frame.activeCaptionColor" | java.awt.Color
Active Title Bar color2 | "win.frame.activeCaptionGradientColor"(TBI) | java.awt.Color
Active Title Bar font color | "win.frame.captionTextColor" | java.awt.Color
Active Window Border color | "win.frame.activeBorderColor" | java.awt.Color
Application Background color | "win.mdi.backgroundColor" | java.lang.Color
Desktop color | "win.desktop.backgroundColor" | java.awt.Color
Inactive Title Bar color1 | "win.frame.inactiveCaptionColor" | java.awt.Color
Inactive Title Bar color2 | "win.frame.inactiveCaptionGradientColor"(TBI) | java.awt.Color
Inactive Title Bar font color | "win.frame.inactiveCaptionTextColor" | java.awt.Color
Inactive Window Border color | "win.frame.inactiveBorderColor" | java.awt.Color
Menu color | "win.menu.backgroundColor" | java.awt.Color
Menu font color | "win.menu.textColor" | java.awt.Color
Message Box font color | "win.frame.textColor?????" | java.awt.Color
Selected Items color | "win.item.highlightColor" | java.awt.Color
Selected Items font color | "win.item.highlightTextColor" | java.awt.Color
ToolTip color | "win.tooltip.backgroundColor" | java.awt.Color
ToolTip font color | "win.tooltip.textColor" | java.awt.Color
Window color | "win.frame.backgroundColor" | java.awt.Color
Window font color | "win.frame.textColor" | java.awt.Color
Hot tracking color | "win.item.hotTrackedColor" | java.awt.Color

Geometry Properties

User Preference | Java Property Name | Type
Active Title Bar size | "win.frame.captionHeight" | java.lang.Integer
Active Window Border size | "win.frame.sizingBorderWidth" | java.lang.Integer
Caption Buttons size | "win.frame.captionButtonHeight" "win.frame.captionButtonWidth" win.frame.captionHeight" | java.lang.Integer
Icon size | "win.icon.hspacing" "win.icon.vspacing"??? | java.lang.Integer
Icon horizontal spacing | "win.icon.hspacing" | java.lang.Integer
Icon vertical spacing | "win.icon.vspacing" | java.lang.Integer
Inactive Title Bar size | "win.frame.captionButtonHeight" "win.frame.captionButtonWidth" "win.frame.captionHeight" | java.lang.Integer
Inactive Window Border size | "win.frame.sizingBorderWidth" | java.lang.Integer
Menu font size | "win.menu.font" "win.menu.height" | java.lang.Integer
Menu Size | "win.menu.height" "win.menu.buttonWidth" | java.awt.Integer
Palette Title size | "win.frame.smallCaptionHeight" "win.frame.smallCaptionButtonHeight" "win.frame.smallCaptionButtonWidth" | java.lang.Integer
Scrollbar width | "win.scrollbar.width" | java.lang.Integer
Scrollbar height | "win.scrollbar.height" | java.lang.Integer
Selected Items size | "win.menu.height" "win.menu.buttonWidth" | java.lang.Integer

Font Properties

User Preference | Java Property Name | Type
Active Title Bar font | "win.frame.captionFont" | java.awt.Font
Icon font | "win.icon.font" | java.awt.Font
Inactive Title Bar font | "win.frame.captionFont" | java.awt.Font
Menu font | "win.menu.font" | java.awt.Font
Message Box font | "win.messagebox.font" | java.awt.Font
Palette Title font | "win.frame.smallCaptionFont" | java.awt.Font
Selected Items font | "win.menu.font" | java.awt.Font
ToolTip font | "win.tooltip.font" | java.awt.Font

Font Compatibility

Now Swing programs running in the Windows look and feel will render with the system font set by the user instead of a Java-defined font. Since this may cause compatibility problems for programs which depend on the old behavior (because of geometry issues, localization dependencies on particular font glyphs, etc.), a runtime property has been provided to allow this feature to be turned off as necessary:

     java -Dswing.useSystemFontSettings=false MyJavaProgram

Visual Effect Properties

User Preference | Java Property Name | Type
Icon title wrapping | "win.icon.titleWrappingOn" | java.lang.Boolean
Window Drag effects | "win.frame.fullWindowDragOn" | java.lang.Boolean
Keyboard Navigation Display | "win.menu.keyboardCuesOn"(TBI) | java.lang.Boolean
Hot tracking on toolbars/menubars | "win.item.hotTrackingOn" | java.lang.Boolean
Title Bar Gradients | "win.frame.captionGradientsOn" | java.lang.Boolean

Audio-feedback Properties

User Preference | Java Property Name | Type
Default sound | "win.sound.default" | java.lang.Runnable
Close sound | "win.sound.close" | java.lang.Runnable
Maximize sound | "win.sound.maximize" | java.lang.Runnable
Minimize sound | "win.sound.minimize" | java.lang.Runnable
Menu Command sound | "win.sound.menuCommand" | java.lang.Runnable
Menu Popup sound | "win.sound.menuPopup" | java.lang.Runnable
Open sound | "win.sound.open" | java.lang.Runnable
Restore Down sound | "win.sound.restoreDown" | java.lang.Runnable
Restore Up sound | "win.sound.restoreUp" | java.lang.Runnable
System Asterisk sound | "win.sound.asterisk" | java.lang.Runnable
System Exclamation sound | "win.sound.exclamation" | java.lang.Runnable
System Exit sound | "win.sound.exit" | java.lang.Runnable
System Hand sound | "win.sound.hand" | java.lang.Runnable
System Question sound | "win.sound.question" | java.lang.Runnable
System Start sound | "win.sound.start" | java.lang.Runnable

Dynamic Changes to Sounds

Note that the object returned for a sound property is simply a Runnable that plays the current audio clip for that property. This means that there is no need for watching for dynamic changes to sound properties because the sound's property value is a live link to the current sound setting.

Input Properties

User Preference | Java Property Name | Type
Double click interval | "awt.multiClickInterval" | java.lang.Integer
Cursor blink rate | "awt.cursorBlinkRate"(TBI) | java.lang.Integer

Respond to Dynamic Changes

In JDK 1.3, AWT added the ability to register for notification when one of these desktop property values changes. This is supported via the addPropertyChangeListener() method on java.awt.Toolkit. Swing's Windows Look and Feel will use this mechanism to watch for dynamic property change events on visual properties, and update the GUI by uninstalling and reinstalling the UI delegates in order for the components to have the most up-to-date visual property values. This dynamic behavior will automatically occur for all Swing programs running the Windows look and feel.

This mechanism will update GUI components by traversing the GUI hierarchy (starting with Frame.getFrames() and traversing all windows/containers/components from there). If a client has any undisplayable components when this occurs (see the isDisplayable() method on java.awt.Component for a definition of when a component is displayable), those components will not update automatically and it will be the client program's responsibility to update the UI on those components to ensure their Look and Feel is up-to-date. For example, this occurs in the SwingSet2 demo because demo panels are created but not added to the GUI heirarchy until they are selected from the demo's tabbedpane. Therefore, before the newly selected demo panel is added to the hierarchy, its UI is updated to ensure it has the most current property settings:

    fragment from SwingSet2.java:  // Ensure panel's UI is current before making visible
    JComponent currentDemoPanel = demo.getDemoPanel();
    SwingUtilities.updateComponentTreeUI(currentDemoPanel);
    // Replace current demo with newly selected demo
    demoPanel.removeAll();
    demoPanel.add(currentDemoPanel, BorderLayout.CENTER);
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.jdi.event.WatchpointEvent (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.event.WatchpointEvent

  • Packages that use WatchpointEvent
    Package Description
    com.sun.jdi.event
    This package defines JDI events and event processing.

    • Uses of WatchpointEvent in com.sun.jdi.event

      Subinterfaces of WatchpointEvent in com.sun.jdi.event
      Modifier and Type Interface and Description
      interface  AccessWatchpointEvent
      Notification of a field access in the target VM.
      interface  ModificationWatchpointEvent
      Notification of a field modification in the target VM.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.jdi.request.WatchpointRequest (Java Debug Interface b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.jdi.request.WatchpointRequest

  • Packages that use WatchpointRequest
    Package Description
    com.sun.jdi.request
    This package is used to request that a JDI event be sent under specified conditions.

    • Uses of WatchpointRequest in com.sun.jdi.request

      Subinterfaces of WatchpointRequest in com.sun.jdi.request
      Modifier and Type Interface and Description
      interface  AccessWatchpointRequest
      Request for notification when the contents of a field are accessed in the target VM.
      interface  ModificationWatchpointRequest
      Request for notification when a field is set.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Debug Interface
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1999, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


What's New in Javadoc 1.4.2

This document describes the changes made to the Javadoc tool between versions 1.4.1 and 1.4.2.

The changes listed below include the bug number and whether the fix was in the Javadoc tool front end ("tool") or standard doclet ("stddoclet"). The term "regression" appears for features that regressed at some point -- for features that worked in 1.3.x, broke in 1.4.0 or 1.4.1, and have been fixed in 1.4.2.

  • Notable New Features
  • Notable Bug Fixes
  • Notable Known Bugs
  • New Features and Bug Fixes
    • Command Line Options
    • Tags
    • Bad API Specifications
    • HTML & Javascript
    • Invalid HTML
    • Links
    • Running Javadoc
    • Error/Warning Messages
    • Accessibility
    • Doclet API

Notable New Features

  • All known bugs related to the U.S. Government's Section 508 requirements for accessibility have been fixed in this version. (4737558, stddoclet)
  • Include serialVersionUID in Serialized Form (4525039, stddoclet)
  • Can now inherit comments from source files not being documented. Your code can automatically inherit comments from interfaces and classes whose source files are on -sourcepath but are not being passed in on the command line. For example, for J2SE, You can do this by unzipping the src.zip file that ships with the SDK (which does not contain all source files, however), and add its path to -sourcepath. When javadoc runs on your code, it will load the doc comments from those source files as needed. For example, if a class in your code implements java.lang.Comparable, the compareTo(Object) method you implement will inherit the doc comment from java.lang.Comparable. This feature was actually available in 1.4.1. (No bug number, tool)
  • When using the -link (or -linkoffline) option, all @see and {@link} tags now create links to excluded classes. This fix greatly simplifies the ability to link to external classes and members. Previously, an external class needed to be either imported or fully qualified in a declaration in order for @see or {@link} to link to its documentation. Now, the only requirements are that the class be fully qualified and that its API docs appear on the path supplied by -link. (4652655, stddoclet)

    Other new features are listed below.

Notable Bug Fixes

  • Links: Fixed @link of a fully-qualified program element to link to external classes with the -link option. (4652655, tool, REGRESSION)
  • Links: Fixed missing internal links on return/parameter types when .java files are passd in (4628281, tool)
  • Execution: Fixed so duplicate classes are documented (4673477, tool, REGRESSION)
  • Serialized form: Fixed link anchors to classes in serialized form (4521661, stddoclet)
  • Javascript: Internet Explorer Javascript load error when linked by -linkoffline (4645058, stddoclet, REGRESSION)
  • HTML: Fixed so there is no diff when passing in package names or .java file names (4506980, stddoclet)

    Other bug fixes are listed below.

Notable Known Bugs

Bugs that can hang the Javadoc tool and highly noticeable bugs are listed here. You see a concise list of bugs listed at important new Javadoc bugs and regressions, and can view listings from our database at Important Bug Fixes and Changes.
  • Javadoc hangs without any useful message if {@inheritDoc} is used in a member that cannot inherit a comment. (4812240, stddoclet) For example:
    public class C {
    /** {@inheritDoc} */
    public abstract void m() {
    }
}
  • Internet Explorer displays unnecessary horizontal scroll bar in the main content pane when frames are showing. A simple workaround is described in the bug report. (4852280, stddoclet)

New Features and Bug Fixes

All new features and bug fixes in 1.4.2 follow.

Command Line Options

  • New feature: Added -packagesheader option for upper left frame (4766385, stddoclet)
  • New feature: Enable "-tag name" shortcut for "-tag name:a:name" (4695326, stddoclet)
  • New feature: Added -linksourcetab option to convert each tab to n spaces. This option is experimental and may change. (4510979, stddoclet)
  • New feature: The -tag option now allows dash (-) separator for xdoclet tags like @ejb:bean (4750173, stddoclet)
  • New feature: New -keywords option adds member names as meta keyword tags to improve API search (4764726, stddoclet)
  • New feature: Added -Xwerror flag to exit nonzero if there are warnings. (4099527, tool)
  • Bug fix: Fixed option -tag tagname:X:taghead so it no longer requires taghead (4628181, stddoclet)
  • Bug fix: Documented -quiet option to quiet only the standard doclet messages (4714350, stddoclet). Opened a new bug 4702454 to request that it quiet the javadoc tool messages as well.
  • Bug fix: Moved documentation for -source option from doclet options to javadoc tool options -- it has always been a tool option (4760924, stddoclet)
Tags
  • New feature: Javadoc now inherits @throws comments for runtime exceptions (4679573, stddoclet)
  • New feature: Javadoc now warns when first argument of @param is not parameter name (4693440, stddoclet)
  • Bug fix: Now compares fully qualified exception names when inheriting @throws text (4684827, stddoclet)
  • Bug fix: Fixed missing 'Throws' heading when followed only by auto-generated exceptions (4530727, stddoclet)
  • Bug fix: Fixed broken @inheritDoc when inheriting from abstract superclass's interface (4720974, stddoclet)
API Specifications
  • New feature: Now includes serialVersionUID in Serialized Form (4525039 stddoclet)
  • New feature: Can now inherit comments from source files not being documented. Your code can automatically inherit comments from interfaces and classes whose source files are on -sourcepath but are not being passed in on the command line. See example. (No bug number, tool)
  • Bug fix: Fixed missing inherited nested classes from summary table (4638588, stddoclet)
  • Bug fix: Fixed so javadoc no longer incorrectly lists hidden fields (4492178, stddoclet)
  • Bug fix: Added serializable superclass of non-public serializable class (4671694, stddoclet)
  • Bug fix: No longer documents override of private method, such as createBufferStrategy (4634891, stddoclet)
HTML & Javascript
  • New feature: Now includes javadoc version number and build in generated HTML comment (4749707, stddoclet)
  • Bug fix: Added "#anchor" names back to links that point to classes in serialized form page (4521661, stddoclet, REGRESSION)
  • Bug fix: Fixed Javascript IE load error when linked by -linkoffline (4645058, stddoclet, REGRESSION)
  • Bug fix: Fixed so there is no diff when passing in package names or .java file names (4506980, stddoclet)
  • Bug fix: Fixed invalid stylesheet.css file (font-size: normal) (4417174, stddoclet)
  • Bug fix: Fixed window title to not change when loading left frames (javascript, stddoclet) (4747738, stddoclet)
Invalid HTML
  • Bug fix: Added missing whitespace in DOCTYPE declaration (4625400, stddoclet)
  • Bug fix: Fixed invalid HTML in frameset DTD and extra <DL> (4275630, stddoclet)
  • Bug fix: Fixed <NOFRAMES>, which is not allowed outside <FRAMESET> element (4753048, stddoclet)
  • Bug fix: Fixed wrong !DOCTYPE in index-all.html file (4418115, stddoclet)
  • Bug fix: Fixed HTML table tags that were inserted in wrong place in package use page (4415270, stddoclet)
Links
  • Bug fix: Internal links missing from return/param types when .java files passd in (4628281, tool, REGRESSION)
  • Bug fix: Fixed @link of a fully-qualified program element to link to external classes with the -link option (4652655, tool, REGRESSION)
  • Bug fix: Fixed -link and -linkoffline to create proper relative links (4720957, stddoclet)
  • Bug fix: The -linksource option no longer produces '\' in links when run on Windows (4511110, stddoclet)
  • Bug fix: The label in {@link java.lang label} is no longer ignored when linking to a package name (4524136, stddoclet)
  • Bug fix: @link tag no longer malformed when only newline exists between first and second arguments (4739870, stddoclet)
Running Javadoc
  • Bug fix: No longer crashes when test file of unnamed package was included in source directory (4670772, tool)
  • Bug fix: Fixed so duplicate classes are once again documented (4673477, tool, REGRESSION)
  • Bug fix: Empty jarfile on classpath: Fixed so empty jarfile in classpath no longer throws an exception (4697113, stddoclet)
  • Bug fix: Files: When source and destination directories are the same, doc-files are no longer trashed (4258405, stddoclet)

Error/Warning Messages

  • Bug fix: Improve unhelpful error message "foo.jar: Body tag missing from HTML" (4691095, stddoclet)
  • Bug fix: Fixed so javadoc no longer reports errors when classpath jar files contain package.html files (4697040, stddoclet)
  • Bug fix: Fixed erroneous "Parameter foo is documented more than once." warnings. (4745855, stddoclet)
  • Bug fix: Now uses Messager printwriters inead of System.out and System.err (4644257, stddoclet)
Accessibility
  • Bug fix: Add title description to links describing italic style as "interface" (4714257, stddoclet)
  • Bug fix: Added ability to skip over nav bar for accessibility (4638136, stddoclet)
  • Bug fix: Added "summary" attribute to tables for accessibility (4637604, 4775148, stddoclet)
  • Bug fix: Added title attribute to <FRAME> tags for accessibility (4636655, stddoclet)
  • Bug fix: Put <H1>, <H2>, <H3> in proper sequence (4636667, stddoclet)
  • Bug fix: Add text equivalent of ASCII art in class tree for accessibility (4706779, stddoclet)
Doclet API
  • New feature: Extended Doclet API with holder() method in Tag interface (4706525, stddoclet)
  • Bug fix: Doc objects are once again == comparable (4731054, tool, REGRESSION)
  • Bug fix: Fixed bad ClassDoc for nested classes when built from .class files (4694497, tool)
  • Bug fix: Clarified the specification for Doc.position() (4748246, stddoclet)
  • Bug fix: Clarified the specification for RootDoc classes() method (4748234, stddoclet)
  • Bug fix: Clarified the specification for com.sun.javadoc.SeeTag (4754029, stddoclet)
  • Bug fix: Clarified the specification for PackageDoc.ordinaryClasses() needs clarification (4748244, stddoclet)
  • Bug fix: Clarified the specification for "kind" in com.sun.javadoc.Doc (4502589, stddoclet)
  • Bug fix: Clarified the specification for Doc.isClass() and all "class" references (4748245, stddoclet)
  • Bug fix: Clarified the specification for "class" further (4763596, stddoclet)
  • Bug fix: Clarified the specification for PackageDoc.allClasses() method and the term "included" (4748240, stddoclet)
  • Bug fix: Clarified the specification for ProgramElementDoc.qualifiedName() parameter list (4621267, stddoclet)
  • Bug fix: Clarified the specification for RootDoc.classes() and PackageDoc.allClasses() (4748238, stddoclet)
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


What's New in Javadoc 5.0

This document describes the changes made to the Javadoc tool between versions 1.4.2 and 5.0 (formerly 1.5.0).

The changes listed below include the bug number and whether the fix was in the Javadoc tool front end ("tool") or standard doclet ("stddoclet"). The term "regression" appears for features that regressed at some point -- usually for features that worked in 1.3.x, broke in 1.4.x, and have been fixed in 5.0.

  • Notable New Features
  • Notable Bug Fixes
  • Known Bugs
  • Incompatibilities with Custom Doclets
  • New Features and Bug Fixes
    • Command Line Options
    • Tags and Taglets
    • Links
    • Generated API Specifications
    • Formatting and Invalid HTML
    • Navigation Bar
    • Accessibility
    • Running Javadoc
    • Error/Warning/Status Messages
    • Doclet API

Notable New Features

  • Generics, enums, and varargs: Added support for these new language features in the javadoc tool front-end (Doclet API) (4421066, tool) and standard doclet (4789689, stddoclet, 1 vote)
  • Annotations: Added support for annotations and annotation types in the javadoc tool front-end (Doclet API) (4904495, tool) and standard doclet (4905985, stddoclet)
  • BreakIterator: We have removed the -breakiterator warning messages from 5.0, and have left the default sentence-break algorithm unchanged from earlier releases. That is, the -breakiterator option is not the default in 5.0, nor do we expect it to become the default. This is a reversal from our former intention that the default would change in the "next major release" (5.0). This means if you have not modified your source code to eliminate the breakiterator warnings in 1.4.x, then you don't have to do anything, and the warnings will go away in 5.0. The reason for this reversal is because any benefit to having -breakiterator become the default would be outweighed by the incompatible source change it would require. We regret any extra work and confusion this has caused. (The -breakiterator option was added in 1.4.0; for English locale only, it forces the use of BreakIterator class to determine where the first sentence in a doc comment ends, as BreakIterator already does for other languages.) (4959985, tool)
    Furthermore, in a future release (hopefully 5.1) we will add new javadoc tags (feature request 4921374) to enable you to mark summaries explicitly and avoid using heuristics of any kind.
  • New tags {@literal} and {@code} The {@literal} tag denotes literal text. The enclosed text is interpreted as not containing HTML markup or nested javadoc tags. For example, the doc comment text: {@literal a<B>c} displays in the generated HTML page unchanged: a<B>c -- that is, the <B> is not interpreted as bold.
    The {@code} tag formats literal text in the code font; {@code abc} is equivalent to <code>{@literal abc}</code>.
  • Tag {@value arg}: This inline tag now accepts the name of a program element: {@value package.class#field}. This enables it to be used in any doc comment, not just in the doc comment of the constant field. (4764045, stddoclet, 2 votes)
  • package-info.java: You can now create a source file with this name to store package comments and annotations. It can be used in place of package.html (which supports only comments, not annotations). If package-info.java is present, javadoc should ignore package.html and look instead for the package doc comment immediately preceding the (possibly annotated) package declaration. The javadoc tool handles the selection and parsing of package-info.java and package.html and passes the doc comments to the doclet. See Package Comment Files.
  • @Deprecated annotation: This is a new annotation in 5.0 that should be used in addition to the @deprecated tag for deprecating program elements. The Java Language Specification now requires compilers to issue warnings when the @Deprecated annotation (but not necessarily the tag) is used. The @deprecated tag provides a place to describe what replaces the deprecated program element. See @Deprecated annotation.
  • Standard doclet reimplementation - The standard doclet and MIF doclet were re-implemented to share as much code as possible. This has made it possible to reduce the number of bugs in both doclets and raise the capabilities of the MIF doclet to that of the standard doclet. (The new MIF doclet has not yet been released -- it will probably be named version 1.4 Beta 1.) The key reason we merged these two doclets is because they both try to generate essentially the same document but in different formats (HTML and PDF). (4638723, stddoclet, 2 votes)
    We plan to publish this shared code as a doclet toolkit, as described on the Javadoc home page.

    All new features are listed below.

Notable Bug Fixes

  • Option -tag: (regression) Fixed -tag so its name can once again contain a dash "-", as it allowed in 1.4.1. (4920381, stddoclet, 59 votes)
  • Hang due to {@inheritDoc}: No longer hangs when {@inheritDoc} (1) cannot inherit or (2) inherits from super-superinterface. (4812240, stddoclet, 18 votes)
  • Tag @param: (regression) Fixed @param so the parameter name (the first argument) is printed even if incorrect, as it worked in 1.3.1. (4802275, stddoclet, 1 vote)
  • Tag {@value}: Using {@value} in a custom tag no longer generates a NullPointerException. (4821796, stddoclet, 1 vote)
  • Browser scroll bar: Internet Explorer no longer displays an unnecessary horizontal scroll bar when frames are showing. (4852280, stddoclet, 5 votes)
  • Inheriting package-private docs: When -private option is used, now properly documents methods inherited from package-private classes only in the inherited method summary table and not in the detail section. (4780441, stddoclet, 5 votes)
  • First sentence ending with {@inheritDoc}: The end of a first sentence containing {@inheritDoc} is now determined correctly. (4767038, stddoclet, 4 votes)
  • First sentence broken link with {@docRoot}: A first sentence containing a {@docRoot} link is no longer broken in the single-page index. (4760191, stddoclet, 3 votes)
  • Inherited comment link: An inherited comment now links directly to the proper member, not just to the class. (4368820, stddoclet, 1 vote)
  • Alphabetic index sorting: Index sorting is again case-independent. Only in 1.4.1 and 1.4.2 it was sorted uppercase then lowercase. (4984419, stddoclet, no votes)

    All bug fixes are listed below.

Known Bugs

Javadoc 5.0 has no known bugs that cause it to hang or crash. You can view listings from our Bug Database. The notable bugs are:
  • Six-fold performance degradation since 1.4.2 for deeply inherited classes. The slowdown is partly due to the extra processing required by generic type parameters.
    Workaround: None. (5081166)
  • @param in base class is ignored if {@inheritDoc} in main description.
    Workaround: None. (4778311)
  • Produces faulty Constant Values page if a constant contain angle bracket '<'
    Workaround: None. (5077317)
  • Malformed HTML tag throws error due to message not found in resource file.
    Error message: java.util.MissingResourceException: Can't find resource for bundle com.sun.tools.doclets.formats.html.resources.standard, key doclet.malformed_html_link_tag
    Workaround: Reduce the number of packages and classes passed into javadoc until the error goes away and you locate the source file that contains the malformed tag. Then fix the malformed tag. A malformed HTML tag is one that begins properly but is otherwise improper. For example <action> is interpreted as a malformed <a> tag. (5082928)

Incompatibilities with Custom Doclets

Custom doclets written prior to 5.0 will have compatibility problems when run on source files that use new language features in 5.0.
  • New Language Features: The Doclet API and standard doclet were revised to handle the new 5.0 language features -- generics, enums, varargs and annotations. To handle these features, custom doclets would also need to be revised.

    The Javadoc tool tries -- to the extent possible -- to present so-called "legacy" doclets with a view of the program that 1) continues to work with pre-5.0 source code, and 2) matches their expectations for 5.0 source code. So, for example, type parameters and type arguments are stripped from generic constructs, type variables and wildcard types are replaced by their erasures, and ClassDoc.fields() will return enum constants.

    But legacy support is not specified with precision. It's a compatibility mode that will suffice until the doclet gets updated to understand the language it is operating on. The only guarantee is source and binary compatibility of doclets themselves: when using the 5.0 Javadoc tool, if your doclet is based on 1.4 and the source code on which you're operating is also based on 1.4, then you can still compile the doclet and it will still operate as before (modulo bug fixes).

New Features and Bug Fixes

The following is a list of essentially all new features and bug fixes in 5.0. Only very minor changes are omitted (such as fixing broken links in the documentation for the Doclet API) and bugs introduced in early-access releases of 5.0 but fixed in the final release are omitted.

Command Line Options

  • New feature: New -keywords option adds HTML meta tags to each generated file to help with search (4776637, stddoclet)
  • New feature: New -notimestamp option suppresses hidden timestamp embedded near the top of HTML pages (4777717
  • New feature: It is now possible to create test subpackages that contain hyphens that the -subpackages option will skip over without producing warnings. That is, this option will no longer warn if it encounters a directory with an illegal Java name (which is consistent with illegal source filenames). (4773013, tool)
  • Bug fix: The -help option no longer mistakenly shows "[classnames]" in the usage. (4775743, tool)
  • Bug fix: The -group option no longer causes a duplicate warning. (4924383, stddoclet)
Tags and Taglets
  • New feature: The {@literal} tag denotes literal text. The enclosed text is interpreted as not containing HTML markup or nested javadoc tags. For example, the doc comment text: {@literal a<B>c} displays in the generated HTML page unchanged: a<B>c -- that is, the <B> is not interpreted as bold.
  • New feature: The {@code} tag formats literal text in the code font. It is equivalent to <code>{@literal}</code>.
  • New feature: The {@value} inline tag now accepts the name of a program element and label: {@value package.class#member label}. This enables it to be used in any doc comment. (4764045, stddoclet)
  • New feature: Not a Javadoc tag, the @Deprecated annotation is new in 5.0 and should be used in addition to the @deprecated tag for deprecating program elements. See @Deprecated annotation.
  • Bug fix: (regresion): Fixed @param so the parameter name (its first argument) is printed even if incorrect, as it worked in 1.3.1. (4802275, stddoclet)
  • Bug fix: (regression) Fixed -tag so its name can once again contain a dash "-", as was allowed in 1.4.1. (4920381, stddoclet)
  • Bug fix: A first sentence containing a {@docRoot} link is no longer broken in the single-page index. (4760191, stddoclet)
  • Bug fix: The end of a first sentence containing {@inheritDoc} is now determined correctly. (4767038, stddoclet, 4 votes)
  • Bug fix: Use of the {@docroot} tag in -bottom text no longer causes a broken link on the help-doc.html page. (4851991, stddoclet)
  • Bug fix: Modified taglet code to allow standalone tags to handle inline tags. (4654308, stddoclet)
  • Bug fix: Use of {@value} in a custom tag no longer generates a NullPointerException. (4821796, stddoclet)
  • Bug fix: Inline tags now allow nested braces that do not belong to inline tags. (4965490, tool)
  • Bug fix: @param, @return and some @throws tags now inherit comments properly. (4915434, stddoclet)
  • Bug fix: @throws documentation is now auto-inherited if the exception is checked. (4947455, stddoclet)
Links
  • Bug fix: An inherited comment now links directly to the proper member, not just to the class. (4368820, stddoclet)
  • Bug fix: The summary heading is no longer missing when a class has no direct members but inherits members. (4904036, stddoclet)
  • Bug fix: Relative link in <a href> in first sentence no longer generates a broken link when it appears on other pages. (4460354, stddoclet)

    For more link bug fixes, see "Tags and Taglets", associated with the {@docRoot} tag.

Documented Source files
  • New feature: package-info.java is a reserved name for a source file to store package comments and annotations. package-info.java is described above.
Generated API Specifications
  • New feature: Added support for generics, enums, and varargs in the javadoc tool front-end (Doclet API) (4421066, tool) and standard doclet (4789689, stddoclet)
  • New feature: Added support for annotations and annotation types in the javadoc tool front-end (Doclet API) (4904495, tool) and standard doclet (4905985, stddoclet)
  • New feature: For legibility, constant field values of type long are now printed with "L" rather than lowercase "l". (4869993, tool)
  • New feature: For legibility, serialVersionUID values of type long are now printed with "L" rather than lowercase "l". (4821483, stddoclet)
  • New feature: Table of contents has been added to the top of the "Deprecated" list. (4927552, stddoclet)
  • Bug fix: No longer hangs when {@inheritDoc} (1) cannot inherit or (2) inherits from super-superinterface. (4812240, stddoclet)
  • Bug fix: Inherited non-public superclass is no longer mentioned (4874845, stddoclet)
  • Bug fix: "Specified by:" and "Overrides:" comments are now inherited from externally referenced classes. (4857717, stddoclet)
  • Bug fix: Documentation is no longer inherited from members of package-private classes. (4780441, stddoclet)
  • Bug fix: Order of method descriptions can no longer change from one run to the next. (4885372, stddoclet)
  • Bug fix: When class B extends class A which implements interface I, in the documentation for I, we now document that B implements I (under "All implementing classes"). (4947464, stddoclet)
  • Bug fix: Correct return type now shows up in member summary when a method inherits documentation from an overridden method that returns a different type. (4951228, stddoclet)
  • Bug fix: Now generates doc for readObjectNoData() in serialized form page. (4770063, stddoclet)
  • Bug fix: Now generates a package summary page for the unnamed package, if present. (4774450, stddoclet)
  • Bug fix: Now prints "Unnamed" as the name of the unnamed package, rather than printing empty string. (4904075, stddoclet)
  • Bug fix: All inherited methods from multiple extended interfaces are now documented. (4933335, stddoclet)
  • Bug fix: Interface methods are no longer marked "public" (just a change -- not actually a bug). (4682448, stddoclet)
  • Bug fix: Constructor comments are now indented properly. (4904037, stddoclet)
  • Bug fix: packages.html (note the plural) file is no longer included, as it has not been used or needed since 1.1. (4475679, stddoclet)
  • Bug fix: When a type parameter in the member summary is greater than 10 characters, now add a line break to shorten it (4927167, stddoclet)
Formatting and Invalid HTML
  • Bug fix: Now outputs <NOSCRIPT> tag with each <SCRIPT> tag. (4855054, stddoclet)
  • Bug fix: Internet Explorer no longer displays an unnecessary horizontal scroll bar when frames are showing. (4852280, stddoclet)
  • Bug fix: Newlines are no longer hard-coded as "\n". (4938109, stddoclet)
  • Bug fix: Table border added around class headings in constant value summary. (4904025, stddoclet)
  • Bug fix: Now prints certain HTML source comments conditionally (4904038, stddoclet)
Navigation Bar
  • Bug fix: An extra column no longer appears in the first row of the navbar. (4664607, stddoclet, 1 vote)
  • Bug fix: Package link is now active when documenting only one package. (4689286, stddoclet)
  • Bug fix: Next/Prev Class links now iterate through all interfaces and classes in current package. (4131628, stddoclet)

Accessibility

  • Bug fix: Table headings now use
    . (4905786, stddoclet)
    • Bug fix: Missing space added at end of alternate text for inherit.gif. (4956908, stddoclet)
    Running Javadoc
    • Bug fix: No longer get InvocationTargetException when a source flie links to another source file in the wrong directory. (4835749, stddoclet)
    • Bug fix: (regression) No longer fails on internal classes, as it worked in 1.4.1. (4843578, tool)

    Error/Warning/Notice Messages

    • New feature: Now warns when @return tag is present in void method. (4490068, stddoclet)
    • New feature: Now displays message when creating new destination directory (4657239, stddoclet)
    • Bug fix: BreakIterator warnings no longer appear. For more information, see above. (4959985, tool)
    • Bug fix: The "first sentence" warning is no longer split between stderr and stdout. (4753853, tool)
    • Bug fix: DocLocale.java implementation has been modified to allow for proper translation. (4780921, tool)
    • Bug fix: Now uses DocletErrorReporter to print option errors, rather than MessageRetriever. (4927928, stddoclet)
    • Bug fix: Message no longer says "error" when it's really a warning for a missing package-list file. (4625883, stddoclet)
    Doclet API
    • New feature: Added support for generics, enums, and varargs in the javadoc tool front-end (Doclet API) (4421066, tool) and standard doclet (4789689, stddoclet)
    • New feature: Added support for annotations and annotation types in the javadoc tool front-end (Doclet API) (4904495, tool) and standard doclet (4905985, stddoclet)
    • New feature: Add Doclet.languageVersion method to determine which version of Java source code the doclet was written for. (4909767, tool)

    Standard Doclet Implementation

    • Bug fix: Re-implemented standard doclet to maximize shared code for doclets emulating the stddoclet (4638723, stddoclet)
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Interface com.sun.source.tree.WhileLoopTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.WhileLoopTree

  • Packages that use WhileLoopTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of WhileLoopTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type WhileLoopTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitWhileLoop(WhileLoopTree node, P p)

    • Uses of WhileLoopTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type WhileLoopTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitWhileLoop(WhileLoopTree node, P p)
      R | SimpleTreeVisitor.visitWhileLoop(WhileLoopTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.source.tree.WildcardTree (Compiler Tree API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.source.tree.WildcardTree

  • Packages that use WildcardTree
    Package Description
    com.sun.source.tree
    Provides interfaces to represent source code as abstract syntax trees (AST).
    com.sun.source.util
    Provides utilities for operations on abstract syntax trees (AST).

    • Uses of WildcardTree in com.sun.source.tree

      Methods in com.sun.source.tree with parameters of type WildcardTree
      Modifier and Type | Method and Description
      R | TreeVisitor.visitWildcard(WildcardTree node, P p)

    • Uses of WildcardTree in com.sun.source.util

      Methods in com.sun.source.util with parameters of type WildcardTree
      Modifier and Type | Method and Description
      R | TreeScanner.visitWildcard(WildcardTree node, P p)
      R | SimpleTreeVisitor.visitWildcard(WildcardTree node, P p)
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Compiler Tree API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2005, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Uses of Interface com.sun.mirror.type.WildcardType (Mirror API b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Interface
com.sun.mirror.type.WildcardType

  • Packages that use WildcardType
    Package Description
    com.sun.mirror.util
    Utilities to assist in the processing of declarations and types.

    • Uses of WildcardType in com.sun.mirror.util

      Methods in com.sun.mirror.util that return WildcardType
      Modifier and Type Method and Description
      WildcardType Types.getWildcardType(Collection<ReferenceType> upperBounds, Collection<ReferenceType> lowerBounds)
      Deprecated.
      Returns a new wildcard.
      Methods in com.sun.mirror.util with parameters of type WildcardType
      Modifier and Type Method and Description
      void TypeVisitor.visitWildcardType(WildcardType t)
      Deprecated.
      Visits a wildcard.
      void SimpleTypeVisitor.visitWildcardType(WildcardType t)
      Deprecated.
      Visits a wildcard.
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Mirror API
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 2004, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


Windows Look and Feel Update

Overview

The ideal Swing application running under the Windows look and feel would be indistinguishable from its native running counterparts, however due to both changes in the native Windows look and feel (Windows 98, Windows 2000, etc.) and atrophy of our existing Windows look and feel implementation, this has not been the reality. However, for this release we have provided an updated Windows look and feel which integrates seamlessly into the Windows desktop.

This project was composed of a set of independent smaller projects, which involve either fixing a previous emulation deficiency or adding functionality to track 2000/98 features. In some cases the project spans both Swing and AWT:

  • Fix Emulation Bugs
  • Desktop Property Support
  • Column-Wrapping Lists
  • Hot-tracking Toolbar Buttons
  • Gradient Titlebars
  • Keyboard Navigation Hiding
  • Scroll Wheel Support
  • Menu/Tooltip Transition Effects
  • FileChooser Makeover

We chose to modify and enhance the com.sun.java.swing.plaf.windows look and feel package rather than introduce a new 'window2000' package. Almost all of the new functionality is keyed off of Windows native user preferences so that an updated windows look and feel package gracefully runs on eitherWindows 95, Windows 98, Windows NT or Windows 2000 machines. In other words, if a running Swing application detects that a particular user preference (such as Menu fading) doesn't exist, then the windows look and feel will not execute that feature.

The focus of this project was quality, not quantity. Where we deemed it difficult to implement a feature with a high quality result, we deferred that feature to a future release when we can emulate it with better fidelity.

Fix Emulation Bugs

There were many bugs filed against our Windows look and feel and we fixed many of these with this release. We are tracking these bugs witha "w2k" keyword. See Windows Look And Feel Buglist for a list of these windows look and feel bugs.

Desktop Property Support

The current Windows look and feel in Swing only tracks the user's desktop colorscheme (via AWT's SystemColor mechanism). However, on the Windowsdesktop, the user can set many more GUI preferences, such as fonts, sounds, metrics, and can change them at any time and have Windows programs dynamically reflect those changes. We have revised Swing to honor a wider range of user preferences and to also support responding to dynamic changes made by the user. See Windows Desktop Properties Support Specification for details.

Column-Wrapping Lists

List was only capable of displaying a single column and has been updated to support wrapping into multiple columns (like the Windows Explorer pane). This feature is also used to better support the Windows filechooser. See JList Spec update for details.

Hot-Tracking Toolbar Buttons

Buttons contained inside toolbars have become flat in appearance and only when they are 'rolled over' do the borders appear. This feature is supported by the Metal look and feel, but will be added as a general Swing toolbar feature.

Gradient Titlebars

The titlebars on toplevel windows in Windows 2000 by default use a gradient pattern instead of a solid bar color. We get this for free on toplevel windows such as JFrame, however we will use Java2D to implement this rendering for JInternalFrame.

Scroll Wheel Support

Almost all PCs these days come with a scroll-wheel on the mouse and to support this AWT is adding support for scroll wheel input and Swing's scrolling components (JScrollPane, JScrollbar) are being modified to handle this new event type. See MouseWheel API for details of AWT support and see JScrollPane changes for details of support in Swing.

Keyboard Navigation Hiding

In windows the user can set a desktop property which causes applications to hide their keyboard navigation cues *until* ALT is pressed, at which time they magically appear. If the user has this option set on the desktop, Swing will implement this behavior in its menus. See Keyboard Navigation Spec for more information.

Menu/Tooltip Transition Effects

The most obvious feature addition to the Windows look and feel is the new stylistic menu animation. In Windows 98, menus can be set to appear by sliding out. Windows 2000 then introduced a very hip fade-in/fade-out for menus and tooltips.

In order to ensure the most accurate visual effect, this feature is implemented by forcing menus/tooltips to be true toplevel "heavyweight" windows which can take advantage of Microsoft Windows native window animation functionality inside the AWT.

File Chooser Makeover

Although Swing's JFileChooser component closely resembles the Windows file chooser, there are some deficiencies which limit its use on the Windows platform, such as the lack of support for network browsing and the Windows virtual desktop("My Computer", "My Network", etc.). See JFileChooser Spec update for more information.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JAX-WS RI 2.1.1 -- wsgen

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

wsgen - Java™ API for XML Web Services (JAX-WS) 2.0

Specification Version: 2.1
Implementation Version: 2.1.1

The wsgen tool generates JAX-WS portable artifacts used in JAX-WS web services. The tool reads a web service endpoint implementation class (SEI) and generates all the required artifacts for web service deployment, and invocation

Contents

  • Overview
  • Launching wsgen
  • Syntax
  • Example

Overview

The wsgen tool generates JAX-WS portable artifacts used in JAX-WS web services. The tool reads a web service endpoint class and generates all the required artifacts for web service deployment, and invocation. JAXWS 2.1.1 RI also provides a wsgen ant task, see Wsgen ant task for details.

Launching wsgen

  • Solaris/Linux
    • export JAXWS_HOME=/pathto/jaxws-ri
    • $JAXWS_HOME/bin/wsgen.sh -help
  • Windows
    • set JAXWS_HOME=c:\pathto\jaxws-ri
    • %JAXWS_HOME%\bin\wsgen.bat -help

Syntax

wsgen [options] <SEI>

The following table lists the wsgen options.

Option

Description

-classpath <path>

Specify where to find input class files

-cp <path>

Same as -classpath <path>

-d <directory>

Specify where to place generated output files

-extension

allow vendor extensions (functionality not specified by the specification). Use of extensions may result in applications that are not portable or may not interoperate with other implementations

-help

Display help

-keep

Keep generated files

-r <directory>

Used only in conjunction with the -wsdl option. Specify where to place generated resource files such as WSDLs

-s <directory>

Specify where to place generated source files

-verbose

Output messages about what the compiler is doing

-version

Print version information. Use of this option will ONLY print version information. Normal processing will not occur.

-wsdl[:protocol]

By default wsgen does not generate a WSDL file. This flag is optional and will cause wsgen to generate a WSDL file and is usually only used so that the developer can look at the WSDL before the endpoint is deploy. The protocol is optional and is used to specify what protocol should be used in the wsdl:binding. Valid protocols include: soap1.1 and Xsoap1.2. The default is soap1.1. Xsoap1.2 is not standard and can only be used in conjunction with the -extension option.

-servicename <name>

Used only in conjunction with the -wsdl option. Used to specify a particular wsdl:service name to be generated in the WSDL. Example, -servicename "{http://mynamespace/}MyService"

-portname <name>

Used only in conjunction with the -wsdl option. Used to specify a particular wsdl:port name to be generated in the WSDL. Example, -portname "{http://mynamespace/}MyPort"

Example

wsgen -d stock -cp myclasspath stock.StockService

This will generate the wrapper classes needed for StockService annotated with @WebService annotation inside stockdirectory.

wsgen -wsdl -d stock -cp myclasspath stock.StockService

This will generate a SOAP 1.1 WSDL and schema for your Java class stock.StockService annotated with @WebService annotation.

wsgen -wsdl:Xsoap1.2 -d stock -cp myclasspath stock.StockService

Will generate a SOAP 1.2 WSDL.

Note that you do not have to generate WSDL at the development time as JAXWS runtime will automatically generate a WSDL for you when you deploy your service.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JAX-WS RI 2.1.1 -- wsimport

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

wsimport - Java™ API for XML Web Services (JAX-WS) 2.0

Specification Version: 2.1
Implementation Version: 2.1.1

Contents

  • Overview
  • Launching wsimport
  • Syntax
  • Example

Overview

The wsimport tool generates JAX-WS portable artifacts, such as:

  • Service Endpoint Interface (SEI)
  • Service
  • Exception class mapped from wsdl:fault (if any)
  • Async Reponse Bean derived from response wsdl:message (if any)
  • JAXB generated value types (mapped java classes from schema types)

These artifacts can be packaged in a WAR file with the WSDL and schema documents along with the endpoint implementation to be deployed. also provides wsimport ant task, see Wsimport ant task.

Launching wsimport

  • Solaris/Linux
    • /bin/wsimport.sh -help
  • Windows
    • \bin\wsimport.bat -help

Syntax

wsimport [options] <wsdl>

The following table lists the wsimport options.

Option

Description

-d <directory>

Specify where to place generated output files

-b <path>

Specify external JAX-WS or JAXB binding files (Each <file> must have its own -b)

-B <jaxbOption>

Pass this option to JAXB schema compiler

-catalog

Specify catalog file to resolve external entity references, it supports TR9401, XCatalog, and OASIS XML Catalog format. Please read the documentation of catalog and see catalog sample.

-extension

Allow vendor extensions (functionality not specified by the specification). Use of extensions may result in applications that are not portable or may not interoperate with other implementations

-help

Display help

-httpproxy:<host>:<port>

Specify an HTTP proxy server (port defaults to 8080)

-keep

Keep generated files

-p
Specifying a target package via this command-line option, overrides any wsdl and schema binding customization for package name and the default package name algorithm defined in the specification
-s <directory>

Specify where to place generated source files

-verbose

Output messages about what the compiler is doing

-version

Print version information

-wsdllocation <location>
@WebServiceClient.wsdlLocation value
-target
Generate code as per the given JAX-WS specification version. version 2.0 will generate compliant code for JAX-WS 2.0 spec.
-quiet
Suppress wsimport output

Multiple JAX-WS and JAXB binding files can be specified using -b option and they can be used to customize various things like package names, bean names, etc. More information on JAX-WS and JAXB binding files can be found in the customization documentation.

The following table lists wsimport non-standard options:

Option

Description

-XadditionalHeaders

Map headers not bound to request or response message to Java method parameters.

-Xauthfile <file>

WSDL URI that specifies the file that contains authorization information; this URI is in the following format:

http://username:password@example.org/stock?wsdl

-Xdebug

Print debugging information.

-Xno-addressing-databinding

Enable binding of W3C EndpointReferenceType to Java.

-Xnocompile

Do not compile generated Java files.

Example

wsimport -p stockquote http://stockquote.xyz/quote?wsdl

This will generate the Java artifacts and compile them by importing the http://stockquote.xyz/quote?wsdl.

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Uses of Class com.sun.security.auth.X500Principal (Java Authentication and Authorization Service b138)

  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Uses of Class
com.sun.security.auth.X500Principal

No usage of com.sun.security.auth.X500Principal
  • Overview
  • Package
  • Class
  • Use
  • Tree
  • Deprecated
  • Index
  • Help
Java Authentication and Authorization Service
DRAFT ea-b138
  • Prev
  • Next
  • Frames
  • No Frames
  • All Classes

Copyright © 1998, 2011, Oracle and/or its affiliates. All rights reserved.
DRAFT ea-b138


XToolkit on Solaris/Linux

Starting with JavaTM SE 5.0, AWT has been re-implemented on the Solaris and Linux platforms. The new Toolkit implementation provides the following advantages:
  • Removes the dependency on Motif and Xt libraries.
  • Interoperates better with other GUI Toolkits.
  • Provides better performance and quality.

The new Toolkit (XToolkit) is default both on Linux and Solaris.

Explicitly Setting the Toolkit

You can explicitly set the toolkit for an applet or application using an environment variable or a system property. Keep in mind that the environment variable overrides the system property.

  • Setting the toolkit for an application:
    • Using an environment variable. This needs to be set before starting the VM.
       csh:
 setenv AWT_TOOLKIT XToolkit #selects the XToolkit
 setenv AWT_TOOLKIT MToolkit #selects the MToolkit

 ksh/bash:
 export AWT_TOOLKIT=XToolkit
 export AWT_TOOLKIT=MToolkit
    • Using a system property on the command line:
       java -Dawt.toolkit=sun.awt.X11.XToolkit MyApp
 java -Dawt.toolkit=sun.awt.motif.MToolkit MyApp
  • Setting the toolkit for an applet:
    • Using an environment variable.

      If the browser is started from a terminal window, the environment variable must be set in the terminal window before launching the browser. If the browser is launched from a desktop icon or menu, the toolkit for an applet cannot be set using an environment variable. The Java Plug-in Control Panel should be used instead.

    • Using the Plug-in Control Panel:
      • Launch the Java Plug-in Control Panel:
        $java_home/bin/ControlPanel
      • Add the system property to the Java Runtime Parameters field under the Advanced tab.
        -Dawt.toolkit=sun.awt.X11.XToolkit
-Dawt.toolkit=sun.awt.motif.MToolkit
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


JAXB RI 2.1.3 -- Binding Compiler (xjc)

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

xjc - Java™ Architecture for XML Binding
Binding Compiler

Specification Version: 2.1
Reference Implementation (RI) Version: 2.1.3

Launching xjc

The binding compiler can be launched using the appropriate xjc shell script in the bin directory for your platform. We also provide an Ant task to run the binding complier - see the instructions for using the XJC Ant task.

% xjc -help

Output

Usage: xjc [-options ...] <schema file/URL/dir/jar> ... [-b <bindinfo>] ...
If dir is specified, all schema files in it will be compiled.
If jar is specified, /META-INF/sun-jaxb.episode binding file will be compiled.
Options:
  -nv                :  do not perform strict validation of the input schema(s)
  -extension         :  allow vendor extensions - do not strictly follow the Compatibility Rules and App E.2 from the JAXB Spec
  -b <file/dir>      :  specify external bindings files (each <file> must have its own -b); if a directory is given, **/*.xjb is searched
  -d <dir>           :  generated files will go into this directory
  -p <pkg>           :  specifies the target package
  -httpproxy <proxy> :  set HTTP/HTTPS proxy; format is [user[:password]@]proxyHost:proxyPort
  -httpproxyfile <f> :  works like -httpproxy but takes the argument in a file to protect password
  -classpath <arg>   :  specify where to find user class files
  -catalog <file>    :  specify catalog files to resolve external entity references; support TR9401, XCatalog, and OASIS XML Catalog format
  -readOnly          :  generated files will be in read-only mode
  -npa               :  suppress generation of package level annotations (**/package-info.java)
  -no-header         :  suppress generation of a file header with timestamp
  -target 2.0        :  behave like XJC 2.0 and generate code that doesnt use any 2.1 features
  -xmlschema         :  treat input as W3C XML Schema (default)
  -relaxng           :  treat input as RELAX NG (experimental,unsupported)
  -relaxng-compact   :  treat input as RELAX NG compact syntax (experimental,unsupported)
  -dtd               :  treat input as XML DTD (experimental,unsupported)
  -wsdl              :  treat input as WSDL and compile schemas inside it (experimental,unsupported)
  -verbose           :  be extra verbose
  -quiet             :  suppress compiler output
  -help              :  display this help message
  -version           :  display version information

Extensions:
  -Xlocator          :  enable source location support for generated code
  -Xsync-methods     :  generate accessor methods with the 'synchronized' keyword
  -mark-generated    :  mark the generated code as @javax.annotation.Generated
  -episode <FILE>    :  generate the episode file for separate compilation

OPTIONS

-nv
By default, the XJC binding compiler performs strict validation of the source schema before processing it. Use this option to disable strict schema validation. This does not mean that the binding compiler will not perform any validation, it simply means that it will perform less-strict validation.
-extension
By default, the XJC binding compiler strictly enforces the rules outlined in the Compatibility chapter of the JAXB Specification. Appendix E.2 defines a set of W3C XML Schema features that are not completely supported by JAXB v1.0. In some cases, you may be allowed to use them in the "-extension" mode enabled by this switch. In the default (strict) mode, you are also limited to using only the binding customizations defined in the specification. By using the "-extension" switch, you will be allowed to use the JAXB Vendor Extensions
-b <file>
Specify one or more external binding files to process. (Each binding file must have its own "-b" switch.) The syntax of the external binding files is extremely flexible. You may have a single binding file that contains customizations for multiple schemas or you can break the customizations into multiple bindings files: xjc schema1.xsd schema2.xsd schema3.xsd -b bindings123.xjb
xjc schema1.xsd schema2.xsd schema3.xsd -b bindings1.xjb -b bindings2.xjb -b bindings3.xjb In addition, the ordering of the schema files and binding files on the command line does not matter.
-d <dir>
By default, the XJC binding compiler will generate the Java content classes in the current directory. Use this option to specify an alternate output directory. The output directory must already exist, the XJC binding compiler will not create it for you.
-p <pkg>
Specifying a target package via this command-line option overrides any binding customization for package name and the default package name algorithm defined in the specification.
-httpproxy <proxy>
Specify the HTTP/HTTPS proxy. The format is [user[:password]@]proxyHost[:proxyPort]. The old -host and -port are still supported by the RI for backwards compatibility, but they have been deprecated. Note that the password specified with this option is an argument that is visible to other users who use the top command, for example. For greater security, use -httpproxyfile, below.
-httpproxyfile <file>
Specify the HTTP/HTTPS proxy using a file. Same format as above, but the password specified in the file is not visible to other users.
-classpath <arg>
Specify where to find client application class files used by the <jxb:javaType> and <xjc:superClass> customizations.
-catalog <file>
Specify catalog files to resolve external entity references. Supports TR9401, XCatalog, and OASIS XML Catalog format. Please read the XML Entity and URI Resolvers document or the catalog-resolver sample application.
-readOnly
By default, the XJC binding compiler does not write-protect the Java source files it generates. Use this option to force the XJC binding compiler to mark the generated Java sources read-only.
-npa
Supress the generation of package level annotations into **/package-info.java. Using this switch causes the generated code to internalize those annotations into the other generated classes.
-no-header
Supress the generation of a file header comment that includes some note and timestamp. Using this makes the generated code more diff-friendly.
-target 2.0
Avoid generating code that relies on any JAXB 2.1 features. This will allow the generated code to run with JAXB 2.0 runtime (such as JavaSE 6.)
-xmlschema
Treat input schemas as W3C XML Schema (default). If you do not specify this switch, your input schemas will be treated as W3C XML Schema.
-relaxng
Treat input schemas as RELAX NG (experimental, unsupported). Support for RELAX NG schemas is provided as a JAXB Vendor Extension.
-relaxng-compact
Treat input schemas as RELAX NG compact syntax(experimental, unsupported). Support for RELAX NG schemas is provided as a JAXB Vendor Extension.
-dtd
Treat input schemas as XML DTD (experimental, unsupported). Support for RELAX NG schemas is provided as a JAXB Vendor Extension.
-wsdl
Treat input as WSDL and compile schemas inside it (experimental,unsupported).
-quiet
Suppress compiler output, such as progress information and warnings.
-verbose
Be extra verbose, such as printing informational messages or displaying stack traces upon some errors.
-help
Display a brief summary of the compiler switches.
-version
Display the compiler version information.
<schema file/URL/dir>
Specify one or more schema files to compile. If you specify a directory, then xjc will scan it for all schema files and compile them.

Non-Standard Command Line Options

-Xlocator
Causes the generated code to expose SAX Locator information about the source XML in the Java bean instances after unmarshalling.
-Xsync-methods
Causes all of the generated method signatures to include the synchronized keyword.
-mark-generated
Mark the generated code with the annotation @javax.annotation.Generated.
-episode <file>
Generate the specified episode file for separate compilation.

Deprecated and Removed Command Line Options

-host & -port
These options have been deprecated and replaced with the -httpproxy option. For backwards compatibility, we will continue to support these options, but they will no longer be documented and may be removed from future releases.
-use-runtime
Since the JAXB 2.0 specification has defined a portable runtime, it is no longer necessary for the JAXB RI to generate **/impl/runtime packages. Therefore, this switch is obsolete and has been removed.
-source
The -source compatibility switch was introduced in the first JAXB 2.0 Early Access release. We have decided to remove this switch from future releases of JAXB 2.0. If you need to generate 1.0.x code, please use an installation of the 1.0.x codebase.

Compiler Restrictions

In general, it is safest to compile all related schemas as a single unit with the same binding compiler switches.

Please keep the following list of restrictions in mind when running xjc. Most of these issues only apply when compiling multiple schemas with multiple invocations of xjc.

  • To compile multiple schemas at the same time, keep the following precedence rules for the target Java package name in mind:
    1. The "-p" command line option takes the highest precedence.
    2. <jaxb:package> customization
    3. If targetNamespace is declared, apply targetNamespace -> Java package name algorithm defined in the specification.
    4. If no targetNamespace is declared, use a hardcoded package named "generated".
  • It is not legal to have more than one <jaxb:schemaBindings> per namespace, so it is impossible to have two schemas in the same target namespace compiled into different Java packages.
  • All schemas being compiled into the same Java package must be submitted to the XJC binding compiler at the same time - they cannot be compiled independently and work as expected.
  • Element substitution groups spread across multiple schema files must be compiled at the same time.

See Also

  • Running the binding compiler (XJC): [command-line instructions, using the XJC Ant task]
  • Java Architecture for XML Binding (JAXB)
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Java XML Digital Signature API

Skip to Content
  • Oracle Technology Network
  • Software Downloads
  • Documentation
Search

XML Digital Signature API

Overview and Tutorial

Table of Contents

Java XML Digital Signature API

XML Security Stack

Package Hierarchy

Service Providers

Introduction to XML Signatures

Example of an XML Signature

XML Digital Signature API Examples

validate Example

Validating an XML Signature

Instantiating the Document that Contains the Signature

Specifying the Signature Element to be Validated

Creating a Validation Context

Unmarshaling the XML Signature

Validating the XML Signature

What If the XML Signature Fails to Validate?

Using KeySelectors

genenveloped Example

Generating an XML Signature

Instantiating the Document to be Signed

Creating a Public Key Pair

Creating a Signing Context

Assembling the XML Signature

Generating the XML Signature

Printing or Displaying the Resulting Document

Java XML Digital Signature API

The Java XML Digital Signature API is a standard Java API for generating and validating XML Signatures. This API was defined under the Java Community Process as JSR 105 (see http://jcp.org/en/jsr/detail?id=105). This JSR is final and this release of Java SE contains an FCS access implementation of the Final version of the APIs.

XML Signatures can be applied to data of any type, XML or binary (see http://www.w3.org/TR/xmldsig-core/). The resulting signature is represented in XML. An XML Signature can be used to secure your data and provide data integrity, message authentication, and signer authentication.

After providing a brief overview of XML Signatures and the XML Digital Signature API, this document presents two examples that demonstrate how to use the API to validate and generate an XML Signature. This document assumes that you have a basic knowledge of cryptography and digital signatures.

The API is designed to support all of the required or recommended features of the W3C Recommendation for XML-Signature Syntax and Processing. The API is extensible and pluggable and is based on the Java Cryptography Service Provider Architecture. The API is designed for two types of developers:

  • Developers who want to use the XML Digital Signature API to generate and validate XML signatures
  • Developers who want to create a concrete implementation of the XML Digital Signature API and register it as a cryptographic service of a JCA provider

Package Hierarchy

The six packages listed below comprise the XML Digital Signature API:

  • javax.xml.crypto
  • javax.xml.crypto.dsig
  • javax.xml.crypto.dsig.keyinfo
  • javax.xml.crypto.dsig.spec
  • javax.xml.crypto.dom
  • javax.xml.crypto.dsig.dom

The javax.xml.crypto package contains common classes that are used to perform XML cryptographic operations, such as generating an XML signature or encrypting XML data. Two notable classes in this package are the KeySelector class, which allows developers to supply implementations that locate and optionally validate keys using the information contained in a KeyInfo object, and the URIDereferencer class, which allows developers to create and specify their own URI dereferencing implementations.

The javax.xml.crypto.dsig package includes interfaces that represent the core elements defined in the W3C XML digital signature specification. Of primary significance is the XMLSignature class, which allows you to sign and validate an XML digital signature. Most of the XML signature structures or elements are represented by a corresponding interface (except for the KeyInfo structures, which are included in their own package and are discussed in the next paragraph). These interfaces include: SignedInfo, CanonicalizationMethod, SignatureMethod, Reference, Transform, DigestMethod, XMLObject, Manifest, SignatureProperty, and SignatureProperties. The XMLSignatureFactory class is an abstract factory that is used to create objects that implement these interfaces.

The javax.xml.crypto.dsig.keyinfo package contains interfaces that represent most of the KeyInfo structures defined in the W3C XML digital signature recommendation, including KeyInfo, KeyName, KeyValue, X509Data, X509IssuerSerial, RetrievalMethod, and PGPData. The KeyInfoFactory class is an abstract factory that is used to create objects that implement these interfaces.

The javax.xml.crypto.dsig.spec package contains interfaces and classes representing input parameters for the digest, signature, transform, or canonicalization algorithms used in the processing of XML signatures.

Finally, the javax.xml.crypto.dom and javax.xml.crypto.dsig.dom packages contains DOM-specific classes for the javax.xml.crypto and javax.xml.crypto.dsig packages, respectively. Only developers and users who are creating or using a DOM-based XMLSignatureFactory or KeyInfoFactory implementation will need to make direct use of these packages.

Service Providers

A JSR 105 cryptographic service is a concrete implementation of the abstract XMLSignatureFactory and KeyInfoFactory classes and is responsible for creating objects and algorithms that parse, generate and validate XML Signatures and KeyInfo structures. A concrete implementation of XMLSignatureFactory must provide support for each of the required algorithms as specified by the W3C recommendation for XML Signatures. It can optionally support other algorithms as defined by the W3C recommendation or other specifications.

JSR 105 leverages the JCA provider model for registering and loading XMLSignatureFactory and KeyInfoFactory implementations.

Each concrete XMLSignatureFactory or KeyInfoFactory implementation supports a specific XML mechanism type that identifies the XML processing mechanism that an implementation uses internally to parse and generate XML signature and KeyInfo structures. This JSR supports one standard type, DOM. The XML Digital Signature provider implementation that is bundled with Java SE supports the DOM mechanism. Support for new standard types, such as JDOM, may be added in the future.

An XML Digital Signature API implementation should use underlying JCA engine classes, such as java.security.Signature and java.security.MessageDigest, to perform cryptographic operations.

In addition to the XMLSignatureFactory and KeyInfoFactory classes, JSR 105 supports a service provider interface for transform and canonicalization algorithms. The TransformService class allows you to develop and plug in an implementation of a specific transform or canonicalization algorithm for a particular XML mechanism type. The TransformService class uses the standard JCA provider model for registering and loading implementations. Each JSR 105 implementation should use the TransformService class to find a provider that supports transform and canonicalization algorithms in XML Signatures that it is generating or validating.

Introduction to XML Signatures

You can use an XML Signature to sign any arbitrary data, whether it is XML or binary. The data is identified via URIs in one or more Reference elements. XML Signatures are described in one or more of three forms: detached, enveloping, or enveloped. A detached signature is over data that is external, or outside of the signature element itself. Enveloping signatures are signatures over data that is inside the signature element, and an enveloped signature is a signature that is contained inside the data that it is signing.

Example of an XML Signature

The easiest way to describe the contents of an XML Signature is to show an actual sample and describe each component in more detail. The following is an example of an enveloped XML Signature generated over the contents of an XML document. The contents of the document before it is signed are:

<Envelope xmlns="urn:envelope">
</Envelope>

The resulting enveloped XML Signature, indented and formatted for readability, is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<Envelope xmlns="urn:envelope">
  <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
    <SignedInfo>
      <CanonicalizationMethod
        Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"/>
      <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#dsa-sha1"/>
      <Reference URI="">
        <Transforms>
          <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
        </Transforms>
        <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
        <DigestValue>uooqbWYa5VCqcJCbuymBKqm17vY=</DigestValue>
      </Reference>
    </SignedInfo>
    <SignatureValue>
      KedJuTob5gtvYx9qM3k3gm7kbLBwVbEQRl26S2tmXjqNND7MRGtoew==
    </SignatureValue>
    <KeyInfo>
      <KeyValue>
        <DSAKeyValue>
          <P>
            /KaCzo4Syrom78z3EQ5SbbB4sF7ey80etKII864WF64B81uRpH5t9jQTxe
            Eu0ImbzRMqzVDZkVG9xD7nN1kuFw==
          </P>
          <Q>li7dzDacuo67Jg7mtqEm2TRuOMU=</Q>
          <G>
            Z4Rxsnqc9E7pGknFFH2xqaryRPBaQ01khpMdLRQnG541Awtx/
            XPaF5Bpsy4pNWMOHCBiNU0NogpsQW5QvnlMpA==
          </G>
          <Y>
            qV38IqrWJG0V/mZQvRVi1OHw9Zj84nDC4jO8P0axi1gb6d+475yhMjSc/
            BrIVC58W3ydbkK+Ri4OKbaRZlYeRA==
          </Y>
        </DSAKeyValue>
      </KeyValue>
    </KeyInfo>
  </Signature>
</Envelope>

The Signature element has been inserted inside the content that it is signing, thereby making it an enveloped signature. The required SignedInfo element contains the information that is actually signed:

<SignedInfo>
  <CanonicalizationMethod
    Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"/>
  <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#dsa-sha1"/>
  <Reference URI="">
    <Transforms>
      <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
    </Transforms>
    <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
    <DigestValue>uooqbWYa5VCqcJCbuymBKqm17vY=</DigestValue>
  </Reference>
</SignedInfo>

The required CanonicalizationMethod element defines the algorithm used to canonicalize the SignedInfo element before it is signed or validated. Canonicalization is the process of converting XML content to a canonical form, to take into account changes that can invalidate a signature over that data. Canonicalization is necessary due to the nature of XML and the way it is parsed by different processors and intermediaries, which can change the data such that the signature is no longer valid but the signed data is still logically equivalent.

The required SignatureMethod element defines the digital signature algorithm used to generate the signature, in this case DSA with SHA-1.

One or more Reference elements identify the data that is digested. Each Reference element identifies the data via a URI. In this example, the value of the URI is the empty String (""), which indicates the root of the document. The optional Transforms element contains a list of one or more Transform elements, each of which describes a transformation algorithm used to transform the data before it is digested. In this example, there is one Transform element for the enveloped transform algorithm. The enveloped transform is required for enveloped signatures so that the signature element itself is removed before calculating the signature value. The required DigestMethod element defines the algorithm used to digest the data, in this case SHA1. Finally the required DigestValue element contains the actual base64-encoded digested value.

The required SignatureValue element contains the base64-encoded signature value of the signature over the SignedInfo element.

The optional KeyInfo element contains information about the key that is needed to validate the signature:

<KeyInfo>
  <KeyValue>
    <DSAKeyValue>
      <P>
        /KaCzo4Syrom78z3EQ5SbbB4sF7ey80etKII864WF64B81uRpH5t9jQTxe
        Eu0ImbzRMqzVDZkVG9xD7nN1kuFw==
      </P>
      <Q>li7dzDacuo67Jg7mtqEm2TRuOMU=</Q>
      <G>
        Z4Rxsnqc9E7pGknFFH2xqaryRPBaQ01khpMdLRQnG541Awtx/
        XPaF5Bpsy4pNWMOHCBiNU0NogpsQW5QvnlMpA==
      </G>
      <Y>
        qV38IqrWJG0V/mZQvRVi1OHw9Zj84nDC4jO8P0axi1gb6d+475yhMjSc/
        BrIVC58W3ydbkK+Ri4OKbaRZlYeRA==
      </Y>
    </DSAKeyValue>
  </KeyValue>
</KeyInfo>

This KeyInfo element contains a KeyValue element, which in turn contains a DSAKeyValue element consisting of the public key needed to validate the signature. KeyInfo can contain various content such as X.509 certificates and PGP key identifiers. See the KeyInfo section of the XML Signature Recommendation for more information on the different KeyInfo types.

XML Digital Signature API Examples

The following sections describe two examples that show how to use the XML Digital Signature API:

  • Validate example
  • Signing example

validate Example

You can find the code shown in this section in the Validate.java file in the docs/technotes/guides/security/xmldsig directory. The file on which it operates, envelopedSignature.xml, is in the same directory.

To compile and run the example, execute the following commands from the docs/technotes/guides/security/xmldsig directory:

$ javac Validate.java
$ java Validate signature.xml

The sample program will validate the signature in the file signature.xml in the current working directory.

Validating an XML Signature

This example shows you how to validate an XML Signature using the JSR 105 API. The example uses DOM (the Document Object Model) to parse an XML document containing a Signature element and a JSR 105 DOM implementation to validate the signature.

Instantiating the Document that Contains the Signature

First we use a JAXP DocumentBuilderFactory to parse the XML document containing the Signature. An application obtains the default implementation for DocumentBuilderFactory by calling the following line of code:

DocumentBuilderFactory dbf =
  DocumentBuilderFactory.newInstance();

We must also make the factory namespace-aware:

dbf.setNamespaceAware(true);

Next, we use the factory to get an instance of a DocumentBuilder, which is used to parse the document:

DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse(new FileInputStream(argv[0]));

Specifying the Signature Element to be Validated

We need to specify the Signature element that we want to validate, since there could be more than one in the document. We use the DOM method Document.getElementsByTagNameNS, passing it the XML Signature namespace URI and the tag name of the Signature element, as shown:

NodeList nl = doc.getElementsByTagNameNS
  (XMLSignature.XMLNS, "Signature");
if (nl.getLength() == 0) {
  throw new Exception("Cannot find Signature element");
}

This returns a list of all Signature elements in the document. In this example, there is only one Signature element.

Creating a Validation Context

We create an XMLValidateContext instance containing input parameters for validating the signature. Since we are using DOM, we instantiate a DOMValidateContext instance (a subclass of XMLValidateContext), and pass it two parameters, a KeyValueKeySelector object and a reference to the Signature element to be validated (which is the first entry of the NodeList we generated earlier):

DOMValidateContext valContext = new DOMValidateContext
  (new KeyValueKeySelector(), nl.item(0));

The KeyValueKeySelector is explained in greater detail in Using KeySelectors.

Unmarshaling the XML Signature

We extract the contents of the Signature element into an XMLSignature object. This process is called unmarshalling. The Signature element is unmarshalled using an XMLSignatureFactory object. An application can obtain a DOM implementation of XMLSignatureFactory by calling the following line of code:

XMLSignatureFactory factory =
  XMLSignatureFactory.getInstance("DOM");

We then invoke the unmarshalXMLSignature method of the factory to unmarshal an XMLSignature object, and pass it the validation context we created earlier:

XMLSignature signature =
  factory.unmarshalXMLSignature(valContext);

Validating the XML Signature

Now we are ready to validate the signature. We do this by invoking the validate method on the XMLSignature object, and pass it the validation context as follows:

boolean coreValidity = signature.validate(valContext);

The validate method returns "true" if the signature validates successfully according to the core validation rules in the W3C XML Signature Recommendation, and false otherwise.

What If the XML Signature Fails to Validate?

If the XMLSignature.validate method returns false, we can try to narrow down the cause of the failure. There are two phases in core XML Signature validation:

  • Signature validation (the cryptographic verification of the signature)
  • Reference validation (the verification of the digest of each reference in the signature)

Each phase must be successful for the signature to be valid. To check if the signature failed to cryptographically validate, we can check the status, as follows:

boolean sv =
  signature.getSignatureValue().validate(valContext);
System.out.println("signature validation status: " + sv);

We can also iterate over the references and check the validation status of each one, as follows:

Iterator i =
  signature.getSignedInfo().getReferences().iterator();
for (int j=0; i.hasNext(); j++) {
  boolean refValid = ((Reference)
    i.next()).validate(valContext);
  System.out.println("ref["+j+"] validity status: " +
    refValid);
}

Using KeySelectors

KeySelectors are used to find and select keys that are needed to validate an XMLSignature. Earlier, when we created a DOMValidateContext object, we passed a KeySelector object as the first argument:

DOMValidateContext valContext = new DOMValidateContext
  (new KeyValueKeySelector(), nl.item(0));

Alternatively, we could have passed a PublicKey as the first argument if we already knew what key is needed to validate the signature. However, we often don't know.

The KeyValueKeySelector is a concrete implementation of the abstract KeySelector class. The KeyValueKeySelector implementation tries to find an appropriate validation key using the data contained in KeyValue elements of the KeyInfo element of an XMLSignature. It does not determine if the key is trusted. This is a very simple KeySelector implementation, designed for illustration rather than real-world usage. A more practical example of a KeySelector is one that searches a KeyStore for trusted keys that match X509Data information (for example, X509SubjectName, X509IssuerSerial, X509SKI, or X509Certificate elements) contained in a KeyInfo.

The implementation of the KeyValueKeySelector is as follows:

private static class KeyValueKeySelector extends KeySelector {

  public KeySelectorResult select(KeyInfo keyInfo,
      KeySelector.Purpose purpose,
      AlgorithmMethod method,
      XMLCryptoContext context)
    throws KeySelectorException {

    if (keyInfo == null) {
      throw new KeySelectorException("Null KeyInfo object!");
    }
    SignatureMethod sm = (SignatureMethod) method;
    List list = keyInfo.getContent();

    for (int i = 0; i < list.size(); i++) {
      XMLStructure xmlStructure = (XMLStructure) list.get(i);
      if (xmlStructure instanceof KeyValue) {
        PublicKey pk = null;
        try {
          pk = ((KeyValue)xmlStructure).getPublicKey();
        } catch (KeyException ke) {
          throw new KeySelectorException(ke);
        }
        // make sure algorithm is compatible with method
        if (algEquals(sm.getAlgorithm(),
            pk.getAlgorithm())) {
          return new SimpleKeySelectorResult(pk);
        }
      }
    }
    throw new KeySelectorException("No KeyValue element
found!");
  }

  static boolean algEquals(String algURI, String algName) {
    if (algName.equalsIgnoreCase("DSA") &&
        algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) {
      return true;
    } else if (algName.equalsIgnoreCase("RSA") &&
        algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1)) {
      return true;
    } else {
      return false;
    }
  }
}

genenveloped Example

The code discussed in this section is in the GenEnveloped.java file in the docs/technotes/guides/security/xmldsig directory. The file on which it operates, envelope.xml, is in the same directory. It generates the file envelopedSignature.xml.

To compile and run this sample, execute the following command from the docs/technotes/guides/security/xmldsig directory:

$ javac GenEnveloped.java
$ java GenEnveloped envelope.xml envelopedSignature.xml

The sample program will generate an enveloped signature of the document in the file envelope.xml and store it in the file envelopedSignature.xml in the current working directory.

Generating an XML Signature

This example shows you how to generate an XML Signature using the XML Digital Signature API. More specifically, the example generates an enveloped XML Signature of an XML document. An enveloped signature is a signature that is contained inside the content that it is signing. The example uses DOM (the Document Object Model) to parse the XML document to be signed and a JSR 105 DOM implementation to generate the resulting signature.

A basic knowledge of XML Signatures and their different components is helpful for understanding this section. See http://www.w3.org/TR/xmldsig-core/ for more information.

Instantiating the Document to be Signed

First, we use a JAXP DocumentBuilderFactory to parse the XML document that we want to sign. An application obtains the default implementation for DocumentBuilderFactory by calling the following line of code:

DocumentBuilderFactory dbf =
  DocumentBuilderFactory.newInstance();

We must also make the factory namespace-aware:

dbf.setNamespaceAware(true);

Next, we use the factory to get an instance of a DocumentBuilder, which is used to parse the document:

DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse(new FileInputStream(argv[0]));

Creating a Public Key Pair

We generate a public key pair. Later in the example, we will use the private key to generate the signature. We create the key pair with a KeyPairGenerator. In this example, we will create a DSA KeyPair with a length of 512 bytes :

KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
kpg.initialize(512);
KeyPair kp = kpg.generateKeyPair();

In practice, the private key is usually previously generated and stored in a KeyStore file with an associated public key certificate.

Creating a Signing Context

We create an XML Digital Signature XMLSignContext containing input parameters for generating the signature. Since we are using DOM, we instantiate a DOMSignContext (a subclass of XMLSignContext), and pass it two parameters, the private key that will be used to sign the document and the root of the document to be signed:

DOMSignContext dsc = new DOMSignContext
  (kp.getPrivate(), doc.getDocumentElement());

Assembling the XML Signature

We assemble the different parts of the Signature element into an XMLSignature object. These objects are all created and assembled using an XMLSignatureFactory object. An application obtains a DOM implementation of XMLSignatureFactory by calling the following line of code:

XMLSignatureFactory fac =
  XMLSignatureFactory.getInstance("DOM");

We then invoke various factory methods to create the different parts of the XMLSignature object as shown below. We create a Reference object, passing to it the following:

  • The URI of the object to be signed (We specify a URI of "", which implies the root of the document.)
  • The DigestMethod (we use SHA1)
  • A single Transform, the enveloped Transform, which is required for enveloped signatures so that the signature itself is removed before calculating the signature value
Reference ref = fac.newReference
  ("", fac.newDigestMethod(DigestMethod.SHA1, null),
    Collections.singletonList
      (fac.newTransform(Transform.ENVELOPED,
        (TransformParameterSpec) null)), null, null);

Next, we create the SignedInfo object, which is the object that is actually signed, as shown below. When creating the SignedInfo, we pass as parameters:

  • The CanonicalizationMethod (we use inclusive and preserve comments)
  • The SignatureMethod (we use DSA)
  • A list of References (in this case, only one)
SignedInfo si = fac.newSignedInfo
  (fac.newCanonicalizationMethod
    (CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
      (C14NMethodParameterSpec) null),
    fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null),
    Collections.singletonList(ref));

Next, we create the optional KeyInfo object, which contains information that enables the recipient to find the key needed to validate the signature. In this example, we add a KeyValue object containing the public key. To create KeyInfo and its various subtypes, we use a KeyInfoFactory object, which can be obtained by invoking the getKeyInfoFactory method of the XMLSignatureFactory, as follows:

KeyInfoFactory kif = fac.getKeyInfoFactory();

We then use the KeyInfoFactory to create the KeyValue object and add it to a KeyInfo object:

KeyValue kv = kif.newKeyValue(kp.getPublic());
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));

Finally, we create the XMLSignature object, passing as parameters the SignedInfo and KeyInfo objects that we created earlier:

XMLSignature signature = fac.newXMLSignature(si, ki);

Notice that we haven't actually generated the signature yet; we'll do that in the next step.

Generating the XML Signature

Now we are ready to generate the signature, which we do by invoking the sign method on the XMLSignature object, and pass it the signing context as follows:

signature.sign(dsc);

The resulting document now contains a signature, which has been inserted as the last child element of the root element.

Printing or Displaying the Resulting Document

You can use the following code to print the resulting signed document to a file or standard output:

OutputStream os;
if (args.length > 1) {
  os = new FileOutputStream(args[1]);
} else {
  os = System.out;
}
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
trans.transform(new DOMSource(doc), new StreamResult(os));

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Zip File System Provider

Introduction

The zip file system provider introduced in the Java SE 7 release is an implementation of a custom file system provider. The zip file system provider treats a zip or JAR file as a file system and provides the ability to manipulate the contents of the file. The zip file system provider creates multiple file systems — one file system for each zip or JAR file.

The demo/nio/zipfs/src.zip file in your Java SE 7 installation contains the source code for the zip file system provider. It also contains the Demo.java class that shows how to use the zip file system provider.

Using the Zip File System Provider

You can use the factory methods of the java.nio.file.FileSystems class to create a new zip file system or to obtain a reference to an existing zip file system. Create a zip file system by specifying the path of the zip or JAR file in one of the following ways:

  • By using the JAR URL syntax defined in the java.net.JarURLConnection class
    URI uri = URI.create("jar:file:/codeSamples/zipfs/zipfstest.zip");
FileSystem fs = FileSystems.newFileSystem(uri, env);
  • By specifying a path and using automatic file type detection
    Path zipfile = Paths.get("/codeSamples/zipfs/zipfstest.zip");
FileSystem fs = FileSystems.newFileSystem(zipfile, env, null);

Specify the configuration options for the zip file system in the java.util.Map object passed to the FileSystems.newFileSystem method. See the Zip File System Properties topic for information about the provider-specific configuration properties for the zip file system.

Once you have an instance of a zip file system, you can invoke the methods of the java.nio.file.FileSystem and java.nio.file.Path classes to perform operations such as copying, moving, and renaming files, as well as modifying file attributes.

The following code sample shows how to create a zip file system and copy a file to the new zip file system.

import java.util.*;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.*;

public class ZipFSPUser {
    public static void main(String [] args) throws Throwable {
        Map<String, String> env = new HashMap<>();
        env.put("create", "true");
        // locate file system by using the syntax
        // defined in java.net.JarURLConnection
        URI uri = URI.create("jar:file:/codeSamples/zipfs/zipfstest.zip");

        try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
            Path externalTxtFile = Paths.get("/codeSamples/zipfs/SomeTextFile.txt");
            Path pathInZipfile = zipfs.getPath("/SomeTextFile.txt");
            // copy a file into the zip file
            externalTxtFile.copyTo(pathInZipfile);
        }
    }
}

Resources

  • Developing a Custom File System Provider
  • Zip File System Properties
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us


Zip File System Properties

The following table shows the configurable properties of a zip file system created by the zip file system provider in the Java™ Development Kit (JDK).

Property Name (of Type java.lang.String) | Allowed Values | Property Description
create | true / false | The value should be of type java.lang.String. The default value is false. If the value is true, the zip file system provider creates a new zip file if it does not exist.
encoding | String indicating the encoding scheme | The value should be of type java.lang.String. The value of the property indicates the encoding scheme for the names of the entries in the zip or JAR file. The default value is UTF-8.

Resources

  • Developing a Custom File System Provider
  • Zip File System Provider
Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.
Contact Us